momentic 3.25.0 → 3.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +11 -11
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/run-viewer-static/assets/{index-BQXPNVYo.js → index-C6RPFVBp.js} +268 -258
- package/run-viewer-static/assets/index-ChHJq2FJ.css +1 -0
- package/run-viewer-static/index.html +2 -2
- package/static/assets/{index-CcUFmSpZ.js → index-BvPtAXvF.js} +4 -4
- package/static/assets/index-ChHJq2FJ.css +1 -0
- package/static/index.html +2 -2
- package/run-viewer-static/assets/index-g3OHk3tG.css +0 -1
- package/static/assets/index-g3OHk3tG.css +0 -1
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]="
|
|
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]="22761cd9-d29d-517e-93af-34b51fee0965")}catch(e){}}();
|
|
4
4
|
import * as ko from 'fs';
|
|
5
5
|
import ko__default, { statSync, mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, renameSync, readdir, readdirSync, createReadStream, appendFileSync, rmSync } from 'fs';
|
|
6
6
|
import * as P 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)=>{let u=e.redactedValues.length===0?d:d.map(p=>typeof p=="string"?e.redact(p):p);return r==="stderr"?console.error(...u):console.log(...u)},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=il.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(sl(y,void 0,2)," ");i(n(` ${u}.${f}:`,S));continue}i(n(` ${u}.${f}:`,y));}}else typeof p=="object"?(m=sl(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=sl(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=Ib[t]:this.minLogLevel=t;}setOutputStream(t){this.forcedStream=t;}log(...t){this.logWithLevel(30,il.reset,...t);}info(...t){this.logWithLevel(30,il.white,...t);}debug(...t){this.logWithLevel(20,il.dim,...t);}warn(...t){this.logWithLevel(40,il.yellow,...t);}error(...t){this.logWithLevel(50,il.red,...t);}success(...t){this.logWithLevel(30,il.green,...t);}dimmed(...t){this.logWithLevel(30,il.dim,...t);}underline(...t){this.logWithLevel(30,il.underline,...t);}bold(...t){this.logWithLevel(30,il.bold,...t);}grey(...t){this.logWithLevel(30,il.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}},C=fN._internalSingleton(),Gr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Gr,flush:async()=>{},bindings:()=>({})},AC={},SN=({logger:e,logKey:t,maxCount:n,intervalMs:o},r,i,...s)=>{let a=AC[t];a?clearTimeout(a.timer):(a={count:0,totalCount:0},AC[t]=a),a.totalCount++,a.count<n&&(a.count++,e.debug(r,i,...s)),a.timer=setTimeout(()=>{let l=AC[t];l?.totalCount!==l?.count&&e.debug({logKey:t,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${t}`),delete AC[t];},o);};var cW=1e4,dW=1,Pg=ol.extend({browserType:z$1.enum(nl).optional(),slowMoMs:z$1.number().optional().refine(e=>e===void 0||e<=cW&&e>=-1,{message:`Slow motion must be between 0 and ${cW} 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(nC).optional(),colorScheme:z$1.enum(["light","dark"]).optional()}),uW=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],bN=z$1.object({useMemory:z$1.boolean().optional(),failureRecovery:z$1.boolean().optional().describe("undefined means inherit org settings")}),TN=bN.extend({disableAICaching:z$1.boolean().optional(),failureRecoveryInstructions:z$1.string().optional()}),GSe=z$1.object({viewport:dd.optional()}),Bi=GSe.extend(TN.shape).extend(Pg.shape),EC=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()}),vC=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()}),$Se=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")}),pW=$Se.array(),VSe=z$1.object({name:z$1.string(),value:z$1.string()}),CC=VSe.array(),mW=z$1.object({name:z$1.string(),default:z$1.boolean().optional(),fixtures:tz.array().optional()});var Ca=bN.extend({agentConfig:z$1.record(z$1.string(),z$1.string()).optional(),aiFailureAnalysis:z$1.boolean().optional(),classification:U$.optional(),triage:B$.optional(),healing:Rv.optional(),explore:Iv.optional(),select:Xz.optional()}),zSe=z$1.object({cliOnly:z$1.boolean().optional(),neverShowUsageBanner:z$1.boolean().optional(),hideInternalTraceInfo:z$1.boolean().optional(),bypassUsageLimits:z$1.boolean().optional()}),xb=z$1.object({fakerConstantSeed:z$1.boolean().optional(),isolateCachesByEnvironment:z$1.boolean().optional(),saveCacheOnCancel:z$1.boolean().optional()}),WSe=z$1.enum(["flaky_tests","low_test_coverage","frequent_bugs","fix_flaky_tests","migrate_tests","increase_test_coverage","catch_more_bugs"]),qSe=z$1.enum(["ios","android","web"]),KSe=z$1.enum(["selenium","playwright","cypress","puppeteer","maestro","appium","detox","manual_qa","nothing_yet","other"]),YSe=z$1.enum(["advertisement","ai_search","google_search","hacker_news","linkedin","reddit","referral_from_customer","twitter_x","word_of_mouth","youtube","other"]),JSe=z$1.object({helpIntents:z$1.array(WSe).optional(),helpIntentOtherText:z$1.string().optional(),deviceTypeIntent:qSe.optional(),currentTestingTool:KSe.optional(),heardAboutSource:YSe.optional()}),XSe=z$1.object({discovery:JSe.optional(),needsToCompleteOnboarding:z$1.boolean().optional(),wizardCompletedAt:z$1.iso.datetime().optional()}),Og=z$1.object({ai:Ca.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:zM.optional(),internal:zSe.optional(),advanced:xb.optional(),onboarding:XSe.optional()});function hW(e){try{return Og.parse(e)}catch{return C.warn("Cloud settings contain values this version of the CLI does not support. Please upgrade. Falling back to defaults."),Og.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 Us={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},St=(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))(St||{});var _b=(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))(_b||{});var Mg=z$1.enum(_b).default("NOT_ATTEMPTED"),RC=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(RC||{});var QSe=z$1.object({attempts:z$1.int().nonnegative()}),Wn=z$1.string().pipe(z$1.coerce.date()).or(z$1.date()),ds=z$1.object({id:z$1.string(),runKey:z$1.string(),organizationId:z$1.string(),executionType:Nu.optional().default("WEB"),createdAt:Wn,createdBy:z$1.string(),flake:z$1.boolean().nullish(),scheduledAt:Wn.or(z$1.null()),startedAt:Wn.or(z$1.null()),updatedAt:Wn.nullish(),finishedAt:Wn.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:Wn.nullish(),gitCommitMessage:z$1.string().nullish(),schemaVersion:z$1.string().nullish(),cliVersion:z$1.string().nullish(),section:z$1.enum(RC).nullish(),status:z$1.enum(St),healStatus:Mg,healDetails:dz.nullish(),trigger:z$1.enum(Us),attempts:z$1.number(),runAttempts:z$1.array(z$1.object({id:z$1.string(),status:z$1.enum(St),startedAt:Wn.or(z$1.null()),finishedAt:Wn.or(z$1.null())})).optional(),videos:z$1.array(z$1.string()).optional(),failureReason:z$1.string().nullish(),failureDetails:GV.nullish(),failureRecoveryDetails:QSe.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:Ca.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()}),ZSe={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},wC=ds.pick({...ZSe,test:true}),gW=ds.omit({failureReason:true,failureDetails:true,test:true}),AN=ds.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:Bi.nullish()}).nullish()}).extend(dN.shape),fW=e=>e.includes("PASSED")&&e.includes("FAILED");var ebe=z$1.object({region:z$1.enum(["US","EU"]).optional().describe("New Relic data center region. Defaults to US."),accountId:z$1.string().describe("New Relic account ID to send events to. Supports ${ENV_VAR} interpolation."),licenseKey:z$1.string().optional().describe("New Relic ingest license key. Supports ${ENV_VAR} interpolation. Defaults to the NEW_RELIC_LICENSE_KEY environment variable."),attributes:z$1.record(z$1.string(),z$1.string()).optional().describe("Static attributes (e.g. service, team) added to every event sent to New Relic. Values support ${ENV_VAR} interpolation.")}),yW=z$1.object({newrelic:ebe.optional()}),tbe=z$1.object({category:z$1.string(),reasoning:z$1.string(),citations:z$1.array(Uo).optional()}),nbe=z$1.object({testInputs:z$1.record(z$1.string(),z$1.string()).optional(),envName:z$1.string().optional(),urlOverride:z$1.string().optional()}),obe=z$1.object({reason:z$1.string().optional(),message:z$1.string().optional()}),rbe=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(St),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:nbe.optional(),failure:obe.nullable(),classification:tbe.nullable()}),ibe=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()}),sbe=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()}),SW=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:sbe,runs:z$1.array(rbe),skipped:z$1.array(ibe)});var bW=z$1.enum(["error","warning","passing"]);var TW=z$1.enum(["safe_to_merge","confirm_intended_change","investigate_regression","fix_test","resolve_infra","review_coverage"]);var lbe="One very short, punchy sentence (ideally under 70 characters) summarizing the run group result. Factual, specific, no trailing period, no category prefix. When referencing test names, wrap each in backticks (e.g. `my-test`). No other markdown. Do not capitalize the first word unless it is a proper noun, since a category prefix is prepended before it. Describe the outcome only \u2014 never name the process or mode (no 'dry run', 'auto-heal', 'triage', 'pending'); those are shown separately.";var AW=z$1.object({kind:TW,detail:z$1.string().min(1).max(280)}),bm=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:AW.optional()}),EW=bm.extend({riskLevel:bW.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(120).describe(lbe),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:AW.extend({kind:TW.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 vW=z$1.object({id:z$1.string(),status:z$1.enum(St),trigger:z$1.enum(Us),createdAt:Wn,startedAt:Wn.nullish(),finishedAt:Wn.nullish(),gitCommitSha:z$1.string().nullish(),gitCommitShaShort:z$1.string().nullish(),gitCommitTimestamp:Wn.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:bm.optional(),environments:z$1.string().array().optional(),executionTypes:Nu.array().optional(),localSuiteName:z$1.string().optional(),suite:z$1.object({id:z$1.string(),name:z$1.string()}).nullish(),runs:z$1.object({status:z$1.enum(St)}).array()}),CW=vW.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true,localSuiteName:true}).extend({runs:wC.array()}),RW=vW.extend({runs:ds.array()});var cbe=z$1.object({type:z$1.literal("TARGETING"),name:z$1.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Wz.array(),pageState:z$1.string().optional(),targetSource:z$1.enum(Gl).optional(),targetUpdateTime:z$1.string().optional()}),dbe=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()}),ube=z$1.object({type:z$1.literal("ASSERTION"),relevantElementsSerialized:z$1.string().array().optional(),pageState:z$1.string().optional(),ragUsed:z$1.boolean().optional()}),wW=z$1.discriminatedUnion("type",[cbe,dbe,ube]);var pbe=z$1.object({id:z$1.string(),name:z$1.string()});pbe.extend(z$1.object({createdAt:Wn,createdBy:z$1.string(),schedule:EC,notification:vC,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 IW=z$1.object({id:z$1.guid(),orgId:z$1.string(),createdAt:Wn,startedAt:Wn.or(z$1.null()),finishedAt:Wn.or(z$1.null()),status:z$1.enum(St),trigger:z$1.enum(Us),suite:z$1.object({id:z$1.string(),name:z$1.string()}).nullish(),runs:ds.array()});IW.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true});var xW=IW.extend({runs:wC.array()});function _W({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 IC(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 PW(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 EN=z$1.object({content:z$1.string(),ids:z$1.string().array(),tokenLength:z$1.number()}),mbe=z$1.object({chunks:EN.array()});z$1.object({ids:z$1.string().array(),score:z$1.number(),tokenLength:z$1.number()});mbe.extend({description:z$1.string().describe("Input to pass to RAG engine"),tokenLimit:z$1.number()});var OW=z$1.object({ids:z$1.number().array()}),MW=z$1.object({indices:z$1.number().array()});var al=(n=>(n.Interactive="interactive",n.Runner="runner",n))(al||{}),hbe=z$1.enum(al),hr=z$1.object({disableCache:z$1.boolean().optional(),useMemory:z$1.boolean().optional(),clientMode:hbe.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(FS).optional()});hr.extend({chunks:EN.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 gbe=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()}),NW=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string(),source:zz.optional().catch(void 0),isTieBreakerCall:z$1.boolean().optional(),memory:z$1.discriminatedUnion("type",[Ja,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional(),firstPassModelResults:hC.array().optional(),knowledgeBaseSection:z$1.string().optional()}),LW=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()}),kW=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string().optional(),returnSchema:z$1.string().optional()}),DW=z$1.object({goal:z$1.string(),emulatorState:z$1.string(),screenshot:z$1.string().optional(),returnSchema:z$1.string().optional()}),vN=z$1.union([z$1.literal("NEGATED_CHECK"),z$1.literal("CONDITIONAL_CHECK")]),FW=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string(),url:z$1.string(),contextChoice:lm.optional(),memory:z$1.discriminatedUnion("type",[im,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional(),source:vN.optional(),recoveryHint:z$1.string().optional(),knowledgeBaseSection:z$1.string().optional()}),BW=z$1.object({command:Eu}),CN=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:gbe.array(),actionHint:z$1.string().optional(),lastError:z$1.string().optional()}),UW=z$1.object({results:aC.array(),errorMessage:z$1.string(),errorStack:z$1.string().optional()}),HW=z$1.object({results:aC.array(),goal:z$1.string(),errorMessage:z$1.string()}),jW=z$1.object({failedResults:aC.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 GW=z$1.object({type:z$1.string(),browserContext:z$1.string(),currentStep:z$1.string(),screenshot:z$1.string()}),$W=z$1.object({description:z$1.string(),browserState:z$1.string().optional(),screenshot:z$1.string()}),fbe=z$1.enum(["locator","assertion"]);z$1.object({completionType:fbe,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 VW=z$1.object({keywords:z$1.array(z$1.string())});var xC=(i=>(i.LOCATOR="locator",i.ASSERTION="assertion",i.VISUAL_ASSERTION="visual-assertion",i.TEXT_EXTRACTION="text-extraction",i.FAILURE_RECOVERY="failure-recovery",i))(xC||{}),_C=["locator","assertion","visual-assertion","text-extraction","failure-recovery"];z$1.enum(xC);var ybe=new Set(_C);function Sbe(e){return ybe.has(e)}var bbe=z$1.enum(["v1","v2","v3","v4"]),Tbe=z$1.string().regex(/^v\d+\.\d+$/).describe("pinned sub-version like v3.1");z$1.union([bbe,Tbe,z$1.string().describe("for people with special configurations")]);var ku={locator:"v4.2",assertion:"v4.1","visual-assertion":"v4.0","text-extraction":"v3.0","failure-recovery":"v2.1"},PC={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"]}},zW=(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))(zW||{});z$1.enum(zW);var Abe={locator:["v1"],assertion:["v1"],"visual-assertion":["v1"],"text-extraction":["v1"]};function OC(e){let t=Abe[e];if(!t)return new Set;let n=PC[e],o=new Set;for(let r of t){o.add(r);for(let i of n[r]??[])o.add(i);}return o}function MC(e){for(let[t,n]of Object.entries(e)){if(!Sbe(t))continue;let o=PC[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 oe("UserConfigurationError",`Invalid agent config: "${n}" is not a valid version for "${t}". Valid versions: ${i.join(", ")}`)}if(OC(t).has(n))throw new oe("UserConfigurationError",`Agent config "${n}" for "${t}" is no longer supported because it relies on a legacy model. Upgrade to a newer version.`)}}var pd=P__default.object({id:P__default.guid(),envKey:P__default.string().optional(),skipped:P__default.boolean().optional(),retries:P__default.number().optional()});var md=(r=>(r.PRESET="MOBILE_PRESET_STEP",r.MODULE="MOBILE_MODULE_STEP",r.AI_ACTION="MOBILE_AI_ACTION_STEP",r.CONDITIONAL="MOBILE_CONDITIONAL_STEP",r))(md||{});var Lg=pd.extend({type:P__default.literal("MOBILE_CONDITIONAL_STEP")});var li=z$1.object({id:z$1.string(),name:zv,baseUrl:Wv,description:z$1.string().optional().nullish(),schemaVersion:z$1.string(),advanced:Bi,retries:z$1.number().optional().nullish(),envs:z$1.array(mW).nullish(),parameters:pW.nullish(),disabled:z$1.boolean().optional(),labels:z$1.array(z$1.string()).optional().catch([])}),WW=z$1.enum(["INHERIT","ENABLED","DISABLED"]);var vbe=Bi.shape.geolocation.unwrap().partial().superRefine(({latitude:e,longitude:t},n)=>{e!==void 0&&t===void 0&&n.addIssue({code:"custom",message:"Longitude is required when latitude is provided",path:["longitude"]}),t!==void 0&&e===void 0&&n.addIssue({code:"custom",message:"Latitude is required when longitude is provided",path:["latitude"]});}),Cbe=Bi.shape.proxy.unwrap().partial().superRefine(({server:e,username:t,password:n},o)=>{!e&&(t||n)&&o.addIssue({code:"custom",message:"Proxy host is required when credentials are provided",path:["server"]});}),Rbe=Bi.extend({failureRecovery:WW.optional(),geolocation:vbe.optional(),proxy:Cbe.optional(),useMemory:WW.optional()});li.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,parameters:true}).extend({advanced:Rbe});li.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,advanced:true,parameters:true});var wbe=z$1.object({labels:z$1.array(z$1.string()).optional(),outputs:CC.nullish()}),lo=li.extend(wbe.shape),Ibe=z$1.object({createdAt:z$1.coerce.date(),updatedAt:z$1.coerce.date(),updatedBy:z$1.string().nullable(),schedule:EC,notification:vC,createdBy:z$1.string(),organizationId:z$1.string(),folderId:z$1.string().nullable().optional()}),xbe=li.extend(Ibe.shape);xbe.extend(Ls.shape);var RN=li.extend(Ls.shape);li.extend(rd.shape);var _be="test",Pbe="module",Obe="mobile-test",Mbe="mobile-module",Nbe="test/v2",Lbe="module/v2",kbe="mobile-test/v2",Dbe="mobile-module/v2";var Fe=(l=>(l.TEST=`momentic/${_be}`,l.MODULE=`momentic/${Pbe}`,l.TEST_V2=`momentic/${Nbe}`,l.MODULE_V2=`momentic/${Lbe}`,l.MOBILE_TEST=`momentic/${Obe}`,l.MOBILE_MODULE=`momentic/${Mbe}`,l.MOBILE_TEST_V2=`momentic/${kbe}`,l.MOBILE_MODULE_V2=`momentic/${Dbe}`,l))(Fe||{});li.merge(rd);var Fbe=so.extend({steps:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())),schemaVersion:z$1.string()}),Mb=Fbe.extend({fileType:z$1.literal(Fe.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 NC(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(NC);let t={};for(let[n,o]of Object.entries(e))t[n]=NC(o);return t}var Bbe=/^[a-z0-9]+(?:-[a-z0-9]+){2,}$/,qW=36,co=z$1.union([z$1.guid().max(qW,"V2 IDs must be 36 characters or fewer"),z$1.string().max(qW,"V2 IDs must be 36 characters or fewer").regex(Bbe,"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 LC=P.discriminatedUnion("type",[P.object({type:P.literal("SCREEN")}),P.object({type:P.literal("OPEN_APP")}),P.object({type:P.literal("OPEN_WEBVIEW")})]),hd=P.object({type:P.literal("description"),description:P.string()}),IN=P.object({type:P.literal("CUSTOM_COORDINATES"),startX:P.number().describe("Starting X coordinate in pixels"),startY:P.number().describe("Starting Y coordinate in pixels"),deltaPixels:P.number().describe("Number of pixels to scroll in the specified direction")}),kC=P.discriminatedUnion("type",[...LC.options,P.object({type:P.literal("CUSTOM"),target:hd}),IN]);function Ube(e){return e.toLowerCase().replaceAll("_"," ")}function xN(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 Ube(e.type);default:{throw new Error("Unreachable")}}}var Hbe=P.object({type:P.literal("coordinates"),xPercent:P.number(),yPercent:P.number()}),jbe=P.object({type:P.literal("absolute_percent"),x:P.number(),y:P.number()}),kg=P.discriminatedUnion("type",[hd,Hbe,jbe]);var Gbe=P.object({x1:P.number(),y1:P.number(),x2:P.number(),y2:P.number(),tolerance:P.nativeEnum(ss),preciseTolerance:P.boolean().optional()}),$be=P.object({width:P.number(),height:P.number(),tolerance:P.nativeEnum(ss),preciseTolerance:P.boolean().optional()}),_N=P.object({requiredText:P.string().optional(),requiredAttributes:P.record(P.string(),P.string()).optional(),requiredBounds:P.boolean().optional(),position:Gbe.optional(),shape:$be.optional()}),KW=P.object({xPath:P.string(),requirements:_N.optional()}),Vbe=P.object({type:P.literal("CUSTOM"),target:hd,cache:P.lazy(()=>YW).optional()}),zbe=P.object({pixelDelta:P.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:P.union([LC,Vbe,IN]),direction:P.enum(["up","down"])}),YW=P.object({type:P.literal("NATIVE"),bounds:P.number().array().optional(),resolvedDescription:P.string().optional(),xPath:P.string().optional(),elementOnlySerializedXml:P.string().optional(),scrollDetails:zbe.optional(),requirements:_N.optional(),requiredRelatedElements:KW.array().optional(),memory:Ja.optional()}),Wbe=P.object({type:P.literal("WEBVIEW"),resolvedDescription:P.string().optional(),xPath:P.string().optional(),browserCache:$l.optional(),memory:Ja.optional()}),DC=P.union([YW,Wbe]);var qbe=P.object({left:P.number(),top:P.number(),right:P.number(),bottom:P.number()});P.object({newViewportBounds:qbe});var Kbe=P.object({type:P.literal("CUSTOM"),target:hd,cache:P.lazy(()=>ZW).optional()}),JW=P.object({pixelDelta:P.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:P.union([LC,Kbe,IN]),direction:P.enum(["up","down"])}),XW=(n=>(n.Native="native",n.Appium="appium",n))(XW||{}),PN=P.tuple([P.number(),P.number(),P.number(),P.number()]),QW=KW.extend({bounds:PN.optional(),browserCache:$l.optional()}),ZW=P.object({type:P.literal("NATIVE"),bounds:PN.optional(),resolvedDescription:P.string().optional(),sourceTree:P.nativeEnum(XW).optional(),xPath:P.string().optional(),elementOnlySerializedXml:P.string().optional(),scrollDetails:JW.optional(),requirements:_N.optional(),requiredRelatedElements:QW.array().optional(),memory:Ja.optional()}),Ybe=P.object({type:P.literal("WEBVIEW"),bounds:PN.optional(),resolvedDescription:P.string().optional(),xPath:P.string().optional(),scrollDetails:JW.optional(),browserCache:$l.optional(),requiredRelatedElements:QW.array().optional(),memory:Ja.optional()}),FC=P.discriminatedUnion("type",[ZW,Ybe]);var Jt=(x=>(x.AI_CHECK="AI_CHECK",x.AI_EXTRACT="AI_EXTRACT",x.TAP="TAP",x.TYPE="TYPE",x.PRESS="PRESS",x.PRESS_KEYBOARD="PRESS_KEYBOARD",x.OPEN_APP="OPEN_APP",x.KILL_APP="KILL_APP",x.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",x.SWIPE="SWIPE",x.SCROLL_TO="SCROLL_TO",x.SCREEN_CHECK="SCREEN_CHECK",x.ELEMENT_CHECK="ELEMENT_CHECK",x.VISUAL_DIFF="VISUAL_DIFF",x.DRAG_AND_DROP="DRAG_AND_DROP",x.JAVASCRIPT="JAVASCRIPT",x.REQUEST="REQUEST",x.WAIT="WAIT",x.ADD_FILE="ADD_FILE",x.INSTALL_APP="INSTALL_APP",x.UNINSTALL_APP="UNINSTALL_APP",x.TOGGLE_SETTINGS="TOGGLE_SETTINGS",x.ROTATE_ORIENTATION="ROTATE_ORIENTATION",x.ADB_COMMAND="ADB_COMMAND",x.APPIUM_EXECUTE="APPIUM_EXECUTE",x.STATE="STATE",x))(Jt||{}),Qe=P__default.object({id:P__default.guid(),disableCache:P__default.boolean().optional()}),Dg=P__default.object({updatedAt:P__default.coerce.date().optional(),updatedAtLoggerTags:P__default.record(P__default.string(),P__default.string()).optional()}),wa=Dg.extend({target:DC}),BC=Dg.extend({fromTarget:DC,toTarget:DC}),lc=Dg.extend({target:FC}),e1=Dg.extend({fromTarget:FC,toTarget:FC}),gd=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 t1=Qe.extend({type:P__default.literal("ADB_COMMAND"),command:P__default.string(),jsonArgs:P__default.string().optional()});var Jbe=P__default.string().trim(),o1=Qe.extend({type:P__default.literal("INSTALL_APP"),uri:Jbe});var r1=Qe.extend({type:P__default.literal("OPEN_NOTIFICATION_DRAWER")});var Nb=(r=>(r.AIRPLANE_MODE="AIRPLANE_MODE",r.DATA="DATA",r.WIFI="WIFI",r.LOCATION="LOCATION",r))(Nb||{}),s1=Qe.extend({type:P__default.literal("TOGGLE_SETTINGS"),settingsType:P__default.nativeEnum(Nb)});var l1=Qe.extend({type:P__default.literal("UNINSTALL_APP"),packageName:P__default.string()});var UC=Qe.extend({type:P__default.literal("APPIUM_EXECUTE"),command:P__default.string(),jsonArgs:P__default.string().optional()});var c1=Qe.extend({type:P__default.literal("ADD_FILE"),file:P__default.string(),storageLocation:P__default.string()});var fd=Qe.extend({type:P__default.literal("AI_CHECK"),assertion:P__default.string(),timeoutSecs:P__default.number().optional(),contextChoice:lm.optional(),cache:Dg.extend({memory:im.optional()}).optional()});var d1=Qe.extend({type:P__default.literal("AI_EXTRACT"),goal:P__default.string(),schema:P__default.string().optional()});var Fg=Qe.extend({type:P__default.literal("JAVASCRIPT"),code:P__default.string(),timeout:P__default.number().int().max(600).optional().describe("Max seconds for the code to complete")});var u1=Qe.extend({type:P__default.literal("KILL_APP")});var kb=(n=>(n.HOME="HOME",n.POWER="POWER",n))(kb||{}),HC=(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))(HC||{}),jC=Qe.extend({type:P__default.literal("PRESS"),key:P__default.nativeEnum(kb),longPress:P__default.boolean().optional()}),p1=jC.extend({key:P__default.nativeEnum(HC).or(P__default.nativeEnum(kb))}),m1=jC;var h1=Qe.extend({type:P__default.literal("REQUEST")}).merge(HS);var FN=(n=>(n.PORTRAIT="PORTRAIT",n.LANDSCAPE="LANDSCAPE",n))(FN||{}),f1=Qe.extend({type:P__default.literal("ROTATE_ORIENTATION"),orientation:P__default.nativeEnum(FN)});var eTe=P__default.object({type:P__default.literal("CONTENT"),negated:P__default.boolean().optional(),value:P__default.string()}),Ug=Qe.extend({type:P__default.literal("SCREEN_CHECK"),assertion:eTe,timeout:P__default.number().int().min(0).max(ig).optional().describe("max seconds to wait for the assertion to be true")});var y1=Qe.extend({type:P__default.literal("STATE")});var S1=Qe.extend({type:P__default.literal("VISUAL_DIFF"),path:P__default.string().describe("path to the golden screenshot to compare against"),threshold:P__default.number().min(0).max(1).optional().describe("max allowed fraction of differing pixels before the diff fails (default 0.1)")});P__default.object({created:P__default.boolean(),goldenPath:P__default.string(),threshold:P__default.number(),goldenScreenshotBase64:P__default.string().optional(),currentScreenshotBase64:P__default.string().optional(),diffScreenshotBase64:P__default.string().optional(),goldenScreenshotSnapshotId:P__default.string().optional(),currentScreenshotSnapshotId:P__default.string().optional(),diffScreenshotSnapshotId:P__default.string().optional(),diffPercent:P__default.number().optional(),pass:P__default.boolean().optional(),dimensionMismatch:P__default.boolean().optional()});var T1=Qe.extend({type:P__default.literal("WAIT"),timeoutSecs:P__default.number()});var Db=P__default.discriminatedUnion("type",[y1,fd,d1,Fg,T1,h1,f1,Ug,S1,c1,u1]);P__default.discriminatedUnion("type",[...Db.options,jC]);var UN=Qe.extend({type:P__default.literal("DRAG_AND_DROP"),fromTarget:hd,toTarget:hd,hoverDuration:P__default.number().optional(),dragDuration:P__default.number().optional()}),Fb=UN.extend({cache:BC.optional()}),Bb=UN.extend({cache:e1.optional()});var HN=Qe.extend({type:P__default.literal("ELEMENT_CHECK"),target:kg,assertion:Ov,timeout:P__default.number().int().min(0).max(ig).optional().describe("max seconds to wait for the assertion to be true")}),Tm=HN.extend({cache:wa.optional()}),Am=HN.extend({cache:lc.optional()});var Ub=(n=>(n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(Ub||{}),GC=(t=>(t.CLOSE_KEYBOARD="CLOSE_KEYBOARD",t))(GC||{}),v1={repeat:P__default.number().int().min(1).optional(),keyPressDelayMs:P__default.number().min(0).optional()},C1=Qe.extend({type:P__default.literal("PRESS_KEYBOARD"),key:P__default.nativeEnum(Ub),...v1}),R1=Qe.extend({type:P__default.literal("PRESS_KEYBOARD"),key:P__default.nativeEnum(GC).or(P__default.nativeEnum(Ub)),...v1});var w1=Qe.extend({type:P__default.literal("OPEN_APP"),packageName:P__default.string(),activityName:P__default.string().optional(),intentExtras:P__default.string().optional()}),I1=Qe.extend({type:P__default.literal("OPEN_APP"),packageName:P__default.string(),intentExtras:P__default.string().optional()});var jN=Qe.extend({type:P__default.literal("SCROLL_TO"),target:hd,direction:P__default.enum(["down","up"]),scrollableElement:kC,scrollStepPercent:P__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:P__default.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 20.")}),Hb=jN.extend({cache:wa.optional()}),jb=jN.extend({cache:lc.optional()});var GN=Qe.extend({type:P__default.literal("SWIPE"),direction:P__default.enum(["up","down","left","right"]),scrollableElement:kC,viewportPercent:P__default.number().optional(),durationMs:P__default.number().optional(),relativePosition:_v.optional()}),Gb=GN.extend({cache:wa.optional()}),$b=GN.extend({cache:lc.optional()});var $N=Qe.extend({type:P__default.literal("TAP"),target:kg,longPress:P__default.boolean().optional(),longPressDurationMs:P__default.number().optional(),iterations:P__default.number().optional(),tapDelayMs:P__default.number().optional(),relativePosition:_v.optional(),doubleTap:P__default.boolean().optional(),doubleTapDelayMs:P__default.number().optional()}),Vb=$N.extend({cache:wa.optional()}),zb=$N.extend({cache:lc.optional()});var Wb=(r=>(r.AUTO="auto",r.PROGRAMMATIC="programmatic",r.LONG_PRESS="long-press",r.BACKSPACE="backspace",r))(Wb||{});var VN=Qe.extend({type:P__default.literal("TYPE"),target:kg.optional(),keyPressDelayMs:P__default.number().optional(),text:P__default.string(),clearContent:P__default.boolean().optional(),forceClearContent:P__default.boolean().optional(),replaceStrategy:P__default.nativeEnum(Wb).optional()});var qb=VN.extend({cache:wa.optional()}),Kb=VN.extend({cache:lc.optional()});var Yb=P__default.discriminatedUnion("type",[...Db.options,Vb,qb,p1,R1,l1,o1,t1,UC,Fb,r1,Hb,Gb,s1,Tm,w1]);var Jb=P__default.discriminatedUnion("type",[...Db.options,zb,Kb,m1,C1,I1,$b,Bb,jb,Am,UC]);var P1=P__default.union([P__default.string(),P__default.record(P__default.string(),P__default.unknown().optional())]),zC=pd.extend({type:P__default.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:P__default.number().optional()}),Fu=zC.extend({command:Yb}),Bu=zC.extend({command:Jb}),jg=P__default.object({moduleId:P__default.string(),inputs:P__default.record(P__default.string(),P__default.string()).optional()}),Xb=pd.merge(jg.extend({type:P__default.literal("MOBILE_MODULE_STEP")}));jg.extend({steps:P__default.lazy(()=>cc.array())});jg.extend({steps:P__default.lazy(()=>yd.array())});var zN=(n=>(n.V2="2",n.V3="3",n))(zN||{});var WN=P__default.nativeEnum(zN),iTe=jl.extend({platform:P__default.literal("ANDROID"),resolvedGoal:P__default.string(),steps:P__default.lazy(()=>Fu.array()),autoGeneratedPostcondition:P__default.string().optional()}),sTe=jl.extend({platform:P__default.literal("IOS"),resolvedGoal:P__default.string(),steps:P__default.lazy(()=>Bu.array()),autoGeneratedPostcondition:P__default.string().optional()}),qN=P__default.discriminatedUnion("platform",[iTe,sTe]),Uu=pd.extend({type:P__default.literal("MOBILE_AI_ACTION_STEP"),text:P__default.string(),version:WN.optional(),cache:qN.optional(),precondition:P__default.string().optional(),postcondition:P__default.string().optional()});var lTe=P__default.discriminatedUnion("type",[fd,Ug,Tm,Fg]),KN=zC.extend({command:lTe}),cTe=P__default.discriminatedUnion("type",[fd,Ug,Am,Fg]),YN=zC.extend({command:cTe}),dTe=P__default.object({assertion:KN,steps:P__default.lazy(()=>cc.array())}),uTe=P__default.object({assertion:YN,steps:P__default.lazy(()=>yd.array())}),pTe=Lg.extend({blocks:P__default.lazy(()=>dTe.array()),elseSteps:P__default.lazy(()=>cc.array()).optional()}),mTe=Lg.extend({blocks:P__default.lazy(()=>uTe.array()),elseSteps:P__default.lazy(()=>yd.array()).optional()}),cc=P__default.discriminatedUnion("type",[Fu,Xb,Uu,pTe]),yd=P__default.discriminatedUnion("type",[Bu,Xb,Uu,mTe]);P__default.union([cc.array(),yd.array()]);var JN=P__default.object({parameterNames:P__default.string().array(),defaultParameters:P__default.record(P__default.string(),P__default.string()).optional(),parameterEnums:P__default.record(P__default.string(),P__default.string().array()).optional()}),WC=P__default.object({moduleId:co,name:P__default.string(),description:P__default.string().nullish(),platform:P__default.nativeEnum(rl).optional().default("ANDROID"),parameters:JN.optional(),enabled:P__default.boolean().nullish(),schemaVersion:P__default.string()}),XN=WC.omit({name:true}),hTe=XN.extend({steps:P1.array()});P__default.object({fileType:P__default.literal(Fe.MOBILE_MODULE)}).merge(hTe);var O1=WC.omit({platform:true,schemaVersion:true});({ANDROID:O1.extend({platform:P__default.literal("ANDROID"),steps:cc.array()}),IOS:O1.extend({platform:P__default.literal("IOS"),steps:yd.array()})});var Gg=(t=>(t.MODULE="RESOLVED_MOBILE_MODULE",t))(Gg||{}),M1=P__default.object({description:P__default.string().optional(),name:P__default.string().describe("name of the module"),parameters:JN.optional()}),N1=jg.merge(M1).extend({platform:P__default.literal("ANDROID"),get steps(){return cl.array()}}),L1=jg.merge(M1).extend({platform:P__default.literal("IOS"),get steps(){return dl.array()}});P__default.discriminatedUnion("platform",[N1,L1]);var QN=pd.merge(N1).extend({type:P__default.literal("RESOLVED_MOBILE_MODULE")}),ZN=pd.merge(L1).extend({type:P__default.literal("RESOLVED_MOBILE_MODULE")});P__default.discriminatedUnion("platform",[QN,ZN]);var gTe=P__default.object({assertion:KN,get steps(){return cl.array()}}),eL=Lg.extend({get blocks(){return gTe.array()},get elseSteps(){return cl.array().optional()}}),fTe=P__default.object({assertion:YN,get steps(){return dl.array()}}),tL=Lg.extend({get blocks(){return fTe.array()},get elseSteps(){return dl.array().optional()}}),cl=P__default.discriminatedUnion("type",[QN,Fu,Uu,eL]),dl=P__default.discriminatedUnion("type",[ZN,Bu,Uu,tL]);function k1(e){return Object.values(Gg).includes(e)||Object.values(md).includes(e)}var D1=(i=>(i.PRECONDITION="PRECONDITION",i.REPLAY="REPLAY",i.GENERATE="GENERATE",i.AUTOHEAL="AUTOHEAL",i.POSTCONDITION="POSTCONDITION",i))(D1||{}),F1=z$1.enum(["pending","running","success","failed"]),B1=z$1.object({type:z$1.literal("THOUGHT"),text:z$1.string(),blockId:z$1.string().optional()}),U1=z$1.object({type:z$1.literal("TOOL_CALL"),toolName:z$1.string()}),H1=z$1.object({type:z$1.literal("PHASE"),phase:z$1.nativeEnum(D1),failureMessage:z$1.string().optional()}),yTe=z$1.object({type:z$1.literal("STEP_UPDATE"),stepIndex:z$1.number(),step:cl,status:F1,message:z$1.string().optional(),afterSnapshotId:z$1.string().optional()}),STe=z$1.object({type:z$1.literal("STEP_UPDATE"),stepIndex:z$1.number(),step:dl,status:F1,message:z$1.string().optional(),afterSnapshotId:z$1.string().optional()}),j1=z$1.object({type:z$1.literal("SCREENSHOT"),stepIndex:z$1.number(),screenshotId:z$1.string()}),G1=z$1.object({type:z$1.literal("POSTCONDITION_AUTOGENERATED"),postcondition:z$1.string()}),bTe=z$1.object({type:z$1.literal("CACHED_STEPS_GENERATED"),cachedSteps:Fu.array(),resolvedGoal:z$1.string()}),TTe=z$1.object({type:z$1.literal("CACHED_STEPS_GENERATED"),cachedSteps:Bu.array(),resolvedGoal:z$1.string()}),ATe=z$1.discriminatedUnion("type",[B1,U1,H1,yTe,j1,bTe,G1]),ETe=z$1.discriminatedUnion("type",[B1,U1,H1,STe,j1,TTe,G1]);function $1(e){let t=z$1.object({version:z$1.literal(1),events:e.array(),spans:YM.array().optional()});return z$1.union([t,e.array()]).transform(n=>Array.isArray(n)?{version:1,events:n}:n)}var V1=$1(ATe),z1=$1(ETe);var dc=P__default.object({message:P__default.string().optional(),startTime:P__default.number(),endTime:P__default.number(),status:P__default.nativeEnum(Bt),trace:P__default.unknown().optional().optional(),beforeSnapshot:P__default.string().optional(),afterSnapshot:P__default.string().optional(),data:P__default.unknown().optional().optional().describe("output data from the step"),aiSuggested:P__default.boolean().optional(),beforeTestContext:vg.optional(),afterTestContext:vg.optional()}),W1=dc.merge(Fu).extend({previousAttempts:P__default.lazy(()=>js.array()).optional()}),vTe=dc.merge(Xb).extend({steps:P__default.lazy(()=>js.array()),name:P__default.string().optional(),previousAttempts:P__default.lazy(()=>js.array()).optional()}),CTe=dc.merge(Uu).extend({steps:P__default.lazy(()=>js.array()),previousAttempts:P__default.lazy(()=>js.array()).optional(),failureRecoveryReason:P__default.string().optional(),trajectory:V1.optional()}),RTe=dc.merge(eL).extend({assertionResult:W1.optional(),steps:P__default.lazy(()=>js.array()),previousAttempts:P__default.lazy(()=>js.array()).optional()}),js=P__default.discriminatedUnion("type",[W1,vTe,CTe,RTe]),q1=dc.merge(Bu).extend({previousAttempts:P__default.lazy(()=>Gs.array()).optional()}),wTe=dc.merge(Xb).extend({steps:P__default.lazy(()=>Gs.array()),name:P__default.string().optional(),previousAttempts:P__default.lazy(()=>Gs.array()).optional()}),ITe=dc.merge(Uu).extend({steps:P__default.lazy(()=>Gs.array()),previousAttempts:P__default.lazy(()=>Gs.array()).optional(),failureRecoveryReason:P__default.string().optional(),trajectory:z1.optional()}),xTe=dc.merge(tL).extend({assertionResult:q1.optional(),steps:P__default.lazy(()=>Gs.array()),previousAttempts:P__default.lazy(()=>Gs.array()).optional()}),Gs=P__default.discriminatedUnion("type",[q1,wTe,ITe,xTe]);var _Te=dc.extend({index:P__default.number().optional(),userFacingStepReference:P__default.string().optional(),description:P__default.string()}),K1=_Te.extend({beforeScreenshot:P__default.string().optional(),afterScreenshot:P__default.string().optional()});var Y1=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(ss).optional(),shapeSpecificity:z$1.enum(ss).optional()}),PTe=z$1.object({id:z$1.number(),requirements:Y1}).array();z$1.object({thoughts:z$1.string(),id:z$1.number(),updatedMemory:kS.optional(),inWebview:z$1.boolean().optional(),requirements:Y1.optional(),additionalElements:PTe.optional()});var OTe=z$1.literal("SCROLL_TO"),J1=z$1.object({description:z$1.string(),screenXml:z$1.string(),screenshot:z$1.string(),source:OTe.optional(),memory:z$1.discriminatedUnion("type",[Ja,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional()}),X1=z$1.object({assertion:z$1.string(),screenXml:z$1.string(),screenshot:z$1.string(),contextChoice:lm.optional(),memory:z$1.discriminatedUnion("type",[im,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:DS.optional()});var Q1=z$1.object({failedResults:K1.array(),nextStepsSerialized:z$1.string().array(),currentScreenXml:z$1.string(),currentScreenshot:z$1.string(),customInstructions:z$1.string().optional(),testDescription:z$1.string()}),Z1=(o=>(o.LEGITIMATE="LEGITIMATE",o.RECOVERABLE="RECOVERABLE",o.INELIGIBLE="INELIGIBLE",o))(Z1||{});z$1.object({thoughts:z$1.string(),scenario:z$1.enum(Z1),instructions:z$1.string().nullish(),reasonSummary:z$1.string().nullish()});z$1.looseObject({type:z$1.literal("response.create")});var eq=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 tq="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 $g=(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))($g||{}),Hi=(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))(Hi||{}),MTe=3;function NTe(e){return e==="MODULE"||e==="CONDITIONAL"||e==="WHILE_LOOP"||e==="SECTION"||e==="RESOLVED_MODULE"}function nq(e){if(!NTe(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 oq(e){switch(e.type){case "AI_EXTRACT":case "AI_ASSERTION":return MTe;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 nL=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 qC(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=nL.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 DTe=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()}),FTe=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()}),KC=z$1.object({cookies:nL.array().optional(),origins:DTe.array().optional(),idb:z$1.record(z$1.string(),FTe).optional().describe("key is db name")});function rq(e,t){let n=[];return e.cloneSync()?.serializeSync()?.cookies.forEach(o=>{let r=nL.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 us={type:true,cache:true},iq=[fd.pick(us),Tm.pick(us),Vb.pick(us),qb.pick(us),Gb.pick(us),Hb.pick(us),Fb.pick(us)],oL=P__default.discriminatedUnion("type",iq),sq=[fd.pick(us),Am.pick(us),zb.pick(us),Kb.pick(us),$b.pick(us),Bb.pick(us),jb.pick(us)],rL=P__default.discriminatedUnion("type",sq);Object.values(Jt).filter(e=>iq.some(t=>t.shape.type.safeParse(e).success));Object.values(Jt).filter(e=>sq.some(t=>t.shape.type.safeParse(e).success));var iL=P__default.object({type:P__default.literal("MOBILE_AI_ACTION_STEP"),cache:qN}),YC=P__default.union([oL,iL]),JC=P__default.union([rL,iL]);var sL=(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))(sL||{}),aL=(o=>(o.US="us",o.EU="eu",o.AS="as",o))(aL||{}),aq=(t=>(t.LOCAL="local",t))(aq||{}),lL=P__default.nativeEnum(sL).or(P__default.nativeEnum(aL)),cL=P__default.nativeEnum(sL).or(P__default.nativeEnum(aL)).or(P__default.nativeEnum(aq)),UTe="closest";cL.or(P__default.literal(UTe));var zg=(n=>(n.ANDROID_14="14",n.ANDROID_15="15",n))(zg||{});var XC=(t=>(t.IOS_26="26",t))(XC||{});var HTe=["1.56.1-lim.1","1.60.0-lim.1"],lq=P__default.enum(HTe);var cq=P__default.nativeEnum(zg).or(P__default.nativeEnum(XC));var jTe=P__default.object({disableMomenticAccessibilityTree:P__default.boolean().optional(),autoGrantPermissions:P__default.boolean().optional().describe("Automatically grant app permission prompts during the run. Android only."),autoAcceptAlerts:P__default.boolean().optional().describe("Automatically accept native alert dialogs. iOS only."),autoDismissAlerts:P__default.boolean().optional().describe("Automatically dismiss native alert dialogs. iOS only."),disableXmlSnapshots:P__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:Pg.optional(),locale:P__default.string().optional().describe("Device locale code (e.g. 'fr', 'en-us'). Sets the device language and region. iOS and Android.")}),GTe="avdId",$Te="iosDeviceType",VTe="iosVersion",dL=jTe.extend({region:cL.optional().describe('Where the emulator runs: "local" for an emulator on your machine, or a region for hosted emulators. Defaults to hosted emulators.'),remoteEmulatorSettings:P__default.object({androidVersion:P__default.nativeEnum(zg).optional()}).optional(),localEmulatorSettings:P__default.object({[GTe]:xg,[$Te]:xg,[VTe]:xg}).optional(),geolocation:P__default.object({latitude:P__default.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:P__default.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),waitForStability:P__default.boolean().optional().describe("wait for stability before every targeting action")});var Zb=P__default.object({retries:P__default.number().optional().describe("number of retries to run"),defaultChannel:P__default.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:P__default.string().optional().describe("Default app artifact tag to use. If not set, the latest available tag is used."),defaultEnv:P__default.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:xg.describe("APK to install when using the emulator in the local region."),defaultAppFilePath:xg.describe("App file (e.g. .app or .ipa) to install when using the emulator in the local region."),emulator:dL.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:TN.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),dq=P__default.object({id:co,description:P__default.string(),schemaVersion:P__default.string(),settings:Zb.optional(),disabled:P__default.boolean().optional(),labels:P__default.array(P__default.string()).optional()}),Wg=dq.extend({platform:P__default.literal("ANDROID").optional().default("ANDROID")}),qg=dq.extend({platform:P__default.literal("IOS")}),uq=P__default.discriminatedUnion("platform",[Wg,qg]),pq=P__default.object({fileType:P__default.literal(Fe.MOBILE_TEST)}),mq=pq.merge(Wg),hq=pq.merge(qg);P__default.discriminatedUnion("platform",[mq,hq]);var gq=Wg.merge(P__default.object({steps:P__default.array(cc)})),fq=qg.merge(P__default.object({steps:P__default.array(yd)}));P__default.discriminatedUnion("platform",[gq,fq]);var zTe=mq.merge(gq),WTe=hq.merge(fq);P__default.discriminatedUnion("platform",[zTe,WTe]);P__default.object({name:P__default.string(),steps:P__default.array(cc).optional(),settings:Zb.optional()});var yq=Wg.extend({steps:cl.array(),beforeSteps:cl.array().optional(),afterSteps:cl.array().optional()}),Sq=qg.extend({steps:dl.array(),beforeSteps:dl.array().optional(),afterSteps:dl.array().optional()});P__default.discriminatedUnion("platform",[yq,Sq]);var qTe=yq.extend({name:P__default.string()}),KTe=Sq.extend({name:P__default.string()});P__default.discriminatedUnion("platform",[qTe,KTe]);var _r=P__default.object({startTime:P__default.number(),endTime:P__default.number().optional(),durationMs:P__default.number().optional(),error:P__default.string().optional(),result:P__default.unknown().optional().optional(),attributes:P__default.record(P__default.string(),P__default.unknown().optional()),subSpans:P__default.lazy(()=>pAe.array())});var uL=_r.extend({type:P__default.literal("SECTION"),name:P__default.string()}),YTe=_r.extend({type:P__default.literal("GET_PAGE_STATE")}),JTe=_r.extend({type:P__default.literal("GET_PAGE_SCREENSHOT")}),XTe=_r.extend({type:P__default.literal("SMART_WAITING")}),QTe=_r.extend({type:P__default.literal("SCROLL_ELEMENT_INTO_VIEW")}),ZTe=_r.extend({type:P__default.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:P__default.string().optional(),result:P__default.object({id:P__default.number(),thoughts:P__default.string(),citations:Uo.array().optional()}).optional()}),eAe=_r.extend({type:P__default.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:P__default.string().optional(),elementScreenshotSnapshotId:P__default.string().optional(),result:P__default.object({thoughts:P__default.string(),result:P__default.boolean(),citations:Uo.array().optional()}).optional()}),tAe=_r.extend({type:P__default.literal("AI_EXTRACTION_CALL"),screenshotSnapshotId:P__default.string().optional(),browserStateSnapshotId:P__default.string().optional(),result:P__default.object({thoughts:P__default.string().optional(),result:P__default.unknown().optional().optional()}).optional()}),nAe=_r.extend({type:P__default.literal("ELEMENT_ASSERTION"),name:P__default.string(),result:P__default.object({success:P__default.boolean(),message:P__default.string().optional()}).optional()}),oAe=_r.extend({type:P__default.literal("BROWSER_INTERACTION"),name:P__default.string(),coordinates:P__default.object({x:P__default.number(),y:P__default.number()}).optional(),value:P__default.string().optional(),selector:P__default.string().optional()}),rAe=_r.extend({type:P__default.literal("CACHE_RESOLUTION"),resolutionMethod:P__default.string().optional(),cacheMissReason:P__default.nativeEnum(Xh).optional(),targetSource:P__default.string().optional(),elementScreenshotSnapshotId:P__default.string().optional(),result:P__default.object({serializedElement:P__default.string()}).optional()}),iAe=_r.extend({type:P__default.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:P__default.string().optional(),result:P__default.object({serializedElement:P__default.string()}).optional()}),sAe=_r.extend({type:P__default.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:P__default.string().optional(),result:P__default.object({outcome:P__default.string(),logs:P__default.string().array().optional(),serializedElement:P__default.string().optional(),relativeClickPoint:P__default.object({x:P__default.number(),y:P__default.number()}).optional(),force:P__default.boolean().optional()}).optional()}),aAe=_r.extend({type:P__default.literal("WAIT_FOR_STABILITY")}),lAe=_r.extend({type:P__default.literal("GENERIC"),name:P__default.string()}),cAe=_r.extend({type:P__default.literal("PAGE_ASSERTION"),name:P__default.string(),result:P__default.object({success:P__default.boolean(),message:P__default.string().optional()}).optional()}),dAe=_r.extend({type:P__default.literal("AUTO_FOLLOW_NEW_TABS"),result:P__default.object({followed:P__default.boolean()}).optional()}),uAe=_r.extend({type:P__default.literal("VISUAL_DIFF"),name:P__default.string(),result:P__default.object({success:P__default.boolean(),message:P__default.string().optional()}).optional()});function bq(e){return e.type==="CACHE_RESOLUTION"||e.type==="TARGET_RESOLUTION"}var pAe=P__default.discriminatedUnion("type",[uL,YTe,JTe,XTe,QTe,ZTe,eAe,tAe,nAe,oAe,iAe,rAe,sAe,aAe,cAe,uAe,lAe,dAe]);z$1.object({testId:z$1.string(),sessionId:z$1.string()});var Tq=z$1.object({uploadUrl:z$1.string(),id:z$1.string()});new Set(Object.values(eo));var Rn={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 mAe=z$1.string().refine(e=>Jd.valid(e),{error:"must be a valid semver string"});function pL(e){return Jd.parse(e)||void 0}function eT(e){if(e!==void 0)return e===true||e==="true"||e==="1"}var Eq="on-fail";function vq(e){return e==="on-fail"?"on-fail":e==="false"?false:!!e}var Cq=(n=>(n.CLI="cli",n.MobileCLI="mobile-cli",n))(Cq||{}),hAe=z$1.nativeEnum(Cq),Rq=(o=>(o.Error="error",o.Warn="warn",o.Info="info",o))(Rq||{}),gAe=z$1.nativeEnum(Rq),fAe=z$1.object({id:z$1.string(),level:gAe,versionRange:z$1.string(),announcement:z$1.string()});z$1.object({cliType:hAe,version:mAe});var wq=z$1.object({announcements:z$1.array(fAe)});var tT=55555,QC="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 yAe=z$1.union([z$1.string(),z$1.date()]).transform(e=>e instanceof Date?e:new Date(e)),Iq=z$1.object({phoneNumber:z$1.string(),expiresAt:yAe,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 xq=z$1.object({email:z$1.string(),prefix:z$1.string(),expiresAt:z$1.coerce.date()}),ZC=(n=>(n.RAW="RAW",n.RESPONSE="RESPONSE",n))(ZC||{}),_q=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()}),SAe=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(),bAe=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(),Pq=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:SAe,response:bAe,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(ZC).optional()});var Hu=9e4;var TAe=P.object({url:P.string(),lineNumber:P.number(),columnNumber:P.number()}),Oq=P.object({timestamp:P.number(),text:P.string(),type:P.string(),tabIndex:P.number(),args:P.unknown().optional().array().optional(),url:P.string().optional(),location:TAe.optional()}),Mq=Oq.array(),mL=Mq.array();var nT=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 AAe=z$1.object({name:z$1.string(),version:z$1.string(),comment:z$1.string().optional()}),EAe=z$1.object({name:z$1.string(),version:z$1.string(),comment:z$1.string().optional()}),vAe=z$1.object({onContentLoad:z$1.number().optional(),onLoad:z$1.number().optional(),comment:z$1.string().optional()}),oT=z$1.object({startedDateTime:z$1.string(),id:z$1.string(),title:z$1.string().optional(),pageTimings:vAe,comment:z$1.string().optional()}),CAe=z$1.array(oT),RAe=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()}),Lq=z$1.array(RAe),wAe=z$1.object({name:z$1.string(),value:z$1.string(),comment:z$1.string().optional()}),kq=z$1.array(wAe),IAe=z$1.object({name:z$1.string(),value:z$1.string(),comment:z$1.string().optional()}),xAe=z$1.array(IAe),_Ae=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()}),PAe=z$1.array(_Ae),OAe=z$1.object({mimeType:z$1.string(),params:PAe,text:z$1.string(),comment:z$1.string().optional(),_redactedReason:z$1.string().optional()}),MAe=z$1.object({method:z$1.string(),url:z$1.string(),httpVersion:z$1.string().optional(),cookies:Lq,headers:kq,queryString:xAe,postData:OAe.optional(),headersSize:z$1.number().optional(),bodySize:z$1.number().optional(),comment:z$1.string().optional()}),NAe=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()}),LAe=z$1.object({status:z$1.number(),statusText:z$1.string(),httpVersion:z$1.string().optional(),cookies:Lq,headers:kq,content:NAe,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()}),Nq=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()}),kAe=z$1.object({beforeRequest:Nq.optional(),afterRequest:Nq.optional(),comment:z$1.string().optional()}),DAe=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()}),rT=z$1.object({pageref:z$1.string().optional(),startedDateTime:z$1.string(),time:z$1.number().optional(),request:MAe,response:LAe.optional(),cache:kAe.optional(),timings:DAe,serverIPAddress:z$1.string().optional(),connection:z$1.string().optional(),comment:z$1.string().optional(),_resourceType:z$1.string().optional()}),FAe=z$1.array(rT),BAe=z$1.object({version:z$1.string().default("1.1"),creator:AAe.optional(),browser:EAe.optional(),pages:CAe.optional(),entries:FAe,comment:z$1.string().optional()});z$1.object({log:BAe});z$1.record(z$1.string(),oT);z$1.record(z$1.string(),rT);function hL(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 gL=(A=>(A.DisableClickhouseCaches="disable_clickhouse_caches",A.ShowZeroOpacityElements="show_zero_opacity_elements",A.VisualActions="visual_actions",A.RagV2="rag_v2",A.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",A.GlobalLocatorRedirect="global_locator_redirect",A.FakerConstantSeed="faker_constant_seed",A.AutoExpandIframes="auto_expand_iframes",A.MobileNewAiActionStepsUseV3="mobile_new_ai_action_steps_use_v3",A.PerformanceInsights="performance_insights",A.ShowKnowledgeBase="show_knowledge_base",A.AppGraphBackend="app_graph_backend",A.AppGraphUI="app_graph_ui",A.ClassificationUI="classification_ui",A.HealingUI="healing_ui",A.ExploreUI="explore_ui",A.SlackNotifications="slack_notifications",A.SlackNotificationDms="slack_notification_dms",A.ResultClassificationCache="result_classification_cache",A.HealTraceUI="heal_trace_ui",A))(gL||{});var ju=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null(),z$1.record(z$1.string(),z$1.lazy(()=>ju)),z$1.array(z$1.lazy(()=>ju))]),iT=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(gL).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 sT={".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"},Dq=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var Fq=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)})]),jAe=z$1.object({githubLogin:z$1.string().optional(),email:z$1.string().optional()}),GAe=z$1.object({baseSha:z$1.string().min(1),headSha:z$1.string().min(1)}),$Ae=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()}),VAe=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()});$Ae.extend(VAe.shape).extend({changes:z$1.array(Fq).min(1),coAuthorRange:GAe.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 Bq=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(jAe).optional()});z$1.object({branch:z$1.string().min(1).max(255),commitMessage:z$1.string().min(1),changes:z$1.array(Fq).min(1)});var Uq=z$1.object({branch:z$1.string(),commitSha:z$1.string(),committed:z$1.boolean()}),Hq=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 zAe=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()}),WAe=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()}),jq=z$1.object({mergeBaseSha:z$1.string().min(1),totalCommits:z$1.number(),commits:z$1.array(WAe),files:z$1.array(zAe)}),Gq=z$1.object({content:z$1.string().nullable()}),$q=z$1.object({name:z$1.string().min(1),protected:z$1.boolean()}),Vq=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)}),qAe=z$1.object({name:z$1.string(),path:z$1.string(),body:z$1.string()}),zq=z$1.object({template:qAe});function gr(e){let[t,n,...o]=e.split("/");if(!(!t||!n||o.length>0))return {owner:t,repo:n}}function Wq(e){let t=gr(e);if(t)return t;throw new vt(`Invalid GitHub repository string: ${e}. Expected format "owner/repo".`)}var KAe=/^co-authored-by:\s*.*?<([^>]+)>\s*$/gim,YAe=/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i;function eR(e){return e.match(YAe)?.[1]}function qq(e){let t=[];for(let n of e.matchAll(KAe)){let o=n[1]?.trim();o&&t.push({email:o,githubLogin:eR(o)});}return t}function JAe(e){return (e.githubLogin??(e.email?eR(e.email):void 0))?.toLowerCase().endsWith("[bot]")??false}function Kq(e){return e.filter(t=>!JAe(t))}var Yq="https://static.momentic.ai";function aT(e,t){return {light:`${Yq}/${e}.svg`,dark:`${Yq}/${e}-dark.svg`,alt:t}}var lT={runGroup:aT("run-group-button","View run group"),basePr:aT("view-base-pr-button","View base PR"),branch:aT("view-branch-button","View branch"),commit:aT("view-commit-button","View commit")};function cT({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 Gu=z$1.object({limit:z$1.number().min(1).max(100).optional(),page:z$1.number().min(1).optional()}),fL=z$1.object({page:z$1.number(),pageSize:z$1.number(),pageCount:z$1.number()});var yL=P__default.object({platformSep:P__default.string(),fullPathSegments:P__default.string().array(),relativePathSegments:P__default.string().array(),relativePath:P__default.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:P__default.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:P__default.coerce.date(),createdAt:P__default.coerce.date()});var XAe=z$1.array(yL.extend({id:z$1.string(),name:z$1.string(),description:z$1.string().optional(),labels:z$1.string().array().optional()})),QAe=yL.extend({id:z$1.string(),name:z$1.string(),description:z$1.string().optional(),content:Bv}),ZAe=z$1.array(QAe);z$1.object({tests:XAe,modules:ZAe,labels:z$1.string().array()});z$1.string().array();var Jq=z$1.object({pathSegments:z$1.string().array()});RN.merge(lo);var Xq=z$1.object({schemaVersion:z$1.string(),stepLists:Ls}),Qq=lo.partial().merge(li.pick({id:true})),wm="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",SL={name:z$1.string().min(1).max(255).describe(wm),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(nl).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:dd.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.")},Zq=z$1.object(SL);RN.extend(z$1.object({relativeFilePath:z$1.string().describe("relative to project root")}).shape);var e2=z$1.object({name:z$1.string()});z$1.object({relativeFilePath:z$1.string()});var t2=z$1.object({name:z$1.string(),sourceModuleContent:Bv});z$1.object({relativeFilePath:z$1.string()});var n2=z$1.object({name:z$1.string(),description:z$1.string(),enabled:z$1.boolean(),steps:z$1.lazy(()=>Ht.array()),testFilePath:z$1.string().describe("relative to the project root"),folderPath:z$1.string().optional().describe("user selected folder path")}),o2=z$1.object({name:z$1.string(),description:z$1.string(),enabled:z$1.boolean()}).partial(),r2=z$1.object({folderPath:z$1.string()}),i2=z$1.object({folderPath:z$1.string()});z$1.array(fb);var s2=z$1.object({defaultEnv:z$1.string().optional().describe("name of the default env, or undefined to unset")}),a2=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 bL=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()}),l2=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(bL)});var c2=z$1.object({sourceDirectoryPath:z$1.string().optional(),value:z$1.string(),allowedExtensions:z$1.array(z$1.string()).optional()}),eEe=z$1.object({name:z$1.string(),value:z$1.string(),isDirectory:z$1.boolean()});z$1.object({suggestions:z$1.array(eEe)});var d2=z$1.object({pathSegments:z$1.array(z$1.string())}),u2=z$1.object({pathSegments:z$1.array(z$1.string()),newPathSegments:z$1.array(z$1.string())}),p2=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 m2=typeof process<"u"&&true&&true,tR=58889,Yg=24*60*60*1e3;var h2=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:MM.nullish()});h2.extend({steps:z$1.lazy(()=>Ut.array())});var g2=5*60*1e3,dT=so.extend(h2.omit({id:true,createdAt:true,createdBy:true,organizationId:true,enabled:true}).shape);var tEe="org_01HMJTX4GT1KG94KZRCT8MZ6YB",nEe="org_01HMSCJQBCCG51M2ZF65YC5B8W",oEe="org_01JPR6MGFQSHF3W234R3XJDPMB",rEe=[tEe,nEe,oEe];function f2(e){return rEe.includes(e)}var y2=(o=>(o.AZURE="AZURE",o.KERNEL="KERNEL",o.BROWSERBASE="BROWSERBASE",o))(y2||{}),TL=z$1.enum(y2);z$1.object({azureRegion:z$1.string().optional(),azureWorkspaceId:z$1.string().optional()});z$1.object({});var iEe=z$1.enum(["us-west-2","us-east-1","eu-central-1","ap-southeast-1"]);z$1.object({region:iEe.optional()});var AL=(t=>(t.TEST_REVIEW="TEST_REVIEW",t))(AL||{});var sEe=z$1.object({type:z$1.literal("DESCRIPTION_UPDATE"),thoughts:z$1.string()}),nR=z$1.discriminatedUnion("type",[sEe]),aEe=z$1.object({testId:z$1.string(),name:z$1.string(),orgId:z$1.string(),runId:z$1.string(),steps:Ht.array(),purpose:z$1.enum(AL),details:nR.or(nR.array()).optional()});aEe.pick({name:true,orgId:true});var lEe=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(AL),details:nR.or(nR.array()).optional(),applied:z$1.boolean().nullish(),appliedAt:z$1.coerce.date().nullish()}),S2=lEe.extend({steps:Ht.array()});var b2=z$1.enum(["v1","v2"]);var dEe=z$1.enum(["element","content","attribute","tag_name","style"]),oR=z$1.enum(["exists","visible","enabled","editable","focused","contains","equals","starts_with"]);[...Y$,...K$].forEach(e=>{if(!oR.options.includes(e.toLowerCase()))throw new Error(`V2CheckConditionSchema is missing option: ${e}`)});var EL={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}},E2={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"}},v2={ELEMENT_EXISTENCE:"element",ELEMENT_CONTENT:"content",ELEMENT_ATTRIBUTE:"attribute",ELEMENT_NAME:"tag_name",ELEMENT_STYLE:"style"};function T2(e){return {alias:vL(e),subject:e.subject,condition:e.condition,negated:e.negated,assertionType:EL[e.subject].assertionType,requiresName:EL[e.subject].requiresName,requiresValue:e.subject!=="element"&&e.condition!=="exists"}}function vL(e){let t=EL[e.subject],n=E2[e.condition];if(!C2(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 C2(e,t){let n=E2[t],o=n.elementCondition,r=n.contentOperation;return e==="element"?o!==void 0:r!==void 0}var uEe=dEe.options.flatMap(e=>oR.options.flatMap(t=>C2(e,t)?[T2({subject:e,condition:t,negated:false}),T2({subject:e,condition:t,negated:true})]:[])),R2=new Map(uEe.map(e=>[e.alias,e]));var pEe=z$1.enum(ql),mEe=z$1.enum(Ps);function Gi(e){return R2.get(e)}function I2(e){let t=v2[e.type],n=e.type==="ELEMENT_EXISTENCE"?e.condition:e.operation;return vL({subject:t,condition:hEe(n),negated:e.negated})}function x2(e){return pEe.parse(e.toUpperCase())}function uT(e){return mEe.parse(e.toUpperCase())}function hEe(e){return oR.parse(e.toLowerCase())}var rt={saveAs:z$1.string().optional(),retries:z$1.number().optional(),skipped:z$1.boolean().optional(),comment:z$1.string().optional()};z$1.object(rt);var pT=Object.keys(rt);function Ye(e){return z$1.union([z$1.strictObject({[e.key]:e.simplified}),z$1.strictObject({[e.key]:e.detailed})])}function oo(e){return z$1.strictObject({[e.key]:e.detailed})}var _2='Coordinates must be "x, y" pixel values, e.g. "100, 200"',Jg=z$1.union([Vl,z$1.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,_2)],{error:_2});z$1.union([z$1.string(),Vl]);var zs={css:z$1.string().optional(),coords:Jg.optional(),x:z$1.union([z$1.number(),z$1.string()]).optional(),y:z$1.union([z$1.number(),z$1.string()]).optional()},RL={on:z$1.string().optional(),...zs},Ws={...rt,useSelector:z$1.boolean().optional(),force:z$1.boolean().optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional()},mT={...Ws,offset:Jg.optional()};function $i({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 gEe=$i({descriptionKey:"on",schema:z$1.strictObject({...RL,...mT,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()})}),fEe=$i({descriptionKey:"on",schema:z$1.strictObject({...RL,...mT,rightClick:z$1.boolean().optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),yEe=$i({descriptionKey:"on",schema:z$1.strictObject({...RL,...mT,times:z$1.int().min(1).optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),P2=Ye({key:"click",simplified:z$1.string(),detailed:gEe}),O2=Ye({key:"doubleClick",simplified:z$1.string(),detailed:fEe}),M2=Ye({key:"rightClick",simplified:z$1.string(),detailed:yEe}),SEe=$i({descriptionKey:"into",required:false,schema:z$1.strictObject({text:z$1.string(),into:z$1.string().optional(),...zs,...mT,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()})}),N2=Ye({key:"type",simplified:z$1.string(),detailed:SEe}),L2=oo({key:"select",detailed:$i({descriptionKey:"from",schema:z$1.strictObject({from:z$1.string().optional(),...zs,label:z$1.string().optional(),value:z$1.string().optional(),index:z$1.union([z$1.string(),z$1.number()]).optional(),...Ws})}).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"});})}),k2=Ye({key:"hover",simplified:z$1.string(),detailed:$i({descriptionKey:"on",schema:z$1.strictObject({on:z$1.string().optional(),...zs,...mT})})}),D2=oo({key:"blur",detailed:$i({descriptionKey:"on",required:false,schema:z$1.strictObject({on:z$1.string().optional(),...zs,...Ws})})}),F2=Ye({key:"focus",simplified:z$1.string(),detailed:$i({descriptionKey:"on",schema:z$1.strictObject({on:z$1.string().optional(),...zs,...Ws})})}),B2=oo({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:Jg.optional(),toCoords:Jg.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(),...Ws}).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."});})}),U2=z$1.union([z$1.strictObject({mouseDrag:Jg}),z$1.strictObject({mouseDrag:$i({descriptionKey:"from",required:false,schema:z$1.strictObject({from:z$1.string().optional(),...zs,delta:Jg,steps:z$1.number().optional(),...Ws})})})]),H2=Ye({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(),...rt})}),j2=Ye({key:"keyDown",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),convertMeta:z$1.boolean().optional(),...rt})}),G2=Ye({key:"keyUp",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),convertMeta:z$1.boolean().optional(),...rt})}),hT=z$1.number().int().min(0).max(6e4).multipleOf(1e3),$2=Ye({key:"navigate",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),timeout:hT.optional(),...rt})}),V2=Ye({key:"newTab",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),timeout:hT.optional(),...rt})}),z2=Ye({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:hT.optional(),...rt}).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"});})}),W2=oo({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:hT.optional(),...rt}).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"});})}),q2=oo({key:"goBack",detailed:z$1.strictObject(rt)}),K2=oo({key:"goForward",detailed:z$1.strictObject(rt)}),Y2=oo({key:"refresh",detailed:z$1.strictObject({timeout:hT.optional(),...rt})}),rR=z$1.enum(["goBack","goForward","refresh","paste","authSave","offline","online","blur","visualDiff","captcha","closeTab"]),J2=Ye({key:"scrollUp",simplified:z$1.number().nonnegative(),detailed:$i({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...zs,...Ws})})}),X2=Ye({key:"scrollDown",simplified:z$1.number().nonnegative(),detailed:$i({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...zs,...Ws})})}),Q2=Ye({key:"scrollLeft",simplified:z$1.number().nonnegative(),detailed:$i({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...zs,...Ws})})}),Z2=Ye({key:"scrollRight",simplified:z$1.number().nonnegative(),detailed:$i({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...zs,...Ws})})}),eK=Ye({key:"wait",simplified:z$1.number(),detailed:z$1.strictObject({ms:z$1.number(),...rt})}),bEe=Ye({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(),...rt})}),TEe=Ye({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(),...rt})}),iR=bEe,sR=TEe,tK=Ye({key:"checkPageContains",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),iframe:z$1.string().optional(),...rt})}),nK=Ye({key:"checkPageDoesNotContain",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),iframe:z$1.string().optional(),...rt})}),wL=z$1.union([tK,nK]),AEe=z$1.record(z$1.string(),z$1.unknown().optional()),aR=AEe.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=Gi(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=$i({descriptionKey:"element",schema:z$1.looseObject({element:z$1.string().optional(),...zs,...Ws,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"]});}),oK=Ye({key:"extract",simplified:z$1.string(),detailed:z$1.strictObject({goal:z$1.string(),schema:ju.optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional(),...rt})}),rK=Ye({key:"cookie",simplified:z$1.string(),detailed:z$1.strictObject({value:z$1.string(),...rt})}),iK=oo({key:"localStorage",detailed:z$1.strictObject({key:z$1.string(),value:z$1.string(),...rt})}),sK=Ye({key:"request",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),method:td.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),params:z$1.record(z$1.string(),z$1.string()).optional(),body:ju.optional(),contentType:z$1.enum(Kl).optional(),timeout:z$1.number().optional(),...rt})}),aK=oo({key:"graphqlRequest",detailed:z$1.strictObject({url:z$1.string(),query:z$1.string(),variables:ju.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),timeout:z$1.number().optional(),...rt})}),lR=Ye({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(),...rt})}),Xg={substring:z$1.string().optional(),glob:z$1.string().optional(),regex:z$1.string().optional(),domain:z$1.string().optional()};function EEe(e){return [e.substring,e.glob,e.regex,e.domain].filter(t=>t!==void 0).length}function Qg(e){let t=EEe(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 lK=oo({key:"header",detailed:z$1.strictObject({name:z$1.string(),value:z$1.string(),...Xg,method:z$1.string().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:false});})}),cK=oo({key:"mock",detailed:z$1.strictObject({...Xg,method:z$1.string().optional(),responseGenerator:z$1.string(),fetchOriginalResponse:z$1.boolean().optional(),key:z$1.string().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),dK=Ye({key:"removeRouteMock",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string().optional(),...rt})}),uK=Ye({key:"waitForUrl",simplified:z$1.string(),detailed:z$1.strictObject({...Xg,caseInsensitive:z$1.boolean().optional(),timeout:z$1.number().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),pK=Ye({key:"waitForUrlNotToMatch",simplified:z$1.string(),detailed:z$1.strictObject({...Xg,caseInsensitive:z$1.boolean().optional(),timeout:z$1.number().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),vEe=z$1.union([uK,pK]),mK=Ye({key:"dialog",simplified:z$1.enum(["ACCEPT","DISMISS"]),detailed:z$1.strictObject({action:z$1.enum(["ACCEPT","DISMISS"]),...rt})}),hK=Ye({key:"fileUpload",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),name:z$1.string().optional(),...rt})}),gK=Ye({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()]),...rt})}),fK=oo({key:"paste",detailed:z$1.strictObject(rt)}),yK=oo({key:"captcha",detailed:z$1.strictObject({...Ws})}),CEe=z$1.strictObject({data:z$1.union([z$1.string(),Ya]),width:z$1.number(),height:z$1.number()}),SK=Ye({key:"visualDiff",simplified:z$1.string(),detailed:$i({descriptionKey:"on",required:false,schema:z$1.strictObject({on:z$1.string().optional(),...zs,threshold:z$1.number().optional(),screenshot:CEe.optional(),...Ws})})}),bK=oo({key:"offline",detailed:z$1.strictObject(rt)}),TK=oo({key:"online",detailed:z$1.strictObject(rt)}),AK=oo({key:"registerRequestListener",detailed:z$1.strictObject({...Xg,key:z$1.string(),method:z$1.string().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),EK=Ye({key:"awaitListener",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),timeout:z$1.number().optional(),...rt})}),vK=oo({key:"recordRequests",detailed:z$1.strictObject({...Xg,key:z$1.string(),method:z$1.string().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),CK=Ye({key:"getRecordedRequests",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),...rt})}),RK=Ye({key:"authLoad",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),...rt})}),wK=Ye({key:"authSave",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string().optional(),...rt})});z$1.union([P2,O2,M2,z2,W2,N2,L2,k2,D2,F2,B2,U2,H2,j2,G2,$2,V2,q2,K2,Y2,J2,X2,Q2,Z2,eK,iR,sR,wL,oK,rK,iK,sK,aK,lR,lK,cK,dK,vEe,mK,hK,gK,fK,yK,SK,bK,TK,AK,EK,vK,CK,RK,wK,aR]);var IK=new Map([["click",P2],["doubleClick",O2],["rightClick",M2],["switchTab",z2],["closeTab",W2],["type",N2],["select",L2],["hover",k2],["blur",D2],["focus",F2],["dragAndDrop",B2],["mouseDrag",U2],["press",H2],["keyDown",j2],["keyUp",G2],["navigate",$2],["newTab",V2],["goBack",q2],["goForward",K2],["refresh",Y2],["scrollUp",J2],["scrollDown",X2],["scrollLeft",Q2],["scrollRight",Z2],["wait",eK],["assert",iR],["assertVisually",sR],["checkPageContains",tK],["checkPageDoesNotContain",nK],["extract",oK],["cookie",rK],["localStorage",iK],["request",sK],["graphqlRequest",aK],["javascript",lR],["header",lK],["mock",cK],["removeRouteMock",dK],["waitForUrl",uK],["waitForUrlNotToMatch",pK],["dialog",mK],["fileUpload",hK],["copy",gK],["paste",fK],["captcha",yK],["visualDiff",SK],["offline",bK],["online",TK],["registerRequestListener",AK],["awaitListener",EK],["recordRequests",vK],["getRecordedRequests",CK],["authLoad",RK],["authSave",wK]]),xK=Object.freeze([...IK.keys()]),mc=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=IK.get(o)??(Gi(o)?aR:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported step type '${o}'.`});return}let i=r.safeParse(e);if(!i.success){let s=REe(i.error.issues,o);s.length>0&&_K(t,s);}});function REe(e,t){return wEe(e).filter(n=>!IEe(n,t))}function _K(e,t){for(let n of t){if(n.code==="invalid_union"){_K(e,IL(n));continue}e.addIssue({...n});}}function wEe(e){let t=[];for(let n of e){if(n.code==="invalid_union"){t.push(...IL(n));continue}t.push(n);}return t}function IEe(e,t){return e.code!=="unrecognized_keys"?false:t===void 0?e.path.length===0:e.path.length===1&&e.path[0]===t}function IL(e){let t=e.errors[0]??[],n=CL(t);for(let o of e.errors.slice(1)){let r=CL(o);r>n&&(t=o,n=r);}return t}function CL(e){return e.reduce((t,n)=>{let o=n.code==="invalid_union"?CL(IL(n)):0;return t+n.path.length+o},0)}var PK=z$1.strictObject({string:z$1.string()}),xEe=z$1.strictObject({javascript:z$1.string()}),OK=z$1.union([PK,xEe]),_Ee=z$1.union([z$1.strictObject({name:z$1.string(),required:z$1.boolean().optional(),default:PK.optional()}),z$1.strictObject({name:z$1.string(),required:z$1.boolean().optional(),defaultValue:z$1.string()})]),MK=_Ee.array(),PEe=z$1.strictObject({name:z$1.string(),default:OK.optional(),enum:z$1.array(z$1.string()).optional()}),NK=PEe.array(),gT=z$1.union([OK,z$1.string()]),LK=z$1.record(z$1.string(),gT);var OEe=z$1.preprocess(e=>typeof e=="number"?String(e):e,IM),cR=z$1.looseObject({goal:z$1.string(),version:OEe.optional(),...rt}),MEe=z$1.union([z$1.strictObject({act:z$1.string()}),z$1.strictObject({act:cR})]),xL=z$1.looseObject({path:z$1.string(),inputs:z$1.record(z$1.string(),gT).optional(),...rt}),NEe=z$1.union([z$1.strictObject({module:z$1.string()}),z$1.strictObject({module:xL})]),Ad=z$1.union([iR,sR,wL,lR,aR]),LEe=new Set(["then",...pT]),kEe=z$1.looseObject({then:z$1.lazy(()=>ul.array()),...rt}).superRefine((e,t)=>{Object.entries(e).filter(([o,r])=>!LEe.has(o)&&Ad.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"Conditional steps require exactly one assertion condition at the top level."});}),DEe=z$1.strictObject({if:kEe}),FEe=new Set(["do","maxIterations",...pT]),BEe=z$1.looseObject({do:z$1.lazy(()=>ul.array()),maxIterations:z$1.number().int().positive().optional(),...rt}).superRefine((e,t)=>{let n=Object.entries(e).filter(([o,r])=>!FEe.has(o)&&Ad.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."});}),UEe=z$1.strictObject({while:BEe}),ul=z$1.lazy(()=>z$1.union([rR,MEe,NEe,DEe,UEe,mc]));z$1.object({before:ul.array().optional(),steps:ul.array(),after:ul.array().optional()});var HEe=z$1.union([dd,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 dd.safeParse({width:Number(n),height:Number(o)}).success},"Viewport must be two numeric values, e.g. 1920, 1080")]),jEe=Bi.omit({viewport:true}).extend({viewport:HEe.optional()}),_L=z$1.object({id:co,version:z$1.string().optional(),url:Wv.optional(),description:z$1.string().optional(),retries:z$1.number().optional(),defaultEnv:z$1.string().optional(),parameters:MK.optional(),outputs:CC.optional(),disabled:z$1.boolean().optional(),labels:z$1.array(z$1.string()).optional()}).extend(jEe.shape),Vu=z$1.looseObject({fileType:z$1.literal(Fe.TEST_V2)}).extend(_L.shape).extend({before:ul.array().optional(),steps:ul.array(),after:ul.array().optional()});var GEe=z$1.array(z$1.string()),$Ee=z$1.union([z$1.string(),z$1.record(z$1.string(),z$1.unknown().optional())]),dR=so.omit({moduleId:true,name:true,parameters:true,defaultParameters:true,parameterEnums:true}).extend({id:co,version:z$1.string().optional(),name:z$1.string().optional(),parameters:z$1.union([NK,GEe]).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()}),uR=z$1.looseObject(dR.extend({fileType:z$1.literal(Fe.MODULE_V2),steps:$Ee.array().optional()}).shape).superRefine(DK),pR=z$1.looseObject(dR.extend({fileType:z$1.literal(Fe.MODULE_V2),steps:ul.array().optional()}).shape).superRefine(DK);function kK(e){return e.steps??[]}function DK(e,t){"main"in e&&t.addIssue({code:"custom",message:"v2 modules must use steps, not main",path:["main"]});}var PL=(n=>(n.TEST="TEST",n.MODULE="MODULE",n))(PL||{}),VEe=z$1.enum(PL),FK=z$1.object({orgId:z$1.string(),entityType:VEe,entityId:z$1.string()}),OL=FK.extend({entityType:z$1.literal("TEST"),stepLists:Xa}),ML=FK.extend({entityType:z$1.literal("MODULE"),steps:Ut.array()});z$1.discriminatedUnion("entityType",[OL,ML]);var BK=(o=>(o.WEB="web",o.ANDROID="android",o.IOS="ios",o))(BK||{}),NL=z$1.nativeEnum(BK);var UK=z$1.object({entity_type:z$1.string(),value:z$1.string(),schema_version:z$1.string().optional()}),HK=Tb(UK),jK=UK.extend({cache_key:z$1.string()});function fT({entityType:e,entityId:t}){return `${e}:${t}`}var _m=z$1.string();var GK='Coordinates must be "x, y" pixel values, e.g. "100, 200"',WK=z$1.union([Vl,z$1.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,GK)],{error:GK}),$K='Percent must be a number or a percent string, e.g. 90 or "90%"',qK=z$1.union([z$1.number(),z$1.string().regex(/^-?\d+(?:\.\d+)?%$/,$K)],{error:$K}).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"})),zEe=z$1.strictObject({x:z$1.number(),y:z$1.number(),delta:z$1.number()}),KK=z$1.union([z$1.string(),zEe]),Hn={...rt,DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional()},WEe=["home","power","back","app_switcher","search","volume_up","volume_down","volume_mute"],qEe=["enter","backspace","close_keyboard"],VK=["airplane_mode","data","wifi","location"],zK=["portrait","landscape"],KEe=z$1.strictObject({on:_m.optional(),longPress:z$1.boolean().optional(),longPressDuration:z$1.number().optional(),iterations:z$1.number().optional(),tapDelay:z$1.number().optional(),offset:WK.optional(),...Hn}),YK=Ye({key:"tap",simplified:_m,detailed:KEe}),YEe=z$1.strictObject({text:z$1.string(),into:_m.optional(),clearContent:z$1.boolean().optional(),forceClearContent:z$1.boolean().optional(),delay:z$1.number().optional(),replaceStrategy:z$1.nativeEnum(Wb).optional(),keyPressDelay:z$1.number().optional(),...Hn}),JK=Ye({key:"type",simplified:z$1.string(),detailed:YEe}),XK=z$1.enum(WEe),JEe=z$1.strictObject({key:XK,longPress:z$1.boolean().optional(),...Hn}),QK=Ye({key:"press",simplified:XK,detailed:JEe}),ZK=z$1.enum(qEe),XEe=z$1.strictObject({key:ZK,repeat:z$1.number().optional(),delay:z$1.number().optional(),keyPressDelay:z$1.number().optional(),...Hn}),eY=Ye({key:"pressKey",simplified:ZK,detailed:XEe}),QEe=z$1.strictObject({package:z$1.string(),activity:z$1.string().optional(),intentExtras:z$1.string().optional(),...Hn}),tY=Ye({key:"openApp",simplified:z$1.string(),detailed:QEe}),nY=oo({key:"killApp",detailed:z$1.strictObject(Hn)}),oY=oo({key:"openNotifications",detailed:z$1.strictObject(Hn)}),rY=z$1.enum(["up","down","left","right"]),ZEe=z$1.strictObject({direction:rY,in:KK.optional(),viewportPercent:qK.optional(),duration:z$1.number().optional(),offset:WK.optional(),...Hn}),iY=Ye({key:"swipe",simplified:rY,detailed:ZEe}),eve=z$1.enum(["up","down"]),tve=z$1.strictObject({on:_m,direction:eve.optional(),in:KK.optional(),scrollStepPercent:qK.optional(),maxScrollAttempts:z$1.number().optional(),...Hn}),sY=Ye({key:"scrollTo",simplified:z$1.string(),detailed:tve}),LL=Ye({key:"assert",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),...Hn})}),kL=Ye({key:"assertVisually",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),...Hn})}),aY=Ye({key:"extract",simplified:z$1.string(),detailed:z$1.strictObject({goal:z$1.string(),schema:ju.optional(),...Hn})}),lY=Ye({key:"checkScreenContains",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),...Hn})}),cY=Ye({key:"checkScreenDoesNotContain",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),...Hn})}),dY=z$1.union([lY,cY]),nve=z$1.record(z$1.string(),z$1.unknown().optional()),DL=nve.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=Gi(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:_m.optional(),timeout:z$1.number().optional(),name:z$1.string().optional(),value:z$1.string().optional(),...Hn}).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"]});}),ove=z$1.strictObject({from:_m,to:_m,hoverDuration:z$1.number().optional(),dragDuration:z$1.number().optional(),...Hn}),uY=oo({key:"dragAndDrop",detailed:ove}),FL=Ye({key:"javascript",simplified:z$1.string(),detailed:z$1.strictObject({code:z$1.string(),timeout:z$1.number().optional(),...Hn})}),pY=Ye({key:"request",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),method:td.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(Kl).optional(),timeout:z$1.number().optional(),...Hn})}),mY=Ye({key:"wait",simplified:z$1.number(),detailed:z$1.strictObject({ms:z$1.number(),...Hn})}),hY=Ye({key:"visualDiff",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),threshold:z$1.number().min(0).max(1).optional(),...Hn})}),gY=oo({key:"addFile",detailed:z$1.strictObject({path:z$1.string(),location:z$1.string(),...Hn})}),fY=Ye({key:"installApp",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),...Hn})}),yY=Ye({key:"uninstallApp",simplified:z$1.string(),detailed:z$1.strictObject({package:z$1.string(),...Hn})}),SY=Ye({key:"toggleSettings",simplified:z$1.enum(VK),detailed:z$1.strictObject({setting:z$1.enum(VK),...Hn})}),bY=Ye({key:"rotate",simplified:z$1.enum(zK),detailed:z$1.strictObject({orientation:z$1.enum(zK),...Hn})}),TY=Ye({key:"adb",simplified:z$1.string(),detailed:z$1.strictObject({command:z$1.string(),args:z$1.string().optional(),...Hn})}),AY=oo({key:"appium",detailed:z$1.strictObject({script:z$1.string(),args:z$1.string().optional(),...Hn})}),EY=oo({key:"debugState",detailed:z$1.strictObject(Hn)}),vY=z$1.enum(["killApp","openNotifications","debugState"]);z$1.union([YK,JK,QK,eY,tY,nY,oY,iY,sY,LL,kL,aY,dY,uY,FL,pY,mY,hY,gY,fY,yY,SY,bY,TY,AY,EY,DL]);var CY=new Map([["tap",YK],["type",JK],["press",QK],["pressKey",eY],["openApp",tY],["killApp",nY],["openNotifications",oY],["swipe",iY],["scrollTo",sY],["assert",LL],["assertVisually",kL],["extract",aY],["checkScreenContains",lY],["checkScreenDoesNotContain",cY],["dragAndDrop",uY],["javascript",FL],["request",pY],["wait",mY],["visualDiff",hY],["addFile",gY],["installApp",fY],["uninstallApp",yY],["toggleSettings",SY],["rotate",bY],["adb",TY],["appium",AY],["debugState",EY]]);Object.freeze([...CY.keys()]);var RY=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=CY.get(o)??(Gi(o)?DL: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});}),wY=z$1.union([LL,kL,dY,FL,DL]);var rve=z$1.preprocess(e=>typeof e=="number"?String(e):e,WN),ive=z$1.looseObject({goal:z$1.string(),version:rve.optional(),precondition:z$1.string().optional(),postcondition:z$1.string().optional(),...rt}),sve=z$1.union([z$1.strictObject({act:z$1.string()}),z$1.strictObject({act:ive})]),ave=z$1.looseObject({path:z$1.string(),inputs:z$1.record(z$1.string(),gT).optional(),...rt}),lve=z$1.union([z$1.strictObject({module:z$1.string()}),z$1.strictObject({module:ave})]),cve=new Set(["then",...pT]),dve=z$1.looseObject({then:z$1.lazy(()=>hc.array()),...rt}).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])=>!cve.has(o)&&wY.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"v2 mobile conditional steps require exactly one assertion condition at the top level."});}),uve=z$1.strictObject({if:dve}),hc=z$1.lazy(()=>z$1.union([vY,sve,lve,uve,RY]));z$1.object({before:hc.array().optional(),steps:hc.array(),after:hc.array().optional()});var BL=["android","ios"],pve=z$1.literal("android"),mve=z$1.literal("ios");z$1.enum(BL);function mR(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 IY=Wg.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z$1.string().optional(),platform:pve,...Zb.shape}),xY=qg.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z$1.string().optional(),platform:mve,...Zb.shape}),hve=z$1.discriminatedUnion("platform",[IY,xY]),_Y=z$1.preprocess(mR,hve),PY={before:hc.array().optional(),steps:hc.array(),after:hc.array().optional()},OY=z$1.looseObject({fileType:z$1.literal(Fe.MOBILE_TEST_V2)}).extend(IY.shape).extend(PY);z$1.preprocess(mR,OY);var MY=z$1.looseObject({fileType:z$1.literal(Fe.MOBILE_TEST_V2)}).extend(xY.shape).extend(PY);z$1.preprocess(mR,MY);var gve=z$1.discriminatedUnion("platform",[OY,MY]);z$1.preprocess(mR,gve);var fve=z$1.preprocess(e=>typeof e=="string"?e.toLowerCase():e,z$1.enum(BL).optional().default("android")),hR=WC.omit({moduleId:true,name:true,schemaVersion:true,platform:true}).extend({id:co,name:z$1.string().optional(),version:z$1.string().optional(),platform:fve});z$1.looseObject(hR.extend({fileType:z$1.literal(Fe.MOBILE_MODULE_V2),steps:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).optional()}).shape);z$1.looseObject(hR.extend({fileType:z$1.literal(Fe.MOBILE_MODULE_V2),steps:hc.array().optional()}).shape);var gR="x-momentic-cli-version",LY="x-momentic-client-mode",fR="x-momentic-runner",kY="x-momentic-cli-type",DY="x-momentic-logger-tags",yve="x-momentic-main-branch-name",Sve="x-momentic-branch-name",bve="x-momentic-commit-timestamp",Tve="x-momentic-last-commit-on-main",Ave="x-momentic-last-commit-on-main-timestamp",Eve="x-momentic-merged-branch-name",FY="x-momentic-session-id",BY="x-momentic-parent-trace-id";var UY="x-momentic-browser-vendor-override";P.object({error:P.boolean(),reason:P.string(),message:P.string()});hr.merge(CN);var HY=Lv;hr.merge(CN);hr.merge(FW).extend({useConsensus:P.boolean().optional(),attemptNumber:P.number().optional()});var UL=q$;hr.merge(BW);var jY=Fz;hr.merge(NW);var GY=hC;hr.merge(gz);hr.merge(LW);var $Y=Lz;hr.merge(kW);hr.merge(DW);hr.merge(GW);hr.merge($W);P.object({testPaths:P.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:P.string().optional(),all:P.boolean().optional(),urlOverride:P.string().optional(),customHeaders:P.record(P.string(),P.string()).optional(),testInputMatrix:P.record(P.string(),P.string()).array().optional()});var VY=P.object({queuedTests:P.unknown().optional().array(),runIds:P.guid().array(),runGroupId:P.string().optional()});P.string().array();P.union([P.object({paths:P.string().array().describe("Export specific test paths or folder paths (e.g. todo-test, auth/onboarding)"),all:P.boolean().describe("run all tests").optional()}),P.object({path:P.string().describe("deprecated; present for backcompat")})]);var vve=P.object({tests:P.record(P.string().describe("Test name (keys correspond to entries in `tests`)"),P.string().describe("Slash-separated folder name path that the test lives in (e.g. 'Auth/Login'). Top-level entities are omitted.")),modules:P.record(P.string().describe("Module name (keys correspond to entries in `modules`)"),P.string().describe("Slash-separated folder name path that the module lives in."))}),zY=P.object({tests:P.record(P.string().describe("Test name"),P.string().describe("Test YAML")),modules:P.record(P.string().describe("Module name"),P.string().describe("Module YAML")),folderPaths:vve.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.")}),Cve=P.object({test:P.string().describe("test YAML"),modules:P.record(P.string().describe("moduleId"),P.string().describe("module YAML"))});Cve.array();P.object({testId:P.string(),schemaVersion:P.string()}).merge(rd);function yR(e){let{gitMainBranch:t,gitBranchName:n,gitCommitTimestamp:o,lastCommitOnMainSha:r,lastCommitOnMainTimestamp:i}=e,s={};return t&&(s[yve]=encodeURIComponent(t)),n&&(s[Sve]=encodeURIComponent(n)),o&&(s[bve]=o.toISOString()),r&&(s[Tve]=encodeURIComponent(r)),i&&(s[Ave]=i.toISOString()),e.mergedGitBranchName&&(s[Eve]=encodeURIComponent(e.mergedGitBranchName)),s}P.object({entries:P.array(bz)});P.object({platform:NL.optional(),entries:P.array(HK)});P.object({testId:P.string(),environment:P.string().optional(),platform:NL.optional()});P.object({testId:P.string(),key:P.string(),environment:P.string().optional()});function WY(e){return P.record(P.string(),P.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 qY=WY(Tz),KY=jK.array();function NY(e){return WY(Ab(e))}var YY={ANDROID:e=>NY(YC).parse(e),IOS:e=>NY(JC).parse(e)},Rve=P.object({id:P.string(),completionType:P.string(),description:P.string().optional(),thoughts:P.string(),result:P.string(),sessionType:P.string(),timeCreated:P.string().optional(),citations:P.array(Uo).optional()}),wve=P.object({id:P.string(),assertion:P.string().optional(),result:P.string(),thoughts:P.string(),sessionType:P.string(),timeCreated:P.string().optional(),citations:P.array(Uo).optional()});P.object({completionType:P.string(),traceIds:P.string().array()});var HL=P.union([Rve,wve]).array(),JY=P.object({trigger:P.nativeEnum(Us),status:P.nativeEnum(St),startedAt:P.coerce.date().optional(),gitCommitSha:P.string().optional(),gitCommitShaShort:P.string().optional(),gitCommitTimestamp:P.coerce.date().optional(),gitBranchName:P.string().optional(),gitOriginUrl:P.string().optional(),gitCommitMessage:P.string().optional(),gitCommitAuthorName:P.string().optional(),githubRepository:P.string().optional(),gitlabProjectPath:P.string().optional(),pipelineId:P.string().optional(),cliVersion:P.string().optional()});P.object({id:P.string()});var XY=P.object({status:P.nativeEnum(St),updatedAt:P.coerce.date().optional(),finishedAt:P.coerce.date().optional()});P.object({summary:bm,githubRepository:P.string().optional(),gitBranchName:P.string().optional()});var Ive=P.object({runId:P.string(),healStatus:Mg,healDetails:Ou.optional()});P.object({updates:Ive.array()});var QY=P.object({stepsSnapshot:P.array(P.record(P.string(),P.unknown().optional())).optional(),beforeStepsSnapshot:P.array(P.record(P.string(),P.unknown().optional())).optional(),afterStepsSnapshot:P.array(P.record(P.string(),P.unknown().optional())).optional(),runGroupId:P.string().optional(),testId:P.string(),testName:P.string(),resolvedBaseUrl:P.string().optional(),environmentName:P.string().optional(),labels:P.array(P.string()).optional(),cliVersion:P.string().optional(),trigger:P.nativeEnum(Us),schemaVersion:P.string().optional(),section:P.nativeEnum(RC).optional(),resolvedInputs:P.record(P.string(),P.string()).optional(),quarantined:P.boolean().optional().default(false),quarantinedReason:P.string().optional(),aiSettings:Ca.optional()});P.object({id:P.string()});var xve=AN.pick({id:true,status:true,healStatus:true,healDetails:true,testName:true,testId:true,test:true,failureReason:true,failureDetails:true}),ZY=xve.array(),eJ=AN.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();P.object({id:P.string()});var tJ=P.object({run:ds.omit({runAttempts:true}),attemptZipUrls:P.array(P.string().url().nullish())}),nJ=P.object({status:P.nativeEnum(St),finishedAt:P.coerce.date().optional(),schemaVersion:P.string().optional().default("1.0.19"),results:P.record(P.string(),P.unknown().optional()).array().optional(),beforeResults:P.record(P.string(),P.unknown().optional()).array().optional(),afterResults:P.record(P.string(),P.unknown().optional()).array().optional()});P.object({screenshot:P.string(),contentType:P.enum(["image/jpeg","image/png"]).optional()});P.object({id:P.string(),screenshot:P.string(),contentType:P.enum(["image/jpeg","image/png"])});var oJ=P.object({key:P.string()}),rJ=P.object({orgId:P.string(),userId:P.string(),email:P.string().optional(),name:P.string().optional(),pylonEmailHash:P.string().optional(),selfServe:P.boolean().optional()}),iJ=P.object({blocked:P.boolean()}),sJ=P.array(nz);P.record(P.string(),P.union([P.string(),P.boolean()]));P.object({workosAccessToken:P.string().min(1),organizationId:P.string().optional(),clientName:P.string().min(1).max(80).optional()});var aJ=P.object({apiKey:P.string(),apiKeyName:P.string(),organizationId:P.string(),user:P.object({id:P.string(),email:P.string().optional()}),selfServe:P.boolean().optional()}),lJ=P.object({error:P.literal("multiple_organizations"),organizations:P.array(P.object({id:P.string(),name:P.string()}))}),_ve=["web","ios","android"];P.object({platforms:P.array(P.enum(_ve)),packageManager:P.enum(["npm","pnpm","yarn","bun"]),wizardVersion:P.string().min(1).max(40),cliVersions:P.object({momentic:P.string().max(40).optional(),momenticMobile:P.string().max(40).optional()}).optional(),firstRunIds:P.array(P.guid()).max(10).optional()});P.object({ok:P.literal(true)});P.object({paths:P.string().array(),env:P.string().optional(),urlOverride:P.string().optional(),customHeaders:P.record(P.string(),P.string()).optional()});var cJ=P.object({suiteRunIds:P.string().array(),runGroupIds:P.string().array()});P.object({suiteRunIds:P.string().array()});xW.array();P.object({runGroupIds:P.string().array()});var SR=P.object({uploadUrl:P.string()});hr.merge(UW);hr.merge(jW);hr.merge(HW);var Pve=P.object({testId:P.string().optional().default(""),testName:P.string().optional().default(""),suiteId:P.string().optional().default(""),suiteName:P.string().optional().default(""),isInteractive:P.boolean().optional().default(false),runner:P.nativeEnum(Hi).optional(),creditsUsed:P.number().optional(),stepsExecuted:P.number().optional(),tokensUsed:P.number().optional(),hostedBrowserSecondsUsed:P.number().optional()}),Ove=P.object({transactionId:P.string(),timestamp:P.string(),event:P.nativeEnum($g),properties:Pve});Ove.array();var dJ=S2.omit({steps:true}).extend({steps:P.array(P.record(P.string(),P.unknown().optional())).describe("unparsed ResolvedStep[]")});P.object({limit:P.number().min(1).max(10).optional(),page:P.number().min(1).optional(),start:Wn.optional(),end:Wn.optional(),gitBranchName:P.string().optional(),status:P.nativeEnum(St).optional()});var uJ=gW.array(),Mve=Gu.extend({testId:co.optional(),gitBranchName:P.string().optional(),gitCommitSha:P.string().optional(),status:P.nativeEnum(St).optional(),label:P.string().array().optional(),start:Wn.optional(),end:Wn.optional(),quarantined:P.boolean().optional(),recovered:P.boolean().optional(),includeFailureDetails:P.boolean().optional(),skipRetentionFilter:P.boolean().optional()});Mve.extend({orgId:P.string().optional(),testId:mr(co),status:mr(P.nativeEnum(St)),gitBranchName:mr(P.string()),label:mr(P.string()),testName:P.string().optional(),trigger:mr(P.nativeEnum(Us)),executionType:mr(Nu),cliVersion:mr(P.string()),githubRepository:mr(P.string()),gitlabProjectPath:mr(P.string()),environment:mr(P.string()),directory:mr(P.string()),failureCategory:mr(P.string()),exclude:mr(P.string()),healed:P.boolean().optional()});var Nve=ds.omit({test:true}),pJ=fL.extend({runs:Nve.array()});P.object({applied:P.boolean().optional(),appliedAt:P.coerce.date().optional()});var mJ=SR.extend({id:P.string()}),Lve=P.object({resultType:P.literal("run").optional().default("run"),runGroupId:P.guid().optional(),persist:P.boolean().optional()}),kve=P.object({resultType:P.literal("explore"),exploreRunId:P.guid(),persist:P.boolean().optional()});P.discriminatedUnion("resultType",[Lve,kve]);var hJ=P.object({runGroupId:P.guid()}),gJ=P.object({quarantined:P.object({testId:co,quarantinedAt:P.coerce.date(),quarantinedBy:P.string().optional(),quarantinedReason:P.string()}).array()}),fJ=Gu.extend({limit:Gu.shape.limit.describe("Max number of quarantined tests to return per page."),page:Gu.shape.page.describe("Page number for pagination (1-based)."),quarantinedAtStart:P.string().pipe(P.coerce.date()).optional().describe("Include tests quarantined at or after this timestamp."),quarantinedAtEnd:P.string().pipe(P.coerce.date()).optional().describe("Include tests quarantined before this timestamp.")}),Dve=P.object({id:P.string(),status:P.literal("FAILED"),startedAt:Wn,finishedAt:Wn,failureReason:P.string().nullish(),healStatus:Mg,healDetails:Ou.nullish()}),yJ=fL.extend({quarantinedTests:P.array(P.object({testId:co,testName:P.string().nullish(),quarantinedAt:Wn,quarantineReason:P.string(),latestFailedRun:Dve.nullable()}))}),SJ=P.object({gitLocalUsername:P.string().optional(),gitLocalEmail:P.string().optional(),gitLocalName:P.string().optional()});P.object({testId:co,testName:P.string().optional(),reason:P.string()}).merge(SJ);P.object({testName:P.string().optional(),reason:P.string().optional()}).merge(SJ);hr.merge(J1);hr.merge(X1);hr.merge(Q1);P.object({apkToInstall:P.object({channel:P.string(),tag:P.string().optional()}).optional(),hostname:P.string().optional(),region:lL.optional(),osVersion:P.nativeEnum(zg).optional(),sessionId:P.string().optional(),playwrightVersion:lq.optional()});var bJ=P.object({name:P.string(),apiUrl:P.string(),webRtcUrl:P.string(),adbUrl:P.string(),token:P.string(),apkDownloadUrl:P.string().optional(),playwrightServerUrl:P.string().optional(),region:P.string().optional(),resolvedTag:P.string().optional()});P.object({appToInstall:P.object({channel:P.string(),tag:P.string().optional()}).optional(),hostname:P.string().optional(),region:lL.optional(),osVersion:P.nativeEnum(XC).optional(),sessionId:P.string().optional(),installAppOnClient:P.boolean().optional()});var TJ=P.object({id:P.string(),apiUrl:P.string(),webRtcUrl:P.string(),wdaUrl:P.string(),token:P.string(),appDownloadUrl:P.string().optional(),appMd5:P.string().optional(),region:P.string().optional(),resolvedTag:P.string().optional()});P.object({channel:P.string().trim().min(1,"channel must be a non-empty string"),tag:P.string().trim().min(1,"tag must be a non-empty string"),md5:P.string()});var AJ=P.object({id:P.string(),uploadUrl:P.string().optional(),downloadUrl:P.string(),md5:P.string().optional()}),Fve=P.object({channel:P.string(),tag:P.string(),md5:P.string(),platform:P.nativeEnum(rl).default("ANDROID"),createdAt:P.number().describe("Unix timestamp in milliseconds")}),EJ=P.object({assets:P.array(Fve)}),vJ=P.object({downloadUrl:P.string()}),jL=(n=>(n.PLAYWRIGHT="PLAYWRIGHT",n.CDP="CDP",n))(jL||{}),Bve=P.nativeEnum(jL);P.object({testId:P.string().optional(),testName:P.string().optional(),runId:P.guid().optional(),attemptedProviders:P.array(TL).optional()});var CJ=P.object({wsEndpoint:P.string(),accessToken:P.string().optional(),endpointType:Bve.optional(),provider:TL.optional()});z$1.object({repositoriesIndexed:z$1.boolean(),indexingInProgress:z$1.boolean(),indexesOutdated:z$1.boolean()});var RJ=(s=>(s.Queued="queued",s.InProgress="in_progress",s.Completed="completed",s.Waiting="waiting",s.Requested="requested",s.Pending="pending",s))(RJ||{}),wJ=(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))(wJ||{});z$1.object({name:z$1.string(),status:z$1.enum(RJ),conclusion:z$1.enum(wJ).nullable()});var yT=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()})}),GL=z$1.object({mergedBranch:z$1.string().optional()});var IJ=z$1.object({orgId:z$1.string(),cacheKeys:z$1.string().array()});z$1.object({keyParams:IJ,clientMetadata:z$1.string(),lockAcquisitionTimeoutMs:z$1.number().optional()});var xJ=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()}),IJ]);var Uve=z$1.object({remainingTtlMs:z$1.number(),value:z$1.string().nullish()});z$1.object({results:z$1.record(z$1.string(),Uve),activeLocks:z$1.string().array()});var _J=0,PJ=5*60*1e3;var OJ=z$1.object({runId:z$1.string().min(1).optional(),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:hM,healDetails:uz.optional()}),Hve=OJ.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 MJ=Hve.array();z$1.object({entries:OJ.array()});function ef(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 jve=z$1.object({version:z$1.string(),json:z$1.record(z$1.string(),z$1.unknown().optional()),hash:z$1.string()}),NJ=z$1.record(z$1.string(),z$1.unknown().optional());z$1.object({newSvgs:z$1.array(jve),metadata:NJ.optional()});var Gve=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:NJ.nullish()}),LJ=z$1.record(z$1.string().describe("icon hash"),Gve);var $L="metadata.json",VL="test.yaml",kJ=".snapshot.zip",zL=lo.extend(Ls.shape),$ve=z$1.object({envName:z$1.string().optional(),baseUrl:z$1.string(),variables:z$1.record(z$1.string(),z$1.unknown().optional()),resolvedEnv:fb.optional()}),DJ=z$1.object({browser:ol.optional(),ai:Ca.optional(),advanced:xb.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:$ve,config:DJ});var FJ=z$1.object({variables:z$1.record(z$1.string(),z$1.unknown().optional()),resolvedEnv:fb.optional()}),Vve=z$1.object({envName:z$1.string().optional(),baseUrl:z$1.string(),encryptedSecrets:z$1.string()}),BJ=z$1.object({momenticVersion:z$1.string(),schemaVersion:z$1.string(),createdAt:z$1.string(),relativeFilePath:z$1.string(),environment:Vve,config:DJ});function UJ(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 HJ=e=>{e.extraHeaders&&(e.extraHeaders=Object.fromEntries(Object.entries(e.extraHeaders).filter(([t,n])=>t.trim()&&n.trim())));};var bR=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}async saveSnapshotCacheEntries(){}async deleteStepCacheEntry(){}};function Wve(e){return e.map(t=>({...t,environment:void 0}))}function WL(e,t){return t?e:Wve(e)}var KL="browser-crash-dump.zip",qL=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new ST}},ST=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new qL}flushResults(t){}};var ct="metadata.json",$r="assets",po="runs";z$1.object({type:z$1.literal("explore"),id:z$1.string(),cliVersion:z$1.string().optional(),startedAt:z$1.string(),finishedAt:z$1.string(),baseSha:z$1.string(),headSha:z$1.string(),ciProvider:z$1.string().optional(),pipelineId:z$1.string().optional(),gitMainBranch:z$1.string().optional(),gitCommitSha:z$1.string().optional(),gitCommitShaShort:z$1.string().optional(),gitBranchName:z$1.string().optional(),gitOriginUrl:z$1.string().optional(),gitCommitMessage:z$1.string().optional(),gitCommitAuthorName:z$1.string().optional(),githubRepository:z$1.string().optional(),gitlabProjectPath:z$1.string().optional(),result:z$1.unknown(),bugs:z$1.array(z$1.unknown()),writtenPaths:z$1.array(z$1.string()),videos:z$1.array(z$1.string()),failure:z$1.unknown().optional()});var qve=z$1.object({step:Ht,status:z$1.enum(Bt),startedAt:z$1.coerce.date(),finishedAt:z$1.coerce.date().optional(),healMetadata:z$1.object({healType:z$1.enum(Eb).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()}),Kve=qve.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});Kve.extend({step:z$1.unknown().optional()});var YL=z$1.object({avdId:z$1.string().optional(),channel:z$1.string().optional(),tag:z$1.string().optional(),region:z$1.string().optional(),osVersion:cq.optional()}),GJ="1.0.0",$J=nJ.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:YL.optional(),viewport:dd.optional(),activeVideos:z$1.array(z$1.object({videoName:z$1.string(),timestamp:z$1.coerce.date()})).optional()}),bT=$J.extend({assetDetails:YL.optional(),finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});$J.extend(uN.shape);var VJ=bT.extend(uN.shape),Yve=z$1.object({results:z$1.array(js),beforeResults:z$1.array(js).optional(),afterResults:z$1.array(js).optional()});bT.extend(Yve.shape);var Jve=z$1.object({results:z$1.array(Gs),beforeResults:z$1.array(Gs).optional(),afterResults:z$1.array(Gs).optional()});bT.extend(Jve.shape);var zJ=eJ.merge(QY).extend({executionType:Nu.optional().default("WEB"),testId:co,testDescription:z$1.string().optional(),directory:z$1.string().optional(),runGroupId:z$1.guid(),status:z$1.enum(St),healStatus:Mg,startedAt:z$1.coerce.date(),schemaVersion:z$1.string().nullish(),attempts:z$1.number(),failureRecoveryDetails:z$1.object({attempts:z$1.number()}).optional(),aiSettings:Ca.optional(),avgCpuUsage:z$1.number().optional(),avgMemoryUsage:z$1.number().optional()}),Xve=zJ.extend(YL.shape),Pm=zJ.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});Xve.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});var jJ=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(TC),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()}),Qve=JY.merge(XY).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:Ca.optional(),browser:ol.optional(),aiSelect:z$1.union([jJ.transform(e=>[e]),z$1.array(jJ)]).optional()}),_a=Qve.extend({healRiskSummary:bm.optional(),updatedAt:z$1.coerce.date().optional().transform(e=>e??new Date),finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});var Zve=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"]),eCe=new Set(["MODULE","RESOLVED_MODULE"]);function TR(e){return e.type!=="PRESET_ACTION"?e.type:e.command.type}function AR(e){return eCe.has(e.type)?false:e.type!=="PRESET_ACTION"?true:!Zve.has(e.command.type)}var WJ="progress.json",qJ="1.0.0",tCe=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(St),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(St),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:tCe.array()});function KJ(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch(t){return C.error({err:t},`Error reading path ${e} during directory existence check.`),false}}var YJ="CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih",tf="https://us-west.metrics.momentic.ai",nf="c60c6a0f-60da-41a7-a61b-07969a0aa303",Om=!!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 cCe=new Set(["exit","quit"]),QJ=(()=>{try{return statSync("/.dockerenv"),!0}catch{return false}})();async function tr(e){return Om||QJ?true:(await C.flush(),await new Promise(n=>setTimeout(n,100)),await confirm({message:e}))}async function JL(e){let t=dirname(e);return KJ(t)?existsSync(e)?tr(`File '${JJ(e)}' already exists. Overwrite existing content?`):true:await tr(`Directory '${JJ(t)}' doesn't exist. Create it now?`)?(mkdirSync(t,{recursive:true}),true):false}function JJ(e){return e.replace(/(\s+)/g,"\\$1")}async function ZJ(e,t){return Om||QJ?t:(await input({message:e,default:t})).trim()||t}async function XL(){let e;try{e=(await input({message:"ask"})).trim();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError"){C.info("");return}throw t}if(!cCe.has(e.toLowerCase()))return e}var of=new Map,tX="Log throttle exceeded",bCe=100,TCe=5e3,ACe=mCe(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}}),ECe=`${tf}/logs/json`,QL=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 ACe(ECe,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":YJ,"x-momentic-metrics-api-key":nf},body:sl(t),signal:AbortSignal.timeout(5e3)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch{}}},ZL=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??Ed.hostname(),this.disableConsoleLogs=o,this.bindingAttributes={...t,env:"production"},this.flushIntervalMs=r??5e3,this.maxBatchSize=i??10,this.buffer=s??new QL(this.flushIntervalMs,this.maxBatchSize);let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=eX(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===tX)return true;let n=Date.now();return n-this.lastWindowStart>TCe&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,tX),this.droppedLogsInWindow=false,this.lastWindowStart=n),this.logsInCurrentWindow<bCe?(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(Ib[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=yCe.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=vCe();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:aW({message:o||"",...i})};this.buffer.push(l);}setApp(t){let n=this.bindingAttributes.app;this.bindingAttributes.app=t,of.set("app",this),of.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=lW[t]):(this.minLevelValue=Ib[t],this.consoleLogger.level=t);}enableConsoleLogs(){this.disableConsoleLogs=false;}},rf=({app:e,hostname:t,disableConsoleLogs:n})=>(of.has(e)||of.set(e,new ZL({bindings:{app:e},hostname:t,disableConsoleLogs:n})),of.get(e));function vCe(){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 ER(){await Promise.all([...of.values()].map(e=>e.flush()));}var zu=class extends Error{callSiteStack;constructor(t){super(t),this.name="TimeoutError";}};var oX=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 xe(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 Promise.resolve(e).catch(()=>{}),c(oX(m));d=()=>c(oX(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 zu(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 vR="organization";function CR(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:{[vR]: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:vR,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 rX(e,t,n){let o,r=0,i=3,s,a;for(;r<i;)try{let l=await xe(e.getAllFlagsAndPayloads(n??t,{personProperties:{organizationId:t},groups:{[vR]: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 RR=class e extends iT{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 rX(r,n,o);return new e(r,n,o,i,s)}async refresh(){let{flags:n,payloads:o}=await rX(this.client,this.orgId,this.userId);this.flags=n,this.payloads=o;}};var _Ce=2e3,Mm=e=>Number.parseInt(e,10),tk=e=>readFileSync(e,"utf8").trim(),sf=e=>Mm(tk(e)),iX,wR,TT={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0};function lX(){return {...TT}}var xR=Ed.platform(),PCe=Ed.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 ek(e=Date.now()){let t=Ed.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 cX(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 OCe(){let e=ek();return ()=>{let t=ek(),n=cX(e,t);return e=t,n}}function sX(){try{let t=readFileSync("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(t?.[1])return Mm(t[1])}catch{}try{let e=sf("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(e))return e/1e3}catch{}return null}function MCe(){try{let t=tk("/sys/fs/cgroup/cpu.max").split(" "),n=t[0],o=t[1];return !n||!o||n==="max"?null:Mm(n)/Mm(o)}catch{}try{let e=sf("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),t=sf("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return e===-1||isNaN(t)?null:e/t}catch{return null}}function NCe(){if(xR!=="linux")return null;let e=sX();if(e===null)return null;let t=MCe()??Ed.cpus().length,n=e,o=Date.now();return ()=>{let r=sX();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 LCe(){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(Ed.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 dX({intervalMs:e=_Ce,maxSamples:t=1e4,keepSamples:n=true,onSample:o}={}){let r=[],i=NCe()??OCe(),s=LCe(),a=()=>{let d=Date.now(),u=pX(),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 IR=e=>{try{let t={},n=!1,o=pX(),r=DCe();TT.samples++,o.freePercentage<.05&&(Object.assign(t,process.memoryUsage()),n=!0,TT.lowMemorySamples++),r&&r?.total>80&&(n=!0,TT.highCpuSamples++);let i=xCe.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(n=!0,TT.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{}},uX=e=>{IR(e),setTimeout(()=>IR(e),5e3);};function _R(e){return IR(e),{interval:setInterval(()=>IR(e),2e4),cpuMetadata:PCe,platform:xR}}function kCe(){if(xR!=="linux")return null;try{let e=tk("/sys/fs/cgroup/memory.max"),t=sf("/sys/fs/cgroup/memory.current");if(e==="max"||isNaN(t))return null;let n=Mm(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=sf("/sys/fs/cgroup/memory/memory.limit_in_bytes"),t=sf("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(e)||isNaN(t))return null;let n=Ed.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 pX(){let e=kCe();if(e)return e;let t=Ed.totalmem(),n=xR==="darwin"?FCe():(()=>{let r=Ed.freemem();return {availableMemory:r,rawFreeMemory:r,cachedMemory:0}})(),o=n.availableMemory/t;return {totalMemory:t,freeMemory:n.availableMemory,freePercentage:o}}function DCe(){let e=ek();if(!wR)return wR=e,null;let t=cX(wR,e);return wR=e,t?(iX=t,iX):null}function FCe(){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?Mm(n):4096,r=d=>{let p=e.match(new RegExp(`${d}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Mm(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=Ed.freemem();return {availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}process.env.APP||"unknown";var PR="deployment.environment",OR="service.instance.id";function mX(){return process.env.MOMENTIC_LOCAL_DEV==="1"&&process.env.LOCAL_SIGNOZ==="true"}var af=false,MR,AT,ET,fX=[],NR;function LR(){return af}function yX(e){fX.push(e);}async function JCe(){for(let e of fX)try{await e();}catch{}}function XCe(){return LR()&&trace.getSpan(context.active())!==void 0}function QCe(){return mX()?new OTLPTraceExporter({url:"http://localhost:4318/v1/traces"}):new OTLPTraceExporter({url:`${tf}/v1/traces`,headers:{"x-momentic-metrics-api-key":nf}})}function ZCe(e){let t="production",n=v4$1(),o=QCe();return new NodeTracerProvider({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:e,[PR]:t,[OR]:n,[ATTR_SERVICE_VERSION]:"3.25.0"}),spanProcessors:[new BatchSpanProcessor(o)]})}function eRe(e){NR=registerInstrumentations({tracerProvider:e,instrumentations:[new UndiciInstrumentation({requireParentforSpans:true})]});}function tRe(e){return !e&&!MR?trace.getTracer("momentic-serverless"):ET?.getTracer("momentic-serverless")??trace.getTracer("momentic-serverless")}async function vd(e){if(!(!e.enabled||af))try{MR=e.serviceName;let t=ZCe(e.serviceName);ET=t,AT=new AsyncLocalStorageContextManager,t.register({contextManager:AT.enable(),propagator:new W3CTraceContextPropagator}),eRe(t),af=!0;}catch{af=false,MR=void 0,ET=void 0,AT=void 0,NR=void 0;}}async function kR(){if(af)try{await JCe(),await ET?.shutdown();}catch{}finally{NR?.();try{AT?.disable();}catch{}af=false,MR=void 0,AT=void 0,ET=void 0,NR=void 0;}}async function He(e){if(!LR()||!e.root&&!XCe())return e.fn(void 0);let t=e.serviceName===void 0?e.attributes:{...e.attributes??{},"momentic.span_service_name":e.serviceName};return await tRe(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 vT=class{increment(t,n,o){}gauge(t,n){}distribution(t,n,o){}async flush(){}async recordDuration(t){return await ok(t)}};async function ok({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 xe(s,{milliseconds:n,message:o??`Timed out after ${n}ms recording duration for ${t}`})}function nRe(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 rk(e,t){let n=nRe(e);return !t||Object.keys(t).length===0?n:{...t,...n}}function mRe(){return new OTLPMetricExporter({url:`${tf}/v1/metrics`,headers:{"x-momentic-metrics-api-key":nf},temporalityPreference:AggregationTemporalityPreference.DELTA})}var ik=[100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],DR=(e,t)=>({instrumentName:e,instrumentType:InstrumentType.HISTOGRAM,aggregation:{type:AggregationType.EXPLICIT_BUCKET_HISTOGRAM,options:{boundaries:t,recordMinMax:false}}}),hRe=[DR("test_event_duration",ik),DR("test_step_duration",ik),DR("test_mobile_step_duration",ik),DR("web_agent_action_duration",[25,50,100,200,350,500,750,1e3,2e3,5e3,1e4,2e4])],FR=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,[PR]:n,[OR]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:v4$1(),[ATTR_SERVICE_VERSION]:"3.25.0"}),r=mRe(),i=new PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:t.exportIntervalMs??6e4});this.provider=new MeterProvider({resource:o,readers:[i],views:hRe}),metrics.setGlobalMeterProvider(this.provider),this.meter=metrics.getMeter("momentic-serverless");}increment(t,n,o){try{let r=rk(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=rk(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 ok(t)}finally{this.distribution(n,Date.now()-r,o);}}};var wt=new vT;function bX(e){if(!e.disabled)try{wt=new FR(e);}catch{wt=new vT;}}var sk;function TX(e){sk=e;}function Wu(e){fRe(e)&&sk&&sk(e);}var gRe=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function fRe(e){return e instanceof Error&&e.name==="AbortError"?false:ob(e,Cu)?true:ob(e,Oe)?false:e instanceof oe?gRe.has(e.reason):true}function yRe({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;wt.distribution("ai_session_tokens",r,[...o,"category:input"]),wt.distribution("ai_session_tokens",Math.max(0,Math.min(i,r)),[...o,"category:cached_input"]),wt.distribution("ai_session_tokens",s,[...o,"category:output"]);}function BR({usage:e,promptType:t,logger:n,message:o,result:r="success",attributes:i}){yRe({usage:e,promptType:t,result:r}),n.info({...i,promptType:t,result:r,usage:e},o);}function ps({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&&BR({usage:a,promptType:t,logger:n,result:i,message:r,attributes:s});});}}function NX(){return globalThis.crypto}function dk(e){let t=NX(),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 Ku(){let e=NX();if(e&&typeof e.randomUUID=="function")return e.randomUUID();let t=dk(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 uk(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 bRe(e){return new Promise(t=>setTimeout(t,e))}function RT(e){if(e)return e.endsWith("/")?e:`${e}/`}function TRe(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 ARe(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 ERe(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=ARe(i,r);n.debug&&console.warn(`${o} ${t} retry ${i}/${n.maxAttempts} in ${s}ms`),s>0&&await bRe(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 Nm(e,t,n,o){let r=`POST ${e}`;await ERe(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=TRe(i.headers);throw typeof l=="number"&&(a.retryAfterMs=l),a.retryable=i.status===429||i.status>=500,a}},r,o);}var AX={UNSET:0,ERROR:2};function EX(e){let t=e?e.traceIdB64:uk(dk(16)),n=uk(dk(8));return {traceIdB64:t,spanIdB64:n,parentSpanIdB64:e?e.spanIdB64:void 0}}function wT(){return Date.now().toString()+"000000"}function vX(e){return String(Math.floor(e))+"000000"}function Z(e,t){if(t!==void 0)return {key:e,value:{stringValue:t}}}function it(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{intValue:String(Math.trunc(t))}}}function cf(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{doubleValue:t}}}function vRe(e,t){if(t!==void 0)return {key:e,value:{boolValue:t}}}function Cd(e,t){if(!(!t||t.length===0))return {key:e,value:{arrayValue:{values:t.filter(n=>typeof n=="string").map(n=>({stringValue:n}))}}}}function ak(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 CX(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 CRe="RAINDROP_LOCAL_DEBUGGER",RRe="RAINDROP_WORKSHOP",RX="http://localhost:5899/v1/";function Sk(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 wRe(){let e=Sk(RRe);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 IRe(e){return e?!!(e==="localhost"||e==="127.0.0.1"||e==="0.0.0.0"||e==="::1"||e.endsWith(".localhost")):false}function xRe(){try{let e=globalThis?.location;if(e&&typeof e.hostname=="string"&&e.hostname.length>0)return e.hostname}catch{}}function _Re(){return !!(IRe(xRe())||Sk("NODE_ENV")==="development")}function km(e){var t,n,o;if(e===null)return null;if(typeof e=="string"&&e.length>0)return (t=RT(e))!=null?t:null;let r=Sk(CRe);if(r)return (n=RT(r))!=null?n:null;let i=wRe();return i==="disable"?null:i==="enable"?RX:i&&"url"in i?(o=RT(i.url))!=null?o:null:_Re()?RX:null}function zR(e){return km(e)!==null}function PRe(e,t={}){var n;let o=km(t.baseUrl);o&&Nm(`${o}traces`,e,{},{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function ORe(e,t={}){var n;let o=km(t.baseUrl);if(!o)return;let r=t.writeKey?{Authorization:`Bearer ${t.writeKey}`}:{};Nm(`${o}events/track_partial`,e,r,{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function qu(e,t={}){var n,o;let r=km(t.baseUrl);r&&Nm(`${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 MRe(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 NRe=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=RT(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=km(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=MRe(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 Nm(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 Nm(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,...A}=(i=g.properties)!=null?i:{},v=(s=g.convoId)!=null?s:f.convoId,w=(l=(a=g.isPending)!=null?a:f.isPending)!=null?l:true,I={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:v},properties:{...A,...T?{"raindrop.wizardSession":T}:{},$context:this.context},attachments:g.attachments,is_pending:w},_=`${this.baseUrl}events/track_partial`;if(this.debug&&console.log(`${this.prefix} sending track_partial`,{eventId:e,eventName:y,userId:S,convoId:v,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(x=>({type:x.type,role:x.role,name:x.name,valuePreview:x.value.slice(0,60)})))!=null?m:[],endpoint:_}),this.localDebuggerUrl&&ORe(I,{baseUrl:this.localDebuggerUrl,writeKey:this.writeKey,debug:this.debug,sdkName:this.sdkName}),!this.writeKey){w||this.sticky.delete(e);return}let R=Nm(_,I,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(R);try{try{await R,this.debug&&console.log(`${this.prefix} sent track_partial ${e} (${y})`);}catch(x){let O=x instanceof Error?x.message:String(x);console.warn(`${this.prefix} failed to send track_partial (dropping): ${O}`);}}finally{this.inFlight.delete(R);}w||this.sticky.delete(e);}},LX=["apikey","apisecret","apitoken","secretaccesskey","sessiontoken","privatekey","privatekeyid","clientsecret","accesstoken","refreshtoken","oauthtoken","bearertoken","authorization","password","passphrase"],kX="[REDACTED]";function DX(e){return e.toLowerCase().replace(/[-_.]/g,"")}function FX(e,t){var n,o;let r=LRe((n=t?.secretKeyNames)!=null?n:LX),i=(o=t?.placeholder)!=null?o:kX,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(DX(d))?c[d]=i:c[d]=a(u);return c};return a(e)}function LRe(e){let t=new Set;for(let n of e)t.add(DX(n));return t}var BX=["ai.request.providerOptions","ai.response.providerMetadata"];function UX(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=HX(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 kRe=new Set(BX);function HX(e,t){if(!kRe.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=FX(o),i;try{i=JSON.stringify(r);}catch{return}if(i!==n)return {stringValue:i}}var DRe=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=RT(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=km(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=UX(t)),t}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}startSpan(e){var t,n;let o=EX(e.parent),r=(t=e.startTimeUnixNano)!=null?t:wT(),i=[Z("ai.telemetry.metadata.raindrop.eventId",e.eventId),Z("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(ak({ids:s.ids,name:s.name,startTimeUnixNano:s.startTimeUnixNano,endTimeUnixNano:s.startTimeUnixNano,attributes:s.attributes,status:{code:AX.UNSET}})),s}mirrorToLocalDebugger(e){if(!this.localDebuggerUrl)return;let t=this.redactSpan(e);if(t===null)return;let n=CX([t],this.serviceName,this.serviceVersion);PRe(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:wT(),(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:AX.ERROR,message:s};}let i=ak({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=EX(e.parent),o=[Z("ai.telemetry.metadata.raindrop.eventId",e.eventId)];(t=e.attributes)!=null&&t.length&&o.push(...e.attributes);let r=ak({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=CX(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=Nm(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(()=>{})));}},FRe={};function wX(){return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE}var BRe=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();}}},URe=class{},HRe=class extends URe{constructor(){super(),this._fallback=null;let e=wX();if(e){this._storage=new e;return}this._fallback=new BRe,this._storage=this._fallback;}maybeAdoptAsyncLocalStorage(){if(!this._fallback||!this._fallback.isEmpty())return;let e=wX();e&&(this._storage=new e,this._fallback=null);}isReady(){return true}getParentSpanIds(){this.maybeAdoptAsyncLocalStorage();let e=this._storage.getStore();if(!(!e||e===FRe))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()}},lk=null;function Yu(){return lk||(lk=globalThis.RAINDROP_CONTEXT_MANAGER?new globalThis.RAINDROP_CONTEXT_MANAGER:new HRe),lk}function jX(e,t){return Yu().runInContext(e,t)}async function Lm(){return Yu().getParentSpanIds()}async function IT(e,t){let n=Yu(),o={traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId};return n.runInContext(o,t)}async function*jRe(e,t){let n;for(;;){let o=await jX(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 ve(e){return typeof e=="object"&&e!==null}function ui(e){return typeof e=="function"}function IX(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 $R(e){try{return JSON.stringify(e)}catch{return}}function ut(e){try{return JSON.stringify(e,(t,n)=>n instanceof Uint8Array?uk(n):n)}catch{return}}function JR(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(!ve(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 bk(e){if(!ve(e))return;let t=e.text;return typeof t=="string"?t:void 0}function GRe(e){var t;if(!ve(e))return;let n=e.object;if(n!==void 0)return (t=$R(n))!=null?t:String(n)}function $Re(e){if(typeof e!="function")return false;let t=e.prototype;return ve(t)?typeof t.generate=="function"&&typeof t.stream=="function":false}function Tk(e){if(!ve(e))return;let t=e.model;if(typeof t=="string"&&t.length)return t;let n=e.response;if(ve(n)){let o=n.modelId;if(typeof o=="string"&&o.length)return o}}function xT(e){if(ve(e)){if(typeof e.finishReason=="string")return e.finishReason;if(ve(e.finishReason)&&typeof e.finishReason.unified=="string")return e.finishReason.unified}}function xX(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 VR(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=xX(e);return n?`data:${t};base64,${n}`:void 0}if(e instanceof ArrayBuffer){let n=xX(new Uint8Array(e));return n?`data:${t};base64,${n}`:void 0}}function GX(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 _X(e){if(typeof e.mediaType=="string")return e.mediaType;if(typeof e.mimeType=="string")return e.mimeType;let t=e.file;if(ve(t)){if(typeof t.mediaType=="string")return t.mediaType;if(typeof t.mimeType=="string")return t.mimeType}}function VRe(e){if(typeof e.filename=="string")return e.filename;if(typeof e.name=="string")return e.name;let t=e.file;if(ve(t)){if(typeof t.filename=="string")return t.filename;if(typeof t.name=="string")return t.name}}function zRe(e){if("data"in e)return e.data;let t=e.file;if(ve(t)){if("file_data"in t)return t.file_data;if("data"in t)return t.data}}function WRe(e,t){var n,o,r;let i=e.type;if(typeof i=="string"){if(i==="image"){let s=(n=_X(e))!=null?n:"image/png",a=VR(e.image,s);return a?{type:"image",role:t,value:a}:void 0}if(i==="image_url"){let s=e.image_url,a=ve(s)?s.url:s,l=VR(a,"image/png");return l?{type:"image",role:t,value:l}:void 0}if(i==="file"){let s=_X(e),a=zRe(e),l=s?.startsWith("image/")===true,c=l&&s?VR(a,s):GX(a);if(!c)return;let d=(r=(o=VRe(e))!=null?o:s)!=null?r:"file";return {type:l?"image":"text",role:t,name:d,value:c}}}}function pk(e,t){if(!Array.isArray(e))return;let n=[];for(let o of e){if(!ve(o))continue;let r=WRe(o,t);r&&n.push(r);}return n.length?n:void 0}function qRe(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?VR(s,i):GX(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 KRe(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(!ve(o))continue;let r=qRe(o);r&&n.push(r);}return n.length?n:void 0}function $X(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t="";for(let n of e)!ve(n)||n.type!=="text"||typeof n.text!="string"||(t+=n.text);return t.length?t:void 0}function Ak(e){let t=e.messages;if(Array.isArray(t))return t;let n=e.prompt;if(Array.isArray(n))return n}function VX(e){let t=Ak(e);if(t)for(let n=t.length-1;n>=0;n--){let o=t[n];if(ve(o)&&o.role==="user")return o}}function Ek(e){var t;if(ve(e))return pk((t=VX(e))==null?void 0:t.content,"input")}async function vk(e){if(!ve(e))return;let t=await KRe(e.files);if(t?.length)return t;let n=XR(e);for(let o=n.length-1;o>=0;o--){let r=n[o];if(!(!ve(r)||r.role!=="assistant"))return pk(r.content,"output")}return pk(e.content,"output")}function Ck(e){var t,n;if(!ve(e))return;let o=(t=VX(e))==null?void 0:t.content;if(o===void 0)return;let r=$X(o);return r!==void 0?r:(n=ut(o))!=null?n:String(o)}function Rk(e){var t;if(!ve(e))return;let n=e.prompt;if(typeof n=="string")return n;let o=Ak(e);if(Array.isArray(o)&&o.length>0){let i=o[o.length-1];if(ve(i)){let s=i.content,a=$X(s);if(a!==void 0)return a;let l=$R(s);if(l)return l}return (t=$R(o))!=null?t:void 0}let r=e.input;return typeof r=="string"?r:$R(e)}function wk(e){if(!ve(e))return [];let t=[];typeof e.system=="string"&&e.system&&t.push({role:"system",content:e.system});let n=Ak(e);if(Array.isArray(n)){for(let o of n)ve(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 XR(e){if(!ve(e))return [];let t=e.response;if(ve(t)&&Array.isArray(t.messages))return t.messages.filter(o=>ve(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(ve(o)&&ve(o.response)){let r=o.response.messages;if(Array.isArray(r))return r.filter(i=>ve(i)&&typeof i.role=="string"&&"content"in i).map(i=>i)}}return []}function WR(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=ut(e.input);return t!==void 0?`name:${e.toolName}|input:${t}`:`name:${e.toolName}`}}function YRe(e,t){return e.isError===true||e.type==="tool-error"?true:ve(t)&&typeof t.type=="string"?t.type.startsWith("error")||t.type==="execution-denied":false}function JRe(e){if(typeof e=="string"&&e.length>0)return e;if(ve(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 ut(e)}function XRe(e){if(!ve(e))return [];let t=e.content;return Array.isArray(t)?t.filter(ve):ve(t)?[t]:[]}function QRe(e){return "input"in e?e.input:"args"in e?e.args:void 0}function Ik(e){let t=e.toolCallId;return typeof t=="string"&&t.length>0?t:void 0}function ZRe(e){return "output"in e?e.output:"result"in e?e.result:e.error}function ewe(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 twe(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 nwe(e){var t,n,o,r;let{spans:i,pendingKeysByToolName:s,part:a}=e,l=Ik(a),c=typeof a.toolName=="string"?a.toolName:void 0,d=QRe(a),u=WR({toolCallId:l,toolName:c,input:d});if(!u)return;let p=l==null?WR({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&&ewe(s,c,u);}function owe(e){var t,n,o;let{spans:r,pendingKeysByToolName:i,part:s}=e,a=Ik(s),l=typeof s.toolName=="string"?s.toolName:void 0,c=ZRe(s),d=WR({toolCallId:a,toolName:l,input:void 0}),u=a!=null?d:(t=twe(i,l))!=null?t:d;if(!u)return;let p=r.get(u),m=YRe(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?JRe(c):void 0});}function zX(e){let t=new Map,n=new Map;for(let o of e)for(let r of XRe(o)){if(r.type==="tool-call"){nwe({spans:t,pendingKeysByToolName:n,part:r});continue}(r.type==="tool-result"||r.type==="tool-error")&&owe({spans:t,pendingKeysByToolName:n,part:r});}return [...t.values()]}function rwe(e){if(!Array.isArray(e))return;let t="";for(let n of e)ve(n)&&n.type==="text"&&typeof n.text=="string"&&(t+=n.text);return t.length?t:void 0}function iwe(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!ve(n)||n.type!=="tool-call")continue;let o=Ik(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 uf(e){if(!ve(e))return;let t=e.experimental_telemetry;if(ve(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:ve(t.metadata)?t.metadata:void 0}}function Pa(e,t){return {operationName:`${e}${t?` ${t}`:""}`,resourceName:t}}function WX(e,t){if(t==null)return;if(typeof t=="string")return Z(e,t);if(typeof t=="number")return Number.isInteger(t)?it(e,t):cf(e,t);if(typeof t=="boolean")return vRe(e,t);if(Array.isArray(t)&&t.every(o=>typeof o=="string"))return Cd(e,t);let n=ut(t);return n?Z(e,n):void 0}function QR(e){return e?Object.entries(e).filter(([t])=>!t.startsWith("raindrop.internal.")).map(([t,n])=>WX(`ai.telemetry.metadata.${t==="raindrop.userId"?"raindrop.ai.userId":t}`,n)):[]}function xk(e){return ve(e)?Object.entries(e).filter(([,t])=>typeof t=="string").map(([t,n])=>Z(`ai.request.headers.${t}`,n)):[]}function _k(e){if(!ve(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(Cd(`ai.settings.${o}`,r)):o==="timeout"&&typeof r=="number"?t.push(it(`ai.settings.${o}`,r)):t.push(WX(`ai.settings.${o}`,r));}return t}function qX(e){return ve(e)?[cf("gen_ai.request.frequency_penalty",typeof e.frequencyPenalty=="number"?e.frequencyPenalty:void 0),it("gen_ai.request.max_tokens",typeof e.maxOutputTokens=="number"?e.maxOutputTokens:void 0),cf("gen_ai.request.presence_penalty",typeof e.presencePenalty=="number"?e.presencePenalty:void 0),...Array.isArray(e.stopSequences)&&e.stopSequences.every(t=>typeof t=="string")?[Cd("gen_ai.request.stop_sequences",e.stopSequences)]:[],cf("gen_ai.request.temperature",typeof e.temperature=="number"?e.temperature:void 0),it("gen_ai.request.top_k",typeof e.topK=="number"?e.topK:void 0),cf("gen_ai.request.top_p",typeof e.topP=="number"?e.topP:void 0)]:[]}function KX(e){if(!ve(e)||!ve(e.providerOptions))return;let t=ut(e.providerOptions);return t?Z("ai.request.providerOptions",t):void 0}var swe=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();}}},UR=null;function YX(){if(UR)return UR;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return UR=e?new e:new swe,UR}function Pk(){return YX().getStore()}function mk(e,t){return YX().run(e,t)}function JX(e){var t;if(e.length===0)return;let n=e[0];if(!ve(n))return;let o=ve(n.metadata)?n.metadata:void 0,r=ve(n.telemetry)?n.telemetry.metadata:void 0,i=ve(r)?r:void 0,s=uf(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 awe=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();}}},HR=null;function Ok(){if(HR)return HR;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return HR=e?new e:new awe,HR}function hk(){return Ok().getStore()}function gk(e){var t;let n=Ok();(t=n.enterWith)==null||t.call(n,e);}function XX(){var e;let t=Ok();(e=t.enterWith)==null||e.call(t,void 0);}var Mk=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=Pk(),m=u??p?.rawMetadata,h=this.extractRaindropMetadata(m),g=Yu().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:Ku(),T=g&&g.eventId===S?{traceIdB64:g.traceIdB64,spanIdB64:g.spanIdB64}:void 0,{operationName:A,resourceName:v}=Pa(t.operationId,d),w=!a&&this.subagentWrapping?hk():void 0,I=!a&&this.subagentWrapping&&w===void 0&&typeof m?.["ash.subagent.name"]=="string"?m["ash.subagent.name"]:void 0,_=(s=w?.toolName)!=null?s:I,R,x;if(_&&this.sendTraces){let N=w?[Z("raindrop.parent.callId",w.parentCallId),Z("raindrop.parent.toolCallId",w.toolCallId),Z("raindrop.parent.toolName",w.toolName)]:[];R=this.traceShipper.startSpan({name:_,parent:T,eventId:S,operationId:"ai.toolCall",attributes:[Z("operation.name","ai.toolCall"),Z("resource.name",_),Z("raindrop.span.kind","tool_call"),Z("ai.toolCall.name",_),Z("raindrop.subagent.name",_),Z("raindrop.agent.role","subagent"),...N]});let k=this.spanParentRef(R),W=this.traceShipper.startSpan({name:"agent.subagent",parent:k,eventId:S,operationId:"agent.subagent",attributes:[Z("operation.name","agent.subagent"),Z("raindrop.span.kind","llm_call"),Z("raindrop.subagent.name",_)]});this.traceShipper.endSpan(W),x=k;}let O;if(this.sendTraces){let N=!a&&l?[Z("ai.prompt",ut({system:t.system,prompt:t.prompt,messages:t.messages}))]:[],k=a&&l?t.operationId==="ai.embedMany"?[Z("ai.values",ut(t.value))]:[Z("ai.value",ut(t.value))]:[];O=this.traceShipper.startSpan({name:t.operationId,parent:x??T,eventId:S,operationId:t.operationId,attributes:[Z("operation.name",A),Z("resource.name",v),Z("ai.telemetry.functionId",d),Z("ai.model.provider",t.provider),Z("ai.model.id",t.modelId),...QR(m?Object.fromEntries(Object.entries(m).filter(([W])=>W!=="raindrop.eventId"&&W!=="raindrop.internal.eventIdGenerated")):void 0),...N,...k]});}this.callStates.set(t.callId,{operationId:t.operationId,eventId:S,rootSpan:O,rootParent:O?this.spanParentRef(O):x??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:_,subagentToolCallSpan:R});},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}=Pa(r,n.functionId),a=[];n.recordInputs&&(t.promptMessages&&a.push(Z("ai.prompt.messages",ut(t.promptMessages))),t.stepTools&&a.push(Cd("ai.prompt.tools",t.stepTools.map(c=>JSON.stringify(c)))),t.stepToolChoice!=null&&a.push(Z("ai.prompt.toolChoice",JSON.stringify(t.stepToolChoice))));let l=this.traceShipper.startSpan({name:r,parent:n.rootParent,eventId:n.eventId,operationId:r,attributes:[Z("operation.name",i),Z("resource.name",s),Z("ai.telemetry.functionId",n.functionId),Z("ai.model.provider",t.provider),Z("ai.model.id",t.modelId),Z("gen_ai.system",t.provider),Z("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(Z("ai.response.finishReason",t.finishReason),Z("ai.response.text",(n=t.text)!=null?n:void 0),Z("ai.response.id",(o=t.response)==null?void 0:o.id),Z("ai.response.model",(r=t.response)==null?void 0:r.modelId),Z("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),Z("ai.response.providerMetadata",t.providerMetadata?ut(t.providerMetadata):void 0)),((a=t.toolCalls)==null?void 0:a.length)>0&&p.push(Z("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=Ib[t]:this.minLogLevel=t;}setOutputStream(t){this.forcedStream=t;}log(...t){this.logWithLevel(30,il.reset,...t);}info(...t){this.logWithLevel(30,il.white,...t);}debug(...t){this.logWithLevel(20,il.dim,...t);}warn(...t){this.logWithLevel(40,il.yellow,...t);}error(...t){this.logWithLevel(50,il.red,...t);}success(...t){this.logWithLevel(30,il.green,...t);}dimmed(...t){this.logWithLevel(30,il.dim,...t);}underline(...t){this.logWithLevel(30,il.underline,...t);}bold(...t){this.logWithLevel(30,il.bold,...t);}grey(...t){this.logWithLevel(30,il.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}},C=fN._internalSingleton(),Gr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Gr,flush:async()=>{},bindings:()=>({})},AC={},SN=({logger:e,logKey:t,maxCount:n,intervalMs:o},r,i,...s)=>{let a=AC[t];a?clearTimeout(a.timer):(a={count:0,totalCount:0},AC[t]=a),a.totalCount++,a.count<n&&(a.count++,e.debug(r,i,...s)),a.timer=setTimeout(()=>{let l=AC[t];l?.totalCount!==l?.count&&e.debug({logKey:t,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${t}`),delete AC[t];},o);};var cW=1e4,dW=1,Pg=ol.extend({browserType:z$1.enum(nl).optional(),slowMoMs:z$1.number().optional().refine(e=>e===void 0||e<=cW&&e>=-1,{message:`Slow motion must be between 0 and ${cW} 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(nC).optional(),colorScheme:z$1.enum(["light","dark"]).optional()}),uW=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],bN=z$1.object({useMemory:z$1.boolean().optional(),failureRecovery:z$1.boolean().optional().describe("undefined means inherit org settings")}),TN=bN.extend({disableAICaching:z$1.boolean().optional(),failureRecoveryInstructions:z$1.string().optional()}),GSe=z$1.object({viewport:dd.optional()}),Bi=GSe.extend(TN.shape).extend(Pg.shape),EC=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()}),vC=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()}),$Se=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")}),pW=$Se.array(),VSe=z$1.object({name:z$1.string(),value:z$1.string()}),CC=VSe.array(),mW=z$1.object({name:z$1.string(),default:z$1.boolean().optional(),fixtures:tz.array().optional()});var Ca=bN.extend({agentConfig:z$1.record(z$1.string(),z$1.string()).optional(),aiFailureAnalysis:z$1.boolean().optional(),classification:U$.optional(),triage:B$.optional(),healing:Rv.optional(),explore:Iv.optional(),select:Xz.optional()}),zSe=z$1.object({cliOnly:z$1.boolean().optional(),neverShowUsageBanner:z$1.boolean().optional(),hideInternalTraceInfo:z$1.boolean().optional(),bypassUsageLimits:z$1.boolean().optional()}),xb=z$1.object({fakerConstantSeed:z$1.boolean().optional(),isolateCachesByEnvironment:z$1.boolean().optional(),saveCacheOnCancel:z$1.boolean().optional()}),WSe=z$1.enum(["flaky_tests","low_test_coverage","frequent_bugs","fix_flaky_tests","migrate_tests","increase_test_coverage","catch_more_bugs"]),qSe=z$1.enum(["ios","android","web"]),KSe=z$1.enum(["selenium","playwright","cypress","puppeteer","maestro","appium","detox","manual_qa","nothing_yet","other"]),YSe=z$1.enum(["advertisement","ai_search","google_search","hacker_news","linkedin","reddit","referral_from_customer","twitter_x","word_of_mouth","youtube","other"]),JSe=z$1.object({helpIntents:z$1.array(WSe).optional(),helpIntentOtherText:z$1.string().optional(),deviceTypeIntent:qSe.optional(),currentTestingTool:KSe.optional(),heardAboutSource:YSe.optional()}),XSe=z$1.object({discovery:JSe.optional(),needsToCompleteOnboarding:z$1.boolean().optional(),wizardCompletedAt:z$1.iso.datetime().optional()}),Og=z$1.object({ai:Ca.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:zM.optional(),internal:zSe.optional(),advanced:xb.optional(),onboarding:XSe.optional()});function hW(e){try{return Og.parse(e)}catch{return C.warn("Cloud settings contain values this version of the CLI does not support. Please upgrade. Falling back to defaults."),Og.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 Us={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},St=(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))(St||{});var _b=(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))(_b||{});var Mg=z$1.enum(_b).default("NOT_ATTEMPTED"),RC=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(RC||{});var QSe=z$1.object({attempts:z$1.int().nonnegative()}),Wn=z$1.string().pipe(z$1.coerce.date()).or(z$1.date()),ds=z$1.object({id:z$1.string(),runKey:z$1.string(),organizationId:z$1.string(),executionType:Nu.optional().default("WEB"),createdAt:Wn,createdBy:z$1.string(),flake:z$1.boolean().nullish(),scheduledAt:Wn.or(z$1.null()),startedAt:Wn.or(z$1.null()),updatedAt:Wn.nullish(),finishedAt:Wn.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:Wn.nullish(),gitCommitMessage:z$1.string().nullish(),schemaVersion:z$1.string().nullish(),cliVersion:z$1.string().nullish(),section:z$1.enum(RC).nullish(),status:z$1.enum(St),healStatus:Mg,healDetails:dz.nullish(),trigger:z$1.enum(Us),attempts:z$1.number(),runAttempts:z$1.array(z$1.object({id:z$1.string(),status:z$1.enum(St),startedAt:Wn.or(z$1.null()),finishedAt:Wn.or(z$1.null())})).optional(),videos:z$1.array(z$1.string()).optional(),failureReason:z$1.string().nullish(),failureDetails:GV.nullish(),failureRecoveryDetails:QSe.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:Ca.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()}),ZSe={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},wC=ds.pick({...ZSe,test:true}),gW=ds.omit({failureReason:true,failureDetails:true,test:true}),AN=ds.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:Bi.nullish()}).nullish()}).extend(dN.shape),fW=e=>e.includes("PASSED")&&e.includes("FAILED");var ebe=z$1.object({region:z$1.enum(["US","EU"]).optional().describe("New Relic data center region. Defaults to US."),accountId:z$1.string().describe("New Relic account ID to send events to. Supports ${ENV_VAR} interpolation."),licenseKey:z$1.string().optional().describe("New Relic ingest license key. Supports ${ENV_VAR} interpolation. Defaults to the NEW_RELIC_LICENSE_KEY environment variable."),attributes:z$1.record(z$1.string(),z$1.string()).optional().describe("Static attributes (e.g. service, team) added to every event sent to New Relic. Values support ${ENV_VAR} interpolation.")}),yW=z$1.object({newrelic:ebe.optional()}),tbe=z$1.object({category:z$1.string(),reasoning:z$1.string(),citations:z$1.array(Uo).optional()}),nbe=z$1.object({testInputs:z$1.record(z$1.string(),z$1.string()).optional(),envName:z$1.string().optional(),urlOverride:z$1.string().optional()}),obe=z$1.object({reason:z$1.string().optional(),message:z$1.string().optional()}),rbe=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(St),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:nbe.optional(),failure:obe.nullable(),classification:tbe.nullable()}),ibe=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()}),sbe=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()}),SW=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:sbe,runs:z$1.array(rbe),skipped:z$1.array(ibe)});var bW=z$1.enum(["error","warning","passing"]);var TW=z$1.enum(["safe_to_merge","confirm_intended_change","investigate_regression","fix_test","resolve_infra","review_coverage"]);var lbe="One very short, punchy sentence (ideally under 70 characters) summarizing the run group result. Factual, specific, no trailing period, no category prefix. When referencing test names, wrap each in backticks (e.g. `my-test`). No other markdown. Do not capitalize the first word unless it is a proper noun, since a category prefix is prepended before it. Describe the outcome only \u2014 never name the process or mode (no 'dry run', 'auto-heal', 'triage', 'pending'); those are shown separately.";var AW=z$1.object({kind:TW,detail:z$1.string().min(1).max(280)}),bm=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:AW.optional()}),EW=bm.extend({riskLevel:bW.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(120).describe(lbe),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:AW.extend({kind:TW.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 vW=z$1.object({id:z$1.string(),status:z$1.enum(St),trigger:z$1.enum(Us),createdAt:Wn,startedAt:Wn.nullish(),finishedAt:Wn.nullish(),gitCommitSha:z$1.string().nullish(),gitCommitShaShort:z$1.string().nullish(),gitCommitTimestamp:Wn.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:bm.optional(),environments:z$1.string().array().optional(),executionTypes:Nu.array().optional(),localSuiteName:z$1.string().optional(),suite:z$1.object({id:z$1.string(),name:z$1.string()}).nullish(),runs:z$1.object({status:z$1.enum(St)}).array()}),CW=vW.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true,localSuiteName:true}).extend({runs:wC.array()}),RW=vW.extend({runs:ds.array()});var cbe=z$1.object({type:z$1.literal("TARGETING"),name:z$1.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Wz.array(),pageState:z$1.string().optional(),targetSource:z$1.enum(Gl).optional(),targetUpdateTime:z$1.string().optional()}),dbe=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()}),ube=z$1.object({type:z$1.literal("ASSERTION"),relevantElementsSerialized:z$1.string().array().optional(),pageState:z$1.string().optional(),ragUsed:z$1.boolean().optional()}),wW=z$1.discriminatedUnion("type",[cbe,dbe,ube]);var pbe=z$1.object({id:z$1.string(),name:z$1.string()});pbe.extend(z$1.object({createdAt:Wn,createdBy:z$1.string(),schedule:EC,notification:vC,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 IW=z$1.object({id:z$1.guid(),orgId:z$1.string(),createdAt:Wn,startedAt:Wn.or(z$1.null()),finishedAt:Wn.or(z$1.null()),status:z$1.enum(St),trigger:z$1.enum(Us),suite:z$1.object({id:z$1.string(),name:z$1.string()}).nullish(),runs:ds.array()});IW.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true});var xW=IW.extend({runs:wC.array()});function _W({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 IC(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 PW(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 EN=z$1.object({content:z$1.string(),ids:z$1.string().array(),tokenLength:z$1.number()}),mbe=z$1.object({chunks:EN.array()});z$1.object({ids:z$1.string().array(),score:z$1.number(),tokenLength:z$1.number()});mbe.extend({description:z$1.string().describe("Input to pass to RAG engine"),tokenLimit:z$1.number()});var OW=z$1.object({ids:z$1.number().array()}),MW=z$1.object({indices:z$1.number().array()});var al=(n=>(n.Interactive="interactive",n.Runner="runner",n))(al||{}),hbe=z$1.enum(al),hr=z$1.object({disableCache:z$1.boolean().optional(),useMemory:z$1.boolean().optional(),clientMode:hbe.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(FS).optional()});hr.extend({chunks:EN.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 gbe=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()}),NW=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string(),source:zz.optional().catch(void 0),isTieBreakerCall:z$1.boolean().optional(),memory:z$1.discriminatedUnion("type",[Ja,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional(),firstPassModelResults:hC.array().optional(),knowledgeBaseSection:z$1.string().optional()}),LW=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()}),kW=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string().optional(),returnSchema:z$1.string().optional()}),DW=z$1.object({goal:z$1.string(),emulatorState:z$1.string(),screenshot:z$1.string().optional(),returnSchema:z$1.string().optional()}),vN=z$1.union([z$1.literal("NEGATED_CHECK"),z$1.literal("CONDITIONAL_CHECK")]),FW=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string(),url:z$1.string(),contextChoice:lm.optional(),memory:z$1.discriminatedUnion("type",[im,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional(),source:vN.optional(),recoveryHint:z$1.string().optional(),knowledgeBaseSection:z$1.string().optional()}),BW=z$1.object({command:Eu}),CN=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:gbe.array(),actionHint:z$1.string().optional(),lastError:z$1.string().optional()}),UW=z$1.object({results:aC.array(),errorMessage:z$1.string(),errorStack:z$1.string().optional()}),HW=z$1.object({results:aC.array(),goal:z$1.string(),errorMessage:z$1.string()}),jW=z$1.object({failedResults:aC.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 GW=z$1.object({type:z$1.string(),browserContext:z$1.string(),currentStep:z$1.string(),screenshot:z$1.string()}),$W=z$1.object({description:z$1.string(),browserState:z$1.string().optional(),screenshot:z$1.string()}),fbe=z$1.enum(["locator","assertion"]);z$1.object({completionType:fbe,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 VW=z$1.object({keywords:z$1.array(z$1.string())});var xC=(i=>(i.LOCATOR="locator",i.ASSERTION="assertion",i.VISUAL_ASSERTION="visual-assertion",i.TEXT_EXTRACTION="text-extraction",i.FAILURE_RECOVERY="failure-recovery",i))(xC||{}),_C=["locator","assertion","visual-assertion","text-extraction","failure-recovery"];z$1.enum(xC);var ybe=new Set(_C);function Sbe(e){return ybe.has(e)}var bbe=z$1.enum(["v1","v2","v3","v4"]),Tbe=z$1.string().regex(/^v\d+\.\d+$/).describe("pinned sub-version like v3.1");z$1.union([bbe,Tbe,z$1.string().describe("for people with special configurations")]);var ku={locator:"v4.2",assertion:"v4.1","visual-assertion":"v4.0","text-extraction":"v3.0","failure-recovery":"v2.1"},PC={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"]}},zW=(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))(zW||{});z$1.enum(zW);var Abe={locator:["v1"],assertion:["v1"],"visual-assertion":["v1"],"text-extraction":["v1"]};function OC(e){let t=Abe[e];if(!t)return new Set;let n=PC[e],o=new Set;for(let r of t){o.add(r);for(let i of n[r]??[])o.add(i);}return o}function MC(e){for(let[t,n]of Object.entries(e)){if(!Sbe(t))continue;let o=PC[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 oe("UserConfigurationError",`Invalid agent config: "${n}" is not a valid version for "${t}". Valid versions: ${i.join(", ")}`)}if(OC(t).has(n))throw new oe("UserConfigurationError",`Agent config "${n}" for "${t}" is no longer supported because it relies on a legacy model. Upgrade to a newer version.`)}}var pd=P__default.object({id:P__default.guid(),envKey:P__default.string().optional(),skipped:P__default.boolean().optional(),retries:P__default.number().optional()});var md=(r=>(r.PRESET="MOBILE_PRESET_STEP",r.MODULE="MOBILE_MODULE_STEP",r.AI_ACTION="MOBILE_AI_ACTION_STEP",r.CONDITIONAL="MOBILE_CONDITIONAL_STEP",r))(md||{});var Lg=pd.extend({type:P__default.literal("MOBILE_CONDITIONAL_STEP")});var li=z$1.object({id:z$1.string(),name:zv,baseUrl:Wv,description:z$1.string().optional().nullish(),schemaVersion:z$1.string(),advanced:Bi,retries:z$1.number().optional().nullish(),envs:z$1.array(mW).nullish(),parameters:pW.nullish(),disabled:z$1.boolean().optional(),labels:z$1.array(z$1.string()).optional().catch([])}),WW=z$1.enum(["INHERIT","ENABLED","DISABLED"]);var vbe=Bi.shape.geolocation.unwrap().partial().superRefine(({latitude:e,longitude:t},n)=>{e!==void 0&&t===void 0&&n.addIssue({code:"custom",message:"Longitude is required when latitude is provided",path:["longitude"]}),t!==void 0&&e===void 0&&n.addIssue({code:"custom",message:"Latitude is required when longitude is provided",path:["latitude"]});}),Cbe=Bi.shape.proxy.unwrap().partial().superRefine(({server:e,username:t,password:n},o)=>{!e&&(t||n)&&o.addIssue({code:"custom",message:"Proxy host is required when credentials are provided",path:["server"]});}),Rbe=Bi.extend({failureRecovery:WW.optional(),geolocation:vbe.optional(),proxy:Cbe.optional(),useMemory:WW.optional()});li.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,parameters:true}).extend({advanced:Rbe});li.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,advanced:true,parameters:true});var wbe=z$1.object({labels:z$1.array(z$1.string()).optional(),outputs:CC.nullish()}),lo=li.extend(wbe.shape),Ibe=z$1.object({createdAt:z$1.coerce.date(),updatedAt:z$1.coerce.date(),updatedBy:z$1.string().nullable(),schedule:EC,notification:vC,createdBy:z$1.string(),organizationId:z$1.string(),folderId:z$1.string().nullable().optional()}),xbe=li.extend(Ibe.shape);xbe.extend(Ls.shape);var RN=li.extend(Ls.shape);li.extend(rd.shape);var _be="test",Pbe="module",Obe="mobile-test",Mbe="mobile-module",Nbe="test/v2",Lbe="module/v2",kbe="mobile-test/v2",Dbe="mobile-module/v2";var Fe=(l=>(l.TEST=`momentic/${_be}`,l.MODULE=`momentic/${Pbe}`,l.TEST_V2=`momentic/${Nbe}`,l.MODULE_V2=`momentic/${Lbe}`,l.MOBILE_TEST=`momentic/${Obe}`,l.MOBILE_MODULE=`momentic/${Mbe}`,l.MOBILE_TEST_V2=`momentic/${kbe}`,l.MOBILE_MODULE_V2=`momentic/${Dbe}`,l))(Fe||{});li.merge(rd);var Fbe=so.extend({steps:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())),schemaVersion:z$1.string()}),Mb=Fbe.extend({fileType:z$1.literal(Fe.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 NC(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(NC);let t={};for(let[n,o]of Object.entries(e))t[n]=NC(o);return t}var Bbe=/^[a-z0-9]+(?:-[a-z0-9]+){2,}$/,qW=36,co=z$1.union([z$1.guid().max(qW,"V2 IDs must be 36 characters or fewer"),z$1.string().max(qW,"V2 IDs must be 36 characters or fewer").regex(Bbe,"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 LC=P.discriminatedUnion("type",[P.object({type:P.literal("SCREEN")}),P.object({type:P.literal("OPEN_APP")}),P.object({type:P.literal("OPEN_WEBVIEW")})]),hd=P.object({type:P.literal("description"),description:P.string()}),IN=P.object({type:P.literal("CUSTOM_COORDINATES"),startX:P.number().describe("Starting X coordinate in pixels"),startY:P.number().describe("Starting Y coordinate in pixels"),deltaPixels:P.number().describe("Number of pixels to scroll in the specified direction")}),kC=P.discriminatedUnion("type",[...LC.options,P.object({type:P.literal("CUSTOM"),target:hd}),IN]);function Ube(e){return e.toLowerCase().replaceAll("_"," ")}function xN(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 Ube(e.type);default:{throw new Error("Unreachable")}}}var Hbe=P.object({type:P.literal("coordinates"),xPercent:P.number(),yPercent:P.number()}),jbe=P.object({type:P.literal("absolute_percent"),x:P.number(),y:P.number()}),kg=P.discriminatedUnion("type",[hd,Hbe,jbe]);var Gbe=P.object({x1:P.number(),y1:P.number(),x2:P.number(),y2:P.number(),tolerance:P.nativeEnum(ss),preciseTolerance:P.boolean().optional()}),$be=P.object({width:P.number(),height:P.number(),tolerance:P.nativeEnum(ss),preciseTolerance:P.boolean().optional()}),_N=P.object({requiredText:P.string().optional(),requiredAttributes:P.record(P.string(),P.string()).optional(),requiredBounds:P.boolean().optional(),position:Gbe.optional(),shape:$be.optional()}),KW=P.object({xPath:P.string(),requirements:_N.optional()}),Vbe=P.object({type:P.literal("CUSTOM"),target:hd,cache:P.lazy(()=>YW).optional()}),zbe=P.object({pixelDelta:P.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:P.union([LC,Vbe,IN]),direction:P.enum(["up","down"])}),YW=P.object({type:P.literal("NATIVE"),bounds:P.number().array().optional(),resolvedDescription:P.string().optional(),xPath:P.string().optional(),elementOnlySerializedXml:P.string().optional(),scrollDetails:zbe.optional(),requirements:_N.optional(),requiredRelatedElements:KW.array().optional(),memory:Ja.optional()}),Wbe=P.object({type:P.literal("WEBVIEW"),resolvedDescription:P.string().optional(),xPath:P.string().optional(),browserCache:$l.optional(),memory:Ja.optional()}),DC=P.union([YW,Wbe]);var qbe=P.object({left:P.number(),top:P.number(),right:P.number(),bottom:P.number()});P.object({newViewportBounds:qbe});var Kbe=P.object({type:P.literal("CUSTOM"),target:hd,cache:P.lazy(()=>ZW).optional()}),JW=P.object({pixelDelta:P.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:P.union([LC,Kbe,IN]),direction:P.enum(["up","down"])}),XW=(n=>(n.Native="native",n.Appium="appium",n))(XW||{}),PN=P.tuple([P.number(),P.number(),P.number(),P.number()]),QW=KW.extend({bounds:PN.optional(),browserCache:$l.optional()}),ZW=P.object({type:P.literal("NATIVE"),bounds:PN.optional(),resolvedDescription:P.string().optional(),sourceTree:P.nativeEnum(XW).optional(),xPath:P.string().optional(),elementOnlySerializedXml:P.string().optional(),scrollDetails:JW.optional(),requirements:_N.optional(),requiredRelatedElements:QW.array().optional(),memory:Ja.optional()}),Ybe=P.object({type:P.literal("WEBVIEW"),bounds:PN.optional(),resolvedDescription:P.string().optional(),xPath:P.string().optional(),scrollDetails:JW.optional(),browserCache:$l.optional(),requiredRelatedElements:QW.array().optional(),memory:Ja.optional()}),FC=P.discriminatedUnion("type",[ZW,Ybe]);var Jt=(x=>(x.AI_CHECK="AI_CHECK",x.AI_EXTRACT="AI_EXTRACT",x.TAP="TAP",x.TYPE="TYPE",x.PRESS="PRESS",x.PRESS_KEYBOARD="PRESS_KEYBOARD",x.OPEN_APP="OPEN_APP",x.KILL_APP="KILL_APP",x.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",x.SWIPE="SWIPE",x.SCROLL_TO="SCROLL_TO",x.SCREEN_CHECK="SCREEN_CHECK",x.ELEMENT_CHECK="ELEMENT_CHECK",x.VISUAL_DIFF="VISUAL_DIFF",x.DRAG_AND_DROP="DRAG_AND_DROP",x.JAVASCRIPT="JAVASCRIPT",x.REQUEST="REQUEST",x.WAIT="WAIT",x.ADD_FILE="ADD_FILE",x.INSTALL_APP="INSTALL_APP",x.UNINSTALL_APP="UNINSTALL_APP",x.TOGGLE_SETTINGS="TOGGLE_SETTINGS",x.ROTATE_ORIENTATION="ROTATE_ORIENTATION",x.ADB_COMMAND="ADB_COMMAND",x.APPIUM_EXECUTE="APPIUM_EXECUTE",x.STATE="STATE",x))(Jt||{}),Qe=P__default.object({id:P__default.guid(),disableCache:P__default.boolean().optional()}),Dg=P__default.object({updatedAt:P__default.coerce.date().optional(),updatedAtLoggerTags:P__default.record(P__default.string(),P__default.string()).optional()}),wa=Dg.extend({target:DC}),BC=Dg.extend({fromTarget:DC,toTarget:DC}),lc=Dg.extend({target:FC}),e1=Dg.extend({fromTarget:FC,toTarget:FC}),gd=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 t1=Qe.extend({type:P__default.literal("ADB_COMMAND"),command:P__default.string(),jsonArgs:P__default.string().optional()});var Jbe=P__default.string().trim(),o1=Qe.extend({type:P__default.literal("INSTALL_APP"),uri:Jbe});var r1=Qe.extend({type:P__default.literal("OPEN_NOTIFICATION_DRAWER")});var Nb=(r=>(r.AIRPLANE_MODE="AIRPLANE_MODE",r.DATA="DATA",r.WIFI="WIFI",r.LOCATION="LOCATION",r))(Nb||{}),s1=Qe.extend({type:P__default.literal("TOGGLE_SETTINGS"),settingsType:P__default.nativeEnum(Nb)});var l1=Qe.extend({type:P__default.literal("UNINSTALL_APP"),packageName:P__default.string()});var UC=Qe.extend({type:P__default.literal("APPIUM_EXECUTE"),command:P__default.string(),jsonArgs:P__default.string().optional()});var c1=Qe.extend({type:P__default.literal("ADD_FILE"),file:P__default.string(),storageLocation:P__default.string()});var fd=Qe.extend({type:P__default.literal("AI_CHECK"),assertion:P__default.string(),timeoutSecs:P__default.number().optional(),contextChoice:lm.optional(),cache:Dg.extend({memory:im.optional()}).optional()});var d1=Qe.extend({type:P__default.literal("AI_EXTRACT"),goal:P__default.string(),schema:P__default.string().optional()});var Fg=Qe.extend({type:P__default.literal("JAVASCRIPT"),code:P__default.string(),timeout:P__default.number().int().max(600).optional().describe("Max seconds for the code to complete")});var u1=Qe.extend({type:P__default.literal("KILL_APP")});var kb=(n=>(n.HOME="HOME",n.POWER="POWER",n))(kb||{}),HC=(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))(HC||{}),jC=Qe.extend({type:P__default.literal("PRESS"),key:P__default.nativeEnum(kb),longPress:P__default.boolean().optional()}),p1=jC.extend({key:P__default.nativeEnum(HC).or(P__default.nativeEnum(kb))}),m1=jC;var h1=Qe.extend({type:P__default.literal("REQUEST")}).merge(HS);var FN=(n=>(n.PORTRAIT="PORTRAIT",n.LANDSCAPE="LANDSCAPE",n))(FN||{}),f1=Qe.extend({type:P__default.literal("ROTATE_ORIENTATION"),orientation:P__default.nativeEnum(FN)});var eTe=P__default.object({type:P__default.literal("CONTENT"),negated:P__default.boolean().optional(),value:P__default.string()}),Ug=Qe.extend({type:P__default.literal("SCREEN_CHECK"),assertion:eTe,timeout:P__default.number().int().min(0).max(ig).optional().describe("max seconds to wait for the assertion to be true")});var y1=Qe.extend({type:P__default.literal("STATE")});var S1=Qe.extend({type:P__default.literal("VISUAL_DIFF"),path:P__default.string().describe("path to the golden screenshot to compare against"),threshold:P__default.number().min(0).max(1).optional().describe("max allowed fraction of differing pixels before the diff fails (default 0.1)")});P__default.object({created:P__default.boolean(),goldenPath:P__default.string(),threshold:P__default.number(),goldenScreenshotBase64:P__default.string().optional(),currentScreenshotBase64:P__default.string().optional(),diffScreenshotBase64:P__default.string().optional(),goldenScreenshotSnapshotId:P__default.string().optional(),currentScreenshotSnapshotId:P__default.string().optional(),diffScreenshotSnapshotId:P__default.string().optional(),diffPercent:P__default.number().optional(),pass:P__default.boolean().optional(),dimensionMismatch:P__default.boolean().optional()});var T1=Qe.extend({type:P__default.literal("WAIT"),timeoutSecs:P__default.number()});var Db=P__default.discriminatedUnion("type",[y1,fd,d1,Fg,T1,h1,f1,Ug,S1,c1,u1]);P__default.discriminatedUnion("type",[...Db.options,jC]);var UN=Qe.extend({type:P__default.literal("DRAG_AND_DROP"),fromTarget:hd,toTarget:hd,hoverDuration:P__default.number().optional(),dragDuration:P__default.number().optional()}),Fb=UN.extend({cache:BC.optional()}),Bb=UN.extend({cache:e1.optional()});var HN=Qe.extend({type:P__default.literal("ELEMENT_CHECK"),target:kg,assertion:Ov,timeout:P__default.number().int().min(0).max(ig).optional().describe("max seconds to wait for the assertion to be true")}),Tm=HN.extend({cache:wa.optional()}),Am=HN.extend({cache:lc.optional()});var Ub=(n=>(n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(Ub||{}),GC=(t=>(t.CLOSE_KEYBOARD="CLOSE_KEYBOARD",t))(GC||{}),v1={repeat:P__default.number().int().min(1).optional(),keyPressDelayMs:P__default.number().min(0).optional()},C1=Qe.extend({type:P__default.literal("PRESS_KEYBOARD"),key:P__default.nativeEnum(Ub),...v1}),R1=Qe.extend({type:P__default.literal("PRESS_KEYBOARD"),key:P__default.nativeEnum(GC).or(P__default.nativeEnum(Ub)),...v1});var w1=Qe.extend({type:P__default.literal("OPEN_APP"),packageName:P__default.string(),activityName:P__default.string().optional(),intentExtras:P__default.string().optional()}),I1=Qe.extend({type:P__default.literal("OPEN_APP"),packageName:P__default.string(),intentExtras:P__default.string().optional()});var jN=Qe.extend({type:P__default.literal("SCROLL_TO"),target:hd,direction:P__default.enum(["down","up"]),scrollableElement:kC,scrollStepPercent:P__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:P__default.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 20.")}),Hb=jN.extend({cache:wa.optional()}),jb=jN.extend({cache:lc.optional()});var GN=Qe.extend({type:P__default.literal("SWIPE"),direction:P__default.enum(["up","down","left","right"]),scrollableElement:kC,viewportPercent:P__default.number().optional(),durationMs:P__default.number().optional(),relativePosition:_v.optional()}),Gb=GN.extend({cache:wa.optional()}),$b=GN.extend({cache:lc.optional()});var $N=Qe.extend({type:P__default.literal("TAP"),target:kg,longPress:P__default.boolean().optional(),longPressDurationMs:P__default.number().optional(),iterations:P__default.number().optional(),tapDelayMs:P__default.number().optional(),relativePosition:_v.optional(),doubleTap:P__default.boolean().optional(),doubleTapDelayMs:P__default.number().optional()}),Vb=$N.extend({cache:wa.optional()}),zb=$N.extend({cache:lc.optional()});var Wb=(r=>(r.AUTO="auto",r.PROGRAMMATIC="programmatic",r.LONG_PRESS="long-press",r.BACKSPACE="backspace",r))(Wb||{});var VN=Qe.extend({type:P__default.literal("TYPE"),target:kg.optional(),keyPressDelayMs:P__default.number().optional(),text:P__default.string(),clearContent:P__default.boolean().optional(),forceClearContent:P__default.boolean().optional(),replaceStrategy:P__default.nativeEnum(Wb).optional()});var qb=VN.extend({cache:wa.optional()}),Kb=VN.extend({cache:lc.optional()});var Yb=P__default.discriminatedUnion("type",[...Db.options,Vb,qb,p1,R1,l1,o1,t1,UC,Fb,r1,Hb,Gb,s1,Tm,w1]);var Jb=P__default.discriminatedUnion("type",[...Db.options,zb,Kb,m1,C1,I1,$b,Bb,jb,Am,UC]);var P1=P__default.union([P__default.string(),P__default.record(P__default.string(),P__default.unknown().optional())]),zC=pd.extend({type:P__default.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:P__default.number().optional()}),Fu=zC.extend({command:Yb}),Bu=zC.extend({command:Jb}),jg=P__default.object({moduleId:P__default.string(),inputs:P__default.record(P__default.string(),P__default.string()).optional()}),Xb=pd.merge(jg.extend({type:P__default.literal("MOBILE_MODULE_STEP")}));jg.extend({steps:P__default.lazy(()=>cc.array())});jg.extend({steps:P__default.lazy(()=>yd.array())});var zN=(n=>(n.V2="2",n.V3="3",n))(zN||{});var WN=P__default.nativeEnum(zN),iTe=jl.extend({platform:P__default.literal("ANDROID"),resolvedGoal:P__default.string(),steps:P__default.lazy(()=>Fu.array()),autoGeneratedPostcondition:P__default.string().optional()}),sTe=jl.extend({platform:P__default.literal("IOS"),resolvedGoal:P__default.string(),steps:P__default.lazy(()=>Bu.array()),autoGeneratedPostcondition:P__default.string().optional()}),qN=P__default.discriminatedUnion("platform",[iTe,sTe]),Uu=pd.extend({type:P__default.literal("MOBILE_AI_ACTION_STEP"),text:P__default.string(),version:WN.optional(),cache:qN.optional(),precondition:P__default.string().optional(),postcondition:P__default.string().optional()});var lTe=P__default.discriminatedUnion("type",[fd,Ug,Tm,Fg]),KN=zC.extend({command:lTe}),cTe=P__default.discriminatedUnion("type",[fd,Ug,Am,Fg]),YN=zC.extend({command:cTe}),dTe=P__default.object({assertion:KN,steps:P__default.lazy(()=>cc.array())}),uTe=P__default.object({assertion:YN,steps:P__default.lazy(()=>yd.array())}),pTe=Lg.extend({blocks:P__default.lazy(()=>dTe.array()),elseSteps:P__default.lazy(()=>cc.array()).optional()}),mTe=Lg.extend({blocks:P__default.lazy(()=>uTe.array()),elseSteps:P__default.lazy(()=>yd.array()).optional()}),cc=P__default.discriminatedUnion("type",[Fu,Xb,Uu,pTe]),yd=P__default.discriminatedUnion("type",[Bu,Xb,Uu,mTe]);P__default.union([cc.array(),yd.array()]);var JN=P__default.object({parameterNames:P__default.string().array(),defaultParameters:P__default.record(P__default.string(),P__default.string()).optional(),parameterEnums:P__default.record(P__default.string(),P__default.string().array()).optional()}),WC=P__default.object({moduleId:co,name:P__default.string(),description:P__default.string().nullish(),platform:P__default.nativeEnum(rl).optional().default("ANDROID"),parameters:JN.optional(),enabled:P__default.boolean().nullish(),schemaVersion:P__default.string()}),XN=WC.omit({name:true}),hTe=XN.extend({steps:P1.array()});P__default.object({fileType:P__default.literal(Fe.MOBILE_MODULE)}).merge(hTe);var O1=WC.omit({platform:true,schemaVersion:true});({ANDROID:O1.extend({platform:P__default.literal("ANDROID"),steps:cc.array()}),IOS:O1.extend({platform:P__default.literal("IOS"),steps:yd.array()})});var Gg=(t=>(t.MODULE="RESOLVED_MOBILE_MODULE",t))(Gg||{}),M1=P__default.object({description:P__default.string().optional(),name:P__default.string().describe("name of the module"),parameters:JN.optional()}),N1=jg.merge(M1).extend({platform:P__default.literal("ANDROID"),get steps(){return cl.array()}}),L1=jg.merge(M1).extend({platform:P__default.literal("IOS"),get steps(){return dl.array()}});P__default.discriminatedUnion("platform",[N1,L1]);var QN=pd.merge(N1).extend({type:P__default.literal("RESOLVED_MOBILE_MODULE")}),ZN=pd.merge(L1).extend({type:P__default.literal("RESOLVED_MOBILE_MODULE")});P__default.discriminatedUnion("platform",[QN,ZN]);var gTe=P__default.object({assertion:KN,get steps(){return cl.array()}}),eL=Lg.extend({get blocks(){return gTe.array()},get elseSteps(){return cl.array().optional()}}),fTe=P__default.object({assertion:YN,get steps(){return dl.array()}}),tL=Lg.extend({get blocks(){return fTe.array()},get elseSteps(){return dl.array().optional()}}),cl=P__default.discriminatedUnion("type",[QN,Fu,Uu,eL]),dl=P__default.discriminatedUnion("type",[ZN,Bu,Uu,tL]);function k1(e){return Object.values(Gg).includes(e)||Object.values(md).includes(e)}var D1=(i=>(i.PRECONDITION="PRECONDITION",i.REPLAY="REPLAY",i.GENERATE="GENERATE",i.AUTOHEAL="AUTOHEAL",i.POSTCONDITION="POSTCONDITION",i))(D1||{}),F1=z$1.enum(["pending","running","success","failed"]),B1=z$1.object({type:z$1.literal("THOUGHT"),text:z$1.string(),blockId:z$1.string().optional()}),U1=z$1.object({type:z$1.literal("TOOL_CALL"),toolName:z$1.string()}),H1=z$1.object({type:z$1.literal("PHASE"),phase:z$1.nativeEnum(D1),failureMessage:z$1.string().optional()}),yTe=z$1.object({type:z$1.literal("STEP_UPDATE"),stepIndex:z$1.number(),step:cl,status:F1,message:z$1.string().optional(),afterSnapshotId:z$1.string().optional()}),STe=z$1.object({type:z$1.literal("STEP_UPDATE"),stepIndex:z$1.number(),step:dl,status:F1,message:z$1.string().optional(),afterSnapshotId:z$1.string().optional()}),j1=z$1.object({type:z$1.literal("SCREENSHOT"),stepIndex:z$1.number(),screenshotId:z$1.string()}),G1=z$1.object({type:z$1.literal("POSTCONDITION_AUTOGENERATED"),postcondition:z$1.string()}),bTe=z$1.object({type:z$1.literal("CACHED_STEPS_GENERATED"),cachedSteps:Fu.array(),resolvedGoal:z$1.string()}),TTe=z$1.object({type:z$1.literal("CACHED_STEPS_GENERATED"),cachedSteps:Bu.array(),resolvedGoal:z$1.string()}),ATe=z$1.discriminatedUnion("type",[B1,U1,H1,yTe,j1,bTe,G1]),ETe=z$1.discriminatedUnion("type",[B1,U1,H1,STe,j1,TTe,G1]);function $1(e){let t=z$1.object({version:z$1.literal(1),events:e.array(),spans:YM.array().optional()});return z$1.union([t,e.array()]).transform(n=>Array.isArray(n)?{version:1,events:n}:n)}var V1=$1(ATe),z1=$1(ETe);var dc=P__default.object({message:P__default.string().optional(),startTime:P__default.number(),endTime:P__default.number(),status:P__default.nativeEnum(Bt),trace:P__default.unknown().optional().optional(),beforeSnapshot:P__default.string().optional(),afterSnapshot:P__default.string().optional(),data:P__default.unknown().optional().optional().describe("output data from the step"),aiSuggested:P__default.boolean().optional(),beforeTestContext:vg.optional(),afterTestContext:vg.optional()}),W1=dc.merge(Fu).extend({previousAttempts:P__default.lazy(()=>js.array()).optional()}),vTe=dc.merge(Xb).extend({steps:P__default.lazy(()=>js.array()),name:P__default.string().optional(),previousAttempts:P__default.lazy(()=>js.array()).optional()}),CTe=dc.merge(Uu).extend({steps:P__default.lazy(()=>js.array()),previousAttempts:P__default.lazy(()=>js.array()).optional(),failureRecoveryReason:P__default.string().optional(),trajectory:V1.optional()}),RTe=dc.merge(eL).extend({assertionResult:W1.optional(),steps:P__default.lazy(()=>js.array()),previousAttempts:P__default.lazy(()=>js.array()).optional()}),js=P__default.discriminatedUnion("type",[W1,vTe,CTe,RTe]),q1=dc.merge(Bu).extend({previousAttempts:P__default.lazy(()=>Gs.array()).optional()}),wTe=dc.merge(Xb).extend({steps:P__default.lazy(()=>Gs.array()),name:P__default.string().optional(),previousAttempts:P__default.lazy(()=>Gs.array()).optional()}),ITe=dc.merge(Uu).extend({steps:P__default.lazy(()=>Gs.array()),previousAttempts:P__default.lazy(()=>Gs.array()).optional(),failureRecoveryReason:P__default.string().optional(),trajectory:z1.optional()}),xTe=dc.merge(tL).extend({assertionResult:q1.optional(),steps:P__default.lazy(()=>Gs.array()),previousAttempts:P__default.lazy(()=>Gs.array()).optional()}),Gs=P__default.discriminatedUnion("type",[q1,wTe,ITe,xTe]);var _Te=dc.extend({index:P__default.number().optional(),userFacingStepReference:P__default.string().optional(),description:P__default.string()}),K1=_Te.extend({beforeScreenshot:P__default.string().optional(),afterScreenshot:P__default.string().optional()});var Y1=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(ss).optional(),shapeSpecificity:z$1.enum(ss).optional()}),PTe=z$1.object({id:z$1.number(),requirements:Y1}).array();z$1.object({thoughts:z$1.string(),id:z$1.number(),updatedMemory:kS.optional(),inWebview:z$1.boolean().optional(),requirements:Y1.optional(),additionalElements:PTe.optional()});var OTe=z$1.literal("SCROLL_TO"),J1=z$1.object({description:z$1.string(),screenXml:z$1.string(),screenshot:z$1.string(),source:OTe.optional(),memory:z$1.discriminatedUnion("type",[Ja,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional()}),X1=z$1.object({assertion:z$1.string(),screenXml:z$1.string(),screenshot:z$1.string(),contextChoice:lm.optional(),memory:z$1.discriminatedUnion("type",[im,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:DS.optional()});var Q1=z$1.object({failedResults:K1.array(),nextStepsSerialized:z$1.string().array(),currentScreenXml:z$1.string(),currentScreenshot:z$1.string(),customInstructions:z$1.string().optional(),testDescription:z$1.string()}),Z1=(o=>(o.LEGITIMATE="LEGITIMATE",o.RECOVERABLE="RECOVERABLE",o.INELIGIBLE="INELIGIBLE",o))(Z1||{});z$1.object({thoughts:z$1.string(),scenario:z$1.enum(Z1),instructions:z$1.string().nullish(),reasonSummary:z$1.string().nullish()});z$1.looseObject({type:z$1.literal("response.create")});var eq=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 tq="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 $g=(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))($g||{}),Hi=(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))(Hi||{}),MTe=3;function NTe(e){return e==="MODULE"||e==="CONDITIONAL"||e==="WHILE_LOOP"||e==="SECTION"||e==="RESOLVED_MODULE"}function nq(e){if(!NTe(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 oq(e){switch(e.type){case "AI_EXTRACT":case "AI_ASSERTION":return MTe;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 nL=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 qC(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=nL.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 DTe=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()}),FTe=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()}),KC=z$1.object({cookies:nL.array().optional(),origins:DTe.array().optional(),idb:z$1.record(z$1.string(),FTe).optional().describe("key is db name")});function rq(e,t){let n=[];return e.cloneSync()?.serializeSync()?.cookies.forEach(o=>{let r=nL.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 us={type:true,cache:true},iq=[fd.pick(us),Tm.pick(us),Vb.pick(us),qb.pick(us),Gb.pick(us),Hb.pick(us),Fb.pick(us)],oL=P__default.discriminatedUnion("type",iq),sq=[fd.pick(us),Am.pick(us),zb.pick(us),Kb.pick(us),$b.pick(us),Bb.pick(us),jb.pick(us)],rL=P__default.discriminatedUnion("type",sq);Object.values(Jt).filter(e=>iq.some(t=>t.shape.type.safeParse(e).success));Object.values(Jt).filter(e=>sq.some(t=>t.shape.type.safeParse(e).success));var iL=P__default.object({type:P__default.literal("MOBILE_AI_ACTION_STEP"),cache:qN}),YC=P__default.union([oL,iL]),JC=P__default.union([rL,iL]);var sL=(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))(sL||{}),aL=(o=>(o.US="us",o.EU="eu",o.AS="as",o))(aL||{}),aq=(t=>(t.LOCAL="local",t))(aq||{}),lL=P__default.nativeEnum(sL).or(P__default.nativeEnum(aL)),cL=P__default.nativeEnum(sL).or(P__default.nativeEnum(aL)).or(P__default.nativeEnum(aq)),UTe="closest";cL.or(P__default.literal(UTe));var zg=(n=>(n.ANDROID_14="14",n.ANDROID_15="15",n))(zg||{});var XC=(t=>(t.IOS_26="26",t))(XC||{});var HTe=["1.56.1-lim.1","1.60.0-lim.1"],lq=P__default.enum(HTe);var cq=P__default.nativeEnum(zg).or(P__default.nativeEnum(XC));var jTe=P__default.object({disableMomenticAccessibilityTree:P__default.boolean().optional(),autoGrantPermissions:P__default.boolean().optional().describe("Automatically grant app permission prompts during the run. Android only."),autoAcceptAlerts:P__default.boolean().optional().describe("Automatically accept native alert dialogs. iOS only."),autoDismissAlerts:P__default.boolean().optional().describe("Automatically dismiss native alert dialogs. iOS only."),disableXmlSnapshots:P__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:Pg.optional(),locale:P__default.string().optional().describe("Device locale code (e.g. 'fr', 'en-us'). Sets the device language and region. iOS and Android.")}),GTe="avdId",$Te="iosDeviceType",VTe="iosVersion",dL=jTe.extend({region:cL.optional().describe('Where the emulator runs: "local" for an emulator on your machine, or a region for hosted emulators. Defaults to hosted emulators.'),remoteEmulatorSettings:P__default.object({androidVersion:P__default.nativeEnum(zg).optional()}).optional(),localEmulatorSettings:P__default.object({[GTe]:xg,[$Te]:xg,[VTe]:xg}).optional(),geolocation:P__default.object({latitude:P__default.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:P__default.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),waitForStability:P__default.boolean().optional().describe("wait for stability before every targeting action")});var Zb=P__default.object({retries:P__default.number().optional().describe("number of retries to run"),defaultChannel:P__default.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:P__default.string().optional().describe("Default app artifact tag to use. If not set, the latest available tag is used."),defaultEnv:P__default.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:xg.describe("APK to install when using the emulator in the local region."),defaultAppFilePath:xg.describe("App file (e.g. .app or .ipa) to install when using the emulator in the local region."),emulator:dL.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:TN.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),dq=P__default.object({id:co,description:P__default.string(),schemaVersion:P__default.string(),settings:Zb.optional(),disabled:P__default.boolean().optional(),labels:P__default.array(P__default.string()).optional()}),Wg=dq.extend({platform:P__default.literal("ANDROID").optional().default("ANDROID")}),qg=dq.extend({platform:P__default.literal("IOS")}),uq=P__default.discriminatedUnion("platform",[Wg,qg]),pq=P__default.object({fileType:P__default.literal(Fe.MOBILE_TEST)}),mq=pq.merge(Wg),hq=pq.merge(qg);P__default.discriminatedUnion("platform",[mq,hq]);var gq=Wg.merge(P__default.object({steps:P__default.array(cc)})),fq=qg.merge(P__default.object({steps:P__default.array(yd)}));P__default.discriminatedUnion("platform",[gq,fq]);var zTe=mq.merge(gq),WTe=hq.merge(fq);P__default.discriminatedUnion("platform",[zTe,WTe]);P__default.object({name:P__default.string(),steps:P__default.array(cc).optional(),settings:Zb.optional()});var yq=Wg.extend({steps:cl.array(),beforeSteps:cl.array().optional(),afterSteps:cl.array().optional()}),Sq=qg.extend({steps:dl.array(),beforeSteps:dl.array().optional(),afterSteps:dl.array().optional()});P__default.discriminatedUnion("platform",[yq,Sq]);var qTe=yq.extend({name:P__default.string()}),KTe=Sq.extend({name:P__default.string()});P__default.discriminatedUnion("platform",[qTe,KTe]);var _r=P__default.object({startTime:P__default.number(),endTime:P__default.number().optional(),durationMs:P__default.number().optional(),error:P__default.string().optional(),result:P__default.unknown().optional().optional(),attributes:P__default.record(P__default.string(),P__default.unknown().optional()),subSpans:P__default.lazy(()=>pAe.array())});var uL=_r.extend({type:P__default.literal("SECTION"),name:P__default.string()}),YTe=_r.extend({type:P__default.literal("GET_PAGE_STATE")}),JTe=_r.extend({type:P__default.literal("GET_PAGE_SCREENSHOT")}),XTe=_r.extend({type:P__default.literal("SMART_WAITING")}),QTe=_r.extend({type:P__default.literal("SCROLL_ELEMENT_INTO_VIEW")}),ZTe=_r.extend({type:P__default.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:P__default.string().optional(),result:P__default.object({id:P__default.number(),thoughts:P__default.string(),citations:Uo.array().optional()}).optional()}),eAe=_r.extend({type:P__default.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:P__default.string().optional(),elementScreenshotSnapshotId:P__default.string().optional(),result:P__default.object({thoughts:P__default.string(),result:P__default.boolean(),citations:Uo.array().optional()}).optional()}),tAe=_r.extend({type:P__default.literal("AI_EXTRACTION_CALL"),screenshotSnapshotId:P__default.string().optional(),browserStateSnapshotId:P__default.string().optional(),result:P__default.object({thoughts:P__default.string().optional(),result:P__default.unknown().optional().optional()}).optional()}),nAe=_r.extend({type:P__default.literal("ELEMENT_ASSERTION"),name:P__default.string(),result:P__default.object({success:P__default.boolean(),message:P__default.string().optional()}).optional()}),oAe=_r.extend({type:P__default.literal("BROWSER_INTERACTION"),name:P__default.string(),coordinates:P__default.object({x:P__default.number(),y:P__default.number()}).optional(),value:P__default.string().optional(),selector:P__default.string().optional()}),rAe=_r.extend({type:P__default.literal("CACHE_RESOLUTION"),resolutionMethod:P__default.string().optional(),cacheMissReason:P__default.nativeEnum(Xh).optional(),targetSource:P__default.string().optional(),elementScreenshotSnapshotId:P__default.string().optional(),result:P__default.object({serializedElement:P__default.string()}).optional()}),iAe=_r.extend({type:P__default.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:P__default.string().optional(),result:P__default.object({serializedElement:P__default.string()}).optional()}),sAe=_r.extend({type:P__default.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:P__default.string().optional(),result:P__default.object({outcome:P__default.string(),logs:P__default.string().array().optional(),serializedElement:P__default.string().optional(),relativeClickPoint:P__default.object({x:P__default.number(),y:P__default.number()}).optional(),force:P__default.boolean().optional()}).optional()}),aAe=_r.extend({type:P__default.literal("WAIT_FOR_STABILITY")}),lAe=_r.extend({type:P__default.literal("GENERIC"),name:P__default.string()}),cAe=_r.extend({type:P__default.literal("PAGE_ASSERTION"),name:P__default.string(),result:P__default.object({success:P__default.boolean(),message:P__default.string().optional()}).optional()}),dAe=_r.extend({type:P__default.literal("AUTO_FOLLOW_NEW_TABS"),result:P__default.object({followed:P__default.boolean()}).optional()}),uAe=_r.extend({type:P__default.literal("VISUAL_DIFF"),name:P__default.string(),result:P__default.object({success:P__default.boolean(),message:P__default.string().optional()}).optional()});function bq(e){return e.type==="CACHE_RESOLUTION"||e.type==="TARGET_RESOLUTION"}var pAe=P__default.discriminatedUnion("type",[uL,YTe,JTe,XTe,QTe,ZTe,eAe,tAe,nAe,oAe,iAe,rAe,sAe,aAe,cAe,uAe,lAe,dAe]);z$1.object({testId:z$1.string(),sessionId:z$1.string()});var Tq=z$1.object({uploadUrl:z$1.string(),id:z$1.string()});new Set(Object.values(eo));var Rn={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 mAe=z$1.string().refine(e=>Jd.valid(e),{error:"must be a valid semver string"});function pL(e){return Jd.parse(e)||void 0}function eT(e){if(e!==void 0)return e===true||e==="true"||e==="1"}var Eq="on-fail";function vq(e){return e==="on-fail"?"on-fail":e==="false"?false:!!e}var Cq=(n=>(n.CLI="cli",n.MobileCLI="mobile-cli",n))(Cq||{}),hAe=z$1.nativeEnum(Cq),Rq=(o=>(o.Error="error",o.Warn="warn",o.Info="info",o))(Rq||{}),gAe=z$1.nativeEnum(Rq),fAe=z$1.object({id:z$1.string(),level:gAe,versionRange:z$1.string(),announcement:z$1.string()});z$1.object({cliType:hAe,version:mAe});var wq=z$1.object({announcements:z$1.array(fAe)});var tT=55555,QC="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 yAe=z$1.union([z$1.string(),z$1.date()]).transform(e=>e instanceof Date?e:new Date(e)),Iq=z$1.object({phoneNumber:z$1.string(),expiresAt:yAe,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 xq=z$1.object({email:z$1.string(),prefix:z$1.string(),expiresAt:z$1.coerce.date()}),ZC=(n=>(n.RAW="RAW",n.RESPONSE="RESPONSE",n))(ZC||{}),_q=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()}),SAe=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(),bAe=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(),Pq=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:SAe,response:bAe,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(ZC).optional()});var Hu=9e4;var TAe=P.object({url:P.string(),lineNumber:P.number(),columnNumber:P.number()}),Oq=P.object({timestamp:P.number(),text:P.string(),type:P.string(),tabIndex:P.number(),args:P.unknown().optional().array().optional(),url:P.string().optional(),location:TAe.optional()}),Mq=Oq.array(),mL=Mq.array();var nT=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 AAe=z$1.object({name:z$1.string(),version:z$1.string(),comment:z$1.string().optional()}),EAe=z$1.object({name:z$1.string(),version:z$1.string(),comment:z$1.string().optional()}),vAe=z$1.object({onContentLoad:z$1.number().optional(),onLoad:z$1.number().optional(),comment:z$1.string().optional()}),oT=z$1.object({startedDateTime:z$1.string(),id:z$1.string(),title:z$1.string().optional(),pageTimings:vAe,comment:z$1.string().optional()}),CAe=z$1.array(oT),RAe=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()}),Lq=z$1.array(RAe),wAe=z$1.object({name:z$1.string(),value:z$1.string(),comment:z$1.string().optional()}),kq=z$1.array(wAe),IAe=z$1.object({name:z$1.string(),value:z$1.string(),comment:z$1.string().optional()}),xAe=z$1.array(IAe),_Ae=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()}),PAe=z$1.array(_Ae),OAe=z$1.object({mimeType:z$1.string(),params:PAe,text:z$1.string(),comment:z$1.string().optional(),_redactedReason:z$1.string().optional()}),MAe=z$1.object({method:z$1.string(),url:z$1.string(),httpVersion:z$1.string().optional(),cookies:Lq,headers:kq,queryString:xAe,postData:OAe.optional(),headersSize:z$1.number().optional(),bodySize:z$1.number().optional(),comment:z$1.string().optional()}),NAe=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()}),LAe=z$1.object({status:z$1.number(),statusText:z$1.string(),httpVersion:z$1.string().optional(),cookies:Lq,headers:kq,content:NAe,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()}),Nq=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()}),kAe=z$1.object({beforeRequest:Nq.optional(),afterRequest:Nq.optional(),comment:z$1.string().optional()}),DAe=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()}),rT=z$1.object({pageref:z$1.string().optional(),startedDateTime:z$1.string(),time:z$1.number().optional(),request:MAe,response:LAe.optional(),cache:kAe.optional(),timings:DAe,serverIPAddress:z$1.string().optional(),connection:z$1.string().optional(),comment:z$1.string().optional(),_resourceType:z$1.string().optional()}),FAe=z$1.array(rT),BAe=z$1.object({version:z$1.string().default("1.1"),creator:AAe.optional(),browser:EAe.optional(),pages:CAe.optional(),entries:FAe,comment:z$1.string().optional()});z$1.object({log:BAe});z$1.record(z$1.string(),oT);z$1.record(z$1.string(),rT);function hL(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 gL=(A=>(A.DisableClickhouseCaches="disable_clickhouse_caches",A.ShowZeroOpacityElements="show_zero_opacity_elements",A.VisualActions="visual_actions",A.RagV2="rag_v2",A.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",A.GlobalLocatorRedirect="global_locator_redirect",A.FakerConstantSeed="faker_constant_seed",A.AutoExpandIframes="auto_expand_iframes",A.MobileNewAiActionStepsUseV3="mobile_new_ai_action_steps_use_v3",A.PerformanceInsights="performance_insights",A.ShowKnowledgeBase="show_knowledge_base",A.AppGraphBackend="app_graph_backend",A.AppGraphUI="app_graph_ui",A.ClassificationUI="classification_ui",A.HealingUI="healing_ui",A.ExploreUI="explore_ui",A.SlackNotifications="slack_notifications",A.SlackNotificationDms="slack_notification_dms",A.ResultClassificationCache="result_classification_cache",A.HealTraceUI="heal_trace_ui",A))(gL||{});var ju=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null(),z$1.record(z$1.string(),z$1.lazy(()=>ju)),z$1.array(z$1.lazy(()=>ju))]),iT=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(gL).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 sT={".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"},Dq=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var Fq=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)})]),jAe=z$1.object({githubLogin:z$1.string().optional(),email:z$1.string().optional()}),GAe=z$1.object({baseSha:z$1.string().min(1),headSha:z$1.string().min(1)}),$Ae=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()}),VAe=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()});$Ae.extend(VAe.shape).extend({changes:z$1.array(Fq).min(1),coAuthorRange:GAe.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 Bq=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(jAe).optional()});z$1.object({branch:z$1.string().min(1).max(255),commitMessage:z$1.string().min(1),changes:z$1.array(Fq).min(1)});var Uq=z$1.object({branch:z$1.string(),commitSha:z$1.string(),committed:z$1.boolean()}),Hq=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 zAe=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()}),WAe=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()}),jq=z$1.object({mergeBaseSha:z$1.string().min(1),totalCommits:z$1.number(),commits:z$1.array(WAe),files:z$1.array(zAe)}),Gq=z$1.object({content:z$1.string().nullable()}),$q=z$1.object({name:z$1.string().min(1),protected:z$1.boolean()}),Vq=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)}),qAe=z$1.object({name:z$1.string(),path:z$1.string(),body:z$1.string()}),zq=z$1.object({template:qAe});function gr(e){let[t,n,...o]=e.split("/");if(!(!t||!n||o.length>0))return {owner:t,repo:n}}function Wq(e){let t=gr(e);if(t)return t;throw new vt(`Invalid GitHub repository string: ${e}. Expected format "owner/repo".`)}var KAe=/^co-authored-by:\s*.*?<([^>]+)>\s*$/gim,YAe=/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i;function eR(e){return e.match(YAe)?.[1]}function qq(e){let t=[];for(let n of e.matchAll(KAe)){let o=n[1]?.trim();o&&t.push({email:o,githubLogin:eR(o)});}return t}function JAe(e){return (e.githubLogin??(e.email?eR(e.email):void 0))?.toLowerCase().endsWith("[bot]")??false}function Kq(e){return e.filter(t=>!JAe(t))}var Yq="https://static.momentic.ai";function aT(e,t){return {light:`${Yq}/${e}.svg`,dark:`${Yq}/${e}-dark.svg`,alt:t}}var lT={runGroup:aT("run-group-button","View run group"),basePr:aT("view-base-pr-button","View base PR"),branch:aT("view-branch-button","View branch"),commit:aT("view-commit-button","View commit")};function cT({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 Gu=z$1.object({limit:z$1.number().min(1).max(100).optional(),page:z$1.number().min(1).optional()}),fL=z$1.object({page:z$1.number(),pageSize:z$1.number(),pageCount:z$1.number()});var yL=P__default.object({platformSep:P__default.string(),fullPathSegments:P__default.string().array(),relativePathSegments:P__default.string().array(),relativePath:P__default.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:P__default.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:P__default.coerce.date(),createdAt:P__default.coerce.date()});var XAe=z$1.array(yL.extend({id:z$1.string(),name:z$1.string(),description:z$1.string().optional(),labels:z$1.string().array().optional()})),QAe=yL.extend({id:z$1.string(),name:z$1.string(),description:z$1.string().optional(),content:Bv}),ZAe=z$1.array(QAe);z$1.object({tests:XAe,modules:ZAe,labels:z$1.string().array()});z$1.string().array();var Jq=z$1.object({pathSegments:z$1.string().array()});RN.merge(lo);var Xq=z$1.object({schemaVersion:z$1.string(),stepLists:Ls}),Qq=lo.partial().merge(li.pick({id:true})),wm="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",SL={name:z$1.string().min(1).max(255).describe(wm),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(nl).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:dd.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.")},Zq=z$1.object(SL);RN.extend(z$1.object({relativeFilePath:z$1.string().describe("relative to project root")}).shape);var e2=z$1.object({name:z$1.string()});z$1.object({relativeFilePath:z$1.string()});var t2=z$1.object({name:z$1.string(),sourceModuleContent:Bv});z$1.object({relativeFilePath:z$1.string()});var n2=z$1.object({name:z$1.string(),description:z$1.string(),enabled:z$1.boolean(),steps:z$1.lazy(()=>Ht.array()),testFilePath:z$1.string().describe("relative to the project root"),folderPath:z$1.string().optional().describe("user selected folder path")}),o2=z$1.object({name:z$1.string(),description:z$1.string(),enabled:z$1.boolean()}).partial(),r2=z$1.object({folderPath:z$1.string()}),i2=z$1.object({folderPath:z$1.string()});z$1.array(fb);var s2=z$1.object({defaultEnv:z$1.string().optional().describe("name of the default env, or undefined to unset")}),a2=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 bL=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()}),l2=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(bL)});var c2=z$1.object({sourceDirectoryPath:z$1.string().optional(),value:z$1.string(),allowedExtensions:z$1.array(z$1.string()).optional()}),eEe=z$1.object({name:z$1.string(),value:z$1.string(),isDirectory:z$1.boolean()});z$1.object({suggestions:z$1.array(eEe)});var d2=z$1.object({pathSegments:z$1.array(z$1.string())}),u2=z$1.object({pathSegments:z$1.array(z$1.string()),newPathSegments:z$1.array(z$1.string())}),p2=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 m2=typeof process<"u"&&true&&true,tR=58889,Yg=24*60*60*1e3;var h2=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:MM.nullish()});h2.extend({steps:z$1.lazy(()=>Ut.array())});var g2=5*60*1e3,dT=so.extend(h2.omit({id:true,createdAt:true,createdBy:true,organizationId:true,enabled:true}).shape);var tEe="org_01HMJTX4GT1KG94KZRCT8MZ6YB",nEe="org_01HMSCJQBCCG51M2ZF65YC5B8W",oEe="org_01JPR6MGFQSHF3W234R3XJDPMB",rEe=[tEe,nEe,oEe];function f2(e){return rEe.includes(e)}var y2=(o=>(o.AZURE="AZURE",o.KERNEL="KERNEL",o.BROWSERBASE="BROWSERBASE",o))(y2||{}),TL=z$1.enum(y2);z$1.object({azureRegion:z$1.string().optional(),azureWorkspaceId:z$1.string().optional()});z$1.object({});var iEe=z$1.enum(["us-west-2","us-east-1","eu-central-1","ap-southeast-1"]);z$1.object({region:iEe.optional()});var AL=(t=>(t.TEST_REVIEW="TEST_REVIEW",t))(AL||{});var sEe=z$1.object({type:z$1.literal("DESCRIPTION_UPDATE"),thoughts:z$1.string()}),nR=z$1.discriminatedUnion("type",[sEe]),aEe=z$1.object({testId:z$1.string(),name:z$1.string(),orgId:z$1.string(),runId:z$1.string(),steps:Ht.array(),purpose:z$1.enum(AL),details:nR.or(nR.array()).optional()});aEe.pick({name:true,orgId:true});var lEe=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(AL),details:nR.or(nR.array()).optional(),applied:z$1.boolean().nullish(),appliedAt:z$1.coerce.date().nullish()}),S2=lEe.extend({steps:Ht.array()});var b2=z$1.enum(["v1","v2"]);var dEe=z$1.enum(["element","content","attribute","tag_name","style"]),oR=z$1.enum(["exists","visible","enabled","editable","focused","contains","equals","starts_with"]);[...Y$,...K$].forEach(e=>{if(!oR.options.includes(e.toLowerCase()))throw new Error(`V2CheckConditionSchema is missing option: ${e}`)});var EL={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}},E2={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"}},v2={ELEMENT_EXISTENCE:"element",ELEMENT_CONTENT:"content",ELEMENT_ATTRIBUTE:"attribute",ELEMENT_NAME:"tag_name",ELEMENT_STYLE:"style"};function T2(e){return {alias:vL(e),subject:e.subject,condition:e.condition,negated:e.negated,assertionType:EL[e.subject].assertionType,requiresName:EL[e.subject].requiresName,requiresValue:e.subject!=="element"&&e.condition!=="exists"}}function vL(e){let t=EL[e.subject],n=E2[e.condition];if(!C2(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 C2(e,t){let n=E2[t],o=n.elementCondition,r=n.contentOperation;return e==="element"?o!==void 0:r!==void 0}var uEe=dEe.options.flatMap(e=>oR.options.flatMap(t=>C2(e,t)?[T2({subject:e,condition:t,negated:false}),T2({subject:e,condition:t,negated:true})]:[])),R2=new Map(uEe.map(e=>[e.alias,e]));var pEe=z$1.enum(ql),mEe=z$1.enum(Ps);function Gi(e){return R2.get(e)}function I2(e){let t=v2[e.type],n=e.type==="ELEMENT_EXISTENCE"?e.condition:e.operation;return vL({subject:t,condition:hEe(n),negated:e.negated})}function x2(e){return pEe.parse(e.toUpperCase())}function uT(e){return mEe.parse(e.toUpperCase())}function hEe(e){return oR.parse(e.toLowerCase())}var rt={saveAs:z$1.string().optional(),retries:z$1.number().optional(),skipped:z$1.boolean().optional(),comment:z$1.string().optional()};z$1.object(rt);var pT=Object.keys(rt);function Ye(e){return z$1.union([z$1.strictObject({[e.key]:e.simplified}),z$1.strictObject({[e.key]:e.detailed})])}function oo(e){return z$1.strictObject({[e.key]:e.detailed})}var _2='Coordinates must be "x, y" pixel values, e.g. "100, 200"',Jg=z$1.union([Vl,z$1.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,_2)],{error:_2});z$1.union([z$1.string(),Vl]);var zs={css:z$1.string().optional(),coords:Jg.optional(),x:z$1.union([z$1.number(),z$1.string()]).optional(),y:z$1.union([z$1.number(),z$1.string()]).optional()},RL={on:z$1.string().optional(),...zs},Ws={...rt,useSelector:z$1.boolean().optional(),force:z$1.boolean().optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional()},mT={...Ws,offset:Jg.optional()};function $i({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 gEe=$i({descriptionKey:"on",schema:z$1.strictObject({...RL,...mT,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()})}),fEe=$i({descriptionKey:"on",schema:z$1.strictObject({...RL,...mT,rightClick:z$1.boolean().optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),yEe=$i({descriptionKey:"on",schema:z$1.strictObject({...RL,...mT,times:z$1.int().min(1).optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),P2=Ye({key:"click",simplified:z$1.string(),detailed:gEe}),O2=Ye({key:"doubleClick",simplified:z$1.string(),detailed:fEe}),M2=Ye({key:"rightClick",simplified:z$1.string(),detailed:yEe}),SEe=$i({descriptionKey:"into",required:false,schema:z$1.strictObject({text:z$1.string(),into:z$1.string().optional(),...zs,...mT,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()})}),N2=Ye({key:"type",simplified:z$1.string(),detailed:SEe}),L2=oo({key:"select",detailed:$i({descriptionKey:"from",schema:z$1.strictObject({from:z$1.string().optional(),...zs,label:z$1.string().optional(),value:z$1.string().optional(),index:z$1.union([z$1.string(),z$1.number()]).optional(),...Ws})}).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"});})}),k2=Ye({key:"hover",simplified:z$1.string(),detailed:$i({descriptionKey:"on",schema:z$1.strictObject({on:z$1.string().optional(),...zs,...mT})})}),D2=oo({key:"blur",detailed:$i({descriptionKey:"on",required:false,schema:z$1.strictObject({on:z$1.string().optional(),...zs,...Ws})})}),F2=Ye({key:"focus",simplified:z$1.string(),detailed:$i({descriptionKey:"on",schema:z$1.strictObject({on:z$1.string().optional(),...zs,...Ws})})}),B2=oo({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:Jg.optional(),toCoords:Jg.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(),...Ws}).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."});})}),U2=z$1.union([z$1.strictObject({mouseDrag:Jg}),z$1.strictObject({mouseDrag:$i({descriptionKey:"from",required:false,schema:z$1.strictObject({from:z$1.string().optional(),...zs,delta:Jg,steps:z$1.number().optional(),...Ws})})})]),H2=Ye({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(),...rt})}),j2=Ye({key:"keyDown",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),convertMeta:z$1.boolean().optional(),...rt})}),G2=Ye({key:"keyUp",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),convertMeta:z$1.boolean().optional(),...rt})}),hT=z$1.number().int().min(0).max(6e4).multipleOf(1e3),$2=Ye({key:"navigate",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),timeout:hT.optional(),...rt})}),V2=Ye({key:"newTab",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),timeout:hT.optional(),...rt})}),z2=Ye({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:hT.optional(),...rt}).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"});})}),W2=oo({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:hT.optional(),...rt}).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"});})}),q2=oo({key:"goBack",detailed:z$1.strictObject(rt)}),K2=oo({key:"goForward",detailed:z$1.strictObject(rt)}),Y2=oo({key:"refresh",detailed:z$1.strictObject({timeout:hT.optional(),...rt})}),rR=z$1.enum(["goBack","goForward","refresh","paste","authSave","offline","online","blur","visualDiff","captcha","closeTab"]),J2=Ye({key:"scrollUp",simplified:z$1.number().nonnegative(),detailed:$i({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...zs,...Ws})})}),X2=Ye({key:"scrollDown",simplified:z$1.number().nonnegative(),detailed:$i({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...zs,...Ws})})}),Q2=Ye({key:"scrollLeft",simplified:z$1.number().nonnegative(),detailed:$i({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...zs,...Ws})})}),Z2=Ye({key:"scrollRight",simplified:z$1.number().nonnegative(),detailed:$i({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...zs,...Ws})})}),eK=Ye({key:"wait",simplified:z$1.number(),detailed:z$1.strictObject({ms:z$1.number(),...rt})}),bEe=Ye({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(),...rt})}),TEe=Ye({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(),...rt})}),iR=bEe,sR=TEe,tK=Ye({key:"checkPageContains",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),iframe:z$1.string().optional(),...rt})}),nK=Ye({key:"checkPageDoesNotContain",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),iframe:z$1.string().optional(),...rt})}),wL=z$1.union([tK,nK]),AEe=z$1.record(z$1.string(),z$1.unknown().optional()),aR=AEe.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=Gi(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=$i({descriptionKey:"element",schema:z$1.looseObject({element:z$1.string().optional(),...zs,...Ws,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"]});}),oK=Ye({key:"extract",simplified:z$1.string(),detailed:z$1.strictObject({goal:z$1.string(),schema:ju.optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional(),...rt})}),rK=Ye({key:"cookie",simplified:z$1.string(),detailed:z$1.strictObject({value:z$1.string(),...rt})}),iK=oo({key:"localStorage",detailed:z$1.strictObject({key:z$1.string(),value:z$1.string(),...rt})}),sK=Ye({key:"request",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),method:td.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),params:z$1.record(z$1.string(),z$1.string()).optional(),body:ju.optional(),contentType:z$1.enum(Kl).optional(),timeout:z$1.number().optional(),...rt})}),aK=oo({key:"graphqlRequest",detailed:z$1.strictObject({url:z$1.string(),query:z$1.string(),variables:ju.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),timeout:z$1.number().optional(),...rt})}),lR=Ye({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(),...rt})}),Xg={substring:z$1.string().optional(),glob:z$1.string().optional(),regex:z$1.string().optional(),domain:z$1.string().optional()};function EEe(e){return [e.substring,e.glob,e.regex,e.domain].filter(t=>t!==void 0).length}function Qg(e){let t=EEe(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 lK=oo({key:"header",detailed:z$1.strictObject({name:z$1.string(),value:z$1.string(),...Xg,method:z$1.string().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:false});})}),cK=oo({key:"mock",detailed:z$1.strictObject({...Xg,method:z$1.string().optional(),responseGenerator:z$1.string(),fetchOriginalResponse:z$1.boolean().optional(),key:z$1.string().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),dK=Ye({key:"removeRouteMock",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string().optional(),...rt})}),uK=Ye({key:"waitForUrl",simplified:z$1.string(),detailed:z$1.strictObject({...Xg,caseInsensitive:z$1.boolean().optional(),timeout:z$1.number().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),pK=Ye({key:"waitForUrlNotToMatch",simplified:z$1.string(),detailed:z$1.strictObject({...Xg,caseInsensitive:z$1.boolean().optional(),timeout:z$1.number().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),vEe=z$1.union([uK,pK]),mK=Ye({key:"dialog",simplified:z$1.enum(["ACCEPT","DISMISS"]),detailed:z$1.strictObject({action:z$1.enum(["ACCEPT","DISMISS"]),...rt})}),hK=Ye({key:"fileUpload",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),name:z$1.string().optional(),...rt})}),gK=Ye({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()]),...rt})}),fK=oo({key:"paste",detailed:z$1.strictObject(rt)}),yK=oo({key:"captcha",detailed:z$1.strictObject({...Ws})}),CEe=z$1.strictObject({data:z$1.union([z$1.string(),Ya]),width:z$1.number(),height:z$1.number()}),SK=Ye({key:"visualDiff",simplified:z$1.string(),detailed:$i({descriptionKey:"on",required:false,schema:z$1.strictObject({on:z$1.string().optional(),...zs,threshold:z$1.number().optional(),screenshot:CEe.optional(),...Ws})})}),bK=oo({key:"offline",detailed:z$1.strictObject(rt)}),TK=oo({key:"online",detailed:z$1.strictObject(rt)}),AK=oo({key:"registerRequestListener",detailed:z$1.strictObject({...Xg,key:z$1.string(),method:z$1.string().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),EK=Ye({key:"awaitListener",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),timeout:z$1.number().optional(),...rt})}),vK=oo({key:"recordRequests",detailed:z$1.strictObject({...Xg,key:z$1.string(),method:z$1.string().optional(),...rt}).superRefine((e,t)=>{Qg({payload:e,ctx:t,required:true});})}),CK=Ye({key:"getRecordedRequests",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),...rt})}),RK=Ye({key:"authLoad",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),...rt})}),wK=Ye({key:"authSave",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string().optional(),...rt})});z$1.union([P2,O2,M2,z2,W2,N2,L2,k2,D2,F2,B2,U2,H2,j2,G2,$2,V2,q2,K2,Y2,J2,X2,Q2,Z2,eK,iR,sR,wL,oK,rK,iK,sK,aK,lR,lK,cK,dK,vEe,mK,hK,gK,fK,yK,SK,bK,TK,AK,EK,vK,CK,RK,wK,aR]);var IK=new Map([["click",P2],["doubleClick",O2],["rightClick",M2],["switchTab",z2],["closeTab",W2],["type",N2],["select",L2],["hover",k2],["blur",D2],["focus",F2],["dragAndDrop",B2],["mouseDrag",U2],["press",H2],["keyDown",j2],["keyUp",G2],["navigate",$2],["newTab",V2],["goBack",q2],["goForward",K2],["refresh",Y2],["scrollUp",J2],["scrollDown",X2],["scrollLeft",Q2],["scrollRight",Z2],["wait",eK],["assert",iR],["assertVisually",sR],["checkPageContains",tK],["checkPageDoesNotContain",nK],["extract",oK],["cookie",rK],["localStorage",iK],["request",sK],["graphqlRequest",aK],["javascript",lR],["header",lK],["mock",cK],["removeRouteMock",dK],["waitForUrl",uK],["waitForUrlNotToMatch",pK],["dialog",mK],["fileUpload",hK],["copy",gK],["paste",fK],["captcha",yK],["visualDiff",SK],["offline",bK],["online",TK],["registerRequestListener",AK],["awaitListener",EK],["recordRequests",vK],["getRecordedRequests",CK],["authLoad",RK],["authSave",wK]]),xK=Object.freeze([...IK.keys()]),mc=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=IK.get(o)??(Gi(o)?aR:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported step type '${o}'.`});return}let i=r.safeParse(e);if(!i.success){let s=REe(i.error.issues,o);s.length>0&&_K(t,s);}});function REe(e,t){return wEe(e).filter(n=>!IEe(n,t))}function _K(e,t){for(let n of t){if(n.code==="invalid_union"){_K(e,IL(n));continue}e.addIssue({...n});}}function wEe(e){let t=[];for(let n of e){if(n.code==="invalid_union"){t.push(...IL(n));continue}t.push(n);}return t}function IEe(e,t){return e.code!=="unrecognized_keys"?false:t===void 0?e.path.length===0:e.path.length===1&&e.path[0]===t}function IL(e){let t=e.errors[0]??[],n=CL(t);for(let o of e.errors.slice(1)){let r=CL(o);r>n&&(t=o,n=r);}return t}function CL(e){return e.reduce((t,n)=>{let o=n.code==="invalid_union"?CL(IL(n)):0;return t+n.path.length+o},0)}var PK=z$1.strictObject({string:z$1.string()}),xEe=z$1.strictObject({javascript:z$1.string()}),OK=z$1.union([PK,xEe]),_Ee=z$1.union([z$1.strictObject({name:z$1.string(),required:z$1.boolean().optional(),default:PK.optional()}),z$1.strictObject({name:z$1.string(),required:z$1.boolean().optional(),defaultValue:z$1.string()})]),MK=_Ee.array(),PEe=z$1.strictObject({name:z$1.string(),default:OK.optional(),enum:z$1.array(z$1.string()).optional()}),NK=PEe.array(),gT=z$1.union([OK,z$1.string()]),LK=z$1.record(z$1.string(),gT);var OEe=z$1.preprocess(e=>typeof e=="number"?String(e):e,IM),cR=z$1.looseObject({goal:z$1.string(),version:OEe.optional(),...rt}),MEe=z$1.union([z$1.strictObject({act:z$1.string()}),z$1.strictObject({act:cR})]),xL=z$1.looseObject({path:z$1.string(),inputs:z$1.record(z$1.string(),gT).optional(),...rt}),NEe=z$1.union([z$1.strictObject({module:z$1.string()}),z$1.strictObject({module:xL})]),Ad=z$1.union([iR,sR,wL,lR,aR]),LEe=new Set(["then",...pT]),kEe=z$1.looseObject({then:z$1.lazy(()=>ul.array()),...rt}).superRefine((e,t)=>{Object.entries(e).filter(([o,r])=>!LEe.has(o)&&Ad.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"Conditional steps require exactly one assertion condition at the top level."});}),DEe=z$1.strictObject({if:kEe}),FEe=new Set(["do","maxIterations",...pT]),BEe=z$1.looseObject({do:z$1.lazy(()=>ul.array()),maxIterations:z$1.number().int().positive().optional(),...rt}).superRefine((e,t)=>{let n=Object.entries(e).filter(([o,r])=>!FEe.has(o)&&Ad.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."});}),UEe=z$1.strictObject({while:BEe}),ul=z$1.lazy(()=>z$1.union([rR,MEe,NEe,DEe,UEe,mc]));z$1.object({before:ul.array().optional(),steps:ul.array(),after:ul.array().optional()});var HEe=z$1.union([dd,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 dd.safeParse({width:Number(n),height:Number(o)}).success},"Viewport must be two numeric values, e.g. 1920, 1080")]),jEe=Bi.omit({viewport:true}).extend({viewport:HEe.optional()}),_L=z$1.object({id:co,version:z$1.string().optional(),url:Wv.optional(),description:z$1.string().optional(),retries:z$1.number().optional(),defaultEnv:z$1.string().optional(),parameters:MK.optional(),outputs:CC.optional(),disabled:z$1.boolean().optional(),labels:z$1.array(z$1.string()).optional()}).extend(jEe.shape),Vu=z$1.looseObject({fileType:z$1.literal(Fe.TEST_V2)}).extend(_L.shape).extend({before:ul.array().optional(),steps:ul.array(),after:ul.array().optional()});var GEe=z$1.array(z$1.string()),$Ee=z$1.union([z$1.string(),z$1.record(z$1.string(),z$1.unknown().optional())]),dR=so.omit({moduleId:true,name:true,parameters:true,defaultParameters:true,parameterEnums:true}).extend({id:co,version:z$1.string().optional(),name:z$1.string().optional(),parameters:z$1.union([NK,GEe]).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()}),uR=z$1.looseObject(dR.extend({fileType:z$1.literal(Fe.MODULE_V2),steps:$Ee.array().optional()}).shape).superRefine(DK),pR=z$1.looseObject(dR.extend({fileType:z$1.literal(Fe.MODULE_V2),steps:ul.array().optional()}).shape).superRefine(DK);function kK(e){return e.steps??[]}function DK(e,t){"main"in e&&t.addIssue({code:"custom",message:"v2 modules must use steps, not main",path:["main"]});}var PL=(n=>(n.TEST="TEST",n.MODULE="MODULE",n))(PL||{}),VEe=z$1.enum(PL),FK=z$1.object({orgId:z$1.string(),entityType:VEe,entityId:z$1.string()}),OL=FK.extend({entityType:z$1.literal("TEST"),stepLists:Xa}),ML=FK.extend({entityType:z$1.literal("MODULE"),steps:Ut.array()});z$1.discriminatedUnion("entityType",[OL,ML]);var BK=(o=>(o.WEB="web",o.ANDROID="android",o.IOS="ios",o))(BK||{}),NL=z$1.nativeEnum(BK);var UK=z$1.object({entity_type:z$1.string(),value:z$1.string(),schema_version:z$1.string().optional()}),HK=Tb(UK),jK=UK.extend({cache_key:z$1.string()});function fT({entityType:e,entityId:t}){return `${e}:${t}`}var _m=z$1.string();var GK='Coordinates must be "x, y" pixel values, e.g. "100, 200"',WK=z$1.union([Vl,z$1.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,GK)],{error:GK}),$K='Percent must be a number or a percent string, e.g. 90 or "90%"',qK=z$1.union([z$1.number(),z$1.string().regex(/^-?\d+(?:\.\d+)?%$/,$K)],{error:$K}).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"})),zEe=z$1.strictObject({x:z$1.number(),y:z$1.number(),delta:z$1.number()}),KK=z$1.union([z$1.string(),zEe]),Hn={...rt,DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional()},WEe=["home","power","back","app_switcher","search","volume_up","volume_down","volume_mute"],qEe=["enter","backspace","close_keyboard"],VK=["airplane_mode","data","wifi","location"],zK=["portrait","landscape"],KEe=z$1.strictObject({on:_m.optional(),longPress:z$1.boolean().optional(),longPressDuration:z$1.number().optional(),iterations:z$1.number().optional(),tapDelay:z$1.number().optional(),offset:WK.optional(),...Hn}),YK=Ye({key:"tap",simplified:_m,detailed:KEe}),YEe=z$1.strictObject({text:z$1.string(),into:_m.optional(),clearContent:z$1.boolean().optional(),forceClearContent:z$1.boolean().optional(),delay:z$1.number().optional(),replaceStrategy:z$1.nativeEnum(Wb).optional(),keyPressDelay:z$1.number().optional(),...Hn}),JK=Ye({key:"type",simplified:z$1.string(),detailed:YEe}),XK=z$1.enum(WEe),JEe=z$1.strictObject({key:XK,longPress:z$1.boolean().optional(),...Hn}),QK=Ye({key:"press",simplified:XK,detailed:JEe}),ZK=z$1.enum(qEe),XEe=z$1.strictObject({key:ZK,repeat:z$1.number().optional(),delay:z$1.number().optional(),keyPressDelay:z$1.number().optional(),...Hn}),eY=Ye({key:"pressKey",simplified:ZK,detailed:XEe}),QEe=z$1.strictObject({package:z$1.string(),activity:z$1.string().optional(),intentExtras:z$1.string().optional(),...Hn}),tY=Ye({key:"openApp",simplified:z$1.string(),detailed:QEe}),nY=oo({key:"killApp",detailed:z$1.strictObject(Hn)}),oY=oo({key:"openNotifications",detailed:z$1.strictObject(Hn)}),rY=z$1.enum(["up","down","left","right"]),ZEe=z$1.strictObject({direction:rY,in:KK.optional(),viewportPercent:qK.optional(),duration:z$1.number().optional(),offset:WK.optional(),...Hn}),iY=Ye({key:"swipe",simplified:rY,detailed:ZEe}),eve=z$1.enum(["up","down"]),tve=z$1.strictObject({on:_m,direction:eve.optional(),in:KK.optional(),scrollStepPercent:qK.optional(),maxScrollAttempts:z$1.number().optional(),...Hn}),sY=Ye({key:"scrollTo",simplified:z$1.string(),detailed:tve}),LL=Ye({key:"assert",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),...Hn})}),kL=Ye({key:"assertVisually",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),...Hn})}),aY=Ye({key:"extract",simplified:z$1.string(),detailed:z$1.strictObject({goal:z$1.string(),schema:ju.optional(),...Hn})}),lY=Ye({key:"checkScreenContains",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),...Hn})}),cY=Ye({key:"checkScreenDoesNotContain",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),...Hn})}),dY=z$1.union([lY,cY]),nve=z$1.record(z$1.string(),z$1.unknown().optional()),DL=nve.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=Gi(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:_m.optional(),timeout:z$1.number().optional(),name:z$1.string().optional(),value:z$1.string().optional(),...Hn}).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"]});}),ove=z$1.strictObject({from:_m,to:_m,hoverDuration:z$1.number().optional(),dragDuration:z$1.number().optional(),...Hn}),uY=oo({key:"dragAndDrop",detailed:ove}),FL=Ye({key:"javascript",simplified:z$1.string(),detailed:z$1.strictObject({code:z$1.string(),timeout:z$1.number().optional(),...Hn})}),pY=Ye({key:"request",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),method:td.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(Kl).optional(),timeout:z$1.number().optional(),...Hn})}),mY=Ye({key:"wait",simplified:z$1.number(),detailed:z$1.strictObject({ms:z$1.number(),...Hn})}),hY=Ye({key:"visualDiff",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),threshold:z$1.number().min(0).max(1).optional(),...Hn})}),gY=oo({key:"addFile",detailed:z$1.strictObject({path:z$1.string(),location:z$1.string(),...Hn})}),fY=Ye({key:"installApp",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),...Hn})}),yY=Ye({key:"uninstallApp",simplified:z$1.string(),detailed:z$1.strictObject({package:z$1.string(),...Hn})}),SY=Ye({key:"toggleSettings",simplified:z$1.enum(VK),detailed:z$1.strictObject({setting:z$1.enum(VK),...Hn})}),bY=Ye({key:"rotate",simplified:z$1.enum(zK),detailed:z$1.strictObject({orientation:z$1.enum(zK),...Hn})}),TY=Ye({key:"adb",simplified:z$1.string(),detailed:z$1.strictObject({command:z$1.string(),args:z$1.string().optional(),...Hn})}),AY=oo({key:"appium",detailed:z$1.strictObject({script:z$1.string(),args:z$1.string().optional(),...Hn})}),EY=oo({key:"debugState",detailed:z$1.strictObject(Hn)}),vY=z$1.enum(["killApp","openNotifications","debugState"]);z$1.union([YK,JK,QK,eY,tY,nY,oY,iY,sY,LL,kL,aY,dY,uY,FL,pY,mY,hY,gY,fY,yY,SY,bY,TY,AY,EY,DL]);var CY=new Map([["tap",YK],["type",JK],["press",QK],["pressKey",eY],["openApp",tY],["killApp",nY],["openNotifications",oY],["swipe",iY],["scrollTo",sY],["assert",LL],["assertVisually",kL],["extract",aY],["checkScreenContains",lY],["checkScreenDoesNotContain",cY],["dragAndDrop",uY],["javascript",FL],["request",pY],["wait",mY],["visualDiff",hY],["addFile",gY],["installApp",fY],["uninstallApp",yY],["toggleSettings",SY],["rotate",bY],["adb",TY],["appium",AY],["debugState",EY]]);Object.freeze([...CY.keys()]);var RY=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=CY.get(o)??(Gi(o)?DL: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});}),wY=z$1.union([LL,kL,dY,FL,DL]);var rve=z$1.preprocess(e=>typeof e=="number"?String(e):e,WN),ive=z$1.looseObject({goal:z$1.string(),version:rve.optional(),precondition:z$1.string().optional(),postcondition:z$1.string().optional(),...rt}),sve=z$1.union([z$1.strictObject({act:z$1.string()}),z$1.strictObject({act:ive})]),ave=z$1.looseObject({path:z$1.string(),inputs:z$1.record(z$1.string(),gT).optional(),...rt}),lve=z$1.union([z$1.strictObject({module:z$1.string()}),z$1.strictObject({module:ave})]),cve=new Set(["then",...pT]),dve=z$1.looseObject({then:z$1.lazy(()=>hc.array()),...rt}).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])=>!cve.has(o)&&wY.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"v2 mobile conditional steps require exactly one assertion condition at the top level."});}),uve=z$1.strictObject({if:dve}),hc=z$1.lazy(()=>z$1.union([vY,sve,lve,uve,RY]));z$1.object({before:hc.array().optional(),steps:hc.array(),after:hc.array().optional()});var BL=["android","ios"],pve=z$1.literal("android"),mve=z$1.literal("ios");z$1.enum(BL);function mR(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 IY=Wg.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z$1.string().optional(),platform:pve,...Zb.shape}),xY=qg.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z$1.string().optional(),platform:mve,...Zb.shape}),hve=z$1.discriminatedUnion("platform",[IY,xY]),_Y=z$1.preprocess(mR,hve),PY={before:hc.array().optional(),steps:hc.array(),after:hc.array().optional()},OY=z$1.looseObject({fileType:z$1.literal(Fe.MOBILE_TEST_V2)}).extend(IY.shape).extend(PY);z$1.preprocess(mR,OY);var MY=z$1.looseObject({fileType:z$1.literal(Fe.MOBILE_TEST_V2)}).extend(xY.shape).extend(PY);z$1.preprocess(mR,MY);var gve=z$1.discriminatedUnion("platform",[OY,MY]);z$1.preprocess(mR,gve);var fve=z$1.preprocess(e=>typeof e=="string"?e.toLowerCase():e,z$1.enum(BL).optional().default("android")),hR=WC.omit({moduleId:true,name:true,schemaVersion:true,platform:true}).extend({id:co,name:z$1.string().optional(),version:z$1.string().optional(),platform:fve});z$1.looseObject(hR.extend({fileType:z$1.literal(Fe.MOBILE_MODULE_V2),steps:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).optional()}).shape);z$1.looseObject(hR.extend({fileType:z$1.literal(Fe.MOBILE_MODULE_V2),steps:hc.array().optional()}).shape);var gR="x-momentic-cli-version",LY="x-momentic-client-mode",fR="x-momentic-runner",kY="x-momentic-cli-type",DY="x-momentic-logger-tags",yve="x-momentic-main-branch-name",Sve="x-momentic-branch-name",bve="x-momentic-commit-timestamp",Tve="x-momentic-last-commit-on-main",Ave="x-momentic-last-commit-on-main-timestamp",Eve="x-momentic-merged-branch-name",FY="x-momentic-session-id",BY="x-momentic-parent-trace-id";var UY="x-momentic-browser-vendor-override";P.object({error:P.boolean(),reason:P.string(),message:P.string()});hr.merge(CN);var HY=Lv;hr.merge(CN);hr.merge(FW).extend({useConsensus:P.boolean().optional(),attemptNumber:P.number().optional()});var UL=q$;hr.merge(BW);var jY=Fz;hr.merge(NW);var GY=hC;hr.merge(gz);hr.merge(LW);var $Y=Lz;hr.merge(kW);hr.merge(DW);hr.merge(GW);hr.merge($W);P.object({testPaths:P.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:P.string().optional(),all:P.boolean().optional(),urlOverride:P.string().optional(),customHeaders:P.record(P.string(),P.string()).optional(),testInputMatrix:P.record(P.string(),P.string()).array().optional()});var VY=P.object({queuedTests:P.unknown().optional().array(),runIds:P.guid().array(),runGroupId:P.string().optional()});P.string().array();P.union([P.object({paths:P.string().array().describe("Export specific test paths or folder paths (e.g. todo-test, auth/onboarding)"),all:P.boolean().describe("run all tests").optional()}),P.object({path:P.string().describe("deprecated; present for backcompat")})]);var vve=P.object({tests:P.record(P.string().describe("Test name (keys correspond to entries in `tests`)"),P.string().describe("Slash-separated folder name path that the test lives in (e.g. 'Auth/Login'). Top-level entities are omitted.")),modules:P.record(P.string().describe("Module name (keys correspond to entries in `modules`)"),P.string().describe("Slash-separated folder name path that the module lives in."))}),zY=P.object({tests:P.record(P.string().describe("Test name"),P.string().describe("Test YAML")),modules:P.record(P.string().describe("Module name"),P.string().describe("Module YAML")),folderPaths:vve.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.")}),Cve=P.object({test:P.string().describe("test YAML"),modules:P.record(P.string().describe("moduleId"),P.string().describe("module YAML"))});Cve.array();P.object({testId:P.string(),schemaVersion:P.string()}).merge(rd);function yR(e){let{gitMainBranch:t,gitBranchName:n,gitCommitTimestamp:o,lastCommitOnMainSha:r,lastCommitOnMainTimestamp:i}=e,s={};return t&&(s[yve]=encodeURIComponent(t)),n&&(s[Sve]=encodeURIComponent(n)),o&&(s[bve]=o.toISOString()),r&&(s[Tve]=encodeURIComponent(r)),i&&(s[Ave]=i.toISOString()),e.mergedGitBranchName&&(s[Eve]=encodeURIComponent(e.mergedGitBranchName)),s}P.object({entries:P.array(bz)});P.object({platform:NL.optional(),entries:P.array(HK)});P.object({testId:P.string(),environment:P.string().optional(),platform:NL.optional()});P.object({testId:P.string(),key:P.string(),environment:P.string().optional()});function WY(e){return P.record(P.string(),P.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 qY=WY(Tz),KY=jK.array();function NY(e){return WY(Ab(e))}var YY={ANDROID:e=>NY(YC).parse(e),IOS:e=>NY(JC).parse(e)},Rve=P.object({id:P.string(),completionType:P.string(),description:P.string().optional(),thoughts:P.string(),result:P.string(),sessionType:P.string(),timeCreated:P.string().optional(),citations:P.array(Uo).optional()}),wve=P.object({id:P.string(),assertion:P.string().optional(),result:P.string(),thoughts:P.string(),sessionType:P.string(),timeCreated:P.string().optional(),citations:P.array(Uo).optional()});P.object({completionType:P.string(),traceIds:P.string().array()});var HL=P.union([Rve,wve]).array(),JY=P.object({trigger:P.nativeEnum(Us),status:P.nativeEnum(St),startedAt:P.coerce.date().optional(),gitCommitSha:P.string().optional(),gitCommitShaShort:P.string().optional(),gitCommitTimestamp:P.coerce.date().optional(),gitBranchName:P.string().optional(),gitOriginUrl:P.string().optional(),gitCommitMessage:P.string().optional(),gitCommitAuthorName:P.string().optional(),githubRepository:P.string().optional(),gitlabProjectPath:P.string().optional(),pipelineId:P.string().optional(),cliVersion:P.string().optional()});P.object({id:P.string()});var XY=P.object({status:P.nativeEnum(St),updatedAt:P.coerce.date().optional(),finishedAt:P.coerce.date().optional()});P.object({summary:bm,githubRepository:P.string().optional(),gitBranchName:P.string().optional()});var Ive=P.object({runId:P.string(),healStatus:Mg,healDetails:Ou.optional()});P.object({updates:Ive.array()});var QY=P.object({stepsSnapshot:P.array(P.record(P.string(),P.unknown().optional())).optional(),beforeStepsSnapshot:P.array(P.record(P.string(),P.unknown().optional())).optional(),afterStepsSnapshot:P.array(P.record(P.string(),P.unknown().optional())).optional(),runGroupId:P.string().optional(),testId:P.string(),testName:P.string(),resolvedBaseUrl:P.string().optional(),environmentName:P.string().optional(),labels:P.array(P.string()).optional(),cliVersion:P.string().optional(),trigger:P.nativeEnum(Us),schemaVersion:P.string().optional(),section:P.nativeEnum(RC).optional(),resolvedInputs:P.record(P.string(),P.string()).optional(),quarantined:P.boolean().optional().default(false),quarantinedReason:P.string().optional(),aiSettings:Ca.optional()});P.object({id:P.string()});var xve=AN.pick({id:true,status:true,healStatus:true,healDetails:true,testName:true,testId:true,test:true,failureReason:true,failureDetails:true}),ZY=xve.array(),eJ=AN.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();P.object({id:P.string()});var tJ=P.object({run:ds.omit({runAttempts:true}),attemptZipUrls:P.array(P.string().url().nullish())}),nJ=P.object({status:P.nativeEnum(St),finishedAt:P.coerce.date().optional(),schemaVersion:P.string().optional().default("1.0.19"),results:P.record(P.string(),P.unknown().optional()).array().optional(),beforeResults:P.record(P.string(),P.unknown().optional()).array().optional(),afterResults:P.record(P.string(),P.unknown().optional()).array().optional()});P.object({screenshot:P.string(),contentType:P.enum(["image/jpeg","image/png"]).optional()});P.object({id:P.string(),screenshot:P.string(),contentType:P.enum(["image/jpeg","image/png"])});var oJ=P.object({key:P.string()}),rJ=P.object({orgId:P.string(),userId:P.string(),email:P.string().optional(),name:P.string().optional(),pylonEmailHash:P.string().optional(),selfServe:P.boolean().optional()}),iJ=P.object({blocked:P.boolean()}),sJ=P.array(nz);P.record(P.string(),P.union([P.string(),P.boolean()]));P.object({workosAccessToken:P.string().min(1),organizationId:P.string().optional(),clientName:P.string().min(1).max(80).optional()});var aJ=P.object({apiKey:P.string(),apiKeyName:P.string(),organizationId:P.string(),user:P.object({id:P.string(),email:P.string().optional()}),selfServe:P.boolean().optional()}),lJ=P.object({error:P.literal("multiple_organizations"),organizations:P.array(P.object({id:P.string(),name:P.string()}))}),_ve=["web","ios","android"];P.object({platforms:P.array(P.enum(_ve)),packageManager:P.enum(["npm","pnpm","yarn","bun"]),wizardVersion:P.string().min(1).max(40),cliVersions:P.object({momentic:P.string().max(40).optional(),momenticMobile:P.string().max(40).optional()}).optional(),firstRunIds:P.array(P.guid()).max(10).optional()});P.object({ok:P.literal(true)});P.object({paths:P.string().array(),env:P.string().optional(),urlOverride:P.string().optional(),customHeaders:P.record(P.string(),P.string()).optional()});var cJ=P.object({suiteRunIds:P.string().array(),runGroupIds:P.string().array()});P.object({suiteRunIds:P.string().array()});xW.array();P.object({runGroupIds:P.string().array()});var SR=P.object({uploadUrl:P.string()});hr.merge(UW);hr.merge(jW);hr.merge(HW);var Pve=P.object({testId:P.string().optional().default(""),testName:P.string().optional().default(""),suiteId:P.string().optional().default(""),suiteName:P.string().optional().default(""),isInteractive:P.boolean().optional().default(false),runner:P.nativeEnum(Hi).optional(),creditsUsed:P.number().optional(),stepsExecuted:P.number().optional(),tokensUsed:P.number().optional(),hostedBrowserSecondsUsed:P.number().optional()}),Ove=P.object({transactionId:P.string(),timestamp:P.string(),event:P.nativeEnum($g),properties:Pve});Ove.array();var dJ=S2.omit({steps:true}).extend({steps:P.array(P.record(P.string(),P.unknown().optional())).describe("unparsed ResolvedStep[]")});P.object({limit:P.number().min(1).max(10).optional(),page:P.number().min(1).optional(),start:Wn.optional(),end:Wn.optional(),gitBranchName:P.string().optional(),status:P.nativeEnum(St).optional()});var uJ=gW.array(),Mve=Gu.extend({testId:co.optional(),gitBranchName:P.string().optional(),gitCommitSha:P.string().optional(),status:P.nativeEnum(St).optional(),label:P.string().array().optional(),start:Wn.optional(),end:Wn.optional(),quarantined:P.boolean().optional(),recovered:P.boolean().optional(),includeFailureDetails:P.boolean().optional(),skipRetentionFilter:P.boolean().optional()});Mve.extend({orgId:P.string().optional(),testId:mr(co),status:mr(P.nativeEnum(St)),gitBranchName:mr(P.string()),label:mr(P.string()),testName:P.string().optional(),trigger:mr(P.nativeEnum(Us)),executionType:mr(Nu),cliVersion:mr(P.string()),githubRepository:mr(P.string()),gitlabProjectPath:mr(P.string()),environment:mr(P.string()),directory:mr(P.string()),failureCategory:mr(P.string()),exclude:mr(P.string()),healed:P.boolean().optional()});var Nve=ds.omit({test:true}),pJ=fL.extend({runs:Nve.array()});P.object({applied:P.boolean().optional(),appliedAt:P.coerce.date().optional()});var mJ=SR.extend({id:P.string()}),Lve=P.object({resultType:P.literal("run").optional().default("run"),runGroupId:P.guid().optional(),persist:P.boolean().optional()}),kve=P.object({resultType:P.literal("explore"),exploreRunId:P.guid(),persist:P.boolean().optional()});P.discriminatedUnion("resultType",[Lve,kve]);var hJ=P.object({runGroupId:P.guid()}),gJ=P.object({quarantined:P.object({testId:co,quarantinedAt:P.coerce.date(),quarantinedBy:P.string().optional(),quarantinedReason:P.string()}).array()}),fJ=Gu.extend({limit:Gu.shape.limit.describe("Max number of quarantined tests to return per page."),page:Gu.shape.page.describe("Page number for pagination (1-based)."),quarantinedAtStart:P.string().pipe(P.coerce.date()).optional().describe("Include tests quarantined at or after this timestamp."),quarantinedAtEnd:P.string().pipe(P.coerce.date()).optional().describe("Include tests quarantined before this timestamp.")}),Dve=P.object({id:P.string(),status:P.literal("FAILED"),startedAt:Wn,finishedAt:Wn,failureReason:P.string().nullish(),healStatus:Mg,healDetails:Ou.nullish()}),yJ=fL.extend({quarantinedTests:P.array(P.object({testId:co,testName:P.string().nullish(),quarantinedAt:Wn,quarantineReason:P.string(),latestFailedRun:Dve.nullable()}))}),SJ=P.object({gitLocalUsername:P.string().optional(),gitLocalEmail:P.string().optional(),gitLocalName:P.string().optional()});P.object({testId:co,testName:P.string().optional(),reason:P.string()}).merge(SJ);P.object({testName:P.string().optional(),reason:P.string().optional()}).merge(SJ);hr.merge(J1);hr.merge(X1);hr.merge(Q1);P.object({apkToInstall:P.object({channel:P.string(),tag:P.string().optional()}).optional(),hostname:P.string().optional(),region:lL.optional(),osVersion:P.nativeEnum(zg).optional(),sessionId:P.string().optional(),playwrightVersion:lq.optional()});var bJ=P.object({name:P.string(),apiUrl:P.string(),webRtcUrl:P.string(),adbUrl:P.string(),token:P.string(),apkDownloadUrl:P.string().optional(),playwrightServerUrl:P.string().optional(),region:P.string().optional(),resolvedTag:P.string().optional()});P.object({appToInstall:P.object({channel:P.string(),tag:P.string().optional()}).optional(),hostname:P.string().optional(),region:lL.optional(),osVersion:P.nativeEnum(XC).optional(),sessionId:P.string().optional(),installAppOnClient:P.boolean().optional()});var TJ=P.object({id:P.string(),apiUrl:P.string(),webRtcUrl:P.string(),wdaUrl:P.string(),token:P.string(),appDownloadUrl:P.string().optional(),appMd5:P.string().optional(),region:P.string().optional(),resolvedTag:P.string().optional()});P.object({channel:P.string().trim().min(1,"channel must be a non-empty string"),tag:P.string().trim().min(1,"tag must be a non-empty string"),md5:P.string()});var AJ=P.object({id:P.string(),uploadUrl:P.string().optional(),downloadUrl:P.string(),md5:P.string().optional()}),Fve=P.object({channel:P.string(),tag:P.string(),md5:P.string(),platform:P.nativeEnum(rl).default("ANDROID"),createdAt:P.number().describe("Unix timestamp in milliseconds")}),EJ=P.object({assets:P.array(Fve)}),vJ=P.object({downloadUrl:P.string()}),jL=(n=>(n.PLAYWRIGHT="PLAYWRIGHT",n.CDP="CDP",n))(jL||{}),Bve=P.nativeEnum(jL);P.object({testId:P.string().optional(),testName:P.string().optional(),runId:P.guid().optional(),attemptedProviders:P.array(TL).optional()});var CJ=P.object({wsEndpoint:P.string(),accessToken:P.string().optional(),endpointType:Bve.optional(),provider:TL.optional()});z$1.object({repositoriesIndexed:z$1.boolean(),indexingInProgress:z$1.boolean(),indexesOutdated:z$1.boolean()});var RJ=(s=>(s.Queued="queued",s.InProgress="in_progress",s.Completed="completed",s.Waiting="waiting",s.Requested="requested",s.Pending="pending",s))(RJ||{}),wJ=(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))(wJ||{});z$1.object({name:z$1.string(),status:z$1.enum(RJ),conclusion:z$1.enum(wJ).nullable()});var yT=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()})}),GL=z$1.object({mergedBranch:z$1.string().optional()});var IJ=z$1.object({orgId:z$1.string(),cacheKeys:z$1.string().array()});z$1.object({keyParams:IJ,clientMetadata:z$1.string(),lockAcquisitionTimeoutMs:z$1.number().optional()});var xJ=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()}),IJ]);var Uve=z$1.object({remainingTtlMs:z$1.number(),value:z$1.string().nullish()});z$1.object({results:z$1.record(z$1.string(),Uve),activeLocks:z$1.string().array()});var _J=0,PJ=5*60*1e3;var OJ=z$1.object({runId:z$1.string().min(1).optional(),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:hM,healDetails:uz.optional()}),Hve=OJ.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 MJ=Hve.array();z$1.object({entries:OJ.array()});function ef(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 jve=z$1.object({version:z$1.string(),json:z$1.record(z$1.string(),z$1.unknown().optional()),hash:z$1.string()}),NJ=z$1.record(z$1.string(),z$1.unknown().optional());z$1.object({newSvgs:z$1.array(jve),metadata:NJ.optional()});var Gve=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:NJ.nullish()}),LJ=z$1.record(z$1.string().describe("icon hash"),Gve);var $L="metadata.json",VL="test.yaml",kJ=".snapshot.zip",zL=lo.extend(Ls.shape),$ve=z$1.object({envName:z$1.string().optional(),baseUrl:z$1.string(),variables:z$1.record(z$1.string(),z$1.unknown().optional()),resolvedEnv:fb.optional()}),DJ=z$1.object({browser:ol.optional(),ai:Ca.optional(),advanced:xb.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:$ve,config:DJ});var FJ=z$1.object({variables:z$1.record(z$1.string(),z$1.unknown().optional()),resolvedEnv:fb.optional()}),Vve=z$1.object({envName:z$1.string().optional(),baseUrl:z$1.string(),encryptedSecrets:z$1.string()}),BJ=z$1.object({momenticVersion:z$1.string(),schemaVersion:z$1.string(),createdAt:z$1.string(),relativeFilePath:z$1.string(),environment:Vve,config:DJ});function UJ(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 HJ=e=>{e.extraHeaders&&(e.extraHeaders=Object.fromEntries(Object.entries(e.extraHeaders).filter(([t,n])=>t.trim()&&n.trim())));};var bR=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}async saveSnapshotCacheEntries(){}async deleteStepCacheEntry(){}};function Wve(e){return e.map(t=>({...t,environment:void 0}))}function WL(e,t){return t?e:Wve(e)}var KL="browser-crash-dump.zip",qL=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new ST}},ST=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new qL}flushResults(t){}};var ct="metadata.json",$r="assets",po="runs";z$1.object({type:z$1.literal("explore"),id:z$1.string(),cliVersion:z$1.string().optional(),startedAt:z$1.string(),finishedAt:z$1.string(),baseSha:z$1.string(),headSha:z$1.string(),ciProvider:z$1.string().optional(),pipelineId:z$1.string().optional(),gitMainBranch:z$1.string().optional(),gitCommitSha:z$1.string().optional(),gitCommitShaShort:z$1.string().optional(),gitBranchName:z$1.string().optional(),gitOriginUrl:z$1.string().optional(),gitCommitMessage:z$1.string().optional(),gitCommitAuthorName:z$1.string().optional(),githubRepository:z$1.string().optional(),gitlabProjectPath:z$1.string().optional(),result:z$1.unknown(),bugs:z$1.array(z$1.unknown()),writtenPaths:z$1.array(z$1.string()),videos:z$1.array(z$1.string()),failure:z$1.unknown().optional()});var qve=z$1.object({step:Ht,status:z$1.enum(Bt),startedAt:z$1.coerce.date(),finishedAt:z$1.coerce.date().optional(),healMetadata:z$1.object({healType:z$1.enum(Eb).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()}),Kve=qve.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});Kve.extend({step:z$1.unknown().optional()});var YL=z$1.object({avdId:z$1.string().optional(),channel:z$1.string().optional(),tag:z$1.string().optional(),region:z$1.string().optional(),osVersion:cq.optional()}),GJ="1.0.0",$J=nJ.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:YL.optional(),viewport:dd.optional(),activeVideos:z$1.array(z$1.object({videoName:z$1.string(),timestamp:z$1.coerce.date()})).optional()}),bT=$J.extend({assetDetails:YL.optional(),finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});$J.extend(uN.shape);var VJ=bT.extend(uN.shape),Yve=z$1.object({results:z$1.array(js),beforeResults:z$1.array(js).optional(),afterResults:z$1.array(js).optional()});bT.extend(Yve.shape);var Jve=z$1.object({results:z$1.array(Gs),beforeResults:z$1.array(Gs).optional(),afterResults:z$1.array(Gs).optional()});bT.extend(Jve.shape);var zJ=eJ.merge(QY).extend({executionType:Nu.optional().default("WEB"),testId:co,testDescription:z$1.string().optional(),directory:z$1.string().optional(),runGroupId:z$1.guid(),status:z$1.enum(St),healStatus:Mg,startedAt:z$1.coerce.date(),schemaVersion:z$1.string().nullish(),attempts:z$1.number(),failureRecoveryDetails:z$1.object({attempts:z$1.number()}).optional(),aiSettings:Ca.optional(),avgCpuUsage:z$1.number().optional(),avgMemoryUsage:z$1.number().optional()}),Xve=zJ.extend(YL.shape),Pm=zJ.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});Xve.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});var jJ=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(TC),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()}),Qve=JY.merge(XY).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:Ca.optional(),browser:ol.optional(),aiSelect:z$1.union([jJ.transform(e=>[e]),z$1.array(jJ)]).optional()}),_a=Qve.extend({healRiskSummary:bm.optional(),updatedAt:z$1.coerce.date().optional().transform(e=>e??new Date),finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});var Zve=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"]),eCe=new Set(["MODULE","RESOLVED_MODULE"]);function TR(e){return e.type!=="PRESET_ACTION"?e.type:e.command.type}function AR(e){return eCe.has(e.type)?false:e.type!=="PRESET_ACTION"?true:!Zve.has(e.command.type)}var WJ="progress.json",qJ="1.0.0",tCe=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(St),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(St),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:tCe.array()});function KJ(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch(t){return C.error({err:t},`Error reading path ${e} during directory existence check.`),false}}var YJ="CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih",tf="https://us-west.metrics.momentic.ai",nf="c60c6a0f-60da-41a7-a61b-07969a0aa303",Om=!!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 cCe=new Set(["exit","quit"]),QJ=(()=>{try{return statSync("/.dockerenv"),!0}catch{return false}})();async function tr(e){return Om||QJ?true:(await C.flush(),await new Promise(n=>setTimeout(n,100)),await confirm({message:e}))}async function JL(e){let t=dirname(e);return KJ(t)?existsSync(e)?tr(`File '${JJ(e)}' already exists. Overwrite existing content?`):true:await tr(`Directory '${JJ(t)}' doesn't exist. Create it now?`)?(mkdirSync(t,{recursive:true}),true):false}function JJ(e){return e.replace(/(\s+)/g,"\\$1")}async function ZJ(e,t){return Om||QJ?t:(await input({message:e,default:t})).trim()||t}async function XL(){let e;try{e=(await input({message:"ask"})).trim();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError"){C.info("");return}throw t}if(!cCe.has(e.toLowerCase()))return e}var of=new Map,tX="Log throttle exceeded",bCe=100,TCe=5e3,ACe=mCe(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}}),ECe=`${tf}/logs/json`,QL=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 ACe(ECe,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":YJ,"x-momentic-metrics-api-key":nf},body:sl(t),signal:AbortSignal.timeout(5e3)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch{}}},ZL=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??Ed.hostname(),this.disableConsoleLogs=o,this.bindingAttributes={...t,env:"production"},this.flushIntervalMs=r??5e3,this.maxBatchSize=i??10,this.buffer=s??new QL(this.flushIntervalMs,this.maxBatchSize);let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=eX(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===tX)return true;let n=Date.now();return n-this.lastWindowStart>TCe&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,tX),this.droppedLogsInWindow=false,this.lastWindowStart=n),this.logsInCurrentWindow<bCe?(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(Ib[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=yCe.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=vCe();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:aW({message:o||"",...i})};this.buffer.push(l);}setApp(t){let n=this.bindingAttributes.app;this.bindingAttributes.app=t,of.set("app",this),of.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=lW[t]):(this.minLevelValue=Ib[t],this.consoleLogger.level=t);}enableConsoleLogs(){this.disableConsoleLogs=false;}},rf=({app:e,hostname:t,disableConsoleLogs:n})=>(of.has(e)||of.set(e,new ZL({bindings:{app:e},hostname:t,disableConsoleLogs:n})),of.get(e));function vCe(){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 ER(){await Promise.all([...of.values()].map(e=>e.flush()));}var zu=class extends Error{callSiteStack;constructor(t){super(t),this.name="TimeoutError";}};var oX=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 xe(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 Promise.resolve(e).catch(()=>{}),c(oX(m));d=()=>c(oX(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 zu(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 vR="organization";function CR(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:{[vR]: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:vR,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 rX(e,t,n){let o,r=0,i=3,s,a;for(;r<i;)try{let l=await xe(e.getAllFlagsAndPayloads(n??t,{personProperties:{organizationId:t},groups:{[vR]: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 RR=class e extends iT{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 rX(r,n,o);return new e(r,n,o,i,s)}async refresh(){let{flags:n,payloads:o}=await rX(this.client,this.orgId,this.userId);this.flags=n,this.payloads=o;}};var _Ce=2e3,Mm=e=>Number.parseInt(e,10),tk=e=>readFileSync(e,"utf8").trim(),sf=e=>Mm(tk(e)),iX,wR,TT={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0};function lX(){return {...TT}}var xR=Ed.platform(),PCe=Ed.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 ek(e=Date.now()){let t=Ed.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 cX(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 OCe(){let e=ek();return ()=>{let t=ek(),n=cX(e,t);return e=t,n}}function sX(){try{let t=readFileSync("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(t?.[1])return Mm(t[1])}catch{}try{let e=sf("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(e))return e/1e3}catch{}return null}function MCe(){try{let t=tk("/sys/fs/cgroup/cpu.max").split(" "),n=t[0],o=t[1];return !n||!o||n==="max"?null:Mm(n)/Mm(o)}catch{}try{let e=sf("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),t=sf("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return e===-1||isNaN(t)?null:e/t}catch{return null}}function NCe(){if(xR!=="linux")return null;let e=sX();if(e===null)return null;let t=MCe()??Ed.cpus().length,n=e,o=Date.now();return ()=>{let r=sX();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 LCe(){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(Ed.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 dX({intervalMs:e=_Ce,maxSamples:t=1e4,keepSamples:n=true,onSample:o}={}){let r=[],i=NCe()??OCe(),s=LCe(),a=()=>{let d=Date.now(),u=pX(),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 IR=e=>{try{let t={},n=!1,o=pX(),r=DCe();TT.samples++,o.freePercentage<.05&&(Object.assign(t,process.memoryUsage()),n=!0,TT.lowMemorySamples++),r&&r?.total>80&&(n=!0,TT.highCpuSamples++);let i=xCe.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(n=!0,TT.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{}},uX=e=>{IR(e),setTimeout(()=>IR(e),5e3);};function _R(e){return IR(e),{interval:setInterval(()=>IR(e),2e4),cpuMetadata:PCe,platform:xR}}function kCe(){if(xR!=="linux")return null;try{let e=tk("/sys/fs/cgroup/memory.max"),t=sf("/sys/fs/cgroup/memory.current");if(e==="max"||isNaN(t))return null;let n=Mm(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=sf("/sys/fs/cgroup/memory/memory.limit_in_bytes"),t=sf("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(e)||isNaN(t))return null;let n=Ed.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 pX(){let e=kCe();if(e)return e;let t=Ed.totalmem(),n=xR==="darwin"?FCe():(()=>{let r=Ed.freemem();return {availableMemory:r,rawFreeMemory:r,cachedMemory:0}})(),o=n.availableMemory/t;return {totalMemory:t,freeMemory:n.availableMemory,freePercentage:o}}function DCe(){let e=ek();if(!wR)return wR=e,null;let t=cX(wR,e);return wR=e,t?(iX=t,iX):null}function FCe(){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?Mm(n):4096,r=d=>{let p=e.match(new RegExp(`${d}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Mm(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=Ed.freemem();return {availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}process.env.APP||"unknown";var PR="deployment.environment",OR="service.instance.id";function mX(){return process.env.MOMENTIC_LOCAL_DEV==="1"&&process.env.LOCAL_SIGNOZ==="true"}var af=false,MR,AT,ET,fX=[],NR;function LR(){return af}function yX(e){fX.push(e);}async function JCe(){for(let e of fX)try{await e();}catch{}}function XCe(){return LR()&&trace.getSpan(context.active())!==void 0}function QCe(){return mX()?new OTLPTraceExporter({url:"http://localhost:4318/v1/traces"}):new OTLPTraceExporter({url:`${tf}/v1/traces`,headers:{"x-momentic-metrics-api-key":nf}})}function ZCe(e){let t="production",n=v4$1(),o=QCe();return new NodeTracerProvider({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:e,[PR]:t,[OR]:n,[ATTR_SERVICE_VERSION]:"3.25.1"}),spanProcessors:[new BatchSpanProcessor(o)]})}function eRe(e){NR=registerInstrumentations({tracerProvider:e,instrumentations:[new UndiciInstrumentation({requireParentforSpans:true})]});}function tRe(e){return !e&&!MR?trace.getTracer("momentic-serverless"):ET?.getTracer("momentic-serverless")??trace.getTracer("momentic-serverless")}async function vd(e){if(!(!e.enabled||af))try{MR=e.serviceName;let t=ZCe(e.serviceName);ET=t,AT=new AsyncLocalStorageContextManager,t.register({contextManager:AT.enable(),propagator:new W3CTraceContextPropagator}),eRe(t),af=!0;}catch{af=false,MR=void 0,ET=void 0,AT=void 0,NR=void 0;}}async function kR(){if(af)try{await JCe(),await ET?.shutdown();}catch{}finally{NR?.();try{AT?.disable();}catch{}af=false,MR=void 0,AT=void 0,ET=void 0,NR=void 0;}}async function He(e){if(!LR()||!e.root&&!XCe())return e.fn(void 0);let t=e.serviceName===void 0?e.attributes:{...e.attributes??{},"momentic.span_service_name":e.serviceName};return await tRe(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 vT=class{increment(t,n,o){}gauge(t,n){}distribution(t,n,o){}async flush(){}async recordDuration(t){return await ok(t)}};async function ok({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 xe(s,{milliseconds:n,message:o??`Timed out after ${n}ms recording duration for ${t}`})}function nRe(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 rk(e,t){let n=nRe(e);return !t||Object.keys(t).length===0?n:{...t,...n}}function mRe(){return new OTLPMetricExporter({url:`${tf}/v1/metrics`,headers:{"x-momentic-metrics-api-key":nf},temporalityPreference:AggregationTemporalityPreference.DELTA})}var ik=[100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],DR=(e,t)=>({instrumentName:e,instrumentType:InstrumentType.HISTOGRAM,aggregation:{type:AggregationType.EXPLICIT_BUCKET_HISTOGRAM,options:{boundaries:t,recordMinMax:false}}}),hRe=[DR("test_event_duration",ik),DR("test_step_duration",ik),DR("test_mobile_step_duration",ik),DR("web_agent_action_duration",[25,50,100,200,350,500,750,1e3,2e3,5e3,1e4,2e4])],FR=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,[PR]:n,[OR]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:v4$1(),[ATTR_SERVICE_VERSION]:"3.25.1"}),r=mRe(),i=new PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:t.exportIntervalMs??6e4});this.provider=new MeterProvider({resource:o,readers:[i],views:hRe}),metrics.setGlobalMeterProvider(this.provider),this.meter=metrics.getMeter("momentic-serverless");}increment(t,n,o){try{let r=rk(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=rk(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 ok(t)}finally{this.distribution(n,Date.now()-r,o);}}};var wt=new vT;function bX(e){if(!e.disabled)try{wt=new FR(e);}catch{wt=new vT;}}var sk;function TX(e){sk=e;}function Wu(e){fRe(e)&&sk&&sk(e);}var gRe=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function fRe(e){return e instanceof Error&&e.name==="AbortError"?false:ob(e,Cu)?true:ob(e,Oe)?false:e instanceof oe?gRe.has(e.reason):true}function yRe({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;wt.distribution("ai_session_tokens",r,[...o,"category:input"]),wt.distribution("ai_session_tokens",Math.max(0,Math.min(i,r)),[...o,"category:cached_input"]),wt.distribution("ai_session_tokens",s,[...o,"category:output"]);}function BR({usage:e,promptType:t,logger:n,message:o,result:r="success",attributes:i}){yRe({usage:e,promptType:t,result:r}),n.info({...i,promptType:t,result:r,usage:e},o);}function ps({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&&BR({usage:a,promptType:t,logger:n,result:i,message:r,attributes:s});});}}function NX(){return globalThis.crypto}function dk(e){let t=NX(),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 Ku(){let e=NX();if(e&&typeof e.randomUUID=="function")return e.randomUUID();let t=dk(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 uk(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 bRe(e){return new Promise(t=>setTimeout(t,e))}function RT(e){if(e)return e.endsWith("/")?e:`${e}/`}function TRe(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 ARe(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 ERe(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=ARe(i,r);n.debug&&console.warn(`${o} ${t} retry ${i}/${n.maxAttempts} in ${s}ms`),s>0&&await bRe(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 Nm(e,t,n,o){let r=`POST ${e}`;await ERe(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=TRe(i.headers);throw typeof l=="number"&&(a.retryAfterMs=l),a.retryable=i.status===429||i.status>=500,a}},r,o);}var AX={UNSET:0,ERROR:2};function EX(e){let t=e?e.traceIdB64:uk(dk(16)),n=uk(dk(8));return {traceIdB64:t,spanIdB64:n,parentSpanIdB64:e?e.spanIdB64:void 0}}function wT(){return Date.now().toString()+"000000"}function vX(e){return String(Math.floor(e))+"000000"}function Z(e,t){if(t!==void 0)return {key:e,value:{stringValue:t}}}function it(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{intValue:String(Math.trunc(t))}}}function cf(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{doubleValue:t}}}function vRe(e,t){if(t!==void 0)return {key:e,value:{boolValue:t}}}function Cd(e,t){if(!(!t||t.length===0))return {key:e,value:{arrayValue:{values:t.filter(n=>typeof n=="string").map(n=>({stringValue:n}))}}}}function ak(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 CX(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 CRe="RAINDROP_LOCAL_DEBUGGER",RRe="RAINDROP_WORKSHOP",RX="http://localhost:5899/v1/";function Sk(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 wRe(){let e=Sk(RRe);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 IRe(e){return e?!!(e==="localhost"||e==="127.0.0.1"||e==="0.0.0.0"||e==="::1"||e.endsWith(".localhost")):false}function xRe(){try{let e=globalThis?.location;if(e&&typeof e.hostname=="string"&&e.hostname.length>0)return e.hostname}catch{}}function _Re(){return !!(IRe(xRe())||Sk("NODE_ENV")==="development")}function km(e){var t,n,o;if(e===null)return null;if(typeof e=="string"&&e.length>0)return (t=RT(e))!=null?t:null;let r=Sk(CRe);if(r)return (n=RT(r))!=null?n:null;let i=wRe();return i==="disable"?null:i==="enable"?RX:i&&"url"in i?(o=RT(i.url))!=null?o:null:_Re()?RX:null}function zR(e){return km(e)!==null}function PRe(e,t={}){var n;let o=km(t.baseUrl);o&&Nm(`${o}traces`,e,{},{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function ORe(e,t={}){var n;let o=km(t.baseUrl);if(!o)return;let r=t.writeKey?{Authorization:`Bearer ${t.writeKey}`}:{};Nm(`${o}events/track_partial`,e,r,{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function qu(e,t={}){var n,o;let r=km(t.baseUrl);r&&Nm(`${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 MRe(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 NRe=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=RT(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=km(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=MRe(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 Nm(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 Nm(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,...A}=(i=g.properties)!=null?i:{},v=(s=g.convoId)!=null?s:f.convoId,w=(l=(a=g.isPending)!=null?a:f.isPending)!=null?l:true,I={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:v},properties:{...A,...T?{"raindrop.wizardSession":T}:{},$context:this.context},attachments:g.attachments,is_pending:w},_=`${this.baseUrl}events/track_partial`;if(this.debug&&console.log(`${this.prefix} sending track_partial`,{eventId:e,eventName:y,userId:S,convoId:v,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(x=>({type:x.type,role:x.role,name:x.name,valuePreview:x.value.slice(0,60)})))!=null?m:[],endpoint:_}),this.localDebuggerUrl&&ORe(I,{baseUrl:this.localDebuggerUrl,writeKey:this.writeKey,debug:this.debug,sdkName:this.sdkName}),!this.writeKey){w||this.sticky.delete(e);return}let R=Nm(_,I,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(R);try{try{await R,this.debug&&console.log(`${this.prefix} sent track_partial ${e} (${y})`);}catch(x){let O=x instanceof Error?x.message:String(x);console.warn(`${this.prefix} failed to send track_partial (dropping): ${O}`);}}finally{this.inFlight.delete(R);}w||this.sticky.delete(e);}},LX=["apikey","apisecret","apitoken","secretaccesskey","sessiontoken","privatekey","privatekeyid","clientsecret","accesstoken","refreshtoken","oauthtoken","bearertoken","authorization","password","passphrase"],kX="[REDACTED]";function DX(e){return e.toLowerCase().replace(/[-_.]/g,"")}function FX(e,t){var n,o;let r=LRe((n=t?.secretKeyNames)!=null?n:LX),i=(o=t?.placeholder)!=null?o:kX,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(DX(d))?c[d]=i:c[d]=a(u);return c};return a(e)}function LRe(e){let t=new Set;for(let n of e)t.add(DX(n));return t}var BX=["ai.request.providerOptions","ai.response.providerMetadata"];function UX(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=HX(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 kRe=new Set(BX);function HX(e,t){if(!kRe.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=FX(o),i;try{i=JSON.stringify(r);}catch{return}if(i!==n)return {stringValue:i}}var DRe=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=RT(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=km(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=UX(t)),t}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}startSpan(e){var t,n;let o=EX(e.parent),r=(t=e.startTimeUnixNano)!=null?t:wT(),i=[Z("ai.telemetry.metadata.raindrop.eventId",e.eventId),Z("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(ak({ids:s.ids,name:s.name,startTimeUnixNano:s.startTimeUnixNano,endTimeUnixNano:s.startTimeUnixNano,attributes:s.attributes,status:{code:AX.UNSET}})),s}mirrorToLocalDebugger(e){if(!this.localDebuggerUrl)return;let t=this.redactSpan(e);if(t===null)return;let n=CX([t],this.serviceName,this.serviceVersion);PRe(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:wT(),(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:AX.ERROR,message:s};}let i=ak({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=EX(e.parent),o=[Z("ai.telemetry.metadata.raindrop.eventId",e.eventId)];(t=e.attributes)!=null&&t.length&&o.push(...e.attributes);let r=ak({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=CX(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=Nm(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(()=>{})));}},FRe={};function wX(){return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE}var BRe=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();}}},URe=class{},HRe=class extends URe{constructor(){super(),this._fallback=null;let e=wX();if(e){this._storage=new e;return}this._fallback=new BRe,this._storage=this._fallback;}maybeAdoptAsyncLocalStorage(){if(!this._fallback||!this._fallback.isEmpty())return;let e=wX();e&&(this._storage=new e,this._fallback=null);}isReady(){return true}getParentSpanIds(){this.maybeAdoptAsyncLocalStorage();let e=this._storage.getStore();if(!(!e||e===FRe))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()}},lk=null;function Yu(){return lk||(lk=globalThis.RAINDROP_CONTEXT_MANAGER?new globalThis.RAINDROP_CONTEXT_MANAGER:new HRe),lk}function jX(e,t){return Yu().runInContext(e,t)}async function Lm(){return Yu().getParentSpanIds()}async function IT(e,t){let n=Yu(),o={traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId};return n.runInContext(o,t)}async function*jRe(e,t){let n;for(;;){let o=await jX(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 ve(e){return typeof e=="object"&&e!==null}function ui(e){return typeof e=="function"}function IX(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 $R(e){try{return JSON.stringify(e)}catch{return}}function ut(e){try{return JSON.stringify(e,(t,n)=>n instanceof Uint8Array?uk(n):n)}catch{return}}function JR(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(!ve(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 bk(e){if(!ve(e))return;let t=e.text;return typeof t=="string"?t:void 0}function GRe(e){var t;if(!ve(e))return;let n=e.object;if(n!==void 0)return (t=$R(n))!=null?t:String(n)}function $Re(e){if(typeof e!="function")return false;let t=e.prototype;return ve(t)?typeof t.generate=="function"&&typeof t.stream=="function":false}function Tk(e){if(!ve(e))return;let t=e.model;if(typeof t=="string"&&t.length)return t;let n=e.response;if(ve(n)){let o=n.modelId;if(typeof o=="string"&&o.length)return o}}function xT(e){if(ve(e)){if(typeof e.finishReason=="string")return e.finishReason;if(ve(e.finishReason)&&typeof e.finishReason.unified=="string")return e.finishReason.unified}}function xX(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 VR(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=xX(e);return n?`data:${t};base64,${n}`:void 0}if(e instanceof ArrayBuffer){let n=xX(new Uint8Array(e));return n?`data:${t};base64,${n}`:void 0}}function GX(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 _X(e){if(typeof e.mediaType=="string")return e.mediaType;if(typeof e.mimeType=="string")return e.mimeType;let t=e.file;if(ve(t)){if(typeof t.mediaType=="string")return t.mediaType;if(typeof t.mimeType=="string")return t.mimeType}}function VRe(e){if(typeof e.filename=="string")return e.filename;if(typeof e.name=="string")return e.name;let t=e.file;if(ve(t)){if(typeof t.filename=="string")return t.filename;if(typeof t.name=="string")return t.name}}function zRe(e){if("data"in e)return e.data;let t=e.file;if(ve(t)){if("file_data"in t)return t.file_data;if("data"in t)return t.data}}function WRe(e,t){var n,o,r;let i=e.type;if(typeof i=="string"){if(i==="image"){let s=(n=_X(e))!=null?n:"image/png",a=VR(e.image,s);return a?{type:"image",role:t,value:a}:void 0}if(i==="image_url"){let s=e.image_url,a=ve(s)?s.url:s,l=VR(a,"image/png");return l?{type:"image",role:t,value:l}:void 0}if(i==="file"){let s=_X(e),a=zRe(e),l=s?.startsWith("image/")===true,c=l&&s?VR(a,s):GX(a);if(!c)return;let d=(r=(o=VRe(e))!=null?o:s)!=null?r:"file";return {type:l?"image":"text",role:t,name:d,value:c}}}}function pk(e,t){if(!Array.isArray(e))return;let n=[];for(let o of e){if(!ve(o))continue;let r=WRe(o,t);r&&n.push(r);}return n.length?n:void 0}function qRe(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?VR(s,i):GX(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 KRe(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(!ve(o))continue;let r=qRe(o);r&&n.push(r);}return n.length?n:void 0}function $X(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t="";for(let n of e)!ve(n)||n.type!=="text"||typeof n.text!="string"||(t+=n.text);return t.length?t:void 0}function Ak(e){let t=e.messages;if(Array.isArray(t))return t;let n=e.prompt;if(Array.isArray(n))return n}function VX(e){let t=Ak(e);if(t)for(let n=t.length-1;n>=0;n--){let o=t[n];if(ve(o)&&o.role==="user")return o}}function Ek(e){var t;if(ve(e))return pk((t=VX(e))==null?void 0:t.content,"input")}async function vk(e){if(!ve(e))return;let t=await KRe(e.files);if(t?.length)return t;let n=XR(e);for(let o=n.length-1;o>=0;o--){let r=n[o];if(!(!ve(r)||r.role!=="assistant"))return pk(r.content,"output")}return pk(e.content,"output")}function Ck(e){var t,n;if(!ve(e))return;let o=(t=VX(e))==null?void 0:t.content;if(o===void 0)return;let r=$X(o);return r!==void 0?r:(n=ut(o))!=null?n:String(o)}function Rk(e){var t;if(!ve(e))return;let n=e.prompt;if(typeof n=="string")return n;let o=Ak(e);if(Array.isArray(o)&&o.length>0){let i=o[o.length-1];if(ve(i)){let s=i.content,a=$X(s);if(a!==void 0)return a;let l=$R(s);if(l)return l}return (t=$R(o))!=null?t:void 0}let r=e.input;return typeof r=="string"?r:$R(e)}function wk(e){if(!ve(e))return [];let t=[];typeof e.system=="string"&&e.system&&t.push({role:"system",content:e.system});let n=Ak(e);if(Array.isArray(n)){for(let o of n)ve(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 XR(e){if(!ve(e))return [];let t=e.response;if(ve(t)&&Array.isArray(t.messages))return t.messages.filter(o=>ve(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(ve(o)&&ve(o.response)){let r=o.response.messages;if(Array.isArray(r))return r.filter(i=>ve(i)&&typeof i.role=="string"&&"content"in i).map(i=>i)}}return []}function WR(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=ut(e.input);return t!==void 0?`name:${e.toolName}|input:${t}`:`name:${e.toolName}`}}function YRe(e,t){return e.isError===true||e.type==="tool-error"?true:ve(t)&&typeof t.type=="string"?t.type.startsWith("error")||t.type==="execution-denied":false}function JRe(e){if(typeof e=="string"&&e.length>0)return e;if(ve(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 ut(e)}function XRe(e){if(!ve(e))return [];let t=e.content;return Array.isArray(t)?t.filter(ve):ve(t)?[t]:[]}function QRe(e){return "input"in e?e.input:"args"in e?e.args:void 0}function Ik(e){let t=e.toolCallId;return typeof t=="string"&&t.length>0?t:void 0}function ZRe(e){return "output"in e?e.output:"result"in e?e.result:e.error}function ewe(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 twe(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 nwe(e){var t,n,o,r;let{spans:i,pendingKeysByToolName:s,part:a}=e,l=Ik(a),c=typeof a.toolName=="string"?a.toolName:void 0,d=QRe(a),u=WR({toolCallId:l,toolName:c,input:d});if(!u)return;let p=l==null?WR({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&&ewe(s,c,u);}function owe(e){var t,n,o;let{spans:r,pendingKeysByToolName:i,part:s}=e,a=Ik(s),l=typeof s.toolName=="string"?s.toolName:void 0,c=ZRe(s),d=WR({toolCallId:a,toolName:l,input:void 0}),u=a!=null?d:(t=twe(i,l))!=null?t:d;if(!u)return;let p=r.get(u),m=YRe(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?JRe(c):void 0});}function zX(e){let t=new Map,n=new Map;for(let o of e)for(let r of XRe(o)){if(r.type==="tool-call"){nwe({spans:t,pendingKeysByToolName:n,part:r});continue}(r.type==="tool-result"||r.type==="tool-error")&&owe({spans:t,pendingKeysByToolName:n,part:r});}return [...t.values()]}function rwe(e){if(!Array.isArray(e))return;let t="";for(let n of e)ve(n)&&n.type==="text"&&typeof n.text=="string"&&(t+=n.text);return t.length?t:void 0}function iwe(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!ve(n)||n.type!=="tool-call")continue;let o=Ik(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 uf(e){if(!ve(e))return;let t=e.experimental_telemetry;if(ve(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:ve(t.metadata)?t.metadata:void 0}}function Pa(e,t){return {operationName:`${e}${t?` ${t}`:""}`,resourceName:t}}function WX(e,t){if(t==null)return;if(typeof t=="string")return Z(e,t);if(typeof t=="number")return Number.isInteger(t)?it(e,t):cf(e,t);if(typeof t=="boolean")return vRe(e,t);if(Array.isArray(t)&&t.every(o=>typeof o=="string"))return Cd(e,t);let n=ut(t);return n?Z(e,n):void 0}function QR(e){return e?Object.entries(e).filter(([t])=>!t.startsWith("raindrop.internal.")).map(([t,n])=>WX(`ai.telemetry.metadata.${t==="raindrop.userId"?"raindrop.ai.userId":t}`,n)):[]}function xk(e){return ve(e)?Object.entries(e).filter(([,t])=>typeof t=="string").map(([t,n])=>Z(`ai.request.headers.${t}`,n)):[]}function _k(e){if(!ve(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(Cd(`ai.settings.${o}`,r)):o==="timeout"&&typeof r=="number"?t.push(it(`ai.settings.${o}`,r)):t.push(WX(`ai.settings.${o}`,r));}return t}function qX(e){return ve(e)?[cf("gen_ai.request.frequency_penalty",typeof e.frequencyPenalty=="number"?e.frequencyPenalty:void 0),it("gen_ai.request.max_tokens",typeof e.maxOutputTokens=="number"?e.maxOutputTokens:void 0),cf("gen_ai.request.presence_penalty",typeof e.presencePenalty=="number"?e.presencePenalty:void 0),...Array.isArray(e.stopSequences)&&e.stopSequences.every(t=>typeof t=="string")?[Cd("gen_ai.request.stop_sequences",e.stopSequences)]:[],cf("gen_ai.request.temperature",typeof e.temperature=="number"?e.temperature:void 0),it("gen_ai.request.top_k",typeof e.topK=="number"?e.topK:void 0),cf("gen_ai.request.top_p",typeof e.topP=="number"?e.topP:void 0)]:[]}function KX(e){if(!ve(e)||!ve(e.providerOptions))return;let t=ut(e.providerOptions);return t?Z("ai.request.providerOptions",t):void 0}var swe=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();}}},UR=null;function YX(){if(UR)return UR;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return UR=e?new e:new swe,UR}function Pk(){return YX().getStore()}function mk(e,t){return YX().run(e,t)}function JX(e){var t;if(e.length===0)return;let n=e[0];if(!ve(n))return;let o=ve(n.metadata)?n.metadata:void 0,r=ve(n.telemetry)?n.telemetry.metadata:void 0,i=ve(r)?r:void 0,s=uf(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 awe=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();}}},HR=null;function Ok(){if(HR)return HR;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return HR=e?new e:new awe,HR}function hk(){return Ok().getStore()}function gk(e){var t;let n=Ok();(t=n.enterWith)==null||t.call(n,e);}function XX(){var e;let t=Ok();(e=t.enterWith)==null||e.call(t,void 0);}var Mk=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=Pk(),m=u??p?.rawMetadata,h=this.extractRaindropMetadata(m),g=Yu().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:Ku(),T=g&&g.eventId===S?{traceIdB64:g.traceIdB64,spanIdB64:g.spanIdB64}:void 0,{operationName:A,resourceName:v}=Pa(t.operationId,d),w=!a&&this.subagentWrapping?hk():void 0,I=!a&&this.subagentWrapping&&w===void 0&&typeof m?.["ash.subagent.name"]=="string"?m["ash.subagent.name"]:void 0,_=(s=w?.toolName)!=null?s:I,R,x;if(_&&this.sendTraces){let N=w?[Z("raindrop.parent.callId",w.parentCallId),Z("raindrop.parent.toolCallId",w.toolCallId),Z("raindrop.parent.toolName",w.toolName)]:[];R=this.traceShipper.startSpan({name:_,parent:T,eventId:S,operationId:"ai.toolCall",attributes:[Z("operation.name","ai.toolCall"),Z("resource.name",_),Z("raindrop.span.kind","tool_call"),Z("ai.toolCall.name",_),Z("raindrop.subagent.name",_),Z("raindrop.agent.role","subagent"),...N]});let k=this.spanParentRef(R),W=this.traceShipper.startSpan({name:"agent.subagent",parent:k,eventId:S,operationId:"agent.subagent",attributes:[Z("operation.name","agent.subagent"),Z("raindrop.span.kind","llm_call"),Z("raindrop.subagent.name",_)]});this.traceShipper.endSpan(W),x=k;}let O;if(this.sendTraces){let N=!a&&l?[Z("ai.prompt",ut({system:t.system,prompt:t.prompt,messages:t.messages}))]:[],k=a&&l?t.operationId==="ai.embedMany"?[Z("ai.values",ut(t.value))]:[Z("ai.value",ut(t.value))]:[];O=this.traceShipper.startSpan({name:t.operationId,parent:x??T,eventId:S,operationId:t.operationId,attributes:[Z("operation.name",A),Z("resource.name",v),Z("ai.telemetry.functionId",d),Z("ai.model.provider",t.provider),Z("ai.model.id",t.modelId),...QR(m?Object.fromEntries(Object.entries(m).filter(([W])=>W!=="raindrop.eventId"&&W!=="raindrop.internal.eventIdGenerated")):void 0),...N,...k]});}this.callStates.set(t.callId,{operationId:t.operationId,eventId:S,rootSpan:O,rootParent:O?this.spanParentRef(O):x??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:_,subagentToolCallSpan:R});},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}=Pa(r,n.functionId),a=[];n.recordInputs&&(t.promptMessages&&a.push(Z("ai.prompt.messages",ut(t.promptMessages))),t.stepTools&&a.push(Cd("ai.prompt.tools",t.stepTools.map(c=>JSON.stringify(c)))),t.stepToolChoice!=null&&a.push(Z("ai.prompt.toolChoice",JSON.stringify(t.stepToolChoice))));let l=this.traceShipper.startSpan({name:r,parent:n.rootParent,eventId:n.eventId,operationId:r,attributes:[Z("operation.name",i),Z("resource.name",s),Z("ai.telemetry.functionId",n.functionId),Z("ai.model.provider",t.provider),Z("ai.model.id",t.modelId),Z("gen_ai.system",t.provider),Z("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(Z("ai.response.finishReason",t.finishReason),Z("ai.response.text",(n=t.text)!=null?n:void 0),Z("ai.response.id",(o=t.response)==null?void 0:o.id),Z("ai.response.model",(r=t.response)==null?void 0:r.modelId),Z("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),Z("ai.response.providerMetadata",t.providerMetadata?ut(t.providerMetadata):void 0)),((a=t.toolCalls)==null?void 0:a.length)>0&&p.push(Z("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(Z("ai.response.reasoning",h));}p.push(Cd("gen_ai.response.finish_reasons",[t.finishReason]),Z("gen_ai.response.id",(c=t.response)==null?void 0:c.id),Z("gen_ai.response.model",(d=t.response)==null?void 0:d.modelId));let m=t.usage;m&&p.push(it("ai.usage.inputTokens",m.inputTokens),it("ai.usage.outputTokens",m.outputTokens),it("ai.usage.totalTokens",m.totalTokens),it("ai.usage.reasoningTokens",m.reasoningTokens),it("ai.usage.cachedInputTokens",m.cachedInputTokens),it("gen_ai.usage.input_tokens",m.inputTokens),it("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}=Pa(t.operationId,n.functionId),i=n.recordInputs?[Z("ai.values",ut(t.values))]:[],s=this.traceShipper.startSpan({name:t.operationId,parent:n.rootParent,eventId:n.eventId,operationId:t.operationId,attributes:[Z("operation.name",o),Z("resource.name",r),Z("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(Z("ai.embeddings",ut(t.embeddings))),((n=t.usage)==null?void 0:n.tokens)!=null&&i.push(it("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?IT({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(!zR()||!e.rootSpan)return;let d=this.extractRaindropMetadata(e.metadata);qu({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=hk();this.priorParentContexts.set(t.toolCallId,n??null),gk({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}=Pa("ai.toolCall",o.functionId),s=o.recordInputs?[Z("ai.toolCall.args",ut(t.input))]:[],a=this.traceShipper.startSpan({name:"ai.toolCall",parent:o.stepParent,eventId:o.eventId,operationId:"ai.toolCall",attributes:[Z("operation.name",r),Z("resource.name",i),Z("ai.telemetry.functionId",o.functionId),Z("ai.toolCall.name",t.toolName),Z("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?gk(i):XX();}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?[Z("ai.toolCall.result",ut(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}=Pa("ai.toolCall",t.functionId),l=t.recordInputs?[Z("ai.toolCall.args",ut(i.input))]:[],c=this.traceShipper.startSpan({name:"ai.toolCall",parent:t.stepParent,eventId:t.eventId,operationId:"ai.toolCall",attributes:[Z("operation.name",s),Z("resource.name",a),Z("ai.telemetry.functionId",t.functionId),Z("ai.toolCall.name",i.toolName),Z("ai.toolCall.id",i.toolCallId),Z("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?[Z("ai.toolCall.result",ut(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(Z("ai.response.finishReason",e.finishReason),Z("ai.response.text",(n=e.text)!=null?n:void 0),Z("ai.response.providerMetadata",e.providerMetadata?ut(e.providerMetadata):void 0)),((o=e.toolCalls)==null?void 0:o.length)>0&&y.push(Z("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(A=>"text"in A).map(A=>A.text).join(`
|
|
174
174
|
`);T&&y.push(Z("ai.response.reasoning",T));}let S=(i=e.totalUsage)!=null?i:e.usage;S&&y.push(it("ai.usage.inputTokens",S.inputTokens),it("ai.usage.outputTokens",S.outputTokens),it("ai.usage.totalTokens",S.totalTokens),it("ai.usage.reasoningTokens",S.reasoningTokens),it("ai.usage.cachedInputTokens",S.cachedInputTokens)),y.push(it("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,A=(u=e.text)!=null?u:t.accumulatedText||void 0,v=t.inputText,w=(p=e.response)==null?void 0:p.modelId,I={...(m=this.defaultContext)==null?void 0:m.properties,...y.properties},_=(g=y.convoId)!=null?g:(h=this.defaultContext)==null?void 0:h.convoId;this.eventShipper.patch(t.eventId,{eventName:T,userId:S,convoId:_,input:v,output:A,model:w,properties:Object.keys(I).length>0?I:void 0,isPending:false}).catch(R=>{this.debug&&console.warn(`[raindrop-ai/ai-sdk] event patch failed: ${R instanceof Error?R.message:R}`);});}}}finishEmbed(e,t){var n;if(!t.rootSpan)return;let o=[],r=t.operationId==="ai.embedMany";t.recordOutputs&&(r?o.push(Z("ai.embeddings",ut(e.embedding))):o.push(Z("ai.embedding",ut(e.embedding)))),((n=e.usage)==null?void 0:n.tokens)!=null&&o.push(it("ai.usage.tokens",e.usage.tokens)),this.traceShipper.endSpan(t.rootSpan,{attributes:o});}},lwe="__raindrop_report",PX={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"}},cwe="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 df(e){return typeof e!="string"?void 0:e.trim()||void 0}function dwe(e){if(!e)return PX;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?PX:Object.fromEntries(t)}function QX(e){var t,n;let o=dwe(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())||lwe,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-f3),i=Math.min(o.length,n+f3),s=String(i).length,a=[];for(let l=r;l<=i;l++){let c=l===n?eIe:Zwe;a.push(`${c}${String(l).padStart(s)} | ${o[l-1]??""}`);}return a.join(`
|
|
202
202
|
`)}var b3="\r",T3="\x1B[1A",A3="\x1B[J",E3="\x1B[?25l",Jk="\x1B[?25h",iIe="\u28CB\u28D9\u28F9\u28F8\u28FC\u28F4\u28E6\u28E7\u28C7\u28CF",sIe="|/-\\",aIe="\u2736\u2738\u2739\u273A\u2739\u2737",lIe="*",cIe="#0891b2",dIe={pass:{glyph:"\u2713",ascii:"v",paint:(e,t)=>e.green(t)},fail:{glyph:"\u2718",ascii:"x",paint:(e,t)=>e.red(t)},skip:{glyph:"\u2212",ascii:"-",paint:(e,t)=>e.dim(t)},cancel:{glyph:"\u2298",ascii:"o",paint:(e,t)=>e.yellow(t)},retry:{glyph:"\u21BB",ascii:"~",paint:(e,t)=>e.yellow(t)}};function Mn(e){let t=e.colorLevel>0&&(e.isTTY||e.colorForced),n=new Chalk({level:t?e.colorLevel:0}),o=(r,i)=>t?i(n,r):r;return {unicode:e.unicode,color:t,bold:r=>o(r,(i,s)=>i.bold(s)),dim:r=>o(r,(i,s)=>i.gray(s)),code:r=>o(r,(i,s)=>i.hex(cIe)(s)),spinner:r=>{let i=e.unicode?iIe:sIe,s=(r%i.length+i.length)%i.length;return o(i.charAt(s),(a,l)=>a.cyan(l))},classifySpinner:r=>{let i=e.unicode?aIe:lIe,s=(r%i.length+i.length)%i.length;return o(i.charAt(s),(a,l)=>a.cyan(l))},statusGlyph:r=>{let i=dIe[r],s=e.unicode?i.glyph:i.ascii;return t?i.paint(n,s):s},separator:e.unicode?" \xB7 ":" | "}}function C3(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 v3=new Set;function R3(e,t,n=t){v3.has(n)||(v3.add(n),e.warn(t));}var pIe={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}},mIe={PASSED:"PASS",FAILED:"FAIL",CANCELLED:"CANCEL",RETRYING:"RETRY",RUNNING:"RUNNING",SKIP:"SKIP",RUN:"RUNNING",RETRY:"RETRY"};function OT(e,t,n=0){let o=mIe[e];if(!o)return;let r=Mn(t);if(o==="RUNNING")return {badge:r.spinner(n),isTerminal:false};let{glyph:i,isTerminal:s}=pIe[o];return {badge:r.statusGlyph(i),isTerminal:s}}function Rd(e,t){return !t.isTTY||t.colorLevel===0?e:`\x1B]8;;${e}\x07${e}\x1B]8;;\x07`}function w3({parallel:e,remoteBrowser:t}){let n=cpus$1().length;if(t){if(e<=n*4)return;let o=Math.max(1,n*4-2);C.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||C.warn(`Running ${e} workers on a ${n}-core machine. Chrome needs ~2 cores per worker; expect slowdowns.`);}function I3(){let e=lX(),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&&(C.log(""),C.warn(`Machine was under pressure during this run (${t.join(", ")}). Slowdowns and timeouts may be related.`));}var he=rf({app:"cli",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:"3.25.
|
|
204
|
+
`)}var v3=new Set;function R3(e,t,n=t){v3.has(n)||(v3.add(n),e.warn(t));}var pIe={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}},mIe={PASSED:"PASS",FAILED:"FAIL",CANCELLED:"CANCEL",RETRYING:"RETRY",RUNNING:"RUNNING",SKIP:"SKIP",RUN:"RUNNING",RETRY:"RETRY"};function OT(e,t,n=0){let o=mIe[e];if(!o)return;let r=Mn(t);if(o==="RUNNING")return {badge:r.spinner(n),isTerminal:false};let{glyph:i,isTerminal:s}=pIe[o];return {badge:r.statusGlyph(i),isTerminal:s}}function Rd(e,t){return !t.isTTY||t.colorLevel===0?e:`\x1B]8;;${e}\x07${e}\x1B]8;;\x07`}function w3({parallel:e,remoteBrowser:t}){let n=cpus$1().length;if(t){if(e<=n*4)return;let o=Math.max(1,n*4-2);C.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||C.warn(`Running ${e} workers on a ${n}-core machine. Chrome needs ~2 cores per worker; expect slowdowns.`);}function I3(){let e=lX(),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&&(C.log(""),C.warn(`Machine was under pressure during this run (${t.join(", ")}). Slowdowns and timeouts may be related.`));}var he=rf({app:"cli",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:"3.25.1"});var gIe=5,Dm=" ";async function nw({getResults:e,checkDone:t,name:n,timeoutMs:o=18e5}){let r=Date.now(),i=0;for(;Date.now()-r<o;){let s;i>gIe&&(C.error(`Failed to fetch ${n} status too many times.`),process.exit(1));try{s=await e(),i=0;}catch(c){i++,he.warn({err:c},"Failed to fetch run status; retrying."),C.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));}C.error(`Timeout elapsed waiting for ${n} to complete (${Math.floor(o/1e3)}s).`),process.exit(1);}function x3(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 Qk(e){let t=x3(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 pf(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 Zk({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}=x3(e),h=dt(),g=h.unicode?"\u2500":"-",f=process.stdout?.columns||80,y=(S,T,A,v)=>{let w=` ${T+1}) ${n(S)} `,I=Math.max(3,f-w.length-2);C.log(""),C.log(A(`${w}${g.repeat(I)}`)),C.log(""),v();let _=o(S);_&&(C.log(""),C.log(`${Dm}${Rd(_,h)}`));};h3(()=>{d.forEach((_,R)=>{y(_,R,il.red.bold,()=>r?.(_));}),u.forEach((_,R)=>{y(_,d.length+R,il.yellow.bold,()=>{let x=i?.(_)??"Cancelled";C.log(`${Dm}${il.yellow.bold(x)}`);});});let S=(_,R,x)=>{_.length!==0&&(C.log(""),C.log(` ${x(`${_.length} ${R}`)}`),_.forEach(O=>{C.dimmed(`${Dm}${n(O)}`);}));};S(d,"failed",il.red.bold),S(m,"failed",_=>il.red.bold(`${_} (quarantined)`)),S(u,"cancelled",il.yellow.bold),a&&(C.log(""),C.log(` ${il.yellow.bold(`${a} skipped`)}`));let T=c.length+p.length,A=Math.max(1,Math.round((Date.now()-t)/1e3)),v=[];p.length>0&&v.push(`${p.length} quarantined`),s&&s>0&&v.push(`${s} recovered`);let w=v.length>0?` (${v.join(", ")})`:"",I=fIe(e,h,l);C.log(""),C.log(` ${il.green.bold(`${T} passed${w} (${A}s)`)}${I}`),I3();});}function ow(e){return Zk(e),Qk(e.results)}function fIe(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 rw(e){if(!e.failureDetails||!e.failureReason)return;let t=Xl({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;C.log(`${Dm}${il.red.bold(n)}`),o&&o!==n&&(C.log(""),C.log(C3(o,Dm)));let r=y3({failureDetails:e.failureDetails,filePath:e.filePath,results:e.results,beforeResults:e.beforeResults,afterResults:e.afterResults});r&&(C.log(""),C.log(r));let i=e.failureDetails.classification?.citations;if(i&&i.length>0){C.log(""),C.log(`${Dm}${il.bold("Sources:")}`);for(let s of i)C.log(`${Dm} [${s.refId}] ${s.title}`);}}var mf=" ".repeat(6);var yIe=(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);!SIe(r,i)&&o||Object.defineProperty(e,n,i);},SIe=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)},bIe=(e,t)=>{let n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n);},TIe=(e,t)=>`/* Wrapped ${e}*/
|
|
205
205
|
${t}`,AIe=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),EIe=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),vIe=(e,t,n)=>{let o=n===""?"":`with ${n.trim()}() `,r=TIe.bind(null,o,t.toString());Object.defineProperty(r,"name",EIe);let{writable:i,enumerable:s,configurable:a}=AIe;Object.defineProperty(e,"toString",{value:r,writable:i,enumerable:s,configurable:a});};function eD(e,t,{ignoreNonConfigurable:n=false}={}){let{name:o}=e;for(let r of Reflect.ownKeys(t))yIe(e,t,r,n);return bIe(e,t),vIe(e,t,o),e}var iw=new WeakMap,_3=(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(iw.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 eD(i,e),iw.set(i,o),i};_3.callCount=e=>{if(!iw.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return iw.get(e)};var P3=_3;var Fm=[];Fm.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&Fm.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&Fm.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var sw=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",tD=Symbol.for("signal-exit emitter"),nD=globalThis,CIe=Object.defineProperty.bind(Object),oD=class{emitted={afterExit:false,exit:false};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(nD[tD])return nD[tD];CIe(nD,tD,{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}},aw=class{},RIe=e=>({onExit(t,n){return e.onExit(t,n)},load(){return e.load()},unload(){return e.unload()}}),rD=class extends aw{onExit(){return ()=>{}}load(){}unload(){}},iD=class extends aw{#s=sD.platform==="win32"?"SIGINT":"SIGHUP";#n=new oD;#e;#r;#p;#t={};#i=false;constructor(t){super(),this.#e=t,this.#t={};for(let n of Fm)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(!sw(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 Fm)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,Fm.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 sw(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"&&sw(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)}},sD=globalThis.process,{onExit:O3}=RIe(sw(sD)?new iD(sD):new rD);var M3=pl.stderr.isTTY?pl.stderr:pl.stdout.isTTY?pl.stdout:void 0,wIe=M3?P3(()=>{O3(()=>{M3.write("\x1B[?25h");},{alwaysLast:true});}):()=>{},N3=wIe;var cw=false,hf={};hf.show=(e=pl.stderr)=>{e.isTTY&&(cw=false,e.write("\x1B[?25h"));};hf.hide=(e=pl.stderr)=>{e.isTTY&&(N3(),cw=true,e.write("\x1B[?25l"));};hf.toggle=(e,t)=>{e!==void 0&&(cw=e),cw?hf.show(t):hf.hide(t);};var aD=hf;var NT=mM(lD());function cD(){return pl.platform!=="win32"?pl.env.TERM!=="linux":!!pl.env.CI||!!pl.env.WT_SESSION||!!pl.env.TERMINUS_SUBLIME||pl.env.ConEmuTask==="{cmd::Cmder}"||pl.env.TERM_PROGRAM==="Terminus-Sublime"||pl.env.TERM_PROGRAM==="vscode"||pl.env.TERM==="xterm-256color"||pl.env.TERM==="alacritty"||pl.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var xIe={info:il.blue("\u2139"),success:il.green("\u2714"),warning:il.yellow("\u26A0"),error:il.red("\u2716")},_Ie={info:il.blue("i"),success:il.green("\u221A"),warning:il.yellow("\u203C"),error:il.red("\xD7")},PIe=cD()?xIe:_Ie,MT=PIe;function dD({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 OIe=dD();function uD(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return !e.includes("\x1B")&&!e.includes("\x9B")?e:e.replace(OIe,"")}function pD({stream:e=process.stdout}={}){return !!(e&&e.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}function mD(){let{env:e}=pl,{TERM:t,TERM_PROGRAM:n}=e;return pl.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 MIe=3,hD=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(){pl.platform==="win32"||!pl.stdin.isTTY||(pl.stdin.setRawMode(true),pl.stdin.on("data",this.#r),pl.stdin.resume());}#e(){pl.stdin.isTTY&&(pl.stdin.off("data",this.#r),pl.stdin.pause(),pl.stdin.setRawMode(false));}#r(t){t[0]===MIe&&pl.emit("SIGINT");}},NIe=new hD,gD=NIe;mM(lD());var fD=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:pl.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:pD({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,pl.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(!mD())this.#i=NT.default.line;else if(t===void 0)this.#i=NT.default.dots;else if(t!=="default"&&NT.default[t])this.#i=NT.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 uD(r).split(`
|
|
206
206
|
`))this.#e+=Math.max(1,Math.ceil(A9(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=il[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&&aD.hide(this.#o),this.#t.discardStdin&&pl.stdin.isTTY&&(this.#n=true,gD.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&&aD.show(this.#o),this.#t.discardStdin&&pl.stdin.isTTY&&this.#n&&(gD.stop(),this.#n=false),this):this}succeed(t){return this.stopAndPersist({symbol:MT.success,text:t})}fail(t){return this.stopAndPersist({symbol:MT.error,text:t})}warn(t){return this.stopAndPersist({symbol:MT.warning,text:t})}info(t){return this.stopAndPersist({symbol:MT.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+`
|
|
@@ -258,7 +258,7 @@ ${z$1.prettifyError(s)}`:`: ${q(s)}`;C.warn(`Project config at ${e} does not mat
|
|
|
258
258
|
${r.map(i=>i.configFilePath).join(`
|
|
259
259
|
`)}`);if(r.length===0)throw new Oe(`No valid Momentic project file (${Da}) was found in the current directory or any parent directory. Run this command from inside your Momentic project, or pass the '-c / --config' flag pointing at your ${Da}.`);return C.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}async function YOe(e){let t=qOe(e);if(!t||!t.projects||!t.projects.length)return;let n=t.projects.map(s=>(s.endsWith("/")||(s+="/"),`${s}*${Da}`)),o=AbortSignal.timeout(2e3),r;try{r=await kd(n,{cwd:cwd(),maxDepth:lA,ignore:[],nodir:!0,signal:o});}catch(s){throw C.error({err:s},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${dA} is misconfigured.`),s}let i=[];for(let s of r){let a=io__default.join(cwd(),s),l=TF(a);l&&i.push({configFilePath:a,config:l,rootDir:dirname(a)});}return i}async function AF(e,t){if(e){e=io__default.resolve(e);let o=TF(e);return o?[{config:o,configFilePath:e,rootDir:io__default.dirname(e)}]:(console.error(`No valid Momentic project file found at ${e}.`),t||process.exit(1),[])}if(existsSync(dA)){let o=await YOe(dA);if(o)return o}return KOe()}function Fd(e,t){let n=PT.stringify(e);writeFileSync(t,n);}async function qi({project:e,apiClient:t,classificationOverrides:n}){let{classification:o,healing:r,explore:i}=(await t.getOrgSettings()).ai??{},s=XOe({flags:n,config:e.config.ai?.classification,cloudConfig:o}),a=JOe({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 JOe({config:e,cloudConfig:t}){if(!(!e&&!t))return {onHealFail:e?.onHealFail??t?.onFail??fM,onHealSuccess:e?.onHealSuccess??t?.onSuccess??yM,remoteBrowser:e?.remoteBrowser,requestCommitAuthorsAsReviewers:e?.requestCommitAuthorsAsReviewers??t?.requestCommitAuthorsAsReviewers}}function XOe({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??H$,categories:n?.categories??is}}var xZ="golden/visual-diff",_Z="reports",Sl="test-results";var QOe=z$1.object({width:z$1.number(),height:z$1.number()}),Kf=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;apiClient;constructor(t,n,o){let r=io__default.join(t.rootDir,t.config.goldenFileDir??xZ);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=o,this.apiClient=n;}async prepareGoldenScreenshotForComparison(t,n,o){if(RV(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=io__default.join(this.defaultGoldenScreenshotDir,`${n.id}.jpg`));let i=`${r}.metadata.json`;if(this.regenerateGoldenFiles)return ko__default.mkdirSync(io__default.dirname(r),{recursive:true}),ko__default.writeFileSync(r,o.buffer),ko__default.writeFileSync(i,JSON.stringify({width:o.width,height:o.height})),{buffer:Buffer.from(o.buffer),width:o.width,height:o.height};if(ko__default.existsSync(r)){let s=ko__default.readFileSync(r),a=QOe.parse(JSON.parse(ko__default.readFileSync(i,"utf-8")));return {buffer:s,width:a.width,height:a.height}}else throw new oe("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${r}`)}};var PZ=3e3,yn=uA(),tMe=promisify(execFile);async function RF(e,t){try{return await uA(e).revparse(t)}catch(n){if(NZ(n))return;throw n}}async function Bd(e){return RF(e,["--show-toplevel"])}async function OZ(e){return RF(e,["HEAD"])}async function MZ(e){return RF(e,["--abbrev-ref","HEAD"])}async function fI({cwd:e,base:t,head:n,logger:o}){try{let r=(await uA(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 wF(){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 pA({client:e,repository:t,base:n,head:o,logger:r}){let i=gr(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 Fa(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>PZ&&!process.env.CI&&t.warn({operation:n,durationMs:s,thresholdMs:PZ,...r??{}},"[timing] slow git metadata operation");}}function Ic(e){if(e)try{let t=new Date(e);return isNaN(t.getTime())?void 0:t}catch{return}}async function nMe(e){let t=await An(e,yn.raw(["config","--list"])),n={};if(!t)return n;for(let o of t.split(`
|
|
260
260
|
`)){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 oMe(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 tMe("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 rMe(e,t,n){let o=t?.includes("github.com"),r=t?.includes("gitlab.com");try{if(o)return oMe(e,t,n);if(r)return}catch{}}function mA(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 NZ(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 An(e,t){try{return (await t).trim()}catch(n){if(NZ(n))return;e.error({err:n},"Failed to run git command");return}}async function Ba(e,t){if(e)try{return (await uA(t).revparse([e]))?.trim()||void 0}catch{return}}async function hA(e){let t=await Ba(e);return t||await Ba(`origin/${e}`)}function iMe(){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 sMe(e){let[t,n,o]=await Promise.all([An(e,yn.show(["--no-patch","--format=%ci"])),An(e,yn.show(["-s","--pretty=%B"])),An(e,yn.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?Ic(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 aMe(e){let[t,n,o]=await Promise.all([An(e,yn.listRemote(["--get-url","origin"])),An(e,yn.show(["-s","--pretty=%B"])),An(e,yn.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?Ic(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 lMe(e){let[t,n,o,r]=await Promise.all([An(e,yn.show(["--no-patch","--format=%ci"])),An(e,yn.listRemote(["--get-url","origin"])),An(e,yn.show(["-s","--pretty=%B"])),An(e,yn.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?mA(s):void 0;return {ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:t?Ic(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 cMe(e){let[t,n,o]=await Promise.all([An(e,yn.show(["--no-patch","--format=%ci"])),An(e,yn.show(["-s","--pretty=%B"])),An(e,yn.show(["-s","--pretty=%an"]))]),r=process.env.BUILDKITE_REPO,i=r?.includes("github.com"),s=r?.includes("gitlab.com"),a=r?mA(r):void 0;return {ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:t?Ic(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 dMe(e){let[t,n,o]=await Promise.all([An(e,yn.show(["--no-patch","--format=%ci"])),An(e,yn.show(["-s","--pretty=%B"])),An(e,yn.show(["-s","--pretty=%an"]))]),r=process.env["Build.Repository.Uri"],i=r?.includes("github.com"),s=r?.includes("gitlab.com"),a=r?mA(r):void 0;return {ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:t?Ic(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 uMe(e,t,n){let[o,r,i,s,a,l,c,d,u]=await Promise.all([An(e,yn.revparse(["HEAD"])),An(e,yn.revparse(["--short","HEAD"])),An(e,yn.revparse(["--abbrev-ref","HEAD"])),An(e,yn.listRemote(["--get-url","origin"])),An(e,yn.show(["--no-patch","--format=%ci"])),An(e,yn.show(["-s","--pretty=%B"])),An(e,yn.show(["-s","--pretty=%an"])),t?An(e,yn.raw(["merge-base","--fork-point",t])):Promise.resolve(void 0),nMe(e)]),p=d||(t?await An(e,yn.raw(["merge-base",t,"HEAD"])):void 0),m=p?await An(e,yn.show(["--no-patch","--format=%ci",p])):void 0,h=s?.includes("github.com"),g=s?.includes("gitlab.com"),f=s?mA(s):void 0,y=u["user.email"]||void 0,S=u["user.name"]||void 0,T=u["user.username"]||void 0,A=u["github.user"]||void 0,I=(n?.includeHostingUsername??true?await rMe(e,s,u):void 0)??T??A??void 0;return {ciProvider:"none",gitCommitSha:o,gitCommitShaShort:r,gitBranchName:i,gitOriginUrl:s,gitCommitTimestamp:a?Ic(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:I,gitLocalEmail:y,gitLocalName:S,lastCommitOnMainSha:p,lastCommitOnMainTimestamp:m?Ic(m):void 0,githubRepository:h?f:void 0,gitlabProjectPath:g?f:void 0,pipelineId:void 0}}async function pMe(e){let[t,n]=await Promise.all([An(e,yn.show(["--no-patch","--format=%ci"])),An(e,yn.show(["-s","--pretty=%an"]))]),o=process.env.GIT_REPOSITORY_URL,r=o?.includes("github.com"),i=o?.includes("gitlab.com"),s=o?mA(o):void 0;return {ciProvider:"Bitrise",gitCommitSha:process.env.BITRISE_GIT_COMMIT,gitCommitShaShort:process.env.BITRISE_GIT_COMMIT?.slice(0,6),gitCommitTimestamp:t?Ic(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 mMe(){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 hMe(){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:Ic(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:Ic(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 gMe(e){let t=[...e.config.gitProtectedBranches??[]];return e.config.gitMainBranch&&t.push(e.config.gitMainBranch),{gitMainBranch:e.config.gitMainBranch,gitProtectedBranches:t}}async function Ua(e,t,n){let o=iMe();if(!o)return uMe(e,t,n);switch(o){case "GithubActions":return sMe(e);case "GitlabCI":return aMe(e);case "CircleCI":return lMe(e);case "Buildkite":return cMe(e);case "AzureDevOps":return dMe(e);case "GCPCloudBuild":return mMe();case "Bitrise":return pMe(e);case "Custom":return hMe()}}async function fMe(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 Fa({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 Fa({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 Fa({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 yMe(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 Fa({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 Fa({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 Fa({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 SMe(e,t,n){try{if(n.githubRepository){let{owner:o,repo:r}=Wq(n.githubRepository);return await Fa({logger:e,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitHub",fn:()=>yMe(e,t,o,r,n),context:{githubRepository:n.githubRepository}})}else if(n.gitlabProjectPath){let o=n.gitlabProjectPath;return await Fa({logger:e,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitlab",fn:()=>fMe(e,t,o,n),context:{gitlabProjectPath:o}})}}catch(o){e.warn({err:o},"Failed to get remote git metadata");}return n}async function bMe(e,t,n,o){let r={},i={gitMainBranch:n.config.gitMainBranch};return Fa({logger:e,operation:"getGitMetadata.total",fn:async()=>{let[s,a]=await Promise.all([Fa({logger:e,operation:"getGitMetadata.getConfiguredGitMetadata",fn:()=>gMe(n),context:{projectConfigPath:n.configFilePath}}),Fa({logger:e,operation:"getGitMetadata.getEnvironmentGitMetadata",fn:async()=>{let d=await Ua(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 Fa({logger:e,operation:"getGitMetadata.getRemoteMetadataIfNeeded",fn:()=>SMe(e,t,l),context:{githubRepository:l.githubRepository,gitlabProjectPath:l.gitlabProjectPath,gitBranchName:l.gitBranchName}});return {...s,...a,...c}},context:r})}async function LZ(e){try{let t=await uA(e).remote(["show","origin"]);return t?t.match(/HEAD branch: (.*)$/m)?.[1]?.trim():void 0}catch{return}}async function kZ(){try{return (await yn.revparse(["--is-inside-work-tree"])).trim()==="true"}catch{return false}}var CF=new Map;async function TMe(e,t,n){let o,r;try{[o,r]=await Promise.all([An(e,yn.raw(["symbolic-ref","--short","-q","HEAD"]).then(a=>a.trim())),An(e,yn.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 Mr(e,t,n,o){let r=await TMe(e,n,o);if(r&&CF.has(r))return e.debug("Using cached git metadata"),CF.get(r);let i=await bMe(e,t,n,o);return r&&CF.set(r,i),i}var AMe=1024*1024;async function SI({cwd:e,baseRef:t="HEAD"}){let n=uA(await Jf(e)),[o,r]=await Promise.all([n.diff(["--name-only","--diff-filter=ACDMRTUXB",t,"--"]),n.raw(["ls-files","--others","--exclude-standard"])]);return EMe(TI([...DZ(o),...DZ(r)]))}function EMe(e){return e.filter(xF)}function xF(e){let t=bl.basename(e);return e.endsWith(".test.yaml")||e.endsWith(".module.yaml")||t===Da||t===dA}async function bI({cwd:e,paths:t,maxFileSizeBytes:n=AMe}){let o=await Jf(e),r=[];for(let i of TI(t)){let s=HZ({repoRoot:o,relativePath:i});if(!xF(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 FZ({cwd:e}){let t=await Jf(e),n=await promises.mkdtemp(bl.join(IF.tmpdir(),"momentic-git-snapshot-"));try{let o=uA(t).env("GIT_INDEX_FILE",bl.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 Yf({cwd:e,paths:t,baseRef:n="HEAD",maxFileSizeBytes:o}){let r=await Jf(e),i=TI(t??await SI({cwd:r,baseRef:n}));if(i.length===0)return "";let a=(await bI({cwd:r,paths:i,maxFileSizeBytes:o})).filter(c=>c.operation==="upsert").map(c=>c.path),l=await promises.mkdtemp(bl.join(IF.tmpdir(),"momentic-git-patch-"));try{let c=uA(r).env("GIT_INDEX_FILE",bl.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 BZ({cwd:e,patch:t}){let n=await Jf(e),o=await promises.mkdtemp(bl.join(IF.tmpdir(),"momentic-git-apply-")),r=bl.join(o,"heal.patch");try{await promises.writeFile(r,t,"utf8");let i=uA(n),s=vMe(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(HZ({repoRoot:n,relativePath:a}),!xF(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 UZ({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 Jf(e),f=await bI({cwd:g,paths:t??await SI({cwd:g,baseRef:o}),maxFileSizeBytes:h}),y=n??await MZ(g);if(!y)throw new Oe(`Cannot determine base branch because git is not usable in '${g}'.`);let S=o??await OZ(g);if(!S)throw new Oe(`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 DZ(e){return e?e.split(`
|
|
261
|
-
`).filter(t=>t.length>0):[]}function TI(e){return [...new Set(e)]}function vMe(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 TI(n)}async function Jf(e){let t=await Bd(e);if(!t)throw new Oe(`Cannot find a git repository at '${e}'. Install git and run this from inside a git worktree.`);return t}function HZ({repoRoot:e,relativePath:t}){if(!t||bl.isAbsolute(t)||t.includes("\0"))throw new Error(`Unsafe pull request path: ${t}`);let n=bl.resolve(e),o=bl.resolve(n,t);if(o!==n&&!o.startsWith(`${n}${bl.sep}`))throw new Error(`Pull request path escapes repository root: ${t}`);return o}var jZ=new Set([".DS_Store","__MACOSX"]),GZ={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 RMe(e,t,n){if(GZ[n]){let i=GZ[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 _F=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 $Z(e,t){try{let n=io__default.join(t,ct);return _a.parse(JSON.parse(ko__default.readFileSync(n,"utf-8")))}catch{throw new _F(e,t)}}function VZ(e,t,n){let o=randomUUID(),r=e.child({runGroupId:o});ko__default.rmSync(t,{recursive:true,force:true});let i=ko__default.readdirSync(n).filter(l=>!jZ.has(l)).map(l=>io__default.join(n,l));if(i.length===0)throw new Error(`No run groups found in results path: ${n}`);ko__default.mkdirSync(t,{recursive:true});let s={...$Z(n,i[0]),id:o,healRiskSummary:void 0,aiSelect:void 0};for(let l of i){let c=io__default.join(l,po);if(!ko__default.existsSync(c))continue;let d=$Z(n,l);r.info({oldRunGroupId:d.id},"Merging run groups");for(let p in d){if(p==="id")continue;let m=p;s[m]=RMe(s,d,m);}let u=ko__default.readdirSync(c);for(let p of u){if(jZ.has(p))continue;let m=io__default.join(c,p),h=io__default.join(t,po,p);ko__default.cpSync(m,h,{recursive:true});}}let a=io__default.join(t,ct);ko__default.writeFileSync(a,JSON.stringify(s,null,2));}var ye="v1",PF="cli",Xm="3.25.
|
|
261
|
+
`).filter(t=>t.length>0):[]}function TI(e){return [...new Set(e)]}function vMe(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 TI(n)}async function Jf(e){let t=await Bd(e);if(!t)throw new Oe(`Cannot find a git repository at '${e}'. Install git and run this from inside a git worktree.`);return t}function HZ({repoRoot:e,relativePath:t}){if(!t||bl.isAbsolute(t)||t.includes("\0"))throw new Error(`Unsafe pull request path: ${t}`);let n=bl.resolve(e),o=bl.resolve(n,t);if(o!==n&&!o.startsWith(`${n}${bl.sep}`))throw new Error(`Pull request path escapes repository root: ${t}`);return o}var jZ=new Set([".DS_Store","__MACOSX"]),GZ={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 RMe(e,t,n){if(GZ[n]){let i=GZ[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 _F=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 $Z(e,t){try{let n=io__default.join(t,ct);return _a.parse(JSON.parse(ko__default.readFileSync(n,"utf-8")))}catch{throw new _F(e,t)}}function VZ(e,t,n){let o=randomUUID(),r=e.child({runGroupId:o});ko__default.rmSync(t,{recursive:true,force:true});let i=ko__default.readdirSync(n).filter(l=>!jZ.has(l)).map(l=>io__default.join(n,l));if(i.length===0)throw new Error(`No run groups found in results path: ${n}`);ko__default.mkdirSync(t,{recursive:true});let s={...$Z(n,i[0]),id:o,healRiskSummary:void 0,aiSelect:void 0};for(let l of i){let c=io__default.join(l,po);if(!ko__default.existsSync(c))continue;let d=$Z(n,l);r.info({oldRunGroupId:d.id},"Merging run groups");for(let p in d){if(p==="id")continue;let m=p;s[m]=RMe(s,d,m);}let u=ko__default.readdirSync(c);for(let p of u){if(jZ.has(p))continue;let m=io__default.join(c,p),h=io__default.join(t,po,p);ko__default.cpSync(m,h,{recursive:true});}}let a=io__default.join(t,ct);ko__default.writeFileSync(a,JSON.stringify(s,null,2));}var ye="v1",PF="cli",Xm="3.25.1";var wMe=9e4,IMe=3,xMe=1500,_Me=15e3,mo=class extends Error{status;rawError;constructor(t,n,o,r={}){super(o,r),this.status=t,this.rawError=n;}},OF=class extends Oe{constructor(t,n={}){super(t,n),this.name="PlanLimitExceededError";}};async function PMe(e){return e.text().then(t=>{try{return JSON.parse(t).error}catch{return t}})}var MF=class{baseUrl;logger;constructor(t){this.baseUrl=t.baseUrl,this.logger=t.logger;}getHeaders(){let t={"Content-Type":"application/json"};return (t[gR]=Xm),(t[kY]=PF),t}async sendRequest(t,n){let{retries:o=IMe,requestTimeoutMs:r=wMe,initialRetryDelayMs:i=xMe,maxRetryDelayMs:s=_Me,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 mo&&p.status>=400&&p.status<500)throw p.status===402?new OF(p.rawError,{cause:p}):p;if(p instanceof Error&&p.name==="AbortError"&&(d=new zu),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 PMe(d);throw new mo(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);}}},Ki=class extends MF{apiKey;mode;runner;constructor(t){super(t),this.apiKey=t.apiKey,this.mode=t.mode,this.runner=t.runner,C.addRedactedValue(t.apiKey);}getHeaders(){return {...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[LY]:this.mode,[fR]:this.runner}}};var AI=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 NF(e){}function zZ(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=NF,onError:n=NF,onRetry:o=NF,onComment:r}=e,i="",s=true,a,l="",c="";function d(g){let f=s?g.replace(/^\xEF\xBB\xBF/,""):g,[y,S]=OMe(`${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}
|
|
262
262
|
`;break;case "id":a=f.includes("\0")?void 0:f;break;case "retry":/^\d+$/.test(f)?o(parseInt(f,10)):n(new AI(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:y}));break;default:n(new AI(`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(`
|
|
263
263
|
`)?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 OMe(e){let t=[],n="",o=0;for(;o<e.length;){let r=e.indexOf("\r",o),i=e.indexOf(`
|
|
264
264
|
`,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]===`
|
|
@@ -291,7 +291,7 @@ ${t}:`]}}function t8({id:e,model:t,created:n}){return {id:e??void 0,modelId:t??v
|
|
|
291
291
|
`,nFe=1e4,E8=P__default.object({stream:P__default.boolean().optional(),type:P__default.literal("response.create").optional()}).passthrough(),oFe=E8.extend({stream:P__default.literal(true)});function v8(e={}){let t=new gB(e);return async(n,o)=>{if(!sFe(n,o))return fetch(n,o);let r=await rFe(o?.body);if(!r)return fetch(n,o);let i=oFe.safeParse(r);return i.success?t.fetch({httpUrl:C8(n),init:o,request:i.data}):fetch(n,o)}}var gB=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===hB.OPEN?this.websocket:this.openPromise?this.openPromise:(this.openPromise=new Promise((o,r)=>{let i=new hB(aFe(t),{headers:lFe(n?.headers)}),s=setTimeout(()=>{i.terminate(),r(new Error("Timed out opening OpenAI responses websocket"));},nFe);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"};uFe({payload:i,compactThreshold:this.options.compactThreshold});let s=Array.isArray(t.input)?t.input:void 0,a=this.latestResponseId&&s&&this.previousFullInput?cFe({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=mFe(t),r;try{r=JSON.parse(o);}catch(a){n.controller.error(a),this.pendingRequest=void 0,this.websocket?.close();return}let i=eq.safeParse(r),s=i.success?i.data:void 0;if(pFe(s)&&n.sentContinuation&&!n.startedStreaming&&!n.retryingFullContext&&this.websocket?.readyState===hB.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(hFe(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(tFe)),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 rFe(e){let t=await iFe(e);if(!t)return;let n=E8.safeParse(JSON.parse(t));return n.success?n.data:void 0}async function iFe(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 sFe(e,t){return (t?.method??(e instanceof Request?e.method:"GET")).toUpperCase()==="POST"&&C8(e).endsWith("/responses")}function C8(e){return e instanceof Request?e.url:e.toString()}function aFe(e){let t=new URL(e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function lFe(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 cFe({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(dFe)}function dFe(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 uFe({payload:e,compactThreshold:t}){t&&(e.context_management=[{type:"compaction",compact_threshold:t}]);}function pFe(e){return e?.type==="error"&&e.code==="previous_response_not_found"}function mFe(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 hFe(e){return new TextEncoder().encode(`data: ${e}
|
|
292
292
|
|
|
293
293
|
`)}function R8(e){return async(t,n)=>{let o=yFe(n?.body);if(!o)return fetch(t,n);let r=e?.priorityServiceTier===true,i=e?.promptCacheKey;fFe(o),r&&(o.service_tier="priority"),i&&(o.prompt_cache_key=i);let s=await fetch(t,{...n,body:JSON.stringify(o)});return SFe({capturePath:e?.requestCapturePath,input:t,status:s.status,body:o}),s}}function fFe(e){if(e.store!==false)return;let t="reasoning.encrypted_content",n=e.include;if(!Array.isArray(n)){e.include=[t];return}n.includes(t)||(e.include=[...n,t]);}function yFe(e){if(typeof e=="string")try{let t=JSON.parse(e);return w8(t)?t:void 0}catch{return}}function SFe({capturePath:e,input:t,status:n,body:o}){e&&appendFileSync(e,`${JSON.stringify({url:TFe(t),status:n,request:bFe(o)})}
|
|
294
|
-
`);}function bFe(e){let t=e.reasoning,n=e.include;return {model:e.model,service_tier:e.service_tier,prompt_cache_key:e.prompt_cache_key,include:Array.isArray(n)?n.filter(o=>typeof o=="string"):void 0,reasoning:w8(t)?{effort:t.effort}:void 0,hasInput:!!e.input,toolsCount:Array.isArray(e.tools)?e.tools.length:0}}function w8(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function TFe(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}var EFe="MOMENTIC_OPENAI_RESPONSES_WEBSOCKET_COMPACT_THRESHOLD",vFe=2e5;function iy(e){let{apiKey:t,sessionId:n,loggerTags:o,runner:r,parentTraceId:i}=e,s={Authorization:`Bearer ${t}`,[gR]:Xm,...n&&{[FY]:n},...r&&{[fR]:r},...i&&{[BY]:i},...o&&{[DY]: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 I8="bedrock/",x8="azure/",_8=e=>t=>{let n=iy(e),o=`${e.baseUrl}/v1/llm/anthropic/${encodeURIComponent(t)}`;return t.startsWith(I8)?o=`${e.baseUrl}/v1/llm/provider/bedrock/anthropic/${encodeURIComponent(t.slice(I8.length))}`:t.startsWith(x8)&&(o=`${e.baseUrl}/v1/llm/provider/foundry/anthropic/${encodeURIComponent(t.slice(x8.length))}`),createAnthropic({baseURL:o,headers:n,apiKey:e.apiKey})(t)},P8=e=>t=>{let n=iy(e),o=e.useOpenAIResponsesWebSocket??false,r=o?e.openAIResponsesWebSocketCompactThreshold??CFe(process.env[EFe])??vFe:void 0;return ry({baseURL:`${e.baseUrl}/v1/llm/provider/openai/${t}`,headers:n,apiKey:e.apiKey,fetch:o?v8({compactThreshold:r}):void 0})(t)},O8=e=>t=>{let n=iy(e);return ry({baseURL:`${e.baseUrl}/v1/llm/provider/xai/${t}`,headers:n,apiKey:e.apiKey,fetch:R8(e.xai)})(t)},M8=e=>t=>{let n=iy(e);return ry({baseURL:`${e.baseUrl}/v1/llm/provider/azure/${t}`,headers:n,apiKey:e.apiKey})(t)};function fB(e){return t=>n=>{let o=iy(t);return ry({baseURL:`${t.baseUrl}/v1/llm/provider/${e}/${n}`,headers:o,apiKey:t.apiKey}).chat(n)}}var N8=fB("azure/deepseek"),L8=fB("azure/kimi"),k8=fB("fireworks/glm"),D8=e=>t=>{let n=iy(e);return tB({baseURL:`${e.baseUrl}/v1/llm/provider/vertex`,headers:n,apiKey:e.apiKey})(t)};function CFe(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}var qo=class extends Ki{agentConfig;constructor(t,n){let o={...ku,...t};MC(o),super(n),this.agentConfig=o;}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(t,n){let o={...t,loggerTags:n.loggerTags},r=await this.sendRequest(`/${ye}/web-agent/recommend-chunks-ai`,{method:"POST",body:o,signal:n.abortSignal});return MW.parse(r)}async rankChunksWithRag(t,n){let o=await this.sendRequest(`/${ye}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Xm,...t},signal:n.abortSignal});return OW.parse(o)}async getScreenshotFromS3(t){let n=await this.sendRequest(`/${ye}/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(`/${ye}/web-agent/locate-element`,{method:"POST",body:o,signal:n.abortSignal});return GY.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(`/${ye}/web-agent/assertion`,{method:"POST",body:o,signal:n.abortSignal});return UL.parse(r)}async getLintStepResult(t,n){let o={...t,disableCache:!!n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${ye}/web-agent/lint/step`,{method:"POST",body:o,signal:n.abortSignal});return jY.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(`/${ye}/web-agent/visual-assertion`,{method:"POST",body:o,signal:n.abortSignal});return UL.parse(r)}async getAiActionCommand(t,n){let o=await this.sendRequest(`/${ye}/web-agent/next-command-dynamic`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return HY.parse(o)}async getMultiturnAiActionCommand(t,n){return await this.sendRequest(`/${ye}/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(`/${ye}/web-agent/ai-action/evaluate`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return cN.parse(o)}async getReverseMappedDescription(t,n){let o=await this.sendRequest(`/${ye}/web-agent/reverse-mapped-description`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return $Y.parse(o)}async getTextExtraction(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},r=await this.sendRequest(`/${ye}/web-agent/text-extraction`,{method:"POST",body:o,signal:n.abortSignal});return lN.parse(r)}async getPageSummary(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${ye}/web-agent/page-summary`,{method:"POST",body:o,signal:n.abortSignal});return $z.parse(r)}async getSmartWaitingDecision(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${ye}/web-agent/smart-waiting`,{method:"POST",body:o,signal:n.abortSignal});return Vz.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(`/${ye}/web-agent/result-classification`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return Uv.parse(o)}async getExtractedKeywords(t,n){let o=await this.sendRequest(`/${ye}/web-agent/extract-keywords`,{method:"POST",body:t,signal:n.abortSignal});return VW.parse(o)}async getAutohealingProposal(t,n){let o=await this.sendRequest(`/${ye}/web-agent/autoheal-section`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return Bz.parse(o)}async getFailureRecoveryProposal(t,n){let o=await this.sendRequest(`/${ye}/web-agent/failure-recovery`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return jz.parse(o)}async getFailureRecoveryPlan(t,n){let o=await this.sendRequest(`/${ye}/web-agent/failure-recovery-plan`,{method:"POST",body:{...t,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["failure-recovery"]},signal:n.abortSignal});return Hz.parse(o)}async getIframeRegex(t,n){let o=await this.sendRequest(`/${ye}/web-agent/iframe-regex`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return fz.parse(o)}createAgentTrace(t){let n=randomUUID(),{completionType:o,runId:r,orgId:i,logger:s}=t,a=async l=>{try{await this.sendRequest(`/${ye}/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(_8,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 P8({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...Wt(o),promptType:r},sessionId:n,useOpenAIResponsesWebSocket:i,runner:this.runner,parentTraceId:s})}getXAIModelFactory(t){return this.buildModelFactory(O8,t)}getAzureOpenAIModelFactory(t){return this.buildModelFactory(M8,t)}getAzureDeepSeekModelFactory(t){return this.buildModelFactory(N8,t)}getAzureKimiModelFactory(t){return this.buildModelFactory(L8,t)}getFireworksGLMModelFactory(t){return this.buildModelFactory(k8,t)}getVertexGeminiModelFactory(t){return this.buildModelFactory(D8,t)}buildModelFactory(t,n){let{sessionId:o,logger:r,streamType:i,parentTraceId:s,xai:a}=n;return t({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...Wt(r),promptType:i},sessionId:o,runner:this.runner,parentTraceId:s,xai:a})}};function bA(e,t,n){return fetch(e,{method:"PUT",body:n,headers:{"Content-Type":t}})}var xt=class extends Ki{getAppUrl(){return ef(this.baseUrl)}async getAuthInfo(){let t;try{t=await this.sendRequest(`/${ye}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});}catch(n){throw n instanceof mo?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 rJ.parse(t)}async getCliAnnouncements(){let t=await this.sendRequest(`/${ye}/announcements`,{method:"GET",retries:1,requestTimeoutMs:5e3});return wq.parse(t).announcements}async getQuotaStatus(){let t=await this.sendRequest(`/${ye}/billing/check-quota`,{method:"GET",retries:3,requestTimeoutMs:5e3});return iJ.parse(t)}async createRemoteBrowserConnection(t){let n=process.env.MOMENTIC_BROWSER_VENDOR_OVERRIDE,o=await this.sendRequest(`/${ye}/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}:{}},extraHeaders:n?{[UY]:n}:void 0,retries:3,requestTimeoutMs:1e4});return CJ.parse(o)}async bulkGetRunStatus(t){let n=await this.sendRequest(`/${ye}/runs/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return ZY.parse(n)}async getRunExport(t){let n=await this.sendRequest(`/${ye}/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tJ.parse(n)}submitInteractiveAgentFeedback(t){try{this.sendRequest(`/${ye}/traces/interactive-agent-feedback`,{method:"POST",body:t,retries:1,requestTimeoutMs:2e3}).catch(n=>{});}catch(n){}return Promise.resolve()}async getResultClassificationCacheEntries(t){let n=await this.sendRequest(`/${ye}/result-classification-cache`,{method:"POST",body:t,retries:1,requestTimeoutMs:1e4});return MJ.parse(n)}async createResultClassificationCacheEntries(t){await this.sendRequest(`/${ye}/result-classification-cache`,{method:"PATCH",body:t,retries:1,requestTimeoutMs:1e4});}async saveRunClassification(t,n){await this.sendRequest(`/${ye}/runs/${encodeURIComponent(t)}/classification`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async uploadRunHealTraceZip(t,n){let o=await this.sendRequest(`/${ye}/runs/${encodeURIComponent(t)}/heal-trace/upload-url`,{method:"POST",retries:3,requestTimeoutMs:1e4}),{uploadUrl:r}=SR.parse(o),i=await bA(r,"application/zip",n);if(!i.ok)throw new Error(`Failed to upload heal trace: ${await i.text()}`)}async saveRunHealMetadataBatch(t){await this.sendRequest(`/${ye}/runs/heal-metadata`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4});}async getTestYAMLExport(t){let n=await this.sendRequest(`/${ye}/tests/export`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return zY.parse(n)}async updateStepCaches(t,n){await this.sendRequest(`/${ye}/cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async updateSnapshotCaches(t,n){await this.sendRequest(`/${ye}/snapshot-cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getStepCacheForTest(t,n){let o=await this.sendRequest(`/${ye}/cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return qY.parse(o)}async getSnapshotCacheForTest(t,n){let o=await this.sendRequest(`/${ye}/snapshot-cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return KY.parse(o)}async deleteStepCacheEntry(t,n){await this.sendRequest(`/${ye}/cache/entry`,{method:"DELETE",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4});}async getWebStepCacheMemoryTraces(t){let n=await this.sendRequest(`/${ye}/cache/traces`,{method:"POST",body:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return HL.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(`/${ye}/${this.cacheRouteForPlatform(t)}/entry`,{method:"DELETE",body:n,extraHeaders:o,retries:3,requestTimeoutMs:1e4});}async getMobileStepCacheMemoryTraces(t,n){let o=await this.sendRequest(`/${ye}/${this.cacheRouteForPlatform(t)}/traces`,{method:"POST",body:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return HL.parse(o)}async updateMobileStepCaches(t){await this.sendRequest(`/${ye}/${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(`/${ye}/${this.cacheRouteForPlatform(t)}`,{method:"POST",body:n,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return YY[t](r)}async queueTests(t){let n=await this.sendRequest(`/${ye}/tests/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return VY.parse(n)}async uploadScreenshot(t){let n=await this.sendRequest(`/${ye}/screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return oJ.parse(n)}async uploadOnDemandScreenshot(t){return await this.sendRequest(`/${ye}/on-demand-screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${ye}/on-demand-screenshots/${t.id}`}}async fetchOnDemandScreenshot(t){let n={};return {data:await this.sendRequest(`/${ye}/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(`/${ye}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return sJ.parse(t)}async acquireCacheLock(t,n){let o=await this.sendRequest(`/${ye}/result-cache/lock`,{method:"POST",body:t,signal:n,retries:3,requestTimeoutMs:3e4});return xJ.parse(o)}async releaseCacheLock(t){await this.sendRequest(`/${ye}/result-cache/lock`,{method:"DELETE",body:{key:t},retries:3,requestTimeoutMs:5e3});}async deleteCacheResult(t){await this.sendRequest(`/${ye}/result-cache/entry`,{method:"DELETE",body:t,retries:3,requestTimeoutMs:5e3});}async setCacheResult(t){await this.sendRequest(`/${ye}/result-cache/entry`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:5e3});}async getCacheResult(t){try{return await this.sendRequest(`/${ye}/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(`/${ye}/suites/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return cJ.parse(n)}async bulkGetRunGroupStatus(t){let n={runGroupIds:t},o=await this.sendRequest(`/${ye}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return CW.array().parse(o)}async getRunGroupWithRuns(t){try{let n=await this.sendRequest(`/${ye}/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return RW.parse(n)}catch(n){if(n instanceof mo&&n.status===404)return null;throw n}}async getRun(t){try{let n=await this.sendRequest(`/${ye}/runs/${encodeURIComponent(t)}/metadata`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ds.parse(n)}catch(n){if(n instanceof mo&&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(`/${ye}/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(`/${ye}/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(`/${ye}/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(`/${ye}/test-fragments/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return dJ.parse(n)}async patchTestFragment(t,n){await this.sendRequest(`/${ye}/test-fragments/${t}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async getPastTestResults(t,n){let o=await this.sendRequest(`/${ye}/results/tests/${t}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return uJ.parse(o)}async listRuns(t){let n=await this.sendRequest(`/${ye}/results/runs`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return pJ.parse(n)}async generateTestResultsUploadUrl(){let t=await this.sendRequest(`/${ye}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return mJ.parse(t)}async startProcessingResultsUpload(t,n){let o=await this.sendRequest(`/${ye}/results/uploads/${t}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return hJ.parse(o)}async fetchIconKnowledgeBase(t){try{let n=await this.sendRequest(`/${ye}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return LJ.parse(n)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(t,n){try{await this.sendRequest(`/${ye}/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(`/${ye}/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 Yz.parse(p)}catch(p){return u.warn({err:p},"Failed to retrieve from knowledge base"),null}}async createKnowledgeItem(t){let n=await this.sendRequest(`/${ye}/knowledge-base/items`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return mN.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(`/${ye}/git/github/${t}/${n}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return yT.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(`/${ye}/git/github/${t}/${n}/compare?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return jq.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(`/${ye}/git/github/${t}/${n}/contents?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Gq.parse(s).content??void 0}async getGithubBranchMetadata(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i=await this.sendRequest(`/${ye}/git/github/${t}/${n}/branch-metadata?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return $q.parse(i)}async createGithubPullRequest(t,n,o){let r=await this.sendRequest(`/${ye}/git/github/${t}/${n}/pull-requests`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return Bq.parse(r)}async createGithubCommit(t,n,o){let r=await this.sendRequest(`/${ye}/git/github/${t}/${n}/commits`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return Uq.parse(r)}async getGithubPullRequestTemplate(t,n){try{let o=await this.sendRequest(`/${ye}/git/github/${t}/${n}/pull-request-template`,{method:"GET",retries:3,requestTimeoutMs:1e4});return zq.parse(o).template}catch(o){if(o instanceof mo&&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(`/${ye}/git/github/${t}/${n}/pull-requests?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof mo&&s.status===404)return;throw s}return Hq.parse(i)}async getCommitFromGithub(t,n,o){let r=await this.sendRequest(`/${ye}/git/github/${t}/${n}/commits/${o}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return yT.parse(r)}async getMergedBranchFromGithub(t,n,o,r){let i=encodeURIComponent(o),s=await this.sendRequest(`/${ye}/git/github/${t}/${n}/${i}/${r}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return GL.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(`/${ye}/git/gitlab/${i}/merge-base-commit?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return yT.parse(s)}async getGitlabMergeRequestForBranch(t,n){let o=new URLSearchParams;o.set("branch",n);let r=encodeURIComponent(t),i;try{i=await this.sendRequest(`/${ye}/git/gitlab/${r}/merge-requests?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof mo&&s.status===404)return;throw s}return Vq.parse(i)}async getCommitFromGitlab(t,n){let o=encodeURIComponent(t),r=await this.sendRequest(`/${ye}/git/gitlab/${o}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return yT.parse(r)}async getMergedBranchFromGitlab(t,n,o){let r=encodeURIComponent(n),i=encodeURIComponent(t),s=await this.sendRequest(`/${ye}/git/gitlab/${i}/${r}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return GL.parse(s)}async getAgentConfig(){let t=await this.sendRequest(`/${ye}/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(`/${ye}/org-settings`,{method:"GET",retries:3,requestTimeoutMs:5e3});return hW(t)}catch(t){if(t instanceof mo&&t.status===404)return this.logger.warn({err:t},"Momentic server does not expose org settings; continuing with local project settings"),Og.parse({});throw t}}async getQuarantinedTests(){let t=await this.sendRequest(`/${ye}/quarantine`,{method:"GET"});return gJ.parse(t)}async listQuarantinedTests(t){let n=await this.sendRequest(`/${ye}/quarantine/details`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return yJ.parse(n)}async sendExploreSlackNotification(t){await this.sendRequest(`/${ye}/explore/slack-notification`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async recordExplorerSuggestedTests(t){await this.sendRequest(`/${ye}/explore/suggested-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async quarantineTest(t,n,o){await this.sendRequest(`/${ye}/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(`/${ye}/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(`/${ye}/limbar/android`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return bJ.parse(n)}async extendEmulatorTtl(t,n){try{await this.sendRequest(`/${ye}/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(`/${ye}/limbar/${this.platformRoute(r)}/upload-url`,{method:"POST",retries:3,body:i,requestTimeoutMs:15e3,logResponse:true});return AJ.parse(s)}async deleteAndroidEmulator(t){await this.sendRequest(`/${ye}/limbar/android/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async getMobileAssets(){let t=await this.sendRequest(`/${ye}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return EJ.parse(t)}async getLimbarAssetDownloadUrl(t,n,o){let r=await this.sendRequest(`/${ye}/limbar/assets/${t}/${n}/${this.platformRoute(o)}/download-url`,{method:"GET",retries:2,requestTimeoutMs:3e4});return vJ.parse(r)}async deleteAsset(t,n,o){await this.sendRequest(`/${ye}/limbar/assets/${t}/${n}/${this.platformRoute(o)}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4});}async createIosEmulator(t){let n=await this.sendRequest(`/${ye}/limbar/ios`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return TJ.parse(n)}async deleteIosEmulator(t){await this.sendRequest(`/${ye}/limbar/ios/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async generateMobileLogcatUploadUrl(t){let n=await this.sendRequest(`/${ye}/logcat/mobile/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Tq.parse(n)}async generateMcpSessionTraceUploadUrl(t){let n=await this.sendRequest(`/${ye}/mcp/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return SR.parse(n)}};async function oh(e){let t=process.versions.node,n=parseInt(t.split(".")[0]);(isNaN(n)||n<18)&&(C.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),C.debug(`Identified node version ${t}`);let o=await e.client.getAuthInfo();return C.debug("Got auth info from API"),o}var Gd=class{apiClient;constructor(t){this.apiClient=t;}async reportBillableEvents(t,n){await this.apiClient.reportBillableEvents(t,n);}};var $d=class extends Ki{generator;constructor(t,n){super(t),this.generator=n;}async runTemplateMatching(t,n={}){let o=await this.sendRequest(`/${ye}/web-agent/template-matching`,{method:"POST",body:t,signal:n?.signal});return yz.parse(o)}async constructIframeRegex(t,n={}){return this.generator.getIframeRegex(t,{abortSignal:n.signal,loggerTags:n.loggerTags})}};var sy=class{constructor(t,n){this.client=t;this.orgId=n;}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let t=this.getApiServerUrl();return ef(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 Vd="v1",_Fe=2e3,F8="sms.lease() and sms.release() are only supported when running tests via the Momentic CLI.",zd=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(`/${Vd}/tools/sms/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(t){return this.httpClient.sendRequest(`/${Vd}/tools/sms/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof mo?new Error(n.rawError):n})}async leasePhoneNumber(t){if(!this.supportsLease)throw new Error(F8);let n=await this.httpClient.sendRequest(`/${Vd}/tools/sms/lease`,{method:"POST",body:t??{}}).catch(r=>{throw r instanceof mo?new Error(r.rawError):new Error(`Failed to lease phone number: ${r.message}`)}),o=Iq.parse(n);return this.activeLeases.set(o.phoneNumber,{leaseToken:o.leaseToken}),o}async releasePhoneNumber(t){if(!this.supportsLease)throw new Error(F8);return this.activeLeases.delete(t.phoneNumber),this.httpClient.sendRequest(`/${Vd}/tools/sms/release`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof mo?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}])=>xe(this.httpClient.sendRequest(`/${Vd}/tools/sms/release`,{method:"POST",body:{phoneNumber:n,leaseToken:o}}),{milliseconds:_Fe,fallback:()=>{}})));}async sendEmail(t){return this.httpClient.sendRequest(`/${Vd}/tools/email/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(t){return this.httpClient.sendRequest(`/${Vd}/tools/email/fetchAll`,{method:"POST",body:t}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(t){return this.httpClient.sendRequest(`/${Vd}/tools/email/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}async createEmail(){let t=await this.httpClient.sendRequest(`/${Vd}/tools/email/create`,{method:"POST",body:{}}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to create email inbox: ${n.message}`)});return xq.parse(t)}};var ay=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 bA(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,{resultType:"run",runGroupId:n,persist:r});return l}async uploadExploreArchive(t,n){let{uploadUrl:o,id:r}=await this.client.generateTestResultsUploadUrl(),i=await bA(o,"application/zip",n);if(!i.ok)throw new Error(`Failed to upload explore results: ${await i.text()}`);await this.client.startProcessingResultsUpload(r,{resultType:"explore",exploreRunId:t});}};function Wd({logger:e,orgId:t,client:n,gitMetadata:o,regenerateCache:r,alwaysSaveCache:i,noCache:s,isolateCachesByEnvironment:a=false,bustOldestCachePercentage:l}){return s?new bR:new SB(e,t,n,o,{regenerateCache:r,alwaysSaveCache:i,bustOldestCachePercentage:l,isolateCachesByEnvironment:a})}var SB=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=yR(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:WL(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:WL(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=np({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&&OFe({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.25.0"];if(wt.increment("step_cache_resolution",a.cacheKeysHit.length,[...l,"outcome:hit"]),wt.increment("step_cache_resolution",a.cacheKeysMissed.length,[...l,"outcome:miss"]),wt.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 ro({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"),wt.increment("step_cache_resolution",1,["platform:web","source:local","fileFormat:v2","snapshotIdentityCache:true",`orgId:${this.orgId}`,"cliVersion:3.25.0","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=pL(a.schema_version),c=pL(lt);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 (${lt}). Please update your momentic package version. Skipping identity restoration from snapshot cache.`);return}}let i=Vw({entries:r,orgId:this.orgId,testId:o,logger:n}),s=$w({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 OFe({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 MFe(e){let t=new Jj,n=io__default.join(e,ct),o=_a.parse(JSON.parse(ko__default.readFileSync(n,"utf-8")));t.addLocalFile(n);for(let r of ko__default.readdirSync(io__default.join(e,po))){if(!r.endsWith(".zip"))continue;let i=r.replace(/\.zip$/,""),s=new Jj(io__default.join(e,po,r));for(let a of s.getEntries())a.isDirectory||t.addFile(io__default.join(po,i,a.entryName),a.getData());}return {runGroupId:o.id,buffer:t.toBuffer()}}async function TA(e){let{client:t,resultsPath:n,persist:o}=e;if(!ko__default.existsSync(n))return {success:false,error:"results path does not exist"};let r=new ay(t);try{let{runGroupId:i,buffer:s}=MFe(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:q(i)}}}var G8=101010256,TB=33639248,NFe=67324752,GI=22,LFe=65535,$I=4294967295,$8=1024*1024;function VI({zipPath:e,files:t,buffers:n}){let o=V8(e);if(!o)return false;let{centralDirectory:r,cdOffset:i,entryCount:s}=o;if(DFe({centralDirectory:r,files:t,buffers:n}))return false;let a=ko__default.openSync(e,"r+");try{let l=i,c=[];for(let p of t){let m=ko__default.statSync(p.sourcePath);if(m.size>$I||l+m.size>$I)return !1;let h=FFe(p.sourcePath),g=Buffer.from(p.entryName,"utf-8"),f=U8({nameBytes:g,crc:h,size:m.size});ko__default.writeSync(a,f,0,f.length,l),c.push(H8({nameBytes:g,crc:h,size:m.size,localHeaderOffset:l})),l+=f.length,l+=BFe(a,p.sourcePath,l);}for(let p of n){let m=Buffer.from(p.entryName,"utf-8"),h=j8.crc32(p.data),g=U8({nameBytes:m,crc:h,size:p.data.length});ko__default.writeSync(a,g,0,g.length,l),c.push(H8({nameBytes:m,crc:h,size:p.data.length,localHeaderOffset:l})),l+=g.length,ko__default.writeSync(a,p.data,0,p.data.length,l),l+=p.data.length;}let d=l;ko__default.writeSync(a,r,0,r.length,l),l+=r.length;for(let p of c)ko__default.writeSync(a,p,0,p.length,l),l+=p.length;let u=UFe({entryCount:s+t.length+n.length,cdSize:l-d,cdOffset:d});return ko__default.writeSync(a,u,0,u.length,l),ko__default.ftruncateSync(a,l+u.length),!0}finally{ko__default.closeSync(a);}}function V8(e){let t=ko__default.statSync(e).size,n=Math.min(t,GI+LFe),o=Buffer.alloc(n),r=ko__default.openSync(e,"r");try{ko__default.readSync(r,o,0,n,t-n);let i=kFe(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===$I||c===$I||c+l>t)return;let u=Buffer.alloc(l);return ko__default.readSync(r,u,0,l,c),l>0&&u.readUInt32LE(0)!==TB?void 0:{centralDirectory:u,cdOffset:c,entryCount:s}}finally{ko__default.closeSync(r);}}function kFe(e){for(let t=e.length-GI;t>=0;t--){if(e.readUInt32LE(t)!==G8)continue;let n=e.readUInt16LE(t+20);if(t+GI+n===e.length)return t}return -1}function z8(e){let t=V8(e);return t&&W8(t.centralDirectory)}function W8(e){let t=[],n=0;for(;n+46<=e.length&&e.readUInt32LE(n)===TB;){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 DFe({centralDirectory:e,files:t,buffers:n}){let o=new Set(W8(e));return t.some(r=>o.has(r.entryName))||n.some(r=>o.has(r.entryName))}function FFe(e){let t=ko__default.openSync(e,"r");try{let n=Buffer.alloc($8),o=0,r;for(;(r=ko__default.readSync(t,n,0,n.length,null))>0;)o=j8.crc32(n.subarray(0,r),o);return o}finally{ko__default.closeSync(t);}}function BFe(e,t,n){let o=ko__default.openSync(t,"r");try{let r=Buffer.alloc($8),i=0,s;for(;(s=ko__default.readSync(o,r,0,r.length,null))>0;)ko__default.writeSync(e,r,0,s,n+i),i+=s;return i}finally{ko__default.closeSync(o);}}function U8({nameBytes:e,crc:t,size:n}){let o=Buffer.alloc(30+e.length);return o.writeUInt32LE(NFe,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 H8({nameBytes:e,crc:t,size:n,localHeaderOffset:o}){let r=Buffer.alloc(46+e.length);return r.writeUInt32LE(TB,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 UFe({entryCount:e,cdSize:t,cdOffset:n}){let o=Buffer.alloc(GI);return o.writeUInt32LE(G8,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 AA=class e{constructor(t,n=true){this.filePath=t;n&&ko__default.rmSync(this.filePath,{recursive:true,force:true}),ko__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(io__default.join(this.filePath,t));return this.children.push(n),n}cwd(){return this.filePath}mkdir(t){ko__default.mkdirSync(io__default.join(this.filePath,t),{recursive:true});}readFile(t){let n=io__default.join(this.filePath,t);if(ko__default.existsSync(n))return ko__default.readFileSync(n)}storeFile(t){let{name:n,contents:o}=t,r=io__default.join(this.filePath,n);try{ko__default.mkdirSync(io__default.dirname(r),{recursive:!0}),ko__default.writeFileSync(r,o);}catch{}}createFileStream(t){let n=io__default.join(this.filePath,t),o=ko__default.createWriteStream(n);return this.streams.push(o),o}createRunArchive(t,n){let o=new AB(io__default.join(this.filePath,po),t,n);return this.children.push(o),o}},AB=class{children=[];tempPath;finalPath;logger;closed=false;constructor(t,n,o){this.tempPath=io__default.join(t,`temp-storage-${n}`),this.finalPath=io__default.join(t,`${n}.zip`),this.logger=o,ko__default.rmSync(this.tempPath,{recursive:true,force:true}),ko__default.rmSync(this.finalPath,{recursive:true,force:true}),ko__default.mkdirSync(this.tempPath,{recursive:true});}readFile(t){let n=io__default.join(this.tempPath,t);if(ko__default.existsSync(n))return ko__default.readFileSync(n)}mkdir(t){ko__default.mkdirSync(io__default.join(this.tempPath,t),{recursive:true});}cd(t){let n=new AA(io__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=io__default.join(this.tempPath,n);ko__default.mkdirSync(io__default.dirname(r),{recursive:true}),ko__default.writeFileSync(r,o);}close(){if(!this.closed){this.closed=true;for(let t of this.children)t.close();try{let t=new Jj;t.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store"&&!K8(r));let n=t.toBuffer();ko__default.writeFileSync(this.finalPath,n);let o=jFe(this.tempPath);if(o.length>0&&!VI({zipPath:this.finalPath,files:o,buffers:[]})){let r=new Jj(this.finalPath);for(let i of o)r.addLocalFile(i.sourcePath,i.entryName.split("/").slice(0,-1).join("/"));r.writeZip(this.finalPath);}ko__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");}}}},HFe=[".webm",".mp4",".mov"];function K8(e){let t=e.toLowerCase();return HFe.some(n=>t.endsWith(n))}function jFe(e){let t=[],n=ko__default.readdirSync(e,{recursive:true,withFileTypes:true});for(let o of n){if(!o.isFile()||!K8(o.name))continue;let r=io__default.join(o.parentPath,o.name),i=io__default.relative(e,r).split(io__default.sep).join("/");t.push({entryName:i,sourcePath:r});}return t}function Q8(e){try{return ko__default.existsSync(e)?JSON.parse(ko__default.readFileSync(e,"utf-8")):void 0}catch{return}}function Y8(e){return ko__default.existsSync(e)?ko__default.readFileSync(e,"utf-8").split(`
|
|
294
|
+
`);}function bFe(e){let t=e.reasoning,n=e.include;return {model:e.model,service_tier:e.service_tier,prompt_cache_key:e.prompt_cache_key,include:Array.isArray(n)?n.filter(o=>typeof o=="string"):void 0,reasoning:w8(t)?{effort:t.effort}:void 0,hasInput:!!e.input,toolsCount:Array.isArray(e.tools)?e.tools.length:0}}function w8(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function TFe(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}var EFe="MOMENTIC_OPENAI_RESPONSES_WEBSOCKET_COMPACT_THRESHOLD",vFe=2e5;function iy(e){let{apiKey:t,sessionId:n,loggerTags:o,runner:r,parentTraceId:i}=e,s={Authorization:`Bearer ${t}`,[gR]:Xm,...n&&{[FY]:n},...r&&{[fR]:r},...i&&{[BY]:i},...o&&{[DY]: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 I8="bedrock/",x8="azure/",_8=e=>t=>{let n=iy(e),o=`${e.baseUrl}/v1/llm/anthropic/${encodeURIComponent(t)}`;return t.startsWith(I8)?o=`${e.baseUrl}/v1/llm/provider/bedrock/anthropic/${encodeURIComponent(t.slice(I8.length))}`:t.startsWith(x8)&&(o=`${e.baseUrl}/v1/llm/provider/foundry/anthropic/${encodeURIComponent(t.slice(x8.length))}`),createAnthropic({baseURL:o,headers:n,apiKey:e.apiKey})(t)},P8=e=>t=>{let n=iy(e),o=e.useOpenAIResponsesWebSocket??false,r=o?e.openAIResponsesWebSocketCompactThreshold??CFe(process.env[EFe])??vFe:void 0;return ry({baseURL:`${e.baseUrl}/v1/llm/provider/openai/${t}`,headers:n,apiKey:e.apiKey,fetch:o?v8({compactThreshold:r}):void 0})(t)},O8=e=>t=>{let n=iy(e);return ry({baseURL:`${e.baseUrl}/v1/llm/provider/xai/${t}`,headers:n,apiKey:e.apiKey,fetch:R8(e.xai)})(t)},M8=e=>t=>{let n=iy(e);return ry({baseURL:`${e.baseUrl}/v1/llm/provider/azure/${t}`,headers:n,apiKey:e.apiKey})(t)};function fB(e){return t=>n=>{let o=iy(t);return ry({baseURL:`${t.baseUrl}/v1/llm/provider/${e}/${n}`,headers:o,apiKey:t.apiKey}).chat(n)}}var N8=fB("azure/deepseek"),L8=fB("azure/kimi"),k8=fB("fireworks/glm"),D8=e=>t=>{let n=iy(e);return tB({baseURL:`${e.baseUrl}/v1/llm/provider/vertex`,headers:n,apiKey:e.apiKey})(t)};function CFe(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}var qo=class extends Ki{agentConfig;constructor(t,n){let o={...ku,...t};MC(o),super(n),this.agentConfig=o;}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(t,n){let o={...t,loggerTags:n.loggerTags},r=await this.sendRequest(`/${ye}/web-agent/recommend-chunks-ai`,{method:"POST",body:o,signal:n.abortSignal});return MW.parse(r)}async rankChunksWithRag(t,n){let o=await this.sendRequest(`/${ye}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Xm,...t},signal:n.abortSignal});return OW.parse(o)}async getScreenshotFromS3(t){let n=await this.sendRequest(`/${ye}/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(`/${ye}/web-agent/locate-element`,{method:"POST",body:o,signal:n.abortSignal});return GY.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(`/${ye}/web-agent/assertion`,{method:"POST",body:o,signal:n.abortSignal});return UL.parse(r)}async getLintStepResult(t,n){let o={...t,disableCache:!!n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${ye}/web-agent/lint/step`,{method:"POST",body:o,signal:n.abortSignal});return jY.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(`/${ye}/web-agent/visual-assertion`,{method:"POST",body:o,signal:n.abortSignal});return UL.parse(r)}async getAiActionCommand(t,n){let o=await this.sendRequest(`/${ye}/web-agent/next-command-dynamic`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return HY.parse(o)}async getMultiturnAiActionCommand(t,n){return await this.sendRequest(`/${ye}/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(`/${ye}/web-agent/ai-action/evaluate`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return cN.parse(o)}async getReverseMappedDescription(t,n){let o=await this.sendRequest(`/${ye}/web-agent/reverse-mapped-description`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return $Y.parse(o)}async getTextExtraction(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},r=await this.sendRequest(`/${ye}/web-agent/text-extraction`,{method:"POST",body:o,signal:n.abortSignal});return lN.parse(r)}async getPageSummary(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${ye}/web-agent/page-summary`,{method:"POST",body:o,signal:n.abortSignal});return $z.parse(r)}async getSmartWaitingDecision(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${ye}/web-agent/smart-waiting`,{method:"POST",body:o,signal:n.abortSignal});return Vz.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(`/${ye}/web-agent/result-classification`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return Uv.parse(o)}async getExtractedKeywords(t,n){let o=await this.sendRequest(`/${ye}/web-agent/extract-keywords`,{method:"POST",body:t,signal:n.abortSignal});return VW.parse(o)}async getAutohealingProposal(t,n){let o=await this.sendRequest(`/${ye}/web-agent/autoheal-section`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return Bz.parse(o)}async getFailureRecoveryProposal(t,n){let o=await this.sendRequest(`/${ye}/web-agent/failure-recovery`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return jz.parse(o)}async getFailureRecoveryPlan(t,n){let o=await this.sendRequest(`/${ye}/web-agent/failure-recovery-plan`,{method:"POST",body:{...t,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["failure-recovery"]},signal:n.abortSignal});return Hz.parse(o)}async getIframeRegex(t,n){let o=await this.sendRequest(`/${ye}/web-agent/iframe-regex`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return fz.parse(o)}createAgentTrace(t){let n=randomUUID(),{completionType:o,runId:r,orgId:i,logger:s}=t,a=async l=>{try{await this.sendRequest(`/${ye}/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(_8,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 P8({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...Wt(o),promptType:r},sessionId:n,useOpenAIResponsesWebSocket:i,runner:this.runner,parentTraceId:s})}getXAIModelFactory(t){return this.buildModelFactory(O8,t)}getAzureOpenAIModelFactory(t){return this.buildModelFactory(M8,t)}getAzureDeepSeekModelFactory(t){return this.buildModelFactory(N8,t)}getAzureKimiModelFactory(t){return this.buildModelFactory(L8,t)}getFireworksGLMModelFactory(t){return this.buildModelFactory(k8,t)}getVertexGeminiModelFactory(t){return this.buildModelFactory(D8,t)}buildModelFactory(t,n){let{sessionId:o,logger:r,streamType:i,parentTraceId:s,xai:a}=n;return t({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...Wt(r),promptType:i},sessionId:o,runner:this.runner,parentTraceId:s,xai:a})}};function bA(e,t,n){return fetch(e,{method:"PUT",body:n,headers:{"Content-Type":t}})}var xt=class extends Ki{getAppUrl(){return ef(this.baseUrl)}async getAuthInfo(){let t;try{t=await this.sendRequest(`/${ye}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});}catch(n){throw n instanceof mo?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 rJ.parse(t)}async getCliAnnouncements(){let t=await this.sendRequest(`/${ye}/announcements`,{method:"GET",retries:1,requestTimeoutMs:5e3});return wq.parse(t).announcements}async getQuotaStatus(){let t=await this.sendRequest(`/${ye}/billing/check-quota`,{method:"GET",retries:3,requestTimeoutMs:5e3});return iJ.parse(t)}async createRemoteBrowserConnection(t){let n=process.env.MOMENTIC_BROWSER_VENDOR_OVERRIDE,o=await this.sendRequest(`/${ye}/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}:{}},extraHeaders:n?{[UY]:n}:void 0,retries:3,requestTimeoutMs:1e4});return CJ.parse(o)}async bulkGetRunStatus(t){let n=await this.sendRequest(`/${ye}/runs/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return ZY.parse(n)}async getRunExport(t){let n=await this.sendRequest(`/${ye}/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tJ.parse(n)}submitInteractiveAgentFeedback(t){try{this.sendRequest(`/${ye}/traces/interactive-agent-feedback`,{method:"POST",body:t,retries:1,requestTimeoutMs:2e3}).catch(n=>{});}catch(n){}return Promise.resolve()}async getResultClassificationCacheEntries(t){let n=await this.sendRequest(`/${ye}/result-classification-cache`,{method:"POST",body:t,retries:1,requestTimeoutMs:1e4});return MJ.parse(n)}async createResultClassificationCacheEntries(t){await this.sendRequest(`/${ye}/result-classification-cache`,{method:"PATCH",body:t,retries:1,requestTimeoutMs:1e4});}async saveRunClassification(t,n){await this.sendRequest(`/${ye}/runs/${encodeURIComponent(t)}/classification`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async uploadRunHealTraceZip(t,n){let o=await this.sendRequest(`/${ye}/runs/${encodeURIComponent(t)}/heal-trace/upload-url`,{method:"POST",retries:3,requestTimeoutMs:1e4}),{uploadUrl:r}=SR.parse(o),i=await bA(r,"application/zip",n);if(!i.ok)throw new Error(`Failed to upload heal trace: ${await i.text()}`)}async saveRunHealMetadataBatch(t){await this.sendRequest(`/${ye}/runs/heal-metadata`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4});}async getTestYAMLExport(t){let n=await this.sendRequest(`/${ye}/tests/export`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return zY.parse(n)}async updateStepCaches(t,n){await this.sendRequest(`/${ye}/cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async updateSnapshotCaches(t,n){await this.sendRequest(`/${ye}/snapshot-cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getStepCacheForTest(t,n){let o=await this.sendRequest(`/${ye}/cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return qY.parse(o)}async getSnapshotCacheForTest(t,n){let o=await this.sendRequest(`/${ye}/snapshot-cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return KY.parse(o)}async deleteStepCacheEntry(t,n){await this.sendRequest(`/${ye}/cache/entry`,{method:"DELETE",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4});}async getWebStepCacheMemoryTraces(t){let n=await this.sendRequest(`/${ye}/cache/traces`,{method:"POST",body:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return HL.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(`/${ye}/${this.cacheRouteForPlatform(t)}/entry`,{method:"DELETE",body:n,extraHeaders:o,retries:3,requestTimeoutMs:1e4});}async getMobileStepCacheMemoryTraces(t,n){let o=await this.sendRequest(`/${ye}/${this.cacheRouteForPlatform(t)}/traces`,{method:"POST",body:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return HL.parse(o)}async updateMobileStepCaches(t){await this.sendRequest(`/${ye}/${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(`/${ye}/${this.cacheRouteForPlatform(t)}`,{method:"POST",body:n,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return YY[t](r)}async queueTests(t){let n=await this.sendRequest(`/${ye}/tests/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return VY.parse(n)}async uploadScreenshot(t){let n=await this.sendRequest(`/${ye}/screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return oJ.parse(n)}async uploadOnDemandScreenshot(t){return await this.sendRequest(`/${ye}/on-demand-screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${ye}/on-demand-screenshots/${t.id}`}}async fetchOnDemandScreenshot(t){let n={};return {data:await this.sendRequest(`/${ye}/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(`/${ye}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return sJ.parse(t)}async acquireCacheLock(t,n){let o=await this.sendRequest(`/${ye}/result-cache/lock`,{method:"POST",body:t,signal:n,retries:3,requestTimeoutMs:3e4});return xJ.parse(o)}async releaseCacheLock(t){await this.sendRequest(`/${ye}/result-cache/lock`,{method:"DELETE",body:{key:t},retries:3,requestTimeoutMs:5e3});}async deleteCacheResult(t){await this.sendRequest(`/${ye}/result-cache/entry`,{method:"DELETE",body:t,retries:3,requestTimeoutMs:5e3});}async setCacheResult(t){await this.sendRequest(`/${ye}/result-cache/entry`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:5e3});}async getCacheResult(t){try{return await this.sendRequest(`/${ye}/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(`/${ye}/suites/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return cJ.parse(n)}async bulkGetRunGroupStatus(t){let n={runGroupIds:t},o=await this.sendRequest(`/${ye}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return CW.array().parse(o)}async getRunGroupWithRuns(t){try{let n=await this.sendRequest(`/${ye}/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return RW.parse(n)}catch(n){if(n instanceof mo&&n.status===404)return null;throw n}}async getRun(t){try{let n=await this.sendRequest(`/${ye}/runs/${encodeURIComponent(t)}/metadata`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ds.parse(n)}catch(n){if(n instanceof mo&&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(`/${ye}/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(`/${ye}/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(`/${ye}/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(`/${ye}/test-fragments/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return dJ.parse(n)}async patchTestFragment(t,n){await this.sendRequest(`/${ye}/test-fragments/${t}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async getPastTestResults(t,n){let o=await this.sendRequest(`/${ye}/results/tests/${t}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return uJ.parse(o)}async listRuns(t){let n=await this.sendRequest(`/${ye}/results/runs`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return pJ.parse(n)}async generateTestResultsUploadUrl(){let t=await this.sendRequest(`/${ye}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return mJ.parse(t)}async startProcessingResultsUpload(t,n){let o=await this.sendRequest(`/${ye}/results/uploads/${t}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return hJ.parse(o)}async fetchIconKnowledgeBase(t){try{let n=await this.sendRequest(`/${ye}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return LJ.parse(n)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(t,n){try{await this.sendRequest(`/${ye}/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(`/${ye}/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 Yz.parse(p)}catch(p){return u.warn({err:p},"Failed to retrieve from knowledge base"),null}}async createKnowledgeItem(t){let n=await this.sendRequest(`/${ye}/knowledge-base/items`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return mN.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(`/${ye}/git/github/${t}/${n}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return yT.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(`/${ye}/git/github/${t}/${n}/compare?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return jq.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(`/${ye}/git/github/${t}/${n}/contents?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Gq.parse(s).content??void 0}async getGithubBranchMetadata(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i=await this.sendRequest(`/${ye}/git/github/${t}/${n}/branch-metadata?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return $q.parse(i)}async createGithubPullRequest(t,n,o){let r=await this.sendRequest(`/${ye}/git/github/${t}/${n}/pull-requests`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return Bq.parse(r)}async createGithubCommit(t,n,o){let r=await this.sendRequest(`/${ye}/git/github/${t}/${n}/commits`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return Uq.parse(r)}async getGithubPullRequestTemplate(t,n){try{let o=await this.sendRequest(`/${ye}/git/github/${t}/${n}/pull-request-template`,{method:"GET",retries:3,requestTimeoutMs:1e4});return zq.parse(o).template}catch(o){if(o instanceof mo&&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(`/${ye}/git/github/${t}/${n}/pull-requests?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof mo&&s.status===404)return;throw s}return Hq.parse(i)}async getCommitFromGithub(t,n,o){let r=await this.sendRequest(`/${ye}/git/github/${t}/${n}/commits/${o}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return yT.parse(r)}async getMergedBranchFromGithub(t,n,o,r){let i=encodeURIComponent(o),s=await this.sendRequest(`/${ye}/git/github/${t}/${n}/${i}/${r}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return GL.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(`/${ye}/git/gitlab/${i}/merge-base-commit?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return yT.parse(s)}async getGitlabMergeRequestForBranch(t,n){let o=new URLSearchParams;o.set("branch",n);let r=encodeURIComponent(t),i;try{i=await this.sendRequest(`/${ye}/git/gitlab/${r}/merge-requests?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof mo&&s.status===404)return;throw s}return Vq.parse(i)}async getCommitFromGitlab(t,n){let o=encodeURIComponent(t),r=await this.sendRequest(`/${ye}/git/gitlab/${o}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return yT.parse(r)}async getMergedBranchFromGitlab(t,n,o){let r=encodeURIComponent(n),i=encodeURIComponent(t),s=await this.sendRequest(`/${ye}/git/gitlab/${i}/${r}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return GL.parse(s)}async getAgentConfig(){let t=await this.sendRequest(`/${ye}/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(`/${ye}/org-settings`,{method:"GET",retries:3,requestTimeoutMs:5e3});return hW(t)}catch(t){if(t instanceof mo&&t.status===404)return this.logger.warn({err:t},"Momentic server does not expose org settings; continuing with local project settings"),Og.parse({});throw t}}async getQuarantinedTests(){let t=await this.sendRequest(`/${ye}/quarantine`,{method:"GET"});return gJ.parse(t)}async listQuarantinedTests(t){let n=await this.sendRequest(`/${ye}/quarantine/details`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return yJ.parse(n)}async sendExploreSlackNotification(t){await this.sendRequest(`/${ye}/explore/slack-notification`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async recordExplorerSuggestedTests(t){await this.sendRequest(`/${ye}/explore/suggested-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async quarantineTest(t,n,o){await this.sendRequest(`/${ye}/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(`/${ye}/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(`/${ye}/limbar/android`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return bJ.parse(n)}async extendEmulatorTtl(t,n){try{await this.sendRequest(`/${ye}/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(`/${ye}/limbar/${this.platformRoute(r)}/upload-url`,{method:"POST",retries:3,body:i,requestTimeoutMs:15e3,logResponse:true});return AJ.parse(s)}async deleteAndroidEmulator(t){await this.sendRequest(`/${ye}/limbar/android/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async getMobileAssets(){let t=await this.sendRequest(`/${ye}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return EJ.parse(t)}async getLimbarAssetDownloadUrl(t,n,o){let r=await this.sendRequest(`/${ye}/limbar/assets/${t}/${n}/${this.platformRoute(o)}/download-url`,{method:"GET",retries:2,requestTimeoutMs:3e4});return vJ.parse(r)}async deleteAsset(t,n,o){await this.sendRequest(`/${ye}/limbar/assets/${t}/${n}/${this.platformRoute(o)}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4});}async createIosEmulator(t){let n=await this.sendRequest(`/${ye}/limbar/ios`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return TJ.parse(n)}async deleteIosEmulator(t){await this.sendRequest(`/${ye}/limbar/ios/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async generateMobileLogcatUploadUrl(t){let n=await this.sendRequest(`/${ye}/logcat/mobile/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Tq.parse(n)}async generateMcpSessionTraceUploadUrl(t){let n=await this.sendRequest(`/${ye}/mcp/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return SR.parse(n)}};async function oh(e){let t=process.versions.node,n=parseInt(t.split(".")[0]);(isNaN(n)||n<18)&&(C.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),C.debug(`Identified node version ${t}`);let o=await e.client.getAuthInfo();return C.debug("Got auth info from API"),o}var Gd=class{apiClient;constructor(t){this.apiClient=t;}async reportBillableEvents(t,n){await this.apiClient.reportBillableEvents(t,n);}};var $d=class extends Ki{generator;constructor(t,n){super(t),this.generator=n;}async runTemplateMatching(t,n={}){let o=await this.sendRequest(`/${ye}/web-agent/template-matching`,{method:"POST",body:t,signal:n?.signal});return yz.parse(o)}async constructIframeRegex(t,n={}){return this.generator.getIframeRegex(t,{abortSignal:n.signal,loggerTags:n.loggerTags})}};var sy=class{constructor(t,n){this.client=t;this.orgId=n;}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let t=this.getApiServerUrl();return ef(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 Vd="v1",_Fe=2e3,F8="sms.lease() and sms.release() are only supported when running tests via the Momentic CLI.",zd=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(`/${Vd}/tools/sms/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(t){return this.httpClient.sendRequest(`/${Vd}/tools/sms/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof mo?new Error(n.rawError):n})}async leasePhoneNumber(t){if(!this.supportsLease)throw new Error(F8);let n=await this.httpClient.sendRequest(`/${Vd}/tools/sms/lease`,{method:"POST",body:t??{}}).catch(r=>{throw r instanceof mo?new Error(r.rawError):new Error(`Failed to lease phone number: ${r.message}`)}),o=Iq.parse(n);return this.activeLeases.set(o.phoneNumber,{leaseToken:o.leaseToken}),o}async releasePhoneNumber(t){if(!this.supportsLease)throw new Error(F8);return this.activeLeases.delete(t.phoneNumber),this.httpClient.sendRequest(`/${Vd}/tools/sms/release`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof mo?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}])=>xe(this.httpClient.sendRequest(`/${Vd}/tools/sms/release`,{method:"POST",body:{phoneNumber:n,leaseToken:o}}),{milliseconds:_Fe,fallback:()=>{}})));}async sendEmail(t){return this.httpClient.sendRequest(`/${Vd}/tools/email/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(t){return this.httpClient.sendRequest(`/${Vd}/tools/email/fetchAll`,{method:"POST",body:t}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(t){return this.httpClient.sendRequest(`/${Vd}/tools/email/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}async createEmail(){let t=await this.httpClient.sendRequest(`/${Vd}/tools/email/create`,{method:"POST",body:{}}).catch(n=>{throw n instanceof mo?new Error(n.rawError):new Error(`Failed to create email inbox: ${n.message}`)});return xq.parse(t)}};var ay=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 bA(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,{resultType:"run",runGroupId:n,persist:r});return l}async uploadExploreArchive(t,n){let{uploadUrl:o,id:r}=await this.client.generateTestResultsUploadUrl(),i=await bA(o,"application/zip",n);if(!i.ok)throw new Error(`Failed to upload explore results: ${await i.text()}`);await this.client.startProcessingResultsUpload(r,{resultType:"explore",exploreRunId:t});}};function Wd({logger:e,orgId:t,client:n,gitMetadata:o,regenerateCache:r,alwaysSaveCache:i,noCache:s,isolateCachesByEnvironment:a=false,bustOldestCachePercentage:l}){return s?new bR:new SB(e,t,n,o,{regenerateCache:r,alwaysSaveCache:i,bustOldestCachePercentage:l,isolateCachesByEnvironment:a})}var SB=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=yR(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:WL(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:WL(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=np({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&&OFe({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.25.1"];if(wt.increment("step_cache_resolution",a.cacheKeysHit.length,[...l,"outcome:hit"]),wt.increment("step_cache_resolution",a.cacheKeysMissed.length,[...l,"outcome:miss"]),wt.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 ro({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"),wt.increment("step_cache_resolution",1,["platform:web","source:local","fileFormat:v2","snapshotIdentityCache:true",`orgId:${this.orgId}`,"cliVersion:3.25.1","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=pL(a.schema_version),c=pL(lt);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 (${lt}). Please update your momentic package version. Skipping identity restoration from snapshot cache.`);return}}let i=Vw({entries:r,orgId:this.orgId,testId:o,logger:n}),s=$w({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 OFe({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 MFe(e){let t=new Jj,n=io__default.join(e,ct),o=_a.parse(JSON.parse(ko__default.readFileSync(n,"utf-8")));t.addLocalFile(n);for(let r of ko__default.readdirSync(io__default.join(e,po))){if(!r.endsWith(".zip"))continue;let i=r.replace(/\.zip$/,""),s=new Jj(io__default.join(e,po,r));for(let a of s.getEntries())a.isDirectory||t.addFile(io__default.join(po,i,a.entryName),a.getData());}return {runGroupId:o.id,buffer:t.toBuffer()}}async function TA(e){let{client:t,resultsPath:n,persist:o}=e;if(!ko__default.existsSync(n))return {success:false,error:"results path does not exist"};let r=new ay(t);try{let{runGroupId:i,buffer:s}=MFe(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:q(i)}}}var G8=101010256,TB=33639248,NFe=67324752,GI=22,LFe=65535,$I=4294967295,$8=1024*1024;function VI({zipPath:e,files:t,buffers:n}){let o=V8(e);if(!o)return false;let{centralDirectory:r,cdOffset:i,entryCount:s}=o;if(DFe({centralDirectory:r,files:t,buffers:n}))return false;let a=ko__default.openSync(e,"r+");try{let l=i,c=[];for(let p of t){let m=ko__default.statSync(p.sourcePath);if(m.size>$I||l+m.size>$I)return !1;let h=FFe(p.sourcePath),g=Buffer.from(p.entryName,"utf-8"),f=U8({nameBytes:g,crc:h,size:m.size});ko__default.writeSync(a,f,0,f.length,l),c.push(H8({nameBytes:g,crc:h,size:m.size,localHeaderOffset:l})),l+=f.length,l+=BFe(a,p.sourcePath,l);}for(let p of n){let m=Buffer.from(p.entryName,"utf-8"),h=j8.crc32(p.data),g=U8({nameBytes:m,crc:h,size:p.data.length});ko__default.writeSync(a,g,0,g.length,l),c.push(H8({nameBytes:m,crc:h,size:p.data.length,localHeaderOffset:l})),l+=g.length,ko__default.writeSync(a,p.data,0,p.data.length,l),l+=p.data.length;}let d=l;ko__default.writeSync(a,r,0,r.length,l),l+=r.length;for(let p of c)ko__default.writeSync(a,p,0,p.length,l),l+=p.length;let u=UFe({entryCount:s+t.length+n.length,cdSize:l-d,cdOffset:d});return ko__default.writeSync(a,u,0,u.length,l),ko__default.ftruncateSync(a,l+u.length),!0}finally{ko__default.closeSync(a);}}function V8(e){let t=ko__default.statSync(e).size,n=Math.min(t,GI+LFe),o=Buffer.alloc(n),r=ko__default.openSync(e,"r");try{ko__default.readSync(r,o,0,n,t-n);let i=kFe(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===$I||c===$I||c+l>t)return;let u=Buffer.alloc(l);return ko__default.readSync(r,u,0,l,c),l>0&&u.readUInt32LE(0)!==TB?void 0:{centralDirectory:u,cdOffset:c,entryCount:s}}finally{ko__default.closeSync(r);}}function kFe(e){for(let t=e.length-GI;t>=0;t--){if(e.readUInt32LE(t)!==G8)continue;let n=e.readUInt16LE(t+20);if(t+GI+n===e.length)return t}return -1}function z8(e){let t=V8(e);return t&&W8(t.centralDirectory)}function W8(e){let t=[],n=0;for(;n+46<=e.length&&e.readUInt32LE(n)===TB;){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 DFe({centralDirectory:e,files:t,buffers:n}){let o=new Set(W8(e));return t.some(r=>o.has(r.entryName))||n.some(r=>o.has(r.entryName))}function FFe(e){let t=ko__default.openSync(e,"r");try{let n=Buffer.alloc($8),o=0,r;for(;(r=ko__default.readSync(t,n,0,n.length,null))>0;)o=j8.crc32(n.subarray(0,r),o);return o}finally{ko__default.closeSync(t);}}function BFe(e,t,n){let o=ko__default.openSync(t,"r");try{let r=Buffer.alloc($8),i=0,s;for(;(s=ko__default.readSync(o,r,0,r.length,null))>0;)ko__default.writeSync(e,r,0,s,n+i),i+=s;return i}finally{ko__default.closeSync(o);}}function U8({nameBytes:e,crc:t,size:n}){let o=Buffer.alloc(30+e.length);return o.writeUInt32LE(NFe,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 H8({nameBytes:e,crc:t,size:n,localHeaderOffset:o}){let r=Buffer.alloc(46+e.length);return r.writeUInt32LE(TB,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 UFe({entryCount:e,cdSize:t,cdOffset:n}){let o=Buffer.alloc(GI);return o.writeUInt32LE(G8,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 AA=class e{constructor(t,n=true){this.filePath=t;n&&ko__default.rmSync(this.filePath,{recursive:true,force:true}),ko__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(io__default.join(this.filePath,t));return this.children.push(n),n}cwd(){return this.filePath}mkdir(t){ko__default.mkdirSync(io__default.join(this.filePath,t),{recursive:true});}readFile(t){let n=io__default.join(this.filePath,t);if(ko__default.existsSync(n))return ko__default.readFileSync(n)}storeFile(t){let{name:n,contents:o}=t,r=io__default.join(this.filePath,n);try{ko__default.mkdirSync(io__default.dirname(r),{recursive:!0}),ko__default.writeFileSync(r,o);}catch{}}createFileStream(t){let n=io__default.join(this.filePath,t),o=ko__default.createWriteStream(n);return this.streams.push(o),o}createRunArchive(t,n){let o=new AB(io__default.join(this.filePath,po),t,n);return this.children.push(o),o}},AB=class{children=[];tempPath;finalPath;logger;closed=false;constructor(t,n,o){this.tempPath=io__default.join(t,`temp-storage-${n}`),this.finalPath=io__default.join(t,`${n}.zip`),this.logger=o,ko__default.rmSync(this.tempPath,{recursive:true,force:true}),ko__default.rmSync(this.finalPath,{recursive:true,force:true}),ko__default.mkdirSync(this.tempPath,{recursive:true});}readFile(t){let n=io__default.join(this.tempPath,t);if(ko__default.existsSync(n))return ko__default.readFileSync(n)}mkdir(t){ko__default.mkdirSync(io__default.join(this.tempPath,t),{recursive:true});}cd(t){let n=new AA(io__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=io__default.join(this.tempPath,n);ko__default.mkdirSync(io__default.dirname(r),{recursive:true}),ko__default.writeFileSync(r,o);}close(){if(!this.closed){this.closed=true;for(let t of this.children)t.close();try{let t=new Jj;t.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store"&&!K8(r));let n=t.toBuffer();ko__default.writeFileSync(this.finalPath,n);let o=jFe(this.tempPath);if(o.length>0&&!VI({zipPath:this.finalPath,files:o,buffers:[]})){let r=new Jj(this.finalPath);for(let i of o)r.addLocalFile(i.sourcePath,i.entryName.split("/").slice(0,-1).join("/"));r.writeZip(this.finalPath);}ko__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");}}}},HFe=[".webm",".mp4",".mov"];function K8(e){let t=e.toLowerCase();return HFe.some(n=>t.endsWith(n))}function jFe(e){let t=[],n=ko__default.readdirSync(e,{recursive:true,withFileTypes:true});for(let o of n){if(!o.isFile()||!K8(o.name))continue;let r=io__default.join(o.parentPath,o.name),i=io__default.relative(e,r).split(io__default.sep).join("/");t.push({entryName:i,sourcePath:r});}return t}function Q8(e){try{return ko__default.existsSync(e)?JSON.parse(ko__default.readFileSync(e,"utf-8")):void 0}catch{return}}function Y8(e){return ko__default.existsSync(e)?ko__default.readFileSync(e,"utf-8").split(`
|
|
295
295
|
`).map(n=>n.trim()).filter(n=>n.length>0):[]}function VFe(e,t){let n=e.attemptIdToAttemptNumber.get(t);if(n)return io__default.join(e.inflatedPath,"attempts",n);let o=io__default.join(e.inflatedPath,"attempts");if(!ko__default.existsSync(o))return;let r=ko__default.readdirSync(o,{withFileTypes:true}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of r){let s=io__default.join(o,i,ct),a=Q8(s);if(typeof a!="object"||a===null)continue;let l=a.id;if(typeof l=="string"&&l===t)return e.attemptIdToAttemptNumber.set(t,i),io__default.join(o,i)}}function J8(e,t,n){let o=io__default.join(e,"attempts");if(!ko__default.existsSync(o))return;let r=ko__default.readdirSync(o,{withFileTypes:true}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of r){let s=io__default.join(o,i,"assets",`${t}.${n}`);if(ko__default.existsSync(s))return s}}var zI=class{constructor(t,n,o){this.outputDir=t;this.runId=n;this.runAttemptId=o;this.runsDir=io__default.join(t,po),this.zipPath=io__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||!ko__default.existsSync(this.zipPath))return;let o=io__default.join(this.runsDir,`temp-unzipped-${t}-${randomUUID()}`);ko__default.mkdirSync(o,{recursive:true}),new Jj(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())ko__default.rmSync(t.inflatedPath,{recursive:true,force:true});this.inflatedByRunId.clear();}getAttemptDir(){let t=this.ensureInflatedRun(this.runId);if(t)return VFe(t,this.runAttemptId)}listVideoAssetPaths(){let t=this.getAttemptDir();if(!t)return [];let n=io__default.join(t,"assets");return ko__default.existsSync(n)?ko__default.readdirSync(n,{withFileTypes:true}).filter(r=>r.isFile()).map(r=>io__default.join(n,r.name)).filter(r=>{let i=io__default.extname(r).toLowerCase();return i===".webm"||i===".mp4"}):[]}readAttemptAssetText(t,n){let o=this.getAttemptDir();if(!o)return;let r=io__default.join(o,"assets",`${t}.${n}`);if(ko__default.existsSync(r))try{return ko__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=Q8(io__default.join(r,"console.json")),s=mL.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=io__default.join(r,"assets","har-pages.log"),s=io__default.join(r,"assets","har-entries.log"),a={};for(let d of Y8(i)){let u=oT.safeParse(X8(d));u.success&&(a[u.data.id]=u.data);}let l={},c=Y8(s);for(let d=0;d<c.length;d++){let u=c[d],p=rT.safeParse(X8(u));if(!p.success)continue;let m=`${p.data.startedDateTime}-${d}`;l[m]=p.data;}if(Object.keys(l).length!==0)return hL(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=J8(r.inflatedPath,n,"html");if(i)try{return ko__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=J8(r.inflatedPath,n,"xml");if(i)try{return ko__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 ko__default.readFileSync(io__default.join(r,"assets",`${n}.${i}`))}catch{continue}}};function X8(e){try{return JSON.parse(e)}catch{return}}function Z8(e,t){let n=zFe(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}: ${q(e)}`}}}function zFe(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}function ly({test:e,envNameOverride:t,urlOverride:n,resolveEnv:o}){let r=t??WFe(e),i,s={};if(r){try{i=o(r);}catch(l){let c=`Failed to resolve environment ${r} for test ${e.name}: ${q(l)}`;throw l instanceof Oe?new Oe(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[Io];typeof l=="string"&&(a=l);}if(!a)throw new Ru(`Cannot run test with no base URL and no ${Io} variable defined in its environment`);return {envName:r,resolvedEnv:i,environmentVariables:s,baseUrl:a}}function WFe(e){for(let t of e.envs??[])if(t.default)return t.name}async function EA(e,t,n,o,r=ht){let i=o??await We(e,false,r),s=i[n],a=qFe(s,t);if(t.id){if(a.length===0)throw new vt(`No ${n} found with id '${t.id}' in project '${e.rootDir}'.`);return WI(a,i)}if(t.name){if(a.length===0)throw new vt(`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 vt([`Multiple ${n} found with exact name '${t.name}'. Please disambiguate by id or path.`,JSON.stringify(l,null,2)].join(`
|
|
296
296
|
`))}return WI(a,i)}if(t.path){let l=t.path;if(a.length===0)throw new vt(`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 WI(c,i);let d=a.map(u=>({id:u.id,path:u.fullFilePath}));throw new vt([`Multiple ${n} matched the provided path '${l}'. Please pass the absolute path.`,JSON.stringify(d,null,2)].join(`
|
|
297
297
|
`))}return WI(a,i)}throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function WI(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 qFe(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 e9({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=KFe({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 KFe({fullFilePath:e,momenticFiles:t,logger:n}){try{return hI(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 t9({cwd:e,projectName:t}){let n=io__default.join(e,Da);if(ko__default.existsSync(n))throw new Error(`A ${Da} file already exists at ${n}. Please rename or remove it to initialize a new project.`);let o=await LZ(e)??"main",r={name:t,include:$f,gitMainBranch:o,fileFormat:"v2",browser:{disableSecondaryCacheResolution:true},ai:{useMemory:true,failureRecovery:true,agentConfig:{...ku}}};return Fd(r,n),{configPath:n}}var XFe="npx skills@latest add momentic-ai/skills",QFe="https://momentic.ai/docs/integrations/mcp-server",ZFe={web:["https://momentic.ai/docs/quickstart/web"],mobile:["https://momentic.ai/docs/quickstart/ios","https://momentic.ai/docs/quickstart/android"]};function n9({platform:e}){let t="npx momentic app",n=ZFe[e].map(r=>il.underline.cyan(r)).join(il.dim(" \xB7 ")),o=(r,i)=>` ${il.dim(r.padEnd(14))}${i}`;C.log(""),C.log(il.bold("Next steps")),C.log(o("Editor skills",il.cyan(XFe))),C.log(o("Coding agent",`${il.dim("Momentic MCP \u2192")} ${il.underline.cyan(QFe)}`)),C.log(o("Local editor",il.cyan(t))),C.log(o("Docs",n));}var o9=["cursor","claude-code","codex","opencode","copilot"],tBe={cursor:io__default.join(".cursor","skills"),"claude-code":io__default.join(".claude","skills"),codex:io__default.join(".agents","skills"),opencode:io__default.join(".opencode","skills"),copilot:io__default.join(".github","skills")};function r9({editor:e,skillsDir:t,cwd:n=process.cwd()}){ko__default.existsSync(t)||(C.error(`Could not find skills directory at ${t}. Is the CLI package installed correctly?`),process.exit(1));let o=ko__default.readdirSync(t).filter(s=>s.endsWith(".md"));o.length===0&&(C.error(`No skill markdown files found in ${t}. Is the CLI package installed correctly?`),process.exit(1));let r=nBe({cwd:n}),i=io__default.join(r,tBe[e]);for(let s of o){let a=io__default.basename(s,".md"),l=io__default.join(i,a),c=ko__default.readFileSync(io__default.join(t,s),"utf8");ko__default.mkdirSync(l,{recursive:true}),ko__default.writeFileSync(io__default.join(l,"SKILL.md"),c),C.success(`Installed SKILL.md at ${io__default.join(l,"SKILL.md")}.`);}}function nBe({cwd:e}){try{return execSync("git rev-parse --show-toplevel",{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||e}catch{return e}}var s9=io__default.join(Ed.homedir(),".momentic"),Ji=io__default.join(s9,"auth.json"),rBe=new Set(["EPERM","EACCES","EROFS"]),iBe=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 qI(){if(!ko__default.existsSync(Ji))return null;try{let e=ko__default.readFileSync(Ji,"utf-8"),t=iBe.safeParse(JSON.parse(e));return t.success?t.data:null}catch{return null}}function a9(e){try{ko__default.mkdirSync(s9,{recursive:!0,mode:448}),ko__default.writeFileSync(Ji,JSON.stringify(e,null,2),{mode:384});}catch(t){throw t4(t)&&rBe.has(t.code)?new Oe(`Couldn't save your Momentic credentials to ${Ji} (${t.code}). Make sure that file and its parent directory are writable and owned by you; for example, they may have been created by a previous \`sudo\` run. Fix the permissions and try again.`,{cause:t}):t}}function l9(){return ko__default.existsSync(Ji)?(ko__default.unlinkSync(Ji),true):false}function dy(){return qI()?.apiKey||void 0}function KI(){return qI()?.serverUrl||void 0}function YI(e){return e.colorLevel>0?(t,n)=>n(il)(t):t=>t}var aBe=13;function c9(e,t){let{appName:n,version:o,url:r,pixelRatio:i,readyInMs:s}=e,a=t.unicode?"\u279C":"->",l=YI(t),c=l(n,g=>g.cyan.bold),d=s===void 0?"":` ${l(`ready in ${s} ms`,g=>g.dim)}`,u=` ${c} ${l(`v${o}`,g=>g.green)}${d}`,p=l(a,g=>g.green),m=(g,f,y)=>{let S=`${g}:`.padEnd(aBe),T=y===void 0?"":` ${l(y,A=>A.dim)}`;return ` ${p} ${l(S,A=>A.bold)} ${f}${T}`},h=[u,""];return h.push(m("Local",l(r,g=>g.cyan))),i!==void 0&&h.push(m("Pixel ratio",String(i),"override with --pixel-ratio")),h.push(` ${p} ${l("Press Ctrl+C to stop",g=>g.dim)}`),h.join(`
|
|
@@ -325,7 +325,7 @@ ${il.cyan(s)}`,a),n)try{await lBe(s);}catch{t.warn(`Could not open a browser aut
|
|
|
325
325
|
`);if(o===this.lastFrame&&this.liveRows===n.length)return;let r=this.eraseSeq();n.length>0&&(r+=`${o}
|
|
326
326
|
`),r+=this.cursorSeq(n.length>0),r.length>0&&this.opts.stream.write(r),this.commitFrame(n,o);}commitFrame(t,n){this.liveRows=t.length,this.lastFrame=n,t.length===0?this.stopTicker():this.ensureTicker();}eraseSeq(){return this.liveRows===0?"":b3+T3.repeat(this.liveRows)+A3}ensureTicker(){this.tickTimer||(this.tickTimer=setInterval(()=>{this.tick+=1,this.update();},this.opts.tickMs),this.tickTimer.unref?.());}stopTicker(){this.tickTimer&&(clearInterval(this.tickTimer),this.tickTimer=void 0);}};var XBe=80,QBe=120,ZBe=20,e0e="classifying failure",tx=class{totalTests=0;nextIndex=0;running=new Map;quarantined=new Set;recovered=new Set;region;theme;screen;constructor(t){this.screen={...t,isTTY:gc(t)},this.theme=Mn(this.screen),this.region=new bp({stream:process.stdout,isTTY:this.screen.isTTY,tickMs:XBe,render:n=>this.renderRunningRows(n)});}onBegin(t){this.totalTests=t.tests.length,this.nextIndex=0,this.quarantined.clear(),this.recovered.clear();for(let n of t.tests)n.quarantined&&this.quarantined.add(n.relativeFilePath);for(let n of t.tests)n.skipped&&(this.nextIndex+=1,this.commitRow({testRef:n.relativeFilePath,status:"SKIP",index:this.nextIndex,note:n.skipped.kind==="quarantined"?n.skipped.reason:void 0}));}onTestBegin(t){this.nextIndex+=1,this.running.set(t,{index:this.nextIndex,status:"RUN",startedAt:Date.now()}),this.region.update();}onTestStatus(t,n,o){let r=this.running.get(t);r?(r.status=n,r.note=o,r.step=void 0,r.classifying=false):(this.nextIndex+=1,this.running.set(t,{index:this.nextIndex,status:n,note:o,startedAt:Date.now()})),this.region.update();}onStepStart(t,n){let o=this.running.get(t);if(o){if(o.step={text:n},o.classifying=n===Zc,o.classifying&&!this.screen.isTTY){let r=this.formatRow({testRef:t,status:o.status,index:o.index,classifying:true,classifyPending:true});r&&this.region.writeAbove(r);return}this.region.update();}}onStepEnd(t,n,o){}onSectionStart(t,n){}onTestEnd(t,n,o){o?.recovered&&this.recovered.add(t);let r=this.running.get(t),i=r?this.formatRow({testRef:t,status:n,index:r.index,elapsedMs:Date.now()-r.startedAt}):this.formatRow({testRef:t,status:n,index:++this.nextIndex});if(r&&this.running.delete(t),i){this.region.writeAbove(i);return}this.region.update();}onEnd(t){this.region.clear();}commitRow(t){let n=this.formatRow(t);n&&this.region.writeAbove(n);}renderRunningRows(t){let n=[];for(let[o,r]of this.running){let i=this.formatRow({testRef:o,status:r.status,index:r.index,note:r.note,elapsedMs:Date.now()-r.startedAt,step:r.step,tick:t,classifying:r.classifying});i&&n.push(i);}return n}formatRow(t){let n=OT(t.status,this.screen,t.tick);if(!n)return;let o=t.classifying===true&&!n.isTerminal,r=o?this.theme.classifySpinner(t.tick??0):n.badge,s=String(this.totalTests).length*2+3,a=`[${t.index}/${this.totalTests}]`.padStart(s),l=this.quarantined.has(t.testRef)?" [quarantined]":"",c=this.recovered.has(t.testRef)?" [recovered]":"",d=typeof t.elapsedMs=="number"?Math.floor(t.elapsedMs/1e3):0,p=(n.isTerminal?typeof t.elapsedMs=="number":d>=1)?` (${Math.max(1,d)}s)`:"",m=this.screen.columns>0?this.screen.columns:QBe,h=s+3+t.testRef.length+l.length+c.length+p.length,g=Math.max(ZBe,m-1)-h,f=o?`${e0e}${t.classifyPending?"\u2026":""}`:t.step&&!n.isTerminal?t.step.text:void 0,S=f?vB(o?" \xB7 ":" \u203A ",f,g):"";g-=S.length;let T=t.note?vB(" ",t.note,g):"";return `${il.dim(a)} ${r} ${t.testRef}${il.dim(l)}${il.dim(c)}${il.dim(S)}${T}${il.dim(p)}`}};var nx=class{constructor(t){this.reporters=t;}onBegin(t){for(let n of this.reporters)n.onBegin(t);}onTestBegin(t){for(let n of this.reporters)n.onTestBegin(t);}onTestStatus(t,n,o){for(let r of this.reporters)r.onTestStatus(t,n,o);}onStepStart(t,n,o){for(let r of this.reporters)r.onStepStart(t,n,o);}onStepEnd(t,n,o){for(let r of this.reporters)r.onStepEnd(t,n,o);}onSectionStart(t,n){for(let o of this.reporters)o.onSectionStart(t,n);}onTestEnd(t,n,o){for(let r of this.reporters)r.onTestEnd(t,n,o);}onEnd(t){for(let n of this.reporters)n.onEnd(t);}};var t0e="classifying failure",ox=class{totalTests=0;nextIndex=0;running=new Map;quarantined=new Set;recovered=new Set;theme;screen;constructor(t){this.screen=t,this.theme=Mn(t);}onBegin(t){this.totalTests=t.tests.length,this.nextIndex=0,this.quarantined.clear(),this.recovered.clear();for(let n of t.tests)n.quarantined&&this.quarantined.add(n.relativeFilePath);for(let n of t.tests){if(!n.skipped)continue;this.nextIndex+=1;let o=n.skipped.kind==="quarantined"?` ${n.skipped.reason}`:"";this.write(`${this.counter(this.nextIndex)}${this.theme.statusGlyph("skip")} ${n.relativeFilePath}${o}`);}}onTestBegin(t){this.nextIndex+=1,this.running.set(t,{index:this.nextIndex,startedAt:Date.now()}),this.write(`${this.counter(this.nextIndex)}${this.theme.bold(t)}`);}onTestStatus(t,n,o){let r=this.running.get(t);r||(this.nextIndex+=1,r={index:this.nextIndex,startedAt:Date.now()},this.running.set(t,r));let i=OT(n,this.screen);if(!i||i.isTerminal||n==="RUN")return;let s=o?` ${il.dim(o)}`:"";this.detail(r,1,`${i.badge} ${this.theme.dim(n.toLowerCase())}${s}`);}onStepStart(t,n,o=0){let r=this.running.get(t);if(r){if(n===Zc){this.detail(r,1,`${this.theme.classifySpinner(0)} ${this.theme.dim(`${t0e}\u2026`)}`);return}this.detail(r,this.stepIndent(r,o),this.theme.dim(`- ${n}`));}}onStepEnd(t,n,o){let r=this.running.get(t);if(!r)return;let i=this.theme.statusGlyph(o.success?"pass":"fail");this.detail(r,this.stepIndent(r,o.depth),`${i} ${this.theme.dim(Kd(o.durationMs))}`);}onSectionStart(t,n){let o=this.running.get(t);o&&(o.sectioned=true,this.detail(o,1,this.theme.dim(n)));}onTestEnd(t,n,o){o?.recovered&&this.recovered.add(t);let r=this.running.get(t),i=OT(n,this.screen),s=r?.index??++this.nextIndex;if(r&&this.running.delete(t),!i)return;let a=this.quarantined.has(t)?" [quarantined]":"",l=this.recovered.has(t)?" [recovered]":"",c=r?` (${Math.max(1,Math.floor((Date.now()-r.startedAt)/1e3))}s)`:"",d=r?"":` ${t}`;this.write(`${this.counter(s)}${i.badge}${d}${il.dim(a)}${il.dim(l)}${il.dim(c)}`);}onEnd(t){}stepIndent(t,n){return n+(t.sectioned?2:1)}detail(t,n,o){this.write(`${this.counter(t.index)}${" ".repeat(n)}${o}`);}counter(t){if(this.totalTests<=1)return "";let o=String(this.totalTests).length*2+3;return il.dim(`[${t}/${this.totalTests}]`.padStart(o))+" "}write(t){process.stdout.write(`${t}
|
|
327
327
|
`);}};var o0e="list",K9="steps",rx=["json","junit","allure","allure-json","playwright-json","buildkite-json"],ix=["newrelic"],q9=[o0e,K9,...rx,...ix];function Y9(e,t){if(!q9.includes(e))throw new InvalidArgumentError$2(`Allowed choices are ${q9.join(", ")}.`);return [...t,e]}function J9(e){let t=[],n=[];for(let r of e.reporter??[]){let i=rx.find(a=>a===r);i&&t.push(i);let s=ix.find(a=>a===r);s&&n.push(s);}let o=e.reporter?.includes(K9)?new ox(e.screen):new tx(e.screen);return {live:new nx([o]),files:t,network:n}}function sx(e,t){return e.split(`
|
|
328
|
-
`).map(n=>t.color?n.startsWith("+")?il.green(n):n.startsWith("-")?il.red(n):n.startsWith("@@")?t.dim(n):n:n)}var PA=25;function Q9(e){return {v2ProjectConfig:{...e.config,fileFormat:"v2"},migratedFilePaths:[]}}function Z9(e){return {legacyProjectConfig:{...e.config,fileFormat:"v1"},migratedFilePaths:[]}}function MB({project:e,newProjectConfig:t,fileFormatLabel:n,migratedFilePaths:o}){e.config=t,Fd(e.config,e.configFilePath),o.push(e.configFilePath),C.info(`Updated ${e.configFilePath} to use ${n} file format`),t.hooks?.postSave&&(C.info(`Running post-save hook for ${o.length} migrated files`),aI([...new Set(o)],t));}async function OA(e,t,n){for(let o=0;o<e.length;o+=t)await Promise.all(e.slice(o,o+t).map(n));}function NB(e){return e.upgradedAgents.length>0||e.enabledUseMemory||e.enabledFailureRecovery}function s0e(e){let t=e.ai??={},n=t.agentConfig??={},o=[];for(let[s,a]of Object.entries(ku)){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 e7({project:e,dryRun:t,migrate:n}){let o=e.config.fileFormat!=="v2",r=PT.stringify(e.config),i=s0e(e.config);if(!o)return !t&&NB(i)&&Fd(e.config,e.configFilePath),{fileFormatChanged:false,aiSettings:i,migration:LB(),configDiff:PB(r,e.config)};let s=await n();return {fileFormatChanged:o,aiSettings:i,migration:s,configDiff:PB(r,{...e.config,fileFormat:"v2"})}}function PB(e,t){return Um(e,PT.stringify(t),{n_surrounding:2})}function t7(e){return PB(PT.stringify(e),{...e,fileFormat:"v2"})}function LB(){return {migratedTestPaths:[],migratedModulePaths:[],alreadyV2TestCount:0,alreadyV2ModuleCount:0}}function kB({summary:e,fileFormatChanged:t,configChange:n,dryRun:o,testNoun:r="test",moduleNoun:i="module"}){let s=dt(),a=Mn(s),l=a.color?il.green("~"):"~";C.info(""),C.info(zn(o?"Upgrade Preview":"Upgrade Summary",s)),C.info("");let c=m=>` ${l} ${a.code(io__default.relative(process.cwd(),m))}`,d=(m,h)=>{let g=Tf(m,h);return `${a.bold(g.charAt(0).toUpperCase()+g.slice(1))} ${a.dim(`(${h})`)}`},u=e.migratedTestPaths.length,p=e.migratedModulePaths.length;if(t||u>0||p>0){let m=o?"Would migrate":"Migrated";if(C.info(`${m} ${a.bold(`${u} ${Tf(r,u)}`)} and ${a.bold(`${p} ${Tf(i,p)}`)} to the simplified format.`),C.info(""),u>0){C.info(d(r,u));for(let h of [...e.migratedTestPaths].sort())C.info(c(h));C.info("");}if(p>0){C.info(d(i,p));for(let h of [...e.migratedModulePaths].sort())C.info(c(h));C.info("");}(e.alreadyV2TestCount>0||e.alreadyV2ModuleCount>0)&&(C.dimmed(`Skipped ${e.alreadyV2TestCount} already-migrated ${Tf(r,e.alreadyV2TestCount)} and ${e.alreadyV2ModuleCount} already-migrated ${Tf(i,e.alreadyV2ModuleCount)}.`),C.info(""));}if(n&&n.diff.trim().length>0){C.info(d("config",1)),C.info(c(n.configFilePath));for(let m of sx(n.diff,a))C.info(` ${m}`);C.info("");}}var DB=false,n7;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.25.0",tracesSampleRate:0,skipOpenTelemetrySetup:!0,sendDefaultPii:!0,beforeSend(n,o){return I4(o?.originalException)||ob(o?.originalException,Oe)||x4(o?.originalException)?null:n}}),TX(e.captureException),n7=n=>{if(!n){e.setUser(null);return}e.setUser({id:n.userId,organizationId:n.orgId,...n.email&&{email:n.email}});},DB=!0;}catch{}var o7=e=>n7?.(e);var l0e=new bw(30,60*1e3),NA="https://api.momentic.ai",my,r7,Xd=e=>{NA=e;},Xi=()=>NA,i7=()=>ef(NA),Tp=e=>{r7=e;},Il=()=>r7,Do=()=>my,s7=()=>{if(!my)throw new Error("Global API client has not been initialized.");return my};var MA,lx,a7,l7,c7,cx,d7,u7=({authInfo:e,apiKey:t,apiClient:n})=>{NA=n.baseUrl,my=n,MA=e.orgId,lx=e.userId,a7=e.email,l7=e.name,c7=e.pylonEmailHash,cx=t,d7=e.selfServe;},Ap=async({apiClient:e,apiKey:t,skipPrompts:n})=>{let o=await oh({client:e});return u7({authInfo:o,apiKey:t,apiClient:e}),o},px=async({apiKey:e,mode:t,runner:n})=>{if(my&&MA&&cx)return MA;let o=new xt({baseUrl:NA,apiKey:e,logger:C,mode:t,runner:n});my=o;try{let r=await o.getAuthInfo();return u7({authInfo:r,apiKey:e,apiClient:o}),r.orgId}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},ho=()=>{if(!MA)throw new Error("Your organization ID is invalid.");return MA},Oc=()=>{if(!lx)throw new Error("Your user ID is invalid.");return lx},p7=()=>lx,hy=()=>a7,m7=()=>l7,h7=()=>c7,mx=()=>d7,xl=()=>{if(!cx)throw new Error("Your API key is invalid.");return cx},dx,ux,Qd=()=>{ux?.abort(),ux=void 0;},Ep=(e,t)=>{dx=e,Qd(),ux=new AbortController;let n=ux.signal,o=[e.configFilePath];e.config.environments?.forEach(r=>{if(!r.envFile)return;let i=io__default.resolve(e.rootDir,r.envFile);try{if(ko__default.lstatSync(i).isSymbolicLink())return;ko__default.existsSync(i)&&o.push(i);}catch(s){C.warn({err:s},`Failed to check if env file ${i} exists`);}});try{c0e({filesToWatch:o,revalidator:t,signal:n,project:e});}catch(r){C.error({err:r},"Failed to start config file watchers");}};async function gy({project:e,apiClient:t}){let n=o=>qi({project:o,apiClient:t});Ep(await n(e),async o=>n(await qt({configFilePath:o})));}var at=()=>{if(!dx)throw new Oe("No Momentic project is currently loaded. Open or select a project before invoking this action.");return dx};function c0e({filesToWatch:e,revalidator:t,signal:n,project:o}){C.debug("Starting watch on the following files:"),e.forEach(r=>{C.debug(`- ${r}`);}),e.forEach(r=>{let i=async(a,l)=>{if(a.mtime.getTime()!==l.mtime.getTime()){l0e.increment("setLocalProject")&&C.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{dx=await Promise.resolve(t(o.configFilePath));}catch(c){C.warn({err:c},`Failed to reload Momentic configuration after a change to ${r}; continuing with the previously loaded configuration`);}}};ko__default.watchFile(r,{persistent:false},i);let s=()=>{ko__default.unwatchFile(r,i),n.removeEventListener("abort",s);};n.addEventListener("abort",s);});}function Et(e){return function(...t){let n=t[t.length-1],o=e(...t);Promise.resolve(o).catch(n);}}var u0e="3.25.0",ih=rf({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:u0e});(async()=>{try{let e=await Ua(ih);e.gitBranchName&&ih.addBinding("branch",e.gitBranchName);}catch{}})();var g7=Router();g7.get("/",async(e,t)=>{let n=at(),o=Do();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await Mr(ih,o,n),i=r?.gitProtectedBranches&&r?.gitBranchName&&r.gitProtectedBranches.includes(r.gitBranchName),{noCache:s,alwaysSaveCache:a}=Il(),l=!s&&(a||!i);t.status(200).json({saveCaches:l,checkedOutBranch:r?.gitBranchName});});var FB=g7;var h0e=5e3,g0e=[".js",".mjs",".cjs",".ts"];function BB(e={}){let t=Router();function n(){let u=at();return io__default.dirname(u.configFilePath)}function o(u){return io__default.join(n(),...u)}function r(u){let p=io__default.relative(n(),u);return p?p.split(io__default.sep):[]}function i(u,p){let m=ko__default.statSync(u),h=r(u);return bL.parse({name:p,absolutePath:u,relativePath:h.join(io__default.sep),pathSegments:h,isDirectory:m.isDirectory(),size:m.size,createdAt:m.birthtime,modifiedAt:m.mtime,accessedAt:m.atime})}function s(u){let p=io__default.relative(n(),u);return p===""||!p.startsWith("..")&&!io__default.isAbsolute(p)}async function a(u){let p=at();return kd(["*"],{cwd:u,ignore:p.config.exclude??[],maxDepth:1,nodir:false,signal:AbortSignal.timeout(h0e)})}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=io__default.relative(u,p).split(io__default.sep).join("/");return m?h?`${h}/`:"./":h}return t.post("/file-reference-suggestions",Et(async(u,p,m)=>{let h=c2.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??g0e).map(R=>R.toLowerCase())),S=l(f);if(S.directoryText.startsWith("/")){p.status(200).json({suggestions:[]});return}let T=io__default.resolve(n(),...c(g)),A=io__default.resolve(T,...c(S.directoryText));if(!s(T)||!s(A)){p.status(200).json({suggestions:[]});return}if(!ko__default.existsSync(A)||!ko__default.statSync(A).isDirectory()){p.status(200).json({suggestions:[]});return}let v;try{v=await a(A);}catch(R){if(R instanceof Error&&R.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw R}let w=v.map(R=>{let x=io__default.join(A,R);return {entryName:R,targetPath:x,isDirectory:ko__default.statSync(x).isDirectory()}}),I=S.filePrefix.toLowerCase(),_=w.filter(R=>R.entryName.startsWith(".")||!R.entryName.toLowerCase().startsWith(I)?false:R.isDirectory?true:y.has(io__default.extname(R.entryName).toLowerCase())).sort((R,x)=>R.isDirectory!==x.isDirectory?R.isDirectory?-1:1:R.entryName.localeCompare(x.entryName)).map(R=>({name:R.entryName,isDirectory:R.isDirectory,value:d({sourceDirectoryPath:T,targetPath:R.targetPath,isDirectory:R.isDirectory})}));p.status(200).json({suggestions:_});})),t.post("/",Et(async(u,p,m)=>{let h;try{h=l2.parse(u.body).pathSegments;}catch(A){p.status(400).json({error:`Failed to parse folder read body: ${A}`});return}let g=o(h);if(!ko__default.existsSync(g)){p.status(404).json({error:`Path not found: ${h.join(io__default.sep)}`});return}if(!ko__default.statSync(g).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(io__default.sep)}`});return}let y;try{y=await a(g);}catch(A){if(A instanceof Error&&A.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw A}let S=y.map(A=>{let v=io__default.join(g,A);return i(v,A)});if(e.allowedFileTypes){let A=new Set(e.allowedFileTypes);S=(await Promise.all(S.map(async v=>{if(v.isDirectory||!(v.name.endsWith(".test.yaml")||v.name.endsWith(".module.yaml")))return v;let I=await f0e(v.absolutePath);return I!==void 0&&A.has(I)?v:null}))).filter(v=>v!==null);}let T={absolutePath:g,pathSegments:h,contents:S};p.status(200).json(T);})),t.put("/",Et(async(u,p,m)=>{let h;try{h=d2.parse(u.body).pathSegments;}catch(y){p.status(400).json({error:`Failed to parse folder create body: ${y}`});return}let g=o(h);if(ko__default.existsSync(g)){p.status(200).json({success:true,message:`Folder already exists: ${h.join(io__default.sep)}`,pathSegments:h});return}ko__default.mkdirSync(g,{recursive:true});let f={success:true,message:`Folder created: ${h.join(io__default.sep)}`,pathSegments:h};p.status(201).json(f);})),t.patch("/",Et(async(u,p,m)=>{let h,g;try{let A=u2.parse(u.body);h=A.pathSegments,g=A.newPathSegments;}catch(A){p.status(400).json({error:`Failed to parse folder update body: ${A}`});return}let f=o(h),y=o(g);if(!ko__default.existsSync(f)){p.status(400).json({error:`Folder not found: ${h.join(io__default.sep)}`});return}if(ko__default.existsSync(y)){p.status(400).json({error:`Destination already exists: ${g.join(io__default.sep)}`});return}let S=io__default.dirname(y);ko__default.existsSync(S)||ko__default.mkdirSync(S,{recursive:true}),ko__default.renameSync(f,y);let T={success:true,message:`Folder moved from ${h.join(io__default.sep)} to ${g.join(io__default.sep)}`,pathSegments:g};p.status(200).json(T);})),t.delete("/",Et(async(u,p,m)=>{let h,g=true;try{let T=p2.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(!ko__default.existsSync(f)){p.status(200).json({success:true,message:`Folder not found: ${h.join(io__default.sep)}`,pathSegments:h});return}if(!ko__default.statSync(f).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(io__default.sep)}`});return}try{if(g)ko__default.rmSync(f,{recursive:!0,force:!0});else {if(ko__default.readdirSync(f).length>0){p.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${h.join("/")}`});return}ko__default.rmdirSync(f);}}catch(T){let{status:A,body:v}=Z8(T,`delete folder ${h.join("/")}`);p.status(A).json(v);return}let S={success:true,message:`Folder deleted: ${h.join("/")}`,pathSegments:h};p.status(200).json(S);})),t}async function f0e(e){try{let t=await ko__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 f7=Router();f7.get("/",async(e,t)=>{let n=at(),o=Do();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await Mr(ih,o,n);t.status(200).json(r);});var UB=f7;var S0e=({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{}}},y7={event:"cancel",createHandler:S0e};var b0e=({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=xw(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:q(d)});}}},S7={event:"clearAIActionCache",createHandler:b0e};var T0e=({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});}}},b7={event:"fetchA11yTree",createHandler:T0e};var A0e=({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});}}},T7={event:"fetchDom",createHandler:A0e};var E0e=({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);}},A7={event:"disconnect",createHandler:E0e};function Es(e){let{result:t,nestedResults:n}=e;if(!e.nestedResults.length)return;let{firstMetadata:o,lastMetadata:r}=v0e(n);C0e(t,o,r);let i=[...e.asyncTasks];e.asyncTasks.push((async()=>{try{await R0e(i,t,o,r);}catch(s){e.logger.error({result:e.result,err:s},"Error hoisting scalar result metadata");}})());}function v0e(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 C0e(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 R0e(e,t,n,o){await Promise.allSettled(e),n&&(t.beforeSnapshot=n.beforeSnapshot),o&&(t.afterSnapshot=o.afterSnapshot);}async function E7(e){let t;try{t=new URL(e.url).hostname;}catch{}let n=[];return e.headers.getSetCookie()?.forEach(o=>{let r=qC(o,t);n.push(...r);}),n}function N0e(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 L0e(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 k0e=Object.getPrototypeOf(async function(){}).constructor;async function v7(e,t,n){let o=t.code;t.options.fragment&&(o=`return ${t.code}`),o=`${o}
|
|
328
|
+
`).map(n=>t.color?n.startsWith("+")?il.green(n):n.startsWith("-")?il.red(n):n.startsWith("@@")?t.dim(n):n:n)}var PA=25;function Q9(e){return {v2ProjectConfig:{...e.config,fileFormat:"v2"},migratedFilePaths:[]}}function Z9(e){return {legacyProjectConfig:{...e.config,fileFormat:"v1"},migratedFilePaths:[]}}function MB({project:e,newProjectConfig:t,fileFormatLabel:n,migratedFilePaths:o}){e.config=t,Fd(e.config,e.configFilePath),o.push(e.configFilePath),C.info(`Updated ${e.configFilePath} to use ${n} file format`),t.hooks?.postSave&&(C.info(`Running post-save hook for ${o.length} migrated files`),aI([...new Set(o)],t));}async function OA(e,t,n){for(let o=0;o<e.length;o+=t)await Promise.all(e.slice(o,o+t).map(n));}function NB(e){return e.upgradedAgents.length>0||e.enabledUseMemory||e.enabledFailureRecovery}function s0e(e){let t=e.ai??={},n=t.agentConfig??={},o=[];for(let[s,a]of Object.entries(ku)){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 e7({project:e,dryRun:t,migrate:n}){let o=e.config.fileFormat!=="v2",r=PT.stringify(e.config),i=s0e(e.config);if(!o)return !t&&NB(i)&&Fd(e.config,e.configFilePath),{fileFormatChanged:false,aiSettings:i,migration:LB(),configDiff:PB(r,e.config)};let s=await n();return {fileFormatChanged:o,aiSettings:i,migration:s,configDiff:PB(r,{...e.config,fileFormat:"v2"})}}function PB(e,t){return Um(e,PT.stringify(t),{n_surrounding:2})}function t7(e){return PB(PT.stringify(e),{...e,fileFormat:"v2"})}function LB(){return {migratedTestPaths:[],migratedModulePaths:[],alreadyV2TestCount:0,alreadyV2ModuleCount:0}}function kB({summary:e,fileFormatChanged:t,configChange:n,dryRun:o,testNoun:r="test",moduleNoun:i="module"}){let s=dt(),a=Mn(s),l=a.color?il.green("~"):"~";C.info(""),C.info(zn(o?"Upgrade Preview":"Upgrade Summary",s)),C.info("");let c=m=>` ${l} ${a.code(io__default.relative(process.cwd(),m))}`,d=(m,h)=>{let g=Tf(m,h);return `${a.bold(g.charAt(0).toUpperCase()+g.slice(1))} ${a.dim(`(${h})`)}`},u=e.migratedTestPaths.length,p=e.migratedModulePaths.length;if(t||u>0||p>0){let m=o?"Would migrate":"Migrated";if(C.info(`${m} ${a.bold(`${u} ${Tf(r,u)}`)} and ${a.bold(`${p} ${Tf(i,p)}`)} to the simplified format.`),C.info(""),u>0){C.info(d(r,u));for(let h of [...e.migratedTestPaths].sort())C.info(c(h));C.info("");}if(p>0){C.info(d(i,p));for(let h of [...e.migratedModulePaths].sort())C.info(c(h));C.info("");}(e.alreadyV2TestCount>0||e.alreadyV2ModuleCount>0)&&(C.dimmed(`Skipped ${e.alreadyV2TestCount} already-migrated ${Tf(r,e.alreadyV2TestCount)} and ${e.alreadyV2ModuleCount} already-migrated ${Tf(i,e.alreadyV2ModuleCount)}.`),C.info(""));}if(n&&n.diff.trim().length>0){C.info(d("config",1)),C.info(c(n.configFilePath));for(let m of sx(n.diff,a))C.info(` ${m}`);C.info("");}}var DB=false,n7;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.25.1",tracesSampleRate:0,skipOpenTelemetrySetup:!0,sendDefaultPii:!0,beforeSend(n,o){return I4(o?.originalException)||ob(o?.originalException,Oe)||x4(o?.originalException)?null:n}}),TX(e.captureException),n7=n=>{if(!n){e.setUser(null);return}e.setUser({id:n.userId,organizationId:n.orgId,...n.email&&{email:n.email}});},DB=!0;}catch{}var o7=e=>n7?.(e);var l0e=new bw(30,60*1e3),NA="https://api.momentic.ai",my,r7,Xd=e=>{NA=e;},Xi=()=>NA,i7=()=>ef(NA),Tp=e=>{r7=e;},Il=()=>r7,Do=()=>my,s7=()=>{if(!my)throw new Error("Global API client has not been initialized.");return my};var MA,lx,a7,l7,c7,cx,d7,u7=({authInfo:e,apiKey:t,apiClient:n})=>{NA=n.baseUrl,my=n,MA=e.orgId,lx=e.userId,a7=e.email,l7=e.name,c7=e.pylonEmailHash,cx=t,d7=e.selfServe;},Ap=async({apiClient:e,apiKey:t,skipPrompts:n})=>{let o=await oh({client:e});return u7({authInfo:o,apiKey:t,apiClient:e}),o},px=async({apiKey:e,mode:t,runner:n})=>{if(my&&MA&&cx)return MA;let o=new xt({baseUrl:NA,apiKey:e,logger:C,mode:t,runner:n});my=o;try{let r=await o.getAuthInfo();return u7({authInfo:r,apiKey:e,apiClient:o}),r.orgId}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},ho=()=>{if(!MA)throw new Error("Your organization ID is invalid.");return MA},Oc=()=>{if(!lx)throw new Error("Your user ID is invalid.");return lx},p7=()=>lx,hy=()=>a7,m7=()=>l7,h7=()=>c7,mx=()=>d7,xl=()=>{if(!cx)throw new Error("Your API key is invalid.");return cx},dx,ux,Qd=()=>{ux?.abort(),ux=void 0;},Ep=(e,t)=>{dx=e,Qd(),ux=new AbortController;let n=ux.signal,o=[e.configFilePath];e.config.environments?.forEach(r=>{if(!r.envFile)return;let i=io__default.resolve(e.rootDir,r.envFile);try{if(ko__default.lstatSync(i).isSymbolicLink())return;ko__default.existsSync(i)&&o.push(i);}catch(s){C.warn({err:s},`Failed to check if env file ${i} exists`);}});try{c0e({filesToWatch:o,revalidator:t,signal:n,project:e});}catch(r){C.error({err:r},"Failed to start config file watchers");}};async function gy({project:e,apiClient:t}){let n=o=>qi({project:o,apiClient:t});Ep(await n(e),async o=>n(await qt({configFilePath:o})));}var at=()=>{if(!dx)throw new Oe("No Momentic project is currently loaded. Open or select a project before invoking this action.");return dx};function c0e({filesToWatch:e,revalidator:t,signal:n,project:o}){C.debug("Starting watch on the following files:"),e.forEach(r=>{C.debug(`- ${r}`);}),e.forEach(r=>{let i=async(a,l)=>{if(a.mtime.getTime()!==l.mtime.getTime()){l0e.increment("setLocalProject")&&C.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{dx=await Promise.resolve(t(o.configFilePath));}catch(c){C.warn({err:c},`Failed to reload Momentic configuration after a change to ${r}; continuing with the previously loaded configuration`);}}};ko__default.watchFile(r,{persistent:false},i);let s=()=>{ko__default.unwatchFile(r,i),n.removeEventListener("abort",s);};n.addEventListener("abort",s);});}function Et(e){return function(...t){let n=t[t.length-1],o=e(...t);Promise.resolve(o).catch(n);}}var u0e="3.25.1",ih=rf({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:u0e});(async()=>{try{let e=await Ua(ih);e.gitBranchName&&ih.addBinding("branch",e.gitBranchName);}catch{}})();var g7=Router();g7.get("/",async(e,t)=>{let n=at(),o=Do();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await Mr(ih,o,n),i=r?.gitProtectedBranches&&r?.gitBranchName&&r.gitProtectedBranches.includes(r.gitBranchName),{noCache:s,alwaysSaveCache:a}=Il(),l=!s&&(a||!i);t.status(200).json({saveCaches:l,checkedOutBranch:r?.gitBranchName});});var FB=g7;var h0e=5e3,g0e=[".js",".mjs",".cjs",".ts"];function BB(e={}){let t=Router();function n(){let u=at();return io__default.dirname(u.configFilePath)}function o(u){return io__default.join(n(),...u)}function r(u){let p=io__default.relative(n(),u);return p?p.split(io__default.sep):[]}function i(u,p){let m=ko__default.statSync(u),h=r(u);return bL.parse({name:p,absolutePath:u,relativePath:h.join(io__default.sep),pathSegments:h,isDirectory:m.isDirectory(),size:m.size,createdAt:m.birthtime,modifiedAt:m.mtime,accessedAt:m.atime})}function s(u){let p=io__default.relative(n(),u);return p===""||!p.startsWith("..")&&!io__default.isAbsolute(p)}async function a(u){let p=at();return kd(["*"],{cwd:u,ignore:p.config.exclude??[],maxDepth:1,nodir:false,signal:AbortSignal.timeout(h0e)})}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=io__default.relative(u,p).split(io__default.sep).join("/");return m?h?`${h}/`:"./":h}return t.post("/file-reference-suggestions",Et(async(u,p,m)=>{let h=c2.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??g0e).map(R=>R.toLowerCase())),S=l(f);if(S.directoryText.startsWith("/")){p.status(200).json({suggestions:[]});return}let T=io__default.resolve(n(),...c(g)),A=io__default.resolve(T,...c(S.directoryText));if(!s(T)||!s(A)){p.status(200).json({suggestions:[]});return}if(!ko__default.existsSync(A)||!ko__default.statSync(A).isDirectory()){p.status(200).json({suggestions:[]});return}let v;try{v=await a(A);}catch(R){if(R instanceof Error&&R.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw R}let w=v.map(R=>{let x=io__default.join(A,R);return {entryName:R,targetPath:x,isDirectory:ko__default.statSync(x).isDirectory()}}),I=S.filePrefix.toLowerCase(),_=w.filter(R=>R.entryName.startsWith(".")||!R.entryName.toLowerCase().startsWith(I)?false:R.isDirectory?true:y.has(io__default.extname(R.entryName).toLowerCase())).sort((R,x)=>R.isDirectory!==x.isDirectory?R.isDirectory?-1:1:R.entryName.localeCompare(x.entryName)).map(R=>({name:R.entryName,isDirectory:R.isDirectory,value:d({sourceDirectoryPath:T,targetPath:R.targetPath,isDirectory:R.isDirectory})}));p.status(200).json({suggestions:_});})),t.post("/",Et(async(u,p,m)=>{let h;try{h=l2.parse(u.body).pathSegments;}catch(A){p.status(400).json({error:`Failed to parse folder read body: ${A}`});return}let g=o(h);if(!ko__default.existsSync(g)){p.status(404).json({error:`Path not found: ${h.join(io__default.sep)}`});return}if(!ko__default.statSync(g).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(io__default.sep)}`});return}let y;try{y=await a(g);}catch(A){if(A instanceof Error&&A.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw A}let S=y.map(A=>{let v=io__default.join(g,A);return i(v,A)});if(e.allowedFileTypes){let A=new Set(e.allowedFileTypes);S=(await Promise.all(S.map(async v=>{if(v.isDirectory||!(v.name.endsWith(".test.yaml")||v.name.endsWith(".module.yaml")))return v;let I=await f0e(v.absolutePath);return I!==void 0&&A.has(I)?v:null}))).filter(v=>v!==null);}let T={absolutePath:g,pathSegments:h,contents:S};p.status(200).json(T);})),t.put("/",Et(async(u,p,m)=>{let h;try{h=d2.parse(u.body).pathSegments;}catch(y){p.status(400).json({error:`Failed to parse folder create body: ${y}`});return}let g=o(h);if(ko__default.existsSync(g)){p.status(200).json({success:true,message:`Folder already exists: ${h.join(io__default.sep)}`,pathSegments:h});return}ko__default.mkdirSync(g,{recursive:true});let f={success:true,message:`Folder created: ${h.join(io__default.sep)}`,pathSegments:h};p.status(201).json(f);})),t.patch("/",Et(async(u,p,m)=>{let h,g;try{let A=u2.parse(u.body);h=A.pathSegments,g=A.newPathSegments;}catch(A){p.status(400).json({error:`Failed to parse folder update body: ${A}`});return}let f=o(h),y=o(g);if(!ko__default.existsSync(f)){p.status(400).json({error:`Folder not found: ${h.join(io__default.sep)}`});return}if(ko__default.existsSync(y)){p.status(400).json({error:`Destination already exists: ${g.join(io__default.sep)}`});return}let S=io__default.dirname(y);ko__default.existsSync(S)||ko__default.mkdirSync(S,{recursive:true}),ko__default.renameSync(f,y);let T={success:true,message:`Folder moved from ${h.join(io__default.sep)} to ${g.join(io__default.sep)}`,pathSegments:g};p.status(200).json(T);})),t.delete("/",Et(async(u,p,m)=>{let h,g=true;try{let T=p2.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(!ko__default.existsSync(f)){p.status(200).json({success:true,message:`Folder not found: ${h.join(io__default.sep)}`,pathSegments:h});return}if(!ko__default.statSync(f).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(io__default.sep)}`});return}try{if(g)ko__default.rmSync(f,{recursive:!0,force:!0});else {if(ko__default.readdirSync(f).length>0){p.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${h.join("/")}`});return}ko__default.rmdirSync(f);}}catch(T){let{status:A,body:v}=Z8(T,`delete folder ${h.join("/")}`);p.status(A).json(v);return}let S={success:true,message:`Folder deleted: ${h.join("/")}`,pathSegments:h};p.status(200).json(S);})),t}async function f0e(e){try{let t=await ko__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 f7=Router();f7.get("/",async(e,t)=>{let n=at(),o=Do();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await Mr(ih,o,n);t.status(200).json(r);});var UB=f7;var S0e=({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{}}},y7={event:"cancel",createHandler:S0e};var b0e=({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=xw(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:q(d)});}}},S7={event:"clearAIActionCache",createHandler:b0e};var T0e=({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});}}},b7={event:"fetchA11yTree",createHandler:T0e};var A0e=({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});}}},T7={event:"fetchDom",createHandler:A0e};var E0e=({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);}},A7={event:"disconnect",createHandler:E0e};function Es(e){let{result:t,nestedResults:n}=e;if(!e.nestedResults.length)return;let{firstMetadata:o,lastMetadata:r}=v0e(n);C0e(t,o,r);let i=[...e.asyncTasks];e.asyncTasks.push((async()=>{try{await R0e(i,t,o,r);}catch(s){e.logger.error({result:e.result,err:s},"Error hoisting scalar result metadata");}})());}function v0e(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 C0e(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 R0e(e,t,n,o){await Promise.allSettled(e),n&&(t.beforeSnapshot=n.beforeSnapshot),o&&(t.afterSnapshot=o.afterSnapshot);}async function E7(e){let t;try{t=new URL(e.url).hostname;}catch{}let n=[];return e.headers.getSetCookie()?.forEach(o=>{let r=qC(o,t);n.push(...r);}),n}function N0e(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 L0e(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 k0e=Object.getPrototypeOf(async function(){}).constructor;async function v7(e,t,n){let o=t.code;t.options.fragment&&(o=`return ${t.code}`),o=`${o}
|
|
329
329
|
//# sourceURL=${QC}`;let{env:r,additionalBindings:i,request:s,response:a}=t.bindings,l=t.tools,c={},d=(T,A)=>{r[T]=A,c[T]=A;},u={},p=(T,A)=>{r[T]=A,u[T]=A;},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 k0e("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","mock",...Object.keys(i??{}),o)(x0e,P0e,l.fakerInstance??faker,I0e,M0e,m,h,O0e,_0e,E7,r,t.options.disallowVariableUpdates?void 0:d,t.options.disallowVariableUpdates?void 0:p,A=>l.sms.send(A),A=>l.sms.fetchLatest(A),l.email,l.sms,N0e(s,a),...Object.values(i??{})))}catch(T){throw new Hv(q(T),{cause:T})}},f=true,y,S;try{let T=await xe(g(),{milliseconds:t.options.timeoutMs,message:`Timeout of ${t.options.timeoutMs}ms exceeded for code execution`,signal:t.signal});y=await L0e(t.options.responseSerialization??"RAW",T);}catch(T){n.error({err:T,env:r,evalCode:o},`[${e}] Error executing code: ${T}`),f=false,T instanceof zu?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 C7({code:e,fragment:t,context:n,localTools:o,logger:r,signal:i,timeoutMs:s=Hu,disallowVariableUpdates:a,additionalBindings:l,responseSerialization:c,mock:d}){let u=randomUUID(),p=await v7(u,{code:e,options:{fragment:t,timeoutMs:s,disallowVariableUpdates:a,responseSerialization:c},bindings:{...n.toObjectCopy(),...d,additionalBindings:l},tools:o,signal:i},r);return C.debug(`[${u}] Got execution result: ${JSON.stringify(p)}`),p}var HB="Momentic's code execution service is temporarily unavailable. This is not a problem with your test. Please try again in a moment.",H0e=mCe(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}}),R7=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,w7=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function I7({orgId:e,code:t,fragment:n,context:o,timeoutMs:r=Hu,retries:i=2,signal:s,logger:a,additionalBindings:l,disallowVariableUpdates:c,responseSerialization:d,mock:u}){if(!R7)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,h=0;if(!w7)throw new Error("Missing lambda auth secret.");let g=createHmac("sha256",w7).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 xe(H0e(R7,{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"),new Cu(HB,{cause:m});if(!p)throw new Cu(HB);let f;try{f=Pq.parse(await p.json());}catch(y){throw new Cu(HB,{cause:y})}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function vp(e){let t;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)t=await I7(e);else if(e.localTools)t=await C7({...e,localTools:e.localTools});else throw new Error("No code evaluation environment available");if(t.error){let n=`Failed to evaluate code:
|
|
330
330
|
${t.error}
|
|
331
331
|
Code received:
|
|
@@ -5793,7 +5793,7 @@ ${e}`;case "ELEMENT_CHECK":return `${wte}
|
|
|
5793
5793
|
${e}`;default:return e}}async function Va({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 bje=["NAVIGATE","NEW_TAB","CLOSE_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function _te({beforeUrl:e,beforePages:t,browser:n,command:o,logger:r}){if(bje.includes(o.type))return;await vo().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 et(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(rp(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 kc(e,t={}){let n=await e.getBrowserState(t);return {serializedTree:n.serialize(t.serializationOpts),tree:n}}var Pte=e=>!!e&&Jh(e),Ote=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?!Ite(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 Nte={minChunkTokenCount:1e4,acceptableChunkTokenCount:25e3,maxChunkTokenCount:5e4,maxLineLength:4e3},Mte=/<(\S+) id="(\d+)".*?>/g,Tje=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,Lte=["h1","h2","section","footer","nav","aside","form","label","dialog"],Aje=[...Lte,"span","div","h3"],Eje=["table","select","form","ul","ol","menu","pre","code","dialog"],vje=["table","form","dialog","nav","section","ul","select"];function kte(e){return Cje(e)}function Cje({logger:e,serializedTree:t,options:n}){let{minChunkTokenCount:o,acceptableChunkTokenCount:r,maxChunkTokenCount:i,maxLineLength:s}=n,a=[],l=t.split(`
|
|
5794
5794
|
`),c=0,d=[],u=0,p=[],m=[],h=false;for(;c<l.length;){h&&(a.push({ids:p,content:d.join(`
|
|
5795
5795
|
`),tokenLength:u}),d=[],u=0,p=m.length?[m[m.length-1].id]:[],h=false);let g=l[c],f=It(g);u+=f,g.length>s&&(g=g.slice(0,s));let T=Array.from(g.matchAll(Mte)).map(W=>W&&W.length>=3?{tagName:W[1],id:W[2]}:void 0).filter(W=>!!W),v=Array.from(g.matchAll(Tje)).map(W=>W&&(W[2]||W[4])).filter(W=>!!W);v.reverse();let w=g.replace(/ id="[0-9]+"/g,"");d.push(w);for(let W of T)p.push(W.id),m.push(W);for(let W of v){let X=m[m.length-1];X&&X.tagName===W&&m.pop();}let I=m.some(W=>Eje.includes(W.tagName)),_=l[c+1]??"",R=It(_),O=Array.from(_.matchAll(Mte)).map(W=>W&&W.length>2?W[1]:void 0).filter(W=>!!W),N=O.some(W=>Lte.includes(W)),k=O.some(W=>Aje.includes(W));u+R>=i&&(h=true),u>=o&&(N&&!I||v.some(W=>vje.includes(W)))&&(h=true),u>=r&&k&&!I&&(h=true),c++;}return d.length&&a.push({ids:p,content:d.join(`
|
|
5796
|
-
`),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 Dte=5e6,wje=1e5,Ije=3e4,xje=6e4,_je=1e5;async function ta(e){let{fixtures:t}=e,{logger:n}=t,o=e.tree,r=e.serializedTree,i=It(r);if(i>Dte)throw new oe("UserConfigurationError",`Page accessibility tree is too large for AI page filtering (${i} tokens). Maximum supported size is ${Dte} tokens.`);if(i>wje){let s=kte({serializedTree:r,options:Nte,logger:n}),a=randomUUID();o=await Pje({...e,chunks:s.chunks,callId:a}),r=o.serialize();let l=It(r);n.info({oldTokens:i,newTokens:l,langfuseCallId:a},"Filtered page using AI chunk ranking");}return r}async function Pje({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:Ije,mediumTokenLimit:xje,hardTokenLimit:_je,callId:t},{abortSignal:a,logger:l,loggerTags:Wt(l)}),d=[];return n.forEach((p,m)=>{c.indices.includes(m)&&(d=d.concat(p.ids));}),i.pruneUsingRelevantIds(new Set(d))}async function N0(e,t){if(!e.description)throw new oe("UserConfigurationError","Cannot locate element with empty description");return Va({action:async()=>Mje(e,t),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:t.browser,logger:e.logger})}async function Mje(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:A}=t,v=e.description,w=vo(),I=e.useMemory&&!n;o&&(v=await yi({orgId:f,s:v,context:o,localTools:S,signal:A,logger:l})),s&&(v=xte(v,s));let{serializedTree:_,tree:R}=await w.startAsyncSpan("GET_PAGE_STATE",async()=>kc(y,{allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,filterByViewport:r,abortSignal:A,skipWait:i,logger:l}),{}),x=await w.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let B,D=Date.now(),Y;for(;!B&&Date.now()-D<3e3;){A.throwIfAborted();try{B=await y.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(te){Y=te;}}if(!B)throw new oe("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${Y?.message}`);return B}),O=_,N=false,W=`data:image/jpeg;base64,${x.toString("base64")}`,X=Wt(l);O=await ta({type:"locator",description:v,screenshot:W,serializedTree:_,tree:R,fixtures:{generator:T,signal:A,logger:l,orgId:f}}),O!==_&&(N=true);let ee=await w.startAsyncSpan("AI_LOCATOR_CALL",async B=>{m&&(B.attributes.isAutoHeal=true),h&&(B.attributes.cacheBustReason=h);let D=await T.getElementLocation({browserState:O,goal:v,screenshot:W,source:s,memory:I?a:void 0},{disableCache:n,abortSignal:A,logger:l,loggerTags:X,useMemory:I,cacheBustReason:h});if(B.result=D,I&&(B.attributes.useMemory=true,B.attributes.memoryTraces=D.rememberedTraces??[],D.updatedMemory&&(B.attributes.memorySavedNewResult=true)),w.storeTraceAsset){let Y=randomUUID();w.storeTraceAsset({snapshotId:Y,data:x}),B.screenshotSnapshotId=Y;}return D});if(l.debug({usedRag:N,result:ee},"Got locator result"),!(ee.id>0))throw new mg(`Could not find any relevant element: ${ee.thoughts}`,ee.updatedMemory?{type:"GCS_TRACES",traces:ee.updatedMemory}:void 0);let{resolution:V,target:M,frameConfig:J}=await w.startAsyncSpan("TARGET_RESOLUTION",async B=>{let D=await y.createTargetFromA11yId({id:ee.id,requirements:ee.requirements,additionalElements:ee.additionalElements,description:v,targetSource:"AI",logger:l,skipSavingVisualAttributes:p,acceptElementMovedError:g});return B.result={serializedElement:D.target.nodeOnlySerializedHtml??"Unknown HTML element"},D});if(V.a11yNode?.properties?.hidden&&V.a11yNode?.properties?.hidden!=="false")throw new oe("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: ${V.displayString}`);return I&&(ee.updatedMemory?M.memory={type:"GCS_TRACES",traces:ee.updatedMemory}:a&&(M.memory=a)),{thoughts:ee.thoughts,target:M,resolution:V,frameConfig:J,screenshot:W}}var Nje=15;async function Mx({command:e,logger:t,fixtures:n,useMemory:o,maxRetries:r=Nje,recoveryHint:i}){if(!e.assertion.trim())throw new oe("ActionFailureError","Assertion command is missing the assertion content");let s=vN.optional().catch(void 0).parse(e.source);e.source&&!s&&t.warn(`Invalid source ${e.source} for AI assertion, ignoring...`);let a=vo();return a.startAsyncSpan("AI_ASSERTION_CALL",async l=>{let{browser:c}=n,d=e.timeout?e.timeout*1e3:c.smartWaitingTimeout,u=qQ(d,r-1),p=0,m=Date.now(),h=m+d,g=m,f,y,S;try{await Va({action:()=>c.clearHighlights(),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:c,logger:t});}catch(v){t.warn({err:v},"Failed to clear highlights before AI check, continuing...");}for(;p<r;){n.abortSignal.throwIfAborted();let v=Date.now();if(p>0){if(v>=h)break;let _=h-v,R=g-v,x=Math.min(R,_);x>0&&await et(x,n.abortSignal);}let w=Date.now();if(p>0&&w>=h)break;let I=false;try{if(f=await Va({action:async()=>{let R=await Bte(c,t,n.abortSignal);return y&&y.serializedTree===R.serializedTree&&y.screenshotBuff.equals(R.screenshotBuff)?(I=!0,f):(y=R,Ute({command:e,state:R,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&>(e,f.updatedMemory,t);break}else throw f?.aiResult.thoughts?new oe("AssertionFailureError",f.aiResult.thoughts):new oe("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(_){n.abortSignal.throwIfAborted(),S=_ instanceof Error?_:new Error(`${_}`),I?t.info(`AI check attempt ${p} failed (re-used previous result)`):t.info({err:_},`AI check assert attempt ${p} failed, retrying...`);}finally{p++,g=w+u;}}if(!f?.aiResult.result){let v=h-Date.now();v>0&&await et(v,n.abortSignal);}if(!f?.aiResult.result)try{f=await Va({action:async()=>Ute({command:e,state:await Bte(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(v){n.abortSignal.throwIfAborted(),S=v instanceof Error?v:new Error(`${v}`);}finally{p++;}f?.updatedMemory&>(e,f.updatedMemory,t);let T=f?.afterScreenshotOverride;if(T&&a.storeTraceAsset){let v=randomUUID();a.storeTraceAsset({snapshotId:v,data:T}),l.screenshotSnapshotId=v;}let A=f?.elementScreenshotOverride;if(A&&a.storeTraceAsset){let v=randomUUID();a.storeTraceAsset({snapshotId:v,data:A}),l.elementScreenshotSnapshotId=v;}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 v=`AI check still failing after ${p} attempts.`;throw S&&(v+=` Latest result: ${S.message}`),new oe("AssertionFailureError",v)}return l.result=f.aiResult,{...f,thoughts:f.aiResult.thoughts,succeedImmediately:false,urlAfterCommand:c.url()}})}async function Bte(e,t,n){await e.waitForPageLoad({signal:n});let[o,r]=await Promise.all([kc(e,{abortSignal:n,skipWait:true,skipWaitForPageLoad:true,logger:t}),e.screenshot({retries:1,respectActiveFrame:true})]);return {...o,screenshotBuff:r}}async function Ute({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",A=h;T!=="VISION_ONLY"&&(A=await ta({type:"assertion",serializedTree:h,tree:g,description:e.assertion,screenshot:y,fixtures:{generator:u,signal:p,logger:l,orgId:n.orgId}}),A);let v={goal:e.assertion,url:S,memory:r?e.cache?.memory:void 0,browserState:A,screenshot:y,contextChoice:T,source:a,recoveryHint:c},I=await(T==="VISION_ONLY"?(R,x)=>u.getVisualAssertionResult(R,x):(R,x)=>u.getAssertionResult(R,x))(v,{useConsensus:o,attemptNumber:s,useMemory:r,disableCache:!!e.disableCache,abortSignal:p,logger:l,loggerTags:Wt(l)}),_;if((I.result||i)&&I.relevantElements?.length){I.relevantElements.map(R=>d.getSerializedFormFromA11yId(R)).filter(R=>!!R);try{let R=I.relevantElements[0],{resolution:x}=await d.createTargetFromA11yId({id:R,description:null,targetSource:"AI",skipSaveToCache:!0});_=await d.screenshot({locator:x.locator,clearHighlights:!0,respectActiveFrame:!0});}catch(R){l.debug({err:R},"Failed to capture element screenshot for trace, continuing...");}await Lje(I.relevantElements,d,l);}return {aiResult:I,afterScreenshotOverride:f,elementScreenshotOverride:_,updatedMemory:r?I.updatedMemory:void 0}}async function Lje(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 xe(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 jte(e){let{command:t,logger:n,fixtures:o,disableCache:r}=e,{browser:i,generator:s,abortSignal:a}=o;if(!t.goal.trim())throw new oe("ActionFailureError","Cannot perform AI extraction without goal");if(t.schema){let u=UJ(t.schema);if(u)throw new oe("UserConfigurationError",u)}let l=await i.getCondensedHtml(),c=await i.screenshot({retries:2}),d=vo();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:Wt(n)});if(u.result=p,kje({tracer:d,span:u,screenshot:c,htmlState:l,logger:n}),p.result==="NOT_FOUND")throw new oe("ActionFailureError","No relevant data found for extraction goal on this page");if(p.thoughts?.includes("MaxGenerationLengthExceededError"))throw new oe("UserConfigurationError",p.thoughts);return {thoughts:p.thoughts||void 0,data:p.result,succeedImmediately:!1,urlAfterCommand:i.url()}})}catch(u){let p=q(u);throw p.includes("MaxGenerationLengthExceededError")?new oe("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 oe("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 kje(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 Gte(e,t){let{logger:n}=e,{abortSignal:o,browser:r}=t,i=Date.now();try{await Dje(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 et(a,o);}finally{n.debug({durationMs:Date.now()-i},"AI smart waiting complete");}}async function Dje(e,t,n){let{abortSignal:o,browser:r}=n;if(r.smartWaitingTimeout<3e3){await et(r.smartWaitingTimeout,o);return}if(!t.description)throw new oe("UserConfigurationError","Cannot locate element with empty description");await xe(Fje(e,t,n),{milliseconds:r.smartWaitingTimeout});}async function Fje(e,t,n){let{logger:o,iframeUrl:r}=t,{browser:i}=n;for(;Date.now()-e<i.smartWaitingTimeout;)if(await Va({action:async()=>Bje(t,n),frameConfig:r?{type:"url",url:r}:void 0,browser:i,logger:o}))return}async function Bje(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 yi({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 oe("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:Wt(o)});return o.debug({result:m},"Got smart waiting result"),m.isPageReady}var Uje=3e4;async function zte(e){return vo().startAsyncSpan("ELEMENT_ASSERTION",async n=>Hje(e,n),{name:"Element check"})}async function Hje(e,t){let{command:n,timeoutMs:o,fixtures:r,disableCache:i}=e,{abortSignal:s}=r,a=()=>Mv(n.cache)?n.cache:void 0,l=a(),c=!i&&!!l?.target&&Jh(l.target),d=cloneDeep(l),u=(A=false)=>{if(l=a(),!!l)if(A){let v=MD(d,l);l.target=v.target,l.updatedAt=v.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,Uje):0,h=p,g=0,f,y=500,S=false;for(;g<2||Date.now()-p<o;){g++,g>1&&await et(y,s),s?.throwIfAborted(),l=a();let A=g===1,v=c&&Date.now()-h>=m;v&&(h=Date.now());let{result:w,elementWasFound:I}=await $te({cacheToUse:l,skipAISmartWaiting:!A,useAIIfCacheFails:!c||v,params:e});if(f=w,S=S||I,w.success)break;u(),y=Math.min(y*1.25,1e4);}if(!f)throw new oe("InternalPlatformError",`Failed to evaluate manual element assertion in ${o}ms.`);if(s?.throwIfAborted(),!f.success){let A=a(),v=A?.target?.memory?{target:{id:-1,memory:A.target.memory}}:void 0,{result:w,elementWasFound:I}=await $te({cacheToUse:v,skipAISmartWaiting:true,useAIIfCacheFails:true,params:e});f=w,S=S||I,f.success||u(true);}let T=a();return f.success&&T?.target&&!S&&(T.target=jT(T.target),T.updatedAt=new Date),t.result={success:f.success,message:f.err?.message},f}async function $te({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&&!ed(r.target))throw new Error("Element assertion with x/y is not supported yet");let d=N4(r.assertion),u=jje(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=>Gje(S.locator,o),options:{...r,allowNotActionableNodesOverride:u,allowIneligibleTagRedirect:u,showZeroOpacityElementsOverride:!0,disableCache:i,memory:h?.target?.memory,disableGlobalLocatorRedirect:!0,source:Sm(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 oe)||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 jje(e){return !(e.type==="ELEMENT_EXISTENCE"&&e.condition==="VISIBLE"&&!e.negated)}async function Gje(e,{command:t,fixtures:n}){return await n.browser.highlight(e),await $je(e,t.assertion)}async function $je(e,t){let n=true,o,r;switch(t.type){case "ELEMENT_CONTENT":{let s=await e.textContent()??"";if(r={elementTextContent:Tn(s,500,true)},!FT(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Af(t);n=false,o=new oe("AssertionFailureError",`The content ${a} '${t.value}': ${s}`);}break}case "ELEMENT_ATTRIBUTE":{r={elementOuterHtml:Tn(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 oe("AssertionFailureError",q(a)),n=false;break}if(!FT(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Af(t);n=false,t.operation==="EXISTS"?o=new oe("AssertionFailureError",`The attribute ${t.attr} ${a}`):o=new oe("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},ha*1e3);break}case "EDITABLE":{n=await e.isEditable({timeout:ha*1e3});break}case "EXISTS":{n=true;break}case "ENABLED":{n=await e.isEnabled({timeout:ha*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=Af(t);o=new oe("AssertionFailureError",`The element ${s}`);}break}case "ELEMENT_NAME":{let s=await e.evaluate(a=>a.tagName);if(!FT(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:true})){let a=Af(t);n=false,o=new oe("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(!FT(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Af(t);n=false,t.operation==="EXISTS"?o=new oe("AssertionFailureError",`The style property ${t.property} ${a}`):o=new oe("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 Wte(e){return e.type==="ELEMENT_EXISTENCE"&&e.negated&&e.condition==="EXISTS"}async function UA(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 Kte(e){let{command:t,browser:n,logger:o}=e;if(t.target&&!ed(t.target))throw new Error("Visual Diff with x/y is not supported yet");return await n.waitForStability({logger:o}),vo().startAsyncSpan("VISUAL_DIFF",async i=>{try{let s=await Wje(e);return i.result={success:!s.fail,message:s.thoughts},s}catch(s){throw s instanceof oe&&(i.result={success:false,message:s.message}),s}},{name:"Compare against golden"})}async function Wje({tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:r,logger:i,screenshotStorage:s}){let a={clearHighlights:true,hideCaret:true},l=t.target&&ed(t.target)?t.target:void 0,c;l?.elementDescriptor?c=(await r({tracer:e,command:t,target:l,cache:t.cache?.target,action:async O=>UA(o,{locator:O.locator,...a}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:true,memory:t.cache?.target?.memory,targetName:"target"}})).result:c=await UA(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 x=`${c.width}x${c.height}`,O=`${d.width}x${d.height}`;return {fail:true,thoughts:`Current screenshot (${x}) does not match saved screenshot dimensions (${O}) - 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 x=u.cover({w:h.width,h:h.height});c.buffer=await x.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height;}else if(y>f){let x=m.cover({w:p.width,h:p.height});d.buffer=await x.getBuffer("image/jpeg"),g="saved";}let A={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},v=t.threshold??.1,I=RHe(L0.decode(d.buffer).data,L0.decode(c.buffer).data,A.data,c.width,c.height,{threshold:v,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,_=I>v*100,R=`Visual diff of ${I.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${v*100}%.`;if(g&&(R+=` The ${g} screenshot was cropped since it was taller by ${S} pixels and wider by ${T} pixels.`),_)throw new oe("ActionFailureError",R);return {fail:_,thoughts:R,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:L0.encode(A,75).data,succeedImmediately:false,urlAfterCommand:o.url()}}var qje=3e4;function Kje(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 Yte({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??qje/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(xf(e.url)&&(l=e.url),n&&_f(e.url,n)&&(l=new URL(e.url,n).toString()),!l)throw new oe("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 xe((async()=>{let h=a?`${c}?${a}`:c;try{let g=Kje(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 oe("ActionFailureError",`Failed to make HTTP request: ${q(g)}`,{errOptions:{cause:g}})}})(),{milliseconds:r*1e3,fallback:()=>{throw new oe("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 oe("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 Yje=5e3;async function Nx({timeout:e=ha,...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 Jte(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 et(a,t.signal),a=Math.min(Math.floor(a*1.5),Yje);else return i}return i=await Jte(t),i}async function Jte(e){return vo().startAsyncSpan("PAGE_ASSERTION",async n=>{let o=await Jje(e);return n.result={success:o.success,message:o.err?.message},o},{name:"Page check"})}async function Jje({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(Xte,{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(Xte,{value:e.value,negated:!!e.negated,returnHtml:!0},"checking page content"));if(!i){let l=e.negated?wd.CONTAINS:Id.CONTAINS;s=new oe("AssertionFailureError",`The page ${l} '${e.value}'.`),r=a;}}catch(a){s=new oe("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 Xte({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 Xje=3e4;async function Qte({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??Xje/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(e.headers||{}).filter(([u,p])=>u&&p));s["Content-Type"]="application/json";let a;if(xf(e.url)&&(a=e.url),n&&_f(e.url,n)&&(a=new URL(e.url,n).toString()),!a)throw new oe("ActionFailureError",`Invalid URL: ${e.url}`);let c=await xe((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 oe("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 oe("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}throw u?.errors?.length&&u?.errors[0]?.message?new oe("ActionFailureError",`GraphQL request failed with status ${c.status}: ${u.errors[0].message}`):new oe("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 by=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();}bindCancellation(t){if(t.aborted)return this.setClosed(),()=>{};let n=()=>this.setClosed();return t.addEventListener("abort",n,{once:true}),()=>t.removeEventListener("abort",n)}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([kc(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 ta({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:{...Wt(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([kc(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 ta({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:{...Wt(s)},langfuseSessionId:a})}catch(h){throw new oe("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(t){return kc(this.browser,t)}async locateElement(t){return await N0(t,this.getControllerFixtures())}async locateElementWithSelector(t,n){return Va({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 oe("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 oe("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 et(500);}}throw a}async scrollIntoViewAndResolveFinalTarget(t){let{resolutionResult:n,disableGlobalLocatorRedirect:o,logger:r}=t,i=vo(),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:nt}),originalElementLocationResult:n.originalElementLocationResult}),a}async resolveCachedTargetForAction(t){let{cache:n,options:o,logger:r}=t,s=await vo().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 Oi&&(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 Va({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=vo(),h=this.logger.child({commandId:s.id}),g=this.shouldUseMemory(),f=cloneDeep(t.cache);if((!f||d)&&!W$(o))throw new oe("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=Ote({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 A=true;if(!Pte(f))return c--,A=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:v,finalTarget:w}=await this.resolveCachedTargetForAction({cache:f,options:i,logger:h}),I=await r(w);if(wt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.25.0"]),_w({cmd:s,key:p,newTarget:f,logger:h,updatedWithAI:!1}),A){let _=v.decisions.filter(R=>R.matched);if(_.length!==1)h.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else {let R=_[0].type;n.recordTargetAutoHeal({healType:R});}}return {result:I,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let w=UM(v);if(w&&!a)return h.warn({err:v},"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(v instanceof oe&&!w)throw h.warn({err:v},"Failed to execute command with target (fatal)"),v;if(c>0&&o){h.info({err:v},"Failed to execute action with cached target, retrying with AI"),wt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.25.0",`missReason:${v instanceof Oi?v.cacheMissReason:"unknown"}`]);let I;f.memory&&Pv(f.memory)&&(I=f.memory);let _=v instanceof Oi&&v.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:I,targetHealingInProgress:true},skipInitialLocateWait:_})}throw new oe("ActionFailureError",`Failed to execute interactive command: ${v instanceof Error?v.message:`${v}`}`,{errOptions:{cause:v}})}}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 Gte({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 A;try{A=await N0({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(I){if(I instanceof mg&&I.updatedLocatorMemory){let _={id:-1,...l,memory:I.updatedLocatorMemory};_w({cmd:s,key:i.targetName,newTarget:_,logger:c,updatedWithAI:!0});}throw I}A.frameConfig&&(this.browser.setActiveFrameConfig(A.frameConfig),y=!0);let v=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:A.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),w=await a(v);return _w({cmd:s,key:i.targetName,newTarget:A.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(o.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=Wt(c)),{result:w,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}catch(A){if(y&&this.browser.setActiveFrameConfig(S),this.throwIfClosed(),f<g&&UM(A)){c.warn({err:A,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw A instanceof oe?A:new oe("ActionFailureError",A.message)}}throw new oe("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(t){return UA(this.browser,t)}async executePresetCommand(t,n,o,r,i){this.options?.slowMoMs&&await et(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 oe("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 _te({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{_7(n,l);}}createCallbacksForBrowser(t){return {createIsolatedFolder:()=>s0(t)}}async traceBrowserInteraction(t,n,o){return vo().startAsyncSpan("BROWSER_INTERACTION",async i=>n(i),{name:t,...o})}async resolveCommandTemplateStrings(t,n){return hx({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()?Mx({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 oe("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new oe("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Mx({command:n,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i})}case "AI_EXTRACT":return jte({command:n,logger:s,fixtures:this.getControllerFixtures(),disableCache:r});case "NAVIGATE":if(!xf(n.url)&&!_f(n.url,this.browser.baseUrl))throw new oe("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 oe("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&&zl(n.target)){let u=ti(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??Hr.height,d=this.browser.getViewport()?.width??Hr.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 oe("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 oe("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=n.delay*1e3;await et(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(zl(n.target)){let p=ti(n.target.pixels),m={...n,relativePosition:n.relativePosition?ti(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?ti(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 Uw(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(zl(n.fromTarget)&&zl(n.toTarget)){let c=ti(n.fromTarget.pixels),d=ti(n.toTarget.pixels);await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0}),{coordinates:c});break}if(zl(n.fromTarget)||zl(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 oe("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&zl(n.target)){let p=ti(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(!ed(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:Sm(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 vp({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 oe("ActionFailureError",l instanceof Error?l.message:`${l}`,{errOptions:{cause:l}})}try{JSON.stringify(a);}catch(l){throw new oe("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&&zl(n.target)){let m=ti(n.target.pixels),h={...n,relativePosition:n.relativePosition?ti(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:Sm(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 Uw(a,p.urlAfterCommand)&&(p.succeedImmediately=true,p.succeedImmediatelyReason="URL changed"),p}case "HOVER":{if(zl(n.target)){let c=ti(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?ti(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(!ed(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&&!ed(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 Uw(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=Zje(fetch,a),c;try{c=new URL(n.url).hostname;}catch{}let d=await Yte({command:n,baseUrl:this.browser.baseUrl,logger:s,fetchImplementation:l});return {data:WS.parse({...d,cookies:rq(a,c)}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GRAPHQL_REQUEST":return {data:await Qte({command:n,baseUrl:this.browser.baseUrl,logger:s}),succeedImmediately:false,urlAfterCommand:this.browser.url()};case "VISUAL_DIFF":return Kte({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 gee({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 oe("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&&cp(n.storageState)){let l=io__default.resolve(n.storageState);ko__default.mkdirSync(io__default.dirname(l),{recursive:true}),ko__default.writeFileSync(l,`${JSON.stringify(a,null,2)}
|
|
5796
|
+
`),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 Dte=5e6,wje=1e5,Ije=3e4,xje=6e4,_je=1e5;async function ta(e){let{fixtures:t}=e,{logger:n}=t,o=e.tree,r=e.serializedTree,i=It(r);if(i>Dte)throw new oe("UserConfigurationError",`Page accessibility tree is too large for AI page filtering (${i} tokens). Maximum supported size is ${Dte} tokens.`);if(i>wje){let s=kte({serializedTree:r,options:Nte,logger:n}),a=randomUUID();o=await Pje({...e,chunks:s.chunks,callId:a}),r=o.serialize();let l=It(r);n.info({oldTokens:i,newTokens:l,langfuseCallId:a},"Filtered page using AI chunk ranking");}return r}async function Pje({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:Ije,mediumTokenLimit:xje,hardTokenLimit:_je,callId:t},{abortSignal:a,logger:l,loggerTags:Wt(l)}),d=[];return n.forEach((p,m)=>{c.indices.includes(m)&&(d=d.concat(p.ids));}),i.pruneUsingRelevantIds(new Set(d))}async function N0(e,t){if(!e.description)throw new oe("UserConfigurationError","Cannot locate element with empty description");return Va({action:async()=>Mje(e,t),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:t.browser,logger:e.logger})}async function Mje(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:A}=t,v=e.description,w=vo(),I=e.useMemory&&!n;o&&(v=await yi({orgId:f,s:v,context:o,localTools:S,signal:A,logger:l})),s&&(v=xte(v,s));let{serializedTree:_,tree:R}=await w.startAsyncSpan("GET_PAGE_STATE",async()=>kc(y,{allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,filterByViewport:r,abortSignal:A,skipWait:i,logger:l}),{}),x=await w.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let B,D=Date.now(),Y;for(;!B&&Date.now()-D<3e3;){A.throwIfAborted();try{B=await y.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(te){Y=te;}}if(!B)throw new oe("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${Y?.message}`);return B}),O=_,N=false,W=`data:image/jpeg;base64,${x.toString("base64")}`,X=Wt(l);O=await ta({type:"locator",description:v,screenshot:W,serializedTree:_,tree:R,fixtures:{generator:T,signal:A,logger:l,orgId:f}}),O!==_&&(N=true);let ee=await w.startAsyncSpan("AI_LOCATOR_CALL",async B=>{m&&(B.attributes.isAutoHeal=true),h&&(B.attributes.cacheBustReason=h);let D=await T.getElementLocation({browserState:O,goal:v,screenshot:W,source:s,memory:I?a:void 0},{disableCache:n,abortSignal:A,logger:l,loggerTags:X,useMemory:I,cacheBustReason:h});if(B.result=D,I&&(B.attributes.useMemory=true,B.attributes.memoryTraces=D.rememberedTraces??[],D.updatedMemory&&(B.attributes.memorySavedNewResult=true)),w.storeTraceAsset){let Y=randomUUID();w.storeTraceAsset({snapshotId:Y,data:x}),B.screenshotSnapshotId=Y;}return D});if(l.debug({usedRag:N,result:ee},"Got locator result"),!(ee.id>0))throw new mg(`Could not find any relevant element: ${ee.thoughts}`,ee.updatedMemory?{type:"GCS_TRACES",traces:ee.updatedMemory}:void 0);let{resolution:V,target:M,frameConfig:J}=await w.startAsyncSpan("TARGET_RESOLUTION",async B=>{let D=await y.createTargetFromA11yId({id:ee.id,requirements:ee.requirements,additionalElements:ee.additionalElements,description:v,targetSource:"AI",logger:l,skipSavingVisualAttributes:p,acceptElementMovedError:g});return B.result={serializedElement:D.target.nodeOnlySerializedHtml??"Unknown HTML element"},D});if(V.a11yNode?.properties?.hidden&&V.a11yNode?.properties?.hidden!=="false")throw new oe("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: ${V.displayString}`);return I&&(ee.updatedMemory?M.memory={type:"GCS_TRACES",traces:ee.updatedMemory}:a&&(M.memory=a)),{thoughts:ee.thoughts,target:M,resolution:V,frameConfig:J,screenshot:W}}var Nje=15;async function Mx({command:e,logger:t,fixtures:n,useMemory:o,maxRetries:r=Nje,recoveryHint:i}){if(!e.assertion.trim())throw new oe("ActionFailureError","Assertion command is missing the assertion content");let s=vN.optional().catch(void 0).parse(e.source);e.source&&!s&&t.warn(`Invalid source ${e.source} for AI assertion, ignoring...`);let a=vo();return a.startAsyncSpan("AI_ASSERTION_CALL",async l=>{let{browser:c}=n,d=e.timeout?e.timeout*1e3:c.smartWaitingTimeout,u=qQ(d,r-1),p=0,m=Date.now(),h=m+d,g=m,f,y,S;try{await Va({action:()=>c.clearHighlights(),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:c,logger:t});}catch(v){t.warn({err:v},"Failed to clear highlights before AI check, continuing...");}for(;p<r;){n.abortSignal.throwIfAborted();let v=Date.now();if(p>0){if(v>=h)break;let _=h-v,R=g-v,x=Math.min(R,_);x>0&&await et(x,n.abortSignal);}let w=Date.now();if(p>0&&w>=h)break;let I=false;try{if(f=await Va({action:async()=>{let R=await Bte(c,t,n.abortSignal);return y&&y.serializedTree===R.serializedTree&&y.screenshotBuff.equals(R.screenshotBuff)?(I=!0,f):(y=R,Ute({command:e,state:R,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&>(e,f.updatedMemory,t);break}else throw f?.aiResult.thoughts?new oe("AssertionFailureError",f.aiResult.thoughts):new oe("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(_){n.abortSignal.throwIfAborted(),S=_ instanceof Error?_:new Error(`${_}`),I?t.info(`AI check attempt ${p} failed (re-used previous result)`):t.info({err:_},`AI check assert attempt ${p} failed, retrying...`);}finally{p++,g=w+u;}}if(!f?.aiResult.result){let v=h-Date.now();v>0&&await et(v,n.abortSignal);}if(!f?.aiResult.result)try{f=await Va({action:async()=>Ute({command:e,state:await Bte(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(v){n.abortSignal.throwIfAborted(),S=v instanceof Error?v:new Error(`${v}`);}finally{p++;}f?.updatedMemory&>(e,f.updatedMemory,t);let T=f?.afterScreenshotOverride;if(T&&a.storeTraceAsset){let v=randomUUID();a.storeTraceAsset({snapshotId:v,data:T}),l.screenshotSnapshotId=v;}let A=f?.elementScreenshotOverride;if(A&&a.storeTraceAsset){let v=randomUUID();a.storeTraceAsset({snapshotId:v,data:A}),l.elementScreenshotSnapshotId=v;}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 v=`AI check still failing after ${p} attempts.`;throw S&&(v+=` Latest result: ${S.message}`),new oe("AssertionFailureError",v)}return l.result=f.aiResult,{...f,thoughts:f.aiResult.thoughts,succeedImmediately:false,urlAfterCommand:c.url()}})}async function Bte(e,t,n){await e.waitForPageLoad({signal:n});let[o,r]=await Promise.all([kc(e,{abortSignal:n,skipWait:true,skipWaitForPageLoad:true,logger:t}),e.screenshot({retries:1,respectActiveFrame:true})]);return {...o,screenshotBuff:r}}async function Ute({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",A=h;T!=="VISION_ONLY"&&(A=await ta({type:"assertion",serializedTree:h,tree:g,description:e.assertion,screenshot:y,fixtures:{generator:u,signal:p,logger:l,orgId:n.orgId}}),A);let v={goal:e.assertion,url:S,memory:r?e.cache?.memory:void 0,browserState:A,screenshot:y,contextChoice:T,source:a,recoveryHint:c},I=await(T==="VISION_ONLY"?(R,x)=>u.getVisualAssertionResult(R,x):(R,x)=>u.getAssertionResult(R,x))(v,{useConsensus:o,attemptNumber:s,useMemory:r,disableCache:!!e.disableCache,abortSignal:p,logger:l,loggerTags:Wt(l)}),_;if((I.result||i)&&I.relevantElements?.length){I.relevantElements.map(R=>d.getSerializedFormFromA11yId(R)).filter(R=>!!R);try{let R=I.relevantElements[0],{resolution:x}=await d.createTargetFromA11yId({id:R,description:null,targetSource:"AI",skipSaveToCache:!0});_=await d.screenshot({locator:x.locator,clearHighlights:!0,respectActiveFrame:!0});}catch(R){l.debug({err:R},"Failed to capture element screenshot for trace, continuing...");}await Lje(I.relevantElements,d,l);}return {aiResult:I,afterScreenshotOverride:f,elementScreenshotOverride:_,updatedMemory:r?I.updatedMemory:void 0}}async function Lje(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 xe(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 jte(e){let{command:t,logger:n,fixtures:o,disableCache:r}=e,{browser:i,generator:s,abortSignal:a}=o;if(!t.goal.trim())throw new oe("ActionFailureError","Cannot perform AI extraction without goal");if(t.schema){let u=UJ(t.schema);if(u)throw new oe("UserConfigurationError",u)}let l=await i.getCondensedHtml(),c=await i.screenshot({retries:2}),d=vo();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:Wt(n)});if(u.result=p,kje({tracer:d,span:u,screenshot:c,htmlState:l,logger:n}),p.result==="NOT_FOUND")throw new oe("ActionFailureError","No relevant data found for extraction goal on this page");if(p.thoughts?.includes("MaxGenerationLengthExceededError"))throw new oe("UserConfigurationError",p.thoughts);return {thoughts:p.thoughts||void 0,data:p.result,succeedImmediately:!1,urlAfterCommand:i.url()}})}catch(u){let p=q(u);throw p.includes("MaxGenerationLengthExceededError")?new oe("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 oe("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 kje(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 Gte(e,t){let{logger:n}=e,{abortSignal:o,browser:r}=t,i=Date.now();try{await Dje(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 et(a,o);}finally{n.debug({durationMs:Date.now()-i},"AI smart waiting complete");}}async function Dje(e,t,n){let{abortSignal:o,browser:r}=n;if(r.smartWaitingTimeout<3e3){await et(r.smartWaitingTimeout,o);return}if(!t.description)throw new oe("UserConfigurationError","Cannot locate element with empty description");await xe(Fje(e,t,n),{milliseconds:r.smartWaitingTimeout});}async function Fje(e,t,n){let{logger:o,iframeUrl:r}=t,{browser:i}=n;for(;Date.now()-e<i.smartWaitingTimeout;)if(await Va({action:async()=>Bje(t,n),frameConfig:r?{type:"url",url:r}:void 0,browser:i,logger:o}))return}async function Bje(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 yi({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 oe("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:Wt(o)});return o.debug({result:m},"Got smart waiting result"),m.isPageReady}var Uje=3e4;async function zte(e){return vo().startAsyncSpan("ELEMENT_ASSERTION",async n=>Hje(e,n),{name:"Element check"})}async function Hje(e,t){let{command:n,timeoutMs:o,fixtures:r,disableCache:i}=e,{abortSignal:s}=r,a=()=>Mv(n.cache)?n.cache:void 0,l=a(),c=!i&&!!l?.target&&Jh(l.target),d=cloneDeep(l),u=(A=false)=>{if(l=a(),!!l)if(A){let v=MD(d,l);l.target=v.target,l.updatedAt=v.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,Uje):0,h=p,g=0,f,y=500,S=false;for(;g<2||Date.now()-p<o;){g++,g>1&&await et(y,s),s?.throwIfAborted(),l=a();let A=g===1,v=c&&Date.now()-h>=m;v&&(h=Date.now());let{result:w,elementWasFound:I}=await $te({cacheToUse:l,skipAISmartWaiting:!A,useAIIfCacheFails:!c||v,params:e});if(f=w,S=S||I,w.success)break;u(),y=Math.min(y*1.25,1e4);}if(!f)throw new oe("InternalPlatformError",`Failed to evaluate manual element assertion in ${o}ms.`);if(s?.throwIfAborted(),!f.success){let A=a(),v=A?.target?.memory?{target:{id:-1,memory:A.target.memory}}:void 0,{result:w,elementWasFound:I}=await $te({cacheToUse:v,skipAISmartWaiting:true,useAIIfCacheFails:true,params:e});f=w,S=S||I,f.success||u(true);}let T=a();return f.success&&T?.target&&!S&&(T.target=jT(T.target),T.updatedAt=new Date),t.result={success:f.success,message:f.err?.message},f}async function $te({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&&!ed(r.target))throw new Error("Element assertion with x/y is not supported yet");let d=N4(r.assertion),u=jje(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=>Gje(S.locator,o),options:{...r,allowNotActionableNodesOverride:u,allowIneligibleTagRedirect:u,showZeroOpacityElementsOverride:!0,disableCache:i,memory:h?.target?.memory,disableGlobalLocatorRedirect:!0,source:Sm(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 oe)||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 jje(e){return !(e.type==="ELEMENT_EXISTENCE"&&e.condition==="VISIBLE"&&!e.negated)}async function Gje(e,{command:t,fixtures:n}){return await n.browser.highlight(e),await $je(e,t.assertion)}async function $je(e,t){let n=true,o,r;switch(t.type){case "ELEMENT_CONTENT":{let s=await e.textContent()??"";if(r={elementTextContent:Tn(s,500,true)},!FT(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Af(t);n=false,o=new oe("AssertionFailureError",`The content ${a} '${t.value}': ${s}`);}break}case "ELEMENT_ATTRIBUTE":{r={elementOuterHtml:Tn(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 oe("AssertionFailureError",q(a)),n=false;break}if(!FT(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Af(t);n=false,t.operation==="EXISTS"?o=new oe("AssertionFailureError",`The attribute ${t.attr} ${a}`):o=new oe("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},ha*1e3);break}case "EDITABLE":{n=await e.isEditable({timeout:ha*1e3});break}case "EXISTS":{n=true;break}case "ENABLED":{n=await e.isEnabled({timeout:ha*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=Af(t);o=new oe("AssertionFailureError",`The element ${s}`);}break}case "ELEMENT_NAME":{let s=await e.evaluate(a=>a.tagName);if(!FT(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:true})){let a=Af(t);n=false,o=new oe("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(!FT(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Af(t);n=false,t.operation==="EXISTS"?o=new oe("AssertionFailureError",`The style property ${t.property} ${a}`):o=new oe("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 Wte(e){return e.type==="ELEMENT_EXISTENCE"&&e.negated&&e.condition==="EXISTS"}async function UA(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 Kte(e){let{command:t,browser:n,logger:o}=e;if(t.target&&!ed(t.target))throw new Error("Visual Diff with x/y is not supported yet");return await n.waitForStability({logger:o}),vo().startAsyncSpan("VISUAL_DIFF",async i=>{try{let s=await Wje(e);return i.result={success:!s.fail,message:s.thoughts},s}catch(s){throw s instanceof oe&&(i.result={success:false,message:s.message}),s}},{name:"Compare against golden"})}async function Wje({tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:r,logger:i,screenshotStorage:s}){let a={clearHighlights:true,hideCaret:true},l=t.target&&ed(t.target)?t.target:void 0,c;l?.elementDescriptor?c=(await r({tracer:e,command:t,target:l,cache:t.cache?.target,action:async O=>UA(o,{locator:O.locator,...a}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:true,memory:t.cache?.target?.memory,targetName:"target"}})).result:c=await UA(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 x=`${c.width}x${c.height}`,O=`${d.width}x${d.height}`;return {fail:true,thoughts:`Current screenshot (${x}) does not match saved screenshot dimensions (${O}) - 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 x=u.cover({w:h.width,h:h.height});c.buffer=await x.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height;}else if(y>f){let x=m.cover({w:p.width,h:p.height});d.buffer=await x.getBuffer("image/jpeg"),g="saved";}let A={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},v=t.threshold??.1,I=RHe(L0.decode(d.buffer).data,L0.decode(c.buffer).data,A.data,c.width,c.height,{threshold:v,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,_=I>v*100,R=`Visual diff of ${I.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${v*100}%.`;if(g&&(R+=` The ${g} screenshot was cropped since it was taller by ${S} pixels and wider by ${T} pixels.`),_)throw new oe("ActionFailureError",R);return {fail:_,thoughts:R,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:L0.encode(A,75).data,succeedImmediately:false,urlAfterCommand:o.url()}}var qje=3e4;function Kje(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 Yte({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??qje/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(xf(e.url)&&(l=e.url),n&&_f(e.url,n)&&(l=new URL(e.url,n).toString()),!l)throw new oe("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 xe((async()=>{let h=a?`${c}?${a}`:c;try{let g=Kje(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 oe("ActionFailureError",`Failed to make HTTP request: ${q(g)}`,{errOptions:{cause:g}})}})(),{milliseconds:r*1e3,fallback:()=>{throw new oe("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 oe("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 Yje=5e3;async function Nx({timeout:e=ha,...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 Jte(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 et(a,t.signal),a=Math.min(Math.floor(a*1.5),Yje);else return i}return i=await Jte(t),i}async function Jte(e){return vo().startAsyncSpan("PAGE_ASSERTION",async n=>{let o=await Jje(e);return n.result={success:o.success,message:o.err?.message},o},{name:"Page check"})}async function Jje({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(Xte,{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(Xte,{value:e.value,negated:!!e.negated,returnHtml:!0},"checking page content"));if(!i){let l=e.negated?wd.CONTAINS:Id.CONTAINS;s=new oe("AssertionFailureError",`The page ${l} '${e.value}'.`),r=a;}}catch(a){s=new oe("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 Xte({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 Xje=3e4;async function Qte({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??Xje/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(e.headers||{}).filter(([u,p])=>u&&p));s["Content-Type"]="application/json";let a;if(xf(e.url)&&(a=e.url),n&&_f(e.url,n)&&(a=new URL(e.url,n).toString()),!a)throw new oe("ActionFailureError",`Invalid URL: ${e.url}`);let c=await xe((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 oe("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 oe("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}throw u?.errors?.length&&u?.errors[0]?.message?new oe("ActionFailureError",`GraphQL request failed with status ${c.status}: ${u.errors[0].message}`):new oe("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 by=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();}bindCancellation(t){if(t.aborted)return this.setClosed(),()=>{};let n=()=>this.setClosed();return t.addEventListener("abort",n,{once:true}),()=>t.removeEventListener("abort",n)}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([kc(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 ta({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:{...Wt(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([kc(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 ta({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:{...Wt(s)},langfuseSessionId:a})}catch(h){throw new oe("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(t){return kc(this.browser,t)}async locateElement(t){return await N0(t,this.getControllerFixtures())}async locateElementWithSelector(t,n){return Va({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 oe("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 oe("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 et(500);}}throw a}async scrollIntoViewAndResolveFinalTarget(t){let{resolutionResult:n,disableGlobalLocatorRedirect:o,logger:r}=t,i=vo(),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:nt}),originalElementLocationResult:n.originalElementLocationResult}),a}async resolveCachedTargetForAction(t){let{cache:n,options:o,logger:r}=t,s=await vo().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 Oi&&(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 Va({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=vo(),h=this.logger.child({commandId:s.id}),g=this.shouldUseMemory(),f=cloneDeep(t.cache);if((!f||d)&&!W$(o))throw new oe("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=Ote({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 A=true;if(!Pte(f))return c--,A=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:v,finalTarget:w}=await this.resolveCachedTargetForAction({cache:f,options:i,logger:h}),I=await r(w);if(wt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.25.1"]),_w({cmd:s,key:p,newTarget:f,logger:h,updatedWithAI:!1}),A){let _=v.decisions.filter(R=>R.matched);if(_.length!==1)h.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else {let R=_[0].type;n.recordTargetAutoHeal({healType:R});}}return {result:I,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let w=UM(v);if(w&&!a)return h.warn({err:v},"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(v instanceof oe&&!w)throw h.warn({err:v},"Failed to execute command with target (fatal)"),v;if(c>0&&o){h.info({err:v},"Failed to execute action with cached target, retrying with AI"),wt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.25.1",`missReason:${v instanceof Oi?v.cacheMissReason:"unknown"}`]);let I;f.memory&&Pv(f.memory)&&(I=f.memory);let _=v instanceof Oi&&v.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:I,targetHealingInProgress:true},skipInitialLocateWait:_})}throw new oe("ActionFailureError",`Failed to execute interactive command: ${v instanceof Error?v.message:`${v}`}`,{errOptions:{cause:v}})}}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 Gte({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 A;try{A=await N0({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(I){if(I instanceof mg&&I.updatedLocatorMemory){let _={id:-1,...l,memory:I.updatedLocatorMemory};_w({cmd:s,key:i.targetName,newTarget:_,logger:c,updatedWithAI:!0});}throw I}A.frameConfig&&(this.browser.setActiveFrameConfig(A.frameConfig),y=!0);let v=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:A.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),w=await a(v);return _w({cmd:s,key:i.targetName,newTarget:A.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(o.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=Wt(c)),{result:w,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}catch(A){if(y&&this.browser.setActiveFrameConfig(S),this.throwIfClosed(),f<g&&UM(A)){c.warn({err:A,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw A instanceof oe?A:new oe("ActionFailureError",A.message)}}throw new oe("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(t){return UA(this.browser,t)}async executePresetCommand(t,n,o,r,i){this.options?.slowMoMs&&await et(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 oe("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 _te({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{_7(n,l);}}createCallbacksForBrowser(t){return {createIsolatedFolder:()=>s0(t)}}async traceBrowserInteraction(t,n,o){return vo().startAsyncSpan("BROWSER_INTERACTION",async i=>n(i),{name:t,...o})}async resolveCommandTemplateStrings(t,n){return hx({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()?Mx({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 oe("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new oe("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Mx({command:n,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i})}case "AI_EXTRACT":return jte({command:n,logger:s,fixtures:this.getControllerFixtures(),disableCache:r});case "NAVIGATE":if(!xf(n.url)&&!_f(n.url,this.browser.baseUrl))throw new oe("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 oe("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&&zl(n.target)){let u=ti(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??Hr.height,d=this.browser.getViewport()?.width??Hr.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 oe("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 oe("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=n.delay*1e3;await et(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(zl(n.target)){let p=ti(n.target.pixels),m={...n,relativePosition:n.relativePosition?ti(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?ti(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 Uw(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(zl(n.fromTarget)&&zl(n.toTarget)){let c=ti(n.fromTarget.pixels),d=ti(n.toTarget.pixels);await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0}),{coordinates:c});break}if(zl(n.fromTarget)||zl(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 oe("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&zl(n.target)){let p=ti(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(!ed(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:Sm(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 vp({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 oe("ActionFailureError",l instanceof Error?l.message:`${l}`,{errOptions:{cause:l}})}try{JSON.stringify(a);}catch(l){throw new oe("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&&zl(n.target)){let m=ti(n.target.pixels),h={...n,relativePosition:n.relativePosition?ti(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:Sm(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 Uw(a,p.urlAfterCommand)&&(p.succeedImmediately=true,p.succeedImmediatelyReason="URL changed"),p}case "HOVER":{if(zl(n.target)){let c=ti(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?ti(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(!ed(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&&!ed(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 Uw(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=Zje(fetch,a),c;try{c=new URL(n.url).hostname;}catch{}let d=await Yte({command:n,baseUrl:this.browser.baseUrl,logger:s,fetchImplementation:l});return {data:WS.parse({...d,cookies:rq(a,c)}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GRAPHQL_REQUEST":return {data:await Qte({command:n,baseUrl:this.browser.baseUrl,logger:s}),succeedImmediately:false,urlAfterCommand:this.browser.url()};case "VISUAL_DIFF":return Kte({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 gee({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 oe("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&&cp(n.storageState)){let l=io__default.resolve(n.storageState);ko__default.mkdirSync(io__default.dirname(l),{recursive:true}),ko__default.writeFileSync(l,`${JSON.stringify(a,null,2)}
|
|
5797
5797
|
`,"utf8");}return {data:a,succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AUTH_LOAD":{let a;if(cp(n.storageState))try{a=JSON.parse(ko__default.readFileSync(io__default.resolve(n.storageState),"utf8"));}catch(c){throw new oe("UserConfigurationError",`Failed to read auth state from '${n.storageState}': ${q(c)}`,{errOptions:{cause:c}})}else if(!n.storageState.trim())a=void 0;else if(a=await vp({orgId:this.orgId,code:n.storageState,fragment:false,context:o,logger:s,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof a!="object")throw new oe("ActionFailureError",`Credentials must evaluate to an object (received ${typeof a} instead)`);let l;try{l=KC.optional().parse(a);}catch(c){throw new oe("ActionFailureError",`Credentials provided do not follow the required format: ${c}`)}await this.browser.loadAuthState(l);break}case "ELEMENT_CHECK":{let a=(n.timeout??ha)*1e3,l=this.generator.getAgentConfig()?.assertion;if(Wte(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 Mx({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&>(n,d.cache?.memory.traces,s);}}let c=await zte({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 Va({action:async()=>Nx({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 Pp(n.requestMatcher),l=this.browser.registerRequestListener(a);return this.registeredListeners[n.key]=l.then(async c=>await d0(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 oe("ActionFailureError",`No listener registered with key: ${n.key}`);let l=n.timeout??10;return {data:await xe(a,{milliseconds:l*1e3,message:`Request listener timed out after ${l} seconds`}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "RECORD_REQUESTS":{let a=new Pp(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]=Ex(c);},onRequestComplete:(l,c)=>{this.recordedRequests[n.key]?.[l]&&(this.recordedRequests[n.key][l]=Ex(c));}}),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GET_RECORDED_REQUESTS":{let a=this.recordedRequests[n.key];if(!a)throw new oe("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 Pp(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 Pp(n.requestMatcher),async(l,c)=>{let d=await vp({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=_q.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:Wt(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 xx({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:Wt(this.logger)})}async getFailureRecoveryPlan(t,n){return this.generator.getFailureRecoveryPlan(t,{disableCache:true,abortSignal:this.executeAbortController.signal,loggerTags:Wt(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(Vr({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 yi({orgId:c,s:f,context:r,logger:o,localTools:s,signal:u});g={orgId:c,cacheKeys:[y,...Object.entries(n).map(([T,A])=>`${T}:${A}`)]},o.info({original:f,keyParams:g},"Module cache key params");let S=Date.now();for(;Date.now()-S<g2;){u?.throwIfAborted();let T=await i.getCacheResult(g);if(T){o.info({cacheResult:Tn(T,1e3,true)},"Got result from module execution cache"),p=Lx(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 A=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${hostname()};runId:${d}`},u);if(A.acquired){h=A.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 et(2500+Math.random()*1e4,u);}}try{if(!p)p=await nGe(e);else if(t.autoAuth){let f=KC.safeParse(p.data);if(!f.success)throw new oe("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},A=await Nx({timeout:ha,assertion:T,browser:l,logger:o,signal:u,autoExpandIframes:!!l.userBrowserSettings.autoExpandIframes});A.success?o.debug({invalResult:A},"Cached result still valid after page check, continuing..."):(o.info({invalResult:A},"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 oGe({step:t,result:p,browser:a.browser,cacheKeyPrefix:h,logger:o,storage:i});}finally{h!==void 0&&await i.releaseCacheLock(h);}}return p},nGe=async e=>{let{currentParentIdChain:t}=e,{step:n,tracer:o}=e.moduleParams,r=Lx(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,Es({asyncTasks:e.work.asyncTasks,nestedResults:a,result:r,logger:e.fixtures.logger}),r};function Lx(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 ene({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 vp({orgId:e,code:l,fragment:!0,context:n,logger:o,localTools:r,signal:i});}return s}catch(a){throw i?.throwIfAborted(),new oe("UserConfigurationError",`Failed to evaluate module inputs: ${a}`)}}async function oGe({step:e,result:t,browser:n,cacheKeyPrefix:o,logger:r,storage:i}){let s=e.cacheConfig?.cacheExpiryMs;(!s||s===_J)&&(s=e.defaultCacheTtl??PJ);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:Vr({json:a,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:a,keyPrefix:o,ttlMs:s});}async function Mp(e,t,n){return rGe(e,t,n)}async function rGe(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 oe?a=`${r}`:a=`An unexpected error occurred: ${r.message}`,e.type==="RESOLVED_MODULE"){let l=Lx(e,{},"FAILED");return l.message=a,l.startedAt=o,l.finishedAt=i,l}return {...If(e),startedAt:o,finishedAt:i,status:s,data:null,message:a,results:[]}}}async function bi(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 tne=500,nne=120;async function ine({gitContext:e,remoteGitContext:t,remoteGitClient:n,githubRepository:o,branchName:r,mainBranchName:i,logger:s}){if(!(!e&&!t))try{let a=e?await sGe(e):lGe(t),l=r!==void 0&&r===i,c=[];if(l){let d=e?await aGe(e):t.comparison.commits.at(-1)?.message;d&&c.push(`Last commit on ${i}:
|
|
5798
5798
|
${one(d.trim())}`);}else {let d=await iGe({remoteGitContext:t,remoteGitClient:n,githubRepository:o,branchName:r,logger:s});d&&c.push(`Open pull request #${d.issueNumber}: ${d.title??"(no title)"}${d.body?`
|
|
5799
5799
|
|
|
@@ -7577,7 +7577,7 @@ with this test we are editing:
|
|
|
7577
7577
|
to pick which of these modules are relevant:
|
|
7578
7578
|
|
|
7579
7579
|
`;let p=SYe(c);u+=p;let m=streamObject({schema:xH,model:d("claude-sonnet-4-5-20250929"),system:yYe,messages:[{role:"user",content:u}],providerOptions:{anthropic:vs}}),h=[];for await(let T of m.textStream)h.push(T);let g=h.join(""),f;try{let T=JSON.parse(g);f=xH.parse(T);}catch(T){r.error({rawResponse:g,parseError:T},"Failed to parse AI response as JSON"),n.addError(`Failed to parse AI response: ${q(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: ${q(c)}`);}}}),dP=[TYe,gYe];var AYe=1e5,bae=Fo({schema:{name:sb,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=lu({response:n,sessionId:t.sessionId,toolName:sb});if(!o)return;o.controller.setOpen();let r=await CH({browser:o.controller.browser,isRemoteBrowser:o.isRemoteBrowser,supportsFileOutput:e.supportsFileOutput,returnBrowserState:t.returnBrowserState,returnScreenshot:t.returnScreenshot,tokenLimit:AYe,hint:t.hint,filtering:{generator:e.generator,orgId:e.orgId,logger:e.logger,signal:o.controller.executeAbortController.signal}});n.addContentParts(r);}}),Tae=Fo({schema:{name:ab,description:qv,inputSchema:{sessionId:z$1.string(),filters:z$1.array(z$1.string().trim().min(1)).min(1).optional().describe(Kv)}},handle:async(e,t,n)=>{let o=lu({response:n,sessionId:t.sessionId,toolName:ab});if(!o)return;let r=await sa({testContext:o.context,supportsFileOutput:e.supportsFileOutput,filters:t.filters});n.addContentParts(r);}});var Aae=Fo({schema:{name:sd,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. ${QA} 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 ${Cr} 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&&(Jr(e.project.rootDir),i=Xr({rootDir:e.project.rootDir,entity:"video",ext:"d"}),mkdirSync(i,{recursive:true}));let s;try{let l=Do();if(!l){n.addError("API client is not initialized; cannot start MCP session.");return}let c=await qi({project:await qt({configFilePath:t.projectConfigPath??e.project.configFilePath,nameFilter:t.projectNameFilter,skipExitOnError:!0}),apiClient:l}),d=new la(l,e.orgId,c);s=await aa.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(q(l));return}ia({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.idleTimeoutMs===void 0?void 0:s.lastAccessedAt+s.idleTimeoutMs,idleTimeoutMinutes:s.idleTimeoutMs===void 0?void 0:s.idleTimeoutMs/(60*1e3),envName:s.envName,baseUrl:s.baseUrl,viewport:a},null,2)),n.addContentParts(await Woe({projectRootAbsolutePath:e.project.rootDir,projectConfigAbsolutePath:e.project.configFilePath,cwd:process.cwd(),stepSchema:Is(),stepSchemaTitle:"Step schema",supportsFileOutput:e.supportsFileOutput}));try{let l=await zp({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:q(l)},null,2));}i&&n.addContentParts($({text:ar({filePath:i,title:"Video output directory"}),section:"Video Output"}));}}),Eae=Fo({schema:{name:Xv,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=aa.getSession(o),i=r?.videoOutputDir,s=await aa.killSession(t.sessionId,"explicit kill");if(s.killed&&ia({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:aa.listSessionIds()},null,2));return}n.addPartFromText(JSON.stringify({sessionId:t.sessionId,killed:!0},null,2));let a=await qoe({killResult:s,rootDir:e.project.rootDir});a&&n.addContentParts($({text:ar({filePath:a.filePath,title:"Session span report"}),section:"Session Spans"})),i&&n.addContentParts($({text:ar({filePath:i,title:"Video output directory"}),section:"Video Output"}));}catch(r){n.addError(q(r));}}});var Ky=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 _H({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]},_H=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 au({orgId:u,parentStep:null,parentTracer:null,socket:c}):new ST);r.setOpen();let y={results:[],asyncTasks:[],state:{autoHealingDisabled:true,failureRecoveryDisabled:true,failureRecoveryAttempts:0},...t&&{fastForwardingToStep:true}},S=()=>ra({listParams:{containerName:"agent-step-list",steps:e,tracer:f},fixtures:g,options:{collectDebugData:false,reinitializeBrowser:false,disableHealing:true},inputs:{orgId:u,userId:p7(),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 uP({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,onStepResult:h}){let g=await v_(e,{project:t,logger:n,tempCaches:u});switch(g.type){case "PRESET_ACTION":return wYe({step:g,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,tempCaches:u,usageTracker:p,apiClient:m,onStepResult:h});case "AI_ACTION_DYNAMIC":return IYe({step:g,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,usageTracker:p,apiClient:m,onStepResult:h});case "RESOLVED_MODULE":return xYe({step:g,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,usageTracker:p,apiClient:m,onStepResult:h});default:{let[f,y]=await Promise.all([Zr({browser:r.browser,supportsFileOutput:d}),sa({testContext:c,supportsFileOutput:d})]);return [...$({text:`Preview for step type ${g.type} is not supported. Only PRESET_ACTION, RESOLVED_MODULE, and AI_ACTION_DYNAMIC are supported.`,section:"Error"}),...f,...y]}}}async function wYe({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,onStepResult:m}){let h=await Ky({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?.(h);let g=[];h?h.status==="SUCCESS"?(_Ye({logger:t,tempCaches:d,command:e.command,parts:g}),g.push(...$({text:`Step Execution successful: ${h.message}`,section:"Successful Result"}))):g.push(...$({text:`Step Execution failed: ${h.message}`,section:"Error"})):g.push(...$({text:"Step Execution errored for an unknown reason.",section:"Error"}));let[f,y]=await Promise.all([Zr({browser:o.browser,supportsFileOutput:c}),sa({testContext:l,supportsFileOutput:c})]);return g.push(...f,...y),g}async function IYe({step:e,logger:t,storage:n,controller:o,codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,supportsFileOutput:c,usageTracker:d,apiClient:u,onStepResult:p}){let m=await Ky({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?.(m);let h=[];m?m.status==="SUCCESS"?h.push(...$({text:`AI action completed successfully: ${m.message??"Goal achieved"}`,section:"Successful Result"})):h.push(...$({text:`AI action failed: ${m.message??"Unknown error while previewing AI action"}`,section:"Error"})):h.push(...$({text:"AI action executed with unknown result.",section:"Error"}));let[g,f]=await Promise.all([Zr({browser:o.browser,supportsFileOutput:c}),sa({testContext:l,supportsFileOutput:c})]);return h.push(...g,...f),h}async function xYe({step:e,logger:t,storage:n,controller:o,codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,supportsFileOutput:c,usageTracker:d,apiClient:u,onStepResult:p}){let m=await Ky({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?.(m);let h=[];m?m.status==="SUCCESS"?h.push(...$({text:`Module executed successfully: ${m.message}`,section:"Successful Result"})):h.push(...$({text:`Module execution failed: ${m.message}`,section:"Error"})):h.push(...$({text:"Module execution errored for an unknown reason.",section:"Error"}));let[g,f]=await Promise.all([Zr({browser:o.browser,supportsFileOutput:c}),sa({testContext:l,supportsFileOutput:c})]);return h.push(...g,...f),h}function _Ye({logger:e,tempCaches:t,command:n,parts:o}){if(t&&pr(n)&&n.cache)try{let r=randomUUID();t[r]=ic.parse(cloneDeep({type:n.type,cache:n.cache})),o.push(...$({text:r,section:"CacheId"}));}catch(r){e.warn({err:r},"Failed to save temp cache for step. Continuing...");}}var vae=({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=mE(i.id,a,t.fromStepId,t.parentStepIdChain);if(o.fastForwardingToStep){if(!l)return false;o.fastForwardingToStep=false;}return o.total+=1,!!(n&&mE(i.id,a,n.toStepId,n.parentStepIdChain))};return zi({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=mE(i.id,a,t.fromStepId,t.parentStepIdChain);if(o.fastForwardingToStep){if(!l)return false;o.fastForwardingToStep=false;}return !!(n&&mE(i.id,a,n.toStepId,n.parentStepIdChain))},onSimpleStepContainer:(i,s)=>r(i,s.parentChain)}),o.total};var OYe="Cannot add a module step inside another module. Modules cannot be nested.";function PH(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 MYe(e,t,n){let o=PH(e,t);if(!n?.length)return o;let r=k4(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 Cae(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])zi({steps:r,onPresetAction:o,onConditional:o,onSimpleStepContainer:o});}async function pP({project:e,storage:t,orgId:n,logger:o,testPath:r,saveChangesToDisk:i,supportsFileOutput:s,tempCaches:a,mutableStepState:l,onStepSplice:c,params:d,envName:u}){let p=io__default.join(e.rootDir,r),m=await t.getTestByPath({relativeTestPath:r,logger:o}),h=l?.stepLists??m,g=cloneDeep({steps:h.steps??[],beforeSteps:h.beforeSteps??[],afterSteps:h.afterSteps??[]}),f=cloneDeep(g),y=await Promise.all(d.steps.map(x=>v_(x,{project:e,logger:o,tempCaches:a}))),S=cloneDeep(y),T=d.parentStepIdChain,A;try{A=MYe(f,d.targetSection,T);}catch(x){return Q($({text:`Error: ${q(x)}`,section:"Error"}))}if(d.startIndex<0||d.startIndex>A.length)return Q($({text:`Error: Invalid startIndex ${d.startIndex} for splicing ${d.targetSection} section with ${A.length} steps (must be 0-${A.length})`,section:"Error"}));let v=y.length,w=d.deleteCount,I=cloneDeep(A.slice(d.startIndex,d.startIndex+w)),_=[];if(T?.length){let x=D4(PH(f,d.targetSection),T,d.targetSection);if(_.push(...x),x.some(N=>N.type==="RESOLVED_MODULE")&&y.some(N=>N.type==="RESOLVED_MODULE"))return Q($({text:`Error: ${OYe}`,section:"Error"}))}A.splice(d.startIndex,d.deleteCount,...y);for(let x of y)x.type==="RESOLVED_MODULE"&&Cae(f,x);for(let x of _)x.type==="RESOLVED_MODULE"&&Cae(f,x);if(l&&(l.stepLists=f),c?.({targetSection:d.targetSection,parentStepIdChain:T??[],startIndex:d.startIndex,deletedSteps:I,insertedSteps:S}),i){let x=await t.updateTestByPath({logger:o,relativeTestPath:r,stepLists:f,schemaVersion:lt});o.info({testPath:r,testFilePath:p,projectFileFormat:e.config.fileFormat,moduleUpdateCount:x.moduleUpdates.length,snapshotCacheCount:x.snapshotCachesToSave.length},"MCP splice persisted test changes to disk");}else o.info({testPath:r,testFilePath:p,projectFileFormat:e.config.fileFormat},"MCP splice skipped disk persistence");let R=[...$({text:`Successfully spliced ${v} step(s) at index ${d.startIndex} in the ${d.targetSection} section, removing ${w} step(s).`,section:"Result"})];return R.push(...await kYe({logger:o,project:e,orgId:n,testId:m.id,environment:u,originalSteps:g,updatedSteps:f})),R.push(...await Rie({rootDir:e.rootDir,supportsFileOutput:s,deletedStepRefs:I.map((x,O)=>({id:x.id,index:d.startIndex+O})),insertedStepRefs:S.map((x,O)=>({id:x.id,index:d.startIndex+O})),deletedSteps:ip(I,{includeCache:false}),insertedSteps:ip(S,{includeCache:false}),metadata:{section:d.targetSection,parentStepIdChain:T??[],startIndex:d.startIndex,deleteCount:w,insertedCount:v},artifactEntity:"splice-restoration-payload"})),d.returnTest&&R.push(...$({text:JSON.stringify(await iP({project:e,storage:t,selector:{path:r},envName:u,logger:o,mutableStepState:l,supportsFileOutput:s,hydrateStepIdentity:false}),null,2),section:"Test Content"})),Q(R)}async function mP({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,onStepResults:T}){let{fromStep:A,toStep:v,targetSection:w}=p,I=await o.getTestByPath({relativeTestPath:n,logger:t}),{alwaysSaveCache:_,noCache:R}=Il(),x=await Ti({logger:t,orgId:a,project:e,alwaysSaveCache:_,noCache:R||S===true}),O=f?.stepLists??{beforeSteps:I.beforeSteps??[],afterSteps:I.afterSteps??[],steps:I.steps};await x.resolveStepCacheEntries({logger:t,schemaVersion:I.schemaVersion,stepLists:O,testId:I.id,environment:c,useSnapshotIdentityCache:!f&&e.config.fileFormat==="v2"}),f&&(f.stepLists=O);let N=S?cloneDeep(O):O;S&&NYe(N);let k=PH(N,w),W=cloneDeep({steps:N.steps,beforeSteps:N.beforeSteps,afterSteps:N.afterSteps}),{result:X}=Hm(k,A.fromStepId,A.parentStepIdChain);if(!X)return Q($({text:`Error: No step found with id "${A.fromStepId}" and parent chain [${A.parentStepIdChain.join(", ")}] in ${w} section.`,section:"Error"}));if(v){let{result:je}=Hm(k,v.toStepId,v.parentStepIdChain);if(!je)return Q($({text:`Error: No step found with id "${v.toStepId}" and parent chain [${v.parentStepIdChain.join(", ")}] in ${w} section.`,section:"Error"}))}if(u?.setProgressTotal){let je=vae({steps:k,fromStep:A,toStep:v});u.setProgressTotal(je);}r.setOpen();let ee;try{ee=await _H({steps:k,controller:r,storage:o,codeEvalTools:i,logger:t,socket:s,orgId:a,sessionId:l,testContext:d,fromStep:A,toStep:v,tracer:u,usageTracker:g,apiClient:y});}finally{await g.flush(t);}let{results:j}=ee;if(j&&j.length>0&&T?.(j),!j||j.length===0)return Q($({text:"Error: No steps were executed.",section:"Error"}));let V=j.at(-1);if(!V)return Q($({text:"Error: No steps were executed.",section:"Error"}));let M={logger:t,cacheStorage:x,orgId:a,testId:I.id,environment:c,originalStepsWithCaches:W,updatedStepsWithCaches:{steps:N.steps,beforeSteps:N.beforeSteps??[],afterSteps:N.afterSteps??[]}},J=V.status!=="SUCCESS";await Gm({logger:t,cacheStorage:x,orgId:a,testId:I.id,environment:c,stepLists:M.updatedStepsWithCaches,useSnapshotIdentityCache:e.config.fileFormat==="v2"}),J?V.status==="FAILED"&&await Cf(M):await $m(M);let B=w==="main"?"":` in ${w}`,D=je=>{let ge="fromStepId"in je?je.fromStepId:je.toStepId;return je.parentStepIdChain.length>0?`id "${ge}" (parent chain [${je.parentStepIdChain.join(", ")}])`:`id "${ge}"`},Y=A?D(A):"beginning",te=v?`Steps from ${Y} through ${D(v)}${B}`:`Steps from ${Y} to end${B}`,ue=[];if(J)ue.push(...$({text:`Error: step with id ${V.id} failed: ${V.message}`,section:"Error"}));else {r.setOpen();let je=`${te} executed successfully.`;ue.push(...$({text:je,section:"Result"})),V.data&&ue.push(...$({text:`Data: ${JSON.stringify(V.data,null,2)}`,section:"Result Data"}));}let[Te,Ae]=await Promise.all([Zr({browser:r.browser,supportsFileOutput:h}),sa({testContext:d,supportsFileOutput:h,limits:{tokenLimit:m}})]);return Q([...ue,...Te,...Ae])}function NYe(e){for(let t of [e.steps,e.beforeSteps,e.afterSteps])t&&LYe(t);}function LYe(e){zi({steps:e,earlyStop:false,onPresetAction:t=>(pr(t.command)&&delete t.command.cache,false),onSimpleStepContainer:()=>false,onConditional:()=>false});}async function kYe({logger:e,project:t,orgId:n,testId:o,environment:r,originalSteps:i,updatedSteps:s}){let a=[];try{let{alwaysSaveCache:l,noCache:c}=Il(),d=await Ti({logger:e,orgId:n,project:t,alwaysSaveCache:l,noCache:c});await Gm({logger:e,cacheStorage:d,orgId:n,testId:o,environment:r,stepLists:s,useSnapshotIdentityCache:t.config.fileFormat==="v2"}),await $m({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(...$({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 OH=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 hP(this.reporter,this.parentStepIdChain.concat(this.step.id),this.setTotal)}},hP=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 OH(this.reporter,t.step,this.parentStepIdChain,this.setTotal)}};function Rae(e,t,n,o,r){let i=pE(e),s={completed:0,total:0},a=new AbortController,l=false,c=m=>{i&&iie(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=Vn(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=Vn(m);r&&(r.currentStep=void 0,r.lastCompletedStep=h),c(`Completed: ${h}`);}};return new hP(p,[],u)}var Iae=`CLI-style step definition. Use the Step Authoring Guide artifact returned from ${sd} when you start your session to get the full step schema.`,DYe=Fo({schema:{name:qV,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:SL},handle:async(e,t,n,o)=>{try{let r=await e.storage.createTest(t);ia({type:"mcp:test_create",test_platform:"web"}),n.addPartFromText(JSON.stringify(r,null,2));}catch(r){n.addError(q(r));return}}}),FYe=Fo({schema:{name:Cr,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 ${um}, 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 ${GM}. 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 zp({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(q(r));return}}}),wae=Fo({schema:{name:Jv,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 ${Sa}. 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=lu({response:n,sessionId:t.sessionId,toolName:Jv});if(!r)return;let i=r.storage.getProject();if(i.config.fileFormat!=="v2"){n.addError(`${Jv} 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}=Il(),d=await Ti({logger:e.logger,orgId:r.orgId,project:i,alwaysSaveCache:l,noCache:c});r.mutableStepState.testId=s.id,r.mutableStepState.stepLists=await Ma({cacheStorage:d,logger:e.logger,schemaVersion:s.schemaVersion,stepLists:a,testId:s.id,environment:r.envName,useSnapshotIdentityCache:true}),n.addContentParts($({text:`Reloaded test ${s.id} from disk into session ${r.sessionId}.`,section:"Result"})),n.addContentParts(await zp({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}));}}),BYe={...wae,addToolToMcpServer:(e,t)=>{e.project.config.fileFormat==="v2"&&wae.addToolToMcpServer(e,t);}},UYe=Fo({schema:{name:GM,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. ${QA} 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: ${q(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: ${q(c)}`);}let l=await Koe({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($({section:"Discovery Errors",text:a.map(c=>`- ${c}`).join(`
|
|
7580
|
-
`)}));}}),xae=Fo({schema:{name:lb,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(Iae)}},handle:async(e,t,n,o)=>{let{sessionId:r,step:i}=t,s=lu({response:n,sessionId:r,toolName:lb});if(!s)return;s.controller.setOpen();let a;try{a=await uP({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:Do()});}finally{await s.usageTracker.flush(e.logger);}n.addContentParts(a);}}),_ae=Fo({schema:{name:um,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(Iae),targetSection:cd.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=lu({response:n,sessionId:t.sessionId,toolName:um});if(!r)return;let i=await pP({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&&ia({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);}}),Pae=Fo({schema:{name:Sa,description:`${Yv} Use step ids from the active session: the Test Content section returned by ${sd}, or the inserted/deleted refs returned by ${um}. 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 ${M_/1e3} seconds, this tool responds early with the currently executing step while execution continues in the background; call ${yg} 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:gC,toStep:fC.optional(),targetSection:cd.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=lu({response:n,sessionId:t.sessionId,toolName:Sa});if(!r)return;r.controller.setOpen(),t.resetSession&&await sP({project:r.storage.getProject(),logger:e.logger,relativeTestPath:r.relativeTestPath,orgId:r.orgId,storage:r.storage,apiKey:xl(),baseUrl:Xi(),controller:r.controller,testContext:r.context,supportsFileOutput:e.supportsFileOutput,isRemoteBrowser:r.isRemoteBrowser});let i=Sie({runs:r.runStepRuns,run:async a=>{let l=Rae(o,e.logger,n,()=>{aa.touchSession(r.sessionId);},bie({runs:r.runStepRuns,stepRunnerId:a})),c=await mP({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:Do(),disableCache:t.disableCache});return ia({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 tH({runs:r.runStepRuns,stepRunnerId:i.stepRunnerId,activeRunCountAtStart:i.activeRunCountAtStart});nH({result:s,response:n,runStepToolName:Sa,statusToolName:yg});}}),Oae=Fo({schema:{name:yg,description:`Check ${Sa} executions for the active session. Responds with active runs, finished runs, and any newly finished results. Poll this after ${Sa} reports that execution is taking longer than ${M_/1e3} seconds. Prefer passing the stepRunnerId reported by ${Sa} to scope the response to that run; only omit it when you need to see every run for the session. Optionally pass timeoutSeconds (0-${eH}, 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 ${Sa}. Recommended for most polls.`),timeoutSeconds:z$1.number().min(0).max(eH).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=lu({response:n,sessionId:t.sessionId,toolName:yg});if(!r)return;let i=await tH({runs:r.runStepRuns,stepRunnerId:t.stepRunnerId,timeoutMs:t.timeoutSeconds*1e3});nH({result:i,response:n,runStepToolName:Sa,statusToolName:yg});}}),Mae=[UYe,DYe,FYe,BYe];var Nae=[bae,Tae,Aae,Eae,xae,Pae,Oae,_ae];async function GYe({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 Ti({logger:t,orgId:r,project:n}),d=await Ma({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 gP({project:e,storage:t,logger:n,relativeTestPath:o,saveChangesToDisk:r,mutableStepState:i,params:s}){let a=ho();Zl(s.name);let l=await t.scanEntities(),c;s.startIndex!==void 0&&o!==void 0&&(c=await GYe({testPath:o,logger:n,project:e,storage:t,orgId:a,mutableStepState:i}));let{stepsToExtract:d,startIndex:u,endIndex:p}=wie({moduleName:s.name,existingModuleNames:Object.values(l.modules).map(R=>R.name),...s,parameterNames:s.parameters,testPath:o,availableSteps:c?.availableSteps,containsNestedModuleStep:L4}),{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:A,testId:v}=c.cacheSaveContext,w=e.config.fileFormat==="v2",{cachesToSave:I,snapshotCachesToSave:_}=await ro({stepLists:S,useSnapshotIdentityCache:w,cacheCreationParams:{orgId:a,testId:v,environment:T}});return w&&await A.saveSnapshotCacheEntries({logger:n,entries:_}),await A.saveStepCacheEntries({logger:n,entries:I}),r&&await t.updateTestByPath({logger:n,relativeTestPath:o,stepLists:S,schemaVersion:lt}),{module:m}}var Lae=Fo({schema:{name:zV,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(wm),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=une({projectRoot:e.project.rootDir,filePath:r,pathLabel:"testPath"}),a=await gP({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(q(s));}}});var kae=Fo({schema:{name:KV,description:"List active local test quarantines in a quarantine-date range, ordered from newest to oldest. Each item includes the quarantine reason and the latest retained failed CLI run, including failure and heal details.",inputSchema:fJ.shape},handle:async(e,t,n)=>{try{let o=await e.apiClient.listQuarantinedTests(t);if(!e.supportsFileOutput){n.addPartFromText(JSON.stringify(o,null,2));return}let r=e.project.rootDir;Jr(r);let i=Xr({rootDir:r,entity:"quarantined-tests",ext:"json"});await writeFile(i,JSON.stringify(o,null,2),"utf8"),n.addContentParts($({section:"Quarantined tests",text:ar({filePath:i,title:`Quarantined tests (${o.quarantinedTests.length})`})}));}catch(o){n.addError(q(o));}}});var Jy=[...Mae,...dP,...Nae,Lae,dre,Sre,kae,vre,mre];var Dae=Jy.map(e=>e.tool),fP=new Map(Dae.map(e=>[e.schema.name,e]));async function Fae(e){let{project:t,applicationName:n,daemonPort:o,daemonToken:r,daemonSessionId:i,logger:s,cliVersion:a}=e,l=t.configFilePath;await aP(e);let{context:c}=lP({...e,logger:s.child({daemonSessionId:i}),applicationName:`${n}-daemon`,serverId:i});await mie({adapter:{getTool:d=>{let u=fP.get(d);if(!u)throw new Error(`Unknown web MCP tool '${d}'. Known tools: ${Array.from(fP.keys()).join(", ")}`);return {name:u.schema.name,execute:async({input:p,extra:m})=>await die({context:c,tool:u,input:p,extra:m})}}},sessionManager:aa,daemonPort:o,daemonToken:r,daemonId:i,cliVersion:a,workerType:"momentic-web-mcp",configPath:l,inactivityTimeoutMsOverride:IH(e)*2,onShutdown:()=>{Qd();}});}async function MH(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 rie({workerType:"momentic-web-mcp",configPath:p,apiKey:o,serverUrl:r,cliVersion:i,logger:n,buildDaemonArgs:({entryScript:m})=>WYe({entryScript:m,serverUrl:r,configPath:p,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u})})}async function Bae(e){let{logger:t,applicationName:n,cliVersion:o,serverUrl:r}=e;Xd(r),await MH(e);let{info:i,mcpLogger:s}=wH({logger:t,applicationName:`${n}-daemon-proxy`,cliVersion:o});return O_({context:{logger:s},info:i,tools:uie({tools:Dae,resolveDaemonStateForCall:()=>MH(e),logger:s})})}var zYe=30*6e4;async function NH({options:e,toolName:t,input:n,timeoutMs:o=zYe}){Xd(e.serverUrl);let r=fP.get(t);if(!r)throw new Error(`Unknown web MCP tool '${t}'. Known tools: ${Array.from(fP.keys()).join(", ")}`);let i=r.schema.inputSchema.parse(n),s=await MH(e);return QU({state:s,toolName:t,input:i,timeoutMs:o})}function WYe({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 LH=async(e,t)=>{try{let{killed:n,failed:o}=await aa.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 kH(e){let{daemon:t,logger:n}=e,o=oie.safeParse(process.env);if(t&&o.success&&o.data[__]==="momentic-web-mcp")return Fae({...e,daemonPort:o.data[I_],daemonToken:o.data[x_],daemonSessionId:o.data[P_]});if(Qu(n,true),t)return await Bae(e);await aP(e);let{context:r,info:i}=lP(e);return O_({context:r,info:i,tools:Jy,shutdownHandlers:[LH,Qd,async()=>{await nP();}]})}var _E="3.25.0",_n=rf({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:_E});(async()=>{try{let e=await Ua(_n);e.gitBranchName&&_n.addBinding("branch",e.gitBranchName);}catch{}})();var Kp=Router();async function SP(e){return (await zf(e,_n)).map(o=>{let r=e.modules[o.moduleId];if(!r){C.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)}Kp.get("/",Et(async(e,t)=>{let n=at(),o=await Xs(n),r=await SP(o);t.status(200).json(r);}));Kp.post("/",Et(async(e,t)=>{let n;try{n=n2.parse(e.body);}catch(l){t.status(400).json({error:`Invalid request body: ${l}`});return}try{Zl(n.name);}catch(l){t.status(400).json({error:`Invalid module name: ${l}`});return}let o=at(),r=await We(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=io__default.join(o.rootDir,n.folderPath??io__default.dirname(n.testFilePath));if(!ko__default.existsSync(s)||!ko__default.statSync(s).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let a=await cI({...n,folder:s,project:o,momenticFiles:r});t.status(201).json(a);}));Kp.get("/:moduleId/tests",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=at(),o=await We(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))fZ(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);}));Kp.get("/:moduleId",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=await Xs(at()),o=n.modules[e.params.moduleId];if(!o){t.status(404).json({error:"Module not found."});return}try{let r=await wc({modHandle:o,momenticFiles:n,logger:C});t.json(r);}catch(r){t.status(400).json({err:r});}}));Kp.post("/:moduleId/duplicate",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=t2.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Zl(n.name);}catch(h){t.status(400).json({error:h.message});return}let o=at(),r=await We(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=io__default.join(o.rootDir,io__default.dirname(i.relativePath));if(!ko__default.existsSync(a)||!ko__default.statSync(a).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let l=Fn(n.name),c=io__default.join(a,`${l}.module.yaml`),d=Cc({projectConfig:o.config,momenticFiles:r,entityType:"module"}),{stepsToSave:u}=await ro({stepLists:{steps:s.steps},createNewCacheIds:true}),p={fileType:Fe.MODULE,schemaVersion:lt,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};La({module:p,filePath:c,projectConfig:o.config,momenticFiles:r});let m={relativeFilePath:io__default.relative(o.rootDir,c)};t.status(201).json(m);}));Kp.patch("/:moduleId/move",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=r2.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${q(i)}`});return}let o=at();if(!(await Xs(o)).modules[e.params.moduleId]){t.status(404).json({error:"Module not found."});return}await TZ({moduleId:e.params.moduleId,targetFolderRelativePath:n.folderPath,project:o}),t.status(200).json({message:"ok"});}));Kp.patch("/:moduleId/metadata",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=o2.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let o=at(),r=await Xs(o);await AZ({moduleId:e.params.moduleId,content:n,momenticFiles:r,logger:C,project:o}),t.status(201).json({message:"ok"});}));var Uae=Kp;var PE=Router();PE.get("/",Et(async(e,t)=>{let n=at(),o=await We(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 SP(o),l={labels:i,tests:s,modules:a};t.status(200).json(l);}));PE.get("/folders",Et(async(e,t)=>{let n=at(),o=await cZ(n);t.status(200).json(o);}));PE.get("/labels",Et(async(e,t)=>{let n=at(),o=await We(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);}));PE.post("/in-folder",Et(async(e,t)=>{let n=Jq.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=at(),[i,s]=await Promise.all([lZ(r,o),Xs(r)]),a=Object.values(i.tests),l=await SP(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 Hae=PE;var DH=Router();DH.get("/",Et((e,t)=>{let n=gI(at(),_n);t.status(200).json(n);}));DH.get("/names",Et((e,t)=>{let o=at().config.environments?.map(r=>r.name)??[];t.status(200).json(o);}));var jae=DH;var Gae=Router();Gae.get("/",Et((e,t)=>{let n={userId:Oc(),orgId:ho(),email:hy(),name:m7(),pylonEmailHash:h7(),cliVersion:_E};t.status(200).json(n);}));var $ae=Gae;var FH="mcp-session-id",Vae="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",bP=Router();function tJe(){let e=process.env[Vae];if(!e)return Rh*60*1e3;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<1?(_n.warn({envVar:Vae,rawValue:e,fallback:Rh},"Invalid MCP session idle timeout env var; falling back to default"),Rh*60*1e3):t*60*1e3}function nJe(e){let{headfulDefault:t,supportsFileOutput:n}={},o={serverId:randomUUID(),applicationName:"momentic-mcp-desktop-server",cliVersion:_E},r=at(),i=xl(),s=Xi(),a=_n.child({orgId:ho(),userId:Oc(),...o}),l=new xt({baseUrl:s,apiKey:i,logger:a,mode:"interactive",runner:"mcp"}),c=eT(process.env.MOMENTIC_HEADFUL_BROWSER),d=new qo(r.config.ai?.agentConfig,{baseUrl:s,apiKey:i,logger:a,mode:"interactive",runner:"mcp"}),u=ho(),p=new la(l,u,r);return {context:{project:r,orgId:u,logger:a,generator:d,apiClient:l,storage:p,serverId:o.serverId,extractBaseDir:Nl(r.rootDir),saveChangesToDisk:true,supportsFileOutput:n??true,knowledgeRetrievalResults:an,knowledgeCitations:[],sessionIdleTimeoutMs:tJe(),headfulDefault:t??c??true,categoryDefinitions:r.config.ai?.classification?.categories??is},info:o}}var cu={};bP.post("/",async(e,t)=>{let n=String(e.headers[FH]??"");try{if(n&&cu[n]){await cu[n].handleRequest(e,t,e.body);return}if(!n&&isInitializeRequest(e.body)){let{context:o,info:r}=nJe(),i=ZU(o,r,Jy),s=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableDnsRebindingProtection:!1,onsessioninitialized:a=>{cu[a]=s;}});s.onclose=()=>{let a=s.sessionId;a&&cu[a]&&delete cu[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});}});bP.get("/",async(e,t)=>{let n=String(e.headers[FH]??"");if(!n||!cu[n]){t.status(400).send("Invalid or missing session ID");return}await cu[n].handleRequest(e,t);});bP.delete("/",async(e,t)=>{let n=String(e.headers[FH]??"");if(!n||!cu[n]){t.status(400).send("Invalid or missing session ID");return}let o=cu[n];try{await o.handleRequest(e,t);}catch{t.headersSent||t.status(500).send("Error processing session termination");}});var Wae=bP;var qae=Router();qae.get("/:id",Et(async(e,t)=>{let{id:n}=e.params;if(!n){t.status(400).json({error:"Missing ID"});return}let o=Do();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){_n.error({err:r,screenshotId:n},"Failed to proxy on-demand screenshot"),t.status(404).json({error:"Screenshot not found"});}}));var Kae=qae;var TP=Router();TP.get("/",Et(async(e,t)=>{let n=new Map;for(let i of await AF())n.set(i.configFilePath,i);let o=at();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);}));TP.get("/current",Et((e,t)=>{let n=at();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);}));TP.post("/set",Et(async(e,t)=>{let n;try{n=a2.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}_n.info("Setting local project");try{let o=await qt({configFilePath:n.configFilePath}),r=Do();if(!r)throw new Error("API client is not initialized.");await gy({project:o,apiClient:r});}catch(o){t.status(400).json({error:`Error setting project: ${o}`});return}t.sendStatus(204);}));var Yae=TP;var Jae=Router();Jae.get("/",Et((e,t)=>{let n=at(),o={ai:n.config.ai,browser:n.config.browser,displayRoot:n.config.displayRoot};t.status(200).json(o);}));var Xae=Jae;var zc=Router();zc.post("/",Et(async(e,t)=>{let n;try{n=Zq.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}try{let o=at(),r=await xE({project:o,input:n});ia({type:"test_editor:test_create",test_platform:"web"}),t.status(201).json(r);}catch(o){if(o instanceof vt){t.status(400).json({error:o.message});return}throw o}}));zc.get("/:testPath",Et(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=at(),r=await Xs(o),i;try{i=await fs(io__default.join(o.rootDir,n),_n,r),await(await Ti({logger:_n,orgId:ho(),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:_n,useSnapshotIdentityCache:o.config.fileFormat==="v2"}),t.status(200).json(i);}catch(s){t.status(400).send({error:s.message});return}(async()=>{try{await mI({relativeTestPath:n,stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps},schemaVersion:lt,momenticFiles:r,project:o});}catch(s){_n.error({err:s},"Failed to save migrated test to disk after initial fetch");}})();}));zc.get("/:testPath/metadata",Et(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=at(),r=io__default.join(o.rootDir,n);if(!ko__default.existsSync(r)){t.status(404).json({error:"Test file not found."});return}let i=ko__default.statSync(r),s=await Ua(_n),a={gitBranch:s.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:s.gitCommitSha??"unknown"};t.status(200).json(a);}));zc.patch("/:testPath/metadata",Et(async(e,t)=>{if(!e.params.testPath){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Qq.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let r={message:"ok",newRelativeTestPath:cA(e.params.testPath,n,at()).newRelativeTestPath};t.status(200).json(r);}));zc.patch("/:testPath",Et(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=Xq.parse(e.body);}catch(m){_n.warn({err:m},"Invalid save request"),t.status(400).json({error:`Invalid request body: ${m}`});return}_n.info({testPath:n},"Save received");let r=at(),i=await Xs(r),s;try{s=fl(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 ro({stepLists:o.stepLists,useSnapshotIdentityCache:a,cacheCreationParams:{orgId:ho(),testId:s.id,environment:s.envs?.find(m=>m.default)?.name}}),p=await Ti({logger:_n,orgId:ho(),project:r});a&&await p.saveSnapshotCacheEntries({logger:_n,entries:u}),await p.saveStepCacheEntries({logger:_n,entries:d}),yF({relativeTestPath:n,stepsToSave:l,moduleUpdates:c,schemaVersion:o.schemaVersion,momenticFiles:i,project:r}),t.status(201).json({message:"ok"});}));zc.patch("/:testPath/environments",Et(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=s2.parse(e.body);}catch(r){t.status(400).json({error:`Invalid request body: ${r}`});return}cA(n,{envs:o.defaultEnv?[{name:o.defaultEnv,default:true}]:[]},at()),t.status(201).json({message:"ok"});}));zc.patch("/:testPath/move",Et(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=i2.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${q(i)}`});return}let r=at();if(!ko__default.existsSync(io__default.join(r.rootDir,n))){t.status(404).json({error:"Test not found."});return}await EZ({relativeTestPath:n,targetFolderRelativePath:o.folderPath,project:r}),t.status(200).json({message:"ok"});}));zc.delete("/:testPath",Et((e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=at(),r=io__default.join(o.rootDir,n);if(!ko__default.existsSync(r)){t.status(404).json({error:"Test not found."});return}ko__default.unlinkSync(r),t.status(200).json({message:"ok"});}));zc.post("/:testPath/duplicate",Et(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=e2.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Zl(o.name);}catch(h){t.status(400).json({error:h.message});return}let r=at(),i=io__default.join(r.rootDir,n);if(!ko__default.existsSync(i)){t.status(404).json({error:"Test not found."});return}let s=await We(r),a;try{a=await fs(i,_n,s);}catch(h){t.status(400).send({error:h.message});return}let l=Cc({projectConfig:r.config,momenticFiles:s,entityType:"test"}),c=lo.parse({...a,name:o.name,id:l}),{stepsToSave:d}=await ro({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps},createNewCacheIds:true}),u=io__default.dirname(i),p=io__default.join(u,`${o.name}.test.yaml`);ka({test:{fileType:Fe.TEST,...c,...d},filePath:p,projectConfig:r.config,momenticFiles:s});let m={relativeFilePath:io__default.relative(r.rootDir,p)};ia({type:"test_editor:test_duplicated"}),t.status(201).json(m);}));var Qae=zc;var du="gpt-5.5-2026-04-23";var Zi={numScreenshots:10,numBrowserStates:2,tokensThreshold:25e4,targetTokens:2e5};function Zy(){return {openai:{reasoningEffort:"medium",reasoningSummary:"auto",textVerbosity:"low",store:false},azure:{reasoningEffort:"medium",reasoningSummary:"auto",textVerbosity:"low",store:false}}}function eS({stepNumber:e,maxTurns:t,messages:n}){let o=t-e;if(!(o>25))return o<=3?`Turn budget: only ${o} of ${t} turns remain before you are force-stopped. ${n.final}`:o<=8?`Turn budget: only ${o} of ${t} turns remain before you are force-stopped. ${n.urgent}`:`Turn budget: roughly ${o} of ${t} turns remain. ${n.winddown}`}var cJe="about:blank",dJe=[".webm",".mp4"];function UH(e){return e?ko__default.mkdtempSync(io__default.join(Ed.tmpdir(),"momentic-explore-video-")):void 0}async function tS(e){let{sessionManager:t,storage:n,logger:o,owner:r,signal:i,timelineLane:s}=e,a=UH(s),l=await t.startTestlessSession({logger:o,storage:n,baseUrl:cJe,runner:"explore",videoOutputDir:a}),c=l.controller.bindCancellation(i),d=async u=>{if(c(),!t.getSession(l.sessionId))return;!(await t.killSession(l.sessionId,`${r} browser session completed`)).killed&&t.getSession(l.sessionId)!==void 0&&u.warn({sessionId:l.sessionId,owner:r},"Explore agent did not clean up its browser session"),HH({logger:u,timelineLane:s,videoOutputDir:a,videoStartTimes:l.videoStartTimes,finishedAt:Date.now()});};return {context:{controller:l.controller,testContext:l.context,codeEvalTools:l.codeEvalTools,tempCaches:l.tempCaches,usageTracker:l.usageTracker,relativeTestPath:l.relativeTestPath,envName:l.envName,isRemoteBrowser:l.isRemoteBrowser,conversationTokenTarget:15e4,cleanupBrowserSession:d},isAlive:()=>t.getSession(l.sessionId)!==void 0}}function HH({logger:e,timelineLane:t,videoOutputDir:n,videoStartTimes:o,finishedAt:r}){if(!(!t||!n))try{for(let i of ko__default.readdirSync(n))dJe.includes(io__default.extname(i))&&t.attachVideo({sourcePath:io__default.join(n,i),startedAt:o?.get(i),finishedAt:r});}catch(i){e.warn({err:i,videoOutputDir:n},"Failed to attach explore browser videos to timeline");}}var ele=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 tle(e){return e.kind==="diff"?e.diffSummary:pt`
|
|
7580
|
+
`)}));}}),xae=Fo({schema:{name:lb,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(Iae)}},handle:async(e,t,n,o)=>{let{sessionId:r,step:i}=t,s=lu({response:n,sessionId:r,toolName:lb});if(!s)return;s.controller.setOpen();let a;try{a=await uP({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:Do()});}finally{await s.usageTracker.flush(e.logger);}n.addContentParts(a);}}),_ae=Fo({schema:{name:um,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(Iae),targetSection:cd.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=lu({response:n,sessionId:t.sessionId,toolName:um});if(!r)return;let i=await pP({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&&ia({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);}}),Pae=Fo({schema:{name:Sa,description:`${Yv} Use step ids from the active session: the Test Content section returned by ${sd}, or the inserted/deleted refs returned by ${um}. 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 ${M_/1e3} seconds, this tool responds early with the currently executing step while execution continues in the background; call ${yg} 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:gC,toStep:fC.optional(),targetSection:cd.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=lu({response:n,sessionId:t.sessionId,toolName:Sa});if(!r)return;r.controller.setOpen(),t.resetSession&&await sP({project:r.storage.getProject(),logger:e.logger,relativeTestPath:r.relativeTestPath,orgId:r.orgId,storage:r.storage,apiKey:xl(),baseUrl:Xi(),controller:r.controller,testContext:r.context,supportsFileOutput:e.supportsFileOutput,isRemoteBrowser:r.isRemoteBrowser});let i=Sie({runs:r.runStepRuns,run:async a=>{let l=Rae(o,e.logger,n,()=>{aa.touchSession(r.sessionId);},bie({runs:r.runStepRuns,stepRunnerId:a})),c=await mP({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:Do(),disableCache:t.disableCache});return ia({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 tH({runs:r.runStepRuns,stepRunnerId:i.stepRunnerId,activeRunCountAtStart:i.activeRunCountAtStart});nH({result:s,response:n,runStepToolName:Sa,statusToolName:yg});}}),Oae=Fo({schema:{name:yg,description:`Check ${Sa} executions for the active session. Responds with active runs, finished runs, and any newly finished results. Poll this after ${Sa} reports that execution is taking longer than ${M_/1e3} seconds. Prefer passing the stepRunnerId reported by ${Sa} to scope the response to that run; only omit it when you need to see every run for the session. Optionally pass timeoutSeconds (0-${eH}, 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 ${Sa}. Recommended for most polls.`),timeoutSeconds:z$1.number().min(0).max(eH).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=lu({response:n,sessionId:t.sessionId,toolName:yg});if(!r)return;let i=await tH({runs:r.runStepRuns,stepRunnerId:t.stepRunnerId,timeoutMs:t.timeoutSeconds*1e3});nH({result:i,response:n,runStepToolName:Sa,statusToolName:yg});}}),Mae=[UYe,DYe,FYe,BYe];var Nae=[bae,Tae,Aae,Eae,xae,Pae,Oae,_ae];async function GYe({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 Ti({logger:t,orgId:r,project:n}),d=await Ma({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 gP({project:e,storage:t,logger:n,relativeTestPath:o,saveChangesToDisk:r,mutableStepState:i,params:s}){let a=ho();Zl(s.name);let l=await t.scanEntities(),c;s.startIndex!==void 0&&o!==void 0&&(c=await GYe({testPath:o,logger:n,project:e,storage:t,orgId:a,mutableStepState:i}));let{stepsToExtract:d,startIndex:u,endIndex:p}=wie({moduleName:s.name,existingModuleNames:Object.values(l.modules).map(R=>R.name),...s,parameterNames:s.parameters,testPath:o,availableSteps:c?.availableSteps,containsNestedModuleStep:L4}),{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:A,testId:v}=c.cacheSaveContext,w=e.config.fileFormat==="v2",{cachesToSave:I,snapshotCachesToSave:_}=await ro({stepLists:S,useSnapshotIdentityCache:w,cacheCreationParams:{orgId:a,testId:v,environment:T}});return w&&await A.saveSnapshotCacheEntries({logger:n,entries:_}),await A.saveStepCacheEntries({logger:n,entries:I}),r&&await t.updateTestByPath({logger:n,relativeTestPath:o,stepLists:S,schemaVersion:lt}),{module:m}}var Lae=Fo({schema:{name:zV,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(wm),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=une({projectRoot:e.project.rootDir,filePath:r,pathLabel:"testPath"}),a=await gP({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(q(s));}}});var kae=Fo({schema:{name:KV,description:"List active local test quarantines in a quarantine-date range, ordered from newest to oldest. Each item includes the quarantine reason and the latest retained failed CLI run, including failure and heal details.",inputSchema:fJ.shape},handle:async(e,t,n)=>{try{let o=await e.apiClient.listQuarantinedTests(t);if(!e.supportsFileOutput){n.addPartFromText(JSON.stringify(o,null,2));return}let r=e.project.rootDir;Jr(r);let i=Xr({rootDir:r,entity:"quarantined-tests",ext:"json"});await writeFile(i,JSON.stringify(o,null,2),"utf8"),n.addContentParts($({section:"Quarantined tests",text:ar({filePath:i,title:`Quarantined tests (${o.quarantinedTests.length})`})}));}catch(o){n.addError(q(o));}}});var Jy=[...Mae,...dP,...Nae,Lae,dre,Sre,kae,vre,mre];var Dae=Jy.map(e=>e.tool),fP=new Map(Dae.map(e=>[e.schema.name,e]));async function Fae(e){let{project:t,applicationName:n,daemonPort:o,daemonToken:r,daemonSessionId:i,logger:s,cliVersion:a}=e,l=t.configFilePath;await aP(e);let{context:c}=lP({...e,logger:s.child({daemonSessionId:i}),applicationName:`${n}-daemon`,serverId:i});await mie({adapter:{getTool:d=>{let u=fP.get(d);if(!u)throw new Error(`Unknown web MCP tool '${d}'. Known tools: ${Array.from(fP.keys()).join(", ")}`);return {name:u.schema.name,execute:async({input:p,extra:m})=>await die({context:c,tool:u,input:p,extra:m})}}},sessionManager:aa,daemonPort:o,daemonToken:r,daemonId:i,cliVersion:a,workerType:"momentic-web-mcp",configPath:l,inactivityTimeoutMsOverride:IH(e)*2,onShutdown:()=>{Qd();}});}async function MH(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 rie({workerType:"momentic-web-mcp",configPath:p,apiKey:o,serverUrl:r,cliVersion:i,logger:n,buildDaemonArgs:({entryScript:m})=>WYe({entryScript:m,serverUrl:r,configPath:p,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u})})}async function Bae(e){let{logger:t,applicationName:n,cliVersion:o,serverUrl:r}=e;Xd(r),await MH(e);let{info:i,mcpLogger:s}=wH({logger:t,applicationName:`${n}-daemon-proxy`,cliVersion:o});return O_({context:{logger:s},info:i,tools:uie({tools:Dae,resolveDaemonStateForCall:()=>MH(e),logger:s})})}var zYe=30*6e4;async function NH({options:e,toolName:t,input:n,timeoutMs:o=zYe}){Xd(e.serverUrl);let r=fP.get(t);if(!r)throw new Error(`Unknown web MCP tool '${t}'. Known tools: ${Array.from(fP.keys()).join(", ")}`);let i=r.schema.inputSchema.parse(n),s=await MH(e);return QU({state:s,toolName:t,input:i,timeoutMs:o})}function WYe({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 LH=async(e,t)=>{try{let{killed:n,failed:o}=await aa.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 kH(e){let{daemon:t,logger:n}=e,o=oie.safeParse(process.env);if(t&&o.success&&o.data[__]==="momentic-web-mcp")return Fae({...e,daemonPort:o.data[I_],daemonToken:o.data[x_],daemonSessionId:o.data[P_]});if(Qu(n,true),t)return await Bae(e);await aP(e);let{context:r,info:i}=lP(e);return O_({context:r,info:i,tools:Jy,shutdownHandlers:[LH,Qd,async()=>{await nP();}]})}var _E="3.25.1",_n=rf({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:_E});(async()=>{try{let e=await Ua(_n);e.gitBranchName&&_n.addBinding("branch",e.gitBranchName);}catch{}})();var Kp=Router();async function SP(e){return (await zf(e,_n)).map(o=>{let r=e.modules[o.moduleId];if(!r){C.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)}Kp.get("/",Et(async(e,t)=>{let n=at(),o=await Xs(n),r=await SP(o);t.status(200).json(r);}));Kp.post("/",Et(async(e,t)=>{let n;try{n=n2.parse(e.body);}catch(l){t.status(400).json({error:`Invalid request body: ${l}`});return}try{Zl(n.name);}catch(l){t.status(400).json({error:`Invalid module name: ${l}`});return}let o=at(),r=await We(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=io__default.join(o.rootDir,n.folderPath??io__default.dirname(n.testFilePath));if(!ko__default.existsSync(s)||!ko__default.statSync(s).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let a=await cI({...n,folder:s,project:o,momenticFiles:r});t.status(201).json(a);}));Kp.get("/:moduleId/tests",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=at(),o=await We(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))fZ(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);}));Kp.get("/:moduleId",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=await Xs(at()),o=n.modules[e.params.moduleId];if(!o){t.status(404).json({error:"Module not found."});return}try{let r=await wc({modHandle:o,momenticFiles:n,logger:C});t.json(r);}catch(r){t.status(400).json({err:r});}}));Kp.post("/:moduleId/duplicate",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=t2.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Zl(n.name);}catch(h){t.status(400).json({error:h.message});return}let o=at(),r=await We(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=io__default.join(o.rootDir,io__default.dirname(i.relativePath));if(!ko__default.existsSync(a)||!ko__default.statSync(a).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let l=Fn(n.name),c=io__default.join(a,`${l}.module.yaml`),d=Cc({projectConfig:o.config,momenticFiles:r,entityType:"module"}),{stepsToSave:u}=await ro({stepLists:{steps:s.steps},createNewCacheIds:true}),p={fileType:Fe.MODULE,schemaVersion:lt,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};La({module:p,filePath:c,projectConfig:o.config,momenticFiles:r});let m={relativeFilePath:io__default.relative(o.rootDir,c)};t.status(201).json(m);}));Kp.patch("/:moduleId/move",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=r2.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${q(i)}`});return}let o=at();if(!(await Xs(o)).modules[e.params.moduleId]){t.status(404).json({error:"Module not found."});return}await TZ({moduleId:e.params.moduleId,targetFolderRelativePath:n.folderPath,project:o}),t.status(200).json({message:"ok"});}));Kp.patch("/:moduleId/metadata",Et(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=o2.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let o=at(),r=await Xs(o);await AZ({moduleId:e.params.moduleId,content:n,momenticFiles:r,logger:C,project:o}),t.status(201).json({message:"ok"});}));var Uae=Kp;var PE=Router();PE.get("/",Et(async(e,t)=>{let n=at(),o=await We(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 SP(o),l={labels:i,tests:s,modules:a};t.status(200).json(l);}));PE.get("/folders",Et(async(e,t)=>{let n=at(),o=await cZ(n);t.status(200).json(o);}));PE.get("/labels",Et(async(e,t)=>{let n=at(),o=await We(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);}));PE.post("/in-folder",Et(async(e,t)=>{let n=Jq.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=at(),[i,s]=await Promise.all([lZ(r,o),Xs(r)]),a=Object.values(i.tests),l=await SP(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 Hae=PE;var DH=Router();DH.get("/",Et((e,t)=>{let n=gI(at(),_n);t.status(200).json(n);}));DH.get("/names",Et((e,t)=>{let o=at().config.environments?.map(r=>r.name)??[];t.status(200).json(o);}));var jae=DH;var Gae=Router();Gae.get("/",Et((e,t)=>{let n={userId:Oc(),orgId:ho(),email:hy(),name:m7(),pylonEmailHash:h7(),cliVersion:_E};t.status(200).json(n);}));var $ae=Gae;var FH="mcp-session-id",Vae="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",bP=Router();function tJe(){let e=process.env[Vae];if(!e)return Rh*60*1e3;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<1?(_n.warn({envVar:Vae,rawValue:e,fallback:Rh},"Invalid MCP session idle timeout env var; falling back to default"),Rh*60*1e3):t*60*1e3}function nJe(e){let{headfulDefault:t,supportsFileOutput:n}={},o={serverId:randomUUID(),applicationName:"momentic-mcp-desktop-server",cliVersion:_E},r=at(),i=xl(),s=Xi(),a=_n.child({orgId:ho(),userId:Oc(),...o}),l=new xt({baseUrl:s,apiKey:i,logger:a,mode:"interactive",runner:"mcp"}),c=eT(process.env.MOMENTIC_HEADFUL_BROWSER),d=new qo(r.config.ai?.agentConfig,{baseUrl:s,apiKey:i,logger:a,mode:"interactive",runner:"mcp"}),u=ho(),p=new la(l,u,r);return {context:{project:r,orgId:u,logger:a,generator:d,apiClient:l,storage:p,serverId:o.serverId,extractBaseDir:Nl(r.rootDir),saveChangesToDisk:true,supportsFileOutput:n??true,knowledgeRetrievalResults:an,knowledgeCitations:[],sessionIdleTimeoutMs:tJe(),headfulDefault:t??c??true,categoryDefinitions:r.config.ai?.classification?.categories??is},info:o}}var cu={};bP.post("/",async(e,t)=>{let n=String(e.headers[FH]??"");try{if(n&&cu[n]){await cu[n].handleRequest(e,t,e.body);return}if(!n&&isInitializeRequest(e.body)){let{context:o,info:r}=nJe(),i=ZU(o,r,Jy),s=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableDnsRebindingProtection:!1,onsessioninitialized:a=>{cu[a]=s;}});s.onclose=()=>{let a=s.sessionId;a&&cu[a]&&delete cu[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});}});bP.get("/",async(e,t)=>{let n=String(e.headers[FH]??"");if(!n||!cu[n]){t.status(400).send("Invalid or missing session ID");return}await cu[n].handleRequest(e,t);});bP.delete("/",async(e,t)=>{let n=String(e.headers[FH]??"");if(!n||!cu[n]){t.status(400).send("Invalid or missing session ID");return}let o=cu[n];try{await o.handleRequest(e,t);}catch{t.headersSent||t.status(500).send("Error processing session termination");}});var Wae=bP;var qae=Router();qae.get("/:id",Et(async(e,t)=>{let{id:n}=e.params;if(!n){t.status(400).json({error:"Missing ID"});return}let o=Do();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){_n.error({err:r,screenshotId:n},"Failed to proxy on-demand screenshot"),t.status(404).json({error:"Screenshot not found"});}}));var Kae=qae;var TP=Router();TP.get("/",Et(async(e,t)=>{let n=new Map;for(let i of await AF())n.set(i.configFilePath,i);let o=at();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);}));TP.get("/current",Et((e,t)=>{let n=at();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);}));TP.post("/set",Et(async(e,t)=>{let n;try{n=a2.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}_n.info("Setting local project");try{let o=await qt({configFilePath:n.configFilePath}),r=Do();if(!r)throw new Error("API client is not initialized.");await gy({project:o,apiClient:r});}catch(o){t.status(400).json({error:`Error setting project: ${o}`});return}t.sendStatus(204);}));var Yae=TP;var Jae=Router();Jae.get("/",Et((e,t)=>{let n=at(),o={ai:n.config.ai,browser:n.config.browser,displayRoot:n.config.displayRoot};t.status(200).json(o);}));var Xae=Jae;var zc=Router();zc.post("/",Et(async(e,t)=>{let n;try{n=Zq.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}try{let o=at(),r=await xE({project:o,input:n});ia({type:"test_editor:test_create",test_platform:"web"}),t.status(201).json(r);}catch(o){if(o instanceof vt){t.status(400).json({error:o.message});return}throw o}}));zc.get("/:testPath",Et(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=at(),r=await Xs(o),i;try{i=await fs(io__default.join(o.rootDir,n),_n,r),await(await Ti({logger:_n,orgId:ho(),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:_n,useSnapshotIdentityCache:o.config.fileFormat==="v2"}),t.status(200).json(i);}catch(s){t.status(400).send({error:s.message});return}(async()=>{try{await mI({relativeTestPath:n,stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps},schemaVersion:lt,momenticFiles:r,project:o});}catch(s){_n.error({err:s},"Failed to save migrated test to disk after initial fetch");}})();}));zc.get("/:testPath/metadata",Et(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=at(),r=io__default.join(o.rootDir,n);if(!ko__default.existsSync(r)){t.status(404).json({error:"Test file not found."});return}let i=ko__default.statSync(r),s=await Ua(_n),a={gitBranch:s.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:s.gitCommitSha??"unknown"};t.status(200).json(a);}));zc.patch("/:testPath/metadata",Et(async(e,t)=>{if(!e.params.testPath){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Qq.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let r={message:"ok",newRelativeTestPath:cA(e.params.testPath,n,at()).newRelativeTestPath};t.status(200).json(r);}));zc.patch("/:testPath",Et(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=Xq.parse(e.body);}catch(m){_n.warn({err:m},"Invalid save request"),t.status(400).json({error:`Invalid request body: ${m}`});return}_n.info({testPath:n},"Save received");let r=at(),i=await Xs(r),s;try{s=fl(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 ro({stepLists:o.stepLists,useSnapshotIdentityCache:a,cacheCreationParams:{orgId:ho(),testId:s.id,environment:s.envs?.find(m=>m.default)?.name}}),p=await Ti({logger:_n,orgId:ho(),project:r});a&&await p.saveSnapshotCacheEntries({logger:_n,entries:u}),await p.saveStepCacheEntries({logger:_n,entries:d}),yF({relativeTestPath:n,stepsToSave:l,moduleUpdates:c,schemaVersion:o.schemaVersion,momenticFiles:i,project:r}),t.status(201).json({message:"ok"});}));zc.patch("/:testPath/environments",Et(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=s2.parse(e.body);}catch(r){t.status(400).json({error:`Invalid request body: ${r}`});return}cA(n,{envs:o.defaultEnv?[{name:o.defaultEnv,default:true}]:[]},at()),t.status(201).json({message:"ok"});}));zc.patch("/:testPath/move",Et(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=i2.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${q(i)}`});return}let r=at();if(!ko__default.existsSync(io__default.join(r.rootDir,n))){t.status(404).json({error:"Test not found."});return}await EZ({relativeTestPath:n,targetFolderRelativePath:o.folderPath,project:r}),t.status(200).json({message:"ok"});}));zc.delete("/:testPath",Et((e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=at(),r=io__default.join(o.rootDir,n);if(!ko__default.existsSync(r)){t.status(404).json({error:"Test not found."});return}ko__default.unlinkSync(r),t.status(200).json({message:"ok"});}));zc.post("/:testPath/duplicate",Et(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=e2.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Zl(o.name);}catch(h){t.status(400).json({error:h.message});return}let r=at(),i=io__default.join(r.rootDir,n);if(!ko__default.existsSync(i)){t.status(404).json({error:"Test not found."});return}let s=await We(r),a;try{a=await fs(i,_n,s);}catch(h){t.status(400).send({error:h.message});return}let l=Cc({projectConfig:r.config,momenticFiles:s,entityType:"test"}),c=lo.parse({...a,name:o.name,id:l}),{stepsToSave:d}=await ro({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps},createNewCacheIds:true}),u=io__default.dirname(i),p=io__default.join(u,`${o.name}.test.yaml`);ka({test:{fileType:Fe.TEST,...c,...d},filePath:p,projectConfig:r.config,momenticFiles:s});let m={relativeFilePath:io__default.relative(r.rootDir,p)};ia({type:"test_editor:test_duplicated"}),t.status(201).json(m);}));var Qae=zc;var du="gpt-5.5-2026-04-23";var Zi={numScreenshots:10,numBrowserStates:2,tokensThreshold:25e4,targetTokens:2e5};function Zy(){return {openai:{reasoningEffort:"medium",reasoningSummary:"auto",textVerbosity:"low",store:false},azure:{reasoningEffort:"medium",reasoningSummary:"auto",textVerbosity:"low",store:false}}}function eS({stepNumber:e,maxTurns:t,messages:n}){let o=t-e;if(!(o>25))return o<=3?`Turn budget: only ${o} of ${t} turns remain before you are force-stopped. ${n.final}`:o<=8?`Turn budget: only ${o} of ${t} turns remain before you are force-stopped. ${n.urgent}`:`Turn budget: roughly ${o} of ${t} turns remain. ${n.winddown}`}var cJe="about:blank",dJe=[".webm",".mp4"];function UH(e){return e?ko__default.mkdtempSync(io__default.join(Ed.tmpdir(),"momentic-explore-video-")):void 0}async function tS(e){let{sessionManager:t,storage:n,logger:o,owner:r,signal:i,timelineLane:s}=e,a=UH(s),l=await t.startTestlessSession({logger:o,storage:n,baseUrl:cJe,runner:"explore",videoOutputDir:a}),c=l.controller.bindCancellation(i),d=async u=>{if(c(),!t.getSession(l.sessionId))return;!(await t.killSession(l.sessionId,`${r} browser session completed`)).killed&&t.getSession(l.sessionId)!==void 0&&u.warn({sessionId:l.sessionId,owner:r},"Explore agent did not clean up its browser session"),HH({logger:u,timelineLane:s,videoOutputDir:a,videoStartTimes:l.videoStartTimes,finishedAt:Date.now()});};return {context:{controller:l.controller,testContext:l.context,codeEvalTools:l.codeEvalTools,tempCaches:l.tempCaches,usageTracker:l.usageTracker,relativeTestPath:l.relativeTestPath,envName:l.envName,isRemoteBrowser:l.isRemoteBrowser,conversationTokenTarget:15e4,cleanupBrowserSession:d},isAlive:()=>t.getSession(l.sessionId)!==void 0}}function HH({logger:e,timelineLane:t,videoOutputDir:n,videoStartTimes:o,finishedAt:r}){if(!(!t||!n))try{for(let i of ko__default.readdirSync(n))dJe.includes(io__default.extname(i))&&t.attachVideo({sourcePath:io__default.join(n,i),startedAt:o?.get(i),finishedAt:r});}catch(i){e.warn({err:i,videoOutputDir:n},"Failed to attach explore browser videos to timeline");}}var ele=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 tle(e){return e.kind==="diff"?e.diffSummary:pt`
|
|
7581
7581
|
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.
|
|
7582
7582
|
|
|
7583
7583
|
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 ${hm} as described in your instructions, and explore the rest yourself. Child findings are merged into your recorded plan automatically.
|
|
@@ -8230,7 +8230,7 @@ ${FP(r)}
|
|
|
8230
8230
|
## Note
|
|
8231
8231
|
|
|
8232
8232
|
${i}`}var c4e=15e4,d4e=`Author a brand-new Momentic test from scratch by delegating to a test-builder sub-agent. The orchestrator allocates an in-memory draft test and a fresh browser session, then hands them to the sub-agent which iteratively authors steps against the live browser. Nothing is written to disk until you call ${jo}. ONLY creates new tests \u2014 to revise an existing on-disk test or to resume work on a draft (created or edited), use ${ki}. After this tool returns, review the draft and decide whether to retry, ${jo}, or ${wr}. To start a draft over from scratch, ${wr} first, then call this tool again. Call this in parallel for each mode='create' test plan \u2014 one call per plan.`,u4e=z$1.object({name:z$1.string().describe("Name of the new test to create. Must satisfy Momentic entity naming rules and not collide with an existing test."),description:z$1.string().optional().describe("Short human-readable description of the test."),baseUrl:z$1.string().optional().describe(`Base URL for the test. Prefer environment over this when possible. You can list available environments with the ${el} tool.`),environment:z$1.string().optional().describe(`Project environment name to bind the test to. Provide this or 'baseUrl', with a preference for environment when possible. You can list available environments with the ${el} tool.`),pathSegments:z$1.array(z$1.string()).optional().describe("Optional folder path (relative to the project root) where the test file should be created, e.g. ['billing', 'subscriptions']. Defaults to the project root."),instructions:z$1.string().describe("Detailed instructions for the test-builder sub-agent: the flow to test, preconditions, expected behaviour, and any context the sub-agent needs.")});function qle({context:e,output:t}){let n=0,o=tool({description:d4e,inputSchema:u4e,execute:async r=>{let i=++n,s=e.logger.child({agentName:"test-builder",buildTestCallIdx:String(i),testName:r.name});if(!r.baseUrl&&!r.environment)throw new vt("Either 'baseUrl' or 'environment' must be provided to build a new test.");await e.cleanupBrowserSession(s);let a=await e.storage.createTest({name:r.name,description:r.description,baseUrl:r.baseUrl,environment:r.environment,pathSegments:r.pathSegments});return rj({context:e,output:t,subLogger:s,myIdx:i,testId:a.id,relativeFilePath:a.relativeFilePath,testName:r.name,testDescription:r.description,instructions:r.instructions,mode:"create"})}});return {name:Ds,tool:o}}var p4e=`Hand a Momentic test to a test-builder sub-agent to revise its steps. Use this for both editing an existing on-disk test (e.g. to cover a changed user journey) and for resuming work on an in-memory draft. The orchestrator looks up the test by selector and the sub-agent picks up from its current steps; the on-disk file is NOT touched until you call ${jo}. The sub-agent sees the existing steps as its starting point and is expected to keep what still works. To author a test from zero, use ${Ds} instead. After this tool returns, decide whether to ${jo} the draft (writes the new steps; for edited drafts this overwrites the existing file) or ${wr} it (for edited drafts the original on-disk test is untouched).`,m4e=z$1.object({testId:z$1.string().min(1).describe("Stable id of the test to edit. Targets either a pending draft test or an on-disk test \u2014 if no draft exists for the id, the on-disk test is cloned into a new draft first. For mode='edit' test plans, pass the plan's existingTestId here."),instructions:z$1.string().describe("Detailed instructions for the test-builder sub-agent: which existing steps to keep, what to change, what to add or remove, and what the final end-to-end flow should look like. The sub-agent will see the current steps when it starts.")});function Kle({context:e,output:t}){let n=0,o=tool({description:p4e,inputSchema:m4e,execute:async r=>{let i=++n,s=e.logger.child({agentName:"test-builder",editTestCallIdx:String(i)}),a=await e.storage.getTest({selector:{id:r.testId},logger:s});return await e.cleanupBrowserSession(s),rj({context:e,output:t,subLogger:s.child({testName:a.test.name}),myIdx:i,testId:a.test.id,relativeFilePath:a.entity.relativePath,testName:a.test.name,testDescription:a.test.description,instructions:r.instructions,mode:"edit"})}});return {name:ki,tool:o}}async function rj({context:e,output:t,subLogger:n,myIdx:o,testId:r,relativeFilePath:i,testName:s,testDescription:a,instructions:l,mode:c}){let d=c==="edit"?"Editor":"Builder",u=e.timelineRecorder?.registerSubagent({kind:"builder",label:`${d} #${o} (${s})`,testId:r}),p=UH(u),m=await e.sessionManager.startSession({logger:n,storage:e.storage,testId:r,runner:"explore",hydrateStepIdentityOnCreate:true,videoOutputDir:p}),h={...e,...m,logger:n,apiKey:xl(),baseUrl:Xi(),extractBaseDir:Nl(e.project.rootDir),testContext:m.context,conversationTokenTarget:c4e,reportedBugs:{},bugRecordings:{}},g;try{let f=await jle({client:e.apiClient,instructions:l,logger:n});f.hits.length>0&&n.info({hits:f.hits.length,agentRuleHits:f.agentRuleHits.length,generalHits:f.generalHits.length,truncated:f.truncated},"Loaded knowledge base entries for test builder");let y=e.buildTimeoutMs!==void 0?AbortSignal.timeout(e.buildTimeoutMs):void 0,S=cle([e.signal,y]);S&&(g=m.controller.bindCancellation(S));let T=Jn({...Vle({instructions:l,context:h,mode:c,testName:s,testDescription:a,testBaseUrl:m.baseUrl,knowledgeBaseSection:f.knowledgeBaseSection}),abortSignal:S}),A=ps({usage:T.totalUsage,promptType:"test-builder",logger:n}),v=e.compactPanes??!1,w=t?.pane(`${d}#${o} (test=${s})`,{commitOnClose:!1,quiet:v,parentLabel:v?e.paneLabel:void 0,retainOnClose:v,sortKey:o,verboseWhileActive:!0});try{w&&await Cs({streamResult:T,pane:w,timelineLane:u});let I=await T.text;return A({message:"Test builder agent completed",attributes:{buildTestCallIdx:o,testId:r,testName:s,mode:c}}),w&&w.close("done"),Q($({text:zle({testId:r,testName:s,testPath:i,summary:I,bugs:Object.values(h.reportedBugs),note:`Draft is held in memory. Call ${jo} or ${wr} for this testId before submitting your build summary. To resume work on this draft, call ${ki} with this testId. The builder's bug reports are already folded into your bug ledger \u2014 do not re-report them; just check whether any duplicate a bug already reported under a different name, and retract duplicates before continuing.`}),section:"Build result"}))}catch(I){w?.close("failed");let _=e.signal?.aborted??!1;if((y?.aborted??!1)&&!_)return n.warn({testId:r,buildTimeoutMs:e.buildTimeoutMs},"Test builder hit its time budget; preserving draft and yielding"),Q($({text:JSON.stringify({testId:r,testPath:i,error:`Test builder ran out of time before finishing. Its in-memory draft is preserved. Decide whether to retry, ${jo}, or ${wr}.`},null,2),section:"Build result"}));throw I}}finally{g?.();for(let y of Object.values(h.reportedBugs))e.reportedBugs[y.name]=y;(await e.sessionManager.killSession(m.sessionId,"build test sub-agent completed")).killed||n.warn({sessionId:m.sessionId,testId:r},"Build test sub-agent did not clean up its browser session"),HH({logger:n,timelineLane:u,videoOutputDir:p,videoStartTimes:m.videoStartTimes,finishedAt:Date.now()}),u?.close();}}var g4e=`Stage an existing on-disk Momentic test for deletion. Use this when a user journey has been removed and the test that covered it is now obsolete \u2014 a test that exercises a flow the product no longer has is a false signal. Like ${ki}, this is a pending change: the file is NOT removed from disk until you call ${jo}, and you can undo it beforehand with ${wr}. Only delete a test when you are confident the journey it covers is genuinely gone \u2014 to revise a test whose journey merely changed, use ${ki} instead.`,f4e=z$1.object({testId:z$1.string().min(1).describe("Stable id of the on-disk test to delete.")});function Jle(e){let t=tool({description:g4e,inputSchema:f4e,execute:async n=>{try{let{entity:o}=await e.storage.deleteTest({id:n.testId});return e.logger.info({testId:o.id,relativeFilePath:o.relativePath},"Explorer staged test deletion"),Q($({section:"Deletion staged",text:`Test "${o.name}" (testId=${o.id}) is staged for deletion. Call ${jo} with this testId to remove it from disk, or ${wr} to keep it.`}))}catch(o){return e.logger.warn({err:o,input:n},"delete_test failed"),Q($({section:"Error",text:`Delete failed: ${q(o)}`}))}},toModelOutput:({output:n})=>n});return {name:pb,tool:t}}var y4e=Ble.extend({testId:z$1.string().min(1).describe("Stable id of the pending draft test to approve."),moduleIds:z$1.array(z$1.string().min(1)).optional().describe("Stable ids of any pending draft modules referenced by the approved test.")}),S4e=z$1.object({testIds:z$1.array(z$1.string().min(1)).min(1).describe("Stable ids of pending draft tests to reject."),moduleIds:z$1.array(z$1.string().min(1)).optional().describe("Stable ids of pending draft modules to reject.")});function Xle(e){let t=tool({description:`List every draft test and module currently held in memory by ${Ds}. Each draft reports a "kind" of "create" or "update". Use this before deciding what to accept or reject, and again before completing the build to confirm nothing is left pending.`,inputSchema:z$1.object({}),execute:async()=>{let n=(await e.storage.listDraftTests(e.logger)).map(r=>({testId:r.test.id,name:r.test.name,relativeFilePath:r.entity.relativePath,kind:r.kind,stepCount:r.test.steps?.length??0})),o=(await e.storage.listDraftModules(e.logger)).map(r=>({moduleId:r.module.moduleId,name:r.module.name,relativeFilePath:r.entity.relativePath,kind:r.kind,stepCount:r.module.steps?.length??0}));return Q($({section:"Pending changes",text:JSON.stringify({tests:n,modules:o},null,2)}))},toModelOutput:({output:n})=>n});return {name:mb,tool:t}}function Qle(e){let t=tool({description:"Approve one test plan by persisting its draft test by id, plus any draft modules it references, and recording the reviewed outcome. Include the plan name, test id, summary, and any notes in this call. The whole batch is validated up front \u2014 accepting a test whose module references aren't included in the same call (and aren't already on disk) is rejected. If any write fails midway the partial write is rolled back and every targeted draft stays pending.",inputSchema:y4e,execute:async n=>{if(!e.explorerResult.testPlans.some(r=>r.name===n.testPlanName))return Q($({section:"Accept rejected",text:`No explorer test plan named "${n.testPlanName}".`}));try{let r=await e.storage.acceptDrafts(e.logger,{testIds:[n.testId],moduleIds:n.moduleIds}),i=r.acceptedTests.find(s=>s.testId===n.testId);return i?(e.logger.info({tests:r.acceptedTests.length,modules:r.acceptedModules.length},"Explorer accepted pending changes"),e.buildResults[n.testPlanName]={testPlanName:n.testPlanName,status:"succeeded",testPath:i.relativeFilePath,summary:n.summary,notes:n.notes},Q($({section:"Accept result",text:JSON.stringify(r,null,2)}))):Q($({section:"Accept rejected",text:`No pending draft test was accepted for testId "${n.testId}". Approve a plan by passing the draft test id directly.`}))}catch(r){return e.logger.warn({err:r,input:n},"accept_pending_changes failed"),Q($({section:"Error",text:`Accept failed: ${q(r)}`}))}},toModelOutput:({output:n})=>n});return {name:jo,tool:t}}function Zle(e){let t=tool({description:"Reject listed draft test ids and module ids, discarding the drafts without writing to disk. This only resolves pending drafts; it does NOT mark any test plan blocked. If rejecting a draft means a plan cannot be completed, call the blocker-reporting tool separately with the concrete blocker reason and evidence. Rejecting a module that is still referenced by a pending test (and that test isn't also being rejected) is refused so the in-memory state stays consistent.",inputSchema:S4e,execute:async n=>{try{let o=await e.storage.rejectDrafts(e.logger,{testIds:n.testIds,moduleIds:n.moduleIds});return e.logger.info({tests:o.rejectedTests.length,modules:o.rejectedModules.length},"Explorer rejected pending changes"),Q($({section:"Reject result",text:JSON.stringify(o,null,2)}))}catch(o){return e.logger.warn({err:o,input:n},"reject_pending_changes failed"),Q($({section:"Error",text:`Reject failed: ${q(o)}`}))}},toModelOutput:({output:n})=>n});return {name:wr,tool:t}}var b4e=[wP,_P,PP,Jp,lS];function ece(e,t){let n={},o=i=>{DP({tools:n,entry:i,logger:e.logger,logPrefix:"Orchestrator ",completionType:"explore-orchestrator",spanPrefix:"orchestrator"});},r=t?.noCode??false;for(let i of [...r?[]:uh,...b4e,...aS,...RP])o(i(e));for(let i of kP)o(i(e));o(qle({context:e,output:t?.output})),o(Kle({context:e,output:t?.output})),o(Jle(e)),o(Xle(e)),o(Qle(e)),o(Zle(e));for(let i of Ule)o(i(e));return n}var tce=200,C4e={winddown:`Begin winding down: finish active builder work, approve viable drafts, reject abandoned drafts, report blockers for plans that cannot be completed, and call ${Fs} once every plan is approved or blocked.`,urgent:`Do not delegate new work. Resolve pending drafts, report blockers for plans that cannot be completed, and call ${Fs} while enough turns remain to correct any rejected completion attempt.`,final:`Do not start more sub-agents. Resolve pending drafts, report any remaining blockers, and call ${Fs} immediately.`},R4e=[{keepLastMessages:8,tools:[fn,So]},{keepLastMessages:5,tools:[bn]}];async function sj(e){let t=e.logger.child({agentName:"explore-orchestrator",agentInvocationId:e.sessionId}),n=e.timelineRecorder?.registerRoot({kind:"orchestrator",label:"Build orchestrator"}),{config:o,context:r,cleanup:i}=await I4e({...e,logger:t,timelineLane:n});try{let s=Date.now();t.info("Orchestrator agent started");let a=Jn(o),l=ps({usage:a.totalUsage,promptType:"explore-orchestrator",logger:t}),c=e.output.pane(r.paneLabel??"Explorer",{commitOnClose:!1});try{await Cs({streamResult:a,pane:c,timelineLane:n}),await a.text,l({message:"Orchestrator agent stream completed",attributes:{durationMs:Date.now()-s}}),c.close("done");}catch(u){throw c.close("failed"),u}finally{e.output.finalize();}if(!r.buildComplete||!r.finalResult)throw new Error(`Orchestrator finished without calling ${Fs}`);let d=r.finalResult;return t.info({builtTests:d.buildSummary?.builtTests.length,duration:Date.now()-s},"Orchestrator agent completed"),{result:d,bugs:Object.values(r.reportedBugs),writtenPaths:r.storage.listWrittenFilePaths()}}catch(s){return e.signal?.aborted?t.warn({err:s},"Orchestrator agent aborted; returning partial result"):t.error({err:s},"Orchestrator agent failed; returning partial result"),{result:r.finalResult??w4e(r),bugs:Object.values(r.reportedBugs),writtenPaths:r.storage.listWrittenFilePaths(),failure:{reason:q(s),cancelled:e.signal?.aborted??false}}}finally{await i(t),n?.close();}}function w4e(e){let t=Object.values(e.buildResults);return t.length===0?e.explorerResult:{...e.explorerResult,buildSummary:{status:EP(t),builtTests:t}}}async function I4e(e){let{sessionId:t,logger:n,timelineLane:o}=e,r=await j0.mkdtemp(io__default.join(Ed.tmpdir(),`momentic-orchestrator-${t}-`)),{sessionManager:i}=e,s,a,l=async c=>{let d=s;d&&(s=void 0,a=void 0,await d(c));};try{let c=Do();if(!c)throw new Error("API client is not initialized; cannot construct orchestrator storage.");let d=new _h(c,e.orgId,e.project),u=await tS({sessionManager:i,storage:d,logger:n,owner:"orchestrator",signal:e.signal,timelineLane:o}),p={...e,...u.context,apiClient:c,serverId:t,sessionId:t,spoolDir:r,storage:d,saveChangesToDisk:!0,supportsFileOutput:!1,sessionManager:i,explorerResult:e.explorerResult,repoRoot:e.repoRoot,reportedBugs:{},bugRecordings:{},buildResults:{},buildComplete:!1,compactPanes:!0,paneLabel:"Explorer"},m=y=>{Object.assign(p,y.context),s=y.context.cleanupBrowserSession,a=y.isAlive;};m(u);let h=async y=>{if(s&&a?.())return;s&&(y.warn("Orchestrator browse session was closed unexpectedly; re-provisioning"),s=void 0,a=void 0);let S=await tS({sessionManager:i,storage:d,logger:y,owner:"orchestrator",signal:e.signal,timelineLane:o});m(S);},g=Dle(e.explorerResult);return {config:x4e({context:p,options:{customPrompt:e.customPrompt,knowledgeBaseSection:e.knowledgeBaseSection,output:e.output,noCode:e.noCode},explorerResultText:g,ensureBrowser:h,signal:e.signal}),context:p,cleanup:async y=>{await l(y),await oS(r,y);}}}catch(c){throw await l(n),await oS(r,n),c}}function x4e({context:e,options:t,explorerResultText:n,ensureBrowser:o,signal:r}){let{logger:i}=e,{customPrompt:s,knowledgeBaseSection:a,noCode:l}=t,c=ece(e,t),d={logger:i,streamType:"explore-orchestrator",sessionId:e.sessionId,agentInvocationId:e.serverId},u=e.generator.getOpenAIModelFactory({...d,useOpenAIResponsesWebSocket:true}),p=e.generator.getAzureOpenAIModelFactory(d),m=async g=>{await o(i);let f=ir({messages:g.messages,phase1:{toolResultPruningRules:R4e,numScreenshots:Zi.numScreenshots,numBrowserStates:Zi.numBrowserStates,browserStateMarkers:[ws]},phase2:{tokensThreshold:Zi.tokensThreshold,targetTokens:Zi.targetTokens},logger:i}),y=eS({stepNumber:g.stepNumber,maxTurns:tce,messages:C4e});return y&&f.push({role:"user",content:y}),{...g,messages:f}},h=[{role:"user",content:n}];return {providerFallback:{scopeKey:`orchestrator:${e.sessionId}`,logger:i,providers:[{id:"openai",model:u(du)},{id:"azure",model:p(du)}]},stopWhen:[stepCountIs(tce),_4e(e)],toolChoice:"required",maxRetries:4,abortSignal:r,system:kle({customPrompt:s,knowledgeBaseSection:a,noCode:l}),providerOptions:Zy(),tools:c,messages:h,prepareStep:m,prompt:void 0,onFinish:async({finishReason:g,usage:f})=>{i.info({finishReason:g,usage:f,sessionId:e.sessionId},"Orchestrator turn finished");}}}function _4e(e){return ({steps:t})=>{let n=t[t.length-1];if(!n)return false;let r=n.toolResults.map(s=>s.toolName).includes(Fs),i=e.buildComplete;return r&&i}}async function aj(e){let t=e.seedMode?await L4e(e):await N4e(e);return await k4e(e,t)}async function N4e(e){let{gitMetadata:t,apiClient:n,baseSha:o,headSha:r}=e,i=await qH(process.cwd()),s=await B4e({gitMetadata:t,apiClient:n,baseShaOverride:o,headShaOverride:r}),a=await Ple({cwd:i,baseSha:s.baseSha,headSha:s.headSha}),l=Ole(a),c=j4e({manifest:a,gitMetadata:t,buildEnabled:e.buildEnabled,cliVersion:e.cliVersion});return {repoRoot:i,baseSha:s.baseSha,headSha:s.headSha,seed:{kind:"diff",diffSummary:l},banner:c,manifest:a}}async function L4e(e){let t=await qH(process.cwd()),n=e.headSha??e.gitMetadata.gitCommitSha??await Ba("HEAD");if(!n)throw new vt("Failed to resolve the current commit for seed mode. Please pass --head with an explicit SHA.");let o=e.baseSha??n,r=H4e({gitMetadata:e.gitMetadata,buildEnabled:e.buildEnabled,cliVersion:e.cliVersion});return {repoRoot:t,baseSha:o,headSha:n,seed:{kind:"seed"},banner:r,paneLabel:"Explorer"}}async function k4e(e,t){let n=Date.now(),o=e.gitMetadata.githubRepository??e.gitMetadata.gitlabProjectPath??"(local)";e.logger.info({event:"explore_run_started",sessionId:e.sessionId,orgId:e.orgId,repo:o,branch:e.gitMetadata.gitBranchName,baseSha:t.baseSha,headSha:t.headSha,seedMode:e.seedMode??false,buildEnabled:e.buildEnabled,noCode:e.noCode??false,parallel:e.parallel,cliVersion:e.cliVersion},"Explore agent run started");let r=lle(e.signal,e.timeoutMs),i=U4e(e.jsonOutput),s=await F4e(e),a=new Wp({sessionGuard:{maxConcurrentSessions:e.parallel}}),l=[],c;try{c=await BP({...e,...r,repoRoot:t.repoRoot,baseSha:t.baseSha,headSha:t.headSha,seed:t.seed,banner:t.banner,manifest:t.manifest,output:i,sessionManager:a,paneLabel:t.paneLabel,replication:{depth:0,writtenPathSink:l},finalizeOutput:e.buildEnabled?!1:void 0,timelineRecorder:s});}catch(v){throw e.logger.error({event:"explore_run_failed",sessionId:e.sessionId,orgId:e.orgId,repo:o,durationMs:Date.now()-n,err:v},"Explore agent run failed"),v}let d=[...c.bugs],u=[...c.writtenPaths,...l],p=c.result,m=c.failure;if(e.buildEnabled&&!m&&p.testPlans.length>0){let v=await sj({explorerResult:p,sessionId:e.sessionId,logger:e.logger,generator:e.generator,apiClient:e.apiClient,orgId:e.orgId,project:e.project,parallel:e.parallel,repoRoot:t.repoRoot,baseSha:t.baseSha,headSha:t.headSha,...r,customPrompt:e.customPrompt,noCode:e.noCode,output:i,sessionManager:a,timelineRecorder:s});p=v.result,d.push(...v.bugs),u.push(...v.writtenPaths),m=v.failure;}else e.buildEnabled&&i.finalize();let h=[...new Set(u)];m?e.logger.warn({event:"explore_run_failed",sessionId:e.sessionId,orgId:e.orgId,repo:o,durationMs:Date.now()-n,reason:m.reason,cancelled:m.cancelled},"Explore agent run failed"):e.logger.info({event:"explore_run_finished",sessionId:e.sessionId,orgId:e.orgId,repo:o,durationMs:Date.now()-n,testPlans:p.testPlans.length,builtTests:p.buildSummary?.builtTests.length??0,bugs:d.length,writtenPaths:h.length},"Explore agent run finished"),e.jsonOutput||C.info(`
|
|
8233
|
-
${Lle(p,d,dt())}`);let g=s?s.finishExplore():void 0,f=g?g.agents.flatMap(v=>oce(v)):[],y=f.map(v=>v.ref),S=d.map(v=>({...v,recording:D4e(v.recording,f)})),{gitMetadata:T}=e,A={type:"explore",id:e.sessionId,cliVersion:e.cliVersion,startedAt:new Date(n).toISOString(),finishedAt:new Date().toISOString(),baseSha:t.baseSha,headSha:t.headSha,ciProvider:T.ciProvider,pipelineId:T.pipelineId,gitMainBranch:T.gitMainBranch,gitCommitSha:T.gitCommitSha,gitCommitShaShort:T.gitCommitShaShort,gitBranchName:T.gitBranchName,gitOriginUrl:T.gitOriginUrl,gitCommitMessage:T.gitCommitMessage,gitCommitAuthorName:T.gitCommitAuthorName,githubRepository:T.githubRepository,gitlabProjectPath:T.gitlabProjectPath,result:p,bugs:S,writtenPaths:h,videos:y,failure:m};return {explorerResult:p,bugs:S,repoRoot:t.repoRoot,writtenPaths:h,baseSha:t.baseSha,headSha:t.headSha,failure:m,metadata:A,timeline:g&&s?{timeline:g,assetsDir:s.assetsDir}:void 0}}function oce(e){let t=[];for(let n of e.videos??[])t.push({ref:`${Sb}/${n.asset}`,startedAt:n.startedAt,finishedAt:n.finishedAt});for(let n of e.spans)for(let o of n.subagents??[])t.push(...oce(o));return t}function D4e(e,t){if(!e)return;let n=t.find(o=>o.startedAt<=e.finishedAt&&(o.finishedAt??1/0)>=e.startedAt);return n?{...e,video:n.
|
|
8233
|
+
${Lle(p,d,dt())}`);let g=s?s.finishExplore():void 0,f=g?g.agents.flatMap(v=>oce(v)):[],y=f.map(v=>v.ref),S=d.map(v=>({...v,recording:D4e(v.recording,f)})),{gitMetadata:T}=e,A={type:"explore",id:e.sessionId,cliVersion:e.cliVersion,startedAt:new Date(n).toISOString(),finishedAt:new Date().toISOString(),baseSha:t.baseSha,headSha:t.headSha,ciProvider:T.ciProvider,pipelineId:T.pipelineId,gitMainBranch:T.gitMainBranch,gitCommitSha:T.gitCommitSha,gitCommitShaShort:T.gitCommitShaShort,gitBranchName:T.gitBranchName,gitOriginUrl:T.gitOriginUrl,gitCommitMessage:T.gitCommitMessage,gitCommitAuthorName:T.gitCommitAuthorName,githubRepository:T.githubRepository,gitlabProjectPath:T.gitlabProjectPath,result:p,bugs:S,writtenPaths:h,videos:y,failure:m};return {explorerResult:p,bugs:S,repoRoot:t.repoRoot,writtenPaths:h,baseSha:t.baseSha,headSha:t.headSha,failure:m,metadata:A,timeline:g&&s?{timeline:g,assetsDir:s.assetsDir}:void 0}}function oce(e){let t=[];for(let n of e.videos??[])t.push({ref:`${Sb}/${n.asset}`,asset:n.asset,startedAt:n.startedAt,finishedAt:n.finishedAt});for(let n of e.spans)for(let o of n.subagents??[])t.push(...oce(o));return t}function D4e(e,t){if(!e)return;let n=t.find(o=>o.startedAt<=e.finishedAt&&(o.finishedAt??1/0)>=e.startedAt);return n?{...e,video:n.asset,videoStartMs:Math.max(0,e.startedAt-n.startedAt),videoEndMs:e.finishedAt-n.startedAt}:e}async function F4e(e){if(!e.recordTimeline)return;let t=await j0.mkdtemp(io__default.join(Ed.tmpdir(),`momentic-explore-trace-${e.sessionId}-`));return new Ey({sessionId:e.sessionId,assetsDir:io__default.join(t,Sb),assetNamespace:"explore",cliVersion:e.cliVersion,logger:e.logger})}async function B4e(e){let{gitMetadata:t,apiClient:n,baseShaOverride:o,headShaOverride:r}=e;if(o&&r)return {baseSha:o,headSha:r};if(o||r)throw new vt("Both base SHA and head SHA must be provided together. Please provide both --base and --head options.");let i=false;if(t.githubRepository&&t.gitBranchName){let l=gr(t.githubRepository);if(!l)throw new vt(`GitHub repository is invalid: ${t.githubRepository}`);let c=await n.getGithubPullRequestForBranch(l.owner,l.repo,t.gitBranchName);if(c){i=true,C.info(`Detected pull request #${c.issueNumber} for branch ${t.gitBranchName}, using it as the diff window for explore.`);let d=await hA(c.headBranch),u=await hA(c.baseBranch);if(d&&u)return {baseSha:u,headSha:d};C.warn("Failed to resolve SHAs for pull request branches, falling back to current commit. This may cause explore results to be inaccurate.");}}else if(t.gitlabProjectPath&&t.gitBranchName){let l=await n.getGitlabMergeRequestForBranch(t.gitlabProjectPath,t.gitBranchName);if(l){i=true,C.info(`Detected merge request !${l.iid} for branch ${t.gitBranchName}, using it as the diff window for explore.`);let c=await hA(l.sourceBranch),d=await hA(l.targetBranch);if(c&&d)return {baseSha:d,headSha:c};C.warn("Failed to resolve SHAs for merge request branches, falling back to current commit. This may cause explore results to be inaccurate.");}}if(!i){let l=t.gitlabProjectPath?"MR":"PR";C.info(`Did not detect a ${l} for this branch, falling back to the current commit`);}let s=t.gitCommitSha??await Ba("HEAD"),a=await Ba("HEAD~1");if(!s||!a)throw new vt("Failed to detect base and head commits for the current environment. Please pass --head and --base options with explicit SHAs.");return {baseSha:a,headSha:s}}function U4e(e){return e?new Rs(new Writable({write(t,n,o){o();}}),{scrollBody:true}):new Rs(process.stdout,{scrollBody:true})}function H4e({gitMetadata:e,buildEnabled:t,cliVersion:n}){let o=e.githubRepository??e.gitlabProjectPath??"(local)",r=e.gitBranchName;return qd({cliName:"Momentic CLI",cliVersion:n??"dev",action:"Seeding tests across the whole app",fields:[t?"build mode":"plan mode"],rows:[{label:"repo",value:r?`${o} (${r})`:o}]},dt(process.stdout))}function j4e({manifest:e,gitMetadata:t,buildEnabled:n,cliVersion:o}){let{files:r,insertions:i,deletions:s}=e.totals,a=r===1?"file":"files",l=e.totalCommits===1?"commit":"commits",c=t.githubRepository??t.gitlabProjectPath??"(local)",d=t.gitBranchName,u=[{label:"repo",value:d?`${c} (${d})`:c},{label:"diff",value:`${e.baseSha.slice(0,7)}..${e.headSha.slice(0,7)}`}];return qd({cliName:"Momentic CLI",cliVersion:o??"dev",action:`Exploring ${r} changed ${a} (+${i} -${s})`,fields:[`${e.totalCommits} ${l}`,n?"build mode":"plan mode"],rows:u},dt(process.stdout))}function ice({target:e,hasKnowledgeBaseEntries:t=false}){let n=`
|
|
8234
8234
|
- ${$n}: search the organization's knowledge base for company-specific terminology, agent rules, or known flows scoped to this test. Pre-loaded matches for this test (if any) already appear in the knowledgeBase block at the top of the first user message; consult that first and call this tool only when you hit a term, flow, or convention you cannot resolve from the evidence, the resolved test, or the live browser. Treat this as an escape hatch for tribal knowledge, not an answer bank: it will not tell you how to solve your heals.`,o=G4e({hasKnowledgeBaseEntries:t});return [`
|
|
8235
8235
|
You are a Momentic test healing subagent. Momentic is a test authoring and execution platform for browser E2E tests using natural language and action based steps.
|
|
8236
8236
|
You have been given an available browser, extra context about the failure including what likely made it fail, and a set of tools you can use to investigate and repair the test.
|
|
@@ -9037,7 +9037,7 @@ ${i.length===0?"(none)":u}
|
|
|
9037
9037
|
`);}var Dl="/v1/app-graph",Xp=class{constructor(t,n){this.apiClient=t;this.logger=n;}async claim(t){let n=await this.apiClient.sendRequest(`${Dl}/ai-select/claim`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return Qz.parse(n)}async getPlan(t){let n=new URLSearchParams({repository:t.repository,headSha:t.headSha}),o=await this.apiClient.sendRequest(`${Dl}/ai-select/plan?${n.toString()}`,{method:"GET",retries:1,requestTimeoutMs:1e4});return eW.parse(o)}async finalize(t){let n=await this.apiClient.sendRequest(`${Dl}/ai-select/finalize`,{method:"POST",body:t,retries:2,requestTimeoutMs:3e4});return Zz.parse(n)}async release(t){await this.apiClient.sendRequest(`${Dl}/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(`${Dl}/ai-select/search/observed-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return gN.parse(n)}async searchSegments(t){let n=await this.apiClient.sendRequest(`${Dl}/ai-select/search/segments`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return gN.parse(n)}async getObservedTest(t){let n=await this.apiClient.sendRequest(`${Dl}/ai-select/observed-tests/${encodeURIComponent(t)}`,{method:"GET",retries:2,requestTimeoutMs:1e4});return tW.parse(n)}async getSegment(t){let n=await this.apiClient.sendRequest(`${Dl}/ai-select/segments/${encodeURIComponent(t)}`,{method:"GET",retries:2,requestTimeoutMs:1e4});return nW.parse(n)}async listObservedTestsForSegment(t){let n=await this.apiClient.sendRequest(`${Dl}/ai-select/segments/${encodeURIComponent(t)}/observed-tests`,{method:"GET",retries:2,requestTimeoutMs:1e4});return oW.parse(n)}async getCodeInsights(t){let n=await this.apiClient.sendRequest(`${Dl}/ai-select/code-insights`,{method:"POST",body:{repository:t.repository,folderPaths:t.folderPaths},retries:1,requestTimeoutMs:1e4});return rW.parse(n).insights}async createCodeInsight(t){let n=await this.apiClient.sendRequest(`${Dl}/ai-select/code-insight`,{method:"POST",body:t,retries:1,requestTimeoutMs:15e3});return iW.parse(n)}},KE=class extends Xp{constructor(t){let n={sendRequest:async()=>({})};super(n,t);}async searchObservedTests(){return {results:[]}}async searchSegments(){return {results:[]}}async getObservedTest(t){return {testId:t,name:"",testPath:null,goal:null,description:null,latestPassed:false,latestQuarantined:false,evidenceCount:0,lastObservedAt:null,lastObservedCommitSha:null,matchedSegments:[],coverageEdges:[]}}async getSegment(t){return {id:t,name:"",description:null,realizations:[],features:[]}}async listObservedTestsForSegment(){return {observedTests:[]}}async getCodeInsights(){return []}async createCodeInsight(){return {id:"noop"}}},M6e=2e3,due=12e4;async function uue(e){let t=Date.now()+(e.timeoutMs??due),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??due}ms`);e.logger.info({attempt:n,claimedBy:o.claimedBy},"ai-select plan computing on another shard; polling"),await et(o.retryAfterMs??M6e);}}async function L6e(e){try{return await hS({repoRoot:e.repoRoot,explicitBase:"HEAD~1",logger:e.logger})}catch{return wj({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:null,logger:e.logger})}}async function pue({params:e,reason:t}){let n=e.config?.onBaseUnavailable??"use-head";switch(n){case "fail":throw new Dh(`AI selection base unavailable and ai.select.onBaseUnavailable is "fail": ${t}`);case "run-all":return {diff:null,reason:t};case "use-head":{let o=await L6e(e);return o?{diff:o,reason:t}:{diff:null,reason:`Could not assemble diff against the HEAD commit's parent: ${t}`}}default:return Xe(n)}}async function Yj(e){return He({name:"ai_select.resolve_plan",root:true,attributes:{"momentic.repository":e.repository},fn:()=>k6e(e)})}async function k6e(e){let t=new Xp(e.apiClient,e.logger),n=e.agentOutputStream?dt(e.agentOutputStream):dt();e.agentOutputStream!==void 0&&!!e.agentOutputStream.isTTY;e.agentOutputStream&&e.agentOutputStream.write(`Selecting tests to run with AI:
|
|
9038
9038
|
`);let r;try{r=await He({name:"ai_select.assemble_diff",attributes:{"momentic.explicit_base":e.explicitBase??"auto"},fn:()=>Ao({text:"Analyzing code changes...",screen:n},()=>hS({repoRoot:e.repoRoot,explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch,logger:e.logger}))});}catch(p){let m=p instanceof Dh?p.message:`Could not assemble diff against base ref: ${q(p)}.`,h=cde({explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch}),g=h?await wj({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:h,logger:e.logger}):null;if(g)r=g;else {let f=await pue({params:e,reason:m});if(f.diff===null)return {kind:"run-all",reason:f.reason,diff:null};r=f.diff;}}if(r.baseSha===r.headSha){let p=`Base ref "${r.baseRef}" resolves to HEAD (${r.headSha}); applying ai.select.onBaseUnavailable fallback behavior.`,m=await pue({params:e,reason:p});if(m.diff===null)return {kind:"run-all",reason:m.reason,diff:null};r=m.diff;}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(`
|
|
9039
9039
|
`)).digest("hex").slice(0,12),s=`${r.headSha}:${i}`,a=r.repoRoot,l=io__default.relative(a,e.repoRoot),c=l?e.candidateTests.map(p=>({...p,testPath:io__default.posix.join(l.split(io__default.sep).join("/"),p.testPath)})):e.candidateTests;if(e.dryRun){let p=await yS({apiClient:t,generator:e.generator,logger:e.logger,repository:e.repository,repoRoot:a,projectRoot:e.repoRoot,diff:r,candidateTests:c,allTestDefinitions:e.allTestDefinitions,importIndexCachePath:Fh(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 uue({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 yS({apiClient:t,generator:e.generator,logger:e.logger,repository:e.repository,repoRoot:a,projectRoot:e.repoRoot,diff:r,candidateTests:c,allTestDefinitions:e.allTestDefinitions,importIndexCachePath:Fh(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: ${q(p)}.`,diff:r}}}async function hue({test:e,fragment:t,entities:n,client:o,logger:r,yes:i}){gt(t.schemaVersion,lt)&&(C.error(`Patch schema version (${t.schemaVersion}) is newer than this CLI supports. Update to the latest CLI and retry.`),process.exit(1)),U4(t.steps).forEach(f=>{n.modules[f]||(C.error(`Patch references module ${f} which is not in this project. The patch or your local files may be out of date.`),process.exit(1));}),t.createdAt.getTime()<Date.now()-7*Yg&&!i&&!await tr("The test patch you are applying is more than 7 days old. Are you sure you want to continue?")&&process.exit(1);let a=e.lastModified.getTime();t.createdAt.getTime()+60*60*1e3<a&&!i&&!await tr("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?")&&process.exit(1);let l=Dd(e.fullFilePath),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${e.fullFilePath} is missing steps array`);let d,u;if(t.schemaVersion!==lt){let{steps:f,newVersion:y}=await Ys({metadata:{id:t.id,schemaVersion:t.schemaVersion},steps:t.steps,logger:C});d=y,u=Ht.array().parse(f);}else u=Ht.array().parse(t.steps);let{stepsToSave:p}=await ro({stepLists:{steps:u}});p.beforeSteps=l.beforeSteps??void 0,p.afterSteps=l.afterSteps??void 0;let m=Um(PT.stringify(c),PT.stringify(p),{n_surrounding:5}),h=dt(),g=Mn(h);C.info(""),C.info(zn("Patch Preview",h)),C.info(""),C.info(g.code(e.relativePath));for(let f of sx(m,g))C.info(` ${f}`);C.info(""),d&&C.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${d}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await tr("Do you want to apply this patch?")&&(C.dimmed("Cancelled."),process.exit(1)),Ym({relativeTestPath:e.relativePath,steps:p,schemaVersion:d??t.schemaVersion,project:n.project,momenticFiles:n}),C.success("Patch applied."),await o.patchTestFragment(t.id,{applied:true,appliedAt:new Date});}function Hh({runId:e,zipPath:t}){let o=new Jj(t).getEntry(ct);if(!o)throw new Error(`Run archive ${t} is missing ${ct}.`);try{return Pm.parse(JSON.parse(o.getData().toString("utf-8")))}catch(r){throw new Error(`Run archive ${e} contains invalid ${ct}.`,{cause:r})}}function gue({runId:e,runDir:t}){let n=io__default.join(t,ct);try{return Pm.parse(JSON.parse(ko__default.readFileSync(n,"utf-8")))}catch(o){throw new Error(`Run directory ${e} contains invalid ${ct}.`,{cause:o})}}function fue({zipPath:e,files:t,buffers:n=[],deletePrefixes:o=[]}){if(t.length===0&&n.length===0)return;let r=z8(e);if(!(r===void 0||r.some(a=>o.some(l=>a.startsWith(l))))&&VI({zipPath:e,files:t,buffers:n}))return;let s=new Jj(e);for(let a of o)for(let l of s.getEntries().slice())l.entryName.startsWith(a)&&s.deleteFile(l.entryName);for(let a of t)s.addFile(a.entryName,ko__default.readFileSync(a.sourcePath));for(let a of n)s.addFile(a.entryName,a.data);ko__default.writeFileSync(e,s.toBuffer());}function eO({zipPath:e,metadata:t}){let n=new Jj(e);n.deleteFile(ct),n.addFile(ct,Buffer.from(JSON.stringify(t,null,2),"utf-8")),ko__default.writeFileSync(e,n.toBuffer());}function U6e(e){switch(e){case "SUCCESS":return "passed";case "CANCELLED":return "skipped";case "FAILED":case "IDLE":case "RUNNING":return "failed";default:return Xe(e)}}function H6e(e){switch(e){case "PASSED":return "passed";case "CANCELLED":return "skipped";case "FAILED":case "PENDING":case "RETRYING":case "RUNNING":case "WAITING_FOR_USER":return "failed";default:return Xe(e)}}async function j6e(e){let{step:t,logger:n,debugDataStorage:o,folder:r,beforeSnapshot:i,afterSnapshot:s}=e,a=await oO({logger:n,debugDataStorage:o,folder:r,label:"before",snapshotId:i});a&&t.attachments.push({name:"Screenshot before step",source:a,type:"image/jpeg"});let l=await oO({logger:n,debugDataStorage:o,folder:r,label:"after",snapshotId:s});l&&t.attachments.push({name:"Screenshot after step",source:l,type:"image/jpeg"});}function G6e(e,t,n){let o=z$1.union([z$1.looseObject({}),z$1.array(z$1.unknown().optional())]).safeParse(n).success,r=`output-attachment-${randomUUID()}.json`;ko__default.writeFileSync(io__default.join(t,r),JSON.stringify(n,null,2)),e.attachments.push({name:"Step output data",source:r,type:o?"application/json":"text/plain"});}function $6e(e){let{step:t,folder:n,beforeTestContext:o,afterTestContext:r}=e;if(o){let i=`before-context-${randomUUID()}.json`;writeFileSync(io__default.join(n,i),Sue(o.env)),t.attachments.push({name:"Test context before step",source:i,type:"application/json"});}if(r){let i=`after-context-${randomUUID()}.json`;writeFileSync(io__default.join(n,i),Sue(r.env)),t.attachments.push({name:"Test context after step",source:i,type:"application/json"});}}function V6e(e){let t=[{name:"suite",value:e.suiteName},{name:"host",value:hostname()},{name:"platform",value:"momentic"},{name:"attempts",value:e.attempts.toString()}];return e.runId&&t.push({name:"runUrl",value:`https://app.momentic.ai/runs/${e.runId}`}),e.quarantined&&t.push({name:"quarantined",value:"true"}),e.quarantinedReason&&t.push({name:"quarantinedReason",value:e.quarantinedReason}),e.quarantinedAt&&t.push({name:"quarantinedAt",value:e.quarantinedAt.toISOString()}),t}async function oO(e){let{logger:t,debugDataStorage:n,folder:o,label:r,snapshotId:i}=e;if(!i)return;let s=await n.getScreenshot(t,i);if(!s)return;let a=`screenshot-${r}-${i}.jpeg`;return ko__default.writeFileSync(io__default.join(o,a),s),a}async function z6e(e,t,n,o){let r=n.folder,i={uuid:o.runAttemptId??randomUUID(),historyId:o.runId??randomUUID(),testCaseId:o.test.id,fullName:o.test.name,name:Fn(o.test.name),status:H6e(o.status),start:o.lastAttemptStartedAt.getTime(),stop:o.finishedAt.getTime(),parameters:[],labels:V6e({suiteName:n.suiteName,attempts:o.attempts,runId:o.runId,quarantined:o.quarantined,quarantinedReason:o.quarantinedMetadata?.quarantinedReason,quarantinedAt:o.quarantinedMetadata?.quarantinedAt}),steps:[]};for(let[l,c]of Object.entries(o.parameters))c!=null&&i.parameters.push({name:l,value:JSON.stringify(c)});o.results&&await Xj(e,t,n.folder,i.steps,o.results);let s=W6e(t,r,o.runAttemptId);s.length>0&&(i.attachments=s);let a=`${o.runAttemptId}-result.json`;ko__default.writeFileSync(io__default.join(r,a),JSON.stringify(i,void 0,2));}async function nO(e,t,n,o){let r={name:Vn(o),start:o.startedAt.getTime(),stop:o.finishedAt.getTime(),status:U6e(o.status),labels:[],steps:[],attachments:[]};if(o.beforeUrl&&r.labels.push({name:"URL before step",value:o.beforeUrl}),o.afterUrl&&r.labels.push({name:"URL after step",value:o.afterUrl}),await j6e({step:r,logger:e,debugDataStorage:t,folder:n,beforeSnapshot:o.beforeSnapshot,afterSnapshot:o.afterSnapshot}),o.message&&(r.statusDetails={message:o.message}),o.data)if(WS.safeParse(o.data).success){let i=WS.parse(o.data),s=i.request,a={...i,request:void 0},l=`output-attachment-api-request-${randomUUID()}.json`,c=`output-attachment-api-response-${randomUUID()}.json`;ko__default.writeFileSync(io__default.join(n,l),JSON.stringify(s,null,2)),ko__default.writeFileSync(io__default.join(n,c),JSON.stringify(a,null,2)),r.attachments.push({name:"API request details",source:l,type:"application/json"}),r.attachments.push({name:"API response details",source:c,type:"application/json"});}else G6e(r,n,o.data);return r}async function Xj(e,t,n,o,r){for(let i of r){let s;switch(i.type){case "PRESET_ACTION":{s=await nO(e,t,n,i);break}case "CONDITIONAL":{s=await nO(e,t,n,i),s.steps=[],i.assertionResult&&s.steps.push(await nO(e,t,n,i.assertionResult)),await Xj(e,t,n,s.steps,i.results);break}case "AI_ACTION_DYNAMIC":case "AI_ACTION":case "SECTION":case "WHILE_LOOP":case "MODULE":{if(s=await nO(e,t,n,i),await Xj(e,t,n,s.steps,i.results),i.type==="MODULE"&&i.inputs){s.parameters=[];for(let[a,l]of Object.entries(i.inputs))s.parameters.push({name:a,value:l});}break}}if(!s){e.warn({result:i},"Failed to convert Momentic result to Allure step");continue}s.attachments||(s.attachments=[]),$6e({step:s,folder:n,beforeTestContext:i.beforeTestContext,afterTestContext:i.afterTestContext}),o.push(s);}}async function bue(e,t,n,o,r){for(let i of r){if(!i.runId||!i.runAttemptId)throw new Error(`Missing runId/runAttemptId for Allure report generation for test '${i.test.name}'`);let s=t.createDebugDataReaderForRunAttempt(i.runId,i.runAttemptId);try{await z6e(e,s,{folder:n,suiteName:o.suiteName},i);}finally{s.close();}}}function Sue(e){try{return JSON.stringify(e,void 0,2)??JSON.stringify({value:null},void 0,2)}catch(t){let n=t instanceof Error?t.message:"unknown error";return JSON.stringify({error:n},void 0,2)}}function W6e(e,t,n){let o=e.listVideoAssetPaths();if(o.length===0)return [];let r=[];for(let i of o){let s=io__default.basename(i),a=n?`${n}-${s}`:s;try{ko__default.copyFileSync(i,io__default.join(t,a));}catch{continue}let l,c=io__default.extname(i).toLowerCase();c===".webm"?l="video/webm":c===".mp4"?l="video/mp4":l="application/octet-stream",r.push({name:s,source:a,type:l});}return r}function rO(e){if(e.status!=="FAILED")return "none";switch(e.failureReason){case "SetupFailureError":return "setup";case "TeardownFailureError":return "teardown";default:return "main"}}function K6e(e){switch(e){case "PASSED":return "passed";case "FAILED":return "failed";case "CANCELLED":return "skipped";case "RETRYING":case "WAITING_FOR_USER":case "PENDING":case "RUNNING":return "unknown";default:return Xe(e)}}function vue(e){let t=io__default.relative(".",e);return t===""?e:t}function Tue(e,t){return Math.max(0,(e.getTime()-t.getTime())/1e3)}function Y6e(e,t,n){let o=Tue(t,e),r=Tue(n,e);return {start_at:o,end_at:r,duration:Math.max(0,r-o)}}function Cue(e){let t=e.reduce((n,[o,r])=>(!r||Object.keys(n).length>=10||(n[o]=r),n),{});return Object.keys(t).length>0?t:void 0}function J6e(e){if(e.status!=="FAILED"||!e.failureReason)return;let t=Xl({failureReason:e.failureReason,classification:e.failureDetails?.classification,manualClassification:e.failureDetails?.manualClassification,errorMessage:e.failureDetails?.errorMessage});if(!(t.title==null||t.description==null))return `${t.title}: ${t.description}`}function X6e(e){if(e.status!=="FAILED")return;let t=[e.failureDetails?.classification?.summary,e.failureDetails?.classification?.rootCause,e.failureDetails?.errorMessage].filter(o=>!!o),n=e.failureDetails?.errorStack?.split(`
|
|
9040
|
-
`).map(o=>o.trim()).filter(Boolean)||[];if(!(t.length===0&&n.length===0))return [{expanded:t,backtrace:n}]}function Q6e(e){let t=e.status==="FAILED"?rO(e):void 0;return Cue([["attempts",e.attempts.toString()],["run_url",e.runId?`https://app.momentic.ai/runs/${e.runId}`:void 0],["failure_section",t],["quarantined",e.quarantined?"true":"false"],["failure_recovery",e.failureRecoveryDetails?.attempts?"true":"false"]])}function Z6e(e,t,n){let o=vue(n.filePath);return {id:n.runId||randomUUID(),scope:e,name:n.testName,location:o,file_name:io__default.basename(o),result:K6e(n.status),failure_reason:J6e(n),failure_expanded:X6e(n),history:Y6e(t,n.lastAttemptStartedAt,n.finishedAt),tags:Q6e(n)}}function Aue(e,t,n,o,r){let i=vue(t);return {id:randomUUID(),scope:e,name:n,location:i,file_name:io__default.basename(i),result:"skipped",history:{start_at:0,end_at:0,duration:0},tags:Cue([["quarantined",r?.quarantined||"false"],["failure_recovery","false"]])}}function e8e(e,t){let n=t.map(i=>Z6e(e.suiteName,e.startedAt,i)),o=e.testsToSkip.map(i=>Aue(e.suiteName,i.relativeFilePath,i.name,i.id,void 0)),r=e.quarantinedTestsToSkip.map(i=>Aue(e.suiteName,i.relativeFilePath,i.name,i.id,{quarantined:"true"}));return [...n,...o,...r]}function Rue(e,t,n){let o=e8e(t,n);ko__default.writeFileSync(io__default.join(e,`${t.suiteName}.buildkite.json`),JSON.stringify(o,null,2));}function bS(e){return {testName:e.test.name,testId:e.test.id,filePath:e.filePath,labels:e.test.labels,baseUrl:e.baseUrl,runId:e.runId,quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata,status:e.status,failureRecoveryDetails:e.failureRecoveryDetails,failureDetails:e.failureDetails,failureReason:e.failureReason,finishedAt:e.finishedAt,lastAttemptStartedAt:e.lastAttemptStartedAt,attempts:e.attempts,parameters:e.parameters}}function Iue(e,t,n){let o=Zj(t,n);ko__default.writeFileSync(io__default.join(e,`${t.suiteName}.momentic.json`),JSON.stringify(o,null,2));}function Zj(e,t){let n=t.map(n8e),o=[...e.testsToSkip.map(r=>wue(r,false)),...e.quarantinedTestsToSkip.map(r=>wue(r,true))];return SW.parse({version:1,runGroup:{startedAt:e.startedAt.toISOString(),finishedAt:e.finishedAt.toISOString(),durationMs:e.finishedAt.getTime()-e.startedAt.getTime()},summary:o8e(n,o),runs:n,skipped:o})}function n8e(e){let t=e.status==="PASSED"&&(e.failureRecoveryDetails?.attempts??0)>0,n=e.failureDetails?.manualClassification??e.failureDetails?.classification,o=e.status==="FAILED"?{reason:e.failureReason,message:e.failureDetails?.errorMessage}:null;return {runId:e.runId,testId:e.testId,testName:e.testName,filePath:io__default.relative(".",e.filePath),labels:e.labels,status:e.status,startedAt:e.lastAttemptStartedAt.toISOString(),finishedAt:e.finishedAt.toISOString(),durationMs:e.finishedAt.getTime()-e.lastAttemptStartedAt.getTime(),attempts:e.attempts,quarantined:e.quarantined??false,recovered:t,parameters:e.parameters,failure:o,classification:n?{reasoning:n.summary,category:n.reason,citations:n.citations}:null}}function wue(e,t){return {testId:e.id,testName:e.name,filePath:io__default.relative(".",e.relativeFilePath),labels:e.labels,quarantined:t}}function o8e(e,t){return {total:e.length+t.length,executed:e.length,skipped:t.length,passed:e.filter(n=>n.status==="PASSED").length,failed:e.filter(n=>n.status==="FAILED").length,cancelled:e.filter(n=>n.status==="CANCELLED").length,quarantined:e.filter(n=>n.quarantined).length+t.filter(n=>n.quarantined).length,recovered:e.filter(n=>n.recovered).length}}function xue(e,t){e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),t.quarantinedReason&&(e.property("quarantined_reason",t.quarantinedReason),e.property("dd_tags[quarantined_reason]",t.quarantinedReason)),t.quarantinedAt&&(e.property("quarantined_at",t.quarantinedAt.toISOString()),e.property("dd_tags[quarantined_at]",t.quarantinedAt.toISOString()));}function i8e(e,t){let n=rO(e);if(t.name(e.testName).className(e.testName).file(io__default.relative(".",e.filePath)).property("id",e.testId).property("dd_tags[id]",e.testId),e.labels&&(t.property("labels",e.labels.join(",")),e.labels.forEach(o=>{t.property("dd_tags[label]",o);})),e.baseUrl&&(t.property("base_url",e.baseUrl),t.property("dd_tags[base_url]",e.baseUrl)),e.runId&&(t.property("run_url",`https://app.momentic.ai/runs/${e.runId}`),t.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${e.runId}`)),e.quarantinedMetadata&&xue(t,e.quarantinedMetadata),n==="setup"&&(t.property("setup_failed","true"),t.property("dd_tags[setup_failed]","true")),n==="main"&&(t.property("main_failed","true"),t.property("dd_tags[main_failed]","true")),n==="teardown"&&(t.property("teardown_failed","true"),t.property("dd_tags[teardown_failed]","true")),e.status==="FAILED"){let o=Xl({failureReason:e.failureReason,classification:e.failureDetails?.classification,manualClassification:e.failureDetails?.manualClassification});if(o.title){let{description:r}=o;e.runId&&(r+=` Visit https://app.momentic.ai/runs/${e.runId} for more details.`),t.failure(r,o.title);}e.failureDetails?.errorStack&&t.stacktrace(e.failureDetails.errorStack);}else e.status==="CANCELLED"&&t.skipped();return t.time((e.finishedAt.getTime()-e.lastAttemptStartedAt.getTime())/1e3).property("started_at",e.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",e.lastAttemptStartedAt.toISOString()).property("finished_at",e.finishedAt.toISOString()).property("dd_tags[finished_at]",e.finishedAt.toISOString()),t.property("attempts",e.attempts.toString()).property("dd_tags[attempts]",e.attempts.toString()),e.parameters?.envName&&(t.property("environment",e.parameters.envName),t.property("dd_tags[environment]",e.parameters.envName)),e.parameters?.urlOverride&&t.property("url_override",e.parameters.urlOverride),t}function s8e(e,t,n){let{suiteId:o,suiteName:r,startedAt:i,finishedAt:s,testsToSkip:a,quarantinedTestsToSkip:l,quarantinedTestsMetadata:c}=t,d=e.testSuite().name(r);o&&d.property("id",o),d.timestamp(i).property("startedAt",i.toISOString()).property("finishedAt",s.toISOString()).time((s.getTime()-i.getTime())/1e3);for(let u of n){let p=d.testCase();i8e(u,p);}for(let u of a){let p=d.testCase();p.name(u.name).className(u.name).file(io__default.relative(".",u.relativeFilePath)).property("id",u.id),u.baseUrl&&p.property("baseUrl",u.baseUrl),u.labels&&(p.property("labels",u.labels.join(",")),u.labels.forEach(m=>{p.property("dd_tags[label]",m);})),p.skipped();}for(let u of l){let p=d.testCase();p.name(u.name).className(u.name).file(io__default.relative(".",u.relativeFilePath)).property("id",u.id);let m=c[u.id];m&&xue(p,m),u.baseUrl&&p.property("baseUrl",u.baseUrl),u.labels&&(p.property("labels",u.labels.join(",")),u.labels.forEach(h=>{p.property("dd_tags[label]",h);})),p.skipped();}return d}function _ue(e,t,n){let o=r8e.newBuilder();s8e(o,t,n),o.writeTo(io__default.join(e,`${t.suiteName}.xml`));}var a8e="insights-collector.newrelic.com",l8e="insights-collector.eu01.nr-data.net",c8e=4e3;async function eG({logger:e,config:t,params:n,runs:o,runGroupId:r,envName:i,appUrl:s,gitMetadata:a}){let l=t.licenseKey??process.env.NEW_RELIC_LICENSE_KEY??"";if(!l){e.error("New Relic reporter is enabled but no license key was found. Set reporting.newrelic.licenseKey in momentic.config.yaml or the NEW_RELIC_LICENSE_KEY environment variable.");return}let c=o.map(bS),d=Zj(n,c),u=Pue({...t.attributes,runGroupId:r,environment:i,suiteName:n.suiteName,gitBranch:a.gitBranchName,gitCommit:a.gitCommitSha,gitRepository:a.githubRepository??a.gitOriginUrl,ciRunUrl:d8e()}),p=d.runs.map((g,f)=>({...u,eventType:"MomenticRun",timestamp:new Date(g.finishedAt).getTime(),...Pue({runId:g.runId,testId:g.testId,testName:g.testName,filePath:g.filePath,status:g.status,startedAt:g.startedAt,finishedAt:g.finishedAt,durationMs:g.durationMs,attempts:g.attempts,quarantined:g.quarantined,recovered:g.recovered,labels:g.labels?.join(","),baseUrl:c[f]?.baseUrl,failureReason:g.failure?.reason,failureMessage:g.failure?.message,classificationCategory:g.classification?.category,classificationReasoning:g.classification?.reasoning,runUrl:g.runId?`${s}/runs/${g.runId}`:void 0})}));p.push({...u,eventType:"MomenticRunGroup",timestamp:new Date(n.finishedAt).getTime(),startedAt:n.startedAt.toISOString(),finishedAt:n.finishedAt.toISOString(),durationMs:d.runGroup.durationMs,runGroupUrl:`${s}/run-groups/${r}`,...d.summary,passRate:d.summary.executed>0?d.summary.passed/d.summary.executed:0});let h=`https://${t.region==="EU"?l8e:a8e}/v1/accounts/${t.accountId}/events`;try{let g=await fetch(h,{method:"POST",headers:{"Content-Type":"application/json","Api-Key":l},body:JSON.stringify(p)});if(!g.ok){let f=await g.text();e.error(`Failed to send test results to New Relic: ${g.status} ${f}`);return}e.info(`Sent ${p.length} events to New Relic account ${t.accountId}`);}catch(g){e.error(`Failed to send test results to New Relic: ${q(g)}`);}}function Pue(e){let t={};for(let[n,o]of Object.entries(e))o==null||o===""||(t[n]=typeof o=="string"?o.slice(0,c8e):o);return t}function d8e(){let e=process.env;return e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:e.CI_JOB_URL??e.BUILDKITE_BUILD_URL??e.CIRCLE_BUILD_URL??void 0}function Oue(e){return {title:Vn(e),duration:e.finishedAt.getTime()-e.startedAt.getTime(),error:e.status==="FAILED"?{value:e.failureReason}:void 0,steps:e.results&&e.type!=="PRESET_ACTION"?e.results.map(Oue):[]}}async function m8e(e,t,n,o){if(o.results?.length){let r=await oO({logger:e,debugDataStorage:t,folder:n,label:"final-state",snapshotId:o.results[o.results.length-1].afterSnapshot});return r?[{name:"Final state screenshot",path:r,contentType:"image/jpeg"}]:[]}return []}async function h8e(e,t,n,o){let r;if(o.status==="FAILED"&&o.failureReason){let i=Xl({failureReason:o.failureReason,classification:o.failureDetails?.classification,manualClassification:o.failureDetails?.manualClassification});r={value:o.failureDetails?.classification?.reason??o.failureReason,message:i.description};}return {status:o.status==="PASSED"?"passed":o.status==="CANCELLED"?"interrupted":"failed",duration:o.finishedAt.getTime()-o.lastAttemptStartedAt.getTime(),error:r,retry:o.attempts-1,steps:o.results?.map(Oue)||[],startTime:o.lastAttemptStartedAt.toISOString(),attachments:await m8e(e,t,n,o)}}async function g8e(e,t,n,o){return {expectedStatus:"passed",status:o.status==="PASSED"?"expected":"unexpected",results:[await h8e(e,t,n,o)]}}async function f8e(e,t,n,o){return {tags:[],title:o.test.name,ok:o.status==="PASSED",tests:[await g8e(e,t,n,o)],id:o.runId,file:o.filePath}}function tG(e,t){return e.reduce((n,o)=>t(o)?n+1:n,0)}async function y8e(e,t,n,o,r){return {suites:[{title:o.suiteName,file:o.projectConfigPath,specs:await Promise.all(r.map(async i=>{let s=i.runId&&i.runAttemptId?t.createDebugDataReaderForRunAttempt(i.runId,i.runAttemptId):new nT;try{return await f8e(e,s,n,i)}finally{s.close();}}))}],errors:[],stats:{startTime:o.startedAt.toISOString(),duration:o.finishedAt.getTime()-o.startedAt.getTime(),expected:tG(r,i=>i.status==="PASSED"),unexpected:tG(r,i=>i.status!=="PASSED"),flaky:tG(r,i=>!!i.isFlake),skipped:0}}}async function Mue(e,t,n,o,r){let i=await y8e(e,t,n,o,r);ko__default.writeFileSync(io__default.join(n,`${o.suiteName}.json`),JSON.stringify(i,null,2));}async function Nue({logger:e,callbacks:t,format:n,params:o,runs:r,folder:i}){switch(existsSync(i)&&!statSync(i).isDirectory()&&(C.error(`The specified reporter output directory '${i}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)),mkdirSync(i,{recursive:true}),n){case "json":{let s=r.map(bS);Iue(i,o,s);return}case "junit":{let s=r.map(bS);_ue(i,o,s);return}case "buildkite-json":{let s=r.map(bS);Rue(i,o,s);return}case "allure":case "allure-json":await bue(e,t,i,o,r);return;case "playwright-json":await Mue(e,t,i,o,r);return;default:throw new Error(`Unknown reporter format requested: '${n}'`)}}function Gh(e){let t=e??R8e();return Lue()&&t===1&&C.warn("Running with --pixel-ratio=1 on a Retina screen. Viewport calculations may be incorrect; omit the flag to auto-detect."),t}function R8e(){let e=Lue(),t=e?2:1;return C.debug(`Auto-detected device pixel ratio ${t} (Mac OS Retina: ${e}).`),t}var Lue=once(()=>{if(platform()!=="darwin")return false;try{return execSync("system_profiler SPDisplaysDataType").toString().includes("Retina")}catch{return false}});async function aO(e,t=true,n=false){let o=_8e(e),r=await I8e.which(o[0],true),i=o.slice(1),s=w8e.exec(x8e(r),i,{delay:100,silent:n});if(t)return s}var kue="the Momentic GitHub app is missing permission to create pull requests or write branches for this repository";function P8e(e,{context:t}){return e instanceof mo?e.rawError.includes("Resource not accessible by integration")?`Cannot create ${t} because ${kue}.`:e.status>=400&&e.status<500?e.rawError:`Could not create ${t} due to a GitHub error.`:`Could not create ${t}: ${q(e)}`}function Due(e){return e instanceof mo?e.rawError.includes("Resource not accessible by integration")?kue:e.status>=400&&e.status<500?e.rawError:"a GitHub error occurred":q(e)}function Fue(e,t){C.error(P8e(e,t));}function lO(e){return Bue(e,"runs","run")}function nG(e){return Bue(e,"run-groups","run group")}function Bue(e,t,n){let o=e.trim(),r=/^https?:\/\//i.test(o)?M8e(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 M8e(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 cO(e){return new Promise((t,n)=>{let o=[];createReadStream(e).pipe(N8e()).on("data",r=>o.push(r)).on("end",()=>t(o)).on("error",r=>n(r));})}var Vt="3.25.0",{checkCLIVersion:lr,getLatestCLIVersion:Uue}=I9({packageName:"momentic",currentVersion:Vt,changelogUrl:"https://github.com/momentic-ai/cli/releases",updateCommand:"npx momentic@latest upgrade"});I0e("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI","POSTHOG_WEB_WRITE_KEY is not set");var{captureEvent:gu,setAnalyticsIdentity:dO,shutdownAnalytics:Hue}=CR({writeKey:"phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",host:"https://p.momentic.ai",platform:"cli",identity:"stashed",flushImmediately:true,onIdentify:o7});async function Ze(){try{await xe(Promise.all([ER(),wt.flush(),Hue(),kR()]),{milliseconds:5e3});}catch{}}async function Qp({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=>ko__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(!ko__default.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m;try{m=ko__default.statSync(p).isDirectory();}catch(g){a.warn({err:g},`Skipping path ${p} because it cannot be read`);return}let h=io__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 tr("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=io__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 fs(d,he,t);if(Jd.gt(u.schemaVersion,lt)&&R3(a,`Test ${d} has schema version ${u.schemaVersion}, which is newer than this version of the CLI supports. Update your momentic package to avoid unexpected behavior.`,"newer-schema-version"),s&&s.length>0){let p=u.labels||[];if(!s.some(h=>p.includes(h)))return null}return {...u,fullFilePath:d,relativeFilePath:io__default.relative(n.rootDir,d)}}catch(u){a.error(`Failed to read and resolve test at '${d}': ${q(u)}`),process.exit(1);}});return compact(await Promise.all(c))}function Gue({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 $ue({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 Vue=()=>process.exit(130),zue=()=>process.exit(143);process.on("SIGINT",Vue);process.on("SIGTERM",zue);function TS(){process.off("SIGINT",Vue),process.off("SIGTERM",zue);}async function Wue({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 yi({orgId:e,s:l,localTools:t,logger:n,context:r});}return i}var que=new Set;async function Kue({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 A={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:he,mode:o.mode,runner:o.runner},{controller:v,context:w}=await EE({baseUrl:e,envName:t,test:r,variables:c,logger:d,orgId:l,localBrowserConfig:m,aiSettings:h,customHeaders:u,codeEvalTools:s,storage:i,enricher:new $d(A,a),generator:a,visualDiffScreenshotStorage:g,devicePixelRatio:n,browserTypeOverride:S,callbacks:{onNetworkPage:I=>f.onNetworkPage(I),onNetworkLogs:I=>f.onNetworkLogs(I)},videoOptions:f.videoOutputPath?{videoOutputPath:f.videoOutputPath,onVideoPageChange:({videoName:I,timestamp:_})=>{f.setActiveVideo(I,_);}}:void 0,validateBrowserType:I=>{Xu(I)||(he.warn({browserType:I,testName:r.name},"Browser required by test does not appear to be installed"),!que.has(I)&&(que.add(I),C.warn(`Browser ${I} does not appear to be installed. Run '${xu(I)}' if you hit launch errors.`)));},createRemoteBrowserConnection:m.remoteBrowser?async()=>{let I=await o.createRemoteBrowserConnection({testId:r.id,testName:r.name,runId:y,attemptedProviders:T});return I.provider&&T?.push(I.provider),I}:void 0});try{await Q_({orgId:l,test:r,testInputs:p,localTools:s,logger:d,context:w});}catch(I){try{await v.browser.cleanup();}catch(_){d.error({err:_},"Failed to clean up browser after test input resolution failed");}throw I instanceof vE&&(C.error(I.message),process.exit(1)),I}return {controller:v,context:w}}function Yue({testAdvancedSettings:e,orgSettings:t,logger:n}){if(e.failureRecovery===false||e.failureRecovery===void 0&&!t?.failureRecovery)return false;if(!Om){let o="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(o),C.debug(o),false}return true}async function Jue({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:A,orgSettings:v}=e;y.info(`Running test '${A.name}' locally (run link: https://app.momentic.ai/runs/${l})`);let w={controller:m,storage:f,usageTracker:S,context:h,logger:y,codeEvalTools:g},I={orgId:s,userId:a,runId:l,testMetadata:A,steps:A.steps,beforeSteps:A.beforeSteps,afterSteps:A.afterSteps,orgSettings:v},_={collectDebugData:true,reinitializeBrowser:true,disableHealing:!await Yue({testAdvancedSettings:A.advanced,orgSettings:v.ai,logger:y})};return Use({fixtures:w,inputs:I,options:_,callbacks:{step:i??{},test:{onTestComplete:async x=>{await m.browser.cleanup({saveRemoteVideos:r!=="on-fail"||x?.status!=="PASSED"}),await g.dispose();}}},testParams:{attemptTracer:T},runParams:{runTracer:c,runGroupTracer:d,project:u,apiClient:p,captureEvent:gu,abortSignal:o.abortSignal}})}async function Xue(e){let{testDefinition:t,logger:n}=e,o=new Date;try{return await j8e(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),C.error({err:r},d),Que({err:Qa(r),parameters:c,test:t,failureReason:oe.reasonFor(r,"UnknownError"),startedAt:o,lastAttemptStartedAt:o,attempts:0,quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata})}}async function j8e(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 sy(r,i),T=Wd({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}),A,v;n?(A={envName:n.metadata.environment.envName,resolvedEnv:n.metadata.environment.resolvedEnv,environmentVariables:{...n.metadata.environment.variables},baseUrl:n.metadata.environment.baseUrl},v={steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps}):(A=ly({test:t,envNameOverride:e.envName,urlOverride:a,resolveEnv:ee=>yl(ee,o,c)}),v=await Ma({cacheStorage:T,logger:c,schemaVersion:t.schemaVersion,stepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,environment:A.envName,useSnapshotIdentityCache:o.config.fileFormat==="v2"}));let{envName:w,resolvedEnv:I,environmentVariables:_,baseUrl:R}=A,x=v.steps,O=v.beforeSteps??void 0,N=v.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:R,environmentName:w,schemaVersion:t.schemaVersion,resolvedInputs:m,quarantined:h,quarantinedReason:g?.quarantinedReason,aiSettings:y.ai}),W=c.child(k.loggerBindings||{});Object.entries(k.envVarBindings||{}).forEach(([ee,j])=>{_[ee]=j;});let X=await G8e({...e,effectiveConfig:y,variables:_,envName:w,resolvedEnv:I,baseUrl:R,storageClient:S,tracer:k,runGroupTracer:l,logger:W,cacheStorage:T,stepsWithCaches:x,beforeStepsWithCaches:O,afterStepsWithCaches:N,usageTracker:f});return await k.finish({logger:c,status:X.status,finishedAt:X.finishedAt,failureDetails:X.failureDetails,failureReason:X.failureReason,isFlake:X.isFlake,failureRecoveryDetails:X.failureRecoveryDetails}),{runId:k.runId,...X}}async function G8e(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:A,devicePixelRatio:v,logUpdate:w,tracer:I,runGroupTracer:_,logger:R,cacheStorage:x,gitMetadata:O,quarantined:N,quarantinedMetadata:k,usageTracker:W}=e,X=n,ee=X.ai?.aiFailureAnalysis??false,j=new Date,V=new Kf(s,l,a),M={envName:h,urlOverride:g,customHeaders:f,testInputs:y},J={...X.browser||{},...T?.browser||{},...t.advanced||{},...e.remoteBrowserOverride?{remoteBrowser:true}:{}},B=J.remoteBrowser===true,D=[],Y,te=Math.abs(A??t.retries??n.retries??1),ue=[];R.info({...O,labels:t.labels,name:t.name,cwd:process.cwd()},"Starting test run using CLI");for(let Te=0;Te<=te;Te++){let Ae=randomUUID(),je=await I.startAttempt(Ae),ge=R.child(je.loggerBindings||{}),se={...t,steps:cloneDeep(o),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)};Te!==0&&w("RETRY",`attempt ${Te+1}/${te+1}`);let Ie=new Date,Je=new zd({httpClient:new Ki({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:ge,mode:l.mode,runner:l.runner}),fakerSeed:X.advanced?.fakerConstantSeed?tT:void 0});try{let{controller:Ve,context:$e}=await Kue({tracer:je,runId:I.runId,baseUrl:d,envName:h,apiClient:l,devicePixelRatio:v,logger:ge,storageClient:u,codeEvalTools:Je,test:se,generator:c,orgId:p,variables:S,customHeaders:f,testInputs:y,localBrowserConfig:J,browserTypeOverride:e.browserTypeOverride,attemptedRemoteBrowserProviders:D,aiSettings:{...X.ai||{},...se.advanced||{}},visualDiffScreenshotStorage:V});e.abortSignal&&(e.abortSignal.aborted?Ve.executeAbortController.abort():e.abortSignal.addEventListener("abort",()=>{Ve.executeAbortController.abort();},{once:!0})),Y=await Jue({attemptMetadata:{attemptNumber:Te+1,orgId:p,userId:m,runId:I.runId},attemptFixtures:{logger:ge,storageClient:u,usageTracker:W,codeEvalTools:Je,context:$e,controller:Ve,tracer:je},attemptInputs:{test:se,orgSettings:X},runFixtures:{runTracer:I,runGroupTracer:_,project:s,apiClient:l,abortSignal:e.abortSignal},recordVideo:e.recordVideo??!1,stepCallbacks:{onStepStart:e.onStepStart,onStepEnd:e.onStepEnd,onSectionStart:e.onSectionStart}});let _t=new Date,dn={logger:R,cacheStorage:x,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 Gm({logger:R,cacheStorage:x,orgId:p,testId:t.id,environment:h,stepLists:dn.updatedStepsWithCaches,useSnapshotIdentityCache:s.config.fileFormat==="v2"}),Y?.status==="PASSED"||Y?.status==="CANCELLED"&&n.advanced?.saveCacheOnCancel?await $m(dn):Y?.status==="FAILED"&&Te===te&&await Cf(dn),await je.finish({logger:ge,result:Y}),ue.unshift(Y.status);let go=await Wue({orgId:p,codeEvalTools:Je,logger:ge,outputDefinitions:t.outputs??[],testContext:$e}),pa=fW(ue),Ri=Te+1;if(Y.status!=="FAILED")return {...Y,runAttemptId:Ae,parameters:M,test:se,filePath:se.relativeFilePath,startedAt:j,lastAttemptStartedAt:Ie,finishedAt:_t,attempts:Ri,baseUrl:d,outputs:go,isFlake:pa,quarantined:N,quarantinedMetadata:k,usedRemoteBrowser:B};let rs=Y.failedStepResult,Bo=rs?.message||"Unknown failure",Qn=rs?.failureReason??$V(Bo)??"UnknownError",wi=ge.child({failureReason:Qn,errorMessage:Bo,numAttempts:(te+1).toString(),name:se.name});if(Te<te){wi.warn(`Retrying failed execution attempt for run: ${Bo}`);continue}wi.error({usedRemoteBrowser:B},`Test failed after all exhausting attempts: ${Bo}`);let Yo=new Error(Bo),vr={errorMessage:Bo,errorStack:Yo.stack},Ii;if(X.ai?.classification?.enabled===!0){let Zn=rs?.failureClassification;Zn||(e.onStepStart?.(Zc),Zn=await L_({runTracer:I,runGroupTracer:_,outputDir:e.outputDir,orgId:p,project:s,generator:c,apiClient:l,logger:R,testPlatform:"web",aiSettings:X.ai,captureEvent:gu,abortSignal:e.abortSignal,failedStepMessage:rs?.message})),Zn&&(Ii=Zn.classification.category,Qn=Zn.classification.category,vr.classification={reason:Zn.classification.category,secondaryCategories:Zn.classification.secondaryCategories,summary:Zn.classification.reasoning,recoverable:Zn.classification.recoverable,confidence:Zn.classification.confidence,action:Zn.action,citations:Zn.classification.citations,source:"v2"});}else if(ee){let Zn;try{if(Y.results&&Y.results.length>0){e.onStepStart?.(Zc);let{classification:U,aiFailureReason:fe}=await YQ({logger:ge,browserStateStorage:je,generator:c,fullResults:Y,failureReason:Qn,error:Yo,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Zn=U,Ii=fe;}}catch(U){ge.warn({err:U},"Failed to classify test results");}Zn&&(vr.classification=Zn,Qn=Ii??Qn,vr.classification.source="v1");}return {...Y,runAttemptId:Ae,parameters:M,failureDetails:vr,failureReason:Qn,test:se,filePath:se.relativeFilePath,startedAt:j,lastAttemptStartedAt:Ie,finishedAt:_t,attempts:Te+1,baseUrl:d,outputs:go,quarantined:N,quarantinedMetadata:k,usedRemoteBrowser:B}}catch(Ve){let $e=`Encountered fatal platform error while running test '${se.name}'`;return ge.error({err:Ve},$e),C.error({err:Ve},$e),await je.finish({logger:ge,result:{status:"FAILED"}}),Que({err:Qa(Ve),parameters:M,test:se,failureReason:oe.reasonFor(Ve,"InternalPlatformError"),startedAt:j,lastAttemptStartedAt:Ie,attempts:Te+1,quarantined:N,quarantinedMetadata:k,runAttemptId:Ae,baseUrl:d,usedRemoteBrowser:B})}}throw new Error("This code should not be reachable")}function Que({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 Zue=3e4;async function vS({timeoutMinutes:e,cancel:t,run:n}){let o=()=>void t("SIGINT received"),r=()=>void t("SIGTERM received");TS(),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 ES=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 xe(Promise.allSettled(Object.values(this.runQueue).map(r=>r.promise)),{milliseconds:Zue}).catch(()=>{this.params.runGroupLogger.warn(`Graceful shutdown timeout of ${Zue}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:A,browserTypeOverride:v,remoteBrowserOverride:w,onResult:I,onFatal:_}=this.params,R=0,x=true;for(;x;){let O=Object.values(this.runQueue);if(O.length===n&&await Promise.race(O.map(ee=>ee.promise)),this.cancelled){x=false;continue}let N=await t();if(N===void 0){x=false;continue}let k=`test-${R++}`,W={...N,startedAt:new Date},X=new AbortController;this.runQueue[k]={done:false,activeRun:W,abortController:X,promise:(async({inputs:ee,quarantined:j,quarantinedMetadata:V,testDefinition:M,snapshot:J,runId:B})=>{let D=M.relativeFilePath.includes("..")?M.fullFilePath:M.relativeFilePath;o.onTestBegin(D);let Y=i.child({testId:M.id,runId:B}),te=new Md({logger:Y,reporter:new Gd(l),runType:"test-run",runId:B,testMetadata:M,suiteMetadata:void 0,runner:"test-runner"});try{let ue=await Xue({testDefinition:M,snapshot:J,project:a,testInputs:ee,quarantined:j,quarantinedMetadata:V,orgId:d,userId:u,runId:B,devicePixelRatio:p,apiClient:l,runGroupTracer:r,outputDir:m,generator:c,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:S,logUpdate:(Te,Ae)=>o.onTestStatus(D,Te,Ae),...z9(o,D),logger:Y,gitMetadata:T,cacheOptions:A,usageTracker:te,browserTypeOverride:v,remoteBrowserOverride:w,recordVideo:this.params.recordVideo,abortSignal:X.signal});o.onTestEnd(D,ue.status,{recovered:ue.status==="PASSED"&&!!ue.failureRecoveryDetails?.attempts}),this.runResults.push(ue),I?.(ue);}catch(ue){let Te=`Encountered unexpected fatal error when running test '${M.name}'`;Y.error({err:ue},Te),C.error({err:ue},Te),Wu(ue),_?.(ue),await this.cancel("Fatal error occurred",false);}finally{let ue=this.runQueue[k];ue&&(ue.done=true),await te.flush(s),delete this.runQueue[k];}})(W)};}return await Promise.allSettled(Object.values(this.runQueue).map(O=>O.promise)),{runResults:this.runResults,cancelledRunsById:this.cancelledRunsById,cancelled:this.cancelled,cancellationReason:this.cancellationReason}}};var V8e=200,z8e=new Set(MV),W8e=new Set(["PASSED","FAILED","CANCELLED"]);function tpe(e){return e.length}function pO(e){return e.filter(t=>z8e.has(t.status)).length}var YE=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});}},uO=class{constructor(t,n,o){this.runGroupId=n;this.logger=o;this.filePath=io__default.join(t,WJ);}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 YE(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<V8e)return;this.lastWriteMs=n;let o=[...this.runs.values()],r={schemaVersion:qJ,runGroupId:this.runGroupId,status:this.runGroupStatus,totalRuns:o.length,completedRuns:o.filter(s=>W8e.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{ko__default.writeFileSync(i,JSON.stringify(r,null,2)),ko__default.renameSync(i,this.filePath);}catch(s){this.logger.warn({err:s},"Failed to write run progress file");}}};function iG(e){return createHash("sha1").update(e).digest("hex")}var K8e=["tab","view","mode","step"],Y8e=[/^[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 J8e(e){return Y8e.some(t=>t.test(e))}function npe(e,t={}){let n;try{n=new URL(e);}catch{return e}let o=new Set(t.queryAllowlist??K8e),i=n.pathname.split("/").map(c=>c.length>0&&J8e(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 X8e=new Set(["id","name","role","type","href","for","placeholder","aria-label","data-testid"]),Q8e=/^[A-Za-z0-9_-]{16,256}$|^:r[0-9a-z]{1,32}:$/,Z8e=[/\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],ope=new Set(["h1","h2","h3","h4","h5","h6"]),e9e=new Set(["input","select","textarea"]);function t9e(e){let t=e;for(let n of Z8e)t=t.replace(n,"{id}");return t}function rpe(e){return t9e(e).toLowerCase().replace(/\s+/g," ").trim().replace(/[.,:;!?]+$/u,"").replace(/\s*\d+\s*$/u,"").trim()}function n9e(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 o9e(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":Q8e.test(t)?"@gen":rpe(t)}function ipe(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=>X8e.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=o9e(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"||ope.has(o)?n.tokens.push(`label=${rpe(a)}`):n.tokens.push(n9e(a))),(o==="button"||r==="button")&&(n.counts.buttons+=1),(o==="a"||r==="link")&&(n.counts.links+=1),(e9e.has(o)||r==="textbox"||r==="combobox")&&(n.counts.formFields+=1),(ope.has(o)||r==="heading")&&(n.counts.headings+=1);for(let l of e.children??[])ipe(l,t+1,n);}function spe(e){let t={tokens:[],counts:{buttons:0,links:0,formFields:0,headings:0}};return ipe(e,0,t),{tokens:t.tokens,counts:t.counts}}function ape(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 mO=128,r9e=4294967295,i9e=(()=>{let e=[];for(let t=0;t<mO;t++)e.push(ape(`perm:${t}`,0));return e})();function lpe(e){let t=new Uint32Array(mO);for(let o=0;o<mO;o++)t[o]=r9e;let n=new Set(e);for(let o of n)for(let r=0;r<mO;r++){let i=ape(o,i9e[r]);i<t[r]&&(t[r]=i);}return t}var a9e=32;function sG(e){let t=npe(e.url,{queryAllowlist:e.queryAllowlist}),{tokens:n,counts:o}=spe(e.dom),r=[`url:${t}`,`counts:buttons=${o.buttons}`,`counts:links=${o.links}`,`counts:formFields=${o.formFields}`,`counts:headings=${o.headings}`,...n],i=lpe(r),s=Buffer.from(i.buffer,i.byteOffset,i.byteLength);return {fingerprintHash:createHash$1("sha256").update(s).digest("hex").slice(0,a9e),minhash:Array.from(i),canonicalUrl:t}}var l9e=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]),Xn="\uFFFD",L;(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";})(L||(L={}));var ts={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function hO(e){return e>=55296&&e<=57343}function cpe(e){return e>=56320&&e<=57343}function dpe(e,t){return (e-55296)*1024+9216+t}function gO(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function fO(e){return e>=64976&&e<=65007||l9e.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 d9e=65536,yO=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=d9e,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(cpe(n))return this.pos++,this._addGap(),dpe(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=true,L.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,L.EOF;let o=this.html.charCodeAt(n);return o===L.CARRIAGE_RETURN?L.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,L.EOF;let t=this.html.charCodeAt(this.pos);return t===L.CARRIAGE_RETURN?(this.isEol=true,this.skipNextNewLine=true,L.LINE_FEED):t===L.LINE_FEED&&(this.isEol=true,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=false,this._addGap(),this.advance()):(this.skipNextNewLine=false,hO(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===L.LINE_FEED||t===L.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){gO(t)?this._err(ce.controlCharacterInInputStream):fO(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 Zt;(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";})(Zt||(Zt={}));function SO(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 p9e=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 upe(e){return e>=55296&&e<=57343||e>1114111?65533:p9e.get(e)??e}function ppe(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 aG=ppe("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 Ai;(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";})(Ai||(Ai={}));var wo;(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";})(wo||(wo={}));var mpe=32;function lG(e){return e>=wo.ZERO&&e<=wo.NINE}function m9e(e){return e>=wo.UPPER_A&&e<=wo.UPPER_F||e>=wo.LOWER_A&&e<=wo.LOWER_F}function h9e(e){return e>=wo.UPPER_A&&e<=wo.UPPER_Z||e>=wo.LOWER_A&&e<=wo.LOWER_Z||lG(e)}function g9e(e){return e===wo.EQUALS||h9e(e)}var Fr;(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";})(Fr||(Fr={}));var Xc;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute";})(Xc||(Xc={}));var bO=class{decodeTree;emitCodePoint;errors;constructor(t,n,o){this.decodeTree=t,this.emitCodePoint=n,this.errors=o;}state=Fr.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Xc.Strict;runConsumed=0;startEntity(t){this.decodeMode=t,this.state=Fr.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0;}write(t,n){switch(this.state){case Fr.EntityStart:return t.charCodeAt(n)===wo.NUM?(this.state=Fr.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=Fr.NamedEntity,this.stateNamedEntity(t,n));case Fr.NumericStart:return this.stateNumericStart(t,n);case Fr.NumericDecimal:return this.stateNumericDecimal(t,n);case Fr.NumericHex:return this.stateNumericHex(t,n);case Fr.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|mpe)===wo.LOWER_X?(this.state=Fr.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=Fr.NumericDecimal,this.stateNumericDecimal(t,n))}stateNumericHex(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(lG(o)||m9e(o)){let r=o<=wo.NINE?o-wo.ZERO:(o|mpe)-wo.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(lG(o))this.result=this.result*10+(o-wo.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===wo.SEMI)this.consumed+=1;else if(this.decodeMode===Xc.Strict)return 0;return this.emitCodePoint(upe(this.result),this.consumed),this.errors&&(t!==wo.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){let{decodeTree:o}=this,r=o[this.treeIndex],i=(r&Ai.VALUE_LENGTH)>>14;for(;n<t.length;){if(i===0&&r&Ai.FLAG13){let a=(r&Ai.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let l=r&Ai.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&Ai.VALUE_LENGTH)>>14;}if(n>=t.length)break;let s=t.charCodeAt(n);if(s===wo.SEMI&&i!==0&&r&Ai.FLAG13)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=f9e(o,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return this.result===0||this.decodeMode===Xc.Attribute&&(i===0||g9e(s))?0:this.emitNotTerminatedNamedEntity();if(r=o[this.treeIndex],i=(r&Ai.VALUE_LENGTH)>>14,i!==0){if(s===wo.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==Xc.Strict&&!(r&Ai.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]&Ai.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]&~(Ai.VALUE_LENGTH|Ai.FLAG13):r[t+1],o),n===3&&this.emitCodePoint(r[t+2],o),o}end(){switch(this.state){case Fr.NamedEntity:return this.result!==0&&(this.decodeMode!==Xc.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Fr.NumericDecimal:return this.emitNumericEntity(0,2);case Fr.NumericHex:return this.emitNumericEntity(0,3);case Fr.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Fr.EntityStart:return 0}}};function f9e(e,t,n,o){let r=(t&Ai.BRANCH_LENGTH)>>7,i=t&Ai.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 Ce;(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/";})(Ce||(Ce={}));var fu;(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";})(fu||(fu={}));var ns;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks";})(ns||(ns={}));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 y9e=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 $h(e){var t;return (t=y9e.get(e))!==null&&t!==void 0?t:b.UNKNOWN}var Me=b,hpe={[Ce.HTML]:new Set([Me.ADDRESS,Me.APPLET,Me.AREA,Me.ARTICLE,Me.ASIDE,Me.BASE,Me.BASEFONT,Me.BGSOUND,Me.BLOCKQUOTE,Me.BODY,Me.BR,Me.BUTTON,Me.CAPTION,Me.CENTER,Me.COL,Me.COLGROUP,Me.DD,Me.DETAILS,Me.DIR,Me.DIV,Me.DL,Me.DT,Me.EMBED,Me.FIELDSET,Me.FIGCAPTION,Me.FIGURE,Me.FOOTER,Me.FORM,Me.FRAME,Me.FRAMESET,Me.H1,Me.H2,Me.H3,Me.H4,Me.H5,Me.H6,Me.HEAD,Me.HEADER,Me.HGROUP,Me.HR,Me.HTML,Me.IFRAME,Me.IMG,Me.INPUT,Me.LI,Me.LINK,Me.LISTING,Me.MAIN,Me.MARQUEE,Me.MENU,Me.META,Me.NAV,Me.NOEMBED,Me.NOFRAMES,Me.NOSCRIPT,Me.OBJECT,Me.OL,Me.P,Me.PARAM,Me.PLAINTEXT,Me.PRE,Me.SCRIPT,Me.SECTION,Me.SELECT,Me.SOURCE,Me.STYLE,Me.SUMMARY,Me.TABLE,Me.TBODY,Me.TD,Me.TEMPLATE,Me.TEXTAREA,Me.TFOOT,Me.TH,Me.THEAD,Me.TITLE,Me.TR,Me.TRACK,Me.UL,Me.WBR,Me.XMP]),[Ce.MATHML]:new Set([Me.MI,Me.MO,Me.MN,Me.MS,Me.MTEXT,Me.ANNOTATION_XML]),[Ce.SVG]:new Set([Me.TITLE,Me.FOREIGN_OBJECT,Me.DESC]),[Ce.XLINK]:new Set,[Ce.XML]:new Set,[Ce.XMLNS]:new Set},JE=new Set([Me.H1,Me.H2,Me.H3,Me.H4,Me.H5,Me.H6]);new Set([ie.STYLE,ie.SCRIPT,ie.XMP,ie.IFRAME,ie.NOEMBED,ie.NOFRAMES,ie.PLAINTEXT]);var H;(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";})(H||(H={}));var Ei={DATA:H.DATA,RCDATA:H.RCDATA,RAWTEXT:H.RAWTEXT,SCRIPT_DATA:H.SCRIPT_DATA,PLAINTEXT:H.PLAINTEXT,CDATA_SECTION:H.CDATA_SECTION};function b9e(e){return e>=L.DIGIT_0&&e<=L.DIGIT_9}function XE(e){return e>=L.LATIN_CAPITAL_A&&e<=L.LATIN_CAPITAL_Z}function T9e(e){return e>=L.LATIN_SMALL_A&&e<=L.LATIN_SMALL_Z}function Zp(e){return T9e(e)||XE(e)}function gpe(e){return Zp(e)||b9e(e)}function TO(e){return e+32}function ype(e){return e===L.SPACE||e===L.LINE_FEED||e===L.TABULATION||e===L.FORM_FEED}function fpe(e){return ype(e)||e===L.SOLIDUS||e===L.GREATER_THAN_SIGN}function A9e(e){return e===L.NULL?ce.nullCharacterReference:e>1114111?ce.characterReferenceOutsideUnicodeRange:hO(e)?ce.surrogateCharacterReference:fO(e)?ce.noncharacterCharacterReference:gO(e)||e===L.CARRIAGE_RETURN?ce.controlCharacterReference:null}var QE=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=H.DATA,this.returnState=H.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new yO(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new bO(aG,(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=A9e(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:Zt.START_TAG,tagName:"",tagID:b.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(1)};}_createEndTagToken(){this.currentToken={type:Zt.END_TAG,tagName:"",tagID:b.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(2)};}_createCommentToken(t){this.currentToken={type:Zt.COMMENT,data:"",location:this.getCurrentLocation(t)};}_createDoctypeToken(t){this.currentToken={type:Zt.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(SO(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=$h(t.tagName),t.type===Zt.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 Zt.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Zt.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Zt.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:Zt.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=ype(t)?Zt.WHITESPACE_CHARACTER:t===L.NULL?Zt.NULL_CHARACTER:Zt.CHARACTER;this._appendCharToCurrentCharacterToken(n,t<65536?String.fromCharCode(t):String.fromCodePoint(t));}_emitChars(t){this._appendCharToCurrentCharacterToken(Zt.CHARACTER,t);}_startCharacterReference(){this.returnState=this.state,this.state=H.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Xc.Attribute:Xc.Legacy);}_isCharacterReferenceInAttribute(){return this.returnState===H.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===H.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===H.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t);}_callState(t){switch(this.state){case H.DATA:{this._stateData(t);break}case H.RCDATA:{this._stateRcdata(t);break}case H.RAWTEXT:{this._stateRawtext(t);break}case H.SCRIPT_DATA:{this._stateScriptData(t);break}case H.PLAINTEXT:{this._statePlaintext(t);break}case H.TAG_OPEN:{this._stateTagOpen(t);break}case H.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case H.TAG_NAME:{this._stateTagName(t);break}case H.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case H.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case H.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case H.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case H.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case H.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case H.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case H.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case H.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case H.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case H.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case H.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case H.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case H.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case H.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case H.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case H.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case H.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case H.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case H.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case H.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case H.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case H.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case H.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case H.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case H.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case H.BOGUS_COMMENT:{this._stateBogusComment(t);break}case H.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case H.COMMENT_START:{this._stateCommentStart(t);break}case H.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case H.COMMENT:{this._stateComment(t);break}case H.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case H.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case H.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case H.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case H.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case H.COMMENT_END:{this._stateCommentEnd(t);break}case H.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case H.DOCTYPE:{this._stateDoctype(t);break}case H.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case H.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case H.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case H.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case H.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case H.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case H.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case H.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case H.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case H.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case H.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case H.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case H.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case H.CDATA_SECTION:{this._stateCdataSection(t);break}case H.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case H.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case H.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case H.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case L.LESS_THAN_SIGN:{this.state=H.TAG_OPEN;break}case L.AMPERSAND:{this._startCharacterReference();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitCodePoint(t);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRcdata(t){switch(t){case L.AMPERSAND:{this._startCharacterReference();break}case L.LESS_THAN_SIGN:{this.state=H.RCDATA_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRawtext(t){switch(t){case L.LESS_THAN_SIGN:{this.state=H.RAWTEXT_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptData(t){switch(t){case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_statePlaintext(t){switch(t){case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateTagOpen(t){if(Zp(t))this._createStartTagToken(),this.state=H.TAG_NAME,this._stateTagName(t);else switch(t){case L.EXCLAMATION_MARK:{this.state=H.MARKUP_DECLARATION_OPEN;break}case L.SOLIDUS:{this.state=H.END_TAG_OPEN;break}case L.QUESTION_MARK:{this._err(ce.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=H.BOGUS_COMMENT,this._stateBogusComment(t);break}case L.EOF:{this._err(ce.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(ce.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=H.DATA,this._stateData(t);}}_stateEndTagOpen(t){if(Zp(t))this._createEndTagToken(),this.state=H.TAG_NAME,this._stateTagName(t);else switch(t){case L.GREATER_THAN_SIGN:{this._err(ce.missingEndTagName),this.state=H.DATA;break}case L.EOF:{this._err(ce.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(ce.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=H.BOGUS_COMMENT,this._stateBogusComment(t);}}_stateTagName(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BEFORE_ATTRIBUTE_NAME;break}case L.SOLIDUS:{this.state=H.SELF_CLOSING_START_TAG;break}case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentTagToken();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.tagName+=Xn;break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(XE(t)?TO(t):t);}}_stateRcdataLessThanSign(t){t===L.SOLIDUS?this.state=H.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=H.RCDATA,this._stateRcdata(t));}_stateRcdataEndTagOpen(t){Zp(t)?(this.state=H.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=H.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 L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=H.BEFORE_ATTRIBUTE_NAME,false;case L.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=H.SELF_CLOSING_START_TAG,false;case L.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=H.DATA,false;default:return !this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=H.RCDATA,this._stateRcdata(t));}_stateRawtextLessThanSign(t){t===L.SOLIDUS?this.state=H.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=H.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagOpen(t){Zp(t)?(this.state=H.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=H.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=H.RAWTEXT,this._stateRawtext(t));}_stateScriptDataLessThanSign(t){switch(t){case L.SOLIDUS:{this.state=H.SCRIPT_DATA_END_TAG_OPEN;break}case L.EXCLAMATION_MARK:{this.state=H.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=H.SCRIPT_DATA,this._stateScriptData(t);}}_stateScriptDataEndTagOpen(t){Zp(t)?(this.state=H.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=H.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=H.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStart(t){t===L.HYPHEN_MINUS?(this.state=H.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=H.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStartDash(t){t===L.HYPHEN_MINUS?(this.state=H.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=H.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscaped(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataEscapedDash(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.state=H.SCRIPT_DATA_ESCAPED,this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=H.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedDashDash(t){switch(t){case L.HYPHEN_MINUS:{this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case L.GREATER_THAN_SIGN:{this.state=H.SCRIPT_DATA,this._emitChars(">");break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.state=H.SCRIPT_DATA_ESCAPED,this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=H.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedLessThanSign(t){t===L.SOLIDUS?this.state=H.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Zp(t)?(this._emitChars("<"),this.state=H.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=H.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagOpen(t){Zp(t)?(this.state=H.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=H.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=H.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(ts.SCRIPT,false)&&fpe(this.preprocessor.peek(ts.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<ts.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED;}else this._ensureHibernation()||(this.state=H.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscaped(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDash(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case L.HYPHEN_MINUS:{this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case L.GREATER_THAN_SIGN:{this.state=H.SCRIPT_DATA,this._emitChars(">");break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedLessThanSign(t){t===L.SOLIDUS?(this.state=H.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(ts.SCRIPT,false)&&fpe(this.preprocessor.peek(ts.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<ts.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=H.SCRIPT_DATA_ESCAPED;}else this._ensureHibernation()||(this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateBeforeAttributeName(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.SOLIDUS:case L.GREATER_THAN_SIGN:case L.EOF:{this.state=H.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case L.EQUALS_SIGN:{this._err(ce.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=H.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=H.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateAttributeName(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:case L.SOLIDUS:case L.GREATER_THAN_SIGN:case L.EOF:{this._leaveAttrName(),this.state=H.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case L.EQUALS_SIGN:{this._leaveAttrName(),this.state=H.BEFORE_ATTRIBUTE_VALUE;break}case L.QUOTATION_MARK:case L.APOSTROPHE:case L.LESS_THAN_SIGN:{this._err(ce.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.name+=Xn;break}default:this.currentAttr.name+=String.fromCodePoint(XE(t)?TO(t):t);}}_stateAfterAttributeName(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.SOLIDUS:{this.state=H.SELF_CLOSING_START_TAG;break}case L.EQUALS_SIGN:{this.state=H.BEFORE_ATTRIBUTE_VALUE;break}case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentTagToken();break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=H.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateBeforeAttributeValue(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.QUOTATION_MARK:{this.state=H.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case L.APOSTROPHE:{this.state=H.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingAttributeValue),this.state=H.DATA,this.emitCurrentTagToken();break}default:this.state=H.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t);}}_stateAttributeValueDoubleQuoted(t){switch(t){case L.QUOTATION_MARK:{this.state=H.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case L.AMPERSAND:{this._startCharacterReference();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Xn;break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueSingleQuoted(t){switch(t){case L.APOSTROPHE:{this.state=H.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case L.AMPERSAND:{this._startCharacterReference();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Xn;break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueUnquoted(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this._leaveAttrValue(),this.state=H.BEFORE_ATTRIBUTE_NAME;break}case L.AMPERSAND:{this._startCharacterReference();break}case L.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=H.DATA,this.emitCurrentTagToken();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Xn;break}case L.QUOTATION_MARK:case L.APOSTROPHE:case L.LESS_THAN_SIGN:case L.EQUALS_SIGN:case L.GRAVE_ACCENT:{this._err(ce.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAfterAttributeValueQuoted(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this._leaveAttrValue(),this.state=H.BEFORE_ATTRIBUTE_NAME;break}case L.SOLIDUS:{this._leaveAttrValue(),this.state=H.SELF_CLOSING_START_TAG;break}case L.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=H.DATA,this.emitCurrentTagToken();break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._err(ce.missingWhitespaceBetweenAttributes),this.state=H.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateSelfClosingStartTag(t){switch(t){case L.GREATER_THAN_SIGN:{let n=this.currentToken;n.selfClosing=true,this.state=H.DATA,this.emitCurrentTagToken();break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._err(ce.unexpectedSolidusInTag),this.state=H.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateBogusComment(t){let n=this.currentToken;switch(t){case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentComment(n);break}case L.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.data+=Xn;break}default:n.data+=String.fromCodePoint(t);}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(ts.DASH_DASH,true)?(this._createCommentToken(ts.DASH_DASH.length+1),this.state=H.COMMENT_START):this._consumeSequenceIfMatch(ts.DOCTYPE,false)?(this.currentLocation=this.getCurrentLocation(ts.DOCTYPE.length+1),this.state=H.DOCTYPE):this._consumeSequenceIfMatch(ts.CDATA_START,true)?this.inForeignNode?this.state=H.CDATA_SECTION:(this._err(ce.cdataInHtmlContent),this._createCommentToken(ts.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=H.BOGUS_COMMENT):this._ensureHibernation()||(this._err(ce.incorrectlyOpenedComment),this._createCommentToken(2),this.state=H.BOGUS_COMMENT,this._stateBogusComment(t));}_stateCommentStart(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.COMMENT_START_DASH;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptClosingOfEmptyComment),this.state=H.DATA;let n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=H.COMMENT,this._stateComment(t);}}_stateCommentStartDash(t){let n=this.currentToken;switch(t){case L.HYPHEN_MINUS:{this.state=H.COMMENT_END;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptClosingOfEmptyComment),this.state=H.DATA,this.emitCurrentComment(n);break}case L.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=H.COMMENT,this._stateComment(t);}}_stateComment(t){let n=this.currentToken;switch(t){case L.HYPHEN_MINUS:{this.state=H.COMMENT_END_DASH;break}case L.LESS_THAN_SIGN:{n.data+="<",this.state=H.COMMENT_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.data+=Xn;break}case L.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 L.EXCLAMATION_MARK:{n.data+="!",this.state=H.COMMENT_LESS_THAN_SIGN_BANG;break}case L.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=H.COMMENT,this._stateComment(t);}}_stateCommentLessThanSignBang(t){t===L.HYPHEN_MINUS?this.state=H.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=H.COMMENT,this._stateComment(t));}_stateCommentLessThanSignBangDash(t){t===L.HYPHEN_MINUS?this.state=H.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=H.COMMENT_END_DASH,this._stateCommentEndDash(t));}_stateCommentLessThanSignBangDashDash(t){t!==L.GREATER_THAN_SIGN&&t!==L.EOF&&this._err(ce.nestedComment),this.state=H.COMMENT_END,this._stateCommentEnd(t);}_stateCommentEndDash(t){let n=this.currentToken;switch(t){case L.HYPHEN_MINUS:{this.state=H.COMMENT_END;break}case L.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=H.COMMENT,this._stateComment(t);}}_stateCommentEnd(t){let n=this.currentToken;switch(t){case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentComment(n);break}case L.EXCLAMATION_MARK:{this.state=H.COMMENT_END_BANG;break}case L.HYPHEN_MINUS:{n.data+="-";break}case L.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=H.COMMENT,this._stateComment(t);}}_stateCommentEndBang(t){let n=this.currentToken;switch(t){case L.HYPHEN_MINUS:{n.data+="--!",this.state=H.COMMENT_END_DASH;break}case L.GREATER_THAN_SIGN:{this._err(ce.incorrectlyClosedComment),this.state=H.DATA,this.emitCurrentComment(n);break}case L.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=H.COMMENT,this._stateComment(t);}}_stateDoctype(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BEFORE_DOCTYPE_NAME;break}case L.GREATER_THAN_SIGN:{this.state=H.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case L.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=H.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);}}_stateBeforeDoctypeName(t){if(XE(t))this._createDoctypeToken(String.fromCharCode(TO(t))),this.state=H.DOCTYPE_NAME;else switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.NULL:{this._err(ce.unexpectedNullCharacter),this._createDoctypeToken(Xn),this.state=H.DOCTYPE_NAME;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeName),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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=H.DOCTYPE_NAME;}}_stateDoctypeName(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.AFTER_DOCTYPE_NAME;break}case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.name+=Xn;break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(XE(t)?TO(t):t);}}_stateAfterDoctypeName(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(ts.PUBLIC,false)?this.state=H.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(ts.SYSTEM,false)?this.state=H.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(ce.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t));}}_stateAfterDoctypePublicKeyword(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case L.QUOTATION_MARK:{this._err(ce.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=H.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{this._err(ce.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=H.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.QUOTATION_MARK:{n.publicId="",this.state=H.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{n.publicId="",this.state=H.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypePublicIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case L.QUOTATION_MARK:{this.state=H.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.publicId+=Xn;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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 L.APOSTROPHE:{this.state=H.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.publicId+=Xn;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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 L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.QUOTATION_MARK:{this._err(ce.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{this._err(ce.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.QUOTATION_MARK:{n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateAfterDoctypeSystemKeyword(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case L.QUOTATION_MARK:{this._err(ce.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{this._err(ce.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.QUOTATION_MARK:{n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypeSystemIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case L.QUOTATION_MARK:{this.state=H.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.systemId+=Xn;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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 L.APOSTROPHE:{this.state=H.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.systemId+=Xn;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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 L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBogusDoctype(t){let n=this.currentToken;switch(t){case L.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.NULL:{this._err(ce.unexpectedNullCharacter);break}case L.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case L.RIGHT_SQUARE_BRACKET:{this.state=H.CDATA_SECTION_BRACKET;break}case L.EOF:{this._err(ce.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateCdataSectionBracket(t){t===L.RIGHT_SQUARE_BRACKET?this.state=H.CDATA_SECTION_END:(this._emitChars("]"),this.state=H.CDATA_SECTION,this._stateCdataSection(t));}_stateCdataSectionEnd(t){switch(t){case L.GREATER_THAN_SIGN:{this.state=H.DATA;break}case L.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=H.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(L.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&gpe(this.preprocessor.peek(1))?H.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState;}_stateAmbiguousAmpersand(t){gpe(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===L.SEMICOLON&&this._err(ce.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t));}};var Ape=new Set([b.DD,b.DT,b.LI,b.OPTGROUP,b.OPTION,b.P,b.RB,b.RP,b.RT,b.RTC]),Spe=new Set([...Ape,b.CAPTION,b.COLGROUP,b.TBODY,b.TD,b.TFOOT,b.TH,b.THEAD,b.TR]),AO=new Set([b.APPLET,b.CAPTION,b.HTML,b.MARQUEE,b.OBJECT,b.TABLE,b.TD,b.TEMPLATE,b.TH]),E9e=new Set([...AO,b.OL,b.UL]),v9e=new Set([...AO,b.BUTTON]),bpe=new Set([b.ANNOTATION_XML,b.MI,b.MN,b.MO,b.MS,b.MTEXT]),Tpe=new Set([b.DESC,b.FOREIGN_OBJECT,b.TITLE]),C9e=new Set([b.TR,b.TEMPLATE,b.HTML]),R9e=new Set([b.TBODY,b.TFOOT,b.THEAD,b.TEMPLATE,b.HTML]),w9e=new Set([b.TABLE,b.TEMPLATE,b.HTML]),I9e=new Set([b.TD,b.TH]),EO=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)===Ce.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])!==Ce.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(JE,Ce.HTML);}popUntilTableCellPopped(){this.popUntilPopped(I9e,Ce.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(w9e,Ce.HTML);}clearBackToTableBodyContext(){this.clearBackTo(R9e,Ce.HTML);}clearBackToTableRowContext(){this.clearBackTo(C9e,Ce.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 Ce.HTML:{if(r===t)return true;if(n.has(r))return false;break}case Ce.SVG:{if(Tpe.has(r))return false;break}case Ce.MATHML:{if(bpe.has(r))return false;break}}}return true}hasInScope(t){return this.hasInDynamicScope(t,AO)}hasInListItemScope(t){return this.hasInDynamicScope(t,E9e)}hasInButtonScope(t){return this.hasInDynamicScope(t,v9e)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){let n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case Ce.HTML:{if(JE.has(n))return true;if(AO.has(n))return false;break}case Ce.SVG:{if(Tpe.has(n))return false;break}case Ce.MATHML:{if(bpe.has(n))return false;break}}}return true}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===Ce.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])===Ce.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])===Ce.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&&Ape.has(this.currentTagId);)this.pop();}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&Spe.has(this.currentTagId);)this.pop();}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&Spe.has(this.currentTagId);)this.pop();}};var Fl;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element";})(Fl||(Fl={}));var Epe={type:Fl.Marker},vO=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===Fl.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(Epe);}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:Fl.Element,element:t,token:n});}insertElementAfterBookmark(t,n){let o=this.entries.indexOf(this.bookmark);this.entries.splice(o,0,{type:Fl.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(Epe);t===-1?this.entries.length=0:this.entries.splice(0,t+1);}getElementEntryInScopeWithTagName(t){let n=this.entries.find(o=>o.type===Fl.Marker||this.treeAdapter.getTagName(o.element)===t);return n&&n.type===Fl.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===Fl.Element&&n.element===t)}};var Bl={createDocument(){return {nodeName:"#document",mode:ns.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};Bl.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(Bl.isTextNode(n)){n.value+=t;return}}Bl.appendChild(e,Bl.createTextNode(t));},insertTextBefore(e,t,n){let o=e.childNodes[e.childNodes.indexOf(n)-1];o&&Bl.isTextNode(o)?o.value+=t:Bl.insertBefore(e,Bl.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 Cpe="html",x9e="about:legacy-compat",_9e="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",Rpe=["+//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//"],P9e=[...Rpe,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],O9e=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),wpe=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],M9e=[...wpe,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function vpe(e,t){return t.some(n=>e.startsWith(n))}function Ipe(e){return e.name===Cpe&&e.publicId===null&&(e.systemId===null||e.systemId===x9e)}function xpe(e){if(e.name!==Cpe)return ns.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===_9e)return ns.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),O9e.has(n))return ns.QUIRKS;let o=t===null?P9e:Rpe;if(vpe(n,o))return ns.QUIRKS;if(o=t===null?wpe:M9e,vpe(n,o))return ns.LIMITED_QUIRKS}return ns.NO_QUIRKS}var _pe={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},L9e="definitionurl",k9e="definitionURL",D9e=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])),F9e=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:Ce.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:Ce.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:Ce.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:Ce.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:Ce.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:Ce.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:Ce.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:Ce.XML}],["xml:space",{prefix:"xml",name:"space",namespace:Ce.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:Ce.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:Ce.XMLNS}]]),B9e=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])),U9e=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 Ppe(e){let t=e.tagID;return t===b.FONT&&e.attrs.some(({name:o})=>o===fu.COLOR||o===fu.SIZE||o===fu.FACE)||U9e.has(t)}function cG(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===L9e){e.attrs[t].name=k9e;break}}function dG(e){for(let t=0;t<e.attrs.length;t++){let n=D9e.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n);}}function CO(e){for(let t=0;t<e.attrs.length;t++){let n=F9e.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 Ope(e){let t=B9e.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=$h(e.tagName));}function H9e(e,t){return t===Ce.MATHML&&(e===b.MI||e===b.MO||e===b.MN||e===b.MS||e===b.MTEXT)}function j9e(e,t,n){if(t===Ce.MATHML&&e===b.ANNOTATION_XML){for(let o=0;o<n.length;o++)if(n[o].name===fu.ENCODING){let r=n[o].value.toLowerCase();return r===_pe.TEXT_HTML||r===_pe.APPLICATION_XML}}return t===Ce.SVG&&(e===b.FOREIGN_OBJECT||e===b.DESC||e===b.TITLE)}function Mpe(e,t,n,o){return (!o||o===Ce.HTML)&&j9e(e,t,n)||(!o||o===Ce.MATHML)&&H9e(e,t)}var G9e="hidden",$9e=8,V9e=3,z;(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";})(z||(z={}));var z9e={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Fpe=new Set([b.TABLE,b.TBODY,b.TFOOT,b.THEAD,b.TR]),Lpe={scriptingEnabled:true,sourceCodeLocationInfo:false,treeAdapter:Bl,onParseError:null},sv=class{constructor(t,n,o=null,r=null){this.fragmentContext=o,this.scriptHandler=r,this.currentToken=null,this.stopped=false,this.insertionMode=z.INITIAL,this.originalInsertionMode=z.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={...Lpe,...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 QE(this.options,this),this.activeFormattingElements=new vO(this.treeAdapter),this.fragmentContextID=o?$h(this.treeAdapter.getTagName(o)):b.UNKNOWN,this._setContextModes(o??this.document,this.fragmentContextID),this.openElements=new EO(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={...Lpe,...n};t??(t=o.treeAdapter.createElement(ie.TEMPLATE,Ce.HTML,[]));let r=o.treeAdapter.createElement("documentmock",Ce.HTML,[]),i=new this(o,r,t);return i.fragmentContextID===b.TEMPLATE&&i.tmplInsertionModeStack.unshift(z.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:z9e,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)===Ce.HTML;this.currentNotInHTML=!o,this.tokenizer.inForeignNode=!o&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t);}_switchToTextParsing(t,n){this._insertElement(t,Ce.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=z.TEXT;}switchToPlaintextParsing(){this.insertionMode=z.TEXT,this.originalInsertionMode=z.IN_BODY,this.tokenizer.state=Ei.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)!==Ce.HTML))switch(this.fragmentContextID){case b.TITLE:case b.TEXTAREA:{this.tokenizer.state=Ei.RCDATA;break}case b.STYLE:case b.XMP:case b.IFRAME:case b.NOEMBED:case b.NOFRAMES:case b.NOSCRIPT:{this.tokenizer.state=Ei.RAWTEXT;break}case b.SCRIPT:{this.tokenizer.state=Ei.SCRIPT_DATA;break}case b.PLAINTEXT:{this.tokenizer.state=Ei.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,Ce.HTML,[]);this._attachElementToTree(o,null),this.openElements.push(o,n);}_insertTemplate(t){let n=this.treeAdapter.createElement(t.tagName,Ce.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,Ce.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===Zt.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)===Ce.MATHML?false:this.tokenizer.inForeignNode||(t.tagID===b.MGLYPH||t.tagID===b.MALIGNMARK)&&o!==void 0&&!this._isIntegrationPoint(o,n,Ce.HTML)}_processToken(t){switch(t.type){case Zt.CHARACTER:{this.onCharacter(t);break}case Zt.NULL_CHARACTER:{this.onNullCharacter(t);break}case Zt.COMMENT:{this.onComment(t);break}case Zt.DOCTYPE:{this.onDoctype(t);break}case Zt.START_TAG:{this._processStartTag(t);break}case Zt.END_TAG:{this.onEndTag(t);break}case Zt.EOF:{this.onEof(t);break}case Zt.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,o){let r=this.treeAdapter.getNamespaceURI(n),i=this.treeAdapter.getAttrList(n);return Mpe(t,r,i,o)}_reconstructActiveFormattingElements(){let t=this.activeFormattingElements.entries.length;if(t){let n=this.activeFormattingElements.entries.findIndex(r=>r.type===Fl.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=z.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=z.IN_ROW;return}case b.TBODY:case b.THEAD:case b.TFOOT:{this.insertionMode=z.IN_TABLE_BODY;return}case b.CAPTION:{this.insertionMode=z.IN_CAPTION;return}case b.COLGROUP:{this.insertionMode=z.IN_COLUMN_GROUP;return}case b.TABLE:{this.insertionMode=z.IN_TABLE;return}case b.BODY:{this.insertionMode=z.IN_BODY;return}case b.FRAMESET:{this.insertionMode=z.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?z.AFTER_HEAD:z.BEFORE_HEAD;return}case b.TD:case b.TH:{if(t>0){this.insertionMode=z.IN_CELL;return}break}case b.HEAD:{if(t>0){this.insertionMode=z.IN_HEAD;return}break}}this.insertionMode=z.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=z.IN_SELECT_IN_TABLE;return}}this.insertionMode=z.IN_SELECT;}_isElementCausesFosterParenting(t){return Fpe.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)===Ce.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 hpe[o].has(n)}onCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){vet(this,t);return}switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{tv(this,t);break}case z.BEFORE_HEAD:{nv(this,t);break}case z.IN_HEAD:{ov(this,t);break}case z.IN_HEAD_NO_SCRIPT:{rv(this,t);break}case z.AFTER_HEAD:{iv(this,t);break}case z.IN_BODY:case z.IN_CAPTION:case z.IN_CELL:case z.IN_TEMPLATE:{Upe(this,t);break}case z.TEXT:case z.IN_SELECT:case z.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case z.IN_TABLE:case z.IN_TABLE_BODY:case z.IN_ROW:{uG(this,t);break}case z.IN_TABLE_TEXT:{zpe(this,t);break}case z.IN_COLUMN_GROUP:{wO(this,t);break}case z.AFTER_BODY:{IO(this,t);break}case z.AFTER_AFTER_BODY:{RO(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){Eet(this,t);return}switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{tv(this,t);break}case z.BEFORE_HEAD:{nv(this,t);break}case z.IN_HEAD:{ov(this,t);break}case z.IN_HEAD_NO_SCRIPT:{rv(this,t);break}case z.AFTER_HEAD:{iv(this,t);break}case z.TEXT:{this._insertCharacters(t);break}case z.IN_TABLE:case z.IN_TABLE_BODY:case z.IN_ROW:{uG(this,t);break}case z.IN_COLUMN_GROUP:{wO(this,t);break}case z.AFTER_BODY:{IO(this,t);break}case z.AFTER_AFTER_BODY:{RO(this,t);break}}}onComment(t){if(this.skipNextNewLine=false,this.currentNotInHTML){pG(this,t);return}switch(this.insertionMode){case z.INITIAL:case z.BEFORE_HTML:case z.BEFORE_HEAD:case z.IN_HEAD:case z.IN_HEAD_NO_SCRIPT:case z.AFTER_HEAD:case z.IN_BODY:case z.IN_TABLE:case z.IN_CAPTION:case z.IN_COLUMN_GROUP:case z.IN_TABLE_BODY:case z.IN_ROW:case z.IN_CELL:case z.IN_SELECT:case z.IN_SELECT_IN_TABLE:case z.IN_TEMPLATE:case z.IN_FRAMESET:case z.AFTER_FRAMESET:{pG(this,t);break}case z.IN_TABLE_TEXT:{ev(this,t);break}case z.AFTER_BODY:{Q9e(this,t);break}case z.AFTER_AFTER_BODY:case z.AFTER_AFTER_FRAMESET:{Z9e(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=false,this.insertionMode){case z.INITIAL:{e7e(this,t);break}case z.BEFORE_HEAD:case z.IN_HEAD:case z.IN_HEAD_NO_SCRIPT:case z.AFTER_HEAD:{this._err(t,ce.misplacedDoctype);break}case z.IN_TABLE_TEXT:{ev(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)?Cet(this,t):this._startTagOutsideForeignContent(t);}_startTagOutsideForeignContent(t){switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{t7e(this,t);break}case z.BEFORE_HEAD:{o7e(this,t);break}case z.IN_HEAD:{Ul(this,t);break}case z.IN_HEAD_NO_SCRIPT:{s7e(this,t);break}case z.AFTER_HEAD:{l7e(this,t);break}case z.IN_BODY:{vi(this,t);break}case z.IN_TABLE:{CS(this,t);break}case z.IN_TABLE_TEXT:{ev(this,t);break}case z.IN_CAPTION:{ret(this,t);break}case z.IN_COLUMN_GROUP:{fG(this,t);break}case z.IN_TABLE_BODY:{PO(this,t);break}case z.IN_ROW:{OO(this,t);break}case z.IN_CELL:{aet(this,t);break}case z.IN_SELECT:{Kpe(this,t);break}case z.IN_SELECT_IN_TABLE:{det(this,t);break}case z.IN_TEMPLATE:{pet(this,t);break}case z.AFTER_BODY:{het(this,t);break}case z.IN_FRAMESET:{get(this,t);break}case z.AFTER_FRAMESET:{yet(this,t);break}case z.AFTER_AFTER_BODY:{Tet(this,t);break}case z.AFTER_AFTER_FRAMESET:{Aet(this,t);break}}}onEndTag(t){this.skipNextNewLine=false,this.currentToken=t,this.currentNotInHTML?Ret(this,t):this._endTagOutsideForeignContent(t);}_endTagOutsideForeignContent(t){switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{n7e(this,t);break}case z.BEFORE_HEAD:{r7e(this,t);break}case z.IN_HEAD:{i7e(this,t);break}case z.IN_HEAD_NO_SCRIPT:{a7e(this,t);break}case z.AFTER_HEAD:{c7e(this,t);break}case z.IN_BODY:{_O(this,t);break}case z.TEXT:{K7e(this,t);break}case z.IN_TABLE:{av(this,t);break}case z.IN_TABLE_TEXT:{ev(this,t);break}case z.IN_CAPTION:{iet(this,t);break}case z.IN_COLUMN_GROUP:{set(this,t);break}case z.IN_TABLE_BODY:{mG(this,t);break}case z.IN_ROW:{qpe(this,t);break}case z.IN_CELL:{cet(this,t);break}case z.IN_SELECT:{Ype(this,t);break}case z.IN_SELECT_IN_TABLE:{uet(this,t);break}case z.IN_TEMPLATE:{met(this,t);break}case z.AFTER_BODY:{Xpe(this,t);break}case z.IN_FRAMESET:{fet(this,t);break}case z.AFTER_FRAMESET:{bet(this,t);break}case z.AFTER_AFTER_BODY:{RO(this,t);break}}}onEof(t){switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{tv(this,t);break}case z.BEFORE_HEAD:{nv(this,t);break}case z.IN_HEAD:{ov(this,t);break}case z.IN_HEAD_NO_SCRIPT:{rv(this,t);break}case z.AFTER_HEAD:{iv(this,t);break}case z.IN_BODY:case z.IN_TABLE:case z.IN_CAPTION:case z.IN_COLUMN_GROUP:case z.IN_TABLE_BODY:case z.IN_ROW:case z.IN_CELL:case z.IN_SELECT:case z.IN_SELECT_IN_TABLE:{$pe(this,t);break}case z.TEXT:{Y7e(this,t);break}case z.IN_TABLE_TEXT:{ev(this,t);break}case z.IN_TEMPLATE:{Jpe(this,t);break}case z.AFTER_BODY:case z.IN_FRAMESET:case z.AFTER_FRAMESET:case z.AFTER_AFTER_BODY:case z.AFTER_AFTER_FRAMESET:{gG(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=false,t.chars.charCodeAt(0)===L.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 z.IN_HEAD:case z.IN_HEAD_NO_SCRIPT:case z.AFTER_HEAD:case z.TEXT:case z.IN_COLUMN_GROUP:case z.IN_SELECT:case z.IN_SELECT_IN_TABLE:case z.IN_FRAMESET:case z.AFTER_FRAMESET:{this._insertCharacters(t);break}case z.IN_BODY:case z.IN_CAPTION:case z.IN_CELL:case z.IN_TEMPLATE:case z.AFTER_BODY:case z.AFTER_AFTER_BODY:case z.AFTER_AFTER_FRAMESET:{Bpe(this,t);break}case z.IN_TABLE:case z.IN_TABLE_BODY:case z.IN_ROW:{uG(this,t);break}case z.IN_TABLE_TEXT:{Vpe(this,t);break}}}};function W9e(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):Gpe(e,t),n}function q9e(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 K9e(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>=V9e;!a||l?(l&&e.activeFormattingElements.removeEntry(a),e.openElements.remove(s)):(s=Y9e(e,a),o===t&&(e.activeFormattingElements.bookmark=a),e.treeAdapter.detachNode(o),e.treeAdapter.appendChild(s,o),o=s);}return o}function Y9e(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 J9e(e,t,n){let o=e.treeAdapter.getTagName(t),r=$h(o);if(e._isElementCausesFosterParenting(r))e._fosterParentElement(n);else {let i=e.treeAdapter.getNamespaceURI(t);r===b.TEMPLATE&&i===Ce.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n);}}function X9e(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 hG(e,t){for(let n=0;n<$9e;n++){let o=W9e(e,t);if(!o)break;let r=q9e(e,o);if(!r)break;e.activeFormattingElements.bookmark=o;let i=K9e(e,r,o.element),s=e.openElements.getCommonAncestor(o.element);e.treeAdapter.detachNode(i),s&&J9e(e,s,i),X9e(e,r,o);}}function pG(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode);}function Q9e(e,t){e._appendCommentNode(t,e.openElements.items[0]);}function Z9e(e,t){e._appendCommentNode(t,e.document);}function gG(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 e7e(e,t){e._setDocumentType(t);let n=t.forceQuirks?ns.QUIRKS:xpe(t);Ipe(t)||e._err(t,ce.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=z.BEFORE_HTML;}function ZE(e,t){e._err(t,ce.missingDoctype,true),e.treeAdapter.setDocumentMode(e.document,ns.QUIRKS),e.insertionMode=z.BEFORE_HTML,e._processToken(t);}function t7e(e,t){t.tagID===b.HTML?(e._insertElement(t,Ce.HTML),e.insertionMode=z.BEFORE_HEAD):tv(e,t);}function n7e(e,t){let n=t.tagID;(n===b.HTML||n===b.HEAD||n===b.BODY||n===b.BR)&&tv(e,t);}function tv(e,t){e._insertFakeRootElement(),e.insertionMode=z.BEFORE_HEAD,e._processToken(t);}function o7e(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.HEAD:{e._insertElement(t,Ce.HTML),e.headElement=e.openElements.current,e.insertionMode=z.IN_HEAD;break}default:nv(e,t);}}function r7e(e,t){let n=t.tagID;n===b.HEAD||n===b.BODY||n===b.HTML||n===b.BR?nv(e,t):e._err(t,ce.endTagWithoutMatchingOpenElement);}function nv(e,t){e._insertFakeElement(ie.HEAD,b.HEAD),e.headElement=e.openElements.current,e.insertionMode=z.IN_HEAD,e._processToken(t);}function Ul(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.BASE:case b.BASEFONT:case b.BGSOUND:case b.LINK:case b.META:{e._appendElement(t,Ce.HTML),t.ackSelfClosing=true;break}case b.TITLE:{e._switchToTextParsing(t,Ei.RCDATA);break}case b.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,Ei.RAWTEXT):(e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_HEAD_NO_SCRIPT);break}case b.NOFRAMES:case b.STYLE:{e._switchToTextParsing(t,Ei.RAWTEXT);break}case b.SCRIPT:{e._switchToTextParsing(t,Ei.SCRIPT_DATA);break}case b.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=false,e.insertionMode=z.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(z.IN_TEMPLATE);break}case b.HEAD:{e._err(t,ce.misplacedStartTagForHeadElement);break}default:ov(e,t);}}function i7e(e,t){switch(t.tagID){case b.HEAD:{e.openElements.pop(),e.insertionMode=z.AFTER_HEAD;break}case b.BODY:case b.BR:case b.HTML:{ov(e,t);break}case b.TEMPLATE:{Vh(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function Vh(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 ov(e,t){e.openElements.pop(),e.insertionMode=z.AFTER_HEAD,e._processToken(t);}function s7e(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.BASEFONT:case b.BGSOUND:case b.HEAD:case b.LINK:case b.META:case b.NOFRAMES:case b.STYLE:{Ul(e,t);break}case b.NOSCRIPT:{e._err(t,ce.nestedNoscriptInHead);break}default:rv(e,t);}}function a7e(e,t){switch(t.tagID){case b.NOSCRIPT:{e.openElements.pop(),e.insertionMode=z.IN_HEAD;break}case b.BR:{rv(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function rv(e,t){let n=t.type===Zt.EOF?ce.openElementsLeftAfterEof:ce.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=z.IN_HEAD,e._processToken(t);}function l7e(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.BODY:{e._insertElement(t,Ce.HTML),e.framesetOk=false,e.insertionMode=z.IN_BODY;break}case b.FRAMESET:{e._insertElement(t,Ce.HTML),e.insertionMode=z.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),Ul(e,t),e.openElements.remove(e.headElement);break}case b.HEAD:{e._err(t,ce.misplacedStartTagForHeadElement);break}default:iv(e,t);}}function c7e(e,t){switch(t.tagID){case b.BODY:case b.HTML:case b.BR:{iv(e,t);break}case b.TEMPLATE:{Vh(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function iv(e,t){e._insertFakeElement(ie.BODY,b.BODY),e.insertionMode=z.IN_BODY,xO(e,t);}function xO(e,t){switch(t.type){case Zt.CHARACTER:{Upe(e,t);break}case Zt.WHITESPACE_CHARACTER:{Bpe(e,t);break}case Zt.COMMENT:{pG(e,t);break}case Zt.START_TAG:{vi(e,t);break}case Zt.END_TAG:{_O(e,t);break}case Zt.EOF:{$pe(e,t);break}}}function Bpe(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t);}function Upe(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=false;}function d7e(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs);}function u7e(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=false,e.treeAdapter.adoptAttributes(n,t.attrs));}function p7e(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_FRAMESET);}function m7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML);}function h7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&JE.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,Ce.HTML);}function g7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML),e.skipNextNewLine=true,e.framesetOk=false;}function f7e(e,t){let n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML),n||(e.formElement=e.openElements.current));}function y7e(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,Ce.HTML);}function S7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML),e.tokenizer.state=Ei.PLAINTEXT;}function b7e(e,t){e.openElements.hasInScope(b.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.framesetOk=false;}function T7e(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(ie.A);n&&(hG(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function A7e(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function E7e(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(b.NOBR)&&(hG(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,Ce.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function v7e(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=false;}function C7e(e,t){e.treeAdapter.getDocumentMode(e.document)!==ns.QUIRKS&&e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML),e.framesetOk=false,e.insertionMode=z.IN_TABLE;}function Hpe(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Ce.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function jpe(e){let t=SO(e,fu.TYPE);return t!=null&&t.toLowerCase()===G9e}function R7e(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Ce.HTML),jpe(t)||(e.framesetOk=false),t.ackSelfClosing=true;}function w7e(e,t){e._appendElement(t,Ce.HTML),t.ackSelfClosing=true;}function I7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._appendElement(t,Ce.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function x7e(e,t){t.tagName=ie.IMG,t.tagID=b.IMG,Hpe(e,t);}function _7e(e,t){e._insertElement(t,Ce.HTML),e.skipNextNewLine=true,e.tokenizer.state=Ei.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=false,e.insertionMode=z.TEXT;}function P7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=false,e._switchToTextParsing(t,Ei.RAWTEXT);}function O7e(e,t){e.framesetOk=false,e._switchToTextParsing(t,Ei.RAWTEXT);}function kpe(e,t){e._switchToTextParsing(t,Ei.RAWTEXT);}function M7e(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.framesetOk=false,e.insertionMode=e.insertionMode===z.IN_TABLE||e.insertionMode===z.IN_CAPTION||e.insertionMode===z.IN_TABLE_BODY||e.insertionMode===z.IN_ROW||e.insertionMode===z.IN_CELL?z.IN_SELECT_IN_TABLE:z.IN_SELECT;}function N7e(e,t){e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML);}function L7e(e,t){e.openElements.hasInScope(b.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,Ce.HTML);}function k7e(e,t){e.openElements.hasInScope(b.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(b.RTC),e._insertElement(t,Ce.HTML);}function D7e(e,t){e._reconstructActiveFormattingElements(),cG(t),CO(t),t.selfClosing?e._appendElement(t,Ce.MATHML):e._insertElement(t,Ce.MATHML),t.ackSelfClosing=true;}function F7e(e,t){e._reconstructActiveFormattingElements(),dG(t),CO(t),t.selfClosing?e._appendElement(t,Ce.SVG):e._insertElement(t,Ce.SVG),t.ackSelfClosing=true;}function Dpe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML);}function vi(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:{A7e(e,t);break}case b.A:{T7e(e,t);break}case b.H1:case b.H2:case b.H3:case b.H4:case b.H5:case b.H6:{h7e(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:{m7e(e,t);break}case b.LI:case b.DD:case b.DT:{y7e(e,t);break}case b.BR:case b.IMG:case b.WBR:case b.AREA:case b.EMBED:case b.KEYGEN:{Hpe(e,t);break}case b.HR:{I7e(e,t);break}case b.RB:case b.RTC:{L7e(e,t);break}case b.RT:case b.RP:{k7e(e,t);break}case b.PRE:case b.LISTING:{g7e(e,t);break}case b.XMP:{P7e(e,t);break}case b.SVG:{F7e(e,t);break}case b.HTML:{d7e(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:{Ul(e,t);break}case b.BODY:{u7e(e,t);break}case b.FORM:{f7e(e,t);break}case b.NOBR:{E7e(e,t);break}case b.MATH:{D7e(e,t);break}case b.TABLE:{C7e(e,t);break}case b.INPUT:{R7e(e,t);break}case b.PARAM:case b.TRACK:case b.SOURCE:{w7e(e,t);break}case b.IMAGE:{x7e(e,t);break}case b.BUTTON:{b7e(e,t);break}case b.APPLET:case b.OBJECT:case b.MARQUEE:{v7e(e,t);break}case b.IFRAME:{O7e(e,t);break}case b.SELECT:{M7e(e,t);break}case b.OPTION:case b.OPTGROUP:{N7e(e,t);break}case b.NOEMBED:case b.NOFRAMES:{kpe(e,t);break}case b.FRAMESET:{p7e(e,t);break}case b.TEXTAREA:{_7e(e,t);break}case b.NOSCRIPT:{e.options.scriptingEnabled?kpe(e,t):Dpe(e,t);break}case b.PLAINTEXT:{S7e(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:Dpe(e,t);}}function B7e(e,t){if(e.openElements.hasInScope(b.BODY)&&(e.insertionMode=z.AFTER_BODY,e.options.sourceCodeLocationInfo)){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t);}}function U7e(e,t){e.openElements.hasInScope(b.BODY)&&(e.insertionMode=z.AFTER_BODY,Xpe(e,t));}function H7e(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n));}function j7e(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 G7e(e){e.openElements.hasInButtonScope(b.P)||e._insertFakeElement(ie.P,b.P),e._closePElement();}function $7e(e){e.openElements.hasInListItemScope(b.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(b.LI),e.openElements.popUntilTagNamePopped(b.LI));}function V7e(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n));}function z7e(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped());}function W7e(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker());}function q7e(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(ie.BR,b.BR),e.openElements.pop(),e.framesetOk=false;}function Gpe(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 _O(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:{hG(e,t);break}case b.P:{G7e(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:{H7e(e,t);break}case b.LI:{$7e(e);break}case b.DD:case b.DT:{V7e(e,t);break}case b.H1:case b.H2:case b.H3:case b.H4:case b.H5:case b.H6:{z7e(e);break}case b.BR:{q7e(e);break}case b.BODY:{B7e(e,t);break}case b.HTML:{U7e(e,t);break}case b.FORM:{j7e(e);break}case b.APPLET:case b.OBJECT:case b.MARQUEE:{W7e(e,t);break}case b.TEMPLATE:{Vh(e,t);break}default:Gpe(e,t);}}function $pe(e,t){e.tmplInsertionModeStack.length>0?Jpe(e,t):gG(e,t);}function K7e(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 Y7e(e,t){e._err(t,ce.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t);}function uG(e,t){if(e.openElements.currentTagId!==void 0&&Fpe.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=false,e.originalInsertionMode=e.insertionMode,e.insertionMode=z.IN_TABLE_TEXT,t.type){case Zt.CHARACTER:{zpe(e,t);break}case Zt.WHITESPACE_CHARACTER:{Vpe(e,t);break}}else lv(e,t);}function J7e(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_CAPTION;}function X7e(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_COLUMN_GROUP;}function Q7e(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(ie.COLGROUP,b.COLGROUP),e.insertionMode=z.IN_COLUMN_GROUP,fG(e,t);}function Z7e(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_TABLE_BODY;}function eet(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(ie.TBODY,b.TBODY),e.insertionMode=z.IN_TABLE_BODY,PO(e,t);}function tet(e,t){e.openElements.hasInTableScope(b.TABLE)&&(e.openElements.popUntilTagNamePopped(b.TABLE),e._resetInsertionMode(),e._processStartTag(t));}function net(e,t){jpe(t)?e._appendElement(t,Ce.HTML):lv(e,t),t.ackSelfClosing=true;}function oet(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,Ce.HTML),e.formElement=e.openElements.current,e.openElements.pop());}function CS(e,t){switch(t.tagID){case b.TD:case b.TH:case b.TR:{eet(e,t);break}case b.STYLE:case b.SCRIPT:case b.TEMPLATE:{Ul(e,t);break}case b.COL:{Q7e(e,t);break}case b.FORM:{oet(e,t);break}case b.TABLE:{tet(e,t);break}case b.TBODY:case b.TFOOT:case b.THEAD:{Z7e(e,t);break}case b.INPUT:{net(e,t);break}case b.CAPTION:{J7e(e,t);break}case b.COLGROUP:{X7e(e,t);break}default:lv(e,t);}}function av(e,t){switch(t.tagID){case b.TABLE:{e.openElements.hasInTableScope(b.TABLE)&&(e.openElements.popUntilTagNamePopped(b.TABLE),e._resetInsertionMode());break}case b.TEMPLATE:{Vh(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:lv(e,t);}}function lv(e,t){let n=e.fosterParentingEnabled;e.fosterParentingEnabled=true,xO(e,t),e.fosterParentingEnabled=n;}function Vpe(e,t){e.pendingCharacterTokens.push(t);}function zpe(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=true;}function ev(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)lv(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t);}var Wpe=new Set([b.CAPTION,b.COL,b.COLGROUP,b.TBODY,b.TD,b.TFOOT,b.TH,b.THEAD,b.TR]);function ret(e,t){let n=t.tagID;Wpe.has(n)?e.openElements.hasInTableScope(b.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=z.IN_TABLE,CS(e,t)):vi(e,t);}function iet(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=z.IN_TABLE,n===b.TABLE&&av(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:_O(e,t);}}function fG(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.COL:{e._appendElement(t,Ce.HTML),t.ackSelfClosing=true;break}case b.TEMPLATE:{Ul(e,t);break}default:wO(e,t);}}function set(e,t){switch(t.tagID){case b.COLGROUP:{e.openElements.currentTagId===b.COLGROUP&&(e.openElements.pop(),e.insertionMode=z.IN_TABLE);break}case b.TEMPLATE:{Vh(e,t);break}case b.COL:break;default:wO(e,t);}}function wO(e,t){e.openElements.currentTagId===b.COLGROUP&&(e.openElements.pop(),e.insertionMode=z.IN_TABLE,e._processToken(t));}function PO(e,t){switch(t.tagID){case b.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_ROW;break}case b.TH:case b.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(ie.TR,b.TR),e.insertionMode=z.IN_ROW,OO(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=z.IN_TABLE,CS(e,t));break}default:CS(e,t);}}function mG(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=z.IN_TABLE);break}case b.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=z.IN_TABLE,av(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:av(e,t);}}function OO(e,t){switch(t.tagID){case b.TH:case b.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,Ce.HTML),e.insertionMode=z.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=z.IN_TABLE_BODY,PO(e,t));break}default:CS(e,t);}}function qpe(e,t){switch(t.tagID){case b.TR:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=z.IN_TABLE_BODY);break}case b.TABLE:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=z.IN_TABLE_BODY,mG(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=z.IN_TABLE_BODY,mG(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:av(e,t);}}function aet(e,t){let n=t.tagID;Wpe.has(n)?(e.openElements.hasInTableScope(b.TD)||e.openElements.hasInTableScope(b.TH))&&(e._closeTableCell(),OO(e,t)):vi(e,t);}function cet(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=z.IN_ROW);break}case b.TABLE:case b.TBODY:case b.TFOOT:case b.THEAD:case b.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),qpe(e,t));break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:break;default:_O(e,t);}}function Kpe(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.OPTION:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e._insertElement(t,Ce.HTML);break}case b.OPTGROUP:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop(),e._insertElement(t,Ce.HTML);break}case b.HR:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop(),e._appendElement(t,Ce.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:{Ul(e,t);break}}}function Ype(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:{Vh(e,t);break}}}function det(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)):Kpe(e,t);}function uet(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)):Ype(e,t);}function pet(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:{Ul(e,t);break}case b.CAPTION:case b.COLGROUP:case b.TBODY:case b.TFOOT:case b.THEAD:{e.tmplInsertionModeStack[0]=z.IN_TABLE,e.insertionMode=z.IN_TABLE,CS(e,t);break}case b.COL:{e.tmplInsertionModeStack[0]=z.IN_COLUMN_GROUP,e.insertionMode=z.IN_COLUMN_GROUP,fG(e,t);break}case b.TR:{e.tmplInsertionModeStack[0]=z.IN_TABLE_BODY,e.insertionMode=z.IN_TABLE_BODY,PO(e,t);break}case b.TD:case b.TH:{e.tmplInsertionModeStack[0]=z.IN_ROW,e.insertionMode=z.IN_ROW,OO(e,t);break}default:e.tmplInsertionModeStack[0]=z.IN_BODY,e.insertionMode=z.IN_BODY,vi(e,t);}}function met(e,t){t.tagID===b.TEMPLATE&&Vh(e,t);}function Jpe(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(b.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):gG(e,t);}function het(e,t){t.tagID===b.HTML?vi(e,t):IO(e,t);}function Xpe(e,t){var n;if(t.tagID===b.HTML){if(e.fragmentContext||(e.insertionMode=z.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 IO(e,t);}function IO(e,t){e.insertionMode=z.IN_BODY,xO(e,t);}function get(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.FRAMESET:{e._insertElement(t,Ce.HTML);break}case b.FRAME:{e._appendElement(t,Ce.HTML),t.ackSelfClosing=true;break}case b.NOFRAMES:{Ul(e,t);break}}}function fet(e,t){t.tagID===b.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==b.FRAMESET&&(e.insertionMode=z.AFTER_FRAMESET));}function yet(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.NOFRAMES:{Ul(e,t);break}}}function bet(e,t){t.tagID===b.HTML&&(e.insertionMode=z.AFTER_AFTER_FRAMESET);}function Tet(e,t){t.tagID===b.HTML?vi(e,t):RO(e,t);}function RO(e,t){e.insertionMode=z.IN_BODY,xO(e,t);}function Aet(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.NOFRAMES:{Ul(e,t);break}}}function Eet(e,t){t.chars=Xn,e._insertCharacters(t);}function vet(e,t){e._insertCharacters(t),e.framesetOk=false;}function Qpe(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==Ce.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop();}function Cet(e,t){if(Ppe(t))Qpe(e),e._startTagOutsideForeignContent(t);else {let n=e._getAdjustedCurrentElement(),o=e.treeAdapter.getNamespaceURI(n);o===Ce.MATHML?cG(t):o===Ce.SVG&&(Ope(t),dG(t)),CO(t),t.selfClosing?e._appendElement(t,o):e._insertElement(t,o),t.ackSelfClosing=true;}}function Ret(e,t){if(t.tagID===b.P||t.tagID===b.BR){Qpe(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)===Ce.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 Zpe(e,t,n){typeof e=="string"&&(n=t,t=e,e=null);let o=sv.getFragmentParser(e,n);return o.tokenizer.write(t,true),o.getFragment()}var wet=5e3,eme=1024;function yG(e){return typeof e.tagName=="string"&&Array.isArray(e.attrs)}function Iet(e){return e.nodeName==="#text"}function SG(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(Iet(l)){let c=l.value;if(c&&c.trim().length>0){let d=c.length>eme?c.slice(0,eme):c;i=i===void 0?d:`${i} ${d}`;}}else if(yG(l)){let c=SG(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 bG(e){let t=Zpe(e),n={nodesLeft:wet};for(let i of t.childNodes)if(yG(i)&&i.tagName.toLowerCase()==="body"){let s=SG(i,n);if(s!==void 0)return s}let o=[];for(let i of t.childNodes){if(n.nodesLeft<=0)break;if(yG(i)){let s=SG(i,n);s!==void 0&&o.push(s);}}let r={tag:"body"};return o.length>0&&(r.children=o),r}var xet=new Set(["PRESET_ACTION","AI_ACTION_DYNAMIC"]),zh=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(`${$r}/${n}.jpeg`)}async getHtmlSnapshot(t,n){return this.diskStorage.readFile(`${$r}/${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))wt.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 TG(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:PW(t.status),finishedAt:t.finishedAt}))),this.sendFinalizedStepStats());}};function _et(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 Xe(e)}}function MO(e){return e.some(t=>t.status==="FAILED")?"FAILED":e.some(t=>t.status==="CANCELLED")?"CANCELLED":"RUNNING"}var TG=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 Ip({storeTraceAsset:c=>this.storeTraceAsset(c)}),wp.initializeRootTracerContext(this.interactionTracer);}children=[];finished=false;interactionTracer;attachBeforeScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${$r}/${n}.jpeg`,contents:o});}attachAfterScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${$r}/${n}.jpeg`,contents:o});}attachBeforeHtmlSnapshot(t){let{snapshotId:n,html:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${$r}/${n}.html`,contents:o});}attachAfterHtmlSnapshot(t){let{snapshotId:n,html:o,url:r,logger:i}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${$r}/${n}.html`,contents:o}),this.appGraphSink&&xet.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";wt.increment("test_event",1,[`name:${o}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:n,healedAt:new Date};}storeTraceAsset(t){this.diskStorage.storeFile({name:`${$r}/${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:_et(t.status),finishedAt:t.finishedAt}))));}recordStepDuration(t,n){if(!AR(t))return;let o=TR(t);wt.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:MO(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:Od(r.steps)})),elseSteps:t.elseSteps?Od(t.elseSteps):void 0,status:MO(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});case "WHILE_LOOP":return n=>({...t,steps:Od(t.steps),status:MO(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:MO(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});default:return Xe(t)}}async startSubSteps(){let t=this.getResultBuilderForCurrentStep(),n=new zh(this.orgId,this.testId,this.testName,this.diskStorage,o=>{let r=t(o);this.parentFlushResults(r);});return this.children.push(n),n}};var NO=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($r),this.harPagesStream=this.diskStorage.createFileStream(`${$r}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${$r}/har-entries.log`),this.resourceUsageStream=this.diskStorage.createFileStream(`${$r}/resource-usage.ndjson`),this.resourceUsageSampler=dX({keepSamples:false,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
|
|
9040
|
+
`).map(o=>o.trim()).filter(Boolean)||[];if(!(t.length===0&&n.length===0))return [{expanded:t,backtrace:n}]}function Q6e(e){let t=e.status==="FAILED"?rO(e):void 0;return Cue([["attempts",e.attempts.toString()],["run_url",e.runId?`https://app.momentic.ai/runs/${e.runId}`:void 0],["failure_section",t],["quarantined",e.quarantined?"true":"false"],["failure_recovery",e.failureRecoveryDetails?.attempts?"true":"false"]])}function Z6e(e,t,n){let o=vue(n.filePath);return {id:n.runId||randomUUID(),scope:e,name:n.testName,location:o,file_name:io__default.basename(o),result:K6e(n.status),failure_reason:J6e(n),failure_expanded:X6e(n),history:Y6e(t,n.lastAttemptStartedAt,n.finishedAt),tags:Q6e(n)}}function Aue(e,t,n,o,r){let i=vue(t);return {id:randomUUID(),scope:e,name:n,location:i,file_name:io__default.basename(i),result:"skipped",history:{start_at:0,end_at:0,duration:0},tags:Cue([["quarantined",r?.quarantined||"false"],["failure_recovery","false"]])}}function e8e(e,t){let n=t.map(i=>Z6e(e.suiteName,e.startedAt,i)),o=e.testsToSkip.map(i=>Aue(e.suiteName,i.relativeFilePath,i.name,i.id,void 0)),r=e.quarantinedTestsToSkip.map(i=>Aue(e.suiteName,i.relativeFilePath,i.name,i.id,{quarantined:"true"}));return [...n,...o,...r]}function Rue(e,t,n){let o=e8e(t,n);ko__default.writeFileSync(io__default.join(e,`${t.suiteName}.buildkite.json`),JSON.stringify(o,null,2));}function bS(e){return {testName:e.test.name,testId:e.test.id,filePath:e.filePath,labels:e.test.labels,baseUrl:e.baseUrl,runId:e.runId,quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata,status:e.status,failureRecoveryDetails:e.failureRecoveryDetails,failureDetails:e.failureDetails,failureReason:e.failureReason,finishedAt:e.finishedAt,lastAttemptStartedAt:e.lastAttemptStartedAt,attempts:e.attempts,parameters:e.parameters}}function Iue(e,t,n){let o=Zj(t,n);ko__default.writeFileSync(io__default.join(e,`${t.suiteName}.momentic.json`),JSON.stringify(o,null,2));}function Zj(e,t){let n=t.map(n8e),o=[...e.testsToSkip.map(r=>wue(r,false)),...e.quarantinedTestsToSkip.map(r=>wue(r,true))];return SW.parse({version:1,runGroup:{startedAt:e.startedAt.toISOString(),finishedAt:e.finishedAt.toISOString(),durationMs:e.finishedAt.getTime()-e.startedAt.getTime()},summary:o8e(n,o),runs:n,skipped:o})}function n8e(e){let t=e.status==="PASSED"&&(e.failureRecoveryDetails?.attempts??0)>0,n=e.failureDetails?.manualClassification??e.failureDetails?.classification,o=e.status==="FAILED"?{reason:e.failureReason,message:e.failureDetails?.errorMessage}:null;return {runId:e.runId,testId:e.testId,testName:e.testName,filePath:io__default.relative(".",e.filePath),labels:e.labels,status:e.status,startedAt:e.lastAttemptStartedAt.toISOString(),finishedAt:e.finishedAt.toISOString(),durationMs:e.finishedAt.getTime()-e.lastAttemptStartedAt.getTime(),attempts:e.attempts,quarantined:e.quarantined??false,recovered:t,parameters:e.parameters,failure:o,classification:n?{reasoning:n.summary,category:n.reason,citations:n.citations}:null}}function wue(e,t){return {testId:e.id,testName:e.name,filePath:io__default.relative(".",e.relativeFilePath),labels:e.labels,quarantined:t}}function o8e(e,t){return {total:e.length+t.length,executed:e.length,skipped:t.length,passed:e.filter(n=>n.status==="PASSED").length,failed:e.filter(n=>n.status==="FAILED").length,cancelled:e.filter(n=>n.status==="CANCELLED").length,quarantined:e.filter(n=>n.quarantined).length+t.filter(n=>n.quarantined).length,recovered:e.filter(n=>n.recovered).length}}function xue(e,t){e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),t.quarantinedReason&&(e.property("quarantined_reason",t.quarantinedReason),e.property("dd_tags[quarantined_reason]",t.quarantinedReason)),t.quarantinedAt&&(e.property("quarantined_at",t.quarantinedAt.toISOString()),e.property("dd_tags[quarantined_at]",t.quarantinedAt.toISOString()));}function i8e(e,t){let n=rO(e);if(t.name(e.testName).className(e.testName).file(io__default.relative(".",e.filePath)).property("id",e.testId).property("dd_tags[id]",e.testId),e.labels&&(t.property("labels",e.labels.join(",")),e.labels.forEach(o=>{t.property("dd_tags[label]",o);})),e.baseUrl&&(t.property("base_url",e.baseUrl),t.property("dd_tags[base_url]",e.baseUrl)),e.runId&&(t.property("run_url",`https://app.momentic.ai/runs/${e.runId}`),t.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${e.runId}`)),e.quarantinedMetadata&&xue(t,e.quarantinedMetadata),n==="setup"&&(t.property("setup_failed","true"),t.property("dd_tags[setup_failed]","true")),n==="main"&&(t.property("main_failed","true"),t.property("dd_tags[main_failed]","true")),n==="teardown"&&(t.property("teardown_failed","true"),t.property("dd_tags[teardown_failed]","true")),e.status==="FAILED"){let o=Xl({failureReason:e.failureReason,classification:e.failureDetails?.classification,manualClassification:e.failureDetails?.manualClassification});if(o.title){let{description:r}=o;e.runId&&(r+=` Visit https://app.momentic.ai/runs/${e.runId} for more details.`),t.failure(r,o.title);}e.failureDetails?.errorStack&&t.stacktrace(e.failureDetails.errorStack);}else e.status==="CANCELLED"&&t.skipped();return t.time((e.finishedAt.getTime()-e.lastAttemptStartedAt.getTime())/1e3).property("started_at",e.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",e.lastAttemptStartedAt.toISOString()).property("finished_at",e.finishedAt.toISOString()).property("dd_tags[finished_at]",e.finishedAt.toISOString()),t.property("attempts",e.attempts.toString()).property("dd_tags[attempts]",e.attempts.toString()),e.parameters?.envName&&(t.property("environment",e.parameters.envName),t.property("dd_tags[environment]",e.parameters.envName)),e.parameters?.urlOverride&&t.property("url_override",e.parameters.urlOverride),t}function s8e(e,t,n){let{suiteId:o,suiteName:r,startedAt:i,finishedAt:s,testsToSkip:a,quarantinedTestsToSkip:l,quarantinedTestsMetadata:c}=t,d=e.testSuite().name(r);o&&d.property("id",o),d.timestamp(i).property("startedAt",i.toISOString()).property("finishedAt",s.toISOString()).time((s.getTime()-i.getTime())/1e3);for(let u of n){let p=d.testCase();i8e(u,p);}for(let u of a){let p=d.testCase();p.name(u.name).className(u.name).file(io__default.relative(".",u.relativeFilePath)).property("id",u.id),u.baseUrl&&p.property("baseUrl",u.baseUrl),u.labels&&(p.property("labels",u.labels.join(",")),u.labels.forEach(m=>{p.property("dd_tags[label]",m);})),p.skipped();}for(let u of l){let p=d.testCase();p.name(u.name).className(u.name).file(io__default.relative(".",u.relativeFilePath)).property("id",u.id);let m=c[u.id];m&&xue(p,m),u.baseUrl&&p.property("baseUrl",u.baseUrl),u.labels&&(p.property("labels",u.labels.join(",")),u.labels.forEach(h=>{p.property("dd_tags[label]",h);})),p.skipped();}return d}function _ue(e,t,n){let o=r8e.newBuilder();s8e(o,t,n),o.writeTo(io__default.join(e,`${t.suiteName}.xml`));}var a8e="insights-collector.newrelic.com",l8e="insights-collector.eu01.nr-data.net",c8e=4e3;async function eG({logger:e,config:t,params:n,runs:o,runGroupId:r,envName:i,appUrl:s,gitMetadata:a}){let l=t.licenseKey??process.env.NEW_RELIC_LICENSE_KEY??"";if(!l){e.error("New Relic reporter is enabled but no license key was found. Set reporting.newrelic.licenseKey in momentic.config.yaml or the NEW_RELIC_LICENSE_KEY environment variable.");return}let c=o.map(bS),d=Zj(n,c),u=Pue({...t.attributes,runGroupId:r,environment:i,suiteName:n.suiteName,gitBranch:a.gitBranchName,gitCommit:a.gitCommitSha,gitRepository:a.githubRepository??a.gitOriginUrl,ciRunUrl:d8e()}),p=d.runs.map((g,f)=>({...u,eventType:"MomenticRun",timestamp:new Date(g.finishedAt).getTime(),...Pue({runId:g.runId,testId:g.testId,testName:g.testName,filePath:g.filePath,status:g.status,startedAt:g.startedAt,finishedAt:g.finishedAt,durationMs:g.durationMs,attempts:g.attempts,quarantined:g.quarantined,recovered:g.recovered,labels:g.labels?.join(","),baseUrl:c[f]?.baseUrl,failureReason:g.failure?.reason,failureMessage:g.failure?.message,classificationCategory:g.classification?.category,classificationReasoning:g.classification?.reasoning,runUrl:g.runId?`${s}/runs/${g.runId}`:void 0})}));p.push({...u,eventType:"MomenticRunGroup",timestamp:new Date(n.finishedAt).getTime(),startedAt:n.startedAt.toISOString(),finishedAt:n.finishedAt.toISOString(),durationMs:d.runGroup.durationMs,runGroupUrl:`${s}/run-groups/${r}`,...d.summary,passRate:d.summary.executed>0?d.summary.passed/d.summary.executed:0});let h=`https://${t.region==="EU"?l8e:a8e}/v1/accounts/${t.accountId}/events`;try{let g=await fetch(h,{method:"POST",headers:{"Content-Type":"application/json","Api-Key":l},body:JSON.stringify(p)});if(!g.ok){let f=await g.text();e.error(`Failed to send test results to New Relic: ${g.status} ${f}`);return}e.info(`Sent ${p.length} events to New Relic account ${t.accountId}`);}catch(g){e.error(`Failed to send test results to New Relic: ${q(g)}`);}}function Pue(e){let t={};for(let[n,o]of Object.entries(e))o==null||o===""||(t[n]=typeof o=="string"?o.slice(0,c8e):o);return t}function d8e(){let e=process.env;return e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:e.CI_JOB_URL??e.BUILDKITE_BUILD_URL??e.CIRCLE_BUILD_URL??void 0}function Oue(e){return {title:Vn(e),duration:e.finishedAt.getTime()-e.startedAt.getTime(),error:e.status==="FAILED"?{value:e.failureReason}:void 0,steps:e.results&&e.type!=="PRESET_ACTION"?e.results.map(Oue):[]}}async function m8e(e,t,n,o){if(o.results?.length){let r=await oO({logger:e,debugDataStorage:t,folder:n,label:"final-state",snapshotId:o.results[o.results.length-1].afterSnapshot});return r?[{name:"Final state screenshot",path:r,contentType:"image/jpeg"}]:[]}return []}async function h8e(e,t,n,o){let r;if(o.status==="FAILED"&&o.failureReason){let i=Xl({failureReason:o.failureReason,classification:o.failureDetails?.classification,manualClassification:o.failureDetails?.manualClassification});r={value:o.failureDetails?.classification?.reason??o.failureReason,message:i.description};}return {status:o.status==="PASSED"?"passed":o.status==="CANCELLED"?"interrupted":"failed",duration:o.finishedAt.getTime()-o.lastAttemptStartedAt.getTime(),error:r,retry:o.attempts-1,steps:o.results?.map(Oue)||[],startTime:o.lastAttemptStartedAt.toISOString(),attachments:await m8e(e,t,n,o)}}async function g8e(e,t,n,o){return {expectedStatus:"passed",status:o.status==="PASSED"?"expected":"unexpected",results:[await h8e(e,t,n,o)]}}async function f8e(e,t,n,o){return {tags:[],title:o.test.name,ok:o.status==="PASSED",tests:[await g8e(e,t,n,o)],id:o.runId,file:o.filePath}}function tG(e,t){return e.reduce((n,o)=>t(o)?n+1:n,0)}async function y8e(e,t,n,o,r){return {suites:[{title:o.suiteName,file:o.projectConfigPath,specs:await Promise.all(r.map(async i=>{let s=i.runId&&i.runAttemptId?t.createDebugDataReaderForRunAttempt(i.runId,i.runAttemptId):new nT;try{return await f8e(e,s,n,i)}finally{s.close();}}))}],errors:[],stats:{startTime:o.startedAt.toISOString(),duration:o.finishedAt.getTime()-o.startedAt.getTime(),expected:tG(r,i=>i.status==="PASSED"),unexpected:tG(r,i=>i.status!=="PASSED"),flaky:tG(r,i=>!!i.isFlake),skipped:0}}}async function Mue(e,t,n,o,r){let i=await y8e(e,t,n,o,r);ko__default.writeFileSync(io__default.join(n,`${o.suiteName}.json`),JSON.stringify(i,null,2));}async function Nue({logger:e,callbacks:t,format:n,params:o,runs:r,folder:i}){switch(existsSync(i)&&!statSync(i).isDirectory()&&(C.error(`The specified reporter output directory '${i}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)),mkdirSync(i,{recursive:true}),n){case "json":{let s=r.map(bS);Iue(i,o,s);return}case "junit":{let s=r.map(bS);_ue(i,o,s);return}case "buildkite-json":{let s=r.map(bS);Rue(i,o,s);return}case "allure":case "allure-json":await bue(e,t,i,o,r);return;case "playwright-json":await Mue(e,t,i,o,r);return;default:throw new Error(`Unknown reporter format requested: '${n}'`)}}function Gh(e){let t=e??R8e();return Lue()&&t===1&&C.warn("Running with --pixel-ratio=1 on a Retina screen. Viewport calculations may be incorrect; omit the flag to auto-detect."),t}function R8e(){let e=Lue(),t=e?2:1;return C.debug(`Auto-detected device pixel ratio ${t} (Mac OS Retina: ${e}).`),t}var Lue=once(()=>{if(platform()!=="darwin")return false;try{return execSync("system_profiler SPDisplaysDataType").toString().includes("Retina")}catch{return false}});async function aO(e,t=true,n=false){let o=_8e(e),r=await I8e.which(o[0],true),i=o.slice(1),s=w8e.exec(x8e(r),i,{delay:100,silent:n});if(t)return s}var kue="the Momentic GitHub app is missing permission to create pull requests or write branches for this repository";function P8e(e,{context:t}){return e instanceof mo?e.rawError.includes("Resource not accessible by integration")?`Cannot create ${t} because ${kue}.`:e.status>=400&&e.status<500?e.rawError:`Could not create ${t} due to a GitHub error.`:`Could not create ${t}: ${q(e)}`}function Due(e){return e instanceof mo?e.rawError.includes("Resource not accessible by integration")?kue:e.status>=400&&e.status<500?e.rawError:"a GitHub error occurred":q(e)}function Fue(e,t){C.error(P8e(e,t));}function lO(e){return Bue(e,"runs","run")}function nG(e){return Bue(e,"run-groups","run group")}function Bue(e,t,n){let o=e.trim(),r=/^https?:\/\//i.test(o)?M8e(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 M8e(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 cO(e){return new Promise((t,n)=>{let o=[];createReadStream(e).pipe(N8e()).on("data",r=>o.push(r)).on("end",()=>t(o)).on("error",r=>n(r));})}var Vt="3.25.1",{checkCLIVersion:lr,getLatestCLIVersion:Uue}=I9({packageName:"momentic",currentVersion:Vt,changelogUrl:"https://github.com/momentic-ai/cli/releases",updateCommand:"npx momentic@latest upgrade"});I0e("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI","POSTHOG_WEB_WRITE_KEY is not set");var{captureEvent:gu,setAnalyticsIdentity:dO,shutdownAnalytics:Hue}=CR({writeKey:"phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",host:"https://p.momentic.ai",platform:"cli",identity:"stashed",flushImmediately:true,onIdentify:o7});async function Ze(){try{await xe(Promise.all([ER(),wt.flush(),Hue(),kR()]),{milliseconds:5e3});}catch{}}async function Qp({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=>ko__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(!ko__default.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m;try{m=ko__default.statSync(p).isDirectory();}catch(g){a.warn({err:g},`Skipping path ${p} because it cannot be read`);return}let h=io__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 tr("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=io__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 fs(d,he,t);if(Jd.gt(u.schemaVersion,lt)&&R3(a,`Test ${d} has schema version ${u.schemaVersion}, which is newer than this version of the CLI supports. Update your momentic package to avoid unexpected behavior.`,"newer-schema-version"),s&&s.length>0){let p=u.labels||[];if(!s.some(h=>p.includes(h)))return null}return {...u,fullFilePath:d,relativeFilePath:io__default.relative(n.rootDir,d)}}catch(u){a.error(`Failed to read and resolve test at '${d}': ${q(u)}`),process.exit(1);}});return compact(await Promise.all(c))}function Gue({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 $ue({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 Vue=()=>process.exit(130),zue=()=>process.exit(143);process.on("SIGINT",Vue);process.on("SIGTERM",zue);function TS(){process.off("SIGINT",Vue),process.off("SIGTERM",zue);}async function Wue({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 yi({orgId:e,s:l,localTools:t,logger:n,context:r});}return i}var que=new Set;async function Kue({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 A={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:he,mode:o.mode,runner:o.runner},{controller:v,context:w}=await EE({baseUrl:e,envName:t,test:r,variables:c,logger:d,orgId:l,localBrowserConfig:m,aiSettings:h,customHeaders:u,codeEvalTools:s,storage:i,enricher:new $d(A,a),generator:a,visualDiffScreenshotStorage:g,devicePixelRatio:n,browserTypeOverride:S,callbacks:{onNetworkPage:I=>f.onNetworkPage(I),onNetworkLogs:I=>f.onNetworkLogs(I)},videoOptions:f.videoOutputPath?{videoOutputPath:f.videoOutputPath,onVideoPageChange:({videoName:I,timestamp:_})=>{f.setActiveVideo(I,_);}}:void 0,validateBrowserType:I=>{Xu(I)||(he.warn({browserType:I,testName:r.name},"Browser required by test does not appear to be installed"),!que.has(I)&&(que.add(I),C.warn(`Browser ${I} does not appear to be installed. Run '${xu(I)}' if you hit launch errors.`)));},createRemoteBrowserConnection:m.remoteBrowser?async()=>{let I=await o.createRemoteBrowserConnection({testId:r.id,testName:r.name,runId:y,attemptedProviders:T});return I.provider&&T?.push(I.provider),I}:void 0});try{await Q_({orgId:l,test:r,testInputs:p,localTools:s,logger:d,context:w});}catch(I){try{await v.browser.cleanup();}catch(_){d.error({err:_},"Failed to clean up browser after test input resolution failed");}throw I instanceof vE&&(C.error(I.message),process.exit(1)),I}return {controller:v,context:w}}function Yue({testAdvancedSettings:e,orgSettings:t,logger:n}){if(e.failureRecovery===false||e.failureRecovery===void 0&&!t?.failureRecovery)return false;if(!Om){let o="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(o),C.debug(o),false}return true}async function Jue({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:A,orgSettings:v}=e;y.info(`Running test '${A.name}' locally (run link: https://app.momentic.ai/runs/${l})`);let w={controller:m,storage:f,usageTracker:S,context:h,logger:y,codeEvalTools:g},I={orgId:s,userId:a,runId:l,testMetadata:A,steps:A.steps,beforeSteps:A.beforeSteps,afterSteps:A.afterSteps,orgSettings:v},_={collectDebugData:true,reinitializeBrowser:true,disableHealing:!await Yue({testAdvancedSettings:A.advanced,orgSettings:v.ai,logger:y})};return Use({fixtures:w,inputs:I,options:_,callbacks:{step:i??{},test:{onTestComplete:async x=>{await m.browser.cleanup({saveRemoteVideos:r!=="on-fail"||x?.status!=="PASSED"}),await g.dispose();}}},testParams:{attemptTracer:T},runParams:{runTracer:c,runGroupTracer:d,project:u,apiClient:p,captureEvent:gu,abortSignal:o.abortSignal}})}async function Xue(e){let{testDefinition:t,logger:n}=e,o=new Date;try{return await j8e(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),C.error({err:r},d),Que({err:Qa(r),parameters:c,test:t,failureReason:oe.reasonFor(r,"UnknownError"),startedAt:o,lastAttemptStartedAt:o,attempts:0,quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata})}}async function j8e(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 sy(r,i),T=Wd({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}),A,v;n?(A={envName:n.metadata.environment.envName,resolvedEnv:n.metadata.environment.resolvedEnv,environmentVariables:{...n.metadata.environment.variables},baseUrl:n.metadata.environment.baseUrl},v={steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps}):(A=ly({test:t,envNameOverride:e.envName,urlOverride:a,resolveEnv:ee=>yl(ee,o,c)}),v=await Ma({cacheStorage:T,logger:c,schemaVersion:t.schemaVersion,stepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,environment:A.envName,useSnapshotIdentityCache:o.config.fileFormat==="v2"}));let{envName:w,resolvedEnv:I,environmentVariables:_,baseUrl:R}=A,x=v.steps,O=v.beforeSteps??void 0,N=v.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:R,environmentName:w,schemaVersion:t.schemaVersion,resolvedInputs:m,quarantined:h,quarantinedReason:g?.quarantinedReason,aiSettings:y.ai}),W=c.child(k.loggerBindings||{});Object.entries(k.envVarBindings||{}).forEach(([ee,j])=>{_[ee]=j;});let X=await G8e({...e,effectiveConfig:y,variables:_,envName:w,resolvedEnv:I,baseUrl:R,storageClient:S,tracer:k,runGroupTracer:l,logger:W,cacheStorage:T,stepsWithCaches:x,beforeStepsWithCaches:O,afterStepsWithCaches:N,usageTracker:f});return await k.finish({logger:c,status:X.status,finishedAt:X.finishedAt,failureDetails:X.failureDetails,failureReason:X.failureReason,isFlake:X.isFlake,failureRecoveryDetails:X.failureRecoveryDetails}),{runId:k.runId,...X}}async function G8e(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:A,devicePixelRatio:v,logUpdate:w,tracer:I,runGroupTracer:_,logger:R,cacheStorage:x,gitMetadata:O,quarantined:N,quarantinedMetadata:k,usageTracker:W}=e,X=n,ee=X.ai?.aiFailureAnalysis??false,j=new Date,V=new Kf(s,l,a),M={envName:h,urlOverride:g,customHeaders:f,testInputs:y},J={...X.browser||{},...T?.browser||{},...t.advanced||{},...e.remoteBrowserOverride?{remoteBrowser:true}:{}},B=J.remoteBrowser===true,D=[],Y,te=Math.abs(A??t.retries??n.retries??1),ue=[];R.info({...O,labels:t.labels,name:t.name,cwd:process.cwd()},"Starting test run using CLI");for(let Te=0;Te<=te;Te++){let Ae=randomUUID(),je=await I.startAttempt(Ae),ge=R.child(je.loggerBindings||{}),se={...t,steps:cloneDeep(o),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)};Te!==0&&w("RETRY",`attempt ${Te+1}/${te+1}`);let Ie=new Date,Je=new zd({httpClient:new Ki({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:ge,mode:l.mode,runner:l.runner}),fakerSeed:X.advanced?.fakerConstantSeed?tT:void 0});try{let{controller:Ve,context:$e}=await Kue({tracer:je,runId:I.runId,baseUrl:d,envName:h,apiClient:l,devicePixelRatio:v,logger:ge,storageClient:u,codeEvalTools:Je,test:se,generator:c,orgId:p,variables:S,customHeaders:f,testInputs:y,localBrowserConfig:J,browserTypeOverride:e.browserTypeOverride,attemptedRemoteBrowserProviders:D,aiSettings:{...X.ai||{},...se.advanced||{}},visualDiffScreenshotStorage:V});e.abortSignal&&(e.abortSignal.aborted?Ve.executeAbortController.abort():e.abortSignal.addEventListener("abort",()=>{Ve.executeAbortController.abort();},{once:!0})),Y=await Jue({attemptMetadata:{attemptNumber:Te+1,orgId:p,userId:m,runId:I.runId},attemptFixtures:{logger:ge,storageClient:u,usageTracker:W,codeEvalTools:Je,context:$e,controller:Ve,tracer:je},attemptInputs:{test:se,orgSettings:X},runFixtures:{runTracer:I,runGroupTracer:_,project:s,apiClient:l,abortSignal:e.abortSignal},recordVideo:e.recordVideo??!1,stepCallbacks:{onStepStart:e.onStepStart,onStepEnd:e.onStepEnd,onSectionStart:e.onSectionStart}});let _t=new Date,dn={logger:R,cacheStorage:x,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 Gm({logger:R,cacheStorage:x,orgId:p,testId:t.id,environment:h,stepLists:dn.updatedStepsWithCaches,useSnapshotIdentityCache:s.config.fileFormat==="v2"}),Y?.status==="PASSED"||Y?.status==="CANCELLED"&&n.advanced?.saveCacheOnCancel?await $m(dn):Y?.status==="FAILED"&&Te===te&&await Cf(dn),await je.finish({logger:ge,result:Y}),ue.unshift(Y.status);let go=await Wue({orgId:p,codeEvalTools:Je,logger:ge,outputDefinitions:t.outputs??[],testContext:$e}),pa=fW(ue),Ri=Te+1;if(Y.status!=="FAILED")return {...Y,runAttemptId:Ae,parameters:M,test:se,filePath:se.relativeFilePath,startedAt:j,lastAttemptStartedAt:Ie,finishedAt:_t,attempts:Ri,baseUrl:d,outputs:go,isFlake:pa,quarantined:N,quarantinedMetadata:k,usedRemoteBrowser:B};let rs=Y.failedStepResult,Bo=rs?.message||"Unknown failure",Qn=rs?.failureReason??$V(Bo)??"UnknownError",wi=ge.child({failureReason:Qn,errorMessage:Bo,numAttempts:(te+1).toString(),name:se.name});if(Te<te){wi.warn(`Retrying failed execution attempt for run: ${Bo}`);continue}wi.error({usedRemoteBrowser:B},`Test failed after all exhausting attempts: ${Bo}`);let Yo=new Error(Bo),vr={errorMessage:Bo,errorStack:Yo.stack},Ii;if(X.ai?.classification?.enabled===!0){let Zn=rs?.failureClassification;Zn||(e.onStepStart?.(Zc),Zn=await L_({runTracer:I,runGroupTracer:_,outputDir:e.outputDir,orgId:p,project:s,generator:c,apiClient:l,logger:R,testPlatform:"web",aiSettings:X.ai,captureEvent:gu,abortSignal:e.abortSignal,failedStepMessage:rs?.message})),Zn&&(Ii=Zn.classification.category,Qn=Zn.classification.category,vr.classification={reason:Zn.classification.category,secondaryCategories:Zn.classification.secondaryCategories,summary:Zn.classification.reasoning,recoverable:Zn.classification.recoverable,confidence:Zn.classification.confidence,action:Zn.action,citations:Zn.classification.citations,source:"v2"});}else if(ee){let Zn;try{if(Y.results&&Y.results.length>0){e.onStepStart?.(Zc);let{classification:U,aiFailureReason:fe}=await YQ({logger:ge,browserStateStorage:je,generator:c,fullResults:Y,failureReason:Qn,error:Yo,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Zn=U,Ii=fe;}}catch(U){ge.warn({err:U},"Failed to classify test results");}Zn&&(vr.classification=Zn,Qn=Ii??Qn,vr.classification.source="v1");}return {...Y,runAttemptId:Ae,parameters:M,failureDetails:vr,failureReason:Qn,test:se,filePath:se.relativeFilePath,startedAt:j,lastAttemptStartedAt:Ie,finishedAt:_t,attempts:Te+1,baseUrl:d,outputs:go,quarantined:N,quarantinedMetadata:k,usedRemoteBrowser:B}}catch(Ve){let $e=`Encountered fatal platform error while running test '${se.name}'`;return ge.error({err:Ve},$e),C.error({err:Ve},$e),await je.finish({logger:ge,result:{status:"FAILED"}}),Que({err:Qa(Ve),parameters:M,test:se,failureReason:oe.reasonFor(Ve,"InternalPlatformError"),startedAt:j,lastAttemptStartedAt:Ie,attempts:Te+1,quarantined:N,quarantinedMetadata:k,runAttemptId:Ae,baseUrl:d,usedRemoteBrowser:B})}}throw new Error("This code should not be reachable")}function Que({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 Zue=3e4;async function vS({timeoutMinutes:e,cancel:t,run:n}){let o=()=>void t("SIGINT received"),r=()=>void t("SIGTERM received");TS(),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 ES=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 xe(Promise.allSettled(Object.values(this.runQueue).map(r=>r.promise)),{milliseconds:Zue}).catch(()=>{this.params.runGroupLogger.warn(`Graceful shutdown timeout of ${Zue}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:A,browserTypeOverride:v,remoteBrowserOverride:w,onResult:I,onFatal:_}=this.params,R=0,x=true;for(;x;){let O=Object.values(this.runQueue);if(O.length===n&&await Promise.race(O.map(ee=>ee.promise)),this.cancelled){x=false;continue}let N=await t();if(N===void 0){x=false;continue}let k=`test-${R++}`,W={...N,startedAt:new Date},X=new AbortController;this.runQueue[k]={done:false,activeRun:W,abortController:X,promise:(async({inputs:ee,quarantined:j,quarantinedMetadata:V,testDefinition:M,snapshot:J,runId:B})=>{let D=M.relativeFilePath.includes("..")?M.fullFilePath:M.relativeFilePath;o.onTestBegin(D);let Y=i.child({testId:M.id,runId:B}),te=new Md({logger:Y,reporter:new Gd(l),runType:"test-run",runId:B,testMetadata:M,suiteMetadata:void 0,runner:"test-runner"});try{let ue=await Xue({testDefinition:M,snapshot:J,project:a,testInputs:ee,quarantined:j,quarantinedMetadata:V,orgId:d,userId:u,runId:B,devicePixelRatio:p,apiClient:l,runGroupTracer:r,outputDir:m,generator:c,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:S,logUpdate:(Te,Ae)=>o.onTestStatus(D,Te,Ae),...z9(o,D),logger:Y,gitMetadata:T,cacheOptions:A,usageTracker:te,browserTypeOverride:v,remoteBrowserOverride:w,recordVideo:this.params.recordVideo,abortSignal:X.signal});o.onTestEnd(D,ue.status,{recovered:ue.status==="PASSED"&&!!ue.failureRecoveryDetails?.attempts}),this.runResults.push(ue),I?.(ue);}catch(ue){let Te=`Encountered unexpected fatal error when running test '${M.name}'`;Y.error({err:ue},Te),C.error({err:ue},Te),Wu(ue),_?.(ue),await this.cancel("Fatal error occurred",false);}finally{let ue=this.runQueue[k];ue&&(ue.done=true),await te.flush(s),delete this.runQueue[k];}})(W)};}return await Promise.allSettled(Object.values(this.runQueue).map(O=>O.promise)),{runResults:this.runResults,cancelledRunsById:this.cancelledRunsById,cancelled:this.cancelled,cancellationReason:this.cancellationReason}}};var V8e=200,z8e=new Set(MV),W8e=new Set(["PASSED","FAILED","CANCELLED"]);function tpe(e){return e.length}function pO(e){return e.filter(t=>z8e.has(t.status)).length}var YE=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});}},uO=class{constructor(t,n,o){this.runGroupId=n;this.logger=o;this.filePath=io__default.join(t,WJ);}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 YE(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<V8e)return;this.lastWriteMs=n;let o=[...this.runs.values()],r={schemaVersion:qJ,runGroupId:this.runGroupId,status:this.runGroupStatus,totalRuns:o.length,completedRuns:o.filter(s=>W8e.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{ko__default.writeFileSync(i,JSON.stringify(r,null,2)),ko__default.renameSync(i,this.filePath);}catch(s){this.logger.warn({err:s},"Failed to write run progress file");}}};function iG(e){return createHash("sha1").update(e).digest("hex")}var K8e=["tab","view","mode","step"],Y8e=[/^[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 J8e(e){return Y8e.some(t=>t.test(e))}function npe(e,t={}){let n;try{n=new URL(e);}catch{return e}let o=new Set(t.queryAllowlist??K8e),i=n.pathname.split("/").map(c=>c.length>0&&J8e(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 X8e=new Set(["id","name","role","type","href","for","placeholder","aria-label","data-testid"]),Q8e=/^[A-Za-z0-9_-]{16,256}$|^:r[0-9a-z]{1,32}:$/,Z8e=[/\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],ope=new Set(["h1","h2","h3","h4","h5","h6"]),e9e=new Set(["input","select","textarea"]);function t9e(e){let t=e;for(let n of Z8e)t=t.replace(n,"{id}");return t}function rpe(e){return t9e(e).toLowerCase().replace(/\s+/g," ").trim().replace(/[.,:;!?]+$/u,"").replace(/\s*\d+\s*$/u,"").trim()}function n9e(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 o9e(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":Q8e.test(t)?"@gen":rpe(t)}function ipe(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=>X8e.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=o9e(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"||ope.has(o)?n.tokens.push(`label=${rpe(a)}`):n.tokens.push(n9e(a))),(o==="button"||r==="button")&&(n.counts.buttons+=1),(o==="a"||r==="link")&&(n.counts.links+=1),(e9e.has(o)||r==="textbox"||r==="combobox")&&(n.counts.formFields+=1),(ope.has(o)||r==="heading")&&(n.counts.headings+=1);for(let l of e.children??[])ipe(l,t+1,n);}function spe(e){let t={tokens:[],counts:{buttons:0,links:0,formFields:0,headings:0}};return ipe(e,0,t),{tokens:t.tokens,counts:t.counts}}function ape(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 mO=128,r9e=4294967295,i9e=(()=>{let e=[];for(let t=0;t<mO;t++)e.push(ape(`perm:${t}`,0));return e})();function lpe(e){let t=new Uint32Array(mO);for(let o=0;o<mO;o++)t[o]=r9e;let n=new Set(e);for(let o of n)for(let r=0;r<mO;r++){let i=ape(o,i9e[r]);i<t[r]&&(t[r]=i);}return t}var a9e=32;function sG(e){let t=npe(e.url,{queryAllowlist:e.queryAllowlist}),{tokens:n,counts:o}=spe(e.dom),r=[`url:${t}`,`counts:buttons=${o.buttons}`,`counts:links=${o.links}`,`counts:formFields=${o.formFields}`,`counts:headings=${o.headings}`,...n],i=lpe(r),s=Buffer.from(i.buffer,i.byteOffset,i.byteLength);return {fingerprintHash:createHash$1("sha256").update(s).digest("hex").slice(0,a9e),minhash:Array.from(i),canonicalUrl:t}}var l9e=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]),Xn="\uFFFD",L;(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";})(L||(L={}));var ts={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function hO(e){return e>=55296&&e<=57343}function cpe(e){return e>=56320&&e<=57343}function dpe(e,t){return (e-55296)*1024+9216+t}function gO(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function fO(e){return e>=64976&&e<=65007||l9e.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 d9e=65536,yO=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=d9e,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(cpe(n))return this.pos++,this._addGap(),dpe(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=true,L.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,L.EOF;let o=this.html.charCodeAt(n);return o===L.CARRIAGE_RETURN?L.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,L.EOF;let t=this.html.charCodeAt(this.pos);return t===L.CARRIAGE_RETURN?(this.isEol=true,this.skipNextNewLine=true,L.LINE_FEED):t===L.LINE_FEED&&(this.isEol=true,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=false,this._addGap(),this.advance()):(this.skipNextNewLine=false,hO(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===L.LINE_FEED||t===L.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){gO(t)?this._err(ce.controlCharacterInInputStream):fO(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 Zt;(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";})(Zt||(Zt={}));function SO(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 p9e=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 upe(e){return e>=55296&&e<=57343||e>1114111?65533:p9e.get(e)??e}function ppe(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 aG=ppe("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 Ai;(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";})(Ai||(Ai={}));var wo;(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";})(wo||(wo={}));var mpe=32;function lG(e){return e>=wo.ZERO&&e<=wo.NINE}function m9e(e){return e>=wo.UPPER_A&&e<=wo.UPPER_F||e>=wo.LOWER_A&&e<=wo.LOWER_F}function h9e(e){return e>=wo.UPPER_A&&e<=wo.UPPER_Z||e>=wo.LOWER_A&&e<=wo.LOWER_Z||lG(e)}function g9e(e){return e===wo.EQUALS||h9e(e)}var Fr;(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";})(Fr||(Fr={}));var Xc;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute";})(Xc||(Xc={}));var bO=class{decodeTree;emitCodePoint;errors;constructor(t,n,o){this.decodeTree=t,this.emitCodePoint=n,this.errors=o;}state=Fr.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Xc.Strict;runConsumed=0;startEntity(t){this.decodeMode=t,this.state=Fr.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0;}write(t,n){switch(this.state){case Fr.EntityStart:return t.charCodeAt(n)===wo.NUM?(this.state=Fr.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=Fr.NamedEntity,this.stateNamedEntity(t,n));case Fr.NumericStart:return this.stateNumericStart(t,n);case Fr.NumericDecimal:return this.stateNumericDecimal(t,n);case Fr.NumericHex:return this.stateNumericHex(t,n);case Fr.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|mpe)===wo.LOWER_X?(this.state=Fr.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=Fr.NumericDecimal,this.stateNumericDecimal(t,n))}stateNumericHex(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(lG(o)||m9e(o)){let r=o<=wo.NINE?o-wo.ZERO:(o|mpe)-wo.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(lG(o))this.result=this.result*10+(o-wo.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===wo.SEMI)this.consumed+=1;else if(this.decodeMode===Xc.Strict)return 0;return this.emitCodePoint(upe(this.result),this.consumed),this.errors&&(t!==wo.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){let{decodeTree:o}=this,r=o[this.treeIndex],i=(r&Ai.VALUE_LENGTH)>>14;for(;n<t.length;){if(i===0&&r&Ai.FLAG13){let a=(r&Ai.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let l=r&Ai.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&Ai.VALUE_LENGTH)>>14;}if(n>=t.length)break;let s=t.charCodeAt(n);if(s===wo.SEMI&&i!==0&&r&Ai.FLAG13)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=f9e(o,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return this.result===0||this.decodeMode===Xc.Attribute&&(i===0||g9e(s))?0:this.emitNotTerminatedNamedEntity();if(r=o[this.treeIndex],i=(r&Ai.VALUE_LENGTH)>>14,i!==0){if(s===wo.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==Xc.Strict&&!(r&Ai.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]&Ai.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]&~(Ai.VALUE_LENGTH|Ai.FLAG13):r[t+1],o),n===3&&this.emitCodePoint(r[t+2],o),o}end(){switch(this.state){case Fr.NamedEntity:return this.result!==0&&(this.decodeMode!==Xc.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Fr.NumericDecimal:return this.emitNumericEntity(0,2);case Fr.NumericHex:return this.emitNumericEntity(0,3);case Fr.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Fr.EntityStart:return 0}}};function f9e(e,t,n,o){let r=(t&Ai.BRANCH_LENGTH)>>7,i=t&Ai.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 Ce;(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/";})(Ce||(Ce={}));var fu;(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";})(fu||(fu={}));var ns;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks";})(ns||(ns={}));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 y9e=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 $h(e){var t;return (t=y9e.get(e))!==null&&t!==void 0?t:b.UNKNOWN}var Me=b,hpe={[Ce.HTML]:new Set([Me.ADDRESS,Me.APPLET,Me.AREA,Me.ARTICLE,Me.ASIDE,Me.BASE,Me.BASEFONT,Me.BGSOUND,Me.BLOCKQUOTE,Me.BODY,Me.BR,Me.BUTTON,Me.CAPTION,Me.CENTER,Me.COL,Me.COLGROUP,Me.DD,Me.DETAILS,Me.DIR,Me.DIV,Me.DL,Me.DT,Me.EMBED,Me.FIELDSET,Me.FIGCAPTION,Me.FIGURE,Me.FOOTER,Me.FORM,Me.FRAME,Me.FRAMESET,Me.H1,Me.H2,Me.H3,Me.H4,Me.H5,Me.H6,Me.HEAD,Me.HEADER,Me.HGROUP,Me.HR,Me.HTML,Me.IFRAME,Me.IMG,Me.INPUT,Me.LI,Me.LINK,Me.LISTING,Me.MAIN,Me.MARQUEE,Me.MENU,Me.META,Me.NAV,Me.NOEMBED,Me.NOFRAMES,Me.NOSCRIPT,Me.OBJECT,Me.OL,Me.P,Me.PARAM,Me.PLAINTEXT,Me.PRE,Me.SCRIPT,Me.SECTION,Me.SELECT,Me.SOURCE,Me.STYLE,Me.SUMMARY,Me.TABLE,Me.TBODY,Me.TD,Me.TEMPLATE,Me.TEXTAREA,Me.TFOOT,Me.TH,Me.THEAD,Me.TITLE,Me.TR,Me.TRACK,Me.UL,Me.WBR,Me.XMP]),[Ce.MATHML]:new Set([Me.MI,Me.MO,Me.MN,Me.MS,Me.MTEXT,Me.ANNOTATION_XML]),[Ce.SVG]:new Set([Me.TITLE,Me.FOREIGN_OBJECT,Me.DESC]),[Ce.XLINK]:new Set,[Ce.XML]:new Set,[Ce.XMLNS]:new Set},JE=new Set([Me.H1,Me.H2,Me.H3,Me.H4,Me.H5,Me.H6]);new Set([ie.STYLE,ie.SCRIPT,ie.XMP,ie.IFRAME,ie.NOEMBED,ie.NOFRAMES,ie.PLAINTEXT]);var H;(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";})(H||(H={}));var Ei={DATA:H.DATA,RCDATA:H.RCDATA,RAWTEXT:H.RAWTEXT,SCRIPT_DATA:H.SCRIPT_DATA,PLAINTEXT:H.PLAINTEXT,CDATA_SECTION:H.CDATA_SECTION};function b9e(e){return e>=L.DIGIT_0&&e<=L.DIGIT_9}function XE(e){return e>=L.LATIN_CAPITAL_A&&e<=L.LATIN_CAPITAL_Z}function T9e(e){return e>=L.LATIN_SMALL_A&&e<=L.LATIN_SMALL_Z}function Zp(e){return T9e(e)||XE(e)}function gpe(e){return Zp(e)||b9e(e)}function TO(e){return e+32}function ype(e){return e===L.SPACE||e===L.LINE_FEED||e===L.TABULATION||e===L.FORM_FEED}function fpe(e){return ype(e)||e===L.SOLIDUS||e===L.GREATER_THAN_SIGN}function A9e(e){return e===L.NULL?ce.nullCharacterReference:e>1114111?ce.characterReferenceOutsideUnicodeRange:hO(e)?ce.surrogateCharacterReference:fO(e)?ce.noncharacterCharacterReference:gO(e)||e===L.CARRIAGE_RETURN?ce.controlCharacterReference:null}var QE=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=H.DATA,this.returnState=H.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new yO(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new bO(aG,(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=A9e(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:Zt.START_TAG,tagName:"",tagID:b.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(1)};}_createEndTagToken(){this.currentToken={type:Zt.END_TAG,tagName:"",tagID:b.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(2)};}_createCommentToken(t){this.currentToken={type:Zt.COMMENT,data:"",location:this.getCurrentLocation(t)};}_createDoctypeToken(t){this.currentToken={type:Zt.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(SO(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=$h(t.tagName),t.type===Zt.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 Zt.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Zt.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Zt.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:Zt.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=ype(t)?Zt.WHITESPACE_CHARACTER:t===L.NULL?Zt.NULL_CHARACTER:Zt.CHARACTER;this._appendCharToCurrentCharacterToken(n,t<65536?String.fromCharCode(t):String.fromCodePoint(t));}_emitChars(t){this._appendCharToCurrentCharacterToken(Zt.CHARACTER,t);}_startCharacterReference(){this.returnState=this.state,this.state=H.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Xc.Attribute:Xc.Legacy);}_isCharacterReferenceInAttribute(){return this.returnState===H.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===H.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===H.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t);}_callState(t){switch(this.state){case H.DATA:{this._stateData(t);break}case H.RCDATA:{this._stateRcdata(t);break}case H.RAWTEXT:{this._stateRawtext(t);break}case H.SCRIPT_DATA:{this._stateScriptData(t);break}case H.PLAINTEXT:{this._statePlaintext(t);break}case H.TAG_OPEN:{this._stateTagOpen(t);break}case H.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case H.TAG_NAME:{this._stateTagName(t);break}case H.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case H.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case H.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case H.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case H.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case H.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case H.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case H.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case H.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case H.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case H.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case H.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case H.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case H.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case H.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case H.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case H.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case H.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case H.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case H.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case H.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case H.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case H.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case H.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case H.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case H.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case H.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case H.BOGUS_COMMENT:{this._stateBogusComment(t);break}case H.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case H.COMMENT_START:{this._stateCommentStart(t);break}case H.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case H.COMMENT:{this._stateComment(t);break}case H.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case H.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case H.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case H.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case H.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case H.COMMENT_END:{this._stateCommentEnd(t);break}case H.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case H.DOCTYPE:{this._stateDoctype(t);break}case H.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case H.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case H.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case H.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case H.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case H.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case H.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case H.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case H.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case H.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case H.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case H.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case H.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case H.CDATA_SECTION:{this._stateCdataSection(t);break}case H.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case H.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case H.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case H.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case L.LESS_THAN_SIGN:{this.state=H.TAG_OPEN;break}case L.AMPERSAND:{this._startCharacterReference();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitCodePoint(t);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRcdata(t){switch(t){case L.AMPERSAND:{this._startCharacterReference();break}case L.LESS_THAN_SIGN:{this.state=H.RCDATA_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRawtext(t){switch(t){case L.LESS_THAN_SIGN:{this.state=H.RAWTEXT_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptData(t){switch(t){case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_statePlaintext(t){switch(t){case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateTagOpen(t){if(Zp(t))this._createStartTagToken(),this.state=H.TAG_NAME,this._stateTagName(t);else switch(t){case L.EXCLAMATION_MARK:{this.state=H.MARKUP_DECLARATION_OPEN;break}case L.SOLIDUS:{this.state=H.END_TAG_OPEN;break}case L.QUESTION_MARK:{this._err(ce.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=H.BOGUS_COMMENT,this._stateBogusComment(t);break}case L.EOF:{this._err(ce.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(ce.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=H.DATA,this._stateData(t);}}_stateEndTagOpen(t){if(Zp(t))this._createEndTagToken(),this.state=H.TAG_NAME,this._stateTagName(t);else switch(t){case L.GREATER_THAN_SIGN:{this._err(ce.missingEndTagName),this.state=H.DATA;break}case L.EOF:{this._err(ce.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(ce.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=H.BOGUS_COMMENT,this._stateBogusComment(t);}}_stateTagName(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BEFORE_ATTRIBUTE_NAME;break}case L.SOLIDUS:{this.state=H.SELF_CLOSING_START_TAG;break}case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentTagToken();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.tagName+=Xn;break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(XE(t)?TO(t):t);}}_stateRcdataLessThanSign(t){t===L.SOLIDUS?this.state=H.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=H.RCDATA,this._stateRcdata(t));}_stateRcdataEndTagOpen(t){Zp(t)?(this.state=H.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=H.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 L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=H.BEFORE_ATTRIBUTE_NAME,false;case L.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=H.SELF_CLOSING_START_TAG,false;case L.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=H.DATA,false;default:return !this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=H.RCDATA,this._stateRcdata(t));}_stateRawtextLessThanSign(t){t===L.SOLIDUS?this.state=H.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=H.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagOpen(t){Zp(t)?(this.state=H.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=H.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=H.RAWTEXT,this._stateRawtext(t));}_stateScriptDataLessThanSign(t){switch(t){case L.SOLIDUS:{this.state=H.SCRIPT_DATA_END_TAG_OPEN;break}case L.EXCLAMATION_MARK:{this.state=H.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=H.SCRIPT_DATA,this._stateScriptData(t);}}_stateScriptDataEndTagOpen(t){Zp(t)?(this.state=H.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=H.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=H.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStart(t){t===L.HYPHEN_MINUS?(this.state=H.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=H.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStartDash(t){t===L.HYPHEN_MINUS?(this.state=H.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=H.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscaped(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataEscapedDash(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.state=H.SCRIPT_DATA_ESCAPED,this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=H.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedDashDash(t){switch(t){case L.HYPHEN_MINUS:{this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case L.GREATER_THAN_SIGN:{this.state=H.SCRIPT_DATA,this._emitChars(">");break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.state=H.SCRIPT_DATA_ESCAPED,this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=H.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedLessThanSign(t){t===L.SOLIDUS?this.state=H.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Zp(t)?(this._emitChars("<"),this.state=H.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=H.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagOpen(t){Zp(t)?(this.state=H.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=H.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=H.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(ts.SCRIPT,false)&&fpe(this.preprocessor.peek(ts.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<ts.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED;}else this._ensureHibernation()||(this.state=H.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscaped(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDash(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case L.HYPHEN_MINUS:{this._emitChars("-");break}case L.LESS_THAN_SIGN:{this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case L.GREATER_THAN_SIGN:{this.state=H.SCRIPT_DATA,this._emitChars(">");break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Xn);break}case L.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedLessThanSign(t){t===L.SOLIDUS?(this.state=H.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(ts.SCRIPT,false)&&fpe(this.preprocessor.peek(ts.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<ts.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=H.SCRIPT_DATA_ESCAPED;}else this._ensureHibernation()||(this.state=H.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateBeforeAttributeName(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.SOLIDUS:case L.GREATER_THAN_SIGN:case L.EOF:{this.state=H.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case L.EQUALS_SIGN:{this._err(ce.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=H.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=H.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateAttributeName(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:case L.SOLIDUS:case L.GREATER_THAN_SIGN:case L.EOF:{this._leaveAttrName(),this.state=H.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case L.EQUALS_SIGN:{this._leaveAttrName(),this.state=H.BEFORE_ATTRIBUTE_VALUE;break}case L.QUOTATION_MARK:case L.APOSTROPHE:case L.LESS_THAN_SIGN:{this._err(ce.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.name+=Xn;break}default:this.currentAttr.name+=String.fromCodePoint(XE(t)?TO(t):t);}}_stateAfterAttributeName(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.SOLIDUS:{this.state=H.SELF_CLOSING_START_TAG;break}case L.EQUALS_SIGN:{this.state=H.BEFORE_ATTRIBUTE_VALUE;break}case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentTagToken();break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=H.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateBeforeAttributeValue(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.QUOTATION_MARK:{this.state=H.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case L.APOSTROPHE:{this.state=H.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingAttributeValue),this.state=H.DATA,this.emitCurrentTagToken();break}default:this.state=H.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t);}}_stateAttributeValueDoubleQuoted(t){switch(t){case L.QUOTATION_MARK:{this.state=H.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case L.AMPERSAND:{this._startCharacterReference();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Xn;break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueSingleQuoted(t){switch(t){case L.APOSTROPHE:{this.state=H.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case L.AMPERSAND:{this._startCharacterReference();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Xn;break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueUnquoted(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this._leaveAttrValue(),this.state=H.BEFORE_ATTRIBUTE_NAME;break}case L.AMPERSAND:{this._startCharacterReference();break}case L.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=H.DATA,this.emitCurrentTagToken();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Xn;break}case L.QUOTATION_MARK:case L.APOSTROPHE:case L.LESS_THAN_SIGN:case L.EQUALS_SIGN:case L.GRAVE_ACCENT:{this._err(ce.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAfterAttributeValueQuoted(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this._leaveAttrValue(),this.state=H.BEFORE_ATTRIBUTE_NAME;break}case L.SOLIDUS:{this._leaveAttrValue(),this.state=H.SELF_CLOSING_START_TAG;break}case L.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=H.DATA,this.emitCurrentTagToken();break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._err(ce.missingWhitespaceBetweenAttributes),this.state=H.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateSelfClosingStartTag(t){switch(t){case L.GREATER_THAN_SIGN:{let n=this.currentToken;n.selfClosing=true,this.state=H.DATA,this.emitCurrentTagToken();break}case L.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._err(ce.unexpectedSolidusInTag),this.state=H.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateBogusComment(t){let n=this.currentToken;switch(t){case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentComment(n);break}case L.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.data+=Xn;break}default:n.data+=String.fromCodePoint(t);}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(ts.DASH_DASH,true)?(this._createCommentToken(ts.DASH_DASH.length+1),this.state=H.COMMENT_START):this._consumeSequenceIfMatch(ts.DOCTYPE,false)?(this.currentLocation=this.getCurrentLocation(ts.DOCTYPE.length+1),this.state=H.DOCTYPE):this._consumeSequenceIfMatch(ts.CDATA_START,true)?this.inForeignNode?this.state=H.CDATA_SECTION:(this._err(ce.cdataInHtmlContent),this._createCommentToken(ts.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=H.BOGUS_COMMENT):this._ensureHibernation()||(this._err(ce.incorrectlyOpenedComment),this._createCommentToken(2),this.state=H.BOGUS_COMMENT,this._stateBogusComment(t));}_stateCommentStart(t){switch(t){case L.HYPHEN_MINUS:{this.state=H.COMMENT_START_DASH;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptClosingOfEmptyComment),this.state=H.DATA;let n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=H.COMMENT,this._stateComment(t);}}_stateCommentStartDash(t){let n=this.currentToken;switch(t){case L.HYPHEN_MINUS:{this.state=H.COMMENT_END;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptClosingOfEmptyComment),this.state=H.DATA,this.emitCurrentComment(n);break}case L.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=H.COMMENT,this._stateComment(t);}}_stateComment(t){let n=this.currentToken;switch(t){case L.HYPHEN_MINUS:{this.state=H.COMMENT_END_DASH;break}case L.LESS_THAN_SIGN:{n.data+="<",this.state=H.COMMENT_LESS_THAN_SIGN;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.data+=Xn;break}case L.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 L.EXCLAMATION_MARK:{n.data+="!",this.state=H.COMMENT_LESS_THAN_SIGN_BANG;break}case L.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=H.COMMENT,this._stateComment(t);}}_stateCommentLessThanSignBang(t){t===L.HYPHEN_MINUS?this.state=H.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=H.COMMENT,this._stateComment(t));}_stateCommentLessThanSignBangDash(t){t===L.HYPHEN_MINUS?this.state=H.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=H.COMMENT_END_DASH,this._stateCommentEndDash(t));}_stateCommentLessThanSignBangDashDash(t){t!==L.GREATER_THAN_SIGN&&t!==L.EOF&&this._err(ce.nestedComment),this.state=H.COMMENT_END,this._stateCommentEnd(t);}_stateCommentEndDash(t){let n=this.currentToken;switch(t){case L.HYPHEN_MINUS:{this.state=H.COMMENT_END;break}case L.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=H.COMMENT,this._stateComment(t);}}_stateCommentEnd(t){let n=this.currentToken;switch(t){case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentComment(n);break}case L.EXCLAMATION_MARK:{this.state=H.COMMENT_END_BANG;break}case L.HYPHEN_MINUS:{n.data+="-";break}case L.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=H.COMMENT,this._stateComment(t);}}_stateCommentEndBang(t){let n=this.currentToken;switch(t){case L.HYPHEN_MINUS:{n.data+="--!",this.state=H.COMMENT_END_DASH;break}case L.GREATER_THAN_SIGN:{this._err(ce.incorrectlyClosedComment),this.state=H.DATA,this.emitCurrentComment(n);break}case L.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=H.COMMENT,this._stateComment(t);}}_stateDoctype(t){switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BEFORE_DOCTYPE_NAME;break}case L.GREATER_THAN_SIGN:{this.state=H.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case L.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=H.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);}}_stateBeforeDoctypeName(t){if(XE(t))this._createDoctypeToken(String.fromCharCode(TO(t))),this.state=H.DOCTYPE_NAME;else switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.NULL:{this._err(ce.unexpectedNullCharacter),this._createDoctypeToken(Xn),this.state=H.DOCTYPE_NAME;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeName),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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=H.DOCTYPE_NAME;}}_stateDoctypeName(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.AFTER_DOCTYPE_NAME;break}case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.name+=Xn;break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(XE(t)?TO(t):t);}}_stateAfterDoctypeName(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(ts.PUBLIC,false)?this.state=H.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(ts.SYSTEM,false)?this.state=H.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(ce.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t));}}_stateAfterDoctypePublicKeyword(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case L.QUOTATION_MARK:{this._err(ce.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=H.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{this._err(ce.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=H.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.QUOTATION_MARK:{n.publicId="",this.state=H.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{n.publicId="",this.state=H.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypePublicIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case L.QUOTATION_MARK:{this.state=H.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.publicId+=Xn;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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 L.APOSTROPHE:{this.state=H.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.publicId+=Xn;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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 L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case L.GREATER_THAN_SIGN:{this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.QUOTATION_MARK:{this._err(ce.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{this._err(ce.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.QUOTATION_MARK:{n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateAfterDoctypeSystemKeyword(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:{this.state=H.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case L.QUOTATION_MARK:{this._err(ce.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{this._err(ce.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.QUOTATION_MARK:{n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case L.APOSTROPHE:{n.systemId="",this.state=H.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case L.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.DATA,this.emitCurrentDoctype(n);break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypeSystemIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case L.QUOTATION_MARK:{this.state=H.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.systemId+=Xn;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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 L.APOSTROPHE:{this.state=H.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case L.NULL:{this._err(ce.unexpectedNullCharacter),n.systemId+=Xn;break}case L.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.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 L.SPACE:case L.LINE_FEED:case L.TABULATION:case L.FORM_FEED:break;case L.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=H.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBogusDoctype(t){let n=this.currentToken;switch(t){case L.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=H.DATA;break}case L.NULL:{this._err(ce.unexpectedNullCharacter);break}case L.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case L.RIGHT_SQUARE_BRACKET:{this.state=H.CDATA_SECTION_BRACKET;break}case L.EOF:{this._err(ce.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateCdataSectionBracket(t){t===L.RIGHT_SQUARE_BRACKET?this.state=H.CDATA_SECTION_END:(this._emitChars("]"),this.state=H.CDATA_SECTION,this._stateCdataSection(t));}_stateCdataSectionEnd(t){switch(t){case L.GREATER_THAN_SIGN:{this.state=H.DATA;break}case L.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=H.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(L.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&gpe(this.preprocessor.peek(1))?H.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState;}_stateAmbiguousAmpersand(t){gpe(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===L.SEMICOLON&&this._err(ce.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t));}};var Ape=new Set([b.DD,b.DT,b.LI,b.OPTGROUP,b.OPTION,b.P,b.RB,b.RP,b.RT,b.RTC]),Spe=new Set([...Ape,b.CAPTION,b.COLGROUP,b.TBODY,b.TD,b.TFOOT,b.TH,b.THEAD,b.TR]),AO=new Set([b.APPLET,b.CAPTION,b.HTML,b.MARQUEE,b.OBJECT,b.TABLE,b.TD,b.TEMPLATE,b.TH]),E9e=new Set([...AO,b.OL,b.UL]),v9e=new Set([...AO,b.BUTTON]),bpe=new Set([b.ANNOTATION_XML,b.MI,b.MN,b.MO,b.MS,b.MTEXT]),Tpe=new Set([b.DESC,b.FOREIGN_OBJECT,b.TITLE]),C9e=new Set([b.TR,b.TEMPLATE,b.HTML]),R9e=new Set([b.TBODY,b.TFOOT,b.THEAD,b.TEMPLATE,b.HTML]),w9e=new Set([b.TABLE,b.TEMPLATE,b.HTML]),I9e=new Set([b.TD,b.TH]),EO=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)===Ce.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])!==Ce.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(JE,Ce.HTML);}popUntilTableCellPopped(){this.popUntilPopped(I9e,Ce.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(w9e,Ce.HTML);}clearBackToTableBodyContext(){this.clearBackTo(R9e,Ce.HTML);}clearBackToTableRowContext(){this.clearBackTo(C9e,Ce.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 Ce.HTML:{if(r===t)return true;if(n.has(r))return false;break}case Ce.SVG:{if(Tpe.has(r))return false;break}case Ce.MATHML:{if(bpe.has(r))return false;break}}}return true}hasInScope(t){return this.hasInDynamicScope(t,AO)}hasInListItemScope(t){return this.hasInDynamicScope(t,E9e)}hasInButtonScope(t){return this.hasInDynamicScope(t,v9e)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){let n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case Ce.HTML:{if(JE.has(n))return true;if(AO.has(n))return false;break}case Ce.SVG:{if(Tpe.has(n))return false;break}case Ce.MATHML:{if(bpe.has(n))return false;break}}}return true}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===Ce.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])===Ce.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])===Ce.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&&Ape.has(this.currentTagId);)this.pop();}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&Spe.has(this.currentTagId);)this.pop();}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&Spe.has(this.currentTagId);)this.pop();}};var Fl;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element";})(Fl||(Fl={}));var Epe={type:Fl.Marker},vO=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===Fl.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(Epe);}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:Fl.Element,element:t,token:n});}insertElementAfterBookmark(t,n){let o=this.entries.indexOf(this.bookmark);this.entries.splice(o,0,{type:Fl.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(Epe);t===-1?this.entries.length=0:this.entries.splice(0,t+1);}getElementEntryInScopeWithTagName(t){let n=this.entries.find(o=>o.type===Fl.Marker||this.treeAdapter.getTagName(o.element)===t);return n&&n.type===Fl.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===Fl.Element&&n.element===t)}};var Bl={createDocument(){return {nodeName:"#document",mode:ns.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};Bl.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(Bl.isTextNode(n)){n.value+=t;return}}Bl.appendChild(e,Bl.createTextNode(t));},insertTextBefore(e,t,n){let o=e.childNodes[e.childNodes.indexOf(n)-1];o&&Bl.isTextNode(o)?o.value+=t:Bl.insertBefore(e,Bl.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 Cpe="html",x9e="about:legacy-compat",_9e="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",Rpe=["+//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//"],P9e=[...Rpe,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],O9e=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),wpe=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],M9e=[...wpe,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function vpe(e,t){return t.some(n=>e.startsWith(n))}function Ipe(e){return e.name===Cpe&&e.publicId===null&&(e.systemId===null||e.systemId===x9e)}function xpe(e){if(e.name!==Cpe)return ns.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===_9e)return ns.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),O9e.has(n))return ns.QUIRKS;let o=t===null?P9e:Rpe;if(vpe(n,o))return ns.QUIRKS;if(o=t===null?wpe:M9e,vpe(n,o))return ns.LIMITED_QUIRKS}return ns.NO_QUIRKS}var _pe={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},L9e="definitionurl",k9e="definitionURL",D9e=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])),F9e=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:Ce.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:Ce.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:Ce.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:Ce.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:Ce.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:Ce.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:Ce.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:Ce.XML}],["xml:space",{prefix:"xml",name:"space",namespace:Ce.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:Ce.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:Ce.XMLNS}]]),B9e=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])),U9e=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 Ppe(e){let t=e.tagID;return t===b.FONT&&e.attrs.some(({name:o})=>o===fu.COLOR||o===fu.SIZE||o===fu.FACE)||U9e.has(t)}function cG(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===L9e){e.attrs[t].name=k9e;break}}function dG(e){for(let t=0;t<e.attrs.length;t++){let n=D9e.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n);}}function CO(e){for(let t=0;t<e.attrs.length;t++){let n=F9e.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 Ope(e){let t=B9e.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=$h(e.tagName));}function H9e(e,t){return t===Ce.MATHML&&(e===b.MI||e===b.MO||e===b.MN||e===b.MS||e===b.MTEXT)}function j9e(e,t,n){if(t===Ce.MATHML&&e===b.ANNOTATION_XML){for(let o=0;o<n.length;o++)if(n[o].name===fu.ENCODING){let r=n[o].value.toLowerCase();return r===_pe.TEXT_HTML||r===_pe.APPLICATION_XML}}return t===Ce.SVG&&(e===b.FOREIGN_OBJECT||e===b.DESC||e===b.TITLE)}function Mpe(e,t,n,o){return (!o||o===Ce.HTML)&&j9e(e,t,n)||(!o||o===Ce.MATHML)&&H9e(e,t)}var G9e="hidden",$9e=8,V9e=3,z;(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";})(z||(z={}));var z9e={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Fpe=new Set([b.TABLE,b.TBODY,b.TFOOT,b.THEAD,b.TR]),Lpe={scriptingEnabled:true,sourceCodeLocationInfo:false,treeAdapter:Bl,onParseError:null},sv=class{constructor(t,n,o=null,r=null){this.fragmentContext=o,this.scriptHandler=r,this.currentToken=null,this.stopped=false,this.insertionMode=z.INITIAL,this.originalInsertionMode=z.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={...Lpe,...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 QE(this.options,this),this.activeFormattingElements=new vO(this.treeAdapter),this.fragmentContextID=o?$h(this.treeAdapter.getTagName(o)):b.UNKNOWN,this._setContextModes(o??this.document,this.fragmentContextID),this.openElements=new EO(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={...Lpe,...n};t??(t=o.treeAdapter.createElement(ie.TEMPLATE,Ce.HTML,[]));let r=o.treeAdapter.createElement("documentmock",Ce.HTML,[]),i=new this(o,r,t);return i.fragmentContextID===b.TEMPLATE&&i.tmplInsertionModeStack.unshift(z.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:z9e,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)===Ce.HTML;this.currentNotInHTML=!o,this.tokenizer.inForeignNode=!o&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t);}_switchToTextParsing(t,n){this._insertElement(t,Ce.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=z.TEXT;}switchToPlaintextParsing(){this.insertionMode=z.TEXT,this.originalInsertionMode=z.IN_BODY,this.tokenizer.state=Ei.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)!==Ce.HTML))switch(this.fragmentContextID){case b.TITLE:case b.TEXTAREA:{this.tokenizer.state=Ei.RCDATA;break}case b.STYLE:case b.XMP:case b.IFRAME:case b.NOEMBED:case b.NOFRAMES:case b.NOSCRIPT:{this.tokenizer.state=Ei.RAWTEXT;break}case b.SCRIPT:{this.tokenizer.state=Ei.SCRIPT_DATA;break}case b.PLAINTEXT:{this.tokenizer.state=Ei.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,Ce.HTML,[]);this._attachElementToTree(o,null),this.openElements.push(o,n);}_insertTemplate(t){let n=this.treeAdapter.createElement(t.tagName,Ce.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,Ce.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===Zt.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)===Ce.MATHML?false:this.tokenizer.inForeignNode||(t.tagID===b.MGLYPH||t.tagID===b.MALIGNMARK)&&o!==void 0&&!this._isIntegrationPoint(o,n,Ce.HTML)}_processToken(t){switch(t.type){case Zt.CHARACTER:{this.onCharacter(t);break}case Zt.NULL_CHARACTER:{this.onNullCharacter(t);break}case Zt.COMMENT:{this.onComment(t);break}case Zt.DOCTYPE:{this.onDoctype(t);break}case Zt.START_TAG:{this._processStartTag(t);break}case Zt.END_TAG:{this.onEndTag(t);break}case Zt.EOF:{this.onEof(t);break}case Zt.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,o){let r=this.treeAdapter.getNamespaceURI(n),i=this.treeAdapter.getAttrList(n);return Mpe(t,r,i,o)}_reconstructActiveFormattingElements(){let t=this.activeFormattingElements.entries.length;if(t){let n=this.activeFormattingElements.entries.findIndex(r=>r.type===Fl.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=z.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=z.IN_ROW;return}case b.TBODY:case b.THEAD:case b.TFOOT:{this.insertionMode=z.IN_TABLE_BODY;return}case b.CAPTION:{this.insertionMode=z.IN_CAPTION;return}case b.COLGROUP:{this.insertionMode=z.IN_COLUMN_GROUP;return}case b.TABLE:{this.insertionMode=z.IN_TABLE;return}case b.BODY:{this.insertionMode=z.IN_BODY;return}case b.FRAMESET:{this.insertionMode=z.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?z.AFTER_HEAD:z.BEFORE_HEAD;return}case b.TD:case b.TH:{if(t>0){this.insertionMode=z.IN_CELL;return}break}case b.HEAD:{if(t>0){this.insertionMode=z.IN_HEAD;return}break}}this.insertionMode=z.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=z.IN_SELECT_IN_TABLE;return}}this.insertionMode=z.IN_SELECT;}_isElementCausesFosterParenting(t){return Fpe.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)===Ce.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 hpe[o].has(n)}onCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){vet(this,t);return}switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{tv(this,t);break}case z.BEFORE_HEAD:{nv(this,t);break}case z.IN_HEAD:{ov(this,t);break}case z.IN_HEAD_NO_SCRIPT:{rv(this,t);break}case z.AFTER_HEAD:{iv(this,t);break}case z.IN_BODY:case z.IN_CAPTION:case z.IN_CELL:case z.IN_TEMPLATE:{Upe(this,t);break}case z.TEXT:case z.IN_SELECT:case z.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case z.IN_TABLE:case z.IN_TABLE_BODY:case z.IN_ROW:{uG(this,t);break}case z.IN_TABLE_TEXT:{zpe(this,t);break}case z.IN_COLUMN_GROUP:{wO(this,t);break}case z.AFTER_BODY:{IO(this,t);break}case z.AFTER_AFTER_BODY:{RO(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){Eet(this,t);return}switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{tv(this,t);break}case z.BEFORE_HEAD:{nv(this,t);break}case z.IN_HEAD:{ov(this,t);break}case z.IN_HEAD_NO_SCRIPT:{rv(this,t);break}case z.AFTER_HEAD:{iv(this,t);break}case z.TEXT:{this._insertCharacters(t);break}case z.IN_TABLE:case z.IN_TABLE_BODY:case z.IN_ROW:{uG(this,t);break}case z.IN_COLUMN_GROUP:{wO(this,t);break}case z.AFTER_BODY:{IO(this,t);break}case z.AFTER_AFTER_BODY:{RO(this,t);break}}}onComment(t){if(this.skipNextNewLine=false,this.currentNotInHTML){pG(this,t);return}switch(this.insertionMode){case z.INITIAL:case z.BEFORE_HTML:case z.BEFORE_HEAD:case z.IN_HEAD:case z.IN_HEAD_NO_SCRIPT:case z.AFTER_HEAD:case z.IN_BODY:case z.IN_TABLE:case z.IN_CAPTION:case z.IN_COLUMN_GROUP:case z.IN_TABLE_BODY:case z.IN_ROW:case z.IN_CELL:case z.IN_SELECT:case z.IN_SELECT_IN_TABLE:case z.IN_TEMPLATE:case z.IN_FRAMESET:case z.AFTER_FRAMESET:{pG(this,t);break}case z.IN_TABLE_TEXT:{ev(this,t);break}case z.AFTER_BODY:{Q9e(this,t);break}case z.AFTER_AFTER_BODY:case z.AFTER_AFTER_FRAMESET:{Z9e(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=false,this.insertionMode){case z.INITIAL:{e7e(this,t);break}case z.BEFORE_HEAD:case z.IN_HEAD:case z.IN_HEAD_NO_SCRIPT:case z.AFTER_HEAD:{this._err(t,ce.misplacedDoctype);break}case z.IN_TABLE_TEXT:{ev(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)?Cet(this,t):this._startTagOutsideForeignContent(t);}_startTagOutsideForeignContent(t){switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{t7e(this,t);break}case z.BEFORE_HEAD:{o7e(this,t);break}case z.IN_HEAD:{Ul(this,t);break}case z.IN_HEAD_NO_SCRIPT:{s7e(this,t);break}case z.AFTER_HEAD:{l7e(this,t);break}case z.IN_BODY:{vi(this,t);break}case z.IN_TABLE:{CS(this,t);break}case z.IN_TABLE_TEXT:{ev(this,t);break}case z.IN_CAPTION:{ret(this,t);break}case z.IN_COLUMN_GROUP:{fG(this,t);break}case z.IN_TABLE_BODY:{PO(this,t);break}case z.IN_ROW:{OO(this,t);break}case z.IN_CELL:{aet(this,t);break}case z.IN_SELECT:{Kpe(this,t);break}case z.IN_SELECT_IN_TABLE:{det(this,t);break}case z.IN_TEMPLATE:{pet(this,t);break}case z.AFTER_BODY:{het(this,t);break}case z.IN_FRAMESET:{get(this,t);break}case z.AFTER_FRAMESET:{yet(this,t);break}case z.AFTER_AFTER_BODY:{Tet(this,t);break}case z.AFTER_AFTER_FRAMESET:{Aet(this,t);break}}}onEndTag(t){this.skipNextNewLine=false,this.currentToken=t,this.currentNotInHTML?Ret(this,t):this._endTagOutsideForeignContent(t);}_endTagOutsideForeignContent(t){switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{n7e(this,t);break}case z.BEFORE_HEAD:{r7e(this,t);break}case z.IN_HEAD:{i7e(this,t);break}case z.IN_HEAD_NO_SCRIPT:{a7e(this,t);break}case z.AFTER_HEAD:{c7e(this,t);break}case z.IN_BODY:{_O(this,t);break}case z.TEXT:{K7e(this,t);break}case z.IN_TABLE:{av(this,t);break}case z.IN_TABLE_TEXT:{ev(this,t);break}case z.IN_CAPTION:{iet(this,t);break}case z.IN_COLUMN_GROUP:{set(this,t);break}case z.IN_TABLE_BODY:{mG(this,t);break}case z.IN_ROW:{qpe(this,t);break}case z.IN_CELL:{cet(this,t);break}case z.IN_SELECT:{Ype(this,t);break}case z.IN_SELECT_IN_TABLE:{uet(this,t);break}case z.IN_TEMPLATE:{met(this,t);break}case z.AFTER_BODY:{Xpe(this,t);break}case z.IN_FRAMESET:{fet(this,t);break}case z.AFTER_FRAMESET:{bet(this,t);break}case z.AFTER_AFTER_BODY:{RO(this,t);break}}}onEof(t){switch(this.insertionMode){case z.INITIAL:{ZE(this,t);break}case z.BEFORE_HTML:{tv(this,t);break}case z.BEFORE_HEAD:{nv(this,t);break}case z.IN_HEAD:{ov(this,t);break}case z.IN_HEAD_NO_SCRIPT:{rv(this,t);break}case z.AFTER_HEAD:{iv(this,t);break}case z.IN_BODY:case z.IN_TABLE:case z.IN_CAPTION:case z.IN_COLUMN_GROUP:case z.IN_TABLE_BODY:case z.IN_ROW:case z.IN_CELL:case z.IN_SELECT:case z.IN_SELECT_IN_TABLE:{$pe(this,t);break}case z.TEXT:{Y7e(this,t);break}case z.IN_TABLE_TEXT:{ev(this,t);break}case z.IN_TEMPLATE:{Jpe(this,t);break}case z.AFTER_BODY:case z.IN_FRAMESET:case z.AFTER_FRAMESET:case z.AFTER_AFTER_BODY:case z.AFTER_AFTER_FRAMESET:{gG(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=false,t.chars.charCodeAt(0)===L.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 z.IN_HEAD:case z.IN_HEAD_NO_SCRIPT:case z.AFTER_HEAD:case z.TEXT:case z.IN_COLUMN_GROUP:case z.IN_SELECT:case z.IN_SELECT_IN_TABLE:case z.IN_FRAMESET:case z.AFTER_FRAMESET:{this._insertCharacters(t);break}case z.IN_BODY:case z.IN_CAPTION:case z.IN_CELL:case z.IN_TEMPLATE:case z.AFTER_BODY:case z.AFTER_AFTER_BODY:case z.AFTER_AFTER_FRAMESET:{Bpe(this,t);break}case z.IN_TABLE:case z.IN_TABLE_BODY:case z.IN_ROW:{uG(this,t);break}case z.IN_TABLE_TEXT:{Vpe(this,t);break}}}};function W9e(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):Gpe(e,t),n}function q9e(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 K9e(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>=V9e;!a||l?(l&&e.activeFormattingElements.removeEntry(a),e.openElements.remove(s)):(s=Y9e(e,a),o===t&&(e.activeFormattingElements.bookmark=a),e.treeAdapter.detachNode(o),e.treeAdapter.appendChild(s,o),o=s);}return o}function Y9e(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 J9e(e,t,n){let o=e.treeAdapter.getTagName(t),r=$h(o);if(e._isElementCausesFosterParenting(r))e._fosterParentElement(n);else {let i=e.treeAdapter.getNamespaceURI(t);r===b.TEMPLATE&&i===Ce.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n);}}function X9e(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 hG(e,t){for(let n=0;n<$9e;n++){let o=W9e(e,t);if(!o)break;let r=q9e(e,o);if(!r)break;e.activeFormattingElements.bookmark=o;let i=K9e(e,r,o.element),s=e.openElements.getCommonAncestor(o.element);e.treeAdapter.detachNode(i),s&&J9e(e,s,i),X9e(e,r,o);}}function pG(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode);}function Q9e(e,t){e._appendCommentNode(t,e.openElements.items[0]);}function Z9e(e,t){e._appendCommentNode(t,e.document);}function gG(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 e7e(e,t){e._setDocumentType(t);let n=t.forceQuirks?ns.QUIRKS:xpe(t);Ipe(t)||e._err(t,ce.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=z.BEFORE_HTML;}function ZE(e,t){e._err(t,ce.missingDoctype,true),e.treeAdapter.setDocumentMode(e.document,ns.QUIRKS),e.insertionMode=z.BEFORE_HTML,e._processToken(t);}function t7e(e,t){t.tagID===b.HTML?(e._insertElement(t,Ce.HTML),e.insertionMode=z.BEFORE_HEAD):tv(e,t);}function n7e(e,t){let n=t.tagID;(n===b.HTML||n===b.HEAD||n===b.BODY||n===b.BR)&&tv(e,t);}function tv(e,t){e._insertFakeRootElement(),e.insertionMode=z.BEFORE_HEAD,e._processToken(t);}function o7e(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.HEAD:{e._insertElement(t,Ce.HTML),e.headElement=e.openElements.current,e.insertionMode=z.IN_HEAD;break}default:nv(e,t);}}function r7e(e,t){let n=t.tagID;n===b.HEAD||n===b.BODY||n===b.HTML||n===b.BR?nv(e,t):e._err(t,ce.endTagWithoutMatchingOpenElement);}function nv(e,t){e._insertFakeElement(ie.HEAD,b.HEAD),e.headElement=e.openElements.current,e.insertionMode=z.IN_HEAD,e._processToken(t);}function Ul(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.BASE:case b.BASEFONT:case b.BGSOUND:case b.LINK:case b.META:{e._appendElement(t,Ce.HTML),t.ackSelfClosing=true;break}case b.TITLE:{e._switchToTextParsing(t,Ei.RCDATA);break}case b.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,Ei.RAWTEXT):(e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_HEAD_NO_SCRIPT);break}case b.NOFRAMES:case b.STYLE:{e._switchToTextParsing(t,Ei.RAWTEXT);break}case b.SCRIPT:{e._switchToTextParsing(t,Ei.SCRIPT_DATA);break}case b.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=false,e.insertionMode=z.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(z.IN_TEMPLATE);break}case b.HEAD:{e._err(t,ce.misplacedStartTagForHeadElement);break}default:ov(e,t);}}function i7e(e,t){switch(t.tagID){case b.HEAD:{e.openElements.pop(),e.insertionMode=z.AFTER_HEAD;break}case b.BODY:case b.BR:case b.HTML:{ov(e,t);break}case b.TEMPLATE:{Vh(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function Vh(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 ov(e,t){e.openElements.pop(),e.insertionMode=z.AFTER_HEAD,e._processToken(t);}function s7e(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.BASEFONT:case b.BGSOUND:case b.HEAD:case b.LINK:case b.META:case b.NOFRAMES:case b.STYLE:{Ul(e,t);break}case b.NOSCRIPT:{e._err(t,ce.nestedNoscriptInHead);break}default:rv(e,t);}}function a7e(e,t){switch(t.tagID){case b.NOSCRIPT:{e.openElements.pop(),e.insertionMode=z.IN_HEAD;break}case b.BR:{rv(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function rv(e,t){let n=t.type===Zt.EOF?ce.openElementsLeftAfterEof:ce.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=z.IN_HEAD,e._processToken(t);}function l7e(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.BODY:{e._insertElement(t,Ce.HTML),e.framesetOk=false,e.insertionMode=z.IN_BODY;break}case b.FRAMESET:{e._insertElement(t,Ce.HTML),e.insertionMode=z.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),Ul(e,t),e.openElements.remove(e.headElement);break}case b.HEAD:{e._err(t,ce.misplacedStartTagForHeadElement);break}default:iv(e,t);}}function c7e(e,t){switch(t.tagID){case b.BODY:case b.HTML:case b.BR:{iv(e,t);break}case b.TEMPLATE:{Vh(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function iv(e,t){e._insertFakeElement(ie.BODY,b.BODY),e.insertionMode=z.IN_BODY,xO(e,t);}function xO(e,t){switch(t.type){case Zt.CHARACTER:{Upe(e,t);break}case Zt.WHITESPACE_CHARACTER:{Bpe(e,t);break}case Zt.COMMENT:{pG(e,t);break}case Zt.START_TAG:{vi(e,t);break}case Zt.END_TAG:{_O(e,t);break}case Zt.EOF:{$pe(e,t);break}}}function Bpe(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t);}function Upe(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=false;}function d7e(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs);}function u7e(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=false,e.treeAdapter.adoptAttributes(n,t.attrs));}function p7e(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_FRAMESET);}function m7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML);}function h7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&JE.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,Ce.HTML);}function g7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML),e.skipNextNewLine=true,e.framesetOk=false;}function f7e(e,t){let n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML),n||(e.formElement=e.openElements.current));}function y7e(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,Ce.HTML);}function S7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML),e.tokenizer.state=Ei.PLAINTEXT;}function b7e(e,t){e.openElements.hasInScope(b.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.framesetOk=false;}function T7e(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(ie.A);n&&(hG(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function A7e(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function E7e(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(b.NOBR)&&(hG(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,Ce.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function v7e(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=false;}function C7e(e,t){e.treeAdapter.getDocumentMode(e.document)!==ns.QUIRKS&&e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Ce.HTML),e.framesetOk=false,e.insertionMode=z.IN_TABLE;}function Hpe(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Ce.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function jpe(e){let t=SO(e,fu.TYPE);return t!=null&&t.toLowerCase()===G9e}function R7e(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Ce.HTML),jpe(t)||(e.framesetOk=false),t.ackSelfClosing=true;}function w7e(e,t){e._appendElement(t,Ce.HTML),t.ackSelfClosing=true;}function I7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._appendElement(t,Ce.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function x7e(e,t){t.tagName=ie.IMG,t.tagID=b.IMG,Hpe(e,t);}function _7e(e,t){e._insertElement(t,Ce.HTML),e.skipNextNewLine=true,e.tokenizer.state=Ei.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=false,e.insertionMode=z.TEXT;}function P7e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=false,e._switchToTextParsing(t,Ei.RAWTEXT);}function O7e(e,t){e.framesetOk=false,e._switchToTextParsing(t,Ei.RAWTEXT);}function kpe(e,t){e._switchToTextParsing(t,Ei.RAWTEXT);}function M7e(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML),e.framesetOk=false,e.insertionMode=e.insertionMode===z.IN_TABLE||e.insertionMode===z.IN_CAPTION||e.insertionMode===z.IN_TABLE_BODY||e.insertionMode===z.IN_ROW||e.insertionMode===z.IN_CELL?z.IN_SELECT_IN_TABLE:z.IN_SELECT;}function N7e(e,t){e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML);}function L7e(e,t){e.openElements.hasInScope(b.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,Ce.HTML);}function k7e(e,t){e.openElements.hasInScope(b.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(b.RTC),e._insertElement(t,Ce.HTML);}function D7e(e,t){e._reconstructActiveFormattingElements(),cG(t),CO(t),t.selfClosing?e._appendElement(t,Ce.MATHML):e._insertElement(t,Ce.MATHML),t.ackSelfClosing=true;}function F7e(e,t){e._reconstructActiveFormattingElements(),dG(t),CO(t),t.selfClosing?e._appendElement(t,Ce.SVG):e._insertElement(t,Ce.SVG),t.ackSelfClosing=true;}function Dpe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ce.HTML);}function vi(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:{A7e(e,t);break}case b.A:{T7e(e,t);break}case b.H1:case b.H2:case b.H3:case b.H4:case b.H5:case b.H6:{h7e(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:{m7e(e,t);break}case b.LI:case b.DD:case b.DT:{y7e(e,t);break}case b.BR:case b.IMG:case b.WBR:case b.AREA:case b.EMBED:case b.KEYGEN:{Hpe(e,t);break}case b.HR:{I7e(e,t);break}case b.RB:case b.RTC:{L7e(e,t);break}case b.RT:case b.RP:{k7e(e,t);break}case b.PRE:case b.LISTING:{g7e(e,t);break}case b.XMP:{P7e(e,t);break}case b.SVG:{F7e(e,t);break}case b.HTML:{d7e(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:{Ul(e,t);break}case b.BODY:{u7e(e,t);break}case b.FORM:{f7e(e,t);break}case b.NOBR:{E7e(e,t);break}case b.MATH:{D7e(e,t);break}case b.TABLE:{C7e(e,t);break}case b.INPUT:{R7e(e,t);break}case b.PARAM:case b.TRACK:case b.SOURCE:{w7e(e,t);break}case b.IMAGE:{x7e(e,t);break}case b.BUTTON:{b7e(e,t);break}case b.APPLET:case b.OBJECT:case b.MARQUEE:{v7e(e,t);break}case b.IFRAME:{O7e(e,t);break}case b.SELECT:{M7e(e,t);break}case b.OPTION:case b.OPTGROUP:{N7e(e,t);break}case b.NOEMBED:case b.NOFRAMES:{kpe(e,t);break}case b.FRAMESET:{p7e(e,t);break}case b.TEXTAREA:{_7e(e,t);break}case b.NOSCRIPT:{e.options.scriptingEnabled?kpe(e,t):Dpe(e,t);break}case b.PLAINTEXT:{S7e(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:Dpe(e,t);}}function B7e(e,t){if(e.openElements.hasInScope(b.BODY)&&(e.insertionMode=z.AFTER_BODY,e.options.sourceCodeLocationInfo)){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t);}}function U7e(e,t){e.openElements.hasInScope(b.BODY)&&(e.insertionMode=z.AFTER_BODY,Xpe(e,t));}function H7e(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n));}function j7e(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 G7e(e){e.openElements.hasInButtonScope(b.P)||e._insertFakeElement(ie.P,b.P),e._closePElement();}function $7e(e){e.openElements.hasInListItemScope(b.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(b.LI),e.openElements.popUntilTagNamePopped(b.LI));}function V7e(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n));}function z7e(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped());}function W7e(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker());}function q7e(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(ie.BR,b.BR),e.openElements.pop(),e.framesetOk=false;}function Gpe(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 _O(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:{hG(e,t);break}case b.P:{G7e(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:{H7e(e,t);break}case b.LI:{$7e(e);break}case b.DD:case b.DT:{V7e(e,t);break}case b.H1:case b.H2:case b.H3:case b.H4:case b.H5:case b.H6:{z7e(e);break}case b.BR:{q7e(e);break}case b.BODY:{B7e(e,t);break}case b.HTML:{U7e(e,t);break}case b.FORM:{j7e(e);break}case b.APPLET:case b.OBJECT:case b.MARQUEE:{W7e(e,t);break}case b.TEMPLATE:{Vh(e,t);break}default:Gpe(e,t);}}function $pe(e,t){e.tmplInsertionModeStack.length>0?Jpe(e,t):gG(e,t);}function K7e(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 Y7e(e,t){e._err(t,ce.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t);}function uG(e,t){if(e.openElements.currentTagId!==void 0&&Fpe.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=false,e.originalInsertionMode=e.insertionMode,e.insertionMode=z.IN_TABLE_TEXT,t.type){case Zt.CHARACTER:{zpe(e,t);break}case Zt.WHITESPACE_CHARACTER:{Vpe(e,t);break}}else lv(e,t);}function J7e(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_CAPTION;}function X7e(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_COLUMN_GROUP;}function Q7e(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(ie.COLGROUP,b.COLGROUP),e.insertionMode=z.IN_COLUMN_GROUP,fG(e,t);}function Z7e(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_TABLE_BODY;}function eet(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(ie.TBODY,b.TBODY),e.insertionMode=z.IN_TABLE_BODY,PO(e,t);}function tet(e,t){e.openElements.hasInTableScope(b.TABLE)&&(e.openElements.popUntilTagNamePopped(b.TABLE),e._resetInsertionMode(),e._processStartTag(t));}function net(e,t){jpe(t)?e._appendElement(t,Ce.HTML):lv(e,t),t.ackSelfClosing=true;}function oet(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,Ce.HTML),e.formElement=e.openElements.current,e.openElements.pop());}function CS(e,t){switch(t.tagID){case b.TD:case b.TH:case b.TR:{eet(e,t);break}case b.STYLE:case b.SCRIPT:case b.TEMPLATE:{Ul(e,t);break}case b.COL:{Q7e(e,t);break}case b.FORM:{oet(e,t);break}case b.TABLE:{tet(e,t);break}case b.TBODY:case b.TFOOT:case b.THEAD:{Z7e(e,t);break}case b.INPUT:{net(e,t);break}case b.CAPTION:{J7e(e,t);break}case b.COLGROUP:{X7e(e,t);break}default:lv(e,t);}}function av(e,t){switch(t.tagID){case b.TABLE:{e.openElements.hasInTableScope(b.TABLE)&&(e.openElements.popUntilTagNamePopped(b.TABLE),e._resetInsertionMode());break}case b.TEMPLATE:{Vh(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:lv(e,t);}}function lv(e,t){let n=e.fosterParentingEnabled;e.fosterParentingEnabled=true,xO(e,t),e.fosterParentingEnabled=n;}function Vpe(e,t){e.pendingCharacterTokens.push(t);}function zpe(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=true;}function ev(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)lv(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t);}var Wpe=new Set([b.CAPTION,b.COL,b.COLGROUP,b.TBODY,b.TD,b.TFOOT,b.TH,b.THEAD,b.TR]);function ret(e,t){let n=t.tagID;Wpe.has(n)?e.openElements.hasInTableScope(b.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=z.IN_TABLE,CS(e,t)):vi(e,t);}function iet(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=z.IN_TABLE,n===b.TABLE&&av(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:_O(e,t);}}function fG(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.COL:{e._appendElement(t,Ce.HTML),t.ackSelfClosing=true;break}case b.TEMPLATE:{Ul(e,t);break}default:wO(e,t);}}function set(e,t){switch(t.tagID){case b.COLGROUP:{e.openElements.currentTagId===b.COLGROUP&&(e.openElements.pop(),e.insertionMode=z.IN_TABLE);break}case b.TEMPLATE:{Vh(e,t);break}case b.COL:break;default:wO(e,t);}}function wO(e,t){e.openElements.currentTagId===b.COLGROUP&&(e.openElements.pop(),e.insertionMode=z.IN_TABLE,e._processToken(t));}function PO(e,t){switch(t.tagID){case b.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,Ce.HTML),e.insertionMode=z.IN_ROW;break}case b.TH:case b.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(ie.TR,b.TR),e.insertionMode=z.IN_ROW,OO(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=z.IN_TABLE,CS(e,t));break}default:CS(e,t);}}function mG(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=z.IN_TABLE);break}case b.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=z.IN_TABLE,av(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:av(e,t);}}function OO(e,t){switch(t.tagID){case b.TH:case b.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,Ce.HTML),e.insertionMode=z.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=z.IN_TABLE_BODY,PO(e,t));break}default:CS(e,t);}}function qpe(e,t){switch(t.tagID){case b.TR:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=z.IN_TABLE_BODY);break}case b.TABLE:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=z.IN_TABLE_BODY,mG(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=z.IN_TABLE_BODY,mG(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:av(e,t);}}function aet(e,t){let n=t.tagID;Wpe.has(n)?(e.openElements.hasInTableScope(b.TD)||e.openElements.hasInTableScope(b.TH))&&(e._closeTableCell(),OO(e,t)):vi(e,t);}function cet(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=z.IN_ROW);break}case b.TABLE:case b.TBODY:case b.TFOOT:case b.THEAD:case b.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),qpe(e,t));break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:break;default:_O(e,t);}}function Kpe(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.OPTION:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e._insertElement(t,Ce.HTML);break}case b.OPTGROUP:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop(),e._insertElement(t,Ce.HTML);break}case b.HR:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop(),e._appendElement(t,Ce.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:{Ul(e,t);break}}}function Ype(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:{Vh(e,t);break}}}function det(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)):Kpe(e,t);}function uet(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)):Ype(e,t);}function pet(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:{Ul(e,t);break}case b.CAPTION:case b.COLGROUP:case b.TBODY:case b.TFOOT:case b.THEAD:{e.tmplInsertionModeStack[0]=z.IN_TABLE,e.insertionMode=z.IN_TABLE,CS(e,t);break}case b.COL:{e.tmplInsertionModeStack[0]=z.IN_COLUMN_GROUP,e.insertionMode=z.IN_COLUMN_GROUP,fG(e,t);break}case b.TR:{e.tmplInsertionModeStack[0]=z.IN_TABLE_BODY,e.insertionMode=z.IN_TABLE_BODY,PO(e,t);break}case b.TD:case b.TH:{e.tmplInsertionModeStack[0]=z.IN_ROW,e.insertionMode=z.IN_ROW,OO(e,t);break}default:e.tmplInsertionModeStack[0]=z.IN_BODY,e.insertionMode=z.IN_BODY,vi(e,t);}}function met(e,t){t.tagID===b.TEMPLATE&&Vh(e,t);}function Jpe(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(b.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):gG(e,t);}function het(e,t){t.tagID===b.HTML?vi(e,t):IO(e,t);}function Xpe(e,t){var n;if(t.tagID===b.HTML){if(e.fragmentContext||(e.insertionMode=z.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 IO(e,t);}function IO(e,t){e.insertionMode=z.IN_BODY,xO(e,t);}function get(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.FRAMESET:{e._insertElement(t,Ce.HTML);break}case b.FRAME:{e._appendElement(t,Ce.HTML),t.ackSelfClosing=true;break}case b.NOFRAMES:{Ul(e,t);break}}}function fet(e,t){t.tagID===b.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==b.FRAMESET&&(e.insertionMode=z.AFTER_FRAMESET));}function yet(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.NOFRAMES:{Ul(e,t);break}}}function bet(e,t){t.tagID===b.HTML&&(e.insertionMode=z.AFTER_AFTER_FRAMESET);}function Tet(e,t){t.tagID===b.HTML?vi(e,t):RO(e,t);}function RO(e,t){e.insertionMode=z.IN_BODY,xO(e,t);}function Aet(e,t){switch(t.tagID){case b.HTML:{vi(e,t);break}case b.NOFRAMES:{Ul(e,t);break}}}function Eet(e,t){t.chars=Xn,e._insertCharacters(t);}function vet(e,t){e._insertCharacters(t),e.framesetOk=false;}function Qpe(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==Ce.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop();}function Cet(e,t){if(Ppe(t))Qpe(e),e._startTagOutsideForeignContent(t);else {let n=e._getAdjustedCurrentElement(),o=e.treeAdapter.getNamespaceURI(n);o===Ce.MATHML?cG(t):o===Ce.SVG&&(Ope(t),dG(t)),CO(t),t.selfClosing?e._appendElement(t,o):e._insertElement(t,o),t.ackSelfClosing=true;}}function Ret(e,t){if(t.tagID===b.P||t.tagID===b.BR){Qpe(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)===Ce.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 Zpe(e,t,n){typeof e=="string"&&(n=t,t=e,e=null);let o=sv.getFragmentParser(e,n);return o.tokenizer.write(t,true),o.getFragment()}var wet=5e3,eme=1024;function yG(e){return typeof e.tagName=="string"&&Array.isArray(e.attrs)}function Iet(e){return e.nodeName==="#text"}function SG(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(Iet(l)){let c=l.value;if(c&&c.trim().length>0){let d=c.length>eme?c.slice(0,eme):c;i=i===void 0?d:`${i} ${d}`;}}else if(yG(l)){let c=SG(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 bG(e){let t=Zpe(e),n={nodesLeft:wet};for(let i of t.childNodes)if(yG(i)&&i.tagName.toLowerCase()==="body"){let s=SG(i,n);if(s!==void 0)return s}let o=[];for(let i of t.childNodes){if(n.nodesLeft<=0)break;if(yG(i)){let s=SG(i,n);s!==void 0&&o.push(s);}}let r={tag:"body"};return o.length>0&&(r.children=o),r}var xet=new Set(["PRESET_ACTION","AI_ACTION_DYNAMIC"]),zh=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(`${$r}/${n}.jpeg`)}async getHtmlSnapshot(t,n){return this.diskStorage.readFile(`${$r}/${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))wt.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 TG(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:PW(t.status),finishedAt:t.finishedAt}))),this.sendFinalizedStepStats());}};function _et(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 Xe(e)}}function MO(e){return e.some(t=>t.status==="FAILED")?"FAILED":e.some(t=>t.status==="CANCELLED")?"CANCELLED":"RUNNING"}var TG=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 Ip({storeTraceAsset:c=>this.storeTraceAsset(c)}),wp.initializeRootTracerContext(this.interactionTracer);}children=[];finished=false;interactionTracer;attachBeforeScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${$r}/${n}.jpeg`,contents:o});}attachAfterScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${$r}/${n}.jpeg`,contents:o});}attachBeforeHtmlSnapshot(t){let{snapshotId:n,html:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${$r}/${n}.html`,contents:o});}attachAfterHtmlSnapshot(t){let{snapshotId:n,html:o,url:r,logger:i}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${$r}/${n}.html`,contents:o}),this.appGraphSink&&xet.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";wt.increment("test_event",1,[`name:${o}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:n,healedAt:new Date};}storeTraceAsset(t){this.diskStorage.storeFile({name:`${$r}/${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:_et(t.status),finishedAt:t.finishedAt}))));}recordStepDuration(t,n){if(!AR(t))return;let o=TR(t);wt.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:MO(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:Od(r.steps)})),elseSteps:t.elseSteps?Od(t.elseSteps):void 0,status:MO(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});case "WHILE_LOOP":return n=>({...t,steps:Od(t.steps),status:MO(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:MO(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});default:return Xe(t)}}async startSubSteps(){let t=this.getResultBuilderForCurrentStep(),n=new zh(this.orgId,this.testId,this.testName,this.diskStorage,o=>{let r=t(o);this.parentFlushResults(r);});return this.children.push(n),n}};var NO=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($r),this.harPagesStream=this.diskStorage.createFileStream(`${$r}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${$r}/har-entries.log`),this.resourceUsageStream=this.diskStorage.createFileStream(`${$r}/resource-usage.ndjson`),this.resourceUsageSampler=dX({keepSamples:false,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
|
|
9041
9041
|
`),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 io__default.resolve(this.diskStorage.cwd(),$r)}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)}
|
|
9042
9042
|
`);}appendUiState(t){this.finished||(this.uiStatesStream||(this.uiStatesStream=this.diskStorage.createFileStream(tq)),this.uiStatesStream.write(`${JSON.stringify(t)}
|
|
9043
9043
|
`));}buildAppGraphSink(){return ({html:t,url:n,stepId:o,parentStepIdChain:r,logger:i})=>{let s=iG(t),a=s===this.previousHtmlByteHash?this.previousFingerprint:void 0;if(!a){try{a=sG({url:n,dom:bG(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)}
|
|
@@ -9114,4 +9114,4 @@ Entering interactive mode. Ask follow-up questions about this triage.`),C.info("
|
|
|
9114
9114
|
`))&&process.exit(1),n||await age();let o=new xt({baseUrl:e.server,apiKey:e.apiKey,logger:he,mode:"runner",runner:"test-runner"}),{orgId:r}=await o.getAuthInfo(),i=await Mr(he,o,t),s=await e7({project:t,dryRun:n,migrate:()=>nM({project:t,apiClient:o,gitMetadata:i,orgId:r,dryRun:n})});kB({summary:s.migration,fileFormatChanged:s.fileFormatChanged,configChange:{diff:s.configDiff,configFilePath:t.configFilePath},dryRun:n}),s.fileFormatChanged||NB(s.aiSettings)?n?C.success("Dry run complete. Rerun without --dry-run to apply."):(C.success("Upgraded project to latest recommended settings."),C.dimmed(" Optional: rerun tests with --regenerate-cache to rebuild caches from scratch (slower).")):C.success("Project is already up to date."),await Ze(),process.exit(0);});function cge(e){let t=e.listRuns.bind(e);return e.listRuns=async n=>t({...n,skipRetentionFilter:true}),e}async function x$(e){let t=e.config.fileFormat==="v2",{totalErrors:n,parsingErrors:o,parsingErrorDetails:r,failedTestFilePaths:i,failedModuleFilePaths:s}=t?await DG({project:e}):await kG({project:e,fix:false});o>0&&(bf({parsingErrors:o,parsingErrorDetails:r,failedTestFilePaths:i,failedModuleFilePaths:s,rootDir:e.rootDir}),process.exit(1)),n>0&&(C.error(`Found ${n} ${t?"lint ":""}errors`),C.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 aot(){uge("Main program started"),w4();try{await tn.parseAsync(process.argv),await Ze();}catch(e){let t={};try{t.playwrightVersion=execSync("npx playwright --version",{stdio:["ignore","pipe","pipe"]}).toString();}catch(o){he.error({err:o},"Error fetching debug information");}let n=Vv(e,Oe);n?(he.error({err:e,debugInfo:t},"User-facing error in CLI"),C.error(n.message)):(he.error({err:e,debugInfo:t},"Uncaught error in CLI"),C.error({err:e},"Momentic CLI exited unexpectedly")),IB({err:e,doctorCommand:"`npx momentic doctor`"}),await Ze(),process.exit(1);}}L5e.setMaxListeners(25);process.on("warning",e=>{he.warn({err:e},`Node warning received on CLI: ${e.message}`);});uge("CLI parsing setup complete");aot();
|
|
9115
9115
|
//# sourceMappingURL=out.js.map
|
|
9116
9116
|
//# sourceMappingURL=cli.js.map
|
|
9117
|
-
//# debugId=
|
|
9117
|
+
//# debugId=22761cd9-d29d-517e-93af-34b51fee0965
|