momentic 3.62.2 → 3.62.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b07a097b-31c7-5baf-866f-7f2df24b5ea7")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a3f68874-d6b9-5f3b-b638-b45758964ab2")}catch(e){}}();
4
4
  import * as Un from 'fs';
5
5
  import Un__default, { statSync, mkdirSync, readFileSync, existsSync, readdir, readdirSync, createReadStream, writeFileSync, appendFileSync, rmSync, unlinkSync, renameSync } from 'fs';
6
6
  import * as Cn from 'path';
@@ -181,18 +181,18 @@ What the agent did: ${n}`:t}var bR=Al.extend({type:z.literal("AI_ACTION_DYNAMIC"
181
181
  Options:
182
182
  ${a.map(([l,c])=>`${l}: ${c}`).join(`
183
183
  `)}`;}o.required===false&&(r=r.nullable(),i+=`
184
- Use null when unknown or not applicable.`),t[o.name]=r.describe(i);}return z.strictObject(t)}function $Ge(e){let t=[e.testCases??[],e.bugReproductions??[]].map(o=>z.toJSONSchema(HGe(o)));return new TextEncoder().encode(JSON.stringify(t)).byteLength}var hZ=UGe.refine(e=>$Ge(e)<=jGe,"Field guidance is too long. Shorten descriptions or remove fields or options.");var YT=Ju.extend({browserType:z.enum(Yu).optional(),basicAuthorization:z.object({username:z.string().optional(),password:z.string().optional()}).optional(),geolocation:z.object({latitude:z.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:z.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:z.boolean().optional(),locale:z.string().optional(),timezone:z.enum(KP).optional(),colorScheme:z.enum(["light","dark"]).optional()}),gZ=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],Q$=z.object({useMemory:z.boolean().optional(),failureRecovery:z.boolean().optional().describe("undefined means inherit org settings")}),Z$=Q$.extend({disableAICaching:z.boolean().optional()}),VGe=z.object({viewport:jp.optional()}),Us=VGe.extend(Z$.shape).extend(YT.shape),gk=z.object({cron:z.string().refine(e=>isValidCron(e),{error:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:z.boolean().default(false),env:z.string().optional(),timeZone:z.string().default("America/Los_Angeles"),jobKey:z.string().optional()}),fk=z.object({onSuccess:z.boolean().default(false),failureMessage:z.string().optional(),onFailure:z.boolean().default(true),successMessage:z.string().optional()}),WGe=z.object({name:z.string(),required:z.boolean().optional(),defaultValue:z.string().describe("this is not optional because we need a value when the editor is first loaded")}),fZ=WGe.array(),qGe=z.object({name:z.string(),value:z.string()}),yk=qGe.array(),yZ=z.object({name:z.string(),default:z.boolean().optional(),fixtures:J8.array().optional()});var _l=Q$.extend({agentConfig:z.record(z.string(),z.string()).optional(),aiFailureAnalysis:z.boolean().optional(),classification:wQ.optional(),healing:mT.optional(),explore:pP.optional(),select:eZ.optional(),aiActionVersion:yR.optional()}),KGe=z.object({cliOnly:z.boolean().optional(),moDefault:z.boolean().optional(),neverShowUsageBanner:z.boolean().optional(),hideInternalTraceInfo:z.boolean().optional(),bypassUsageLimits:z.boolean().optional()}),XR=z.object({aiActionShorthand:z.boolean().optional().describe("Serialize eligible multi-word AI action V3 goals as bare strings in simplified YAML."),fakerConstantSeed:z.boolean().optional(),isolateCachesByEnvironment:z.boolean().optional(),saveCacheOnCancel:z.boolean().optional()}),YGe=z.object({includePassingRuns:z.boolean().optional(),showFailedTestDetails:z.boolean().optional()}),JGe=z.enum(["flaky_tests","low_test_coverage","frequent_bugs","fix_flaky_tests","migrate_tests","increase_test_coverage","catch_more_bugs"]),XGe=z.enum(["ios","android","web"]),QGe=z.enum(["selenium","playwright","cypress","puppeteer","maestro","appium","detox","manual_qa","nothing_yet","other"]),t1=z.enum(["advertisement","ai_search","google_search","hacker_news","linkedin","reddit","referral_from_customer","twitter_x","word_of_mouth","youtube","teammate_or_manager","investor_or_accelerator","agent_directory","newsletter","podcast","conference_or_event","billboard","other"]),ZGe=z.object({helpIntents:z.array(JGe).optional(),helpIntentOtherText:z.string().optional(),deviceTypeIntent:XGe.optional(),currentTestingTool:QGe.optional(),heardAboutSource:t1.optional(),heardAboutSourceOtherText:z.string().max(200).optional()}),e2e=z.object({discovery:ZGe.optional(),needsToCompleteOnboarding:z.boolean().optional(),needsWorkspaceName:z.boolean().optional(),wizardCompletedAt:z.iso.datetime().optional(),goal:z.enum(["mo","e2e"]).optional(),flowVersion:z.number().int().optional().catch(void 0)}),JT=z.object({moCustomFields:hZ.optional(),ai:_l.optional(),githubAppInstallationId:z.number().nullish(),githubAppSummaryMessageEnabled:z.boolean().nullish(),githubPullRequestComments:YGe.optional(),githubReleaseAppInstallationId:z.number().nullish(),gitlabAppAccessToken:z.string().nullish(),gitlabAppBaseUrl:z.string().nullish(),browser:m$.optional(),internal:KGe.optional(),advanced:XR.optional(),onboarding:e2e.optional()}),t2e=5;function bZ(e){let t=e,o=[];for(let n=0;n<t2e;n++){let r=JT.safeParse(t);if(r.success)return o.length>0&&x.warn(`Ignoring cloud settings this version of the CLI does not support: ${o.join(", ")}. Please upgrade. Everything else was applied.`),r.data;let i=o2e(r.error.issues.map(l=>[...l.path]).filter(l=>l.length>0));if(i.length===0)break;let a=structuredClone(t),s=[...i].sort(n2e);for(let l of s)e1(a,l);if(JSON.stringify(a)===JSON.stringify(t)){for(let l of s)l.length>1&&e1(a,l.slice(0,-1));if(JSON.stringify(a)===JSON.stringify(t))break}o.push(...i.map(l=>l.join("."))),t=a;}return x.warn("Cloud settings could not be read by this version of the CLI. Please upgrade. Falling back to defaults."),JT.parse({})}function o2e(e){return [...new Map(e.map(o=>[o.join("\0"),o])).values()]}function n2e(e,t){if(e.length!==t.length)return t.length-e.length;for(let o=e.length-1;o>=0;o--){let n=e[o],r=t[o];if(typeof n=="number"&&typeof r=="number"&&n!==r)return r-n}return 0}function e1(e,t){let[o,...n]=t;if(!(o===void 0||typeof e!="object"||e===null)){if(n.length===0){Array.isArray(e)&&typeof o=="number"?e.splice(o,1):delete e[o];return}e1(e[o],n);}}z.object({globalOverrides:z.record(z.string(),z.string()).optional(),agentConfig:z.record(z.string(),z.string()).optional()});z.record(z.string(),z.string()).nullish();var SZ="Evaluating run assertions",bk=z.string();function QR(e){return (e.runAssertions?.length??0)>0}var r2e=z.object({videoName:z.string(),startSeconds:z.number(),endSeconds:z.number().optional()}),o1=z.discriminatedUnion("type",[z.object({type:z.literal("videoMoment"),moment:r2e})]),n1=(r=>(r.PASSED="passed",r.FAILED="failed",r.SKIPPED="skipped",r.INCONCLUSIVE="inconclusive",r))(n1||{}),i2e=z.nativeEnum(n1),a2e=z.array(z.unknown()).default([]).transform(e=>e.flatMap(t=>{let o=o1.safeParse(t);return o.success?[o.data]:[]})),s2e=z.object({description:z.string(),status:i2e,reasoning:z.string(),evidence:a2e}),l2e=z.object({attemptNumber:z.number(),evaluations:s2e.array(),durationMs:z.number()});function TZ(e){let t=e.filter(o=>o.status==="failed");if(t.length!==0)return `Run assertion(s) not met: ${t.map(o=>o.description).join("; ")}`}var vZ=z.object({attempts:l2e.array()}),c2e=/\[\[e(\d+)\]\]/g;function AZ(e){return [...e.matchAll(c2e)].map(t=>Number(t[1]))}var ic={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ho=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(ho||{});var XT=(a=>(a.NOT_ATTEMPTED="NOT_ATTEMPTED",a.PERM_HEAL_SUCCEEDED="PERM_HEAL_SUCCEEDED",a.PERM_HEAL_FAILED="PERM_HEAL_FAILED",a.PERM_HEAL_UNATTEMPTED="PERM_HEAL_UNATTEMPTED",a.PERM_HEAL_ON_SUCCESS_FAILED="PERM_HEAL_ON_SUCCESS_FAILED",a.PERM_HEAL_NOT_NEEDED="PERM_HEAL_NOT_NEEDED",a))(XT||{});var Qy=z.enum(XT).default("NOT_ATTEMPTED"),Sk=(o=>(o.BEFORE_ALL="BEFORE_ALL",o.AFTER_ALL="AFTER_ALL",o))(Sk||{});var u2e=z.object({attempts:z.int().nonnegative()}),br=z.string().pipe(z.coerce.date()).or(z.date()),js=z.object({id:z.string(),runKey:z.string(),organizationId:z.string(),executionType:Hp.optional().default("WEB"),createdAt:br,createdBy:z.string(),flake:z.boolean().nullish(),scheduledAt:br.or(z.null()),startedAt:br.or(z.null()),updatedAt:br.nullish(),finishedAt:br.or(z.null()),resolvedBaseUrl:z.string().nullish(),environmentName:z.string().nullish(),gitBranchName:z.string().nullish(),gitMainBranch:z.string().nullish(),githubRepository:z.string().nullish(),gitlabProjectPath:z.string().nullish(),labels:z.array(z.string()).optional(),gitOriginUrl:z.string().nullish(),gitCommitSha:z.string().nullish(),gitCommitShaShort:z.string().nullish(),gitCommitAuthorName:z.string().nullish(),gitCommitTimestamp:br.nullish(),gitCommitMessage:z.string().nullish(),schemaVersion:z.string().nullish(),cliVersion:z.string().nullish(),section:z.enum(Sk).nullish(),status:z.enum(ho),healStatus:Qy,healDetails:a9.nullish(),trigger:z.enum(ic),attempts:z.number(),runAttempts:z.array(z.object({id:z.string(),status:z.enum(ho),startedAt:br.or(z.null()),finishedAt:br.or(z.null())})).optional(),videos:z.array(z.string()).optional(),failureReason:z.string().nullish(),failureDetails:NQ.nullish(),failureRecoveryDetails:u2e.nullish(),pipelineId:z.string().nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),quarantined:z.boolean().nullish().default(false),quarantinedReason:z.string().nullish(),localTestId:z.string().nullish(),testId:z.string().nullish(),testName:z.string().nullish(),description:z.string().nullish(),directory:z.string().nullish(),test:z.object({name:z.string(),id:z.string()}).nullish().default(null),suiteId:z.string().nullish(),aiSettings:_l.nullish(),stepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),beforeStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),afterStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),runAssertionResults:vZ.nullish()}),d2e={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},Tk=js.pick({...d2e,test:true}),EZ=js.omit({failureReason:true,failureDetails:true,test:true}),r1=js.extend({stepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),beforeStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),afterStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),test:z.object({name:z.string(),id:z.string(),description:z.string().nullish(),baseUrl:z.string().nullish(),advanced:Us.nullish()}).nullish()}).extend(B$.shape),wZ=e=>e.includes("PASSED")&&e.includes("FAILED");var m2e=z.object({region:z.enum(["US","EU"]).optional().describe("New Relic data center region. Defaults to US."),accountId:z.string().describe("New Relic account ID to send events to. Supports ${ENV_VAR} interpolation."),licenseKey:z.string().optional().describe("New Relic ingest license key. Supports ${ENV_VAR} interpolation. Defaults to the NEW_RELIC_LICENSE_KEY environment variable."),attributes:z.record(z.string(),z.string()).optional().describe("Static attributes (e.g. service, team) added to every event sent to New Relic. Values support ${ENV_VAR} interpolation.")}),RZ=z.object({newrelic:m2e.optional()}),p2e=z.object({category:z.string(),reasoning:z.string(),citations:z.array(Kn).optional()}),h2e=z.object({testInputs:z.record(z.string(),z.string()).optional(),envName:z.string().optional(),urlOverride:z.string().optional()}),g2e=z.object({reason:z.string().optional(),message:z.string().optional()}),f2e=z.object({runId:z.string().optional(),testId:z.string(),testName:z.string(),filePath:z.string(),labels:z.array(z.string()).optional(),status:z.enum(ho),startedAt:z.string(),finishedAt:z.string(),durationMs:z.number(),attempts:z.number(),quarantined:z.boolean(),recovered:z.boolean(),parameters:h2e.optional(),failure:g2e.nullable(),classification:p2e.nullable()}),y2e=z.object({testId:z.string(),testName:z.string(),filePath:z.string(),labels:z.array(z.string()).optional(),quarantined:z.boolean()}),b2e=z.object({total:z.number(),executed:z.number(),skipped:z.number(),passed:z.number(),failed:z.number(),cancelled:z.number(),quarantined:z.number(),recovered:z.number()}),CZ=z.object({version:z.literal(1),runGroup:z.object({startedAt:z.string(),finishedAt:z.string(),durationMs:z.number()}),summary:b2e,runs:z.array(f2e),skipped:z.array(y2e)});var IZ=z.enum(["error","warning","passing"]);var xZ=z.enum(["safe_to_merge","confirm_intended_change","investigate_regression","fix_test","resolve_infra","review_coverage"]),T2e=xZ.exclude(["review_coverage"]);var v2e="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 _Z=z.object({kind:xZ,detail:z.string().min(1).max(280)}),Zy=z.object({riskLevel:z.string(),headline:z.string().min(1).max(200).describe("One-sentence summary of what happened in this run. Plain text, no markdown."),overview:z.string().min(1).max(280).optional().describe("One plain-text sentence giving the bottom line of the run. No markdown."),summaryMarkdown:z.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:_Z.optional()}),OZ=Zy.extend({riskLevel:IZ.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.string().min(1).max(120).describe(v2e),overview:z.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.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:_Z.extend({kind:T2e.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."),detail:z.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 w2e=z.enum(["SELECTED","RUN_ALL","RUN_NONE","SHADOW"]),ZR=z.object({mode:w2e,baseRef:z.string().nullable(),headSha:z.string(),planId:z.string().nullable(),totalCandidates:z.number().int().nonnegative(),selectedCount:z.number().int().nonnegative(),anchorSegmentIds:z.array(z.string()),userSummary:z.string(),toolCallCount:z.number().int().nonnegative(),selectedTests:z.array(pk),forcedTests:z.array(z.object({name:z.string(),testPath:z.string(),status:z.enum(["A","M","R","C","T"])})).optional().default([]),runAllReason:z.string().nullable()});function PZ(e){return uniqWith([...e],isEqual)}var kZ=z.object({id:z.string(),status:z.enum(ho),trigger:z.enum(ic),createdAt:br,startedAt:br.nullish(),finishedAt:br.nullish(),gitCommitSha:z.string().nullish(),gitCommitShaShort:z.string().nullish(),gitCommitTimestamp:br.nullish(),gitBranchName:z.string().nullish(),gitOriginUrl:z.string().nullish(),gitCommitMessage:z.string().nullish(),gitCommitAuthorName:z.string().nullish(),projectName:z.string().nullish(),relativeProjectDir:z.string().nullish(),githubRepository:z.string().nullish(),gitlabProjectPath:z.string().nullish(),pipelineId:z.string().nullish(),ciProvider:z.string().nullish(),cliVersion:z.string().nullish(),labels:z.string().array().optional(),healRiskSummary:Zy.optional(),aiSelect:ZR.array().optional(),environments:z.string().array().optional(),executionTypes:Hp.array().optional(),localSuiteName:z.string().optional(),suite:z.object({id:z.string(),name:z.string()}).nullish(),runs:z.object({status:z.enum(ho)}).array()}),MZ=kZ.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true,localSuiteName:true}).extend({runs:Tk.array()}),vk=kZ.extend({runs:js.array()});var R2e=z.object({type:z.literal("TARGETING"),name:z.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:V9.array(),pageState:z.string().optional(),targetSource:z.enum(Hu).optional(),targetUpdateTime:z.string().optional()}),C2e=z.object({type:z.literal("AI_LOCATION"),matched:z.boolean(),pageState:z.string().optional(),ragUsed:z.boolean().optional(),thoughts:z.string().optional()}),I2e=z.object({type:z.literal("ASSERTION"),relevantElementsSerialized:z.string().array().optional(),pageState:z.string().optional(),ragUsed:z.boolean().optional()}),Ak=z.discriminatedUnion("type",[R2e,C2e,I2e]);var x2e=z.object({id:z.string(),name:z.string()});x2e.extend(z.object({createdAt:br,createdBy:z.string(),schedule:gk,notification:fk,environment:z.object({name:z.string()}).nullish(),beforeTests:z.object({id:z.string()}).array().nullish(),afterTests:z.object({id:z.string()}).array().nullish()}).shape);var LZ=z.object({id:z.guid(),orgId:z.string(),createdAt:br,startedAt:br.or(z.null()),finishedAt:br.or(z.null()),status:z.enum(ho),trigger:z.enum(ic),suite:z.object({id:z.string(),name:z.string()}).nullish(),runs:js.array()});LZ.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true});var NZ=LZ.extend({runs:Tk.array()});function DZ({beforeStatus:e,mainStatus:t,afterStatus:o}){return e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":o==="FAILED"?"FAILED":o==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":"PASSED"}function Ek(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 FZ(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 i1=z.object({content:z.string(),ids:z.string().array(),tokenLength:z.number()}),_2e=z.object({chunks:i1.array()});z.object({ids:z.string().array(),score:z.number(),tokenLength:z.number()});_2e.extend({description:z.string().describe("Input to pass to RAG engine"),tokenLimit:z.number()});var BZ=z.object({ids:z.number().array()}),UZ=z.object({indices:z.number().array()});var ac=(o=>(o.Interactive="interactive",o.Runner="runner",o))(ac||{}),O2e=z.enum(ac),_i=z.object({disableCache:z.boolean().optional(),useMemory:z.boolean().optional(),clientMode:O2e.optional(),loggerTags:z.record(z.string(),z.string()).optional(),langfuseSessionId:z.string().optional(),agentConfigVersion:z.string().optional(),effort:Nt.optional(),cacheBustReason:z.enum(nR).optional()});_i.extend({chunks:i1.array(),description:z.string().describe("Input to pass to AI"),type:z.union([z.literal("locator"),z.literal("assertion"),z.literal("ai-action")]),softTokenLimit:z.number(),mediumTokenLimit:z.number().optional(),hardTokenLimit:z.number(),callId:z.string().optional(),useJev:z.boolean().optional().describe("Score chunks with Jev. Only clients that cut their chunks for Jev send it; left out, the full ranker scores them, which is what older clients get.")});var P2e=z.object({screenshotBase64AfterCommand:z.string(),urlAfterCommand:z.string(),serializedCommand:z.string(),elementInteracted:z.string().optional(),thoughts:z.string().optional()}),jZ=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string(),source:$9.optional().catch(void 0),markIneligibleElementsInChecks:z.boolean().optional(),isTieBreakerCall:z.boolean().optional(),memory:z.discriminatedUnion("type",[$u,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional(),firstPassModelResults:ak.array().optional(),knowledgeBaseSection:z.string().optional()}),zZ=z.object({target:z.string().or(z.number()),browserState:z.string().optional(),screenshot:z.string().optional(),boundingBox:z.object({x:z.number(),y:z.number(),height:z.number(),width:z.number()}).optional()}),HZ=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string().optional(),returnSchema:z.string().optional()}),$Z=z.object({goal:z.string(),emulatorState:z.string(),screenshot:z.string().optional(),returnSchema:z.string().optional()}),a1=z.union([z.literal("NEGATED_CHECK"),z.literal("CONDITIONAL_CHECK")]),GZ=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string(),url:z.string(),contextChoice:Wy.optional(),memory:z.discriminatedUnion("type",[$y,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional(),source:a1.optional(),recoveryHint:z.string().optional(),knowledgeBaseSection:z.string().optional()}),VZ=z.object({command:Sg}),s1=z.object({goal:z.string(),browserState:z.string(),startingScreenshot:z.string().optional(),screenshot:z.string(),url:z.string(),history:P2e.array(),actionHint:z.string().optional(),lastError:z.string().optional()}),WZ=z.object({results:QP.array(),errorMessage:z.string(),errorStack:z.string().optional()}),qZ=z.object({results:QP.array(),goal:z.string(),errorMessage:z.string()}),KZ=z.object({failedResults:QP.array(),nextStepsSerialized:z.string().array(),currentUrl:z.string(),currentPageState:z.string(),currentScreenshot:z.string(),testDescription:z.string().optional()});z.object({description:z.string(),type:z.union([z.literal("locator"),z.literal("assertion"),z.literal("ai-action")]),excerpt:z.string()});var YZ=z.object({type:z.string(),browserContext:z.string(),currentStep:z.string(),screenshot:z.string()}),JZ=z.object({description:z.string(),browserState:z.string().optional(),screenshot:z.string()}),XZ=z.object({description:z.string().optional(),screenshot:z.string(),platform:q9}),k2e=z.enum(["locator","assertion"]);z.object({completionType:k2e,currentGoal:z.string(),pastGoal:z.string().optional(),currentScreenshot:z.string(),pastScreenshot:z.string(),pastResult:z.union([z.boolean(),z.number()])});z.object({goal:z.string()});var QZ=z.object({keywords:z.array(z.string())});var Zu=___default.object({id:___default.guid(),envKey:___default.string().optional(),skipped:___default.boolean().optional(),retries:___default.number().optional()});var Xc=(i=>(i.PRESET="MOBILE_PRESET_STEP",i.MODULE="MOBILE_MODULE_STEP",i.AI_ACTION="MOBILE_AI_ACTION_STEP",i.CONDITIONAL="MOBILE_CONDITIONAL_STEP",i.WHILE_LOOP="MOBILE_WHILE_LOOP_STEP",i))(Xc||{});var Lg=Zu.extend({type:___default.literal("MOBILE_CONDITIONAL_STEP")});var ls=z.object({id:z.string(),name:FP,baseUrl:BP,description:z.string().optional().nullish(),schemaVersion:z.string(),advanced:Us,retries:z.number().optional().nullish(),envs:z.array(yZ).nullish(),parameters:fZ.nullish(),disabled:z.boolean().optional(),labels:z.array(z.string()).optional().catch([]),runAssertions:bk.array().nullish()}),l1=z.enum(["INHERIT","ENABLED","DISABLED"]);var L2e=Us.shape.geolocation.unwrap().partial().superRefine(({latitude:e,longitude:t},o)=>{e!==void 0&&t===void 0&&o.addIssue({code:"custom",message:"Longitude is required when latitude is provided",path:["longitude"]}),t!==void 0&&e===void 0&&o.addIssue({code:"custom",message:"Latitude is required when longitude is provided",path:["latitude"]});}),N2e=Us.shape.proxy.unwrap().partial().superRefine(({server:e,username:t,password:o},n)=>{!e&&(t||o)&&n.addIssue({code:"custom",message:"Proxy host is required when credentials are provided",path:["server"]});}),D2e=Us.extend({failureRecovery:l1.optional(),geolocation:L2e.optional(),proxy:N2e.optional(),slowMoMs:z.union([d$,z.literal(-1)]).optional(),turbo:l1.optional(),useMemory:l1.optional()});ls.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,parameters:true,runAssertions:true}).extend({advanced:D2e});ls.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,advanced:true,parameters:true,runAssertions:true});var F2e=z.object({labels:z.array(z.string()).optional(),outputs:yk.nullish()}),Ir=ls.extend(F2e.shape),B2e=z.object({createdAt:z.coerce.date(),updatedAt:z.coerce.date(),updatedBy:z.string().nullable(),schedule:gk,notification:fk,createdBy:z.string(),organizationId:z.string(),folderId:z.string().nullable().optional()}),U2e=ls.extend(B2e.shape);U2e.extend(oc.shape);var c1=ls.extend(oc.shape);ls.extend(Mp.shape);var j2e="test",z2e="module",H2e="mobile-test",$2e="mobile-module",G2e="test/v2",V2e="module/v2",W2e="mobile-test/v2",q2e="mobile-module/v2";var ze=(l=>(l.TEST=`momentic/${j2e}`,l.MODULE=`momentic/${z2e}`,l.TEST_V2=`momentic/${G2e}`,l.MODULE_V2=`momentic/${V2e}`,l.MOBILE_TEST=`momentic/${H2e}`,l.MOBILE_MODULE=`momentic/${$2e}`,l.MOBILE_TEST_V2=`momentic/${W2e}`,l.MOBILE_MODULE_V2=`momentic/${q2e}`,l))(ze||{});ls.merge(Mp);var K2e=kr.extend({steps:z.array(z.record(z.string(),z.unknown().optional())),schemaVersion:z.string()}),oC=K2e.extend({fileType:z.literal(ze.MODULE)});z.object({test:z.string().describe("YAML for the test, including metadata and steps"),modules:z.record(z.string(),z.string()).describe("Map of module name to YAML for the module")});function wk(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(wk);let t={};for(let[o,n]of Object.entries(e))t[o]=wk(n);return t}var Y2e=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,ZZ=36,Lr=z.union([z.guid().max(ZZ,"V2 IDs must be 36 characters or fewer"),z.string().max(ZZ,"V2 IDs must be 36 characters or fewer").regex(Y2e,"V2 IDs must be lowercase kebab-case, e.g. checkout-flow")],{error:"ID must be a UUID or lowercase kebab-case, e.g. checkout-flow (36 characters max)"});var Rk=_.discriminatedUnion("type",[_.object({type:_.literal("SCREEN")}),_.object({type:_.literal("OPEN_APP")}),_.object({type:_.literal("OPEN_WEBVIEW")})]),$p=_.object({type:_.literal("description"),description:_.string()}),d1=_.object({type:_.literal("CUSTOM_COORDINATES"),startX:_.number().describe("Starting X coordinate in pixels"),startY:_.number().describe("Starting Y coordinate in pixels"),deltaPixels:_.number().describe("Number of pixels to scroll in the specified direction")}),Ck=_.discriminatedUnion("type",[...Rk.options,_.object({type:_.literal("CUSTOM"),target:$p}),d1]);function J2e(e){return e.toLowerCase().replaceAll("_"," ")}function m1(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 J2e(e.type);default:{throw new Error("Unreachable")}}}var X2e=_.object({type:_.literal("coordinates"),xPercent:_.number(),yPercent:_.number()}),Q2e=_.object({type:_.literal("absolute_percent"),x:_.number(),y:_.number()}),QT=_.discriminatedUnion("type",[$p,X2e,Q2e]);var Z2e=_.object({x1:_.number(),y1:_.number(),x2:_.number(),y2:_.number(),tolerance:_.nativeEnum(vl),preciseTolerance:_.boolean().optional()}),eVe=_.object({width:_.number(),height:_.number(),tolerance:_.nativeEnum(vl),preciseTolerance:_.boolean().optional()}),p1=_.object({requiredText:_.string().optional(),requiredAttributes:_.record(_.string(),_.string()).optional(),requiredBounds:_.boolean().optional(),position:Z2e.optional(),shape:eVe.optional()}),e7=_.object({xPath:_.string(),requirements:p1.optional()}),tVe=_.object({type:_.literal("CUSTOM"),target:$p,cache:_.lazy(()=>t7).optional()}),oVe=_.object({pixelDelta:_.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:_.union([Rk,tVe,d1]),direction:_.enum(["up","down"])}),t7=_.object({type:_.literal("NATIVE"),bounds:_.number().array().optional(),resolvedDescription:_.string().optional(),xPath:_.string().optional(),elementOnlySerializedXml:_.string().optional(),scrollDetails:oVe.optional(),requirements:p1.optional(),requiredRelatedElements:e7.array().optional(),memory:$u.optional()}),nVe=_.object({type:_.literal("WEBVIEW"),resolvedDescription:_.string().optional(),xPath:_.string().optional(),browserCache:Kd.optional(),memory:$u.optional()}),Ik=_.union([t7,nVe]);var rVe=_.object({left:_.number(),top:_.number(),right:_.number(),bottom:_.number()});_.object({newViewportBounds:rVe});var iVe=_.object({type:_.literal("CUSTOM"),target:$p,cache:_.lazy(()=>i7).optional()}),o7=_.object({pixelDelta:_.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:_.union([Rk,iVe,d1]),direction:_.enum(["up","down"])}),n7=(o=>(o.Native="native",o.Appium="appium",o))(n7||{}),h1=_.tuple([_.number(),_.number(),_.number(),_.number()]),r7=e7.extend({bounds:h1.optional(),browserCache:Kd.optional()}),i7=_.object({type:_.literal("NATIVE"),bounds:h1.optional(),resolvedDescription:_.string().optional(),sourceTree:_.nativeEnum(n7).optional(),xPath:_.string().optional(),elementOnlySerializedXml:_.string().optional(),scrollDetails:o7.optional(),requirements:p1.optional(),requiredRelatedElements:r7.array().optional(),memory:$u.optional()}),aVe=_.object({type:_.literal("WEBVIEW"),bounds:h1.optional(),resolvedDescription:_.string().optional(),xPath:_.string().optional(),scrollDetails:o7.optional(),browserCache:Kd.optional(),requiredRelatedElements:r7.array().optional(),memory:$u.optional()}),xk=_.discriminatedUnion("type",[i7,aVe]);var jo=(M=>(M.AI_CHECK="AI_CHECK",M.AI_EXTRACT="AI_EXTRACT",M.TAP="TAP",M.TYPE="TYPE",M.PRESS="PRESS",M.PRESS_KEYBOARD="PRESS_KEYBOARD",M.OPEN_APP="OPEN_APP",M.KILL_APP="KILL_APP",M.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",M.SWIPE="SWIPE",M.SCROLL_TO="SCROLL_TO",M.SCREEN_CHECK="SCREEN_CHECK",M.ELEMENT_CHECK="ELEMENT_CHECK",M.VISUAL_DIFF="VISUAL_DIFF",M.DRAG_AND_DROP="DRAG_AND_DROP",M.JAVASCRIPT="JAVASCRIPT",M.REQUEST="REQUEST",M.WAIT="WAIT",M.ADD_FILE="ADD_FILE",M.INSTALL_APP="INSTALL_APP",M.UNINSTALL_APP="UNINSTALL_APP",M.TOGGLE_SETTINGS="TOGGLE_SETTINGS",M.ROTATE_ORIENTATION="ROTATE_ORIENTATION",M.ADB_COMMAND="ADB_COMMAND",M.APPIUM_EXECUTE="APPIUM_EXECUTE",M.SET_CAMERA="SET_CAMERA",M.CLEAR_CAMERA="CLEAR_CAMERA",M.SET_MICROPHONE="SET_MICROPHONE",M.CLEAR_MICROPHONE="CLEAR_MICROPHONE",M.STATE="STATE",M))(jo||{});var Et=___default.object({id:___default.guid(),disableCache:___default.boolean().optional()}),ZT=___default.object({updatedAt:___default.coerce.date().optional(),updatedAtLoggerTags:___default.record(___default.string(),___default.string()).optional()}),Qc=ZT.extend({target:Ik}),_k=ZT.extend({fromTarget:Ik,toTarget:Ik}),um=ZT.extend({target:xk}),a7=ZT.extend({fromTarget:xk,toTarget:xk}),Gp=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 `${Math.round(e.x)}%, ${Math.round(e.y)}%`}};var s7=Et.extend({type:___default.literal("ADB_COMMAND"),command:___default.string(),jsonArgs:___default.string().optional()});var l7=Et.extend({type:___default.literal("OPEN_NOTIFICATION_DRAWER")});var nC=(r=>(r.AIRPLANE_MODE="AIRPLANE_MODE",r.DATA="DATA",r.WIFI="WIFI",r.LOCATION="LOCATION",r))(nC||{}),u7=Et.extend({type:___default.literal("TOGGLE_SETTINGS"),settingsType:___default.nativeEnum(nC)});var m7=Et.extend({type:___default.literal("UNINSTALL_APP"),packageName:___default.string()});var Ok=Et.extend({type:___default.literal("APPIUM_EXECUTE"),command:___default.string(),jsonArgs:___default.string().optional()});var p7=Et.extend({type:___default.literal("ADD_FILE"),file:___default.string(),storageLocation:___default.string()});var Vp=Et.extend({type:___default.literal("AI_CHECK"),assertion:___default.string(),timeoutSecs:___default.number().optional(),contextChoice:Wy.optional(),cache:ZT.extend({memory:$y.optional()}).optional()});var h7=Et.extend({type:___default.literal("AI_EXTRACT"),goal:___default.string(),schema:___default.string().optional()});var f7=Et.extend({type:___default.literal("INSTALL_APP"),uri:___default.string().trim()});var ev=Et.extend({type:___default.literal("JAVASCRIPT"),code:___default.string(),timeout:___default.number().int().max(600).optional().describe("Max seconds for the code to complete")});var y7=Et.extend({type:___default.literal("KILL_APP")});var iC=(o=>(o.HOME="HOME",o.POWER="POWER",o))(iC||{}),Pk=(a=>(a.BACK="BACK",a.APP_SWITCHER="APP_SWITCHER",a.SEARCH="SEARCH",a.VOLUME_UP="VOLUME_UP",a.VOLUME_DOWN="VOLUME_DOWN",a.VOLUME_MUTE="VOLUME_MUTE",a))(Pk||{}),kk=Et.extend({type:___default.literal("PRESS"),key:___default.nativeEnum(iC),longPress:___default.boolean().optional()}),b7=kk.extend({key:___default.nativeEnum(Pk).or(___default.nativeEnum(iC))}),S7=kk;var T7=Et.extend({type:___default.literal("REQUEST")}).merge(aR);var v1=(o=>(o.PORTRAIT="PORTRAIT",o.LANDSCAPE="LANDSCAPE",o))(v1||{}),A7=Et.extend({type:___default.literal("ROTATE_ORIENTATION"),orientation:___default.nativeEnum(v1)});var uVe=___default.object({type:___default.literal("CONTENT"),negated:___default.boolean().optional(),value:___default.string()}),ov=Et.extend({type:___default.literal("SCREEN_CHECK"),assertion:uVe,timeout:___default.number().int().min(0).max(em).optional().describe("max seconds to wait for the assertion to be true")});var E7=Et.extend({type:___default.literal("STATE")});var w7=Et.extend({type:___default.literal("VISUAL_DIFF"),path:___default.string().describe("path to the golden screenshot to compare against"),threshold:___default.number().min(0).max(1).optional().describe("max allowed fraction of differing pixels before the diff fails (default 0.1)")});___default.object({created:___default.boolean(),goldenPath:___default.string(),threshold:___default.number(),goldenScreenshotBase64:___default.string().optional(),currentScreenshotBase64:___default.string().optional(),diffScreenshotBase64:___default.string().optional(),goldenScreenshotSnapshotId:___default.string().optional(),currentScreenshotSnapshotId:___default.string().optional(),diffScreenshotSnapshotId:___default.string().optional(),diffPercent:___default.number().optional(),pass:___default.boolean().optional(),dimensionMismatch:___default.boolean().optional()});var C7=Et.extend({type:___default.literal("WAIT"),timeoutSecs:___default.number()});var aC=___default.discriminatedUnion("type",[E7,Vp,h7,ev,C7,T7,A7,ov,w7,p7,f7,y7]);___default.discriminatedUnion("type",[...aC.options,kk]);var E1=Et.extend({type:___default.literal("DRAG_AND_DROP"),fromTarget:$p,toTarget:$p,hoverDuration:___default.number().optional(),dragDuration:___default.number().optional()}),sC=E1.extend({cache:_k.optional()}),lC=E1.extend({cache:a7.optional()});var w1=Et.extend({type:___default.literal("ELEMENT_CHECK"),target:QT,assertion:xP,timeout:___default.number().int().min(0).max(em).optional().describe("max seconds to wait for the assertion to be true")}),eb=w1.extend({cache:Qc.optional()}),tb=w1.extend({cache:um.optional()});var cC=(o=>(o.ENTER="ENTER",o.BACKSPACE="BACKSPACE",o))(cC||{}),Mk=(t=>(t.CLOSE_KEYBOARD="CLOSE_KEYBOARD",t))(Mk||{}),_7={repeat:___default.number().int().min(1).optional(),keyPressDelayMs:___default.number().min(0).optional()},O7=Et.extend({type:___default.literal("PRESS_KEYBOARD"),key:___default.nativeEnum(cC),..._7}),P7=Et.extend({type:___default.literal("PRESS_KEYBOARD"),key:___default.nativeEnum(Mk).or(___default.nativeEnum(cC)),..._7});var k7=Et.extend({type:___default.literal("OPEN_APP"),packageName:___default.string(),activityName:___default.string().optional(),intentExtras:___default.string().optional()}),M7=Et.extend({type:___default.literal("OPEN_APP"),packageName:___default.string(),intentExtras:___default.string().optional()});var R1=Et.extend({type:___default.literal("SCROLL_TO"),target:$p,direction:___default.enum(["down","up"]),scrollableElement:Ck,scrollStepPercent:___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:___default.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 20.")}),uC=R1.extend({cache:Qc.optional()}),dC=R1.extend({cache:um.optional()});var C1=Et.extend({type:___default.literal("SWIPE"),direction:___default.enum(["up","down","left","right"]),scrollableElement:Ck,viewportPercent:___default.number().optional(),durationMs:___default.number().optional(),relativePosition:CP.optional()}),mC=C1.extend({cache:Qc.optional()}),pC=C1.extend({cache:um.optional()});var I1=Et.extend({type:___default.literal("TAP"),target:QT,longPress:___default.boolean().optional(),longPressDurationMs:___default.number().optional(),iterations:___default.number().optional(),tapDelayMs:___default.number().optional(),relativePosition:CP.optional(),doubleTap:___default.boolean().optional(),doubleTapDelayMs:___default.number().optional()}),hC=I1.extend({cache:Qc.optional()}),gC=I1.extend({cache:um.optional()});var fC=(r=>(r.AUTO="auto",r.PROGRAMMATIC="programmatic",r.LONG_PRESS="long-press",r.BACKSPACE="backspace",r))(fC||{});var x1=Et.extend({type:___default.literal("TYPE"),target:QT.optional(),keyPressDelayMs:___default.number().optional(),waitForKeyboardSettle:___default.boolean().optional(),text:___default.string(),clearContent:___default.boolean().optional(),forceClearContent:___default.boolean().optional(),replaceStrategy:___default.nativeEnum(fC).optional()});var yC=x1.extend({cache:Qc.optional()}),bC=x1.extend({cache:um.optional()});var SC=___default.discriminatedUnion("type",[...aC.options,hC,yC,b7,P7,m7,s7,Ok,sC,l7,uC,mC,u7,eb,k7]);var N7=Et.extend({type:___default.literal("SET_CAMERA"),file:___default.string(),loop:___default.boolean().optional(),playAudio:___default.boolean().optional()}),D7=Et.extend({type:___default.literal("CLEAR_CAMERA")});var F7=Et.extend({type:___default.literal("SET_MICROPHONE"),file:___default.string(),once:___default.boolean().optional()}),B7=Et.extend({type:___default.literal("CLEAR_MICROPHONE")});var vC=___default.discriminatedUnion("type",[...aC.options,gC,bC,S7,O7,M7,pC,lC,dC,tb,Ok,N7,D7,F7,B7]);var Wp=Zu.extend({type:___default.literal("MOBILE_WHILE_LOOP_STEP"),maxIterations:___default.number().int().positive().optional()});var z7=___default.union([___default.string(),___default.record(___default.string(),___default.unknown().optional())]),Fk=Zu.extend({type:___default.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:___default.number().optional()}),nv=Fk.extend({command:SC}),rv=Fk.extend({command:vC}),iv=___default.object({moduleId:___default.string(),inputs:___default.record(___default.string(),___default.string()).optional()}),wC=Zu.merge(iv.extend({type:___default.literal("MOBILE_MODULE_STEP")}));iv.extend({steps:___default.lazy(()=>td.array())});iv.extend({steps:___default.lazy(()=>dm.array())});var _1=(o=>(o.V2="2",o.V3="3",o))(_1||{});var H7="3",O1=___default.nativeEnum(_1),RC=___default.object({status:___default.literal("SUCCESS"),message:___default.string().optional(),results:___default.object({description:___default.string(),status:___default.enum(io),message:___default.string().optional()}).array(),finalScreenshot:Ql.optional()}),AC=___default.lazy(()=>___default.discriminatedUnion("type",[nv,AVe])),EC=___default.lazy(()=>___default.discriminatedUnion("type",[rv,EVe]));var gVe=qd.extend({platform:___default.literal("ANDROID"),resolvedGoal:___default.string(),steps:___default.lazy(()=>AC.array()),lastSuccessfulRun:RC.optional()}),fVe=qd.extend({platform:___default.literal("IOS"),resolvedGoal:___default.string(),steps:___default.lazy(()=>EC.array()),lastSuccessfulRun:RC.optional()}),P1=___default.discriminatedUnion("platform",[gVe,fVe]),Dg=Zu.extend({type:___default.literal("MOBILE_AI_ACTION_STEP"),text:___default.string(),version:O1.optional(),cache:P1.optional(),disableCache:___default.boolean().optional(),precondition:___default.string().optional(),postcondition:___default.string().optional()});var bVe=___default.discriminatedUnion("type",[Vp,ov,eb,ev]),Fg=Fk.extend({command:bVe}),SVe=___default.discriminatedUnion("type",[Vp,ov,tb,ev]),Bg=Fk.extend({command:SVe}),TVe=___default.object({assertion:Fg,steps:___default.lazy(()=>td.array())}),vVe=___default.object({assertion:Bg,steps:___default.lazy(()=>dm.array())}),AVe=Lg.extend({blocks:___default.lazy(()=>___default.object({assertion:Fg,steps:AC.array()}).array()),elseSteps:___default.lazy(()=>AC.array()).optional()}),EVe=Lg.extend({blocks:___default.lazy(()=>___default.object({assertion:Bg,steps:EC.array()}).array()),elseSteps:___default.lazy(()=>EC.array()).optional()}),wVe=Lg.extend({blocks:___default.lazy(()=>TVe.array()),elseSteps:___default.lazy(()=>td.array()).optional()}),RVe=Lg.extend({blocks:___default.lazy(()=>vVe.array()),elseSteps:___default.lazy(()=>dm.array()).optional()}),CVe=Wp.extend({condition:Fg.optional(),steps:___default.lazy(()=>td.array())}),IVe=Wp.extend({condition:Bg.optional(),steps:___default.lazy(()=>dm.array())}),td=___default.discriminatedUnion("type",[nv,wC,Dg,wVe,CVe]),dm=___default.discriminatedUnion("type",[rv,wC,Dg,RVe,IVe]);___default.union([td.array(),dm.array()]);var k1=___default.object({parameterNames:___default.string().array(),defaultParameters:___default.record(___default.string(),___default.string()).optional(),parameterEnums:___default.record(___default.string(),___default.string().array()).optional()}),Bk=___default.object({moduleId:Lr,name:___default.string(),description:___default.string().nullish(),platform:___default.nativeEnum(Kc).optional().default("ANDROID"),parameters:k1.optional(),enabled:___default.boolean().nullish(),schemaVersion:___default.string()}),M1=Bk.omit({name:true}),xVe=M1.extend({steps:z7.array()});___default.object({fileType:___default.literal(ze.MOBILE_MODULE)}).merge(xVe);var $7=Bk.omit({platform:true,schemaVersion:true});({ANDROID:$7.extend({platform:___default.literal("ANDROID"),steps:td.array()}),IOS:$7.extend({platform:___default.literal("IOS"),steps:dm.array()})});var ab=(t=>(t.MODULE="RESOLVED_MOBILE_MODULE",t))(ab||{}),G7=___default.object({description:___default.string().optional(),name:___default.string().describe("name of the module"),parameters:k1.optional()}),V7=iv.merge(G7).extend({platform:___default.literal("ANDROID"),get steps(){return Zc.array()}}),W7=iv.merge(G7).extend({platform:___default.literal("IOS"),get steps(){return eu.array()}});___default.discriminatedUnion("platform",[V7,W7]);var L1=Zu.merge(V7).extend({type:___default.literal("RESOLVED_MOBILE_MODULE")}),N1=Zu.merge(W7).extend({type:___default.literal("RESOLVED_MOBILE_MODULE")});___default.discriminatedUnion("platform",[L1,N1]);var _Ve=___default.object({assertion:Fg,get steps(){return Zc.array()}}),D1=Lg.extend({get blocks(){return _Ve.array()},get elseSteps(){return Zc.array().optional()}}),OVe=___default.object({assertion:Bg,get steps(){return eu.array()}}),F1=Lg.extend({get blocks(){return OVe.array()},get elseSteps(){return eu.array().optional()}}),PVe=Wp.extend({condition:Fg.optional(),get steps(){return Zc.array()}}),kVe=Wp.extend({condition:Bg.optional(),get steps(){return eu.array()}}),Zc=___default.discriminatedUnion("type",[L1,nv,Dg,D1,PVe]),eu=___default.discriminatedUnion("type",[N1,rv,Dg,F1,kVe]);function q7(e){return Object.values(ab).includes(e)||Object.values(Xc).includes(e)}var K7=(a=>(a.PRECONDITION="PRECONDITION",a.REPLAY="REPLAY",a.GENERATE="GENERATE",a.AUTOHEAL="AUTOHEAL",a.POSTCONDITION="POSTCONDITION",a.GOAL_CHECK="GOAL_CHECK",a))(K7||{}),Y7=z.enum(["pending","running","success","failed"]),J7=z.object({type:z.literal("THOUGHT"),text:z.string(),blockId:z.string().optional()}),X7=z.object({type:z.literal("TOOL_CALL"),toolName:z.string()}),Q7=z.object({type:z.literal("PHASE"),phase:z.nativeEnum(K7),failureMessage:z.string().optional()}),MVe=z.object({type:z.literal("STEP_UPDATE"),stepIndex:z.number(),step:Zc,status:Y7,conditionMet:z.boolean().optional(),message:z.string().optional(),afterSnapshotId:z.string().optional()}),LVe=z.object({type:z.literal("STEP_UPDATE"),stepIndex:z.number(),step:eu,status:Y7,conditionMet:z.boolean().optional(),message:z.string().optional(),afterSnapshotId:z.string().optional()}),Z7=z.object({type:z.literal("SCREENSHOT"),stepIndex:z.number(),screenshotId:z.string()}),eee=z.object({type:z.literal("POSTCONDITION_AUTOGENERATED"),postcondition:z.string()}),tee=z.object({type:z.literal("POSTCONDITION_REVISED"),postcondition:z.string(),previousPostcondition:z.string()}),oee=z.object({type:z.literal("GOAL_CHECK"),achieved:z.boolean(),reasoning:z.string(),violatedUserRule:z.boolean().default(false)}),NVe=z.object({type:z.literal("CACHED_STEPS_GENERATED"),cachedSteps:AC.array(),resolvedGoal:z.string(),lastSuccessfulRun:RC.optional()}),DVe=z.object({type:z.literal("CACHED_STEPS_GENERATED"),cachedSteps:EC.array(),resolvedGoal:z.string(),lastSuccessfulRun:RC.optional()}),FVe=z.discriminatedUnion("type",[J7,X7,Q7,MVe,Z7,NVe,eee,tee,oee]),BVe=z.discriminatedUnion("type",[J7,X7,Q7,LVe,Z7,DVe,eee,tee,oee]);function nee(e){let t=z.object({version:z.literal(1),events:e.array(),spans:f$.array().optional()});return z.union([t,e.array()]).transform(o=>Array.isArray(o)?{version:1,events:o}:o)}var ree=nee(FVe),iee=nee(BVe);var tu=___default.object({message:___default.string().optional(),startTime:___default.number(),endTime:___default.number(),status:___default.nativeEnum(io),trace:___default.unknown().optional().optional(),beforeSnapshot:___default.string().optional(),afterSnapshot:___default.string().optional(),data:___default.unknown().optional().optional().describe("output data from the step"),aiSuggested:___default.boolean().optional(),beforeTestContext:HT.optional(),afterTestContext:HT.optional()}),aee=tu.merge(nv).extend({previousAttempts:___default.lazy(()=>Hs.array()).optional()}),UVe=tu.merge(wC).extend({steps:___default.lazy(()=>Hs.array()),name:___default.string().optional(),previousAttempts:___default.lazy(()=>Hs.array()).optional()}),jVe=tu.merge(Dg).extend({steps:___default.lazy(()=>Hs.array()),previousAttempts:___default.lazy(()=>Hs.array()).optional(),failureRecoveryReason:___default.string().optional(),trajectory:ree.optional()}),zVe=tu.merge(D1).extend({assertionResult:aee.optional(),steps:___default.lazy(()=>Hs.array()),previousAttempts:___default.lazy(()=>Hs.array()).optional()}),HVe=tu.merge(Wp).extend({condition:Fg.optional(),steps:___default.lazy(()=>Hs.array()),iterationCount:___default.number().optional(),iterationResultCounts:___default.number().array().optional(),firstIterationConditionSkipped:___default.boolean().optional(),previousAttempts:___default.lazy(()=>Hs.array()).optional()}),Hs=___default.discriminatedUnion("type",[aee,UVe,jVe,zVe,HVe]),see=tu.merge(rv).extend({previousAttempts:___default.lazy(()=>$s.array()).optional()}),$Ve=tu.merge(wC).extend({steps:___default.lazy(()=>$s.array()),name:___default.string().optional(),previousAttempts:___default.lazy(()=>$s.array()).optional()}),GVe=tu.merge(Dg).extend({steps:___default.lazy(()=>$s.array()),previousAttempts:___default.lazy(()=>$s.array()).optional(),failureRecoveryReason:___default.string().optional(),trajectory:iee.optional()}),VVe=tu.merge(F1).extend({assertionResult:see.optional(),steps:___default.lazy(()=>$s.array()),previousAttempts:___default.lazy(()=>$s.array()).optional()}),WVe=tu.merge(Wp).extend({condition:Bg.optional(),steps:___default.lazy(()=>$s.array()),iterationCount:___default.number().optional(),iterationResultCounts:___default.number().array().optional(),firstIterationConditionSkipped:___default.boolean().optional(),previousAttempts:___default.lazy(()=>$s.array()).optional()}),$s=___default.discriminatedUnion("type",[see,$Ve,GVe,VVe,WVe]);var qVe=tu.extend({index:___default.number().optional(),userFacingStepReference:___default.string().optional(),description:___default.string()}),lee=qVe.extend({beforeScreenshot:___default.string().optional(),afterScreenshot:___default.string().optional()});var cee=z.object({attributesRequired:z.array(z.string()).optional(),textRequired:z.boolean().optional(),boundsRequired:z.boolean().optional(),positionSpecificity:z.enum(vl).optional(),shapeSpecificity:z.enum(vl).optional()}),KVe=z.object({id:z.number(),requirements:cee}).array();z.object({thoughts:z.string(),id:z.number(),updatedMemory:tR.optional(),inWebview:z.boolean().optional(),requirements:cee.optional(),additionalElements:KVe.optional()});var YVe=z.literal("SCROLL_TO"),uee=z.object({description:z.string(),screenXml:z.string(),screenshot:z.string(),source:YVe.optional(),memory:z.discriminatedUnion("type",[$u,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional()}),dee=z.object({assertion:z.string(),screenXml:z.string(),screenshot:z.string(),contextChoice:Wy.optional(),knowledgeBaseSection:z.string().optional(),memory:z.discriminatedUnion("type",[$y,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional()});z.object({thoughts:z.string(),result:z.boolean(),relevantElements:z.array(z.number()).optional(),updatedMemory:oR.optional(),citations:Kn.array().optional()});var mee=z.object({failedResults:lee.array(),nextStepsSerialized:z.string().array(),currentScreenXml:z.string(),currentScreenshot:z.string(),testDescription:z.string()}),pee=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(pee||{});z.object({thoughts:z.string(),scenario:z.enum(pee),instructions:z.string().nullish(),reasonSummary:z.string().nullish()});var JVe=new Set(["gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]);function hee(e){return JVe.has(e)}z.looseObject({type:z.literal("response.create")});var gee=z.union([z.looseObject({response:z.looseObject({id:z.string()}),sequence_number:z.number(),type:z.literal("response.completed")}),z.looseObject({code:z.string().nullable(),message:z.string(),sequence_number:z.number(),type:z.literal("error")})]);var sb="1",fee=z.enum(["GENERATED","CACHE"]),B1=fee.enum,yee=z.enum(["PULL_REQUEST","DIRECT_COMMIT","PATCH","LOCAL_CHANGES","OWNER_PULL_REQUEST","ALREADY_FIXED_ELSEWHERE"]),qp=yee.enum,XVe=z.object({patchId:z.uuid(),sourceRunId:z.string().min(1).optional(),testId:z.string().min(1),testPath:z.string().min(1),writtenPaths:z.array(z.string().min(1)).min(1).optional(),environment:z.string().min(1).optional()}),QVe=z.object({applicationId:z.uuid(),patchId:z.uuid(),sourceRunId:z.string().min(1).optional(),source:fee,delivery:yee,environment:z.string().min(1).optional(),repository:z.string().min(1).optional(),baseBranch:z.string().min(1).optional(),headBranch:z.string().min(1).optional(),prNumber:z.int().positive().optional(),commitSha:z.string().min(1).optional(),appliedAt:z.iso.datetime().optional(),patchedTestBundleHash:z.string().min(1).optional(),baseTestBundleHash:z.string().min(1).optional()});z.object({patches:z.array(XVe).max(1e3),applications:z.array(QVe).max(1e3)});var ZVe=200,eWe=50,tWe=z.object({testId:z.string().min(1),patchIds:z.array(z.string().min(1)).max(eWe).min(1)});z.object({repository:z.string().min(1),baseBranch:z.string().min(1),excludeHeadBranch:z.string().min(1).optional(),failures:z.array(tWe).min(1).max(ZVe)});var bee=z.object({existingFixes:z.array(PH)});var See="ui_states.jsonl";z.object({stepId:z.string(),parentStepIdChain:z.array(z.string()),fingerprintHash:z.string(),minhash:z.array(z.number().int()),canonicalUrl:z.string(),capturedAt:z.number().describe("Unix timestamp in milliseconds"),archivalFingerprintHash:z.string().optional(),archivalMinhash:z.array(z.number().int()).optional()});var oWe=z.object({testId:z.string(),name:z.string(),relativeFilePath:z.string(),coverage:z.string(),note:z.string().optional()}),nWe=z.object({name:z.string(),summary:z.string(),status:z.string().optional(),existingCoverage:z.array(oWe).default([])}),rWe=z.object({name:z.string(),summary:z.string(),importance:z.string().optional(),relatedJourney:z.string().optional(),mode:z.string().optional(),preconditions:z.array(z.string()).default([]),outline:z.array(z.string()).default([]),acceptanceCriteria:z.array(z.string()).default([]),existingTestId:z.string().optional(),existingTestPath:z.string().optional(),customAttributes:z.record(z.string(),z.unknown()).optional()}),iWe=z.object({testPlanName:z.string(),status:z.string(),testPath:z.string().optional(),summary:z.string(),notes:z.array(z.string()).optional()}),aWe=z.object({status:z.string(),builtTests:z.array(iWe).default([]),summary:z.string().optional(),notes:z.string().optional()}),sWe=z.object({control:z.string(),status:z.string(),result:z.string()}),lWe=z.object({testPlanName:z.string(),status:z.string(),summary:z.string(),verified:z.array(z.string()).default([]),gaps:z.array(z.string()).default([]),reportedBugs:z.array(z.string()).default([]),controls:z.array(sWe).default([]),customAttributes:z.record(z.string(),z.unknown()).optional()}),cWe=z.object({status:z.string(),planReports:z.array(lWe).default([]),summary:z.string().optional(),notes:z.string().optional()});z.object({summary:z.string().optional(),changedJourneys:z.array(nWe).default([]),testPlans:z.array(rWe).default([]),buildSummary:aWe.optional(),bugbashSummary:cWe.optional()});var uWe=z.object({agentId:z.string().optional(),video:z.string().optional(),startedAt:z.number().optional(),finishedAt:z.number().optional(),videoStartMs:z.number().optional(),videoEndMs:z.number().optional()});z.object({name:z.string(),summary:z.string(),expected:z.string(),actual:z.string(),severity:z.string().optional(),reproSteps:z.array(z.string()).default([]),recording:uWe.optional()});function Tee(e){return [...new Map(e.map(t=>[t.name,t])).values()]}var lb=(d=>(d.TestRun="test-run",d.MobileTestRun="mobile-test-run",d.CreditsUsed="credits-used",d.CreditsUsedV2="credits-used-v2",d.StepsExecuted="steps-executed",d.LLMTokensUsed="llm-tokens-used",d.AIAgentInvocation="ai-agent-invocation",d.AITriageTestResult="ai-triage-test-result",d.SandboxRuntimeSecondsUsed="sandbox-runtime-seconds-used",d.HostedBrowserSecondsUsed="hosted-browser-seconds-used",d.LimrunEmulatorSessionMinutesUsed="limrun-emulator-session-minutes-used",d))(lb||{}),Ug=(r=>(r.Select="select",r.Classify="classify",r.Triage="triage",r.Mo="mo",r))(Ug||{}),av=(r=>(r.Fixed="fixed",r.CannotFix="cannot-fix",r.NoFixNeeded="no-fix-needed",r.Error="error",r))(av||{}),us=(d=>(d.TestRunner="test-runner",d.Editor="editor",d.Mcp="mcp",d.Mo="mo",d.Select="ai-select",d.Explore="explore",d.Heal="heal",d.ResultClassification="result-classification",d.GithubPrSummary="github-pr-summary",d.AppGraph="app-graph",d.RunViewer="run-viewer",d))(us||{}),vee="sessionId";var dWe=3;function mWe(e){return e==="MODULE"||e==="CONDITIONAL"||e==="WHILE_LOOP"||e==="SECTION"||e==="RESOLVED_MODULE"}function Aee(e){if(!mWe(e))switch(e){case "PRESET_ACTION":return 0;case "AI_ACTION":return 3;case "AI_ACTION_DYNAMIC":return 5;default:(o=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}function Uk(e){switch(e.type){case "AI_EXTRACT":case "AI_ASSERTION":return dWe;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:(o=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}var U1=z.object({name:z.string(),value:z.string(),url:z.string().optional(),domain:z.string().optional(),path:z.string().optional(),expires:z.number().default(Date.now()/1e3+60*60*24*365),httpOnly:z.boolean().optional(),secure:z.boolean().default(true),sameSite:z.union([z.literal("Strict"),z.literal("Lax"),z.literal("None")]).default("None")});function jk(e,t){let o=[],n=splitCookiesString(e);for(let r of n){let i=parseString(r,{decodeValues:false});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=false),!i.path&&i.domain&&(i.path="/"),!i.domain&&t&&(i.domain=t);let s=U1.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});o.push(s);let l=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),c=r.match(/\b(\S+)=([^;]*)/g);if(c)for(let u of c){let[d,m]=u.split("=");if(!d||!m)throw new Error(`Invalid key-value pair in cookie: ${u}`);l.includes(d.toLowerCase())||o.push({...s,name:d,value:m});}}return o}var gWe=z.object({origin:z.string(),localStorage:z.array(z.object({name:z.string(),value:z.string()})),sessionStorage:z.array(z.object({name:z.string(),value:z.string()})).optional()}),fWe=z.object({entries:z.record(z.string(),z.array(z.tuple([z.unknown().optional(),z.unknown().optional()]))),version:z.number().optional(),stores:z.record(z.string(),z.object({keyPath:z.union([z.string(),z.array(z.string())]).nullable(),autoIncrement:z.boolean(),indexes:z.array(z.object({name:z.string(),keyPath:z.union([z.string(),z.array(z.string())]),unique:z.boolean(),multiEntry:z.boolean()}))})).optional()}),zk=z.object({cookies:U1.array().optional(),origins:gWe.array().optional(),idb:z.record(z.string(),fWe).optional().describe("key is db name")});function Eee(e,t){let o=[];return e.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let r=U1.safeParse({name:n.key,...n});if(!r.success)return;let i=r.data;!i.domain&&!i.url&&(i.domain=t),o.push(i);}),o}var Ol={type:true,cache:true},wee=[Vp.pick(Ol),eb.pick(Ol),hC.pick(Ol),yC.pick(Ol),mC.pick(Ol),uC.pick(Ol),sC.pick(Ol)],j1=___default.discriminatedUnion("type",wee),Ree=[Vp.pick(Ol),tb.pick(Ol),gC.pick(Ol),bC.pick(Ol),pC.pick(Ol),lC.pick(Ol),dC.pick(Ol)],z1=___default.discriminatedUnion("type",Ree);Object.values(jo).filter(e=>wee.some(t=>t.shape.type.safeParse(e).success));Object.values(jo).filter(e=>Ree.some(t=>t.shape.type.safeParse(e).success));var H1=___default.object({type:___default.literal("MOBILE_AI_ACTION_STEP"),cache:P1}),Hk=___default.union([j1,H1]),$k=___default.union([z1,H1]);var $1=(a=>(a.US_EAST_1="us-east1",a.US_EAST_2="us-east2",a.US_WEST_1="us-west1",a.US_WEST_2="us-west2",a.EU_NORTH_1="eu-north1",a.AS_SOUTH_1="as-south1",a))($1||{}),Gk=(n=>(n.US="us",n.EU="eu",n.AS="as",n))(Gk||{}),Cee=(t=>(t.LOCAL="local",t))(Cee||{}),IC=___default.nativeEnum(Gk),G1=___default.nativeEnum($1).or(___default.nativeEnum(Gk)),V1=___default.nativeEnum($1).or(___default.nativeEnum(Gk)).or(___default.nativeEnum(Cee)),bWe="closest";V1.or(___default.literal(bWe));var lv=(o=>(o.ANDROID_14="14",o.ANDROID_15="15",o))(lv||{});var Vk=(t=>(t.IOS_26="26",t))(Vk||{});var SWe=["1.56.1-lim.1","1.60.0-lim.1"],Iee=___default.enum(SWe);var xee=___default.nativeEnum(lv).or(___default.nativeEnum(Vk));var TWe=___default.object({disableMomenticAccessibilityTree:___default.boolean().optional(),autoGrantPermissions:___default.boolean().optional().describe("Automatically grant app permission prompts during the run. Android only."),autoAcceptAlerts:___default.boolean().optional().describe("Automatically accept native alert dialogs. iOS only."),autoDismissAlerts:___default.boolean().optional().describe("Automatically dismiss native alert dialogs. iOS only."),disableXmlSnapshots:___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:YT.optional(),locale:___default.string().optional().describe("Device locale code (e.g. 'fr', 'en-us'). Sets the device language and region. iOS and Android.")}),vWe="avdId",AWe="iosDeviceType",EWe="iosVersion",wWe="localEmulatorStartTimeout",_ee=___default.number().int().positive(),RWe=___default.object({downloadKbps:_ee.optional().describe("Maximum download bandwidth in kilobits per second."),uploadKbps:_ee.optional().describe("Maximum upload bandwidth in kilobits per second.")}),CWe=___default.object({selectors:___default.array(___default.string().trim().min(1)).min(1).max(74).describe("Required destinations to route through the CLI runner: domains, wildcard subdomains (which exclude the root domain), or IP/localhost:port destinations. URLs and catch-all wildcards are not supported."),capture:___default.boolean().optional().describe("Record HTTP(S) requests and responses for tunneled traffic. Defaults to false. View captured traffic in the run's Network tab. HTTPS inspection may break certificate-pinned apps.")}),W1=TWe.extend({tunnel:___default.union([___default.literal(false),CWe]).optional().describe("Route selected traffic from hosted mobile CLI emulators through the CLI runner. Off by default; set false to disable a project-level tunnel. Enable capture to save HTTP(S) network logs."),enableLogcatCapture:___default.boolean().optional().describe("Enable Android emulator logcat capture. This is disabled by default to reduce log streaming overhead and emulator lag."),enableSyslogCapture:___default.boolean().optional().describe("Enable iOS simulator syslog capture. This is disabled by default to reduce log streaming overhead and simulator lag."),region:V1.optional().describe('Where the emulator runs: "local" for an emulator on your machine, or a region for hosted emulators. Defaults to hosted emulators.'),jurisdiction:IC.optional().describe('Pin hosted emulators to a single jurisdiction: "us", "eu", or "as". Emulators may run in any data center within that jurisdiction, but never outside it: unlike region, this is a hard constraint, and emulator creation fails instead of falling back to another jurisdiction.'),smartWaitingTimeoutMs:___default.number().optional().refine(e=>e===void 0||e>=0,{message:"Smart waiting timeout must not be negative"}).describe("Budget for every wait and retry on an interaction: settling the screen, the readiness check before an AI locate, and retrying a cached target. In milliseconds. Defaults to 5000."),remoteEmulatorSettings:___default.object({androidVersion:___default.nativeEnum(lv).optional()}).optional(),localEmulatorSettings:___default.object({[vWe]:qT,[AWe]:qT,[EWe]:qT}).optional(),[wWe]:___default.number().positive().optional().describe("How long to wait for a local emulator or simulator to finish starting, in milliseconds. Defaults to 300000. Raise this on slow machines such as hosted CI runners."),geolocation:___default.object({latitude:___default.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:___default.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),networkConditions:RWe.optional().describe("Limit the emulator's Wi-Fi bandwidth for the whole run, in kilobits per second. Hosted Android emulators only."),waitForStability:___default.boolean().optional().describe("Wait for the screen to settle after every step that can change it. Off by default. Does not affect the waits before targeting: an AI locate always waits for a ready screen, and a cached target is retried until the smart-waiting timeout either way."),elementCheckTimeoutSeconds:___default.number().int().min(0).max(em).optional().describe("Default max seconds to wait for element check assertions to be true. Element check steps with an explicit timeout are unaffected."),keyPressDelayMs:___default.number().min(0).max(1e3).optional().describe("Default delay in milliseconds between key presses for type steps. Steps with an explicit key press delay are unaffected.")});var xC=___default.object({retries:___default.number().optional().describe("number of retries to run"),defaultChannel:___default.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:___default.string().optional().describe("Default app artifact tag or alias to use. If not set, the latest available tag is used."),defaultEnv:___default.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:qT.describe("APK to install when using the emulator in the local region."),defaultAppFilePath:qT.describe("App file (e.g. .app or .ipa) to install when using the emulator in the local region."),emulator:W1.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:Z$.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),Oee=___default.object({id:Lr,description:___default.string(),schemaVersion:___default.string(),settings:xC.optional(),disabled:___default.boolean().optional(),labels:___default.array(___default.string()).optional()}),cv=Oee.extend({platform:___default.literal("ANDROID").optional().default("ANDROID")}),uv=Oee.extend({platform:___default.literal("IOS")}),Pee=___default.discriminatedUnion("platform",[cv,uv]),kee=___default.object({fileType:___default.literal(ze.MOBILE_TEST)}),Mee=kee.merge(cv),Lee=kee.merge(uv);___default.discriminatedUnion("platform",[Mee,Lee]);var Nee=cv.merge(___default.object({steps:___default.array(td)})),Dee=uv.merge(___default.object({steps:___default.array(dm)}));___default.discriminatedUnion("platform",[Nee,Dee]);var IWe=Mee.merge(Nee),xWe=Lee.merge(Dee);___default.discriminatedUnion("platform",[IWe,xWe]);___default.object({name:___default.string(),steps:___default.array(td).optional(),settings:xC.optional()});var Fee=cv.extend({steps:Zc.array(),beforeSteps:Zc.array().optional(),afterSteps:Zc.array().optional()}),Bee=uv.extend({steps:eu.array(),beforeSteps:eu.array().optional(),afterSteps:eu.array().optional()});___default.discriminatedUnion("platform",[Fee,Bee]);var _We=Fee.extend({name:___default.string()}),OWe=Bee.extend({name:___default.string()});___default.discriminatedUnion("platform",[_We,OWe]);var Sa=___default.object({startTime:___default.number(),endTime:___default.number().optional(),durationMs:___default.number().optional(),error:___default.string().optional(),result:___default.unknown().optional().optional(),attributes:___default.record(___default.string(),___default.unknown().optional()),subSpans:___default.lazy(()=>KWe.array())});var _C=Sa.extend({type:___default.literal("SECTION"),name:___default.string()}),PWe=Sa.extend({type:___default.literal("GET_PAGE_STATE")}),kWe=Sa.extend({type:___default.literal("GET_PAGE_SCREENSHOT")}),MWe=Sa.extend({type:___default.literal("SMART_WAITING")}),LWe=Sa.extend({type:___default.literal("SCROLL_ELEMENT_INTO_VIEW")}),NWe=Sa.extend({type:___default.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:___default.string().optional(),result:___default.object({id:___default.number(),thoughts:___default.string(),citations:Kn.array().optional()}).optional()}),DWe=Sa.extend({type:___default.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:___default.string().optional(),elementScreenshotSnapshotId:___default.string().optional(),result:___default.object({thoughts:___default.string(),result:___default.boolean(),citations:Kn.array().optional()}).optional()}),FWe=Sa.extend({type:___default.literal("AI_EXTRACTION_CALL"),screenshotSnapshotId:___default.string().optional(),browserStateSnapshotId:___default.string().optional(),result:___default.object({thoughts:___default.string().optional(),result:___default.unknown().optional().optional()}).optional()}),BWe=Sa.extend({type:___default.literal("ELEMENT_ASSERTION"),name:___default.string(),result:___default.object({success:___default.boolean(),message:___default.string().optional()}).optional()}),UWe=Sa.extend({type:___default.literal("BROWSER_INTERACTION"),name:___default.string(),coordinates:___default.object({x:___default.number(),y:___default.number()}).optional(),value:___default.string().optional(),selector:___default.string().optional()}),jWe=Sa.extend({type:___default.literal("CACHE_RESOLUTION"),resolutionMethod:___default.string().optional(),cacheMissReason:___default.nativeEnum(gT).optional(),targetSource:___default.string().optional(),elementScreenshotSnapshotId:___default.string().optional(),evaluationDurationMs:___default.number().optional(),resolutionAttempts:___default.number().optional(),result:___default.object({serializedElement:___default.string()}).optional()}),zWe=Sa.extend({type:___default.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:___default.string().optional(),result:___default.object({serializedElement:___default.string()}).optional()}),HWe=Sa.extend({type:___default.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:___default.string().optional(),result:___default.object({outcome:___default.string(),logs:___default.string().array().optional(),serializedElement:___default.string().optional(),relativeClickPoint:___default.object({x:___default.number(),y:___default.number()}).optional(),force:___default.boolean().optional()}).optional()}),$We=Sa.extend({type:___default.literal("WAIT_FOR_STABILITY")}),GWe=Sa.extend({type:___default.literal("GENERIC"),name:___default.string()}),VWe=Sa.extend({type:___default.literal("PAGE_ASSERTION"),name:___default.string(),result:___default.object({success:___default.boolean(),message:___default.string().optional()}).optional()}),WWe=Sa.extend({type:___default.literal("AUTO_FOLLOW_NEW_TABS"),result:___default.object({followed:___default.boolean()}).optional()}),qWe=Sa.extend({type:___default.literal("VISUAL_DIFF"),name:___default.string(),result:___default.object({success:___default.boolean(),message:___default.string().optional()}).optional()});function Uee(e){return e.type==="CACHE_RESOLUTION"||e.type==="TARGET_RESOLUTION"}var KWe=___default.discriminatedUnion("type",[_C,PWe,kWe,MWe,LWe,NWe,DWe,FWe,BWe,UWe,zWe,jWe,HWe,$We,VWe,qWe,GWe,WWe]);z.object({testId:z.string(),sessionId:z.string()});var jee=z.object({uploadUrl:z.string(),id:z.string()});new Set(Object.values(jn));var On={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.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",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 YWe=z.string().refine(e=>Ph.valid(e),{error:"must be a valid semver string"});function q1(e){return Ph.parse(e)||void 0}function OC(e){if(e!==void 0)return e===true||e==="true"||e==="1"}function Hee(e){if(e!=="true"&&e!=="false")throw new ae(`Expected true or false, got "${e}".`);return e==="true"}var $ee="on-fail";function K1(e){return e==="on-fail"?"on-fail":e==="false"?false:!!e}var Gee=(o=>(o.CLI="cli",o.MobileCLI="mobile-cli",o))(Gee||{}),JWe=z.nativeEnum(Gee),Vee=(n=>(n.Error="error",n.Warn="warn",n.Info="info",n))(Vee||{}),XWe=z.nativeEnum(Vee),QWe=z.object({id:z.string(),level:XWe,versionRange:z.string(),announcement:z.string()});z.object({cliType:JWe,version:YWe});var Wee=z.object({announcements:z.array(QWe)});var PC=55555,Wk="momentic-code-eval.js";z.object({body:z.string(),to:z.string(),from:z.string()});z.object({from:z.string().optional(),to:z.string(),timeout:z.number().optional(),beforeDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional()});z.object({timeoutMs:z.number().nonnegative().optional()}).optional();z.object({phoneNumber:z.string(),leaseToken:z.string()});var ZWe=z.union([z.string(),z.date()]).transform(e=>e instanceof Date?e:new Date(e)),qee=z.object({phoneNumber:z.string(),expiresAt:ZWe,leaseToken:z.string()});z.object({to:z.email(),from:z.string(),subject:z.string(),body:z.string(),html:z.string().optional()});z.object({inbox:z.string().transform(e=>e.toLowerCase()),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),timeout:z.number().optional(),trimWhitespace:z.boolean().optional()});z.object({inbox:z.string(),limit:z.number().optional(),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),trimWhitespace:z.boolean().optional()});var Kee=z.object({email:z.string(),prefix:z.string(),expiresAt:z.coerce.date()}),qk=(o=>(o.RAW="RAW",o.RESPONSE="RESPONSE",o))(qk||{}),Yee=z.object({body:z.string().nullish(),status:z.number().optional(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}),eqe=z.object({url:z.string(),options:z.object({method:z.string(),body:z.string().nullish(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}).optional()}).optional(),tqe=z.object({body:z.string().nullish(),options:z.object({status:z.number(),statusText:z.string().optional(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}).optional()}).optional(),Jee=z.object({result:z.unknown().optional(),variableUpdates:z.record(z.string(),z.unknown().optional()).optional(),persistentVariableUpdates:z.record(z.string(),z.unknown().optional()).optional(),error:z.string().optional(),success:z.boolean()});z.object({id:z.string().optional(),orgId:z.string(),momenticLambdaAuthHash:z.string(),momenticLambdaAuthTimestamp:z.number(),code:z.string(),fragment:z.boolean(),state:z.object({env:z.record(z.string(),z.unknown().optional()),request:eqe,response:tqe,additionalBindings:z.record(z.string(),z.unknown().optional()).optional()}),timeoutMs:z.number().optional(),disallowVariableUpdates:z.boolean().optional(),responseSerialization:z.enum(qk).optional()});var jg=9e4;function Xee({orgId:e,timestamp:t}){return `${e}:${t}`}var oqe=_.object({url:_.string(),lineNumber:_.number(),columnNumber:_.number()}),Qee=_.object({timestamp:_.number(),text:_.string(),type:_.string(),tabIndex:_.number(),args:_.unknown().optional().array().optional(),url:_.string().optional(),location:oqe.optional()}),Zee=Qee.array(),kC=Zee.array();var MC=class{async getConsoleLogsForRunAttempt(t,o,n){}async getNetworkLogsForRunAttempt(t,o,n){}async getHtmlSnapshot(t,o){}async getA11yTreeSnapshot(t,o){}async getScreenshot(t,o){}async storeConsoleLogsForRunAttempt(t,o,n,r){}async storeNetworkLogsForRunAttempt(t,o,n,r){}listVideoAssetPaths(){return []}close(){}async storeScreenshot(t,o,n){}async storeOnDemandScreenshotById(t,o,n,r){}async storeHtmlSnapshot(t,o,n){}};var Kk=1e3,Y1=1e6,nqe=["image","font","video","audio"],rqe=["javascript"],iqe=["text"],aqe=["json","xml","html"];function J1(e){let[t,o]=e.split("/");return t&&nqe.includes(t)||o&&rqe.some(n=>o.includes(n))?false:!!(t&&iqe.includes(t)||o&&aqe.some(n=>o.includes(n)))}var sqe=z.object({name:z.string(),version:z.string(),comment:z.string().optional()}),lqe=z.object({name:z.string(),version:z.string(),comment:z.string().optional()}),cqe=z.object({onContentLoad:z.number().optional(),onLoad:z.number().optional(),comment:z.string().optional()}),LC=z.object({startedDateTime:z.string(),id:z.string(),title:z.string().optional(),pageTimings:cqe,comment:z.string().optional()}),uqe=z.array(LC),dqe=z.object({name:z.string(),value:z.string(),path:z.string().optional(),domain:z.string().optional(),expires:z.string().optional(),httpOnly:z.boolean().optional(),secure:z.boolean().optional(),comment:z.string().optional()}),tte=z.array(dqe),mqe=z.object({name:z.string(),value:z.string(),comment:z.string().optional()}),ote=z.array(mqe),pqe=z.object({name:z.string(),value:z.string(),comment:z.string().optional()}),hqe=z.array(pqe),gqe=z.object({name:z.string(),value:z.string().optional(),fileName:z.string().optional(),contentType:z.string().optional(),comment:z.string().optional()}),fqe=z.array(gqe),yqe=z.object({mimeType:z.string(),params:fqe,text:z.string(),comment:z.string().optional(),_redactedReason:z.string().optional()}),bqe=z.object({method:z.string(),url:z.string(),httpVersion:z.string().optional(),cookies:tte,headers:ote,queryString:hqe,postData:yqe.optional(),headersSize:z.number().optional(),bodySize:z.number().optional(),comment:z.string().optional()}),Sqe=z.object({size:z.number().optional(),compression:z.number().optional(),mimeType:z.string().optional(),text:z.string().optional(),encoding:z.string().optional(),comment:z.string().optional(),_redactedReason:z.string().optional()}),Tqe=z.object({status:z.number(),statusText:z.string(),httpVersion:z.string().optional(),cookies:tte,headers:ote,content:Sqe,redirectURL:z.string().optional(),headersSize:z.number().optional(),bodySize:z.number().optional(),comment:z.string().optional(),_mocked:z.boolean().optional()}),ete=z.object({expires:z.string().optional(),lastAccess:z.string(),eTag:z.string(),hitCount:z.number(),comment:z.string().optional()}),vqe=z.object({beforeRequest:ete.optional(),afterRequest:ete.optional(),comment:z.string().optional()}),Aqe=z.object({blocked:z.number().optional(),dns:z.number().optional(),connect:z.number().optional(),send:z.number(),wait:z.number(),receive:z.number(),ssl:z.number().optional(),comment:z.string().optional()}),Kp=z.object({pageref:z.string().optional(),startedDateTime:z.string(),time:z.number().optional(),request:bqe,response:Tqe.optional(),cache:vqe.optional(),timings:Aqe,serverIPAddress:z.string().optional(),connection:z.string().optional(),comment:z.string().optional(),_resourceType:z.string().optional(),_responseState:z.enum(["pending","received","finished","failed"]).optional()});function X1(e){return e._responseState?e._responseState==="finished"||e._responseState==="failed":!!e.response}var Eqe=z.array(Kp),wqe=z.object({version:z.string().default("1.1"),creator:sqe.optional(),browser:lqe.optional(),pages:uqe.optional(),entries:Eqe,comment:z.string().optional()}),Q1=z.object({log:wqe});z.record(z.string(),LC);z.record(z.string(),Kp);function Z1(e,t){return {log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(e).sort((o,n)=>new Date(o.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(t).sort((o,n)=>new Date(o.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}var nte=3,rte=z.object({failureCount:z.number().int().nonnegative(),lastSuccess:z.object({actionSummary:z.string().min(1),recordedAt:z.coerce.date()}).optional()}),Rqe=z.object({stepId:z.string().min(1),baseTestFileHash:z.string().min(1),branchName:z.string().min(1).optional(),environment:z.string().min(1).optional()}),Cqe={runId:z.string().min(1).optional()},Iqe=Rqe.extend(Cqe);Iqe.extend({succeeded:z.boolean(),actionSummary:z.string().min(1).optional()});var Yk=(L=>(L.DisableClickhouseCaches="disable_clickhouse_caches",L.ShowZeroOpacityElements="show_zero_opacity_elements",L.VisualActions="visual_actions",L.RagV2="rag_v2",L.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",L.GlobalLocatorRedirect="global_locator_redirect",L.FakerConstantSeed="faker_constant_seed",L.AutoExpandIframes="auto_expand_iframes",L.MobileNewAiActionStepsUseV3="mobile_new_ai_action_steps_use_v3",L.PerformanceInsights="performance_insights",L.ShowKnowledgeBase="show_knowledge_base",L.AppGraphBackend="app_graph_backend",L.AppGraphUI="app_graph_ui",L.ClassificationUI="classification_ui",L.HealingUI="healing_ui",L.ExploreUI="explore_ui",L.SlackNotifications="slack_notifications",L.SlackNotificationDms="slack_notification_dms",L.HealTraceUI="heal_trace_ui",L.ExploreTraceUI="explore_trace_ui",L.LinearIntegration="linear_integration",L.AtlassianIntegration="atlassian_integration",L.PosthogIntegration="posthog_integration",L.QaseIntegration="qase_integration",L.HostingIntegrations="hosting_integrations",L.TestinyIntegration="testiny_integration",L.TestRailIntegration="testrail_integration",L.RunAssertions="run_assertions",L.Mo="mo",L.MoSignupCredits="mo_signup_credits",L.MoMobile="mo_mobile",L))(Yk||{});var zg=z.union([z.string(),z.number(),z.boolean(),z.null(),z.record(z.string(),z.lazy(()=>zg)),z.array(z.lazy(()=>zg))]),cb=class{flags;payloads;constructor(t,o){this.flags=t,this.payloads=o;}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(([o,n])=>{typeof n=="boolean"&&Object.values(Yk).includes(o)&&(t[o]=this.isBooleanFlagEnabled(o));}),t}getAllFlagPayloads(){return cloneDeep(this.payloads)}getFlagPayload(t){let o=this.payloads[t];if(o!==void 0){if(typeof o=="string")try{return JSON.parse(o)}catch{return o}return o}}refresh(){throw new Error("Not implemented")}};var eG={".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",".caf":"audio/x-caf",".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",".m4a":"audio/mp4",".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"},ate=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var lte=z.discriminatedUnion("operation",[z.object({operation:z.literal("upsert"),path:z.string().min(1),content:z.string()}),z.object({operation:z.literal("delete"),path:z.string().min(1)})]),xqe=z.object({baseSha:z.string().min(1),headSha:z.string().min(1)}),_qe=z.object({baseBranch:z.string().min(1).max(255),baseCommitSha:z.string().min(1),expectedHeadSha:z.string().min(1).nullable().optional(),expectedBaseSha:z.string().min(1).optional(),headBranch:z.string().min(1).max(255).optional(),branchPrefix:z.string().min(1).max(255).optional(),idempotencyKey:z.string().min(1).optional()}),Oqe=5,Pqe=z.object({commitMessage:z.string().min(1),title:z.string().min(1),body:z.string(),reviewers:z.array(z.string().min(1)).optional(),teamReviewers:z.array(z.string().min(1)).optional(),fallbackReviewers:z.array(z.string().min(1)).max(Oqe).optional(),draft:z.boolean().optional()});_qe.extend(Pqe.shape).extend({changes:z.array(lte).min(1),coAuthorRange:xqe.optional(),requestCommitAuthorsAsReviewers:z.boolean().optional(),assignCommitAuthorsAsAssignees:z.boolean().optional(),assignees:z.array(z.string().min(1)).optional(),omitBaseCommitCoAuthors:z.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 cte=z.object({pullRequestUrl:z.url(),pullRequestNumber:z.number(),headBranch:z.string(),commitSha:z.string(),created:z.boolean(),authors:z.array(Hw).optional(),assignees:z.array(z.string()).optional(),reviewers:z.array(z.string()).optional()});z.object({branch:z.string().min(1).max(255),expectedHeadSha:z.string().min(1).optional(),commitMessage:z.string().min(1),changes:z.array(lte).min(1)});var ute=z.object({branch:z.string(),commitSha:z.string(),committed:z.boolean()});z.object({usernames:z.array(z.string().min(1)).min(1).max(50)});var dte=z.object({usernamesWithMergeAccess:z.array(z.string())}),mte=z.object({shas:z.array(z.string().min(1)).min(1).max(20)}),pte=z.object({authorsBySha:z.record(z.string(),z.array(Hw)),filesBySha:z.record(z.string(),z.array(z.string())).optional(),candidatesBySha:z.record(z.string(),z.array(z.object({githubLogin:z.string(),via:z.string(),isApp:z.boolean().optional()}))).optional(),touchedPaths:z.array(z.string())});z.object({query:z.string().min(1).max(256)});var oG=z.object({number:z.number(),title:z.string(),state:z.enum(["open","merged","closed"]),authorLogin:z.string().optional(),updatedAt:z.string().optional(),htmlUrl:z.string().optional(),body:z.string().optional(),changedPaths:z.array(z.string()).optional()}),hte=z.object({pullRequests:z.array(oG),scanned:z.number(),truncated:z.boolean()}),gte=z.object({authorLogin:z.string().min(1).optional(),authorIsBot:z.boolean().optional(),humanAssigneeLogins:z.array(z.string().min(1)).optional()}),fte=gte.extend({issueNumber:z.number(),htmlUrl:z.url(),headBranch:z.string().min(1),baseBranch:z.string().min(1),latestCommitSha:z.string().min(1),mergeCommitSha:z.string().min(1).optional(),draft:z.boolean().optional(),title:z.string().optional(),body:z.string().optional()});function yte(e){return e.authorLogin&&e.authorIsBot===false?e.authorLogin:e.humanAssigneeLogins?.[0]}gte.extend({number:z.number(),htmlUrl:z.url()});var nG=100;z.object({path:z.string().min(1),ref:z.string().min(1),limit:z.coerce.number().int().min(1).max(nG)});var kqe=z.object({path:z.string().min(1),status:z.string().min(1),additions:z.number(),deletions:z.number(),previousPath:z.string().optional(),patch:z.string().optional()}),bte=z.object({sha:z.string().min(1),author:z.string().optional(),email:z.string().optional(),date:z.string().optional(),message:z.string()}),Ste=z.object({mergeBaseSha:z.string().min(1),totalCommits:z.number(),commits:z.array(bte),files:z.array(kqe)}),Tte=z.object({commits:z.array(bte)}),vte=z.object({content:z.string().nullable()}),Ate=z.object({name:z.string().min(1),protected:z.boolean(),commit:z.object({sha:z.string().min(1)}).optional().catch(void 0)}),Ete=z.object({iid:z.number(),webUrl:z.url(),sourceBranch:z.string().min(1),targetBranch:z.string().min(1),latestCommitSha:z.string().min(1),description:z.string().optional()}),Mqe=z.object({name:z.string(),path:z.string(),body:z.string()}),Rte=z.object({template:Mqe});function Xk({githubRepository:e,gitlabProjectPath:t,gitOriginUrl:o}){let n=Lqe(o);return e?tG(n?.host??"github.com",e):t?tG(n?.host??"gitlab.com",t):n?tG(n.host,n.repositoryPath):void 0}function NC(e){let t=e?.trim();if(!t)return;let o="refs/heads/";return t.startsWith(o)?t.slice(o.length):t}function Lqe(e){let t=e?.trim();if(!t)return;if(t.includes("://"))try{let a=new URL(t);return ["git:","http:","https:","ssh:"].includes(a.protocol)?{host:a.host,repositoryPath:a.pathname}:void 0}catch{return}let o=t.indexOf(":");if(o<=0)return;let n=t.slice(0,o),r=t.slice(o+1),i=n.slice(n.lastIndexOf("@")+1);return i&&r?{host:i,repositoryPath:r}:void 0}function Nr(e){let[t,o,...n]=e.split("/");if(!(!t||!o||n.length>0))return {owner:t,repo:o}}function tG(e,t){let o=e.trim().toLowerCase(),n=t.trim().split("/").filter(i=>i.length>0);if(!o||n.length===0)return;if(o===`ssh.${Jk}`)o=Jk,n[0]?.toLowerCase()==="v3"&&(n=n.slice(1));else if(o.endsWith(ste)){let i=o.slice(0,-ste.length);if(!i)return;o=Jk,n=[i,...n];}o===Jk&&(n=n.filter(i=>i.toLowerCase()!=="_git"));let r=n.at(-1);if(r?.toLowerCase().endsWith(".git")){let i=r.slice(0,-4);if(!i)return;n[n.length-1]=i;}return `${o}/${n.join("/")}`.toLowerCase()}function Cte(e){let t=Nr(e);if(t)return t;throw new yo(`Invalid GitHub repository string: ${e}. Expected format "owner/repo".`)}var Jk="dev.azure.com",ste=".visualstudio.com",Nqe=/^co-authored-by:\s*.*?<([^>]+)>\s*$/gim,Dqe=/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i;function rG(e){return e.match(Dqe)?.[1]}function Fqe(e){let t=[];for(let o of e.matchAll(Nqe)){let n=o[1]?.trim();n&&t.push({email:n,githubLogin:rG(n)});}return t}function Ite(e){let t=[];for(let o of e.split("\0")){let n=o.trim();if(!n)continue;let r=n.indexOf(`
185
- `),i=r===-1?n:n.slice(0,r),a=r===-1?"":n.slice(r+1),s=[];i&&s.push({email:i,githubLogin:rG(i)}),s.push(...Fqe(a)),t.push(s);}return t}function Bqe(e){return (e.githubLogin??(e.email?rG(e.email):void 0))?.toLowerCase().endsWith("[bot]")??false}function xte(e){return e.filter(t=>!Bqe(t))}var _te="https://static.momentic.ai";function DC(e,t){return {light:`${_te}/${e}.svg`,dark:`${_te}/${e}-dark.svg`,alt:t}}var FC={runGroup:DC("run-group-button","View run group"),basePr:DC("view-base-pr-button","View base PR"),branch:DC("view-branch-button","View branch"),commit:DC("view-commit-button","View commit")};function BC({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 Hg=z.object({limit:z.number().min(1).max(100).optional(),page:z.number().min(1).optional()}),iG=z.object({page:z.number(),pageSize:z.number(),pageCount:z.number()});var aG=___default.object({platformSep:___default.string(),fullPathSegments:___default.string().array(),relativePathSegments:___default.string().array(),relativePath:___default.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:___default.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:___default.coerce.date(),createdAt:___default.coerce.date()});var Uqe=z.array(aG.extend({id:z.string(),name:z.string(),description:z.string().optional(),labels:z.string().array().optional()})),jqe=aG.extend({id:z.string(),name:z.string(),description:z.string().optional(),content:DP}),zqe=z.array(jqe);z.object({tests:Uqe,modules:zqe,labels:z.string().array()});z.string().array();var Ote=z.object({pathSegments:z.string().array()});c1.merge(Ir);var Pte=z.object({schemaVersion:z.string(),stepLists:oc}),kte=Ir.partial().merge(ls.pick({id:true})),db="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",sG={name:z.string().min(1).max(255).describe(db),description:z.string().optional(),baseUrl:z.url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:z.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.enum(Yu).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:jp.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:z.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.")},Mte=z.object(sG);c1.extend(z.object({relativeFilePath:z.string().describe("relative to project root")}).shape);var Lte=z.object({name:z.string()});z.object({relativeFilePath:z.string()});var Nte=z.object({name:z.string(),sourceModuleContent:DP});z.object({relativeFilePath:z.string()});var Dte=z.object({name:z.string(),description:z.string(),enabled:z.boolean(),steps:z.lazy(()=>Uo.array()),testFilePath:z.string().describe("relative to the project root"),folderPath:z.string().optional().describe("user selected folder path")}),Fte=z.object({name:z.string(),description:z.string(),enabled:z.boolean()}).partial(),Bte=z.object({folderPath:z.string()}),Ute=z.object({folderPath:z.string()});z.array(FR);var jte=z.object({defaultEnv:z.string().optional().describe("name of the default env, or undefined to unset")}),zte=z.object({configFilePath:z.string().describe("full path on disk")});z.object({hasEntities:z.boolean()});z.string().array();z.object({message:z.string(),newRelativeTestPath:z.string().optional()});var lG=z.object({name:z.string(),absolutePath:z.string(),relativePath:z.string(),pathSegments:z.array(z.string()),isDirectory:z.boolean(),size:z.number(),createdAt:z.coerce.date(),modifiedAt:z.coerce.date(),accessedAt:z.coerce.date()}),Hte=z.object({pathSegments:z.array(z.string()),directoriesOnly:z.boolean().optional()});z.object({absolutePath:z.string(),pathSegments:z.array(z.string()),contents:z.array(lG)});var $te=z.object({sourceDirectoryPath:z.string().optional(),value:z.string(),allowedExtensions:z.array(z.string()).optional()}),Hqe=z.object({name:z.string(),value:z.string(),isDirectory:z.boolean()});z.object({suggestions:z.array(Hqe)});var Gte=z.object({pathSegments:z.array(z.string())}),Vte=z.object({pathSegments:z.array(z.string()),newPathSegments:z.array(z.string())}),Wte=z.object({pathSegments:z.array(z.string()),recursive:z.boolean().optional()});z.object({success:z.boolean(),message:z.string(),pathSegments:z.array(z.string()).optional()});z.object({gitBranch:z.string(),fileMtime:z.coerce.date(),gitCommitSha:z.string()});var qte=typeof process<"u"&&true&&true,Qk=58889,mv=24*60*60*1e3;var Kte=z.record(z.string(),z.string()),$qe=z.object({type:z.literal("stdio").optional(),command:z.string().min(1),args:z.array(z.string()).optional(),env:Kte.optional(),cwd:z.string().optional()}),Gqe=z.object({type:z.enum(["http","sse"]).optional(),url:z.string().min(1),headers:Kte.optional()}),Vqe=z.union([$qe,Gqe]),Yte=z.record(z.string().min(1),Vqe);var Jte=z.string().trim().min(1).max(255).regex(/^[^/\\]+$/).refine(e=>e!=="."&&e!=="..");z.object({source:z.string().trim().min(1).max(500).refine(e=>Jte.safeParse(e.split("/").at(-1)).success)});var Xte=z.object({filename:Jte,downloadUrl:z.url()});z.object({filename:z.string().trim().min(1),destination:z.string().trim().min(1).optional()});var Qte=z.object({destination:z.string(),uploadUrl:z.url()});var jC=(n=>(n.DARWIN="darwin",n.LINUX="linux",n.WINDOWS="win32",n))(jC||{}),Zte=z.enum(jC),zC=(r=>(r.AZURE="AZURE",r.KERNEL="KERNEL",r.BROWSERBASE="BROWSERBASE",r.SELF_HOSTED="SELF_HOSTED",r))(zC||{}),Zk=z.enum(zC);z.object({azureRegion:z.string().optional(),azureWorkspaceId:z.string().optional()});z.object({});var HC=z.enum(["westus3","eastus2"]);z.object({});var Wqe=z.enum(["us-west-2","us-east-1","eu-central-1","ap-southeast-1"]);z.object({region:Wqe.optional()});var cG=(t=>(t.TEST_REVIEW="TEST_REVIEW",t))(cG||{});var qqe=z.object({type:z.literal("DESCRIPTION_UPDATE"),thoughts:z.string()}),eM=z.discriminatedUnion("type",[qqe]),Kqe=z.object({testId:z.string(),name:z.string(),orgId:z.string(),runId:z.string(),steps:Uo.array(),purpose:z.enum(cG),details:eM.or(eM.array()).optional()});Kqe.pick({name:true,orgId:true});var Yqe=z.object({id:z.string(),name:z.string().nullish(),createdAt:z.string().pipe(z.coerce.date()).or(z.date()),organizationId:z.string(),schemaVersion:z.string(),runId:z.string().nullish(),purpose:z.enum(cG),details:eM.or(eM.array()).optional(),applied:z.boolean().nullish(),appliedAt:z.coerce.date().nullish()}),eoe=Yqe.extend({steps:Uo.array()});var toe=z.enum(["v1","v2"]);var Xqe=z.enum(["element","content","attribute","tag_name","style"]),tM=z.enum(["exists","visible","enabled","editable","focused","contains","equals","starts_with"]);[...WQ,...VQ].forEach(e=>{if(!tM.options.includes(e.toLowerCase()))throw new Error(`V2CheckConditionSchema is missing option: ${e}`)});var uG={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}},roe={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"}},ioe={ELEMENT_EXISTENCE:"element",ELEMENT_CONTENT:"content",ELEMENT_ATTRIBUTE:"attribute",ELEMENT_NAME:"tag_name",ELEMENT_STYLE:"style"};function ooe(e){return {alias:dG(e),subject:e.subject,condition:e.condition,negated:e.negated,assertionType:uG[e.subject].assertionType,requiresName:uG[e.subject].requiresName,requiresValue:e.subject!=="element"&&e.condition!=="exists"}}function dG(e){let t=uG[e.subject],o=roe[e.condition];if(!aoe(e.subject,e.condition))throw new Error(`Unsupported element check alias for subject '${e.subject}' and condition '${e.condition}'.`);let n=e.negated?o.negativeAliasSuffix:o.positiveAliasSuffix;return `checkElement${t.aliasPrefix}${n}`}function aoe(e,t){let o=roe[t],n=o.elementCondition,r=o.contentOperation;return e==="element"?n!==void 0:r!==void 0}var Qqe=Xqe.options.flatMap(e=>tM.options.flatMap(t=>aoe(e,t)?[ooe({subject:e,condition:t,negated:false}),ooe({subject:e,condition:t,negated:true})]:[])),oM=new Map(Qqe.map(e=>[e.alias,e]));var Zqe=z.enum(Qd),eKe=z.enum(Zl);function qs(e){return oM.get(e)}function loe(e){let t=ioe[e.type],o=e.type==="ELEMENT_EXISTENCE"?e.condition:e.operation;return dG({subject:t,condition:tKe(o),negated:e.negated})}function coe(e){return Zqe.parse(e.toUpperCase())}function $C(e){return eKe.parse(e.toUpperCase())}function tKe(e){return tM.parse(e.toLowerCase())}var hv=z.string().regex(/\S+\s+\S+/,"Bare AI action goals must contain multiple words.").describe("Multi-word natural-language goal for an AI action V3 step."),Bt={saveAs:z.string().optional(),retries:z.number().optional(),skipped:z.boolean().optional(),comment:z.string().optional()};z.object(Bt);var gv=Object.keys(Bt);function Tt(e){return z.union([z.strictObject({[e.key]:e.simplified}),z.strictObject({[e.key]:e.detailed})])}function mr(e){return z.strictObject({[e.key]:e.detailed})}function oKe(e,t){let o=Array.from({length:t.length+1},(n,r)=>r);for(let n=1;n<=e.length;n+=1){let r=[n],i=e.charAt(n-1);for(let a=1;a<=t.length;a+=1)r.push(i===t.charAt(a-1)?o[a-1]??0:Math.min((o[a-1]??0)+1,(o[a]??0)+1,(r[a-1]??0)+1));o.splice(0,o.length,...r);}return o[t.length]??0}function uoe(e,t){let o=e.toLowerCase(),n,r=.5;for(let i of t){let a=i.toLowerCase(),s=Math.max(o.length,a.length),l=s===0?1:1-oKe(o,a)/s;l>r&&(r=l,n=i);}return n}var doe='Coordinates must be "x, y" pixel values, e.g. "100, 200"',fv=z.union([Yd,z.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,doe)],{error:doe});z.union([z.string(),Yd]);var Pl={css:z.string().optional(),coords:fv.optional(),x:z.union([z.number(),z.string()]).optional(),y:z.union([z.number(),z.string()]).optional()},pG={on:z.string().optional(),...Pl},uc={...Bt,effort:Nt.optional(),useSelector:z.boolean().optional(),force:z.boolean().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional()},bv={...uc,offset:fv.optional()};function ds({schema:e,descriptionKey:t,required:o=true}){return e.superRefine((n,r)=>{let a=[t in n?Object.entries(n).find(([s])=>s===t)?.[1]:void 0,"css"in n?n.css:void 0,"coords"in n?n.coords:void 0,"x"in n||"y"in n?true:void 0].filter(s=>s!==void 0).length;o&&a!==1&&r.addIssue({code:"custom",message:`Use exactly one target: ${t}, css, coords, or x/y.`}),!o&&a>1&&r.addIssue({code:"custom",message:`Use at most one target: ${t}, css, coords, or x/y.`}),("x"in n||"y"in n)&&(!("x"in n)||n.x===void 0||!("y"in n)||n.y===void 0)&&r.addIssue({code:"custom",message:"x and y must be provided together."});})}var nKe=ds({descriptionKey:"on",schema:z.strictObject({...pG,...bv,times:z.int().min(1).optional(),rightClick:z.boolean().optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),rKe=ds({descriptionKey:"on",schema:z.strictObject({...pG,...bv,rightClick:z.boolean().optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),iKe=ds({descriptionKey:"on",schema:z.strictObject({...pG,...bv,times:z.int().min(1).optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),moe=Tt({key:"click",simplified:z.string(),detailed:nKe}),poe=Tt({key:"doubleClick",simplified:z.string(),detailed:rKe}),hoe=Tt({key:"rightClick",simplified:z.string(),detailed:iKe}),aKe=ds({descriptionKey:"into",required:false,schema:z.strictObject({text:z.string(),into:z.string().optional(),...Pl,...bv,pressEnter:z.boolean().optional(),clear:z.union([z.literal("inputs"),z.literal("always"),z.literal("never"),z.boolean()]).optional(),delay:z.number().optional()})}),goe=Tt({key:"type",simplified:z.string(),detailed:aKe}),sKe=ds({descriptionKey:"into",required:false,schema:z.strictObject({text:z.string(),into:z.string().optional(),...Pl,...bv,pressEnter:z.boolean().optional()})}),foe=Tt({key:"fill",simplified:z.string(),detailed:sKe}),yoe=mr({key:"select",detailed:ds({descriptionKey:"from",schema:z.strictObject({from:z.string().optional(),...Pl,label:z.string().optional(),value:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),...uc})}).superRefine((e,t)=>{[e.label,e.value,e.index].filter(n=>n!==void 0).length!==1&&t.addIssue({code:"custom",message:"select requires exactly one of label, value, or index"});})}),boe=Tt({key:"hover",simplified:z.string(),detailed:ds({descriptionKey:"on",schema:z.strictObject({on:z.string().optional(),...Pl,...bv})})}),Soe=mr({key:"blur",detailed:ds({descriptionKey:"on",required:false,schema:z.strictObject({on:z.string().optional(),...Pl,...uc})})}),Toe=Tt({key:"focus",simplified:z.string(),detailed:ds({descriptionKey:"on",schema:z.strictObject({on:z.string().optional(),...Pl,...uc})})}),voe=mr({key:"dragAndDrop",detailed:z.strictObject({from:z.string().optional(),to:z.string().optional(),fromCss:z.string().optional(),toCss:z.string().optional(),fromCoords:fv.optional(),toCoords:fv.optional(),fromX:z.union([z.number(),z.string()]).optional(),fromY:z.union([z.number(),z.string()]).optional(),toX:z.union([z.number(),z.string()]).optional(),toY:z.union([z.number(),z.string()]).optional(),steps:z.number().optional(),hover:z.number().optional(),...uc}).superRefine((e,t)=>{let o=[e.from,e.fromCss,e.fromCoords,e.fromX!==void 0||e.fromY!==void 0?true:void 0].filter(r=>r!==void 0).length,n=[e.to,e.toCss,e.toCoords,e.toX!==void 0||e.toY!==void 0?true:void 0].filter(r=>r!==void 0).length;o!==1&&t.addIssue({code:"custom",message:"Use exactly one from target."}),n!==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."});})}),Aoe=z.union([z.strictObject({mouseDrag:fv}),z.strictObject({mouseDrag:ds({descriptionKey:"from",required:false,schema:z.strictObject({from:z.string().optional(),...Pl,delta:fv,steps:z.number().optional(),...uc})})})]),Eoe=Tt({key:"press",simplified:z.string(),detailed:z.strictObject({key:z.string(),repeat:z.number().optional(),delay:z.number().optional(),convertMeta:z.boolean().optional(),...Bt,effort:Nt.optional()})}),woe=Tt({key:"keyDown",simplified:z.string(),detailed:z.strictObject({key:z.string(),convertMeta:z.boolean().optional(),...Bt,effort:Nt.optional()})}),Roe=Tt({key:"keyUp",simplified:z.string(),detailed:z.strictObject({key:z.string(),convertMeta:z.boolean().optional(),...Bt,effort:Nt.optional()})}),yv=z.number().int().min(0).max(6e4).multipleOf(1e3),Coe=Tt({key:"navigate",simplified:z.string(),detailed:z.strictObject({url:z.string(),timeout:yv.optional(),...Bt,effort:Nt.optional()})}),Ioe=Tt({key:"newTab",simplified:z.string(),detailed:z.strictObject({url:z.string(),timeout:yv.optional(),...Bt,effort:Nt.optional()})}),xoe=Tt({key:"switchTab",simplified:z.union([z.number(),z.string()]),detailed:z.strictObject({substring:z.string().optional(),regex:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),timeout:yv.optional(),loadTimeout:yv.optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(n=>n!==void 0).length!==1&&t.addIssue({code:"custom",message:"switchTab requires exactly one of substring, regex, or index"});})}),_oe=mr({key:"closeTab",detailed:z.strictObject({substring:z.string().optional(),regex:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),timeout:yv.optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(n=>n!==void 0).length<=1||t.addIssue({code:"custom",message:"closeTab accepts at most one of substring, regex, or index"});})}),Ooe=mr({key:"goBack",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),Poe=mr({key:"goForward",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),koe=mr({key:"refresh",detailed:z.strictObject({timeout:yv.optional(),...Bt,effort:Nt.optional()})}),mb=z.enum(["goBack","goForward","refresh","paste","authSave","offline","online","blur","visualDiff","captcha","closeTab"]),Moe=Tt({key:"scrollUp",simplified:z.number().nonnegative(),detailed:ds({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Pl,...uc})})}),Loe=Tt({key:"scrollDown",simplified:z.number().nonnegative(),detailed:ds({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Pl,...uc})})}),Noe=Tt({key:"scrollLeft",simplified:z.number().nonnegative(),detailed:ds({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Pl,...uc})})}),Doe=Tt({key:"scrollRight",simplified:z.number().nonnegative(),detailed:ds({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Pl,...uc})})}),Foe=Tt({key:"wait",simplified:z.number(),detailed:z.strictObject({ms:z.number(),...Bt,effort:Nt.optional()})}),lKe=Tt({key:"assert",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),source:z.string().optional(),...Bt,effort:Nt.optional()})}),cKe=Tt({key:"assertVisually",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),source:z.string().optional(),...Bt,effort:Nt.optional()})}),nM=lKe,rM=cKe,Boe=Tt({key:"checkPageContains",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),iframe:z.string().optional(),...Bt,effort:Nt.optional()})}),Uoe=Tt({key:"checkPageDoesNotContain",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),iframe:z.string().optional(),...Bt,effort:Nt.optional()})}),hG=z.union([Boe,Uoe]),uKe=z.record(z.string(),z.unknown().optional()),iM=uKe.superRefine((e,t)=>{let o=Object.keys(e),n=o[0];if(o.length!==1||n===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=qs(n);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=ds({descriptionKey:"element",schema:z.looseObject({element:z.string().optional(),...Pl,...uc,timeout:z.number().optional(),name:z.string().optional(),value:z.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"]});}),joe=Tt({key:"extract",simplified:z.string(),detailed:z.strictObject({goal:z.string(),schema:zg.optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),...Bt,effort:Nt.optional()})}),zoe=Tt({key:"cookie",simplified:z.string(),detailed:z.strictObject({value:z.string(),...Bt,effort:Nt.optional()})}),Hoe=mr({key:"localStorage",detailed:z.strictObject({key:z.string(),value:z.string(),...Bt,effort:Nt.optional()})}),$oe=Tt({key:"request",simplified:z.string(),detailed:z.strictObject({url:z.string(),method:Op.optional(),headers:z.record(z.string(),z.string()).optional(),params:z.record(z.string(),z.string()).optional(),body:zg.optional(),contentType:z.enum(Zd).optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()})}),Goe=mr({key:"graphqlRequest",detailed:z.strictObject({url:z.string(),query:z.string(),variables:zg.optional(),headers:z.record(z.string(),z.string()).optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()})}),aM=Tt({key:"javascript",simplified:z.string(),detailed:z.strictObject({code:z.string(),environment:z.enum(["node","browser","NODE","BROWSER"]).optional(),fragment:z.boolean().optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()})}),Sv={substring:z.string().optional(),glob:z.string().optional(),regex:z.string().optional(),domain:z.string().optional()};function dKe(e){return [e.substring,e.glob,e.regex,e.domain].filter(t=>t!==void 0).length}function Tv(e){let t=dKe(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 Voe=mr({key:"header",detailed:z.strictObject({name:z.string(),value:z.string(),...Sv,method:z.string().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:false});})}),Woe=mr({key:"mock",detailed:z.strictObject({...Sv,method:z.string().optional(),responseGenerator:z.string(),fetchOriginalResponse:z.boolean().optional(),key:z.string().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),qoe=Tt({key:"removeRouteMock",simplified:z.string(),detailed:z.strictObject({key:z.string().optional(),...Bt,effort:Nt.optional()})}),Koe=Tt({key:"waitForUrl",simplified:z.string(),detailed:z.strictObject({...Sv,caseInsensitive:z.boolean().optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),Yoe=Tt({key:"waitForUrlNotToMatch",simplified:z.string(),detailed:z.strictObject({...Sv,caseInsensitive:z.boolean().optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),mKe=z.union([Koe,Yoe]),Joe=Tt({key:"dialog",simplified:z.enum(["ACCEPT","DISMISS"]),detailed:z.strictObject({action:z.enum(["ACCEPT","DISMISS"]),...Bt,effort:Nt.optional()})}),Xoe=Tt({key:"fileUpload",simplified:z.string(),detailed:z.strictObject({path:z.string(),name:z.string().optional(),...Bt,effort:Nt.optional()})}),Qoe=Tt({key:"copy",simplified:z.union([z.string(),z.boolean(),z.null()]),detailed:z.strictObject({value:z.union([z.string(),z.boolean(),z.null()]),...Bt,effort:Nt.optional()})}),Zoe=mr({key:"paste",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),ene=mr({key:"captcha",detailed:z.strictObject({...uc})}),pKe=z.strictObject({data:z.union([z.string(),Ql]),width:z.number(),height:z.number()}),tne=Tt({key:"visualDiff",simplified:z.string(),detailed:ds({descriptionKey:"on",required:false,schema:z.strictObject({on:z.string().optional(),...Pl,threshold:z.number().optional(),screenshot:pKe.optional(),...uc})})}),one=mr({key:"offline",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),nne=mr({key:"online",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),rne=mr({key:"registerRequestListener",detailed:z.strictObject({...Sv,key:z.string(),method:z.string().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),ine=Tt({key:"awaitListener",simplified:z.string(),detailed:z.strictObject({key:z.string(),timeout:z.number().optional(),...Bt,effort:Nt.optional()})}),ane=mr({key:"recordRequests",detailed:z.strictObject({...Sv,key:z.string(),method:z.string().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),sne=Tt({key:"getRecordedRequests",simplified:z.string(),detailed:z.strictObject({key:z.string(),...Bt,effort:Nt.optional()})}),lne=Tt({key:"authLoad",simplified:z.string(),detailed:z.strictObject({path:z.string(),...Bt,effort:Nt.optional()})}),cne=Tt({key:"authSave",simplified:z.string(),detailed:z.strictObject({path:z.string().optional(),...Bt,effort:Nt.optional()})});z.union([moe,poe,hoe,xoe,_oe,goe,foe,yoe,boe,Soe,Toe,voe,Aoe,Eoe,woe,Roe,Coe,Ioe,Ooe,Poe,koe,Moe,Loe,Noe,Doe,Foe,nM,rM,hG,joe,zoe,Hoe,$oe,Goe,aM,Voe,Woe,qoe,mKe,Joe,Xoe,Qoe,Zoe,ene,tne,one,nne,rne,ine,ane,sne,lne,cne,iM]);var une=new Map([["click",moe],["doubleClick",poe],["rightClick",hoe],["switchTab",xoe],["closeTab",_oe],["type",goe],["fill",foe],["select",yoe],["hover",boe],["blur",Soe],["focus",Toe],["dragAndDrop",voe],["mouseDrag",Aoe],["press",Eoe],["keyDown",woe],["keyUp",Roe],["navigate",Coe],["newTab",Ioe],["goBack",Ooe],["goForward",Poe],["refresh",koe],["scrollUp",Moe],["scrollDown",Loe],["scrollLeft",Noe],["scrollRight",Doe],["wait",Foe],["assert",nM],["assertVisually",rM],["checkPageContains",Boe],["checkPageDoesNotContain",Uoe],["extract",joe],["cookie",zoe],["localStorage",Hoe],["request",$oe],["graphqlRequest",Goe],["javascript",aM],["header",Voe],["mock",Woe],["removeRouteMock",qoe],["waitForUrl",Koe],["waitForUrlNotToMatch",Yoe],["dialog",Joe],["fileUpload",Xoe],["copy",Qoe],["paste",Zoe],["captcha",ene],["visualDiff",tne],["offline",one],["online",nne],["registerRequestListener",rne],["awaitListener",ine],["recordRequests",ane],["getRecordedRequests",sne],["authLoad",lne],["authSave",cne]]),gG=Object.freeze([...une.keys()]),hKe=[...gG,...oM.keys()],ym=z.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 o=Object.keys(e),n=o[0];if(o.length!==1||n===void 0){t.addIssue({code:"custom",message:"Steps must have exactly one action key."});return}let r=une.get(n)??(qs(n)?iM:void 0);if(!r){let a=uoe(n,hKe);t.addIssue({code:"custom",message:`Unsupported step type '${n}'.${a?` Did you mean '${a}'?`:""} See https://momentic.ai/docs/reference/commands for every step type.`});return}let i=r.safeParse(e);if(!i.success){let a=gKe(i.error.issues,n);a.length>0&&dne(t,a);}});function gKe(e,t){return fKe(e).filter(o=>!yKe(o,t))}function dne(e,t){for(let o of t){if(o.code==="invalid_union"){dne(e,fG(o));continue}e.addIssue({...o});}}function fKe(e){let t=[];for(let o of e){if(o.code==="invalid_union"){t.push(...fG(o));continue}t.push(o);}return t}function yKe(e,t){return e.code!=="unrecognized_keys"?false:t===void 0?e.path.length===0:e.path.length===1&&e.path[0]===t}function fG(e){let t=e.errors[0]??[],o=mG(t);for(let n of e.errors.slice(1)){let r=mG(n);r>o&&(t=n,o=r);}return t}function mG(e){return e.reduce((t,o)=>{let n=o.code==="invalid_union"?mG(fG(o)):0;return t+o.path.length+n},0)}var mne=z.strictObject({string:z.string()}),bKe=z.strictObject({javascript:z.string()}),pne=z.union([mne,bKe]),SKe=z.union([z.strictObject({name:z.string(),required:z.boolean().optional(),default:mne.optional()}),z.strictObject({name:z.string(),required:z.boolean().optional(),defaultValue:z.string()})]),hne=SKe.array(),TKe=z.strictObject({name:z.string(),default:pne.optional(),enum:z.array(z.string()).optional()}),gne=TKe.array(),GC=z.union([pne,z.string()]),fne=z.record(z.string(),GC);var vKe=z.preprocess(e=>typeof e=="number"?String(e):e,yR),sM=z.looseObject({goal:z.string(),version:vKe.optional(),cache:z.literal(false).optional(),...Bt}),AKe=z.union([z.strictObject({act:z.string()}),z.strictObject({act:sM})]),yG=z.looseObject({path:z.string(),inputs:z.record(z.string(),GC).optional(),...Bt}),EKe=z.union([z.strictObject({module:z.string()}),z.strictObject({module:yG})]),Yp=z.union([nM,rM,hG,aM,iM]),wKe=new Set(["then","effort",...gv]),RKe=z.looseObject({then:z.lazy(()=>od.array()),effort:Nt.optional(),...Bt}).superRefine((e,t)=>{Object.entries(e).filter(([n,r])=>!wKe.has(n)&&Yp.safeParse({[n]:r}).success).length!==1&&t.addIssue({code:"custom",message:"Conditional steps require exactly one assertion condition at the top level."});}),CKe=z.strictObject({if:RKe}),IKe=new Set(["do","maxIterations","effort",...gv]),xKe=z.looseObject({do:z.lazy(()=>od.array()),maxIterations:z.number().int().positive().optional(),effort:Nt.optional(),...Bt}).superRefine((e,t)=>{let o=Object.entries(e).filter(([n,r])=>!IKe.has(n)&&Yp.safeParse({[n]:r}).success).length;if(o>1){t.addIssue({code:"custom",message:"While loops accept at most one condition at the top level."});return}o===0&&e.maxIterations===void 0&&t.addIssue({code:"custom",message:"While loops require a condition or a maximum number of iterations."});}),_Ke=z.strictObject({while:xKe}),od=z.lazy(()=>z.union([mb,hv,AKe,EKe,CKe,_Ke,ym]));z.object({before:od.array().optional(),steps:od.array(),after:od.array().optional()});var OKe=z.union([jp,z.string().refine(e=>{let t=e.match(/^\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*$/);if(!t)return false;let[,o,n]=t;return jp.safeParse({width:Number(o),height:Number(n)}).success},"Viewport must be two numeric values, e.g. 1920, 1080")]),PKe=Us.omit({viewport:true}).extend({viewport:OKe.optional()}),bG=z.object({id:Lr,version:z.string().optional(),url:BP.optional(),description:z.string().optional(),retries:z.number().optional(),defaultEnv:z.string().optional(),parameters:hne.optional(),outputs:yk.optional(),disabled:z.boolean().optional(),labels:z.array(z.string()).optional(),runAssertions:bk.array().optional()}).extend(PKe.shape),kKe=z.looseObject({fileType:z.literal(ze.TEST_V2)}).extend(bG.shape).extend({before:od.array().optional(),steps:od.array(),after:od.array().optional()}),Gg=kKe.superRefine(LKe),MKe={beforeSteps:"before",afterSteps:"after"};function LKe(e,t){for(let[o,n]of Object.entries(MKe))o in e&&t.addIssue({code:"custom",message:`v2 tests must use ${n}, not ${o}`,path:[o]});}var NKe=z.array(z.string()),DKe=z.union([z.string(),z.record(z.string(),z.unknown().optional())]),lM=kr.omit({moduleId:true,name:true,parameters:true,defaultParameters:true,parameterEnums:true}).extend({id:Lr,version:z.string().optional(),name:z.string().optional(),parameters:z.union([gne,NKe]).optional(),defaultParameters:z.record(z.string(),z.string()).optional(),parameterEnums:z.record(z.string(),z.array(z.string())).optional()}),cM=z.looseObject(lM.extend({fileType:z.literal(ze.MODULE_V2),steps:DKe.array().optional()}).shape).superRefine(bne),uM=z.looseObject(lM.extend({fileType:z.literal(ze.MODULE_V2),steps:od.array().optional()}).shape).superRefine(bne);function yne(e){return e.steps??[]}function bne(e,t){"main"in e&&t.addIssue({code:"custom",message:"v2 modules must use steps, not main",path:["main"]});}var SG=(o=>(o.TEST="TEST",o.MODULE="MODULE",o))(SG||{}),FKe=z.enum(SG),Sne=z.object({orgId:z.string(),entityType:FKe,entityId:z.string()}),TG=Sne.extend({entityType:z.literal("TEST"),stepLists:qu}),vG=Sne.extend({entityType:z.literal("MODULE"),steps:Bo.array()});z.discriminatedUnion("entityType",[TG,vG]);var Tne=(n=>(n.WEB="web",n.ANDROID="android",n.IOS="ios",n))(Tne||{}),AG=z.nativeEnum(Tne);var vne=z.object({entity_type:z.string(),value:z.string(),schema_version:z.string().optional()}),Ane=zR(vne),Ene=vne.extend({cache_key:z.string()});function VC({entityType:e,entityId:t}){return `${e}:${t}`}var hb=z.string();var wne='Coordinates must be "x, y" pixel values, e.g. "100, 200"',xne=z.union([Yd,z.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,wne)],{error:wne}),Rne='Percent must be a number or a percent string, e.g. 90 or "90%"',_ne=z.union([z.number(),z.string().regex(/^-?\d+(?:\.\d+)?%$/,Rne)],{error:Rne}).transform(e=>typeof e=="number"?e:Number(e.slice(0,-1))).pipe(z.number().min(0,{message:"Percent must be >= 0"}).max(100,{message:"Percent must be <= 100"})),BKe=z.strictObject({x:z.number(),y:z.number(),delta:z.number()}),One=z.union([z.string(),BKe]),Pn={...Bt,DANGEROUS_FORCE_DYNAMIC:z.boolean().optional()},UKe=["home","power","back","app_switcher","search","volume_up","volume_down","volume_mute"],jKe=["enter","backspace","close_keyboard"],Cne=["airplane_mode","data","wifi","location"],Ine=["portrait","landscape"],zKe=z.strictObject({on:hb.optional(),longPress:z.boolean().optional(),longPressDuration:z.number().optional(),iterations:z.number().optional(),tapDelay:z.number().optional(),offset:xne.optional(),...Pn}),Pne=Tt({key:"tap",simplified:hb,detailed:zKe}),HKe=z.strictObject({text:z.string(),into:hb.optional(),clearContent:z.boolean().optional(),forceClearContent:z.boolean().optional(),delay:z.number().optional(),waitForKeyboardSettle:z.boolean().optional(),replaceStrategy:z.nativeEnum(fC).optional(),keyPressDelay:z.number().optional(),...Pn}),kne=Tt({key:"type",simplified:z.string(),detailed:HKe}),Mne=z.enum(UKe),$Ke=z.strictObject({key:Mne,longPress:z.boolean().optional(),...Pn}),Lne=Tt({key:"press",simplified:Mne,detailed:$Ke}),Nne=z.enum(jKe),GKe=z.strictObject({key:Nne,repeat:z.number().optional(),delay:z.number().optional(),keyPressDelay:z.number().optional(),...Pn}),Dne=Tt({key:"pressKey",simplified:Nne,detailed:GKe}),VKe=z.strictObject({package:z.string(),activity:z.string().optional(),intentExtras:z.string().optional(),...Pn}),Fne=Tt({key:"openApp",simplified:z.string(),detailed:VKe}),Bne=mr({key:"killApp",detailed:z.strictObject(Pn)}),Une=mr({key:"openNotifications",detailed:z.strictObject(Pn)}),jne=z.enum(["up","down","left","right"]),WKe=z.strictObject({direction:jne,in:One.optional(),viewportPercent:_ne.optional(),duration:z.number().optional(),offset:xne.optional(),...Pn}),zne=Tt({key:"swipe",simplified:jne,detailed:WKe}),qKe=z.enum(["up","down"]),KKe=z.strictObject({on:hb,direction:qKe.optional(),in:One.optional(),scrollStepPercent:_ne.optional(),maxScrollAttempts:z.number().optional(),...Pn}),Hne=Tt({key:"scrollTo",simplified:z.string(),detailed:KKe}),EG=Tt({key:"assert",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),...Pn})}),wG=Tt({key:"assertVisually",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),...Pn})}),$ne=Tt({key:"extract",simplified:z.string(),detailed:z.strictObject({goal:z.string(),schema:zg.optional(),...Pn})}),Gne=Tt({key:"checkScreenContains",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),...Pn})}),Vne=Tt({key:"checkScreenDoesNotContain",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),...Pn})}),Wne=z.union([Gne,Vne]),YKe=z.record(z.string(),z.unknown().optional()),RG=YKe.superRefine((e,t)=>{let o=Object.keys(e),n=o[0];if(o.length!==1||n===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=qs(n);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.looseObject({on:hb.optional(),timeout:z.number().optional(),name:z.string().optional(),value:z.string().optional(),...Pn}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}i.data.on===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a target via 'on'`,path:[r.alias,"on"]}),r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),JKe=z.strictObject({from:hb,to:hb,hoverDuration:z.number().optional(),dragDuration:z.number().optional(),...Pn}),qne=mr({key:"dragAndDrop",detailed:JKe}),CG=Tt({key:"javascript",simplified:z.string(),detailed:z.strictObject({code:z.string(),timeout:z.number().optional(),...Pn})}),Kne=Tt({key:"request",simplified:z.string(),detailed:z.strictObject({url:z.string(),method:Op.optional(),headers:z.record(z.string(),z.string()).optional(),params:z.record(z.string(),z.string()).optional(),body:z.string().optional(),bodyType:z.nativeEnum(Zd).optional(),timeout:z.number().optional(),...Pn})}),Yne=Tt({key:"wait",simplified:z.number(),detailed:z.strictObject({ms:z.number(),...Pn})}),Jne=Tt({key:"visualDiff",simplified:z.string(),detailed:z.strictObject({path:z.string(),threshold:z.number().min(0).max(1).optional(),...Pn})}),Xne=mr({key:"addFile",detailed:z.strictObject({path:z.string(),location:z.string(),...Pn})}),Qne=Tt({key:"setCamera",simplified:z.string(),detailed:z.strictObject({path:z.string(),loop:z.boolean().optional(),playAudio:z.boolean().optional(),...Pn})}),Zne=mr({key:"clearCamera",detailed:z.strictObject(Pn)}),ere=Tt({key:"setMicrophone",simplified:z.string(),detailed:z.strictObject({path:z.string(),once:z.boolean().optional(),...Pn})}),tre=mr({key:"clearMicrophone",detailed:z.strictObject(Pn)}),ore=Tt({key:"installApp",simplified:z.string(),detailed:z.strictObject({path:z.string(),...Pn})}),nre=Tt({key:"uninstallApp",simplified:z.string(),detailed:z.strictObject({package:z.string(),...Pn})}),rre=Tt({key:"toggleSettings",simplified:z.enum(Cne),detailed:z.strictObject({setting:z.enum(Cne),...Pn})}),ire=Tt({key:"rotate",simplified:z.enum(Ine),detailed:z.strictObject({orientation:z.enum(Ine),...Pn})}),are=Tt({key:"adb",simplified:z.string(),detailed:z.strictObject({command:z.string(),args:z.string().optional(),...Pn})}),sre=mr({key:"appium",detailed:z.strictObject({script:z.string(),args:z.string().optional(),...Pn})}),lre=mr({key:"debugState",detailed:z.strictObject(Pn)}),cre=z.enum(["killApp","openNotifications","debugState","clearCamera","clearMicrophone"]);z.union([Pne,kne,Lne,Dne,Fne,Bne,Une,zne,Hne,EG,wG,$ne,Wne,qne,CG,Kne,Yne,Jne,Xne,Qne,Zne,ere,tre,ore,nre,rre,ire,are,sre,lre,RG]);var ure=new Map([["tap",Pne],["type",kne],["press",Lne],["pressKey",Dne],["openApp",Fne],["killApp",Bne],["openNotifications",Une],["swipe",zne],["scrollTo",Hne],["assert",EG],["assertVisually",wG],["extract",$ne],["checkScreenContains",Gne],["checkScreenDoesNotContain",Vne],["dragAndDrop",qne],["javascript",CG],["request",Kne],["wait",Yne],["visualDiff",Jne],["addFile",Xne],["setCamera",Qne],["clearCamera",Zne],["setMicrophone",ere],["clearMicrophone",tre],["installApp",ore],["uninstallApp",nre],["toggleSettings",rre],["rotate",ire],["adb",are],["appium",sre],["debugState",lre]]);Object.freeze([...ure.keys()]);var dre=z.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 o=Object.keys(e),n=o[0];if(o.length!==1||n===void 0){t.addIssue({code:"custom",message:"v2 mobile commands must have exactly one action key."});return}let r=ure.get(n)??(qs(n)?RG:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported v2 mobile command '${n}'.`});return}let i=r.safeParse(e);if(!i.success)for(let a of i.error.issues)t.addIssue({...a});}),IG=z.union([EG,wG,Wne,CG,RG]);var XKe=z.preprocess(e=>typeof e=="number"?String(e):e,O1),QKe=z.looseObject({goal:z.string(),version:XKe.optional(),cache:z.literal(false).optional(),precondition:z.string().optional(),postcondition:z.string().optional(),...Bt}),ZKe=z.union([z.strictObject({act:z.string()}),z.strictObject({act:QKe})]),eYe=z.looseObject({path:z.string(),inputs:z.record(z.string(),GC).optional(),...Bt}),tYe=z.union([z.strictObject({module:z.string()}),z.strictObject({module:eYe})]),oYe=new Set(["then",...gv]),nYe=z.looseObject({then:z.lazy(()=>nd.array()),...Bt}).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(([n,r])=>!oYe.has(n)&&IG.safeParse({[n]:r}).success).length!==1&&t.addIssue({code:"custom",message:"v2 mobile conditional steps require exactly one assertion condition at the top level."});}),rYe=z.strictObject({if:nYe}),iYe=new Set(["do","maxIterations",...gv]),aYe=z.looseObject({do:z.lazy(()=>nd.array()),maxIterations:z.number().int().positive().optional(),...Bt}).superRefine((e,t)=>{let o=Object.entries(e).filter(([n,r])=>!iYe.has(n)&&IG.safeParse({[n]:r}).success).length;if(o>1){t.addIssue({code:"custom",message:"While loops accept at most one condition at the top level."});return}o===0&&e.maxIterations===void 0&&t.addIssue({code:"custom",message:"While loops require a condition or a maximum number of iterations."});}),sYe=z.strictObject({while:aYe}),nd=z.lazy(()=>z.union([cre,hv,ZKe,tYe,rYe,sYe,dre]));z.object({before:nd.array().optional(),steps:nd.array(),after:nd.array().optional()});var lYe=z.literal("android"),cYe=z.literal("ios");function dM(e){if(typeof e!="object"||e===null)return e;let t=e;if(typeof t.platform!="string")return e;let o=t.platform.toLowerCase();return o===t.platform?e:{...t,platform:o}}var mre=cv.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z.string().optional(),platform:lYe,...xC.shape}),pre=uv.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z.string().optional(),platform:cYe,...xC.shape}),uYe=z.discriminatedUnion("platform",[mre,pre]),hre=z.preprocess(dM,uYe),gre={before:nd.array().optional(),steps:nd.array(),after:nd.array().optional()},fre=z.looseObject({fileType:z.literal(ze.MOBILE_TEST_V2)}).extend(mre.shape).extend(gre);z.preprocess(dM,fre);var yre=z.looseObject({fileType:z.literal(ze.MOBILE_TEST_V2)}).extend(pre.shape).extend(gre);z.preprocess(dM,yre);var dYe=z.discriminatedUnion("platform",[fre,yre]);z.preprocess(dM,dYe);var mYe=z.preprocess(e=>typeof e=="string"?e.toLowerCase():e,z.enum(lk).optional().default("android")),mM=Bk.omit({moduleId:true,name:true,schemaVersion:true,platform:true}).extend({id:Lr,name:z.string().optional(),version:z.string().optional(),platform:mYe});z.looseObject(mM.extend({fileType:z.literal(ze.MOBILE_MODULE_V2),steps:z.array(z.record(z.string(),z.unknown().optional())).optional()}).shape);z.looseObject(mM.extend({fileType:z.literal(ze.MOBILE_MODULE_V2),steps:nd.array().optional()}).shape);var pM="x-momentic-cli-version",Sre="x-momentic-client-mode",hM="x-momentic-runner",Tre="x-momentic-cli-type",gM="x-momentic-logger-tags",xG="x-momentic-effective-ai-effort",pYe="x-momentic-main-branch-name",hYe="x-momentic-branch-name",gYe="x-momentic-commit-timestamp",fYe="x-momentic-last-commit-on-main",yYe="x-momentic-last-commit-on-main-timestamp",bYe="x-momentic-merged-branch-name",vre="x-momentic-session-id",fM=529,Are="x-momentic-parent-trace-id";_.object({error:_.boolean(),reason:_.string(),message:_.string()});_i.merge(s1);var Ere=kP;_i.merge(s1);_i.merge(GZ).extend({useConsensus:_.boolean().optional(),attemptNumber:_.number().optional()});var _G=GQ;_i.merge(VZ);var wre=L9;_i.merge(jZ);var Rre=ak;_i.merge(m9);_i.merge(zZ);var Cre=P9;_i.merge(HZ);_i.merge($Z);_i.merge(YZ);_i.merge(JZ);_i.merge(XZ);_.object({testPaths:_.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:_.string().optional(),all:_.boolean().optional(),urlOverride:_.string().optional(),customHeaders:_.record(_.string(),_.string()).optional(),testInputMatrix:_.record(_.string(),_.string()).array().optional()});var Ire=_.object({queuedTests:_.unknown().optional().array(),runIds:_.guid().array(),runGroupId:_.string().optional()});_.string().array();_.union([_.object({paths:_.string().array().describe("Export specific test paths or folder paths (e.g. todo-test, auth/onboarding)"),all:_.boolean().describe("run all tests").optional()}),_.object({path:_.string().describe("deprecated; present for backcompat")})]);var SYe=_.object({tests:_.record(_.string().describe("Test name (keys correspond to entries in `tests`)"),_.string().describe("Slash-separated folder name path that the test lives in (e.g. 'Auth/Login'). Top-level entities are omitted.")),modules:_.record(_.string().describe("Module name (keys correspond to entries in `modules`)"),_.string().describe("Slash-separated folder name path that the module lives in."))}),xre=_.object({tests:_.record(_.string().describe("Test name"),_.string().describe("Test YAML")),modules:_.record(_.string().describe("Module name"),_.string().describe("Module YAML")),folderPaths:SYe.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.")}),TYe=_.object({test:_.string().describe("test YAML"),modules:_.record(_.string().describe("moduleId"),_.string().describe("module YAML"))});TYe.array();_.object({testId:_.string(),schemaVersion:_.string()}).merge(Mp);function yM(e){let{gitMainBranch:t,gitBranchName:o,gitCommitTimestamp:n,lastCommitOnMainSha:r,lastCommitOnMainTimestamp:i}=e,a={};return t&&(a[pYe]=encodeURIComponent(t)),o&&(a[hYe]=encodeURIComponent(o)),n&&(a[gYe]=n.toISOString()),r&&(a[fYe]=encodeURIComponent(r)),i&&(a[yYe]=i.toISOString()),e.mergedGitBranchName&&(a[bYe]=encodeURIComponent(e.mergedGitBranchName)),a}_.object({entries:_.array(f9)});_.object({platform:AG.optional(),entries:_.array(Ane)});_.object({testId:_.string(),environment:_.string().optional(),platform:AG.optional()});_.object({testId:_.string(),key:_.string(),environment:_.string().optional()});function _re(e){return _.record(_.string(),_.unknown().optional()).transform(t=>{let o={};for(let[n,r]of Object.entries(t)){let i=e.safeParse(r);i.success&&(o[n]=i.data);}return o})}var Ore=_re(y9),Pre=Ene.array();function bre(e){return _re(HR(e))}var kre={ANDROID:e=>bre(Hk).parse(e),IOS:e=>bre($k).parse(e)},vYe=_.object({id:_.string(),completionType:_.string(),description:_.string().optional(),thoughts:_.string(),result:_.string(),sessionType:_.string(),timeCreated:_.string().optional(),citations:_.array(Kn).optional()}),AYe=_.object({id:_.string(),assertion:_.string().optional(),result:_.string(),thoughts:_.string(),sessionType:_.string(),timeCreated:_.string().optional(),citations:_.array(Kn).optional()});_.object({completionType:_.string(),traceIds:_.string().array()});var OG=_.union([vYe,AYe]).array(),Mre=_.object({trigger:_.nativeEnum(ic),status:_.nativeEnum(ho),startedAt:_.coerce.date().optional(),gitCommitSha:_.string().optional(),gitCommitShaShort:_.string().optional(),gitCommitTimestamp:_.coerce.date().optional(),gitBranchName:_.string().optional(),gitOriginUrl:_.string().optional(),gitCommitMessage:_.string().optional(),gitCommitAuthorName:_.string().optional(),projectName:_.string().optional(),relativeProjectDir:_.string().optional(),githubRepository:_.string().optional(),gitlabProjectPath:_.string().optional(),pipelineId:_.string().optional(),cliVersion:_.string().optional()});_.object({id:_.string()});var Lre=_.object({status:_.nativeEnum(ho),updatedAt:_.coerce.date().optional(),finishedAt:_.coerce.date().optional()});_.object({summary:Zy,githubRepository:_.string().optional(),gitBranchName:_.string().optional()});var EYe=_.object({runId:_.string(),healStatus:Qy,healDetails:Pg.optional()});_.object({updates:EYe.array()});var Nre=_.object({stepsSnapshot:_.array(_.record(_.string(),_.unknown().optional())).optional(),beforeStepsSnapshot:_.array(_.record(_.string(),_.unknown().optional())).optional(),afterStepsSnapshot:_.array(_.record(_.string(),_.unknown().optional())).optional(),runGroupId:_.string().optional(),testId:_.string(),testName:_.string(),resolvedBaseUrl:_.string().optional(),environmentName:_.string().optional(),labels:_.array(_.string()).optional(),cliVersion:_.string().optional(),trigger:_.nativeEnum(ic),schemaVersion:_.string().optional(),section:_.nativeEnum(Sk).optional(),resolvedInputs:_.record(_.string(),_.string()).optional(),quarantined:_.boolean().optional().default(false),quarantinedReason:_.string().optional(),aiSettings:_l.optional()});_.object({id:_.string()});var wYe=r1.pick({id:true,status:true,healStatus:true,healDetails:true,testName:true,testId:true,test:true,failureReason:true,failureDetails:true}),Dre=wYe.array(),Fre=r1.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,runAssertionResults:true}).partial();_.object({id:_.string()});var bM=_.object({run:js.omit({runAttempts:true}),attemptZipUrls:_.array(_.string().url().nullish())}),Bre=_.object({status:_.nativeEnum(ho),finishedAt:_.coerce.date().optional(),schemaVersion:_.string().optional().default("1.0.19"),results:_.record(_.string(),_.unknown().optional()).array().optional(),beforeResults:_.record(_.string(),_.unknown().optional()).array().optional(),afterResults:_.record(_.string(),_.unknown().optional()).array().optional()});_.object({screenshot:_.string(),contentType:_.enum(["image/jpeg","image/png"]).optional()});_.object({id:_.string(),screenshot:_.string(),contentType:_.enum(["image/jpeg","image/png"])});var Ure=_.object({key:_.string()}),jre=_.object({orgId:_.string(),userId:_.string(),email:_.string().optional(),name:_.string().optional(),pylonEmailHash:_.string().optional(),selfServe:_.boolean().optional(),heardAboutAnswered:_.boolean().optional(),needsWorkspaceName:_.boolean().optional(),orgName:_.string().optional()}),zre=_.object({blocked:_.boolean()}),Hre=_.array(X8),$re=_.record(_.string(),_.union([_.string(),_.boolean()]));_.object({workosAccessToken:_.string().min(1),organizationId:_.string().optional(),clientName:_.string().min(1).max(80).optional()});var Gre=_.object({apiKey:_.string(),apiKeyName:_.string(),organizationId:_.string(),user:_.object({id:_.string(),email:_.string().optional()}),selfServe:_.boolean().optional()}),Vre=_.object({error:_.literal("multiple_organizations"),organizations:_.array(_.object({id:_.string(),name:_.string()}))}),RYe=80,CYe=_.string().trim().min(1).max(RYe);_.object({name:CYe});var IYe=["web","ios","android"];_.object({platforms:_.array(_.enum(IYe)),packageManager:_.enum(["npm","pnpm","yarn","bun"]),wizardVersion:_.string().min(1).max(40),cliVersions:_.object({momentic:_.string().max(40).optional(),momenticMobile:_.string().max(40).optional()}).optional(),firstRunIds:_.array(_.guid()).max(10).optional(),heardAboutSource:t1.optional(),heardAboutSourceOtherText:_.string().max(200).optional()});_.object({ok:_.literal(true)});_.object({paths:_.string().array(),env:_.string().optional(),urlOverride:_.string().optional(),customHeaders:_.record(_.string(),_.string()).optional()});var Wre=_.object({suiteRunIds:_.string().array(),runGroupIds:_.string().array()});_.object({suiteRunIds:_.string().array()});NZ.array();_.object({runGroupIds:_.string().array()});var SM=_.object({uploadUrl:_.string()});_i.merge(WZ);_i.merge(KZ);_i.merge(qZ);var TM=_.object({runId:_.string().optional().default(""),runGroupId:_.string().optional().default(""),envName:_.string().optional().default(""),platform:_.string().optional().default(""),testId:_.string().optional().default(""),testName:_.string().optional().default(""),suiteId:_.string().optional().default(""),suiteName:_.string().optional().default(""),isInteractive:_.boolean().optional().default(false),runner:_.nativeEnum(us).optional(),aiFeature:_.nativeEnum(Ug).optional(),cached:_.boolean().optional(),outcome:_.nativeEnum(av).optional(),hasFixedTest:_.boolean().optional(),hasCannotFixTest:_.boolean().optional(),hasNoFixNeededTest:_.boolean().optional(),result:_.enum(["success","failure"]).optional(),creditsUsed:_.number().optional(),stepsExecuted:_.number().optional(),tokensUsed:_.number().optional(),aiCostUsd:_.number().nonnegative().optional(),[vee]:_.string().optional(),agentInvocationId:_.string().optional(),moRuntimeSecondsUsed:_.number().nonnegative().optional(),moSpend:_.number().nonnegative().optional(),hostedBrowserSecondsUsed:_.number().optional(),sessionMinutesUsed:_.number().nonnegative().optional(),labels:_.array(_.string()).optional()});_.object({orgId:_.string(),runId:_.string().optional(),testId:_.string().optional(),isInteractive:_.boolean().optional(),runner:_.nativeEnum(us).optional()});var xYe=_.object({transactionId:_.string(),timestamp:_.string(),event:_.nativeEnum(lb),properties:TM});xYe.array();var qre=eoe.omit({steps:true}).extend({steps:_.array(_.record(_.string(),_.unknown().optional())).describe("unparsed ResolvedStep[]")});_.object({limit:_.number().min(1).max(10).optional(),page:_.number().min(1).optional(),start:br.optional(),end:br.optional(),gitBranchName:_.string().optional(),status:_.nativeEnum(ho).optional()});var Kre=EZ.array(),Yre=js.array(),WC=Hg.extend({executionType:Hp.array().min(1).optional(),testId:Lr.optional(),gitBranchName:_.string().optional(),gitCommitSha:_.string().optional(),status:_.nativeEnum(ho).optional(),label:_.string().array().optional(),start:br.optional(),end:br.optional(),quarantined:_.boolean().optional(),recovered:_.boolean().optional(),failureCategory:_.string().min(1).array().min(1).optional().describe("Effective built-in or custom failure category IDs. Manual classifications override automated classifications."),minAttempts:_.number().int().min(2).optional().describe("Minimum total attempt count, including the first attempt."),includeFailureDetails:_.boolean().optional(),skipRetentionFilter:_.boolean().optional()});WC.extend({orgId:_.string().optional(),testId:Xi(Lr),status:Xi(_.nativeEnum(ho)),gitBranchName:Xi(_.string()),label:Xi(_.string()),testName:_.string().optional(),trigger:Xi(_.nativeEnum(ic)),executionType:Xi(Hp),cliVersion:Xi(_.string()),githubRepository:Xi(_.string()),gitlabProjectPath:Xi(_.string()),environment:Xi(_.string()),directory:Xi(_.string()),failureCategory:Xi(_.string()),exclude:Xi(_.string()),healed:_.boolean().optional()});var _Ye=js.omit({test:true}),Jre=iG.extend({runs:_Ye.array(),executionTypeFilterApplied:_.boolean().optional()});_.object({applied:_.boolean().optional(),appliedAt:_.coerce.date().optional()});var Xre=SM.extend({id:_.string()}),OYe=_.object({resultType:_.literal("run").optional().default("run"),runGroupId:_.guid().optional(),persist:_.boolean().optional()}),PYe=_.object({resultType:_.literal("explore"),exploreRunId:_.guid(),persist:_.boolean().optional()});_.discriminatedUnion("resultType",[OYe,PYe]);var Qre=_.object({runGroupId:_.guid()}),kYe=_.object({status:Qy,runId:_.string(),rootCause:_.string().nullable().optional(),solution:_.string().nullable().optional(),verificationNotes:_.string().nullable().optional(),markedAt:_.string()}),Zre=_.object({quarantined:_.object({testId:Lr,quarantinedAt:_.coerce.date(),quarantinedBy:_.string().optional(),quarantinedReason:_.string(),verdict:kYe.nullish().default(null)}).array()}),PG=Hg.extend({limit:Hg.shape.limit.describe("Max number of quarantined tests to return per page."),page:Hg.shape.page.describe("Page number for pagination (1-based)."),quarantinedAtStart:_.string().pipe(_.coerce.date()).optional().describe("Include tests quarantined at or after this timestamp."),quarantinedAtEnd:_.string().pipe(_.coerce.date()).optional().describe("Include tests quarantined before this timestamp.")}),MYe=_.object({id:_.string(),status:_.literal("FAILED"),startedAt:br,finishedAt:br,failureReason:_.string().nullish(),healStatus:Qy,healDetails:Pg.nullish()}),eie=iG.extend({quarantinedTests:_.array(_.object({testId:Lr,testName:_.string().nullish(),quarantinedAt:br,quarantineReason:_.string(),latestFailedRun:MYe.nullable()}))}),tie=_.object({gitLocalUsername:_.string().optional(),gitLocalEmail:_.string().optional(),gitLocalName:_.string().optional()});_.object({testId:Lr,testName:_.string().optional(),reason:_.string()}).merge(tie);_.object({testName:_.string().optional(),reason:_.string().optional()}).merge(tie);_i.merge(uee);_i.merge(dee);_i.merge(mee);_.object({apkToInstall:_.object({channel:_.string(),tag:_.string().optional()}).optional(),hostname:_.string().optional(),region:G1.optional(),jurisdiction:IC.optional(),osVersion:_.nativeEnum(lv).optional(),sessionId:_.string().optional(),runId:_.string().optional(),testId:_.string().optional(),playwrightVersion:Iee.optional()});var oie=_.object({name:_.string(),apiUrl:_.string(),webRtcUrl:_.string(),adbUrl:_.string(),token:_.string(),apkDownloadUrl:_.string().optional(),playwrightServerUrl:_.string().optional(),region:_.string().optional(),resolvedTag:_.string().optional(),sessionExpiresAt:_.number().optional()});_.object({appToInstall:_.object({channel:_.string(),tag:_.string().optional()}).optional(),hostname:_.string().optional(),region:G1.optional(),jurisdiction:IC.optional(),osVersion:_.nativeEnum(Vk).optional(),sessionId:_.string().optional(),runId:_.string().optional(),testId:_.string().optional(),installAppOnClient:_.boolean().optional()});var nie=_.object({id:_.string(),apiUrl:_.string(),webRtcUrl:_.string(),wdaUrl:_.string(),token:_.string(),appDownloadUrl:_.string().optional(),appMd5:_.string().optional(),region:_.string().optional(),resolvedTag:_.string().optional(),sessionExpiresAt:_.number().optional()});_.object({channel:_.string().trim().min(1,"channel must be a non-empty string"),tag:_.string().trim().min(1,"tag must be a non-empty string").refine(e=>e.toLowerCase()!==GR,{message:`"${GR}" is a reserved tag and cannot be used when uploading an asset.`}).optional(),alias:_.string().trim().min(1,"alias must be a non-empty string").refine(e=>e.toLowerCase()!==GR,{message:`"${GR}" is a reserved alias and cannot be assigned when uploading an asset.`}).optional(),md5:_.string()});var rie=_.object({id:_.string(),tag:_.string().optional(),alias:_.string().optional(),uploadUrl:_.string().optional(),downloadUrl:_.string(),md5:_.string().optional()}),LYe=_.object({channel:_.string(),tag:_.string(),md5:_.string(),platform:_.nativeEnum(Kc).default("ANDROID"),createdAt:_.number().describe("Unix timestamp in milliseconds")}),NYe=_.object({channel:_.string(),alias:_.string(),platform:_.nativeEnum(Kc).default("ANDROID"),tag:_.string()}),iie=_.object({assets:_.array(LYe),aliases:_.array(NYe).default([])}),aie=_.object({downloadUrl:_.string()}),vM=(o=>(o.PLAYWRIGHT="PLAYWRIGHT",o.CDP="CDP",o))(vM||{}),DYe=_.nativeEnum(vM),sie=_.string().trim().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,79}$/);_.object({access:sie.optional(),envName:_.string().optional(),moSessionId:_.string().min(1).max(128).optional(),runAttemptId:_.guid().optional(),runGroupId:_.guid().optional(),testId:_.string().optional(),testName:_.string().optional(),runId:_.guid().optional(),attemptedProviders:_.array(Zk).optional(),localhostTunnel:_.boolean().optional()});var FYe=_.object({access:sie.optional(),allocationRequestId:_.guid(),browserFleetRegion:HC.optional(),envName:_.string().optional(),runAttemptId:_.guid(),runGroupId:_.guid().optional(),runId:_.guid(),testId:_.string().min(1).max(128),testName:_.string().optional()});FYe.extend({attemptedProviders:_.array(Zk).max(Object.values(zC).length).default([])}).strict();var BYe=_.discriminatedUnion("mode",[_.object({mode:_.literal("playwright")}).strict(),_.object({mode:_.literal("private-service"),connectorId:_.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/),serviceIds:_.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/).array().min(1).max(32).refine(e=>new Set(e).size===e.length,{message:"service IDs must be unique"}).optional()}).strict()]),lie=_.object({accessToken:_.string().min(1),expiresAt:_.iso.datetime(),fleetApiUrl:_.url(),provider:_.literal("SELF_HOSTED"),tokenType:_.literal("Bearer")}),UYe=lie.extend({network:BYe}).strict(),cie=_.union([UYe,lie.strict()]),jYe=_.object({hostname:_.string(),lease:_.string(),server:_.object({host:_.string(),port:_.number().int().positive()})}),uie=_.object({wsEndpoint:_.string(),accessToken:_.string().optional(),endpointType:DYe.optional(),provider:Zk.optional(),operatingSystem:Zte.optional(),tunnel:jYe.optional()});var zYe=200,HYe=2e3,qC=z.string().trim().min(1).max(zYe),Vg=z.string().trim().min(1).max(HYe),Av=z.array(Vg),$Ye=z.enum(["verified","issues_found","blocked"]),AM=z.object({customFields:JR.optional().catch(void 0),name:qC,summary:Vg,preconditions:Av,outline:Av,acceptanceCriteria:Av}),GYe=z.object({startedAt:z.number(),finishedAt:z.number(),agentId:z.string().optional(),windowId:z.string().optional(),artifactId:z.string().optional()}),VYe=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.(?:jpg|png)$/),WYe=z.object({artifactId:VYe,mediaType:z.enum(["image/jpeg","image/png"])}).refine(({artifactId:e,mediaType:t})=>e.endsWith(t==="image/png"?".png":".jpg"),"Screenshot filename extension must match its media type"),qYe=z.enum(["bug","flag"]),EM=z.object({customFields:JR.optional().catch(void 0),kind:qYe.default("bug"),name:qC,summary:Vg,expected:Vg,actual:Vg,reproSteps:Av,recording:GYe.nullish(),screenshot:WYe.nullish()}),mie=z.object({name:qC.describe("The name of the bug to retract."),reason:z.enum(["duplicate","invalid"]).describe("Why the bug report is being retracted.")}),kG=z.enum(["checked","failed","partial","out_of_scope"]),gb=z.object({control:qC,status:kG,result:Vg}),MG=z.object({status:$Ye,summary:Vg,verified:Av,gaps:Av});z.object({entry:AM});z.object({entry:EM});z.object({entry:gb});z.object({report:MG});z.object({entries:z.array(AM)});z.object({entries:z.array(EM)});z.object({entries:z.array(gb)});z.object({report:MG.nullable()});var LG=z.object({agent:z.string().nullable(),conversationId:z.string().nullable(),createdAt:z.iso.datetime(),updatedAt:z.iso.datetime()}),KYe=AM.extend({...LG.shape,blockedReason:z.string().nullable()}),YYe=EM.extend({...LG.shape,investigatorAgent:z.string().nullable(),investigatorConversationId:z.string().nullable(),reviewedAt:z.iso.datetime().nullable()});gb.extend({agent:z.string(),conversationId:z.string()});var JYe=MG.extend({testCaseName:z.string().nullable(),...LG.shape}),NG=z.enum(["OPEN","ACCEPTED","DUPLICATE","WORKS_AS_INTENDED","CANNOT_REPRODUCE"]);z.object({bugName:z.string(),status:NG,knowledgeItemId:z.string().nullable(),updatedByUserId:z.string().nullable(),updatedAt:z.iso.datetime()});z.object({chatId:z.string().min(1),bugName:qC,status:NG,reviewedKnowledgeItemIds:z.array(z.string().min(1)).optional(),reviewedKnowledgeItemStatus:K9.optional(),linkedKnowledgeItemId:z.string().min(1).nullable().optional()});z.object({entries:z.array(KYe)});z.object({entries:z.array(YYe)});z.object({entries:z.array(JYe)});var die=z.object({testCases:z.number(),issuesFound:z.number(),blocked:z.number(),bugs:z.number(),bugsByTriage:z.record(NG,z.number())});z.union([die.extend({passed:z.number()}),die.extend({verified:z.number()}).transform(({verified:e,...t})=>({...t,passed:e}))]);z.object({entry:AM});z.object({retracted:z.boolean(),conflict:z.string().optional()});z.object({entry:EM,reporterAgent:z.string().min(1).optional(),reporterConversationId:z.string().min(1).optional()}).superRefine((e,t)=>{e.entry.kind!=="flag"||e.entry.screenshot||t.addIssue({code:"custom",message:"Flags require a screenshot",path:["entry","screenshot"]});}).refine(e=>e.reporterAgent===void 0==(e.reporterConversationId===void 0),"reporterAgent and reporterConversationId must be provided together");z.object({reason:Vg});var pie=z.object({id:z.string(),createdAt:z.coerce.date(),createdBy:z.string(),organizationId:z.string(),name:z.string(),description:z.string().nullish(),enabled:z.boolean(),schemaVersion:z.string().describe("Schema version for steps"),parameters:z.string().array().nullish().describe("Parameter list"),parameterEnums:z.record(z.string(),z.string().array()).nullish(),defaultParameters:z.record(z.string(),z.string()).nullish(),defaultCacheKey:z.string().nullish(),defaultCacheTtl:z.number().nullish(),defaultCacheAllInvocations:z.boolean().nullish(),autoAuth:z.boolean().nullish(),defaultRetries:z.int().min(0).nullish(),advanced:YH.nullish()});pie.extend({steps:z.lazy(()=>Bo.array())});var hie=5*60*1e3,KC=kr.extend(pie.omit({id:true,createdAt:true,createdBy:true,organizationId:true,enabled:true}).shape);var XYe="org_01HMJTX4GT1KG94KZRCT8MZ6YB",QYe="org_01HMSCJQBCCG51M2ZF65YC5B8W",ZYe="org_01JPR6MGFQSHF3W234R3XJDPMB";var e4e=[XYe,QYe,ZYe];function fb(e){return e4e.includes(e)}var gie=z.object({id:z.string(),title:z.string(),body:z.string(),imageUrl:z.string().nullable(),videoUrl:z.string().nullable(),ctaUrl:z.string().nullable(),publishedAt:z.string()});z.object({update:gie.nullable()});var fie=z.object({updates:gie.array()});z.object({repositoriesIndexed:z.boolean(),indexingInProgress:z.boolean(),indexesOutdated:z.boolean()});var yie=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(yie||{}),bie=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(bie||{});z.object({name:z.string(),status:z.enum(yie),conclusion:z.enum(bie).nullable()});var YC=z.object({sha:z.string(),parentShas:z.array(z.string()).optional(),message:z.string(),author:z.object({name:z.string().optional(),email:z.string().optional(),date:z.coerce.date().optional()}),committer:z.object({name:z.string().optional(),email:z.string().optional(),date:z.coerce.date().optional()})}),DG=z.object({mergedBranch:z.string().optional()});var Sie=z.object({orgId:z.string(),cacheKeys:z.string().array()});z.object({keyParams:Sie,clientMetadata:z.string(),lockAcquisitionTimeoutMs:z.number().optional()});var Tie=z.object({acquired:z.boolean(),acquiredByMetadata:z.string(),keyPrefix:z.string()});z.object({keyPrefix:z.string(),result:z.string(),ttlMs:z.number()});z.union([z.object({keyPrefix:z.string()}),Sie]);var t4e=z.object({remainingTtlMs:z.number(),value:z.string().nullish()});z.object({results:z.record(z.string(),t4e),activeLocks:z.string().array()});var vie=0,Aie=5*60*1e3;var Eie=z.object({cacheEntryId:z.string().uuid(),category:z.string().min(1)}),wie={isManualOverride:z.boolean().optional(),manualOverrideOf:Eie.optional()},Rie=Gw.extend({identityVersion:z.literal(Xl),cacheEntryId:z.string().uuid().optional(),runId:z.string().min(1).optional(),executionFailureReason:z.string().min(1).optional(),classification:aP,healDetails:w$.optional(),...wie}),Cie=cT.extend({identityVersion:z.literal(jy).optional(),cacheEntryId:z.string().uuid().optional(),runId:z.string().min(1).optional(),testId:z.string().min(1),executionFailureReason:z.string().min(1).optional(),classification:aP,healDetails:w$.optional()}),o4e=z.union([Rie,Cie]),Iie={overriddenBy:Eie.optional(),createdAt:z.coerce.date(),updatedAt:z.coerce.date()},n4e=Rie.extend({cacheEntryId:z.string().uuid(),...Iie}),r4e=Cie.extend({...wie,...Iie}),i4e=r4e.transform(e=>({...e,identityVersion:jy})),xie=z.union([n4e,i4e]);function JC(e){return !e.branchName&&Vw(e.classification.category)}var a4e=Gw.extend({mainBranchName:z.string().min(1).optional()}),s4e=cT.extend({mainBranchName:z.string().min(1).optional(),testId:z.never().optional()}).transform(({testId:e,...t})=>t);z.union([a4e,s4e]);var _ie=xie.array();z.object({entries:o4e.array()});var l4e=Gw.extend({cacheEntryId:z.string().uuid(),runId:z.string().min(1),category:z.string().min(1)}),c4e=cT.extend({testId:z.never().optional(),runId:z.string().min(1),cacheEntryId:z.string().uuid(),category:z.string().min(1)}).transform(({testId:e,...t})=>t);z.union([l4e,c4e]);z.object({status:z.enum(["evicted","not_found","run_mismatch"]),entry:xie.optional()});z.object({runId:z.string().min(1),environment:z.string().min(1).optional(),status:z.enum(["PASSED","FAILED"])});z.object({environment:z.string().min(1).optional()});var wM=z.object({skip:z.boolean(),failed:z.number(),total:z.number()}),u4e=.8;function Oie({failed:e,completed:t,minCompletedRuns:o}){return t>=o&&e/t>=u4e}function Ev(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 d4e=z.object({version:z.string(),json:z.record(z.string(),z.unknown().optional()),hash:z.string()}),Pie=z.record(z.string(),z.unknown().optional());z.object({newSvgs:z.array(d4e),metadata:Pie.optional()});var m4e=z.object({version:z.string(),json:z.record(z.string(),z.unknown().optional()).nullish(),hash:z.string(),description:z.string().nullish(),metadata:Pie.nullish()}),kie=z.record(z.string().describe("icon hash"),m4e);var FG="metadata.json",BG="test.yaml",Mie=".snapshot.zip",UG=Ir.extend(oc.shape),p4e=z.object({envName:z.string().optional(),baseUrl:z.string(),variables:z.record(z.string(),z.unknown().optional()),resolvedEnv:FR.optional()}),Lie=z.object({browser:Ju.optional(),ai:_l.optional(),advanced:XR.optional(),retries:z.number().optional()});z.object({momenticVersion:z.string(),schemaVersion:z.string(),createdAt:z.string(),relativeFilePath:z.string(),environment:p4e,config:Lie});var Nie=z.object({variables:z.record(z.string(),z.unknown().optional()),resolvedEnv:FR.optional()}),h4e=z.object({envName:z.string().optional(),baseUrl:z.string(),encryptedSecrets:z.string()}),Die=z.object({momenticVersion:z.string(),schemaVersion:z.string(),createdAt:z.string(),relativeFilePath:z.string(),environment:h4e,config:Lie});var g4e=z.looseObject({type:z.number(),data:z.record(z.string(),z.unknown()),timestamp:z.number()}),jG=z.custom(e=>g4e.safeParse(e).success);z.object({segments:z.array(z.object({artifactId:z.string(),startedAt:z.number(),finishedAt:z.number(),events:z.array(jG)}))});z.discriminatedUnion("kind",[z.object({kind:z.literal("agent-action"),tool:z.string(),toolCallId:z.string().optional(),detail:z.string().optional(),input:z.unknown().optional()}),z.object({kind:z.literal("step"),phase:z.enum(["start","pass","fail"]),name:z.string()}),z.object({kind:z.literal("window"),phase:z.enum(["start","stop"]),windowId:z.string()}),z.object({kind:z.literal("bug-marker"),title:z.string()}),z.object({kind:z.literal("control"),control:z.string(),status:kG}),z.object({kind:z.literal("network-error"),method:z.string(),url:z.string(),status:z.number()})]);z.looseObject({level:z.string(),payload:z.array(z.string()),trace:z.array(z.string()).optional()});function Fie(e){let t;try{t=JSON.parse(e);}catch(o){return `The schema is not valid JSON. ${o}`}try{validator(t);}catch(o){return `The schema is not a valid JSON schema. ${o}`}}var Bie=e=>{e.extraHeaders&&(e.extraHeaders=Object.fromEntries(Object.entries(e.extraHeaders).filter(([t,o])=>t.trim()&&o.trim())));};var RM=class{async prepareGoldenScreenshotForComparison(t,o,n){return n}};var CM=class{async resolveStepCacheEntries(){return {}}async saveStepCacheEntries(){}async saveSnapshotCacheEntries(){}async deleteStepCacheEntry(){}};function y4e(e){return e.map(t=>({...t,environment:void 0}))}function zG(e,t){return t?e:y4e(e)}var $G="browser-crash-dump.zip",HG=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new XC}},XC=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new HG}flushResults(t){}};var Mt="metadata.json",Ks="assets",ar="runs",GG=z.object({type:z.literal("explore"),id:z.string(),cliVersion:z.string().optional(),startedAt:z.string(),finishedAt:z.string(),baseSha:z.string(),headSha:z.string(),ciProvider:z.string().optional(),pipelineId:z.string().optional(),gitMainBranch:z.string().optional(),gitCommitSha:z.string().optional(),gitCommitShaShort:z.string().optional(),gitBranchName:z.string().optional(),gitOriginUrl:z.string().optional(),gitCommitMessage:z.string().optional(),gitCommitAuthorName:z.string().optional(),githubRepository:z.string().optional(),gitlabProjectPath:z.string().optional(),pullRequestUrl:z.string().optional(),result:z.unknown(),bugs:z.array(z.unknown()),uxNits:z.array(z.unknown()).default([]),writtenPaths:z.array(z.string()),videos:z.array(z.string()),failure:z.unknown().optional()});z.object({exploreRunId:z.guid(),metadata:GG,videoAssets:z.string().array().optional()});var Uie=z.object({uploadUrl:z.string(),videoUploadUrls:z.record(z.string(),z.string()).optional()}),b4e=z.object({step:Uo,status:z.enum(io),startedAt:z.coerce.date(),finishedAt:z.coerce.date().optional(),healMetadata:z.object({healType:z.enum($R).or(z.literal("AI")),healedAt:z.coerce.date()}).optional(),beforeSnapshotId:z.guid().optional(),afterSnapshotId:z.guid().optional(),message:z.string().optional()}),S4e=b4e.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});S4e.extend({step:z.unknown().optional()});var VG=z.object({avdId:z.string().optional(),channel:z.string().optional(),tag:z.string().optional(),region:z.string().optional(),osVersion:xee.optional()}),jie="1.0.0",zie=Bre.extend({id:z.guid().optional(),startedAt:z.coerce.date(),runAttemptSchemaVersion:z.string().optional(),schemaVersion:z.string().optional().default("1.0.19"),results:z.record(z.string(),z.unknown().optional()).array().optional(),beforeResults:z.record(z.string(),z.unknown().optional()).array().optional(),afterResults:z.record(z.string(),z.unknown().optional()).array().optional(),assetDetails:VG.optional(),networkCaptureEnabled:z.boolean().optional(),viewport:jp.optional(),activeVideos:z.array(z.object({videoName:z.string(),timestamp:z.coerce.date()})).optional()}),QC=zie.extend({assetDetails:VG.optional(),finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});zie.extend(U$.shape);var Hie=QC.extend(U$.shape),T4e=z.object({results:z.array(Hs),beforeResults:z.array(Hs).optional(),afterResults:z.array(Hs).optional()});QC.extend(T4e.shape);var v4e=z.object({results:z.array($s),beforeResults:z.array($s).optional(),afterResults:z.array($s).optional()});QC.extend(v4e.shape);var A4e=z.object({creditsUsed:z.number(),stepsExecuted:z.number()}),$ie=Fre.merge(Nre).extend({executionType:Hp.optional().default("WEB"),testId:Lr,testDescription:z.string().optional(),directory:z.string().optional(),runGroupId:z.guid(),status:z.enum(ho),healStatus:Qy,testBundleHash:z.string().optional(),startedAt:z.coerce.date(),schemaVersion:z.string().nullish(),attempts:z.number(),failureRecoveryDetails:z.object({attempts:z.number()}).optional(),aiSettings:_l.optional(),avgCpuUsage:z.number().optional(),avgMemoryUsage:z.number().optional(),usage:A4e.optional().catch(void 0)}),E4e=$ie.extend(VG.shape),Wg=$ie.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});E4e.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});var IM=1e4,w4e=Mre.merge(Lre).extend({id:z.guid().optional(),startedAt:z.coerce.date(),cliVersion:z.string(),labels:z.string().array().optional().default([]),suiteName:z.string().optional(),ciProvider:z.string().optional(),gitMainBranch:z.string().optional(),ai:_l.optional(),browser:Ju.optional(),sourceRunGroupIds:z.array(z.guid()).max(IM).optional(),mergedAt:z.coerce.date().optional(),aiSelect:z.union([ZR.transform(e=>[e]),z.array(ZR)]).optional()}),iu=w4e.extend({healRiskSummary:Zy.optional(),updatedAt:z.coerce.date().optional().transform(e=>e??new Date),finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});var R4e=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"]),C4e=new Set(["MODULE","RESOLVED_MODULE"]);function Gie(e){return e.type!=="PRESET_ACTION"?e.type:e.command.type}function Vie(e){return C4e.has(e.type)?false:e.type!=="PRESET_ACTION"?true:!R4e.has(e.command.type)}var Wie="progress.json",qie="1.0.0",I4e=z.object({runId:z.string(),testId:z.string().optional(),testName:z.string().optional(),directory:z.string().optional(),status:z.nativeEnum(ho),completedSteps:z.number(),totalSteps:z.number(),startedAt:z.coerce.date(),updatedAt:z.coerce.date()});z.object({schemaVersion:z.string(),runGroupId:z.string(),status:z.nativeEnum(ho),totalRuns:z.number(),completedRuns:z.number(),completedSteps:z.number(),totalSteps:z.number(),startedAt:z.coerce.date(),updatedAt:z.coerce.date(),runs:I4e.array()});function Kie(e,t){let o=Cn__default.relative(t,e);return o!==""&&o!==".."&&!o.startsWith(`..${Cn__default.sep}`)&&!Cn__default.isAbsolute(o)}function Yie(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch(t){return x.error({err:t},`Error reading path ${e} during directory existence check.`),false}}var Jie="CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih",wv="https://us-west.metrics.momentic.ai",Rv="c60c6a0f-60da-41a7-a61b-07969a0aa303",ms=!!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 N4e=new Set(["exit","quit"]),qG=(()=>{try{return statSync("/.dockerenv"),!0}catch{return false}})(),D4e=ms||qG||!process.stdin.isTTY;function Zie(){return !ms&&!qG&&!process.stdin.isTTY}async function ki(e){if(ms||qG)return true;if(!process.stdin.isTTY)throw new ae(`Cannot ask for confirmation: "${e}" No interactive terminal is available. Re-run with --yes or in a TTY.`);return await x.flush(),await new Promise(o=>setTimeout(o,100)),await confirm({message:e})}async function KG(e){let t=dirname(e);return Yie(t)?existsSync(e)?ki(`File '${Xie(e)}' already exists. Overwrite existing content?`):true:await ki(`Directory '${Xie(t)}' doesn't exist. Create it now?`)?(mkdirSync(t,{recursive:true}),true):false}function Xie(e){return e.replace(/(\s+)/g,"\\$1")}async function eae(e,t){return D4e?t:(await input({message:e,default:t})).trim()||t}async function YG(){let e;try{e=(await input({message:"ask"})).trim();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError"){x.info("");return}throw t}if(!N4e.has(e.toLowerCase()))return e}var Cv=new Map,rae=new Set;function q4e(e){rae.add(e);}function iae(e){q4e(t=>{e({category:"cli",level:t.severity_text==="ERROR"?"error":t.severity_text==="WARN"?"warning":"info",message:t.body,timestamp:t.timestamp/1e9});});}var oae="Log throttle exceeded",Y4e=100,J4e=5e3,X4e=2e4,Q4e=H4e(global.fetch,{retries:2,retryOn:function(e,t,o){return !!(t!==null||o&&o.status>=500)},retryDelay:function(e){return Math.pow(2,e)*500}});function Z4e({app:e,hostname:t,environment:o,serviceVersion:n}){return {host:t,env:o,[ATTR_SERVICE_NAME]:e,...n?{[ATTR_SERVICE_VERSION]:n}:{}}}var e3e=`${wv}/logs/json`,JG=class{constructor(t,o){this.flushIntervalMs=t;this.maxBatchSize=o;}records=[];flushTimer;flushRequested=false;flushPromise;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(){this.flushRequested=true,this.flushPromise??=Promise.resolve().then(async()=>{try{for(;this.flushRequested;){this.flushRequested=!1;let t=this.records;this.records=[];for(let o=0;o<t.length;o+=this.maxBatchSize)await this.sendBatch(t.slice(o,o+this.maxBatchSize));}}finally{this.flushPromise=void 0;}}),await this.flushPromise;}async sendBatch(t){try{let o=await Q4e(e3e,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":Jie,"x-momentic-metrics-api-key":Rv},body:Qu(t),signal:AbortSignal.timeout(X4e)});if(!o.ok)throw new Error(`Got error status (${o.statusText}) from SigNoz`)}catch{}}},XG=class e{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=false;lastWindowStart=Date.now();flushIntervalMs;maxBatchSize;buffer;constructor({bindings:t,hostname:o,disableConsoleLogs:n,flushIntervalMs:r,maxBatchSize:i,buffer:a}){this.hostname=o??Jp.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...t,env:"production"},this.flushIntervalMs=r??5e3,this.maxBatchSize=i??10,this.buffer=a??new JG(this.flushIntervalMs,this.maxBatchSize);let s={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=tae(s);}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===oae)return true;let o=Date.now();return o-this.lastWindowStart>J4e&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,oae),this.droppedLogsInWindow=false,this.lastWindowStart=o),this.logsInCurrentWindow<Y4e?(this.logsInCurrentWindow++,true):(this.droppedLogsInWindow=true,false)}log(t,o,n,...r){try{this.logHelper(t,o,n,...r);}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`);}}logHelper(t,o,n,...r){if(YR[t]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof o=="string"&&!n&&(o={message:o}),typeof o=="object"&&o&&"err"in o&&o.err instanceof Error&&(o.err=W4e.err(o.err));let i={...this.bindingAttributes,...o&&typeof o=="object"?o:{},...r.length>0?{args:r}:{}},a=Z4e({app:this.bindingAttributes.app,hostname:this.hostname,environment:this.bindingAttributes.env,serviceVersion:this.bindingAttributes.cliVersion??"3.62.2"}),s=t3e();this.disableConsoleLogs||this.consoleLogger[t]({...i,...s??{}},n,...r);let l={timestamp:Math.round(Date.now()*1e6),...s??{},severity_text:t.toUpperCase(),resources:a,attributes:{},body:uZ({message:n||"",...i})};this.buffer.push(l);for(let c of rae)try{c(l);}catch{}}setApp(t){let o=this.bindingAttributes.app;this.bindingAttributes.app=t,Cv.set("app",this),Cv.delete(o);}debug(t,o,...n){this.log("debug",t,o,...n);}info(t,o,...n){this.log("info",t,o,...n);}warn(t,o,...n){this.log("warn",t,o,...n);}error(t,o,...n){this.log("error",t,o,...n);}bindings(){return this.bindingAttributes}addBinding(t,o){this.bindingAttributes[t]=o;}setMinLevel(t){typeof t=="number"?(this.minLevelValue=t,this.consoleLogger.level=dZ[t]):(this.minLevelValue=YR[t],this.consoleLogger.level=t);}enableConsoleLogs(){this.disableConsoleLogs=false;}},Iv=({app:e,hostname:t,disableConsoleLogs:o})=>(Cv.has(e)||Cv.set(e,new XG({bindings:{app:e},hostname:t,disableConsoleLogs:o})),Cv.get(e));function t3e(){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 xM(){await Promise.all([...Cv.values()].map(e=>e.flush()));}var Ua=class extends Error{callSiteStack;constructor(t){super(t),this.name="TimeoutError";}};var aae=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 ye(e,t){let{milliseconds:o,fallback:n,message:r,customTimers:i={setTimeout,clearTimeout}}=t,a;if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);let s=new Error().stack;return new Promise((l,c)=>{let u,d=()=>{i.clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",u);};if(t.signal){let{signal:p}=t;if(p.aborted)return Promise.resolve(e).catch(()=>{}),c(aae(p));u=()=>{d(),c(aae(p));},p.addEventListener("abort",u,{once:true});}let m=()=>{if(t.signal&&t.signal.removeEventListener("abort",u),n)try{l(n());}catch(p){c(p);}else {if(typeof e.cancel=="function"&&Promise.resolve().then(()=>e.cancel()).catch(()=>{}),r instanceof Error){c(r);return}let p=new Ua(r??`Promise timed out after ${o}ms`);p.callSiteStack=s,c(p);}};o<1/0&&(a=i.setTimeout(m,o)),Promise.resolve(e).then(p=>{d(),l(p);}).catch(p=>{d(),c(p);});})}function au({signal:e,timeoutMs:t}){let o=AbortSignal.timeout(t);return e?AbortSignal.any([e,o]):o}var _M="organization";function OM(e){let t=new PostHog(e.writeKey,{host:e.host,...e.flushImmediately?{flushAt:1,flushInterval:0}:{}}),o=e.platform,n=(l,c,u)=>{let{type:d,...m}=l;t.capture({distinctId:c??u??randomUUID(),event:d,...u&&{groups:{[_M]:u}},properties:{platform:o,user_id:c??void 0,org_id:u??void 0,...m,organizationId:u??void 0,...c==null&&u==null&&{$process_person_profile:false}}});},r=({orgId:l,properties:c})=>{t.groupIdentify({groupType:_M,groupKey:l,properties:c});},i=({userId:l,properties:c})=>{Object.values(c).some(d=>d!=null&&d!=="")&&t.identify({distinctId:l,properties:c});},a=()=>t.shutdown();if(e.identity==="stashed"){let l=null;return {shutdownAnalytics:a,groupIdentifyOrg:r,setAnalyticsIdentity:u=>{l=u,e.onIdentify?.(u),i({userId:u.userId,properties:{email:u.email,...u.selfServe!==void 0?{self_serve:u.selfServe}:{}}});},captureEvent:u=>n(u,l?.userId??null,l?.orgId??null)}}return {shutdownAnalytics:a,groupIdentifyOrg:r,identifyUser:i,captureEvent:(l,{userId:c,orgId:u})=>n(l,c,u),captureBillingEvent:(l,{userId:c,orgId:u})=>n(l,c,u)}}async function sae(e,t,o){let n,r=0,i=3,a,s;for(;r<i;)try{let l=await ye(e.getAllFlagsAndPayloads(o??t,{personProperties:{organizationId:t},groups:{[_M]:t}}),{milliseconds:5e3});a=l.featureFlags||{},s=l.featureFlagPayloads||{};break}catch(l){n=l,r++,await new Promise(c=>setTimeout(c,100*r));}if(a&&s)return {flags:a,payloads:s};throw n}var PM=class e extends cb{constructor(o,n,r,i,a){super(i,a);this.client=o;this.orgId=n;this.userId=r;}static createClient(){return new PostHog("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://p.momentic.ai"})}static async init(o,n){let r=e.createClient(),{flags:i,payloads:a}=await sae(r,o,n);return new e(r,o,n,i,a)}static fromCached(o,n,r,i){return new e(e.createClient(),o,n,r,i)}async refresh(){let{flags:o,payloads:n}=await sae(this.client,this.orgId,this.userId);this.flags=o,this.payloads=n;}};var kM="/proc",lae="/sys/fs/cgroup",a3e="/sys/fs/cgroup/memory",cae=8,s3e=1024;function LM(){let e;return ()=>{if(process.platform!=="linux")return;let t=m3e();if(!t)return;let o=p3e({current:t,previous:e});return e=t,o}}function uae(){if(process.platform!=="linux")return;let e=QG(`${lae}/memory.stat`);if(e){let o=QG(`${lae}/memory.events`);return {anonymousBytes:e.anon,fileCacheBytes:e.file,kernelBytes:e.kernel,slabBytes:e.slab,sharedMemoryBytes:e.shmem,pageTablesBytes:e.pagetables,activeAnonymousBytes:e.active_anon,inactiveAnonymousBytes:e.inactive_anon,activeFileBytes:e.active_file,inactiveFileBytes:e.inactive_file,events:o?{low:o.low,high:o.high,max:o.max,oom:o.oom,oomKill:o.oom_kill,oomGroupKill:o.oom_group_kill}:void 0}}let t=QG(`${a3e}/memory.stat`);if(t)return {anonymousBytes:t.total_rss??t.rss,fileCacheBytes:t.total_cache??t.cache,slabBytes:t.total_slab??t.slab,sharedMemoryBytes:t.total_shmem??t.shmem,pageTablesBytes:t.total_pagetables??t.pagetables,activeAnonymousBytes:t.total_active_anon??t.active_anon,inactiveAnonymousBytes:t.total_inactive_anon??t.inactive_anon,activeFileBytes:t.total_active_file??t.active_file,inactiveFileBytes:t.total_inactive_file??t.inactive_file}}function l3e(e){let t={};for(let o of e.split(`
184
+ Use null when unknown or not applicable.`),t[o.name]=r.describe(i);}return z.strictObject(t)}function $Ge(e){let t=[e.testCases??[],e.bugReproductions??[]].map(o=>z.toJSONSchema(HGe(o)));return new TextEncoder().encode(JSON.stringify(t)).byteLength}var hZ=UGe.refine(e=>$Ge(e)<=jGe,"Field guidance is too long. Shorten descriptions or remove fields or options.");var YT=Ju.extend({browserType:z.enum(Yu).optional(),basicAuthorization:z.object({username:z.string().optional(),password:z.string().optional()}).optional(),geolocation:z.object({latitude:z.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:z.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:z.boolean().optional(),locale:z.string().optional(),timezone:z.enum(KP).optional(),colorScheme:z.enum(["light","dark"]).optional()}),gZ=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],Q$=z.object({useMemory:z.boolean().optional(),failureRecovery:z.boolean().optional().describe("undefined means inherit org settings")}),Z$=Q$.extend({disableAICaching:z.boolean().optional()}),VGe=z.object({viewport:jp.optional()}),Us=VGe.extend(Z$.shape).extend(YT.shape),gk=z.object({cron:z.string().refine(e=>isValidCron(e),{error:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:z.boolean().default(false),env:z.string().optional(),timeZone:z.string().default("America/Los_Angeles"),jobKey:z.string().optional()}),fk=z.object({onSuccess:z.boolean().default(false),failureMessage:z.string().optional(),onFailure:z.boolean().default(true),successMessage:z.string().optional()}),WGe=z.object({name:z.string(),required:z.boolean().optional(),defaultValue:z.string().describe("this is not optional because we need a value when the editor is first loaded")}),fZ=WGe.array(),qGe=z.object({name:z.string(),value:z.string()}),yk=qGe.array(),yZ=z.object({name:z.string(),default:z.boolean().optional(),fixtures:J8.array().optional()});var _l=Q$.extend({agentConfig:z.record(z.string(),z.string()).optional(),aiFailureAnalysis:z.boolean().optional(),classification:wQ.optional(),healing:mT.optional(),explore:pP.optional(),select:eZ.optional(),aiActionVersion:yR.optional()}),KGe=z.object({cliOnly:z.boolean().optional(),moDefault:z.boolean().optional(),neverShowUsageBanner:z.boolean().optional(),hideInternalTraceInfo:z.boolean().optional(),bypassUsageLimits:z.boolean().optional()}),XR=z.object({aiActionShorthand:z.boolean().optional().describe("Serialize eligible multi-word AI action V3 goals as bare strings in simplified YAML."),fakerConstantSeed:z.boolean().optional(),isolateCachesByEnvironment:z.boolean().optional(),saveCacheOnCancel:z.boolean().optional()}),YGe=z.object({includePassingRuns:z.boolean().optional(),showFailedTestDetails:z.boolean().optional()}),JGe=z.enum(["flaky_tests","low_test_coverage","frequent_bugs","fix_flaky_tests","migrate_tests","increase_test_coverage","catch_more_bugs"]),XGe=z.enum(["ios","android","web"]),QGe=z.enum(["selenium","playwright","cypress","puppeteer","maestro","appium","detox","manual_qa","nothing_yet","other"]),t1=z.enum(["advertisement","ai_search","google_search","hacker_news","linkedin","reddit","referral_from_customer","twitter_x","word_of_mouth","youtube","teammate_or_manager","investor_or_accelerator","agent_directory","newsletter","podcast","conference_or_event","billboard","other"]),ZGe=z.object({helpIntents:z.array(JGe).optional(),helpIntentOtherText:z.string().optional(),deviceTypeIntent:XGe.optional(),currentTestingTool:QGe.optional(),heardAboutSource:t1.optional(),heardAboutSourceOtherText:z.string().max(200).optional()}),e2e=z.object({discovery:ZGe.optional(),needsToCompleteOnboarding:z.boolean().optional(),needsWorkspaceName:z.boolean().optional(),wizardCompletedAt:z.iso.datetime().optional(),goal:z.enum(["mo","e2e"]).optional(),flowVersion:z.number().int().optional().catch(void 0)}),JT=z.object({moCustomFields:hZ.optional(),ai:_l.optional(),githubAppInstallationId:z.number().nullish(),githubAppSummaryMessageEnabled:z.boolean().nullish(),githubPullRequestComments:YGe.optional(),githubReleaseAppInstallationId:z.number().nullish(),gitlabAppAccessToken:z.string().nullish(),gitlabAppBaseUrl:z.string().nullish(),browser:m$.optional(),internal:KGe.optional(),advanced:XR.optional(),onboarding:e2e.optional()}),t2e=5;function bZ(e){let t=e,o=[];for(let n=0;n<t2e;n++){let r=JT.safeParse(t);if(r.success)return o.length>0&&x.warn(`Ignoring cloud settings this version of the CLI does not support: ${o.join(", ")}. Please upgrade. Everything else was applied.`),r.data;let i=o2e(r.error.issues.map(l=>[...l.path]).filter(l=>l.length>0));if(i.length===0)break;let a=structuredClone(t),s=[...i].sort(n2e);for(let l of s)e1(a,l);if(JSON.stringify(a)===JSON.stringify(t)){for(let l of s)l.length>1&&e1(a,l.slice(0,-1));if(JSON.stringify(a)===JSON.stringify(t))break}o.push(...i.map(l=>l.join("."))),t=a;}return x.warn("Cloud settings could not be read by this version of the CLI. Please upgrade. Falling back to defaults."),JT.parse({})}function o2e(e){return [...new Map(e.map(o=>[o.join("\0"),o])).values()]}function n2e(e,t){if(e.length!==t.length)return t.length-e.length;for(let o=e.length-1;o>=0;o--){let n=e[o],r=t[o];if(typeof n=="number"&&typeof r=="number"&&n!==r)return r-n}return 0}function e1(e,t){let[o,...n]=t;if(!(o===void 0||typeof e!="object"||e===null)){if(n.length===0){Array.isArray(e)&&typeof o=="number"?e.splice(o,1):delete e[o];return}e1(e[o],n);}}z.object({globalOverrides:z.record(z.string(),z.string()).optional(),agentConfig:z.record(z.string(),z.string()).optional()});z.record(z.string(),z.string()).nullish();var SZ="Evaluating run assertions",bk=z.string();function QR(e){return (e.runAssertions?.length??0)>0}var r2e=z.object({videoName:z.string(),startSeconds:z.number(),endSeconds:z.number().optional()}),o1=z.discriminatedUnion("type",[z.object({type:z.literal("videoMoment"),moment:r2e})]),n1=(r=>(r.PASSED="passed",r.FAILED="failed",r.SKIPPED="skipped",r.INCONCLUSIVE="inconclusive",r))(n1||{}),i2e=z.nativeEnum(n1),a2e=z.array(z.unknown()).default([]).transform(e=>e.flatMap(t=>{let o=o1.safeParse(t);return o.success?[o.data]:[]})),s2e=z.object({description:z.string(),status:i2e,reasoning:z.string(),evidence:a2e}),l2e=z.object({attemptNumber:z.number(),evaluations:s2e.array(),durationMs:z.number()});function TZ(e){let t=e.filter(o=>o.status==="failed");if(t.length!==0)return `Run assertion(s) not met: ${t.map(o=>o.description).join("; ")}`}var vZ=z.object({attempts:l2e.array()}),c2e=/\[\[e(\d+)\]\]/g;function AZ(e){return [...e.matchAll(c2e)].map(t=>Number(t[1]))}var ic={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ho=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(ho||{});var XT=(a=>(a.NOT_ATTEMPTED="NOT_ATTEMPTED",a.PERM_HEAL_SUCCEEDED="PERM_HEAL_SUCCEEDED",a.PERM_HEAL_FAILED="PERM_HEAL_FAILED",a.PERM_HEAL_UNATTEMPTED="PERM_HEAL_UNATTEMPTED",a.PERM_HEAL_ON_SUCCESS_FAILED="PERM_HEAL_ON_SUCCESS_FAILED",a.PERM_HEAL_NOT_NEEDED="PERM_HEAL_NOT_NEEDED",a))(XT||{});var Qy=z.enum(XT).default("NOT_ATTEMPTED"),Sk=(o=>(o.BEFORE_ALL="BEFORE_ALL",o.AFTER_ALL="AFTER_ALL",o))(Sk||{});var u2e=z.object({attempts:z.int().nonnegative()}),br=z.string().pipe(z.coerce.date()).or(z.date()),js=z.object({id:z.string(),runKey:z.string(),organizationId:z.string(),executionType:Hp.optional().default("WEB"),createdAt:br,createdBy:z.string(),flake:z.boolean().nullish(),scheduledAt:br.or(z.null()),startedAt:br.or(z.null()),updatedAt:br.nullish(),finishedAt:br.or(z.null()),resolvedBaseUrl:z.string().nullish(),environmentName:z.string().nullish(),gitBranchName:z.string().nullish(),gitMainBranch:z.string().nullish(),githubRepository:z.string().nullish(),gitlabProjectPath:z.string().nullish(),labels:z.array(z.string()).optional(),gitOriginUrl:z.string().nullish(),gitCommitSha:z.string().nullish(),gitCommitShaShort:z.string().nullish(),gitCommitAuthorName:z.string().nullish(),gitCommitTimestamp:br.nullish(),gitCommitMessage:z.string().nullish(),schemaVersion:z.string().nullish(),cliVersion:z.string().nullish(),section:z.enum(Sk).nullish(),status:z.enum(ho),healStatus:Qy,healDetails:a9.nullish(),trigger:z.enum(ic),attempts:z.number(),runAttempts:z.array(z.object({id:z.string(),status:z.enum(ho),startedAt:br.or(z.null()),finishedAt:br.or(z.null())})).optional(),videos:z.array(z.string()).optional(),failureReason:z.string().nullish(),failureDetails:NQ.nullish(),failureRecoveryDetails:u2e.nullish(),pipelineId:z.string().nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),quarantined:z.boolean().nullish().default(false),quarantinedReason:z.string().nullish(),localTestId:z.string().nullish(),testId:z.string().nullish(),testName:z.string().nullish(),description:z.string().nullish(),directory:z.string().nullish(),test:z.object({name:z.string(),id:z.string()}).nullish().default(null),suiteId:z.string().nullish(),aiSettings:_l.nullish(),stepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),beforeStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),afterStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),runAssertionResults:vZ.nullish()}),d2e={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},Tk=js.pick({...d2e,test:true}),EZ=js.omit({failureReason:true,failureDetails:true,test:true}),r1=js.extend({stepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),beforeStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),afterStepsSnapshot:z.array(z.record(z.string(),z.unknown().optional())).nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),test:z.object({name:z.string(),id:z.string(),description:z.string().nullish(),baseUrl:z.string().nullish(),advanced:Us.nullish()}).nullish()}).extend(B$.shape),wZ=e=>e.includes("PASSED")&&e.includes("FAILED");var m2e=z.object({region:z.enum(["US","EU"]).optional().describe("New Relic data center region. Defaults to US."),accountId:z.string().describe("New Relic account ID to send events to. Supports ${ENV_VAR} interpolation."),licenseKey:z.string().optional().describe("New Relic ingest license key. Supports ${ENV_VAR} interpolation. Defaults to the NEW_RELIC_LICENSE_KEY environment variable."),attributes:z.record(z.string(),z.string()).optional().describe("Static attributes (e.g. service, team) added to every event sent to New Relic. Values support ${ENV_VAR} interpolation.")}),RZ=z.object({newrelic:m2e.optional()}),p2e=z.object({category:z.string(),reasoning:z.string(),citations:z.array(Kn).optional()}),h2e=z.object({testInputs:z.record(z.string(),z.string()).optional(),envName:z.string().optional(),urlOverride:z.string().optional()}),g2e=z.object({reason:z.string().optional(),message:z.string().optional()}),f2e=z.object({runId:z.string().optional(),testId:z.string(),testName:z.string(),filePath:z.string(),labels:z.array(z.string()).optional(),status:z.enum(ho),startedAt:z.string(),finishedAt:z.string(),durationMs:z.number(),attempts:z.number(),quarantined:z.boolean(),recovered:z.boolean(),parameters:h2e.optional(),failure:g2e.nullable(),classification:p2e.nullable()}),y2e=z.object({testId:z.string(),testName:z.string(),filePath:z.string(),labels:z.array(z.string()).optional(),quarantined:z.boolean()}),b2e=z.object({total:z.number(),executed:z.number(),skipped:z.number(),passed:z.number(),failed:z.number(),cancelled:z.number(),quarantined:z.number(),recovered:z.number()}),CZ=z.object({version:z.literal(1),runGroup:z.object({startedAt:z.string(),finishedAt:z.string(),durationMs:z.number()}),summary:b2e,runs:z.array(f2e),skipped:z.array(y2e)});var IZ=z.enum(["error","warning","passing"]);var xZ=z.enum(["safe_to_merge","confirm_intended_change","investigate_regression","fix_test","resolve_infra","review_coverage"]),T2e=xZ.exclude(["review_coverage"]);var v2e="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 _Z=z.object({kind:xZ,detail:z.string().min(1).max(280)}),Zy=z.object({riskLevel:z.string(),headline:z.string().min(1).max(200).describe("One-sentence summary of what happened in this run. Plain text, no markdown."),overview:z.string().min(1).max(280).optional().describe("One plain-text sentence giving the bottom line of the run. No markdown."),summaryMarkdown:z.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:_Z.optional()}),OZ=Zy.extend({riskLevel:IZ.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.string().min(1).max(120).describe(v2e),overview:z.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.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:_Z.extend({kind:T2e.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."),detail:z.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 w2e=z.enum(["SELECTED","RUN_ALL","RUN_NONE","SHADOW"]),ZR=z.object({mode:w2e,baseRef:z.string().nullable(),headSha:z.string(),planId:z.string().nullable(),totalCandidates:z.number().int().nonnegative(),selectedCount:z.number().int().nonnegative(),anchorSegmentIds:z.array(z.string()),userSummary:z.string(),toolCallCount:z.number().int().nonnegative(),selectedTests:z.array(pk),forcedTests:z.array(z.object({name:z.string(),testPath:z.string(),status:z.enum(["A","M","R","C","T"])})).optional().default([]),runAllReason:z.string().nullable()});function PZ(e){return uniqWith([...e],isEqual)}var kZ=z.object({id:z.string(),status:z.enum(ho),trigger:z.enum(ic),createdAt:br,startedAt:br.nullish(),finishedAt:br.nullish(),gitCommitSha:z.string().nullish(),gitCommitShaShort:z.string().nullish(),gitCommitTimestamp:br.nullish(),gitBranchName:z.string().nullish(),gitOriginUrl:z.string().nullish(),gitCommitMessage:z.string().nullish(),gitCommitAuthorName:z.string().nullish(),projectName:z.string().nullish(),relativeProjectDir:z.string().nullish(),githubRepository:z.string().nullish(),gitlabProjectPath:z.string().nullish(),pipelineId:z.string().nullish(),ciProvider:z.string().nullish(),cliVersion:z.string().nullish(),labels:z.string().array().optional(),healRiskSummary:Zy.optional(),aiSelect:ZR.array().optional(),environments:z.string().array().optional(),executionTypes:Hp.array().optional(),localSuiteName:z.string().optional(),suite:z.object({id:z.string(),name:z.string()}).nullish(),runs:z.object({status:z.enum(ho)}).array()}),MZ=kZ.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true,localSuiteName:true}).extend({runs:Tk.array()}),vk=kZ.extend({runs:js.array()});var R2e=z.object({type:z.literal("TARGETING"),name:z.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:V9.array(),pageState:z.string().optional(),targetSource:z.enum(Hu).optional(),targetUpdateTime:z.string().optional()}),C2e=z.object({type:z.literal("AI_LOCATION"),matched:z.boolean(),pageState:z.string().optional(),ragUsed:z.boolean().optional(),thoughts:z.string().optional()}),I2e=z.object({type:z.literal("ASSERTION"),relevantElementsSerialized:z.string().array().optional(),pageState:z.string().optional(),ragUsed:z.boolean().optional()}),Ak=z.discriminatedUnion("type",[R2e,C2e,I2e]);var x2e=z.object({id:z.string(),name:z.string()});x2e.extend(z.object({createdAt:br,createdBy:z.string(),schedule:gk,notification:fk,environment:z.object({name:z.string()}).nullish(),beforeTests:z.object({id:z.string()}).array().nullish(),afterTests:z.object({id:z.string()}).array().nullish()}).shape);var LZ=z.object({id:z.guid(),orgId:z.string(),createdAt:br,startedAt:br.or(z.null()),finishedAt:br.or(z.null()),status:z.enum(ho),trigger:z.enum(ic),suite:z.object({id:z.string(),name:z.string()}).nullish(),runs:js.array()});LZ.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true});var NZ=LZ.extend({runs:Tk.array()});function DZ({beforeStatus:e,mainStatus:t,afterStatus:o}){return e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":o==="FAILED"?"FAILED":o==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":"PASSED"}function Ek(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 FZ(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 i1=z.object({content:z.string(),ids:z.string().array(),tokenLength:z.number()}),_2e=z.object({chunks:i1.array()});z.object({ids:z.string().array(),score:z.number(),tokenLength:z.number()});_2e.extend({description:z.string().describe("Input to pass to RAG engine"),tokenLimit:z.number()});var BZ=z.object({ids:z.number().array()}),UZ=z.object({indices:z.number().array()});var ac=(o=>(o.Interactive="interactive",o.Runner="runner",o))(ac||{}),O2e=z.enum(ac),_i=z.object({disableCache:z.boolean().optional(),useMemory:z.boolean().optional(),clientMode:O2e.optional(),loggerTags:z.record(z.string(),z.string()).optional(),langfuseSessionId:z.string().optional(),agentConfigVersion:z.string().optional(),effort:Nt.optional(),cacheBustReason:z.enum(nR).optional()});_i.extend({chunks:i1.array(),description:z.string().describe("Input to pass to AI"),type:z.union([z.literal("locator"),z.literal("assertion"),z.literal("ai-action")]),softTokenLimit:z.number(),mediumTokenLimit:z.number().optional(),hardTokenLimit:z.number(),callId:z.string().optional(),useJev:z.boolean().optional().describe("Score chunks with Jev. Only clients that cut their chunks for Jev send it; left out, the full ranker scores them, which is what older clients get.")});var P2e=z.object({screenshotBase64AfterCommand:z.string(),urlAfterCommand:z.string(),serializedCommand:z.string(),elementInteracted:z.string().optional(),thoughts:z.string().optional()}),jZ=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string(),source:$9.optional().catch(void 0),markIneligibleElementsInChecks:z.boolean().optional(),isTieBreakerCall:z.boolean().optional(),memory:z.discriminatedUnion("type",[$u,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional(),firstPassModelResults:ak.array().optional(),knowledgeBaseSection:z.string().optional()}),zZ=z.object({target:z.string().or(z.number()),browserState:z.string().optional(),screenshot:z.string().optional(),boundingBox:z.object({x:z.number(),y:z.number(),height:z.number(),width:z.number()}).optional()}),HZ=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string().optional(),returnSchema:z.string().optional()}),$Z=z.object({goal:z.string(),emulatorState:z.string(),screenshot:z.string().optional(),returnSchema:z.string().optional()}),a1=z.union([z.literal("NEGATED_CHECK"),z.literal("CONDITIONAL_CHECK")]),GZ=z.object({goal:z.string(),browserState:z.string(),screenshot:z.string(),url:z.string(),contextChoice:Wy.optional(),memory:z.discriminatedUnion("type",[$y,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional(),source:a1.optional(),recoveryHint:z.string().optional(),knowledgeBaseSection:z.string().optional()}),VZ=z.object({command:Sg}),s1=z.object({goal:z.string(),browserState:z.string(),startingScreenshot:z.string().optional(),screenshot:z.string(),url:z.string(),history:P2e.array(),actionHint:z.string().optional(),lastError:z.string().optional()}),WZ=z.object({results:QP.array(),errorMessage:z.string(),errorStack:z.string().optional()}),qZ=z.object({results:QP.array(),goal:z.string(),errorMessage:z.string()}),KZ=z.object({failedResults:QP.array(),nextStepsSerialized:z.string().array(),currentUrl:z.string(),currentPageState:z.string(),currentScreenshot:z.string(),testDescription:z.string().optional()});z.object({description:z.string(),type:z.union([z.literal("locator"),z.literal("assertion"),z.literal("ai-action")]),excerpt:z.string()});var YZ=z.object({type:z.string(),browserContext:z.string(),currentStep:z.string(),screenshot:z.string()}),JZ=z.object({description:z.string(),browserState:z.string().optional(),screenshot:z.string()}),XZ=z.object({description:z.string().optional(),screenshot:z.string(),platform:q9}),k2e=z.enum(["locator","assertion"]);z.object({completionType:k2e,currentGoal:z.string(),pastGoal:z.string().optional(),currentScreenshot:z.string(),pastScreenshot:z.string(),pastResult:z.union([z.boolean(),z.number()])});z.object({goal:z.string()});var QZ=z.object({keywords:z.array(z.string())});var Zu=___default.object({id:___default.guid(),envKey:___default.string().optional(),skipped:___default.boolean().optional(),retries:___default.number().optional()});var Xc=(i=>(i.PRESET="MOBILE_PRESET_STEP",i.MODULE="MOBILE_MODULE_STEP",i.AI_ACTION="MOBILE_AI_ACTION_STEP",i.CONDITIONAL="MOBILE_CONDITIONAL_STEP",i.WHILE_LOOP="MOBILE_WHILE_LOOP_STEP",i))(Xc||{});var Lg=Zu.extend({type:___default.literal("MOBILE_CONDITIONAL_STEP")});var ls=z.object({id:z.string(),name:FP,baseUrl:BP,description:z.string().optional().nullish(),schemaVersion:z.string(),advanced:Us,retries:z.number().optional().nullish(),envs:z.array(yZ).nullish(),parameters:fZ.nullish(),disabled:z.boolean().optional(),labels:z.array(z.string()).optional().catch([]),runAssertions:bk.array().nullish()}),l1=z.enum(["INHERIT","ENABLED","DISABLED"]);var L2e=Us.shape.geolocation.unwrap().partial().superRefine(({latitude:e,longitude:t},o)=>{e!==void 0&&t===void 0&&o.addIssue({code:"custom",message:"Longitude is required when latitude is provided",path:["longitude"]}),t!==void 0&&e===void 0&&o.addIssue({code:"custom",message:"Latitude is required when longitude is provided",path:["latitude"]});}),N2e=Us.shape.proxy.unwrap().partial().superRefine(({server:e,username:t,password:o},n)=>{!e&&(t||o)&&n.addIssue({code:"custom",message:"Proxy host is required when credentials are provided",path:["server"]});}),D2e=Us.extend({failureRecovery:l1.optional(),geolocation:L2e.optional(),proxy:N2e.optional(),slowMoMs:z.union([d$,z.literal(-1)]).optional(),turbo:l1.optional(),useMemory:l1.optional()});ls.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,parameters:true,runAssertions:true}).extend({advanced:D2e});ls.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,advanced:true,parameters:true,runAssertions:true});var F2e=z.object({labels:z.array(z.string()).optional(),outputs:yk.nullish()}),Ir=ls.extend(F2e.shape),B2e=z.object({createdAt:z.coerce.date(),updatedAt:z.coerce.date(),updatedBy:z.string().nullable(),schedule:gk,notification:fk,createdBy:z.string(),organizationId:z.string(),folderId:z.string().nullable().optional()}),U2e=ls.extend(B2e.shape);U2e.extend(oc.shape);var c1=ls.extend(oc.shape);ls.extend(Mp.shape);var j2e="test",z2e="module",H2e="mobile-test",$2e="mobile-module",G2e="test/v2",V2e="module/v2",W2e="mobile-test/v2",q2e="mobile-module/v2";var ze=(l=>(l.TEST=`momentic/${j2e}`,l.MODULE=`momentic/${z2e}`,l.TEST_V2=`momentic/${G2e}`,l.MODULE_V2=`momentic/${V2e}`,l.MOBILE_TEST=`momentic/${H2e}`,l.MOBILE_MODULE=`momentic/${$2e}`,l.MOBILE_TEST_V2=`momentic/${W2e}`,l.MOBILE_MODULE_V2=`momentic/${q2e}`,l))(ze||{});ls.merge(Mp);var K2e=kr.extend({steps:z.array(z.record(z.string(),z.unknown().optional())),schemaVersion:z.string()}),oC=K2e.extend({fileType:z.literal(ze.MODULE)});z.object({test:z.string().describe("YAML for the test, including metadata and steps"),modules:z.record(z.string(),z.string()).describe("Map of module name to YAML for the module")});function wk(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(wk);let t={};for(let[o,n]of Object.entries(e))t[o]=wk(n);return t}var Y2e=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,ZZ=36,Lr=z.union([z.guid().max(ZZ,"V2 IDs must be 36 characters or fewer"),z.string().max(ZZ,"V2 IDs must be 36 characters or fewer").regex(Y2e,"V2 IDs must be lowercase kebab-case, e.g. checkout-flow")],{error:"ID must be a UUID or lowercase kebab-case, e.g. checkout-flow (36 characters max)"});var Rk=_.discriminatedUnion("type",[_.object({type:_.literal("SCREEN")}),_.object({type:_.literal("OPEN_APP")}),_.object({type:_.literal("OPEN_WEBVIEW")})]),$p=_.object({type:_.literal("description"),description:_.string()}),d1=_.object({type:_.literal("CUSTOM_COORDINATES"),startX:_.number().describe("Starting X coordinate in pixels"),startY:_.number().describe("Starting Y coordinate in pixels"),deltaPixels:_.number().describe("Number of pixels to scroll in the specified direction")}),Ck=_.discriminatedUnion("type",[...Rk.options,_.object({type:_.literal("CUSTOM"),target:$p}),d1]);function J2e(e){return e.toLowerCase().replaceAll("_"," ")}function m1(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 J2e(e.type);default:{throw new Error("Unreachable")}}}var X2e=_.object({type:_.literal("coordinates"),xPercent:_.number(),yPercent:_.number()}),Q2e=_.object({type:_.literal("absolute_percent"),x:_.number(),y:_.number()}),QT=_.discriminatedUnion("type",[$p,X2e,Q2e]);var Z2e=_.object({x1:_.number(),y1:_.number(),x2:_.number(),y2:_.number(),tolerance:_.nativeEnum(vl),preciseTolerance:_.boolean().optional()}),eVe=_.object({width:_.number(),height:_.number(),tolerance:_.nativeEnum(vl),preciseTolerance:_.boolean().optional()}),p1=_.object({requiredText:_.string().optional(),requiredAttributes:_.record(_.string(),_.string()).optional(),requiredBounds:_.boolean().optional(),position:Z2e.optional(),shape:eVe.optional()}),e7=_.object({xPath:_.string(),requirements:p1.optional()}),tVe=_.object({type:_.literal("CUSTOM"),target:$p,cache:_.lazy(()=>t7).optional()}),oVe=_.object({pixelDelta:_.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:_.union([Rk,tVe,d1]),direction:_.enum(["up","down"])}),t7=_.object({type:_.literal("NATIVE"),bounds:_.number().array().optional(),resolvedDescription:_.string().optional(),xPath:_.string().optional(),elementOnlySerializedXml:_.string().optional(),scrollDetails:oVe.optional(),requirements:p1.optional(),requiredRelatedElements:e7.array().optional(),memory:$u.optional()}),nVe=_.object({type:_.literal("WEBVIEW"),resolvedDescription:_.string().optional(),xPath:_.string().optional(),browserCache:Kd.optional(),memory:$u.optional()}),Ik=_.union([t7,nVe]);var rVe=_.object({left:_.number(),top:_.number(),right:_.number(),bottom:_.number()});_.object({newViewportBounds:rVe});var iVe=_.object({type:_.literal("CUSTOM"),target:$p,cache:_.lazy(()=>i7).optional()}),o7=_.object({pixelDelta:_.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:_.union([Rk,iVe,d1]),direction:_.enum(["up","down"])}),n7=(o=>(o.Native="native",o.Appium="appium",o))(n7||{}),h1=_.tuple([_.number(),_.number(),_.number(),_.number()]),r7=e7.extend({bounds:h1.optional(),browserCache:Kd.optional()}),i7=_.object({type:_.literal("NATIVE"),bounds:h1.optional(),resolvedDescription:_.string().optional(),sourceTree:_.nativeEnum(n7).optional(),xPath:_.string().optional(),elementOnlySerializedXml:_.string().optional(),scrollDetails:o7.optional(),requirements:p1.optional(),requiredRelatedElements:r7.array().optional(),memory:$u.optional()}),aVe=_.object({type:_.literal("WEBVIEW"),bounds:h1.optional(),resolvedDescription:_.string().optional(),xPath:_.string().optional(),scrollDetails:o7.optional(),browserCache:Kd.optional(),requiredRelatedElements:r7.array().optional(),memory:$u.optional()}),xk=_.discriminatedUnion("type",[i7,aVe]);var jo=(M=>(M.AI_CHECK="AI_CHECK",M.AI_EXTRACT="AI_EXTRACT",M.TAP="TAP",M.TYPE="TYPE",M.PRESS="PRESS",M.PRESS_KEYBOARD="PRESS_KEYBOARD",M.OPEN_APP="OPEN_APP",M.KILL_APP="KILL_APP",M.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",M.SWIPE="SWIPE",M.SCROLL_TO="SCROLL_TO",M.SCREEN_CHECK="SCREEN_CHECK",M.ELEMENT_CHECK="ELEMENT_CHECK",M.VISUAL_DIFF="VISUAL_DIFF",M.DRAG_AND_DROP="DRAG_AND_DROP",M.JAVASCRIPT="JAVASCRIPT",M.REQUEST="REQUEST",M.WAIT="WAIT",M.ADD_FILE="ADD_FILE",M.INSTALL_APP="INSTALL_APP",M.UNINSTALL_APP="UNINSTALL_APP",M.TOGGLE_SETTINGS="TOGGLE_SETTINGS",M.ROTATE_ORIENTATION="ROTATE_ORIENTATION",M.ADB_COMMAND="ADB_COMMAND",M.APPIUM_EXECUTE="APPIUM_EXECUTE",M.SET_CAMERA="SET_CAMERA",M.CLEAR_CAMERA="CLEAR_CAMERA",M.SET_MICROPHONE="SET_MICROPHONE",M.CLEAR_MICROPHONE="CLEAR_MICROPHONE",M.STATE="STATE",M))(jo||{});var Et=___default.object({id:___default.guid(),disableCache:___default.boolean().optional()}),ZT=___default.object({updatedAt:___default.coerce.date().optional(),updatedAtLoggerTags:___default.record(___default.string(),___default.string()).optional()}),Qc=ZT.extend({target:Ik}),_k=ZT.extend({fromTarget:Ik,toTarget:Ik}),um=ZT.extend({target:xk}),a7=ZT.extend({fromTarget:xk,toTarget:xk}),Gp=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 `${Math.round(e.x)}%, ${Math.round(e.y)}%`}};var s7=Et.extend({type:___default.literal("ADB_COMMAND"),command:___default.string(),jsonArgs:___default.string().optional()});var l7=Et.extend({type:___default.literal("OPEN_NOTIFICATION_DRAWER")});var nC=(r=>(r.AIRPLANE_MODE="AIRPLANE_MODE",r.DATA="DATA",r.WIFI="WIFI",r.LOCATION="LOCATION",r))(nC||{}),u7=Et.extend({type:___default.literal("TOGGLE_SETTINGS"),settingsType:___default.nativeEnum(nC)});var m7=Et.extend({type:___default.literal("UNINSTALL_APP"),packageName:___default.string()});var Ok=Et.extend({type:___default.literal("APPIUM_EXECUTE"),command:___default.string(),jsonArgs:___default.string().optional()});var p7=Et.extend({type:___default.literal("ADD_FILE"),file:___default.string(),storageLocation:___default.string()});var Vp=Et.extend({type:___default.literal("AI_CHECK"),assertion:___default.string(),timeoutSecs:___default.number().optional(),contextChoice:Wy.optional(),cache:ZT.extend({memory:$y.optional()}).optional()});var h7=Et.extend({type:___default.literal("AI_EXTRACT"),goal:___default.string(),schema:___default.string().optional()});var f7=Et.extend({type:___default.literal("INSTALL_APP"),uri:___default.string().trim()});var ev=Et.extend({type:___default.literal("JAVASCRIPT"),code:___default.string(),timeout:___default.number().int().max(600).optional().describe("Max seconds for the code to complete")});var y7=Et.extend({type:___default.literal("KILL_APP")});var iC=(o=>(o.HOME="HOME",o.POWER="POWER",o))(iC||{}),Pk=(a=>(a.BACK="BACK",a.APP_SWITCHER="APP_SWITCHER",a.SEARCH="SEARCH",a.VOLUME_UP="VOLUME_UP",a.VOLUME_DOWN="VOLUME_DOWN",a.VOLUME_MUTE="VOLUME_MUTE",a))(Pk||{}),kk=Et.extend({type:___default.literal("PRESS"),key:___default.nativeEnum(iC),longPress:___default.boolean().optional()}),b7=kk.extend({key:___default.nativeEnum(Pk).or(___default.nativeEnum(iC))}),S7=kk;var T7=Et.extend({type:___default.literal("REQUEST")}).merge(aR);var v1=(o=>(o.PORTRAIT="PORTRAIT",o.LANDSCAPE="LANDSCAPE",o))(v1||{}),A7=Et.extend({type:___default.literal("ROTATE_ORIENTATION"),orientation:___default.nativeEnum(v1)});var uVe=___default.object({type:___default.literal("CONTENT"),negated:___default.boolean().optional(),value:___default.string()}),ov=Et.extend({type:___default.literal("SCREEN_CHECK"),assertion:uVe,timeout:___default.number().int().min(0).max(em).optional().describe("max seconds to wait for the assertion to be true")});var E7=Et.extend({type:___default.literal("STATE")});var w7=Et.extend({type:___default.literal("VISUAL_DIFF"),path:___default.string().describe("path to the golden screenshot to compare against"),threshold:___default.number().min(0).max(1).optional().describe("max allowed fraction of differing pixels before the diff fails (default 0.1)")});___default.object({created:___default.boolean(),goldenPath:___default.string(),threshold:___default.number(),goldenScreenshotBase64:___default.string().optional(),currentScreenshotBase64:___default.string().optional(),diffScreenshotBase64:___default.string().optional(),goldenScreenshotSnapshotId:___default.string().optional(),currentScreenshotSnapshotId:___default.string().optional(),diffScreenshotSnapshotId:___default.string().optional(),diffPercent:___default.number().optional(),pass:___default.boolean().optional(),dimensionMismatch:___default.boolean().optional()});var C7=Et.extend({type:___default.literal("WAIT"),timeoutSecs:___default.number()});var aC=___default.discriminatedUnion("type",[E7,Vp,h7,ev,C7,T7,A7,ov,w7,p7,f7,y7]);___default.discriminatedUnion("type",[...aC.options,kk]);var E1=Et.extend({type:___default.literal("DRAG_AND_DROP"),fromTarget:$p,toTarget:$p,hoverDuration:___default.number().optional(),dragDuration:___default.number().optional()}),sC=E1.extend({cache:_k.optional()}),lC=E1.extend({cache:a7.optional()});var w1=Et.extend({type:___default.literal("ELEMENT_CHECK"),target:QT,assertion:xP,timeout:___default.number().int().min(0).max(em).optional().describe("max seconds to wait for the assertion to be true")}),eb=w1.extend({cache:Qc.optional()}),tb=w1.extend({cache:um.optional()});var cC=(o=>(o.ENTER="ENTER",o.BACKSPACE="BACKSPACE",o))(cC||{}),Mk=(t=>(t.CLOSE_KEYBOARD="CLOSE_KEYBOARD",t))(Mk||{}),_7={repeat:___default.number().int().min(1).optional(),keyPressDelayMs:___default.number().min(0).optional()},O7=Et.extend({type:___default.literal("PRESS_KEYBOARD"),key:___default.nativeEnum(cC),..._7}),P7=Et.extend({type:___default.literal("PRESS_KEYBOARD"),key:___default.nativeEnum(Mk).or(___default.nativeEnum(cC)),..._7});var k7=Et.extend({type:___default.literal("OPEN_APP"),packageName:___default.string(),activityName:___default.string().optional(),intentExtras:___default.string().optional()}),M7=Et.extend({type:___default.literal("OPEN_APP"),packageName:___default.string(),intentExtras:___default.string().optional()});var R1=Et.extend({type:___default.literal("SCROLL_TO"),target:$p,direction:___default.enum(["down","up"]),scrollableElement:Ck,scrollStepPercent:___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:___default.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 20.")}),uC=R1.extend({cache:Qc.optional()}),dC=R1.extend({cache:um.optional()});var C1=Et.extend({type:___default.literal("SWIPE"),direction:___default.enum(["up","down","left","right"]),scrollableElement:Ck,viewportPercent:___default.number().optional(),durationMs:___default.number().optional(),relativePosition:CP.optional()}),mC=C1.extend({cache:Qc.optional()}),pC=C1.extend({cache:um.optional()});var I1=Et.extend({type:___default.literal("TAP"),target:QT,longPress:___default.boolean().optional(),longPressDurationMs:___default.number().optional(),iterations:___default.number().optional(),tapDelayMs:___default.number().optional(),relativePosition:CP.optional(),doubleTap:___default.boolean().optional(),doubleTapDelayMs:___default.number().optional()}),hC=I1.extend({cache:Qc.optional()}),gC=I1.extend({cache:um.optional()});var fC=(r=>(r.AUTO="auto",r.PROGRAMMATIC="programmatic",r.LONG_PRESS="long-press",r.BACKSPACE="backspace",r))(fC||{});var x1=Et.extend({type:___default.literal("TYPE"),target:QT.optional(),keyPressDelayMs:___default.number().optional(),waitForKeyboardSettle:___default.boolean().optional(),text:___default.string(),clearContent:___default.boolean().optional(),forceClearContent:___default.boolean().optional(),replaceStrategy:___default.nativeEnum(fC).optional()});var yC=x1.extend({cache:Qc.optional()}),bC=x1.extend({cache:um.optional()});var SC=___default.discriminatedUnion("type",[...aC.options,hC,yC,b7,P7,m7,s7,Ok,sC,l7,uC,mC,u7,eb,k7]);var N7=Et.extend({type:___default.literal("SET_CAMERA"),file:___default.string(),loop:___default.boolean().optional(),playAudio:___default.boolean().optional()}),D7=Et.extend({type:___default.literal("CLEAR_CAMERA")});var F7=Et.extend({type:___default.literal("SET_MICROPHONE"),file:___default.string(),once:___default.boolean().optional()}),B7=Et.extend({type:___default.literal("CLEAR_MICROPHONE")});var vC=___default.discriminatedUnion("type",[...aC.options,gC,bC,S7,O7,M7,pC,lC,dC,tb,Ok,N7,D7,F7,B7]);var Wp=Zu.extend({type:___default.literal("MOBILE_WHILE_LOOP_STEP"),maxIterations:___default.number().int().positive().optional()});var z7=___default.union([___default.string(),___default.record(___default.string(),___default.unknown().optional())]),Fk=Zu.extend({type:___default.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:___default.number().optional()}),nv=Fk.extend({command:SC}),rv=Fk.extend({command:vC}),iv=___default.object({moduleId:___default.string(),inputs:___default.record(___default.string(),___default.string()).optional()}),wC=Zu.merge(iv.extend({type:___default.literal("MOBILE_MODULE_STEP")}));iv.extend({steps:___default.lazy(()=>td.array())});iv.extend({steps:___default.lazy(()=>dm.array())});var _1=(o=>(o.V2="2",o.V3="3",o))(_1||{});var H7="3",O1=___default.nativeEnum(_1),RC=___default.object({status:___default.literal("SUCCESS"),message:___default.string().optional(),results:___default.object({description:___default.string(),status:___default.enum(io),message:___default.string().optional()}).array(),finalScreenshot:Ql.optional()}),AC=___default.lazy(()=>___default.discriminatedUnion("type",[nv,AVe])),EC=___default.lazy(()=>___default.discriminatedUnion("type",[rv,EVe]));var gVe=qd.extend({platform:___default.literal("ANDROID"),resolvedGoal:___default.string(),steps:___default.lazy(()=>AC.array()),lastSuccessfulRun:RC.optional()}),fVe=qd.extend({platform:___default.literal("IOS"),resolvedGoal:___default.string(),steps:___default.lazy(()=>EC.array()),lastSuccessfulRun:RC.optional()}),P1=___default.discriminatedUnion("platform",[gVe,fVe]),Dg=Zu.extend({type:___default.literal("MOBILE_AI_ACTION_STEP"),text:___default.string(),version:O1.optional(),cache:P1.optional(),disableCache:___default.boolean().optional(),precondition:___default.string().optional(),postcondition:___default.string().optional()});var bVe=___default.discriminatedUnion("type",[Vp,ov,eb,ev]),Fg=Fk.extend({command:bVe}),SVe=___default.discriminatedUnion("type",[Vp,ov,tb,ev]),Bg=Fk.extend({command:SVe}),TVe=___default.object({assertion:Fg,steps:___default.lazy(()=>td.array())}),vVe=___default.object({assertion:Bg,steps:___default.lazy(()=>dm.array())}),AVe=Lg.extend({blocks:___default.lazy(()=>___default.object({assertion:Fg,steps:AC.array()}).array()),elseSteps:___default.lazy(()=>AC.array()).optional()}),EVe=Lg.extend({blocks:___default.lazy(()=>___default.object({assertion:Bg,steps:EC.array()}).array()),elseSteps:___default.lazy(()=>EC.array()).optional()}),wVe=Lg.extend({blocks:___default.lazy(()=>TVe.array()),elseSteps:___default.lazy(()=>td.array()).optional()}),RVe=Lg.extend({blocks:___default.lazy(()=>vVe.array()),elseSteps:___default.lazy(()=>dm.array()).optional()}),CVe=Wp.extend({condition:Fg.optional(),steps:___default.lazy(()=>td.array())}),IVe=Wp.extend({condition:Bg.optional(),steps:___default.lazy(()=>dm.array())}),td=___default.discriminatedUnion("type",[nv,wC,Dg,wVe,CVe]),dm=___default.discriminatedUnion("type",[rv,wC,Dg,RVe,IVe]);___default.union([td.array(),dm.array()]);var k1=___default.object({parameterNames:___default.string().array(),defaultParameters:___default.record(___default.string(),___default.string()).optional(),parameterEnums:___default.record(___default.string(),___default.string().array()).optional()}),Bk=___default.object({moduleId:Lr,name:___default.string(),description:___default.string().nullish(),platform:___default.nativeEnum(Kc).optional().default("ANDROID"),parameters:k1.optional(),enabled:___default.boolean().nullish(),schemaVersion:___default.string()}),M1=Bk.omit({name:true}),xVe=M1.extend({steps:z7.array()});___default.object({fileType:___default.literal(ze.MOBILE_MODULE)}).merge(xVe);var $7=Bk.omit({platform:true,schemaVersion:true});({ANDROID:$7.extend({platform:___default.literal("ANDROID"),steps:td.array()}),IOS:$7.extend({platform:___default.literal("IOS"),steps:dm.array()})});var ab=(t=>(t.MODULE="RESOLVED_MOBILE_MODULE",t))(ab||{}),G7=___default.object({description:___default.string().optional(),name:___default.string().describe("name of the module"),parameters:k1.optional()}),V7=iv.merge(G7).extend({platform:___default.literal("ANDROID"),get steps(){return Zc.array()}}),W7=iv.merge(G7).extend({platform:___default.literal("IOS"),get steps(){return eu.array()}});___default.discriminatedUnion("platform",[V7,W7]);var L1=Zu.merge(V7).extend({type:___default.literal("RESOLVED_MOBILE_MODULE")}),N1=Zu.merge(W7).extend({type:___default.literal("RESOLVED_MOBILE_MODULE")});___default.discriminatedUnion("platform",[L1,N1]);var _Ve=___default.object({assertion:Fg,get steps(){return Zc.array()}}),D1=Lg.extend({get blocks(){return _Ve.array()},get elseSteps(){return Zc.array().optional()}}),OVe=___default.object({assertion:Bg,get steps(){return eu.array()}}),F1=Lg.extend({get blocks(){return OVe.array()},get elseSteps(){return eu.array().optional()}}),PVe=Wp.extend({condition:Fg.optional(),get steps(){return Zc.array()}}),kVe=Wp.extend({condition:Bg.optional(),get steps(){return eu.array()}}),Zc=___default.discriminatedUnion("type",[L1,nv,Dg,D1,PVe]),eu=___default.discriminatedUnion("type",[N1,rv,Dg,F1,kVe]);function q7(e){return Object.values(ab).includes(e)||Object.values(Xc).includes(e)}var K7=(a=>(a.PRECONDITION="PRECONDITION",a.REPLAY="REPLAY",a.GENERATE="GENERATE",a.AUTOHEAL="AUTOHEAL",a.POSTCONDITION="POSTCONDITION",a.GOAL_CHECK="GOAL_CHECK",a))(K7||{}),Y7=z.enum(["pending","running","success","failed"]),J7=z.object({type:z.literal("THOUGHT"),text:z.string(),blockId:z.string().optional()}),X7=z.object({type:z.literal("TOOL_CALL"),toolName:z.string()}),Q7=z.object({type:z.literal("PHASE"),phase:z.nativeEnum(K7),failureMessage:z.string().optional()}),MVe=z.object({type:z.literal("STEP_UPDATE"),stepIndex:z.number(),step:Zc,status:Y7,conditionMet:z.boolean().optional(),message:z.string().optional(),afterSnapshotId:z.string().optional()}),LVe=z.object({type:z.literal("STEP_UPDATE"),stepIndex:z.number(),step:eu,status:Y7,conditionMet:z.boolean().optional(),message:z.string().optional(),afterSnapshotId:z.string().optional()}),Z7=z.object({type:z.literal("SCREENSHOT"),stepIndex:z.number(),screenshotId:z.string()}),eee=z.object({type:z.literal("POSTCONDITION_AUTOGENERATED"),postcondition:z.string()}),tee=z.object({type:z.literal("POSTCONDITION_REVISED"),postcondition:z.string(),previousPostcondition:z.string()}),oee=z.object({type:z.literal("GOAL_CHECK"),achieved:z.boolean(),reasoning:z.string(),violatedUserRule:z.boolean().default(false)}),NVe=z.object({type:z.literal("CACHED_STEPS_GENERATED"),cachedSteps:AC.array(),resolvedGoal:z.string(),lastSuccessfulRun:RC.optional()}),DVe=z.object({type:z.literal("CACHED_STEPS_GENERATED"),cachedSteps:EC.array(),resolvedGoal:z.string(),lastSuccessfulRun:RC.optional()}),FVe=z.discriminatedUnion("type",[J7,X7,Q7,MVe,Z7,NVe,eee,tee,oee]),BVe=z.discriminatedUnion("type",[J7,X7,Q7,LVe,Z7,DVe,eee,tee,oee]);function nee(e){let t=z.object({version:z.literal(1),events:e.array(),spans:f$.array().optional()});return z.union([t,e.array()]).transform(o=>Array.isArray(o)?{version:1,events:o}:o)}var ree=nee(FVe),iee=nee(BVe);var tu=___default.object({message:___default.string().optional(),startTime:___default.number(),endTime:___default.number(),status:___default.nativeEnum(io),trace:___default.unknown().optional().optional(),beforeSnapshot:___default.string().optional(),afterSnapshot:___default.string().optional(),data:___default.unknown().optional().optional().describe("output data from the step"),aiSuggested:___default.boolean().optional(),beforeTestContext:HT.optional(),afterTestContext:HT.optional()}),aee=tu.merge(nv).extend({previousAttempts:___default.lazy(()=>Hs.array()).optional()}),UVe=tu.merge(wC).extend({steps:___default.lazy(()=>Hs.array()),name:___default.string().optional(),previousAttempts:___default.lazy(()=>Hs.array()).optional()}),jVe=tu.merge(Dg).extend({steps:___default.lazy(()=>Hs.array()),previousAttempts:___default.lazy(()=>Hs.array()).optional(),failureRecoveryReason:___default.string().optional(),trajectory:ree.optional()}),zVe=tu.merge(D1).extend({assertionResult:aee.optional(),steps:___default.lazy(()=>Hs.array()),previousAttempts:___default.lazy(()=>Hs.array()).optional()}),HVe=tu.merge(Wp).extend({condition:Fg.optional(),steps:___default.lazy(()=>Hs.array()),iterationCount:___default.number().optional(),iterationResultCounts:___default.number().array().optional(),firstIterationConditionSkipped:___default.boolean().optional(),previousAttempts:___default.lazy(()=>Hs.array()).optional()}),Hs=___default.discriminatedUnion("type",[aee,UVe,jVe,zVe,HVe]),see=tu.merge(rv).extend({previousAttempts:___default.lazy(()=>$s.array()).optional()}),$Ve=tu.merge(wC).extend({steps:___default.lazy(()=>$s.array()),name:___default.string().optional(),previousAttempts:___default.lazy(()=>$s.array()).optional()}),GVe=tu.merge(Dg).extend({steps:___default.lazy(()=>$s.array()),previousAttempts:___default.lazy(()=>$s.array()).optional(),failureRecoveryReason:___default.string().optional(),trajectory:iee.optional()}),VVe=tu.merge(F1).extend({assertionResult:see.optional(),steps:___default.lazy(()=>$s.array()),previousAttempts:___default.lazy(()=>$s.array()).optional()}),WVe=tu.merge(Wp).extend({condition:Bg.optional(),steps:___default.lazy(()=>$s.array()),iterationCount:___default.number().optional(),iterationResultCounts:___default.number().array().optional(),firstIterationConditionSkipped:___default.boolean().optional(),previousAttempts:___default.lazy(()=>$s.array()).optional()}),$s=___default.discriminatedUnion("type",[see,$Ve,GVe,VVe,WVe]);var qVe=tu.extend({index:___default.number().optional(),userFacingStepReference:___default.string().optional(),description:___default.string()}),lee=qVe.extend({beforeScreenshot:___default.string().optional(),afterScreenshot:___default.string().optional()});var cee=z.object({attributesRequired:z.array(z.string()).optional(),textRequired:z.boolean().optional(),boundsRequired:z.boolean().optional(),positionSpecificity:z.enum(vl).optional(),shapeSpecificity:z.enum(vl).optional()}),KVe=z.object({id:z.number(),requirements:cee}).array();z.object({thoughts:z.string(),id:z.number(),updatedMemory:tR.optional(),inWebview:z.boolean().optional(),requirements:cee.optional(),additionalElements:KVe.optional()});var YVe=z.literal("SCROLL_TO"),uee=z.object({description:z.string(),screenXml:z.string(),screenshot:z.string(),source:YVe.optional(),memory:z.discriminatedUnion("type",[$u,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional()}),dee=z.object({assertion:z.string(),screenXml:z.string(),screenshot:z.string(),contextChoice:Wy.optional(),knowledgeBaseSection:z.string().optional(),memory:z.discriminatedUnion("type",[$y,z.object({type:z.literal("RESOLVED_TRACES"),traces:z.unknown().optional().array()})]).optional()});z.object({thoughts:z.string(),result:z.boolean(),relevantElements:z.array(z.number()).optional(),updatedMemory:oR.optional(),citations:Kn.array().optional()});var mee=z.object({failedResults:lee.array(),nextStepsSerialized:z.string().array(),currentScreenXml:z.string(),currentScreenshot:z.string(),testDescription:z.string()}),pee=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(pee||{});z.object({thoughts:z.string(),scenario:z.enum(pee),instructions:z.string().nullish(),reasonSummary:z.string().nullish()});var JVe=new Set(["gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]);function hee(e){return JVe.has(e)}z.looseObject({type:z.literal("response.create")});var gee=z.union([z.looseObject({response:z.looseObject({id:z.string()}),sequence_number:z.number(),type:z.literal("response.completed")}),z.looseObject({code:z.string().nullable(),message:z.string(),sequence_number:z.number(),type:z.literal("error")})]);var sb="1",fee=z.enum(["GENERATED","CACHE"]),B1=fee.enum,yee=z.enum(["PULL_REQUEST","DIRECT_COMMIT","PATCH","LOCAL_CHANGES","OWNER_PULL_REQUEST","ALREADY_FIXED_ELSEWHERE"]),qp=yee.enum,XVe=z.object({patchId:z.uuid(),sourceRunId:z.string().min(1).optional(),testId:z.string().min(1),testPath:z.string().min(1),writtenPaths:z.array(z.string().min(1)).min(1).optional(),environment:z.string().min(1).optional()}),QVe=z.object({applicationId:z.uuid(),patchId:z.uuid(),sourceRunId:z.string().min(1).optional(),source:fee,delivery:yee,environment:z.string().min(1).optional(),repository:z.string().min(1).optional(),baseBranch:z.string().min(1).optional(),headBranch:z.string().min(1).optional(),prNumber:z.int().positive().optional(),commitSha:z.string().min(1).optional(),appliedAt:z.iso.datetime().optional(),patchedTestBundleHash:z.string().min(1).optional(),baseTestBundleHash:z.string().min(1).optional()});z.object({patches:z.array(XVe).max(1e3),applications:z.array(QVe).max(1e3)});var ZVe=200,eWe=50,tWe=z.object({testId:z.string().min(1),patchIds:z.array(z.string().min(1)).max(eWe).min(1)});z.object({repository:z.string().min(1),baseBranch:z.string().min(1),excludeHeadBranch:z.string().min(1).optional(),failures:z.array(tWe).min(1).max(ZVe)});var bee=z.object({existingFixes:z.array(PH)});var See="ui_states.jsonl";z.object({stepId:z.string(),parentStepIdChain:z.array(z.string()),fingerprintHash:z.string(),minhash:z.array(z.number().int()),canonicalUrl:z.string(),capturedAt:z.number().describe("Unix timestamp in milliseconds"),archivalFingerprintHash:z.string().optional(),archivalMinhash:z.array(z.number().int()).optional()});var oWe=z.object({testId:z.string(),name:z.string(),relativeFilePath:z.string(),coverage:z.string(),note:z.string().optional()}),nWe=z.object({name:z.string(),summary:z.string(),status:z.string().optional(),existingCoverage:z.array(oWe).default([])}),rWe=z.object({name:z.string(),summary:z.string(),importance:z.string().optional(),relatedJourney:z.string().optional(),mode:z.string().optional(),preconditions:z.array(z.string()).default([]),outline:z.array(z.string()).default([]),acceptanceCriteria:z.array(z.string()).default([]),existingTestId:z.string().optional(),existingTestPath:z.string().optional(),customAttributes:z.record(z.string(),z.unknown()).optional()}),iWe=z.object({testPlanName:z.string(),status:z.string(),testPath:z.string().optional(),summary:z.string(),notes:z.array(z.string()).optional()}),aWe=z.object({status:z.string(),builtTests:z.array(iWe).default([]),summary:z.string().optional(),notes:z.string().optional()}),sWe=z.object({control:z.string(),status:z.string(),result:z.string()}),lWe=z.object({testPlanName:z.string(),status:z.string(),summary:z.string(),verified:z.array(z.string()).default([]),gaps:z.array(z.string()).default([]),reportedBugs:z.array(z.string()).default([]),controls:z.array(sWe).default([]),customAttributes:z.record(z.string(),z.unknown()).optional()}),cWe=z.object({status:z.string(),planReports:z.array(lWe).default([]),summary:z.string().optional(),notes:z.string().optional()});z.object({summary:z.string().optional(),changedJourneys:z.array(nWe).default([]),testPlans:z.array(rWe).default([]),buildSummary:aWe.optional(),bugbashSummary:cWe.optional()});var uWe=z.object({agentId:z.string().optional(),video:z.string().optional(),startedAt:z.number().optional(),finishedAt:z.number().optional(),videoStartMs:z.number().optional(),videoEndMs:z.number().optional()});z.object({name:z.string(),summary:z.string(),expected:z.string(),actual:z.string(),severity:z.string().optional(),reproSteps:z.array(z.string()).default([]),recording:uWe.optional()});function Tee(e){return [...new Map(e.map(t=>[t.name,t])).values()]}var lb=(d=>(d.TestRun="test-run",d.MobileTestRun="mobile-test-run",d.CreditsUsed="credits-used",d.CreditsUsedV2="credits-used-v2",d.StepsExecuted="steps-executed",d.LLMTokensUsed="llm-tokens-used",d.AIAgentInvocation="ai-agent-invocation",d.AITriageTestResult="ai-triage-test-result",d.SandboxRuntimeSecondsUsed="sandbox-runtime-seconds-used",d.HostedBrowserSecondsUsed="hosted-browser-seconds-used",d.LimrunEmulatorSessionMinutesUsed="limrun-emulator-session-minutes-used",d))(lb||{}),Ug=(r=>(r.Select="select",r.Classify="classify",r.Triage="triage",r.Mo="mo",r))(Ug||{}),av=(r=>(r.Fixed="fixed",r.CannotFix="cannot-fix",r.NoFixNeeded="no-fix-needed",r.Error="error",r))(av||{}),us=(d=>(d.TestRunner="test-runner",d.Editor="editor",d.Mcp="mcp",d.Mo="mo",d.Select="ai-select",d.Explore="explore",d.Heal="heal",d.ResultClassification="result-classification",d.GithubPrSummary="github-pr-summary",d.AppGraph="app-graph",d.RunViewer="run-viewer",d))(us||{}),vee="sessionId";var dWe=3;function mWe(e){return e==="MODULE"||e==="CONDITIONAL"||e==="WHILE_LOOP"||e==="SECTION"||e==="RESOLVED_MODULE"}function Aee(e){if(!mWe(e))switch(e){case "PRESET_ACTION":return 0;case "AI_ACTION":return 3;case "AI_ACTION_DYNAMIC":return 5;default:(o=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}function Uk(e){switch(e.type){case "AI_EXTRACT":case "AI_ASSERTION":return dWe;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:(o=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}var U1=z.object({name:z.string(),value:z.string(),url:z.string().optional(),domain:z.string().optional(),path:z.string().optional(),expires:z.number().default(Date.now()/1e3+60*60*24*365),httpOnly:z.boolean().optional(),secure:z.boolean().default(true),sameSite:z.union([z.literal("Strict"),z.literal("Lax"),z.literal("None")]).default("None")});function jk(e,t){let o=[],n=splitCookiesString(e);for(let r of n){let i=parseString(r,{decodeValues:false});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=false),!i.path&&i.domain&&(i.path="/"),!i.domain&&t&&(i.domain=t);let s=U1.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});o.push(s);let l=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),c=r.match(/\b(\S+)=([^;]*)/g);if(c)for(let u of c){let[d,m]=u.split("=");if(!d||!m)throw new Error(`Invalid key-value pair in cookie: ${u}`);l.includes(d.toLowerCase())||o.push({...s,name:d,value:m});}}return o}var gWe=z.object({origin:z.string(),localStorage:z.array(z.object({name:z.string(),value:z.string()})),sessionStorage:z.array(z.object({name:z.string(),value:z.string()})).optional()}),fWe=z.object({entries:z.record(z.string(),z.array(z.tuple([z.unknown().optional(),z.unknown().optional()]))),version:z.number().optional(),stores:z.record(z.string(),z.object({keyPath:z.union([z.string(),z.array(z.string())]).nullable(),autoIncrement:z.boolean(),indexes:z.array(z.object({name:z.string(),keyPath:z.union([z.string(),z.array(z.string())]),unique:z.boolean(),multiEntry:z.boolean()}))})).optional()}),zk=z.object({cookies:U1.array().optional(),origins:gWe.array().optional(),idb:z.record(z.string(),fWe).optional().describe("key is db name")});function Eee(e,t){let o=[];return e.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let r=U1.safeParse({name:n.key,...n});if(!r.success)return;let i=r.data;!i.domain&&!i.url&&(i.domain=t),o.push(i);}),o}var Ol={type:true,cache:true},wee=[Vp.pick(Ol),eb.pick(Ol),hC.pick(Ol),yC.pick(Ol),mC.pick(Ol),uC.pick(Ol),sC.pick(Ol)],j1=___default.discriminatedUnion("type",wee),Ree=[Vp.pick(Ol),tb.pick(Ol),gC.pick(Ol),bC.pick(Ol),pC.pick(Ol),lC.pick(Ol),dC.pick(Ol)],z1=___default.discriminatedUnion("type",Ree);Object.values(jo).filter(e=>wee.some(t=>t.shape.type.safeParse(e).success));Object.values(jo).filter(e=>Ree.some(t=>t.shape.type.safeParse(e).success));var H1=___default.object({type:___default.literal("MOBILE_AI_ACTION_STEP"),cache:P1}),Hk=___default.union([j1,H1]),$k=___default.union([z1,H1]);var $1=(a=>(a.US_EAST_1="us-east1",a.US_EAST_2="us-east2",a.US_WEST_1="us-west1",a.US_WEST_2="us-west2",a.EU_NORTH_1="eu-north1",a.AS_SOUTH_1="as-south1",a))($1||{}),Gk=(n=>(n.US="us",n.EU="eu",n.AS="as",n))(Gk||{}),Cee=(t=>(t.LOCAL="local",t))(Cee||{}),IC=___default.nativeEnum(Gk),G1=___default.nativeEnum($1).or(___default.nativeEnum(Gk)),V1=___default.nativeEnum($1).or(___default.nativeEnum(Gk)).or(___default.nativeEnum(Cee)),bWe="closest";V1.or(___default.literal(bWe));var lv=(o=>(o.ANDROID_14="14",o.ANDROID_15="15",o))(lv||{});var Vk=(t=>(t.IOS_26="26",t))(Vk||{});var SWe=["1.56.1-lim.1","1.60.0-lim.1"],Iee=___default.enum(SWe);var xee=___default.nativeEnum(lv).or(___default.nativeEnum(Vk));var TWe=___default.object({disableMomenticAccessibilityTree:___default.boolean().optional(),autoGrantPermissions:___default.boolean().optional().describe("Automatically grant app permission prompts during the run. Android only."),autoAcceptAlerts:___default.boolean().optional().describe("Automatically accept native alert dialogs. iOS only."),autoDismissAlerts:___default.boolean().optional().describe("Automatically dismiss native alert dialogs. iOS only."),disableXmlSnapshots:___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:YT.optional(),locale:___default.string().optional().describe("Device locale code (e.g. 'fr', 'en-us'). Sets the device language and region. iOS and Android.")}),vWe="avdId",AWe="iosDeviceType",EWe="iosVersion",wWe="localEmulatorStartTimeout",_ee=___default.number().int().positive(),RWe=___default.object({downloadKbps:_ee.optional().describe("Maximum download bandwidth in kilobits per second."),uploadKbps:_ee.optional().describe("Maximum upload bandwidth in kilobits per second.")}),CWe=___default.object({selectors:___default.array(___default.string().trim().min(1,"Tunnel destinations cannot be blank.")).min(1,"Enter at least one tunnel destination.").describe("Required destinations to route through the CLI runner: domains, wildcard subdomains (which exclude the root domain), or IP/localhost:port destinations. URLs and catch-all wildcards are not supported."),capture:___default.boolean().optional().describe("Record HTTP(S) requests and responses for tunneled traffic. Defaults to false. View captured traffic in the run's Network tab. HTTPS inspection may break certificate-pinned apps.")}),W1=TWe.extend({tunnel:___default.union([___default.literal(false),CWe]).optional().describe("Route selected traffic from hosted mobile CLI emulators through the CLI runner. Off by default; set false to disable a project-level tunnel. Enable capture to save HTTP(S) network logs."),enableLogcatCapture:___default.boolean().optional().describe("Enable Android emulator logcat capture. This is disabled by default to reduce log streaming overhead and emulator lag."),enableSyslogCapture:___default.boolean().optional().describe("Enable iOS simulator syslog capture. This is disabled by default to reduce log streaming overhead and simulator lag."),region:V1.optional().describe('Where the emulator runs: "local" for an emulator on your machine, or a region for hosted emulators. Defaults to hosted emulators.'),jurisdiction:IC.optional().describe('Pin hosted emulators to a single jurisdiction: "us", "eu", or "as". Emulators may run in any data center within that jurisdiction, but never outside it: unlike region, this is a hard constraint, and emulator creation fails instead of falling back to another jurisdiction.'),smartWaitingTimeoutMs:___default.number().optional().refine(e=>e===void 0||e>=0,{message:"Smart waiting timeout must not be negative"}).describe("Budget for every wait and retry on an interaction: settling the screen, the readiness check before an AI locate, and retrying a cached target. In milliseconds. Defaults to 5000."),remoteEmulatorSettings:___default.object({androidVersion:___default.nativeEnum(lv).optional()}).optional(),localEmulatorSettings:___default.object({[vWe]:qT,[AWe]:qT,[EWe]:qT}).optional(),[wWe]:___default.number().positive().optional().describe("How long to wait for a local emulator or simulator to finish starting, in milliseconds. Defaults to 300000. Raise this on slow machines such as hosted CI runners."),geolocation:___default.object({latitude:___default.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:___default.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),networkConditions:RWe.optional().describe("Limit the emulator's Wi-Fi bandwidth for the whole run, in kilobits per second. Hosted Android emulators only."),waitForStability:___default.boolean().optional().describe("Wait for the screen to settle after every step that can change it. Off by default. Does not affect the waits before targeting: an AI locate always waits for a ready screen, and a cached target is retried until the smart-waiting timeout either way."),elementCheckTimeoutSeconds:___default.number().int().min(0).max(em).optional().describe("Default max seconds to wait for element check assertions to be true. Element check steps with an explicit timeout are unaffected."),keyPressDelayMs:___default.number().min(0).max(1e3).optional().describe("Default delay in milliseconds between key presses for type steps. Steps with an explicit key press delay are unaffected.")});var xC=___default.object({retries:___default.number().optional().describe("number of retries to run"),defaultChannel:___default.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:___default.string().optional().describe("Default app artifact tag or alias to use. If not set, the latest available tag is used."),defaultEnv:___default.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:qT.describe("APK to install when using the emulator in the local region."),defaultAppFilePath:qT.describe("App file (e.g. .app or .ipa) to install when using the emulator in the local region."),emulator:W1.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:Z$.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),Oee=___default.object({id:Lr,description:___default.string(),schemaVersion:___default.string(),settings:xC.optional(),disabled:___default.boolean().optional(),labels:___default.array(___default.string()).optional()}),cv=Oee.extend({platform:___default.literal("ANDROID").optional().default("ANDROID")}),uv=Oee.extend({platform:___default.literal("IOS")}),Pee=___default.discriminatedUnion("platform",[cv,uv]),kee=___default.object({fileType:___default.literal(ze.MOBILE_TEST)}),Mee=kee.merge(cv),Lee=kee.merge(uv);___default.discriminatedUnion("platform",[Mee,Lee]);var Nee=cv.merge(___default.object({steps:___default.array(td)})),Dee=uv.merge(___default.object({steps:___default.array(dm)}));___default.discriminatedUnion("platform",[Nee,Dee]);var IWe=Mee.merge(Nee),xWe=Lee.merge(Dee);___default.discriminatedUnion("platform",[IWe,xWe]);___default.object({name:___default.string(),steps:___default.array(td).optional(),settings:xC.optional()});var Fee=cv.extend({steps:Zc.array(),beforeSteps:Zc.array().optional(),afterSteps:Zc.array().optional()}),Bee=uv.extend({steps:eu.array(),beforeSteps:eu.array().optional(),afterSteps:eu.array().optional()});___default.discriminatedUnion("platform",[Fee,Bee]);var _We=Fee.extend({name:___default.string()}),OWe=Bee.extend({name:___default.string()});___default.discriminatedUnion("platform",[_We,OWe]);var Sa=___default.object({startTime:___default.number(),endTime:___default.number().optional(),durationMs:___default.number().optional(),error:___default.string().optional(),result:___default.unknown().optional().optional(),attributes:___default.record(___default.string(),___default.unknown().optional()),subSpans:___default.lazy(()=>KWe.array())});var _C=Sa.extend({type:___default.literal("SECTION"),name:___default.string()}),PWe=Sa.extend({type:___default.literal("GET_PAGE_STATE")}),kWe=Sa.extend({type:___default.literal("GET_PAGE_SCREENSHOT")}),MWe=Sa.extend({type:___default.literal("SMART_WAITING")}),LWe=Sa.extend({type:___default.literal("SCROLL_ELEMENT_INTO_VIEW")}),NWe=Sa.extend({type:___default.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:___default.string().optional(),result:___default.object({id:___default.number(),thoughts:___default.string(),citations:Kn.array().optional()}).optional()}),DWe=Sa.extend({type:___default.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:___default.string().optional(),elementScreenshotSnapshotId:___default.string().optional(),result:___default.object({thoughts:___default.string(),result:___default.boolean(),citations:Kn.array().optional()}).optional()}),FWe=Sa.extend({type:___default.literal("AI_EXTRACTION_CALL"),screenshotSnapshotId:___default.string().optional(),browserStateSnapshotId:___default.string().optional(),result:___default.object({thoughts:___default.string().optional(),result:___default.unknown().optional().optional()}).optional()}),BWe=Sa.extend({type:___default.literal("ELEMENT_ASSERTION"),name:___default.string(),result:___default.object({success:___default.boolean(),message:___default.string().optional()}).optional()}),UWe=Sa.extend({type:___default.literal("BROWSER_INTERACTION"),name:___default.string(),coordinates:___default.object({x:___default.number(),y:___default.number()}).optional(),value:___default.string().optional(),selector:___default.string().optional()}),jWe=Sa.extend({type:___default.literal("CACHE_RESOLUTION"),resolutionMethod:___default.string().optional(),cacheMissReason:___default.nativeEnum(gT).optional(),targetSource:___default.string().optional(),elementScreenshotSnapshotId:___default.string().optional(),evaluationDurationMs:___default.number().optional(),resolutionAttempts:___default.number().optional(),result:___default.object({serializedElement:___default.string()}).optional()}),zWe=Sa.extend({type:___default.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:___default.string().optional(),result:___default.object({serializedElement:___default.string()}).optional()}),HWe=Sa.extend({type:___default.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:___default.string().optional(),result:___default.object({outcome:___default.string(),logs:___default.string().array().optional(),serializedElement:___default.string().optional(),relativeClickPoint:___default.object({x:___default.number(),y:___default.number()}).optional(),force:___default.boolean().optional()}).optional()}),$We=Sa.extend({type:___default.literal("WAIT_FOR_STABILITY")}),GWe=Sa.extend({type:___default.literal("GENERIC"),name:___default.string()}),VWe=Sa.extend({type:___default.literal("PAGE_ASSERTION"),name:___default.string(),result:___default.object({success:___default.boolean(),message:___default.string().optional()}).optional()}),WWe=Sa.extend({type:___default.literal("AUTO_FOLLOW_NEW_TABS"),result:___default.object({followed:___default.boolean()}).optional()}),qWe=Sa.extend({type:___default.literal("VISUAL_DIFF"),name:___default.string(),result:___default.object({success:___default.boolean(),message:___default.string().optional()}).optional()});function Uee(e){return e.type==="CACHE_RESOLUTION"||e.type==="TARGET_RESOLUTION"}var KWe=___default.discriminatedUnion("type",[_C,PWe,kWe,MWe,LWe,NWe,DWe,FWe,BWe,UWe,zWe,jWe,HWe,$We,VWe,qWe,GWe,WWe]);z.object({testId:z.string(),sessionId:z.string()});var jee=z.object({uploadUrl:z.string(),id:z.string()});new Set(Object.values(jn));var On={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.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",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 YWe=z.string().refine(e=>Ph.valid(e),{error:"must be a valid semver string"});function q1(e){return Ph.parse(e)||void 0}function OC(e){if(e!==void 0)return e===true||e==="true"||e==="1"}function Hee(e){if(e!=="true"&&e!=="false")throw new ae(`Expected true or false, got "${e}".`);return e==="true"}var $ee="on-fail";function K1(e){return e==="on-fail"?"on-fail":e==="false"?false:!!e}var Gee=(o=>(o.CLI="cli",o.MobileCLI="mobile-cli",o))(Gee||{}),JWe=z.nativeEnum(Gee),Vee=(n=>(n.Error="error",n.Warn="warn",n.Info="info",n))(Vee||{}),XWe=z.nativeEnum(Vee),QWe=z.object({id:z.string(),level:XWe,versionRange:z.string(),announcement:z.string()});z.object({cliType:JWe,version:YWe});var Wee=z.object({announcements:z.array(QWe)});var PC=55555,Wk="momentic-code-eval.js";z.object({body:z.string(),to:z.string(),from:z.string()});z.object({from:z.string().optional(),to:z.string(),timeout:z.number().optional(),beforeDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional()});z.object({timeoutMs:z.number().nonnegative().optional()}).optional();z.object({phoneNumber:z.string(),leaseToken:z.string()});var ZWe=z.union([z.string(),z.date()]).transform(e=>e instanceof Date?e:new Date(e)),qee=z.object({phoneNumber:z.string(),expiresAt:ZWe,leaseToken:z.string()});z.object({to:z.email(),from:z.string(),subject:z.string(),body:z.string(),html:z.string().optional()});z.object({inbox:z.string().transform(e=>e.toLowerCase()),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),timeout:z.number().optional(),trimWhitespace:z.boolean().optional()});z.object({inbox:z.string(),limit:z.number().optional(),afterDate:z.string().pipe(z.coerce.date()).or(z.date()).optional(),trimWhitespace:z.boolean().optional()});var Kee=z.object({email:z.string(),prefix:z.string(),expiresAt:z.coerce.date()}),qk=(o=>(o.RAW="RAW",o.RESPONSE="RESPONSE",o))(qk||{}),Yee=z.object({body:z.string().nullish(),status:z.number().optional(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}),eqe=z.object({url:z.string(),options:z.object({method:z.string(),body:z.string().nullish(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}).optional()}).optional(),tqe=z.object({body:z.string().nullish(),options:z.object({status:z.number(),statusText:z.string().optional(),headers:z.array(z.tuple([z.string(),z.string()])).optional()}).optional()}).optional(),Jee=z.object({result:z.unknown().optional(),variableUpdates:z.record(z.string(),z.unknown().optional()).optional(),persistentVariableUpdates:z.record(z.string(),z.unknown().optional()).optional(),error:z.string().optional(),success:z.boolean()});z.object({id:z.string().optional(),orgId:z.string(),momenticLambdaAuthHash:z.string(),momenticLambdaAuthTimestamp:z.number(),code:z.string(),fragment:z.boolean(),state:z.object({env:z.record(z.string(),z.unknown().optional()),request:eqe,response:tqe,additionalBindings:z.record(z.string(),z.unknown().optional()).optional()}),timeoutMs:z.number().optional(),disallowVariableUpdates:z.boolean().optional(),responseSerialization:z.enum(qk).optional()});var jg=9e4;function Xee({orgId:e,timestamp:t}){return `${e}:${t}`}var oqe=_.object({url:_.string(),lineNumber:_.number(),columnNumber:_.number()}),Qee=_.object({timestamp:_.number(),text:_.string(),type:_.string(),tabIndex:_.number(),args:_.unknown().optional().array().optional(),url:_.string().optional(),location:oqe.optional()}),Zee=Qee.array(),kC=Zee.array();var MC=class{async getConsoleLogsForRunAttempt(t,o,n){}async getNetworkLogsForRunAttempt(t,o,n){}async getHtmlSnapshot(t,o){}async getA11yTreeSnapshot(t,o){}async getScreenshot(t,o){}async storeConsoleLogsForRunAttempt(t,o,n,r){}async storeNetworkLogsForRunAttempt(t,o,n,r){}listVideoAssetPaths(){return []}close(){}async storeScreenshot(t,o,n){}async storeOnDemandScreenshotById(t,o,n,r){}async storeHtmlSnapshot(t,o,n){}};var Kk=1e3,Y1=1e6,nqe=["image","font","video","audio"],rqe=["javascript"],iqe=["text"],aqe=["json","xml","html"];function J1(e){let[t,o]=e.split("/");return t&&nqe.includes(t)||o&&rqe.some(n=>o.includes(n))?false:!!(t&&iqe.includes(t)||o&&aqe.some(n=>o.includes(n)))}var sqe=z.object({name:z.string(),version:z.string(),comment:z.string().optional()}),lqe=z.object({name:z.string(),version:z.string(),comment:z.string().optional()}),cqe=z.object({onContentLoad:z.number().optional(),onLoad:z.number().optional(),comment:z.string().optional()}),LC=z.object({startedDateTime:z.string(),id:z.string(),title:z.string().optional(),pageTimings:cqe,comment:z.string().optional()}),uqe=z.array(LC),dqe=z.object({name:z.string(),value:z.string(),path:z.string().optional(),domain:z.string().optional(),expires:z.string().optional(),httpOnly:z.boolean().optional(),secure:z.boolean().optional(),comment:z.string().optional()}),tte=z.array(dqe),mqe=z.object({name:z.string(),value:z.string(),comment:z.string().optional()}),ote=z.array(mqe),pqe=z.object({name:z.string(),value:z.string(),comment:z.string().optional()}),hqe=z.array(pqe),gqe=z.object({name:z.string(),value:z.string().optional(),fileName:z.string().optional(),contentType:z.string().optional(),comment:z.string().optional()}),fqe=z.array(gqe),yqe=z.object({mimeType:z.string(),params:fqe,text:z.string(),comment:z.string().optional(),_redactedReason:z.string().optional()}),bqe=z.object({method:z.string(),url:z.string(),httpVersion:z.string().optional(),cookies:tte,headers:ote,queryString:hqe,postData:yqe.optional(),headersSize:z.number().optional(),bodySize:z.number().optional(),comment:z.string().optional()}),Sqe=z.object({size:z.number().optional(),compression:z.number().optional(),mimeType:z.string().optional(),text:z.string().optional(),encoding:z.string().optional(),comment:z.string().optional(),_redactedReason:z.string().optional()}),Tqe=z.object({status:z.number(),statusText:z.string(),httpVersion:z.string().optional(),cookies:tte,headers:ote,content:Sqe,redirectURL:z.string().optional(),headersSize:z.number().optional(),bodySize:z.number().optional(),comment:z.string().optional(),_mocked:z.boolean().optional()}),ete=z.object({expires:z.string().optional(),lastAccess:z.string(),eTag:z.string(),hitCount:z.number(),comment:z.string().optional()}),vqe=z.object({beforeRequest:ete.optional(),afterRequest:ete.optional(),comment:z.string().optional()}),Aqe=z.object({blocked:z.number().optional(),dns:z.number().optional(),connect:z.number().optional(),send:z.number(),wait:z.number(),receive:z.number(),ssl:z.number().optional(),comment:z.string().optional()}),Kp=z.object({pageref:z.string().optional(),startedDateTime:z.string(),time:z.number().optional(),request:bqe,response:Tqe.optional(),cache:vqe.optional(),timings:Aqe,serverIPAddress:z.string().optional(),connection:z.string().optional(),comment:z.string().optional(),_resourceType:z.string().optional(),_responseState:z.enum(["pending","received","finished","failed"]).optional()});function X1(e){return e._responseState?e._responseState==="finished"||e._responseState==="failed":!!e.response}var Eqe=z.array(Kp),wqe=z.object({version:z.string().default("1.1"),creator:sqe.optional(),browser:lqe.optional(),pages:uqe.optional(),entries:Eqe,comment:z.string().optional()}),Q1=z.object({log:wqe});z.record(z.string(),LC);z.record(z.string(),Kp);function Z1(e,t){return {log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(e).sort((o,n)=>new Date(o.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(t).sort((o,n)=>new Date(o.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}var nte=3,rte=z.object({failureCount:z.number().int().nonnegative(),lastSuccess:z.object({actionSummary:z.string().min(1),recordedAt:z.coerce.date()}).optional()}),Rqe=z.object({stepId:z.string().min(1),baseTestFileHash:z.string().min(1),branchName:z.string().min(1).optional(),environment:z.string().min(1).optional()}),Cqe={runId:z.string().min(1).optional()},Iqe=Rqe.extend(Cqe);Iqe.extend({succeeded:z.boolean(),actionSummary:z.string().min(1).optional()});var Yk=(L=>(L.DisableClickhouseCaches="disable_clickhouse_caches",L.ShowZeroOpacityElements="show_zero_opacity_elements",L.VisualActions="visual_actions",L.RagV2="rag_v2",L.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",L.GlobalLocatorRedirect="global_locator_redirect",L.FakerConstantSeed="faker_constant_seed",L.AutoExpandIframes="auto_expand_iframes",L.MobileNewAiActionStepsUseV3="mobile_new_ai_action_steps_use_v3",L.PerformanceInsights="performance_insights",L.ShowKnowledgeBase="show_knowledge_base",L.AppGraphBackend="app_graph_backend",L.AppGraphUI="app_graph_ui",L.ClassificationUI="classification_ui",L.HealingUI="healing_ui",L.ExploreUI="explore_ui",L.SlackNotifications="slack_notifications",L.SlackNotificationDms="slack_notification_dms",L.HealTraceUI="heal_trace_ui",L.ExploreTraceUI="explore_trace_ui",L.LinearIntegration="linear_integration",L.AtlassianIntegration="atlassian_integration",L.PosthogIntegration="posthog_integration",L.QaseIntegration="qase_integration",L.HostingIntegrations="hosting_integrations",L.TestinyIntegration="testiny_integration",L.TestRailIntegration="testrail_integration",L.RunAssertions="run_assertions",L.Mo="mo",L.MoSignupCredits="mo_signup_credits",L.MoMobile="mo_mobile",L))(Yk||{});var zg=z.union([z.string(),z.number(),z.boolean(),z.null(),z.record(z.string(),z.lazy(()=>zg)),z.array(z.lazy(()=>zg))]),cb=class{flags;payloads;constructor(t,o){this.flags=t,this.payloads=o;}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(([o,n])=>{typeof n=="boolean"&&Object.values(Yk).includes(o)&&(t[o]=this.isBooleanFlagEnabled(o));}),t}getAllFlagPayloads(){return cloneDeep(this.payloads)}getFlagPayload(t){let o=this.payloads[t];if(o!==void 0){if(typeof o=="string")try{return JSON.parse(o)}catch{return o}return o}}refresh(){throw new Error("Not implemented")}};var eG={".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",".caf":"audio/x-caf",".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",".m4a":"audio/mp4",".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"},ate=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var lte=z.discriminatedUnion("operation",[z.object({operation:z.literal("upsert"),path:z.string().min(1),content:z.string()}),z.object({operation:z.literal("delete"),path:z.string().min(1)})]),xqe=z.object({baseSha:z.string().min(1),headSha:z.string().min(1)}),_qe=z.object({baseBranch:z.string().min(1).max(255),baseCommitSha:z.string().min(1),expectedHeadSha:z.string().min(1).nullable().optional(),expectedBaseSha:z.string().min(1).optional(),headBranch:z.string().min(1).max(255).optional(),branchPrefix:z.string().min(1).max(255).optional(),idempotencyKey:z.string().min(1).optional()}),Oqe=5,Pqe=z.object({commitMessage:z.string().min(1),title:z.string().min(1),body:z.string(),reviewers:z.array(z.string().min(1)).optional(),teamReviewers:z.array(z.string().min(1)).optional(),fallbackReviewers:z.array(z.string().min(1)).max(Oqe).optional(),draft:z.boolean().optional()});_qe.extend(Pqe.shape).extend({changes:z.array(lte).min(1),coAuthorRange:xqe.optional(),requestCommitAuthorsAsReviewers:z.boolean().optional(),assignCommitAuthorsAsAssignees:z.boolean().optional(),assignees:z.array(z.string().min(1)).optional(),omitBaseCommitCoAuthors:z.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 cte=z.object({pullRequestUrl:z.url(),pullRequestNumber:z.number(),headBranch:z.string(),commitSha:z.string(),created:z.boolean(),authors:z.array(Hw).optional(),assignees:z.array(z.string()).optional(),reviewers:z.array(z.string()).optional()});z.object({branch:z.string().min(1).max(255),expectedHeadSha:z.string().min(1).optional(),commitMessage:z.string().min(1),changes:z.array(lte).min(1)});var ute=z.object({branch:z.string(),commitSha:z.string(),committed:z.boolean()});z.object({usernames:z.array(z.string().min(1)).min(1).max(50)});var dte=z.object({usernamesWithMergeAccess:z.array(z.string())}),mte=z.object({shas:z.array(z.string().min(1)).min(1).max(20)}),pte=z.object({authorsBySha:z.record(z.string(),z.array(Hw)),filesBySha:z.record(z.string(),z.array(z.string())).optional(),candidatesBySha:z.record(z.string(),z.array(z.object({githubLogin:z.string(),via:z.string(),isApp:z.boolean().optional()}))).optional(),touchedPaths:z.array(z.string())});z.object({query:z.string().min(1).max(256)});var oG=z.object({number:z.number(),title:z.string(),state:z.enum(["open","merged","closed"]),authorLogin:z.string().optional(),updatedAt:z.string().optional(),htmlUrl:z.string().optional(),body:z.string().optional(),changedPaths:z.array(z.string()).optional()}),hte=z.object({pullRequests:z.array(oG),scanned:z.number(),truncated:z.boolean()}),gte=z.object({authorLogin:z.string().min(1).optional(),authorIsBot:z.boolean().optional(),humanAssigneeLogins:z.array(z.string().min(1)).optional()}),fte=gte.extend({issueNumber:z.number(),htmlUrl:z.url(),headBranch:z.string().min(1),baseBranch:z.string().min(1),latestCommitSha:z.string().min(1),mergeCommitSha:z.string().min(1).optional(),draft:z.boolean().optional(),title:z.string().optional(),body:z.string().optional()});function yte(e){return e.authorLogin&&e.authorIsBot===false?e.authorLogin:e.humanAssigneeLogins?.[0]}gte.extend({number:z.number(),htmlUrl:z.url()});var nG=100;z.object({path:z.string().min(1),ref:z.string().min(1),limit:z.coerce.number().int().min(1).max(nG)});var kqe=z.object({path:z.string().min(1),status:z.string().min(1),additions:z.number(),deletions:z.number(),previousPath:z.string().optional(),patch:z.string().optional()}),bte=z.object({sha:z.string().min(1),author:z.string().optional(),email:z.string().optional(),date:z.string().optional(),message:z.string()}),Ste=z.object({mergeBaseSha:z.string().min(1),totalCommits:z.number(),commits:z.array(bte),files:z.array(kqe)}),Tte=z.object({commits:z.array(bte)}),vte=z.object({content:z.string().nullable()}),Ate=z.object({name:z.string().min(1),protected:z.boolean(),commit:z.object({sha:z.string().min(1)}).optional().catch(void 0)}),Ete=z.object({iid:z.number(),webUrl:z.url(),sourceBranch:z.string().min(1),targetBranch:z.string().min(1),latestCommitSha:z.string().min(1),description:z.string().optional()}),Mqe=z.object({name:z.string(),path:z.string(),body:z.string()}),Rte=z.object({template:Mqe});function Xk({githubRepository:e,gitlabProjectPath:t,gitOriginUrl:o}){let n=Lqe(o);return e?tG(n?.host??"github.com",e):t?tG(n?.host??"gitlab.com",t):n?tG(n.host,n.repositoryPath):void 0}function NC(e){let t=e?.trim();if(!t)return;let o="refs/heads/";return t.startsWith(o)?t.slice(o.length):t}function Lqe(e){let t=e?.trim();if(!t)return;if(t.includes("://"))try{let a=new URL(t);return ["git:","http:","https:","ssh:"].includes(a.protocol)?{host:a.host,repositoryPath:a.pathname}:void 0}catch{return}let o=t.indexOf(":");if(o<=0)return;let n=t.slice(0,o),r=t.slice(o+1),i=n.slice(n.lastIndexOf("@")+1);return i&&r?{host:i,repositoryPath:r}:void 0}function Nr(e){let[t,o,...n]=e.split("/");if(!(!t||!o||n.length>0))return {owner:t,repo:o}}function tG(e,t){let o=e.trim().toLowerCase(),n=t.trim().split("/").filter(i=>i.length>0);if(!o||n.length===0)return;if(o===`ssh.${Jk}`)o=Jk,n[0]?.toLowerCase()==="v3"&&(n=n.slice(1));else if(o.endsWith(ste)){let i=o.slice(0,-ste.length);if(!i)return;o=Jk,n=[i,...n];}o===Jk&&(n=n.filter(i=>i.toLowerCase()!=="_git"));let r=n.at(-1);if(r?.toLowerCase().endsWith(".git")){let i=r.slice(0,-4);if(!i)return;n[n.length-1]=i;}return `${o}/${n.join("/")}`.toLowerCase()}function Cte(e){let t=Nr(e);if(t)return t;throw new yo(`Invalid GitHub repository string: ${e}. Expected format "owner/repo".`)}var Jk="dev.azure.com",ste=".visualstudio.com",Nqe=/^co-authored-by:\s*.*?<([^>]+)>\s*$/gim,Dqe=/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i;function rG(e){return e.match(Dqe)?.[1]}function Fqe(e){let t=[];for(let o of e.matchAll(Nqe)){let n=o[1]?.trim();n&&t.push({email:n,githubLogin:rG(n)});}return t}function Ite(e){let t=[];for(let o of e.split("\0")){let n=o.trim();if(!n)continue;let r=n.indexOf(`
185
+ `),i=r===-1?n:n.slice(0,r),a=r===-1?"":n.slice(r+1),s=[];i&&s.push({email:i,githubLogin:rG(i)}),s.push(...Fqe(a)),t.push(s);}return t}function Bqe(e){return (e.githubLogin??(e.email?rG(e.email):void 0))?.toLowerCase().endsWith("[bot]")??false}function xte(e){return e.filter(t=>!Bqe(t))}var _te="https://static.momentic.ai";function DC(e,t){return {light:`${_te}/${e}.svg`,dark:`${_te}/${e}-dark.svg`,alt:t}}var FC={runGroup:DC("run-group-button","View run group"),basePr:DC("view-base-pr-button","View base PR"),branch:DC("view-branch-button","View branch"),commit:DC("view-commit-button","View commit")};function BC({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 Hg=z.object({limit:z.number().min(1).max(100).optional(),page:z.number().min(1).optional()}),iG=z.object({page:z.number(),pageSize:z.number(),pageCount:z.number()});var aG=___default.object({platformSep:___default.string(),fullPathSegments:___default.string().array(),relativePathSegments:___default.string().array(),relativePath:___default.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:___default.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:___default.coerce.date(),createdAt:___default.coerce.date()});var Uqe=z.array(aG.extend({id:z.string(),name:z.string(),description:z.string().optional(),labels:z.string().array().optional()})),jqe=aG.extend({id:z.string(),name:z.string(),description:z.string().optional(),content:DP}),zqe=z.array(jqe);z.object({tests:Uqe,modules:zqe,labels:z.string().array()});z.string().array();var Ote=z.object({pathSegments:z.string().array()});c1.merge(Ir);var Pte=z.object({schemaVersion:z.string(),stepLists:oc}),kte=Ir.partial().merge(ls.pick({id:true})),db="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",sG={name:z.string().min(1).max(255).describe(db),description:z.string().optional(),baseUrl:z.url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:z.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.enum(Yu).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:jp.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:z.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.")},Mte=z.object(sG);c1.extend(z.object({relativeFilePath:z.string().describe("relative to project root")}).shape);var Lte=z.object({name:z.string()});z.object({relativeFilePath:z.string()});var Nte=z.object({name:z.string(),sourceModuleContent:DP});z.object({relativeFilePath:z.string()});var Dte=z.object({name:z.string(),description:z.string(),enabled:z.boolean(),steps:z.lazy(()=>Uo.array()),testFilePath:z.string().describe("relative to the project root"),folderPath:z.string().optional().describe("user selected folder path")}),Fte=z.object({name:z.string(),description:z.string(),enabled:z.boolean()}).partial(),Bte=z.object({folderPath:z.string()}),Ute=z.object({folderPath:z.string()});z.array(FR);var jte=z.object({defaultEnv:z.string().optional().describe("name of the default env, or undefined to unset")}),zte=z.object({configFilePath:z.string().describe("full path on disk")});z.object({hasEntities:z.boolean()});z.string().array();z.object({message:z.string(),newRelativeTestPath:z.string().optional()});var lG=z.object({name:z.string(),absolutePath:z.string(),relativePath:z.string(),pathSegments:z.array(z.string()),isDirectory:z.boolean(),size:z.number(),createdAt:z.coerce.date(),modifiedAt:z.coerce.date(),accessedAt:z.coerce.date()}),Hte=z.object({pathSegments:z.array(z.string()),directoriesOnly:z.boolean().optional()});z.object({absolutePath:z.string(),pathSegments:z.array(z.string()),contents:z.array(lG)});var $te=z.object({sourceDirectoryPath:z.string().optional(),value:z.string(),allowedExtensions:z.array(z.string()).optional()}),Hqe=z.object({name:z.string(),value:z.string(),isDirectory:z.boolean()});z.object({suggestions:z.array(Hqe)});var Gte=z.object({pathSegments:z.array(z.string())}),Vte=z.object({pathSegments:z.array(z.string()),newPathSegments:z.array(z.string())}),Wte=z.object({pathSegments:z.array(z.string()),recursive:z.boolean().optional()});z.object({success:z.boolean(),message:z.string(),pathSegments:z.array(z.string()).optional()});z.object({gitBranch:z.string(),fileMtime:z.coerce.date(),gitCommitSha:z.string()});var qte=typeof process<"u"&&true&&true,Qk=58889,mv=24*60*60*1e3;var Kte=z.record(z.string(),z.string()),$qe=z.object({type:z.literal("stdio").optional(),command:z.string().min(1),args:z.array(z.string()).optional(),env:Kte.optional(),cwd:z.string().optional()}),Gqe=z.object({type:z.enum(["http","sse"]).optional(),url:z.string().min(1),headers:Kte.optional()}),Vqe=z.union([$qe,Gqe]),Yte=z.record(z.string().min(1),Vqe);var Jte=z.string().trim().min(1).max(255).regex(/^[^/\\]+$/).refine(e=>e!=="."&&e!=="..");z.object({source:z.string().trim().min(1).max(500).refine(e=>Jte.safeParse(e.split("/").at(-1)).success)});var Xte=z.object({filename:Jte,downloadUrl:z.url()});z.object({filename:z.string().trim().min(1),destination:z.string().trim().min(1).optional()});var Qte=z.object({destination:z.string(),uploadUrl:z.url()});var jC=(n=>(n.DARWIN="darwin",n.LINUX="linux",n.WINDOWS="win32",n))(jC||{}),Zte=z.enum(jC),zC=(r=>(r.AZURE="AZURE",r.KERNEL="KERNEL",r.BROWSERBASE="BROWSERBASE",r.SELF_HOSTED="SELF_HOSTED",r))(zC||{}),Zk=z.enum(zC);z.object({azureRegion:z.string().optional(),azureWorkspaceId:z.string().optional()});z.object({});var HC=z.enum(["westus3","eastus2"]);z.object({});var Wqe=z.enum(["us-west-2","us-east-1","eu-central-1","ap-southeast-1"]);z.object({region:Wqe.optional()});var cG=(t=>(t.TEST_REVIEW="TEST_REVIEW",t))(cG||{});var qqe=z.object({type:z.literal("DESCRIPTION_UPDATE"),thoughts:z.string()}),eM=z.discriminatedUnion("type",[qqe]),Kqe=z.object({testId:z.string(),name:z.string(),orgId:z.string(),runId:z.string(),steps:Uo.array(),purpose:z.enum(cG),details:eM.or(eM.array()).optional()});Kqe.pick({name:true,orgId:true});var Yqe=z.object({id:z.string(),name:z.string().nullish(),createdAt:z.string().pipe(z.coerce.date()).or(z.date()),organizationId:z.string(),schemaVersion:z.string(),runId:z.string().nullish(),purpose:z.enum(cG),details:eM.or(eM.array()).optional(),applied:z.boolean().nullish(),appliedAt:z.coerce.date().nullish()}),eoe=Yqe.extend({steps:Uo.array()});var toe=z.enum(["v1","v2"]);var Xqe=z.enum(["element","content","attribute","tag_name","style"]),tM=z.enum(["exists","visible","enabled","editable","focused","contains","equals","starts_with"]);[...WQ,...VQ].forEach(e=>{if(!tM.options.includes(e.toLowerCase()))throw new Error(`V2CheckConditionSchema is missing option: ${e}`)});var uG={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}},roe={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"}},ioe={ELEMENT_EXISTENCE:"element",ELEMENT_CONTENT:"content",ELEMENT_ATTRIBUTE:"attribute",ELEMENT_NAME:"tag_name",ELEMENT_STYLE:"style"};function ooe(e){return {alias:dG(e),subject:e.subject,condition:e.condition,negated:e.negated,assertionType:uG[e.subject].assertionType,requiresName:uG[e.subject].requiresName,requiresValue:e.subject!=="element"&&e.condition!=="exists"}}function dG(e){let t=uG[e.subject],o=roe[e.condition];if(!aoe(e.subject,e.condition))throw new Error(`Unsupported element check alias for subject '${e.subject}' and condition '${e.condition}'.`);let n=e.negated?o.negativeAliasSuffix:o.positiveAliasSuffix;return `checkElement${t.aliasPrefix}${n}`}function aoe(e,t){let o=roe[t],n=o.elementCondition,r=o.contentOperation;return e==="element"?n!==void 0:r!==void 0}var Qqe=Xqe.options.flatMap(e=>tM.options.flatMap(t=>aoe(e,t)?[ooe({subject:e,condition:t,negated:false}),ooe({subject:e,condition:t,negated:true})]:[])),oM=new Map(Qqe.map(e=>[e.alias,e]));var Zqe=z.enum(Qd),eKe=z.enum(Zl);function qs(e){return oM.get(e)}function loe(e){let t=ioe[e.type],o=e.type==="ELEMENT_EXISTENCE"?e.condition:e.operation;return dG({subject:t,condition:tKe(o),negated:e.negated})}function coe(e){return Zqe.parse(e.toUpperCase())}function $C(e){return eKe.parse(e.toUpperCase())}function tKe(e){return tM.parse(e.toLowerCase())}var hv=z.string().regex(/\S+\s+\S+/,"Bare AI action goals must contain multiple words.").describe("Multi-word natural-language goal for an AI action V3 step."),Bt={saveAs:z.string().optional(),retries:z.number().optional(),skipped:z.boolean().optional(),comment:z.string().optional()};z.object(Bt);var gv=Object.keys(Bt);function Tt(e){return z.union([z.strictObject({[e.key]:e.simplified}),z.strictObject({[e.key]:e.detailed})])}function mr(e){return z.strictObject({[e.key]:e.detailed})}function oKe(e,t){let o=Array.from({length:t.length+1},(n,r)=>r);for(let n=1;n<=e.length;n+=1){let r=[n],i=e.charAt(n-1);for(let a=1;a<=t.length;a+=1)r.push(i===t.charAt(a-1)?o[a-1]??0:Math.min((o[a-1]??0)+1,(o[a]??0)+1,(r[a-1]??0)+1));o.splice(0,o.length,...r);}return o[t.length]??0}function uoe(e,t){let o=e.toLowerCase(),n,r=.5;for(let i of t){let a=i.toLowerCase(),s=Math.max(o.length,a.length),l=s===0?1:1-oKe(o,a)/s;l>r&&(r=l,n=i);}return n}var doe='Coordinates must be "x, y" pixel values, e.g. "100, 200"',fv=z.union([Yd,z.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,doe)],{error:doe});z.union([z.string(),Yd]);var Pl={css:z.string().optional(),coords:fv.optional(),x:z.union([z.number(),z.string()]).optional(),y:z.union([z.number(),z.string()]).optional()},pG={on:z.string().optional(),...Pl},uc={...Bt,effort:Nt.optional(),useSelector:z.boolean().optional(),force:z.boolean().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional()},bv={...uc,offset:fv.optional()};function ds({schema:e,descriptionKey:t,required:o=true}){return e.superRefine((n,r)=>{let a=[t in n?Object.entries(n).find(([s])=>s===t)?.[1]:void 0,"css"in n?n.css:void 0,"coords"in n?n.coords:void 0,"x"in n||"y"in n?true:void 0].filter(s=>s!==void 0).length;o&&a!==1&&r.addIssue({code:"custom",message:`Use exactly one target: ${t}, css, coords, or x/y.`}),!o&&a>1&&r.addIssue({code:"custom",message:`Use at most one target: ${t}, css, coords, or x/y.`}),("x"in n||"y"in n)&&(!("x"in n)||n.x===void 0||!("y"in n)||n.y===void 0)&&r.addIssue({code:"custom",message:"x and y must be provided together."});})}var nKe=ds({descriptionKey:"on",schema:z.strictObject({...pG,...bv,times:z.int().min(1).optional(),rightClick:z.boolean().optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),rKe=ds({descriptionKey:"on",schema:z.strictObject({...pG,...bv,rightClick:z.boolean().optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),iKe=ds({descriptionKey:"on",schema:z.strictObject({...pG,...bv,times:z.int().min(1).optional(),waitForDownload:z.boolean().optional(),delay:z.number().optional(),downloadTimeout:z.number().optional()})}),moe=Tt({key:"click",simplified:z.string(),detailed:nKe}),poe=Tt({key:"doubleClick",simplified:z.string(),detailed:rKe}),hoe=Tt({key:"rightClick",simplified:z.string(),detailed:iKe}),aKe=ds({descriptionKey:"into",required:false,schema:z.strictObject({text:z.string(),into:z.string().optional(),...Pl,...bv,pressEnter:z.boolean().optional(),clear:z.union([z.literal("inputs"),z.literal("always"),z.literal("never"),z.boolean()]).optional(),delay:z.number().optional()})}),goe=Tt({key:"type",simplified:z.string(),detailed:aKe}),sKe=ds({descriptionKey:"into",required:false,schema:z.strictObject({text:z.string(),into:z.string().optional(),...Pl,...bv,pressEnter:z.boolean().optional()})}),foe=Tt({key:"fill",simplified:z.string(),detailed:sKe}),yoe=mr({key:"select",detailed:ds({descriptionKey:"from",schema:z.strictObject({from:z.string().optional(),...Pl,label:z.string().optional(),value:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),...uc})}).superRefine((e,t)=>{[e.label,e.value,e.index].filter(n=>n!==void 0).length!==1&&t.addIssue({code:"custom",message:"select requires exactly one of label, value, or index"});})}),boe=Tt({key:"hover",simplified:z.string(),detailed:ds({descriptionKey:"on",schema:z.strictObject({on:z.string().optional(),...Pl,...bv})})}),Soe=mr({key:"blur",detailed:ds({descriptionKey:"on",required:false,schema:z.strictObject({on:z.string().optional(),...Pl,...uc})})}),Toe=Tt({key:"focus",simplified:z.string(),detailed:ds({descriptionKey:"on",schema:z.strictObject({on:z.string().optional(),...Pl,...uc})})}),voe=mr({key:"dragAndDrop",detailed:z.strictObject({from:z.string().optional(),to:z.string().optional(),fromCss:z.string().optional(),toCss:z.string().optional(),fromCoords:fv.optional(),toCoords:fv.optional(),fromX:z.union([z.number(),z.string()]).optional(),fromY:z.union([z.number(),z.string()]).optional(),toX:z.union([z.number(),z.string()]).optional(),toY:z.union([z.number(),z.string()]).optional(),steps:z.number().optional(),hover:z.number().optional(),...uc}).superRefine((e,t)=>{let o=[e.from,e.fromCss,e.fromCoords,e.fromX!==void 0||e.fromY!==void 0?true:void 0].filter(r=>r!==void 0).length,n=[e.to,e.toCss,e.toCoords,e.toX!==void 0||e.toY!==void 0?true:void 0].filter(r=>r!==void 0).length;o!==1&&t.addIssue({code:"custom",message:"Use exactly one from target."}),n!==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."});})}),Aoe=z.union([z.strictObject({mouseDrag:fv}),z.strictObject({mouseDrag:ds({descriptionKey:"from",required:false,schema:z.strictObject({from:z.string().optional(),...Pl,delta:fv,steps:z.number().optional(),...uc})})})]),Eoe=Tt({key:"press",simplified:z.string(),detailed:z.strictObject({key:z.string(),repeat:z.number().optional(),delay:z.number().optional(),convertMeta:z.boolean().optional(),...Bt,effort:Nt.optional()})}),woe=Tt({key:"keyDown",simplified:z.string(),detailed:z.strictObject({key:z.string(),convertMeta:z.boolean().optional(),...Bt,effort:Nt.optional()})}),Roe=Tt({key:"keyUp",simplified:z.string(),detailed:z.strictObject({key:z.string(),convertMeta:z.boolean().optional(),...Bt,effort:Nt.optional()})}),yv=z.number().int().min(0).max(6e4).multipleOf(1e3),Coe=Tt({key:"navigate",simplified:z.string(),detailed:z.strictObject({url:z.string(),timeout:yv.optional(),...Bt,effort:Nt.optional()})}),Ioe=Tt({key:"newTab",simplified:z.string(),detailed:z.strictObject({url:z.string(),timeout:yv.optional(),...Bt,effort:Nt.optional()})}),xoe=Tt({key:"switchTab",simplified:z.union([z.number(),z.string()]),detailed:z.strictObject({substring:z.string().optional(),regex:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),timeout:yv.optional(),loadTimeout:yv.optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(n=>n!==void 0).length!==1&&t.addIssue({code:"custom",message:"switchTab requires exactly one of substring, regex, or index"});})}),_oe=mr({key:"closeTab",detailed:z.strictObject({substring:z.string().optional(),regex:z.string().optional(),index:z.union([z.string(),z.number()]).optional(),timeout:yv.optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(n=>n!==void 0).length<=1||t.addIssue({code:"custom",message:"closeTab accepts at most one of substring, regex, or index"});})}),Ooe=mr({key:"goBack",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),Poe=mr({key:"goForward",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),koe=mr({key:"refresh",detailed:z.strictObject({timeout:yv.optional(),...Bt,effort:Nt.optional()})}),mb=z.enum(["goBack","goForward","refresh","paste","authSave","offline","online","blur","visualDiff","captcha","closeTab"]),Moe=Tt({key:"scrollUp",simplified:z.number().nonnegative(),detailed:ds({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Pl,...uc})})}),Loe=Tt({key:"scrollDown",simplified:z.number().nonnegative(),detailed:ds({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Pl,...uc})})}),Noe=Tt({key:"scrollLeft",simplified:z.number().nonnegative(),detailed:ds({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Pl,...uc})})}),Doe=Tt({key:"scrollRight",simplified:z.number().nonnegative(),detailed:ds({descriptionKey:"in",required:false,schema:z.strictObject({pixels:z.number().nonnegative().optional(),in:z.string().optional(),...Pl,...uc})})}),Foe=Tt({key:"wait",simplified:z.number(),detailed:z.strictObject({ms:z.number(),...Bt,effort:Nt.optional()})}),lKe=Tt({key:"assert",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),source:z.string().optional(),...Bt,effort:Nt.optional()})}),cKe=Tt({key:"assertVisually",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),source:z.string().optional(),...Bt,effort:Nt.optional()})}),nM=lKe,rM=cKe,Boe=Tt({key:"checkPageContains",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),iframe:z.string().optional(),...Bt,effort:Nt.optional()})}),Uoe=Tt({key:"checkPageDoesNotContain",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),iframe:z.string().optional(),...Bt,effort:Nt.optional()})}),hG=z.union([Boe,Uoe]),uKe=z.record(z.string(),z.unknown().optional()),iM=uKe.superRefine((e,t)=>{let o=Object.keys(e),n=o[0];if(o.length!==1||n===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=qs(n);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=ds({descriptionKey:"element",schema:z.looseObject({element:z.string().optional(),...Pl,...uc,timeout:z.number().optional(),name:z.string().optional(),value:z.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"]});}),joe=Tt({key:"extract",simplified:z.string(),detailed:z.strictObject({goal:z.string(),schema:zg.optional(),DANGEROUS_FORCE_DYNAMIC:z.boolean().optional(),iframe:z.string().optional(),...Bt,effort:Nt.optional()})}),zoe=Tt({key:"cookie",simplified:z.string(),detailed:z.strictObject({value:z.string(),...Bt,effort:Nt.optional()})}),Hoe=mr({key:"localStorage",detailed:z.strictObject({key:z.string(),value:z.string(),...Bt,effort:Nt.optional()})}),$oe=Tt({key:"request",simplified:z.string(),detailed:z.strictObject({url:z.string(),method:Op.optional(),headers:z.record(z.string(),z.string()).optional(),params:z.record(z.string(),z.string()).optional(),body:zg.optional(),contentType:z.enum(Zd).optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()})}),Goe=mr({key:"graphqlRequest",detailed:z.strictObject({url:z.string(),query:z.string(),variables:zg.optional(),headers:z.record(z.string(),z.string()).optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()})}),aM=Tt({key:"javascript",simplified:z.string(),detailed:z.strictObject({code:z.string(),environment:z.enum(["node","browser","NODE","BROWSER"]).optional(),fragment:z.boolean().optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()})}),Sv={substring:z.string().optional(),glob:z.string().optional(),regex:z.string().optional(),domain:z.string().optional()};function dKe(e){return [e.substring,e.glob,e.regex,e.domain].filter(t=>t!==void 0).length}function Tv(e){let t=dKe(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 Voe=mr({key:"header",detailed:z.strictObject({name:z.string(),value:z.string(),...Sv,method:z.string().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:false});})}),Woe=mr({key:"mock",detailed:z.strictObject({...Sv,method:z.string().optional(),responseGenerator:z.string(),fetchOriginalResponse:z.boolean().optional(),key:z.string().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),qoe=Tt({key:"removeRouteMock",simplified:z.string(),detailed:z.strictObject({key:z.string().optional(),...Bt,effort:Nt.optional()})}),Koe=Tt({key:"waitForUrl",simplified:z.string(),detailed:z.strictObject({...Sv,caseInsensitive:z.boolean().optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),Yoe=Tt({key:"waitForUrlNotToMatch",simplified:z.string(),detailed:z.strictObject({...Sv,caseInsensitive:z.boolean().optional(),timeout:z.number().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),mKe=z.union([Koe,Yoe]),Joe=Tt({key:"dialog",simplified:z.enum(["ACCEPT","DISMISS"]),detailed:z.strictObject({action:z.enum(["ACCEPT","DISMISS"]),...Bt,effort:Nt.optional()})}),Xoe=Tt({key:"fileUpload",simplified:z.string(),detailed:z.strictObject({path:z.string(),name:z.string().optional(),...Bt,effort:Nt.optional()})}),Qoe=Tt({key:"copy",simplified:z.union([z.string(),z.boolean(),z.null()]),detailed:z.strictObject({value:z.union([z.string(),z.boolean(),z.null()]),...Bt,effort:Nt.optional()})}),Zoe=mr({key:"paste",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),ene=mr({key:"captcha",detailed:z.strictObject({...uc})}),pKe=z.strictObject({data:z.union([z.string(),Ql]),width:z.number(),height:z.number()}),tne=Tt({key:"visualDiff",simplified:z.string(),detailed:ds({descriptionKey:"on",required:false,schema:z.strictObject({on:z.string().optional(),...Pl,threshold:z.number().optional(),screenshot:pKe.optional(),...uc})})}),one=mr({key:"offline",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),nne=mr({key:"online",detailed:z.strictObject({...Bt,effort:Nt.optional()})}),rne=mr({key:"registerRequestListener",detailed:z.strictObject({...Sv,key:z.string(),method:z.string().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),ine=Tt({key:"awaitListener",simplified:z.string(),detailed:z.strictObject({key:z.string(),timeout:z.number().optional(),...Bt,effort:Nt.optional()})}),ane=mr({key:"recordRequests",detailed:z.strictObject({...Sv,key:z.string(),method:z.string().optional(),...Bt,effort:Nt.optional()}).superRefine((e,t)=>{Tv({payload:e,ctx:t,required:true});})}),sne=Tt({key:"getRecordedRequests",simplified:z.string(),detailed:z.strictObject({key:z.string(),...Bt,effort:Nt.optional()})}),lne=Tt({key:"authLoad",simplified:z.string(),detailed:z.strictObject({path:z.string(),...Bt,effort:Nt.optional()})}),cne=Tt({key:"authSave",simplified:z.string(),detailed:z.strictObject({path:z.string().optional(),...Bt,effort:Nt.optional()})});z.union([moe,poe,hoe,xoe,_oe,goe,foe,yoe,boe,Soe,Toe,voe,Aoe,Eoe,woe,Roe,Coe,Ioe,Ooe,Poe,koe,Moe,Loe,Noe,Doe,Foe,nM,rM,hG,joe,zoe,Hoe,$oe,Goe,aM,Voe,Woe,qoe,mKe,Joe,Xoe,Qoe,Zoe,ene,tne,one,nne,rne,ine,ane,sne,lne,cne,iM]);var une=new Map([["click",moe],["doubleClick",poe],["rightClick",hoe],["switchTab",xoe],["closeTab",_oe],["type",goe],["fill",foe],["select",yoe],["hover",boe],["blur",Soe],["focus",Toe],["dragAndDrop",voe],["mouseDrag",Aoe],["press",Eoe],["keyDown",woe],["keyUp",Roe],["navigate",Coe],["newTab",Ioe],["goBack",Ooe],["goForward",Poe],["refresh",koe],["scrollUp",Moe],["scrollDown",Loe],["scrollLeft",Noe],["scrollRight",Doe],["wait",Foe],["assert",nM],["assertVisually",rM],["checkPageContains",Boe],["checkPageDoesNotContain",Uoe],["extract",joe],["cookie",zoe],["localStorage",Hoe],["request",$oe],["graphqlRequest",Goe],["javascript",aM],["header",Voe],["mock",Woe],["removeRouteMock",qoe],["waitForUrl",Koe],["waitForUrlNotToMatch",Yoe],["dialog",Joe],["fileUpload",Xoe],["copy",Qoe],["paste",Zoe],["captcha",ene],["visualDiff",tne],["offline",one],["online",nne],["registerRequestListener",rne],["awaitListener",ine],["recordRequests",ane],["getRecordedRequests",sne],["authLoad",lne],["authSave",cne]]),gG=Object.freeze([...une.keys()]),hKe=[...gG,...oM.keys()],ym=z.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 o=Object.keys(e),n=o[0];if(o.length!==1||n===void 0){t.addIssue({code:"custom",message:"Steps must have exactly one action key."});return}let r=une.get(n)??(qs(n)?iM:void 0);if(!r){let a=uoe(n,hKe);t.addIssue({code:"custom",message:`Unsupported step type '${n}'.${a?` Did you mean '${a}'?`:""} See https://momentic.ai/docs/reference/commands for every step type.`});return}let i=r.safeParse(e);if(!i.success){let a=gKe(i.error.issues,n);a.length>0&&dne(t,a);}});function gKe(e,t){return fKe(e).filter(o=>!yKe(o,t))}function dne(e,t){for(let o of t){if(o.code==="invalid_union"){dne(e,fG(o));continue}e.addIssue({...o});}}function fKe(e){let t=[];for(let o of e){if(o.code==="invalid_union"){t.push(...fG(o));continue}t.push(o);}return t}function yKe(e,t){return e.code!=="unrecognized_keys"?false:t===void 0?e.path.length===0:e.path.length===1&&e.path[0]===t}function fG(e){let t=e.errors[0]??[],o=mG(t);for(let n of e.errors.slice(1)){let r=mG(n);r>o&&(t=n,o=r);}return t}function mG(e){return e.reduce((t,o)=>{let n=o.code==="invalid_union"?mG(fG(o)):0;return t+o.path.length+n},0)}var mne=z.strictObject({string:z.string()}),bKe=z.strictObject({javascript:z.string()}),pne=z.union([mne,bKe]),SKe=z.union([z.strictObject({name:z.string(),required:z.boolean().optional(),default:mne.optional()}),z.strictObject({name:z.string(),required:z.boolean().optional(),defaultValue:z.string()})]),hne=SKe.array(),TKe=z.strictObject({name:z.string(),default:pne.optional(),enum:z.array(z.string()).optional()}),gne=TKe.array(),GC=z.union([pne,z.string()]),fne=z.record(z.string(),GC);var vKe=z.preprocess(e=>typeof e=="number"?String(e):e,yR),sM=z.looseObject({goal:z.string(),version:vKe.optional(),cache:z.literal(false).optional(),...Bt}),AKe=z.union([z.strictObject({act:z.string()}),z.strictObject({act:sM})]),yG=z.looseObject({path:z.string(),inputs:z.record(z.string(),GC).optional(),...Bt}),EKe=z.union([z.strictObject({module:z.string()}),z.strictObject({module:yG})]),Yp=z.union([nM,rM,hG,aM,iM]),wKe=new Set(["then","effort",...gv]),RKe=z.looseObject({then:z.lazy(()=>od.array()),effort:Nt.optional(),...Bt}).superRefine((e,t)=>{Object.entries(e).filter(([n,r])=>!wKe.has(n)&&Yp.safeParse({[n]:r}).success).length!==1&&t.addIssue({code:"custom",message:"Conditional steps require exactly one assertion condition at the top level."});}),CKe=z.strictObject({if:RKe}),IKe=new Set(["do","maxIterations","effort",...gv]),xKe=z.looseObject({do:z.lazy(()=>od.array()),maxIterations:z.number().int().positive().optional(),effort:Nt.optional(),...Bt}).superRefine((e,t)=>{let o=Object.entries(e).filter(([n,r])=>!IKe.has(n)&&Yp.safeParse({[n]:r}).success).length;if(o>1){t.addIssue({code:"custom",message:"While loops accept at most one condition at the top level."});return}o===0&&e.maxIterations===void 0&&t.addIssue({code:"custom",message:"While loops require a condition or a maximum number of iterations."});}),_Ke=z.strictObject({while:xKe}),od=z.lazy(()=>z.union([mb,hv,AKe,EKe,CKe,_Ke,ym]));z.object({before:od.array().optional(),steps:od.array(),after:od.array().optional()});var OKe=z.union([jp,z.string().refine(e=>{let t=e.match(/^\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*$/);if(!t)return false;let[,o,n]=t;return jp.safeParse({width:Number(o),height:Number(n)}).success},"Viewport must be two numeric values, e.g. 1920, 1080")]),PKe=Us.omit({viewport:true}).extend({viewport:OKe.optional()}),bG=z.object({id:Lr,version:z.string().optional(),url:BP.optional(),description:z.string().optional(),retries:z.number().optional(),defaultEnv:z.string().optional(),parameters:hne.optional(),outputs:yk.optional(),disabled:z.boolean().optional(),labels:z.array(z.string()).optional(),runAssertions:bk.array().optional()}).extend(PKe.shape),kKe=z.looseObject({fileType:z.literal(ze.TEST_V2)}).extend(bG.shape).extend({before:od.array().optional(),steps:od.array(),after:od.array().optional()}),Gg=kKe.superRefine(LKe),MKe={beforeSteps:"before",afterSteps:"after"};function LKe(e,t){for(let[o,n]of Object.entries(MKe))o in e&&t.addIssue({code:"custom",message:`v2 tests must use ${n}, not ${o}`,path:[o]});}var NKe=z.array(z.string()),DKe=z.union([z.string(),z.record(z.string(),z.unknown().optional())]),lM=kr.omit({moduleId:true,name:true,parameters:true,defaultParameters:true,parameterEnums:true}).extend({id:Lr,version:z.string().optional(),name:z.string().optional(),parameters:z.union([gne,NKe]).optional(),defaultParameters:z.record(z.string(),z.string()).optional(),parameterEnums:z.record(z.string(),z.array(z.string())).optional()}),cM=z.looseObject(lM.extend({fileType:z.literal(ze.MODULE_V2),steps:DKe.array().optional()}).shape).superRefine(bne),uM=z.looseObject(lM.extend({fileType:z.literal(ze.MODULE_V2),steps:od.array().optional()}).shape).superRefine(bne);function yne(e){return e.steps??[]}function bne(e,t){"main"in e&&t.addIssue({code:"custom",message:"v2 modules must use steps, not main",path:["main"]});}var SG=(o=>(o.TEST="TEST",o.MODULE="MODULE",o))(SG||{}),FKe=z.enum(SG),Sne=z.object({orgId:z.string(),entityType:FKe,entityId:z.string()}),TG=Sne.extend({entityType:z.literal("TEST"),stepLists:qu}),vG=Sne.extend({entityType:z.literal("MODULE"),steps:Bo.array()});z.discriminatedUnion("entityType",[TG,vG]);var Tne=(n=>(n.WEB="web",n.ANDROID="android",n.IOS="ios",n))(Tne||{}),AG=z.nativeEnum(Tne);var vne=z.object({entity_type:z.string(),value:z.string(),schema_version:z.string().optional()}),Ane=zR(vne),Ene=vne.extend({cache_key:z.string()});function VC({entityType:e,entityId:t}){return `${e}:${t}`}var hb=z.string();var wne='Coordinates must be "x, y" pixel values, e.g. "100, 200"',xne=z.union([Yd,z.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,wne)],{error:wne}),Rne='Percent must be a number or a percent string, e.g. 90 or "90%"',_ne=z.union([z.number(),z.string().regex(/^-?\d+(?:\.\d+)?%$/,Rne)],{error:Rne}).transform(e=>typeof e=="number"?e:Number(e.slice(0,-1))).pipe(z.number().min(0,{message:"Percent must be >= 0"}).max(100,{message:"Percent must be <= 100"})),BKe=z.strictObject({x:z.number(),y:z.number(),delta:z.number()}),One=z.union([z.string(),BKe]),Pn={...Bt,DANGEROUS_FORCE_DYNAMIC:z.boolean().optional()},UKe=["home","power","back","app_switcher","search","volume_up","volume_down","volume_mute"],jKe=["enter","backspace","close_keyboard"],Cne=["airplane_mode","data","wifi","location"],Ine=["portrait","landscape"],zKe=z.strictObject({on:hb.optional(),longPress:z.boolean().optional(),longPressDuration:z.number().optional(),iterations:z.number().optional(),tapDelay:z.number().optional(),offset:xne.optional(),...Pn}),Pne=Tt({key:"tap",simplified:hb,detailed:zKe}),HKe=z.strictObject({text:z.string(),into:hb.optional(),clearContent:z.boolean().optional(),forceClearContent:z.boolean().optional(),delay:z.number().optional(),waitForKeyboardSettle:z.boolean().optional(),replaceStrategy:z.nativeEnum(fC).optional(),keyPressDelay:z.number().optional(),...Pn}),kne=Tt({key:"type",simplified:z.string(),detailed:HKe}),Mne=z.enum(UKe),$Ke=z.strictObject({key:Mne,longPress:z.boolean().optional(),...Pn}),Lne=Tt({key:"press",simplified:Mne,detailed:$Ke}),Nne=z.enum(jKe),GKe=z.strictObject({key:Nne,repeat:z.number().optional(),delay:z.number().optional(),keyPressDelay:z.number().optional(),...Pn}),Dne=Tt({key:"pressKey",simplified:Nne,detailed:GKe}),VKe=z.strictObject({package:z.string(),activity:z.string().optional(),intentExtras:z.string().optional(),...Pn}),Fne=Tt({key:"openApp",simplified:z.string(),detailed:VKe}),Bne=mr({key:"killApp",detailed:z.strictObject(Pn)}),Une=mr({key:"openNotifications",detailed:z.strictObject(Pn)}),jne=z.enum(["up","down","left","right"]),WKe=z.strictObject({direction:jne,in:One.optional(),viewportPercent:_ne.optional(),duration:z.number().optional(),offset:xne.optional(),...Pn}),zne=Tt({key:"swipe",simplified:jne,detailed:WKe}),qKe=z.enum(["up","down"]),KKe=z.strictObject({on:hb,direction:qKe.optional(),in:One.optional(),scrollStepPercent:_ne.optional(),maxScrollAttempts:z.number().optional(),...Pn}),Hne=Tt({key:"scrollTo",simplified:z.string(),detailed:KKe}),EG=Tt({key:"assert",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),...Pn})}),wG=Tt({key:"assertVisually",simplified:z.string(),detailed:z.strictObject({that:z.string(),timeout:z.number().optional(),...Pn})}),$ne=Tt({key:"extract",simplified:z.string(),detailed:z.strictObject({goal:z.string(),schema:zg.optional(),...Pn})}),Gne=Tt({key:"checkScreenContains",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),...Pn})}),Vne=Tt({key:"checkScreenDoesNotContain",simplified:z.string(),detailed:z.strictObject({text:z.string(),timeout:z.number().optional(),...Pn})}),Wne=z.union([Gne,Vne]),YKe=z.record(z.string(),z.unknown().optional()),RG=YKe.superRefine((e,t)=>{let o=Object.keys(e),n=o[0];if(o.length!==1||n===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=qs(n);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.looseObject({on:hb.optional(),timeout:z.number().optional(),name:z.string().optional(),value:z.string().optional(),...Pn}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}i.data.on===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a target via 'on'`,path:[r.alias,"on"]}),r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),JKe=z.strictObject({from:hb,to:hb,hoverDuration:z.number().optional(),dragDuration:z.number().optional(),...Pn}),qne=mr({key:"dragAndDrop",detailed:JKe}),CG=Tt({key:"javascript",simplified:z.string(),detailed:z.strictObject({code:z.string(),timeout:z.number().optional(),...Pn})}),Kne=Tt({key:"request",simplified:z.string(),detailed:z.strictObject({url:z.string(),method:Op.optional(),headers:z.record(z.string(),z.string()).optional(),params:z.record(z.string(),z.string()).optional(),body:z.string().optional(),bodyType:z.nativeEnum(Zd).optional(),timeout:z.number().optional(),...Pn})}),Yne=Tt({key:"wait",simplified:z.number(),detailed:z.strictObject({ms:z.number(),...Pn})}),Jne=Tt({key:"visualDiff",simplified:z.string(),detailed:z.strictObject({path:z.string(),threshold:z.number().min(0).max(1).optional(),...Pn})}),Xne=mr({key:"addFile",detailed:z.strictObject({path:z.string(),location:z.string(),...Pn})}),Qne=Tt({key:"setCamera",simplified:z.string(),detailed:z.strictObject({path:z.string(),loop:z.boolean().optional(),playAudio:z.boolean().optional(),...Pn})}),Zne=mr({key:"clearCamera",detailed:z.strictObject(Pn)}),ere=Tt({key:"setMicrophone",simplified:z.string(),detailed:z.strictObject({path:z.string(),once:z.boolean().optional(),...Pn})}),tre=mr({key:"clearMicrophone",detailed:z.strictObject(Pn)}),ore=Tt({key:"installApp",simplified:z.string(),detailed:z.strictObject({path:z.string(),...Pn})}),nre=Tt({key:"uninstallApp",simplified:z.string(),detailed:z.strictObject({package:z.string(),...Pn})}),rre=Tt({key:"toggleSettings",simplified:z.enum(Cne),detailed:z.strictObject({setting:z.enum(Cne),...Pn})}),ire=Tt({key:"rotate",simplified:z.enum(Ine),detailed:z.strictObject({orientation:z.enum(Ine),...Pn})}),are=Tt({key:"adb",simplified:z.string(),detailed:z.strictObject({command:z.string(),args:z.string().optional(),...Pn})}),sre=mr({key:"appium",detailed:z.strictObject({script:z.string(),args:z.string().optional(),...Pn})}),lre=mr({key:"debugState",detailed:z.strictObject(Pn)}),cre=z.enum(["killApp","openNotifications","debugState","clearCamera","clearMicrophone"]);z.union([Pne,kne,Lne,Dne,Fne,Bne,Une,zne,Hne,EG,wG,$ne,Wne,qne,CG,Kne,Yne,Jne,Xne,Qne,Zne,ere,tre,ore,nre,rre,ire,are,sre,lre,RG]);var ure=new Map([["tap",Pne],["type",kne],["press",Lne],["pressKey",Dne],["openApp",Fne],["killApp",Bne],["openNotifications",Une],["swipe",zne],["scrollTo",Hne],["assert",EG],["assertVisually",wG],["extract",$ne],["checkScreenContains",Gne],["checkScreenDoesNotContain",Vne],["dragAndDrop",qne],["javascript",CG],["request",Kne],["wait",Yne],["visualDiff",Jne],["addFile",Xne],["setCamera",Qne],["clearCamera",Zne],["setMicrophone",ere],["clearMicrophone",tre],["installApp",ore],["uninstallApp",nre],["toggleSettings",rre],["rotate",ire],["adb",are],["appium",sre],["debugState",lre]]);Object.freeze([...ure.keys()]);var dre=z.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 o=Object.keys(e),n=o[0];if(o.length!==1||n===void 0){t.addIssue({code:"custom",message:"v2 mobile commands must have exactly one action key."});return}let r=ure.get(n)??(qs(n)?RG:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported v2 mobile command '${n}'.`});return}let i=r.safeParse(e);if(!i.success)for(let a of i.error.issues)t.addIssue({...a});}),IG=z.union([EG,wG,Wne,CG,RG]);var XKe=z.preprocess(e=>typeof e=="number"?String(e):e,O1),QKe=z.looseObject({goal:z.string(),version:XKe.optional(),cache:z.literal(false).optional(),precondition:z.string().optional(),postcondition:z.string().optional(),...Bt}),ZKe=z.union([z.strictObject({act:z.string()}),z.strictObject({act:QKe})]),eYe=z.looseObject({path:z.string(),inputs:z.record(z.string(),GC).optional(),...Bt}),tYe=z.union([z.strictObject({module:z.string()}),z.strictObject({module:eYe})]),oYe=new Set(["then",...gv]),nYe=z.looseObject({then:z.lazy(()=>nd.array()),...Bt}).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(([n,r])=>!oYe.has(n)&&IG.safeParse({[n]:r}).success).length!==1&&t.addIssue({code:"custom",message:"v2 mobile conditional steps require exactly one assertion condition at the top level."});}),rYe=z.strictObject({if:nYe}),iYe=new Set(["do","maxIterations",...gv]),aYe=z.looseObject({do:z.lazy(()=>nd.array()),maxIterations:z.number().int().positive().optional(),...Bt}).superRefine((e,t)=>{let o=Object.entries(e).filter(([n,r])=>!iYe.has(n)&&IG.safeParse({[n]:r}).success).length;if(o>1){t.addIssue({code:"custom",message:"While loops accept at most one condition at the top level."});return}o===0&&e.maxIterations===void 0&&t.addIssue({code:"custom",message:"While loops require a condition or a maximum number of iterations."});}),sYe=z.strictObject({while:aYe}),nd=z.lazy(()=>z.union([cre,hv,ZKe,tYe,rYe,sYe,dre]));z.object({before:nd.array().optional(),steps:nd.array(),after:nd.array().optional()});var lYe=z.literal("android"),cYe=z.literal("ios");function dM(e){if(typeof e!="object"||e===null)return e;let t=e;if(typeof t.platform!="string")return e;let o=t.platform.toLowerCase();return o===t.platform?e:{...t,platform:o}}var mre=cv.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z.string().optional(),platform:lYe,...xC.shape}),pre=uv.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z.string().optional(),platform:cYe,...xC.shape}),uYe=z.discriminatedUnion("platform",[mre,pre]),hre=z.preprocess(dM,uYe),gre={before:nd.array().optional(),steps:nd.array(),after:nd.array().optional()},fre=z.looseObject({fileType:z.literal(ze.MOBILE_TEST_V2)}).extend(mre.shape).extend(gre);z.preprocess(dM,fre);var yre=z.looseObject({fileType:z.literal(ze.MOBILE_TEST_V2)}).extend(pre.shape).extend(gre);z.preprocess(dM,yre);var dYe=z.discriminatedUnion("platform",[fre,yre]);z.preprocess(dM,dYe);var mYe=z.preprocess(e=>typeof e=="string"?e.toLowerCase():e,z.enum(lk).optional().default("android")),mM=Bk.omit({moduleId:true,name:true,schemaVersion:true,platform:true}).extend({id:Lr,name:z.string().optional(),version:z.string().optional(),platform:mYe});z.looseObject(mM.extend({fileType:z.literal(ze.MOBILE_MODULE_V2),steps:z.array(z.record(z.string(),z.unknown().optional())).optional()}).shape);z.looseObject(mM.extend({fileType:z.literal(ze.MOBILE_MODULE_V2),steps:nd.array().optional()}).shape);var pM="x-momentic-cli-version",Sre="x-momentic-client-mode",hM="x-momentic-runner",Tre="x-momentic-cli-type",gM="x-momentic-logger-tags",xG="x-momentic-effective-ai-effort",pYe="x-momentic-main-branch-name",hYe="x-momentic-branch-name",gYe="x-momentic-commit-timestamp",fYe="x-momentic-last-commit-on-main",yYe="x-momentic-last-commit-on-main-timestamp",bYe="x-momentic-merged-branch-name",vre="x-momentic-session-id",fM=529,Are="x-momentic-parent-trace-id";_.object({error:_.boolean(),reason:_.string(),message:_.string()});_i.merge(s1);var Ere=kP;_i.merge(s1);_i.merge(GZ).extend({useConsensus:_.boolean().optional(),attemptNumber:_.number().optional()});var _G=GQ;_i.merge(VZ);var wre=L9;_i.merge(jZ);var Rre=ak;_i.merge(m9);_i.merge(zZ);var Cre=P9;_i.merge(HZ);_i.merge($Z);_i.merge(YZ);_i.merge(JZ);_i.merge(XZ);_.object({testPaths:_.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:_.string().optional(),all:_.boolean().optional(),urlOverride:_.string().optional(),customHeaders:_.record(_.string(),_.string()).optional(),testInputMatrix:_.record(_.string(),_.string()).array().optional()});var Ire=_.object({queuedTests:_.unknown().optional().array(),runIds:_.guid().array(),runGroupId:_.string().optional()});_.string().array();_.union([_.object({paths:_.string().array().describe("Export specific test paths or folder paths (e.g. todo-test, auth/onboarding)"),all:_.boolean().describe("run all tests").optional()}),_.object({path:_.string().describe("deprecated; present for backcompat")})]);var SYe=_.object({tests:_.record(_.string().describe("Test name (keys correspond to entries in `tests`)"),_.string().describe("Slash-separated folder name path that the test lives in (e.g. 'Auth/Login'). Top-level entities are omitted.")),modules:_.record(_.string().describe("Module name (keys correspond to entries in `modules`)"),_.string().describe("Slash-separated folder name path that the module lives in."))}),xre=_.object({tests:_.record(_.string().describe("Test name"),_.string().describe("Test YAML")),modules:_.record(_.string().describe("Module name"),_.string().describe("Module YAML")),folderPaths:SYe.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.")}),TYe=_.object({test:_.string().describe("test YAML"),modules:_.record(_.string().describe("moduleId"),_.string().describe("module YAML"))});TYe.array();_.object({testId:_.string(),schemaVersion:_.string()}).merge(Mp);function yM(e){let{gitMainBranch:t,gitBranchName:o,gitCommitTimestamp:n,lastCommitOnMainSha:r,lastCommitOnMainTimestamp:i}=e,a={};return t&&(a[pYe]=encodeURIComponent(t)),o&&(a[hYe]=encodeURIComponent(o)),n&&(a[gYe]=n.toISOString()),r&&(a[fYe]=encodeURIComponent(r)),i&&(a[yYe]=i.toISOString()),e.mergedGitBranchName&&(a[bYe]=encodeURIComponent(e.mergedGitBranchName)),a}_.object({entries:_.array(f9)});_.object({platform:AG.optional(),entries:_.array(Ane)});_.object({testId:_.string(),environment:_.string().optional(),platform:AG.optional()});_.object({testId:_.string(),key:_.string(),environment:_.string().optional()});function _re(e){return _.record(_.string(),_.unknown().optional()).transform(t=>{let o={};for(let[n,r]of Object.entries(t)){let i=e.safeParse(r);i.success&&(o[n]=i.data);}return o})}var Ore=_re(y9),Pre=Ene.array();function bre(e){return _re(HR(e))}var kre={ANDROID:e=>bre(Hk).parse(e),IOS:e=>bre($k).parse(e)},vYe=_.object({id:_.string(),completionType:_.string(),description:_.string().optional(),thoughts:_.string(),result:_.string(),sessionType:_.string(),timeCreated:_.string().optional(),citations:_.array(Kn).optional()}),AYe=_.object({id:_.string(),assertion:_.string().optional(),result:_.string(),thoughts:_.string(),sessionType:_.string(),timeCreated:_.string().optional(),citations:_.array(Kn).optional()});_.object({completionType:_.string(),traceIds:_.string().array()});var OG=_.union([vYe,AYe]).array(),Mre=_.object({trigger:_.nativeEnum(ic),status:_.nativeEnum(ho),startedAt:_.coerce.date().optional(),gitCommitSha:_.string().optional(),gitCommitShaShort:_.string().optional(),gitCommitTimestamp:_.coerce.date().optional(),gitBranchName:_.string().optional(),gitOriginUrl:_.string().optional(),gitCommitMessage:_.string().optional(),gitCommitAuthorName:_.string().optional(),projectName:_.string().optional(),relativeProjectDir:_.string().optional(),githubRepository:_.string().optional(),gitlabProjectPath:_.string().optional(),pipelineId:_.string().optional(),cliVersion:_.string().optional()});_.object({id:_.string()});var Lre=_.object({status:_.nativeEnum(ho),updatedAt:_.coerce.date().optional(),finishedAt:_.coerce.date().optional()});_.object({summary:Zy,githubRepository:_.string().optional(),gitBranchName:_.string().optional()});var EYe=_.object({runId:_.string(),healStatus:Qy,healDetails:Pg.optional()});_.object({updates:EYe.array()});var Nre=_.object({stepsSnapshot:_.array(_.record(_.string(),_.unknown().optional())).optional(),beforeStepsSnapshot:_.array(_.record(_.string(),_.unknown().optional())).optional(),afterStepsSnapshot:_.array(_.record(_.string(),_.unknown().optional())).optional(),runGroupId:_.string().optional(),testId:_.string(),testName:_.string(),resolvedBaseUrl:_.string().optional(),environmentName:_.string().optional(),labels:_.array(_.string()).optional(),cliVersion:_.string().optional(),trigger:_.nativeEnum(ic),schemaVersion:_.string().optional(),section:_.nativeEnum(Sk).optional(),resolvedInputs:_.record(_.string(),_.string()).optional(),quarantined:_.boolean().optional().default(false),quarantinedReason:_.string().optional(),aiSettings:_l.optional()});_.object({id:_.string()});var wYe=r1.pick({id:true,status:true,healStatus:true,healDetails:true,testName:true,testId:true,test:true,failureReason:true,failureDetails:true}),Dre=wYe.array(),Fre=r1.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,runAssertionResults:true}).partial();_.object({id:_.string()});var bM=_.object({run:js.omit({runAttempts:true}),attemptZipUrls:_.array(_.string().url().nullish())}),Bre=_.object({status:_.nativeEnum(ho),finishedAt:_.coerce.date().optional(),schemaVersion:_.string().optional().default("1.0.19"),results:_.record(_.string(),_.unknown().optional()).array().optional(),beforeResults:_.record(_.string(),_.unknown().optional()).array().optional(),afterResults:_.record(_.string(),_.unknown().optional()).array().optional()});_.object({screenshot:_.string(),contentType:_.enum(["image/jpeg","image/png"]).optional()});_.object({id:_.string(),screenshot:_.string(),contentType:_.enum(["image/jpeg","image/png"])});var Ure=_.object({key:_.string()}),jre=_.object({orgId:_.string(),userId:_.string(),email:_.string().optional(),name:_.string().optional(),pylonEmailHash:_.string().optional(),selfServe:_.boolean().optional(),heardAboutAnswered:_.boolean().optional(),needsWorkspaceName:_.boolean().optional(),orgName:_.string().optional()}),zre=_.object({blocked:_.boolean()}),Hre=_.array(X8),$re=_.record(_.string(),_.union([_.string(),_.boolean()]));_.object({workosAccessToken:_.string().min(1),organizationId:_.string().optional(),clientName:_.string().min(1).max(80).optional()});var Gre=_.object({apiKey:_.string(),apiKeyName:_.string(),organizationId:_.string(),user:_.object({id:_.string(),email:_.string().optional()}),selfServe:_.boolean().optional()}),Vre=_.object({error:_.literal("multiple_organizations"),organizations:_.array(_.object({id:_.string(),name:_.string()}))}),RYe=80,CYe=_.string().trim().min(1).max(RYe);_.object({name:CYe});var IYe=["web","ios","android"];_.object({platforms:_.array(_.enum(IYe)),packageManager:_.enum(["npm","pnpm","yarn","bun"]),wizardVersion:_.string().min(1).max(40),cliVersions:_.object({momentic:_.string().max(40).optional(),momenticMobile:_.string().max(40).optional()}).optional(),firstRunIds:_.array(_.guid()).max(10).optional(),heardAboutSource:t1.optional(),heardAboutSourceOtherText:_.string().max(200).optional()});_.object({ok:_.literal(true)});_.object({paths:_.string().array(),env:_.string().optional(),urlOverride:_.string().optional(),customHeaders:_.record(_.string(),_.string()).optional()});var Wre=_.object({suiteRunIds:_.string().array(),runGroupIds:_.string().array()});_.object({suiteRunIds:_.string().array()});NZ.array();_.object({runGroupIds:_.string().array()});var SM=_.object({uploadUrl:_.string()});_i.merge(WZ);_i.merge(KZ);_i.merge(qZ);var TM=_.object({runId:_.string().optional().default(""),runGroupId:_.string().optional().default(""),envName:_.string().optional().default(""),platform:_.string().optional().default(""),testId:_.string().optional().default(""),testName:_.string().optional().default(""),suiteId:_.string().optional().default(""),suiteName:_.string().optional().default(""),isInteractive:_.boolean().optional().default(false),runner:_.nativeEnum(us).optional(),aiFeature:_.nativeEnum(Ug).optional(),cached:_.boolean().optional(),outcome:_.nativeEnum(av).optional(),hasFixedTest:_.boolean().optional(),hasCannotFixTest:_.boolean().optional(),hasNoFixNeededTest:_.boolean().optional(),result:_.enum(["success","failure"]).optional(),creditsUsed:_.number().optional(),stepsExecuted:_.number().optional(),tokensUsed:_.number().optional(),aiCostUsd:_.number().nonnegative().optional(),[vee]:_.string().optional(),agentInvocationId:_.string().optional(),moRuntimeSecondsUsed:_.number().nonnegative().optional(),moSpend:_.number().nonnegative().optional(),hostedBrowserSecondsUsed:_.number().optional(),sessionMinutesUsed:_.number().nonnegative().optional(),labels:_.array(_.string()).optional()});_.object({orgId:_.string(),runId:_.string().optional(),testId:_.string().optional(),isInteractive:_.boolean().optional(),runner:_.nativeEnum(us).optional()});var xYe=_.object({transactionId:_.string(),timestamp:_.string(),event:_.nativeEnum(lb),properties:TM});xYe.array();var qre=eoe.omit({steps:true}).extend({steps:_.array(_.record(_.string(),_.unknown().optional())).describe("unparsed ResolvedStep[]")});_.object({limit:_.number().min(1).max(10).optional(),page:_.number().min(1).optional(),start:br.optional(),end:br.optional(),gitBranchName:_.string().optional(),status:_.nativeEnum(ho).optional()});var Kre=EZ.array(),Yre=js.array(),WC=Hg.extend({executionType:Hp.array().min(1).optional(),testId:Lr.optional(),gitBranchName:_.string().optional(),gitCommitSha:_.string().optional(),status:_.nativeEnum(ho).optional(),label:_.string().array().optional(),start:br.optional(),end:br.optional(),quarantined:_.boolean().optional(),recovered:_.boolean().optional(),failureCategory:_.string().min(1).array().min(1).optional().describe("Effective built-in or custom failure category IDs. Manual classifications override automated classifications."),minAttempts:_.number().int().min(2).optional().describe("Minimum total attempt count, including the first attempt."),includeFailureDetails:_.boolean().optional(),skipRetentionFilter:_.boolean().optional()});WC.extend({orgId:_.string().optional(),testId:Xi(Lr),status:Xi(_.nativeEnum(ho)),gitBranchName:Xi(_.string()),label:Xi(_.string()),testName:_.string().optional(),trigger:Xi(_.nativeEnum(ic)),executionType:Xi(Hp),cliVersion:Xi(_.string()),githubRepository:Xi(_.string()),gitlabProjectPath:Xi(_.string()),environment:Xi(_.string()),directory:Xi(_.string()),failureCategory:Xi(_.string()),exclude:Xi(_.string()),healed:_.boolean().optional()});var _Ye=js.omit({test:true}),Jre=iG.extend({runs:_Ye.array(),executionTypeFilterApplied:_.boolean().optional()});_.object({applied:_.boolean().optional(),appliedAt:_.coerce.date().optional()});var Xre=SM.extend({id:_.string()}),OYe=_.object({resultType:_.literal("run").optional().default("run"),runGroupId:_.guid().optional(),persist:_.boolean().optional()}),PYe=_.object({resultType:_.literal("explore"),exploreRunId:_.guid(),persist:_.boolean().optional()});_.discriminatedUnion("resultType",[OYe,PYe]);var Qre=_.object({runGroupId:_.guid()}),kYe=_.object({status:Qy,runId:_.string(),rootCause:_.string().nullable().optional(),solution:_.string().nullable().optional(),verificationNotes:_.string().nullable().optional(),markedAt:_.string()}),Zre=_.object({quarantined:_.object({testId:Lr,quarantinedAt:_.coerce.date(),quarantinedBy:_.string().optional(),quarantinedReason:_.string(),verdict:kYe.nullish().default(null)}).array()}),PG=Hg.extend({limit:Hg.shape.limit.describe("Max number of quarantined tests to return per page."),page:Hg.shape.page.describe("Page number for pagination (1-based)."),quarantinedAtStart:_.string().pipe(_.coerce.date()).optional().describe("Include tests quarantined at or after this timestamp."),quarantinedAtEnd:_.string().pipe(_.coerce.date()).optional().describe("Include tests quarantined before this timestamp.")}),MYe=_.object({id:_.string(),status:_.literal("FAILED"),startedAt:br,finishedAt:br,failureReason:_.string().nullish(),healStatus:Qy,healDetails:Pg.nullish()}),eie=iG.extend({quarantinedTests:_.array(_.object({testId:Lr,testName:_.string().nullish(),quarantinedAt:br,quarantineReason:_.string(),latestFailedRun:MYe.nullable()}))}),tie=_.object({gitLocalUsername:_.string().optional(),gitLocalEmail:_.string().optional(),gitLocalName:_.string().optional()});_.object({testId:Lr,testName:_.string().optional(),reason:_.string()}).merge(tie);_.object({testName:_.string().optional(),reason:_.string().optional()}).merge(tie);_i.merge(uee);_i.merge(dee);_i.merge(mee);_.object({apkToInstall:_.object({channel:_.string(),tag:_.string().optional()}).optional(),hostname:_.string().optional(),region:G1.optional(),jurisdiction:IC.optional(),osVersion:_.nativeEnum(lv).optional(),sessionId:_.string().optional(),runId:_.string().optional(),testId:_.string().optional(),playwrightVersion:Iee.optional()});var oie=_.object({name:_.string(),apiUrl:_.string(),webRtcUrl:_.string(),adbUrl:_.string(),token:_.string(),apkDownloadUrl:_.string().optional(),playwrightServerUrl:_.string().optional(),region:_.string().optional(),resolvedTag:_.string().optional(),sessionExpiresAt:_.number().optional()});_.object({appToInstall:_.object({channel:_.string(),tag:_.string().optional()}).optional(),hostname:_.string().optional(),region:G1.optional(),jurisdiction:IC.optional(),osVersion:_.nativeEnum(Vk).optional(),sessionId:_.string().optional(),runId:_.string().optional(),testId:_.string().optional(),installAppOnClient:_.boolean().optional()});var nie=_.object({id:_.string(),apiUrl:_.string(),webRtcUrl:_.string(),wdaUrl:_.string(),token:_.string(),appDownloadUrl:_.string().optional(),appMd5:_.string().optional(),region:_.string().optional(),resolvedTag:_.string().optional(),sessionExpiresAt:_.number().optional()});_.object({channel:_.string().trim().min(1,"channel must be a non-empty string"),tag:_.string().trim().min(1,"tag must be a non-empty string").refine(e=>e.toLowerCase()!==GR,{message:`"${GR}" is a reserved tag and cannot be used when uploading an asset.`}).optional(),alias:_.string().trim().min(1,"alias must be a non-empty string").refine(e=>e.toLowerCase()!==GR,{message:`"${GR}" is a reserved alias and cannot be assigned when uploading an asset.`}).optional(),md5:_.string()});var rie=_.object({id:_.string(),tag:_.string().optional(),alias:_.string().optional(),uploadUrl:_.string().optional(),downloadUrl:_.string(),md5:_.string().optional()}),LYe=_.object({channel:_.string(),tag:_.string(),md5:_.string(),platform:_.nativeEnum(Kc).default("ANDROID"),createdAt:_.number().describe("Unix timestamp in milliseconds")}),NYe=_.object({channel:_.string(),alias:_.string(),platform:_.nativeEnum(Kc).default("ANDROID"),tag:_.string()}),iie=_.object({assets:_.array(LYe),aliases:_.array(NYe).default([])}),aie=_.object({downloadUrl:_.string()}),vM=(o=>(o.PLAYWRIGHT="PLAYWRIGHT",o.CDP="CDP",o))(vM||{}),DYe=_.nativeEnum(vM),sie=_.string().trim().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,79}$/);_.object({access:sie.optional(),envName:_.string().optional(),moSessionId:_.string().min(1).max(128).optional(),runAttemptId:_.guid().optional(),runGroupId:_.guid().optional(),testId:_.string().optional(),testName:_.string().optional(),runId:_.guid().optional(),attemptedProviders:_.array(Zk).optional(),localhostTunnel:_.boolean().optional()});var FYe=_.object({access:sie.optional(),allocationRequestId:_.guid(),browserFleetRegion:HC.optional(),envName:_.string().optional(),runAttemptId:_.guid(),runGroupId:_.guid().optional(),runId:_.guid(),testId:_.string().min(1).max(128),testName:_.string().optional()});FYe.extend({attemptedProviders:_.array(Zk).max(Object.values(zC).length).default([])}).strict();var BYe=_.discriminatedUnion("mode",[_.object({mode:_.literal("playwright")}).strict(),_.object({mode:_.literal("private-service"),connectorId:_.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/),serviceIds:_.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/).array().min(1).max(32).refine(e=>new Set(e).size===e.length,{message:"service IDs must be unique"}).optional()}).strict()]),lie=_.object({accessToken:_.string().min(1),expiresAt:_.iso.datetime(),fleetApiUrl:_.url(),provider:_.literal("SELF_HOSTED"),tokenType:_.literal("Bearer")}),UYe=lie.extend({network:BYe}).strict(),cie=_.union([UYe,lie.strict()]),jYe=_.object({hostname:_.string(),lease:_.string(),server:_.object({host:_.string(),port:_.number().int().positive()})}),uie=_.object({wsEndpoint:_.string(),accessToken:_.string().optional(),endpointType:DYe.optional(),provider:Zk.optional(),operatingSystem:Zte.optional(),tunnel:jYe.optional()});var zYe=200,HYe=2e3,qC=z.string().trim().min(1).max(zYe),Vg=z.string().trim().min(1).max(HYe),Av=z.array(Vg),$Ye=z.enum(["verified","issues_found","blocked"]),AM=z.object({customFields:JR.optional().catch(void 0),name:qC,summary:Vg,preconditions:Av,outline:Av,acceptanceCriteria:Av}),GYe=z.object({startedAt:z.number(),finishedAt:z.number(),agentId:z.string().optional(),windowId:z.string().optional(),artifactId:z.string().optional()}),VYe=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.(?:jpg|png)$/),WYe=z.object({artifactId:VYe,mediaType:z.enum(["image/jpeg","image/png"])}).refine(({artifactId:e,mediaType:t})=>e.endsWith(t==="image/png"?".png":".jpg"),"Screenshot filename extension must match its media type"),qYe=z.enum(["bug","flag"]),EM=z.object({customFields:JR.optional().catch(void 0),kind:qYe.default("bug"),name:qC,summary:Vg,expected:Vg,actual:Vg,reproSteps:Av,recording:GYe.nullish(),screenshot:WYe.nullish()}),mie=z.object({name:qC.describe("The name of the bug to retract."),reason:z.enum(["duplicate","invalid"]).describe("Why the bug report is being retracted.")}),kG=z.enum(["checked","failed","partial","out_of_scope"]),gb=z.object({control:qC,status:kG,result:Vg}),MG=z.object({status:$Ye,summary:Vg,verified:Av,gaps:Av});z.object({entry:AM});z.object({entry:EM});z.object({entry:gb});z.object({report:MG});z.object({entries:z.array(AM)});z.object({entries:z.array(EM)});z.object({entries:z.array(gb)});z.object({report:MG.nullable()});var LG=z.object({agent:z.string().nullable(),conversationId:z.string().nullable(),createdAt:z.iso.datetime(),updatedAt:z.iso.datetime()}),KYe=AM.extend({...LG.shape,blockedReason:z.string().nullable()}),YYe=EM.extend({...LG.shape,investigatorAgent:z.string().nullable(),investigatorConversationId:z.string().nullable(),reviewedAt:z.iso.datetime().nullable()});gb.extend({agent:z.string(),conversationId:z.string()});var JYe=MG.extend({testCaseName:z.string().nullable(),...LG.shape}),NG=z.enum(["OPEN","ACCEPTED","DUPLICATE","WORKS_AS_INTENDED","CANNOT_REPRODUCE"]);z.object({bugName:z.string(),status:NG,knowledgeItemId:z.string().nullable(),updatedByUserId:z.string().nullable(),updatedAt:z.iso.datetime()});z.object({chatId:z.string().min(1),bugName:qC,status:NG,reviewedKnowledgeItemIds:z.array(z.string().min(1)).optional(),reviewedKnowledgeItemStatus:K9.optional(),linkedKnowledgeItemId:z.string().min(1).nullable().optional()});z.object({entries:z.array(KYe)});z.object({entries:z.array(YYe)});z.object({entries:z.array(JYe)});var die=z.object({testCases:z.number(),issuesFound:z.number(),blocked:z.number(),bugs:z.number(),bugsByTriage:z.record(NG,z.number())});z.union([die.extend({passed:z.number()}),die.extend({verified:z.number()}).transform(({verified:e,...t})=>({...t,passed:e}))]);z.object({entry:AM});z.object({retracted:z.boolean(),conflict:z.string().optional()});z.object({entry:EM,reporterAgent:z.string().min(1).optional(),reporterConversationId:z.string().min(1).optional()}).superRefine((e,t)=>{e.entry.kind!=="flag"||e.entry.screenshot||t.addIssue({code:"custom",message:"Flags require a screenshot",path:["entry","screenshot"]});}).refine(e=>e.reporterAgent===void 0==(e.reporterConversationId===void 0),"reporterAgent and reporterConversationId must be provided together");z.object({reason:Vg});var pie=z.object({id:z.string(),createdAt:z.coerce.date(),createdBy:z.string(),organizationId:z.string(),name:z.string(),description:z.string().nullish(),enabled:z.boolean(),schemaVersion:z.string().describe("Schema version for steps"),parameters:z.string().array().nullish().describe("Parameter list"),parameterEnums:z.record(z.string(),z.string().array()).nullish(),defaultParameters:z.record(z.string(),z.string()).nullish(),defaultCacheKey:z.string().nullish(),defaultCacheTtl:z.number().nullish(),defaultCacheAllInvocations:z.boolean().nullish(),autoAuth:z.boolean().nullish(),defaultRetries:z.int().min(0).nullish(),advanced:YH.nullish()});pie.extend({steps:z.lazy(()=>Bo.array())});var hie=5*60*1e3,KC=kr.extend(pie.omit({id:true,createdAt:true,createdBy:true,organizationId:true,enabled:true}).shape);var XYe="org_01HMJTX4GT1KG94KZRCT8MZ6YB",QYe="org_01HMSCJQBCCG51M2ZF65YC5B8W",ZYe="org_01JPR6MGFQSHF3W234R3XJDPMB";var e4e=[XYe,QYe,ZYe];function fb(e){return e4e.includes(e)}var gie=z.object({id:z.string(),title:z.string(),body:z.string(),imageUrl:z.string().nullable(),videoUrl:z.string().nullable(),ctaUrl:z.string().nullable(),publishedAt:z.string()});z.object({update:gie.nullable()});var fie=z.object({updates:gie.array()});z.object({repositoriesIndexed:z.boolean(),indexingInProgress:z.boolean(),indexesOutdated:z.boolean()});var yie=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(yie||{}),bie=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(bie||{});z.object({name:z.string(),status:z.enum(yie),conclusion:z.enum(bie).nullable()});var YC=z.object({sha:z.string(),parentShas:z.array(z.string()).optional(),message:z.string(),author:z.object({name:z.string().optional(),email:z.string().optional(),date:z.coerce.date().optional()}),committer:z.object({name:z.string().optional(),email:z.string().optional(),date:z.coerce.date().optional()})}),DG=z.object({mergedBranch:z.string().optional()});var Sie=z.object({orgId:z.string(),cacheKeys:z.string().array()});z.object({keyParams:Sie,clientMetadata:z.string(),lockAcquisitionTimeoutMs:z.number().optional()});var Tie=z.object({acquired:z.boolean(),acquiredByMetadata:z.string(),keyPrefix:z.string()});z.object({keyPrefix:z.string(),result:z.string(),ttlMs:z.number()});z.union([z.object({keyPrefix:z.string()}),Sie]);var t4e=z.object({remainingTtlMs:z.number(),value:z.string().nullish()});z.object({results:z.record(z.string(),t4e),activeLocks:z.string().array()});var vie=0,Aie=5*60*1e3;var Eie=z.object({cacheEntryId:z.string().uuid(),category:z.string().min(1)}),wie={isManualOverride:z.boolean().optional(),manualOverrideOf:Eie.optional()},Rie=Gw.extend({identityVersion:z.literal(Xl),cacheEntryId:z.string().uuid().optional(),runId:z.string().min(1).optional(),executionFailureReason:z.string().min(1).optional(),classification:aP,healDetails:w$.optional(),...wie}),Cie=cT.extend({identityVersion:z.literal(jy).optional(),cacheEntryId:z.string().uuid().optional(),runId:z.string().min(1).optional(),testId:z.string().min(1),executionFailureReason:z.string().min(1).optional(),classification:aP,healDetails:w$.optional()}),o4e=z.union([Rie,Cie]),Iie={overriddenBy:Eie.optional(),createdAt:z.coerce.date(),updatedAt:z.coerce.date()},n4e=Rie.extend({cacheEntryId:z.string().uuid(),...Iie}),r4e=Cie.extend({...wie,...Iie}),i4e=r4e.transform(e=>({...e,identityVersion:jy})),xie=z.union([n4e,i4e]);function JC(e){return !e.branchName&&Vw(e.classification.category)}var a4e=Gw.extend({mainBranchName:z.string().min(1).optional()}),s4e=cT.extend({mainBranchName:z.string().min(1).optional(),testId:z.never().optional()}).transform(({testId:e,...t})=>t);z.union([a4e,s4e]);var _ie=xie.array();z.object({entries:o4e.array()});var l4e=Gw.extend({cacheEntryId:z.string().uuid(),runId:z.string().min(1),category:z.string().min(1)}),c4e=cT.extend({testId:z.never().optional(),runId:z.string().min(1),cacheEntryId:z.string().uuid(),category:z.string().min(1)}).transform(({testId:e,...t})=>t);z.union([l4e,c4e]);z.object({status:z.enum(["evicted","not_found","run_mismatch"]),entry:xie.optional()});z.object({runId:z.string().min(1),environment:z.string().min(1).optional(),status:z.enum(["PASSED","FAILED"])});z.object({environment:z.string().min(1).optional()});var wM=z.object({skip:z.boolean(),failed:z.number(),total:z.number()}),u4e=.8;function Oie({failed:e,completed:t,minCompletedRuns:o}){return t>=o&&e/t>=u4e}function Ev(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 d4e=z.object({version:z.string(),json:z.record(z.string(),z.unknown().optional()),hash:z.string()}),Pie=z.record(z.string(),z.unknown().optional());z.object({newSvgs:z.array(d4e),metadata:Pie.optional()});var m4e=z.object({version:z.string(),json:z.record(z.string(),z.unknown().optional()).nullish(),hash:z.string(),description:z.string().nullish(),metadata:Pie.nullish()}),kie=z.record(z.string().describe("icon hash"),m4e);var FG="metadata.json",BG="test.yaml",Mie=".snapshot.zip",UG=Ir.extend(oc.shape),p4e=z.object({envName:z.string().optional(),baseUrl:z.string(),variables:z.record(z.string(),z.unknown().optional()),resolvedEnv:FR.optional()}),Lie=z.object({browser:Ju.optional(),ai:_l.optional(),advanced:XR.optional(),retries:z.number().optional()});z.object({momenticVersion:z.string(),schemaVersion:z.string(),createdAt:z.string(),relativeFilePath:z.string(),environment:p4e,config:Lie});var Nie=z.object({variables:z.record(z.string(),z.unknown().optional()),resolvedEnv:FR.optional()}),h4e=z.object({envName:z.string().optional(),baseUrl:z.string(),encryptedSecrets:z.string()}),Die=z.object({momenticVersion:z.string(),schemaVersion:z.string(),createdAt:z.string(),relativeFilePath:z.string(),environment:h4e,config:Lie});var g4e=z.looseObject({type:z.number(),data:z.record(z.string(),z.unknown()),timestamp:z.number()}),jG=z.custom(e=>g4e.safeParse(e).success);z.object({segments:z.array(z.object({artifactId:z.string(),startedAt:z.number(),finishedAt:z.number(),events:z.array(jG)}))});z.discriminatedUnion("kind",[z.object({kind:z.literal("agent-action"),tool:z.string(),toolCallId:z.string().optional(),detail:z.string().optional(),input:z.unknown().optional()}),z.object({kind:z.literal("step"),phase:z.enum(["start","pass","fail"]),name:z.string()}),z.object({kind:z.literal("window"),phase:z.enum(["start","stop"]),windowId:z.string()}),z.object({kind:z.literal("bug-marker"),title:z.string()}),z.object({kind:z.literal("control"),control:z.string(),status:kG}),z.object({kind:z.literal("network-error"),method:z.string(),url:z.string(),status:z.number()})]);z.looseObject({level:z.string(),payload:z.array(z.string()),trace:z.array(z.string()).optional()});function Fie(e){let t;try{t=JSON.parse(e);}catch(o){return `The schema is not valid JSON. ${o}`}try{validator(t);}catch(o){return `The schema is not a valid JSON schema. ${o}`}}var Bie=e=>{e.extraHeaders&&(e.extraHeaders=Object.fromEntries(Object.entries(e.extraHeaders).filter(([t,o])=>t.trim()&&o.trim())));};var RM=class{async prepareGoldenScreenshotForComparison(t,o,n){return n}};var CM=class{async resolveStepCacheEntries(){return {}}async saveStepCacheEntries(){}async saveSnapshotCacheEntries(){}async deleteStepCacheEntry(){}};function y4e(e){return e.map(t=>({...t,environment:void 0}))}function zG(e,t){return t?e:y4e(e)}var $G="browser-crash-dump.zip",HG=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new XC}},XC=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new HG}flushResults(t){}};var Mt="metadata.json",Ks="assets",ar="runs",GG=z.object({type:z.literal("explore"),id:z.string(),cliVersion:z.string().optional(),startedAt:z.string(),finishedAt:z.string(),baseSha:z.string(),headSha:z.string(),ciProvider:z.string().optional(),pipelineId:z.string().optional(),gitMainBranch:z.string().optional(),gitCommitSha:z.string().optional(),gitCommitShaShort:z.string().optional(),gitBranchName:z.string().optional(),gitOriginUrl:z.string().optional(),gitCommitMessage:z.string().optional(),gitCommitAuthorName:z.string().optional(),githubRepository:z.string().optional(),gitlabProjectPath:z.string().optional(),pullRequestUrl:z.string().optional(),result:z.unknown(),bugs:z.array(z.unknown()),uxNits:z.array(z.unknown()).default([]),writtenPaths:z.array(z.string()),videos:z.array(z.string()),failure:z.unknown().optional()});z.object({exploreRunId:z.guid(),metadata:GG,videoAssets:z.string().array().optional()});var Uie=z.object({uploadUrl:z.string(),videoUploadUrls:z.record(z.string(),z.string()).optional()}),b4e=z.object({step:Uo,status:z.enum(io),startedAt:z.coerce.date(),finishedAt:z.coerce.date().optional(),healMetadata:z.object({healType:z.enum($R).or(z.literal("AI")),healedAt:z.coerce.date()}).optional(),beforeSnapshotId:z.guid().optional(),afterSnapshotId:z.guid().optional(),message:z.string().optional()}),S4e=b4e.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});S4e.extend({step:z.unknown().optional()});var VG=z.object({avdId:z.string().optional(),channel:z.string().optional(),tag:z.string().optional(),region:z.string().optional(),osVersion:xee.optional()}),jie="1.0.0",zie=Bre.extend({id:z.guid().optional(),startedAt:z.coerce.date(),runAttemptSchemaVersion:z.string().optional(),schemaVersion:z.string().optional().default("1.0.19"),results:z.record(z.string(),z.unknown().optional()).array().optional(),beforeResults:z.record(z.string(),z.unknown().optional()).array().optional(),afterResults:z.record(z.string(),z.unknown().optional()).array().optional(),assetDetails:VG.optional(),networkCaptureEnabled:z.boolean().optional(),viewport:jp.optional(),activeVideos:z.array(z.object({videoName:z.string(),timestamp:z.coerce.date()})).optional()}),QC=zie.extend({assetDetails:VG.optional(),finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});zie.extend(U$.shape);var Hie=QC.extend(U$.shape),T4e=z.object({results:z.array(Hs),beforeResults:z.array(Hs).optional(),afterResults:z.array(Hs).optional()});QC.extend(T4e.shape);var v4e=z.object({results:z.array($s),beforeResults:z.array($s).optional(),afterResults:z.array($s).optional()});QC.extend(v4e.shape);var A4e=z.object({creditsUsed:z.number(),stepsExecuted:z.number()}),$ie=Fre.merge(Nre).extend({executionType:Hp.optional().default("WEB"),testId:Lr,testDescription:z.string().optional(),directory:z.string().optional(),runGroupId:z.guid(),status:z.enum(ho),healStatus:Qy,testBundleHash:z.string().optional(),startedAt:z.coerce.date(),schemaVersion:z.string().nullish(),attempts:z.number(),failureRecoveryDetails:z.object({attempts:z.number()}).optional(),aiSettings:_l.optional(),avgCpuUsage:z.number().optional(),avgMemoryUsage:z.number().optional(),usage:A4e.optional().catch(void 0)}),E4e=$ie.extend(VG.shape),Wg=$ie.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});E4e.extend({finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});var IM=1e4,w4e=Mre.merge(Lre).extend({id:z.guid().optional(),startedAt:z.coerce.date(),cliVersion:z.string(),labels:z.string().array().optional().default([]),suiteName:z.string().optional(),ciProvider:z.string().optional(),gitMainBranch:z.string().optional(),ai:_l.optional(),browser:Ju.optional(),sourceRunGroupIds:z.array(z.guid()).max(IM).optional(),mergedAt:z.coerce.date().optional(),aiSelect:z.union([ZR.transform(e=>[e]),z.array(ZR)]).optional()}),iu=w4e.extend({healRiskSummary:Zy.optional(),updatedAt:z.coerce.date().optional().transform(e=>e??new Date),finishedAt:z.coerce.date().optional().transform(e=>e??new Date)});var R4e=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"]),C4e=new Set(["MODULE","RESOLVED_MODULE"]);function Gie(e){return e.type!=="PRESET_ACTION"?e.type:e.command.type}function Vie(e){return C4e.has(e.type)?false:e.type!=="PRESET_ACTION"?true:!R4e.has(e.command.type)}var Wie="progress.json",qie="1.0.0",I4e=z.object({runId:z.string(),testId:z.string().optional(),testName:z.string().optional(),directory:z.string().optional(),status:z.nativeEnum(ho),completedSteps:z.number(),totalSteps:z.number(),startedAt:z.coerce.date(),updatedAt:z.coerce.date()});z.object({schemaVersion:z.string(),runGroupId:z.string(),status:z.nativeEnum(ho),totalRuns:z.number(),completedRuns:z.number(),completedSteps:z.number(),totalSteps:z.number(),startedAt:z.coerce.date(),updatedAt:z.coerce.date(),runs:I4e.array()});function Kie(e,t){let o=Cn__default.relative(t,e);return o!==""&&o!==".."&&!o.startsWith(`..${Cn__default.sep}`)&&!Cn__default.isAbsolute(o)}function Yie(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch(t){return x.error({err:t},`Error reading path ${e} during directory existence check.`),false}}var Jie="CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih",wv="https://us-west.metrics.momentic.ai",Rv="c60c6a0f-60da-41a7-a61b-07969a0aa303",ms=!!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 N4e=new Set(["exit","quit"]),qG=(()=>{try{return statSync("/.dockerenv"),!0}catch{return false}})(),D4e=ms||qG||!process.stdin.isTTY;function Zie(){return !ms&&!qG&&!process.stdin.isTTY}async function ki(e){if(ms||qG)return true;if(!process.stdin.isTTY)throw new ae(`Cannot ask for confirmation: "${e}" No interactive terminal is available. Re-run with --yes or in a TTY.`);return await x.flush(),await new Promise(o=>setTimeout(o,100)),await confirm({message:e})}async function KG(e){let t=dirname(e);return Yie(t)?existsSync(e)?ki(`File '${Xie(e)}' already exists. Overwrite existing content?`):true:await ki(`Directory '${Xie(t)}' doesn't exist. Create it now?`)?(mkdirSync(t,{recursive:true}),true):false}function Xie(e){return e.replace(/(\s+)/g,"\\$1")}async function eae(e,t){return D4e?t:(await input({message:e,default:t})).trim()||t}async function YG(){let e;try{e=(await input({message:"ask"})).trim();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError"){x.info("");return}throw t}if(!N4e.has(e.toLowerCase()))return e}var Cv=new Map,rae=new Set;function q4e(e){rae.add(e);}function iae(e){q4e(t=>{e({category:"cli",level:t.severity_text==="ERROR"?"error":t.severity_text==="WARN"?"warning":"info",message:t.body,timestamp:t.timestamp/1e9});});}var oae="Log throttle exceeded",Y4e=100,J4e=5e3,X4e=2e4,Q4e=H4e(global.fetch,{retries:2,retryOn:function(e,t,o){return !!(t!==null||o&&o.status>=500)},retryDelay:function(e){return Math.pow(2,e)*500}});function Z4e({app:e,hostname:t,environment:o,serviceVersion:n}){return {host:t,env:o,[ATTR_SERVICE_NAME]:e,...n?{[ATTR_SERVICE_VERSION]:n}:{}}}var e3e=`${wv}/logs/json`,JG=class{constructor(t,o){this.flushIntervalMs=t;this.maxBatchSize=o;}records=[];flushTimer;flushRequested=false;flushPromise;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(){this.flushRequested=true,this.flushPromise??=Promise.resolve().then(async()=>{try{for(;this.flushRequested;){this.flushRequested=!1;let t=this.records;this.records=[];for(let o=0;o<t.length;o+=this.maxBatchSize)await this.sendBatch(t.slice(o,o+this.maxBatchSize));}}finally{this.flushPromise=void 0;}}),await this.flushPromise;}async sendBatch(t){try{let o=await Q4e(e3e,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":Jie,"x-momentic-metrics-api-key":Rv},body:Qu(t),signal:AbortSignal.timeout(X4e)});if(!o.ok)throw new Error(`Got error status (${o.statusText}) from SigNoz`)}catch{}}},XG=class e{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=false;lastWindowStart=Date.now();flushIntervalMs;maxBatchSize;buffer;constructor({bindings:t,hostname:o,disableConsoleLogs:n,flushIntervalMs:r,maxBatchSize:i,buffer:a}){this.hostname=o??Jp.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...t,env:"production"},this.flushIntervalMs=r??5e3,this.maxBatchSize=i??10,this.buffer=a??new JG(this.flushIntervalMs,this.maxBatchSize);let s={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=tae(s);}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===oae)return true;let o=Date.now();return o-this.lastWindowStart>J4e&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,oae),this.droppedLogsInWindow=false,this.lastWindowStart=o),this.logsInCurrentWindow<Y4e?(this.logsInCurrentWindow++,true):(this.droppedLogsInWindow=true,false)}log(t,o,n,...r){try{this.logHelper(t,o,n,...r);}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`);}}logHelper(t,o,n,...r){if(YR[t]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof o=="string"&&!n&&(o={message:o}),typeof o=="object"&&o&&"err"in o&&o.err instanceof Error&&(o.err=W4e.err(o.err));let i={...this.bindingAttributes,...o&&typeof o=="object"?o:{},...r.length>0?{args:r}:{}},a=Z4e({app:this.bindingAttributes.app,hostname:this.hostname,environment:this.bindingAttributes.env,serviceVersion:this.bindingAttributes.cliVersion??"3.62.3"}),s=t3e();this.disableConsoleLogs||this.consoleLogger[t]({...i,...s??{}},n,...r);let l={timestamp:Math.round(Date.now()*1e6),...s??{},severity_text:t.toUpperCase(),resources:a,attributes:{},body:uZ({message:n||"",...i})};this.buffer.push(l);for(let c of rae)try{c(l);}catch{}}setApp(t){let o=this.bindingAttributes.app;this.bindingAttributes.app=t,Cv.set("app",this),Cv.delete(o);}debug(t,o,...n){this.log("debug",t,o,...n);}info(t,o,...n){this.log("info",t,o,...n);}warn(t,o,...n){this.log("warn",t,o,...n);}error(t,o,...n){this.log("error",t,o,...n);}bindings(){return this.bindingAttributes}addBinding(t,o){this.bindingAttributes[t]=o;}setMinLevel(t){typeof t=="number"?(this.minLevelValue=t,this.consoleLogger.level=dZ[t]):(this.minLevelValue=YR[t],this.consoleLogger.level=t);}enableConsoleLogs(){this.disableConsoleLogs=false;}},Iv=({app:e,hostname:t,disableConsoleLogs:o})=>(Cv.has(e)||Cv.set(e,new XG({bindings:{app:e},hostname:t,disableConsoleLogs:o})),Cv.get(e));function t3e(){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 xM(){await Promise.all([...Cv.values()].map(e=>e.flush()));}var Ua=class extends Error{callSiteStack;constructor(t){super(t),this.name="TimeoutError";}};var aae=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 ye(e,t){let{milliseconds:o,fallback:n,message:r,customTimers:i={setTimeout,clearTimeout}}=t,a;if(typeof o!="number"||Math.sign(o)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);let s=new Error().stack;return new Promise((l,c)=>{let u,d=()=>{i.clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",u);};if(t.signal){let{signal:p}=t;if(p.aborted)return Promise.resolve(e).catch(()=>{}),c(aae(p));u=()=>{d(),c(aae(p));},p.addEventListener("abort",u,{once:true});}let m=()=>{if(t.signal&&t.signal.removeEventListener("abort",u),n)try{l(n());}catch(p){c(p);}else {if(typeof e.cancel=="function"&&Promise.resolve().then(()=>e.cancel()).catch(()=>{}),r instanceof Error){c(r);return}let p=new Ua(r??`Promise timed out after ${o}ms`);p.callSiteStack=s,c(p);}};o<1/0&&(a=i.setTimeout(m,o)),Promise.resolve(e).then(p=>{d(),l(p);}).catch(p=>{d(),c(p);});})}function au({signal:e,timeoutMs:t}){let o=AbortSignal.timeout(t);return e?AbortSignal.any([e,o]):o}var _M="organization";function OM(e){let t=new PostHog(e.writeKey,{host:e.host,...e.flushImmediately?{flushAt:1,flushInterval:0}:{}}),o=e.platform,n=(l,c,u)=>{let{type:d,...m}=l;t.capture({distinctId:c??u??randomUUID(),event:d,...u&&{groups:{[_M]:u}},properties:{platform:o,user_id:c??void 0,org_id:u??void 0,...m,organizationId:u??void 0,...c==null&&u==null&&{$process_person_profile:false}}});},r=({orgId:l,properties:c})=>{t.groupIdentify({groupType:_M,groupKey:l,properties:c});},i=({userId:l,properties:c})=>{Object.values(c).some(d=>d!=null&&d!=="")&&t.identify({distinctId:l,properties:c});},a=()=>t.shutdown();if(e.identity==="stashed"){let l=null;return {shutdownAnalytics:a,groupIdentifyOrg:r,setAnalyticsIdentity:u=>{l=u,e.onIdentify?.(u),i({userId:u.userId,properties:{email:u.email,...u.selfServe!==void 0?{self_serve:u.selfServe}:{}}});},captureEvent:u=>n(u,l?.userId??null,l?.orgId??null)}}return {shutdownAnalytics:a,groupIdentifyOrg:r,identifyUser:i,captureEvent:(l,{userId:c,orgId:u})=>n(l,c,u),captureBillingEvent:(l,{userId:c,orgId:u})=>n(l,c,u)}}async function sae(e,t,o){let n,r=0,i=3,a,s;for(;r<i;)try{let l=await ye(e.getAllFlagsAndPayloads(o??t,{personProperties:{organizationId:t},groups:{[_M]:t}}),{milliseconds:5e3});a=l.featureFlags||{},s=l.featureFlagPayloads||{};break}catch(l){n=l,r++,await new Promise(c=>setTimeout(c,100*r));}if(a&&s)return {flags:a,payloads:s};throw n}var PM=class e extends cb{constructor(o,n,r,i,a){super(i,a);this.client=o;this.orgId=n;this.userId=r;}static createClient(){return new PostHog("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://p.momentic.ai"})}static async init(o,n){let r=e.createClient(),{flags:i,payloads:a}=await sae(r,o,n);return new e(r,o,n,i,a)}static fromCached(o,n,r,i){return new e(e.createClient(),o,n,r,i)}async refresh(){let{flags:o,payloads:n}=await sae(this.client,this.orgId,this.userId);this.flags=o,this.payloads=n;}};var kM="/proc",lae="/sys/fs/cgroup",a3e="/sys/fs/cgroup/memory",cae=8,s3e=1024;function LM(){let e;return ()=>{if(process.platform!=="linux")return;let t=m3e();if(!t)return;let o=p3e({current:t,previous:e});return e=t,o}}function uae(){if(process.platform!=="linux")return;let e=QG(`${lae}/memory.stat`);if(e){let o=QG(`${lae}/memory.events`);return {anonymousBytes:e.anon,fileCacheBytes:e.file,kernelBytes:e.kernel,slabBytes:e.slab,sharedMemoryBytes:e.shmem,pageTablesBytes:e.pagetables,activeAnonymousBytes:e.active_anon,inactiveAnonymousBytes:e.inactive_anon,activeFileBytes:e.active_file,inactiveFileBytes:e.inactive_file,events:o?{low:o.low,high:o.high,max:o.max,oom:o.oom,oomKill:o.oom_kill,oomGroupKill:o.oom_group_kill}:void 0}}let t=QG(`${a3e}/memory.stat`);if(t)return {anonymousBytes:t.total_rss??t.rss,fileCacheBytes:t.total_cache??t.cache,slabBytes:t.total_slab??t.slab,sharedMemoryBytes:t.total_shmem??t.shmem,pageTablesBytes:t.total_pagetables??t.pagetables,activeAnonymousBytes:t.total_active_anon??t.active_anon,inactiveAnonymousBytes:t.total_inactive_anon??t.inactive_anon,activeFileBytes:t.total_active_file??t.active_file,inactiveFileBytes:t.total_inactive_file??t.inactive_file}}function l3e(e){let t={};for(let o of e.split(`
186
186
  `)){let[n,r]=o.trim().split(/\s+/,2);if(!n||!r)continue;let i=Number.parseInt(r,10);Number.isFinite(i)&&(t[n]=i);}return t}function c3e(e,t){let o,n,r;for(let i of t.split(`
187
187
  `)){let a=i.indexOf(":");if(a===-1)continue;let s=i.slice(0,a),l=i.slice(a+1).trim();if(s==="Name"&&(o=l),s==="PPid"&&(n=Number.parseInt(l,10)),s==="VmRSS"){let c=Number.parseInt(l,10);Number.isFinite(c)&&(r=c*s3e);}}if(!(!o||n===void 0||r===void 0))return {pid:e,parentPid:n,name:o,rssBytes:r}}function u3e(e){let t=e.lastIndexOf(")");if(t===-1)return;let o=e.slice(t+1).trim().split(/\s+/),n=Number.parseInt(o[11]??"",10),r=Number.parseInt(o[12]??"",10);if(!(!Number.isFinite(n)||!Number.isFinite(r)))return n+r}function d3e(e){let t=e.split(`
188
- `).find(n=>n.startsWith("cpu "));if(!t)return;let o=t.trim().split(/\s+/).slice(1).slice(0,8).map(n=>Number.parseInt(n,10));if(!(o.length===0||o.some(n=>!Number.isFinite(n))))return o.reduce((n,r)=>n+r,0)}function QG(e){try{return l3e(readFileSync(e,"utf8"))}catch{return}}function m3e(){let e;try{e=d3e(readFileSync(`${kM}/stat`,"utf8"));}catch{return}if(e===void 0)return;let t=new Map,o;try{o=readdirSync(kM);}catch{return}for(let n of o){if(!/^\d+$/.test(n))continue;let r=Number.parseInt(n,10);try{let i=c3e(r,readFileSync(`${kM}/${n}/status`,"utf8")),a=u3e(readFileSync(`${kM}/${n}/stat`,"utf8"));if(!i||a===void 0)continue;t.set(r,{...i,cpuTicks:a});}catch{}}return {totalTicks:e,processes:t}}function p3e({current:e,previous:t}){let o=t?e.totalTicks-t.totalTicks:void 0,n=h3e(e.processes),r=new Map,i=0,a=0,s=0,l=false;for(let u of e.processes.values()){i+=u.rssBytes;let d=t?.processes.get(u.pid),m=d?u.cpuTicks-d.cpuTicks:void 0,p=m!==void 0&&m>=0&&o!==void 0&&o>0?m/o*100:void 0,h=r.get(u.name)??{name:u.name,processCount:0,rssBytes:0};h.processCount++,h.rssBytes+=u.rssBytes,p!==void 0&&(h.cpuPercentage=(h.cpuPercentage??0)+p),r.set(u.name,h),n.has(u.pid)&&(a+=u.rssBytes,p!==void 0&&(s+=p,l=true));}let c=[...r.values()];return {visibleProcessCount:e.processes.size,visibleProcessRssBytes:i,currentProcessTreeCount:n.size,currentProcessTreeRssBytes:a,currentProcessTreeCpuPercentage:l?s:void 0,topMemoryProcessGroups:[...c].sort((u,d)=>d.rssBytes-u.rssBytes).slice(0,cae),topCpuProcessGroups:c.filter(u=>u.cpuPercentage!==void 0).sort((u,d)=>(d.cpuPercentage??0)-(u.cpuPercentage??0)).slice(0,cae)}}function h3e(e){let t=new Set;if(!e.has(process.pid))return t;t.add(process.pid);let o=true;for(;o;){o=false;for(let n of e.values())t.has(n.pid)||!t.has(n.parentPid)||(t.add(n.pid),o=true);}return t}var y3e=2e3,b3e=2e4,S3e=.1,T3e=70,v3e=.8,yb=e=>Number.parseInt(e,10),ZG=e=>readFileSync(e,"utf8").trim(),xv=e=>yb(ZG(e));function hae({summary:e,detailedSnapshots:t}){let o={"momentic.resource.samples":e.samples,"momentic.resource.low_memory_samples":e.lowMemorySamples,"momentic.resource.high_cpu_samples":e.highCpuSamples,"momentic.resource.high_heap_samples":e.highHeapSamples,"momentic.resource.min_free_memory_ratio":e.minFreeMemoryRatio,"momentic.resource.max_cpu_percentage":e.maxCpuPercentage,"momentic.resource.max_heap_usage_ratio":e.maxHeapUsageRatio,"momentic.resource.max_memory_used_bytes":e.maxMemoryUsedBytes,"momentic.resource.max_current_process_tree_rss_bytes":e.maxCurrentProcessTreeRssBytes,"momentic.resource.max_visible_process_rss_bytes":e.maxVisibleProcessRssBytes,"momentic.resource.detailed_snapshots":t};if(!t||!e.peakMemoryDetails)return o;let n=e.peakMemoryDetails.cgroupMemory,r=e.peakMemoryDetails.processes,i={"momentic.resource.peak_cgroup_anonymous_bytes":n?.anonymousBytes,"momentic.resource.peak_cgroup_file_cache_bytes":n?.fileCacheBytes,"momentic.resource.peak_cgroup_kernel_bytes":n?.kernelBytes,"momentic.resource.peak_cgroup_slab_bytes":n?.slabBytes,"momentic.resource.peak_cgroup_shared_memory_bytes":n?.sharedMemoryBytes,"momentic.resource.peak_cgroup_page_tables_bytes":n?.pageTablesBytes,"momentic.resource.peak_cgroup_oom_events":n?.events?.oom,"momentic.resource.peak_cgroup_oom_kill_events":n?.events?.oomKill,"momentic.resource.peak_cgroup_oom_group_kill_events":n?.events?.oomGroupKill};for(let[s,l]of Object.entries(i))l!==void 0&&(o[s]=l);o["momentic.resource.peak_detailed_memory_used_bytes"]=e.peakDetailedMemoryUsedBytes,r&&(o["momentic.resource.peak_memory_process_groups"]=JSON.stringify(r.topMemoryProcessGroups));let a=e.peakCpuDetails?.processes;return a&&(o["momentic.resource.peak_cpu_process_groups"]=JSON.stringify(a.topCpuProcessGroups),a.currentProcessTreeCpuPercentage!==void 0&&(o["momentic.resource.peak_current_process_tree_cpu_percentage"]=a.currentProcessTreeCpuPercentage)),o}var ZC={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0};function gae(){return {...ZC}}var NM=Jp.platform(),A3e=Jp.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 dae(e=Date.now()){let t=Jp.cpus(),o={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let n of t)o.user+=n.times.user,o.nice+=n.times.nice,o.sys+=n.times.sys,o.idle+=n.times.idle,o.irq+=n.times.irq;return o.total=o.user+o.nice+o.sys+o.idle+o.irq,o}function E3e(e,t){let o={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 o.total<=0?null:{measurementTime:t.measurementTime,intervalMs:t.measurementTime-e.measurementTime,user:o.user/o.total*100,nice:o.nice/o.total*100,sys:o.sys/o.total*100,idle:o.idle/o.total*100,irq:o.irq/o.total*100,total:100-o.idle/o.total*100}}function DM(){let e=dae();return ()=>{let t=dae(),o=E3e(e,t);return e=t,o}}function mae(){try{let t=readFileSync("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(t?.[1])return yb(t[1])}catch{}try{let e=xv("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(e))return e/1e3}catch{}return null}function w3e(){try{let t=ZG("/sys/fs/cgroup/cpu.max").split(" "),o=t[0],n=t[1];return !o||!n||o==="max"?null:yb(o)/yb(n)}catch{}try{let e=xv("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),t=xv("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return e===-1||isNaN(t)?null:e/t}catch{return null}}function FM(){if(NM!=="linux")return null;let e=mae();if(e===null)return null;let t=w3e()??Jp.cpus().length,o=e,n=Date.now();return ()=>{let r=mae();if(r===null)return null;let i=Date.now(),a=i-n;if(a<=0)return null;let s=r-o,l=a*1e3,c=Math.max(0,Math.min(100,s/l/t*100));return o=r,n=i,{measurementTime:i,intervalMs:a,user:c,nice:0,sys:0,idle:Math.max(0,100-c),irq:0,total:c}}}function R3e(){let e=process.cpuUsage(),t=process.hrtime.bigint();return ()=>{let o=process.cpuUsage(),n=process.hrtime.bigint(),r=Number(n-t)/1e6,i=o.user-e.user,a=o.system-e.system;if(e=o,t=n,r<=0)return null;let s=Math.max(Jp.cpus().length,1),l=c=>Math.max(0,c/1e3/r*100/s);return {total:l(i+a),user:l(i),sys:l(a),intervalMs:r}}}function fae({intervalMs:e=y3e,maxSamples:t=1e4,keepSamples:o=true,onSample:n}={}){let r=[],i=FM()??DM(),a=R3e(),s=()=>{let u=Date.now(),d=Sae(),m=process.memoryUsage(),p=i(),h=a(),g={timestamp:u,system:{cpu:p,memory:{total:d.totalMemory,free:d.freeMemory,freePercentage:d.freePercentage}},process:{cpu:h,memory:{rss:m.rss,heapTotal:m.heapTotal,heapUsed:m.heapUsed,external:m.external,arrayBuffers:m.arrayBuffers}}};n?.(g),o&&(r.push(g),r.length>t&&r.shift());};s();let l=setInterval(s,e),c=u=>({samples:o?[...r]:[]});return {stop:()=>(clearInterval(l),c()),getSeries:()=>c()}}var C3e=LM(),I3e=FM()??DM(),yae=e=>{e2({logger:e,processUsageTracker:C3e,cpuUsageTracker:I3e});},bae=e=>{let t=LM(),o=FM()??DM(),n=()=>e2({logger:e,processUsageTracker:t,cpuUsageTracker:o});n(),setTimeout(n,5e3);};function BM(e,t={}){let o=LM(),n=FM()??DM(),r={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0,minFreeMemoryRatio:1,maxCpuPercentage:0,maxHeapUsageRatio:0,maxMemoryUsedBytes:0,maxCurrentProcessTreeRssBytes:0,maxVisibleProcessRssBytes:0,peakDetailedMemoryUsedBytes:0},i=()=>{let a=e2({logger:e,processUsageTracker:o,cpuUsageTracker:n});if(!a)return;r.samples++,a.memoryPressure&&r.lowMemorySamples++,a.cpuPressure&&r.highCpuSamples++,a.heapPressure&&r.highHeapSamples++,r.minFreeMemoryRatio=Math.min(r.minFreeMemoryRatio,a.memory.freePercentage);let s=a.cpu?.total??0;a.details&&s>=r.maxCpuPercentage&&(r.peakCpuDetails=a.details),r.maxCpuPercentage=Math.max(r.maxCpuPercentage,s),r.maxHeapUsageRatio=Math.max(r.maxHeapUsageRatio,a.heapUsageRatio),r.maxMemoryUsedBytes=Math.max(r.maxMemoryUsedBytes,a.memory.totalMemory-a.memory.freeMemory),r.maxCurrentProcessTreeRssBytes=Math.max(r.maxCurrentProcessTreeRssBytes,a.details?.processes?.currentProcessTreeRssBytes??0),r.maxVisibleProcessRssBytes=Math.max(r.maxVisibleProcessRssBytes,a.details?.processes?.visibleProcessRssBytes??0);let l=a.memory.totalMemory-a.memory.freeMemory;a.details&&l>=r.peakDetailedMemoryUsedBytes&&(r.peakDetailedMemoryUsedBytes=l,r.peakMemoryDetails=a.details);};return i(),{interval:setInterval(i,t.intervalMs??b3e),cpuMetadata:A3e,platform:NM,getSummary:()=>({...r})}}function e2({logger:e,processUsageTracker:t,cpuUsageTracker:o}){try{let n={},r=Sae(),i=o();ZC.samples++;let a=r.freePercentage<.05;a&&(Object.assign(n,process.memoryUsage()),ZC.lowMemorySamples++);let s=i!==null&&i.total>80;s&&ZC.highCpuSamples++;let l=f3e.getHeapStatistics(),c=l.used_heap_size,u=l.heap_size_limit,d=c/u,m=d>.9;m&&ZC.highHeapSamples++;let p=a||s||m,g=r.freePercentage<S3e||i!==null&&i.total>T3e||d>v3e?{cgroupMemory:uae(),processes:t()}:void 0;return p?e.warn({memory:r,cpu:i,heapStats:l,resourceUsageDetails:g,...n},"Critical resource usage metrics detected"):e.debug({memory:r,cpu:i,heapUsageRatio:d,resourceUsageDetails:g},"Got machine resource usage metrics"),{memory:r,cpu:i,heapUsageRatio:d,memoryPressure:a,cpuPressure:s,heapPressure:m,details:g}}catch{return}}function x3e(){if(NM!=="linux")return null;try{let e=ZG("/sys/fs/cgroup/memory.max"),t=xv("/sys/fs/cgroup/memory.current");if(e==="max"||isNaN(t))return null;let o=yb(e);if(isNaN(o))return null;let n=Math.max(0,o-t);return {totalMemory:o,freeMemory:n,freePercentage:n/o}}catch{}try{let e=xv("/sys/fs/cgroup/memory/memory.limit_in_bytes"),t=xv("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(e)||isNaN(t))return null;let o=Jp.totalmem();if(e>=o)return null;let n=Math.max(0,e-t);return {totalMemory:e,freeMemory:n,freePercentage:n/e}}catch{return null}}function Sae(){let e=x3e();if(e)return e;let t=Jp.totalmem(),o=NM==="darwin"?_3e():(()=>{let r=Jp.freemem();return {availableMemory:r,rawFreeMemory:r,cachedMemory:0}})(),n=o.availableMemory/t;return {totalMemory:t,freeMemory:o.availableMemory,freePercentage:n}}function _3e(){try{let e=execSync("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),o=e.match(/page size of (\d+) bytes/)?.[1],n=o?yb(o):4096,r=u=>{let m=e.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?yb(m):0},i=r("Pages free"),a=r("Pages inactive"),s=r("Pages speculative"),l=i*n,c=(a+s)*n;return {availableMemory:l+c,rawFreeMemory:l,cachedMemory:c}}catch{let e=Jp.freemem();return {availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}process.env.APP||"unknown";var UM="deployment.environment",jM="service.instance.id";function Tae(){return process.env.MOMENTIC_LOCAL_DEV==="1"&&process.env.LOCAL_SIGNOZ==="true"}var bb=false,zM,tI=new Map,H3e={forceFlush:()=>Promise.resolve(),onStart:e=>{let{traceId:t,spanId:o}=e.spanContext();tI.set(`${t}:${o}`,e);},onEnd:e=>{let{traceId:t,spanId:o}=e.spanContext();tI.delete(`${t}:${o}`);},shutdown:()=>Promise.resolve()},eI,oI,$3e=[],HM,G3e=2e4;function oi(){return bb}async function V3e(){for(let e of $3e)try{await e();}catch{}}function W3e(){return oi()&&trace.getSpan(context.active())!==void 0}function q3e(){return Tae()?new OTLPTraceExporter({url:"http://localhost:4318/v1/traces"}):new OTLPTraceExporter({url:`${wv}/v1/traces`,headers:{"x-momentic-metrics-api-key":Rv},timeoutMillis:G3e})}function K3e(e){let t="production",o=v4$1(),n=q3e();return new NodeTracerProvider({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:e,[UM]:t,[jM]:o,[ATTR_SERVICE_VERSION]:"3.62.2"}),spanProcessors:[H3e,new BatchSpanProcessor(n)]})}function Y3e(e){HM=registerInstrumentations({tracerProvider:e,instrumentations:[new UndiciInstrumentation({requireParentforSpans:true})]});}function J3e(e){return !e&&!zM?trace.getTracer("momentic-serverless"):oI?.getTracer("momentic-serverless")??trace.getTracer("momentic-serverless")}async function su(e){if(!(!e.enabled||bb))try{zM=e.serviceName;let t=K3e(e.serviceName);oI=t,eI=new AsyncLocalStorageContextManager,t.register({contextManager:eI.enable(),propagator:new W3CTraceContextPropagator}),Y3e(t),bb=!0;}catch{bb=false,zM=void 0,oI=void 0,eI=void 0,HM=void 0;}}function X3e(e){if(bb){for(let t of Array.from(tI.values()).reverse())try{t.setAttribute("momentic.aborted",!0),t.setAttribute("momentic.abort_reason",e),t.setStatus({code:SpanStatusCode.ERROR,message:e}),t.end();}catch{}tI.clear();}}async function $M(e="shutdown"){if(bb)try{X3e(e),await Promise.allSettled([oI?.shutdown(),V3e()]);}catch{}finally{HM?.();try{eI?.disable();}catch{}bb=false,zM=void 0,tI.clear(),eI=void 0,oI=void 0,HM=void 0;}}async function ge(e){if(!oi()||!e.root&&!e.newTrace&&!W3e())return e.fn(void 0);let t=e.serviceName===void 0?e.attributes:{...e.attributes??{},"momentic.span_service_name":e.serviceName};return await J3e(e.serviceName).startActiveSpan(e.name,{attributes:t,kind:e.kind??SpanKind.CLIENT},e.newTrace?ROOT_CONTEXT:context.active(),async o=>{try{let n=await e.fn(o);return o.setStatus({code:SpanStatusCode.OK}),n}catch(n){throw o.setStatus({code:SpanStatusCode.ERROR,message:n instanceof Error?n.message.slice(0,300):void 0}),n instanceof Error&&o.recordException(n),n}finally{o.end();}})}var nI=class{increment(t,o,n){}gauge(t,o){}distribution(t,o,n){}async flush(){}async recordDuration(t){return await n2(t)}};async function n2({fn:e,name:t,timeoutMs:o,timeoutMessage:n,trace:r}){let i=r?()=>ge({name:r.name,attributes:r.attributes,fn:e}):e,a=Promise.resolve(i());return o===void 0?await a:await ye(a,{milliseconds:o,message:n??`Timed out after ${o}ms recording duration for ${t}`})}function GM(e){return e instanceof Error?e.name==="TimeoutError"?"timeout":e.name==="AbortError"?"aborted":"error":"error"}function r2(e){if(!e||e.length===0)return {};let t={};for(let o of e){let n=o.indexOf(":");if(n>-1){let r=o.slice(0,n).trim(),i=o.slice(n+1).trim();r&&(t[r]=i);continue}t[o]=true;}return t}function i2(e,t){let o=r2(e);return !t||Object.keys(t).length===0?o:{...t,...o}}function d5e(){return new OTLPMetricExporter({url:`${wv}/v1/metrics`,headers:{"x-momentic-metrics-api-key":Rv},temporalityPreference:AggregationTemporalityPreference.DELTA})}var a2=[100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],lu=(e,t,o)=>({instrumentName:e,instrumentType:InstrumentType.HISTOGRAM,aggregation:{type:AggregationType.EXPLICIT_BUCKET_HISTOGRAM,options:{boundaries:t,recordMinMax:false}},...o?{attributeKeys:o}:void 0}),m5e=[1e3,5e3,15e3,3e4,6e4,12e4,3e5,6e5,12e5,18e5,36e5],p5e=[500,1e3,2e3,5e3,1e4,2e4,3e4,6e4,12e4,3e5,6e5],Eae=[25,50,100,250,500,1e3,2e3,3e3,5e3,7500,1e4,15e3,3e4,6e4],h5e=[50,100,250,500,1e3,2e3,5e3,1e4,2e4,3e4,6e4,12e4,3e5],s2=[1e4,3e4,6e4,12e4,3e5,6e5,9e5,12e5,18e5,36e5,54e5,72e5,108e5],g5e=[lu("test_event_duration",a2),lu("test_step_duration",a2),lu("test_mobile_step_duration",a2),lu("web_agent_action_duration",[25,50,100,200,350,500,750,1e3,2e3,5e3,1e4,2e4,3e4,6e4],["op","outcome"]),lu("mo_turn_duration_ms",m5e,["agent","outcome","env","platform"]),lu("mo_model_preparation_duration_ms",Eae,["agent","env","platform"]),lu("mo_model_time_to_first_token_ms",Eae,["agent","env","platform"]),lu("mo_step_duration_ms",p5e,["agent","env"]),lu("mo_tool_call_duration_ms",h5e,["agent","tool","outcome","env"]),lu("sandbox_bug_reproduction_latency",s2,["outcome","env"]),lu("sandbox_bugbash_latency",s2,["env"]),lu("sandbox_explore_latency",s2,["env"])],VM=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(t){let o=this.counterCache.get(t);if(o)return o;let n=this.meter.createCounter(t);return this.counterCache.set(t,n),n}getHistogram(t){let o=this.histogramCache.get(t);if(o)return o;let n=this.meter.createHistogram(t);return this.histogramCache.set(t,n),n}ensureObservableGauge(t){let o=this.observableGaugeCache.get(t);if(o)return o;let n=this.meter.createObservableGauge(t);return n.addCallback(r=>{let i=this.gaugeValues.get(t);i!==void 0&&r.observe(i,this.globalAttributes);}),this.observableGaugeCache.set(t,n),n}constructor(t){this.globalAttributes={...t.globalAttributes??{}};let o=typeof process<"u"?"production":"unknown",n=resourceFromAttributes({[ATTR_SERVICE_NAME]:t.serviceName,[UM]:o,[jM]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:v4$1(),[ATTR_SERVICE_VERSION]:"3.62.2"}),r=d5e(),i=new PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:t.exportIntervalMs??6e4});this.provider=new MeterProvider({resource:n,readers:[i],views:g5e}),metrics.setGlobalMeterProvider(this.provider),this.meter=this.provider.getMeter("momentic-serverless");}increment(t,o,n){try{let r=i2(n,this.globalAttributes);this.getCounter(t).add(typeof o=="number"?o:1,r);}catch{}}gauge(t,o){try{this.ensureObservableGauge(t),this.gaugeValues.set(t,o);}catch{}}distribution(t,o,n){try{let r=i2(n,this.globalAttributes);this.getHistogram(t).record(o,r);}catch{}}async flush(){try{await this.provider.forceFlush();}catch{}}async recordDuration(t){let{name:o,recordOutcome:n,tags:r}=t,i=Date.now(),a="success";try{return await n2(t)}catch(s){throw a=GM(s),s}finally{this.distribution(o,Date.now()-i,n?[...r??[],`outcome:${a}`]:r);}}};var zo=new nI;function wae(e){if(!e.disabled)try{zo=new VM(e);}catch{zo=new nI;}}var l2;function Rae(e){l2=e;}function Tm(e){y5e(e)&&l2&&l2(e);}var f5e=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function y5e(e){return e instanceof Error&&e.name==="AbortError"?false:Qw(e,hg)?true:Qw(e,ae)?false:e instanceof ie?f5e.has(e.reason):true}var b5e=z.object({openrouter:z.object({usage:z.object({cost:z.number().finite().nonnegative()})})});function _v({feature:e,orgId:t,result:o}){zo.increment("ai_agent_invocations",1,[`feature:${e}`,`orgId:${t}`,`result:${o}`]);}function S5e(e){let t=b5e.safeParse(e);return t.success?t.data.openrouter.usage.cost:void 0}function qM(e){let t;for(let o of e){let n=S5e(o);n!==void 0&&(t=(t??0)+n);}return t}function qg(e){let t=0,o=0,n=0,r=0,i=0,a=0,s=0,l=0;for(let c of e)t+=c.inputTokens??0,o+=c.inputTokenDetails.noCacheTokens??0,n+=c.inputTokenDetails.cacheReadTokens??0,r+=c.inputTokenDetails.cacheWriteTokens??0,i+=c.outputTokens??0,a+=c.outputTokenDetails.textTokens??0,s+=c.outputTokenDetails.reasoningTokens??0,l+=c.totalTokens??0;return {inputTokens:t,inputTokenDetails:{noCacheTokens:o,cacheReadTokens:n,cacheWriteTokens:r},outputTokens:i,outputTokenDetails:{textTokens:a,reasoningTokens:s},totalTokens:l}}function T5e({usage:e,promptType:t,result:o="success",tags:n=[]}){let r=[`type:${t}`,`result:${o}`,...n],i=e.inputTokens??0,a=e.inputTokenDetails.cacheReadTokens??0,s=e.inputTokenDetails.cacheWriteTokens??0,l=e.outputTokens??0;zo.distribution("ai_session_tokens",i,[...r,"category:input"]),zo.distribution("ai_session_tokens",Math.max(0,Math.min(a,i)),[...r,"category:cached_input"]),zo.distribution("ai_session_tokens",Math.max(0,Math.min(s,i-a)),[...r,"category:cache_write_input"]),zo.distribution("ai_session_tokens",l,[...r,"category:output"]);}function rd({usage:e,costUsd:t,promptType:o,logger:n,message:r,result:i="success",attributes:a,metricTags:s}){T5e({usage:e,promptType:o,result:i,tags:s}),n.info({...a,promptType:o,result:i,usage:e,costUsd:t},r);}function Mi({usage:e,promptType:t,logger:o,metricTags:n}){let r=Promise.resolve(e).catch(i=>{o.warn({err:i,promptType:t},"Failed to resolve AI session usage");});return ({message:i,result:a="success",attributes:s})=>{r.then(l=>{l&&rd({usage:l,promptType:t,logger:o,result:a,message:i,attributes:s,metricTags:n});});}}var v5e=1e4;function KM({durationMs:e,executor:t,logger:o,orgId:n,resolvedStep:r,status:i}){if(!Vie(r))return;let a=Gie(r);zo.distribution("test_step_duration",e,[`type:${a}`,"platform:browser",`executor:${t}`,`orgId:${n}`]),!(i!=="SUCCESS"||e<v5e)&&o.info({durationMs:e,executor:t,orgId:n,outcome:"success",stepId:r.id,stepType:a},"test_step_latency_outlier");}function id(e){let t=e.toLowerCase(),o=[["google.vertex","gcp.vertex_ai"],["google.generative-ai","gcp.gemini"],["google-vertex","gcp.vertex_ai"],["amazon-bedrock","aws.bedrock"],["azure-openai","azure.ai.openai"],["anthropic","anthropic"],["openai","openai"],["azure","azure.ai.inference"],["google","gcp.gemini"],["mistral","mistral_ai"],["cohere","cohere"],["bedrock","aws.bedrock"],["groq","groq"],["deepseek","deepseek"],["perplexity","perplexity"],["xai","x_ai"]];for(let[n,r]of o)if(t===n||t.startsWith(n+".")||t.startsWith(n+"-"))return r;return e}function c2(e){var t;return (t={"ai.generateText":"invoke_agent","ai.streamText":"invoke_agent","ai.generateObject":"invoke_agent","ai.streamObject":"invoke_agent","ai.embed":"embeddings","ai.embedMany":"embeddings","ai.rerank":"rerank"}[e])!=null?t:e}function rI(e){return typeof e=="string"?[{type:"text",content:e}]:Array.isArray(e)?e.map(t=>({type:"text",content:t.content})):[{type:"text",content:e.content}]}function A5e(e){var t,o,n,r,i;switch(e.type){case "text":return {type:"text",content:e.text};case "reasoning":return {type:"reasoning",content:e.text};case "tool-call":return {type:"tool_call",id:(t=e.toolCallId)!=null?t:null,name:e.toolName,arguments:e.input};case "tool-result":{let a=e.output,s;return a&&(a.type==="text"||a.type==="error-text"||a.type==="json"||a.type==="error-json"?s=a.value:a.type==="execution-denied"?s={denied:true,reason:a.reason}:s=a),{type:"tool_call_response",id:(o=e.toolCallId)!=null?o:null,response:s}}case "file":{let a=e.data,s=(()=>{if(typeof a=="object"&&a!==null&&!(a instanceof URL)&&!(a instanceof Uint8Array)&&!(a instanceof ArrayBuffer)&&"type"in a)switch(a.type){case "data":return a.data;case "url":return a.url;case "text":return a.text;default:return ""}return a})(),l;if(s instanceof Uint8Array)l=convertDataContentToBase64String(s);else if(typeof s=="string"){if(s.startsWith("http://")||s.startsWith("https://"))return {type:"uri",modality:Kg(e.mediaType),mime_type:(n=e.mediaType)!=null?n:null,uri:s};l=s;}else {if(s instanceof URL)return {type:"uri",modality:Kg(e.mediaType),mime_type:(r=e.mediaType)!=null?r:null,uri:s.toString()};l=String(s);}return {type:"blob",modality:Kg(e.mediaType),mime_type:(i=e.mediaType)!=null?i:null,content:l}}case "tool-approval-response":return {type:"tool_approval_response",approval_id:e.approvalId,approved:e.approved,reason:e.reason};case "custom":return {type:"custom",kind:e.kind};case "reasoning-file":return {type:String(e.type)};default:return {type:String(e.type)}}}function Kg(e){return !e||e.startsWith("image/")?"image":e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":"image"}function E5e(e){return e.map(t=>{if(t.role==="system")return {role:"system",parts:[{type:"text",content:t.content}]};let o=t.content.map(A5e);return {role:t.role,parts:o}})}function u2({prompt:e,messages:t}){let o=[];if(typeof e=="string")o.push({role:"user",parts:[{type:"text",content:e}]});else if(Array.isArray(e))for(let n of e){let r=Cae(n);r&&o.push(r);}if(t)for(let n of t){let r=Cae(n);r&&o.push(r);}return o}function Cae(e){return e.role==="system"?{role:"system",parts:[{type:"text",content:e.content}]}:e.role==="user"?typeof e.content=="string"?{role:"user",parts:[{type:"text",content:e.content}]}:{role:"user",parts:e.content.map(n=>{var r,i,a,s,l,c,u,d;switch(n.type){case "text":return {type:"text",content:n.text};case "image":{let m=n.image;return m instanceof URL?{type:"uri",modality:"image",mime_type:(r=n.mediaType)!=null?r:null,uri:m.toString()}:typeof m=="string"?m.startsWith("http://")||m.startsWith("https://")?{type:"uri",modality:"image",mime_type:(i=n.mediaType)!=null?i:null,uri:m}:{type:"blob",modality:"image",mime_type:(a=n.mediaType)!=null?a:null,content:m}:{type:"blob",modality:"image",mime_type:(s=n.mediaType)!=null?s:null,content:convertDataContentToBase64String(m)}}case "file":{let m=n.data,p=(()=>{if(typeof m=="object"&&m!==null&&!(m instanceof URL)&&!(m instanceof Uint8Array)&&!(m instanceof ArrayBuffer)&&"type"in m)switch(m.type){case "data":return m.data;case "url":return m.url;case "text":return m.text;default:return ""}return m})();return p instanceof URL?{type:"uri",modality:Kg(n.mediaType),mime_type:(l=n.mediaType)!=null?l:null,uri:p.toString()}:typeof p=="string"?p.startsWith("http://")||p.startsWith("https://")?{type:"uri",modality:Kg(n.mediaType),mime_type:(c=n.mediaType)!=null?c:null,uri:p}:{type:"blob",modality:Kg(n.mediaType),mime_type:(u=n.mediaType)!=null?u:null,content:p}:{type:"blob",modality:Kg(n.mediaType),mime_type:(d=n.mediaType)!=null?d:null,content:convertDataContentToBase64String(p)}}default:return {type:String(n.type)}}})}:e.role==="assistant"?typeof e.content=="string"?{role:"assistant",parts:[{type:"text",content:e.content}]}:{role:"assistant",parts:e.content.map(n=>{var r,i;switch(n.type){case "text":return {type:"text",content:n.text};case "reasoning":return {type:"reasoning",content:n.text};case "tool-call":return {type:"tool_call",id:(r=n.toolCallId)!=null?r:null,name:n.toolName,arguments:n.input};case "tool-result":{let a=n.output,s;return a&&(a.type==="text"||a.type==="error-text"||a.type==="json"||a.type==="error-json"?s=a.value:a.type==="execution-denied"?s={denied:true,reason:a.reason}:s=a),{type:"tool_call_response",id:(i=n.toolCallId)!=null?i:null,response:s}}default:return {type:String(n.type)}}})}:e.role==="tool"?{role:"tool",parts:e.content.map(n=>{var r;if(n.type==="tool-result"){let i=n.output,a;return i&&(i.type==="text"||i.type==="error-text"||i.type==="json"||i.type==="error-json"?a=i.value:i.type==="execution-denied"?a={denied:true,reason:i.reason}:a=i),{type:"tool_call_response",id:(r=n.toolCallId)!=null?r:null,response:a}}return {type:String(n.type)}})}:e}function Iae({text:e,reasoning:t,toolCalls:o,toolResults:n,files:r,finishReason:i}){let a=[];if(t)for(let s of t)"text"in s&&s.text&&a.push({type:"reasoning",content:s.text});if(e!=null&&e.length>0&&a.push({type:"text",content:e}),o)for(let s of o)a.push({type:"tool_call",id:s.toolCallId,name:s.toolName,arguments:s.input});if(n)for(let s of n)a.push({type:"tool_call_response",id:s.toolCallId,response:s.output});if(r)for(let s of r)a.push({type:"blob",modality:Kg(s.mediaType),mime_type:s.mediaType,content:s.base64});return [{role:"assistant",parts:a,finish_reason:Oae(i)}]}function xae({objectText:e,finishReason:t}){return [{role:"assistant",parts:[{type:"text",content:e}],finish_reason:Oae(t)}]}function Oae(e){var t;return (t={stop:"stop",length:"length","content-filter":"content_filter","tool-calls":"tool_call",error:"error",other:"stop",unknown:"stop"}[e])!=null?t:e}function Xp(e,t){let o=RetryError.isInstance(t)?t.lastError:t;APICallError$1.isInstance(o)&&o.statusCode!=null&&e.setAttribute("http.response.status_code",o.statusCode),t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:SpanStatusCode.ERROR});}function C5e(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function JM(e){if(!Array.isArray(e))return typeof e=="number"&&!Number.isFinite(e)?void 0:e;let t=new Set(e.filter(C5e).map(n=>typeof n));if(t.size!==1)return;let[o]=t;if(o==="string")return e.filter(n=>typeof n=="string");if(o==="number"){let n=e.filter(r=>typeof r=="number");return n.every(Number.isFinite)?n:void 0}return e.filter(n=>typeof n=="boolean")}function I5e(e){let t={};for(let[o,n]of Object.entries(e??{})){if(n==null)continue;let r=JM(n);r!=null&&(t[o]=r);}return t}function x5e(e){return e?.isEnabled!==false}function Fr(e,t){if(!x5e(e))return {};let o={};for(let[n,r]of Object.entries(t)){if(r==null)continue;if(typeof r=="object"&&"input"in r&&typeof r.input=="function"){if(e?.recordInputs===false)continue;let a=r.input();if(a!=null){let s=JM(a);s!=null&&(o[n]=s);}continue}if(typeof r=="object"&&"output"in r&&typeof r.output=="function"){if(e?.recordOutputs===false)continue;let a=r.output();if(a!=null){let s=JM(a);s!=null&&(o[n]=s);}continue}let i=JM(r);i!=null&&(o[n]=i);}return o}var _5e={usage:false,providerMetadata:false,embedding:false,reranking:false,experimental_evaluation:false,runtimeContext:false,headers:false,toolChoice:false,schema:false};function O5e(e){var t,o,n,r,i,a,s,l,c;return {..._5e,usage:(t=e.usage)!=null?t:false,providerMetadata:(o=e.providerMetadata)!=null?o:false,embedding:(n=e.embedding)!=null?n:false,reranking:(r=e.reranking)!=null?r:false,experimental_evaluation:(i=e.experimental_evaluation)!=null?i:false,runtimeContext:(a=e.runtimeContext)!=null?a:false,headers:(s=e.headers)!=null?s:false,toolChoice:(l=e.toolChoice)!=null?l:false,schema:(c=e.schema)!=null?c:false}}function YM(e){let t={};for(let[o,n]of Object.entries(e??{}))Pae(t,`ai.settings.context.${o}`,n);return t}function Pae(e,t,o){if(o!=null){if(Array.isArray(o)||typeof o!="object"){e[t]=o;return}for(let[n,r]of Object.entries(o))Pae(e,`${t}.${n}`,r);}}function iI(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!=null).map(([t,o])=>[`ai.request.headers.${t}`,o]))}function aI(e){var t,o,n;return {"ai.usage.inputTokenDetails.noCacheTokens":(t=e.inputTokenDetails)==null?void 0:t.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":(o=e.outputTokenDetails)==null?void 0:o.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(n=e.outputTokenDetails)==null?void 0:n.reasoningTokens}}function Kr(e,t,o){let n={};for(let[r,i]of Object.entries(o))!t[r]||i==null||Object.assign(n,Fr(e,i));return n}function XM(e){return e==null?void 0:e/1e3}function P5e(e){var t;return {"gen_ai.client.operation.duration":XM(e.responseTimeMs),"gen_ai.client.operation.time_to_first_chunk":XM(e.timeToFirstOutputMs),"gen_ai.client.operation.time_per_output_chunk":XM((t=e.timeBetweenOutputChunksMs)==null?void 0:t.avg)}}var kae=class{constructor(e={}){this.callStates=new Map;var t;this.tracer=(t=e.tracer)!=null?t:trace.getTracer("gen_ai"),this.supplementalAttributes=O5e(e),this.enrichSpan=e.enrichSpan;}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e);}getSpanAttributes({attributes:e,spanType:t,operationId:o,callId:n,runtimeContext:r}){var i;let a;try{a=(i=this.enrichSpan)==null?void 0:i.call(this,{spanType:t,operationId:o,callId:n,runtimeContext:r});}catch{a=void 0;}return {...I5e(a),...e}}executeTool({callId:e,toolCallId:t,execute:o}){var n;let r=(n=this.getCallState(e))==null?void 0:n.toolSpans.get(t);return r==null?o():context.with(r.context,o)}executeLanguageModelCall({callId:e,execute:t}){var o;let n=this.getCallState(e),r=(o=n?.inferenceContext)!=null?o:n?.stepContext;return r==null?t():context.with(r,t)}onStart(e){if(e.operationId==="ai.embed"||e.operationId==="ai.embedMany"){this.onEmbedOperationStart(e);return}if(e.operationId==="ai.rerank"){this.onRerankOperationStart(e);return}if(e.operationId==="ai.generateObject"||e.operationId==="ai.streamObject"){this.onObjectOperationStart(e);return}this.onGenerateStart(e);}onGenerateStart(e){var t;let o={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},n={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},r=id(e.provider),i=c2(e.operationId),a=e.runtimeContext,s=Kr(o,this.supplementalAttributes,{runtimeContext:YM(a),headers:iI(e.headers)}),l=Fr(o,{"gen_ai.operation.name":i,"gen_ai.provider.name":r,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":o.functionId,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":(t=e.temperature)!=null?t:void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.stop_sequences":e.stopSequences,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.instructions!=null?{input:()=>JSON.stringify(rI(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(u2({prompt:void 0,messages:e.messages}))},...s}),c=`${i} ${e.modelId}`,u=this.tracer.startSpan(c,{attributes:this.getSpanAttributes({attributes:l,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:a}),kind:SpanKind.INTERNAL}),d=trace.setSpan(context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:o,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:n,provider:e.provider,modelId:e.modelId,runtimeContext:a,baseSupplementalAttributes:s});}onObjectOperationStart(e){var t;let o={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},n={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},r=id(e.provider),i=c2(e.operationId),a=Kr(o,this.supplementalAttributes,{headers:iI(e.headers)}),s=Fr(o,{"gen_ai.operation.name":i,"gen_ai.provider.name":r,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":o.functionId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":(t=e.temperature)!=null?t:void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.system?{input:()=>JSON.stringify(rI(e.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(u2({prompt:e.prompt,messages:e.messages}))},...a,...Kr(o,this.supplementalAttributes,{schema:{"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}})}),l=`${i} ${e.modelId}`,c=this.tracer.startSpan(l,{attributes:this.getSpanAttributes({attributes:s,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:SpanKind.INTERNAL}),u=trace.setSpan(context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:o,rootSpan:c,rootContext:u,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:n,provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a,objectSystemInstructions:e.system});}onObjectStepStart(e){var t,o;let n=this.getCallState(e.callId);if(!n?.rootSpan||!n.rootContext)return;let{telemetry:r}=n,i=id(e.provider),a=n.objectSystemInstructions==null?0:rI(n.objectSystemInstructions).length,s=(t=e.promptMessages)==null?void 0:t.slice(a),l=Fr(r,{"gen_ai.operation.name":"chat","gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":n.settings.frequencyPenalty,"gen_ai.request.max_tokens":n.settings.maxOutputTokens,"gen_ai.request.presence_penalty":n.settings.presencePenalty,"gen_ai.request.temperature":(o=n.settings.temperature)!=null?o:void 0,"gen_ai.request.top_k":n.settings.topK,"gen_ai.request.top_p":n.settings.topP,"gen_ai.system_instructions":n.objectSystemInstructions!=null?{input:()=>JSON.stringify(rI(n.objectSystemInstructions))}:void 0,"gen_ai.input.messages":{input:()=>s?JSON.stringify(E5e(s)):void 0},...n.baseSupplementalAttributes}),c=`chat ${e.modelId}`;n.inferenceSpan=this.tracer.startSpan(c,{attributes:this.getSpanAttributes({attributes:l,spanType:"languageModel",operationId:n.operationId,callId:e.callId,runtimeContext:n.runtimeContext}),kind:SpanKind.CLIENT},n.rootContext),n.inferenceContext=trace.setSpan(n.rootContext,n.inferenceSpan);}onObjectStepEnd(e){var t;let o=this.getCallState(e.callId);if(!o?.inferenceSpan)return;let{telemetry:n}=o;o.inferenceSpan.setAttributes(Fr(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(t=e.usage.inputTokenDetails)==null?void 0:t.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(xae({objectText:e.objectText,finishReason:e.finishReason}))}catch{return e.objectText}}},...Kr(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:aI(e.usage)})})),o.inferenceSpan.end(),o.inferenceSpan=void 0,o.inferenceContext=void 0;}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o=e.runtimeContext,n=id(e.provider),r=Kr(t,this.supplementalAttributes,{runtimeContext:YM(o),headers:iI(e.headers)}),i=e.value,a=e.operationId==="ai.embedMany",s=c2(e.operationId),l=Fr(t,{"gen_ai.operation.name":s,"gen_ai.provider.name":n,"gen_ai.request.model":e.modelId,...r,...Kr(t,this.supplementalAttributes,{embedding:a?{"ai.values":{input:()=>i.map(m=>JSON.stringify(m))}}:{"ai.value":{input:()=>JSON.stringify(i)}}})}),c=`${s} ${e.modelId}`,u=this.tracer.startSpan(c,{attributes:this.getSpanAttributes({attributes:l,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:o}),kind:SpanKind.CLIENT}),d=trace.setSpan(context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:o,baseSupplementalAttributes:r});}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:o}=t;t.runtimeContext=e.runtimeContext;let n=Fr(o,{"gen_ai.operation.name":"agent_step",...t.baseSupplementalAttributes,...Kr(o,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>e.stepToolChoice!=null?JSON.stringify(e.stepToolChoice):void 0}}})});t.stepSpan=this.tracer.startSpan(`step ${e.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:n,spanType:"step",operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:SpanKind.INTERNAL},t.rootContext),t.stepContext=trace.setSpan(t.rootContext,t.stepSpan);}onLanguageModelCallStart(e){var t;let o=this.getCallState(e.callId);if(!o?.stepContext)return;let{telemetry:n}=o,r=id(e.provider);o.inferenceToolDefinitions=e.tools;let i=Fr(n,{"gen_ai.operation.name":"chat","gen_ai.provider.name":r,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":o.settings.frequencyPenalty,"gen_ai.request.max_tokens":o.settings.maxOutputTokens,"gen_ai.request.presence_penalty":o.settings.presencePenalty,"gen_ai.request.stop_sequences":o.settings.stopSequences,"gen_ai.request.temperature":(t=o.settings.temperature)!=null?t:void 0,"gen_ai.request.top_k":o.settings.topK,"gen_ai.request.top_p":o.settings.topP,"gen_ai.system_instructions":e.instructions!=null?{input:()=>JSON.stringify(rI(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>{let a=u2({prompt:void 0,messages:e.messages});return a.length>0?JSON.stringify(a):void 0}},"gen_ai.tool.definitions":{input:()=>e.tools?JSON.stringify(e.tools):void 0}});o.inferenceSpan=this.tracer.startSpan(`chat ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:i,spanType:"languageModel",operationId:o.operationId,callId:e.callId,runtimeContext:o.runtimeContext}),kind:SpanKind.CLIENT},o.stepContext),o.inferenceContext=trace.setSpan(o.stepContext,o.inferenceSpan);}onLanguageModelCallEnd(e){var t,o,n;let r=this.getCallState(e.callId);if(!r?.inferenceSpan)return;let{telemetry:i}=r,a=id(e.provider),s=[...(t=r.inferenceToolDefinitions)!=null?t:[]],l=new Set(s.flatMap(m=>typeof m.name=="string"?[m.name]:[])),c=false;for(let m of e.content)m.type!=="tool-call"||!m.providerExecuted||l.has(m.toolName)||(s.push({type:"extension",name:m.toolName}),l.add(m.toolName),c=true);r.inferenceSpan.setAttributes(Fr(i,{...P5e(e.performance),"gen_ai.provider.name":a,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.responseId,"gen_ai.response.model":e.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(o=e.usage.inputTokenDetails)==null?void 0:o.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(n=e.usage.inputTokenDetails)==null?void 0:n.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(Iae({text:e.content.filter(m=>m.type==="text").map(m=>m.text).join("")||void 0,reasoning:e.content.filter(m=>m.type==="reasoning"),toolCalls:e.content.filter(m=>m.type==="tool-call"),toolResults:e.content.filter(m=>m.type==="tool-result"),files:e.content.filter(m=>m.type==="file").map(m=>m.file),finishReason:e.finishReason}))},"gen_ai.tool.definitions":c?{input:()=>JSON.stringify(s)}:void 0,...Kr(i,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:aI(e.usage)})}));let u=new Map;for(let m of e.content)(m.type==="tool-error"||m.type==="tool-result"&&m.preliminary!==true)&&u.set(m.toolCallId,m);let d=new Set;for(let m of e.content){if(m.type!=="tool-call"||!m.providerExecuted||d.has(m.toolCallId))continue;d.add(m.toolCallId);let p=this.tracer.startSpan(`execute_tool ${m.toolName}`,{attributes:this.getSpanAttributes({attributes:Fr(i,{"gen_ai.operation.name":"execute_tool","gen_ai.tool.name":m.toolName,"gen_ai.tool.call.id":m.toolCallId,"gen_ai.tool.type":"extension","gen_ai.tool.call.arguments":{input:()=>JSON.stringify(m.input)}}),spanType:"tool",operationId:r.operationId,callId:e.callId,runtimeContext:r.runtimeContext}),kind:SpanKind.INTERNAL},r.inferenceContext),h=u.get(m.toolCallId);if(h?.type==="tool-result")try{p.setAttributes(Fr(i,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(h.output)}}));}catch{}else h?.type==="tool-error"&&Xp(p,h.error);p.end();}r.inferenceSpan.end(),r.inferenceSpan=void 0,r.inferenceContext=void 0,r.inferenceToolDefinitions=void 0;}onToolExecutionStart(e){var t;let o=this.getCallState(e.callId),n=(t=o?.stepContext)!=null?t:o?.rootContext;if(!o||!n)return;let{telemetry:r}=o,{toolCall:i}=e,a=Fr(r,{"gen_ai.operation.name":"execute_tool","gen_ai.tool.name":i.toolName,"gen_ai.tool.call.id":i.toolCallId,"gen_ai.tool.type":i.providerExecuted?"extension":"function","gen_ai.tool.call.arguments":{input:()=>JSON.stringify(i.input)}}),s=`execute_tool ${i.toolName}`,l=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:a,spanType:"tool",operationId:o.operationId,callId:e.callId,runtimeContext:o.runtimeContext}),kind:SpanKind.INTERNAL},n),c=trace.setSpan(n,l);o.toolSpans.set(i.toolCallId,{span:l,context:c});}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let o=t.toolSpans.get(e.toolCall.toolCallId);if(!o)return;let{span:n}=o,{telemetry:r}=t,{toolOutput:i}=e;if(n.setAttributes(Fr(r,{"gen_ai.execute_tool.duration":XM(e.toolExecutionMs)})),i.type==="tool-result")try{n.setAttributes(Fr(r,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(i.output)}}));}catch{}else Xp(n,i.error);n.end(),t.toolSpans.delete(e.toolCall.toolCallId);}onStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:o}=t;t.stepSpan.setAttributes(Kr(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:aI(e.usage)})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0;}onStepFinish(e){this.onStepEnd(e);}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId==="ai.embed"||t.operationId==="ai.embedMany"){this.onEmbedOperationEnd(e);return}if(t.operationId==="ai.rerank"){this.onRerankOperationEnd(e);return}if(t.operationId==="ai.generateObject"||t.operationId==="ai.streamObject"){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e);}}onGenerateEnd(e){var t,o;let n=this.getCallState(e.callId);if(!n?.rootSpan)return;let{telemetry:r}=n;n.rootSpan.setAttributes(Fr(r,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(t=e.usage.inputTokenDetails)==null?void 0:t.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(o=e.usage.inputTokenDetails)==null?void 0:o.cacheWriteTokens,"gen_ai.output.messages":{output:()=>{var i;return JSON.stringify(Iae({text:(i=e.text)!=null?i:void 0,reasoning:e.finalStep.reasoning,toolCalls:e.toolCalls,toolResults:e.toolResults,files:e.files,finishReason:e.finishReason}))}},...Kr(r,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0},usage:aI(e.usage)})})),n.rootSpan.end(),this.cleanupCallState(e.callId);}onObjectOperationEnd(e){var t;let o=this.getCallState(e.callId);if(!o?.rootSpan)return;let{telemetry:n}=o;o.rootSpan.setAttributes(Fr(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(t=e.usage.inputTokenDetails)==null?void 0:t.cacheReadTokens,"gen_ai.output.messages":{output:()=>e.object!=null?JSON.stringify(xae({objectText:JSON.stringify(e.object),finishReason:e.finishReason})):void 0},...Kr(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:aI(e.usage)})})),o.rootSpan.end(),this.cleanupCallState(e.callId);}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:o}=t,n=t.operationId==="ai.embedMany";t.rootSpan.setAttributes(Fr(o,{...Kr(o,this.supplementalAttributes,{embedding:n?{"ai.embeddings":{output:()=>e.embedding.map(r=>JSON.stringify(r))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}}})})),t.rootSpan.end(),this.cleanupCallState(e.callId);}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:o}=t,n=id(t.provider),r=Fr(o,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...Kr(o,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>e.values.map(l=>JSON.stringify(l))}}})}),i=`embeddings ${t.modelId}`,a=this.tracer.startSpan(i,{attributes:this.getSpanAttributes({attributes:r,spanType:"embedding",operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:SpanKind.CLIENT},t.rootContext),s=trace.setSpan(t.rootContext,a);t.embedSpans.set(e.embedCallId,{span:a,context:s});}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let o=t.embedSpans.get(e.embedCallId);if(!o)return;let{span:n}=o,{telemetry:r}=t;n.setAttributes(Fr(r,{"gen_ai.usage.input_tokens":e.usage.tokens,...Kr(r,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>e.embeddings.map(i=>JSON.stringify(i))}}})})),n.end(),t.embedSpans.delete(e.embedCallId);}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o=e.runtimeContext,n=id(e.provider),r=Kr(t,this.supplementalAttributes,{runtimeContext:YM(o),headers:iI(e.headers)}),i=Fr(t,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":n,"gen_ai.request.model":e.modelId,...r,...Kr(t,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(c=>JSON.stringify(c))}}})}),a=`rerank ${e.modelId}`,s=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:i,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:o}),kind:SpanKind.CLIENT}),l=trace.setSpan(context.active(),s);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:s,rootContext:l,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:o,baseSupplementalAttributes:r});}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId));}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:o}=t,n=id(t.provider),r=Fr(o,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...Kr(o,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(l=>JSON.stringify(l))}}})}),i=`rerank ${t.modelId}`,a=this.tracer.startSpan(i,{attributes:this.getSpanAttributes({attributes:r,spanType:"reranking",operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:SpanKind.CLIENT},t.rootContext),s=trace.setSpan(t.rootContext,a);t.rerankSpan={span:a,context:s};}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:o}=t.rerankSpan,{telemetry:n}=t;o.setAttributes(Kr(n,this.supplementalAttributes,{reranking:{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(r=>JSON.stringify(r))}}})),o.end(),t.rerankSpan=void 0;}onEvaluateOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o=e.runtimeContext,n=Kr(t,this.supplementalAttributes,{runtimeContext:YM(o),headers:iI(e.headers)}),r=Fr(t,{"gen_ai.operation.name":"evaluate","gen_ai.provider.name":id(e.provider),"gen_ai.request.model":e.modelId,...n,...Kr(t,this.supplementalAttributes,{experimental_evaluation:{"ai.evaluation.state":{input:()=>JSON.stringify(e.state)},"ai.evaluation.questions":{input:()=>JSON.stringify(e.questions)}}})}),i=this.tracer.startSpan(`evaluate ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:r,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:o}),kind:SpanKind.CLIENT}),a=trace.setSpan(context.active(),i);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:i,rootContext:a,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:o,baseSupplementalAttributes:n});}onEvaluateOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.setAttributes(Kr(t.telemetry,this.supplementalAttributes,{experimental_evaluation:{"ai.evaluation.answers":{output:()=>JSON.stringify(e.answers)}}})),t.rootSpan.end(),this.cleanupCallState(e.callId));}experimental_onEvaluateStart(e){this.onEvaluateOperationStart(e);}experimental_onEvaluateEnd(e){this.onEvaluateOperationEnd(e);}experimental_onEvaluationModelCallStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let o=Fr(t.telemetry,{"gen_ai.operation.name":"evaluate","gen_ai.provider.name":id(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...Kr(t.telemetry,this.supplementalAttributes,{experimental_evaluation:{"ai.evaluation.state":{input:()=>JSON.stringify(e.state)},"ai.evaluation.questions":{input:()=>JSON.stringify(e.questions)}}})}),n=this.tracer.startSpan(`evaluate ${t.modelId}`,{attributes:this.getSpanAttributes({attributes:o,spanType:"experimental_evaluation",operationId:e.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:SpanKind.CLIENT},t.rootContext);t.evaluationSpan={span:n,context:trace.setSpan(t.rootContext,n)};}experimental_onEvaluationModelCallEnd(e){var t,o;let n=this.getCallState(e.callId);n?.evaluationSpan&&(n.evaluationSpan.span.setAttributes(Fr(n.telemetry,{"gen_ai.usage.input_tokens":(t=e.usage)==null?void 0:t.inputTokens,"gen_ai.usage.output_tokens":(o=e.usage)==null?void 0:o.outputTokens,...Kr(n.telemetry,this.supplementalAttributes,{experimental_evaluation:{"ai.evaluation.answers":{output:()=>JSON.stringify(e.answers)}},providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0}})})),n.evaluationSpan.span.end(),n.evaluationSpan=void 0);}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:o}of t.toolSpans.values())o.end();t.toolSpans.clear(),t.inferenceSpan&&(t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:o}of t.embedSpans.values())o.end();t.embedSpans.clear(),t.rerankSpan&&(t.rerankSpan.span.end(),t.rerankSpan=void 0),t.evaluationSpan&&(t.evaluationSpan.span.end(),t.evaluationSpan=void 0),t.rootSpan.end(),this.cleanupCallState(e.callId);}}onError(e){var t;let o=e;if(!o?.callId)return;let n=this.getCallState(o.callId);if(!n?.rootSpan)return;let r=(t=o.error)!=null?t:e;for(let{span:i}of n.toolSpans.values())Xp(i,r),i.end();n.toolSpans.clear(),n.inferenceSpan&&(Xp(n.inferenceSpan,r),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0),n.stepSpan&&(Xp(n.stepSpan,r),n.stepSpan.end(),n.stepSpan=void 0,n.stepContext=void 0);for(let{span:i}of n.embedSpans.values())Xp(i,r),i.end();n.embedSpans.clear(),n.rerankSpan&&(Xp(n.rerankSpan.span,r),n.rerankSpan.span.end(),n.rerankSpan=void 0),n.evaluationSpan&&(Xp(n.evaluationSpan.span,r),n.evaluationSpan.span.end(),n.evaluationSpan=void 0),Xp(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(o.callId);}};function m2(e={}){return new kae({enrichSpan:({runtimeContext:t})=>{let o=Object.fromEntries(Object.entries(e).map(([n,r])=>[`ai.telemetry.metadata.${n}`,r]));for(let n of ["orgId","runId","sessionId"]){let r=t?.[n];typeof r=="string"&&(o[`ai.telemetry.metadata.${n}`]=r);}return o}})}var ps=m2();function rt(e=process.stdout){let t=e===process.stderr?supportsColorStderr:supportsColor,o=process.env.CLICOLOR_FORCE!==void 0&&process.env.CLICOLOR_FORCE!=="0",n=o||process.env.FORCE_COLOR!==void 0&&process.env.FORCE_COLOR!=="0",r=t?t.level:0;o&&r===0&&(r=1),(process.env.NO_COLOR!==void 0&&process.env.NO_COLOR!==""||process.env.CLICOLOR==="0")&&!n&&(r=0);let a=process.env.LC_ALL??process.env.LC_CTYPE??process.env.LANG??"",s=process.env.MOMENTIC_NO_UNICODE===void 0&&process.env.TERM!=="linux"&&(process.platform==="win32"||/utf-?8/i.test(a));return {isTTY:!!e.isTTY,colorLevel:r,unicode:s,columns:e.columns??-1,ci:ms,colorForced:n}}function vm(e){return e.isTTY&&!e.ci&&e.columns>0}var Mae="\r",Lae="\x1B[1A",Nae="\x1B[J",Dae="\x1B[?25l",p2="\x1B[?25h",N5e="\u28CB\u28D9\u28F9\u28F8\u28FC\u28F4\u28E6\u28E7\u28C7\u28CF",D5e="|/-\\",F5e="\u2736\u2738\u2739\u273A\u2739\u2737",B5e="*",U5e="#0891b2",j5e={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 ht(e){let t=e.colorLevel>0&&(e.isTTY||e.colorForced),o=new Chalk({level:t?e.colorLevel:0}),n=(r,i)=>t?i(o,r):r;return {unicode:e.unicode,color:t,bold:r=>n(r,(i,a)=>i.bold(a)),dim:r=>n(r,(i,a)=>i.gray(a)),red:r=>n(r,(i,a)=>i.red(a)),green:r=>n(r,(i,a)=>i.green(a)),yellow:r=>n(r,(i,a)=>i.yellow(a)),code:r=>n(r,(i,a)=>i.hex(U5e)(a)),spinner:r=>{let i=e.unicode?N5e:D5e,a=(r%i.length+i.length)%i.length;return n(i.charAt(a),(s,l)=>s.cyan(l))},classifySpinner:r=>{let i=e.unicode?F5e:B5e,a=(r%i.length+i.length)%i.length;return n(i.charAt(a),(s,l)=>s.cyan(l))},statusGlyph:r=>{let i=j5e[r],a=e.unicode?i.glyph:i.ascii;return t?i.paint(o,a):a},separator:e.unicode?" \xB7 ":" | "}}var h2=class extends Console{_buffer=[];Console=Console;constructor(){super({write:t=>(this._buffer.push(t),true)});}_log(t){this._buffer.push(t);}debug(t,...o){this._log(format(t,...o));}error(t,...o){this._log(format(t,...o));}info(t,...o){this._log(format(t,...o));}log(t,...o){this._log(format(t,...o));}warn(t,...o){this._log(format(t,...o));}flushed(){return this._buffer.length>0?this._buffer.join(`
188
+ `).find(n=>n.startsWith("cpu "));if(!t)return;let o=t.trim().split(/\s+/).slice(1).slice(0,8).map(n=>Number.parseInt(n,10));if(!(o.length===0||o.some(n=>!Number.isFinite(n))))return o.reduce((n,r)=>n+r,0)}function QG(e){try{return l3e(readFileSync(e,"utf8"))}catch{return}}function m3e(){let e;try{e=d3e(readFileSync(`${kM}/stat`,"utf8"));}catch{return}if(e===void 0)return;let t=new Map,o;try{o=readdirSync(kM);}catch{return}for(let n of o){if(!/^\d+$/.test(n))continue;let r=Number.parseInt(n,10);try{let i=c3e(r,readFileSync(`${kM}/${n}/status`,"utf8")),a=u3e(readFileSync(`${kM}/${n}/stat`,"utf8"));if(!i||a===void 0)continue;t.set(r,{...i,cpuTicks:a});}catch{}}return {totalTicks:e,processes:t}}function p3e({current:e,previous:t}){let o=t?e.totalTicks-t.totalTicks:void 0,n=h3e(e.processes),r=new Map,i=0,a=0,s=0,l=false;for(let u of e.processes.values()){i+=u.rssBytes;let d=t?.processes.get(u.pid),m=d?u.cpuTicks-d.cpuTicks:void 0,p=m!==void 0&&m>=0&&o!==void 0&&o>0?m/o*100:void 0,h=r.get(u.name)??{name:u.name,processCount:0,rssBytes:0};h.processCount++,h.rssBytes+=u.rssBytes,p!==void 0&&(h.cpuPercentage=(h.cpuPercentage??0)+p),r.set(u.name,h),n.has(u.pid)&&(a+=u.rssBytes,p!==void 0&&(s+=p,l=true));}let c=[...r.values()];return {visibleProcessCount:e.processes.size,visibleProcessRssBytes:i,currentProcessTreeCount:n.size,currentProcessTreeRssBytes:a,currentProcessTreeCpuPercentage:l?s:void 0,topMemoryProcessGroups:[...c].sort((u,d)=>d.rssBytes-u.rssBytes).slice(0,cae),topCpuProcessGroups:c.filter(u=>u.cpuPercentage!==void 0).sort((u,d)=>(d.cpuPercentage??0)-(u.cpuPercentage??0)).slice(0,cae)}}function h3e(e){let t=new Set;if(!e.has(process.pid))return t;t.add(process.pid);let o=true;for(;o;){o=false;for(let n of e.values())t.has(n.pid)||!t.has(n.parentPid)||(t.add(n.pid),o=true);}return t}var y3e=2e3,b3e=2e4,S3e=.1,T3e=70,v3e=.8,yb=e=>Number.parseInt(e,10),ZG=e=>readFileSync(e,"utf8").trim(),xv=e=>yb(ZG(e));function hae({summary:e,detailedSnapshots:t}){let o={"momentic.resource.samples":e.samples,"momentic.resource.low_memory_samples":e.lowMemorySamples,"momentic.resource.high_cpu_samples":e.highCpuSamples,"momentic.resource.high_heap_samples":e.highHeapSamples,"momentic.resource.min_free_memory_ratio":e.minFreeMemoryRatio,"momentic.resource.max_cpu_percentage":e.maxCpuPercentage,"momentic.resource.max_heap_usage_ratio":e.maxHeapUsageRatio,"momentic.resource.max_memory_used_bytes":e.maxMemoryUsedBytes,"momentic.resource.max_current_process_tree_rss_bytes":e.maxCurrentProcessTreeRssBytes,"momentic.resource.max_visible_process_rss_bytes":e.maxVisibleProcessRssBytes,"momentic.resource.detailed_snapshots":t};if(!t||!e.peakMemoryDetails)return o;let n=e.peakMemoryDetails.cgroupMemory,r=e.peakMemoryDetails.processes,i={"momentic.resource.peak_cgroup_anonymous_bytes":n?.anonymousBytes,"momentic.resource.peak_cgroup_file_cache_bytes":n?.fileCacheBytes,"momentic.resource.peak_cgroup_kernel_bytes":n?.kernelBytes,"momentic.resource.peak_cgroup_slab_bytes":n?.slabBytes,"momentic.resource.peak_cgroup_shared_memory_bytes":n?.sharedMemoryBytes,"momentic.resource.peak_cgroup_page_tables_bytes":n?.pageTablesBytes,"momentic.resource.peak_cgroup_oom_events":n?.events?.oom,"momentic.resource.peak_cgroup_oom_kill_events":n?.events?.oomKill,"momentic.resource.peak_cgroup_oom_group_kill_events":n?.events?.oomGroupKill};for(let[s,l]of Object.entries(i))l!==void 0&&(o[s]=l);o["momentic.resource.peak_detailed_memory_used_bytes"]=e.peakDetailedMemoryUsedBytes,r&&(o["momentic.resource.peak_memory_process_groups"]=JSON.stringify(r.topMemoryProcessGroups));let a=e.peakCpuDetails?.processes;return a&&(o["momentic.resource.peak_cpu_process_groups"]=JSON.stringify(a.topCpuProcessGroups),a.currentProcessTreeCpuPercentage!==void 0&&(o["momentic.resource.peak_current_process_tree_cpu_percentage"]=a.currentProcessTreeCpuPercentage)),o}var ZC={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0};function gae(){return {...ZC}}var NM=Jp.platform(),A3e=Jp.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 dae(e=Date.now()){let t=Jp.cpus(),o={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let n of t)o.user+=n.times.user,o.nice+=n.times.nice,o.sys+=n.times.sys,o.idle+=n.times.idle,o.irq+=n.times.irq;return o.total=o.user+o.nice+o.sys+o.idle+o.irq,o}function E3e(e,t){let o={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 o.total<=0?null:{measurementTime:t.measurementTime,intervalMs:t.measurementTime-e.measurementTime,user:o.user/o.total*100,nice:o.nice/o.total*100,sys:o.sys/o.total*100,idle:o.idle/o.total*100,irq:o.irq/o.total*100,total:100-o.idle/o.total*100}}function DM(){let e=dae();return ()=>{let t=dae(),o=E3e(e,t);return e=t,o}}function mae(){try{let t=readFileSync("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(t?.[1])return yb(t[1])}catch{}try{let e=xv("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(e))return e/1e3}catch{}return null}function w3e(){try{let t=ZG("/sys/fs/cgroup/cpu.max").split(" "),o=t[0],n=t[1];return !o||!n||o==="max"?null:yb(o)/yb(n)}catch{}try{let e=xv("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),t=xv("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return e===-1||isNaN(t)?null:e/t}catch{return null}}function FM(){if(NM!=="linux")return null;let e=mae();if(e===null)return null;let t=w3e()??Jp.cpus().length,o=e,n=Date.now();return ()=>{let r=mae();if(r===null)return null;let i=Date.now(),a=i-n;if(a<=0)return null;let s=r-o,l=a*1e3,c=Math.max(0,Math.min(100,s/l/t*100));return o=r,n=i,{measurementTime:i,intervalMs:a,user:c,nice:0,sys:0,idle:Math.max(0,100-c),irq:0,total:c}}}function R3e(){let e=process.cpuUsage(),t=process.hrtime.bigint();return ()=>{let o=process.cpuUsage(),n=process.hrtime.bigint(),r=Number(n-t)/1e6,i=o.user-e.user,a=o.system-e.system;if(e=o,t=n,r<=0)return null;let s=Math.max(Jp.cpus().length,1),l=c=>Math.max(0,c/1e3/r*100/s);return {total:l(i+a),user:l(i),sys:l(a),intervalMs:r}}}function fae({intervalMs:e=y3e,maxSamples:t=1e4,keepSamples:o=true,onSample:n}={}){let r=[],i=FM()??DM(),a=R3e(),s=()=>{let u=Date.now(),d=Sae(),m=process.memoryUsage(),p=i(),h=a(),g={timestamp:u,system:{cpu:p,memory:{total:d.totalMemory,free:d.freeMemory,freePercentage:d.freePercentage}},process:{cpu:h,memory:{rss:m.rss,heapTotal:m.heapTotal,heapUsed:m.heapUsed,external:m.external,arrayBuffers:m.arrayBuffers}}};n?.(g),o&&(r.push(g),r.length>t&&r.shift());};s();let l=setInterval(s,e),c=u=>({samples:o?[...r]:[]});return {stop:()=>(clearInterval(l),c()),getSeries:()=>c()}}var C3e=LM(),I3e=FM()??DM(),yae=e=>{e2({logger:e,processUsageTracker:C3e,cpuUsageTracker:I3e});},bae=e=>{let t=LM(),o=FM()??DM(),n=()=>e2({logger:e,processUsageTracker:t,cpuUsageTracker:o});n(),setTimeout(n,5e3);};function BM(e,t={}){let o=LM(),n=FM()??DM(),r={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0,minFreeMemoryRatio:1,maxCpuPercentage:0,maxHeapUsageRatio:0,maxMemoryUsedBytes:0,maxCurrentProcessTreeRssBytes:0,maxVisibleProcessRssBytes:0,peakDetailedMemoryUsedBytes:0},i=()=>{let a=e2({logger:e,processUsageTracker:o,cpuUsageTracker:n});if(!a)return;r.samples++,a.memoryPressure&&r.lowMemorySamples++,a.cpuPressure&&r.highCpuSamples++,a.heapPressure&&r.highHeapSamples++,r.minFreeMemoryRatio=Math.min(r.minFreeMemoryRatio,a.memory.freePercentage);let s=a.cpu?.total??0;a.details&&s>=r.maxCpuPercentage&&(r.peakCpuDetails=a.details),r.maxCpuPercentage=Math.max(r.maxCpuPercentage,s),r.maxHeapUsageRatio=Math.max(r.maxHeapUsageRatio,a.heapUsageRatio),r.maxMemoryUsedBytes=Math.max(r.maxMemoryUsedBytes,a.memory.totalMemory-a.memory.freeMemory),r.maxCurrentProcessTreeRssBytes=Math.max(r.maxCurrentProcessTreeRssBytes,a.details?.processes?.currentProcessTreeRssBytes??0),r.maxVisibleProcessRssBytes=Math.max(r.maxVisibleProcessRssBytes,a.details?.processes?.visibleProcessRssBytes??0);let l=a.memory.totalMemory-a.memory.freeMemory;a.details&&l>=r.peakDetailedMemoryUsedBytes&&(r.peakDetailedMemoryUsedBytes=l,r.peakMemoryDetails=a.details);};return i(),{interval:setInterval(i,t.intervalMs??b3e),cpuMetadata:A3e,platform:NM,getSummary:()=>({...r})}}function e2({logger:e,processUsageTracker:t,cpuUsageTracker:o}){try{let n={},r=Sae(),i=o();ZC.samples++;let a=r.freePercentage<.05;a&&(Object.assign(n,process.memoryUsage()),ZC.lowMemorySamples++);let s=i!==null&&i.total>80;s&&ZC.highCpuSamples++;let l=f3e.getHeapStatistics(),c=l.used_heap_size,u=l.heap_size_limit,d=c/u,m=d>.9;m&&ZC.highHeapSamples++;let p=a||s||m,g=r.freePercentage<S3e||i!==null&&i.total>T3e||d>v3e?{cgroupMemory:uae(),processes:t()}:void 0;return p?e.warn({memory:r,cpu:i,heapStats:l,resourceUsageDetails:g,...n},"Critical resource usage metrics detected"):e.debug({memory:r,cpu:i,heapUsageRatio:d,resourceUsageDetails:g},"Got machine resource usage metrics"),{memory:r,cpu:i,heapUsageRatio:d,memoryPressure:a,cpuPressure:s,heapPressure:m,details:g}}catch{return}}function x3e(){if(NM!=="linux")return null;try{let e=ZG("/sys/fs/cgroup/memory.max"),t=xv("/sys/fs/cgroup/memory.current");if(e==="max"||isNaN(t))return null;let o=yb(e);if(isNaN(o))return null;let n=Math.max(0,o-t);return {totalMemory:o,freeMemory:n,freePercentage:n/o}}catch{}try{let e=xv("/sys/fs/cgroup/memory/memory.limit_in_bytes"),t=xv("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(e)||isNaN(t))return null;let o=Jp.totalmem();if(e>=o)return null;let n=Math.max(0,e-t);return {totalMemory:e,freeMemory:n,freePercentage:n/e}}catch{return null}}function Sae(){let e=x3e();if(e)return e;let t=Jp.totalmem(),o=NM==="darwin"?_3e():(()=>{let r=Jp.freemem();return {availableMemory:r,rawFreeMemory:r,cachedMemory:0}})(),n=o.availableMemory/t;return {totalMemory:t,freeMemory:o.availableMemory,freePercentage:n}}function _3e(){try{let e=execSync("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),o=e.match(/page size of (\d+) bytes/)?.[1],n=o?yb(o):4096,r=u=>{let m=e.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?yb(m):0},i=r("Pages free"),a=r("Pages inactive"),s=r("Pages speculative"),l=i*n,c=(a+s)*n;return {availableMemory:l+c,rawFreeMemory:l,cachedMemory:c}}catch{let e=Jp.freemem();return {availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}process.env.APP||"unknown";var UM="deployment.environment",jM="service.instance.id";function Tae(){return process.env.MOMENTIC_LOCAL_DEV==="1"&&process.env.LOCAL_SIGNOZ==="true"}var bb=false,zM,tI=new Map,H3e={forceFlush:()=>Promise.resolve(),onStart:e=>{let{traceId:t,spanId:o}=e.spanContext();tI.set(`${t}:${o}`,e);},onEnd:e=>{let{traceId:t,spanId:o}=e.spanContext();tI.delete(`${t}:${o}`);},shutdown:()=>Promise.resolve()},eI,oI,$3e=[],HM,G3e=2e4;function oi(){return bb}async function V3e(){for(let e of $3e)try{await e();}catch{}}function W3e(){return oi()&&trace.getSpan(context.active())!==void 0}function q3e(){return Tae()?new OTLPTraceExporter({url:"http://localhost:4318/v1/traces"}):new OTLPTraceExporter({url:`${wv}/v1/traces`,headers:{"x-momentic-metrics-api-key":Rv},timeoutMillis:G3e})}function K3e(e){let t="production",o=v4$1(),n=q3e();return new NodeTracerProvider({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:e,[UM]:t,[jM]:o,[ATTR_SERVICE_VERSION]:"3.62.3"}),spanProcessors:[H3e,new BatchSpanProcessor(n)]})}function Y3e(e){HM=registerInstrumentations({tracerProvider:e,instrumentations:[new UndiciInstrumentation({requireParentforSpans:true})]});}function J3e(e){return !e&&!zM?trace.getTracer("momentic-serverless"):oI?.getTracer("momentic-serverless")??trace.getTracer("momentic-serverless")}async function su(e){if(!(!e.enabled||bb))try{zM=e.serviceName;let t=K3e(e.serviceName);oI=t,eI=new AsyncLocalStorageContextManager,t.register({contextManager:eI.enable(),propagator:new W3CTraceContextPropagator}),Y3e(t),bb=!0;}catch{bb=false,zM=void 0,oI=void 0,eI=void 0,HM=void 0;}}function X3e(e){if(bb){for(let t of Array.from(tI.values()).reverse())try{t.setAttribute("momentic.aborted",!0),t.setAttribute("momentic.abort_reason",e),t.setStatus({code:SpanStatusCode.ERROR,message:e}),t.end();}catch{}tI.clear();}}async function $M(e="shutdown"){if(bb)try{X3e(e),await Promise.allSettled([oI?.shutdown(),V3e()]);}catch{}finally{HM?.();try{eI?.disable();}catch{}bb=false,zM=void 0,tI.clear(),eI=void 0,oI=void 0,HM=void 0;}}async function ge(e){if(!oi()||!e.root&&!e.newTrace&&!W3e())return e.fn(void 0);let t=e.serviceName===void 0?e.attributes:{...e.attributes??{},"momentic.span_service_name":e.serviceName};return await J3e(e.serviceName).startActiveSpan(e.name,{attributes:t,kind:e.kind??SpanKind.CLIENT},e.newTrace?ROOT_CONTEXT:context.active(),async o=>{try{let n=await e.fn(o);return o.setStatus({code:SpanStatusCode.OK}),n}catch(n){throw o.setStatus({code:SpanStatusCode.ERROR,message:n instanceof Error?n.message.slice(0,300):void 0}),n instanceof Error&&o.recordException(n),n}finally{o.end();}})}var nI=class{increment(t,o,n){}gauge(t,o){}distribution(t,o,n){}async flush(){}async recordDuration(t){return await n2(t)}};async function n2({fn:e,name:t,timeoutMs:o,timeoutMessage:n,trace:r}){let i=r?()=>ge({name:r.name,attributes:r.attributes,fn:e}):e,a=Promise.resolve(i());return o===void 0?await a:await ye(a,{milliseconds:o,message:n??`Timed out after ${o}ms recording duration for ${t}`})}function GM(e){return e instanceof Error?e.name==="TimeoutError"?"timeout":e.name==="AbortError"?"aborted":"error":"error"}function r2(e){if(!e||e.length===0)return {};let t={};for(let o of e){let n=o.indexOf(":");if(n>-1){let r=o.slice(0,n).trim(),i=o.slice(n+1).trim();r&&(t[r]=i);continue}t[o]=true;}return t}function i2(e,t){let o=r2(e);return !t||Object.keys(t).length===0?o:{...t,...o}}function d5e(){return new OTLPMetricExporter({url:`${wv}/v1/metrics`,headers:{"x-momentic-metrics-api-key":Rv},temporalityPreference:AggregationTemporalityPreference.DELTA})}var a2=[100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],lu=(e,t,o)=>({instrumentName:e,instrumentType:InstrumentType.HISTOGRAM,aggregation:{type:AggregationType.EXPLICIT_BUCKET_HISTOGRAM,options:{boundaries:t,recordMinMax:false}},...o?{attributeKeys:o}:void 0}),m5e=[1e3,5e3,15e3,3e4,6e4,12e4,3e5,6e5,12e5,18e5,36e5],p5e=[500,1e3,2e3,5e3,1e4,2e4,3e4,6e4,12e4,3e5,6e5],Eae=[25,50,100,250,500,1e3,2e3,3e3,5e3,7500,1e4,15e3,3e4,6e4],h5e=[50,100,250,500,1e3,2e3,5e3,1e4,2e4,3e4,6e4,12e4,3e5],s2=[1e4,3e4,6e4,12e4,3e5,6e5,9e5,12e5,18e5,36e5,54e5,72e5,108e5],g5e=[lu("test_event_duration",a2),lu("test_step_duration",a2),lu("test_mobile_step_duration",a2),lu("web_agent_action_duration",[25,50,100,200,350,500,750,1e3,2e3,5e3,1e4,2e4,3e4,6e4],["op","outcome"]),lu("mo_turn_duration_ms",m5e,["agent","outcome","env","platform"]),lu("mo_model_preparation_duration_ms",Eae,["agent","env","platform"]),lu("mo_model_time_to_first_token_ms",Eae,["agent","env","platform"]),lu("mo_step_duration_ms",p5e,["agent","env"]),lu("mo_tool_call_duration_ms",h5e,["agent","tool","outcome","env"]),lu("sandbox_bug_reproduction_latency",s2,["outcome","env"]),lu("sandbox_bugbash_latency",s2,["env"]),lu("sandbox_explore_latency",s2,["env"])],VM=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(t){let o=this.counterCache.get(t);if(o)return o;let n=this.meter.createCounter(t);return this.counterCache.set(t,n),n}getHistogram(t){let o=this.histogramCache.get(t);if(o)return o;let n=this.meter.createHistogram(t);return this.histogramCache.set(t,n),n}ensureObservableGauge(t){let o=this.observableGaugeCache.get(t);if(o)return o;let n=this.meter.createObservableGauge(t);return n.addCallback(r=>{let i=this.gaugeValues.get(t);i!==void 0&&r.observe(i,this.globalAttributes);}),this.observableGaugeCache.set(t,n),n}constructor(t){this.globalAttributes={...t.globalAttributes??{}};let o=typeof process<"u"?"production":"unknown",n=resourceFromAttributes({[ATTR_SERVICE_NAME]:t.serviceName,[UM]:o,[jM]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:v4$1(),[ATTR_SERVICE_VERSION]:"3.62.3"}),r=d5e(),i=new PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:t.exportIntervalMs??6e4});this.provider=new MeterProvider({resource:n,readers:[i],views:g5e}),metrics.setGlobalMeterProvider(this.provider),this.meter=this.provider.getMeter("momentic-serverless");}increment(t,o,n){try{let r=i2(n,this.globalAttributes);this.getCounter(t).add(typeof o=="number"?o:1,r);}catch{}}gauge(t,o){try{this.ensureObservableGauge(t),this.gaugeValues.set(t,o);}catch{}}distribution(t,o,n){try{let r=i2(n,this.globalAttributes);this.getHistogram(t).record(o,r);}catch{}}async flush(){try{await this.provider.forceFlush();}catch{}}async recordDuration(t){let{name:o,recordOutcome:n,tags:r}=t,i=Date.now(),a="success";try{return await n2(t)}catch(s){throw a=GM(s),s}finally{this.distribution(o,Date.now()-i,n?[...r??[],`outcome:${a}`]:r);}}};var zo=new nI;function wae(e){if(!e.disabled)try{zo=new VM(e);}catch{zo=new nI;}}var l2;function Rae(e){l2=e;}function Tm(e){y5e(e)&&l2&&l2(e);}var f5e=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function y5e(e){return e instanceof Error&&e.name==="AbortError"?false:Qw(e,hg)?true:Qw(e,ae)?false:e instanceof ie?f5e.has(e.reason):true}var b5e=z.object({openrouter:z.object({usage:z.object({cost:z.number().finite().nonnegative()})})});function _v({feature:e,orgId:t,result:o}){zo.increment("ai_agent_invocations",1,[`feature:${e}`,`orgId:${t}`,`result:${o}`]);}function S5e(e){let t=b5e.safeParse(e);return t.success?t.data.openrouter.usage.cost:void 0}function qM(e){let t;for(let o of e){let n=S5e(o);n!==void 0&&(t=(t??0)+n);}return t}function qg(e){let t=0,o=0,n=0,r=0,i=0,a=0,s=0,l=0;for(let c of e)t+=c.inputTokens??0,o+=c.inputTokenDetails.noCacheTokens??0,n+=c.inputTokenDetails.cacheReadTokens??0,r+=c.inputTokenDetails.cacheWriteTokens??0,i+=c.outputTokens??0,a+=c.outputTokenDetails.textTokens??0,s+=c.outputTokenDetails.reasoningTokens??0,l+=c.totalTokens??0;return {inputTokens:t,inputTokenDetails:{noCacheTokens:o,cacheReadTokens:n,cacheWriteTokens:r},outputTokens:i,outputTokenDetails:{textTokens:a,reasoningTokens:s},totalTokens:l}}function T5e({usage:e,promptType:t,result:o="success",tags:n=[]}){let r=[`type:${t}`,`result:${o}`,...n],i=e.inputTokens??0,a=e.inputTokenDetails.cacheReadTokens??0,s=e.inputTokenDetails.cacheWriteTokens??0,l=e.outputTokens??0;zo.distribution("ai_session_tokens",i,[...r,"category:input"]),zo.distribution("ai_session_tokens",Math.max(0,Math.min(a,i)),[...r,"category:cached_input"]),zo.distribution("ai_session_tokens",Math.max(0,Math.min(s,i-a)),[...r,"category:cache_write_input"]),zo.distribution("ai_session_tokens",l,[...r,"category:output"]);}function rd({usage:e,costUsd:t,promptType:o,logger:n,message:r,result:i="success",attributes:a,metricTags:s}){T5e({usage:e,promptType:o,result:i,tags:s}),n.info({...a,promptType:o,result:i,usage:e,costUsd:t},r);}function Mi({usage:e,promptType:t,logger:o,metricTags:n}){let r=Promise.resolve(e).catch(i=>{o.warn({err:i,promptType:t},"Failed to resolve AI session usage");});return ({message:i,result:a="success",attributes:s})=>{r.then(l=>{l&&rd({usage:l,promptType:t,logger:o,result:a,message:i,attributes:s,metricTags:n});});}}var v5e=1e4;function KM({durationMs:e,executor:t,logger:o,orgId:n,resolvedStep:r,status:i}){if(!Vie(r))return;let a=Gie(r);zo.distribution("test_step_duration",e,[`type:${a}`,"platform:browser",`executor:${t}`,`orgId:${n}`]),!(i!=="SUCCESS"||e<v5e)&&o.info({durationMs:e,executor:t,orgId:n,outcome:"success",stepId:r.id,stepType:a},"test_step_latency_outlier");}function id(e){let t=e.toLowerCase(),o=[["google.vertex","gcp.vertex_ai"],["google.generative-ai","gcp.gemini"],["google-vertex","gcp.vertex_ai"],["amazon-bedrock","aws.bedrock"],["azure-openai","azure.ai.openai"],["anthropic","anthropic"],["openai","openai"],["azure","azure.ai.inference"],["google","gcp.gemini"],["mistral","mistral_ai"],["cohere","cohere"],["bedrock","aws.bedrock"],["groq","groq"],["deepseek","deepseek"],["perplexity","perplexity"],["xai","x_ai"]];for(let[n,r]of o)if(t===n||t.startsWith(n+".")||t.startsWith(n+"-"))return r;return e}function c2(e){var t;return (t={"ai.generateText":"invoke_agent","ai.streamText":"invoke_agent","ai.generateObject":"invoke_agent","ai.streamObject":"invoke_agent","ai.embed":"embeddings","ai.embedMany":"embeddings","ai.rerank":"rerank"}[e])!=null?t:e}function rI(e){return typeof e=="string"?[{type:"text",content:e}]:Array.isArray(e)?e.map(t=>({type:"text",content:t.content})):[{type:"text",content:e.content}]}function A5e(e){var t,o,n,r,i;switch(e.type){case "text":return {type:"text",content:e.text};case "reasoning":return {type:"reasoning",content:e.text};case "tool-call":return {type:"tool_call",id:(t=e.toolCallId)!=null?t:null,name:e.toolName,arguments:e.input};case "tool-result":{let a=e.output,s;return a&&(a.type==="text"||a.type==="error-text"||a.type==="json"||a.type==="error-json"?s=a.value:a.type==="execution-denied"?s={denied:true,reason:a.reason}:s=a),{type:"tool_call_response",id:(o=e.toolCallId)!=null?o:null,response:s}}case "file":{let a=e.data,s=(()=>{if(typeof a=="object"&&a!==null&&!(a instanceof URL)&&!(a instanceof Uint8Array)&&!(a instanceof ArrayBuffer)&&"type"in a)switch(a.type){case "data":return a.data;case "url":return a.url;case "text":return a.text;default:return ""}return a})(),l;if(s instanceof Uint8Array)l=convertDataContentToBase64String(s);else if(typeof s=="string"){if(s.startsWith("http://")||s.startsWith("https://"))return {type:"uri",modality:Kg(e.mediaType),mime_type:(n=e.mediaType)!=null?n:null,uri:s};l=s;}else {if(s instanceof URL)return {type:"uri",modality:Kg(e.mediaType),mime_type:(r=e.mediaType)!=null?r:null,uri:s.toString()};l=String(s);}return {type:"blob",modality:Kg(e.mediaType),mime_type:(i=e.mediaType)!=null?i:null,content:l}}case "tool-approval-response":return {type:"tool_approval_response",approval_id:e.approvalId,approved:e.approved,reason:e.reason};case "custom":return {type:"custom",kind:e.kind};case "reasoning-file":return {type:String(e.type)};default:return {type:String(e.type)}}}function Kg(e){return !e||e.startsWith("image/")?"image":e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":"image"}function E5e(e){return e.map(t=>{if(t.role==="system")return {role:"system",parts:[{type:"text",content:t.content}]};let o=t.content.map(A5e);return {role:t.role,parts:o}})}function u2({prompt:e,messages:t}){let o=[];if(typeof e=="string")o.push({role:"user",parts:[{type:"text",content:e}]});else if(Array.isArray(e))for(let n of e){let r=Cae(n);r&&o.push(r);}if(t)for(let n of t){let r=Cae(n);r&&o.push(r);}return o}function Cae(e){return e.role==="system"?{role:"system",parts:[{type:"text",content:e.content}]}:e.role==="user"?typeof e.content=="string"?{role:"user",parts:[{type:"text",content:e.content}]}:{role:"user",parts:e.content.map(n=>{var r,i,a,s,l,c,u,d;switch(n.type){case "text":return {type:"text",content:n.text};case "image":{let m=n.image;return m instanceof URL?{type:"uri",modality:"image",mime_type:(r=n.mediaType)!=null?r:null,uri:m.toString()}:typeof m=="string"?m.startsWith("http://")||m.startsWith("https://")?{type:"uri",modality:"image",mime_type:(i=n.mediaType)!=null?i:null,uri:m}:{type:"blob",modality:"image",mime_type:(a=n.mediaType)!=null?a:null,content:m}:{type:"blob",modality:"image",mime_type:(s=n.mediaType)!=null?s:null,content:convertDataContentToBase64String(m)}}case "file":{let m=n.data,p=(()=>{if(typeof m=="object"&&m!==null&&!(m instanceof URL)&&!(m instanceof Uint8Array)&&!(m instanceof ArrayBuffer)&&"type"in m)switch(m.type){case "data":return m.data;case "url":return m.url;case "text":return m.text;default:return ""}return m})();return p instanceof URL?{type:"uri",modality:Kg(n.mediaType),mime_type:(l=n.mediaType)!=null?l:null,uri:p.toString()}:typeof p=="string"?p.startsWith("http://")||p.startsWith("https://")?{type:"uri",modality:Kg(n.mediaType),mime_type:(c=n.mediaType)!=null?c:null,uri:p}:{type:"blob",modality:Kg(n.mediaType),mime_type:(u=n.mediaType)!=null?u:null,content:p}:{type:"blob",modality:Kg(n.mediaType),mime_type:(d=n.mediaType)!=null?d:null,content:convertDataContentToBase64String(p)}}default:return {type:String(n.type)}}})}:e.role==="assistant"?typeof e.content=="string"?{role:"assistant",parts:[{type:"text",content:e.content}]}:{role:"assistant",parts:e.content.map(n=>{var r,i;switch(n.type){case "text":return {type:"text",content:n.text};case "reasoning":return {type:"reasoning",content:n.text};case "tool-call":return {type:"tool_call",id:(r=n.toolCallId)!=null?r:null,name:n.toolName,arguments:n.input};case "tool-result":{let a=n.output,s;return a&&(a.type==="text"||a.type==="error-text"||a.type==="json"||a.type==="error-json"?s=a.value:a.type==="execution-denied"?s={denied:true,reason:a.reason}:s=a),{type:"tool_call_response",id:(i=n.toolCallId)!=null?i:null,response:s}}default:return {type:String(n.type)}}})}:e.role==="tool"?{role:"tool",parts:e.content.map(n=>{var r;if(n.type==="tool-result"){let i=n.output,a;return i&&(i.type==="text"||i.type==="error-text"||i.type==="json"||i.type==="error-json"?a=i.value:i.type==="execution-denied"?a={denied:true,reason:i.reason}:a=i),{type:"tool_call_response",id:(r=n.toolCallId)!=null?r:null,response:a}}return {type:String(n.type)}})}:e}function Iae({text:e,reasoning:t,toolCalls:o,toolResults:n,files:r,finishReason:i}){let a=[];if(t)for(let s of t)"text"in s&&s.text&&a.push({type:"reasoning",content:s.text});if(e!=null&&e.length>0&&a.push({type:"text",content:e}),o)for(let s of o)a.push({type:"tool_call",id:s.toolCallId,name:s.toolName,arguments:s.input});if(n)for(let s of n)a.push({type:"tool_call_response",id:s.toolCallId,response:s.output});if(r)for(let s of r)a.push({type:"blob",modality:Kg(s.mediaType),mime_type:s.mediaType,content:s.base64});return [{role:"assistant",parts:a,finish_reason:Oae(i)}]}function xae({objectText:e,finishReason:t}){return [{role:"assistant",parts:[{type:"text",content:e}],finish_reason:Oae(t)}]}function Oae(e){var t;return (t={stop:"stop",length:"length","content-filter":"content_filter","tool-calls":"tool_call",error:"error",other:"stop",unknown:"stop"}[e])!=null?t:e}function Xp(e,t){let o=RetryError.isInstance(t)?t.lastError:t;APICallError$1.isInstance(o)&&o.statusCode!=null&&e.setAttribute("http.response.status_code",o.statusCode),t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:SpanStatusCode.ERROR});}function C5e(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function JM(e){if(!Array.isArray(e))return typeof e=="number"&&!Number.isFinite(e)?void 0:e;let t=new Set(e.filter(C5e).map(n=>typeof n));if(t.size!==1)return;let[o]=t;if(o==="string")return e.filter(n=>typeof n=="string");if(o==="number"){let n=e.filter(r=>typeof r=="number");return n.every(Number.isFinite)?n:void 0}return e.filter(n=>typeof n=="boolean")}function I5e(e){let t={};for(let[o,n]of Object.entries(e??{})){if(n==null)continue;let r=JM(n);r!=null&&(t[o]=r);}return t}function x5e(e){return e?.isEnabled!==false}function Fr(e,t){if(!x5e(e))return {};let o={};for(let[n,r]of Object.entries(t)){if(r==null)continue;if(typeof r=="object"&&"input"in r&&typeof r.input=="function"){if(e?.recordInputs===false)continue;let a=r.input();if(a!=null){let s=JM(a);s!=null&&(o[n]=s);}continue}if(typeof r=="object"&&"output"in r&&typeof r.output=="function"){if(e?.recordOutputs===false)continue;let a=r.output();if(a!=null){let s=JM(a);s!=null&&(o[n]=s);}continue}let i=JM(r);i!=null&&(o[n]=i);}return o}var _5e={usage:false,providerMetadata:false,embedding:false,reranking:false,experimental_evaluation:false,runtimeContext:false,headers:false,toolChoice:false,schema:false};function O5e(e){var t,o,n,r,i,a,s,l,c;return {..._5e,usage:(t=e.usage)!=null?t:false,providerMetadata:(o=e.providerMetadata)!=null?o:false,embedding:(n=e.embedding)!=null?n:false,reranking:(r=e.reranking)!=null?r:false,experimental_evaluation:(i=e.experimental_evaluation)!=null?i:false,runtimeContext:(a=e.runtimeContext)!=null?a:false,headers:(s=e.headers)!=null?s:false,toolChoice:(l=e.toolChoice)!=null?l:false,schema:(c=e.schema)!=null?c:false}}function YM(e){let t={};for(let[o,n]of Object.entries(e??{}))Pae(t,`ai.settings.context.${o}`,n);return t}function Pae(e,t,o){if(o!=null){if(Array.isArray(o)||typeof o!="object"){e[t]=o;return}for(let[n,r]of Object.entries(o))Pae(e,`${t}.${n}`,r);}}function iI(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!=null).map(([t,o])=>[`ai.request.headers.${t}`,o]))}function aI(e){var t,o,n;return {"ai.usage.inputTokenDetails.noCacheTokens":(t=e.inputTokenDetails)==null?void 0:t.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":(o=e.outputTokenDetails)==null?void 0:o.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(n=e.outputTokenDetails)==null?void 0:n.reasoningTokens}}function Kr(e,t,o){let n={};for(let[r,i]of Object.entries(o))!t[r]||i==null||Object.assign(n,Fr(e,i));return n}function XM(e){return e==null?void 0:e/1e3}function P5e(e){var t;return {"gen_ai.client.operation.duration":XM(e.responseTimeMs),"gen_ai.client.operation.time_to_first_chunk":XM(e.timeToFirstOutputMs),"gen_ai.client.operation.time_per_output_chunk":XM((t=e.timeBetweenOutputChunksMs)==null?void 0:t.avg)}}var kae=class{constructor(e={}){this.callStates=new Map;var t;this.tracer=(t=e.tracer)!=null?t:trace.getTracer("gen_ai"),this.supplementalAttributes=O5e(e),this.enrichSpan=e.enrichSpan;}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e);}getSpanAttributes({attributes:e,spanType:t,operationId:o,callId:n,runtimeContext:r}){var i;let a;try{a=(i=this.enrichSpan)==null?void 0:i.call(this,{spanType:t,operationId:o,callId:n,runtimeContext:r});}catch{a=void 0;}return {...I5e(a),...e}}executeTool({callId:e,toolCallId:t,execute:o}){var n;let r=(n=this.getCallState(e))==null?void 0:n.toolSpans.get(t);return r==null?o():context.with(r.context,o)}executeLanguageModelCall({callId:e,execute:t}){var o;let n=this.getCallState(e),r=(o=n?.inferenceContext)!=null?o:n?.stepContext;return r==null?t():context.with(r,t)}onStart(e){if(e.operationId==="ai.embed"||e.operationId==="ai.embedMany"){this.onEmbedOperationStart(e);return}if(e.operationId==="ai.rerank"){this.onRerankOperationStart(e);return}if(e.operationId==="ai.generateObject"||e.operationId==="ai.streamObject"){this.onObjectOperationStart(e);return}this.onGenerateStart(e);}onGenerateStart(e){var t;let o={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},n={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},r=id(e.provider),i=c2(e.operationId),a=e.runtimeContext,s=Kr(o,this.supplementalAttributes,{runtimeContext:YM(a),headers:iI(e.headers)}),l=Fr(o,{"gen_ai.operation.name":i,"gen_ai.provider.name":r,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":o.functionId,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":(t=e.temperature)!=null?t:void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.stop_sequences":e.stopSequences,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.instructions!=null?{input:()=>JSON.stringify(rI(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(u2({prompt:void 0,messages:e.messages}))},...s}),c=`${i} ${e.modelId}`,u=this.tracer.startSpan(c,{attributes:this.getSpanAttributes({attributes:l,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:a}),kind:SpanKind.INTERNAL}),d=trace.setSpan(context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:o,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:n,provider:e.provider,modelId:e.modelId,runtimeContext:a,baseSupplementalAttributes:s});}onObjectOperationStart(e){var t;let o={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},n={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},r=id(e.provider),i=c2(e.operationId),a=Kr(o,this.supplementalAttributes,{headers:iI(e.headers)}),s=Fr(o,{"gen_ai.operation.name":i,"gen_ai.provider.name":r,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":o.functionId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":(t=e.temperature)!=null?t:void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.system?{input:()=>JSON.stringify(rI(e.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(u2({prompt:e.prompt,messages:e.messages}))},...a,...Kr(o,this.supplementalAttributes,{schema:{"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}})}),l=`${i} ${e.modelId}`,c=this.tracer.startSpan(l,{attributes:this.getSpanAttributes({attributes:s,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:SpanKind.INTERNAL}),u=trace.setSpan(context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:o,rootSpan:c,rootContext:u,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:n,provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a,objectSystemInstructions:e.system});}onObjectStepStart(e){var t,o;let n=this.getCallState(e.callId);if(!n?.rootSpan||!n.rootContext)return;let{telemetry:r}=n,i=id(e.provider),a=n.objectSystemInstructions==null?0:rI(n.objectSystemInstructions).length,s=(t=e.promptMessages)==null?void 0:t.slice(a),l=Fr(r,{"gen_ai.operation.name":"chat","gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":n.settings.frequencyPenalty,"gen_ai.request.max_tokens":n.settings.maxOutputTokens,"gen_ai.request.presence_penalty":n.settings.presencePenalty,"gen_ai.request.temperature":(o=n.settings.temperature)!=null?o:void 0,"gen_ai.request.top_k":n.settings.topK,"gen_ai.request.top_p":n.settings.topP,"gen_ai.system_instructions":n.objectSystemInstructions!=null?{input:()=>JSON.stringify(rI(n.objectSystemInstructions))}:void 0,"gen_ai.input.messages":{input:()=>s?JSON.stringify(E5e(s)):void 0},...n.baseSupplementalAttributes}),c=`chat ${e.modelId}`;n.inferenceSpan=this.tracer.startSpan(c,{attributes:this.getSpanAttributes({attributes:l,spanType:"languageModel",operationId:n.operationId,callId:e.callId,runtimeContext:n.runtimeContext}),kind:SpanKind.CLIENT},n.rootContext),n.inferenceContext=trace.setSpan(n.rootContext,n.inferenceSpan);}onObjectStepEnd(e){var t;let o=this.getCallState(e.callId);if(!o?.inferenceSpan)return;let{telemetry:n}=o;o.inferenceSpan.setAttributes(Fr(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(t=e.usage.inputTokenDetails)==null?void 0:t.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(xae({objectText:e.objectText,finishReason:e.finishReason}))}catch{return e.objectText}}},...Kr(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:aI(e.usage)})})),o.inferenceSpan.end(),o.inferenceSpan=void 0,o.inferenceContext=void 0;}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o=e.runtimeContext,n=id(e.provider),r=Kr(t,this.supplementalAttributes,{runtimeContext:YM(o),headers:iI(e.headers)}),i=e.value,a=e.operationId==="ai.embedMany",s=c2(e.operationId),l=Fr(t,{"gen_ai.operation.name":s,"gen_ai.provider.name":n,"gen_ai.request.model":e.modelId,...r,...Kr(t,this.supplementalAttributes,{embedding:a?{"ai.values":{input:()=>i.map(m=>JSON.stringify(m))}}:{"ai.value":{input:()=>JSON.stringify(i)}}})}),c=`${s} ${e.modelId}`,u=this.tracer.startSpan(c,{attributes:this.getSpanAttributes({attributes:l,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:o}),kind:SpanKind.CLIENT}),d=trace.setSpan(context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:o,baseSupplementalAttributes:r});}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:o}=t;t.runtimeContext=e.runtimeContext;let n=Fr(o,{"gen_ai.operation.name":"agent_step",...t.baseSupplementalAttributes,...Kr(o,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>e.stepToolChoice!=null?JSON.stringify(e.stepToolChoice):void 0}}})});t.stepSpan=this.tracer.startSpan(`step ${e.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:n,spanType:"step",operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:SpanKind.INTERNAL},t.rootContext),t.stepContext=trace.setSpan(t.rootContext,t.stepSpan);}onLanguageModelCallStart(e){var t;let o=this.getCallState(e.callId);if(!o?.stepContext)return;let{telemetry:n}=o,r=id(e.provider);o.inferenceToolDefinitions=e.tools;let i=Fr(n,{"gen_ai.operation.name":"chat","gen_ai.provider.name":r,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":o.settings.frequencyPenalty,"gen_ai.request.max_tokens":o.settings.maxOutputTokens,"gen_ai.request.presence_penalty":o.settings.presencePenalty,"gen_ai.request.stop_sequences":o.settings.stopSequences,"gen_ai.request.temperature":(t=o.settings.temperature)!=null?t:void 0,"gen_ai.request.top_k":o.settings.topK,"gen_ai.request.top_p":o.settings.topP,"gen_ai.system_instructions":e.instructions!=null?{input:()=>JSON.stringify(rI(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>{let a=u2({prompt:void 0,messages:e.messages});return a.length>0?JSON.stringify(a):void 0}},"gen_ai.tool.definitions":{input:()=>e.tools?JSON.stringify(e.tools):void 0}});o.inferenceSpan=this.tracer.startSpan(`chat ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:i,spanType:"languageModel",operationId:o.operationId,callId:e.callId,runtimeContext:o.runtimeContext}),kind:SpanKind.CLIENT},o.stepContext),o.inferenceContext=trace.setSpan(o.stepContext,o.inferenceSpan);}onLanguageModelCallEnd(e){var t,o,n;let r=this.getCallState(e.callId);if(!r?.inferenceSpan)return;let{telemetry:i}=r,a=id(e.provider),s=[...(t=r.inferenceToolDefinitions)!=null?t:[]],l=new Set(s.flatMap(m=>typeof m.name=="string"?[m.name]:[])),c=false;for(let m of e.content)m.type!=="tool-call"||!m.providerExecuted||l.has(m.toolName)||(s.push({type:"extension",name:m.toolName}),l.add(m.toolName),c=true);r.inferenceSpan.setAttributes(Fr(i,{...P5e(e.performance),"gen_ai.provider.name":a,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.responseId,"gen_ai.response.model":e.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(o=e.usage.inputTokenDetails)==null?void 0:o.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(n=e.usage.inputTokenDetails)==null?void 0:n.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(Iae({text:e.content.filter(m=>m.type==="text").map(m=>m.text).join("")||void 0,reasoning:e.content.filter(m=>m.type==="reasoning"),toolCalls:e.content.filter(m=>m.type==="tool-call"),toolResults:e.content.filter(m=>m.type==="tool-result"),files:e.content.filter(m=>m.type==="file").map(m=>m.file),finishReason:e.finishReason}))},"gen_ai.tool.definitions":c?{input:()=>JSON.stringify(s)}:void 0,...Kr(i,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:aI(e.usage)})}));let u=new Map;for(let m of e.content)(m.type==="tool-error"||m.type==="tool-result"&&m.preliminary!==true)&&u.set(m.toolCallId,m);let d=new Set;for(let m of e.content){if(m.type!=="tool-call"||!m.providerExecuted||d.has(m.toolCallId))continue;d.add(m.toolCallId);let p=this.tracer.startSpan(`execute_tool ${m.toolName}`,{attributes:this.getSpanAttributes({attributes:Fr(i,{"gen_ai.operation.name":"execute_tool","gen_ai.tool.name":m.toolName,"gen_ai.tool.call.id":m.toolCallId,"gen_ai.tool.type":"extension","gen_ai.tool.call.arguments":{input:()=>JSON.stringify(m.input)}}),spanType:"tool",operationId:r.operationId,callId:e.callId,runtimeContext:r.runtimeContext}),kind:SpanKind.INTERNAL},r.inferenceContext),h=u.get(m.toolCallId);if(h?.type==="tool-result")try{p.setAttributes(Fr(i,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(h.output)}}));}catch{}else h?.type==="tool-error"&&Xp(p,h.error);p.end();}r.inferenceSpan.end(),r.inferenceSpan=void 0,r.inferenceContext=void 0,r.inferenceToolDefinitions=void 0;}onToolExecutionStart(e){var t;let o=this.getCallState(e.callId),n=(t=o?.stepContext)!=null?t:o?.rootContext;if(!o||!n)return;let{telemetry:r}=o,{toolCall:i}=e,a=Fr(r,{"gen_ai.operation.name":"execute_tool","gen_ai.tool.name":i.toolName,"gen_ai.tool.call.id":i.toolCallId,"gen_ai.tool.type":i.providerExecuted?"extension":"function","gen_ai.tool.call.arguments":{input:()=>JSON.stringify(i.input)}}),s=`execute_tool ${i.toolName}`,l=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:a,spanType:"tool",operationId:o.operationId,callId:e.callId,runtimeContext:o.runtimeContext}),kind:SpanKind.INTERNAL},n),c=trace.setSpan(n,l);o.toolSpans.set(i.toolCallId,{span:l,context:c});}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let o=t.toolSpans.get(e.toolCall.toolCallId);if(!o)return;let{span:n}=o,{telemetry:r}=t,{toolOutput:i}=e;if(n.setAttributes(Fr(r,{"gen_ai.execute_tool.duration":XM(e.toolExecutionMs)})),i.type==="tool-result")try{n.setAttributes(Fr(r,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(i.output)}}));}catch{}else Xp(n,i.error);n.end(),t.toolSpans.delete(e.toolCall.toolCallId);}onStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:o}=t;t.stepSpan.setAttributes(Kr(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:aI(e.usage)})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0;}onStepFinish(e){this.onStepEnd(e);}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId==="ai.embed"||t.operationId==="ai.embedMany"){this.onEmbedOperationEnd(e);return}if(t.operationId==="ai.rerank"){this.onRerankOperationEnd(e);return}if(t.operationId==="ai.generateObject"||t.operationId==="ai.streamObject"){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e);}}onGenerateEnd(e){var t,o;let n=this.getCallState(e.callId);if(!n?.rootSpan)return;let{telemetry:r}=n;n.rootSpan.setAttributes(Fr(r,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(t=e.usage.inputTokenDetails)==null?void 0:t.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(o=e.usage.inputTokenDetails)==null?void 0:o.cacheWriteTokens,"gen_ai.output.messages":{output:()=>{var i;return JSON.stringify(Iae({text:(i=e.text)!=null?i:void 0,reasoning:e.finalStep.reasoning,toolCalls:e.toolCalls,toolResults:e.toolResults,files:e.files,finishReason:e.finishReason}))}},...Kr(r,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0},usage:aI(e.usage)})})),n.rootSpan.end(),this.cleanupCallState(e.callId);}onObjectOperationEnd(e){var t;let o=this.getCallState(e.callId);if(!o?.rootSpan)return;let{telemetry:n}=o;o.rootSpan.setAttributes(Fr(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(t=e.usage.inputTokenDetails)==null?void 0:t.cacheReadTokens,"gen_ai.output.messages":{output:()=>e.object!=null?JSON.stringify(xae({objectText:JSON.stringify(e.object),finishReason:e.finishReason})):void 0},...Kr(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:aI(e.usage)})})),o.rootSpan.end(),this.cleanupCallState(e.callId);}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:o}=t,n=t.operationId==="ai.embedMany";t.rootSpan.setAttributes(Fr(o,{...Kr(o,this.supplementalAttributes,{embedding:n?{"ai.embeddings":{output:()=>e.embedding.map(r=>JSON.stringify(r))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}}})})),t.rootSpan.end(),this.cleanupCallState(e.callId);}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:o}=t,n=id(t.provider),r=Fr(o,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...Kr(o,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>e.values.map(l=>JSON.stringify(l))}}})}),i=`embeddings ${t.modelId}`,a=this.tracer.startSpan(i,{attributes:this.getSpanAttributes({attributes:r,spanType:"embedding",operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:SpanKind.CLIENT},t.rootContext),s=trace.setSpan(t.rootContext,a);t.embedSpans.set(e.embedCallId,{span:a,context:s});}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let o=t.embedSpans.get(e.embedCallId);if(!o)return;let{span:n}=o,{telemetry:r}=t;n.setAttributes(Fr(r,{"gen_ai.usage.input_tokens":e.usage.tokens,...Kr(r,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>e.embeddings.map(i=>JSON.stringify(i))}}})})),n.end(),t.embedSpans.delete(e.embedCallId);}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o=e.runtimeContext,n=id(e.provider),r=Kr(t,this.supplementalAttributes,{runtimeContext:YM(o),headers:iI(e.headers)}),i=Fr(t,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":n,"gen_ai.request.model":e.modelId,...r,...Kr(t,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(c=>JSON.stringify(c))}}})}),a=`rerank ${e.modelId}`,s=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:i,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:o}),kind:SpanKind.CLIENT}),l=trace.setSpan(context.active(),s);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:s,rootContext:l,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:o,baseSupplementalAttributes:r});}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId));}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:o}=t,n=id(t.provider),r=Fr(o,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...Kr(o,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(l=>JSON.stringify(l))}}})}),i=`rerank ${t.modelId}`,a=this.tracer.startSpan(i,{attributes:this.getSpanAttributes({attributes:r,spanType:"reranking",operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:SpanKind.CLIENT},t.rootContext),s=trace.setSpan(t.rootContext,a);t.rerankSpan={span:a,context:s};}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:o}=t.rerankSpan,{telemetry:n}=t;o.setAttributes(Kr(n,this.supplementalAttributes,{reranking:{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(r=>JSON.stringify(r))}}})),o.end(),t.rerankSpan=void 0;}onEvaluateOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o=e.runtimeContext,n=Kr(t,this.supplementalAttributes,{runtimeContext:YM(o),headers:iI(e.headers)}),r=Fr(t,{"gen_ai.operation.name":"evaluate","gen_ai.provider.name":id(e.provider),"gen_ai.request.model":e.modelId,...n,...Kr(t,this.supplementalAttributes,{experimental_evaluation:{"ai.evaluation.state":{input:()=>JSON.stringify(e.state)},"ai.evaluation.questions":{input:()=>JSON.stringify(e.questions)}}})}),i=this.tracer.startSpan(`evaluate ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:r,spanType:"operation",operationId:e.operationId,callId:e.callId,runtimeContext:o}),kind:SpanKind.CLIENT}),a=trace.setSpan(context.active(),i);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:i,rootContext:a,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,evaluationSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:o,baseSupplementalAttributes:n});}onEvaluateOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.setAttributes(Kr(t.telemetry,this.supplementalAttributes,{experimental_evaluation:{"ai.evaluation.answers":{output:()=>JSON.stringify(e.answers)}}})),t.rootSpan.end(),this.cleanupCallState(e.callId));}experimental_onEvaluateStart(e){this.onEvaluateOperationStart(e);}experimental_onEvaluateEnd(e){this.onEvaluateOperationEnd(e);}experimental_onEvaluationModelCallStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let o=Fr(t.telemetry,{"gen_ai.operation.name":"evaluate","gen_ai.provider.name":id(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...Kr(t.telemetry,this.supplementalAttributes,{experimental_evaluation:{"ai.evaluation.state":{input:()=>JSON.stringify(e.state)},"ai.evaluation.questions":{input:()=>JSON.stringify(e.questions)}}})}),n=this.tracer.startSpan(`evaluate ${t.modelId}`,{attributes:this.getSpanAttributes({attributes:o,spanType:"experimental_evaluation",operationId:e.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:SpanKind.CLIENT},t.rootContext);t.evaluationSpan={span:n,context:trace.setSpan(t.rootContext,n)};}experimental_onEvaluationModelCallEnd(e){var t,o;let n=this.getCallState(e.callId);n?.evaluationSpan&&(n.evaluationSpan.span.setAttributes(Fr(n.telemetry,{"gen_ai.usage.input_tokens":(t=e.usage)==null?void 0:t.inputTokens,"gen_ai.usage.output_tokens":(o=e.usage)==null?void 0:o.outputTokens,...Kr(n.telemetry,this.supplementalAttributes,{experimental_evaluation:{"ai.evaluation.answers":{output:()=>JSON.stringify(e.answers)}},providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0}})})),n.evaluationSpan.span.end(),n.evaluationSpan=void 0);}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:o}of t.toolSpans.values())o.end();t.toolSpans.clear(),t.inferenceSpan&&(t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:o}of t.embedSpans.values())o.end();t.embedSpans.clear(),t.rerankSpan&&(t.rerankSpan.span.end(),t.rerankSpan=void 0),t.evaluationSpan&&(t.evaluationSpan.span.end(),t.evaluationSpan=void 0),t.rootSpan.end(),this.cleanupCallState(e.callId);}}onError(e){var t;let o=e;if(!o?.callId)return;let n=this.getCallState(o.callId);if(!n?.rootSpan)return;let r=(t=o.error)!=null?t:e;for(let{span:i}of n.toolSpans.values())Xp(i,r),i.end();n.toolSpans.clear(),n.inferenceSpan&&(Xp(n.inferenceSpan,r),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0),n.stepSpan&&(Xp(n.stepSpan,r),n.stepSpan.end(),n.stepSpan=void 0,n.stepContext=void 0);for(let{span:i}of n.embedSpans.values())Xp(i,r),i.end();n.embedSpans.clear(),n.rerankSpan&&(Xp(n.rerankSpan.span,r),n.rerankSpan.span.end(),n.rerankSpan=void 0),n.evaluationSpan&&(Xp(n.evaluationSpan.span,r),n.evaluationSpan.span.end(),n.evaluationSpan=void 0),Xp(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(o.callId);}};function m2(e={}){return new kae({enrichSpan:({runtimeContext:t})=>{let o=Object.fromEntries(Object.entries(e).map(([n,r])=>[`ai.telemetry.metadata.${n}`,r]));for(let n of ["orgId","runId","sessionId"]){let r=t?.[n];typeof r=="string"&&(o[`ai.telemetry.metadata.${n}`]=r);}return o}})}var ps=m2();function rt(e=process.stdout){let t=e===process.stderr?supportsColorStderr:supportsColor,o=process.env.CLICOLOR_FORCE!==void 0&&process.env.CLICOLOR_FORCE!=="0",n=o||process.env.FORCE_COLOR!==void 0&&process.env.FORCE_COLOR!=="0",r=t?t.level:0;o&&r===0&&(r=1),(process.env.NO_COLOR!==void 0&&process.env.NO_COLOR!==""||process.env.CLICOLOR==="0")&&!n&&(r=0);let a=process.env.LC_ALL??process.env.LC_CTYPE??process.env.LANG??"",s=process.env.MOMENTIC_NO_UNICODE===void 0&&process.env.TERM!=="linux"&&(process.platform==="win32"||/utf-?8/i.test(a));return {isTTY:!!e.isTTY,colorLevel:r,unicode:s,columns:e.columns??-1,ci:ms,colorForced:n}}function vm(e){return e.isTTY&&!e.ci&&e.columns>0}var Mae="\r",Lae="\x1B[1A",Nae="\x1B[J",Dae="\x1B[?25l",p2="\x1B[?25h",N5e="\u28CB\u28D9\u28F9\u28F8\u28FC\u28F4\u28E6\u28E7\u28C7\u28CF",D5e="|/-\\",F5e="\u2736\u2738\u2739\u273A\u2739\u2737",B5e="*",U5e="#0891b2",j5e={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 ht(e){let t=e.colorLevel>0&&(e.isTTY||e.colorForced),o=new Chalk({level:t?e.colorLevel:0}),n=(r,i)=>t?i(o,r):r;return {unicode:e.unicode,color:t,bold:r=>n(r,(i,a)=>i.bold(a)),dim:r=>n(r,(i,a)=>i.gray(a)),red:r=>n(r,(i,a)=>i.red(a)),green:r=>n(r,(i,a)=>i.green(a)),yellow:r=>n(r,(i,a)=>i.yellow(a)),code:r=>n(r,(i,a)=>i.hex(U5e)(a)),spinner:r=>{let i=e.unicode?N5e:D5e,a=(r%i.length+i.length)%i.length;return n(i.charAt(a),(s,l)=>s.cyan(l))},classifySpinner:r=>{let i=e.unicode?F5e:B5e,a=(r%i.length+i.length)%i.length;return n(i.charAt(a),(s,l)=>s.cyan(l))},statusGlyph:r=>{let i=j5e[r],a=e.unicode?i.glyph:i.ascii;return t?i.paint(o,a):a},separator:e.unicode?" \xB7 ":" | "}}var h2=class extends Console{_buffer=[];Console=Console;constructor(){super({write:t=>(this._buffer.push(t),true)});}_log(t){this._buffer.push(t);}debug(t,...o){this._log(format(t,...o));}error(t,...o){this._log(format(t,...o));}info(t,...o){this._log(format(t,...o));}log(t,...o){this._log(format(t,...o));}warn(t,...o){this._log(format(t,...o));}flushed(){return this._buffer.length>0?this._buffer.join(`
189
189
  `):void 0}};function Bae(e){let t=globalThis.console,o=new h2;globalThis.console=o;try{e();}finally{let n=o.flushed();n&&process.stdout.write(`${n}
190
190
  `),globalThis.console=t;}}var $5e=" ",G5e=" ",V5e=" ",W5e=" > ",jae=3;function zae(e){if(!e.failureDetails)return;let t=e.filePath?QM(e.filePath):void 0;if(t&&t.doc.get("fileType")!==ze.TEST_V2)return;let o=t?q5e({root:t,result:e}):void 0,n=e.failureDetails.classification?.previousStepsDescription??[];if(n.length===0&&!o)return;let r=[`${$5e}Failed at:`];for(let i of n)r.push(`${G5e}- ${i}`);if(o){let i=Y5e(o);i&&(r.push(""),r.push(i));}return r.join(`
191
191
  `)}function QM(e){let t;try{t=readFileSync(e,"utf-8");}catch{return}let o=new LineCounter,n=tl.parseDocument(t,{lineCounter:o});if(!(n.errors.length>0))return {filePath:e,text:t,doc:n,lineCounter:o}}function q5e({root:e,result:t}){let o=[["before",t.beforeResults],["steps",t.results],["after",t.afterResults]];for(let[n,r]of o){if(!r)continue;let i=g2({source:e,yamlPath:[n],results:r});if(i)return i}}function g2({source:e,yamlPath:t,results:o}){let n=o.findIndex(l=>l.status==="FAILED"),r=o[n];if(!r)return;let i=[...t,n],a=e.doc.getIn(i,true);if(!tl.isNode(a))return;let s={source:e,node:a};if(r.type==="MODULE"){let l=K5e({source:e,stepPath:i});return l?g2({source:l,yamlPath:["steps"],results:r.results})??s:s}if(r.type==="CONDITIONAL"){let l=e.doc.getIn([...i,"if","then"],true);return !tl.isNode(l)||!tl.isSeq(l)?s:g2({source:e,yamlPath:[...i,"if","then"],results:r.results})??s}return s}function K5e({source:e,stepPath:t}){let o=e.doc.getIn([...t,"module"]),n=typeof o=="string"?o:e.doc.getIn([...t,"module","path"]);if(typeof n!="string")return;let r=Cn__default.resolve(Cn__default.dirname(e.filePath),n),i=QM(r);if(i?.doc.get("fileType")===ze.MODULE_V2)return i}function Y5e(e){let t=e.node.range;if(t)return f2(e.source,t[0])}function Hae(e,t){let o=typeof t[0]=="number"?["steps",...t]:t;for(let n=o.length;n>=0;n--){let r=n===0?e.doc.contents:e.doc.getIn(o.slice(0,n),true);if(tl.isNode(r)&&r.range){let i=r.range[0],{line:a,col:s}=e.lineCounter.linePos(i);return {line:a,col:s,startOffset:i}}}}function f2(e,t){let o=e.lineCounter.linePos(t).line,n=e.text.split(`
192
192
  `);if(o<1||o>n.length)return;let r=Math.max(1,o-jae),i=Math.min(n.length,o+jae),a=String(i).length,s=[];for(let l=r;l<=i;l++){let c=l===o?W5e:V5e;s.push(`${c}${String(l).padStart(a)} | ${n[l-1]??""}`);}return s.join(`
193
193
  `)}function Gae(e,t=""){let o=process.stdout?.columns||process.stderr?.columns||80,n=Math.max(o-t.length,20),r=[];for(let i of e.split(`
194
194
  `)){let a="";for(let s of i.split(" ")){if(!a.length){a=s;continue}let l=`${a} ${s}`;if(l.length<=n){a=l;continue}r.push(t+a),a=s;}r.push(t+a);}return r.join(`
195
- `)}var $ae=new Set;function Vae(e,t,o=t){$ae.has(o)||($ae.add(o),e.warn(t));}var X5e={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}},Q5e={PASSED:"PASS",FAILED:"FAIL",CANCELLED:"CANCEL",RETRYING:"RETRY",RUNNING:"RUNNING",SKIP:"SKIP",RUN:"RUNNING",RETRY:"RETRY"};function cI(e,t,o=0){let n=Q5e[e];if(!n)return;let r=ht(t);if(n==="RUNNING")return {badge:r.spinner(o),isTerminal:false};let{glyph:i,isTerminal:a}=X5e[n];return {badge:r.statusGlyph(i),isTerminal:a}}function Br(e,t){return !t.isTTY||t.colorLevel===0?e:`\x1B]8;;${e}\x07${e}\x1B]8;;\x07`}function Wae({parallel:e,remoteBrowser:t}){let o=cpus$1().length;if(t){if(e<=o*4)return;let n=Math.max(1,o*4-2);x.warn(`Running ${e} workers on a ${o}-core machine with a remote browser. We recommend at most ~${n} workers ((cores \xD7 4) \u2212 2) to avoid local saturation.`);return}o>=e*2||x.warn(`Running ${e} workers on a ${o}-core machine. Chrome needs ~2 cores per worker; expect slowdowns.`);}function qae(){let e=gae(),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&&(x.log(""),x.warn(`Machine was under pressure during this run (${t.join(", ")}). Slowdowns and timeouts may be related.`));}var Re=Iv({app:"cli",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:"3.62.2"});var eJe=5,Ov=" ";async function ZM({getResults:e,checkDone:t,name:o,timeoutMs:n=18e5}){let r=Date.now(),i=0;for(;Date.now()-r<n;){let a;i>eJe&&(x.error(`Failed to fetch ${o} status too many times.`),process.exit(1));try{a=await e(),i=0;}catch(c){i++,Re.warn({err:c},"Failed to fetch run status; retrying."),x.warn({err:c},"Failed to fetch run status; retrying."),await new Promise(u=>setTimeout(u,1500*i));continue}if(t(a))return a;let l=Math.max(1e4,Math.floor(n/100));await new Promise(c=>setTimeout(c,l));}x.error(`Timeout elapsed waiting for ${o} to complete (${Math.floor(n/1e3)}s).`),process.exit(1);}function Kae(e){let t={passed:[],failed:[],cancelled:[],quarantinedPassed:[],quarantinedFailed:[]};for(let o of e)switch(o.status){case "PASSED":(o.quarantined?t.quarantinedPassed:t.passed).push(o);break;case "FAILED":(o.quarantined?t.quarantinedFailed:t.failed).push(o);break;case "CANCELLED":t.cancelled.push(o);break}return t}function b2(e){let t=Kae(e),o=t.failed.filter(r=>r.failureDetails?.classification?.action==="heal"),n=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:o.length,warnElectedFailures:n.length}}function Pv(e,{onlyQuarantined:t=false,overrideExitCode:o=false}={}){let n=o?e.healElectedFailures+e.warnElectedFailures:0,r=e.failed-n,i=t?e.quarantinedFailed:0;return r+i>0||e.cancelled>0}function S2({results:e,startTime:t,getPath:o,getUrl:n,printFailureBody:r,getCancellationReason:i,recoveredCount:a,skippedCount:s,videoRecordingActive:l}){let{passed:c,failed:u,cancelled:d,quarantinedPassed:m,quarantinedFailed:p}=Kae(e),h=rt(),g=ht(h),f=(y,b,S,A)=>{x.log(""),x.log(S(` ${b+1}) ${o(y)}`)),x.log(""),A();let T=n(y);T&&(x.log(""),x.log(`${Ov}${Br(T,h)}`));};Bae(()=>{u.forEach((C,O)=>{f(C,O,g.red,()=>r?.(C));}),d.forEach((C,O)=>{f(C,u.length+O,g.yellow,()=>{let P=i?.(C)??"Cancelled";x.log(`${Ov}${g.yellow(P)}`);});});let y=c.length+m.length,b=Math.max(1,Math.round((Date.now()-t)/1e3)),S=[];m.length>0&&S.push(`${m.length} quarantined`),a&&a>0&&S.push(`${a} recovered`);let A=S.length>0?` (${S.join(", ")})`:"",T=tJe(e,h,l),v=[];u.length>0&&v.push(g.bold(g.red(`${u.length} failed`))),p.length>0&&v.push(g.bold(g.red(`${p.length} failed (quarantined)`))),d.length>0&&v.push(g.bold(g.yellow(`${d.length} cancelled`))),s&&v.push(g.yellow(`${s} skipped`)),v.push(g.bold(g.green(`${y} passed${A}`)));let R=e.length+(s??0),I=(C,O)=>` ${g.dim(C.padEnd(8))} ${O}`;x.log(""),x.log(I("Tests",`${v.join(g.dim(" | "))} ${g.dim(`(${R})`)}`)),x.log(I("Duration",`${b}s${g.dim(T)}`)),u.length+p.length>0&&(x.log(""),x.log(` ${g.dim("Run")} ${g.code("momentic ai triage")} ${g.dim(`to attempt automatic fixes${g.separator}${Br("https://momentic.ai/docs/reliability/auto-heal",h)}`)}`)),qae();});}function eL(e){return S2(e),b2(e.results)}function tJe(e,t,o=false){let n=e.length;if(n===0)return "";let r=e.filter(s=>s.usedRemoteBrowser).length;return r===0?"":`${t.unicode?" \xB7 ":" | "}${r}/${n} ran on remote browser${o?" (video saved async)":""}`}function tL(e){if(!e.failureDetails||!e.failureReason)return;let t=Vd({failureReason:e.failureReason,classification:e.failureDetails.classification,manualClassification:e.failureDetails.manualClassification}),o=t.title??e.failureReason,n=e.failureDetails.classification?.rootCause??t.description??t.title??e.failureReason,r=rt(),i=ht(r);x.log(`${Ov}${i.bold(i.red(o))}`),n&&n!==o&&(x.log(""),x.log(i.dim(Gae(n,Ov))));let a=zae({failureDetails:e.failureDetails,filePath:e.filePath,results:e.results,beforeResults:e.beforeResults,afterResults:e.afterResults});a&&(x.log(""),x.log(a));let s=e.failureDetails.classification?.citations;if(s&&s.length>0){x.log(""),x.log(`${Ov}${i.dim("Sources")}`);for(let l of s)x.log(`${Ov} ${i.dim(`[${l.refId}]`)} ${l.title}`);}}var kv=" ".repeat(6);var oJe=(e,t,o,n)=>{if(o==="length"||o==="prototype"||o==="arguments"||o==="caller")return;let r=Object.getOwnPropertyDescriptor(e,o),i=Object.getOwnPropertyDescriptor(t,o);!nJe(r,i)&&n||Object.defineProperty(e,o,i);},nJe=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)},rJe=(e,t)=>{let o=Object.getPrototypeOf(t);o!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,o);},iJe=(e,t)=>`/* Wrapped ${e}*/
195
+ `)}var $ae=new Set;function Vae(e,t,o=t){$ae.has(o)||($ae.add(o),e.warn(t));}var X5e={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}},Q5e={PASSED:"PASS",FAILED:"FAIL",CANCELLED:"CANCEL",RETRYING:"RETRY",RUNNING:"RUNNING",SKIP:"SKIP",RUN:"RUNNING",RETRY:"RETRY"};function cI(e,t,o=0){let n=Q5e[e];if(!n)return;let r=ht(t);if(n==="RUNNING")return {badge:r.spinner(o),isTerminal:false};let{glyph:i,isTerminal:a}=X5e[n];return {badge:r.statusGlyph(i),isTerminal:a}}function Br(e,t){return !t.isTTY||t.colorLevel===0?e:`\x1B]8;;${e}\x07${e}\x1B]8;;\x07`}function Wae({parallel:e,remoteBrowser:t}){let o=cpus$1().length;if(t){if(e<=o*4)return;let n=Math.max(1,o*4-2);x.warn(`Running ${e} workers on a ${o}-core machine with a remote browser. We recommend at most ~${n} workers ((cores \xD7 4) \u2212 2) to avoid local saturation.`);return}o>=e*2||x.warn(`Running ${e} workers on a ${o}-core machine. Chrome needs ~2 cores per worker; expect slowdowns.`);}function qae(){let e=gae(),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&&(x.log(""),x.warn(`Machine was under pressure during this run (${t.join(", ")}). Slowdowns and timeouts may be related.`));}var Re=Iv({app:"cli",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:"3.62.3"});var eJe=5,Ov=" ";async function ZM({getResults:e,checkDone:t,name:o,timeoutMs:n=18e5}){let r=Date.now(),i=0;for(;Date.now()-r<n;){let a;i>eJe&&(x.error(`Failed to fetch ${o} status too many times.`),process.exit(1));try{a=await e(),i=0;}catch(c){i++,Re.warn({err:c},"Failed to fetch run status; retrying."),x.warn({err:c},"Failed to fetch run status; retrying."),await new Promise(u=>setTimeout(u,1500*i));continue}if(t(a))return a;let l=Math.max(1e4,Math.floor(n/100));await new Promise(c=>setTimeout(c,l));}x.error(`Timeout elapsed waiting for ${o} to complete (${Math.floor(n/1e3)}s).`),process.exit(1);}function Kae(e){let t={passed:[],failed:[],cancelled:[],quarantinedPassed:[],quarantinedFailed:[]};for(let o of e)switch(o.status){case "PASSED":(o.quarantined?t.quarantinedPassed:t.passed).push(o);break;case "FAILED":(o.quarantined?t.quarantinedFailed:t.failed).push(o);break;case "CANCELLED":t.cancelled.push(o);break}return t}function b2(e){let t=Kae(e),o=t.failed.filter(r=>r.failureDetails?.classification?.action==="heal"),n=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:o.length,warnElectedFailures:n.length}}function Pv(e,{onlyQuarantined:t=false,overrideExitCode:o=false}={}){let n=o?e.healElectedFailures+e.warnElectedFailures:0,r=e.failed-n,i=t?e.quarantinedFailed:0;return r+i>0||e.cancelled>0}function S2({results:e,startTime:t,getPath:o,getUrl:n,printFailureBody:r,getCancellationReason:i,recoveredCount:a,skippedCount:s,videoRecordingActive:l}){let{passed:c,failed:u,cancelled:d,quarantinedPassed:m,quarantinedFailed:p}=Kae(e),h=rt(),g=ht(h),f=(y,b,S,A)=>{x.log(""),x.log(S(` ${b+1}) ${o(y)}`)),x.log(""),A();let T=n(y);T&&(x.log(""),x.log(`${Ov}${Br(T,h)}`));};Bae(()=>{u.forEach((C,O)=>{f(C,O,g.red,()=>r?.(C));}),d.forEach((C,O)=>{f(C,u.length+O,g.yellow,()=>{let P=i?.(C)??"Cancelled";x.log(`${Ov}${g.yellow(P)}`);});});let y=c.length+m.length,b=Math.max(1,Math.round((Date.now()-t)/1e3)),S=[];m.length>0&&S.push(`${m.length} quarantined`),a&&a>0&&S.push(`${a} recovered`);let A=S.length>0?` (${S.join(", ")})`:"",T=tJe(e,h,l),v=[];u.length>0&&v.push(g.bold(g.red(`${u.length} failed`))),p.length>0&&v.push(g.bold(g.red(`${p.length} failed (quarantined)`))),d.length>0&&v.push(g.bold(g.yellow(`${d.length} cancelled`))),s&&v.push(g.yellow(`${s} skipped`)),v.push(g.bold(g.green(`${y} passed${A}`)));let R=e.length+(s??0),I=(C,O)=>` ${g.dim(C.padEnd(8))} ${O}`;x.log(""),x.log(I("Tests",`${v.join(g.dim(" | "))} ${g.dim(`(${R})`)}`)),x.log(I("Duration",`${b}s${g.dim(T)}`)),u.length+p.length>0&&(x.log(""),x.log(` ${g.dim("Run")} ${g.code("momentic ai triage")} ${g.dim(`to attempt automatic fixes${g.separator}${Br("https://momentic.ai/docs/reliability/auto-heal",h)}`)}`)),qae();});}function eL(e){return S2(e),b2(e.results)}function tJe(e,t,o=false){let n=e.length;if(n===0)return "";let r=e.filter(s=>s.usedRemoteBrowser).length;return r===0?"":`${t.unicode?" \xB7 ":" | "}${r}/${n} ran on remote browser${o?" (video saved async)":""}`}function tL(e){if(!e.failureDetails||!e.failureReason)return;let t=Vd({failureReason:e.failureReason,classification:e.failureDetails.classification,manualClassification:e.failureDetails.manualClassification}),o=t.title??e.failureReason,n=e.failureDetails.classification?.rootCause??t.description??t.title??e.failureReason,r=rt(),i=ht(r);x.log(`${Ov}${i.bold(i.red(o))}`),n&&n!==o&&(x.log(""),x.log(i.dim(Gae(n,Ov))));let a=zae({failureDetails:e.failureDetails,filePath:e.filePath,results:e.results,beforeResults:e.beforeResults,afterResults:e.afterResults});a&&(x.log(""),x.log(a));let s=e.failureDetails.classification?.citations;if(s&&s.length>0){x.log(""),x.log(`${Ov}${i.dim("Sources")}`);for(let l of s)x.log(`${Ov} ${i.dim(`[${l.refId}]`)} ${l.title}`);}}var kv=" ".repeat(6);var oJe=(e,t,o,n)=>{if(o==="length"||o==="prototype"||o==="arguments"||o==="caller")return;let r=Object.getOwnPropertyDescriptor(e,o),i=Object.getOwnPropertyDescriptor(t,o);!nJe(r,i)&&n||Object.defineProperty(e,o,i);},nJe=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)},rJe=(e,t)=>{let o=Object.getPrototypeOf(t);o!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,o);},iJe=(e,t)=>`/* Wrapped ${e}*/
196
196
  ${t}`,aJe=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),sJe=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),lJe=(e,t,o)=>{let n=o===""?"":`with ${o.trim()}() `,r=iJe.bind(null,n,t.toString());Object.defineProperty(r,"name",sJe);let{writable:i,enumerable:a,configurable:s}=aJe;Object.defineProperty(e,"toString",{value:r,writable:i,enumerable:a,configurable:s});};function T2(e,t,{ignoreNonConfigurable:o=false}={}){let{name:n}=e;for(let r of Reflect.ownKeys(t))oJe(e,t,r,o);return rJe(e,t),lJe(e,t,n),e}var oL=new WeakMap,Yae=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let o,n=0,r=e.displayName||e.name||"<anonymous>",i=function(...a){if(oL.set(i,++n),n===1)o=e.apply(this,a),e=void 0;else if(t.throw===true)throw new Error(`Function \`${r}\` can only be called once`);return o};return T2(i,e),oL.set(i,n),i};Yae.callCount=e=>{if(!oL.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return oL.get(e)};var Jae=Yae;var vb=[];vb.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&vb.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&vb.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var nL=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",v2=Symbol.for("signal-exit emitter"),A2=globalThis,cJe=Object.defineProperty.bind(Object),E2=class{emitted={afterExit:false,exit:false};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(A2[v2])return A2[v2];cJe(A2,v2,{value:this,writable:false,enumerable:false,configurable:false});}on(t,o){this.listeners[t].push(o);}removeListener(t,o){let n=this.listeners[t],r=n.indexOf(o);r!==-1&&(r===0&&n.length===1?n.length=0:n.splice(r,1));}emit(t,o,n){if(this.emitted[t])return false;this.emitted[t]=true;let r=false;for(let i of this.listeners[t])r=i(o,n)===true||r;return t==="exit"&&(r=this.emit("afterExit",o,n)||r),r}},rL=class{},uJe=e=>({onExit(t,o){return e.onExit(t,o)},load(){return e.load()},unload(){return e.unload()}}),w2=class extends rL{onExit(){return ()=>{}}load(){}unload(){}},R2=class extends rL{#n=C2.platform==="win32"?"SIGINT":"SIGHUP";#t=new E2;#e;#i;#m;#o={};#a=false;constructor(t){super(),this.#e=t,this.#o={};for(let o of vb)this.#o[o]=()=>{let n=this.#e.listeners(o),{count:r}=this.#t,i=t;if(typeof i.__signal_exit_emitter__=="object"&&typeof i.__signal_exit_emitter__.count=="number"&&(r+=i.__signal_exit_emitter__.count),n.length===r){this.unload();let a=this.#t.emit("exit",null,o),s=o==="SIGHUP"?this.#n:o;a||t.kill(t.pid,s);}};this.#m=t.reallyExit,this.#i=t.emit;}onExit(t,o){if(!nL(this.#e))return ()=>{};this.#a===false&&this.load();let n=o?.alwaysLast?"afterExit":"exit";return this.#t.on(n,t),()=>{this.#t.removeListener(n,t),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload();}}load(){if(!this.#a){this.#a=true,this.#t.count+=1;for(let t of vb)try{let o=this.#o[t];o&&this.#e.on(t,o);}catch{}this.#e.emit=(t,...o)=>this.#p(t,...o),this.#e.reallyExit=t=>this.#r(t);}}unload(){this.#a&&(this.#a=false,vb.forEach(t=>{let o=this.#o[t];if(!o)throw new Error("Listener not defined for signal: "+t);try{this.#e.removeListener(t,o);}catch{}}),this.#e.emit=this.#i,this.#e.reallyExit=this.#m,this.#t.count-=1);}#r(t){return nL(this.#e)?(this.#e.exitCode=t||0,this.#t.emit("exit",this.#e.exitCode,null),this.#m.call(this.#e,this.#e.exitCode)):0}#p(t,...o){let n=this.#i;if(t==="exit"&&nL(this.#e)){typeof o[0]=="number"&&(this.#e.exitCode=o[0]);let r=n.call(this.#e,t,...o);return this.#t.emit("exit",this.#e.exitCode,null),r}else return n.call(this.#e,t,...o)}},C2=globalThis.process,{onExit:Xae}=uJe(nL(C2)?new R2(C2):new w2);var Qae=ad.stderr.isTTY?ad.stderr:ad.stdout.isTTY?ad.stdout:void 0,dJe=Qae?Jae(()=>{Xae(()=>{Qae.write("\x1B[?25h");},{alwaysLast:true});}):()=>{},Zae=dJe;var aL=false,Mv={};Mv.show=(e=ad.stderr)=>{e.isTTY&&(aL=false,e.write("\x1B[?25h"));};Mv.hide=(e=ad.stderr)=>{e.isTTY&&(Zae(),aL=true,e.write("\x1B[?25l"));};Mv.toggle=(e,t)=>{e!==void 0&&(aL=e),aL?Mv.show(t):Mv.hide(t);};var I2=Mv;var dI=CH(x2());function _2(){return ad.platform!=="win32"?ad.env.TERM!=="linux":!!ad.env.CI||!!ad.env.WT_SESSION||!!ad.env.TERMINUS_SUBLIME||ad.env.ConEmuTask==="{cmd::Cmder}"||ad.env.TERM_PROGRAM==="Terminus-Sublime"||ad.env.TERM_PROGRAM==="vscode"||ad.env.TERM==="xterm-256color"||ad.env.TERM==="alacritty"||ad.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var pJe={info:Yc.blue("\u2139"),success:Yc.green("\u2714"),warning:Yc.yellow("\u26A0"),error:Yc.red("\u2716")},hJe={info:Yc.blue("i"),success:Yc.green("\u221A"),warning:Yc.yellow("\u203C"),error:Yc.red("\xD7")},gJe=_2()?pJe:hJe,uI=gJe;function O2({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 fJe=O2();function P2(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return !e.includes("\x1B")&&!e.includes("\x9B")?e:e.replace(fJe,"")}function k2({stream:e=process.stdout}={}){return !!(e&&e.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}function M2(){let{env:e}=ad,{TERM:t,TERM_PROGRAM:o}=e;return ad.platform!=="win32"?t!=="linux":!!e.WT_SESSION||!!e.TERMINUS_SUBLIME||e.ConEmuTask==="{cmd::Cmder}"||o==="Terminus-Sublime"||o==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var yJe=3,L2=class{#n=0;start(){this.#n++,this.#n===1&&this.#t();}stop(){if(this.#n<=0)throw new Error("`stop` called more times than `start`");this.#n--,this.#n===0&&this.#e();}#t(){ad.platform==="win32"||!ad.stdin.isTTY||(ad.stdin.setRawMode(true),ad.stdin.on("data",this.#i),ad.stdin.resume());}#e(){ad.stdin.isTTY&&(ad.stdin.off("data",this.#i),ad.stdin.pause(),ad.stdin.setRawMode(false));}#i(t){t[0]===yJe&&ad.emit("SIGINT");}},bJe=new L2,N2=bJe;CH(x2());var D2=class{#n=0;#t=false;#e=0;#i=-1;#m=0;#o;#a;#r;#p;#g;#c;#u;#d;#f;#s;#l;color;constructor(t){typeof t=="string"&&(t={text:t}),this.#o={color:"cyan",stream:ad.stderr,discardStdin:true,hideCursor:true,...t},this.color=this.#o.color,this.spinner=this.#o.spinner,this.#g=this.#o.interval,this.#r=this.#o.stream,this.#c=typeof this.#o.isEnabled=="boolean"?this.#o.isEnabled:k2({stream:this.#r}),this.#u=typeof this.#o.isSilent=="boolean"?this.#o.isSilent:false,this.text=this.#o.text,this.prefixText=this.#o.prefixText,this.suffixText=this.#o.suffixText,this.indent=this.#o.indent,ad.env.NODE_ENV==="test"&&(this._stream=this.#r,this._isEnabled=this.#c,Object.defineProperty(this,"_linesToClear",{get(){return this.#n},set(o){this.#n=o;}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#i}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}));}get indent(){return this.#d}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.#d=t,this.#h();}get interval(){return this.#g??this.#a.interval??100}get spinner(){return this.#a}set spinner(t){if(this.#i=-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.#a=t;}else if(!M2())this.#a=dI.default.line;else if(t===void 0)this.#a=dI.default.dots;else if(t!=="default"&&dI.default[t])this.#a=dI.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.#s}set prefixText(t=""){this.#s=t,this.#h();}get suffixText(){return this.#l}set suffixText(t=""){this.#l=t,this.#h();}get isSpinning(){return this.#p!==void 0}#y(t=this.#s,o=" "){return typeof t=="string"&&t!==""?t+o:typeof t=="function"?t()+o:""}#b(t=this.#l,o=" "){return typeof t=="string"&&t!==""?o+t:typeof t=="function"?o+t():""}#h(){let t=this.#r.columns??80,o=this.#y(this.#s,"-"),n=this.#b(this.#l,"-"),r=" ".repeat(this.#d)+o+"--"+this.#f+"--"+n;this.#e=0;for(let i of P2(r).split(`
197
197
  `))this.#e+=Math.max(1,Math.ceil(NSe(i,{countAnsiEscapeCodes:true})/t));}get isEnabled(){return this.#c&&!this.#u}set isEnabled(t){if(typeof t!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#c=t;}get isSilent(){return this.#u}set isSilent(t){if(typeof t!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#u=t;}frame(){let t=Date.now();(this.#i===-1||t-this.#m>=this.interval)&&(this.#i=++this.#i%this.#a.frames.length,this.#m=t);let{frames:o}=this.#a,n=o[this.#i];this.color&&(n=Yc[this.color](n));let r=typeof this.#s=="string"&&this.#s!==""?this.#s+" ":"",i=typeof this.text=="string"?" "+this.text:"",a=typeof this.#l=="string"&&this.#l!==""?" "+this.#l:"";return r+n+i+a}clear(){if(!this.#c||!this.#r.isTTY)return this;this.#r.cursorTo(0);for(let t=0;t<this.#n;t++)t>0&&this.#r.moveCursor(0,-1),this.#r.clearLine(1);return (this.#d||this.lastIndent!==this.#d)&&this.#r.cursorTo(this.#d),this.lastIndent=this.#d,this.#n=0,this}render(){return this.#u?this:(this.clear(),this.#r.write(this.frame()),this.#n=this.#e,this)}start(t){return t&&(this.text=t),this.#u?this:this.#c?this.isSpinning?this:(this.#o.hideCursor&&I2.hide(this.#r),this.#o.discardStdin&&ad.stdin.isTTY&&(this.#t=true,N2.start()),this.render(),this.#p=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#r.write(`- ${this.text}
198
198
  `),this)}stop(){return this.#c?(clearInterval(this.#p),this.#p=void 0,this.#i=0,this.clear(),this.#o.hideCursor&&I2.show(this.#r),this.#o.discardStdin&&ad.stdin.isTTY&&this.#t&&(N2.stop(),this.#t=false),this):this}succeed(t){return this.stopAndPersist({symbol:uI.success,text:t})}fail(t){return this.stopAndPersist({symbol:uI.error,text:t})}warn(t){return this.stopAndPersist({symbol:uI.warning,text:t})}info(t){return this.stopAndPersist({symbol:uI.info,text:t})}stopAndPersist(t={}){if(this.#u)return this;let o=t.prefixText??this.#s,n=this.#y(o," "),r=t.symbol??" ",i=t.text??this.text,s=typeof i=="string"?(r?" ":"")+i:"",l=t.suffixText??this.#l,c=this.#b(l," "),u=n+r+s+c+`
@@ -271,7 +271,7 @@ ${z.prettifyError(s)}`:`: ${W(s)}`;x.warn(`Project config at ${e} does not match
271
271
  ${r.map(i=>i.configFilePath).join(`
272
272
  `)}`);if(r.length===0)throw new ae(`No valid Momentic project file (${Dl}) 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 ${Dl}.`);return x.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}async function i9e(e){let t=n9e(e);if(!t||!t.projects||!t.projects.length)return;let o=t.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${Dl}`)),n=AbortSignal.timeout(2e3),r;try{r=await Om(o,{cwd:cwd(),maxDepth:mA,ignore:[],nodir:!0,signal:n});}catch(a){throw x.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${HI} is misconfigured.`),a}let i=[];for(let a of r){let s=Cn__default.join(cwd(),a),l=qV(s);l&&i.push({configFilePath:s,config:l,rootDir:dirname(s)});}return i}async function KV(e,t){if(e){e=Cn__default.resolve(e);let n=qV(e);if(!n){if(!t)throw new ae(`No valid Momentic project file found at ${e}.`);return console.error(`No valid Momentic project file found at ${e}.`),[]}return [{config:n,configFilePath:e,rootDir:Cn__default.dirname(e)}]}if(existsSync(HI)){let n=await i9e(HI);if(n)return n}return r9e()}function jb(e,t){let o=tl.stringify(e);writeFileSync(t,o);}var a9e={name:" Project name. Appears in reports and in the Momentic app.",include:' Globs that select test and module files, relative to this file. Add exclude: ["out/**"] to skip files.',retries:" How many times Momentic reruns a failed test. Example: retries: 2",parallel:' How many tests run at once. "auto" picks a count from your CPU cores, and a higher one on hosted browsers. Example: parallel: 4',recordVideo:" Record video of each test: true, false, or on-fail (keep video for failed tests only).",gitMainBranch:" Main branch of the repo. New branches seed their step cache from the nearest commit on it. See https://momentic.ai/docs/reliability/step-cache",fileFormat:" Test file format version.",advanced:" Advanced options. See https://momentic.ai/docs/configuration/advanced",browser:" Browser settings for every test. See https://momentic.ai/docs/configuration/browser",ai:" AI agent settings. See https://momentic.ai/docs/configuration/ai",environments:" One entry per environment. Read envVariables in tests as {{env.NAME}}. See https://momentic.ai/docs/configuration/environment-variables"},s9e=[" Store a separate step cache per environment. See https://momentic.ai/docs/reliability/step-cache"," isolateCachesByEnvironment: true"].join(`
273
273
  `),l9e=[" Run tests on Momentic hosted browsers instead of local Chromium."," Use this in CI to run tests in parallel without adding machines. See https://momentic.ai/docs/running-tests/hosted-test-environments"," remoteBrowser: true"," Skip some browser readiness and stability waits. Faster, less accurate on dynamic sites. See https://momentic.ai/docs/running-tests/performance"," turbo: true"," defaultBrowserType: Chromium"," timezone: America/Los_Angeles"," pageLoadTimeoutMs: 8000"," smartWaitingTimeoutMs: 5000"].join(`
274
- `);function gf(e,t,{commentBefore:o,comment:n}){let r=e.items.find(i=>tl.isPair(i)&&tl.isScalar(i.key)&&i.key.value===t);if(r&&(o!==void 0&&tl.isScalar(r.key)&&(r.key.commentBefore=o),n!==void 0)){let i=r.value;(tl.isMap(i)||tl.isSeq(i)||tl.isScalar(i))&&(i.comment=n);}}function fde(e){let t=new tl.Document(e);if(!tl.isMap(t.contents))return t.toString();let o=true;for(let a of t.contents.items){if(!tl.isPair(a)||!tl.isScalar(a.key))continue;let s=a.key.value,l=Object.entries(a9e).find(([c])=>c===s)?.[1];l!==void 0&&(a.key.commentBefore=l),a.key.spaceBefore=!o,o=false;}gf(t.contents,"advanced",{comment:s9e}),gf(t.contents,"browser",{comment:l9e});let n=t.get("advanced");tl.isMap(n)&&gf(n,"aiActionShorthand",{commentBefore:" Save short AI action goals as bare strings. See https://momentic.ai/docs/configuration/advanced#advanced-aiactionshorthand"});let r=t.get("browser");tl.isMap(r)&&(gf(r,"autoExpandIframes",{commentBefore:" Let the AI act on elements inside iframes. See https://momentic.ai/docs/configuration/browser#browser-autoexpandiframes"}),gf(r,"disableSecondaryCacheResolution",{commentBefore:" Skip fuzzy cache matching so a cached step does not resolve to the wrong element. See https://momentic.ai/docs/configuration/browser#browser-disablesecondarycacheresolution"}));let i=t.get("ai");return tl.isMap(i)&&(gf(i,"useMemory",{commentBefore:" Reuse decisions from past runs so the AI picks the same elements and assertions. See https://momentic.ai/docs/ai/memory"}),gf(i,"failureRecovery",{commentBefore:" Let the AI find a path forward when a step fails. See https://momentic.ai/docs/reliability/auto-maintenance#failure-recovery"}),gf(i,"agentConfig",{commentBefore:" Version of each AI agent. See https://momentic.ai/docs/ai/agents"})),t.toString()}var je="v1",YV="cli",zb="3.62.2";var u9e=9e4,d9e=3,m9e=1500,p9e=15e3,h9e=6e4,Lo=class extends Error{code;status;rawError;retryAfterMs;constructor(t,o,n,r={}){super(n,r),this.code=r.code,this.status=t,this.rawError=o,this.retryAfterMs=r.retryAfterMs;}},yA=class extends ae{constructor(t,o={}){super(t,o),this.name="RateLimitExceededError";}},JV=class extends ae{constructor(t,o={}){super(t,o),this.name="PlanLimitExceededError";}},$I=class extends ae{constructor(t,o={}){super(t,o),this.name="AuthenticationError";}};function g9e(e){if(!e)return;let t=Number(e.trim());if(Number.isFinite(t)&&t>=0)return t*1e3;let o=Date.parse(e);if(!Number.isNaN(o))return Math.max(o-Date.now(),0)}async function f9e(e){let t=await e.text();try{let o=JSON.parse(t);if(typeof o!="object"||o===null)return {rawError:t};let n="code"in o?o.code:void 0,r="error"in o?o.error:void 0;return {...typeof n=="string"?{code:n}:{},rawError:typeof r=="string"?r:t}}catch{return {rawError:t}}}var XV=class{baseUrl;logger;constructor(t){this.baseUrl=t.baseUrl,this.logger=t.logger;}getHeaders(t){let o={"Content-Type":"application/json"};return (o[pM]=zb),(o[Tre]=YV),o}async sendRequest(t,o){let{retries:n=d9e,requestTimeoutMs:r=u9e,initialRetryDelayMs:i=m9e,maxRetryDelayMs:a=p9e,onFailedRequest:s}=o,l=n,c=n,u,d={path:t,baseUrl:this.baseUrl,method:o.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(t,o,r)}catch(m){u=m;try{s?.(u);}catch{}let p=m instanceof Lo&&m.status===429?m:void 0;if(m instanceof Lo&&!p&&m.status>=400&&m.status<500)throw m.status===402?new JV(m.rawError,{cause:m}):m.status===401||m.status===403?new $I(m.rawError,{cause:m}):m;if(m instanceof Lo&&m.status===fM)throw m;if(m instanceof Error&&m.name==="AbortError"&&!o.signal?.aborted&&(u=new Ua),p&&(l===0||o.signal?.aborted))throw new yA(`The Momentic API rate limited ${o.method} ${t} after ${c} ${c===1?"attempt":"attempts"}: ${p.rawError} Run fewer tests at once, or try again in a minute.`,{cause:p});if(l===0||o.signal?.aborted)throw u;let h=c-l,g=Math.min(i*Math.pow(2,h-1),a);if(p&&(g=Math.min(Math.max(g,p.retryAfterMs??0),h9e)),await wb(g,o.signal),o.signal?.aborted)throw u}throw u?(this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u):new Error(`Refusing to send ${o.method} ${t}: retries was ${c}, so no request was attempted.`)}async sendSingleRequestHelper(t,o,n){let r={path:t,baseUrl:this.baseUrl,method:o.method};o.signal?.throwIfAborted();let i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();o.signal&&o.signal.addEventListener("abort",s,{once:true});let l=Date.now(),c=o.body?JSON.stringify(o.body):void 0,u={...this.getHeaders({serializedBody:c,method:o.method,path:t}),...o.extraHeaders};try{let d=await fetch(`${this.baseUrl}${t}`,{method:o.method,body:c,headers:u,signal:i.signal}),m=o.responseHeadersObject;if(m&&d.headers.forEach((h,g)=>{m[g.toLowerCase()]=h;}),!d.ok){let{code:h,rawError:g}=await f9e(d);throw new Lo(d.status,g,`Request to ${o.method} ${t} failed with status ${d.status}: ${g}`,{code:h,retryAfterMs:g9e(d.headers.get("retry-after"))})}let p;if(d.status===204)p={};else if(o.responseType==="buffer"){let h=await d.arrayBuffer();p=Buffer.from(h);}else {let h=await d.text();try{p=JSON.parse(h);}catch{p=h;}}return this.logger&&o.logResponse===!0&&p&&this.logger.debug({result:p,status:d.status,durationMs:Date.now()-l,...r},"Got response from Momentic server"),p}finally{clearTimeout(a),o.signal&&o.signal.removeEventListener("abort",s);}}};function y9e(e){try{validateHeaderValue("Authorization",e);}catch(t){throw new ae("Your Momentic API key contains a character that cannot be sent over HTTP. Copy the full key from https://app.momentic.ai/settings/api-keys and set MOMENTIC_API_KEY again.",{cause:t})}}var ol=class extends XV{apiKey;mode;runner;constructor(t){super(t),y9e(t.apiKey),this.apiKey=t.apiKey,this.mode=t.mode,this.runner=t.runner,x.addRedactedValue(t.apiKey);}getHeaders(t){return {...super.getHeaders(t),Authorization:`Bearer ${this.apiKey}`,[Sre]:this.mode,[hM]:this.runner}}};var xN=class extends Error{constructor(t,o){super(t),this.name="ParseError",this.type=o.type,this.field=o.field,this.value=o.value,this.line=o.line;}};function QV(e){}function yde(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=QV,onError:o=QV,onRetry:n=QV,onComment:r}=e,i="",a=true,s,l="",c="";function u(g){let f=a?g.replace(/^\xEF\xBB\xBF/,""):g,[y,b]=b9e(`${i}${f}`);for(let S of y)d(S);i=b,a=false;}function d(g){if(g===""){p();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),b=g[f+1]===" "?2:1,S=g.slice(f+b);m(y,S,g);return}m(g,"",g);}function m(g,f,y){switch(g){case "event":c=f;break;case "data":l=`${l}${f}
274
+ `);function gf(e,t,{commentBefore:o,comment:n}){let r=e.items.find(i=>tl.isPair(i)&&tl.isScalar(i.key)&&i.key.value===t);if(r&&(o!==void 0&&tl.isScalar(r.key)&&(r.key.commentBefore=o),n!==void 0)){let i=r.value;(tl.isMap(i)||tl.isSeq(i)||tl.isScalar(i))&&(i.comment=n);}}function fde(e){let t=new tl.Document(e);if(!tl.isMap(t.contents))return t.toString();let o=true;for(let a of t.contents.items){if(!tl.isPair(a)||!tl.isScalar(a.key))continue;let s=a.key.value,l=Object.entries(a9e).find(([c])=>c===s)?.[1];l!==void 0&&(a.key.commentBefore=l),a.key.spaceBefore=!o,o=false;}gf(t.contents,"advanced",{comment:s9e}),gf(t.contents,"browser",{comment:l9e});let n=t.get("advanced");tl.isMap(n)&&gf(n,"aiActionShorthand",{commentBefore:" Save short AI action goals as bare strings. See https://momentic.ai/docs/configuration/advanced#advanced-aiactionshorthand"});let r=t.get("browser");tl.isMap(r)&&(gf(r,"autoExpandIframes",{commentBefore:" Let the AI act on elements inside iframes. See https://momentic.ai/docs/configuration/browser#browser-autoexpandiframes"}),gf(r,"disableSecondaryCacheResolution",{commentBefore:" Skip fuzzy cache matching so a cached step does not resolve to the wrong element. See https://momentic.ai/docs/configuration/browser#browser-disablesecondarycacheresolution"}));let i=t.get("ai");return tl.isMap(i)&&(gf(i,"useMemory",{commentBefore:" Reuse decisions from past runs so the AI picks the same elements and assertions. See https://momentic.ai/docs/ai/memory"}),gf(i,"failureRecovery",{commentBefore:" Let the AI find a path forward when a step fails. See https://momentic.ai/docs/reliability/auto-maintenance#failure-recovery"}),gf(i,"agentConfig",{commentBefore:" Version of each AI agent. See https://momentic.ai/docs/ai/agents"})),t.toString()}var je="v1",YV="cli",zb="3.62.3";var u9e=9e4,d9e=3,m9e=1500,p9e=15e3,h9e=6e4,Lo=class extends Error{code;status;rawError;retryAfterMs;constructor(t,o,n,r={}){super(n,r),this.code=r.code,this.status=t,this.rawError=o,this.retryAfterMs=r.retryAfterMs;}},yA=class extends ae{constructor(t,o={}){super(t,o),this.name="RateLimitExceededError";}},JV=class extends ae{constructor(t,o={}){super(t,o),this.name="PlanLimitExceededError";}},$I=class extends ae{constructor(t,o={}){super(t,o),this.name="AuthenticationError";}};function g9e(e){if(!e)return;let t=Number(e.trim());if(Number.isFinite(t)&&t>=0)return t*1e3;let o=Date.parse(e);if(!Number.isNaN(o))return Math.max(o-Date.now(),0)}async function f9e(e){let t=await e.text();try{let o=JSON.parse(t);if(typeof o!="object"||o===null)return {rawError:t};let n="code"in o?o.code:void 0,r="error"in o?o.error:void 0;return {...typeof n=="string"?{code:n}:{},rawError:typeof r=="string"?r:t}}catch{return {rawError:t}}}var XV=class{baseUrl;logger;constructor(t){this.baseUrl=t.baseUrl,this.logger=t.logger;}getHeaders(t){let o={"Content-Type":"application/json"};return (o[pM]=zb),(o[Tre]=YV),o}async sendRequest(t,o){let{retries:n=d9e,requestTimeoutMs:r=u9e,initialRetryDelayMs:i=m9e,maxRetryDelayMs:a=p9e,onFailedRequest:s}=o,l=n,c=n,u,d={path:t,baseUrl:this.baseUrl,method:o.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(t,o,r)}catch(m){u=m;try{s?.(u);}catch{}let p=m instanceof Lo&&m.status===429?m:void 0;if(m instanceof Lo&&!p&&m.status>=400&&m.status<500)throw m.status===402?new JV(m.rawError,{cause:m}):m.status===401||m.status===403?new $I(m.rawError,{cause:m}):m;if(m instanceof Lo&&m.status===fM)throw m;if(m instanceof Error&&m.name==="AbortError"&&!o.signal?.aborted&&(u=new Ua),p&&(l===0||o.signal?.aborted))throw new yA(`The Momentic API rate limited ${o.method} ${t} after ${c} ${c===1?"attempt":"attempts"}: ${p.rawError} Run fewer tests at once, or try again in a minute.`,{cause:p});if(l===0||o.signal?.aborted)throw u;let h=c-l,g=Math.min(i*Math.pow(2,h-1),a);if(p&&(g=Math.min(Math.max(g,p.retryAfterMs??0),h9e)),await wb(g,o.signal),o.signal?.aborted)throw u}throw u?(this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u):new Error(`Refusing to send ${o.method} ${t}: retries was ${c}, so no request was attempted.`)}async sendSingleRequestHelper(t,o,n){let r={path:t,baseUrl:this.baseUrl,method:o.method};o.signal?.throwIfAborted();let i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();o.signal&&o.signal.addEventListener("abort",s,{once:true});let l=Date.now(),c=o.body?JSON.stringify(o.body):void 0,u={...this.getHeaders({serializedBody:c,method:o.method,path:t}),...o.extraHeaders};try{let d=await fetch(`${this.baseUrl}${t}`,{method:o.method,body:c,headers:u,signal:i.signal}),m=o.responseHeadersObject;if(m&&d.headers.forEach((h,g)=>{m[g.toLowerCase()]=h;}),!d.ok){let{code:h,rawError:g}=await f9e(d);throw new Lo(d.status,g,`Request to ${o.method} ${t} failed with status ${d.status}: ${g}`,{code:h,retryAfterMs:g9e(d.headers.get("retry-after"))})}let p;if(d.status===204)p={};else if(o.responseType==="buffer"){let h=await d.arrayBuffer();p=Buffer.from(h);}else {let h=await d.text();try{p=JSON.parse(h);}catch{p=h;}}return this.logger&&o.logResponse===!0&&p&&this.logger.debug({result:p,status:d.status,durationMs:Date.now()-l,...r},"Got response from Momentic server"),p}finally{clearTimeout(a),o.signal&&o.signal.removeEventListener("abort",s);}}};function y9e(e){try{validateHeaderValue("Authorization",e);}catch(t){throw new ae("Your Momentic API key contains a character that cannot be sent over HTTP. Copy the full key from https://app.momentic.ai/settings/api-keys and set MOMENTIC_API_KEY again.",{cause:t})}}var ol=class extends XV{apiKey;mode;runner;constructor(t){super(t),y9e(t.apiKey),this.apiKey=t.apiKey,this.mode=t.mode,this.runner=t.runner,x.addRedactedValue(t.apiKey);}getHeaders(t){return {...super.getHeaders(t),Authorization:`Bearer ${this.apiKey}`,[Sre]:this.mode,[hM]:this.runner}}};var xN=class extends Error{constructor(t,o){super(t),this.name="ParseError",this.type=o.type,this.field=o.field,this.value=o.value,this.line=o.line;}};function QV(e){}function yde(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=QV,onError:o=QV,onRetry:n=QV,onComment:r}=e,i="",a=true,s,l="",c="";function u(g){let f=a?g.replace(/^\xEF\xBB\xBF/,""):g,[y,b]=b9e(`${i}${f}`);for(let S of y)d(S);i=b,a=false;}function d(g){if(g===""){p();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),b=g[f+1]===" "?2:1,S=g.slice(f+b);m(y,S,g);return}m(g,"",g);}function m(g,f,y){switch(g){case "event":c=f;break;case "data":l=`${l}${f}
275
275
  `;break;case "id":s=f.includes("\0")?void 0:f;break;case "retry":/^\d+$/.test(f)?n(parseInt(f,10)):o(new xN(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:y}));break;default:o(new xN(`Unknown field "${g.length>20?`${g.slice(0,20)}\u2026`:g}"`,{type:"unknown-field",field:g,value:f,line:y}));break}}function p(){l.length>0&&t({id:s,event:c||void 0,data:l.endsWith(`
276
276
  `)?l.slice(0,-1):l}),s=void 0,l="",c="";}function h(g={}){i&&g.consume&&d(i),a=true,s=void 0,l="",c="",i="";}return {feed:u,reset:h}}function b9e(e){let t=[],o="",n=0;for(;n<e.length;){let r=e.indexOf("\r",n),i=e.indexOf(`
277
277
  `,n),a=-1;if(r!==-1&&i!==-1?a=Math.min(r,i):r!==-1?a=r:i!==-1&&(a=i),a===-1){o=e.slice(n);break}else {let s=e.slice(n,a);t.push(s),n=a+1,e[n-1]==="\r"&&e[n]===`
@@ -367,7 +367,7 @@ ${s}
367
367
  `,Zct=1e4,eut=6e4,aye=___default.object({stream:___default.boolean().optional(),type:___default.literal("response.create").optional()}).passthrough(),tut=aye.extend({stream:___default.literal(true)});function sye(e={}){let t=new Hq(e),o=e.fetch??fetch;return async(n,r)=>{if(!nut(n,r))return o(n,r);let i=await out(r?.body);if(!i)return o(n,r);let a=tut.safeParse(i);return a.success?t.fetch({httpUrl:lye(n),init:r,request:a.data}):o(n,r)}}var Hq=class{constructor(t){this.options=t;}websocket;openPromise;latestResponseId;previousDurableInput;pendingRequest;observedCompactionItems=new Set;compactionState;async fetch({httpUrl:t,init:o,request:n}){if(this.pendingRequest)return (this.options.fetch??fetch)(t,o);this.observedCompactionItems.clear();let r={"momentic.websocket_has_pending_request":false,"momentic.websocket_ready_state":this.websocket?.readyState??-1};await ge({name:"openai.responses_websocket.fetch.started",attributes:r,fn:async()=>{}});let i=await ge({name:"openai.responses_websocket.open",attributes:r,fn:()=>this.open({httpUrl:t,init:o})}),a=new ReadableStream({start:async s=>{let l={controller:s,fullRequest:n,lastMessageAtMs:Date.now(),maxMessageGapMs:0,messageTimeout:void 0,sentContinuation:false,startedStreaming:false,retryingFullContext:false,compactionItem:void 0};this.pendingRequest=l;let c={"momentic.websocket_ready_state":i.readyState};await ge({name:"openai.responses_websocket.send.started",attributes:c,fn:async()=>{}}),await ge({name:"openai.responses_websocket.send",attributes:c,fn:async()=>this.sendRequest({websocket:i,pendingRequest:l})});},cancel:()=>{this.clearMessageTimeout(this.pendingRequest),this.websocket?.close(),this.websocket=void 0,this.openPromise=void 0,this.latestResponseId=void 0,this.previousDurableInput=void 0,this.pendingRequest=void 0;}});return new Response(a,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache, no-transform"}})}async open({httpUrl:t,init:o}){return this.websocket?.readyState===zq.OPEN?this.websocket:this.openPromise?this.openPromise:(this.openPromise=new Promise((n,r)=>{let i=new zq(rut(t),{headers:{...iye(o?.headers),...iye(this.options.getHeaders?.({httpUrl:t,init:o}))}}),a=setTimeout(()=>{i.terminate(),r(new Error("Timed out opening OpenAI responses websocket"));},Zct);i.once("open",()=>{clearTimeout(a),this.websocket=i,this.openPromise=void 0,n(i);}),i.once("error",s=>{clearTimeout(a),this.resetConnection(),r(s);}),i.on("close",(s,l)=>{let c={"momentic.websocket_close_code":s,"momentic.websocket_close_reason":l.toString(),"momentic.websocket_had_pending_request":!!this.pendingRequest,"momentic.websocket_max_message_gap_ms":this.pendingRequest?.maxMessageGapMs??0};this.resetConnection(),ge({name:"openai.responses_websocket.closed",attributes:c,fn:async()=>{}});}),i.on("message",s=>{this.handleMessage(s);});}),this.openPromise)}sendRequest({websocket:t,pendingRequest:o}){let n=this.buildPayload(o.fullRequest);o.sentContinuation=!!n.previous_response_id,this.sendPayload({websocket:t,pendingRequest:o,payload:n});}sendPayload({websocket:t,pendingRequest:o,payload:n}){o.lastMessageAtMs=Date.now(),this.armMessageTimeout(o);try{t.send(JSON.stringify(n),r=>{r&&this.failPendingRequest({pendingRequest:o,err:r});});}catch(r){this.failPendingRequest({pendingRequest:o,err:Gi(r)});}}buildPayload(t){let{background:o,stream:n,...r}=t,i={...r,type:"response.create"};iut({payload:i,compactThreshold:this.options.compactThreshold});let a=Array.isArray(t.input)?t.input:void 0,s=this.latestResponseId&&a&&this.previousDurableInput?eye({currentInput:a,previousInput:this.previousDurableInput,isTransientInputItem:this.options.isTransientInputItem}):void 0;if(s&&s.length>0&&(this.options.prepareInput?.(s,t)??s)===s)return i.input=s,i.previous_response_id=this.latestResponseId,i;this.options.getCompactionState&&(this.compactionState=this.options.getCompactionState());let c=(this.compactionState&&a?PD({currentInput:a,state:this.compactionState,isTransientInputItem:this.options.isTransientInputItem}):void 0)??a;return c&&(i.input=this.options.prepareInput?.(c,t)??c),delete i.previous_response_id,i}handleMessage(t){let o=this.pendingRequest;if(!o)return;let n=Date.now();o.maxMessageGapMs=Math.max(o.maxMessageGapMs,n-o.lastMessageAtMs),o.lastMessageAtMs=n,this.armMessageTimeout(o);let r=sut(t),i;try{i=JSON.parse(r);}catch(l){this.failPendingRequest({pendingRequest:o,err:Gi(l)});return}let a=gee.safeParse(i),s=a.success?a.data:void 0;if(aut(s)&&o.sentContinuation&&!o.startedStreaming&&!o.retryingFullContext&&this.websocket?.readyState===zq.OPEN){this.latestResponseId=void 0,this.previousDurableInput=void 0,o.retryingFullContext=true,o.sentContinuation=false;let l=this.buildPayload(o.fullRequest);delete l.previous_response_id,this.sendPayload({websocket:this.websocket,pendingRequest:o,payload:l});return}if(o.startedStreaming=true,_D(i)){let l=OD(i);l&&(o.compactionItem=l);let c=Qfe(i),u=c??"compaction-without-id",d=this.options.compactThreshold;d!==void 0&&!this.observedCompactionItems.has(u)&&(this.observedCompactionItems.add(u),this.options.onCompaction?.({compactThreshold:d,itemId:c,transport:"websocket"}));}else o.controller.enqueue(lut(i));if(s?.type==="response.completed"){let l=Array.isArray(o.fullRequest.input)?o.fullRequest.input:void 0;o.compactionItem&&l&&(this.compactionState=cx({input:l,item:o.compactionItem,isTransientInputItem:this.options.isTransientInputItem}),this.options.onCompactionStateChange?.(this.compactionState)),this.latestResponseId=s.response.id,this.previousDurableInput=l?.filter(c=>!this.options.isTransientInputItem?.(c)),this.closePendingRequest("completed");return}s?.type==="error"&&(this.latestResponseId=void 0,this.previousDurableInput=void 0,this.closePendingRequest("error"));}closePendingRequest(t){let o=this.pendingRequest;o&&(this.clearMessageTimeout(o),o.controller.enqueue(new TextEncoder().encode(Qct)),o.controller.close(),this.pendingRequest=void 0,ge({name:"openai.responses_websocket.response_finished",attributes:{"momentic.websocket_max_message_gap_ms":o.maxMessageGapMs,"momentic.websocket_response_outcome":t,"momentic.websocket_sent_continuation":o.sentContinuation},fn:async()=>{}}));}resetConnection(){this.websocket=void 0,this.openPromise=void 0,this.latestResponseId=void 0,this.previousDurableInput=void 0;let t=this.pendingRequest;t&&(this.clearMessageTimeout(t),t.controller.error(new Error("OpenAI responses websocket connection closed")),this.pendingRequest=void 0);}armMessageTimeout(t){this.clearMessageTimeout(t);let o=this.options.messageTimeoutMs??eut;t.messageTimeout=setTimeout(()=>{let n={"momentic.websocket_message_timeout_ms":o,"momentic.websocket_max_message_gap_ms":t.maxMessageGapMs,"momentic.websocket_ready_state":this.websocket?.readyState??-1,"momentic.websocket_retrying_full_context":t.retryingFullContext,"momentic.websocket_sent_continuation":t.sentContinuation,"momentic.websocket_started_streaming":t.startedStreaming};this.failPendingRequest({pendingRequest:t,err:new Error(`OpenAI responses websocket timed out after ${o}ms without receiving a message`)}),ge({name:"openai.responses_websocket.message_timeout",attributes:n,fn:async()=>{}});},o);}clearMessageTimeout(t){t?.messageTimeout&&(clearTimeout(t.messageTimeout),t.messageTimeout=void 0);}failPendingRequest({pendingRequest:t,err:o}){if(this.pendingRequest!==t)return;this.clearMessageTimeout(t),this.pendingRequest=void 0,t.controller.error(o);let n=this.websocket;this.resetConnection(),n?.terminate();}};async function out(e){let t=await kD(e);if(!t)return;let o=aye.safeParse(JSON.parse(t));return o.success?o.data:void 0}function nut(e,t){return (t?.method??(e instanceof Request?e.method:"GET")).toUpperCase()==="POST"&&lye(e).endsWith("/responses")}function lye(e){return e instanceof Request?e.url:e.toString()}function rut(e){let t=new URL(e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function iye(e){if(!e)return {};if(e instanceof Headers){let t={};return e.forEach((o,n)=>{t[n]=o;}),t}return Array.isArray(e)?Object.fromEntries(e):e}function iut({payload:e,compactThreshold:t}){t&&(e.context_management=[{type:"compaction",compact_threshold:t}]);}function aut(e){return e?.type==="error"&&e.code==="previous_response_not_found"}function sut(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 lut(e){return new TextEncoder().encode(`data: ${JSON.stringify(e)}
368
368
 
369
369
  `)}function uye(e){return {specificationVersion:e.specificationVersion,provider:e.provider,modelId:e.modelId,supportedUrls:e.supportedUrls,doGenerate:t=>e.doGenerate(cye(t)),doStream:t=>e.doStream(cye(t))}}function cye(e){return {...e,providerOptions:{...e.providerOptions,openai:{...e.providerOptions?.openai,store:false}}}}function ND(e){return async(t,o)=>{let n=dut(o?.body);if(!n)return fetch(t,o);let r=e?.priorityServiceTier===true,i=e?.promptCacheKey;n.store=false,uut(n),r&&(n.service_tier="priority"),i&&(n.prompt_cache_key=i);let a=await fetch(t,{...o,body:JSON.stringify(n)});return mut({capturePath:e?.requestCapturePath,input:t,status:a.status,body:n}),a}}function uut(e){if(e.store!==false)return;let t="reasoning.encrypted_content",o=e.include;if(!Array.isArray(o)){e.include=[t];return}o.includes(t)||(e.include=[...o,t]);}function dut(e){if(typeof e=="string")try{let t=JSON.parse(e);return dye(t)?t:void 0}catch{return}}function mut({capturePath:e,input:t,status:o,body:n}){e&&appendFileSync(e,`${JSON.stringify({url:hut(t),status:o,request:put(n)})}
370
- `);}function put(e){let t=e.reasoning,o=e.include;return {model:e.model,service_tier:e.service_tier,prompt_cache_key:e.prompt_cache_key,include:Array.isArray(o)?o.filter(n=>typeof n=="string"):void 0,reasoning:dye(t)?{effort:t.effort}:void 0,hasInput:!!e.input,toolsCount:Array.isArray(e.tools)?e.tools.length:0}}function dye(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function hut(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}var gut=3e5;function DD(e){let t=e.split("/").at(-1)??e;return t.startsWith("grok-4.5")||t.startsWith("grok-4.6")}var fut=z.object({input:z.array(z.custom()),instructions:z.unknown().optional(),model:z.string(),tools:z.unknown().optional()}).passthrough(),yut=z.object({output:z.array(z.object({type:z.literal("compaction"),id:z.string(),encrypted_content:z.string()})).min(1),usage:z.object({dropped_message_count:z.number().int().nonnegative(),input_tokens:z.number().int().nonnegative(),output_tokens:z.number().int().nonnegative()})});function mye(e={}){let t=e.compactThreshold??gut,o=ND(e.requestOptions),n;return async(r,i)=>{let a=i?.method??(r instanceof Request?r.method:"GET"),s=new URL(r instanceof Request?r.url:r.toString());if(a.toUpperCase()!=="POST"||!s.pathname.endsWith("/responses"))return o(r,i);let l=typeof i?.body=="string"?i.body:void 0;if(!l)return o(r,i);let c;try{c=JSON.parse(l);}catch{return o(r,i)}let u=fut.safeParse(c);if(!u.success)return o(r,i);let d=u.data.input,m=n&&d.length>=n.boundaryInput.length&&n.boundaryInput.every((g,f)=>JSON.stringify(g)===JSON.stringify(d[f]))?[n.item,...d.slice(n.boundaryInput.length)]:void 0;n&&!m&&(n=void 0);let p=m??d;if((m&&n?n.outputTokens:0)+Gt({input:m?m.slice(1):d,instructions:u.data.instructions,tools:u.data.tools})>=t){let g=await but({url:s,init:i,model:u.data.model,providerInput:p});if(g){let f=g.output[0];n={item:f,boundaryInput:d,outputTokens:g.usage.output_tokens},p=[f],e.onCompaction?.({compactThreshold:t,droppedMessageCount:g.usage.dropped_message_count,inputTokens:g.usage.input_tokens,itemId:f.id,outputTokens:g.usage.output_tokens});}}return o(r,{...i,body:JSON.stringify({...u.data,input:p,previous_response_id:void 0})})}}async function but({url:e,init:t,model:o,providerInput:n}){e.pathname=`${e.pathname.replace(/\/$/,"")}/compact`;let r=await fetch(e,{...t,body:JSON.stringify({input:n,model:o})});if(!r.ok)return;let i;try{i=await r.json();}catch{return}let a=yut.safeParse(i);return a.success?a.data:void 0}var Aut="MOMENTIC_OPENAI_RESPONSES_WEBSOCKET_COMPACT_THRESHOLD";function Qb(e){let{apiKey:t,sessionId:o,loggerTags:n,runner:r,parentTraceId:i}=e,a={Authorization:`Bearer ${t}`,[pM]:zb,...o&&{[vre]:o},...r&&{[hM]:r},...i&&{[Are]:i},...n&&{[gM]:JSON.stringify(n)}};for(let[s,l]of Object.entries(a))a[s]=l.replace(/[\u0100-\uffff]/g,c=>"\\u"+c.charCodeAt(0).toString(16).padStart(4,"0"));return a}var pye="bedrock/",hye="azure/",gye="anthropic/",fye=e=>t=>{let o=Qb(e),n=t,r=`${e.baseUrl}/v1/llm/anthropic/${encodeURIComponent(t)}`;return t.startsWith(pye)?(r=`${e.baseUrl}/v1/llm/provider/bedrock/anthropic/${encodeURIComponent(t.slice(pye.length))}`,new AnthropicLanguageModel(n,{provider:"anthropic.messages",baseURL:r,headers:{...o,"anthropic-version":"2023-06-01","x-api-key":e.apiKey},supportsNativeStructuredOutput:false,supportsStrictTools:false})):(t.startsWith(hye)?r=`${e.baseUrl}/v1/llm/provider/foundry/anthropic/${encodeURIComponent(t.slice(hye.length))}`:t.startsWith(gye)&&(n=t.slice(gye.length),r=`${e.baseUrl}/v1/llm/provider/anthropic/${encodeURIComponent(n)}`),createAnthropic({baseURL:r,headers:o,apiKey:e.apiKey})(n))},yye=e=>t=>Tye(e,t,"openai"),bye=e=>t=>{let o=Qb(e),n=ND(e.xai);return DD(t)&&(n=mye({requestOptions:e.xai,onCompaction:r=>e.onXAINativeCompaction?.({...r,model:t})})),createXai({baseURL:`${e.baseUrl}/v1/llm/provider/xai/${t}`,headers:o,apiKey:e.apiKey,fetch:n}).responses(t)},Sye=e=>t=>Tye(e,t,"azure");function Tye(e,t,o){let n=e.useOpenAIResponsesWebSocket===true&&(o==="openai"||hee(t)),r=n?e.openAIResponsesWebSocketCompactThreshold??Eut(process.env[Aut])??jq(t):e.openAIResponsesCompactThreshold??jq(t),i=a=>e.onOpenAINativeCompaction?.({...a,model:t});return uye(rx({baseURL:`${e.baseUrl}/v1/llm/provider/${o}/${t}`,headers:Qb(e),apiKey:e.apiKey,fetch:n?sye({compactThreshold:r,onCompaction:i}):nye({compactThreshold:r,onCompaction:i})})(t))}function vye(e){return t=>o=>{let n=Qb(t);return rx({baseURL:`${t.baseUrl}/v1/llm/provider/${e}/${o}`,headers:n,apiKey:t.apiKey}).chat(o)}}var Aye=vye("azure/deepseek"),Eye=vye("azure/kimi"),wye=e=>t=>{let o=Qb(e);return rx({baseURL:`${e.baseUrl}/v1/llm/provider/fireworks`,headers:o,apiKey:e.apiKey}).chat(t)},Rye=e=>t=>{let o=Qb(e);return Bq({baseURL:`${e.baseUrl}/v1/llm/provider/openrouter`,headers:o,apiKey:e.apiKey,compatibility:"strict"}).chat(t)},Cye=e=>t=>{let o=Qb(e);return kW({baseURL:`${e.baseUrl}/v1/llm/provider/vertex`,headers:o,apiKey:e.apiKey})(t)};function Eut(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}function Iye(e){let t=Nt.safeParse(e[xG]);return delete e[xG],t.success?t.data:void 0}var ii=class extends ol{agentConfig;apiPathPrefix;supportsAiActionTurbo;constructor(t,o){let n={...yg,...t};wP(n),super(o),this.apiPathPrefix=o.apiPathPrefix??`/${je}`,this.agentConfig=n,this.supportsAiActionTurbo=o.supportsAiActionTurbo??false;}getAgentConfig(){return this.agentConfig}async compactConversationNonNative(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/llm/compact`,{method:"POST",body:{...Cut(t),sessionId:o.sessionId,parentTraceId:o.parentTraceId},signal:o.abortSignal,retries:1,requestTimeoutMs:15e3,extraHeaders:{[gM]:JSON.stringify($q(o))}});return H9.parse(n)}async rankChunksWithAi(t,o){let n={...t,loggerTags:o.loggerTags},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:o.abortSignal});return UZ.parse(r)}async rankChunksWithRag(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:zb,...t},signal:o.abortSignal});return BZ.parse(n)}async getScreenshotFromS3(t){let o=await this.sendRequest(`${this.apiPathPrefix}/s3/visual-diff-screenshot`,{method:"POST",body:{url:t}});return z.string().parse(o)}async getElementLocation(t,o){let n={...t,disableCache:o.disableCache,loggerTags:o.loggerTags,useMemory:o.useMemory,cacheBustReason:o.cacheBustReason,effort:o.effort,agentConfigVersion:this.agentConfig?.locator},r={},i=()=>{let s=Iye(r);s&&o.onEffectiveEffort?.(s);},a=await this.sendRequest(`${this.apiPathPrefix}/web-agent/locate-element`,{method:"POST",body:n,signal:o.abortSignal,responseHeadersObject:r,onFailedRequest:i});return i(),Rre.parse(a)}async getAssertionResult(t,o){let n={...t,disableCache:!!o.disableCache,useConsensus:!!o.useConsensus,attemptNumber:o.attemptNumber,loggerTags:o.loggerTags,useMemory:o.useMemory,effort:o.effort,agentConfigVersion:this.agentConfig?.assertion},r={},i=()=>{let s=Iye(r);s&&o.onEffectiveEffort?.(s);},a=await this.sendRequest(`${this.apiPathPrefix}/web-agent/assertion`,{method:"POST",body:n,signal:o.abortSignal,responseHeadersObject:r,onFailedRequest:i});return i(),_G.parse(a)}async getLintStepResult(t,o){let n={...t,disableCache:!!o.disableCache,loggerTags:o.loggerTags},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/lint/step`,{method:"POST",body:n,signal:o.abortSignal});return wre.parse(r)}async getVisualAssertionResult(t,o){let n={...t,disableCache:!!o.disableCache,useConsensus:!!o.useConsensus,attemptNumber:o.attemptNumber,loggerTags:o.loggerTags,useMemory:o.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/visual-assertion`,{method:"POST",body:n,signal:o.abortSignal});return _G.parse(r)}async getAiActionCommand(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/next-command-dynamic`,{method:"POST",body:{...t,disableCache:o.disableCache,loggerTags:o.loggerTags},signal:o.abortSignal});return Ere.parse(n)}async getMultiturnAiActionCommand(t,o){return await this.sendRequest(`${this.apiPathPrefix}/web-agent/ai-action/next-command`,{method:"POST",body:{...t,disableCache:o.disableCache,loggerTags:o.loggerTags},signal:o.abortSignal})}async getMultiturnAiActionEvaluation(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/ai-action/evaluate`,{method:"POST",body:{...t,disableCache:o.disableCache,loggerTags:o.loggerTags},signal:o.abortSignal});return M$.parse(n)}async getAiActionTurboDecision(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/ai-action/turbo-decision`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal,requestTimeoutMs:3e3,retries:1});return d9.parse(n)}async getReverseMappedDescription(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/reverse-mapped-description`,{method:"POST",body:{...t,disableCache:o.disableCache,loggerTags:o.loggerTags},signal:o.abortSignal});return Cre.parse(n)}async getTextExtraction(t,o){let n={...t,disableCache:o.disableCache,loggerTags:o.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/text-extraction`,{method:"POST",body:n,signal:o.abortSignal});return k$.parse(r)}async getPageSummary(t,o){let n={...t,disableCache:o.disableCache,loggerTags:o.loggerTags},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/page-summary`,{method:"POST",body:n,signal:o.abortSignal});return j9.parse(r)}async getSmartWaitingDecision(t,o){let n={...t,disableCache:o.disableCache,loggerTags:o.loggerTags},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/smart-waiting`,{method:"POST",body:n,signal:o.abortSignal});return z9.parse(r)}async getKnowledgeSuggestion(t,o){throw new Error("Knowledge suggestion generation is only available on InternalGenerator")}async getTestResultClassification(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/result-classification`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal});return Kw.parse(n)}async getExtractedKeywords(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/extract-keywords`,{method:"POST",body:t,signal:o.abortSignal});return QZ.parse(n)}async getAutohealingProposal(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/autoheal-section`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal});return N9.parse(n)}async getFailureRecoveryProposal(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/failure-recovery`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal});return B9.parse(n)}async getFailureRecoveryPlan(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/failure-recovery-plan`,{method:"POST",body:{...t,loggerTags:o.loggerTags,agentConfigVersion:this.agentConfig?.["failure-recovery"]},signal:o.abortSignal});return F9.parse(n)}async getFailureRecoveryMemory(t,o){try{let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/failure-recovery-memory`,{method:"POST",body:t,retries:1,requestTimeoutMs:5e3});return rte.parse(n)}catch(n){return o.logger.warn({err:n},"Failed to read failure recovery memory"),{failureCount:0}}}async recordFailureRecoveryOutcome(t,o){try{await this.sendRequest(`${this.apiPathPrefix}/web-agent/failure-recovery-memory`,{method:"PATCH",body:t,retries:1,requestTimeoutMs:5e3});}catch(n){o.logger.warn({err:n},"Failed to record failure recovery outcome");}}async getOrgLevelFailureRate(t,o){let n=t.environment?`?environment=${encodeURIComponent(t.environment)}`:"";try{let r=await this.sendRequest(`${this.apiPathPrefix}/org-level-failure-rate${n}`,{method:"GET",retries:1,requestTimeoutMs:5e3});return wM.parse(r)}catch(r){return o.logger.warn({err:r},"Failed to read org-level failure rate"),{skip:false,failed:0,total:0}}}async getIframeRegex(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/iframe-regex`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal});return p9.parse(n)}createAgentTrace(t){let o=randomUUID(),{completionType:n,runId:r,orgId:i,logger:a}=t,s=a.bindings().sessionId,l=async c=>{try{await this.sendRequest(`${this.apiPathPrefix}/traces/result-classification`,{method:"POST",body:{id:o,completionType:n,input:{runId:r},sessionId:s,...c,metadata:{orgId:i,runId:r,...c.metadata}}});}catch(u){a.warn({err:u},"Failed to upsert result classification trace");}};return l({}),{id:o,update:l}}getAnthropicModelFactory(t){return this.buildModelFactory(fye,t)}getModelProviderCandidate(t,o){return t.startsWith("bedrock/")?{id:"anthropic-bedrock",model:this.getAnthropicBedrockModelFactory(o)(t.slice(8))}:t.startsWith("azure/claude-")?{id:"anthropic-foundry",model:this.getAnthropicFoundryModelFactory(o)(t.slice(6))}:t.startsWith("anthropic/")?{id:"anthropic",model:this.getAnthropicModelFactory(o)(t)}:t.startsWith("openrouter/")?{id:"openrouter",model:this.getOpenRouterModelFactory(o)(t.slice(11))}:t.startsWith("fireworks/")?{id:"fireworks",model:this.getFireworksModelFactory(o)(t)}:t.startsWith("xai/")?{id:"xai",model:this.getXAIModelFactory(o)(t.slice(4))}:t.startsWith("vertex/gemini-")?{id:"google-vertex",model:this.getVertexGeminiModelFactory(o)(t.slice(7))}:t.startsWith("azure/")?{id:"azure",model:this.getAzureOpenAIModelFactory(o)(t.slice(6))}:t.startsWith("claude-")?{id:"anthropic",model:this.getAnthropicModelFactory(o)(t)}:{id:"openai",model:this.getOpenAIModelFactory(o)(t)}}getAnthropicBedrockModelFactory(t){let o=this.getAnthropicModelFactory(t);return n=>o(`bedrock/${n}`)}getAnthropicFoundryModelFactory(t){let o=this.getAnthropicModelFactory(t);return n=>o(`azure/${n}`)}getOpenAIModelFactory(t){let{sessionId:o,logger:n,streamType:r,useOpenAIResponsesWebSocket:i,parentTraceId:a}=t;return yye({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:$q(t),sessionId:o,useOpenAIResponsesWebSocket:i,runner:this.runner,parentTraceId:a,onOpenAINativeCompaction:s=>{n.info({promptType:r,nativeCompaction:s},"Native conversation compaction completed");}})}getXAIModelFactory(t){let{logger:o,streamType:n}=t;return this.buildModelFactory(bye,t,{onXAINativeCompaction:r=>{o.info({promptType:n,nativeCompaction:r},"Native conversation compaction completed");}})}getOpenRouterModelFactory(t){return this.buildModelFactory(Rye,t)}getAzureOpenAIModelFactory(t){let{logger:o,streamType:n}=t;return this.buildModelFactory(Sye,t,{onOpenAINativeCompaction:r=>{o.info({promptType:n,nativeCompaction:r},"Native conversation compaction completed");}})}getAzureDeepSeekModelFactory(t){return this.buildModelFactory(Aye,t)}getAzureKimiModelFactory(t){return this.buildModelFactory(Eye,t)}getFireworksModelFactory(t){return this.buildModelFactory(wye,t)}getVertexGeminiModelFactory(t){return this.buildModelFactory(Cye,t)}buildModelFactory(t,o,n){let{sessionId:r,parentTraceId:i,xai:a,useOpenAIResponsesWebSocket:s}=o;return t({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:$q(o),sessionId:r,runner:this.runner,parentTraceId:i,xai:a,useOpenAIResponsesWebSocket:s,...n})}};function $q(e){return {...Wo(e.logger),agentInvocationId:e.agentInvocationId,promptType:e.streamType}}function Cut(e){return {...e,messages:e.messages.map(Gq)}}function Gq(e){return e instanceof Uint8Array||e instanceof ArrayBuffer?Buffer.from(e).toString("base64"):e instanceof URL?e.toString():Array.isArray(e)?e.map(Gq):typeof e!="object"||e===null?e:Object.fromEntries(Object.entries(e).map(([t,o])=>[t,Gq(o)]))}async function FD(e,t,o){let{size:n}=await Un__default.promises.stat(o),r=new URL(e),i=t==="application/zip"?AbortSignal.timeout(wL(n)):void 0,a;if(r.protocol==="http:")a=request;else if(r.protocol==="https:")a=request$1;else throw new Error(`Unsupported signed upload URL protocol: ${r.protocol}`);return new Promise((s,l)=>{let c=Un__default.createReadStream(o),u=new Promise(f=>c.once("close",f)),d,m=0,p=false,h=false,g=f=>{h||(h=true,c.destroy(),d.destroy(),u.then(()=>l(f)));};try{d=a(r,{method:"PUT",signal:i,headers:{"Content-Length":n,"Content-Type":t}},f=>{p=!0;let y=m<n,b=f.socket;c.unpipe(d),c.destroy(),!d.destroyed&&!d.writableEnded&&d.end();let S=f.statusCode??500,A=S===204||S===205||S===304;if(y&&S>=200&&S<300&&!A){h=!0,d.destroy(),f.destroy(),b.destroy(),u.then(()=>l(new Error(`Upload server returned ${S} before the request body was fully written.`)));return}let T=[];f.on("data",v=>T.push(v)),f.on("error",g),f.on("end",()=>{if(h)return;h=!0,d.destroy(),y&&b.destroy();let v=new Headers;for(let[I,C]of Object.entries(f.headers))if(Array.isArray(C))for(let O of C)v.append(I,O);else C!==void 0&&v.set(I,C);let R=A?null:Buffer.concat(T);u.then(()=>{try{s(new Response(R,{headers:v,status:S,statusText:f.statusMessage}));}catch(I){l(I);}});});});}catch(f){c.destroy(),u.then(()=>l(f));return}d.on("error",f=>{p||g(f);}),c.on("data",f=>{m+=Buffer.byteLength(f);}),c.on("error",g),c.pipe(d);})}function _ye(e,t,o,n){return fetch(e,{method:"PUT",body:o,signal:n,headers:{"Content-Type":t}})}var _ut=2e3,so=class extends ol{apiPathPrefix;constructor(t){super(t),this.apiPathPrefix=t.apiPathPrefix??`/${je}`;}getAppUrl(){return Ev(this.baseUrl)}limbarPath(t){return `${this.apiPathPrefix}/limbar/${t}`}async getAuthInfo(){let t;try{t=await this.sendRequest(`/${je}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});}catch(o){throw o instanceof $I?new ae(`Your Momentic API key was rejected (${o.message}). Run your CLI's \`login\` command or set a valid MOMENTIC_API_KEY. If the key was revoked or expired, create a new one at https://app.momentic.ai/settings/api-keys.`,{cause:o}):o instanceof Lo?o.status>=400&&o.status<500?new ae(o.rawError,{cause:o}):new Error(`Momentic server error (HTTP ${o.status}). Please try again in a moment.`,{cause:o}):o instanceof ae?o: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:o})}return jre.parse(t)}async getFeatureFlags(){let t=await this.sendRequest(`/${je}/auth/flags`,{method:"GET",retries:1,requestTimeoutMs:5e3});return $re.parse(t)}async getCliAnnouncements(){let t=await this.sendRequest(`/${je}/announcements`,{method:"GET",retries:1,requestTimeoutMs:5e3});return Wee.parse(t).announcements}async createMoSessionUpload(t,o,n){let r=AbortSignal.timeout(6e4),i=`/${je}/mo/sessions/${encodeURIComponent(t)}/uploads`,a=0,s;for(;!r.aborted;){let l;try{l=await this.sendRequest(i,{method:"POST",body:o,retries:1,requestTimeoutMs:15e3,signal:r});}catch(c){if(r.aborted&&(c===r.reason||c instanceof Error&&c.name==="AbortError")&&s)throw s;if(c instanceof Lo&&c.status===404)throw new ae(`Mo session ${t} was not found.`,{cause:c});if(c instanceof Lo&&c.code==="MO_SANDBOX_NOT_READY"){if(n?.(),s=c,await wb(Math.max(c.retryAfterMs??1e3,100),r),r.aborted)throw c;continue}if(c instanceof Lo&&c.status>=400&&c.status<500||c instanceof Lo&&c.status===fM||c instanceof ae&&!(c instanceof yA)||(s=c instanceof Error?c:void 0,a++,a>=3||r.aborted))throw c;let u=1500*2**(a-1);if(c instanceof yA&&(u=Math.max(u,hi(c,Lo)?.retryAfterMs??0)),await wb(u,r),r.aborted)throw c}return Qte.parse(l)}throw s??r.reason}async createMoSessionDownload(t,o,n){let r;try{r=await this.sendRequest(`/${je}/mo/sessions/${encodeURIComponent(t)}/downloads`,{method:"POST",body:o,retries:3,requestTimeoutMs:15e3,signal:n});}catch(i){throw i instanceof Lo&&i.status===404?new ae(i.rawError,{cause:i}):i}return Xte.parse(r)}async listProductUpdates(t=3){let o=await this.sendRequest(`/${je}/product-updates?limit=${t}`,{method:"GET",retries:1,requestTimeoutMs:5e3});return fie.parse(o).updates}async getQuotaStatus(){let t=await this.sendRequest(`/${je}/billing/check-quota`,{method:"GET",retries:3,requestTimeoutMs:5e3});return zre.parse(t)}async createRemoteBrowserConnection(t){let o=await this.sendRequest(`/${je}/browsers/connection`,{method:"POST",body:{...t?.envName?{envName:t.envName}:{},...t?.runAttemptId?{runAttemptId:t.runAttemptId}:{},...t?.runGroupId?{runGroupId:t.runGroupId}:{},...t?.testId?{testId:t.testId}:{},...t?.testName?{testName:t.testName}:{},...t?.runId?{runId:t.runId}:{},...t?.attemptedProviders?{attemptedProviders:t.attemptedProviders}:{}},retries:3,requestTimeoutMs:12e4});return uie.parse(o)}async tryCreateBrowserFleetAccessToken(t,o){let n;try{n=await this.sendRequest(`/${je}/browsers/token`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4,signal:o});}catch(i){if(i instanceof Lo&&(i.status===400||i.status===404||i.status===409))return null;throw i}let r=cie.parse(n);return "network"in r?r:null}async bulkGetRunStatus(t){let o=await this.sendRequest(`/${je}/runs/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Dre.parse(o)}async getOrgLevelFailureRate(t){let o=t?`?environment=${encodeURIComponent(t)}`:"",n=await this.sendRequest(`/${je}/org-level-failure-rate${o}`,{method:"GET",retries:1,requestTimeoutMs:5e3});return wM.parse(n)}async recordRunOutcomeForFailureRate(t){await this.sendRequest(`/${je}/org-level-failure-rate`,{method:"POST",body:t,retries:1,requestTimeoutMs:5e3});}async getRunExport(t,o){let n=await this.sendRequest(`/${je}/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4,signal:o});return bM.parse(n)}submitInteractiveAgentFeedback(t){try{this.sendRequest(`/${je}/traces/interactive-agent-feedback`,{method:"POST",body:t,retries:1,requestTimeoutMs:2e3}).catch(o=>{});}catch(o){}return Promise.resolve()}async getResultClassificationCacheEntries(t){let o=await this.sendRequest(`/${je}/result-classification-cache`,{method:"POST",body:t,retries:1,requestTimeoutMs:1e4});return _ie.parse(o)}async createResultClassificationCacheEntries(t){await this.sendRequest(`/${je}/result-classification-cache`,{method:"PATCH",body:t,retries:1,requestTimeoutMs:1e4});}async createAiTriageMetrics(t){await this.sendRequest(`/${je}/ai-triage-metrics`,{method:"POST",body:t,retries:1,requestTimeoutMs:3e3});}async getAiTriageExistingFixes(t){let o=await this.sendRequest(`/${je}/ai-triage-metrics/existing-fixes`,{method:"POST",body:t,retries:1,requestTimeoutMs:5e3});return bee.parse(o)}async saveRunClassification(t,o){await this.sendRequest(`/${je}/runs/${encodeURIComponent(t)}/classification`,{method:"PATCH",body:o,retries:3,requestTimeoutMs:1e4});}async uploadRunHealTraceZip(t,o){let n=await this.sendRequest(`/${je}/runs/${encodeURIComponent(t)}/heal-trace/upload-url`,{method:"POST",retries:3,requestTimeoutMs:1e4}),{uploadUrl:r}=SM.parse(n),i=await _ye(r,"application/zip",o,AbortSignal.timeout(wL(o.byteLength)));if(!i.ok)throw new Error(`Failed to upload heal trace: ${await i.text()}`)}async saveRunHealMetadataBatch(t){await this.sendRequest(`/${je}/runs/heal-metadata`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4});}async getTestYAMLExport(t){let o=await this.sendRequest(`/${je}/tests/export`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return xre.parse(o)}async updateStepCaches(t,o){await this.sendRequest(`/${je}/cache`,{method:"PATCH",body:t,extraHeaders:o,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async updateSnapshotCaches(t,o){await this.sendRequest(`/${je}/snapshot-cache`,{method:"PATCH",body:t,extraHeaders:o,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getStepCacheForTest(t,o){let n=await this.sendRequest(`/${je}/cache`,{method:"POST",body:t,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Ore.parse(n)}async getSnapshotCacheForTest(t,o){let n=await this.sendRequest(`/${je}/snapshot-cache`,{method:"POST",body:t,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Pre.parse(n)}async deleteStepCacheEntry(t,o){await this.sendRequest(`/${je}/cache/entry`,{method:"DELETE",body:t,extraHeaders:o,retries:3,requestTimeoutMs:1e4});}async getWebStepCacheMemoryTraces(t){let o=await this.sendRequest(`/${je}/cache/traces`,{method:"POST",body:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return OG.parse(o)}cacheRouteForPlatform(t){switch(t){case "ANDROID":return "android-cache";case "IOS":return "ios-cache"}}async deleteMobileStepCacheEntry({platform:t,body:o,headers:n}){await this.sendRequest(`/${je}/${this.cacheRouteForPlatform(t)}/entry`,{method:"DELETE",body:o,extraHeaders:n,retries:3,requestTimeoutMs:1e4});}async getMobileStepCacheMemoryTraces(t,o){let n=await this.sendRequest(`/${je}/${this.cacheRouteForPlatform(t)}/traces`,{method:"POST",body:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return OG.parse(n)}async updateMobileStepCaches(t){await this.sendRequest(`/${je}/${this.cacheRouteForPlatform(t.platform)}`,{method:"PATCH",body:t.body,extraHeaders:t.headers,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getMobileStepCacheForTest({platform:t,body:o,headers:n}){let r=await this.sendRequest(`/${je}/${this.cacheRouteForPlatform(t)}`,{method:"POST",body:o,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return kre[t](r)}async queueTests(t){let o=await this.sendRequest(`/${je}/tests/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Ire.parse(o)}async uploadScreenshot(t){let o=await this.sendRequest(`/${je}/screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Ure.parse(o)}async uploadOnDemandScreenshot(t){return await this.sendRequest(`/${je}/on-demand-screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${je}/on-demand-screenshots/${t.id}`}}async fetchOnDemandScreenshot(t){let o={};return {data:await this.sendRequest(`/${je}/on-demand-screenshots/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:5e3,responseType:"buffer",responseHeadersObject:o}),contentType:o["content-type"]??"image/jpeg"}}async getAllEnvironments(){let t=await this.sendRequest(`/${je}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Hre.parse(t)}async acquireCacheLock(t,o){let n=await this.sendRequest(`/${je}/result-cache/lock`,{method:"POST",body:t,signal:o,retries:3,requestTimeoutMs:3e4});return Tie.parse(n)}async releaseCacheLock(t){await this.sendRequest(`/${je}/result-cache/lock`,{method:"DELETE",body:{key:t},retries:3,requestTimeoutMs:5e3});}async deleteCacheResult(t){await this.sendRequest(`/${je}/result-cache/entry`,{method:"DELETE",body:t,retries:3,requestTimeoutMs:5e3});}async setCacheResult(t){await this.sendRequest(`/${je}/result-cache/entry`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:5e3});}async getCacheResult(t){try{return await this.sendRequest(`/${je}/result-cache/entry`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3})}catch(o){if(o instanceof Error&&o.message.includes("404"))return null;throw o}}async queueSuiteRuns(t){let o=await this.sendRequest(`/${je}/suites/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Wre.parse(o)}async bulkGetRunGroupStatus(t){let o={runGroupIds:t},n=await this.sendRequest(`/${je}/run-groups/status`,{method:"POST",body:o,retries:3,requestTimeoutMs:5e3});return MZ.array().parse(n)}async getRunGroupWithRuns(t){try{let o=await this.sendRequest(`/${je}/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return vk.parse(o)}catch(o){if(o instanceof Lo&&o.status===404)return null;throw o}}async getRun(t){try{let o=await this.sendRequest(`/${je}/runs/${encodeURIComponent(t)}/metadata`,{method:"GET",retries:3,requestTimeoutMs:1e4});return js.parse(o)}catch(o){if(o instanceof Lo&&o.status===404)return null;throw o}}async getRunsByCommit(t){let n=[];for(let r=1;;r++){let i=await this.listRuns({gitCommitSha:t,includeFailureDetails:true,limit:100,page:r});if(n.push(...i.runs.map(a=>({...a,test:null}))),i.runs.length<100||r>=i.pageCount)break}return n}async getRunGroupRuns(t){let o=await this.sendRequest(`/${je}/run-groups/${encodeURIComponent(t)}/runs`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Yre.parse(o)}async updateGithubPRHealRiskSummary(t,o){await this.sendRequest(`/${je}/run-groups/${encodeURIComponent(t)}/github-pr-heal-risk-summary`,{method:"PATCH",body:o,retries:3,requestTimeoutMs:1e4});}async uploadProposedSteps(t,o){try{await this.sendRequest(`/${je}/test-fragments/`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});}catch(n){o.error({err:n},"Failed to upload proposed steps");}}async reportBillableEvents(t,o){try{await this.sendRequest(`/${je}/billing/events`,{method:"POST",body:o,retries:10,requestTimeoutMs:1e4});}catch(n){t.error({err:n},"Failed to report billable event");}}async fetchTestFragment(t){let o=await this.sendRequest(`/${je}/test-fragments/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return qre.parse(o)}async patchTestFragment(t,o){await this.sendRequest(`/${je}/test-fragments/${t}`,{method:"PATCH",body:o,retries:3,requestTimeoutMs:1e4});}async getPastTestResults(t,o){let n=await this.sendRequest(`/${je}/results/tests/${t}`,{method:"POST",body:o,retries:3,requestTimeoutMs:1e4});return Kre.parse(n)}async listRuns(t,o){let n=await this.sendRequest(`/${je}/results/runs`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4,signal:o});return Jre.parse(n)}async generateTestResultsUploadUrl(){let t=await this.sendRequest(`/${je}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Xre.parse(t)}async startProcessingResultsUpload(t,o){let n=await this.sendRequest(`/${je}/results/uploads/${t}/process`,{method:"POST",body:o,retries:3,requestTimeoutMs:1e4});return Qre.parse(n)}async startExploreTraceUpload(t){let o=await this.sendRequest(`/${je}/explore/trace-uploads`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return Uie.parse(o)}async fetchIconKnowledgeBase(t){try{let o=await this.sendRequest(`/${je}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return kie.parse(o)}catch(o){return t.error({err:o},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(t,o){try{await this.sendRequest(`/${je}/knowledge-base/icons`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});}catch(n){o.error({err:n},"Failed to save new icons to icon knowledge base");}}async retrieveKnowledgeBase({query:t,clientName:o,testId:n,environmentId:r,types:i,agentSubtype:a,limit:s,mode:l,scoreMultiplier:c,scopeBuckets:u,retries:d,signal:m,timeoutMs:p},h){try{let g=await this.sendRequest(`/${je}/knowledge-base/retrieve`,{method:"POST",body:{query:t,clientName:o,testId:n,environmentId:r,types:i,agentSubtype:a,limit:s,mode:l,scoreMultiplier:c,scopeBuckets:u,timeoutMs:p},retries:d??3,requestTimeoutMs:p===void 0?5e3:p+_ut,signal:m});return Q9.parse(g)}catch(g){return h.warn({err:g},"Failed to retrieve from knowledge base"),null}}async createKnowledgeItem(t){let o=await this.sendRequest(`/${je}/knowledge-base/items`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return H$.parse(o)}async getMergeBaseCommitFromGithub(t,o,n,r){let i=new URLSearchParams;i.set("base",n),i.set("head",r);let a=await this.sendRequest(`/${je}/git/github/${t}/${o}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return YC.parse(a)}async compareCommitsFromGithub({owner:t,repo:o,base:n,head:r},i){i?.throwIfAborted();let a=new URLSearchParams;a.set("base",n),a.set("head",r);let s=await this.sendRequest(`/${je}/git/github/${t}/${o}/compare?${a.toString()}`,{signal:i,method:"GET",retries:3,requestTimeoutMs:5e3});return Ste.parse(s)}async listGithubCommitsForPath({owner:t,repo:o,path:n,ref:r,limit:i}){let a=new URLSearchParams;a.set("path",n),a.set("ref",r),a.set("limit",String(i));let s=await this.sendRequest(`/${je}/git/github/${t}/${o}/commits?${a.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Tte.parse(s).commits}async getGithubFileContent({owner:t,repo:o,path:n,ref:r}){let i=new URLSearchParams;i.set("path",n),i.set("ref",r);let a=await this.sendRequest(`/${je}/git/github/${t}/${o}/contents?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return vte.parse(a).content??void 0}async getGithubBranchMetadata(t,o,n,r){r?.throwIfAborted();let i=new URLSearchParams;i.set("branch",n);let a=await this.sendRequest(`/${je}/git/github/${t}/${o}/branch-metadata?${i.toString()}`,{signal:r,method:"GET",retries:3,requestTimeoutMs:1e4});return Ate.parse(a)}async createGithubPullRequest(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/pull-requests`,{method:"POST",body:n,retries:3,requestTimeoutMs:6e4});return cte.parse(r)}async createGithubCommit(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/commits`,{method:"POST",body:n,retries:3,requestTimeoutMs:6e4});return ute.parse(r)}async getGithubPullRequestTemplate(t,o){try{let n=await this.sendRequest(`/${je}/git/github/${t}/${o}/pull-request-template`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Rte.parse(n).template}catch(n){if(n instanceof Lo&&n.status===404)return;throw n}}async getGithubPullRequestForBranch(t,o,n){let r=new URLSearchParams;r.set("branch",n);let i;try{i=await this.sendRequest(`/${je}/git/github/${t}/${o}/pull-requests?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(a){if(a instanceof Lo&&a.status===404)return;throw a}return fte.parse(i)}async getCommitFromGithub(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return YC.parse(r)}async getGithubDefaultBranch(t,o){try{let n=await this.sendRequest(`/${je}/git/github/${t}/${o}/default-branch`,{method:"GET"}),r=z.object({defaultBranch:z.string().min(1)}).safeParse(n);return r.success?r.data.defaultBranch:void 0}catch{return}}async getGithubCollaboratorsWithMergeAccess(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/collaborator-merge-access`,{method:"POST",body:{usernames:n},retries:3,requestTimeoutMs:15e3});return dte.parse(r).usernamesWithMergeAccess}async searchGithubRelatedPullRequests(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/related-pull-requests`,{method:"POST",body:{query:n},retries:2,requestTimeoutMs:6e4});return hte.parse(r)}async getGithubRelatedPullRequestDetails(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/related-pull-requests/${n}`,{method:"GET",retries:2,requestTimeoutMs:6e4});return z.object({pullRequest:oG}).parse(r).pullRequest}async getGithubCommitDetails(t,o,n){let r=mte.parse({shas:n}),i=await this.sendRequest(`/${je}/git/github/${t}/${o}/commit-details`,{method:"POST",body:r,retries:3,requestTimeoutMs:2e4});return pte.parse(i)}async getMergedBranchFromGithub(t,o,n,r){let i=encodeURIComponent(n),a=await this.sendRequest(`/${je}/git/github/${t}/${o}/${i}/${r}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return DG.parse(a)}async getMergeBaseCommitFromGitlab(t,o,n){let r=new URLSearchParams;r.set("base",o),r.set("head",n);let i=encodeURIComponent(t),a=await this.sendRequest(`/${je}/git/gitlab/${i}/merge-base-commit?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return YC.parse(a)}async getGitlabMergeRequestForBranch(t,o){let n=new URLSearchParams;n.set("branch",o);let r=encodeURIComponent(t),i;try{i=await this.sendRequest(`/${je}/git/gitlab/${r}/merge-requests?${n.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(a){if(a instanceof Lo&&a.status===404)return;throw a}return Ete.parse(i)}async getCommitFromGitlab(t,o){let n=encodeURIComponent(t),r=await this.sendRequest(`/${je}/git/gitlab/${n}/commits/${o}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return YC.parse(r)}async getMergedBranchFromGitlab(t,o,n){let r=encodeURIComponent(o),i=encodeURIComponent(t),a=await this.sendRequest(`/${je}/git/gitlab/${i}/${r}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return DG.parse(a)}async getAgentConfig(){let t=await this.sendRequest(`/${je}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return z.record(z.string(),z.string()).parse(t)}async getOrgSettings(){try{let t=await this.sendRequest(`/${je}/org-settings`,{method:"GET",retries:3,requestTimeoutMs:5e3});return bZ(t)}catch(t){if(t instanceof Lo&&t.status===404)return this.logger.warn({err:t},"Momentic server does not expose org settings; continuing with local project settings"),JT.parse({});throw t}}async getQuarantinedTests(){let t=await this.sendRequest(`/${je}/quarantine`,{method:"GET"});return Zre.parse(t)}async listQuarantinedTests(t){let o=await this.sendRequest(`/${je}/quarantine/details`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return eie.parse(o)}async sendExploreSlackNotification(t){await this.sendRequest(`/${je}/explore/slack-notification`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async recordExplorerSuggestedTests(t){await this.sendRequest(`/${je}/explore/suggested-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async quarantineTest(t,o,n){await this.sendRequest(`/${je}/quarantine`,{method:"POST",body:{testId:t.id,testName:t.name,reason:o,...n??{}},retries:3,requestTimeoutMs:1e4});}async unquarantineTest(t,o,n){await this.sendRequest(`/${je}/quarantine/${t.id}`,{method:"DELETE",body:{testName:t.name,reason:o,...n??{}},retries:3,requestTimeoutMs:1e4});}platformRoute(t){switch(t){case "ANDROID":return "android";case "IOS":return "ios"}}async createAndroidEmulator(t){let o=await this.sendRequest(this.limbarPath("android"),{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return oie.parse(o)}async extendEmulatorTtl(t,o){let n=Date.now();try{await this.sendRequest(this.limbarPath(`${this.platformRoute(t)}/${o}/keepalive`),{method:"POST",retries:3,requestTimeoutMs:15e3}),this.logger.debug({platform:t,emulatorName:o,durationMs:Date.now()-n},"Extended emulator keepalive");}catch(r){this.logger.warn({err:r,platform:t,emulatorName:o,durationMs:Date.now()-n},"Failed to extend emulator keepalive");}}async generateAssetUploadUrl({channel:t,tag:o,alias:n,md5:r,platform:i}){let a={channel:t,tag:o,alias:n,md5:r},s=await this.sendRequest(this.limbarPath(`${this.platformRoute(i)}/upload-url`),{method:"POST",retries:3,body:a,requestTimeoutMs:15e3,logResponse:true});return rie.parse(s)}async deleteAndroidEmulator(t){await this.sendRequest(this.limbarPath(`android/${t}`),{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async getMobileAssets(){let t=await this.sendRequest(this.limbarPath("assets"),{method:"GET",retries:3,requestTimeoutMs:1e4});return iie.parse(t)}async getLimbarAssetDownloadUrl(t,o,n){let r=await this.sendRequest(this.limbarPath(`assets/${t}/${o}/${this.platformRoute(n)}/download-url`),{method:"GET",retries:2,requestTimeoutMs:3e4});return aie.parse(r)}async deleteAsset(t,o,n){await this.sendRequest(this.limbarPath(`assets/${t}/${o}/${this.platformRoute(n)}`),{method:"DELETE",retries:3,requestTimeoutMs:1e4});}async createIosEmulator(t){let o=await this.sendRequest(this.limbarPath("ios"),{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return nie.parse(o)}async deleteIosEmulator(t){await this.sendRequest(this.limbarPath(`ios/${t}`),{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async generateMobileLogcatUploadUrl(t){let o=await this.sendRequest(`/${je}/logcat/mobile/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return jee.parse(o)}async generateMcpSessionTraceUploadUrl(t){let o=await this.sendRequest(`/${je}/mcp/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return SM.parse(o)}};async function Zb(e){let t=process.versions.node,o=parseInt(t.split(".")[0]);(isNaN(o)||o<18)&&(x.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),x.debug(`Identified node version ${t}`);let n=await e.client.getAuthInfo();return x.debug("Got auth info from API"),n}var Th=class{apiClient;constructor(t){this.apiClient=t;}async reportBillableEvents(t,o){await this.apiClient.reportBillableEvents(t,o);}};async function vh({reporter:e,logger:t,feature:o,cached:n,outcome:r,result:i,runId:a,testId:s,testName:l,labels:c,triageTestResults:u=[],sessionId:d,agentInvocationId:m,transactionId:p}){if(o==="triage"&&r===void 0)throw new Error("Triage invocation outcome is required");if(o==="triage"&&(!d||!m))throw new Error("Triage invocation IDs are required");if(o!=="triage"&&u.length>0)throw new Error("Only triage invocations can report test outcomes");let h=new Date().toISOString(),g=new Set(u.map(A=>A.outcome)),f=r;i==="failure"&&(f="error");let y={cached:n,sessionId:d,agentInvocationId:m},b=TM.parse({...y,runId:a,testId:s,testName:l,aiFeature:o,outcome:f,labels:c,hasFixedTest:g.has("fixed"),hasCannotFixTest:g.has("cannot-fix"),hasNoFixNeededTest:g.has("no-fix-needed")}),S=[{event:"ai-agent-invocation",timestamp:h,transactionId:p,properties:b},...u.map(A=>({event:"ai-triage-test-result",timestamp:h,transactionId:`${p}:test-result:${A.testId}`,properties:TM.parse({...y,runId:A.runId,testId:A.testId,testName:A.testName,aiFeature:"triage",outcome:A.outcome,labels:A.labels})}))];try{await e.reportBillableEvents(t,S);}catch(A){t.warn({err:A,feature:o,cached:n,outcome:f},"Failed to report AI agent invocation");}}var Ah=class extends ol{generator;constructor(t,o){super(t),this.generator=o;}async runTemplateMatching(t,o={}){let n=await this.sendRequest(`/${je}/web-agent/template-matching`,{method:"POST",body:t,signal:o?.signal});return h9.parse(n)}async constructIframeRegex(t,o={}){return this.generator.getIframeRegex(t,{abortSignal:o.signal,loggerTags:o.loggerTags})}};var LA=class{constructor(t,o){this.client=t;this.orgId=o;}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let t=this.getApiServerUrl();return Ev(t)}async acquireCacheLock(t,o){return this.client.acquireCacheLock(t,o)}async createOnDemandScreenshot(t,o,n){let{apiServerUrl:r}=await this.client.uploadOnDemandScreenshot({id:t,screenshot:o.toString("base64"),contentType:n});return {apiServerUrl:r,appServerUrl:`${this.getAppServerUrl()}/api/on-demand-screenshots/${t}`,universalHandle:{id:t,contentType:n}}}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,o){return this.client.saveNewIcons(t,o)}};var Out="x-momentic-internal-api-endpoint-secret",BD=class extends so{internalHeaders;constructor({internalApiSecret:t,...o}){super(o),this.internalHeaders=t?{[Out]:t}:{},t&&x.addRedactedValue(t);}async getRunExport(t,o){let n=await this.sendRequest(`/internal/eval/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4,extraHeaders:this.internalHeaders,signal:o});return bM.parse(n)}async getRunGroupWithRuns(t){try{let o=await this.sendRequest(`/internal/eval/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4,extraHeaders:this.internalHeaders});return vk.parse(o)}catch(o){if(o instanceof Lo&&o.status===404)return null;throw o}}};var Eh="v1",Mut=2e3,Oye="sms.lease() and sms.release() are only supported when running tests via the Momentic CLI.",wh=class{httpClient;fakerInstance;fakerSeed;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.fakerSeed=t.fakerSeed,this.supportsLease=t.supportsLease??true,this.resetFaker();}resetFaker(){if(this.fakerSeed===void 0){this.fakerInstance=void 0;return}this.fakerInstance=new Faker({locale:en$1}),this.fakerInstance.seed(this.fakerSeed);}async sendSms(t){return this.httpClient.sendRequest(`/${Eh}/tools/sms/send`,{method:"POST",body:t}).then(()=>{}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to send sms: ${o.message}`)})}async fetchLatestSms(t){return this.httpClient.sendRequest(`/${Eh}/tools/sms/fetchLatest`,{method:"POST",body:t}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):o})}async leasePhoneNumber(t){if(!this.supportsLease)throw new Error(Oye);let o=await this.httpClient.sendRequest(`/${Eh}/tools/sms/lease`,{method:"POST",body:t??{}}).catch(r=>{throw r instanceof Lo?new Error(r.rawError):new Error(`Failed to lease phone number: ${r.message}`)}),n=qee.parse(o);return this.activeLeases.set(n.phoneNumber,{leaseToken:n.leaseToken}),n}async releasePhoneNumber(t){if(!this.supportsLease)throw new Error(Oye);return this.activeLeases.delete(t.phoneNumber),this.httpClient.sendRequest(`/${Eh}/tools/sms/release`,{method:"POST",body:t}).then(()=>{}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to release phone number: ${o.message}`)})}async dispose(){let t=[...this.activeLeases.entries()];this.activeLeases.clear(),await Promise.allSettled(t.map(([o,{leaseToken:n}])=>ye(this.httpClient.sendRequest(`/${Eh}/tools/sms/release`,{method:"POST",body:{phoneNumber:o,leaseToken:n}}),{milliseconds:Mut,fallback:()=>{}})));}async sendEmail(t){return this.httpClient.sendRequest(`/${Eh}/tools/email/send`,{method:"POST",body:t}).then(()=>{}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to send email: ${o.message}`)})}async fetchAllEmails(t){return this.httpClient.sendRequest(`/${Eh}/tools/email/fetchAll`,{method:"POST",body:t}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to fetch all emails: ${o.message}`)})}async fetchLatestEmail(t){return this.httpClient.sendRequest(`/${Eh}/tools/email/fetchLatest`,{method:"POST",body:t}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to fetch latest emails: ${o.message}`)})}async createEmail(){let t=await this.httpClient.sendRequest(`/${Eh}/tools/email/create`,{method:"POST",body:{}}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to create email inbox: ${o.message}`)});return Kee.parse(t)}};var NA=class{constructor(t){this.client=t;}async uploadResultsArchive(t){let{runGroupId:o,archivePath:n,persist:r}=t,{uploadUrl:i,id:a}=await this.client.generateTestResultsUploadUrl(),s=await FD(i,"application/zip",n);if(!s.ok)throw new Error(`Failed to upload test results: ${await s.text()}`);let{runGroupId:l}=await this.client.startProcessingResultsUpload(a,{resultType:"run",runGroupId:o,persist:r});return l}async uploadExploreArchive(t){let{exploreRunId:o,metadata:n,archivePath:r,videos:i}=t,{uploadUrl:a,videoUploadUrls:s}=await this.client.startExploreTraceUpload({exploreRunId:o,metadata:n,videoAssets:i?.map(c=>c.name)});for(let c of i??[]){let u=s?.[c.name];if(!u)throw new Error(`Missing upload URL for video asset ${c.name}`);let d=await FD(u,c.contentType,c.path);if(!d.ok)throw new Error(`Failed to upload explore video ${c.name}: ${await d.text()}`)}let l=await FD(a,"application/zip",r);if(!l.ok)throw new Error(`Failed to upload explore results: ${await l.text()}`)}};function Rh({logger:e,orgId:t,client:o,gitMetadata:n,regenerateCache:r,alwaysSaveCache:i,noCache:a,isolateCachesByEnvironment:s=false,bustOldestCachePercentage:l}){return a?new CM:new Vq(e,t,o,n,{regenerateCache:r,alwaysSaveCache:i,bustOldestCachePercentage:l,isolateCachesByEnvironment:s})}var Vq=class{constructor(t,o,n,r,i){this.orgId=o;this.client=n;let{regenerateCache:a,alwaysSaveCache:s,bustOldestCachePercentage:l,isolateCachesByEnvironment:c}=i,{gitBranchName:u,gitProtectedBranches:d}=r;t.info({options:i,gitBranchName:u,gitProtectedBranches:d},"Cache storage initialization options"),this.cacheHeaders=yM(r),this.isolateCachesByEnvironment=c,this.readCaches=!a;let m=u&&d.includes(u);s||!m?this.writeCaches=true:this.writeCaches=false,m||(this.bustOldestCachePercentage=l);}cacheHeaders;readCaches;writeCaches;isolateCachesByEnvironment;bustOldestCachePercentage;async saveStepCacheEntries({entries:t,logger:o}){if(!this.writeCaches){o.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:zG(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(n){o.error({err:n},"Failed to save step cache entries");}}async saveSnapshotCacheEntries({entries:t,logger:o}){if(t.length!==0)try{await this.client.updateSnapshotCaches({entries:zG(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(n){o.error({err:n},"Failed to save snapshot cache entries");}}async deleteStepCacheEntry({logger:t,testId:o,key:n,environment:r}){await this.client.deleteStepCacheEntry({testId:o,key:n,environment:this.isolateCachesByEnvironment?r:void 0},this.cacheHeaders),t.debug({testId:o,key:n},"Deleted step cache entry");}async resolveStepCacheEntries(t){let{restoredIdentity:o,restoredStepLists:n}=await this.restoreAndPersistStepIdentity(t);if(!this.readCaches)return t.logger.debug("Skipping cache resolution because of regenerate flag"),{restoredStepLists:n};let{steps:r,beforeSteps:i,afterSteps:a}=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 d=Object.entries(s).map(([h,g])=>({key:h,time:g.value.cache?.updatedAt?.getTime()??0}));d.sort((h,g)=>h.time-g.time);let m=d.length,p=Math.max(1,Math.floor(m*this.bustOldestCachePercentage/100));d.slice(0,p).forEach(({key:h})=>{delete s[h];}),t.logger.info({nCachesToBust:p,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:m},"Busted oldest caches");}let l={totalSteps:0,cacheKeysHit:[],cacheKeysMissed:[],uniqueKeysHit:[],cacheMissSamples:[]};for(let d of [r,i,a]){if(!d)continue;let m=of({steps:d,stepCacheEntries:s,logger:t.logger});l.totalSteps+=m.totalSteps,l.cacheKeysHit.push(...m.cacheKeysHit),l.cacheKeysMissed.push(...m.cacheKeysMissed),l.uniqueKeysHit.push(...m.uniqueKeysHit),l.cacheMissSamples.push(...m.cacheMissSamples);}o&&Nut({cacheResolutionStats:l,logger:t.logger,restoredIdentity:o,schemaVersion:t.schemaVersion,testId:t.testId});let c=["platform:web","source:local",`fileFormat:${t.useSnapshotIdentityCache?"v2":"v1"}`,`snapshotIdentityCache:${t.useSnapshotIdentityCache}`,`orgId:${this.orgId}`,"cliVersion:3.62.2"];if(zo.increment("step_cache_resolution",l.cacheKeysHit.length,[...c,"outcome:hit"]),zo.increment("step_cache_resolution",l.cacheKeysMissed.length,[...c,"outcome:miss"]),zo.increment("step_cache_resolution",l.totalSteps,[...c,"outcome:total"]),!this.writeCaches)return t.logger.debug("Skipping cache last used at update because branch is protected"),{restoredStepLists:n};let{cachesToSave:u}=await sr({stepLists:t.stepLists,useSnapshotIdentityCache:false,cacheCreationParams:{environment:t.environment,testId:t.testId,orgId:this.orgId}});return this.saveStepCacheEntries({entries:u,logger:t.logger}),{restoredStepLists:n}}async restoreAndPersistStepIdentity(t){let o=t.useSnapshotIdentityCache?await this.tryRestoreStepIdsFromSnapshot(t):void 0;if(!o)return {restoredIdentity:void 0,restoredStepLists:void 0};let{snapshotCachesToSave:n}=await sr({stepLists:t.stepLists,useSnapshotIdentityCache:true,cacheCreationParams:{environment:t.environment,testId:t.testId,orgId:this.orgId}});return this.saveSnapshotCacheEntries({entries:n,logger:t.logger}),{restoredIdentity:o,restoredStepLists:structuredClone(o.stepLists)}}async tryRestoreStepIdsFromSnapshot(t){try{return await this.restoreStepIdsFromSnapshot(t)}catch(o){t.logger.warn({err:o,testId:t.testId},"Failed to restore step ids from snapshot cache; proceeding without identity cache"),zo.increment("step_cache_resolution",1,["platform:web","source:local","fileFormat:v2","snapshotIdentityCache:true",`orgId:${this.orgId}`,"cliVersion:3.62.2","outcome:identity_restore_error"]);return}}async restoreStepIdsFromSnapshot(t){let{logger:o,testId:n}=t,r=await this.client.getSnapshotCacheForTest({testId:n,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders);for(let s of r){if(!s.schema_version)continue;let l=q1(s.schema_version),c=q1(qt);if(l&&c&&l.compare(c)>0){o.warn(`Snapshot cache for test ${n} was written at schema version ${s.schema_version}, which is newer than this CLI's latest (${qt}). Please update your momentic package version. Skipping identity restoration from snapshot cache.`);return}}let i=eN({entries:r,orgId:this.orgId,testId:n,logger:o}),a=ZL({currentStepLists:t.stepLists,previousSnapshot:i.testSnapshot,previousModuleSnapshots:i.moduleSnapshots,generateUuid:randomUUID});return t.stepLists.steps.splice(0,t.stepLists.steps.length,...a.stepLists.steps),t.stepLists.beforeSteps=a.stepLists.beforeSteps,t.stepLists.afterSteps=a.stepLists.afterSteps,o.debug({snapshotEntries:r.length,testSnapshotHit:!!i.testSnapshot,moduleSnapshots:Array.from(i.moduleSnapshots.keys()),mintedSteps:a.stats.mintedSteps,stats:a.stats,moduleRestoreResults:a.moduleRestoreResults.map(({moduleId:s,snapshotHit:l,stats:c})=>({moduleId:s,snapshotHit:l,stats:c}))},"Restored step ids from snapshot cache"),a}};function Nut({cacheResolutionStats:e,logger:t,restoredIdentity:o,schemaVersion:n,testId:r}){let i=e.cacheKeysHit.length,a=e.cacheKeysMissed.length,s=i+a,l=s>0?Math.round(a/s*1e3)/10:0,c=o.stats.matchedSteps+o.stats.mintedSteps,u=c>0?Math.round(o.stats.mintedSteps/c*1e3)/10:0,d=o.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})),m=o.stats.mintedSteps>=5&&u>=25,p=m||o.stats.bustedConditionals>0||d.some(({stats:g})=>g.mintedSteps>=5||g.bustedConditionals>0),h={cacheHits:i,cacheMissRate:l,cacheMisses:a,cacheMissSamples:e.cacheMissSamples.slice(0,10),hasHighMintRate:m,identityMintRate:u,moduleIdentityIssueCount:d.length,moduleIdentityIssues:d,schemaVersion:n,snapshotIdentityCache:true,stepIdentityStats:o.stats,testId:r,totalCacheableSteps:e.totalSteps};if(!p){t.debug(h,"V2 cache resolution completed");return}t.warn(h,"V2 cache resolution degraded");}async function cl({project:e,apiClient:t,classificationOverrides:o}){let{classification:n,healing:r,explore:i}=(await Dut(t))?.ai??{},a=But({flags:o,config:e.config.ai?.classification,cloudCategories:n?.categories}),s={...e.config.ai};return o?.disabled&&(s.aiFailureAnalysis=false),{...e,config:{...e.config,ai:{...s,classification:a,healing:r,explore:i}}}}async function Dut(e){try{return await e.getOrgSettings()}catch(t){if(!Fut(t))throw t;x.warn({err:t},"Could not load organization settings from Momentic. Continuing with local project configuration.");return}}function Fut(e){return e instanceof Lo?e.status>=500:e instanceof Ua||fI(e)}function But({flags:e,config:t,cloudCategories:o}){if(!(!t&&!o))return {enabled:e?.disabled?false:t?.enabled??false,overrideExitCode:e?.overrideExitCode??t?.overrideExitCode??RQ,categories:o??Tl}}var Pye="golden/visual-diff",kye="reports",Ed="test-results";var Uut=z.object({width:z.number(),height:z.number()}),FA=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;apiClient;constructor(t,o,n){let r=Cn__default.join(t.rootDir,t.config.goldenFileDir??Pye);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=n,this.apiClient=o;}async prepareGoldenScreenshotForComparison(t,o,n){if(v8(o.screenshot?.data))return {buffer:(await this.apiClient.fetchOnDemandScreenshot(o.screenshot.data.id)).data,width:o.screenshot.width,height:o.screenshot.height};if(o.screenshot?.data?.startsWith("https://")){let a=await fetch(o.screenshot.data);return {buffer:Buffer.from(await a.arrayBuffer()),width:o.screenshot.width,height:o.screenshot.height}}let r=o.screenshot?.data;r||(r=Cn__default.join(this.defaultGoldenScreenshotDir,`${o.id}.jpg`));let i=`${r}.metadata.json`;if(this.regenerateGoldenFiles)return Un__default.mkdirSync(Cn__default.dirname(r),{recursive:true}),Un__default.writeFileSync(r,n.buffer),Un__default.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(Un__default.existsSync(r)){let a=Un__default.readFileSync(r),s=Uut.parse(JSON.parse(Un__default.readFileSync(i,"utf-8")));return {buffer:a,width:s.width,height:s.height}}else throw new ie("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${r}`)}};var Lye=["GIT_SSH","GIT_SSH_COMMAND","GIT_SSH_VARIANT","GIT_ASKPASS","GIT_PROXY_COMMAND","GIT_TERMINAL_PROMPT","SSH_ASKPASS"],Mye=new Set(Lye),zut=new Set(["EDITOR","VISUAL","PAGER","PREFIX"]);function Hut(e,t=process.platform){let o={};for(let[n,r]of Object.entries(e)){let i=n.toUpperCase(),a=t==="win32"&&Mye.has(i)?i:n;r!==void 0&&!zut.has(i)&&(!i.startsWith("GIT_")||Mye.has(a))&&(o[a]=r);}return o.LC_ALL="C",o.LANG="C",o}function Ai(e,t,o=true){t?.throwIfAborted();let n=Hut(process.env);return simpleGit({baseDir:e??process.cwd(),abort:t,trimmed:o,allowEnvironment:Lye,unsafe:{allowUnsafeAskPass:!!(n.GIT_ASKPASS||n.SSH_ASKPASS),allowUnsafeGitProxy:!!n.GIT_PROXY_COMMAND,allowUnsafeSshCommand:!!(n.GIT_SSH||n.GIT_SSH_COMMAND)}}).env(n)}var Dye=3e3,ra=Ai();async function Kq(e,t,o){try{return await Ai(e,o).revparse(t)}catch(n){if(o?.throwIfAborted(),zye(n))return;throw n}}async function Eu(e,t){return Kq(e,["--show-toplevel"],t)}async function BA(e){let t=await Eu(e);if(!t)return;let o=Cn__default.relative(t,e);if(!(o.startsWith("..")||Cn__default.isAbsolute(o)))return o===""?".":o}async function Fye(e){return Kq(e,["HEAD"])}async function Bye(e){try{return (await Ai(e).revparse(["--is-shallow-repository"])).trim()==="true"}catch{return false}}async function Uye(e){return Kq(e,["--abbrev-ref","HEAD"])}async function UA({cwd:e,base:t,head:o,logger:n,abortSignal:r}){try{let i=(await Ai(e,r).raw(["merge-base",t,o])).trim();if(i.length>0)return i;n.warn({base:t,head:o},"git merge-base returned empty");}catch(i){r?.throwIfAborted(),n.warn({err:i,base:t,head:o},"git merge-base failed");}}function Yq(){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 jA({client:e,repository:t,base:o,head:n,logger:r,abortSignal:i}){let a=Nr(t);if(a)try{i?.throwIfAborted();let s=await e.compareCommitsFromGithub({owner:a.owner,repo:a.repo,base:o,head:n},i);return s.commits.length===0?void 0:s}catch(s){i?.throwIfAborted(),r.warn({err:s,repository:t,base:o,head:n},"remote commit compare failed");return}}async function Au(e){let{logger:t,operation:o,fn:n,context:r}=e,i=Date.now();try{return await n()}finally{let a=Date.now()-i;a>Dye&&!process.env.CI&&t.warn({operation:o,durationMs:a,thresholdMs:Dye,...r??{}},"[timing] slow git metadata operation");}}function Gm(e){if(e)try{let t=new Date(e);return isNaN(t.getTime())?void 0:t}catch{return}}async function jye(e,t){let o=await ur(e,t.raw(["config","--null","--list"])),n={};if(!o)return n;for(let r of o.split("\0")){let i=r.indexOf(`
370
+ `);}function put(e){let t=e.reasoning,o=e.include;return {model:e.model,service_tier:e.service_tier,prompt_cache_key:e.prompt_cache_key,include:Array.isArray(o)?o.filter(n=>typeof n=="string"):void 0,reasoning:dye(t)?{effort:t.effort}:void 0,hasInput:!!e.input,toolsCount:Array.isArray(e.tools)?e.tools.length:0}}function dye(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function hut(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}var gut=3e5;function DD(e){let t=e.split("/").at(-1)??e;return t.startsWith("grok-4.5")||t.startsWith("grok-4.6")}var fut=z.object({input:z.array(z.custom()),instructions:z.unknown().optional(),model:z.string(),tools:z.unknown().optional()}).passthrough(),yut=z.object({output:z.array(z.object({type:z.literal("compaction"),id:z.string(),encrypted_content:z.string()})).min(1),usage:z.object({dropped_message_count:z.number().int().nonnegative(),input_tokens:z.number().int().nonnegative(),output_tokens:z.number().int().nonnegative()})});function mye(e={}){let t=e.compactThreshold??gut,o=ND(e.requestOptions),n;return async(r,i)=>{let a=i?.method??(r instanceof Request?r.method:"GET"),s=new URL(r instanceof Request?r.url:r.toString());if(a.toUpperCase()!=="POST"||!s.pathname.endsWith("/responses"))return o(r,i);let l=typeof i?.body=="string"?i.body:void 0;if(!l)return o(r,i);let c;try{c=JSON.parse(l);}catch{return o(r,i)}let u=fut.safeParse(c);if(!u.success)return o(r,i);let d=u.data.input,m=n&&d.length>=n.boundaryInput.length&&n.boundaryInput.every((g,f)=>JSON.stringify(g)===JSON.stringify(d[f]))?[n.item,...d.slice(n.boundaryInput.length)]:void 0;n&&!m&&(n=void 0);let p=m??d;if((m&&n?n.outputTokens:0)+Gt({input:m?m.slice(1):d,instructions:u.data.instructions,tools:u.data.tools})>=t){let g=await but({url:s,init:i,model:u.data.model,providerInput:p});if(g){let f=g.output[0];n={item:f,boundaryInput:d,outputTokens:g.usage.output_tokens},p=[f],e.onCompaction?.({compactThreshold:t,droppedMessageCount:g.usage.dropped_message_count,inputTokens:g.usage.input_tokens,itemId:f.id,outputTokens:g.usage.output_tokens});}}return o(r,{...i,body:JSON.stringify({...u.data,input:p,previous_response_id:void 0})})}}async function but({url:e,init:t,model:o,providerInput:n}){e.pathname=`${e.pathname.replace(/\/$/,"")}/compact`;let r=await fetch(e,{...t,body:JSON.stringify({input:n,model:o})});if(!r.ok)return;let i;try{i=await r.json();}catch{return}let a=yut.safeParse(i);return a.success?a.data:void 0}var Aut="MOMENTIC_OPENAI_RESPONSES_WEBSOCKET_COMPACT_THRESHOLD";function Qb(e){let{apiKey:t,sessionId:o,loggerTags:n,runner:r,parentTraceId:i}=e,a={Authorization:`Bearer ${t}`,[pM]:zb,...o&&{[vre]:o},...r&&{[hM]:r},...i&&{[Are]:i},...n&&{[gM]:JSON.stringify(n)}};for(let[s,l]of Object.entries(a))a[s]=l.replace(/[\u0100-\uffff]/g,c=>"\\u"+c.charCodeAt(0).toString(16).padStart(4,"0"));return a}var pye="bedrock/",hye="azure/",gye="anthropic/",fye=e=>t=>{let o=Qb(e),n=t,r=`${e.baseUrl}/v1/llm/anthropic/${encodeURIComponent(t)}`;return t.startsWith(pye)?(r=`${e.baseUrl}/v1/llm/provider/bedrock/anthropic/${encodeURIComponent(t.slice(pye.length))}`,new AnthropicLanguageModel(n,{provider:"anthropic.messages",baseURL:r,headers:{...o,"anthropic-version":"2023-06-01","x-api-key":e.apiKey},supportsNativeStructuredOutput:false,supportsStrictTools:false})):(t.startsWith(hye)?r=`${e.baseUrl}/v1/llm/provider/foundry/anthropic/${encodeURIComponent(t.slice(hye.length))}`:t.startsWith(gye)&&(n=t.slice(gye.length),r=`${e.baseUrl}/v1/llm/provider/anthropic/${encodeURIComponent(n)}`),createAnthropic({baseURL:r,headers:o,apiKey:e.apiKey})(n))},yye=e=>t=>Tye(e,t,"openai"),bye=e=>t=>{let o=Qb(e),n=ND(e.xai);return DD(t)&&(n=mye({requestOptions:e.xai,onCompaction:r=>e.onXAINativeCompaction?.({...r,model:t})})),createXai({baseURL:`${e.baseUrl}/v1/llm/provider/xai/${t}`,headers:o,apiKey:e.apiKey,fetch:n}).responses(t)},Sye=e=>t=>Tye(e,t,"azure");function Tye(e,t,o){let n=e.useOpenAIResponsesWebSocket===true&&(o==="openai"||hee(t)),r=n?e.openAIResponsesWebSocketCompactThreshold??Eut(process.env[Aut])??jq(t):e.openAIResponsesCompactThreshold??jq(t),i=a=>e.onOpenAINativeCompaction?.({...a,model:t});return uye(rx({baseURL:`${e.baseUrl}/v1/llm/provider/${o}/${t}`,headers:Qb(e),apiKey:e.apiKey,fetch:n?sye({compactThreshold:r,onCompaction:i}):nye({compactThreshold:r,onCompaction:i})})(t))}function vye(e){return t=>o=>{let n=Qb(t);return rx({baseURL:`${t.baseUrl}/v1/llm/provider/${e}/${o}`,headers:n,apiKey:t.apiKey}).chat(o)}}var Aye=vye("azure/deepseek"),Eye=vye("azure/kimi"),wye=e=>t=>{let o=Qb(e);return rx({baseURL:`${e.baseUrl}/v1/llm/provider/fireworks`,headers:o,apiKey:e.apiKey}).chat(t)},Rye=e=>t=>{let o=Qb(e);return Bq({baseURL:`${e.baseUrl}/v1/llm/provider/openrouter`,headers:o,apiKey:e.apiKey,compatibility:"strict"}).chat(t)},Cye=e=>t=>{let o=Qb(e);return kW({baseURL:`${e.baseUrl}/v1/llm/provider/vertex`,headers:o,apiKey:e.apiKey})(t)};function Eut(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}function Iye(e){let t=Nt.safeParse(e[xG]);return delete e[xG],t.success?t.data:void 0}var ii=class extends ol{agentConfig;apiPathPrefix;supportsAiActionTurbo;constructor(t,o){let n={...yg,...t};wP(n),super(o),this.apiPathPrefix=o.apiPathPrefix??`/${je}`,this.agentConfig=n,this.supportsAiActionTurbo=o.supportsAiActionTurbo??false;}getAgentConfig(){return this.agentConfig}async compactConversationNonNative(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/llm/compact`,{method:"POST",body:{...Cut(t),sessionId:o.sessionId,parentTraceId:o.parentTraceId},signal:o.abortSignal,retries:1,requestTimeoutMs:15e3,extraHeaders:{[gM]:JSON.stringify($q(o))}});return H9.parse(n)}async rankChunksWithAi(t,o){let n={...t,loggerTags:o.loggerTags},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:o.abortSignal});return UZ.parse(r)}async rankChunksWithRag(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:zb,...t},signal:o.abortSignal});return BZ.parse(n)}async getScreenshotFromS3(t){let o=await this.sendRequest(`${this.apiPathPrefix}/s3/visual-diff-screenshot`,{method:"POST",body:{url:t}});return z.string().parse(o)}async getElementLocation(t,o){let n={...t,disableCache:o.disableCache,loggerTags:o.loggerTags,useMemory:o.useMemory,cacheBustReason:o.cacheBustReason,effort:o.effort,agentConfigVersion:this.agentConfig?.locator},r={},i=()=>{let s=Iye(r);s&&o.onEffectiveEffort?.(s);},a=await this.sendRequest(`${this.apiPathPrefix}/web-agent/locate-element`,{method:"POST",body:n,signal:o.abortSignal,responseHeadersObject:r,onFailedRequest:i});return i(),Rre.parse(a)}async getAssertionResult(t,o){let n={...t,disableCache:!!o.disableCache,useConsensus:!!o.useConsensus,attemptNumber:o.attemptNumber,loggerTags:o.loggerTags,useMemory:o.useMemory,effort:o.effort,agentConfigVersion:this.agentConfig?.assertion},r={},i=()=>{let s=Iye(r);s&&o.onEffectiveEffort?.(s);},a=await this.sendRequest(`${this.apiPathPrefix}/web-agent/assertion`,{method:"POST",body:n,signal:o.abortSignal,responseHeadersObject:r,onFailedRequest:i});return i(),_G.parse(a)}async getLintStepResult(t,o){let n={...t,disableCache:!!o.disableCache,loggerTags:o.loggerTags},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/lint/step`,{method:"POST",body:n,signal:o.abortSignal});return wre.parse(r)}async getVisualAssertionResult(t,o){let n={...t,disableCache:!!o.disableCache,useConsensus:!!o.useConsensus,attemptNumber:o.attemptNumber,loggerTags:o.loggerTags,useMemory:o.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/visual-assertion`,{method:"POST",body:n,signal:o.abortSignal});return _G.parse(r)}async getAiActionCommand(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/next-command-dynamic`,{method:"POST",body:{...t,disableCache:o.disableCache,loggerTags:o.loggerTags},signal:o.abortSignal});return Ere.parse(n)}async getMultiturnAiActionCommand(t,o){return await this.sendRequest(`${this.apiPathPrefix}/web-agent/ai-action/next-command`,{method:"POST",body:{...t,disableCache:o.disableCache,loggerTags:o.loggerTags},signal:o.abortSignal})}async getMultiturnAiActionEvaluation(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/ai-action/evaluate`,{method:"POST",body:{...t,disableCache:o.disableCache,loggerTags:o.loggerTags},signal:o.abortSignal});return M$.parse(n)}async getAiActionTurboDecision(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/ai-action/turbo-decision`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal,requestTimeoutMs:3e3,retries:1});return d9.parse(n)}async getReverseMappedDescription(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/reverse-mapped-description`,{method:"POST",body:{...t,disableCache:o.disableCache,loggerTags:o.loggerTags},signal:o.abortSignal});return Cre.parse(n)}async getTextExtraction(t,o){let n={...t,disableCache:o.disableCache,loggerTags:o.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/text-extraction`,{method:"POST",body:n,signal:o.abortSignal});return k$.parse(r)}async getPageSummary(t,o){let n={...t,disableCache:o.disableCache,loggerTags:o.loggerTags},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/page-summary`,{method:"POST",body:n,signal:o.abortSignal});return j9.parse(r)}async getSmartWaitingDecision(t,o){let n={...t,disableCache:o.disableCache,loggerTags:o.loggerTags},r=await this.sendRequest(`${this.apiPathPrefix}/web-agent/smart-waiting`,{method:"POST",body:n,signal:o.abortSignal});return z9.parse(r)}async getKnowledgeSuggestion(t,o){throw new Error("Knowledge suggestion generation is only available on InternalGenerator")}async getTestResultClassification(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/result-classification`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal});return Kw.parse(n)}async getExtractedKeywords(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/extract-keywords`,{method:"POST",body:t,signal:o.abortSignal});return QZ.parse(n)}async getAutohealingProposal(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/autoheal-section`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal});return N9.parse(n)}async getFailureRecoveryProposal(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/failure-recovery`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal});return B9.parse(n)}async getFailureRecoveryPlan(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/failure-recovery-plan`,{method:"POST",body:{...t,loggerTags:o.loggerTags,agentConfigVersion:this.agentConfig?.["failure-recovery"]},signal:o.abortSignal});return F9.parse(n)}async getFailureRecoveryMemory(t,o){try{let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/failure-recovery-memory`,{method:"POST",body:t,retries:1,requestTimeoutMs:5e3});return rte.parse(n)}catch(n){return o.logger.warn({err:n},"Failed to read failure recovery memory"),{failureCount:0}}}async recordFailureRecoveryOutcome(t,o){try{await this.sendRequest(`${this.apiPathPrefix}/web-agent/failure-recovery-memory`,{method:"PATCH",body:t,retries:1,requestTimeoutMs:5e3});}catch(n){o.logger.warn({err:n},"Failed to record failure recovery outcome");}}async getOrgLevelFailureRate(t,o){let n=t.environment?`?environment=${encodeURIComponent(t.environment)}`:"";try{let r=await this.sendRequest(`${this.apiPathPrefix}/org-level-failure-rate${n}`,{method:"GET",retries:1,requestTimeoutMs:5e3});return wM.parse(r)}catch(r){return o.logger.warn({err:r},"Failed to read org-level failure rate"),{skip:false,failed:0,total:0}}}async getIframeRegex(t,o){let n=await this.sendRequest(`${this.apiPathPrefix}/web-agent/iframe-regex`,{method:"POST",body:{...t,loggerTags:o.loggerTags},signal:o.abortSignal});return p9.parse(n)}createAgentTrace(t){let o=randomUUID(),{completionType:n,runId:r,orgId:i,logger:a}=t,s=a.bindings().sessionId,l=async c=>{try{await this.sendRequest(`${this.apiPathPrefix}/traces/result-classification`,{method:"POST",body:{id:o,completionType:n,input:{runId:r},sessionId:s,...c,metadata:{orgId:i,runId:r,...c.metadata}}});}catch(u){a.warn({err:u},"Failed to upsert result classification trace");}};return l({}),{id:o,update:l}}getAnthropicModelFactory(t){return this.buildModelFactory(fye,t)}getModelProviderCandidate(t,o){return t.startsWith("bedrock/")?{id:"anthropic-bedrock",model:this.getAnthropicBedrockModelFactory(o)(t.slice(8))}:t.startsWith("azure/claude-")?{id:"anthropic-foundry",model:this.getAnthropicFoundryModelFactory(o)(t.slice(6))}:t.startsWith("anthropic/")?{id:"anthropic",model:this.getAnthropicModelFactory(o)(t)}:t.startsWith("openrouter/")?{id:"openrouter",model:this.getOpenRouterModelFactory(o)(t.slice(11))}:t.startsWith("fireworks/")?{id:"fireworks",model:this.getFireworksModelFactory(o)(t)}:t.startsWith("xai/")?{id:"xai",model:this.getXAIModelFactory(o)(t.slice(4))}:t.startsWith("vertex/gemini-")?{id:"google-vertex",model:this.getVertexGeminiModelFactory(o)(t.slice(7))}:t.startsWith("azure/")?{id:"azure",model:this.getAzureOpenAIModelFactory(o)(t.slice(6))}:t.startsWith("claude-")?{id:"anthropic",model:this.getAnthropicModelFactory(o)(t)}:{id:"openai",model:this.getOpenAIModelFactory(o)(t)}}getAnthropicBedrockModelFactory(t){let o=this.getAnthropicModelFactory(t);return n=>o(`bedrock/${n}`)}getAnthropicFoundryModelFactory(t){let o=this.getAnthropicModelFactory(t);return n=>o(`azure/${n}`)}getOpenAIModelFactory(t){let{sessionId:o,logger:n,streamType:r,useOpenAIResponsesWebSocket:i,parentTraceId:a}=t;return yye({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:$q(t),sessionId:o,useOpenAIResponsesWebSocket:i,runner:this.runner,parentTraceId:a,onOpenAINativeCompaction:s=>{n.info({promptType:r,nativeCompaction:s},"Native conversation compaction completed");}})}getXAIModelFactory(t){let{logger:o,streamType:n}=t;return this.buildModelFactory(bye,t,{onXAINativeCompaction:r=>{o.info({promptType:n,nativeCompaction:r},"Native conversation compaction completed");}})}getOpenRouterModelFactory(t){return this.buildModelFactory(Rye,t)}getAzureOpenAIModelFactory(t){let{logger:o,streamType:n}=t;return this.buildModelFactory(Sye,t,{onOpenAINativeCompaction:r=>{o.info({promptType:n,nativeCompaction:r},"Native conversation compaction completed");}})}getAzureDeepSeekModelFactory(t){return this.buildModelFactory(Aye,t)}getAzureKimiModelFactory(t){return this.buildModelFactory(Eye,t)}getFireworksModelFactory(t){return this.buildModelFactory(wye,t)}getVertexGeminiModelFactory(t){return this.buildModelFactory(Cye,t)}buildModelFactory(t,o,n){let{sessionId:r,parentTraceId:i,xai:a,useOpenAIResponsesWebSocket:s}=o;return t({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:$q(o),sessionId:r,runner:this.runner,parentTraceId:i,xai:a,useOpenAIResponsesWebSocket:s,...n})}};function $q(e){return {...Wo(e.logger),agentInvocationId:e.agentInvocationId,promptType:e.streamType}}function Cut(e){return {...e,messages:e.messages.map(Gq)}}function Gq(e){return e instanceof Uint8Array||e instanceof ArrayBuffer?Buffer.from(e).toString("base64"):e instanceof URL?e.toString():Array.isArray(e)?e.map(Gq):typeof e!="object"||e===null?e:Object.fromEntries(Object.entries(e).map(([t,o])=>[t,Gq(o)]))}async function FD(e,t,o){let{size:n}=await Un__default.promises.stat(o),r=new URL(e),i=t==="application/zip"?AbortSignal.timeout(wL(n)):void 0,a;if(r.protocol==="http:")a=request;else if(r.protocol==="https:")a=request$1;else throw new Error(`Unsupported signed upload URL protocol: ${r.protocol}`);return new Promise((s,l)=>{let c=Un__default.createReadStream(o),u=new Promise(f=>c.once("close",f)),d,m=0,p=false,h=false,g=f=>{h||(h=true,c.destroy(),d.destroy(),u.then(()=>l(f)));};try{d=a(r,{method:"PUT",signal:i,headers:{"Content-Length":n,"Content-Type":t}},f=>{p=!0;let y=m<n,b=f.socket;c.unpipe(d),c.destroy(),!d.destroyed&&!d.writableEnded&&d.end();let S=f.statusCode??500,A=S===204||S===205||S===304;if(y&&S>=200&&S<300&&!A){h=!0,d.destroy(),f.destroy(),b.destroy(),u.then(()=>l(new Error(`Upload server returned ${S} before the request body was fully written.`)));return}let T=[];f.on("data",v=>T.push(v)),f.on("error",g),f.on("end",()=>{if(h)return;h=!0,d.destroy(),y&&b.destroy();let v=new Headers;for(let[I,C]of Object.entries(f.headers))if(Array.isArray(C))for(let O of C)v.append(I,O);else C!==void 0&&v.set(I,C);let R=A?null:Buffer.concat(T);u.then(()=>{try{s(new Response(R,{headers:v,status:S,statusText:f.statusMessage}));}catch(I){l(I);}});});});}catch(f){c.destroy(),u.then(()=>l(f));return}d.on("error",f=>{p||g(f);}),c.on("data",f=>{m+=Buffer.byteLength(f);}),c.on("error",g),c.pipe(d);})}function _ye(e,t,o,n){return fetch(e,{method:"PUT",body:o,signal:n,headers:{"Content-Type":t}})}var _ut=2e3,so=class extends ol{apiPathPrefix;constructor(t){super(t),this.apiPathPrefix=t.apiPathPrefix??`/${je}`;}getAppUrl(){return Ev(this.baseUrl)}limbarPath(t){return `${this.apiPathPrefix}/limbar/${t}`}async getAuthInfo(){let t;try{t=await this.sendRequest(`/${je}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});}catch(o){throw o instanceof $I?new ae(`Your Momentic API key was rejected (${o.message}). Run your CLI's \`login\` command or set a valid MOMENTIC_API_KEY. If the key was revoked or expired, create a new one at https://app.momentic.ai/settings/api-keys.`,{cause:o}):o instanceof Lo?o.status>=400&&o.status<500?new ae(o.rawError,{cause:o}):new Error(`Momentic server error (HTTP ${o.status}). Please try again in a moment.`,{cause:o}):o instanceof ae?o: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:o})}return jre.parse(t)}async getFeatureFlags(){let t=await this.sendRequest(`/${je}/auth/flags`,{method:"GET",retries:1,requestTimeoutMs:5e3});return $re.parse(t)}async getCliAnnouncements(){let t=await this.sendRequest(`/${je}/announcements`,{method:"GET",retries:1,requestTimeoutMs:5e3});return Wee.parse(t).announcements}async createMoSessionUpload(t,o,n){let r=AbortSignal.timeout(6e4),i=`/${je}/mo/sessions/${encodeURIComponent(t)}/uploads`,a=0,s;for(;!r.aborted;){let l;try{l=await this.sendRequest(i,{method:"POST",body:o,retries:1,requestTimeoutMs:15e3,signal:r});}catch(c){if(r.aborted&&(c===r.reason||c instanceof Error&&c.name==="AbortError")&&s)throw s;if(c instanceof Lo&&c.status===404)throw new ae(`Mo session ${t} was not found.`,{cause:c});if(c instanceof Lo&&c.code==="MO_SANDBOX_NOT_READY"){if(n?.(),s=c,await wb(Math.max(c.retryAfterMs??1e3,100),r),r.aborted)throw c;continue}if(c instanceof Lo&&c.status>=400&&c.status<500||c instanceof Lo&&c.status===fM||c instanceof ae&&!(c instanceof yA)||(s=c instanceof Error?c:void 0,a++,a>=3||r.aborted))throw c;let u=1500*2**(a-1);if(c instanceof yA&&(u=Math.max(u,hi(c,Lo)?.retryAfterMs??0)),await wb(u,r),r.aborted)throw c}return Qte.parse(l)}throw s??r.reason}async createMoSessionDownload(t,o,n){let r;try{r=await this.sendRequest(`/${je}/mo/sessions/${encodeURIComponent(t)}/downloads`,{method:"POST",body:o,retries:3,requestTimeoutMs:15e3,signal:n});}catch(i){throw i instanceof Lo&&i.status===404?new ae(i.rawError,{cause:i}):i}return Xte.parse(r)}async listProductUpdates(t=3){let o=await this.sendRequest(`/${je}/product-updates?limit=${t}`,{method:"GET",retries:1,requestTimeoutMs:5e3});return fie.parse(o).updates}async getQuotaStatus(){let t=await this.sendRequest(`/${je}/billing/check-quota`,{method:"GET",retries:3,requestTimeoutMs:5e3});return zre.parse(t)}async createRemoteBrowserConnection(t){let o=await this.sendRequest(`/${je}/browsers/connection`,{method:"POST",body:{...t?.envName?{envName:t.envName}:{},...t?.runAttemptId?{runAttemptId:t.runAttemptId}:{},...t?.runGroupId?{runGroupId:t.runGroupId}:{},...t?.testId?{testId:t.testId}:{},...t?.testName?{testName:t.testName}:{},...t?.runId?{runId:t.runId}:{},...t?.attemptedProviders?{attemptedProviders:t.attemptedProviders}:{}},retries:3,requestTimeoutMs:12e4});return uie.parse(o)}async tryCreateBrowserFleetAccessToken(t,o){let n;try{n=await this.sendRequest(`/${je}/browsers/token`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4,signal:o});}catch(i){if(i instanceof Lo&&(i.status===400||i.status===404||i.status===409))return null;throw i}let r=cie.parse(n);return "network"in r?r:null}async bulkGetRunStatus(t){let o=await this.sendRequest(`/${je}/runs/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Dre.parse(o)}async getOrgLevelFailureRate(t){let o=t?`?environment=${encodeURIComponent(t)}`:"",n=await this.sendRequest(`/${je}/org-level-failure-rate${o}`,{method:"GET",retries:1,requestTimeoutMs:5e3});return wM.parse(n)}async recordRunOutcomeForFailureRate(t){await this.sendRequest(`/${je}/org-level-failure-rate`,{method:"POST",body:t,retries:1,requestTimeoutMs:5e3});}async getRunExport(t,o){let n=await this.sendRequest(`/${je}/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4,signal:o});return bM.parse(n)}submitInteractiveAgentFeedback(t){try{this.sendRequest(`/${je}/traces/interactive-agent-feedback`,{method:"POST",body:t,retries:1,requestTimeoutMs:2e3}).catch(o=>{});}catch(o){}return Promise.resolve()}async getResultClassificationCacheEntries(t){let o=await this.sendRequest(`/${je}/result-classification-cache`,{method:"POST",body:t,retries:1,requestTimeoutMs:1e4});return _ie.parse(o)}async createResultClassificationCacheEntries(t){await this.sendRequest(`/${je}/result-classification-cache`,{method:"PATCH",body:t,retries:1,requestTimeoutMs:1e4});}async createAiTriageMetrics(t){await this.sendRequest(`/${je}/ai-triage-metrics`,{method:"POST",body:t,retries:1,requestTimeoutMs:3e3});}async getAiTriageExistingFixes(t){let o=await this.sendRequest(`/${je}/ai-triage-metrics/existing-fixes`,{method:"POST",body:t,retries:1,requestTimeoutMs:5e3});return bee.parse(o)}async saveRunClassification(t,o){await this.sendRequest(`/${je}/runs/${encodeURIComponent(t)}/classification`,{method:"PATCH",body:o,retries:3,requestTimeoutMs:1e4});}async uploadRunHealTraceZip(t,o){let n=await this.sendRequest(`/${je}/runs/${encodeURIComponent(t)}/heal-trace/upload-url`,{method:"POST",retries:3,requestTimeoutMs:1e4}),{uploadUrl:r}=SM.parse(n),i=await _ye(r,"application/zip",o,AbortSignal.timeout(wL(o.byteLength)));if(!i.ok)throw new Error(`Failed to upload heal trace: ${await i.text()}`)}async saveRunHealMetadataBatch(t){await this.sendRequest(`/${je}/runs/heal-metadata`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4});}async getTestYAMLExport(t){let o=await this.sendRequest(`/${je}/tests/export`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return xre.parse(o)}async updateStepCaches(t,o){await this.sendRequest(`/${je}/cache`,{method:"PATCH",body:t,extraHeaders:o,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async updateSnapshotCaches(t,o){await this.sendRequest(`/${je}/snapshot-cache`,{method:"PATCH",body:t,extraHeaders:o,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getStepCacheForTest(t,o){let n=await this.sendRequest(`/${je}/cache`,{method:"POST",body:t,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Ore.parse(n)}async getSnapshotCacheForTest(t,o){let n=await this.sendRequest(`/${je}/snapshot-cache`,{method:"POST",body:t,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Pre.parse(n)}async deleteStepCacheEntry(t,o){await this.sendRequest(`/${je}/cache/entry`,{method:"DELETE",body:t,extraHeaders:o,retries:3,requestTimeoutMs:1e4});}async getWebStepCacheMemoryTraces(t){let o=await this.sendRequest(`/${je}/cache/traces`,{method:"POST",body:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return OG.parse(o)}cacheRouteForPlatform(t){switch(t){case "ANDROID":return "android-cache";case "IOS":return "ios-cache"}}async deleteMobileStepCacheEntry({platform:t,body:o,headers:n}){await this.sendRequest(`/${je}/${this.cacheRouteForPlatform(t)}/entry`,{method:"DELETE",body:o,extraHeaders:n,retries:3,requestTimeoutMs:1e4});}async getMobileStepCacheMemoryTraces(t,o){let n=await this.sendRequest(`/${je}/${this.cacheRouteForPlatform(t)}/traces`,{method:"POST",body:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return OG.parse(n)}async updateMobileStepCaches(t){await this.sendRequest(`/${je}/${this.cacheRouteForPlatform(t.platform)}`,{method:"PATCH",body:t.body,extraHeaders:t.headers,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getMobileStepCacheForTest({platform:t,body:o,headers:n}){let r=await this.sendRequest(`/${je}/${this.cacheRouteForPlatform(t)}`,{method:"POST",body:o,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return kre[t](r)}async queueTests(t){let o=await this.sendRequest(`/${je}/tests/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Ire.parse(o)}async uploadScreenshot(t){let o=await this.sendRequest(`/${je}/screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Ure.parse(o)}async uploadOnDemandScreenshot(t){return await this.sendRequest(`/${je}/on-demand-screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${je}/on-demand-screenshots/${t.id}`}}async fetchOnDemandScreenshot(t){let o={};return {data:await this.sendRequest(`/${je}/on-demand-screenshots/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:5e3,responseType:"buffer",responseHeadersObject:o}),contentType:o["content-type"]??"image/jpeg"}}async getAllEnvironments(){let t=await this.sendRequest(`/${je}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Hre.parse(t)}async acquireCacheLock(t,o){let n=await this.sendRequest(`/${je}/result-cache/lock`,{method:"POST",body:t,signal:o,retries:3,requestTimeoutMs:3e4});return Tie.parse(n)}async releaseCacheLock(t){await this.sendRequest(`/${je}/result-cache/lock`,{method:"DELETE",body:{key:t},retries:3,requestTimeoutMs:5e3});}async deleteCacheResult(t){await this.sendRequest(`/${je}/result-cache/entry`,{method:"DELETE",body:t,retries:3,requestTimeoutMs:5e3});}async setCacheResult(t){await this.sendRequest(`/${je}/result-cache/entry`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:5e3});}async getCacheResult(t){try{return await this.sendRequest(`/${je}/result-cache/entry`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3})}catch(o){if(o instanceof Error&&o.message.includes("404"))return null;throw o}}async queueSuiteRuns(t){let o=await this.sendRequest(`/${je}/suites/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Wre.parse(o)}async bulkGetRunGroupStatus(t){let o={runGroupIds:t},n=await this.sendRequest(`/${je}/run-groups/status`,{method:"POST",body:o,retries:3,requestTimeoutMs:5e3});return MZ.array().parse(n)}async getRunGroupWithRuns(t){try{let o=await this.sendRequest(`/${je}/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return vk.parse(o)}catch(o){if(o instanceof Lo&&o.status===404)return null;throw o}}async getRun(t){try{let o=await this.sendRequest(`/${je}/runs/${encodeURIComponent(t)}/metadata`,{method:"GET",retries:3,requestTimeoutMs:1e4});return js.parse(o)}catch(o){if(o instanceof Lo&&o.status===404)return null;throw o}}async getRunsByCommit(t){let n=[];for(let r=1;;r++){let i=await this.listRuns({gitCommitSha:t,includeFailureDetails:true,limit:100,page:r});if(n.push(...i.runs.map(a=>({...a,test:null}))),i.runs.length<100||r>=i.pageCount)break}return n}async getRunGroupRuns(t){let o=await this.sendRequest(`/${je}/run-groups/${encodeURIComponent(t)}/runs`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Yre.parse(o)}async updateGithubPRHealRiskSummary(t,o){await this.sendRequest(`/${je}/run-groups/${encodeURIComponent(t)}/github-pr-heal-risk-summary`,{method:"PATCH",body:o,retries:3,requestTimeoutMs:1e4});}async uploadProposedSteps(t,o){try{await this.sendRequest(`/${je}/test-fragments/`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});}catch(n){o.error({err:n},"Failed to upload proposed steps");}}async reportBillableEvents(t,o){try{await this.sendRequest(`/${je}/billing/events`,{method:"POST",body:o,retries:10,requestTimeoutMs:1e4});}catch(n){t.error({err:n},"Failed to report billable event");}}async fetchTestFragment(t){let o=await this.sendRequest(`/${je}/test-fragments/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return qre.parse(o)}async patchTestFragment(t,o){await this.sendRequest(`/${je}/test-fragments/${t}`,{method:"PATCH",body:o,retries:3,requestTimeoutMs:1e4});}async getPastTestResults(t,o){let n=await this.sendRequest(`/${je}/results/tests/${t}`,{method:"POST",body:o,retries:3,requestTimeoutMs:1e4});return Kre.parse(n)}async listRuns(t,o){let n=await this.sendRequest(`/${je}/results/runs`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4,signal:o});return Jre.parse(n)}async generateTestResultsUploadUrl(){let t=await this.sendRequest(`/${je}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Xre.parse(t)}async startProcessingResultsUpload(t,o){let n=await this.sendRequest(`/${je}/results/uploads/${t}/process`,{method:"POST",body:o,retries:3,requestTimeoutMs:1e4});return Qre.parse(n)}async startExploreTraceUpload(t){let o=await this.sendRequest(`/${je}/explore/trace-uploads`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return Uie.parse(o)}async fetchIconKnowledgeBase(t){try{let o=await this.sendRequest(`/${je}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return kie.parse(o)}catch(o){return t.error({err:o},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(t,o){try{await this.sendRequest(`/${je}/knowledge-base/icons`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});}catch(n){o.error({err:n},"Failed to save new icons to icon knowledge base");}}async retrieveKnowledgeBase({query:t,clientName:o,testId:n,environmentId:r,types:i,agentSubtype:a,limit:s,mode:l,scoreMultiplier:c,scopeBuckets:u,retries:d,signal:m,timeoutMs:p},h){try{let g=await this.sendRequest(`/${je}/knowledge-base/retrieve`,{method:"POST",body:{query:t,clientName:o,testId:n,environmentId:r,types:i,agentSubtype:a,limit:s,mode:l,scoreMultiplier:c,scopeBuckets:u,timeoutMs:p},retries:d??3,requestTimeoutMs:p===void 0?5e3:p+_ut,signal:m});return Q9.parse(g)}catch(g){return h.warn({err:g},"Failed to retrieve from knowledge base"),null}}async createKnowledgeItem(t){let o=await this.sendRequest(`/${je}/knowledge-base/items`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return H$.parse(o)}async getMergeBaseCommitFromGithub(t,o,n,r){let i=new URLSearchParams;i.set("base",n),i.set("head",r);let a=await this.sendRequest(`/${je}/git/github/${t}/${o}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return YC.parse(a)}async compareCommitsFromGithub({owner:t,repo:o,base:n,head:r},i){i?.throwIfAborted();let a=new URLSearchParams;a.set("base",n),a.set("head",r);let s=await this.sendRequest(`/${je}/git/github/${t}/${o}/compare?${a.toString()}`,{signal:i,method:"GET",retries:3,requestTimeoutMs:5e3});return Ste.parse(s)}async listGithubCommitsForPath({owner:t,repo:o,path:n,ref:r,limit:i}){let a=new URLSearchParams;a.set("path",n),a.set("ref",r),a.set("limit",String(i));let s=await this.sendRequest(`/${je}/git/github/${t}/${o}/commits?${a.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Tte.parse(s).commits}async getGithubFileContent({owner:t,repo:o,path:n,ref:r}){let i=new URLSearchParams;i.set("path",n),i.set("ref",r);let a=await this.sendRequest(`/${je}/git/github/${t}/${o}/contents?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return vte.parse(a).content??void 0}async getGithubBranchMetadata(t,o,n,r){r?.throwIfAborted();let i=new URLSearchParams;i.set("branch",n);let a=await this.sendRequest(`/${je}/git/github/${t}/${o}/branch-metadata?${i.toString()}`,{signal:r,method:"GET",retries:3,requestTimeoutMs:1e4});return Ate.parse(a)}async createGithubPullRequest(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/pull-requests`,{method:"POST",body:n,retries:3,requestTimeoutMs:6e4});return cte.parse(r)}async createGithubCommit(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/commits`,{method:"POST",body:n,retries:3,requestTimeoutMs:6e4});return ute.parse(r)}async getGithubPullRequestTemplate(t,o){try{let n=await this.sendRequest(`/${je}/git/github/${t}/${o}/pull-request-template`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Rte.parse(n).template}catch(n){if(n instanceof Lo&&n.status===404)return;throw n}}async getGithubPullRequestForBranch(t,o,n){let r=new URLSearchParams;r.set("branch",n);let i;try{i=await this.sendRequest(`/${je}/git/github/${t}/${o}/pull-requests?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(a){if(a instanceof Lo&&a.status===404)return;throw a}return fte.parse(i)}async getCommitFromGithub(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return YC.parse(r)}async getGithubDefaultBranch(t,o){try{let n=await this.sendRequest(`/${je}/git/github/${t}/${o}/default-branch`,{method:"GET"}),r=z.object({defaultBranch:z.string().min(1)}).safeParse(n);return r.success?r.data.defaultBranch:void 0}catch{return}}async getGithubCollaboratorsWithMergeAccess(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/collaborator-merge-access`,{method:"POST",body:{usernames:n},retries:3,requestTimeoutMs:15e3});return dte.parse(r).usernamesWithMergeAccess}async searchGithubRelatedPullRequests(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/related-pull-requests`,{method:"POST",body:{query:n},retries:2,requestTimeoutMs:6e4});return hte.parse(r)}async getGithubRelatedPullRequestDetails(t,o,n){let r=await this.sendRequest(`/${je}/git/github/${t}/${o}/related-pull-requests/${n}`,{method:"GET",retries:2,requestTimeoutMs:6e4});return z.object({pullRequest:oG}).parse(r).pullRequest}async getGithubCommitDetails(t,o,n){let r=mte.parse({shas:n}),i=await this.sendRequest(`/${je}/git/github/${t}/${o}/commit-details`,{method:"POST",body:r,retries:3,requestTimeoutMs:2e4});return pte.parse(i)}async getMergedBranchFromGithub(t,o,n,r){let i=encodeURIComponent(n),a=await this.sendRequest(`/${je}/git/github/${t}/${o}/${i}/${r}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return DG.parse(a)}async getMergeBaseCommitFromGitlab(t,o,n){let r=new URLSearchParams;r.set("base",o),r.set("head",n);let i=encodeURIComponent(t),a=await this.sendRequest(`/${je}/git/gitlab/${i}/merge-base-commit?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return YC.parse(a)}async getGitlabMergeRequestForBranch(t,o){let n=new URLSearchParams;n.set("branch",o);let r=encodeURIComponent(t),i;try{i=await this.sendRequest(`/${je}/git/gitlab/${r}/merge-requests?${n.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(a){if(a instanceof Lo&&a.status===404)return;throw a}return Ete.parse(i)}async getCommitFromGitlab(t,o){let n=encodeURIComponent(t),r=await this.sendRequest(`/${je}/git/gitlab/${n}/commits/${o}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return YC.parse(r)}async getMergedBranchFromGitlab(t,o,n){let r=encodeURIComponent(o),i=encodeURIComponent(t),a=await this.sendRequest(`/${je}/git/gitlab/${i}/${r}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return DG.parse(a)}async getAgentConfig(){let t=await this.sendRequest(`/${je}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return z.record(z.string(),z.string()).parse(t)}async getOrgSettings(){try{let t=await this.sendRequest(`/${je}/org-settings`,{method:"GET",retries:3,requestTimeoutMs:5e3});return bZ(t)}catch(t){if(t instanceof Lo&&t.status===404)return this.logger.warn({err:t},"Momentic server does not expose org settings; continuing with local project settings"),JT.parse({});throw t}}async getQuarantinedTests(){let t=await this.sendRequest(`/${je}/quarantine`,{method:"GET"});return Zre.parse(t)}async listQuarantinedTests(t){let o=await this.sendRequest(`/${je}/quarantine/details`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return eie.parse(o)}async sendExploreSlackNotification(t){await this.sendRequest(`/${je}/explore/slack-notification`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async recordExplorerSuggestedTests(t){await this.sendRequest(`/${je}/explore/suggested-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async quarantineTest(t,o,n){await this.sendRequest(`/${je}/quarantine`,{method:"POST",body:{testId:t.id,testName:t.name,reason:o,...n??{}},retries:3,requestTimeoutMs:1e4});}async unquarantineTest(t,o,n){await this.sendRequest(`/${je}/quarantine/${t.id}`,{method:"DELETE",body:{testName:t.name,reason:o,...n??{}},retries:3,requestTimeoutMs:1e4});}platformRoute(t){switch(t){case "ANDROID":return "android";case "IOS":return "ios"}}async createAndroidEmulator(t){let o=await this.sendRequest(this.limbarPath("android"),{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return oie.parse(o)}async extendEmulatorTtl(t,o){let n=Date.now();try{await this.sendRequest(this.limbarPath(`${this.platformRoute(t)}/${o}/keepalive`),{method:"POST",retries:3,requestTimeoutMs:15e3}),this.logger.debug({platform:t,emulatorName:o,durationMs:Date.now()-n},"Extended emulator keepalive");}catch(r){this.logger.warn({err:r,platform:t,emulatorName:o,durationMs:Date.now()-n},"Failed to extend emulator keepalive");}}async generateAssetUploadUrl({channel:t,tag:o,alias:n,md5:r,platform:i}){let a={channel:t,tag:o,alias:n,md5:r},s=await this.sendRequest(this.limbarPath(`${this.platformRoute(i)}/upload-url`),{method:"POST",retries:3,body:a,requestTimeoutMs:15e3,logResponse:true});return rie.parse(s)}async deleteAndroidEmulator(t){await this.sendRequest(this.limbarPath(`android/${t}`),{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async getMobileAssets(){let t=await this.sendRequest(this.limbarPath("assets"),{method:"GET",retries:3,requestTimeoutMs:1e4});return iie.parse(t)}async getLimbarAssetDownloadUrl(t,o,n){let r=await this.sendRequest(this.limbarPath(`assets/${t}/${o}/${this.platformRoute(n)}/download-url`),{method:"GET",retries:2,requestTimeoutMs:3e4});return aie.parse(r)}async deleteAsset(t,o,n){await this.sendRequest(this.limbarPath(`assets/${t}/${o}/${this.platformRoute(n)}`),{method:"DELETE",retries:3,requestTimeoutMs:1e4});}async createIosEmulator(t){let o=await this.sendRequest(this.limbarPath("ios"),{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return nie.parse(o)}async deleteIosEmulator(t){await this.sendRequest(this.limbarPath(`ios/${t}`),{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async generateMobileLogcatUploadUrl(t){let o=await this.sendRequest(`/${je}/logcat/mobile/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return jee.parse(o)}async generateMcpSessionTraceUploadUrl(t){let o=await this.sendRequest(`/${je}/mcp/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return SM.parse(o)}};async function Zb(e){let t=process.versions.node,o=parseInt(t.split(".")[0]);(isNaN(o)||o<18)&&(x.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),x.debug(`Identified node version ${t}`);let n=await e.client.getAuthInfo();return x.debug("Got auth info from API"),n}var Th=class{apiClient;constructor(t){this.apiClient=t;}async reportBillableEvents(t,o){await this.apiClient.reportBillableEvents(t,o);}};async function vh({reporter:e,logger:t,feature:o,cached:n,outcome:r,result:i,runId:a,testId:s,testName:l,labels:c,triageTestResults:u=[],sessionId:d,agentInvocationId:m,transactionId:p}){if(o==="triage"&&r===void 0)throw new Error("Triage invocation outcome is required");if(o==="triage"&&(!d||!m))throw new Error("Triage invocation IDs are required");if(o!=="triage"&&u.length>0)throw new Error("Only triage invocations can report test outcomes");let h=new Date().toISOString(),g=new Set(u.map(A=>A.outcome)),f=r;i==="failure"&&(f="error");let y={cached:n,sessionId:d,agentInvocationId:m},b=TM.parse({...y,runId:a,testId:s,testName:l,aiFeature:o,outcome:f,labels:c,hasFixedTest:g.has("fixed"),hasCannotFixTest:g.has("cannot-fix"),hasNoFixNeededTest:g.has("no-fix-needed")}),S=[{event:"ai-agent-invocation",timestamp:h,transactionId:p,properties:b},...u.map(A=>({event:"ai-triage-test-result",timestamp:h,transactionId:`${p}:test-result:${A.testId}`,properties:TM.parse({...y,runId:A.runId,testId:A.testId,testName:A.testName,aiFeature:"triage",outcome:A.outcome,labels:A.labels})}))];try{await e.reportBillableEvents(t,S);}catch(A){t.warn({err:A,feature:o,cached:n,outcome:f},"Failed to report AI agent invocation");}}var Ah=class extends ol{generator;constructor(t,o){super(t),this.generator=o;}async runTemplateMatching(t,o={}){let n=await this.sendRequest(`/${je}/web-agent/template-matching`,{method:"POST",body:t,signal:o?.signal});return h9.parse(n)}async constructIframeRegex(t,o={}){return this.generator.getIframeRegex(t,{abortSignal:o.signal,loggerTags:o.loggerTags})}};var LA=class{constructor(t,o){this.client=t;this.orgId=o;}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let t=this.getApiServerUrl();return Ev(t)}async acquireCacheLock(t,o){return this.client.acquireCacheLock(t,o)}async createOnDemandScreenshot(t,o,n){let{apiServerUrl:r}=await this.client.uploadOnDemandScreenshot({id:t,screenshot:o.toString("base64"),contentType:n});return {apiServerUrl:r,appServerUrl:`${this.getAppServerUrl()}/api/on-demand-screenshots/${t}`,universalHandle:{id:t,contentType:n}}}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,o){return this.client.saveNewIcons(t,o)}};var Out="x-momentic-internal-api-endpoint-secret",BD=class extends so{internalHeaders;constructor({internalApiSecret:t,...o}){super(o),this.internalHeaders=t?{[Out]:t}:{},t&&x.addRedactedValue(t);}async getRunExport(t,o){let n=await this.sendRequest(`/internal/eval/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4,extraHeaders:this.internalHeaders,signal:o});return bM.parse(n)}async getRunGroupWithRuns(t){try{let o=await this.sendRequest(`/internal/eval/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4,extraHeaders:this.internalHeaders});return vk.parse(o)}catch(o){if(o instanceof Lo&&o.status===404)return null;throw o}}};var Eh="v1",Mut=2e3,Oye="sms.lease() and sms.release() are only supported when running tests via the Momentic CLI.",wh=class{httpClient;fakerInstance;fakerSeed;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.fakerSeed=t.fakerSeed,this.supportsLease=t.supportsLease??true,this.resetFaker();}resetFaker(){if(this.fakerSeed===void 0){this.fakerInstance=void 0;return}this.fakerInstance=new Faker({locale:en$1}),this.fakerInstance.seed(this.fakerSeed);}async sendSms(t){return this.httpClient.sendRequest(`/${Eh}/tools/sms/send`,{method:"POST",body:t}).then(()=>{}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to send sms: ${o.message}`)})}async fetchLatestSms(t){return this.httpClient.sendRequest(`/${Eh}/tools/sms/fetchLatest`,{method:"POST",body:t}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):o})}async leasePhoneNumber(t){if(!this.supportsLease)throw new Error(Oye);let o=await this.httpClient.sendRequest(`/${Eh}/tools/sms/lease`,{method:"POST",body:t??{}}).catch(r=>{throw r instanceof Lo?new Error(r.rawError):new Error(`Failed to lease phone number: ${r.message}`)}),n=qee.parse(o);return this.activeLeases.set(n.phoneNumber,{leaseToken:n.leaseToken}),n}async releasePhoneNumber(t){if(!this.supportsLease)throw new Error(Oye);return this.activeLeases.delete(t.phoneNumber),this.httpClient.sendRequest(`/${Eh}/tools/sms/release`,{method:"POST",body:t}).then(()=>{}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to release phone number: ${o.message}`)})}async dispose(){let t=[...this.activeLeases.entries()];this.activeLeases.clear(),await Promise.allSettled(t.map(([o,{leaseToken:n}])=>ye(this.httpClient.sendRequest(`/${Eh}/tools/sms/release`,{method:"POST",body:{phoneNumber:o,leaseToken:n}}),{milliseconds:Mut,fallback:()=>{}})));}async sendEmail(t){return this.httpClient.sendRequest(`/${Eh}/tools/email/send`,{method:"POST",body:t}).then(()=>{}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to send email: ${o.message}`)})}async fetchAllEmails(t){return this.httpClient.sendRequest(`/${Eh}/tools/email/fetchAll`,{method:"POST",body:t}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to fetch all emails: ${o.message}`)})}async fetchLatestEmail(t){return this.httpClient.sendRequest(`/${Eh}/tools/email/fetchLatest`,{method:"POST",body:t}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to fetch latest emails: ${o.message}`)})}async createEmail(){let t=await this.httpClient.sendRequest(`/${Eh}/tools/email/create`,{method:"POST",body:{}}).catch(o=>{throw o instanceof Lo?new Error(o.rawError):new Error(`Failed to create email inbox: ${o.message}`)});return Kee.parse(t)}};var NA=class{constructor(t){this.client=t;}async uploadResultsArchive(t){let{runGroupId:o,archivePath:n,persist:r}=t,{uploadUrl:i,id:a}=await this.client.generateTestResultsUploadUrl(),s=await FD(i,"application/zip",n);if(!s.ok)throw new Error(`Failed to upload test results: ${await s.text()}`);let{runGroupId:l}=await this.client.startProcessingResultsUpload(a,{resultType:"run",runGroupId:o,persist:r});return l}async uploadExploreArchive(t){let{exploreRunId:o,metadata:n,archivePath:r,videos:i}=t,{uploadUrl:a,videoUploadUrls:s}=await this.client.startExploreTraceUpload({exploreRunId:o,metadata:n,videoAssets:i?.map(c=>c.name)});for(let c of i??[]){let u=s?.[c.name];if(!u)throw new Error(`Missing upload URL for video asset ${c.name}`);let d=await FD(u,c.contentType,c.path);if(!d.ok)throw new Error(`Failed to upload explore video ${c.name}: ${await d.text()}`)}let l=await FD(a,"application/zip",r);if(!l.ok)throw new Error(`Failed to upload explore results: ${await l.text()}`)}};function Rh({logger:e,orgId:t,client:o,gitMetadata:n,regenerateCache:r,alwaysSaveCache:i,noCache:a,isolateCachesByEnvironment:s=false,bustOldestCachePercentage:l}){return a?new CM:new Vq(e,t,o,n,{regenerateCache:r,alwaysSaveCache:i,bustOldestCachePercentage:l,isolateCachesByEnvironment:s})}var Vq=class{constructor(t,o,n,r,i){this.orgId=o;this.client=n;let{regenerateCache:a,alwaysSaveCache:s,bustOldestCachePercentage:l,isolateCachesByEnvironment:c}=i,{gitBranchName:u,gitProtectedBranches:d}=r;t.info({options:i,gitBranchName:u,gitProtectedBranches:d},"Cache storage initialization options"),this.cacheHeaders=yM(r),this.isolateCachesByEnvironment=c,this.readCaches=!a;let m=u&&d.includes(u);s||!m?this.writeCaches=true:this.writeCaches=false,m||(this.bustOldestCachePercentage=l);}cacheHeaders;readCaches;writeCaches;isolateCachesByEnvironment;bustOldestCachePercentage;async saveStepCacheEntries({entries:t,logger:o}){if(!this.writeCaches){o.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:zG(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(n){o.error({err:n},"Failed to save step cache entries");}}async saveSnapshotCacheEntries({entries:t,logger:o}){if(t.length!==0)try{await this.client.updateSnapshotCaches({entries:zG(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(n){o.error({err:n},"Failed to save snapshot cache entries");}}async deleteStepCacheEntry({logger:t,testId:o,key:n,environment:r}){await this.client.deleteStepCacheEntry({testId:o,key:n,environment:this.isolateCachesByEnvironment?r:void 0},this.cacheHeaders),t.debug({testId:o,key:n},"Deleted step cache entry");}async resolveStepCacheEntries(t){let{restoredIdentity:o,restoredStepLists:n}=await this.restoreAndPersistStepIdentity(t);if(!this.readCaches)return t.logger.debug("Skipping cache resolution because of regenerate flag"),{restoredStepLists:n};let{steps:r,beforeSteps:i,afterSteps:a}=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 d=Object.entries(s).map(([h,g])=>({key:h,time:g.value.cache?.updatedAt?.getTime()??0}));d.sort((h,g)=>h.time-g.time);let m=d.length,p=Math.max(1,Math.floor(m*this.bustOldestCachePercentage/100));d.slice(0,p).forEach(({key:h})=>{delete s[h];}),t.logger.info({nCachesToBust:p,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:m},"Busted oldest caches");}let l={totalSteps:0,cacheKeysHit:[],cacheKeysMissed:[],uniqueKeysHit:[],cacheMissSamples:[]};for(let d of [r,i,a]){if(!d)continue;let m=of({steps:d,stepCacheEntries:s,logger:t.logger});l.totalSteps+=m.totalSteps,l.cacheKeysHit.push(...m.cacheKeysHit),l.cacheKeysMissed.push(...m.cacheKeysMissed),l.uniqueKeysHit.push(...m.uniqueKeysHit),l.cacheMissSamples.push(...m.cacheMissSamples);}o&&Nut({cacheResolutionStats:l,logger:t.logger,restoredIdentity:o,schemaVersion:t.schemaVersion,testId:t.testId});let c=["platform:web","source:local",`fileFormat:${t.useSnapshotIdentityCache?"v2":"v1"}`,`snapshotIdentityCache:${t.useSnapshotIdentityCache}`,`orgId:${this.orgId}`,"cliVersion:3.62.3"];if(zo.increment("step_cache_resolution",l.cacheKeysHit.length,[...c,"outcome:hit"]),zo.increment("step_cache_resolution",l.cacheKeysMissed.length,[...c,"outcome:miss"]),zo.increment("step_cache_resolution",l.totalSteps,[...c,"outcome:total"]),!this.writeCaches)return t.logger.debug("Skipping cache last used at update because branch is protected"),{restoredStepLists:n};let{cachesToSave:u}=await sr({stepLists:t.stepLists,useSnapshotIdentityCache:false,cacheCreationParams:{environment:t.environment,testId:t.testId,orgId:this.orgId}});return this.saveStepCacheEntries({entries:u,logger:t.logger}),{restoredStepLists:n}}async restoreAndPersistStepIdentity(t){let o=t.useSnapshotIdentityCache?await this.tryRestoreStepIdsFromSnapshot(t):void 0;if(!o)return {restoredIdentity:void 0,restoredStepLists:void 0};let{snapshotCachesToSave:n}=await sr({stepLists:t.stepLists,useSnapshotIdentityCache:true,cacheCreationParams:{environment:t.environment,testId:t.testId,orgId:this.orgId}});return this.saveSnapshotCacheEntries({entries:n,logger:t.logger}),{restoredIdentity:o,restoredStepLists:structuredClone(o.stepLists)}}async tryRestoreStepIdsFromSnapshot(t){try{return await this.restoreStepIdsFromSnapshot(t)}catch(o){t.logger.warn({err:o,testId:t.testId},"Failed to restore step ids from snapshot cache; proceeding without identity cache"),zo.increment("step_cache_resolution",1,["platform:web","source:local","fileFormat:v2","snapshotIdentityCache:true",`orgId:${this.orgId}`,"cliVersion:3.62.3","outcome:identity_restore_error"]);return}}async restoreStepIdsFromSnapshot(t){let{logger:o,testId:n}=t,r=await this.client.getSnapshotCacheForTest({testId:n,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders);for(let s of r){if(!s.schema_version)continue;let l=q1(s.schema_version),c=q1(qt);if(l&&c&&l.compare(c)>0){o.warn(`Snapshot cache for test ${n} was written at schema version ${s.schema_version}, which is newer than this CLI's latest (${qt}). Please update your momentic package version. Skipping identity restoration from snapshot cache.`);return}}let i=eN({entries:r,orgId:this.orgId,testId:n,logger:o}),a=ZL({currentStepLists:t.stepLists,previousSnapshot:i.testSnapshot,previousModuleSnapshots:i.moduleSnapshots,generateUuid:randomUUID});return t.stepLists.steps.splice(0,t.stepLists.steps.length,...a.stepLists.steps),t.stepLists.beforeSteps=a.stepLists.beforeSteps,t.stepLists.afterSteps=a.stepLists.afterSteps,o.debug({snapshotEntries:r.length,testSnapshotHit:!!i.testSnapshot,moduleSnapshots:Array.from(i.moduleSnapshots.keys()),mintedSteps:a.stats.mintedSteps,stats:a.stats,moduleRestoreResults:a.moduleRestoreResults.map(({moduleId:s,snapshotHit:l,stats:c})=>({moduleId:s,snapshotHit:l,stats:c}))},"Restored step ids from snapshot cache"),a}};function Nut({cacheResolutionStats:e,logger:t,restoredIdentity:o,schemaVersion:n,testId:r}){let i=e.cacheKeysHit.length,a=e.cacheKeysMissed.length,s=i+a,l=s>0?Math.round(a/s*1e3)/10:0,c=o.stats.matchedSteps+o.stats.mintedSteps,u=c>0?Math.round(o.stats.mintedSteps/c*1e3)/10:0,d=o.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})),m=o.stats.mintedSteps>=5&&u>=25,p=m||o.stats.bustedConditionals>0||d.some(({stats:g})=>g.mintedSteps>=5||g.bustedConditionals>0),h={cacheHits:i,cacheMissRate:l,cacheMisses:a,cacheMissSamples:e.cacheMissSamples.slice(0,10),hasHighMintRate:m,identityMintRate:u,moduleIdentityIssueCount:d.length,moduleIdentityIssues:d,schemaVersion:n,snapshotIdentityCache:true,stepIdentityStats:o.stats,testId:r,totalCacheableSteps:e.totalSteps};if(!p){t.debug(h,"V2 cache resolution completed");return}t.warn(h,"V2 cache resolution degraded");}async function cl({project:e,apiClient:t,classificationOverrides:o}){let{classification:n,healing:r,explore:i}=(await Dut(t))?.ai??{},a=But({flags:o,config:e.config.ai?.classification,cloudCategories:n?.categories}),s={...e.config.ai};return o?.disabled&&(s.aiFailureAnalysis=false),{...e,config:{...e.config,ai:{...s,classification:a,healing:r,explore:i}}}}async function Dut(e){try{return await e.getOrgSettings()}catch(t){if(!Fut(t))throw t;x.warn({err:t},"Could not load organization settings from Momentic. Continuing with local project configuration.");return}}function Fut(e){return e instanceof Lo?e.status>=500:e instanceof Ua||fI(e)}function But({flags:e,config:t,cloudCategories:o}){if(!(!t&&!o))return {enabled:e?.disabled?false:t?.enabled??false,overrideExitCode:e?.overrideExitCode??t?.overrideExitCode??RQ,categories:o??Tl}}var Pye="golden/visual-diff",kye="reports",Ed="test-results";var Uut=z.object({width:z.number(),height:z.number()}),FA=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;apiClient;constructor(t,o,n){let r=Cn__default.join(t.rootDir,t.config.goldenFileDir??Pye);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=n,this.apiClient=o;}async prepareGoldenScreenshotForComparison(t,o,n){if(v8(o.screenshot?.data))return {buffer:(await this.apiClient.fetchOnDemandScreenshot(o.screenshot.data.id)).data,width:o.screenshot.width,height:o.screenshot.height};if(o.screenshot?.data?.startsWith("https://")){let a=await fetch(o.screenshot.data);return {buffer:Buffer.from(await a.arrayBuffer()),width:o.screenshot.width,height:o.screenshot.height}}let r=o.screenshot?.data;r||(r=Cn__default.join(this.defaultGoldenScreenshotDir,`${o.id}.jpg`));let i=`${r}.metadata.json`;if(this.regenerateGoldenFiles)return Un__default.mkdirSync(Cn__default.dirname(r),{recursive:true}),Un__default.writeFileSync(r,n.buffer),Un__default.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(Un__default.existsSync(r)){let a=Un__default.readFileSync(r),s=Uut.parse(JSON.parse(Un__default.readFileSync(i,"utf-8")));return {buffer:a,width:s.width,height:s.height}}else throw new ie("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${r}`)}};var Lye=["GIT_SSH","GIT_SSH_COMMAND","GIT_SSH_VARIANT","GIT_ASKPASS","GIT_PROXY_COMMAND","GIT_TERMINAL_PROMPT","SSH_ASKPASS"],Mye=new Set(Lye),zut=new Set(["EDITOR","VISUAL","PAGER","PREFIX"]);function Hut(e,t=process.platform){let o={};for(let[n,r]of Object.entries(e)){let i=n.toUpperCase(),a=t==="win32"&&Mye.has(i)?i:n;r!==void 0&&!zut.has(i)&&(!i.startsWith("GIT_")||Mye.has(a))&&(o[a]=r);}return o.LC_ALL="C",o.LANG="C",o}function Ai(e,t,o=true){t?.throwIfAborted();let n=Hut(process.env);return simpleGit({baseDir:e??process.cwd(),abort:t,trimmed:o,allowEnvironment:Lye,unsafe:{allowUnsafeAskPass:!!(n.GIT_ASKPASS||n.SSH_ASKPASS),allowUnsafeGitProxy:!!n.GIT_PROXY_COMMAND,allowUnsafeSshCommand:!!(n.GIT_SSH||n.GIT_SSH_COMMAND)}}).env(n)}var Dye=3e3,ra=Ai();async function Kq(e,t,o){try{return await Ai(e,o).revparse(t)}catch(n){if(o?.throwIfAborted(),zye(n))return;throw n}}async function Eu(e,t){return Kq(e,["--show-toplevel"],t)}async function BA(e){let t=await Eu(e);if(!t)return;let o=Cn__default.relative(t,e);if(!(o.startsWith("..")||Cn__default.isAbsolute(o)))return o===""?".":o}async function Fye(e){return Kq(e,["HEAD"])}async function Bye(e){try{return (await Ai(e).revparse(["--is-shallow-repository"])).trim()==="true"}catch{return false}}async function Uye(e){return Kq(e,["--abbrev-ref","HEAD"])}async function UA({cwd:e,base:t,head:o,logger:n,abortSignal:r}){try{let i=(await Ai(e,r).raw(["merge-base",t,o])).trim();if(i.length>0)return i;n.warn({base:t,head:o},"git merge-base returned empty");}catch(i){r?.throwIfAborted(),n.warn({err:i,base:t,head:o},"git merge-base failed");}}function Yq(){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 jA({client:e,repository:t,base:o,head:n,logger:r,abortSignal:i}){let a=Nr(t);if(a)try{i?.throwIfAborted();let s=await e.compareCommitsFromGithub({owner:a.owner,repo:a.repo,base:o,head:n},i);return s.commits.length===0?void 0:s}catch(s){i?.throwIfAborted(),r.warn({err:s,repository:t,base:o,head:n},"remote commit compare failed");return}}async function Au(e){let{logger:t,operation:o,fn:n,context:r}=e,i=Date.now();try{return await n()}finally{let a=Date.now()-i;a>Dye&&!process.env.CI&&t.warn({operation:o,durationMs:a,thresholdMs:Dye,...r??{}},"[timing] slow git metadata operation");}}function Gm(e){if(e)try{let t=new Date(e);return isNaN(t.getTime())?void 0:t}catch{return}}async function jye(e,t){let o=await ur(e,t.raw(["config","--null","--list"])),n={};if(!o)return n;for(let r of o.split("\0")){let i=r.indexOf(`
371
371
  `);if(i===-1)continue;let a=r.slice(0,i),s=r.slice(i+1).trim();n[a]=s;}return n}function mx(e){if(e.startsWith("git@")){let t=e.split(":");if(t.length===2){let o=t[1].replace(".git","").split("/");if(o.length===2){let n=o[0],r=o[1];return `${n}/${r}`}}}else if(e.startsWith("http")||e.startsWith("https")){let o=new URL(e).pathname.split("/").filter(Boolean);if(o.length>=2){let n=o[0],r=o[1].replace(".git","");return `${n}/${r}`}}}var $ut=["not a git repository","ENOENT","detected dubious ownership","does not have any commits yet","ambiguous argument","Not a valid object name","Needed a single revision","No such ref"];function zye(e){return e instanceof Error?$ut.some(t=>e.message.includes(t)):false}async function ur(e,t){try{return (await t).trim()}catch(o){if(zye(o))return;e.error({err:o},"Failed to run git command");return}}async function Wa(e,t,o){if(e)try{return (await Ai(t,o).revparse([e]))?.trim()||void 0}catch{o?.throwIfAborted();return}}async function px(e){let t=await Wa(e);return t||await Wa(`origin/${e}`)}function Hye(e,t){return e.ciProvider==="GithubActions"&&e.gitBranchName!==void 0&&e.gitCommitSha!==void 0&&/^refs\/pull\/\d+\/merge$/.test(process.env.GITHUB_REF??"")&&process.env.GITHUB_HEAD_REF===e.gitBranchName&&process.env.GITHUB_SHA===t}function $ye(){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 Gut(e){let[t,o,n]=await Promise.all([ur(e,ra.show(["--no-patch","--format=%ci"])),ur(e,ra.show(["-s","--pretty=%B"])),ur(e,ra.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?Gm(t):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:r,gitCommitMessage:o,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID,ciBuildUrl:r&&process.env.GITHUB_RUN_ID?`${r}/actions/runs/${process.env.GITHUB_RUN_ID}`:void 0,ciWorkflowName:process.env.GITHUB_WORKFLOW}}async function Vut(e){let[t,o,n]=await Promise.all([ur(e,ra.listRemote(["--get-url","origin"])),ur(e,ra.show(["-s","--pretty=%B"])),ur(e,ra.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?Gm(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:t,gitCommitMessage:o,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`,ciBuildUrl:process.env.CI_PIPELINE_URL,ciWorkflowName:process.env.CI_PIPELINE_NAME}}async function Wut(e){let[t,o,n,r]=await Promise.all([ur(e,ra.show(["--no-patch","--format=%ci"])),ur(e,ra.listRemote(["--get-url","origin"])),ur(e,ra.show(["-s","--pretty=%B"])),ur(e,ra.show(["-s","--pretty=%an"]))]),a=process.env.CIRCLE_REPOSITORY_URL?.trim()||void 0||o||void 0,s=a?.includes("github.com")??false,l=a?.includes("gitlab.com")??false,c=a?mx(a):void 0;return {ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:t?Gm(t):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:a,gitCommitMessage:n,gitCommitAuthorName:r,githubRepository:s?c:void 0,gitlabProjectPath:l?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID,ciBuildUrl:process.env.CIRCLE_WORKFLOW_ID?`https://app.circleci.com/pipelines/workflows/${process.env.CIRCLE_WORKFLOW_ID}`:void 0}}async function qut(e){let[t,o,n]=await Promise.all([ur(e,ra.show(["--no-patch","--format=%ci"])),ur(e,ra.show(["-s","--pretty=%B"])),ur(e,ra.show(["-s","--pretty=%an"]))]),r=process.env.BUILDKITE_REPO,i=r?.includes("github.com"),a=r?.includes("gitlab.com"),s=r?mx(r):void 0;return {ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:t?Gm(t):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:r,gitCommitMessage:o,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`,ciBuildUrl:process.env.BUILDKITE_BUILD_URL,ciWorkflowName:process.env.BUILDKITE_PIPELINE_NAME}}async function Kut(e){let[t,o,n]=await Promise.all([ur(e,ra.show(["--no-patch","--format=%ci"])),ur(e,ra.show(["-s","--pretty=%B"])),ur(e,ra.show(["-s","--pretty=%an"]))]),r=process.env["Build.Repository.Uri"],i=r?.includes("github.com"),a=r?.includes("gitlab.com"),s=r?mx(r):void 0,l=process.env["Build.SourceBranch"],c=l?.startsWith("refs/heads/")?l:process.env["Build.SourceBranchName"];return {ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:t?Gm(t):void 0,gitBranchName:NC(process.env["System.PullRequest.SourceBranch"]??c),gitOriginUrl:r,gitCommitMessage:o,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function Gye(e,t,o,n="full"){let r=Ai(o?.repoDir),[i,a,s,l,c]=await Promise.all([Yut(e,r,n),ur(e,r.revparse(["--abbrev-ref","HEAD"])),ur(e,r.listRemote(["--get-url","origin"])),t?ur(e,r.raw(["merge-base","--fork-point",t])):Promise.resolve(void 0),n==="full"?jye(e,r):Promise.resolve(void 0)]),u=i.sha??await ur(e,r.revparse(["HEAD"])),d=s??c?.["remote.origin.url"]??await ur(e,r.raw(["config","--get","remote.origin.url"])),m=l||(t?await ur(e,r.raw(["merge-base",t,"HEAD"])):void 0),p=m?await ur(e,r.show(["--no-patch","--format=%cI",m])):void 0,h=d?.includes("github.com"),g=d?.includes("gitlab.com"),f=d?mx(d):void 0,y=c?.["user.email"]||void 0,b=c?.["user.name"]||void 0,S=c?.["user.username"]||void 0,A=c?.["github.user"]||void 0,T=S??A??void 0;return {ciProvider:"none",gitCommitSha:u,gitCommitShaShort:i.shaShort,gitBranchName:a,gitOriginUrl:d,gitCommitTimestamp:Gm(i.timestamp),gitCommitMessage:i.message,gitCommitAuthorName:i.authorName,gitLocalUsername:T,gitLocalEmail:y,gitLocalName:b,lastCommitOnMainSha:m,lastCommitOnMainTimestamp:p?Gm(p):void 0,githubRepository:h?f:void 0,gitlabProjectPath:g?f:void 0,pipelineId:void 0}}async function Yut(e,t,o){let n=o==="full"?"%H%x00%h%x00%cI%x00%an%x00%B":"%H%x00%cI",r=await ur(e,t.raw(["log","-1",`--format=${n}`,"HEAD"]));if(!r)return {};if(o==="cache"){let[u,d]=r.split("\0");return {sha:u||void 0,timestamp:d||void 0}}let[i,a,s,l,...c]=r.split("\0");return {sha:i||void 0,shaShort:a||void 0,timestamp:s||void 0,authorName:l||void 0,message:c.join("\0")||void 0}}async function Jut(e){let[t,o]=await Promise.all([ur(e,ra.show(["--no-patch","--format=%ci"])),ur(e,ra.show(["-s","--pretty=%an"]))]),n=process.env.GIT_REPOSITORY_URL,r=n?.includes("github.com"),i=n?.includes("gitlab.com"),a=n?mx(n):void 0;return {ciProvider:"Bitrise",gitCommitSha:process.env.BITRISE_GIT_COMMIT,gitCommitShaShort:process.env.BITRISE_GIT_COMMIT?.slice(0,6),gitCommitTimestamp:t?Gm(t):void 0,gitBranchName:process.env.BITRISE_GIT_BRANCH,gitOriginUrl:n,gitCommitMessage:process.env.BITRISE_GIT_MESSAGE,gitCommitAuthorName:o,githubRepository:r?a:void 0,gitlabProjectPath:i?a:void 0,pipelineId:`${process.env.BITRISE_APP_SLUG}:${process.env.BITRISE_BUILD_SLUG}`,ciBuildUrl:process.env.BITRISE_BUILD_URL,ciWorkflowName:process.env.BITRISE_TRIGGERED_WORKFLOW_TITLE}}async function Xut(){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 Qut(){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:Gm(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:Gm(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}}function UD({project:e,resolvedMainBranch:t}){e.config.gitMainBranch||x.warn(t?` gitMainBranch is not set in momentic.config.yaml; using "${t}" from the checkout's origin/HEAD. Set it explicitly if that is not your main branch.`:" gitMainBranch is not set in momentic.config.yaml and could not be inferred from the checkout, so comparisons against the main branch are an estimate. Set it to get accurate results.");}async function eS(e){try{let t=(await Ai(e).raw(["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])).trim(),o="refs/remotes/origin/";return t.startsWith(o)?t.slice(o.length):void 0}catch{return}}async function Zut(e){let t=[...e.config.gitProtectedBranches??[]];return e.config.gitMainBranch&&t.push(e.config.gitMainBranch),{gitMainBranch:e.config.gitMainBranch??await eS(e.rootDir),gitProtectedBranches:t}}async function wu(e,t,o){let n=$ye();if(!n)return Gye(e,t,o);switch(n){case "GithubActions":return Gut(e);case "GitlabCI":return Vut(e);case "CircleCI":return Wut(e);case "Buildkite":return qut(e);case "AzureDevOps":return Kut(e);case "GCPCloudBuild":return Xut();case "Bitrise":return Jut(e);case "Custom":return Qut()}}async function Jq(e,t){let o=await jye(e,Ai(t));return {gitLocalUsername:o["user.username"]??o["github.user"]??void 0,gitLocalEmail:o["user.email"]||void 0,gitLocalName:o["user.name"]||void 0}}async function edt(e,t,o,n,r){let i=n,a=n.gitCommitSha;if(!a)return i;if(!i.gitCommitTimestamp||r==="full"&&(!i.gitCommitAuthorName||!i.gitCommitMessage))try{let c=await Au({logger:e,operation:"getRemoteMetadataFromGitlab.getCommitFromGitlab",fn:()=>t.getCommitFromGitlab(o,a),context:{projectPath:o,gitCommitSha:a}});c&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??c.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??c.author.name,gitCommitMessage:i.gitCommitMessage??c.message});}catch(c){e.warn({err:c},"Failed to get commit from Gitlab");}let l=n.gitMainBranch;if(l&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let c=await Au({logger:e,operation:"getRemoteMetadataFromGitlab.getMergeBaseCommitFromGitlab",fn:()=>t.getMergeBaseCommitFromGitlab(o,l,a),context:{projectPath:o,mainBranch:l}});i={...i,lastCommitOnMainSha:c.sha,lastCommitOnMainTimestamp:c.committer.date};}catch(c){e.warn({err:c},"Failed to get merge base commit from Gitlab");}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!i.mergedGitBranchName){let c=n.gitBranchName;try{let u=await Au({logger:e,operation:"getRemoteMetadataFromGitlab.getMergedBranchFromGitlab",fn:()=>t.getMergedBranchFromGitlab(o,c,a),context:{projectPath:o,branchName:c,gitCommitSha:a}});u.mergedBranch&&(i={...i,mergedGitBranchName:u.mergedBranch});}catch(u){e.warn({err:u},"Failed to get merged branch from Gitlab");}}return i}async function tdt(e,t,o,n,r,i){let a=r,s=r.gitCommitSha;if(!s)return a;if(!a.gitCommitTimestamp||i==="full"&&(!a.gitCommitAuthorName||!a.gitCommitMessage))try{let u=await Au({logger:e,operation:"getRemoteMetadataFromGitHub.getCommitFromGithub",fn:()=>t.getCommitFromGithub(o,n,s),context:{owner:o,repo:n,gitCommitSha:s}});u&&(a={...a,gitCommitTimestamp:a.gitCommitTimestamp??u.committer.date,gitCommitAuthorName:a.gitCommitAuthorName??u.author.name,gitCommitMessage:a.gitCommitMessage??u.message});}catch(u){e.warn({err:u},"Failed to get commit from GitHub");}let c=r.gitMainBranch;if(c&&(!a.lastCommitOnMainSha||!a.lastCommitOnMainTimestamp))try{let u=await Au({logger:e,operation:"getRemoteMetadataFromGitHub.getMergeBaseCommitFromGithub",fn:()=>t.getMergeBaseCommitFromGithub(o,n,c,s),context:{owner:o,repo:n,mainBranch:c}});a={...a,lastCommitOnMainSha:u.sha,lastCommitOnMainTimestamp:u.committer.date};}catch(u){e.warn({err:u},"Failed to get merge base commit from GitHub");}if(r.gitBranchName&&r.gitBranchName===r.gitMainBranch&&!a.mergedGitBranchName){let u=r.gitBranchName;try{let d=await Au({logger:e,operation:"getRemoteMetadataFromGitHub.getMergedBranchFromGithub",fn:()=>t.getMergedBranchFromGithub(o,n,u,s),context:{owner:o,repo:n,branchName:u,gitCommitSha:s}});d.mergedBranch&&(a={...a,mergedGitBranchName:d.mergedBranch});}catch(d){e.warn({err:d},"Failed to get merged branch from GitHub");}}return a}async function odt(e,t,o,n){try{if(o.githubRepository){let{owner:r,repo:i}=Cte(o.githubRepository);return await Au({logger:e,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitHub",fn:()=>tdt(e,t,r,i,o,n),context:{githubRepository:o.githubRepository}})}else if(o.gitlabProjectPath){let r=o.gitlabProjectPath;return await Au({logger:e,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitlab",fn:()=>edt(e,t,r,o,n),context:{gitlabProjectPath:r}})}}catch(r){e.warn({err:r},"Failed to get remote git metadata");}return o}async function Vye(e,t,o,n){let r=n==="full"?"getGitMetadata":"getGitMetadataForCache",i={},a={gitMainBranch:o.config.gitMainBranch};return Au({logger:e,operation:`${r}.total`,fn:async()=>{let[s,l]=await Promise.all([Au({logger:e,operation:`${r}.getConfiguredGitMetadata`,fn:()=>Zut(o),context:{projectConfigPath:o.configFilePath}}),Au({logger:e,operation:`${r}.getEnvironmentGitMetadata`,fn:async()=>{let d=$ye()?await wu(e,o.config.gitMainBranch,{repoDir:o.rootDir}):await Gye(e,o.config.gitMainBranch,{repoDir:o.rootDir},n);return a.ciProvider=d.ciProvider,d},context:a})]),c={...s,...l};i.gitBranchName=c.gitBranchName,i.githubRepository=c.githubRepository,i.gitlabProjectPath=c.gitlabProjectPath,(!c.lastCommitOnMainSha||!c.lastCommitOnMainTimestamp)&&c.gitBranchName===s.gitMainBranch&&(c.lastCommitOnMainSha=c.gitCommitSha,c.lastCommitOnMainTimestamp=c.gitCommitTimestamp);let u=await Au({logger:e,operation:`${r}.getRemoteMetadataIfNeeded`,fn:()=>odt(e,t,c,n),context:{githubRepository:c.githubRepository,gitlabProjectPath:c.gitlabProjectPath,gitBranchName:c.gitBranchName}});return {...s,...l,...u}},context:i})}async function Wye(e){try{let t=await Ai(e).remote(["show","origin"]);return t?t.match(/HEAD branch: (.*)$/m)?.[1]?.trim():void 0}catch{return}}async function qye(){try{return (await ra.revparse(["--is-inside-work-tree"])).trim()==="true"}catch{return false}}var ux,dx;async function Kye(e,t){let o=Ai(t.rootDir),[n,r]=await Promise.all([o.raw(["symbolic-ref","--short","-q","HEAD"]).then(s=>s.trim()||void 0).catch(()=>{}),ur(e,o.revparse(["--verify","HEAD"]).then(s=>s.trim()))]);if(!r)return;let i=`${t.configFilePath}:${t.config.gitMainBranch}:${t.config.gitProtectedBranches?.join(",")}`,a=n?`branch:${n}`:"detached";return `${t.rootDir}:${a}:${r}:${i}`}async function Of(e,t,o){let n=await Kye(e,o);if(n&&ux?.snapshotKey===n)return e.debug("Using cached git metadata"),await ux.value;let r=Vye(e,t,o,"full");n&&(ux={snapshotKey:n,value:r});try{return await r}catch(i){throw ux?.value===r&&(ux=void 0),i}}async function Vm(e,t,o){let n=await Kye(e,o);if(n&&dx?.snapshotKey===n)return e.debug("Using cached git metadata for cache resolution"),await dx.value;let r=Vye(e,t,o,"cache").then(i=>({gitMainBranch:i.gitMainBranch,gitProtectedBranches:i.gitProtectedBranches,gitBranchName:i.gitBranchName,gitCommitTimestamp:i.gitCommitTimestamp,lastCommitOnMainSha:i.lastCommitOnMainSha,lastCommitOnMainTimestamp:i.lastCommitOnMainTimestamp,mergedGitBranchName:i.mergedGitBranchName}));n&&(dx={snapshotKey:n,value:r});try{return await r}catch(i){throw dx?.value===r&&(dx=void 0),i}}var rdt=z.object({pull_request:z.object({body:z.string().nullable().optional()}).optional()});async function jD({client:e,gitMetadata:t,logger:o}){let n=process.env.CI_MERGE_REQUEST_DESCRIPTION;if(n&&n.trim().length>0)return n;let r=await idt(o);if(r!==void 0)return r;let i=t.gitBranchName;if(i)try{if(t.githubRepository){let a=Nr(t.githubRepository);if(!a)return;let s=await e.getGithubPullRequestForBranch(a.owner,a.repo,i);return s?.body?.trim()?s.body:void 0}if(t.gitlabProjectPath){let a=await e.getGitlabMergeRequestForBranch(t.gitlabProjectPath,i);return a?.description?.trim()?a.description:void 0}}catch(a){o.warn({err:a},"Failed to load change request description from remote git metadata");}}async function idt(e){let t=process.env.GITHUB_EVENT_PATH;if(t)try{let o=JSON.parse(await readFile(t,"utf8")),r=rdt.parse(o).pull_request?.body;return r?.trim()?r:void 0}catch(o){e.warn({err:o,eventPath:t},"Failed to load change request description from GitHub event");return}}var adt=1024*1024;async function Pf({absoluteRepoRoot:e,baseRef:t="HEAD",candidateRepoRelativePaths:o}){gx(e);let n=simpleGit(e),r=o?hx(o):[];if(o&&r.length===0)return [];for(let l of r)eK({absoluteRepoRoot:e,repoRelativePath:l});let i=r.map(Qq),[a,s]=await Promise.all([n.diff(["--name-only","--diff-filter=ACDMRTUXB",t,"--",...i]),n.raw(["ls-files","--others","--exclude-standard","--",...i])]);return sdt(hx([...Yye(a),...Yye(s)]))}function sdt(e){return e.filter(Ih)}function Ih(e){let t=Ch.basename(e);return e.endsWith(".test.yaml")||e.endsWith(".module.yaml")||t===Dl||t===HI}async function zD({absoluteRepoRoot:e,repoRelativePaths:t,maxFileSizeBytes:o=adt}){gx(e);let n=[];for(let r of hx(t)){let i=eK({absoluteRepoRoot:e,repoRelativePath:r});if(!Ih(r))throw new Error(`Pull request path is not a Momentic file: ${r}`);let a=await promises.stat(i).catch(()=>{});if(!a){n.push({operation:"delete",path:r});continue}if(!a.isFile())throw new Error(`Cannot create pull request change for non-file path: ${r}`);if(a.size>o)throw new Error(`Cannot create pull request change for oversized file: ${r}`);let s=await promises.readFile(i,"utf8");if(s.includes("\0"))throw new Error(`Cannot create pull request change for binary file: ${r}`);n.push({operation:"upsert",path:r,content:s});}return n}async function kf({absoluteRepoRoot:e,repoRelativePaths:t,baseRef:o="HEAD",maxFileSizeBytes:n}){gx(e);let r=hx(t??await Pf({absoluteRepoRoot:e,baseRef:o}));if(r.length===0)return "";let a=(await zD({absoluteRepoRoot:e,repoRelativePaths:r,maxFileSizeBytes:n})).filter(l=>l.operation==="upsert").map(l=>l.path),s=await promises.mkdtemp(Ch.join(Jye.tmpdir(),"momentic-git-patch-"));try{let l=simpleGit({baseDir:e,allowEnvironment:["GIT_INDEX_FILE"]}).env("GIT_INDEX_FILE",Ch.join(s,"index"));return await l.raw(["read-tree",o]),a.length>0&&await l.raw(["add","--intent-to-add","--",...a.map(Qq)]),await l.raw(["diff","--binary","--",...r.map(Qq)])}finally{await promises.rm(s,{recursive:true,force:true});}}async function Xye({absoluteRepoRoot:e,patch:t}){gx(e);let o=await promises.mkdtemp(Ch.join(Jye.tmpdir(),"momentic-git-apply-")),n=Ch.join(o,"heal.patch");try{await promises.writeFile(n,t,"utf8");let r=simpleGit(e),i=ldt(await r.raw(["apply","--numstat","-z","--",n]));if(i.length===0)throw new Error("Cannot apply an empty heal patch.");for(let a of i)if(eK({absoluteRepoRoot:e,repoRelativePath:a}),!Ih(a))throw new Error(`Heal patch path is not a Momentic file: ${a}`);return await r.raw(["apply","--check","--",n]),await r.raw(["apply","--",n]),i}finally{await promises.rm(o,{recursive:true,force:true});}}async function Qye({absoluteRepoRoot:e,repoRelativePaths:t,baseBranch:o,baseCommitSha:n,headBranch:r,branchPrefix:i,idempotencyKey:a,commitMessage:s,title:l,body:c,reviewers:u,teamReviewers:d,fallbackReviewers:m,draft:p,coAuthorRange:h,omitBaseCommitCoAuthors:g,requestCommitAuthorsAsReviewers:f,assignCommitAuthorsAsAssignees:y,assignees:b,maxFileSizeBytes:S}){gx(e);let A=await zD({absoluteRepoRoot:e,repoRelativePaths:t??await Pf({absoluteRepoRoot:e,baseRef:n}),maxFileSizeBytes:S}),T=o??await Uye(e);if(!T)throw new ae(`Cannot determine base branch because git is not usable in '${e}'.`);let v=n??await Fye(e);if(!v)throw new ae(`Cannot determine base commit SHA because git is not usable in '${e}'.`);return {baseBranch:T,baseCommitSha:v,headBranch:r,branchPrefix:i,idempotencyKey:a,commitMessage:s,title:l,body:c,changes:A,reviewers:u,teamReviewers:d,fallbackReviewers:m,draft:p,coAuthorRange:h,requestCommitAuthorsAsReviewers:f,assignCommitAuthorsAsAssignees:y,assignees:b,omitBaseCommitCoAuthors:g}}function Yye(e){return e?e.split(`
372
372
  `).filter(t=>t.length>0):[]}function hx(e){return [...new Set(e)]}function Qq(e){return `:(literal)${e}`}function ldt(e){let t=e.split("\0"),o=[];for(let n=0;n<t.length;n++){let r=t[n];if(!r)continue;let i=r.split(" ");if(i.length<3)throw new Error("Cannot determine files touched by heal patch.");let a=i.slice(2).join(" ");if(a){o.push(a);continue}let s=t[++n],l=t[++n];if(!s||!l)throw new Error("Cannot determine renamed files touched by heal patch.");o.push(s,l);}return hx(o)}function gx(e){if(!Ch.isAbsolute(e))throw new Error(`Git repository root must be absolute: ${e}`)}function eK({absoluteRepoRoot:e,repoRelativePath:t}){if(!t||Ch.isAbsolute(t)||t.includes("\0"))throw new Error(`Unsafe pull request path: ${t}`);let o=Ch.resolve(e,t);if(o!==e&&!o.startsWith(`${e}${Ch.sep}`))throw new Error(`Pull request path escapes repository root: ${t}`);return o}var Zye=Cn__default.join(".momentic","skills"),ebe="SKILL.md",ddt=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,mdt=50;function pdt({rootDir:e,fileSystem:t}){let o=Cn__default.resolve(e);for(let n=0;n<mdt;n++){let r=Cn__default.join(o,Zye);if(t.existsSync(r))return r;let i=Cn__default.dirname(o);if(i===o)break;o=i;}return Cn__default.join(Cn__default.resolve(e),Zye)}function hdt({rootDir:e,fileSystem:t=Lt}){let o=pdt({rootDir:e,fileSystem:t}),n=tbe({skillsDir:o,fileSystem:t}),r=[];for(let i of n){let a=Cn__default.basename(Cn__default.dirname(i)),s=Cn__default.relative(o,Cn__default.dirname(i)).split(Cn__default.sep).join("/"),l=gdt({dirName:a,skillPath:s,filePath:i,fileSystem:t});l&&r.push(l);}return r.sort((i,a)=>i.name.localeCompare(a.name)||i.path.localeCompare(a.path))}function zA({rootDir:e,agent:t,fileSystem:o=Lt}){let n=hdt({rootDir:e,fileSystem:o}).filter(r=>r.agents===void 0||r.agents.includes(t));if(n.length!==0)return n.map(r=>`<skill name="${r.name}" path="${r.path}" description="${r.description}">
373
373
  ${r.body}
@@ -482,7 +482,7 @@ ${r.code(Br(u,n))}`,i),t)try{await ppt(u);}catch{e.warn(`Could not open a browse
482
482
  `),r+=this.cursorSeq(o.length>0),r.length>0&&this.opts.stream.write(r),this.commitFrame(o,n);}commitFrame(t,o){this.liveRows=t.length,this.lastFrame=o,t.length===0?this.stopTicker():this.ensureTicker();}eraseSeq(){return this.liveRows===0?"":Mae+Lae.repeat(this.liveRows)+Nae}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 lht=80,cht=120,uht=20,dht="classifying failure",h0=class{totalTests=0;nextIndex=0;running=new Map;quarantined=new Set;recovered=new Set;region;theme;screen;constructor(t){this.screen={...t,isTTY:vm(t)},this.theme=ht(this.screen),this.region=new jf({stream:process.stdout,isTTY:this.screen.isTTY,tickMs:lht,render:o=>this.renderRunningRows(o)});}onBegin(t){this.totalTests=t.tests.length,this.nextIndex=0,this.quarantined.clear(),this.recovered.clear();for(let o of t.tests)o.quarantined&&this.quarantined.add(o.relativeFilePath);for(let o of t.tests)o.skipped&&(this.nextIndex+=1,this.commitRow({testRef:o.relativeFilePath,status:"SKIP",index:this.nextIndex,note:o.skipped.kind==="quarantined"?o.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,o,n){let r=this.running.get(t);r?(r.status=o,r.note=n,r.step=void 0,r.classifying=false):(this.nextIndex+=1,this.running.set(t,{index:this.nextIndex,status:o,note:n,startedAt:Date.now()})),this.region.update();}onStepStart(t,o){let n=this.running.get(t);if(n){if(n.step={text:o},n.classifying=o===xp,n.classifying&&!this.screen.isTTY){let r=this.formatRow({testRef:t,status:n.status,index:n.index,classifying:true,classifyPending:true});r&&this.region.writeAbove(r);return}this.region.update();}}onStepEnd(t,o,n){}onSectionStart(t,o){}onTestEnd(t,o,n){n?.recovered&&this.recovered.add(t);let r=this.running.get(t),i=r?this.formatRow({testRef:t,status:o,index:r.index,elapsedMs:Date.now()-r.startedAt}):this.formatRow({testRef:t,status:o,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 o=this.formatRow(t);o&&this.region.writeAbove(o);}renderRunningRows(t){let o=[];for(let[n,r]of this.running){let i=this.formatRow({testRef:n,status:r.status,index:r.index,note:r.note,elapsedMs:Date.now()-r.startedAt,step:r.step,tick:t,classifying:r.classifying});i&&o.push(i);}return o}formatRow(t){let o=cI(t.status,this.screen,t.tick);if(!o)return;let n=t.classifying===true&&!o.isTerminal,r=n?this.theme.classifySpinner(t.tick??0):o.badge,a=String(this.totalTests).length*2+3,s=`[${t.index}/${this.totalTests}]`.padStart(a),l=this.quarantined.has(t.testRef)?" [quarantined]":"",c=this.recovered.has(t.testRef)?" [recovered]":"",u=typeof t.elapsedMs=="number"?Math.floor(t.elapsedMs/1e3):0,m=(o.isTerminal?typeof t.elapsedMs=="number":u>=1)?` (${Math.max(1,u)}s)`:"",p=this.screen.columns>0?this.screen.columns:cht,h=a+3+t.testRef.length+l.length+c.length+m.length,g=Math.max(uht,p-1)-h,f=n?`${dht}${t.classifyPending?"\u2026":""}`:t.step&&!o.isTerminal?t.step.text:void 0,b=f?OK(n?" \xB7 ":" \u203A ",f,g):"";g-=b.length;let S=t.note?OK(" ",t.note,g):"";return `${this.theme.dim(s)} ${r} ${t.testRef}${this.theme.dim(l)}${this.theme.dim(c)}${this.theme.dim(b)}${S}${this.theme.dim(m)}`}};var g0=class{constructor(t){this.reporters=t;}onBegin(t){for(let o of this.reporters)o.onBegin(t);}onTestBegin(t){for(let o of this.reporters)o.onTestBegin(t);}onTestStatus(t,o,n){for(let r of this.reporters)r.onTestStatus(t,o,n);}onStepStart(t,o,n){for(let r of this.reporters)r.onStepStart(t,o,n);}onStepEnd(t,o,n){for(let r of this.reporters)r.onStepEnd(t,o,n);}onSectionStart(t,o){for(let n of this.reporters)n.onSectionStart(t,o);}onTestEnd(t,o,n){for(let r of this.reporters)r.onTestEnd(t,o,n);}onEnd(t){for(let o of this.reporters)o.onEnd(t);}};var mht="classifying failure",f0=class{totalTests=0;nextIndex=0;running=new Map;quarantined=new Set;recovered=new Set;theme;screen;constructor(t){this.screen=t,this.theme=ht(t);}onBegin(t){this.totalTests=t.tests.length,this.nextIndex=0,this.quarantined.clear(),this.recovered.clear();for(let o of t.tests)o.quarantined&&this.quarantined.add(o.relativeFilePath);for(let o of t.tests){if(!o.skipped)continue;this.nextIndex+=1;let n=o.skipped.kind==="quarantined"?` ${o.skipped.reason}`:"";this.write(`${this.counter(this.nextIndex)}${this.theme.statusGlyph("skip")} ${o.relativeFilePath}${n}`);}}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,o,n){let r=this.running.get(t);r||(this.nextIndex+=1,r={index:this.nextIndex,startedAt:Date.now()},this.running.set(t,r));let i=cI(o,this.screen);if(!i||i.isTerminal||o==="RUN")return;let a=n?` ${this.theme.dim(n)}`:"";this.detail(r,1,`${i.badge} ${this.theme.dim(o.toLowerCase())}${a}`);}onStepStart(t,o,n=0){let r=this.running.get(t);if(r){if(o===xp){this.detail(r,1,`${this.theme.classifySpinner(0)} ${this.theme.dim(`${mht}\u2026`)}`);return}this.detail(r,this.stepIndent(r,n),this.theme.dim(`- ${o}`));}}onStepEnd(t,o,n){let r=this.running.get(t);if(!r)return;let i=this.theme.statusGlyph(n.success?"pass":"fail");this.detail(r,this.stepIndent(r,n.depth),`${i} ${this.theme.dim(Oh(n.durationMs))}`);}onSectionStart(t,o){let n=this.running.get(t);n&&(n.sectioned=true,this.detail(n,1,this.theme.dim(o)));}onTestEnd(t,o,n){n?.recovered&&this.recovered.add(t);let r=this.running.get(t),i=cI(o,this.screen),a=r?.index??++this.nextIndex;if(r&&this.running.delete(t),!i)return;let s=this.quarantined.has(t)?" [quarantined]":"",l=this.recovered.has(t)?" [recovered]":"",c=r?` (${Math.max(1,Math.floor((Date.now()-r.startedAt)/1e3))}s)`:"",u=r?"":` ${t}`;this.write(`${this.counter(a)}${i.badge}${u}${this.theme.dim(s)}${this.theme.dim(l)}${this.theme.dim(c)}`);}onEnd(t){}stepIndent(t,o){return o+(t.sectioned?2:1)}detail(t,o,n){this.write(`${this.counter(t.index)}${" ".repeat(o)}${n}`);}counter(t){if(this.totalTests<=1)return "";let n=String(this.totalTests).length*2+3;return this.theme.dim(`[${t}/${this.totalTests}]`.padStart(n))+" "}write(t){process.stdout.write(`${t}
483
483
  `);}};var hht="list",yTe="steps",bTe="dot",y0=["json","junit","allure","allure-json","playwright-json","buildkite-json"],b0=["newrelic"],fTe=[hht,yTe,bTe,...y0,...b0];function STe(e,t){if(!fTe.includes(e))throw new InvalidArgumentError$2(`Allowed choices are ${fTe.join(", ")}.`);return [...t,e]}function TTe(e){let t=[],o=[];for(let r of e.reporter??[]){let i=y0.find(s=>s===r);i&&t.push(i);let a=b0.find(s=>s===r);a&&o.push(a);}let n;return e.reporter?.includes(bTe)?n=new p0(e.screen):e.reporter?.includes(yTe)?n=new f0(e.screen):n=new h0(e.screen),{live:new g0([n]),files:t,network:o}}function S0(e,t){return e.split(`
484
484
  `).map(o=>t.color?o.startsWith("+")?Yc.green(o):o.startsWith("-")?Yc.red(o):o.startsWith("@@")?t.dim(o):o:o)}var yht="MOMENTIC_SKIP_UPGRADE_PROMPT",bht=24*60*60*1e3;async function ATe(e){let{runUpgrade:t}=e;if(!t||process.env.NO_UPDATE_NOTIFIER||process.env[yht]!==void 0||ms||!process.stdin.isTTY||!process.stdout.isTTY)return;let o;try{o=await kK(e);}catch(n){e.logger.warn({err:n},"Failed to check for a newer CLI version");return}if(!(!o||!Ph.gt(o,e.currentVersion))&&QA(`upgrade-prompt-${e.packageName}-${o}`,bht)){MK(e,o,rt());try{if(!await confirm({message:`Upgrade ${e.packageName} to v${o} now?`,default:!0})){x.log(` Run ${e.updateCommand} at any time to update.`);return}await t(o,e.logger),x.success(`Upgraded ${e.packageName} to v${o}. This command continues on v${e.currentVersion}; new runs use v${o}.`);}catch(n){if(n instanceof Error&&n.name==="ExitPromptError")return;e.logger.warn({err:n},"Failed to upgrade the CLI"),x.warn(`Could not upgrade ${e.packageName}: ${W(n)}. Run ${e.updateCommand} to update manually.`);}}}var Sht="https://api.momentic.ai";function ETe({server:e,serverSource:t,apiKeySource:o}){return t!=="default"||o==="default"?e:Sht}function wTe(e,t){switch(e){case "cli":return "--api-key";case "env":return "MOMENTIC_API_KEY";default:return t}}function RTe({auth:e,serverUrl:t,appUrl:o,keySource:n,screen:r}){let i=ht(r),a=e.name??e.email??e.userId,s=[];e.email!==void 0&&s.push({label:"Email",value:e.email}),s.push({label:"User ID",value:e.userId},{label:"Org ID",value:e.orgId},{label:"Server",value:t},{label:"App",value:Br(o,r)},{label:"API key",value:i.dim(n)}),x.log(`Signed in as ${i.bold(a)}`),x.log(Km(s,r));}var Dx=25;function CTe(e){return {v2ProjectConfig:{...e.config,fileFormat:"v2"},migratedFilePaths:[]}}function ITe(e){return {legacyProjectConfig:{...e.config,fileFormat:"v1"},migratedFilePaths:[]}}function HK({project:e,newProjectConfig:t,fileFormatLabel:o,migratedFilePaths:n}){e.config=t,jb(e.config,e.configFilePath),n.push(e.configFilePath),x.info(`Updated ${e.configFilePath} to use ${o} file format`),t.hooks?.postSave&&(x.info(`Running post-save hook for ${n.length} migrated files`),gA([...new Set(n)],t));}async function Fx(e,t,o){for(let n=0;n<e.length;n+=t)await Promise.all(e.slice(n,n+t).map(o));}function $K(e){return e.upgradedAgents.length>0||e.enabledUseMemory||e.enabledFailureRecovery}function vht(e){let t=e.ai??={},o=t.agentConfig??={},n=[];for(let[a,s]of Object.entries(yg)){let l=o[a];l!==s&&(l?.startsWith(`${s}.`)||(o[a]=s,n.push({type:a,newValue:s})));}let r=t.useMemory!==true;r&&(t.useMemory=true);let i=t.failureRecovery!==true;return i&&(t.failureRecovery=true),{upgradedAgents:n,enabledUseMemory:r,enabledFailureRecovery:i}}async function xTe({project:e,dryRun:t,migrate:o}){let n=e.config.fileFormat!=="v2",r=tl.stringify(e.config),i=vht(e.config);if(!n)return !t&&$K(i)&&jb(e.config,e.configFilePath),{fileFormatChanged:false,aiSettings:i,migration:GK(),configDiff:jK(r,e.config)};let a=await o();return {fileFormatChanged:n,aiSettings:i,migration:a,configDiff:jK(r,{...e.config,fileFormat:"v2"})}}function jK(e,t){return Rb(e,tl.stringify(t),{n_surrounding:2})}function _Te(e){return jK(tl.stringify(e),{...e,fileFormat:"v2"})}function GK(){return {migratedTestPaths:[],migratedModulePaths:[],alreadyV2TestCount:0,alreadyV2ModuleCount:0}}function VK({summary:e,fileFormatChanged:t,configChange:o,dryRun:n,testNoun:r="test",moduleNoun:i="module"}){let a=rt(),s=ht(a),l=s.green("~");x.info(""),x.info(Uf(n?"Upgrade Preview":"Upgrade Summary",a)),x.info("");let c=p=>` ${l} ${s.code(Cn__default.relative(process.cwd(),p))}`,u=(p,h)=>{let g=Bv(p,h);return `${s.bold(g.charAt(0).toUpperCase()+g.slice(1))} ${s.dim(`(${h})`)}`},d=e.migratedTestPaths.length,m=e.migratedModulePaths.length;if(t||d>0||m>0){let p=n?"Would migrate":"Migrated";if(x.info(`${p} ${s.bold(`${d} ${Bv(r,d)}`)} and ${s.bold(`${m} ${Bv(i,m)}`)} to the simplified format.`),x.info(""),d>0){x.info(u(r,d));for(let h of [...e.migratedTestPaths].sort())x.info(c(h));x.info("");}if(m>0){x.info(u(i,m));for(let h of [...e.migratedModulePaths].sort())x.info(c(h));x.info("");}(e.alreadyV2TestCount>0||e.alreadyV2ModuleCount>0)&&(x.dimmed(`Skipped ${e.alreadyV2TestCount} already-migrated ${Bv(r,e.alreadyV2TestCount)} and ${e.alreadyV2ModuleCount} already-migrated ${Bv(i,e.alreadyV2ModuleCount)}.`),x.info(""));}if(o&&o.diff.trim().length>0){x.info(u("config",1)),x.info(c(o.configFilePath));for(let p of S0(o.diff,s))x.info(` ${p}`);x.info("");}}var He={Success:0,Failure:1,Sigint:130,Sigterm:143},oE=class extends Error{exitCode;constructor(t){super(`CLI exit ${t}`),this.name="CliExit",this.exitCode=t;}};function Je(e){throw new oE(e)}function lS(e){if(e instanceof oE)throw e}function T0(){return new Promise(()=>{})}var Bx=class extends Error{constructor(t){super("Reported CLI failure",{cause:t}),this.name="ReportedError";}};function wi(e){return new Bx(e)}function OTe(e){return hi(e,Bx)!==void 0}function PTe(e){return hi(e,Bx)?.cause??e}var bo=class extends ae{code;constructor(t,o,n){super(o,n),this.name="CliError",this.code=t;}},Aht={group:"internal",retry:"case-by-case",attribution:"unknown"};function Ux(e,t){return {code:e,...t.catalog[e]??Aht}}function Eht(e,t){let o=hi(e,bo);if(o)return Ux(o.code,t);let n=t.extraClassifier?.(e);return n!==void 0?Ux(n,t):e instanceof CommanderError?Ux(t.argsCode,t):hi(e,ae)?Ux(t.userCode,t):Ux(t.internalCode,t)}var wht=/API key is required|required option '--api-key/;function Rht(e){let t=hi(e,CommanderError);return t!==void 0&&wht.test(t.message)}var Cht=/No valid Momentic project file|Multiple valid projects|Project config at .*does not match/;function Iht(e){let t=hi(e,ae);return t!==void 0&&Cht.test(t.message)}function LTe(e,t){let o=hi(e,Lo);if(o)return o.status===401||o.status===403?t.authForbidden:o.status===404?t.resourceNotFound:o.status>=500?t.apiUnavailable:t.apiError;if(Rht(e))return t.authRequired;if(t.projectConfigError!==void 0&&Iht(e))return t.projectConfigError}function xht(e){return {failure_code:e.code,failure_group:e.group,failure_attribution:e.attribution,failure_retryable:e.retry}}var _ht=/\u001b\[[0-9;]*m/g,kTe=400;function Oht(e){let t=e.replace(_ht,"").trim();return t.length>kTe?`${t.slice(0,kTe)}\u2026`:t}function MTe(e,t,o){try{process.stderr.write(`${e}-error: ${JSON.stringify({code:t.code,group:t.group,retry:t.retry,attribution:t.attribution,message:Oht(o)})}
485
- `);}catch{}}async function NTe(e){let{cliName:t,err:o,taxonomy:n,cleanup:r,captureException:i,messages:a}=e,s=Eht(o,n),l=xht(s);o instanceof CommanderError&&(o.exitCode!==0&&(Re.error({err:o,...e.argsLogFields?.(),...l},a.invalidArgs),MTe(t,s,o.message)),await r(),process.exit(o.exitCode));let c=hi(o,oE);c&&(await r(),process.exit(c.exitCode));let u=PTe(o),d=hi(o,ae),m=OTe(o),p={err:o,...e.failureLogFields?.(o),...l};d?(Re.error(p,a.userFacing),m||x.error(d.message)):(Re.error(p,a.uncaught),m||x.error({err:o},a.unexpectedExit)),MTe(t,s,d?.message??W(u)),e.doctorCommand&&m0({err:u,doctorCommand:e.doctorCommand}),i(u),await r(),process.exit(He.Failure);}var qK=false,DTe,FTe;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.62.2",tracesSampleRate:0,skipOpenTelemetrySetup:!0,sendDefaultPii:!0,beforeSend(o,n){return Qse(n?.originalException)||Qw(n?.originalException,ae)||Zse(n?.originalException)?null:o}}),Rae(e.captureException),iae(e.addBreadcrumb),DTe=o=>{if(!o){e.setUser(null);return}e.setUser({id:o.userId,organizationId:o.orgId,...o.email&&{email:o.email}});},FTe=()=>e.flush(2e3),qK=!0;}catch{}var BTe=e=>DTe?.(e);async function UTe(){await FTe?.().catch(()=>{});}var kht=new vL(30,60*1e3),zx="https://api.momentic.ai",nE,jTe,kh=e=>{zx=e;},Pc=()=>zx,zTe=()=>Ev(zx),zf=e=>{jTe=e;},Cd=()=>jTe,hr=()=>nE,HTe=()=>{if(!nE)throw new Error("Global API client has not been initialized.");return nE};var jx,A0,$Te,GTe,VTe,E0,WTe,qTe=({authInfo:e,apiKey:t,apiClient:o})=>{zx=o.baseUrl,nE=o,jx=e.orgId,A0=e.userId,$Te=e.email,GTe=e.name,VTe=e.pylonEmailHash,E0=t,WTe=e.selfServe;},Hf=async({apiClient:e,apiKey:t,skipPrompts:o})=>{let n=await Zb({client:e});return qTe({authInfo:n,apiKey:t,apiClient:e}),n},C0=async({apiKey:e,mode:t,runner:o})=>{if(nE&&jx&&E0)return jx;let n=new so({baseUrl:zx,apiKey:e,logger:x,mode:t,runner:o});nE=n;try{let r=await n.getAuthInfo();return qTe({authInfo:r,apiKey:e,apiClient:n}),r.orgId}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},si=()=>{if(!jx)throw new Error("Your organization ID is invalid.");return jx},Xm=()=>{if(!A0)throw new Error("Your user ID is invalid.");return A0},KTe=()=>A0,rE=()=>$Te,YTe=()=>GTe,JTe=()=>VTe,I0=()=>WTe,Mh=()=>{if(!E0)throw new Error("Your API key is invalid.");return E0},w0,R0,Lh=()=>{R0?.abort(),R0=void 0;},$f=(e,t)=>{w0=e,Lh(),R0=new AbortController;let o=R0.signal,n=[e.configFilePath];e.config.environments?.forEach(r=>{if(!r.envFile)return;let i=Cn__default.resolve(e.rootDir,r.envFile);try{if(Un__default.lstatSync(i).isSymbolicLink())return;Un__default.existsSync(i)&&n.push(i);}catch(a){x.warn({err:a},`Failed to check if env file ${i} exists`);}});try{Mht({filesToWatch:n,revalidator:t,signal:o,project:e});}catch(r){x.error({err:r},"Failed to start config file watchers");}};async function iE({project:e,apiClient:t}){let o=n=>cl({project:n,apiClient:t});$f(await o(e),async n=>o(await on({configFilePath:n})));}var Xt=()=>{if(!w0)throw new ae("No Momentic project is currently loaded. Open or select a project before invoking this action.");return w0};function Mht({filesToWatch:e,revalidator:t,signal:o,project:n}){x.debug("Starting watch on the following files:"),e.forEach(r=>{x.debug(`- ${r}`);}),e.forEach(r=>{let i=async(s,l)=>{if(s.mtime.getTime()!==l.mtime.getTime()){kht.increment("setLocalProject")&&x.warn(`A file change under the ${n.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{w0=await Promise.resolve(t(n.configFilePath));}catch(c){x.warn({err:c},`Failed to reload Momentic configuration after a change to ${r}; continuing with the previously loaded configuration`);}}};Un__default.watchFile(r,{persistent:false},i);let a=()=>{Un__default.unwatchFile(r,i),o.removeEventListener("abort",a);};o.addEventListener("abort",a);});}function So(e){return function(...t){let o=t[t.length-1],n=e(...t);Promise.resolve(n).catch(o);}}var Nht="3.62.2",Nh=Iv({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:Nht});(async()=>{try{let e=await wu(Nh);e.gitBranchName&&Nh.addBinding("branch",e.gitBranchName);}catch{}})();var XTe=Router();XTe.get("/",async(e,t)=>{let o=Xt(),n=hr();if(!n){t.status(500).json({message:"API client not initialized"});return}let r=await Vm(Nh,n,o),i=r?.gitProtectedBranches&&r?.gitBranchName&&r.gitProtectedBranches.includes(r.gitBranchName),{noCache:a,alwaysSaveCache:s}=Cd(),l=!a&&(s||!i);t.status(200).json({saveCaches:l,checkedOutBranch:r?.gitBranchName});});var KK=XTe;var Bht=5e3,Uht=[".js",".mjs",".cjs",".ts"];function YK(e={}){let t=Router();function o(){let d=Xt();return Cn__default.dirname(d.configFilePath)}function n(d){return Cn__default.join(o(),...d)}function r(d){let m=Cn__default.relative(o(),d);return m?m.split(Cn__default.sep):[]}function i(d,m){let p=Un__default.statSync(d),h=r(d);return lG.parse({name:m,absolutePath:d,relativePath:h.join(Cn__default.sep),pathSegments:h,isDirectory:p.isDirectory(),size:p.size,createdAt:p.birthtime,modifiedAt:p.mtime,accessedAt:p.atime})}function a(d){let m=Cn__default.relative(o(),d);return m===""||!m.startsWith("..")&&!Cn__default.isAbsolute(m)}async function s(d){let m=Xt();return Om(["*"],{cwd:d,ignore:m.config.exclude??[],maxDepth:1,nodir:false,signal:AbortSignal.timeout(Bht)})}function l(d){let m=d.trimStart().replace(/^file:\/\//,"").replaceAll("\\","/"),p=m.lastIndexOf("/");return p===-1?{directoryText:"",filePrefix:m}:{directoryText:m.slice(0,p+1),filePrefix:m.slice(p+1)}}function c(d){return d.replaceAll("\\","/").split("/").filter(m=>m&&m!==".")}function u({sourceDirectoryPath:d,targetPath:m,isDirectory:p}){let h=Cn__default.relative(d,m).split(Cn__default.sep).join("/");return p?h?`${h}/`:"./":h}return t.post("/file-reference-suggestions",So(async(d,m,p)=>{let h=$te.safeParse(d.body);if(!h.success){m.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??Uht).map(C=>C.toLowerCase())),b=l(f);if(b.directoryText.startsWith("/")){m.status(200).json({suggestions:[]});return}let S=Cn__default.resolve(o(),...c(g)),A=Cn__default.resolve(S,...c(b.directoryText));if(!a(S)||!a(A)){m.status(200).json({suggestions:[]});return}if(!Un__default.existsSync(A)||!Un__default.statSync(A).isDirectory()){m.status(200).json({suggestions:[]});return}let T;try{T=await s(A);}catch(C){if(C instanceof Error&&C.name==="TimeoutError"){m.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw C}let v=T.map(C=>{let O=Cn__default.join(A,C);return {entryName:C,targetPath:O,isDirectory:Un__default.statSync(O).isDirectory()}}),R=b.filePrefix.toLowerCase(),I=v.filter(C=>C.entryName.startsWith(".")||!C.entryName.toLowerCase().startsWith(R)?false:C.isDirectory?true:y.has(Cn__default.extname(C.entryName).toLowerCase())).sort((C,O)=>C.isDirectory!==O.isDirectory?C.isDirectory?-1:1:C.entryName.localeCompare(O.entryName)).map(C=>({name:C.entryName,isDirectory:C.isDirectory,value:u({sourceDirectoryPath:S,targetPath:C.targetPath,isDirectory:C.isDirectory})}));m.status(200).json({suggestions:I});})),t.post("/",So(async(d,m,p)=>{let h,g;try{let T=Hte.parse(d.body);h=T.pathSegments,g=T.directoriesOnly??!1;}catch(T){m.status(400).json({error:`Failed to parse folder read body: ${T}`});return}let f=n(h);if(!Un__default.existsSync(f)){m.status(404).json({error:`Path not found: ${h.join(Cn__default.sep)}`});return}if(!Un__default.statSync(f).isDirectory()){m.status(400).json({error:`Path is not a directory: ${h.join(Cn__default.sep)}`});return}let b;try{b=await s(f);}catch(T){if(T instanceof Error&&T.name==="TimeoutError"){m.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw T}let S=b.map(T=>{let v=Cn__default.join(f,T);return i(v,T)});if(g&&(S=S.filter(T=>T.isDirectory)),e.allowedFileTypes){let T=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 jht(v.absolutePath);return I!==void 0&&T.has(I)?v:null}))).filter(v=>v!==null);}let A={absolutePath:f,pathSegments:h,contents:S};m.status(200).json(A);})),t.put("/",So(async(d,m,p)=>{let h;try{h=Gte.parse(d.body).pathSegments;}catch(y){m.status(400).json({error:`Failed to parse folder create body: ${y}`});return}let g=n(h);if(Un__default.existsSync(g)){m.status(200).json({success:true,message:`Folder already exists: ${h.join(Cn__default.sep)}`,pathSegments:h});return}Un__default.mkdirSync(g,{recursive:true});let f={success:true,message:`Folder created: ${h.join(Cn__default.sep)}`,pathSegments:h};m.status(201).json(f);})),t.patch("/",So(async(d,m,p)=>{let h,g;try{let A=Vte.parse(d.body);h=A.pathSegments,g=A.newPathSegments;}catch(A){m.status(400).json({error:`Failed to parse folder update body: ${A}`});return}let f=n(h),y=n(g);if(!Un__default.existsSync(f)){m.status(400).json({error:`Folder not found: ${h.join(Cn__default.sep)}`});return}if(Un__default.existsSync(y)){m.status(400).json({error:`Destination already exists: ${g.join(Cn__default.sep)}`});return}let b=Cn__default.dirname(y);Un__default.existsSync(b)||Un__default.mkdirSync(b,{recursive:true}),Un__default.renameSync(f,y);let S={success:true,message:`Folder moved from ${h.join(Cn__default.sep)} to ${g.join(Cn__default.sep)}`,pathSegments:g};m.status(200).json(S);})),t.delete("/",So(async(d,m,p)=>{let h,g=true;try{let S=Wte.parse(d.body);h=S.pathSegments,g=S.recursive??!0;}catch(S){m.status(400).json({error:`Failed to parse folder delete body: ${S}`});return}let f=n(h);if(!Un__default.existsSync(f)){m.status(200).json({success:true,message:`Folder not found: ${h.join(Cn__default.sep)}`,pathSegments:h});return}if(!Un__default.statSync(f).isDirectory()){m.status(400).json({error:`Path is not a directory: ${h.join(Cn__default.sep)}`});return}try{if(g)Un__default.rmSync(f,{recursive:!0,force:!0});else {if(Un__default.readdirSync(f).length>0){m.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${h.join("/")}`});return}Un__default.rmdirSync(f);}}catch(S){let{status:A,body:T}=Ibe(S,`delete folder ${h.join("/")}`);m.status(A).json(T);return}let b={success:true,message:`Folder deleted: ${h.join("/")}`,pathSegments:h};m.status(200).json(b);})),t}async function jht(e){try{let t=await Un__default.promises.open(e,"r");try{let o=Buffer.alloc(4096),{bytesRead:n}=await t.read(o,0,o.length,0);return o.toString("utf-8",0,n).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await t.close();}}catch{}}var QTe=Router();QTe.get("/",async(e,t)=>{let o=Xt(),n=hr();if(!n){t.status(500).json({message:"API client not initialized"});return}let r=await Of(Nh,n,o);t.status(200).json(r);});var JK=QTe;var ZTe=Router();ZTe.get("/",async(e,t)=>{let o=hr(),n=[];try{n=await o?.listProductUpdates()??[];}catch(r){Nh.debug({err:r},"Failed to fetch product updates");}t.status(200).json({updates:n});});var XK=ZTe;var $ht=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{sessionId:n}=e;return async()=>{t.info({sessionId:n},"Cancel event received");let r=o.getSession(n);if(!r)throw new Error("No active session found");try{r.controller.setClosed();}catch{}}},eve={event:"cancel",createHandler:$ht};var Ght=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{testId:n,sessionId:r}=e;return async(i,a)=>{let{stepId:s,environment:l,parentStepIdChain:c}=i;t.info({testId:n,stepId:s},"Clearing AI action cache");try{let u=o.getSession(r);if(!u)throw new Error("No active session found");let d=zv(s,c.join(":")||void 0);await Promise.all(d.map(m=>u.cacheStorage.deleteStepCacheEntry({logger:t,testId:n,key:m,environment:l}))),a({ok:!0});}catch(u){t.error({testId:n,stepId:s,err:u},"Failed to clear AI action cache"),a({ok:false,error:W(u)});}}},tve={event:"clearAIActionCache",createHandler:Ght};var Vht=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{sessionId:n}=e;return async(r,i)=>{let a=o.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=(await s.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});}}},ove={event:"fetchA11yTree",createHandler:Vht};var Wht=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{sessionId:n}=e;return async(r,i)=>{let a=o.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=await s.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});}}},nve={event:"fetchDom",createHandler:Wht};var qht=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{sessionId:n}=e;return r=>{t.info({sessionId:n,reason:r},`Disconnect event received (${r})`),o.removeSession(n,t);}},rve={event:"disconnect",createHandler:qht};function Hl(e){let{result:t,nestedResults:o}=e;if(!e.nestedResults.length)return;let{firstMetadata:n,lastMetadata:r}=Kht(o);Yht(t,n,r);let i=o[o.length-1];i.status!=="SUCCESS"&&(t.message=i.message,t.failureReason=i.failureReason,t.failureClassification=i.failureClassification);let a=[...e.asyncTasks];e.asyncTasks.push((async()=>{try{await Jht(a,t,n,r);}catch(s){e.logger.error({result:e.result,err:s},"Error hoisting scalar result metadata");}})());}function Kht(e){let t=e[0],o;for(;;){switch(t.type){case "PRESET_ACTION":case "CONDITIONAL":o=t;break;case "AI_ACTION_DYNAMIC":case "AI_ACTION":case "MODULE":case "SECTION":case "WHILE_LOOP":if(!t.results.length){o=t;break}t=t.results[0];break;default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(o)break}let n=e[e.length-1],r;for(;;){switch(n.type){case "PRESET_ACTION":{r=n;break}case "AI_ACTION_DYNAMIC":case "CONDITIONAL":case "AI_ACTION":case "MODULE":case "SECTION":case "WHILE_LOOP":if(!n.results.length){r=n;break}n=n.results[n.results.length-1];break;default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(r)break}return {firstMetadata:o,lastMetadata:r}}function Yht(e,t,o){t&&(e.beforeUrl=t.beforeUrl),o&&(e.afterUrl=o.afterUrl,e.data=o.data);}async function Jht(e,t,o,n){await Promise.allSettled(e),o&&(t.beforeSnapshot=o.beforeSnapshot),n&&(t.afterSnapshot=n.afterSnapshot);}function Hx(e,t,o){let n={};return Object.entries(t).forEach(([i,a])=>{n[i]=JSON.stringify(a);}),{type:"MODULE",id:e.id,moduleId:e.moduleId,moduleName:e.name,startedAt:new Date,cacheConfig:e.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:o}}async function Gf(e,t,o){return Xht(e,t,o)}async function Xht(e,t,o){let n=new Date;try{return o.throwIfAborted(),await t()}catch(r){let i=new Date,a="FAILED",s;if(o.aborted||r instanceof DOMException&&r.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):r instanceof ie?s=`${r}`:s=`An unexpected error occurred: ${r.message}`,e.type==="RESOLVED_MODULE"){let l=Hx(e,{},"FAILED");return l.message=s,l.startedAt=n,l.finishedAt=i,l}return {...Xv(e),startedAt:n,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function Ts(e,t){let o=false;try{return e&&!e.state.failureRecoveryDisabled&&(e.state.failureRecoveryDisabled=!0,o=!0),await t()}finally{e&&o&&(e.state.failureRecoveryDisabled=void 0);}}var aE=20,x0=100;function QK(e){return e.baseDerivedFrom==="estimate"}var Qht={config:"the main branch configured for this project","run-metadata":"the main branch recorded with this run","origin-head":"the remote's default branch from origin/HEAD, which git records at clone time and never refreshes \u2014 if this repository's default branch has changed since, this window is against the old one",estimate:"an estimate: a fixed number of commits back from head, because the main branch could not be resolved. The window therefore contains commits made on the main branch that this branch did not make, and a file may appear newly added when it merely predates the base. Do not conclude that this branch introduced a change from its presence in this window alone"};function _0(e){return e.baseDerivedFrom?` The base of this comparison window is ${Qht[e.baseDerivedFrom]}.`:""}function D({text:e,section:t}){if(!t)return [{type:"text",text:e}];let o=`### ${t}`;return e.length===0?[{type:"text",text:o}]:[{type:"text",text:`${o}
485
+ `);}catch{}}async function NTe(e){let{cliName:t,err:o,taxonomy:n,cleanup:r,captureException:i,messages:a}=e,s=Eht(o,n),l=xht(s);o instanceof CommanderError&&(o.exitCode!==0&&(Re.error({err:o,...e.argsLogFields?.(),...l},a.invalidArgs),MTe(t,s,o.message)),await r(),process.exit(o.exitCode));let c=hi(o,oE);c&&(await r(),process.exit(c.exitCode));let u=PTe(o),d=hi(o,ae),m=OTe(o),p={err:o,...e.failureLogFields?.(o),...l};d?(Re.error(p,a.userFacing),m||x.error(d.message)):(Re.error(p,a.uncaught),m||x.error({err:o},a.unexpectedExit)),MTe(t,s,d?.message??W(u)),e.doctorCommand&&m0({err:u,doctorCommand:e.doctorCommand}),i(u),await r(),process.exit(He.Failure);}var qK=false,DTe,FTe;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.62.3",tracesSampleRate:0,skipOpenTelemetrySetup:!0,sendDefaultPii:!0,beforeSend(o,n){return Qse(n?.originalException)||Qw(n?.originalException,ae)||Zse(n?.originalException)?null:o}}),Rae(e.captureException),iae(e.addBreadcrumb),DTe=o=>{if(!o){e.setUser(null);return}e.setUser({id:o.userId,organizationId:o.orgId,...o.email&&{email:o.email}});},FTe=()=>e.flush(2e3),qK=!0;}catch{}var BTe=e=>DTe?.(e);async function UTe(){await FTe?.().catch(()=>{});}var kht=new vL(30,60*1e3),zx="https://api.momentic.ai",nE,jTe,kh=e=>{zx=e;},Pc=()=>zx,zTe=()=>Ev(zx),zf=e=>{jTe=e;},Cd=()=>jTe,hr=()=>nE,HTe=()=>{if(!nE)throw new Error("Global API client has not been initialized.");return nE};var jx,A0,$Te,GTe,VTe,E0,WTe,qTe=({authInfo:e,apiKey:t,apiClient:o})=>{zx=o.baseUrl,nE=o,jx=e.orgId,A0=e.userId,$Te=e.email,GTe=e.name,VTe=e.pylonEmailHash,E0=t,WTe=e.selfServe;},Hf=async({apiClient:e,apiKey:t,skipPrompts:o})=>{let n=await Zb({client:e});return qTe({authInfo:n,apiKey:t,apiClient:e}),n},C0=async({apiKey:e,mode:t,runner:o})=>{if(nE&&jx&&E0)return jx;let n=new so({baseUrl:zx,apiKey:e,logger:x,mode:t,runner:o});nE=n;try{let r=await n.getAuthInfo();return qTe({authInfo:r,apiKey:e,apiClient:n}),r.orgId}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},si=()=>{if(!jx)throw new Error("Your organization ID is invalid.");return jx},Xm=()=>{if(!A0)throw new Error("Your user ID is invalid.");return A0},KTe=()=>A0,rE=()=>$Te,YTe=()=>GTe,JTe=()=>VTe,I0=()=>WTe,Mh=()=>{if(!E0)throw new Error("Your API key is invalid.");return E0},w0,R0,Lh=()=>{R0?.abort(),R0=void 0;},$f=(e,t)=>{w0=e,Lh(),R0=new AbortController;let o=R0.signal,n=[e.configFilePath];e.config.environments?.forEach(r=>{if(!r.envFile)return;let i=Cn__default.resolve(e.rootDir,r.envFile);try{if(Un__default.lstatSync(i).isSymbolicLink())return;Un__default.existsSync(i)&&n.push(i);}catch(a){x.warn({err:a},`Failed to check if env file ${i} exists`);}});try{Mht({filesToWatch:n,revalidator:t,signal:o,project:e});}catch(r){x.error({err:r},"Failed to start config file watchers");}};async function iE({project:e,apiClient:t}){let o=n=>cl({project:n,apiClient:t});$f(await o(e),async n=>o(await on({configFilePath:n})));}var Xt=()=>{if(!w0)throw new ae("No Momentic project is currently loaded. Open or select a project before invoking this action.");return w0};function Mht({filesToWatch:e,revalidator:t,signal:o,project:n}){x.debug("Starting watch on the following files:"),e.forEach(r=>{x.debug(`- ${r}`);}),e.forEach(r=>{let i=async(s,l)=>{if(s.mtime.getTime()!==l.mtime.getTime()){kht.increment("setLocalProject")&&x.warn(`A file change under the ${n.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{w0=await Promise.resolve(t(n.configFilePath));}catch(c){x.warn({err:c},`Failed to reload Momentic configuration after a change to ${r}; continuing with the previously loaded configuration`);}}};Un__default.watchFile(r,{persistent:false},i);let a=()=>{Un__default.unwatchFile(r,i),o.removeEventListener("abort",a);};o.addEventListener("abort",a);});}function So(e){return function(...t){let o=t[t.length-1],n=e(...t);Promise.resolve(n).catch(o);}}var Nht="3.62.3",Nh=Iv({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:Nht});(async()=>{try{let e=await wu(Nh);e.gitBranchName&&Nh.addBinding("branch",e.gitBranchName);}catch{}})();var XTe=Router();XTe.get("/",async(e,t)=>{let o=Xt(),n=hr();if(!n){t.status(500).json({message:"API client not initialized"});return}let r=await Vm(Nh,n,o),i=r?.gitProtectedBranches&&r?.gitBranchName&&r.gitProtectedBranches.includes(r.gitBranchName),{noCache:a,alwaysSaveCache:s}=Cd(),l=!a&&(s||!i);t.status(200).json({saveCaches:l,checkedOutBranch:r?.gitBranchName});});var KK=XTe;var Bht=5e3,Uht=[".js",".mjs",".cjs",".ts"];function YK(e={}){let t=Router();function o(){let d=Xt();return Cn__default.dirname(d.configFilePath)}function n(d){return Cn__default.join(o(),...d)}function r(d){let m=Cn__default.relative(o(),d);return m?m.split(Cn__default.sep):[]}function i(d,m){let p=Un__default.statSync(d),h=r(d);return lG.parse({name:m,absolutePath:d,relativePath:h.join(Cn__default.sep),pathSegments:h,isDirectory:p.isDirectory(),size:p.size,createdAt:p.birthtime,modifiedAt:p.mtime,accessedAt:p.atime})}function a(d){let m=Cn__default.relative(o(),d);return m===""||!m.startsWith("..")&&!Cn__default.isAbsolute(m)}async function s(d){let m=Xt();return Om(["*"],{cwd:d,ignore:m.config.exclude??[],maxDepth:1,nodir:false,signal:AbortSignal.timeout(Bht)})}function l(d){let m=d.trimStart().replace(/^file:\/\//,"").replaceAll("\\","/"),p=m.lastIndexOf("/");return p===-1?{directoryText:"",filePrefix:m}:{directoryText:m.slice(0,p+1),filePrefix:m.slice(p+1)}}function c(d){return d.replaceAll("\\","/").split("/").filter(m=>m&&m!==".")}function u({sourceDirectoryPath:d,targetPath:m,isDirectory:p}){let h=Cn__default.relative(d,m).split(Cn__default.sep).join("/");return p?h?`${h}/`:"./":h}return t.post("/file-reference-suggestions",So(async(d,m,p)=>{let h=$te.safeParse(d.body);if(!h.success){m.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??Uht).map(C=>C.toLowerCase())),b=l(f);if(b.directoryText.startsWith("/")){m.status(200).json({suggestions:[]});return}let S=Cn__default.resolve(o(),...c(g)),A=Cn__default.resolve(S,...c(b.directoryText));if(!a(S)||!a(A)){m.status(200).json({suggestions:[]});return}if(!Un__default.existsSync(A)||!Un__default.statSync(A).isDirectory()){m.status(200).json({suggestions:[]});return}let T;try{T=await s(A);}catch(C){if(C instanceof Error&&C.name==="TimeoutError"){m.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw C}let v=T.map(C=>{let O=Cn__default.join(A,C);return {entryName:C,targetPath:O,isDirectory:Un__default.statSync(O).isDirectory()}}),R=b.filePrefix.toLowerCase(),I=v.filter(C=>C.entryName.startsWith(".")||!C.entryName.toLowerCase().startsWith(R)?false:C.isDirectory?true:y.has(Cn__default.extname(C.entryName).toLowerCase())).sort((C,O)=>C.isDirectory!==O.isDirectory?C.isDirectory?-1:1:C.entryName.localeCompare(O.entryName)).map(C=>({name:C.entryName,isDirectory:C.isDirectory,value:u({sourceDirectoryPath:S,targetPath:C.targetPath,isDirectory:C.isDirectory})}));m.status(200).json({suggestions:I});})),t.post("/",So(async(d,m,p)=>{let h,g;try{let T=Hte.parse(d.body);h=T.pathSegments,g=T.directoriesOnly??!1;}catch(T){m.status(400).json({error:`Failed to parse folder read body: ${T}`});return}let f=n(h);if(!Un__default.existsSync(f)){m.status(404).json({error:`Path not found: ${h.join(Cn__default.sep)}`});return}if(!Un__default.statSync(f).isDirectory()){m.status(400).json({error:`Path is not a directory: ${h.join(Cn__default.sep)}`});return}let b;try{b=await s(f);}catch(T){if(T instanceof Error&&T.name==="TimeoutError"){m.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw T}let S=b.map(T=>{let v=Cn__default.join(f,T);return i(v,T)});if(g&&(S=S.filter(T=>T.isDirectory)),e.allowedFileTypes){let T=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 jht(v.absolutePath);return I!==void 0&&T.has(I)?v:null}))).filter(v=>v!==null);}let A={absolutePath:f,pathSegments:h,contents:S};m.status(200).json(A);})),t.put("/",So(async(d,m,p)=>{let h;try{h=Gte.parse(d.body).pathSegments;}catch(y){m.status(400).json({error:`Failed to parse folder create body: ${y}`});return}let g=n(h);if(Un__default.existsSync(g)){m.status(200).json({success:true,message:`Folder already exists: ${h.join(Cn__default.sep)}`,pathSegments:h});return}Un__default.mkdirSync(g,{recursive:true});let f={success:true,message:`Folder created: ${h.join(Cn__default.sep)}`,pathSegments:h};m.status(201).json(f);})),t.patch("/",So(async(d,m,p)=>{let h,g;try{let A=Vte.parse(d.body);h=A.pathSegments,g=A.newPathSegments;}catch(A){m.status(400).json({error:`Failed to parse folder update body: ${A}`});return}let f=n(h),y=n(g);if(!Un__default.existsSync(f)){m.status(400).json({error:`Folder not found: ${h.join(Cn__default.sep)}`});return}if(Un__default.existsSync(y)){m.status(400).json({error:`Destination already exists: ${g.join(Cn__default.sep)}`});return}let b=Cn__default.dirname(y);Un__default.existsSync(b)||Un__default.mkdirSync(b,{recursive:true}),Un__default.renameSync(f,y);let S={success:true,message:`Folder moved from ${h.join(Cn__default.sep)} to ${g.join(Cn__default.sep)}`,pathSegments:g};m.status(200).json(S);})),t.delete("/",So(async(d,m,p)=>{let h,g=true;try{let S=Wte.parse(d.body);h=S.pathSegments,g=S.recursive??!0;}catch(S){m.status(400).json({error:`Failed to parse folder delete body: ${S}`});return}let f=n(h);if(!Un__default.existsSync(f)){m.status(200).json({success:true,message:`Folder not found: ${h.join(Cn__default.sep)}`,pathSegments:h});return}if(!Un__default.statSync(f).isDirectory()){m.status(400).json({error:`Path is not a directory: ${h.join(Cn__default.sep)}`});return}try{if(g)Un__default.rmSync(f,{recursive:!0,force:!0});else {if(Un__default.readdirSync(f).length>0){m.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${h.join("/")}`});return}Un__default.rmdirSync(f);}}catch(S){let{status:A,body:T}=Ibe(S,`delete folder ${h.join("/")}`);m.status(A).json(T);return}let b={success:true,message:`Folder deleted: ${h.join("/")}`,pathSegments:h};m.status(200).json(b);})),t}async function jht(e){try{let t=await Un__default.promises.open(e,"r");try{let o=Buffer.alloc(4096),{bytesRead:n}=await t.read(o,0,o.length,0);return o.toString("utf-8",0,n).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await t.close();}}catch{}}var QTe=Router();QTe.get("/",async(e,t)=>{let o=Xt(),n=hr();if(!n){t.status(500).json({message:"API client not initialized"});return}let r=await Of(Nh,n,o);t.status(200).json(r);});var JK=QTe;var ZTe=Router();ZTe.get("/",async(e,t)=>{let o=hr(),n=[];try{n=await o?.listProductUpdates()??[];}catch(r){Nh.debug({err:r},"Failed to fetch product updates");}t.status(200).json({updates:n});});var XK=ZTe;var $ht=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{sessionId:n}=e;return async()=>{t.info({sessionId:n},"Cancel event received");let r=o.getSession(n);if(!r)throw new Error("No active session found");try{r.controller.setClosed();}catch{}}},eve={event:"cancel",createHandler:$ht};var Ght=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{testId:n,sessionId:r}=e;return async(i,a)=>{let{stepId:s,environment:l,parentStepIdChain:c}=i;t.info({testId:n,stepId:s},"Clearing AI action cache");try{let u=o.getSession(r);if(!u)throw new Error("No active session found");let d=zv(s,c.join(":")||void 0);await Promise.all(d.map(m=>u.cacheStorage.deleteStepCacheEntry({logger:t,testId:n,key:m,environment:l}))),a({ok:!0});}catch(u){t.error({testId:n,stepId:s,err:u},"Failed to clear AI action cache"),a({ok:false,error:W(u)});}}},tve={event:"clearAIActionCache",createHandler:Ght};var Vht=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{sessionId:n}=e;return async(r,i)=>{let a=o.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=(await s.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});}}},ove={event:"fetchA11yTree",createHandler:Vht};var Wht=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{sessionId:n}=e;return async(r,i)=>{let a=o.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=await s.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});}}},nve={event:"fetchDom",createHandler:Wht};var qht=({metadata:e,logger:t,globalE2eStateManager:o})=>{let{sessionId:n}=e;return r=>{t.info({sessionId:n,reason:r},`Disconnect event received (${r})`),o.removeSession(n,t);}},rve={event:"disconnect",createHandler:qht};function Hl(e){let{result:t,nestedResults:o}=e;if(!e.nestedResults.length)return;let{firstMetadata:n,lastMetadata:r}=Kht(o);Yht(t,n,r);let i=o[o.length-1];i.status!=="SUCCESS"&&(t.message=i.message,t.failureReason=i.failureReason,t.failureClassification=i.failureClassification);let a=[...e.asyncTasks];e.asyncTasks.push((async()=>{try{await Jht(a,t,n,r);}catch(s){e.logger.error({result:e.result,err:s},"Error hoisting scalar result metadata");}})());}function Kht(e){let t=e[0],o;for(;;){switch(t.type){case "PRESET_ACTION":case "CONDITIONAL":o=t;break;case "AI_ACTION_DYNAMIC":case "AI_ACTION":case "MODULE":case "SECTION":case "WHILE_LOOP":if(!t.results.length){o=t;break}t=t.results[0];break;default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(o)break}let n=e[e.length-1],r;for(;;){switch(n.type){case "PRESET_ACTION":{r=n;break}case "AI_ACTION_DYNAMIC":case "CONDITIONAL":case "AI_ACTION":case "MODULE":case "SECTION":case "WHILE_LOOP":if(!n.results.length){r=n;break}n=n.results[n.results.length-1];break;default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(r)break}return {firstMetadata:o,lastMetadata:r}}function Yht(e,t,o){t&&(e.beforeUrl=t.beforeUrl),o&&(e.afterUrl=o.afterUrl,e.data=o.data);}async function Jht(e,t,o,n){await Promise.allSettled(e),o&&(t.beforeSnapshot=o.beforeSnapshot),n&&(t.afterSnapshot=n.afterSnapshot);}function Hx(e,t,o){let n={};return Object.entries(t).forEach(([i,a])=>{n[i]=JSON.stringify(a);}),{type:"MODULE",id:e.id,moduleId:e.moduleId,moduleName:e.name,startedAt:new Date,cacheConfig:e.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:o}}async function Gf(e,t,o){return Xht(e,t,o)}async function Xht(e,t,o){let n=new Date;try{return o.throwIfAborted(),await t()}catch(r){let i=new Date,a="FAILED",s;if(o.aborted||r instanceof DOMException&&r.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):r instanceof ie?s=`${r}`:s=`An unexpected error occurred: ${r.message}`,e.type==="RESOLVED_MODULE"){let l=Hx(e,{},"FAILED");return l.message=s,l.startedAt=n,l.finishedAt=i,l}return {...Xv(e),startedAt:n,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function Ts(e,t){let o=false;try{return e&&!e.state.failureRecoveryDisabled&&(e.state.failureRecoveryDisabled=!0,o=!0),await t()}finally{e&&o&&(e.state.failureRecoveryDisabled=void 0);}}var aE=20,x0=100;function QK(e){return e.baseDerivedFrom==="estimate"}var Qht={config:"the main branch configured for this project","run-metadata":"the main branch recorded with this run","origin-head":"the remote's default branch from origin/HEAD, which git records at clone time and never refreshes \u2014 if this repository's default branch has changed since, this window is against the old one",estimate:"an estimate: a fixed number of commits back from head, because the main branch could not be resolved. The window therefore contains commits made on the main branch that this branch did not make, and a file may appear newly added when it merely predates the base. Do not conclude that this branch introduced a change from its presence in this window alone"};function _0(e){return e.baseDerivedFrom?` The base of this comparison window is ${Qht[e.baseDerivedFrom]}.`:""}function D({text:e,section:t}){if(!t)return [{type:"text",text:e}];let o=`### ${t}`;return e.length===0?[{type:"text",text:o}]:[{type:"text",text:`${o}
486
486
  ${e}`}]}function Ra({base64Data:e,mediaType:t,section:o}){return o?[{type:"text",text:`### ${o}`},{type:"media",data:e,mediaType:t}]:[{type:"media",data:e,mediaType:t}]}function O0(e,t){return {role:"user",content:e.map(n=>n.type==="media"?{...n,type:"file"}:{type:"text",text:n.text}),providerOptions:t}}function eY(e){return e.map(t=>t.role==="tool"?{...t,content:t.content.map(o=>o.type==="tool-result"?{...o,output:we(o.output)}:o)}:t.role==="assistant"&&Array.isArray(t.content)?{...t,content:t.content.map(o=>o.type==="tool-result"?{...o,output:we(o.output)}:o)}:t)}function we(e){return e.type!=="content"?e:{...e,value:e.value.map(t=>t.type==="media"?{...t,type:"file",data:{type:"data",data:t.data}}:t)}}function J(e){if(e.length===0)throw new yo("No content parts provided to construct the tool response content.");return {type:"content",value:e}}function $l(e){return {type:"content",value:[{type:"text",text:e}]}}function tY({data:e,filters:t}){let o=Ase(e,t??[]);return kg(o)?o:{}}function P0({data:e,filters:t,tokenLimit:o,perItemLimit:n=Math.max(1,Math.floor(o/4))}){let r=tY({data:e,filters:t}),i=JSON.stringify(r,null,2);if(Gt(i)<=o)return i;let a=oY({environmentVariables:r,perItemLimit:n}),s=JSON.stringify(a,null,2);return Gt(s)<=o?s:JSON.stringify(nY(a,o),null,2)}function oY({environmentVariables:e,perItemLimit:t}){return Object.fromEntries(Object.entries(e).map(([o,n])=>{if(kg(n))return [o,ive(n,t)];let r=ive({[o]:n},t);return [o,r[o]]}))}function ive(e,t=2e4){let o={};for(let[n,r]of Object.entries(e)){if(typeof r=="object"&&r!==null){let i=JSON.stringify(r,null,2);if(Gt(i)>t){o[n]="[too large truncated]";continue}o[n]=r;continue}if(typeof r=="string"){o[n]=Zht(r,t);continue}o[n]=r;}return o}function Zht(e,t){let o=Gt(e);if(o<=t)return e;let n=Math.max(1,Math.floor(t*(e.length/o)));return `${e.slice(0,n)}... [truncated]`}function nY(e,t){let o={},n=0,r=Object.entries(e).map(([i,a])=>{let s=JSON.stringify(a,null,2),l=Gt(s);return {key:i,value:a,tokens:l}}).sort((i,a)=>i.tokens-a.tokens);for(let{key:i,value:a,tokens:s}of r)n+s<=t&&(o[i]=a,n+=s);return o}function ave({projectRoot:e,filePath:t,pathLabel:o="path"}){if(!t||!Cn__default.isAbsolute(t))return t;let n=Cn__default.relative(e,t);if(n.startsWith("..")||Cn__default.isAbsolute(n))throw new Error(`Error: ${o} "${t}" must be inside project root "${e}".`);return n}function sve(e){return e.map(t=>{switch(t.type){case "text":return t;case "media":return {type:"image",data:t.data,mimeType:t.mediaType};default:return (n=>{throw new Error("Unhandled content part")})()}})}var mve=["__generated__"],pve=[".env",".npmrc",".netrc",".git-credentials","credentials","credentials.json"],hve=[".env.","id_rsa","id_ecdsa","id_ed25519","service-account"],gve=[".pem",".key",".p12",".pfx",".keystore",".jks",".tfstate"],fve=[".tfstate."],M0=[...pve.map(e=>`**/${e}`),...hve.map(e=>`**/${e}*`),...gve.map(e=>`**/*${e}`),...fve.map(e=>`**/*${e}*`)];function lve(e){let t=Cn__default.basename(e).toLowerCase();return pve.includes(t)||hve.some(o=>t.startsWith(o))||gve.some(o=>t.endsWith(o))||fve.some(o=>t.includes(o))}function sE(e){return `Relative paths resolve at the Git repository root \`${e}\`, never at the server cwd; absolute paths are also accepted.`}function cve(e,t){return Cn__default.resolve(Cn__default.resolve(e),t)}async function $x(e,t){let o=cve(e,t);if(Cn__default.isAbsolute(t)||await uve(o))return o;let n=cve(process.cwd(),t);return n===o||!await uve(n)?o:n}async function uve(e){try{return await iY.stat(e),!0}catch{return false}}async function yve(e,t){let o=await $x(e,t);if(lve(o))throw new Error(`Path '${t}' matches the sensitive-file deny list (likely credentials or secrets) and cannot be read.`);let n=await iY.realpath(o);if(lve(n))throw new Error(`Path '${t}' matches the sensitive-file deny list (likely credentials or secrets) and cannot be read.`);return n}var tgt=z.object({pattern:z.string().min(1).describe("Glob pattern to match against file paths (relative to the search root). Patterns are NOT recursive by default \u2014 `*` matches a single path segment, the same way shell globs do. Prefix with `**/` for recursive globs (e.g. `**/*.ts` to find all TypeScript files, `**/open-app*` to find any file whose basename starts with `open-app`)."),path:z.string().optional().describe("Optional directory to start the search in. Relative paths resolve at the Git repository root given in this tool's description, not at the server cwd. Defaults to the repository root."),maxResults:z.int().min(1).max(1e3).default(100).describe("Maximum number of paths to return. Defaults to 100.")});function ogt(e){return `Find files by glob pattern. ${sE(e)} Skips common build/dependency/IDE directories (package manager folders, .git, dist, build, .next, __generated__, etc.) by default. Returns one repo-relative path per line.`}function N0(e){return {tool:tool({description:ogt(e.repoRoot),inputSchema:tgt,execute:async(o,{abortSignal:n})=>{let r=await ngt(o,e,n);return J(D({text:rgt(o.pattern,r)}))},toModelOutput:({output:o})=>we(o)}),name:Vr}}async function ngt({pattern:e,path:t,maxResults:o},n,r){let i=au({signal:r,timeoutMs:3e4});i.throwIfAborted();let a=Cn__default.resolve(n.repoRoot),s=t?await $x(a,t):a,l=await Om([e],{cwd:s,ignore:[...mve.map(c=>`**/${c}`),...M0],maxDepth:1/0,nodir:true,signal:i});return i.throwIfAborted(),l.slice(0,o).map(c=>Cn__default.relative(a,Cn__default.resolve(s,c)))}function rgt(e,t){return t.length===0?!e.includes("**/")&&!e.startsWith("**")?`(no matching files. Tip: '${e}' only matches at the top of the search root \u2014 prepend '**/' for a recursive match, e.g. '**/${e}'.)`:"(no matching files)":t.join(`
487
487
  `)}async function D0({baseRef:e,headRef:t,context:o,abortSignal:n}){if(!e&&!t)return {baseSha:o.baseSha,headSha:o.headSha};if(!e||!t)throw new Error("baseRef and headRef must be provided together");let[r,i]=await Promise.all([Wa(`${e}^{commit}`,o.repoRoot,n),Wa(`${t}^{commit}`,o.repoRoot,n)]);if(!r)throw new Error(`Could not resolve baseRef '${e}'`);if(!i)throw new Error(`Could not resolve headRef '${t}'`);return {baseSha:r,headSha:i}}function Gx({lines:e,startLine:t,maxLines:o,maxBytes:n,truncateLineChars:r}){let i=e.length,a=Math.max(1,t);if(a>i)return {content:"",endLine:a-1,droppedLines:0,droppedBytesFromByteCap:0};let s=Math.min(i,a-1+o),l=e.slice(a-1,s).map(g=>r?bve(g,300):g),c=l.join(`
488
488
  `),u=Buffer.byteLength(c,"utf-8");if(u<=n)return {content:c,endLine:s,droppedLines:i-s,droppedBytesFromByteCap:0};let d=0,m=0;for(let g of l){let f=(d===0?0:1)+Buffer.byteLength(g,"utf-8");if(d>0&&m+f>n)break;m+=f,d++;}let p=l.slice(0,d).join(`
@@ -2658,7 +2658,7 @@ ${e}`;default:return e}}async function kc({frameConfig:e,action:t,browser:o}){le
2658
2658
  ${u.join(`
2659
2659
  `)}`,g.tokenLength=f,g.ids=[...new Set([...g.ids,...m])]):s.push({ids:m,content:u.join(`
2660
2660
  `),tokenLength:d});}return s.forEach((g,f)=>{let y=g.ids[0],b=g.ids[g.ids.length-1];e.debug({tokenLength:g.tokenLength,minId:y,maxId:b},`Chunk for page filtering (index ${f+1}/${s.length})`);}),{chunks:s}}var bOe=5e6,YOt=1e5,JOt=3e4,XOt=6e4,QOt=1e5;async function Lc(e){let{fixtures:t}=e,{logger:o}=t,n=e.tree,r=e.serializedTree,i=Gt(r);if(i>bOe)throw new ie("UserConfigurationError",`Page accessibility tree is too large for AI page filtering (${i} tokens). Maximum supported size is ${bOe} tokens.`);if(i>YOt){let a=e.options?.useJev===true,s=yOe({serializedTree:r,options:a?gOe:hOe,logger:o}),l=randomUUID();n=await ZOt({...e,chunks:s.chunks,callId:l,useJev:a}),r=n.serialize();let c=Gt(r);o.info({oldTokens:i,newTokens:c,langfuseCallId:l},"Filtered page using AI chunk ranking");}return r}async function ZOt({type:e,callId:t,chunks:o,description:n,fixtures:r,tree:i,useJev:a}){let{generator:s,signal:l,logger:c}=r,u=await s.rankChunksWithAi({chunks:o,description:n,type:e,softTokenLimit:JOt,mediumTokenLimit:XOt,hardTokenLimit:QOt,callId:t,useJev:a},{abortSignal:l,logger:c,loggerTags:Wo(c)}),d=[];return o.forEach((p,h)=>{u.indices.includes(h)&&(d=d.concat(p.ids));}),i.pruneUsingRelevantIds(new Set(d))}function tPt(e,t){return t.markIneligibleElementsInChecks===true&&e.source==="ELEMENT_CHECK"&&e.allowNotActionableNodesOverride===false?true:void 0}async function u5(e,t){if(!e.description)throw new ie("UserConfigurationError","Cannot locate element with empty description");return kc({action:async()=>TOe(e,t),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:t.browser,logger:e.logger})}async function SOe(e,t){if(e.length===0)return [];if(e.some(s=>s.iframeUrl))throw new ie("UserConfigurationError","Batch element location does not support explicit iframe URLs");let o=e[0],n=e.findIndex(s=>s.allowNotActionableNodesOverride!==o.allowNotActionableNodesOverride||s.allowIneligibleTagRedirect!==o.allowIneligibleTagRedirect||s.showZeroOpacityElementsOverride!==o.showZeroOpacityElementsOverride||s.filterByViewport!==o.filterByViewport||s.skipWait!==o.skipWait);if(n!==-1)throw new ie("UserConfigurationError",`Batch element location requires identical page-capture settings, but target ${n+1} differs from target 1`);let r=await vOe(o,t),i=Promise.resolve(),a=async s=>{let l=i.then(s,s);return i=l.then(()=>{},()=>{}),l};return Promise.allSettled(e.map(s=>TOe(s,t,{...r,materialize:a})))}async function TOe(e,t,o){let{disableCache:n,testContext:r,source:i,memory:a,logger:s,skipSavingVisualAttributes:l,isAutoHeal:c,cacheBustReason:u,acceptElementMovedError:d,pastLocatorMiss:m}=e,{orgId:p,browser:h,codeEvaluator:g,generator:f,abortSignal:y}=t,b=e.description,S=Ar(),A=e.useMemory&&!n;r&&(b=await Es({orgId:p,s:b,context:r,codeEvaluator:g,signal:y,logger:s})),i&&(b=cOe(b,i));let{serializedTree:T,tree:v,screenshotBuff:R}=o??await vOe(e,t);if(m?.serializedTree===T&&m?.screenshotBuff?.equals(R))throw s.info("Skipping AI locate, the page is unchanged since the last miss"),new zy("Could not find any relevant element: the page has not changed since the last attempt",void 0);let I=T,C=false,P=`data:image/jpeg;base64,${R.toString("base64")}`,k=Wo(s);I=await Lc({type:"locator",description:b,screenshot:P,serializedTree:T,tree:v,fixtures:{generator:f,signal:y,logger:s,orgId:p},options:t.pageFiltering}),I!==T&&(C=true);let N=await S.startAsyncSpan("AI_LOCATOR_CALL",async K=>{c&&(K.attributes.isAutoHeal=true),u&&(K.attributes.cacheBustReason=u);let ee=await f.getElementLocation({browserState:I,goal:b,screenshot:P,source:i,markIneligibleElementsInChecks:tPt(e,h.userBrowserSettings),memory:A?a:void 0},{disableCache:n,effort:e.effort,onEffectiveEffort:e.onEffectiveEffort,abortSignal:y,logger:s,loggerTags:k,useMemory:A,cacheBustReason:u});if(K.result=ee,A&&(K.attributes.useMemory=true,K.attributes.memoryTraces=ee.rememberedTraces??[],ee.updatedMemory&&(K.attributes.memorySavedNewResult=true)),S.storeTraceAsset){let z=randomUUID();S.storeTraceAsset({snapshotId:z,data:R}),K.screenshotSnapshotId=z;}return ee});if(s.debug({usedRag:C,result:N},"Got locator result"),!(N.id>0))throw m&&(m.serializedTree=T,m.screenshotBuff=R),new zy(`Could not find any relevant element: ${N.thoughts}`,N.updatedMemory?{type:"GCS_TRACES",traces:N.updatedMemory}:void 0);let L=()=>S.startAsyncSpan("TARGET_RESOLUTION",async K=>{let ee=await h.createTargetFromA11yId({id:N.id,requirements:N.requirements,additionalElements:N.additionalElements,description:b,targetSource:"AI",logger:s,skipSavingVisualAttributes:l,acceptElementMovedError:d});return K.result={serializedElement:ee.target.nodeOnlySerializedHtml??"Unknown HTML element"},ee}),{resolution:G,target:X,frameConfig:B}=o?.materialize?await o.materialize(L):await L();if(G.a11yNode?.properties?.hidden&&G.a11yNode?.properties?.hidden!=="false")throw new ie("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: ${G.displayString}`);return A&&(N.updatedMemory?X.memory={type:"GCS_TRACES",traces:N.updatedMemory}:a&&(X.memory=a)),{thoughts:N.thoughts,target:X,resolution:G,frameConfig:B,screenshot:P}}async function vOe(e,t){let{allowNotActionableNodesOverride:o,allowIneligibleTagRedirect:n,showZeroOpacityElementsOverride:r,filterByViewport:i,skipWait:a,logger:s}=e,{browser:l,abortSignal:c}=t,u=Ar(),{serializedTree:d,tree:m}=await u.startAsyncSpan("GET_PAGE_STATE",async()=>Mc(l,{allowNotActionableNodesOverride:o,allowIneligibleTagRedirect:n,showZeroOpacityElementsOverride:r,filterByViewport:i,abortSignal:c,skipWait:a,logger:s}),{}),p=await u.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let h,g=Date.now(),f;for(;!h&&Date.now()-g<3e3;){c.throwIfAborted();try{h=await l.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(y){f=y;}}if(!h)throw new ie("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${f?.message}`);return h});return {serializedTree:d,tree:m,screenshotBuff:p}}var oPt=15;async function nU({command:e,logger:t,fixtures:o,useMemory:n,maxRetries:r=oPt,recoveryHint:i,effort:a,onEffectiveEffort:s}){if(!e.assertion.trim())throw new ie("ActionFailureError","Assertion command is missing the assertion content");let l=a1.optional().catch(void 0).parse(e.source);e.source&&!l&&t.warn(`Invalid source ${e.source} for AI assertion, ignoring...`);let c=Ar();return c.startAsyncSpan("AI_ASSERTION_CALL",async u=>{let{browser:d}=o,m=e.timeout?e.timeout*1e3:d.smartWaitingTimeout,p=kce(m,r-1),h=0,g=Date.now(),f=g+m,y=g,b,S,A;try{await kc({action:()=>d.clearHighlights(),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:d,logger:t});}catch(R){t.warn({err:R},"Failed to clear highlights before AI check, continuing...");}for(;h<r;){o.abortSignal.throwIfAborted();let R=Date.now();if(h>0){if(R>=f)break;let O=f-R,P=y-R,k=Math.min(P,O);k>0&&await Pt(k,o.abortSignal);}let I=Date.now();if(h>0&&I>=f)break;let C=false;try{if(b=await kc({action:async()=>{let P=await EOe(d,t,o.abortSignal);return S&&S.serializedTree===P.serializedTree&&S.screenshotBuff.equals(P.screenshotBuff)?(C=!0,b):(S=P,wOe({command:e,state:P,fixtures:o,useMemory:n,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:h,logger:t,source:l,recoveryHint:i,effort:a,onEffectiveEffort:s}))},frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:d}),b?.aiResult.result){b?.updatedMemory&&vI(e,b.updatedMemory,t);break}else throw b?.aiResult.thoughts?new ie("AssertionFailureError",b.aiResult.thoughts):new ie("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(O){o.abortSignal.throwIfAborted(),A=O instanceof Error?O:new Error(`${O}`),C?t.info(`AI check attempt ${h} failed (re-used previous result)`):t.info({err:O},`AI check assert attempt ${h} failed, retrying...`);}finally{h++,y=I+p;}}if(!b?.aiResult.result){let R=f-Date.now();R>0&&await Pt(R,o.abortSignal);}if(!b?.aiResult.result)try{b=await kc({action:async()=>wOe({command:e,state:await EOe(d,t,o.abortSignal),fixtures:o,useMemory:n,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:h,logger:t,recoveryHint:i,effort:a,onEffectiveEffort:s}),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:d});}catch(R){o.abortSignal.throwIfAborted(),A=R instanceof Error?R:new Error(`${R}`);}finally{h++;}b?.updatedMemory&&vI(e,b.updatedMemory,t);let T=b?.afterScreenshotOverride;if(T&&c.storeTraceAsset){let R=randomUUID();c.storeTraceAsset({snapshotId:R,data:T}),u.screenshotSnapshotId=R;}let v=b?.elementScreenshotOverride;if(v&&c.storeTraceAsset){let R=randomUUID();c.storeTraceAsset({snapshotId:R,data:v}),u.elementScreenshotSnapshotId=R;}if(n&&(u.attributes.useMemory=true,u.attributes.memoryTraces=b?.aiResult.rememberedTraces??[],b?.updatedMemory&&(u.attributes.memorySavedNewResult=true)),!b?.aiResult.result){u.result=b?.aiResult??{thoughts:A?.message??"AI check failed after all attempts",result:false};let R=`AI check still failing after ${h} attempts.`;throw A&&(R+=` Latest result: ${A.message}`),new ie("AssertionFailureError",R)}return u.result=b.aiResult,{...b,thoughts:b.aiResult.thoughts,succeedImmediately:false,urlAfterCommand:d.url()}})}async function EOe(e,t,o){await e.waitForPageLoad({signal:o});let[n,r]=await Promise.all([Mc(e,{abortSignal:o,skipWait:true,skipWaitForPageLoad:true,logger:t}),e.screenshot({retries:1,respectActiveFrame:true})]);return {...n,screenshotBuff:r}}async function wOe({command:e,state:t,fixtures:o,useConsensus:n,useMemory:r,highlightElementsOnFailure:i,attemptNumber:a,source:s,logger:l,recoveryHint:c,effort:u,onEffectiveEffort:d}){let {browser:m,generator:p,abortSignal:h}=o,{serializedTree:f,tree:y}=t,b=t.screenshotBuff,S=b.toString("base64"),A=m.url(),T=e.contextChoice??"MULTIMODAL",v=f;T!=="VISION_ONLY"&&(v=await Lc({type:"assertion",serializedTree:f,tree:y,description:e.assertion,screenshot:S,fixtures:{generator:p,signal:h,logger:l,orgId:o.orgId},options:o.pageFiltering}),v);let R={goal:e.assertion,url:A,memory:r?e.cache?.memory:void 0,browserState:v,screenshot:S,contextChoice:T,source:s,recoveryHint:c},C=await(T==="VISION_ONLY"?(P,k)=>p.getVisualAssertionResult(P,k):(P,k)=>p.getAssertionResult(P,k))(R,{useConsensus:n,attemptNumber:a,useMemory:r,disableCache:!!e.disableCache,effort:u,onEffectiveEffort:d,abortSignal:h,logger:l,loggerTags:Wo(l)}),O;if((C.result||i)&&C.relevantElements?.length){C.relevantElements.map(P=>m.getSerializedFormFromA11yId(P)).filter(P=>!!P);try{let P=C.relevantElements[0],{resolution:k}=await m.createTargetFromA11yId({id:P,description:null,targetSource:"AI",skipSaveToCache:!0});O=await m.screenshot({locator:k.locator,clearHighlights:!0,respectActiveFrame:!0});}catch(P){l.debug({err:P},"Failed to capture element screenshot for trace, continuing...");}await nPt(C.relevantElements,m,l);}return {aiResult:C,afterScreenshotOverride:b,elementScreenshotOverride:O,updatedMemory:r?C.updatedMemory:void 0}}async function nPt(e,t,o){let n=Date.now();for(let r of e){if(Date.now()-n>2e3){o.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await ye(t.highlightA11yId(r),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}});}catch(i){o.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}async function COe(e){let{command:t,logger:o,fixtures:n,disableCache:r,autoExpandIframes:i}=e,{browser:a,generator:s,abortSignal:l}=n;if(!t.goal.trim())throw new ie("ActionFailureError","Cannot perform AI extraction without goal");if(t.schema){let m=Fie(t.schema);if(m)throw new ie("UserConfigurationError",m)}let c;i&&!t.iframeUrl?c=(await a.evaluateFunctionInAllFrames(rPt,{bannedAttributes:a.userBrowserSettings.bannedAttributes})).join(`
2661
- `):c=await a.getCondensedHtml();let u=await a.screenshot({retries:2,respectActiveFrame:true}),d=Ar();try{return await d.startAsyncSpan("AI_EXTRACTION_CALL",async m=>{let p=await s.getTextExtraction({goal:t.goal,browserState:c,returnSchema:t.schema,screenshot:`data:image/jpeg;base64,${u.toString("base64")}`},{disableCache:r,abortSignal:l,loggerTags:Wo(o)});if(m.result=p,iPt({tracer:d,span:m,screenshot:u,htmlState:c,logger:o}),p.result==="NOT_FOUND")throw new ie("ActionFailureError","No relevant data found for extraction goal on this page");if(p.thoughts?.includes("MaxGenerationLengthExceededError"))throw new ie("UserConfigurationError",p.thoughts);return {thoughts:p.thoughts||void 0,data:p.result,succeedImmediately:!1,urlAfterCommand:a.url()}})}catch(m){let p=W(m);throw p.includes("MaxGenerationLengthExceededError")?new ie("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 ie("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:m}}):m}}function rPt({bannedAttributes:e}){return window._momentic?.getCondensedHtmlTree?.({bannedAttributes:e})?.result??""}function iPt(e){let{tracer:t,span:o,screenshot:n,htmlState:r,logger:i}=e;if(t.storeTraceAsset)try{let a=randomUUID();t.storeTraceAsset({snapshotId:a,data:n}),o.screenshotSnapshotId=a;let s=randomUUID();t.storeTraceAsset({snapshotId:s,data:Buffer.from(r),extension:"html"}),o.browserStateSnapshotId=s;}catch(a){i.debug({err:a},"Failed to store extraction trace assets");}}var IOe=500;async function xOe(e,t){let{logger:o}=e,{abortSignal:n,browser:r}=t,i=Date.now();try{await aPt(i,e,t);}catch(a){if(_p(a)||n.aborted)return;o.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=r.smartWaitingTimeout-(Date.now()-i);s>0&&await Pt(s,n);}finally{o.debug({durationMs:Date.now()-i},"AI smart waiting complete");}}async function aPt(e,t,o){let{abortSignal:n,browser:r}=o;if(r.smartWaitingTimeout<3e3){await Pt(r.smartWaitingTimeout,n);return}if(!t.description)throw new ie("UserConfigurationError","Cannot locate element with empty description");await ye(sPt(e,t,o),{milliseconds:r.smartWaitingTimeout});}async function sPt(e,t,o){let{logger:n,iframeUrl:r,testContext:i}=t,{abortSignal:a,browser:s,codeEvaluator:l,orgId:c}=o,u=i?await Es({orgId:c,s:t.description,context:i,codeEvaluator:l,signal:a,logger:n}):t.description,d;for(;Date.now()-e<s.smartWaitingTimeout;){let m=Date.now();if(await kc({action:async()=>{let g=await lPt(u,t,o,d);return d=g.notReadyScreenshot,g.isReady},frameConfig:r?{type:"url",url:r}:void 0,browser:s,logger:n}))return;let h=Date.now()-m;h<IOe&&await Pt(IOe-h,a);}}async function lPt(e,t,o,n){let{logger:r}=t,{browser:i,abortSignal:a,generator:s}=o;a.throwIfAborted();let l;try{l=await i.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(m){throw new ie("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: ${m instanceof Error?m.message:m}`)}if(n?.equals(l))return r.debug("Skipping smart waiting AI call, the page is unchanged"),{isReady:false,notReadyScreenshot:n};let u=`data:image/jpeg;base64,${l.toString("base64")}`;a.throwIfAborted();let d=await s.getSmartWaitingDecision({description:e,screenshot:u},{abortSignal:a,loggerTags:Wo(r)});return r.debug({result:d},"Got smart waiting result"),{isReady:d.isPageReady,notReadyScreenshot:d.isPageReady?void 0:l}}var cPt=3e4;function uPt({command:e,originalCache:t,cacheToUse:o,keepMemory:n}){if(o){if(n){let r=eV(t,o);return o.target=r.target,o.updatedAt=r.updatedAt,o}if(!t){let r=lm(e);r!=="NEGATED_CHECK"&&r!=="NEGATED_ELEMENT_VISIBLE_CHECK"&&(e.cache=void 0);return}return o.target=t.target,o.updatedAt=t.updatedAt,o}}async function POe(e){return Ar().startAsyncSpan("ELEMENT_ASSERTION",async o=>dPt(e,o),{name:"Element check"})}async function dPt(e,t){let{command:o,timeoutMs:n,fixtures:r,disableCache:i}=e,{abortSignal:a}=r,s=()=>_P(o.cache)?o.cache:void 0,l=s(),c=!i&&!!l?.target&&hT(l.target),u=cloneDeep(l),d=(T=false)=>{l=uPt({command:o,originalCache:u,cacheToUse:s(),keepMemory:T});},m={},p=Date.now(),h=c?Math.max(n/10,cPt):0,g=p,f=0,y,b=500,S=false;for(;f<2||Date.now()-p<n;){f++,f>1&&await Pt(b,a),a?.throwIfAborted(),l=s();let T=f===1,v=c&&Date.now()-g>=h;v&&(g=Date.now());let{result:R,elementWasFound:I}=await _Oe({cacheToUse:l,skipAISmartWaiting:!T,useAIIfCacheFails:!c||v,pastLocatorMiss:m,params:e});if(y=R,S=S||I,R.success)break;d(),b=Math.min(b*1.25,1e4);}if(!y)throw new ie("InternalPlatformError",`Failed to evaluate manual element assertion in ${n}ms.`);if(a?.throwIfAborted(),!y.success){let T=s(),v=T?.target?.memory?{target:{id:-1,memory:T.target.memory}}:void 0,{result:R,elementWasFound:I}=await _Oe({cacheToUse:v,skipAISmartWaiting:true,useAIIfCacheFails:true,params:e});y=R,S=S||I,y.success||d(true);}let A=s();return y.success&&A?.target&&!S&&(A.target=rf(A.target),A.updatedAt=new Date),t.result={success:y.success,message:y.err?.message},y}async function _Oe({cacheToUse:e,skipAISmartWaiting:t,useAIIfCacheFails:o,pastLocatorMiss:n,params:r}){let{command:i,disableCache:a,fixtures:s,tracer:l,targetingWrapper:c}=r,{logger:u}=s;if(i.target&&!Gu(i.target))throw new Error("Element assertion with x/y is not supported yet");let d=sle(i.assertion),m=mPt(i.assertion),p,h=false,g=cloneDeep(e);try{let{elementInteractedDisplayString:f,result:y,thoughts:b}=await c({tracer:l,command:i,target:i.target,cache:g?.target,action:async S=>pPt(S.locator,r),options:{...i,allowNotActionableNodesOverride:m,allowIneligibleTagRedirect:m,showZeroOpacityElementsOverride:!0,disableCache:a,memory:g?.target?.memory,disableGlobalLocatorRedirect:!0,source:lm(i),skipAISmartWaiting:t,targetName:"target",pastLocatorMiss:n},retriesWithAI:o?1:0});return p={success:y.success,data:y.data,err:y.err,elementInteractedDisplayString:f,thoughts:b},h=!0,y.success||(u.warn({aiThoughts:b,elementString:f,err:y.err},"Element check found an element but failed"),p={...y,thoughts:b}),{result:p,elementWasFound:h}}catch(f){if(d)return p={success:true,thoughts:`The element described does not exist on the page: ${f.message}`,err:void 0,data:void 0},{result:p,elementWasFound:h};if(!(f instanceof ie)||f.reason!="ActionFailureError")throw f;return p={success:false,err:f,data:void 0,thoughts:void 0},u.warn({err:f},"Element check did not find an element and failed"),{result:p,elementWasFound:h}}}function mPt(e){return !(e.type==="ELEMENT_EXISTENCE"&&e.condition==="VISIBLE"&&!e.negated)}async function pPt(e,{command:t,fixtures:o}){return await o.browser.highlight(e),await hPt(e,t.assertion)}async function hPt(e,t){let o=true,n,r;switch(t.type){case "ELEMENT_CONTENT":{let a=await e.textContent()??"";if(r={elementTextContent:Dn(a,500,true)},!bI(a,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let s=Uv(t);o=false,n=new ie("AssertionFailureError",`The content ${s} '${t.value}': ${a}`);}break}case "ELEMENT_ATTRIBUTE":{r={elementOuterHtml:Dn(await e.evaluate(s=>s.cloneNode(false).outerHTML),500,true)};let a=null;try{a=await e.getAttribute(t.attr,{timeout:3e3});}catch(s){n=new ie("AssertionFailureError",W(s)),o=false;break}if(!bI(a,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let s=Uv(t);o=false,t.operation==="EXISTS"?n=new ie("AssertionFailureError",`The attribute ${t.attr} ${s}`):n=new ie("AssertionFailureError",`The attribute ${t.attr} ${s} '${t.value}': ${a}`);}break}case "ELEMENT_EXISTENCE":{switch(t.condition){case "VISIBLE":{o=await e.evaluate(async(s,l)=>{let c=Date.now();for(;Date.now()-c<l;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return true}return false},jc*1e3);break}case "EDITABLE":{o=await e.isEditable({timeout:jc*1e3});break}case "EXISTS":{o=true;break}case "ENABLED":{o=await e.isEnabled({timeout:jc*1e3});break}case "FOCUSED":{o=await e.evaluate(s=>s===document.activeElement);break}default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})(t.condition)}if(o=t.negated?!o:o,!o){let a=Uv(t);n=new ie("AssertionFailureError",`The element ${a}`);}break}case "ELEMENT_NAME":{let a=await e.evaluate(s=>s.tagName);if(!bI(a,t.value,t.operation,{negated:!!t.negated,ignoreCase:true})){let s=Uv(t);o=false,n=new ie("AssertionFailureError",`The element tag name ${s} '${t.value}': ${a}`);}break}case "ELEMENT_STYLE":{let a=await e.evaluate((s,l)=>window.getComputedStyle(s).getPropertyValue(l),t.property);if(!bI(a,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let s=Uv(t);o=false,t.operation==="EXISTS"?n=new ie("AssertionFailureError",`The style property ${t.property} ${s}`):n=new ie("AssertionFailureError",`The style property ${t.property} ${s} '${t.value}': ${a}`);}break}default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}return {thoughts:void 0,success:o,data:r,err:n}}function kOe(e){return e.type==="ELEMENT_EXISTENCE"&&e.negated&&e.condition==="EXISTS"}async function U_(e,t){let o=await e.screenshot(t),{width:n,height:r}=YB(o);return {buffer:o,width:Math.ceil(n),height:Math.ceil(r)}}async function LOe(e){let{command:t,browser:o,logger:n}=e;if(t.target&&!Gu(t.target))throw new Error("Visual Diff with x/y is not supported yet");return await o.waitForStability({logger:n}),Ar().startAsyncSpan("VISUAL_DIFF",async i=>{try{let a=await fPt(e);return i.result={success:!a.fail,message:a.thoughts},a}catch(a){throw a instanceof ie&&(i.result={success:false,message:a.message}),a}},{name:"Compare against golden"})}async function fPt({tracer:e,command:t,disableCache:o,browser:n,targetingWrapper:r,logger:i,screenshotStorage:a}){let s={clearHighlights:true,hideCaret:true},l=t.target&&Gu(t.target)?t.target:void 0,c;l?.elementDescriptor?c=(await r({tracer:e,command:t,target:l,cache:t.cache?.target,action:async P=>U_(n,{locator:P.locator,...s}),options:{...t,disableCache:o,disableGlobalLocatorRedirect:true,memory:t.cache?.target?.memory,targetName:"target"}})).result:c=await U_(n,s);let u=await a.prepareGoldenScreenshotForComparison(i,t,c);if((c.height!==u.height||c.width!==u.width)&&i.warn({currHeight:c.height,currWidth:c.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-u.height)>10||Math.abs(c.width-u.width)>10){let O=`${c.width}x${c.height}`,P=`${u.width}x${u.height}`;return {fail:true,thoughts:`Current screenshot (${O}) does not match saved screenshot dimensions (${P}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:false,urlAfterCommand:n.url()}}let d=await Jimp.fromBuffer(c.buffer),m={width:c.width,height:c.height},p=await Jimp.fromBuffer(u.buffer),h={width:u.width,height:u.height},g,f=m.width*m.height,y=h.width*h.height,b=Math.abs(m.height-h.height),S=Math.abs(m.width-h.width);if(f>y){let O=d.cover({w:h.width,h:h.height});c.buffer=await O.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height;}else if(y>f){let O=p.cover({w:m.width,h:m.height});u.buffer=await O.getBuffer("image/jpeg"),g="saved";}let A={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},T=t.threshold??.1,R=z_t(d5.decode(u.buffer).data,d5.decode(c.buffer).data,A.data,c.width,c.height,{threshold:T,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,I=R>T*100,C=`Visual diff of ${R.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${T*100}%.`;if(g&&(C+=` The ${g} screenshot was cropped since it was taller by ${b} pixels and wider by ${S} pixels.`),I)throw new ie("ActionFailureError",C);return {fail:I,thoughts:C,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:d5.encode(A,75).data,succeedImmediately:false,urlAfterCommand:n.url()}}var yPt=3e4;function bPt(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(([o,n])=>{t.append(o,n);}),{content:t.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function NOe({command:e,logger:t,baseUrl:o,fetchImplementation:n=fetch}){let r=e.timeout??yPt/1e3,i=Object.fromEntries(Object.entries(e.headers||{}).filter(([h,g])=>h&&g)),a=new URLSearchParams;Object.entries(e.params||{}).filter(([h,g])=>h&&g).forEach(([h,g])=>{a.append(h,g);});let s=a.toString(),l;if(Qv(e.url)&&(l=e.url),o&&Zv(e.url,o)&&(l=new URL(e.url,o).toString()),!l)throw new ie("ActionFailureError",`Invalid URL: ${e.url}`);let c=l;t.info({url:c,searchParams:s,headers:i,body:e.body,method:e.method},"Making HTTP request");let d=await ye((async()=>{let h=s?`${c}?${s}`:c;try{let g=bPt(e),f=new Headers(i);return g.contentType&&!f.has("Content-Type")&&f.set("Content-Type",g.contentType),await n(h,{headers:f,method:e.method,body:g.content})}catch(g){throw new ie("ActionFailureError",`Failed to make HTTP request: ${W(g)}`,{errOptions:{cause:g}})}})(),{milliseconds:r*1e3,fallback:()=>{throw new ie("ActionFailureError",`Fetch request timed out after ${r} seconds`)}});if(!d.ok){let h;try{h=await d.text();}catch(g){h=`Failed to read response body: ${g}`;}throw new ie("ActionFailureError",`Fetch request failed with status ${d.status}: ${h}`)}let m={};d.headers.forEach((h,g)=>{m[g]=h;});let p={status:d.status,headers:m,request:{url:d.url,method:e.method,headers:i}};if(e.body?.type==="json"&&e.body.content)try{p.request.json=JSON.parse(e.body.content);}catch{}if(d.headers.get("content-type")?.includes("json"))try{p.json=await d.json();}catch{}else d.headers.get("content-type")?.includes("text")&&(p.text=await d.text());return p}var SPt=5e3;async function rU({timeout:e=jc,...t}){let o=Date.now(),n=e*1e3,r=n+1e4,i,a=0,s=500;for(;a-o<n;){if(Date.now()-o>r){t.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}t.signal?.throwIfAborted();let l=Date.now();i=await DOe(t),a=Date.now();let c=a-l;if(c>1e3&&t.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await Pt(s,t.signal),s=Math.min(Math.floor(s*1.5),SPt);else return i}return i=await DOe(t),i}async function DOe(e){return Ar().startAsyncSpan("PAGE_ASSERTION",async o=>{let n=await TPt(e);return o.result={success:n.success,message:n.err?.message},n},{name:"Page check"})}async function TPt({assertion:e,browser:t,autoExpandIframes:o}){switch(e.type){case "CONTENT":case "CONTENT":{let r,i=false,a;try{let s;if(o){let l=await t.evaluateFunctionInAllFrames(FOe,{value:e.value,negated:!!e.negated,returnHtml:!1});i=e.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml;}else ({evaluation:i,pageHtml:s}=await t.evaluateFunctionInPage(FOe,{value:e.value,negated:!!e.negated,returnHtml:!0},"checking page content"));if(!i){let l=e.negated?Qp.CONTAINS:Zp.CONTAINS;a=new ie("AssertionFailureError",`The page ${l} '${e.value}'.`),r=s;}}catch(s){a=new ie("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`);}return {success:i,err:a,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 FOe({value:e,negated:t,returnHtml:o}){let n=document.body.innerHTML,r=n.includes(e)===!t;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:r,pageHtml:!r&&o?n:void 0}}var vPt=3e4;async function BOe({command:e,logger:t,baseUrl:o,fetchImplementation:n=fetch}){let r=e.timeout??vPt/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(e.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(Qv(e.url)&&(s=e.url),o&&Zv(e.url,o)&&(s=new URL(e.url,o).toString()),!s)throw new ie("ActionFailureError",`Invalid URL: ${e.url}`);let c=await ye((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:e.query,variables:e.variables?JSON.parse(e.variables):void 0}),signal:i.signal})}catch(d){throw new Error(`Failed to make HTTP request: ${d}`,{cause:d})}})(),{milliseconds:r*1e3});if(!c)throw new ie("ActionFailureError",`GraphQL request timed out after ${r} seconds`);if(!c.ok){let d,m=await c.text();try{d=JSON.parse(m);}catch{throw new ie("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new ie("ActionFailureError",`GraphQL request failed with status ${c.status}: ${d.errors[0].message}`):new ie("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}let u={};return c.headers.forEach((d,m)=>{u[m]=d;}),{status:c.status,headers:u,json:await c.json()}}var KE=class{orgId;options;storage;codeEvaluator;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];stepSequenceActive=false;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:t,generator:o,logger:n,storage:r,orgId:i,codeEvaluator:a,uploadedFileStorage:s,visualDiffScreenshotStorage:l,options:c}){this.orgId=i,this.options=c,this.browser=t,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=r,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=l,this.codeEvaluator=a,this.generator=o,this.logger=n;}setOpen(){this.closed&&this.resetAbortController();}resetAbortController(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal);}async resetSession(t){this.registeredListeners={},this.recordedRequests={},await this.browser.reset(t);}setClosed(){this.executeAbortController.abort();}bindCancellation(t){if(t.aborted)return this.setClosed(),()=>{};let o=()=>this.setClosed();return t.addEventListener("abort",o,{once:true}),()=>t.removeEventListener("abort",o)}throwIfClosed(){this.executeAbortController.signal.throwIfAborted();}get closed(){return this.executeAbortController.signal.aborted}async withExecutionOptions(t,o){this.executionOptionsStack.push(t);try{return await o()}finally{this.executionOptionsStack.pop();}}async withExclusiveStepSequence(t){if(this.stepSequenceActive)throw new Error("Another step sequence is already active.");this.stepSequenceActive=true;try{return await t()}finally{this.stepSequenceActive=false;}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:t,startingScreenshot:o,history:n,disableCache:r,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[l,c]=await Promise.all([Mc(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:s}),this.browser.screenshot({retries:1,clearHighlights:true})]),u=`data:image/jpeg;base64,${c.toString("base64")}`,d=await Lc({type:"ai-action",description:t,screenshot:u,serializedTree:l.serializedTree,tree:l.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId},options:this.options?.pageFiltering}),m={url:this.browser.url(),browserState:d,startingScreenshot:o,history:n,goal:t,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:{...Wo(s)},langfuseSessionId:i})}async promptToCommand({goal:t,startingScreenshot:o,history:n,actionHint:r,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let l=this.browser.url(),[c,u]=await Promise.all([Mc(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:a}),this.browser.screenshot({retries:1,clearHighlights:true})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,m=await Lc({type:"ai-action",description:t,screenshot:d,serializedTree:c.serializedTree,tree:c.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId},options:this.options?.pageFiltering}),p={url:l,browserState:m,startingScreenshot:o,history:n,goal:t,actionHint:r,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Wo(a)},langfuseSessionId:s})}catch(h){throw new ie("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(t){return Mc(this.browser,t)}async locateElement(t){return await u5(t,this.getControllerFixtures())}async locateMultipleElements(t){return SOe(t,this.getControllerFixtures())}async locateElementWithSelector(t,o){return kc({action:async()=>{let n=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:n}},frameConfig:o?{type:"url",url:o}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return {browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,pageFiltering:this.options?.pageFiltering,storage:this.storage,codeEvaluator:this.codeEvaluator,abortSignal:this.executeAbortController.signal}}get pageFilteringOptions(){return this.options?.pageFiltering}shouldUseMemory(){return this.options?.useMemory??true}async wrapMultiElementTargetingCommand({tracer:t,command:o,targetNames:n,descriptions:r,caches:i,action:a,options:s,retriesWithAI:l=1}){let c=[];for(let u=0;u<r.length;u++){let d=r[u],m=await this.wrapElementTargetingCommand({tracer:t,command:o,target:d,cache:i[u],action:async p=>p,options:{...s,targetName:n[u]}});c.push(m);}try{let u=await a(...c.map(p=>p.result)),d=p=>p==="fromTarget"?"From Target":p==="toTarget"?"To Target":"Target",m=c.map((p,h)=>p.thoughts?`${d(n[h])}: ${p.thoughts}`:void 0).filter(p=>!!p).join(" -------------- ")||void 0;return {result:u,elementInteractedDisplayStrings:c.map(p=>p.elementInteractedDisplayString),thoughts:m}}catch(u){if(this.throwIfClosed(),l>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:t,command:o,targetNames:n,descriptions:r,caches:r.map(()=>{}),action:a,options:s,retriesWithAI:l-1});throw new ie("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapHardcodedCssTargetingCommandHelper({target:t,action:o,options:n,command:r}){let i=this.logger.child({commandId:r.id}),{targetName:a}=n;if(t.type!=="description")throw new ie("ActionFailureError","Cannot use selector with non-description target");let s,l=Date.now(),c=Date.now();for(;Date.now()-c<this.browser.smartWaitingTimeout;){l=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({selector:t.elementDescriptor,targetName:a,logger:i});return {result:await o({locator:u.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;s=u,i.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await Pt(500);}}throw s}async scrollIntoViewAndResolveFinalTarget(t){let{resolutionResult:o,disableGlobalLocatorRedirect:n,logger:r}=t,i=Ar(),a=!n&&this.browser.userBrowserSettings.globalLocatorRedirect!==false;(this.browser.userBrowserSettings.visualActions||a)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(o.locator);});let s;return a&&(s=await i.startAsyncSpan("LOCATOR_REDIRECT",async l=>{let{targetingResult:c,metadata:u}=await this.browser.performTargetRedirection(o,r);if(l.result=u,u.outcome==="redirected to new element"&&c&&i.storeTraceAsset&&!this.browser.userBrowserSettings.disableBrowserMonitoring){let d=randomUUID();(async()=>{try{let m=await this.browser.screenshot({locator:c.locator,clearHighlights:!0,boundingBoxOverride:c.serverSideBoundingBox??void 0});i.storeTraceAsset?.({snapshotId:d,data:m});}catch(m){r.debug({err:m},"Failed to capture element screenshot for redirect trace");}})(),l.elementScreenshotSnapshotId=d;}return c})),s||(s={locator:o.locator,serverSideBoundingBox:await o.locator.boundingBox({timeout:Dt}),originalElementLocationResult:o.originalElementLocationResult}),s}async resolveCachedTargetForAction(t){let{cache:o,options:n,logger:r}=t,a=await Ar().startAsyncSpan("CACHE_RESOLUTION",async l=>{l.targetSource=o.targetSource,l.attributes.smartWaitingTimeoutMs=this.browser.smartWaitingTimeout;let c={attempts:0,evaluationDurationMs:0};try{let u=await this.browser.resolveTarget(o,{allowNotActionableNodesOverride:n.allowNotActionableNodesOverride,logger:r,signal:this.executeAbortController.signal,...n.resolveTargetOptions,stats:c,acceptElementMovedError:n.force});l.attributes.targetDisplayString=u.displayString,l.attributes.decisions=u.decisions;let d=u.decisions.find(m=>m.matched);return d&&(l.resolutionMethod=d.type),u}catch(u){throw u instanceof Za&&(l.cacheMissReason=u.cacheMissReason,l.attributes.decisions=u.decisions),u}finally{c.attempts>0&&(l.resolutionAttempts=c.attempts,l.evaluationDurationMs=c.evaluationDurationMs);}}),s=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:a,disableGlobalLocatorRedirect:n.disableGlobalLocatorRedirect,logger:r});return n.force||await a.revalidator?.(),{resolutionResult:a,finalTarget:s}}async wrapElementTargetingCommand(t){return await kc({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:o,target:n,action:r,options:i,command:a,finalAttempt:s=false,originalCache:l=t.cache}=t,{retriesWithAI:c=1}=t,{disableCache:u,useSelector:d,targetName:m}=i,p=Ar(),h=this.logger.child({commandId:a.id}),g=this.shouldUseMemory(),f=cloneDeep(t.cache);if((!f||u)&&!$Q(n))throw new ie("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(t);let y=false,b;u&&(h.info("Cache explicitly disabled for this step"),y=true,b="Cache explicitly disabled",f=void 0);let S=mOe({cache:f,description:n.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:h});f=S.cache,y=y||S.cacheBustedBeforeAction,!b&&S.cacheBustReason&&(b=S.cacheBustReason);let A=true,T=i.memory??f?.memory;if(!dOe(f))return c--,A=false,this.executeTargetingCommandWithAI({tracer:p,stepTracer:o,target:n,options:{...i,memory:T},command:a,action:r,originalCache:l,logger:h,useMemory:g,cacheBustedBeforeAction:y,cacheBustReason:b});try{let{resolutionResult:v,finalTarget:R}=await this.resolveCachedTargetForAction({cache:f,options:i,logger:h}),I=await r(R);if(zo.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.62.2"]),kL({cmd:a,key:m,newTarget:f,logger:h,updatedWithAI:!1}),A){let C=v.decisions.filter(O=>O.matched);if(C.length!==1)h.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else {let O=C[0].type;o.recordTargetAutoHeal({healType:O});}}return {result:I,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let R=UH(v);if(R&&!s)return h.warn({err:v},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:o,command:a,target:n,action:r,cache:l,originalCache:l,retriesWithAI:c,finalAttempt:true,options:i});if(v instanceof ie&&!R)throw h.warn({err:v},"Failed to execute command with target (fatal)"),v;if(c>0&&n){h.info({err:v,cacheDecisions:v instanceof Za?aOe(v.decisions):void 0},"Failed to execute action with cached target, retrying with AI"),zo.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.62.2",`missReason:${v instanceof Za?v.cacheMissReason:"unknown"}`]);let I;f.memory&&IP(f.memory)&&(I=f.memory);let C=v instanceof Za&&v.cacheMissReason==="failing-ldist";return this.wrapElementTargetingCommandHelper({tracer:o,command:a,target:n,cache:void 0,action:r,originalCache:l,retriesWithAI:c,finalAttempt:true,options:{...i,memory:I,targetHealingInProgress:true},skipInitialLocateWait:C})}throw new ie("ActionFailureError",`Failed to execute interactive command: ${v instanceof Error?v.message:`${v}`}`,{errOptions:{cause:v}})}}async executeTargetingCommandWithAI(t){let{tracer:o,stepTracer:n,target:r,options:i,command:a,action:s,originalCache:l,logger:c,useMemory:u,cacheBustedBeforeAction:d,cacheBustReason:m,skipInitialLocateWait:p}=t;c.info({description:r.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:d,memory:i.memory,useMemory:u},"Prompting AI for an updated element location");let h=this.browser.executionMode==="turbo"||this.getCurrentExecutionOptions().skipAISmartWaiting||i.skipAISmartWaiting,g=false;(d||!l)&&!h?(await o.startAsyncSpan("SMART_WAITING",async()=>await xOe({description:r.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:c,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())),g=true):(d||!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 f=2;for(let y=1;y<=f;y++){let b=false,S=this.browser.getActiveFrameConfig(),A=i.force||y>1;try{let T;try{T=await u5({description:r.elementDescriptor,disableCache:!!i.disableCache,effort:i.effort,onEffectiveEffort:i.onEffectiveEffort,iframeUrl:i.iframeUrl,source:i.source,useMemory:u,memory:u?i.memory:void 0,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,allowIneligibleTagRedirect:i.allowIneligibleTagRedirect,showZeroOpacityElementsOverride:i.showZeroOpacityElementsOverride,logger:c,skipWait:g||h||p,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:m,acceptElementMovedError:A,pastLocatorMiss:i.pastLocatorMiss},this.getControllerFixtures());}catch(I){if(I instanceof zy&&I.updatedLocatorMemory){let C={id:-1,...l,memory:I.updatedLocatorMemory};kL({cmd:a,key:i.targetName,newTarget:C,logger:c,updatedWithAI:!0});}throw I}T.frameConfig&&(this.browser.setActiveFrameConfig(T.frameConfig),b=!0);let v=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:T.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),R=await s(v);return kL({cmd:a,key:i.targetName,newTarget:T.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=Wo(c)),{result:R,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}catch(T){if(b&&this.browser.setActiveFrameConfig(S),this.throwIfClosed(),y<f&&UH(T)){c.warn({err:T,aiAttempt:y},"Encountered retryable AI targeting error; retrying with AI once");continue}throw T instanceof ie?T:new ie("ActionFailureError",T.message,{errOptions:{cause:T}})}}throw new ie("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(t){return U_(this.browser,t)}async waitBetweenSteps(){this.options?.slowMoMs&&await Pt(this.options.slowMoMs,this.executeAbortController.signal);}async executePresetCommand(t,o,n,r,i,a,s){let l=await this.browser.getOpenPages(),c=this.browser.url(),u;try{u=await this.resolveCommandTemplateStrings(o,n);}catch(d){throw this.throwIfClosed(),new ie("ActionFailureError",`Failed to substitute template strings in command: ${d.message}`,{errOptions:{cause:d}})}try{let d=await ge({name:`cli.command.${o.type}`,attributes:{"momentic.command_type":o.type,"momentic.command_id":o.id},fn:()=>this.executePresetCommandHelper(t,o,n,r,i,a,s)});return this.options?.autoFollowNewTabs&&await uOe({beforeUrl:c,command:o,beforePages:l.map(m=>m.url),browser:this.browser,logger:this.logger}),d}catch(d){throw d.name!=="AbortError"&&this.logger.warn({err:d},"Error thrown in action controller"),d}finally{DIe(o,u);}}createCallbacksForBrowser(t){return {createIsolatedFolder:()=>D3(t)}}async traceBrowserInteraction(t,o,n){return Ar().startAsyncSpan("BROWSER_INTERACTION",async i=>o(i),{name:t,...n})}async resolveCommandTemplateStrings(t,o){return PB({obj:t,context:o,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,codeEvaluator:this.codeEvaluator})}async executePresetCommandHelper(t,o,n,r,i,a,s){r=r||"disableCache"in o&&!!o.disableCache;let l=this.logger.child({commandId:o.id}),c=u=>this.wrapElementTargetingCommand({...u,options:{...u.options,effort:a,onEffectiveEffort:s}});switch(o.type){case "SUCCESS":{let u=o.condition;return u?.assertion.trim()?nU({command:u,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:l,recoveryHint:i,effort:a,onEffectiveEffort:s}):{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AI_ASSERTION":{if(!o.assertion.trim())throw new ie("ActionFailureError","Missing assertion");if(o.timeout&&o.timeout>1800)throw new ie("AssertionFailureError",`AI check timeout of ${o.timeout} exceeds the maximum allowed value of 30 minutes.`);return nU({command:o,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:l,recoveryHint:i,effort:a,onEffectiveEffort:s})}case "AI_EXTRACT":return kc({action:()=>COe({command:o,logger:l,fixtures:this.getControllerFixtures(),disableCache:r,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:o.iframeUrl?{type:"url",url:o.iframeUrl}:void 0,browser:this.browser,logger:l});case "NAVIGATE":if(!Qv(o.url)&&!Zv(o.url,this.browser.baseUrl))throw new ie("ActionFailureError",`Invalid URL provided to navigate command: ${o.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:o.url,loadTimeoutMs:o.loadTimeout?o.loadTimeout*1e3:void 0}));break;case "DIALOG":this.browser.registerDialogHandler(o.action);break;case "CAPTCHA":throw new ie("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 u,d;if(o.target&&Jd(o.target)){let h=es(o.target.pixels);await this.browser.hoverUsingVisualCoordinates(h);}else if(o.target&&o.target.elementDescriptor.trim()){let{elementInteractedDisplayString:h,thoughts:g}=await c({tracer:t,command:o,target:o.target,cache:o.cache?.target,action:f=>this.browser.hover(f),options:{...o,targetName:"target",disableGlobalLocatorRedirect:true,disableCache:r}});u=h,d=g;}let m=this.browser.getViewport()?.height??Fa.height,p=this.browser.getViewport()?.width??Fa.width;switch(o.type){case "SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(o.deltaY??m)));break;case "SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(o.deltaY??m));break;case "SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(o.deltaX??p)));break;case "SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(o.deltaX??p));break}return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u,thoughts:d}}case "WAIT_FOR_URL":{if(o.timeout&&o.timeout>1800)throw new ie("UserConfigurationError",`Wait for URL timeout of ${o.timeout} exceeds the maximum allowed value of 30 minutes.`);let u=o.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:u},{timeout:o.timeout?o.timeout*1e3:void 0,negated:o.negated,caseInsensitive:o.caseInsensitive});break}case "WAIT":{if(o.delay>1800)throw new ie("UserConfigurationError",`Wait timeout of ${o.delay} seconds exceeds the maximum allowed value of 30 minutes`);let u=o.delay*1e3;await Pt(u,this.executeAbortController.signal);break}case "REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:o.loadTimeout?o.loadTimeout*1e3:void 0}));break;case "CLICK":{if(Jd(o.target)){let g=es(o.target.pixels),f={...o,relativePosition:o.relativePosition?es(o.relativePosition):void 0};await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(g,f),{coordinates:g});break}let u=this.browser.url(),{elementInteractedDisplayString:d,result:m,thoughts:p}=await c({tracer:t,target:o.target,command:o,cache:o.cache?.target,action:g=>this.traceBrowserInteraction("Click",async f=>{let y={...o,relativePosition:o.relativePosition?es(o.relativePosition):void 0},b=await this.browser.click(g,this.createCallbacksForBrowser(this.orgId),y);return b.coordinates&&(f.coordinates=b.coordinates),b},{selector:g.locator.toString()}),options:{...o,targetName:"target",disableCache:r}}),h={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:d,thoughts:p,data:m.downloadedFile?{downloadedFile:m.downloadedFile}:void 0};return KL(u,h.urlAfterCommand)&&(h.succeedImmediately=true,h.succeedImmediatelyReason="URL changed"),h}case "COPY":return await this.browser.copy(o.value),{succeedImmediately:false,data:o.value,urlAfterCommand:this.browser.url()};case "PASTE":{await this.browser.paste();break}case "DRAG":{if(Jd(o.fromTarget)&&Jd(o.toTarget)){let m=es(o.fromTarget.pixels),p=es(o.toTarget.pixels);await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(m,p,{hoverDurationMs:o.hoverSeconds?o.hoverSeconds*1e3:void 0}),{coordinates:m});break}if(Jd(o.fromTarget)||Jd(o.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:u,thoughts:d}=await this.wrapMultiElementTargetingCommand({tracer:t,command:o,targetNames:["fromTarget","toTarget"],descriptions:[o.fromTarget,o.toTarget],caches:[o.cache?.fromTarget,o.cache?.toTarget],action:(m,p)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(m,p,{hoverDurationMs:o.hoverSeconds?o.hoverSeconds*1e3:void 0,steps:o.steps})),options:{...o,disableCache:r,effort:a,onEffectiveEffort:s}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u[0],thoughts:d}}case "MOUSE_DRAG":{let u=parseInt(o.deltaX),d=parseInt(o.deltaY),m=o.steps??5;if(isNaN(u)||isNaN(d))throw new ie("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${o.deltaX}, ${o.deltaY})`);if(o.target&&Jd(o.target)){let g=es(o.target.pixels);await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:u,deltaY:d,steps:m,fromTarget:g}),{coordinates:g});break}let p,h;if(o.target?.elementDescriptor){let{elementInteractedDisplayString:g,thoughts:f}=await c({tracer:t,command:o,target:o.target,cache:o.cache?.target,action:async y=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(u,d,m,y.locator,{force:o.force})),options:{...o,targetName:"target",disableCache:r}});p=g,h=f;}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(u,d,m,void 0,{force:o.force}));return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:h}}case "SELECT_OPTION":{if(!Gu(o.target))throw new Error("Select with x/y is not supported yet");let u=o.target.elementDescriptor,d=o.choice,{elementInteractedDisplayString:m,thoughts:p}=await c({tracer:t,command:o,target:{type:"description",elementDescriptor:u},cache:o.cache?.target,action:h=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(h,d,o.force),{value:d.type==="LABEL"?d.label:d.type==="VALUE"?d.value:d.index}),options:{...o,targetName:"target",disableCache:r,source:lm(o)}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:p}}case "TAB":{let u=o.timeout===void 0?void 0:o.timeout*1e3,d=o.loadTimeout??o.timeout,m={loadTimeoutMs:d===void 0?void 0:d*1e3,timeoutMs:u,retry:true};await this.browser.switchToPage(o.action,m);break}case "NEW_TAB":await this.browser.createNewTab(o.url,{loadTimeoutMs:o.loadTimeout?o.loadTimeout*1e3:void 0});break;case "CLOSE_TAB":await this.browser.closePage(o.action,{retry:true});break;case "COOKIE":{if(!o.value)break;let u=await this.browser.setCookie(o.value);l.debug({results:u},"Set cookies");break}case "LOCAL_STORAGE":if(!o.value||!o.key)break;await this.browser.setLocalStorage(o.key,o.value);break;case "JAVASCRIPT":{let u;try{o.environment==="BROWSER"?(u=await this.browser.evaluateCodeInPage({code:o.code,fragment:o.fragment??!1,context:n.toObjectCopy(),timeoutMs:o.timeout?o.timeout*1e3:void 0}),l.info({result:u},"Executed JavaScript in browser")):u=await hy({orgId:this.orgId,code:o.code,fragment:!!o.fragment,context:n,timeoutMs:o.timeout?o.timeout*1e3:void 0,logger:l,codeEvaluator:this.codeEvaluator,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async d=>{if(!this.options?.scratchPadId){l.warn({updates:d},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:d,logger:l});}}});}catch(d){throw this.throwIfClosed(),new ie("ActionFailureError",d instanceof Error?d.message:`${d}`,{errOptions:{cause:d}})}try{JSON.stringify(u);}catch(d){throw new ie("ActionFailureError",`Return value is not serializable: ${d instanceof Error?d.message:`${d}`}`,{errOptions:{cause:d}})}return {urlAfterCommand:this.browser.url(),succeedImmediately:false,data:u}}case "TYPE":{if(o.target&&Jd(o.target)){let f=es(o.target.pixels),y={...o,relativePosition:o.relativePosition?es(o.relativePosition):void 0};await this.browser.clickUsingVisualCoordinates(f,y),await this.traceBrowserInteraction("Type",()=>this.browser.type(o.value,{force:o.force,clearContent:o.clearContent,forceClearContent:o.forceClearContent,delay:o.delay??this.browser.userBrowserSettings.typeDelayMs,pressEnter:o.pressEnter,fill:o.fill},true),{value:o.value});break}let u=this.browser.url(),d,m,p=cloneDeep(o.target),h=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(p){let{elementInteractedDisplayString:f,thoughts:y}=await c({tracer:t,command:o,target:p,cache:o.cache?.target,action:b=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(o.value,b,{force:o.force,clearContent:o.clearContent,forceClearContent:o.forceClearContent,delay:o.delay??this.browser.userBrowserSettings.typeDelayMs,pressEnter:o.pressEnter,relativePosition:o.relativePosition,fill:o.fill}),{value:o.value,selector:b.locator.toString()}),options:{...o,targetName:"target",disableCache:r,disableGlobalLocatorRedirect:!h,source:lm(o)}});d=f,m=y;}else await this.traceBrowserInteraction("Type",()=>this.browser.type(o.value,{force:o.force,clearContent:o.clearContent,forceClearContent:o.forceClearContent,delay:o.delay??this.browser.userBrowserSettings.typeDelayMs,pressEnter:o.pressEnter,fill:o.fill},true),{value:o.value});let g={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:d,thoughts:m};return KL(u,g.urlAfterCommand)&&(g.succeedImmediately=true,g.succeedImmediatelyReason="URL changed"),g}case "HOVER":{if(Jd(o.target)){let m=es(o.target.pixels);await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(m),{coordinates:m});break}let{elementInteractedDisplayString:u,thoughts:d}=await c({tracer:t,command:o,target:o.target,cache:o.cache?.target,action:m=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(m,{relativePosition:o.relativePosition?es(o.relativePosition):void 0}),{selector:m.locator.toString()}),options:{...o,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u,thoughts:d}}case "FOCUS":{if(!Gu(o.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:u,thoughts:d}=await c({tracer:t,command:o,target:o.target,cache:o.cache?.target,action:m=>this.browser.focus(m),options:{...o,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u,thoughts:d}}case "BLUR":{if(o.target&&!Gu(o.target))throw new Error("Blur with x/y is not supported yet");if(!o.target||!o.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:false,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:u,thoughts:d}=await c({tracer:t,target:o.target,command:o,cache:o.cache?.target,action:m=>this.browser.blur(m),options:{...o,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u,thoughts:d}}case "PRESS":{let u=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(o.value,{repeat:o.repeat,convertMeta:o.convertMeta??true,delayMs:o.delayMs??this.browser.userBrowserSettings.pressDelayMs}),{value:o.value});let d={urlAfterCommand:this.browser.url(),succeedImmediately:false};return KL(u,d.urlAfterCommand)&&(d.succeedImmediately=true,d.succeedImmediatelyReason="URL changed"),d}case "KEY_DOWN":return await this.browser.keyDown(o.value,{convertMeta:o.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "KEY_UP":return await this.browser.keyUp(o.value,{convertMeta:o.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "REQUEST":{let u=new CookieJar,d=EPt(fetch,u),m;try{m=new URL(o.url).hostname;}catch{}let p=await NOe({command:o,baseUrl:this.browser.baseUrl,logger:l,fetchImplementation:d});return {data:mR.parse({...p,cookies:Eee(u,m)}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GRAPHQL_REQUEST":return {data:await BOe({command:o,baseUrl:this.browser.baseUrl,logger:l}),succeedImmediately:false,urlAfterCommand:this.browser.url()};case "VISUAL_DIFF":return LOe({tracer:t,command:o,disableCache:r,browser:this.browser,logger:l,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:c});case "FILE_UPLOAD":{let u,d;if(o.fileSource.type==="URL"?(d=o.fileSource.url,u=await Uxe({uri:o.fileSource.url,logger:l,orgId:this.orgId})):o.fileSource.type==="USER_FILE"&&(d=o.fileSource.name,u=await this.uploadedFileStorage?.getFileForUpload(o.fileSource.name,this.orgId)),!u)throw new ie("UserConfigurationError",`Attempted to use non-existent file for upload step: ${d}`);await this.browser.setFileChooserHandler({...u,filename:o.filename});break}case "AUTH_SAVE":{let u=await this.browser.saveAuthState();if(o.storageState&&hf(o.storageState)){let d=Cn__default.resolve(o.storageState);Un__default.mkdirSync(Cn__default.dirname(d),{recursive:true}),Un__default.writeFileSync(d,`${JSON.stringify(u,null,2)}
2661
+ `):c=await a.getCondensedHtml();let u=await a.screenshot({retries:2,respectActiveFrame:true}),d=Ar();try{return await d.startAsyncSpan("AI_EXTRACTION_CALL",async m=>{let p=await s.getTextExtraction({goal:t.goal,browserState:c,returnSchema:t.schema,screenshot:`data:image/jpeg;base64,${u.toString("base64")}`},{disableCache:r,abortSignal:l,loggerTags:Wo(o)});if(m.result=p,iPt({tracer:d,span:m,screenshot:u,htmlState:c,logger:o}),p.result==="NOT_FOUND")throw new ie("ActionFailureError","No relevant data found for extraction goal on this page");if(p.thoughts?.includes("MaxGenerationLengthExceededError"))throw new ie("UserConfigurationError",p.thoughts);return {thoughts:p.thoughts||void 0,data:p.result,succeedImmediately:!1,urlAfterCommand:a.url()}})}catch(m){let p=W(m);throw p.includes("MaxGenerationLengthExceededError")?new ie("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 ie("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:m}}):m}}function rPt({bannedAttributes:e}){return window._momentic?.getCondensedHtmlTree?.({bannedAttributes:e})?.result??""}function iPt(e){let{tracer:t,span:o,screenshot:n,htmlState:r,logger:i}=e;if(t.storeTraceAsset)try{let a=randomUUID();t.storeTraceAsset({snapshotId:a,data:n}),o.screenshotSnapshotId=a;let s=randomUUID();t.storeTraceAsset({snapshotId:s,data:Buffer.from(r),extension:"html"}),o.browserStateSnapshotId=s;}catch(a){i.debug({err:a},"Failed to store extraction trace assets");}}var IOe=500;async function xOe(e,t){let{logger:o}=e,{abortSignal:n,browser:r}=t,i=Date.now();try{await aPt(i,e,t);}catch(a){if(_p(a)||n.aborted)return;o.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=r.smartWaitingTimeout-(Date.now()-i);s>0&&await Pt(s,n);}finally{o.debug({durationMs:Date.now()-i},"AI smart waiting complete");}}async function aPt(e,t,o){let{abortSignal:n,browser:r}=o;if(r.smartWaitingTimeout<3e3){await Pt(r.smartWaitingTimeout,n);return}if(!t.description)throw new ie("UserConfigurationError","Cannot locate element with empty description");await ye(sPt(e,t,o),{milliseconds:r.smartWaitingTimeout});}async function sPt(e,t,o){let{logger:n,iframeUrl:r,testContext:i}=t,{abortSignal:a,browser:s,codeEvaluator:l,orgId:c}=o,u=i?await Es({orgId:c,s:t.description,context:i,codeEvaluator:l,signal:a,logger:n}):t.description,d;for(;Date.now()-e<s.smartWaitingTimeout;){let m=Date.now();if(await kc({action:async()=>{let g=await lPt(u,t,o,d);return d=g.notReadyScreenshot,g.isReady},frameConfig:r?{type:"url",url:r}:void 0,browser:s,logger:n}))return;let h=Date.now()-m;h<IOe&&await Pt(IOe-h,a);}}async function lPt(e,t,o,n){let{logger:r}=t,{browser:i,abortSignal:a,generator:s}=o;a.throwIfAborted();let l;try{l=await i.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(m){throw new ie("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: ${m instanceof Error?m.message:m}`)}if(n?.equals(l))return r.debug("Skipping smart waiting AI call, the page is unchanged"),{isReady:false,notReadyScreenshot:n};let u=`data:image/jpeg;base64,${l.toString("base64")}`;a.throwIfAborted();let d=await s.getSmartWaitingDecision({description:e,screenshot:u},{abortSignal:a,loggerTags:Wo(r)});return r.debug({result:d},"Got smart waiting result"),{isReady:d.isPageReady,notReadyScreenshot:d.isPageReady?void 0:l}}var cPt=3e4;function uPt({command:e,originalCache:t,cacheToUse:o,keepMemory:n}){if(o){if(n){let r=eV(t,o);return o.target=r.target,o.updatedAt=r.updatedAt,o}if(!t){let r=lm(e);r!=="NEGATED_CHECK"&&r!=="NEGATED_ELEMENT_VISIBLE_CHECK"&&(e.cache=void 0);return}return o.target=t.target,o.updatedAt=t.updatedAt,o}}async function POe(e){return Ar().startAsyncSpan("ELEMENT_ASSERTION",async o=>dPt(e,o),{name:"Element check"})}async function dPt(e,t){let{command:o,timeoutMs:n,fixtures:r,disableCache:i}=e,{abortSignal:a}=r,s=()=>_P(o.cache)?o.cache:void 0,l=s(),c=!i&&!!l?.target&&hT(l.target),u=cloneDeep(l),d=(T=false)=>{l=uPt({command:o,originalCache:u,cacheToUse:s(),keepMemory:T});},m={},p=Date.now(),h=c?Math.max(n/10,cPt):0,g=p,f=0,y,b=500,S=false;for(;f<2||Date.now()-p<n;){f++,f>1&&await Pt(b,a),a?.throwIfAborted(),l=s();let T=f===1,v=c&&Date.now()-g>=h;v&&(g=Date.now());let{result:R,elementWasFound:I}=await _Oe({cacheToUse:l,skipAISmartWaiting:!T,useAIIfCacheFails:!c||v,pastLocatorMiss:m,params:e});if(y=R,S=S||I,R.success)break;d(),b=Math.min(b*1.25,1e4);}if(!y)throw new ie("InternalPlatformError",`Failed to evaluate manual element assertion in ${n}ms.`);if(a?.throwIfAborted(),!y.success){let T=s(),v=T?.target?.memory?{target:{id:-1,memory:T.target.memory}}:void 0,{result:R,elementWasFound:I}=await _Oe({cacheToUse:v,skipAISmartWaiting:true,useAIIfCacheFails:true,params:e});y=R,S=S||I,y.success||d(true);}let A=s();return y.success&&A?.target&&!S&&(A.target=rf(A.target),A.updatedAt=new Date),t.result={success:y.success,message:y.err?.message},y}async function _Oe({cacheToUse:e,skipAISmartWaiting:t,useAIIfCacheFails:o,pastLocatorMiss:n,params:r}){let{command:i,disableCache:a,fixtures:s,tracer:l,targetingWrapper:c}=r,{logger:u}=s;if(i.target&&!Gu(i.target))throw new Error("Element assertion with x/y is not supported yet");let d=sle(i.assertion),m=mPt(i.assertion),p,h=false,g=cloneDeep(e);try{let{elementInteractedDisplayString:f,result:y,thoughts:b}=await c({tracer:l,command:i,target:i.target,cache:g?.target,action:async S=>pPt(S.locator,r),options:{...i,allowNotActionableNodesOverride:m,allowIneligibleTagRedirect:m,showZeroOpacityElementsOverride:!0,disableCache:a,memory:g?.target?.memory,disableGlobalLocatorRedirect:!0,source:lm(i),skipAISmartWaiting:t,targetName:"target",pastLocatorMiss:n},retriesWithAI:o?1:0});return p={success:y.success,data:y.data,err:y.err,elementInteractedDisplayString:f,thoughts:b},h=!0,y.success||(u.warn({aiThoughts:b,elementString:f,err:y.err},"Element check found an element but failed"),p={...y,thoughts:b}),{result:p,elementWasFound:h}}catch(f){if(d)return p={success:true,thoughts:`The element described does not exist on the page: ${f.message}`,err:void 0,data:void 0},{result:p,elementWasFound:h};if(!(f instanceof ie)||f.reason!="ActionFailureError")throw f;return p={success:false,err:f,data:void 0,thoughts:void 0},u.warn({err:f},"Element check did not find an element and failed"),{result:p,elementWasFound:h}}}function mPt(e){return !(e.type==="ELEMENT_EXISTENCE"&&e.condition==="VISIBLE"&&!e.negated)}async function pPt(e,{command:t,fixtures:o}){return await o.browser.highlight(e),await hPt(e,t.assertion)}async function hPt(e,t){let o=true,n,r;switch(t.type){case "ELEMENT_CONTENT":{let a=await e.textContent()??"";if(r={elementTextContent:Dn(a,500,true)},!bI(a,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let s=Uv(t);o=false,n=new ie("AssertionFailureError",`The content ${s} '${t.value}': ${a}`);}break}case "ELEMENT_ATTRIBUTE":{r={elementOuterHtml:Dn(await e.evaluate(s=>s.cloneNode(false).outerHTML),500,true)};let a=null;try{a=await e.getAttribute(t.attr,{timeout:3e3});}catch(s){n=new ie("AssertionFailureError",W(s)),o=false;break}if(!bI(a,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let s=Uv(t);o=false,t.operation==="EXISTS"?n=new ie("AssertionFailureError",`The attribute ${t.attr} ${s}`):n=new ie("AssertionFailureError",`The attribute ${t.attr} ${s} '${t.value}': ${a}`);}break}case "ELEMENT_EXISTENCE":{switch(t.condition){case "VISIBLE":{o=await e.evaluate(async(s,l)=>{let c=Date.now();for(;Date.now()-c<l;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return true}return false},jc*1e3);break}case "EDITABLE":{o=await e.isEditable({timeout:jc*1e3});break}case "EXISTS":{o=true;break}case "ENABLED":{o=await e.isEnabled({timeout:jc*1e3});break}case "FOCUSED":{o=await e.evaluate(s=>s===document.activeElement);break}default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})(t.condition)}if(o=t.negated?!o:o,!o){let a=Uv(t);n=new ie("AssertionFailureError",`The element ${a}`);}break}case "ELEMENT_NAME":{let a=await e.evaluate(s=>s.tagName);if(!bI(a,t.value,t.operation,{negated:!!t.negated,ignoreCase:true})){let s=Uv(t);o=false,n=new ie("AssertionFailureError",`The element tag name ${s} '${t.value}': ${a}`);}break}case "ELEMENT_STYLE":{let a=await e.evaluate((s,l)=>window.getComputedStyle(s).getPropertyValue(l),t.property);if(!bI(a,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let s=Uv(t);o=false,t.operation==="EXISTS"?n=new ie("AssertionFailureError",`The style property ${t.property} ${s}`):n=new ie("AssertionFailureError",`The style property ${t.property} ${s} '${t.value}': ${a}`);}break}default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}return {thoughts:void 0,success:o,data:r,err:n}}function kOe(e){return e.type==="ELEMENT_EXISTENCE"&&e.negated&&e.condition==="EXISTS"}async function U_(e,t){let o=await e.screenshot(t),{width:n,height:r}=YB(o);return {buffer:o,width:Math.ceil(n),height:Math.ceil(r)}}async function LOe(e){let{command:t,browser:o,logger:n}=e;if(t.target&&!Gu(t.target))throw new Error("Visual Diff with x/y is not supported yet");return await o.waitForStability({logger:n}),Ar().startAsyncSpan("VISUAL_DIFF",async i=>{try{let a=await fPt(e);return i.result={success:!a.fail,message:a.thoughts},a}catch(a){throw a instanceof ie&&(i.result={success:false,message:a.message}),a}},{name:"Compare against golden"})}async function fPt({tracer:e,command:t,disableCache:o,browser:n,targetingWrapper:r,logger:i,screenshotStorage:a}){let s={clearHighlights:true,hideCaret:true},l=t.target&&Gu(t.target)?t.target:void 0,c;l?.elementDescriptor?c=(await r({tracer:e,command:t,target:l,cache:t.cache?.target,action:async P=>U_(n,{locator:P.locator,...s}),options:{...t,disableCache:o,disableGlobalLocatorRedirect:true,memory:t.cache?.target?.memory,targetName:"target"}})).result:c=await U_(n,s);let u=await a.prepareGoldenScreenshotForComparison(i,t,c);if((c.height!==u.height||c.width!==u.width)&&i.warn({currHeight:c.height,currWidth:c.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-u.height)>10||Math.abs(c.width-u.width)>10){let O=`${c.width}x${c.height}`,P=`${u.width}x${u.height}`;return {fail:true,thoughts:`Current screenshot (${O}) does not match saved screenshot dimensions (${P}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:false,urlAfterCommand:n.url()}}let d=await Jimp.fromBuffer(c.buffer),m={width:c.width,height:c.height},p=await Jimp.fromBuffer(u.buffer),h={width:u.width,height:u.height},g,f=m.width*m.height,y=h.width*h.height,b=Math.abs(m.height-h.height),S=Math.abs(m.width-h.width);if(f>y){let O=d.cover({w:h.width,h:h.height});c.buffer=await O.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height;}else if(y>f){let O=p.cover({w:m.width,h:m.height});u.buffer=await O.getBuffer("image/jpeg"),g="saved";}let A={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},T=t.threshold??.1,R=z_t(d5.decode(u.buffer).data,d5.decode(c.buffer).data,A.data,c.width,c.height,{threshold:T,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,I=R>T*100,C=`Visual diff of ${R.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${T*100}%.`;if(g&&(C+=` The ${g} screenshot was cropped since it was taller by ${b} pixels and wider by ${S} pixels.`),I)throw new ie("ActionFailureError",C);return {fail:I,thoughts:C,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:d5.encode(A,75).data,succeedImmediately:false,urlAfterCommand:n.url()}}var yPt=3e4;function bPt(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(([o,n])=>{t.append(o,n);}),{content:t.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function NOe({command:e,logger:t,baseUrl:o,fetchImplementation:n=fetch}){let r=e.timeout??yPt/1e3,i=Object.fromEntries(Object.entries(e.headers||{}).filter(([h,g])=>h&&g)),a=new URLSearchParams;Object.entries(e.params||{}).filter(([h,g])=>h&&g).forEach(([h,g])=>{a.append(h,g);});let s=a.toString(),l;if(Qv(e.url)&&(l=e.url),o&&Zv(e.url,o)&&(l=new URL(e.url,o).toString()),!l)throw new ie("ActionFailureError",`Invalid URL: ${e.url}`);let c=l;t.info({url:c,searchParams:s,headers:i,body:e.body,method:e.method},"Making HTTP request");let d=await ye((async()=>{let h=s?`${c}?${s}`:c;try{let g=bPt(e),f=new Headers(i);return g.contentType&&!f.has("Content-Type")&&f.set("Content-Type",g.contentType),await n(h,{headers:f,method:e.method,body:g.content})}catch(g){throw new ie("ActionFailureError",`Failed to make HTTP request: ${W(g)}`,{errOptions:{cause:g}})}})(),{milliseconds:r*1e3,fallback:()=>{throw new ie("ActionFailureError",`Fetch request timed out after ${r} seconds`)}});if(!d.ok){let h;try{h=await d.text();}catch(g){h=`Failed to read response body: ${g}`;}throw new ie("ActionFailureError",`Fetch request failed with status ${d.status}: ${h}`)}let m={};d.headers.forEach((h,g)=>{m[g]=h;});let p={status:d.status,headers:m,request:{url:d.url,method:e.method,headers:i}};if(e.body?.type==="json"&&e.body.content)try{p.request.json=JSON.parse(e.body.content);}catch{}if(d.headers.get("content-type")?.includes("json"))try{p.json=await d.json();}catch{}else d.headers.get("content-type")?.includes("text")&&(p.text=await d.text());return p}var SPt=5e3;async function rU({timeout:e=jc,...t}){let o=Date.now(),n=e*1e3,r=n+1e4,i,a=0,s=500;for(;a-o<n;){if(Date.now()-o>r){t.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}t.signal?.throwIfAborted();let l=Date.now();i=await DOe(t),a=Date.now();let c=a-l;if(c>1e3&&t.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await Pt(s,t.signal),s=Math.min(Math.floor(s*1.5),SPt);else return i}return i=await DOe(t),i}async function DOe(e){return Ar().startAsyncSpan("PAGE_ASSERTION",async o=>{let n=await TPt(e);return o.result={success:n.success,message:n.err?.message},n},{name:"Page check"})}async function TPt({assertion:e,browser:t,autoExpandIframes:o}){switch(e.type){case "CONTENT":case "CONTENT":{let r,i=false,a;try{let s;if(o){let l=await t.evaluateFunctionInAllFrames(FOe,{value:e.value,negated:!!e.negated,returnHtml:!1});i=e.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml;}else ({evaluation:i,pageHtml:s}=await t.evaluateFunctionInPage(FOe,{value:e.value,negated:!!e.negated,returnHtml:!0},"checking page content"));if(!i){let l=e.negated?Qp.CONTAINS:Zp.CONTAINS;a=new ie("AssertionFailureError",`The page ${l} '${e.value}'.`),r=s;}}catch(s){a=new ie("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`);}return {success:i,err:a,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 FOe({value:e,negated:t,returnHtml:o}){let n=document.body.innerHTML,r=n.includes(e)===!t;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:r,pageHtml:!r&&o?n:void 0}}var vPt=3e4;async function BOe({command:e,logger:t,baseUrl:o,fetchImplementation:n=fetch}){let r=e.timeout??vPt/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(e.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(Qv(e.url)&&(s=e.url),o&&Zv(e.url,o)&&(s=new URL(e.url,o).toString()),!s)throw new ie("ActionFailureError",`Invalid URL: ${e.url}`);let c=await ye((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:e.query,variables:e.variables?JSON.parse(e.variables):void 0}),signal:i.signal})}catch(d){throw new Error(`Failed to make HTTP request: ${d}`,{cause:d})}})(),{milliseconds:r*1e3});if(!c)throw new ie("ActionFailureError",`GraphQL request timed out after ${r} seconds`);if(!c.ok){let d,m=await c.text();try{d=JSON.parse(m);}catch{throw new ie("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new ie("ActionFailureError",`GraphQL request failed with status ${c.status}: ${d.errors[0].message}`):new ie("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}let u={};return c.headers.forEach((d,m)=>{u[m]=d;}),{status:c.status,headers:u,json:await c.json()}}var KE=class{orgId;options;storage;codeEvaluator;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];stepSequenceActive=false;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:t,generator:o,logger:n,storage:r,orgId:i,codeEvaluator:a,uploadedFileStorage:s,visualDiffScreenshotStorage:l,options:c}){this.orgId=i,this.options=c,this.browser=t,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=r,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=l,this.codeEvaluator=a,this.generator=o,this.logger=n;}setOpen(){this.closed&&this.resetAbortController();}resetAbortController(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal);}async resetSession(t){this.registeredListeners={},this.recordedRequests={},await this.browser.reset(t);}setClosed(){this.executeAbortController.abort();}bindCancellation(t){if(t.aborted)return this.setClosed(),()=>{};let o=()=>this.setClosed();return t.addEventListener("abort",o,{once:true}),()=>t.removeEventListener("abort",o)}throwIfClosed(){this.executeAbortController.signal.throwIfAborted();}get closed(){return this.executeAbortController.signal.aborted}async withExecutionOptions(t,o){this.executionOptionsStack.push(t);try{return await o()}finally{this.executionOptionsStack.pop();}}async withExclusiveStepSequence(t){if(this.stepSequenceActive)throw new Error("Another step sequence is already active.");this.stepSequenceActive=true;try{return await t()}finally{this.stepSequenceActive=false;}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:t,startingScreenshot:o,history:n,disableCache:r,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[l,c]=await Promise.all([Mc(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:s}),this.browser.screenshot({retries:1,clearHighlights:true})]),u=`data:image/jpeg;base64,${c.toString("base64")}`,d=await Lc({type:"ai-action",description:t,screenshot:u,serializedTree:l.serializedTree,tree:l.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId},options:this.options?.pageFiltering}),m={url:this.browser.url(),browserState:d,startingScreenshot:o,history:n,goal:t,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:{...Wo(s)},langfuseSessionId:i})}async promptToCommand({goal:t,startingScreenshot:o,history:n,actionHint:r,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let l=this.browser.url(),[c,u]=await Promise.all([Mc(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:a}),this.browser.screenshot({retries:1,clearHighlights:true})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,m=await Lc({type:"ai-action",description:t,screenshot:d,serializedTree:c.serializedTree,tree:c.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId},options:this.options?.pageFiltering}),p={url:l,browserState:m,startingScreenshot:o,history:n,goal:t,actionHint:r,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Wo(a)},langfuseSessionId:s})}catch(h){throw new ie("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(t){return Mc(this.browser,t)}async locateElement(t){return await u5(t,this.getControllerFixtures())}async locateMultipleElements(t){return SOe(t,this.getControllerFixtures())}async locateElementWithSelector(t,o){return kc({action:async()=>{let n=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:n}},frameConfig:o?{type:"url",url:o}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return {browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,pageFiltering:this.options?.pageFiltering,storage:this.storage,codeEvaluator:this.codeEvaluator,abortSignal:this.executeAbortController.signal}}get pageFilteringOptions(){return this.options?.pageFiltering}shouldUseMemory(){return this.options?.useMemory??true}async wrapMultiElementTargetingCommand({tracer:t,command:o,targetNames:n,descriptions:r,caches:i,action:a,options:s,retriesWithAI:l=1}){let c=[];for(let u=0;u<r.length;u++){let d=r[u],m=await this.wrapElementTargetingCommand({tracer:t,command:o,target:d,cache:i[u],action:async p=>p,options:{...s,targetName:n[u]}});c.push(m);}try{let u=await a(...c.map(p=>p.result)),d=p=>p==="fromTarget"?"From Target":p==="toTarget"?"To Target":"Target",m=c.map((p,h)=>p.thoughts?`${d(n[h])}: ${p.thoughts}`:void 0).filter(p=>!!p).join(" -------------- ")||void 0;return {result:u,elementInteractedDisplayStrings:c.map(p=>p.elementInteractedDisplayString),thoughts:m}}catch(u){if(this.throwIfClosed(),l>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:t,command:o,targetNames:n,descriptions:r,caches:r.map(()=>{}),action:a,options:s,retriesWithAI:l-1});throw new ie("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapHardcodedCssTargetingCommandHelper({target:t,action:o,options:n,command:r}){let i=this.logger.child({commandId:r.id}),{targetName:a}=n;if(t.type!=="description")throw new ie("ActionFailureError","Cannot use selector with non-description target");let s,l=Date.now(),c=Date.now();for(;Date.now()-c<this.browser.smartWaitingTimeout;){l=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({selector:t.elementDescriptor,targetName:a,logger:i});return {result:await o({locator:u.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;s=u,i.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await Pt(500);}}throw s}async scrollIntoViewAndResolveFinalTarget(t){let{resolutionResult:o,disableGlobalLocatorRedirect:n,logger:r}=t,i=Ar(),a=!n&&this.browser.userBrowserSettings.globalLocatorRedirect!==false;(this.browser.userBrowserSettings.visualActions||a)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(o.locator);});let s;return a&&(s=await i.startAsyncSpan("LOCATOR_REDIRECT",async l=>{let{targetingResult:c,metadata:u}=await this.browser.performTargetRedirection(o,r);if(l.result=u,u.outcome==="redirected to new element"&&c&&i.storeTraceAsset&&!this.browser.userBrowserSettings.disableBrowserMonitoring){let d=randomUUID();(async()=>{try{let m=await this.browser.screenshot({locator:c.locator,clearHighlights:!0,boundingBoxOverride:c.serverSideBoundingBox??void 0});i.storeTraceAsset?.({snapshotId:d,data:m});}catch(m){r.debug({err:m},"Failed to capture element screenshot for redirect trace");}})(),l.elementScreenshotSnapshotId=d;}return c})),s||(s={locator:o.locator,serverSideBoundingBox:await o.locator.boundingBox({timeout:Dt}),originalElementLocationResult:o.originalElementLocationResult}),s}async resolveCachedTargetForAction(t){let{cache:o,options:n,logger:r}=t,a=await Ar().startAsyncSpan("CACHE_RESOLUTION",async l=>{l.targetSource=o.targetSource,l.attributes.smartWaitingTimeoutMs=this.browser.smartWaitingTimeout;let c={attempts:0,evaluationDurationMs:0};try{let u=await this.browser.resolveTarget(o,{allowNotActionableNodesOverride:n.allowNotActionableNodesOverride,logger:r,signal:this.executeAbortController.signal,...n.resolveTargetOptions,stats:c,acceptElementMovedError:n.force});l.attributes.targetDisplayString=u.displayString,l.attributes.decisions=u.decisions;let d=u.decisions.find(m=>m.matched);return d&&(l.resolutionMethod=d.type),u}catch(u){throw u instanceof Za&&(l.cacheMissReason=u.cacheMissReason,l.attributes.decisions=u.decisions),u}finally{c.attempts>0&&(l.resolutionAttempts=c.attempts,l.evaluationDurationMs=c.evaluationDurationMs);}}),s=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:a,disableGlobalLocatorRedirect:n.disableGlobalLocatorRedirect,logger:r});return n.force||await a.revalidator?.(),{resolutionResult:a,finalTarget:s}}async wrapElementTargetingCommand(t){return await kc({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:o,target:n,action:r,options:i,command:a,finalAttempt:s=false,originalCache:l=t.cache}=t,{retriesWithAI:c=1}=t,{disableCache:u,useSelector:d,targetName:m}=i,p=Ar(),h=this.logger.child({commandId:a.id}),g=this.shouldUseMemory(),f=cloneDeep(t.cache);if((!f||u)&&!$Q(n))throw new ie("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(t);let y=false,b;u&&(h.info("Cache explicitly disabled for this step"),y=true,b="Cache explicitly disabled",f=void 0);let S=mOe({cache:f,description:n.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:h});f=S.cache,y=y||S.cacheBustedBeforeAction,!b&&S.cacheBustReason&&(b=S.cacheBustReason);let A=true,T=i.memory??f?.memory;if(!dOe(f))return c--,A=false,this.executeTargetingCommandWithAI({tracer:p,stepTracer:o,target:n,options:{...i,memory:T},command:a,action:r,originalCache:l,logger:h,useMemory:g,cacheBustedBeforeAction:y,cacheBustReason:b});try{let{resolutionResult:v,finalTarget:R}=await this.resolveCachedTargetForAction({cache:f,options:i,logger:h}),I=await r(R);if(zo.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.62.3"]),kL({cmd:a,key:m,newTarget:f,logger:h,updatedWithAI:!1}),A){let C=v.decisions.filter(O=>O.matched);if(C.length!==1)h.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else {let O=C[0].type;o.recordTargetAutoHeal({healType:O});}}return {result:I,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let R=UH(v);if(R&&!s)return h.warn({err:v},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:o,command:a,target:n,action:r,cache:l,originalCache:l,retriesWithAI:c,finalAttempt:true,options:i});if(v instanceof ie&&!R)throw h.warn({err:v},"Failed to execute command with target (fatal)"),v;if(c>0&&n){h.info({err:v,cacheDecisions:v instanceof Za?aOe(v.decisions):void 0},"Failed to execute action with cached target, retrying with AI"),zo.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.62.3",`missReason:${v instanceof Za?v.cacheMissReason:"unknown"}`]);let I;f.memory&&IP(f.memory)&&(I=f.memory);let C=v instanceof Za&&v.cacheMissReason==="failing-ldist";return this.wrapElementTargetingCommandHelper({tracer:o,command:a,target:n,cache:void 0,action:r,originalCache:l,retriesWithAI:c,finalAttempt:true,options:{...i,memory:I,targetHealingInProgress:true},skipInitialLocateWait:C})}throw new ie("ActionFailureError",`Failed to execute interactive command: ${v instanceof Error?v.message:`${v}`}`,{errOptions:{cause:v}})}}async executeTargetingCommandWithAI(t){let{tracer:o,stepTracer:n,target:r,options:i,command:a,action:s,originalCache:l,logger:c,useMemory:u,cacheBustedBeforeAction:d,cacheBustReason:m,skipInitialLocateWait:p}=t;c.info({description:r.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:d,memory:i.memory,useMemory:u},"Prompting AI for an updated element location");let h=this.browser.executionMode==="turbo"||this.getCurrentExecutionOptions().skipAISmartWaiting||i.skipAISmartWaiting,g=false;(d||!l)&&!h?(await o.startAsyncSpan("SMART_WAITING",async()=>await xOe({description:r.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:c,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())),g=true):(d||!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 f=2;for(let y=1;y<=f;y++){let b=false,S=this.browser.getActiveFrameConfig(),A=i.force||y>1;try{let T;try{T=await u5({description:r.elementDescriptor,disableCache:!!i.disableCache,effort:i.effort,onEffectiveEffort:i.onEffectiveEffort,iframeUrl:i.iframeUrl,source:i.source,useMemory:u,memory:u?i.memory:void 0,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,allowIneligibleTagRedirect:i.allowIneligibleTagRedirect,showZeroOpacityElementsOverride:i.showZeroOpacityElementsOverride,logger:c,skipWait:g||h||p,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:m,acceptElementMovedError:A,pastLocatorMiss:i.pastLocatorMiss},this.getControllerFixtures());}catch(I){if(I instanceof zy&&I.updatedLocatorMemory){let C={id:-1,...l,memory:I.updatedLocatorMemory};kL({cmd:a,key:i.targetName,newTarget:C,logger:c,updatedWithAI:!0});}throw I}T.frameConfig&&(this.browser.setActiveFrameConfig(T.frameConfig),b=!0);let v=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:T.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),R=await s(v);return kL({cmd:a,key:i.targetName,newTarget:T.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=Wo(c)),{result:R,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}catch(T){if(b&&this.browser.setActiveFrameConfig(S),this.throwIfClosed(),y<f&&UH(T)){c.warn({err:T,aiAttempt:y},"Encountered retryable AI targeting error; retrying with AI once");continue}throw T instanceof ie?T:new ie("ActionFailureError",T.message,{errOptions:{cause:T}})}}throw new ie("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(t){return U_(this.browser,t)}async waitBetweenSteps(){this.options?.slowMoMs&&await Pt(this.options.slowMoMs,this.executeAbortController.signal);}async executePresetCommand(t,o,n,r,i,a,s){let l=await this.browser.getOpenPages(),c=this.browser.url(),u;try{u=await this.resolveCommandTemplateStrings(o,n);}catch(d){throw this.throwIfClosed(),new ie("ActionFailureError",`Failed to substitute template strings in command: ${d.message}`,{errOptions:{cause:d}})}try{let d=await ge({name:`cli.command.${o.type}`,attributes:{"momentic.command_type":o.type,"momentic.command_id":o.id},fn:()=>this.executePresetCommandHelper(t,o,n,r,i,a,s)});return this.options?.autoFollowNewTabs&&await uOe({beforeUrl:c,command:o,beforePages:l.map(m=>m.url),browser:this.browser,logger:this.logger}),d}catch(d){throw d.name!=="AbortError"&&this.logger.warn({err:d},"Error thrown in action controller"),d}finally{DIe(o,u);}}createCallbacksForBrowser(t){return {createIsolatedFolder:()=>D3(t)}}async traceBrowserInteraction(t,o,n){return Ar().startAsyncSpan("BROWSER_INTERACTION",async i=>o(i),{name:t,...n})}async resolveCommandTemplateStrings(t,o){return PB({obj:t,context:o,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,codeEvaluator:this.codeEvaluator})}async executePresetCommandHelper(t,o,n,r,i,a,s){r=r||"disableCache"in o&&!!o.disableCache;let l=this.logger.child({commandId:o.id}),c=u=>this.wrapElementTargetingCommand({...u,options:{...u.options,effort:a,onEffectiveEffort:s}});switch(o.type){case "SUCCESS":{let u=o.condition;return u?.assertion.trim()?nU({command:u,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:l,recoveryHint:i,effort:a,onEffectiveEffort:s}):{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AI_ASSERTION":{if(!o.assertion.trim())throw new ie("ActionFailureError","Missing assertion");if(o.timeout&&o.timeout>1800)throw new ie("AssertionFailureError",`AI check timeout of ${o.timeout} exceeds the maximum allowed value of 30 minutes.`);return nU({command:o,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:l,recoveryHint:i,effort:a,onEffectiveEffort:s})}case "AI_EXTRACT":return kc({action:()=>COe({command:o,logger:l,fixtures:this.getControllerFixtures(),disableCache:r,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:o.iframeUrl?{type:"url",url:o.iframeUrl}:void 0,browser:this.browser,logger:l});case "NAVIGATE":if(!Qv(o.url)&&!Zv(o.url,this.browser.baseUrl))throw new ie("ActionFailureError",`Invalid URL provided to navigate command: ${o.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:o.url,loadTimeoutMs:o.loadTimeout?o.loadTimeout*1e3:void 0}));break;case "DIALOG":this.browser.registerDialogHandler(o.action);break;case "CAPTCHA":throw new ie("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 u,d;if(o.target&&Jd(o.target)){let h=es(o.target.pixels);await this.browser.hoverUsingVisualCoordinates(h);}else if(o.target&&o.target.elementDescriptor.trim()){let{elementInteractedDisplayString:h,thoughts:g}=await c({tracer:t,command:o,target:o.target,cache:o.cache?.target,action:f=>this.browser.hover(f),options:{...o,targetName:"target",disableGlobalLocatorRedirect:true,disableCache:r}});u=h,d=g;}let m=this.browser.getViewport()?.height??Fa.height,p=this.browser.getViewport()?.width??Fa.width;switch(o.type){case "SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(o.deltaY??m)));break;case "SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(o.deltaY??m));break;case "SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(o.deltaX??p)));break;case "SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(o.deltaX??p));break}return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u,thoughts:d}}case "WAIT_FOR_URL":{if(o.timeout&&o.timeout>1800)throw new ie("UserConfigurationError",`Wait for URL timeout of ${o.timeout} exceeds the maximum allowed value of 30 minutes.`);let u=o.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:u},{timeout:o.timeout?o.timeout*1e3:void 0,negated:o.negated,caseInsensitive:o.caseInsensitive});break}case "WAIT":{if(o.delay>1800)throw new ie("UserConfigurationError",`Wait timeout of ${o.delay} seconds exceeds the maximum allowed value of 30 minutes`);let u=o.delay*1e3;await Pt(u,this.executeAbortController.signal);break}case "REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:o.loadTimeout?o.loadTimeout*1e3:void 0}));break;case "CLICK":{if(Jd(o.target)){let g=es(o.target.pixels),f={...o,relativePosition:o.relativePosition?es(o.relativePosition):void 0};await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(g,f),{coordinates:g});break}let u=this.browser.url(),{elementInteractedDisplayString:d,result:m,thoughts:p}=await c({tracer:t,target:o.target,command:o,cache:o.cache?.target,action:g=>this.traceBrowserInteraction("Click",async f=>{let y={...o,relativePosition:o.relativePosition?es(o.relativePosition):void 0},b=await this.browser.click(g,this.createCallbacksForBrowser(this.orgId),y);return b.coordinates&&(f.coordinates=b.coordinates),b},{selector:g.locator.toString()}),options:{...o,targetName:"target",disableCache:r}}),h={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:d,thoughts:p,data:m.downloadedFile?{downloadedFile:m.downloadedFile}:void 0};return KL(u,h.urlAfterCommand)&&(h.succeedImmediately=true,h.succeedImmediatelyReason="URL changed"),h}case "COPY":return await this.browser.copy(o.value),{succeedImmediately:false,data:o.value,urlAfterCommand:this.browser.url()};case "PASTE":{await this.browser.paste();break}case "DRAG":{if(Jd(o.fromTarget)&&Jd(o.toTarget)){let m=es(o.fromTarget.pixels),p=es(o.toTarget.pixels);await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(m,p,{hoverDurationMs:o.hoverSeconds?o.hoverSeconds*1e3:void 0}),{coordinates:m});break}if(Jd(o.fromTarget)||Jd(o.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:u,thoughts:d}=await this.wrapMultiElementTargetingCommand({tracer:t,command:o,targetNames:["fromTarget","toTarget"],descriptions:[o.fromTarget,o.toTarget],caches:[o.cache?.fromTarget,o.cache?.toTarget],action:(m,p)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(m,p,{hoverDurationMs:o.hoverSeconds?o.hoverSeconds*1e3:void 0,steps:o.steps})),options:{...o,disableCache:r,effort:a,onEffectiveEffort:s}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u[0],thoughts:d}}case "MOUSE_DRAG":{let u=parseInt(o.deltaX),d=parseInt(o.deltaY),m=o.steps??5;if(isNaN(u)||isNaN(d))throw new ie("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${o.deltaX}, ${o.deltaY})`);if(o.target&&Jd(o.target)){let g=es(o.target.pixels);await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:u,deltaY:d,steps:m,fromTarget:g}),{coordinates:g});break}let p,h;if(o.target?.elementDescriptor){let{elementInteractedDisplayString:g,thoughts:f}=await c({tracer:t,command:o,target:o.target,cache:o.cache?.target,action:async y=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(u,d,m,y.locator,{force:o.force})),options:{...o,targetName:"target",disableCache:r}});p=g,h=f;}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(u,d,m,void 0,{force:o.force}));return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:h}}case "SELECT_OPTION":{if(!Gu(o.target))throw new Error("Select with x/y is not supported yet");let u=o.target.elementDescriptor,d=o.choice,{elementInteractedDisplayString:m,thoughts:p}=await c({tracer:t,command:o,target:{type:"description",elementDescriptor:u},cache:o.cache?.target,action:h=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(h,d,o.force),{value:d.type==="LABEL"?d.label:d.type==="VALUE"?d.value:d.index}),options:{...o,targetName:"target",disableCache:r,source:lm(o)}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:p}}case "TAB":{let u=o.timeout===void 0?void 0:o.timeout*1e3,d=o.loadTimeout??o.timeout,m={loadTimeoutMs:d===void 0?void 0:d*1e3,timeoutMs:u,retry:true};await this.browser.switchToPage(o.action,m);break}case "NEW_TAB":await this.browser.createNewTab(o.url,{loadTimeoutMs:o.loadTimeout?o.loadTimeout*1e3:void 0});break;case "CLOSE_TAB":await this.browser.closePage(o.action,{retry:true});break;case "COOKIE":{if(!o.value)break;let u=await this.browser.setCookie(o.value);l.debug({results:u},"Set cookies");break}case "LOCAL_STORAGE":if(!o.value||!o.key)break;await this.browser.setLocalStorage(o.key,o.value);break;case "JAVASCRIPT":{let u;try{o.environment==="BROWSER"?(u=await this.browser.evaluateCodeInPage({code:o.code,fragment:o.fragment??!1,context:n.toObjectCopy(),timeoutMs:o.timeout?o.timeout*1e3:void 0}),l.info({result:u},"Executed JavaScript in browser")):u=await hy({orgId:this.orgId,code:o.code,fragment:!!o.fragment,context:n,timeoutMs:o.timeout?o.timeout*1e3:void 0,logger:l,codeEvaluator:this.codeEvaluator,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async d=>{if(!this.options?.scratchPadId){l.warn({updates:d},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:d,logger:l});}}});}catch(d){throw this.throwIfClosed(),new ie("ActionFailureError",d instanceof Error?d.message:`${d}`,{errOptions:{cause:d}})}try{JSON.stringify(u);}catch(d){throw new ie("ActionFailureError",`Return value is not serializable: ${d instanceof Error?d.message:`${d}`}`,{errOptions:{cause:d}})}return {urlAfterCommand:this.browser.url(),succeedImmediately:false,data:u}}case "TYPE":{if(o.target&&Jd(o.target)){let f=es(o.target.pixels),y={...o,relativePosition:o.relativePosition?es(o.relativePosition):void 0};await this.browser.clickUsingVisualCoordinates(f,y),await this.traceBrowserInteraction("Type",()=>this.browser.type(o.value,{force:o.force,clearContent:o.clearContent,forceClearContent:o.forceClearContent,delay:o.delay??this.browser.userBrowserSettings.typeDelayMs,pressEnter:o.pressEnter,fill:o.fill},true),{value:o.value});break}let u=this.browser.url(),d,m,p=cloneDeep(o.target),h=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(p){let{elementInteractedDisplayString:f,thoughts:y}=await c({tracer:t,command:o,target:p,cache:o.cache?.target,action:b=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(o.value,b,{force:o.force,clearContent:o.clearContent,forceClearContent:o.forceClearContent,delay:o.delay??this.browser.userBrowserSettings.typeDelayMs,pressEnter:o.pressEnter,relativePosition:o.relativePosition,fill:o.fill}),{value:o.value,selector:b.locator.toString()}),options:{...o,targetName:"target",disableCache:r,disableGlobalLocatorRedirect:!h,source:lm(o)}});d=f,m=y;}else await this.traceBrowserInteraction("Type",()=>this.browser.type(o.value,{force:o.force,clearContent:o.clearContent,forceClearContent:o.forceClearContent,delay:o.delay??this.browser.userBrowserSettings.typeDelayMs,pressEnter:o.pressEnter,fill:o.fill},true),{value:o.value});let g={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:d,thoughts:m};return KL(u,g.urlAfterCommand)&&(g.succeedImmediately=true,g.succeedImmediatelyReason="URL changed"),g}case "HOVER":{if(Jd(o.target)){let m=es(o.target.pixels);await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(m),{coordinates:m});break}let{elementInteractedDisplayString:u,thoughts:d}=await c({tracer:t,command:o,target:o.target,cache:o.cache?.target,action:m=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(m,{relativePosition:o.relativePosition?es(o.relativePosition):void 0}),{selector:m.locator.toString()}),options:{...o,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u,thoughts:d}}case "FOCUS":{if(!Gu(o.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:u,thoughts:d}=await c({tracer:t,command:o,target:o.target,cache:o.cache?.target,action:m=>this.browser.focus(m),options:{...o,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u,thoughts:d}}case "BLUR":{if(o.target&&!Gu(o.target))throw new Error("Blur with x/y is not supported yet");if(!o.target||!o.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:false,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:u,thoughts:d}=await c({tracer:t,target:o.target,command:o,cache:o.cache?.target,action:m=>this.browser.blur(m),options:{...o,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:u,thoughts:d}}case "PRESS":{let u=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(o.value,{repeat:o.repeat,convertMeta:o.convertMeta??true,delayMs:o.delayMs??this.browser.userBrowserSettings.pressDelayMs}),{value:o.value});let d={urlAfterCommand:this.browser.url(),succeedImmediately:false};return KL(u,d.urlAfterCommand)&&(d.succeedImmediately=true,d.succeedImmediatelyReason="URL changed"),d}case "KEY_DOWN":return await this.browser.keyDown(o.value,{convertMeta:o.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "KEY_UP":return await this.browser.keyUp(o.value,{convertMeta:o.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "REQUEST":{let u=new CookieJar,d=EPt(fetch,u),m;try{m=new URL(o.url).hostname;}catch{}let p=await NOe({command:o,baseUrl:this.browser.baseUrl,logger:l,fetchImplementation:d});return {data:mR.parse({...p,cookies:Eee(u,m)}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GRAPHQL_REQUEST":return {data:await BOe({command:o,baseUrl:this.browser.baseUrl,logger:l}),succeedImmediately:false,urlAfterCommand:this.browser.url()};case "VISUAL_DIFF":return LOe({tracer:t,command:o,disableCache:r,browser:this.browser,logger:l,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:c});case "FILE_UPLOAD":{let u,d;if(o.fileSource.type==="URL"?(d=o.fileSource.url,u=await Uxe({uri:o.fileSource.url,logger:l,orgId:this.orgId})):o.fileSource.type==="USER_FILE"&&(d=o.fileSource.name,u=await this.uploadedFileStorage?.getFileForUpload(o.fileSource.name,this.orgId)),!u)throw new ie("UserConfigurationError",`Attempted to use non-existent file for upload step: ${d}`);await this.browser.setFileChooserHandler({...u,filename:o.filename});break}case "AUTH_SAVE":{let u=await this.browser.saveAuthState();if(o.storageState&&hf(o.storageState)){let d=Cn__default.resolve(o.storageState);Un__default.mkdirSync(Cn__default.dirname(d),{recursive:true}),Un__default.writeFileSync(d,`${JSON.stringify(u,null,2)}
2662
2662
  `,"utf8");}return {data:u,succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AUTH_LOAD":{let u;if(hf(o.storageState))try{u=JSON.parse(Un__default.readFileSync(Cn__default.resolve(o.storageState),"utf8"));}catch(m){throw new ie("UserConfigurationError",`Failed to read auth state from '${o.storageState}': ${W(m)}`,{errOptions:{cause:m}})}else if(!o.storageState.trim())u=void 0;else if(u=await hy({orgId:this.orgId,code:o.storageState,fragment:false,context:n,logger:l,codeEvaluator:this.codeEvaluator,signal:this.executeAbortController.signal}),typeof u!="object")throw new ie("ActionFailureError",`Credentials must evaluate to an object (received ${typeof u} instead)`);let d;try{d=zk.optional().parse(u);}catch(m){throw new ie("ActionFailureError",`Credentials provided do not follow the required format: ${m}`)}await this.browser.loadAuthState(d);break}case "ELEMENT_CHECK":{let u=(o.timeout??this.browser.userBrowserSettings.elementCheckTimeoutSeconds??jc)*1e3,d=this.generator.getAgentConfig()?.assertion;if(kOe(o.assertion)&&!o.useSelector&&o.target.type==="description"&&d&&d!=="v1"){let p={id:o.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: ${o.target.elementDescriptor}`,iframeUrl:o.iframeUrl,timeout:o.timeout??this.browser.userBrowserSettings.elementCheckTimeoutSeconds,source:"NEGATED_CHECK",cache:o.cache&&"memory"in o.cache?{memory:o.cache?.memory}:void 0};try{let h=await nU({command:p,logger:l,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),effort:a,onEffectiveEffort:s});return {succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${h.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:h.afterScreenshotOverride}}finally{p.cache?.memory&&vI(o,p.cache?.memory.traces,l);}}let m=await POe({command:o,tracer:t,timeoutMs:u,targetingWrapper:c,fixtures:this.getControllerFixtures(),disableCache:r});return {fail:!m.success,data:m.data,elementInteracted:m.elementInteractedDisplayString,thoughts:m.err?.message??m.thoughts??`Element assertion ${m.success?"succeeded":"failed"}.`,succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "PAGE_CHECK":{let u=await kc({action:async()=>rU({assertion:o.assertion,browser:this.browser,logger:l,timeout:o.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:o.iframeUrl?{type:"url",url:o.iframeUrl}:void 0,browser:this.browser,logger:l});return {fail:!u.success,data:u.data,thoughts:u.success?"Page assertion passed.":u.err?.message??`Page assertion still failing after ${o.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:false}}case "REGISTER_REQUEST_LISTENER":{let u=new fy(o.requestMatcher),d=this.browser.registerRequestListener(u);return this.registeredListeners[o.key]=d.then(async m=>await H3(m)).catch(m=>{l.error({err:m},"Failed to get request listener response");}),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AWAIT_LISTENER":{let u=this.registeredListeners[o.key];if(!u)throw new ie("ActionFailureError",`No listener registered with key: ${o.key}`);let d=o.timeout??10;return {data:await ye(u,{milliseconds:d*1e3,message:`Request listener timed out after ${d} seconds`}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "RECORD_REQUESTS":{let u=new fy(o.requestMatcher);return this.recordedRequests[o.key]={},await this.browser.registerRequestRecorder(o.key,{matches:d=>u.matches({url:d.request.url,method:d.request.method}),onRequestStart:(d,m)=>{this.recordedRequests[o.key][d]=GB(m);},onRequestComplete:(d,m)=>{this.recordedRequests[o.key]?.[d]&&(this.recordedRequests[o.key][d]=GB(m));}}),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GET_RECORDED_REQUESTS":{let u=this.recordedRequests[o.key];if(!u)throw new ie("ActionFailureError",`No recorder registered with key: ${o.key}`);return this.browser.removeRequestRecorder(o.key),delete this.recordedRequests[o.key],{data:Object.values(u),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "SET_HEADER":{let u;return o.requestMatcher&&(u=new fy(o.requestMatcher)),await this.browser.setHeader(o.name,o.value,u),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "MOCK_ROUTE":return {data:{key:await this.browser.registerMock(o.key,new fy(o.requestMatcher),async(d,m)=>{let p=await hy({orgId:this.orgId,code:o.responseGenerator,fragment:false,context:n,timeoutMs:void 0,logger:l,codeEvaluator:this.codeEvaluator,mock:{request:d,response:m},disallowVariableUpdates:true,responseSerialization:"RESPONSE"}),h=Yee.parse(p);return new Response(h.body,{status:h.status,headers:h.headers})},o.fetchOriginalResponse??false)},succeedImmediately:false,urlAfterCommand:this.browser.url()};case "REMOVE_ROUTE_MOCK":return this.browser.removeMock(o.key),{succeedImmediately:false,urlAfterCommand:this.browser.url()};case "OFFLINE_MODE":return await this.browser.setOfflineMode(o.enable),{succeedImmediately:false,urlAfterCommand:this.browser.url()};default:return (d=>{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:o,disableCache:n,screenshot:r}){return (await this.generator.getReverseMappedDescription({browserState:t,target:o,screenshot:r},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:Wo(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights();}async startRecordMode({params:t,abortController:o,isClickToRecord:n}){this.recordAbortController=o;let r=new QB({signal:o.signal,...t});return await this.browser.startRecording(this.recordAbortController.signal,r,n),r}async runSectionAutohealing(t){return this.generator.getAutohealingProposal(t,{disableCache:true,abortSignal:this.executeAbortController.signal,loggerTags:Wo(this.logger)})}async getFailureRecoveryPlan(t,o){return this.generator.getFailureRecoveryPlan(t,{disableCache:true,abortSignal:this.executeAbortController.signal,loggerTags:Wo(o??this.logger)})}};var YE=class extends $E{generatedSteps=[];screenshotCaptures=[];knowledgeCitations=[];lastSuccessfulRun;exhaustedStepBudget=false;goalCheckRejections=0;constructor(t){super(t),this.generatedSteps=[...t.initialGeneratedSteps??[]],this.lastSuccessfulRun=t.lastSuccessfulRun;}recordGoalCheck(t){t.achieved||(this.goalCheckRejections+=1),this.callbacks.onAiActionEvent?.({type:"GOAL_CHECK",achieved:t.achieved,reasoning:t.reasoning});}spliceGeneratedSteps(t,o,...n){return this.generatedSteps.splice(t,o,...n)}recordGenericToolCall(t,o){this.callbacks.onAiActionEvent?.({type:"GENERIC_TOOL_CALLED",toolName:t,toolCallId:o});}recordKnowledgeLookup(t){this.callbacks.onAiActionEvent?.({type:"KNOWLEDGE_LOOKUP",queries:t.queries,hitCount:t.hitCount,citations:t.citations});}recordScreenshotCapture(t){this.screenshotCaptures.push(t),this.callbacks.onAiActionEvent?.({type:"SCREENSHOT_CAPTURED",screenshot:t});}onSubStepsCreated(t){for(let o of t)this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",step:o});}onSubStepStarted(t){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_STARTED",step:t});}onSubStepExecuted(t,o){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_EXECUTED",step:t,status:o.status,message:o.message});}};var RPt=2,CPt=2,IPt=1,xPt=15;function HOe({resolvedGoal:e,rawGoal:t,postcondition:o,orgId:n,version:r,supportsTurbo:i,logger:a}){let s=e.trim();if(r!=="3-turbo")return;let l;if(s?t.includes("{{")?l="templated_goal":o?.trim()?l="postcondition_set":fb(n)?i||(l="generator_without_turbo"):l="ineligible_org":l="empty_goal",l){a.info({aiActionTurboDeclined:l,orgId:n},"AI action turbo declined a step that selected it");return}return s}function _Pt({repeats:e,stepKey:t,lastStepKey:o,tree:n,lastTree:r}){return r!==void 0&&n===r&&t===o?e+1:0}var OPt=1,PPt=1500,kPt=300;async function MPt(e,{from:t,abortSignal:o,logger:n}){let r=Date.now()+PPt;for(;Date.now()<r;){await Pt(kPt,o);let{serializedTree:i}=await Mc(e,{skipWaitForPageLoad:true,skipWait:true,abortSignal:o,logger:n});if(i!==t)return true}return false}var LPt={repeats:0,identicalActions:0,nudges:0};function NPt(e,{stepKey:t,tree:o}){let n=_Pt({repeats:e.repeats,stepKey:t,lastStepKey:e.lastStepKey,tree:o,lastTree:e.lastTree}),r=t===e.lastActionKey?e.identicalActions+1:0,i=e.lastTree!==void 0&&o!==e.lastTree,a={repeats:n,identicalActions:r,nudges:i?0:e.nudges,lastStepKey:t,lastActionKey:t,lastTree:o};if(r>=xPt)return {verdict:"handoff",reason:"identical",count:r+1,guard:a};if(n<CPt)return {verdict:"execute",guard:a};let s=a.nudges+1;return s>IPt?{verdict:"handoff",reason:"stalled",count:n+1,guard:{...a,nudges:s}}:{verdict:"nudge",guard:{...a,nudges:s,repeats:0,lastStepKey:void 0}}}async function $Oe({params:e,resolvedGoal:t,cacheBeforeTurbo:o,onEvent:n,executeSteps:r,succeed:i,heal:a}){let s=new Date,{step:l}=e.aiStepParams,{controller:c,logger:u}=e.fixtures,d=new YE({controller:c,callbacks:{onAiActionEvent:n,executeSteps:r},logger:u,rootStep:k_({stepId:l.id,currentParentIdChain:e.currentParentIdChain})}),m=await BPt({goal:t,controller:c,logger:u,executeStep:async f=>{let[y]=await d.executeSteps([f],{skipAISmartWaitingForFirstStep:!0});if(!y)throw new Error("Turbo sub-step returned no result");return y},onThought:f=>n({type:"LLM_TEXT_OUTPUT",text:f})}),p={...l,cache:{resolvedGoal:t,steps:m.generatedSteps}};if(m.status==="cancelled")return {...l,cache:o,status:"CANCELLED",startedAt:s,finishedAt:new Date,message:m.message,results:m.results};if(m.status==="done"){let f=await i(m.generatedSteps,m.results,m.message);return f.cache&&n({type:"CACHED_STEPS_GENERATED",cachedSteps:f.cache.steps,resolvedGoal:f.cache.resolvedGoal,lastSuccessfulRun:f.cache.lastSuccessfulRun}),f}if(m.generatedSteps.length===0&&!m.budgetExhausted)return;let h=f=>({...p,status:"FAILED",startedAt:s,finishedAt:new Date,message:f,results:m.results});if(m.budgetExhausted)return h(m.message);n({type:"PHASE_CHANGED",phase:"autoheal",failureMessage:m.message});let g=await a({...e,aiStepParams:{...e.aiStepParams,step:p}},m.generatedSteps,m.results.filter(f=>f.status==="SUCCESS"),`A fast agent executed the cached steps and then stopped (${m.message}). The page is in the state those steps left it in. Continue from here to finish the goal, keeping the cached steps.`);return g.type==="healed"?g.result:h(`Turbo executed ${m.generatedSteps.length} steps, then handed off (${m.message}), and the full agent could not finish.${g.message?` Healing failure: ${g.message}`:""}`)}function DPt(e){switch(e.action){case "CLICK":return `CLICK ${e.targetDescription}`;case "TYPE":return `TYPE ${JSON.stringify(e.text)} into ${e.targetDescription}`;case "PRESS_ENTER":return "PRESS Enter";case "NAVIGATE":return `NAVIGATE ${e.url}`}}async function FPt(e,t,o,n){let r={id:randomUUID(),thoughts:n},i;switch(e.action){case "PRESS_ENTER":i={...r,type:"PRESS",value:"Enter"};break;case "NAVIGATE":i={...r,type:"NAVIGATE",url:e.url};break;case "CLICK":case "TYPE":{let{target:a}=await t.browser.createTargetFromA11yId({id:e.targetId,description:e.targetDescription,targetSource:"AI",logger:o}),s={...r,target:{type:"description",elementDescriptor:e.targetDescription},cache:{target:a}};e.action==="CLICK"?i={...s,type:"CLICK"}:i={...s,type:"TYPE",value:e.text,clearContent:true};break}}return {id:randomUUID(),type:"PRESET_ACTION",command:i}}async function BPt({goal:e,controller:t,logger:o,executeStep:n,onThought:r}){let{browser:i}=t,a=t.generator.getAiActionTurboDecision?.bind(t.generator),s=t.executeAbortController.signal,l=[],c=[],u=[],d=0,m=0,p=LPt;if(!a)return {status:"handoff",message:"this generator has no turbo endpoint",generatedSteps:l,results:c};let h=f=>(r(`Turbo handing off to the full agent: ${f}
2663
2663
 
2664
2664
  `),o.info({aiActionTurboHandoff:f,stepsGenerated:l.length},"AI action turbo handed off to the full agent"),{status:"handoff",message:f,generatedSteps:l,results:c}),g=(f,y)=>{if(d++,u.push(`${f} -> FAILED: ${y}`),!(d<RPt))return h(`${f} failed: ${y}`)};for(let f=0;f<kp;f++)try{s.throwIfAborted();let y={snapshotMs:0,decideMs:0,buildMs:0,executeMs:0},b=Date.now(),{serializedTree:S}=await Mc(i,{skipWaitForPageLoad:!0,skipWait:f>0,abortSignal:s,logger:o});y.snapshotMs=Date.now()-b,b=Date.now();let A=await a({goal:e,url:i.url(),browserState:S,history:u},{logger:o,abortSignal:s});if(y.decideMs=Date.now()-b,o.info({decision:A,stepIndex:f,snapshotChars:S.length},"AI action turbo decision"),A.type==="defer")return A.thoughts&&r(`${A.thoughts}
@@ -3206,7 +3206,7 @@ to pick which of these modules are relevant:
3206
3206
 
3207
3207
  `;let d=qLt(c);u+=d;let m=await sp({schema:Hke,abortSignal:n?.signal,providerFallback:{logger:r,providers:["azure/gpt-6-luna","gpt-6-luna","azure/gpt-5.6-luna","gpt-5.6-luna","openrouter/google/gemini-3.7-flash","vertex/gemini-3.8-flash"].map(g=>e.generator.getModelProviderCandidate(g,{sessionId:l,logger:r,streamType:"module-recommendation"}))},instructions:WLt,messages:[{role:"user",content:u}]}),p=new Set(c.map(g=>g.moduleId)),h=m.recommendations.filter(g=>p.has(g.moduleId)?!0:(r.warn({moduleId:g.moduleId,moduleName:g.moduleName},"AI recommended a module that doesn't exist"),!1));o.addPartFromText(JSON.stringify({recommendations:h,totalModulesAnalyzed:c.length},null,2));}catch(c){n?.signal.throwIfAborted(),r.error({err:c},"Error in module recommendation"),o.addError(`Failed to recommend modules: ${W(c)}`);}}}),jU=[YLt,GLt];var JLt=1e4,J5=new WeakSet;async function HS({response:e,extra:t,sessionId:o,toolName:n,attributes:r,operation:i}){let a=Nd({response:e,sessionId:o,toolName:n});if(a)try{await X5({session:a,signal:t?.signal,operation:()=>XLt({extra:t,session:a,toolName:n,attributes:r,operation:i})});}catch(s){e.addError(W(s));}}async function XLt({extra:e,session:t,toolName:o,attributes:n,operation:r}){if(ji.getSession(t.sessionId)!==t||t.cleanupInProgress)throw new Error(`Session '${t.sessionId}' is no longer active.`);t.controller.setOpen();let i=e?.signal?t.controller.bindCancellation(e.signal):void 0,a;try{e?.signal?.throwIfAborted(),a=ge({name:o,root:t.shareDiagnostics,attributes:{"momentic.org_id":t.orgId,"momentic.session_id":t.sessionId,"momentic.test_id":t.testId,...n},fn:()=>r(t)}),await Q5({signal:e?.signal,operation:async()=>await a});}catch(s){if(e?.signal?.aborted&&a){let l,c=await Promise.race([a.then(()=>true,()=>true),new Promise(u=>{l=setTimeout(()=>u(false),JLt);})]);l&&clearTimeout(l),c||ji.killSession(t.sessionId,"cancelled MCP operation did not stop");}throw s}finally{i?.();}}async function X5({session:e,signal:t,operation:o}){if(t?.throwIfAborted(),J5.has(e))throw new Error("Another browser operation is already active for this session. Wait for it to finish or cancel it before retrying.");J5.add(e);try{return await o()}finally{J5.delete(e);}}async function Q5({signal:e,operation:t}){return e?.throwIfAborted(),e?await new Promise((o,n)=>{let r=()=>n(e.reason??new Error("MCP tool call cancelled."));e.addEventListener("abort",r,{once:true}),t().then(o,n).finally(()=>{e.removeEventListener("abort",r);});}):await t()}function zU({signal:e,onCancellation:t}){if(!(!e||!t)){if(e.aborted){t();return}return e.addEventListener("abort",t,{once:true}),()=>e.removeEventListener("abort",t)}}var QLt=Object.getPrototypeOf(async function(){}).constructor;async function $ke({code:e,page:t,signal:o}){return await new QLt("page","signal",`"use strict"; return await (${e})(page, signal);
3208
3208
  //# sourceURL=momentic-mcp/run-playwright-unsafe.js`)(t,o)}var ZLt=1e5,Gke=$r({schema:{name:ER,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. ${ci}`,inputSchema:{sessionId:z.string().describe("The session id to query."),returnBrowserState:z.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.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.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,o,n)=>{await HS({response:o,extra:n,sessionId:t.sessionId,toolName:ER,operation:async r=>{let i=await W5({browser:r.controller.browser,isRemoteBrowser:r.isRemoteBrowser,supportsFileOutput:e.supportsFileOutput,returnBrowserState:t.returnBrowserState,returnScreenshot:t.returnScreenshot,tokenLimit:ZLt,hint:t.hint,filtering:{generator:e.generator,orgId:e.orgId,logger:e.logger,signal:r.controller.executeAbortController.signal}});o.addContentParts(i);}});}}),Vke=$r({schema:{name:wR,description:`${OT} ${ci}`,inputSchema:{sessionId:z.string(),filters:z.array(z.string().trim().min(1)).min(1).optional().describe(PT)}},handle:async(e,t,o)=>{let n=Nd({response:o,sessionId:t.sessionId,toolName:wR});if(!n)return;let r=await Ld({testContext:n.context,supportsFileOutput:e.supportsFileOutput,filters:t.filters});o.addContentParts(r);}}),Wke=$r({schema:{name:a$,description:"UNSAFE escape hatch for running raw Playwright code against the current active Momentic session only. This tool is exposed only when the MCP server starts with --enable-unsafe-full-access. It executes arbitrary JavaScript in the MCP server process and is RCE-equivalent. Code, stateful setup, and handlers registered through this tool are not saved into the Momentic test and will not be available when the test runs later. Do not use this tool to build durable test workflows. Use it only for temporary test-data setup, debugging, custom interactive-session reset logic, or registering handlers needed during the current session when structured Momentic tools cannot express the operation. Do not use it for normal page interactions such as clicking, typing, navigation, element location, or assertions; those bypass Momentic's caches, waits, traces, and authored-step behavior. The function receives the active Playwright Page and an AbortSignal; access its BrowserContext with page.context().",inputSchema:{sessionId:z.string().describe("The active Momentic session id."),code:z.string().trim().min(1).describe("An async JavaScript function invoked with the active Playwright Page and an AbortSignal, for example: async (page, signal) => { signal.throwIfAborted(); await page.context().clearCookies(); return page.url(); }. Return a JSON-serializable value. Await all setup work that must finish before the next tool call. Event and route handlers registered on the page or its context remain active for the session.")}},handle:async(e,t,o,n)=>{await HS({response:o,extra:n,sessionId:t.sessionId,toolName:a$,operation:async r=>{let i=zU({signal:n?.signal,onCancellation:()=>{ji.killSession(t.sessionId,"unsafe MCP tool cancelled");}});try{let a=await $ke({code:t.code,page:r.controller.browser.getActivePage(),signal:n?.signal}),s=JSON.stringify({result:a??null},null,2);o.addPartFromText(s);}finally{i?.();}}});}});var qke=$r({schema:{name:Eg,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. ${u_} 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 ${da} to inspect persisted test state by id or path, especially for a different test.`,inputSchema:{testId:z.string().describe("The test id to target when starting a session."),envName:z.string().optional().describe("Optional environment override (matches CLI --env behavior). Defaults to the test's default env when omitted."),projectConfigPath:z.string().optional().describe("Optional path to a momentic.config.yaml file (matches CLI --config)."),projectNameFilter:z.string().optional().describe("Optional project name filter for workspace configs (matches CLI --filter)."),headfulBrowser:z.boolean().optional().describe("Whether to launch a headful browser for the session. When omitted, uses the MCP server default if configured."),video:z.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."),shareDiagnostics:z.boolean().optional().describe("Share local session diagnostics using the configured OpenTelemetry exporter."),turbo:z.boolean().optional().describe("Prioritize speed over human-like interactions by skipping selected browser readiness and stability waits, at the expense of accuracy on complex or highly dynamic sites.")}},handle:async(e,t,o,n)=>{let{logger:r}=e,i=t.shareDiagnostics??e.shareDiagnostics??false;await su({serviceName:"mcp",enabled:i});let a=t.video??e.videoDefault??false,s;a&&(zr(e.project.rootDir),s=Hr({rootDir:e.project.rootDir,entity:"video",ext:"d"}),mkdirSync(s,{recursive:true}));let l;try{let m=hr();if(!m){o.addError("API client is not initialized; cannot start MCP session.");return}let p=await cl({project:await on({configFilePath:t.projectConfigPath??e.project.configFilePath,nameFilter:t.projectNameFilter,skipExitOnError:!0}),apiClient:m}),h=new Fc(m,e.orgId,p),g;t.turbo===!0?g="turbo":t.turbo===!1&&(g="standard"),l=await ji.startSession({logger:r,storage:h,testId:t.testId,idleTimeoutMs:e.sessionIdleTimeoutMs,runner:"mcp",envName:t.envName,headfulOverride:t.headfulBrowser??e.headfulDefault??!0,customHeaders:e.customHeaders,devicePixelRatio:e.devicePixelRatio,videoOutputDir:s,browserExecutionMode:g,shareDiagnostics:i,abortSignal:n?.signal});}catch(m){o.addError(W(m));return}let c=n?.signal?l.controller.bindCancellation(n.signal):void 0;c&&o.addCleanupCallback(c);let u=zU({signal:n?.signal,onCancellation:()=>{ji.killSession(l.sessionId,"MCP session start cancelled");}});u&&o.addCleanupCallback(u),n?.signal.throwIfAborted(),Dc({type:"mcp:session_started",test_platform:"web"});let d=l.controller.browser.getViewport();o.addPartFromText(JSON.stringify({sessionId:l.sessionId,testId:l.testId,testFileAbsolutePath:l.testFileAbsolutePath,projectRootAbsolutePath:e.project.rootDir,projectConfigAbsolutePath:e.project.configFilePath,cwd:IE(),createdAt:l.createdAt,expiresAt:l.idleTimeoutMs===void 0?void 0:l.lastAccessedAt+l.idleTimeoutMs,idleTimeoutMinutes:l.idleTimeoutMs===void 0?void 0:l.idleTimeoutMs/(60*1e3),envName:l.envName,baseUrl:l.baseUrl,viewport:d,browserExecutionMode:l.controller.browser.executionMode,authoringStrategy:"Prefer momentic_preview_steps for known adjacent steps. Use momentic_locate_multiple_elements first only when future targets are already present and earlier interactions will not replace or materially change them. CacheIds are optional; persist cacheless steps unchanged."},null,2)),o.addContentParts(await pwe({projectRootAbsolutePath:e.project.rootDir,projectConfigAbsolutePath:e.project.configFilePath,cwd:IE(),stepSchema:vs(),stepSchemaTitle:"Step schema",supportsFileOutput:e.supportsFileOutput}));try{let m=await wy({project:l.storage.getProject(),storage:l.storage,selector:{id:l.testId},envName:l.envName,logger:r,mutableStepState:l.mutableStepState,includeCache:!1,hydrateStepIdentity:!0,supportsFileOutput:e.supportsFileOutput});o.addContentParts(m);}catch(m){r.warn({sessionId:l.sessionId,err:m},"Session started but resolved test content could not be loaded");}try{o.addContentParts(await hl({browser:l.controller.browser,supportsFileOutput:e.supportsFileOutput}));}catch(m){r.warn({sessionId:l.sessionId,err:m},"Session started but initial screenshot capture failed"),o.addPartFromText(JSON.stringify({warning:"Session started successfully, but initial screenshot capture failed.",screenshotError:W(m)},null,2));}s&&o.addContentParts(D({text:fr({filePath:s,title:"Video output directory"}),section:"Video Output"}));}}),Kke=$r({schema:{name:i$,description:"Update settings for an active browser session without resetting its page state, cookies, tabs, or caches. Use standard execution when turbo has trouble with a complex or highly dynamic site; switch back to turbo when speed is preferred.",inputSchema:{sessionId:z.string().describe("The session id to update."),settings:z.object({browserExecutionMode:z.enum(["standard","turbo"]).describe("Turbo skips selected browser readiness and stability waits; standard restores the full waiting behavior.")})}},handle:async(e,t,o,n)=>{await HS({response:o,extra:n,sessionId:t.sessionId,toolName:i$,attributes:{"momentic.browser_execution_mode":t.settings.browserExecutionMode},operation:async r=>{let i=r.controller.browser.updateRuntimeSettings({executionMode:t.settings.browserExecutionMode});o.addPartFromText(JSON.stringify({sessionId:r.sessionId,settings:{browserExecutionMode:i.executionMode}},null,2));}});}}),Yke=$r({schema:{name:zP,description:`Kill a granular browser session by sessionId. Returns available session ids if the target is missing. ${ci}`,inputSchema:{sessionId:z.string().describe("The session id to terminate.")}},handle:async(e,t,o)=>{let{sessionId:n}=t;try{let r=ji.getSession(n),i=r?.videoOutputDir,a=await ji.killSession(t.sessionId,"explicit kill");if(a.killed&&Dc({type:"mcp:session_killed",test_platform:"web",reason:"explicit kill"}),!a.killed){r?o.addError(`Failed to terminate session '${t.sessionId}'.`):o.addError(JSON.stringify({message:`No active session found for id '${t.sessionId}'.`,availableSessionIds:ji.listSessionIds()},null,2));return}o.addPartFromText(JSON.stringify({sessionId:t.sessionId,killed:!0},null,2));let s=await hwe({killResult:a,rootDir:e.project.rootDir});s&&o.addContentParts(D({text:fr({filePath:s.filePath,title:"Session span report"}),section:"Session Spans"})),i&&o.addContentParts(D({text:fr({filePath:i,title:"Video output directory"}),section:"Video Output"}));}catch(r){o.addError(W(r));}}});var Z5=async({steps:e,fromStep:t,toStep:o,tracer:n,collectStepScreenshots:r,controller:i,executionOptions:a,storage:s,codeEvaluator:l,logger:c,socket:u,testContext:d,orgId:m,sessionId:p,usageTracker:h,apiClient:g})=>{let f={controller:i,storage:s,codeEvaluator:l,logger:c,context:d,usageTracker:h},y=n??(u?new Kh({orgId:m,parentStep:null,parentTracer:null,socket:u}):new XC),b={results:[],asyncTasks:[],state:{autoHealingDisabled:true,failureRecoveryDisabled:true,failureRecoveryAttempts:0},...t&&{fastForwardingToStep:true}},S=()=>(i.setOpen(),Nc({listParams:{containerName:"agent-step-list",steps:e,tracer:y},fixtures:f,options:{collectDebugData:false,collectStepScreenshots:r,reinitializeBrowser:false,disableHealing:true},inputs:{orgId:m,userId:KTe(),runId:randomUUID(),sessionId:p,clientMode:"interactive",steps:e,testMetadata:null,orgSettings:{},fromStep:t,toStep:o},callbacks:{test:{},step:{}},runParams:g?{apiClient:g}:null,work:b}));return i.withExclusiveStepSequence(()=>a?i.withExecutionOptions(a,S):S())},ew=async({step:e,controller:t,executionOptions:o,storage:n,codeEvaluator:r,logger:i,socket:a,testContext:s,orgId:l,sessionId:c,usageTracker:u,apiClient:d})=>{let m;try{m=await Z5({steps:[e],controller:t,executionOptions:o,storage:n,codeEvaluator:r,logger:i,socket:a,testContext:s,orgId:l,sessionId:c,usageTracker:u,apiClient:d});}finally{u.flushEvents(i);}return m.results[0]};async function oO({step:e,project:t,logger:o,storage:n,controller:r,codeEvaluator:i,socket:a,orgId:s,sessionId:l,testContext:c,supportsFileOutput:u,tempCaches:d,usageTracker:m,apiClient:p,onStepResult:h,includeBrowserState:g,skipAISmartWaiting:f}){let y=await e_(e,{project:t,logger:o,tempCaches:d});switch(y.type){case "PRESET_ACTION":return oNt({step:y,logger:o,storage:n,controller:r,codeEvaluator:i,socket:a,orgId:s,sessionId:l,testContext:c,supportsFileOutput:u,tempCaches:d,usageTracker:m,apiClient:p,onStepResult:h,includeBrowserState:g,skipAISmartWaiting:f});case "AI_ACTION_DYNAMIC":return nNt({step:y,logger:o,storage:n,controller:r,codeEvaluator:i,socket:a,orgId:s,sessionId:l,testContext:c,supportsFileOutput:u,usageTracker:m,apiClient:p,onStepResult:h,includeBrowserState:g,skipAISmartWaiting:f});case "RESOLVED_MODULE":return rNt({step:y,logger:o,storage:n,controller:r,codeEvaluator:i,socket:a,orgId:s,sessionId:l,testContext:c,supportsFileOutput:u,usageTracker:m,apiClient:p,onStepResult:h,includeBrowserState:g,skipAISmartWaiting:f});default:{let[b,S]=await Promise.all([hl({browser:r.browser,supportsFileOutput:u}),Ld({testContext:c,supportsFileOutput:u})]);return [...D({text:`Preview for step type ${y.type} is not supported. Only PRESET_ACTION, RESOLVED_MODULE, and AI_ACTION_DYNAMIC are supported.`,section:"Error"}),...b,...S]}}}async function Jke({steps:e,project:t,logger:o,storage:n,controller:r,codeEvaluator:i,socket:a,orgId:s,sessionId:l,testContext:c,supportsFileOutput:u,tempCaches:d,usageTracker:m,apiClient:p,onStepResult:h}){let g=[],f=0,y;for(let b=0;b<e.length;b++){g.push(...AIe({index:b,rawStep:e[b]}));let S;try{let A=await oO({step:e[b],project:t,logger:o,storage:n,controller:r,codeEvaluator:i,socket:a,orgId:s,sessionId:l,testContext:c,supportsFileOutput:u,usageTracker:m,apiClient:p,tempCaches:d,includeBrowserState:!1,skipAISmartWaiting:b===0,onStepResult:T=>{S=T,h?.(T);}});g.push(...A);}catch(A){r.executeAbortController.signal.throwIfAborted(),o.error({err:A,stepIndex:b+1},"Batch preview step execution errored"),g.push(...D({text:`Step Execution errored: ${W(A)}`,section:"Error"})),y=b+1;break}if(!S||S.status!=="SUCCESS"){y=b+1;break}f++;}g.push(...wIe({completedSteps:f,failedStep:y})),r.executeAbortController.signal.throwIfAborted();try{g.push(...await HU({controller:r,supportsFileOutput:u,testContext:c}));}catch(b){o.warn({err:b},"Batch preview completed but final browser state capture failed"),g.push(...D({text:`Final browser state capture failed: ${W(b)}`,section:"Error"}));}return {parts:g,successful:y===void 0}}async function Xke({steps:e,project:t,logger:o,controller:n,testContext:r,tempCaches:i}){let a=await Promise.all(e.map(l=>e_(l,{project:t,logger:o,tempCaches:i}))),s=a.findIndex(l=>l.type!=="PRESET_ACTION");if(s>=0)throw new Error(`Step ${s+1} must be a supported single-target CLICK, TYPE, HOVER, BLUR, or SELECT_OPTION step with a description`);return RIe({steps:a.map(l=>{if(l.type!=="PRESET_ACTION")throw new Error(`Unsupported step type ${l.type}`);return l}),rawSteps:e,logger:o,controller:n,testContext:r,tempCaches:i})}async function oNt({step:e,logger:t,storage:o,controller:n,codeEvaluator:r,socket:i,orgId:a,sessionId:s,testContext:l,supportsFileOutput:c,tempCaches:u,usageTracker:d,apiClient:m,onStepResult:p,includeBrowserState:h=true,skipAISmartWaiting:g=true}){let f=await ew({step:e,logger:t,storage:o,controller:n,executionOptions:{skipAISmartWaiting:g},codeEvaluator:r,socket:i,orgId:a,sessionId:s,testContext:l,usageTracker:d,apiClient:m});f&&p?.(f);let y=[];return f?.status==="SUCCESS"&&p3({logger:t,tempCaches:u,command:e.command,parts:y}),y.push(...EIe({result:f})),h&&y.push(...await HU({controller:n,supportsFileOutput:c,testContext:l})),y}async function HU({controller:e,supportsFileOutput:t,testContext:o}){await e.browser.waitForStability();let[n,r]=await Promise.all([hl({browser:e.browser,supportsFileOutput:t}),Ld({testContext:o,supportsFileOutput:t})]);return [...n,...r]}async function nNt({step:e,logger:t,storage:o,controller:n,codeEvaluator:r,socket:i,orgId:a,sessionId:s,testContext:l,supportsFileOutput:c,usageTracker:u,apiClient:d,onStepResult:m,includeBrowserState:p=true,skipAISmartWaiting:h=true}){let g=await ew({step:e,logger:t,storage:o,controller:n,executionOptions:{skipAISmartWaiting:h},codeEvaluator:r,socket:i,orgId:a,sessionId:s,testContext:l,usageTracker:u,apiClient:d});g&&m?.(g);let f=[];return g?g.status==="SUCCESS"?f.push(...D({text:`AI action completed successfully: ${g.message??"Goal achieved"}`,section:"Successful Result"})):f.push(...D({text:`AI action failed: ${g.message??"Unknown error while previewing AI action"}`,section:"Error"})):f.push(...D({text:"AI action executed with unknown result.",section:"Error"})),p&&f.push(...await HU({controller:n,supportsFileOutput:c,testContext:l})),f}async function rNt({step:e,logger:t,storage:o,controller:n,codeEvaluator:r,socket:i,orgId:a,sessionId:s,testContext:l,supportsFileOutput:c,usageTracker:u,apiClient:d,onStepResult:m,includeBrowserState:p=true,skipAISmartWaiting:h=true}){let g=await ew({step:e,logger:t,storage:o,controller:n,executionOptions:{skipAISmartWaiting:h},codeEvaluator:r,socket:i,orgId:a,sessionId:s,testContext:l,usageTracker:u,apiClient:d});g&&m?.(g);let f=[];return g?g.status==="SUCCESS"?f.push(...D({text:`Module executed successfully: ${g.message}`,section:"Successful Result"})):f.push(...D({text:`Module execution failed: ${g.message}`,section:"Error"})):f.push(...D({text:"Module execution errored for an unknown reason.",section:"Error"})),p&&f.push(...await HU({controller:n,supportsFileOutput:c,testContext:l})),f}var Qke=({steps:e,fromStep:t,toStep:o})=>{let n={total:0,fastForwardingToStep:true},r=(i,a)=>{if(i.skipped)return false;let s=a.map(c=>c.id),l=P_(i.id,s,t.fromStepId,t.parentStepIdChain);if(n.fastForwardingToStep){if(!l)return false;n.fastForwardingToStep=false;}return n.total+=1,!!(o&&P_(i.id,s,o.toStepId,o.parentStepIdChain))};return Ys({steps:e,earlyStop:true,onPresetAction:(i,a)=>r(i,a.parentChain),onConditional:(i,a)=>{if(i.skipped)return false;let s=a.parentChain.map(c=>c.id),l=P_(i.id,s,t.fromStepId,t.parentStepIdChain);if(n.fastForwardingToStep){if(!l)return false;n.fastForwardingToStep=false;}return !!(o&&P_(i.id,s,o.toStepId,o.parentStepIdChain))},onSimpleStepContainer:(i,a)=>r(i,a.parentChain)}),n.total};var aNt="Cannot add a module step inside another module. Modules cannot be nested.";function eJ(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 sNt(e,t,o){let n=eJ(e,t);if(!o?.length)return n;let r=cle(n,o);if(!r)throw new Error(`No step found with parent chain [${o.join(", ")}] in ${t} section, or parent does not support nested steps`);return r}function Zke(e,t){let o=t.moduleId,n=r=>{r.type!=="RESOLVED_MODULE"||r.moduleId!==o||(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])Ys({steps:r,onPresetAction:n,onConditional:n,onSimpleStepContainer:n});}async function $U({project:e,storage:t,orgId:o,logger:n,testPath:r,saveChangesToDisk:i,supportsFileOutput:a,tempCaches:s,mutableStepState:l,onStepSplice:c,params:u,envName:d}){let m=Cn__default.join(e.rootDir,r),p=await t.getTestByPath({relativeTestPath:r,logger:n}),h=l?.stepLists??p,g=cloneDeep({steps:h.steps??[],beforeSteps:h.beforeSteps??[],afterSteps:h.afterSteps??[]}),f=cloneDeep(g),y;try{y=await Promise.all(u.steps.map(O=>e_(O,{project:e,logger:n,tempCaches:s})));}catch(O){return J(D({text:`Error parsing steps: ${W(O)}`,section:"Error"}))}let b=cloneDeep(y),S=u.parentStepIdChain,A;try{A=sNt(f,u.targetSection,S);}catch(O){return J(D({text:`Error: ${W(O)}`,section:"Error"}))}if(u.startIndex<0||u.startIndex>A.length)return J(D({text:`Error: Invalid startIndex ${u.startIndex} for splicing ${u.targetSection} section with ${A.length} steps (must be 0-${A.length})`,section:"Error"}));let T=y.length,v=u.deleteCount,R=cloneDeep(A.slice(u.startIndex,u.startIndex+v)),I=[];if(S?.length){let O=ule(eJ(f,u.targetSection),S,u.targetSection);if(I.push(...O),O.some(k=>k.type==="RESOLVED_MODULE")&&y.some(k=>k.type==="RESOLVED_MODULE"))return J(D({text:`Error: ${aNt}`,section:"Error"}))}A.splice(u.startIndex,u.deleteCount,...y);for(let O of y)O.type==="RESOLVED_MODULE"&&Zke(f,O);for(let O of I)O.type==="RESOLVED_MODULE"&&Zke(f,O);if(l&&(l.stepLists=f),c?.({targetSection:u.targetSection,parentStepIdChain:S??[],startIndex:u.startIndex,deletedSteps:R,insertedSteps:b}),i){let O=await t.updateTestByPath({logger:n,relativeTestPath:r,stepLists:f,schemaVersion:qt});n.info({testPath:r,testFilePath:m,projectFileFormat:e.config.fileFormat,moduleUpdateCount:O.moduleUpdates.length,snapshotCacheCount:O.snapshotCachesToSave.length},"MCP splice persisted test changes to disk");}else n.info({testPath:r,testFilePath:m,projectFileFormat:e.config.fileFormat},"MCP splice skipped disk persistence");let C=[...D({text:`Successfully spliced ${T} step(s) at index ${u.startIndex} in the ${u.targetSection} section, removing ${v} step(s).`,section:"Result"})];return C.push(...await uNt({logger:n,project:e,orgId:o,testId:p.id,environment:d,originalSteps:g,updatedSteps:f})),C.push(...await vIe({rootDir:e.rootDir,supportsFileOutput:a,deletedStepRefs:R.map((O,P)=>({id:O.id,index:u.startIndex+P})),insertedStepRefs:b.map((O,P)=>({id:O.id,index:u.startIndex+P})),deletedSteps:uf(R,{includeCache:false}),insertedSteps:uf(b,{includeCache:false}),metadata:{section:u.targetSection,parentStepIdChain:S??[],startIndex:u.startIndex,deleteCount:v,insertedCount:T},artifactEntity:"splice-restoration-payload"})),u.returnTest&&C.push(...D({text:JSON.stringify(await NU({project:e,storage:t,selector:{path:r},envName:d,logger:n,mutableStepState:l,supportsFileOutput:a,hydrateStepIdentity:false}),null,2),section:"Test Content"})),J(C)}async function GU({project:e,logger:t,testPath:o,storage:n,controller:r,codeEvaluator:i,socket:a,orgId:s,sessionId:l,envName:c,testContext:u,tracer:d,params:m,tokenLimit:p,supportsFileOutput:h,usageTracker:g,mutableStepState:f,apiClient:y,disableCache:b,collectStepScreenshots:S,abortSignal:A}){let{fromStep:T,toStep:v,targetSection:R}=m,I=await n.getTestByPath({relativeTestPath:o,logger:t}),{alwaysSaveCache:C,noCache:O}=Cd(),P=await Rs({logger:t,orgId:s,project:e,alwaysSaveCache:C,noCache:O||b===true}),k=f?.stepLists??{beforeSteps:I.beforeSteps??[],afterSteps:I.afterSteps??[],steps:I.steps};await P.resolveStepCacheEntries({logger:t,schemaVersion:I.schemaVersion,stepLists:k,testId:I.id,environment:c,useSnapshotIdentityCache:!f&&e.config.fileFormat==="v2"}),f&&(f.stepLists=k);let N=b?cloneDeep(k):k;b&&lNt(N);let M=eJ(N,R),L=cloneDeep({steps:N.steps,beforeSteps:N.beforeSteps,afterSteps:N.afterSteps}),{result:G}=sd(M,T.fromStepId,T.parentStepIdChain);if(!G)return J(D({text:`Error: No step found with id "${T.fromStepId}" and parent chain [${T.parentStepIdChain.join(", ")}] in ${R} section.`,section:"Error"}));if(v){let{result:Q}=sd(M,v.toStepId,v.parentStepIdChain);if(!Q)return J(D({text:`Error: No step found with id "${v.toStepId}" and parent chain [${v.parentStepIdChain.join(", ")}] in ${R} section.`,section:"Error"}))}if(d?.setProgressTotal){let Q=Qke({steps:M,fromStep:T,toStep:v});d.setProgressTotal(Q);}eMe({controller:r,abortSignal:A});let X;try{X=await Z5({steps:M,controller:r,storage:n,codeEvaluator:i,logger:t,socket:a,orgId:s,sessionId:l,testContext:u,fromStep:T,toStep:v,tracer:d,collectStepScreenshots:S,usageTracker:g,apiClient:y});}finally{g.flushEvents(t);}let{results:B}=X;if(!B||B.length===0)return J(D({text:"Error: No steps were executed.",section:"Error"}));let K=B.at(-1);if(!K)return J(D({text:"Error: No steps were executed.",section:"Error"}));let ee={logger:t,cacheStorage:P,orgId:s,testId:I.id,environment:c,originalStepsWithCaches:L,updatedStepsWithCaches:{steps:N.steps,beforeSteps:N.beforeSteps??[],afterSteps:N.afterSteps??[]}},z=K.status!=="SUCCESS";await Pb({logger:t,cacheStorage:P,orgId:s,testId:I.id,environment:c,stepLists:ee.updatedStepsWithCaches,useSnapshotIdentityCache:e.config.fileFormat==="v2"}),z?K.status==="FAILED"&&await qv(ee):await kb(ee);let F=R==="main"?"":` in ${R}`,j=Q=>{let Ce="fromStepId"in Q?Q.fromStepId:Q.toStepId;return Q.parentStepIdChain.length>0?`id "${Ce}" (parent chain [${Q.parentStepIdChain.join(", ")}])`:`id "${Ce}"`},te=T?j(T):"beginning",Ae=v?`Steps from ${te} through ${j(v)}${F}`:`Steps from ${te} to end${F}`,Se=[];if(z)Se.push(...D({text:`Error: step with id ${K.id} failed: ${K.message}`,section:"Error"}));else {eMe({controller:r,abortSignal:A});let Q=`${Ae} executed successfully.`;Se.push(...D({text:Q,section:"Result"})),K.data&&Se.push(...D({text:`Data: ${JSON.stringify(K.data,null,2)}`,section:"Result Data"}));}let[De,at]=await Promise.all([hl({browser:r.browser,supportsFileOutput:h}),Ld({testContext:u,supportsFileOutput:h,limits:{tokenLimit:p}})]);return J([...Se,...De,...at])}function eMe({controller:e,abortSignal:t}){t?.throwIfAborted(),e.setOpen();}function lNt(e){for(let t of [e.steps,e.beforeSteps,e.afterSteps])t&&cNt(t);}function cNt(e){Ys({steps:e,earlyStop:false,onPresetAction:t=>(xi(t.command)&&delete t.command.cache,false),onSimpleStepContainer:()=>false,onConditional:()=>false});}async function uNt({logger:e,project:t,orgId:o,testId:n,environment:r,originalSteps:i,updatedSteps:a}){let s=[];try{let{alwaysSaveCache:l,noCache:c}=Cd(),u=await Rs({logger:e,orgId:o,project:t,alwaysSaveCache:l,noCache:c});await Pb({logger:e,cacheStorage:u,orgId:o,testId:n,environment:r,stepLists:a,useSnapshotIdentityCache:t.config.fileFormat==="v2"}),await kb({logger:e,cacheStorage:u,orgId:o,testId:n,environment:r,originalStepsWithCaches:i,updatedStepsWithCaches:a});}catch(l){e.warn({err:l},"Failed to save step caches after execution, future runs may be slower"),s.push(...D({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 s}var tJ=class{constructor(t,o,n,r){this.reporter=t;this.step=o;this.parentStepIdChain=n;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 VU(this.reporter,this.parentStepIdChain.concat(this.step.id),this.setTotal)}},VU=class{constructor(t,o=[],n){this.reporter=t;this.parentStepIdChain=o;this.setTotal=n;}loggerBindings;setProgressTotal(t){this.setTotal(t);}async getScreenshot(t,o){}async getHtmlSnapshot(t,o){}flushResults(t){}async startStep(t,o){return this.reporter.onStepStart(t.step),new tJ(this.reporter,t.step,this.parentStepIdChain,this.setTotal)}};function tMe(e,t,o,n,r){let i=O_(e),a={completed:0,total:0},s=new AbortController,l=false,c=p=>{i&&tIe(e,a,p,t,s,o);},u=()=>{i&&(l||(l=true,c("Starting step execution...")));},d=p=>{!Number.isFinite(p)||p<0||(a.total=p);},m={onStepStart:p=>{u(),a.total===a.completed&&(a.total+=1);let h=Fn(p);r&&(r.currentStep=h),c(`Starting: ${h}`);},onStepComplete:p=>{n(),u(),a.completed+=1,a.total<a.completed&&(a.total=a.completed);let h=Fn(p);r&&(r.currentStep=void 0,r.lastCompletedStep=h),c(`Completed: ${h}`);}};return new VU(m,[],d)}var WU=`CLI-style step definition. Use the Step Authoring Guide artifact returned from ${Eg} when you start your session to get the full step schema.`,dNt=$r({schema:{name:z8,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:sG},handle:async(e,t,o,n)=>{try{let r=await e.storage.createTest(t);Dc({type:"mcp:test_create",test_platform:"web"}),o.addPartFromText(JSON.stringify(r,null,2));}catch(r){o.addError(W(r));return}}}),mNt=$r({schema:{name:da,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 ${LT}, 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. ${ci}`,inputSchema:{testId:z.string().optional().describe(`Id of the test to fetch. If you do not already know it, list project tests with ${r$}. Either testId or testPath is required.`),testPath:z.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,o,n)=>{try{let r=t.testId?{id:t.testId}:t.testPath?{path:t.testPath}:void 0;if(!r){o.addError("Either testId or testPath is required.");return}let i=await wy({project:e.project,storage:e.storage,selector:r,envName:void 0,logger:e.logger,includeCache:!1,hydrateStepIdentity:!0,supportsFileOutput:e.supportsFileOutput});o.addContentParts(i);}catch(r){o.addError(W(r));return}}}),oMe=$r({schema:{name:jP,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 ${Ag}. Returns updated Test Content with step ids for the active session. ${ci}`,inputSchema:{sessionId:z.string().describe("The active session whose bound test should be reloaded.")}},handle:async(e,t,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:jP});if(!r)return;let i=r.storage.getProject();if(i.config.fileFormat!=="v2"){o.addError(`${jP} is only available for v2 file-format projects.`);return}let a=await r.storage.getTestByPath({relativeTestPath:r.relativeTestPath,logger:e.logger}),s={beforeSteps:a.beforeSteps,steps:a.steps,afterSteps:a.afterSteps},{alwaysSaveCache:l,noCache:c}=Cd(),u=await Rs({logger:e.logger,orgId:r.orgId,project:i,alwaysSaveCache:l,noCache:c});r.mutableStepState.testId=a.id;let{stepListsWithCaches:d}=await du({cacheStorage:u,logger:e.logger,schemaVersion:a.schemaVersion,stepLists:s,testId:a.id,environment:r.envName,useSnapshotIdentityCache:true});r.mutableStepState.stepLists=d,o.addContentParts(D({text:`Reloaded test ${a.id} from disk into session ${r.sessionId}.`,section:"Result"})),o.addContentParts(await wy({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}));}}),pNt={...oMe,addToolToMcpServer:(e,t)=>{e.project.config.fileFormat==="v2"&&oMe.addToolToMcpServer(e,t);}},hNt=$r({schema:{name:r$,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. ${u_} 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,o,n)=>{let{project:r,logger:i}=e,a=[],s=[];try{let[c,u]=await Promise.all([e.storage.listTests(),e.storage.listModules()]),d=c.map(p=>({id:p.id,name:p.name,description:p.description,testFileAbsolutePath:p.fullFilePath,labels:p.labels||[]}));a.push({title:"Tests",entity:"test-list",payload:{tests:d}});let m=u.map(p=>({id:p.id,name:p.name,description:p.description,fullFilePath:p.fullFilePath,type:p.type}));a.push({title:"Modules",entity:"module-list",payload:{modules:m}});}catch(c){s.push(`Tests and modules discovery failed: ${W(c)}`);}try{let c=e.storage.listEnvironments(i);a.push({title:"Environments",entity:"environment-list",payload:{environments:c}});}catch(c){s.push(`Environments discovery failed: ${W(c)}`);}let l=await gwe({artifacts:a,rootDir:r.rootDir,supportsFileOutput:e.supportsFileOutput,projectRootAbsolutePath:r.rootDir,projectConfigAbsolutePath:r.configFilePath,cwd:IE()});o.addContentParts(l),s.length>0&&o.addContentParts(D({section:"Discovery Errors",text:s.map(c=>`- ${c}`).join(`
3209
- `)}));}}),nMe=$r({schema:{name:wg,description:`Execute one preset, AI Action, or module step without adding it to the test. Cache IDs are optional and only returned by successful cache-capable steps. Only one preview or run may execute per session. ${ci}`,inputSchema:{sessionId:z.string(),step:z.string().describe(WU),timeoutSeconds:EB}},handle:async(e,t,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:wg});if(!r)return;let i=wB({runs:r.runStepRuns,toolName:wg,run:()=>oJ({session:r,response:o,extra:n,operation:async()=>{let a=!1;return {parts:await oO({project:r.storage.getProject(),step:t.step,logger:e.logger,storage:r.storage,controller:r.controller,codeEvaluator:r.codeEvaluator,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,supportsFileOutput:e.supportsFileOutput,tempCaches:r.tempCaches,usageTracker:r.usageTracker,apiClient:hr(),onStepResult:l=>{a=l.status==="SUCCESS";}}),isError:!a}}})});await nJ({session:r,response:o,stepRunnerId:i.stepRunnerId,timeoutSeconds:t.timeoutSeconds});}}),rMe=$r({schema:{name:s$,description:`Locate targets for multiple future preset steps against one captured browser state. Locator requests run concurrently and successful results return CacheIds that can be supplied to matching steps with --cache-id. Steps using --disable-cache are located without saving or returning a CacheId. This tool does not execute any interaction. Use it only when the planned interactions before each target are not expected to remove, replace, or materially change those future targets. If an interaction may change the relevant UI, locate that target after the interaction instead. ${ci}`,inputSchema:{sessionId:z.string(),steps:z.array(z.string().describe(WU)).min(1).max(20)}},handle:async(e,t,o,n)=>{await HS({response:o,extra:n,sessionId:t.sessionId,toolName:s$,attributes:{"momentic.element_count":t.steps.length},operation:async r=>{let i=await Xke({project:r.storage.getProject(),steps:t.steps,logger:e.logger,controller:r.controller,testContext:r.context,tempCaches:r.tempCaches});o.addContentParts(i);}});}}),iMe=$r({schema:{name:RR,description:`Execute multiple steps sequentially without adding them to the test. Supports the same preset, AI Action, and module steps as ${wg}, stopping at the first failure. Cache IDs are optional and only returned by successful cache-capable steps. Only one preview or run may execute per session. ${ci}`,inputSchema:{sessionId:z.string(),steps:z.array(z.string().describe(WU)).min(1).max(20),timeoutSeconds:EB}},handle:async(e,t,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:RR});if(!r)return;let i=wB({runs:r.runStepRuns,toolName:RR,run:()=>oJ({session:r,response:o,extra:n,operation:async()=>{let a=await Jke({project:r.storage.getProject(),steps:t.steps,logger:e.logger,storage:r.storage,controller:r.controller,codeEvaluator:r.codeEvaluator,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,supportsFileOutput:e.supportsFileOutput,tempCaches:r.tempCaches,usageTracker:r.usageTracker,apiClient:hr()});return {parts:a.parts,isError:!a.successful}}})});await nJ({session:r,response:o,stepRunnerId:i.stepRunnerId,timeoutSeconds:t.timeoutSeconds});}});async function oJ({session:e,response:t,extra:o,operation:n}){return X5({session:e,signal:o?.signal,operation:async()=>{if(ji.getSession(e.sessionId)!==e||e.cleanupInProgress)throw new Error(`Session '${e.sessionId}' is no longer active.`);e.controller.setOpen();let r=o?.signal?e.controller.bindCancellation(o.signal):void 0;r&&t.addCleanupCallback(r),o?.signal.throwIfAborted();try{return await n()}finally{r?.();}}})}async function nJ({session:e,response:t,stepRunnerId:o,timeoutSeconds:n}){let r=await d3({runs:e.runStepRuns,stepRunnerId:o,timeoutMs:n*1e3});m3({result:r,response:t,statusToolName:AR});}var aMe=$r({schema:{name:LT,description:`Insert, delete, or replace steps in the active session's test by index. Cache IDs are optional and must only be included when a preview or locate tool returned one for that exact step. Many steps do not support caches and successful previews will not return a CacheId; splice those CLI steps unchanged without --cache-id. 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. ${ci}`,inputSchema:{sessionId:z.string(),startIndex:z.number(),deleteCount:z.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.array(z.string()).describe(WU),targetSection:Up.default("main"),parentStepIdChain:z.array(z.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.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,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:LT});if(!r)return;let i=await $U({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&&Dc({type:"mcp:step_added",test_platform:"web",step_count:t.steps.length});let a=i.value.map(s=>s.type==="media"?{type:"media",data:s.data,mediaType:"image/jpeg"}:s);o.addContentParts(a);}}),sMe=$r({schema:{name:Ag,description:`${UP} Use step ids from active Test Content or splice responses, never raw v2 YAML. Only one preview or run may execute per session. ${ci}`,inputSchema:{sessionId:z.string(),fromStep:ck,toStep:uk.optional(),targetSection:Up.default("main"),resetSession:z.boolean().default(false).describe("Whether to reset the browser session before running the steps."),disableCache:z.boolean().default(false).describe("Run this invocation without reading or writing step caches."),timeoutSeconds:EB}},handle:async(e,t,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:Ag});if(!r)return;let i=wB({runs:r.runStepRuns,toolName:Ag,run:a=>oJ({session:r,response:o,extra:n,operation:()=>gNt({context:e,params:t,response:o,extra:n,session:r,stepRunnerId:a})}).then(s=>({parts:s}))});await nJ({session:r,response:o,stepRunnerId:i.stepRunnerId,timeoutSeconds:t.timeoutSeconds});}});async function gNt({context:e,params:t,response:o,extra:n,session:r,stepRunnerId:i}){t.resetSession&&await DU({project:r.storage.getProject(),logger:e.logger,relativeTestPath:r.relativeTestPath,orgId:r.orgId,storage:r.storage,controller:r.controller,testContext:r.context,codeEvaluator:r.codeEvaluator,envName:r.envName,urlOverride:r.urlOverride,testInputs:r.testInputs,supportsFileOutput:e.supportsFileOutput,isRemoteBrowser:r.isRemoteBrowser});let a=tMe(n,e.logger,o,()=>ji.touchSession(r.sessionId),gIe({runs:r.runStepRuns,stepRunnerId:i})),s=await GU({project:r.storage.getProject(),logger:e.logger,testPath:r.relativeTestPath,storage:r.storage,controller:r.controller,codeEvaluator:r.codeEvaluator,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,tracer:a,params:{fromStep:t.fromStep,toStep:t.toStep,targetSection:t.targetSection},supportsFileOutput:e.supportsFileOutput,envName:r.envName,usageTracker:r.usageTracker,mutableStepState:r.mutableStepState,apiClient:hr(),disableCache:t.disableCache});return Dc({type:"mcp:run_step_completed",test_platform:"web",status:"completed"}),s.value.map(l=>l.type==="media"?{type:"media",data:l.data,mediaType:"image/jpeg"}:l)}var lMe=$r({schema:{name:AR,description:`Check active or finished ${wg}, ${RR}, and ${Ag} executions. Pass the returned stepRunnerId to collect that operation's result. Optionally wait up to ${u3} seconds per poll. ${ci}`,inputSchema:{sessionId:z.string(),stepRunnerId:z.string().optional().describe("Scope the poll to one preview or run. Recommended for most polls."),timeoutSeconds:z.number().min(0).max(u3).default(0).describe("How long to wait for the identified preview or run. 0 responds immediately. Ignored without stepRunnerId.")}},handle:async(e,t,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:AR});if(!r)return;let i=await Q5({signal:n?.signal,operation:()=>d3({runs:r.runStepRuns,stepRunnerId:t.stepRunnerId,timeoutMs:t.timeoutSeconds*1e3})});m3({result:i,response:o,statusToolName:AR});}}),cMe=[hNt,dNt,mNt,pNt];var uMe=[Gke,Vke,qke,Kke,Yke,rMe,nMe,iMe,sMe,lMe,aMe];async function bNt({testPath:e,logger:t,project:o,storage:n,orgId:r,mutableStepState:i}){let a=await n.getTestByPath({relativeTestPath:e,logger:t}),s=a.envs?.find(d=>d.default)?.name;if(i&&i.testId!==a.id)throw new Error(`Cannot extract a module from test ${a.id} with mutable state for ${i.testId}.`);let l=i?.stepLists??{steps:a.steps,beforeSteps:a.beforeSteps??void 0,afterSteps:a.afterSteps??void 0},c=await Rs({logger:t,orgId:r,project:o}),{stepListsWithCaches:u}=await du({cacheStorage:c,logger:t,schemaVersion:a.schemaVersion,stepLists:l,testId:a.id,environment:s,useSnapshotIdentityCache:o.config.fileFormat==="v2"});return {availableSteps:u.steps,baseState:{steps:u.steps,beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]},cacheSaveContext:{testId:a.id,environment:s,stepCacheStorage:c}}}async function qU({project:e,storage:t,logger:o,relativeTestPath:n,saveChangesToDisk:r,mutableStepState:i,params:a}){let s=si();om(a.name);let l=await t.scanEntities(),c;a.startIndex!==void 0&&n!==void 0&&(c=await bNt({testPath:n,logger:o,project:e,storage:t,orgId:s,mutableStepState:i}));let{stepsToExtract:u,startIndex:d,endIndex:m}=CIe({moduleName:a.name,existingModuleNames:Object.values(l.modules).map(C=>C.name),...a,parameterNames:a.parameters,testPath:n,availableSteps:c?.availableSteps,containsNestedModuleStep:lle}),{module:p}=await t.createModule({name:a.name,description:a.description??"",enabled:a.enabled??true,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,steps:u,subDir:a.subDir,momenticFiles:l});if(a.startIndex===void 0)return {module:p};if(!n||!c)throw new Error("Failed to initialize extraction state for module create");let h=Object.keys(a.moduleInputs??{}).length>0,g=(p.parameters?.length??0)>0,f;h?f=a.moduleInputs:g?f={}:f=void 0;let y={...p,type:"RESOLVED_MODULE",id:randomUUID(),steps:p.steps,inputs:f},b=cloneDeep(c.baseState);b.steps.splice(d,m-d,y),i&&(i.stepLists=b);let{environment:S,stepCacheStorage:A,testId:T}=c.cacheSaveContext,v=e.config.fileFormat==="v2",{cachesToSave:R,snapshotCachesToSave:I}=await sr({stepLists:b,useSnapshotIdentityCache:v,cacheCreationParams:{orgId:s,testId:T,environment:S}});return v&&await A.saveSnapshotCacheEntries({logger:o,entries:I}),await A.saveStepCacheEntries({logger:o,entries:R}),r&&await t.updateTestByPath({logger:o,relativeTestPath:n,stepLists:b,schemaVersion:qt}),{module:p}}var dMe=$r({schema:{name:U8,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.string().describe(db),description:z.string(),enabled:z.boolean().default(true),parameters:z.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:z.record(z.string(),z.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:z.record(z.string(),z.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:z.record(z.string(),z.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.string().optional().describe("Subdirectory to create the module in. If not provided, the module is created in the project root."),testPath:z.string().optional().describe("Relative path to the test to extract steps from. Required when startIndex is provided."),startIndex:z.number().optional().describe("Start index of steps to extract from the target test (0-based)."),endIndex:z.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,o,n)=>{let{testPath:r,...i}=t;try{let a=ave({projectRoot:e.project.rootDir,filePath:r,pathLabel:"testPath"}),s=await qU({project:e.project,storage:e.storage,logger:e.logger,relativeTestPath:a,saveChangesToDisk:e.saveChangesToDisk,params:i});o.addPartFromText(JSON.stringify(s.module,null,2));}catch(a){o.addError(W(a));}}});var KU=[...cMe,...jU,...uMe,dMe,$we,SCe,jCe,ECe,Xwe,FCe,sCe,gCe,tRe];function YU({enableUnsafeFullAccess:e=false}={}){return e?[...KU,Wke]:KU}async function mMe(e){let{project:t,applicationName:o,daemonPort:n,daemonToken:r,daemonSessionId:i,logger:a,cliVersion:s}=e,l=t.configFilePath,c=gMe(e);await FU(e);let{context:u}=BU({...e,logger:a.child({daemonSessionId:i}),applicationName:`${o}-daemon`,serverId:i});await cIe({adapter:{getTool:d=>{let m=c.get(d);if(!m)throw new Error(`Unknown web MCP tool '${d}'. Known tools: ${Array.from(c.keys()).join(", ")}`);return {name:m.schema.name,execute:async({input:p,extra:h})=>await aIe({context:u,tool:m,input:p,extra:h})}}},sessionManager:ji,daemonPort:n,daemonToken:r,daemonId:i,cliVersion:s,workerType:"momentic-web-mcp",configPath:l,inactivityTimeoutMsOverride:Y5(e)*2,onShutdown:()=>{Lh();}});}async function rJ(e){let{project:t,logger:o,apiKey:n,serverUrl:r,cliVersion:i,alwaysSaveCache:a,noCache:s,videoDefault:l,headfulDefault:c,devicePixelRatio:u,sessionIdleTimeoutMinutes:d,shareDiagnostics:m,enableUnsafeFullAccess:p}=e,h=t.configFilePath;return eIe({workerType:"momentic-web-mcp",configPath:h,apiKey:n,serverUrl:r,cliVersion:i,shareDiagnostics:!!m,enableUnsafeFullAccess:!!p,logger:o,buildDaemonArgs:({entryScript:g})=>vNt({entryScript:g,serverUrl:r,configPath:h,alwaysSaveCache:a,noCache:s,videoDefault:l,headfulDefault:c,devicePixelRatio:u,sessionIdleTimeoutMinutes:d,shareDiagnostics:m,enableUnsafeFullAccess:p})})}async function pMe(e){let{logger:t,applicationName:o,cliVersion:n,serverUrl:r}=e,i=hMe(e);kh(r),await rJ(e);let{info:a,mcpLogger:s}=K5({logger:t,applicationName:`${o}-daemon-proxy`,cliVersion:n});return AB({context:{logger:s},info:a,tools:sIe({tools:i,resolveDaemonStateForCall:()=>rJ(e),logger:s})})}var TNt=30*6e4;async function iJ({options:e,toolName:t,input:o,timeoutMs:n=TNt}){kh(e.serverUrl);let r=gMe(e),i=r.get(t);if(!i)throw new Error(`Unknown web MCP tool '${t}'. Known tools: ${Array.from(r.keys()).join(", ")}`);let a=i.schema.inputSchema.parse(o),s=typeof a.sessionId=="string"?a.sessionId:void 0,l;if(s?l=await x_({workerType:"momentic-web-mcp",configPath:e.project.configFilePath,cliVersion:e.cliVersion,sessionId:s,logger:e.logger}):l=await rJ(e),!l)throw new Error(`No active session found for id '${s}'.`);return l3({state:l,toolName:t,input:a,timeoutMs:n})}function vNt({entryScript:e,serverUrl:t,configPath:o,alwaysSaveCache:n,noCache:r,videoDefault:i,headfulDefault:a,devicePixelRatio:s,sessionIdleTimeoutMinutes:l,shareDiagnostics:c,enableUnsafeFullAccess:u}){let d=[e,"mcp","--server",t,"--daemon","--config",o,"--headful-browser",a?"true":"false","--video",i?"true":"false"];return n&&d.push("--save-cache"),r&&d.push("--disable-cache"),d.push("--pixel-ratio",String(s)),l!==void 0&&d.push("--session-idle-timeout-minutes",String(l)),c&&d.push("--share-diagnostics"),u&&d.push("--enable-unsafe-full-access"),d}function hMe(e){return YU(e).map(t=>t.tool)}function gMe(e){return new Map(hMe(e).map(t=>[t.schema.name,t]))}var aJ=async(e,t)=>{try{let{killed:o,failed:n}=await ji.killAllSessions(e);n.length>0?t.warn({failed:n,reason:e},"Some browser sessions failed to terminate on shutdown"):o.length>0&&t.info({killedCount:o.length,reason:e},"Terminated browser sessions on shutdown");}catch(o){t.warn({err:o,reason:e},"Failed to terminate browser sessions on shutdown");}};async function sJ(e){let{daemon:t,logger:o}=e,n=ZCe.safeParse(process.env);if(t&&n.success&&n.data[TB]==="momentic-web-mcp")return mMe({...e,daemonPort:n.data[bB],daemonToken:n.data[SB],daemonSessionId:n.data[vB]});if(Xg(o,true),t)return await pMe(e);await FU(e);let{context:r,info:i}=BU(e);return AB({context:r,info:i,tools:YU(e),shutdownHandlers:[aJ,Lh,async()=>{await MU();}]})}var nO="3.62.2",Vn=Iv({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:nO});(async()=>{try{let e=await wu(Vn);e.gitBranchName&&Vn.addBinding("branch",e.gitBranchName);}catch{}})();var Iy=Router();async function XU(e,t){let o=Object.values(e.modules).filter(i=>t===void 0||t.has(i.id));return (await $V({momenticFiles:e,moduleHandles:o,logger:Vn})).filter(i=>t===void 0||t.has(i.moduleId)).map(i=>{let a=e.modules[i.moduleId];if(!a){x.warn(`Found a dangling module with ID ${i.moduleId} that could not be found on disk.`);return}return {...a,content:i}}).filter(i=>i!==void 0)}Iy.get("/",So(async(e,t)=>{let o=Xt(),n=await yc(o),r=await XU(n);t.status(200).json(r);}));Iy.post("/",So(async(e,t)=>{let o;try{o=Dte.parse(e.body);}catch(l){t.status(400).json({error:`Invalid request body: ${l}`});return}try{om(o.name);}catch(l){t.status(400).json({error:`Invalid module name: ${l}`});return}let n=Xt(),r=await yt(n),i=r.modules;if(Object.values(i).find(l=>l.name===o.name)){t.status(400).send(`A module with the name "${o.name}" already exists. Please choose a different name.`);return}let a=Cn__default.join(n.rootDir,o.folderPath??Cn__default.dirname(o.testFilePath));if(!Un__default.existsSync(a)||!Un__default.statSync(a).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let s=await TN({...o,folder:a,project:n,momenticFiles:r});t.status(201).json(s);}));Iy.get("/:moduleId/tests",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o=Xt(),n=await yt(o),r=e.params.moduleId;if(!n.modules[r]){t.status(404).json({error:"Module not found."});return}let i=[];for(let s of Object.values(n.tests))VV(s.fullFilePath,n).has(r)&&i.push({id:s.id,name:s.name,relativePath:s.relativePath});let a={tests:i};t.status(200).json(a);}));Iy.get("/:moduleId",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o=await yc(Xt()),n=o.modules[e.params.moduleId];if(!n){t.status(404).json({error:"Module not found."});return}try{let r=await Lm({modHandle:n,momenticFiles:o,logger:x});t.json(r);}catch(r){t.status(400).json({err:r});}}));Iy.post("/:moduleId/duplicate",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o;try{o=Nte.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{om(o.name);}catch(h){t.status(400).json({error:h.message});return}let n=Xt(),r=await yt(n),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===o.name)){t.status(400).send(`A module with the name "${o.name}" already exists. Please choose a different name.`);return}let a=o.sourceModuleContent;if(a.moduleId!==e.params.moduleId){t.status(400).json({error:"Duplicate source module content does not match moduleId."});return}let s=Cn__default.join(n.rootDir,Cn__default.dirname(i.relativePath));if(!Un__default.existsSync(s)||!Un__default.statSync(s).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let l=Yn(o.name),c=Cn__default.join(s,`${l}.module.yaml`),u=km({projectConfig:n.config,momenticFiles:r,entityType:"module"}),{stepsToSave:d}=await sr({stepLists:{steps:a.steps},createNewCacheIds:true}),m={fileType:ze.MODULE,schemaVersion:qt,moduleId:u,name:o.name,description:"",enabled:true,steps:d.steps,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,defaultCacheKey:a.defaultCacheKey,defaultCacheTtl:a.defaultCacheTtl,defaultCacheAllInvocations:a.defaultCacheAllInvocations,autoAuth:a.autoAuth,advanced:a.advanced,defaultRetries:a.defaultRetries};gu({module:m,filePath:c,projectConfig:n.config,momenticFiles:r});let p={relativeFilePath:Cn__default.relative(n.rootDir,c)};t.status(201).json(p);}));Iy.patch("/:moduleId/move",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o;try{o=Bte.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${W(i)}`});return}let n=Xt();if(!(await yc(n)).modules[e.params.moduleId]){t.status(404).json({error:"Module not found."});return}await lde({moduleId:e.params.moduleId,targetFolderRelativePath:o.folderPath,project:n}),t.status(200).json({message:"ok"});}));Iy.patch("/:moduleId/metadata",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o;try{o=Fte.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let n=Xt(),r=await yc(n);await cde({moduleId:e.params.moduleId,content:o,momenticFiles:r,logger:x,project:n}),t.status(201).json({message:"ok"});}));var fMe=Iy;var nw=Router();nw.get("/",So(async(e,t)=>{let o=Xt(),n=await yt(o),r=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(u=>r.add(u));});let i=Array.from(r).sort(),a=Object.values(n.tests),s=await XU(n),l={labels:i,tests:a,modules:s};t.status(200).json(l);}));nw.get("/folders",So(async(e,t)=>{let o=Xt(),n=await Kue(o);t.status(200).json(n);}));nw.get("/summary",So(async(e,t)=>{let o=Xt(),r={hasEntities:await que(o,[ze.TEST,ze.TEST_V2,ze.MODULE,ze.MODULE_V2])};t.status(200).json(r);}));nw.get("/labels",So(async(e,t)=>{let o=Xt(),n=await yt(o),r=new Set;for(let a of Object.values(n.tests))a.labels?.forEach(s=>r.add(s));let i=Array.from(r).sort();t.status(200).json(i);}));nw.post("/in-folder",So(async(e,t)=>{let o=Ote.safeParse(e.body);if(!o.success){t.status(400).json({error:`Failed to parse entities-in-folder body: ${o.error.message}`});return}let{pathSegments:n}=o.data,r=Xt(),i=await Wue(r,n),a=Object.values(i.tests),s=new Set(Object.keys(i.modules)),l=[];if(s.size>0){let u=await yc(r);l=await XU(u,s);}let c={tests:a,modules:l};t.status(200).json(c);}));var yMe=nw;var lJ=Router();lJ.get("/",So((e,t)=>{let o=IN(Xt(),Vn);t.status(200).json(o);}));lJ.get("/names",So((e,t)=>{let n=Xt().config.environments?.map(r=>r.name)??[];t.status(200).json(n);}));var bMe=lJ;var SMe=Router();SMe.get("/",So((e,t)=>{let o={userId:Xm(),orgId:si(),email:rE(),name:YTe(),pylonEmailHash:JTe(),cliVersion:nO};t.status(200).json(o);}));var TMe=SMe;var cJ="mcp-session-id",vMe="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",QU=Router();function ONt(){let e=process.env[vMe];if(!e)return zS*60*1e3;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<1?(Vn.warn({envVar:vMe,rawValue:e,fallback:zS},"Invalid MCP session idle timeout env var; falling back to default"),zS*60*1e3):t*60*1e3}function PNt(e){let{headfulDefault:t,supportsFileOutput:o}={},n={serverId:randomUUID(),applicationName:"momentic-mcp-desktop-server",cliVersion:nO},r=Xt(),i=Mh(),a=Pc(),s=Vn.child({orgId:si(),userId:Xm(),...n}),l=new so({baseUrl:a,apiKey:i,logger:s,mode:"interactive",runner:"mcp"}),c=OC(process.env.MOMENTIC_HEADFUL_BROWSER),u=new ii(r.config.ai?.agentConfig,{baseUrl:a,apiKey:i,logger:s,mode:"interactive",runner:"mcp"}),d=si(),m=new Fc(l,d,r);return {context:{project:r,orgId:d,logger:s,generator:u,apiClient:l,storage:m,serverId:n.serverId,extractBaseDir:Od(r.rootDir),saveChangesToDisk:true,supportsFileOutput:o??true,knowledgeRetrievalResults:tn,knowledgeCitations:[],sessionIdleTimeoutMs:ONt(),headfulDefault:t??c??true,categoryDefinitions:r.config.ai?.classification?.categories??Tl},info:n}}var Jh={};QU.post("/",async(e,t)=>{let o=String(e.headers[cJ]??"");try{if(o&&Jh[o]){await Jh[o].handleRequest(e,t,e.body);return}if(!o&&isInitializeRequest(e.body)){let{context:n,info:r}=PNt(),i=c3(n,r,KU),a=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{Jh[s]=a;}});a.onclose=()=>{let s=a.sessionId;s&&Jh[s]&&delete Jh[s],i.close().catch(()=>{});},await i.connect(a),await a.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});}});QU.get("/",async(e,t)=>{let o=String(e.headers[cJ]??"");if(!o||!Jh[o]){t.status(400).send("Invalid or missing session ID");return}await Jh[o].handleRequest(e,t);});QU.delete("/",async(e,t)=>{let o=String(e.headers[cJ]??"");if(!o||!Jh[o]){t.status(400).send("Invalid or missing session ID");return}let n=Jh[o];try{await n.handleRequest(e,t);}catch{t.headersSent||t.status(500).send("Error processing session termination");}});var EMe=QU;var wMe=Router();wMe.get("/:id",So(async(e,t)=>{let{id:o}=e.params;if(!o){t.status(400).json({error:"Missing ID"});return}let n=hr();if(!n){t.status(500).json({error:"API client not initialized"});return}try{let{data:r,contentType:i}=await n.fetchOnDemandScreenshot(o);t.setHeader("Content-Type",i),t.status(200).send(r);}catch(r){Vn.error({err:r,screenshotId:o},"Failed to proxy on-demand screenshot"),t.status(404).json({error:"Screenshot not found"});}}));var RMe=wMe;var uJ=Router(),CMe=e=>({name:e.config.name,configFilePath:e.configFilePath,fileFormat:e.config.fileFormat});uJ.get("/",So(async(e,t)=>{let o=Xt(),n=new Map;for(let i of await KV())n.set(i.configFilePath,i);n.set(o.configFilePath,o);let r={projects:[...n.values()].map(CMe),current:CMe(o)};t.status(200).json(r);}));uJ.post("/set",So(async(e,t)=>{let o;try{o=zte.parse(e.body);}catch(n){t.status(400).json({error:`Invalid request body: ${n}`});return}Vn.info("Setting local project");try{let n=await on({configFilePath:o.configFilePath}),r=hr();if(!r)throw new Error("API client is not initialized.");await iE({project:n,apiClient:r});}catch(n){t.status(400).json({error:`Error setting project: ${n}`});return}t.sendStatus(204);}));var IMe=uJ;var xMe=Router();xMe.get("/",So((e,t)=>{let o=Xt(),n={ai:o.config.ai,browser:o.config.browser,displayRoot:o.config.displayRoot};t.status(200).json(n);}));var _Me=xMe;var fp=Router();fp.post("/",So(async(e,t)=>{let o;try{o=Mte.parse(e.body);}catch(n){t.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Xt(),r=await tO({project:n,input:o});Dc({type:"test_editor:test_create",test_platform:"web"}),t.status(201).json(r);}catch(n){if(n instanceof yo){t.status(400).json({error:n.message});return}throw n}}));fp.get("/:testPath",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n=Xt(),r=await yc(n),i;try{i=await Nl(Cn__default.join(n.rootDir,o),Vn,r),await(await Rs({logger:Vn,orgId:si(),project:n})).resolveStepCacheEntries({schemaVersion:i.schemaVersion,testId:i.id,environment:i.envs?.find(s=>s.default)?.name,stepLists:{beforeSteps:i.beforeSteps,steps:i.steps,afterSteps:i.afterSteps},logger:Vn,useSnapshotIdentityCache:n.config.fileFormat==="v2"}),t.status(200).json(i);}catch(a){t.status(400).send({error:a.message});return}(async()=>{try{await RN({relativeTestPath:o,stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps},schemaVersion:qt,momenticFiles:r,project:n});}catch(a){Vn.error({err:a},"Failed to save migrated test to disk after initial fetch");}})();}));fp.get("/:testPath/metadata",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n=Xt(),r=Cn__default.join(n.rootDir,o);if(!Un__default.existsSync(r)){t.status(404).json({error:"Test file not found."});return}let i=Un__default.statSync(r),a=await wu(Vn),s={gitBranch:a.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:a.gitCommitSha??"unknown"};t.status(200).json(s);}));fp.patch("/:testPath/metadata",So(async(e,t)=>{if(!e.params.testPath){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=kte.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let r={message:"ok",newRelativeTestPath:jI(e.params.testPath,o,Xt()).newRelativeTestPath};t.status(200).json(r);}));fp.patch("/:testPath",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Pte.parse(e.body);}catch(p){Vn.warn({err:p},"Invalid save request"),t.status(400).json({error:`Invalid request body: ${p}`});return}Vn.info({testPath:o},"Save received");let r=Xt(),i=await yc(r),a;try{a=dd(o,r);}catch(p){t.status(400).json({error:`Existing test file on disk is invalid: ${p}`});return}let s=r.config.fileFormat==="v2",{stepsToSave:l,moduleUpdates:c,cachesToSave:u,snapshotCachesToSave:d}=await sr({stepLists:n.stepLists,useSnapshotIdentityCache:s,cacheCreationParams:{orgId:si(),testId:a.id,environment:a.envs?.find(p=>p.default)?.name}}),m=await Rs({logger:Vn,orgId:si(),project:r});s&&await m.saveSnapshotCacheEntries({logger:Vn,entries:d}),await m.saveStepCacheEntries({logger:Vn,entries:u}),await GV({relativeTestPath:o,stepsToSave:l,moduleUpdates:c,schemaVersion:n.schemaVersion,momenticFiles:i,project:r}),t.status(201).json({message:"ok"});}));fp.patch("/:testPath/environments",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=jte.parse(e.body);}catch(r){t.status(400).json({error:`Invalid request body: ${r}`});return}jI(o,{envs:n.defaultEnv?[{name:n.defaultEnv,default:true}]:[]},Xt()),t.status(201).json({message:"ok"});}));fp.patch("/:testPath/move",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Ute.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${W(i)}`});return}let r=Xt();if(!Un__default.existsSync(Cn__default.join(r.rootDir,o))){t.status(404).json({error:"Test not found."});return}await ude({relativeTestPath:o,targetFolderRelativePath:n.folderPath,project:r}),t.status(200).json({message:"ok"});}));fp.delete("/:testPath",So((e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n=Xt(),r=Cn__default.join(n.rootDir,o);if(!Un__default.existsSync(r)){t.status(404).json({error:"Test not found."});return}Un__default.unlinkSync(r),t.status(200).json({message:"ok"});}));fp.post("/:testPath/duplicate",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Lte.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{om(n.name);}catch(h){t.status(400).json({error:h.message});return}let r=Xt(),i=Cn__default.join(r.rootDir,o);if(!Un__default.existsSync(i)){t.status(404).json({error:"Test not found."});return}let a=await yt(r),s;try{s=await Nl(i,Vn,a);}catch(h){t.status(400).send({error:h.message});return}let l=km({projectConfig:r.config,momenticFiles:a,entityType:"test"}),c=Ir.parse({...s,name:n.name,id:l}),{stepsToSave:u}=await sr({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:true}),d=Cn__default.dirname(i),m=Cn__default.join(d,`${n.name}.test.yaml`);fu({test:{fileType:ze.TEST,...c,...u},filePath:m,projectConfig:r.config,momenticFiles:a});let p={relativeFilePath:Cn__default.relative(r.rootDir,m)};Dc({type:"test_editor:test_duplicated"}),t.status(201).json(p);}));var OMe=fp;var PMe=15e4,gl={numScreenshots:10,numBrowserStates:2,tokensThreshold:25e4,targetTokens:2e5};function yp(){return {openai:{reasoningEffort:I$,reasoningSummary:"auto",textVerbosity:"low",store:false,include:["reasoning.encrypted_content"]},azure:{reasoningEffort:I$,reasoningSummary:"auto",textVerbosity:"low",store:false,include:["reasoning.encrypted_content"]}}}var FNt="about:blank",BNt=[".webm",".mp4"];function pJ(e){return e?Un__default.mkdtempSync(Cn__default.join(Jp.tmpdir(),"momentic-explore-video-")):void 0}async function Dd(e){let{sessionManager:t,storage:o,logger:n,owner:r,signal:i,timelineLane:a}=e,s=pJ(a),l=new rB(n),c=await t.startTestlessSession({logger:n,storage:o,baseUrl:FNt,runner:"explore",disableConsoleLogs:true,callbacks:{onNetworkPage:l.onNetworkPage,onNetworkLogs:l.onNetworkLogs},videoOutputDir:s}).catch(m=>{throw l.close(),m}),u=c.controller.bindCancellation(i),d=async m=>{if(u(),!t.getSession(c.sessionId)){await l.finalize(),l.remove();return}!(await t.killSession(c.sessionId,`${r} browser session completed`)).killed&&t.getSession(c.sessionId)!==void 0&&m.warn({sessionId:c.sessionId,owner:r},"Explore agent did not clean up its browser session"),await l.finalize(),await hJ({logger:m,timelineLane:a,videoOutputDir:s,videoStartTimes:c.videoStartTimes,videoActivations:c.videoActivations,finishedAt:Date.now()}),await UNt({logger:m,timelineLane:a,entriesFilePath:l.entriesFilePath}),l.remove();};return {context:{controller:c.controller,testContext:c.context,codeEvaluator:c.codeEvaluator,tempCaches:c.tempCaches,usageTracker:c.usageTracker,relativeTestPath:c.relativeTestPath,envName:c.envName,isRemoteBrowser:c.isRemoteBrowser,conversationTokenTarget:PMe,networkLogEntriesPath:()=>l.entriesFilePath,cleanupBrowserSession:d},isAlive:()=>t.getSession(c.sessionId)!==void 0}}async function hJ({logger:e,timelineLane:t,videoOutputDir:o,videoStartTimes:n,videoActivations:r,finishedAt:i}){if(!(!t||!o))try{for(let a of await Un__default.promises.readdir(o)){if(!BNt.includes(Cn__default.extname(a)))continue;let s=r?.filter(l=>l.videoName===a).map(l=>l.timestamp).sort((l,c)=>l-c);await t.attachVideo({sourcePath:Cn__default.join(o,a),startedAt:n?.get(a),finishedAt:i,activations:s?.length?s:void 0});}}catch(a){e.warn({err:a,videoOutputDir:o},"Failed to attach explore browser videos to timeline");}}async function UNt({logger:e,timelineLane:t,entriesFilePath:o}){if(t)try{if((await Un__default.promises.stat(o)).size===0)return;await t.attachNetworkLog({sourcePath:o});}catch(n){e.warn({err:n,entriesFilePath:o},"Failed to attach explore network log to timeline");}}var zNt=2/3;function kMe(e,t){return t===void 0?{signal:e}:{signal:AbortSignal.any([e,AbortSignal.timeout(t)]),buildTimeoutMs:Math.floor(t*zNt)}}function iw(e,t){if(!e?.aborted)return W(t);let o=e.reason;return o instanceof Error&&o.name==="TimeoutError"?"AI explore exceeded its --timeout budget before completing":"AI explore was cancelled before completing"}function MMe(e){let t=e.filter(o=>o!==void 0);return t.length===0?void 0:AbortSignal.any(t)}async function Xh(e,t){try{await iY.rm(e,{recursive:!0,force:!0});}catch(o){t.warn({err:o,spoolDir:e},"Failed to clean up explorer spool dir");}}async function fJ(e){return await HNt(e),await $Nt(e),await GNt(e)}async function HNt(e){try{await simpleGit(e).version();}catch(t){throw new Error(`git is not available on PATH. Install git to use 'momentic ai explore' (${W(t)}).`,{cause:t})}}async function $Nt(e){let t;try{t=await simpleGit(e).checkIsRepo();}catch(o){throw new Error(`Failed to determine whether ${e} is a git repository: ${W(o)}`,{cause:o})}if(!t)throw new Error(`${e} is not inside a git repository. Run 'momentic ai explore' from inside a git repository.`)}async function GNt(e){let t=simpleGit(e);try{let o=(await t.revparse(["--show-toplevel"])).trim();if(o.length===0)throw new Error("git rev-parse --show-toplevel returned an empty path.");return o}catch(o){throw new Error(`Failed to resolve git repository toplevel from ${e}: ${W(o)}`,{cause:o})}}z.object({testIds:z.array(z.string().min(1)).optional().describe("Stable test ids for pending in-memory test creates or updates. Omit, or pass an empty list together with moduleIds, to target every pending test."),moduleIds:z.array(z.string().min(1)).optional().describe("Stable module ids for pending in-memory module creates or updates. Omit, or pass an empty list together with testIds, to target every pending module.")});var Qh=class extends Fc{overlay;diskProject;writtenFilePaths=new Set;constructor(t,o,n){let r=new hN(Lt);super(t,o,n,r),this.overlay=r,this.diskProject=n;}hasPendingDrafts(){return this.overlay.hasPendingChanges()}listWrittenFilePaths(){return [...this.writtenFilePaths]}async listDraftTests(t){return this.collectDraftTests(t)}async listDraftModules(t){return this.collectDraftModules(t)}async acceptDrafts(t,o){let n=ZU(await this.collectDraftTests(t),o.testIds,u=>u.test.id,"test"),r=ZU(await this.collectDraftModules(t),o.moduleIds,u=>u.module.moduleId,"module");if(n.length===0&&r.length===0)return {acceptedTests:[],acceptedModules:[]};let i=await yt(this.diskProject,true);this.assertModuleRefsSatisfied(n,r,i);let a=[];try{for(let u of [...r,...n])this.overlay.materialize(u.entity.fullFilePath),u.kind==="create"&&a.push(u.entity.fullFilePath);}catch(u){for(let d of a)VNt(d);throw new Error("Failed to persist pending changes to disk",{cause:u})}let s=[];for(let u of [...r,...n])this.overlay.discard(u.entity.fullFilePath),u.kind!=="delete"&&(this.writtenFilePaths.add(u.entity.fullFilePath),s.push(u.entity.fullFilePath));gA(s,this.diskProject.config);let l=r.map(u=>({moduleId:u.module.moduleId,relativeFilePath:u.entity.relativePath}));return {acceptedTests:n.map(u=>({testId:u.test.id,relativeFilePath:u.entity.relativePath})),acceptedModules:l}}async rejectDrafts(t,o){let n=await this.collectDraftTests(t),r=ZU(n,o.testIds,u=>u.test.id,"test"),i=ZU(await this.collectDraftModules(t),o.moduleIds,u=>u.module.moduleId,"module"),a=new Set(r.map(u=>u.test.id)),s=[];for(let u of i){let d=u.module.moduleId,m=[];for(let p of n)a.has(p.test.id)||p.kind!=="delete"&&LMe(p.test).has(d)&&m.push(p.test.name);m.length!==0&&s.push(`Cannot reject module "${d}" because it is still referenced by pending test(s) ${m.map(p=>`"${p}"`).join(", ")}.`);}if(s.length>0)throw new yo(s.join(`
3209
+ `)}));}}),nMe=$r({schema:{name:wg,description:`Execute one preset, AI Action, or module step without adding it to the test. Cache IDs are optional and only returned by successful cache-capable steps. Only one preview or run may execute per session. ${ci}`,inputSchema:{sessionId:z.string(),step:z.string().describe(WU),timeoutSeconds:EB}},handle:async(e,t,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:wg});if(!r)return;let i=wB({runs:r.runStepRuns,toolName:wg,run:()=>oJ({session:r,response:o,extra:n,operation:async()=>{let a=!1;return {parts:await oO({project:r.storage.getProject(),step:t.step,logger:e.logger,storage:r.storage,controller:r.controller,codeEvaluator:r.codeEvaluator,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,supportsFileOutput:e.supportsFileOutput,tempCaches:r.tempCaches,usageTracker:r.usageTracker,apiClient:hr(),onStepResult:l=>{a=l.status==="SUCCESS";}}),isError:!a}}})});await nJ({session:r,response:o,stepRunnerId:i.stepRunnerId,timeoutSeconds:t.timeoutSeconds});}}),rMe=$r({schema:{name:s$,description:`Locate targets for multiple future preset steps against one captured browser state. Locator requests run concurrently and successful results return CacheIds that can be supplied to matching steps with --cache-id. Steps using --disable-cache are located without saving or returning a CacheId. This tool does not execute any interaction. Use it only when the planned interactions before each target are not expected to remove, replace, or materially change those future targets. If an interaction may change the relevant UI, locate that target after the interaction instead. ${ci}`,inputSchema:{sessionId:z.string(),steps:z.array(z.string().describe(WU)).min(1).max(20)}},handle:async(e,t,o,n)=>{await HS({response:o,extra:n,sessionId:t.sessionId,toolName:s$,attributes:{"momentic.element_count":t.steps.length},operation:async r=>{let i=await Xke({project:r.storage.getProject(),steps:t.steps,logger:e.logger,controller:r.controller,testContext:r.context,tempCaches:r.tempCaches});o.addContentParts(i);}});}}),iMe=$r({schema:{name:RR,description:`Execute multiple steps sequentially without adding them to the test. Supports the same preset, AI Action, and module steps as ${wg}, stopping at the first failure. Cache IDs are optional and only returned by successful cache-capable steps. Only one preview or run may execute per session. ${ci}`,inputSchema:{sessionId:z.string(),steps:z.array(z.string().describe(WU)).min(1).max(20),timeoutSeconds:EB}},handle:async(e,t,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:RR});if(!r)return;let i=wB({runs:r.runStepRuns,toolName:RR,run:()=>oJ({session:r,response:o,extra:n,operation:async()=>{let a=await Jke({project:r.storage.getProject(),steps:t.steps,logger:e.logger,storage:r.storage,controller:r.controller,codeEvaluator:r.codeEvaluator,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,supportsFileOutput:e.supportsFileOutput,tempCaches:r.tempCaches,usageTracker:r.usageTracker,apiClient:hr()});return {parts:a.parts,isError:!a.successful}}})});await nJ({session:r,response:o,stepRunnerId:i.stepRunnerId,timeoutSeconds:t.timeoutSeconds});}});async function oJ({session:e,response:t,extra:o,operation:n}){return X5({session:e,signal:o?.signal,operation:async()=>{if(ji.getSession(e.sessionId)!==e||e.cleanupInProgress)throw new Error(`Session '${e.sessionId}' is no longer active.`);e.controller.setOpen();let r=o?.signal?e.controller.bindCancellation(o.signal):void 0;r&&t.addCleanupCallback(r),o?.signal.throwIfAborted();try{return await n()}finally{r?.();}}})}async function nJ({session:e,response:t,stepRunnerId:o,timeoutSeconds:n}){let r=await d3({runs:e.runStepRuns,stepRunnerId:o,timeoutMs:n*1e3});m3({result:r,response:t,statusToolName:AR});}var aMe=$r({schema:{name:LT,description:`Insert, delete, or replace steps in the active session's test by index. Cache IDs are optional and must only be included when a preview or locate tool returned one for that exact step. Many steps do not support caches and successful previews will not return a CacheId; splice those CLI steps unchanged without --cache-id. 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. ${ci}`,inputSchema:{sessionId:z.string(),startIndex:z.number(),deleteCount:z.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.array(z.string()).describe(WU),targetSection:Up.default("main"),parentStepIdChain:z.array(z.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.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,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:LT});if(!r)return;let i=await $U({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&&Dc({type:"mcp:step_added",test_platform:"web",step_count:t.steps.length});let a=i.value.map(s=>s.type==="media"?{type:"media",data:s.data,mediaType:"image/jpeg"}:s);o.addContentParts(a);}}),sMe=$r({schema:{name:Ag,description:`${UP} Use step ids from active Test Content or splice responses, never raw v2 YAML. Only one preview or run may execute per session. ${ci}`,inputSchema:{sessionId:z.string(),fromStep:ck,toStep:uk.optional(),targetSection:Up.default("main"),resetSession:z.boolean().default(false).describe("Whether to reset the browser session before running the steps."),disableCache:z.boolean().default(false).describe("Run this invocation without reading or writing step caches."),timeoutSeconds:EB}},handle:async(e,t,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:Ag});if(!r)return;let i=wB({runs:r.runStepRuns,toolName:Ag,run:a=>oJ({session:r,response:o,extra:n,operation:()=>gNt({context:e,params:t,response:o,extra:n,session:r,stepRunnerId:a})}).then(s=>({parts:s}))});await nJ({session:r,response:o,stepRunnerId:i.stepRunnerId,timeoutSeconds:t.timeoutSeconds});}});async function gNt({context:e,params:t,response:o,extra:n,session:r,stepRunnerId:i}){t.resetSession&&await DU({project:r.storage.getProject(),logger:e.logger,relativeTestPath:r.relativeTestPath,orgId:r.orgId,storage:r.storage,controller:r.controller,testContext:r.context,codeEvaluator:r.codeEvaluator,envName:r.envName,urlOverride:r.urlOverride,testInputs:r.testInputs,supportsFileOutput:e.supportsFileOutput,isRemoteBrowser:r.isRemoteBrowser});let a=tMe(n,e.logger,o,()=>ji.touchSession(r.sessionId),gIe({runs:r.runStepRuns,stepRunnerId:i})),s=await GU({project:r.storage.getProject(),logger:e.logger,testPath:r.relativeTestPath,storage:r.storage,controller:r.controller,codeEvaluator:r.codeEvaluator,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,tracer:a,params:{fromStep:t.fromStep,toStep:t.toStep,targetSection:t.targetSection},supportsFileOutput:e.supportsFileOutput,envName:r.envName,usageTracker:r.usageTracker,mutableStepState:r.mutableStepState,apiClient:hr(),disableCache:t.disableCache});return Dc({type:"mcp:run_step_completed",test_platform:"web",status:"completed"}),s.value.map(l=>l.type==="media"?{type:"media",data:l.data,mediaType:"image/jpeg"}:l)}var lMe=$r({schema:{name:AR,description:`Check active or finished ${wg}, ${RR}, and ${Ag} executions. Pass the returned stepRunnerId to collect that operation's result. Optionally wait up to ${u3} seconds per poll. ${ci}`,inputSchema:{sessionId:z.string(),stepRunnerId:z.string().optional().describe("Scope the poll to one preview or run. Recommended for most polls."),timeoutSeconds:z.number().min(0).max(u3).default(0).describe("How long to wait for the identified preview or run. 0 responds immediately. Ignored without stepRunnerId.")}},handle:async(e,t,o,n)=>{let r=Nd({response:o,sessionId:t.sessionId,toolName:AR});if(!r)return;let i=await Q5({signal:n?.signal,operation:()=>d3({runs:r.runStepRuns,stepRunnerId:t.stepRunnerId,timeoutMs:t.timeoutSeconds*1e3})});m3({result:i,response:o,statusToolName:AR});}}),cMe=[hNt,dNt,mNt,pNt];var uMe=[Gke,Vke,qke,Kke,Yke,rMe,nMe,iMe,sMe,lMe,aMe];async function bNt({testPath:e,logger:t,project:o,storage:n,orgId:r,mutableStepState:i}){let a=await n.getTestByPath({relativeTestPath:e,logger:t}),s=a.envs?.find(d=>d.default)?.name;if(i&&i.testId!==a.id)throw new Error(`Cannot extract a module from test ${a.id} with mutable state for ${i.testId}.`);let l=i?.stepLists??{steps:a.steps,beforeSteps:a.beforeSteps??void 0,afterSteps:a.afterSteps??void 0},c=await Rs({logger:t,orgId:r,project:o}),{stepListsWithCaches:u}=await du({cacheStorage:c,logger:t,schemaVersion:a.schemaVersion,stepLists:l,testId:a.id,environment:s,useSnapshotIdentityCache:o.config.fileFormat==="v2"});return {availableSteps:u.steps,baseState:{steps:u.steps,beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]},cacheSaveContext:{testId:a.id,environment:s,stepCacheStorage:c}}}async function qU({project:e,storage:t,logger:o,relativeTestPath:n,saveChangesToDisk:r,mutableStepState:i,params:a}){let s=si();om(a.name);let l=await t.scanEntities(),c;a.startIndex!==void 0&&n!==void 0&&(c=await bNt({testPath:n,logger:o,project:e,storage:t,orgId:s,mutableStepState:i}));let{stepsToExtract:u,startIndex:d,endIndex:m}=CIe({moduleName:a.name,existingModuleNames:Object.values(l.modules).map(C=>C.name),...a,parameterNames:a.parameters,testPath:n,availableSteps:c?.availableSteps,containsNestedModuleStep:lle}),{module:p}=await t.createModule({name:a.name,description:a.description??"",enabled:a.enabled??true,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,steps:u,subDir:a.subDir,momenticFiles:l});if(a.startIndex===void 0)return {module:p};if(!n||!c)throw new Error("Failed to initialize extraction state for module create");let h=Object.keys(a.moduleInputs??{}).length>0,g=(p.parameters?.length??0)>0,f;h?f=a.moduleInputs:g?f={}:f=void 0;let y={...p,type:"RESOLVED_MODULE",id:randomUUID(),steps:p.steps,inputs:f},b=cloneDeep(c.baseState);b.steps.splice(d,m-d,y),i&&(i.stepLists=b);let{environment:S,stepCacheStorage:A,testId:T}=c.cacheSaveContext,v=e.config.fileFormat==="v2",{cachesToSave:R,snapshotCachesToSave:I}=await sr({stepLists:b,useSnapshotIdentityCache:v,cacheCreationParams:{orgId:s,testId:T,environment:S}});return v&&await A.saveSnapshotCacheEntries({logger:o,entries:I}),await A.saveStepCacheEntries({logger:o,entries:R}),r&&await t.updateTestByPath({logger:o,relativeTestPath:n,stepLists:b,schemaVersion:qt}),{module:p}}var dMe=$r({schema:{name:U8,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.string().describe(db),description:z.string(),enabled:z.boolean().default(true),parameters:z.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:z.record(z.string(),z.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:z.record(z.string(),z.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:z.record(z.string(),z.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.string().optional().describe("Subdirectory to create the module in. If not provided, the module is created in the project root."),testPath:z.string().optional().describe("Relative path to the test to extract steps from. Required when startIndex is provided."),startIndex:z.number().optional().describe("Start index of steps to extract from the target test (0-based)."),endIndex:z.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,o,n)=>{let{testPath:r,...i}=t;try{let a=ave({projectRoot:e.project.rootDir,filePath:r,pathLabel:"testPath"}),s=await qU({project:e.project,storage:e.storage,logger:e.logger,relativeTestPath:a,saveChangesToDisk:e.saveChangesToDisk,params:i});o.addPartFromText(JSON.stringify(s.module,null,2));}catch(a){o.addError(W(a));}}});var KU=[...cMe,...jU,...uMe,dMe,$we,SCe,jCe,ECe,Xwe,FCe,sCe,gCe,tRe];function YU({enableUnsafeFullAccess:e=false}={}){return e?[...KU,Wke]:KU}async function mMe(e){let{project:t,applicationName:o,daemonPort:n,daemonToken:r,daemonSessionId:i,logger:a,cliVersion:s}=e,l=t.configFilePath,c=gMe(e);await FU(e);let{context:u}=BU({...e,logger:a.child({daemonSessionId:i}),applicationName:`${o}-daemon`,serverId:i});await cIe({adapter:{getTool:d=>{let m=c.get(d);if(!m)throw new Error(`Unknown web MCP tool '${d}'. Known tools: ${Array.from(c.keys()).join(", ")}`);return {name:m.schema.name,execute:async({input:p,extra:h})=>await aIe({context:u,tool:m,input:p,extra:h})}}},sessionManager:ji,daemonPort:n,daemonToken:r,daemonId:i,cliVersion:s,workerType:"momentic-web-mcp",configPath:l,inactivityTimeoutMsOverride:Y5(e)*2,onShutdown:()=>{Lh();}});}async function rJ(e){let{project:t,logger:o,apiKey:n,serverUrl:r,cliVersion:i,alwaysSaveCache:a,noCache:s,videoDefault:l,headfulDefault:c,devicePixelRatio:u,sessionIdleTimeoutMinutes:d,shareDiagnostics:m,enableUnsafeFullAccess:p}=e,h=t.configFilePath;return eIe({workerType:"momentic-web-mcp",configPath:h,apiKey:n,serverUrl:r,cliVersion:i,shareDiagnostics:!!m,enableUnsafeFullAccess:!!p,logger:o,buildDaemonArgs:({entryScript:g})=>vNt({entryScript:g,serverUrl:r,configPath:h,alwaysSaveCache:a,noCache:s,videoDefault:l,headfulDefault:c,devicePixelRatio:u,sessionIdleTimeoutMinutes:d,shareDiagnostics:m,enableUnsafeFullAccess:p})})}async function pMe(e){let{logger:t,applicationName:o,cliVersion:n,serverUrl:r}=e,i=hMe(e);kh(r),await rJ(e);let{info:a,mcpLogger:s}=K5({logger:t,applicationName:`${o}-daemon-proxy`,cliVersion:n});return AB({context:{logger:s},info:a,tools:sIe({tools:i,resolveDaemonStateForCall:()=>rJ(e),logger:s})})}var TNt=30*6e4;async function iJ({options:e,toolName:t,input:o,timeoutMs:n=TNt}){kh(e.serverUrl);let r=gMe(e),i=r.get(t);if(!i)throw new Error(`Unknown web MCP tool '${t}'. Known tools: ${Array.from(r.keys()).join(", ")}`);let a=i.schema.inputSchema.parse(o),s=typeof a.sessionId=="string"?a.sessionId:void 0,l;if(s?l=await x_({workerType:"momentic-web-mcp",configPath:e.project.configFilePath,cliVersion:e.cliVersion,sessionId:s,logger:e.logger}):l=await rJ(e),!l)throw new Error(`No active session found for id '${s}'.`);return l3({state:l,toolName:t,input:a,timeoutMs:n})}function vNt({entryScript:e,serverUrl:t,configPath:o,alwaysSaveCache:n,noCache:r,videoDefault:i,headfulDefault:a,devicePixelRatio:s,sessionIdleTimeoutMinutes:l,shareDiagnostics:c,enableUnsafeFullAccess:u}){let d=[e,"mcp","--server",t,"--daemon","--config",o,"--headful-browser",a?"true":"false","--video",i?"true":"false"];return n&&d.push("--save-cache"),r&&d.push("--disable-cache"),d.push("--pixel-ratio",String(s)),l!==void 0&&d.push("--session-idle-timeout-minutes",String(l)),c&&d.push("--share-diagnostics"),u&&d.push("--enable-unsafe-full-access"),d}function hMe(e){return YU(e).map(t=>t.tool)}function gMe(e){return new Map(hMe(e).map(t=>[t.schema.name,t]))}var aJ=async(e,t)=>{try{let{killed:o,failed:n}=await ji.killAllSessions(e);n.length>0?t.warn({failed:n,reason:e},"Some browser sessions failed to terminate on shutdown"):o.length>0&&t.info({killedCount:o.length,reason:e},"Terminated browser sessions on shutdown");}catch(o){t.warn({err:o,reason:e},"Failed to terminate browser sessions on shutdown");}};async function sJ(e){let{daemon:t,logger:o}=e,n=ZCe.safeParse(process.env);if(t&&n.success&&n.data[TB]==="momentic-web-mcp")return mMe({...e,daemonPort:n.data[bB],daemonToken:n.data[SB],daemonSessionId:n.data[vB]});if(Xg(o,true),t)return await pMe(e);await FU(e);let{context:r,info:i}=BU(e);return AB({context:r,info:i,tools:YU(e),shutdownHandlers:[aJ,Lh,async()=>{await MU();}]})}var nO="3.62.3",Vn=Iv({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:nO});(async()=>{try{let e=await wu(Vn);e.gitBranchName&&Vn.addBinding("branch",e.gitBranchName);}catch{}})();var Iy=Router();async function XU(e,t){let o=Object.values(e.modules).filter(i=>t===void 0||t.has(i.id));return (await $V({momenticFiles:e,moduleHandles:o,logger:Vn})).filter(i=>t===void 0||t.has(i.moduleId)).map(i=>{let a=e.modules[i.moduleId];if(!a){x.warn(`Found a dangling module with ID ${i.moduleId} that could not be found on disk.`);return}return {...a,content:i}}).filter(i=>i!==void 0)}Iy.get("/",So(async(e,t)=>{let o=Xt(),n=await yc(o),r=await XU(n);t.status(200).json(r);}));Iy.post("/",So(async(e,t)=>{let o;try{o=Dte.parse(e.body);}catch(l){t.status(400).json({error:`Invalid request body: ${l}`});return}try{om(o.name);}catch(l){t.status(400).json({error:`Invalid module name: ${l}`});return}let n=Xt(),r=await yt(n),i=r.modules;if(Object.values(i).find(l=>l.name===o.name)){t.status(400).send(`A module with the name "${o.name}" already exists. Please choose a different name.`);return}let a=Cn__default.join(n.rootDir,o.folderPath??Cn__default.dirname(o.testFilePath));if(!Un__default.existsSync(a)||!Un__default.statSync(a).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let s=await TN({...o,folder:a,project:n,momenticFiles:r});t.status(201).json(s);}));Iy.get("/:moduleId/tests",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o=Xt(),n=await yt(o),r=e.params.moduleId;if(!n.modules[r]){t.status(404).json({error:"Module not found."});return}let i=[];for(let s of Object.values(n.tests))VV(s.fullFilePath,n).has(r)&&i.push({id:s.id,name:s.name,relativePath:s.relativePath});let a={tests:i};t.status(200).json(a);}));Iy.get("/:moduleId",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o=await yc(Xt()),n=o.modules[e.params.moduleId];if(!n){t.status(404).json({error:"Module not found."});return}try{let r=await Lm({modHandle:n,momenticFiles:o,logger:x});t.json(r);}catch(r){t.status(400).json({err:r});}}));Iy.post("/:moduleId/duplicate",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o;try{o=Nte.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{om(o.name);}catch(h){t.status(400).json({error:h.message});return}let n=Xt(),r=await yt(n),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===o.name)){t.status(400).send(`A module with the name "${o.name}" already exists. Please choose a different name.`);return}let a=o.sourceModuleContent;if(a.moduleId!==e.params.moduleId){t.status(400).json({error:"Duplicate source module content does not match moduleId."});return}let s=Cn__default.join(n.rootDir,Cn__default.dirname(i.relativePath));if(!Un__default.existsSync(s)||!Un__default.statSync(s).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let l=Yn(o.name),c=Cn__default.join(s,`${l}.module.yaml`),u=km({projectConfig:n.config,momenticFiles:r,entityType:"module"}),{stepsToSave:d}=await sr({stepLists:{steps:a.steps},createNewCacheIds:true}),m={fileType:ze.MODULE,schemaVersion:qt,moduleId:u,name:o.name,description:"",enabled:true,steps:d.steps,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,defaultCacheKey:a.defaultCacheKey,defaultCacheTtl:a.defaultCacheTtl,defaultCacheAllInvocations:a.defaultCacheAllInvocations,autoAuth:a.autoAuth,advanced:a.advanced,defaultRetries:a.defaultRetries};gu({module:m,filePath:c,projectConfig:n.config,momenticFiles:r});let p={relativeFilePath:Cn__default.relative(n.rootDir,c)};t.status(201).json(p);}));Iy.patch("/:moduleId/move",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o;try{o=Bte.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${W(i)}`});return}let n=Xt();if(!(await yc(n)).modules[e.params.moduleId]){t.status(404).json({error:"Module not found."});return}await lde({moduleId:e.params.moduleId,targetFolderRelativePath:o.folderPath,project:n}),t.status(200).json({message:"ok"});}));Iy.patch("/:moduleId/metadata",So(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let o;try{o=Fte.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let n=Xt(),r=await yc(n);await cde({moduleId:e.params.moduleId,content:o,momenticFiles:r,logger:x,project:n}),t.status(201).json({message:"ok"});}));var fMe=Iy;var nw=Router();nw.get("/",So(async(e,t)=>{let o=Xt(),n=await yt(o),r=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(u=>r.add(u));});let i=Array.from(r).sort(),a=Object.values(n.tests),s=await XU(n),l={labels:i,tests:a,modules:s};t.status(200).json(l);}));nw.get("/folders",So(async(e,t)=>{let o=Xt(),n=await Kue(o);t.status(200).json(n);}));nw.get("/summary",So(async(e,t)=>{let o=Xt(),r={hasEntities:await que(o,[ze.TEST,ze.TEST_V2,ze.MODULE,ze.MODULE_V2])};t.status(200).json(r);}));nw.get("/labels",So(async(e,t)=>{let o=Xt(),n=await yt(o),r=new Set;for(let a of Object.values(n.tests))a.labels?.forEach(s=>r.add(s));let i=Array.from(r).sort();t.status(200).json(i);}));nw.post("/in-folder",So(async(e,t)=>{let o=Ote.safeParse(e.body);if(!o.success){t.status(400).json({error:`Failed to parse entities-in-folder body: ${o.error.message}`});return}let{pathSegments:n}=o.data,r=Xt(),i=await Wue(r,n),a=Object.values(i.tests),s=new Set(Object.keys(i.modules)),l=[];if(s.size>0){let u=await yc(r);l=await XU(u,s);}let c={tests:a,modules:l};t.status(200).json(c);}));var yMe=nw;var lJ=Router();lJ.get("/",So((e,t)=>{let o=IN(Xt(),Vn);t.status(200).json(o);}));lJ.get("/names",So((e,t)=>{let n=Xt().config.environments?.map(r=>r.name)??[];t.status(200).json(n);}));var bMe=lJ;var SMe=Router();SMe.get("/",So((e,t)=>{let o={userId:Xm(),orgId:si(),email:rE(),name:YTe(),pylonEmailHash:JTe(),cliVersion:nO};t.status(200).json(o);}));var TMe=SMe;var cJ="mcp-session-id",vMe="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",QU=Router();function ONt(){let e=process.env[vMe];if(!e)return zS*60*1e3;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<1?(Vn.warn({envVar:vMe,rawValue:e,fallback:zS},"Invalid MCP session idle timeout env var; falling back to default"),zS*60*1e3):t*60*1e3}function PNt(e){let{headfulDefault:t,supportsFileOutput:o}={},n={serverId:randomUUID(),applicationName:"momentic-mcp-desktop-server",cliVersion:nO},r=Xt(),i=Mh(),a=Pc(),s=Vn.child({orgId:si(),userId:Xm(),...n}),l=new so({baseUrl:a,apiKey:i,logger:s,mode:"interactive",runner:"mcp"}),c=OC(process.env.MOMENTIC_HEADFUL_BROWSER),u=new ii(r.config.ai?.agentConfig,{baseUrl:a,apiKey:i,logger:s,mode:"interactive",runner:"mcp"}),d=si(),m=new Fc(l,d,r);return {context:{project:r,orgId:d,logger:s,generator:u,apiClient:l,storage:m,serverId:n.serverId,extractBaseDir:Od(r.rootDir),saveChangesToDisk:true,supportsFileOutput:o??true,knowledgeRetrievalResults:tn,knowledgeCitations:[],sessionIdleTimeoutMs:ONt(),headfulDefault:t??c??true,categoryDefinitions:r.config.ai?.classification?.categories??Tl},info:n}}var Jh={};QU.post("/",async(e,t)=>{let o=String(e.headers[cJ]??"");try{if(o&&Jh[o]){await Jh[o].handleRequest(e,t,e.body);return}if(!o&&isInitializeRequest(e.body)){let{context:n,info:r}=PNt(),i=c3(n,r,KU),a=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{Jh[s]=a;}});a.onclose=()=>{let s=a.sessionId;s&&Jh[s]&&delete Jh[s],i.close().catch(()=>{});},await i.connect(a),await a.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});}});QU.get("/",async(e,t)=>{let o=String(e.headers[cJ]??"");if(!o||!Jh[o]){t.status(400).send("Invalid or missing session ID");return}await Jh[o].handleRequest(e,t);});QU.delete("/",async(e,t)=>{let o=String(e.headers[cJ]??"");if(!o||!Jh[o]){t.status(400).send("Invalid or missing session ID");return}let n=Jh[o];try{await n.handleRequest(e,t);}catch{t.headersSent||t.status(500).send("Error processing session termination");}});var EMe=QU;var wMe=Router();wMe.get("/:id",So(async(e,t)=>{let{id:o}=e.params;if(!o){t.status(400).json({error:"Missing ID"});return}let n=hr();if(!n){t.status(500).json({error:"API client not initialized"});return}try{let{data:r,contentType:i}=await n.fetchOnDemandScreenshot(o);t.setHeader("Content-Type",i),t.status(200).send(r);}catch(r){Vn.error({err:r,screenshotId:o},"Failed to proxy on-demand screenshot"),t.status(404).json({error:"Screenshot not found"});}}));var RMe=wMe;var uJ=Router(),CMe=e=>({name:e.config.name,configFilePath:e.configFilePath,fileFormat:e.config.fileFormat});uJ.get("/",So(async(e,t)=>{let o=Xt(),n=new Map;for(let i of await KV())n.set(i.configFilePath,i);n.set(o.configFilePath,o);let r={projects:[...n.values()].map(CMe),current:CMe(o)};t.status(200).json(r);}));uJ.post("/set",So(async(e,t)=>{let o;try{o=zte.parse(e.body);}catch(n){t.status(400).json({error:`Invalid request body: ${n}`});return}Vn.info("Setting local project");try{let n=await on({configFilePath:o.configFilePath}),r=hr();if(!r)throw new Error("API client is not initialized.");await iE({project:n,apiClient:r});}catch(n){t.status(400).json({error:`Error setting project: ${n}`});return}t.sendStatus(204);}));var IMe=uJ;var xMe=Router();xMe.get("/",So((e,t)=>{let o=Xt(),n={ai:o.config.ai,browser:o.config.browser,displayRoot:o.config.displayRoot};t.status(200).json(n);}));var _Me=xMe;var fp=Router();fp.post("/",So(async(e,t)=>{let o;try{o=Mte.parse(e.body);}catch(n){t.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Xt(),r=await tO({project:n,input:o});Dc({type:"test_editor:test_create",test_platform:"web"}),t.status(201).json(r);}catch(n){if(n instanceof yo){t.status(400).json({error:n.message});return}throw n}}));fp.get("/:testPath",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n=Xt(),r=await yc(n),i;try{i=await Nl(Cn__default.join(n.rootDir,o),Vn,r),await(await Rs({logger:Vn,orgId:si(),project:n})).resolveStepCacheEntries({schemaVersion:i.schemaVersion,testId:i.id,environment:i.envs?.find(s=>s.default)?.name,stepLists:{beforeSteps:i.beforeSteps,steps:i.steps,afterSteps:i.afterSteps},logger:Vn,useSnapshotIdentityCache:n.config.fileFormat==="v2"}),t.status(200).json(i);}catch(a){t.status(400).send({error:a.message});return}(async()=>{try{await RN({relativeTestPath:o,stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps},schemaVersion:qt,momenticFiles:r,project:n});}catch(a){Vn.error({err:a},"Failed to save migrated test to disk after initial fetch");}})();}));fp.get("/:testPath/metadata",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n=Xt(),r=Cn__default.join(n.rootDir,o);if(!Un__default.existsSync(r)){t.status(404).json({error:"Test file not found."});return}let i=Un__default.statSync(r),a=await wu(Vn),s={gitBranch:a.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:a.gitCommitSha??"unknown"};t.status(200).json(s);}));fp.patch("/:testPath/metadata",So(async(e,t)=>{if(!e.params.testPath){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=kte.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let r={message:"ok",newRelativeTestPath:jI(e.params.testPath,o,Xt()).newRelativeTestPath};t.status(200).json(r);}));fp.patch("/:testPath",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Pte.parse(e.body);}catch(p){Vn.warn({err:p},"Invalid save request"),t.status(400).json({error:`Invalid request body: ${p}`});return}Vn.info({testPath:o},"Save received");let r=Xt(),i=await yc(r),a;try{a=dd(o,r);}catch(p){t.status(400).json({error:`Existing test file on disk is invalid: ${p}`});return}let s=r.config.fileFormat==="v2",{stepsToSave:l,moduleUpdates:c,cachesToSave:u,snapshotCachesToSave:d}=await sr({stepLists:n.stepLists,useSnapshotIdentityCache:s,cacheCreationParams:{orgId:si(),testId:a.id,environment:a.envs?.find(p=>p.default)?.name}}),m=await Rs({logger:Vn,orgId:si(),project:r});s&&await m.saveSnapshotCacheEntries({logger:Vn,entries:d}),await m.saveStepCacheEntries({logger:Vn,entries:u}),await GV({relativeTestPath:o,stepsToSave:l,moduleUpdates:c,schemaVersion:n.schemaVersion,momenticFiles:i,project:r}),t.status(201).json({message:"ok"});}));fp.patch("/:testPath/environments",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=jte.parse(e.body);}catch(r){t.status(400).json({error:`Invalid request body: ${r}`});return}jI(o,{envs:n.defaultEnv?[{name:n.defaultEnv,default:true}]:[]},Xt()),t.status(201).json({message:"ok"});}));fp.patch("/:testPath/move",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Ute.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${W(i)}`});return}let r=Xt();if(!Un__default.existsSync(Cn__default.join(r.rootDir,o))){t.status(404).json({error:"Test not found."});return}await ude({relativeTestPath:o,targetFolderRelativePath:n.folderPath,project:r}),t.status(200).json({message:"ok"});}));fp.delete("/:testPath",So((e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n=Xt(),r=Cn__default.join(n.rootDir,o);if(!Un__default.existsSync(r)){t.status(404).json({error:"Test not found."});return}Un__default.unlinkSync(r),t.status(200).json({message:"ok"});}));fp.post("/:testPath/duplicate",So(async(e,t)=>{let{testPath:o}=e.params;if(!o){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Lte.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{om(n.name);}catch(h){t.status(400).json({error:h.message});return}let r=Xt(),i=Cn__default.join(r.rootDir,o);if(!Un__default.existsSync(i)){t.status(404).json({error:"Test not found."});return}let a=await yt(r),s;try{s=await Nl(i,Vn,a);}catch(h){t.status(400).send({error:h.message});return}let l=km({projectConfig:r.config,momenticFiles:a,entityType:"test"}),c=Ir.parse({...s,name:n.name,id:l}),{stepsToSave:u}=await sr({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:true}),d=Cn__default.dirname(i),m=Cn__default.join(d,`${n.name}.test.yaml`);fu({test:{fileType:ze.TEST,...c,...u},filePath:m,projectConfig:r.config,momenticFiles:a});let p={relativeFilePath:Cn__default.relative(r.rootDir,m)};Dc({type:"test_editor:test_duplicated"}),t.status(201).json(p);}));var OMe=fp;var PMe=15e4,gl={numScreenshots:10,numBrowserStates:2,tokensThreshold:25e4,targetTokens:2e5};function yp(){return {openai:{reasoningEffort:I$,reasoningSummary:"auto",textVerbosity:"low",store:false,include:["reasoning.encrypted_content"]},azure:{reasoningEffort:I$,reasoningSummary:"auto",textVerbosity:"low",store:false,include:["reasoning.encrypted_content"]}}}var FNt="about:blank",BNt=[".webm",".mp4"];function pJ(e){return e?Un__default.mkdtempSync(Cn__default.join(Jp.tmpdir(),"momentic-explore-video-")):void 0}async function Dd(e){let{sessionManager:t,storage:o,logger:n,owner:r,signal:i,timelineLane:a}=e,s=pJ(a),l=new rB(n),c=await t.startTestlessSession({logger:n,storage:o,baseUrl:FNt,runner:"explore",disableConsoleLogs:true,callbacks:{onNetworkPage:l.onNetworkPage,onNetworkLogs:l.onNetworkLogs},videoOutputDir:s}).catch(m=>{throw l.close(),m}),u=c.controller.bindCancellation(i),d=async m=>{if(u(),!t.getSession(c.sessionId)){await l.finalize(),l.remove();return}!(await t.killSession(c.sessionId,`${r} browser session completed`)).killed&&t.getSession(c.sessionId)!==void 0&&m.warn({sessionId:c.sessionId,owner:r},"Explore agent did not clean up its browser session"),await l.finalize(),await hJ({logger:m,timelineLane:a,videoOutputDir:s,videoStartTimes:c.videoStartTimes,videoActivations:c.videoActivations,finishedAt:Date.now()}),await UNt({logger:m,timelineLane:a,entriesFilePath:l.entriesFilePath}),l.remove();};return {context:{controller:c.controller,testContext:c.context,codeEvaluator:c.codeEvaluator,tempCaches:c.tempCaches,usageTracker:c.usageTracker,relativeTestPath:c.relativeTestPath,envName:c.envName,isRemoteBrowser:c.isRemoteBrowser,conversationTokenTarget:PMe,networkLogEntriesPath:()=>l.entriesFilePath,cleanupBrowserSession:d},isAlive:()=>t.getSession(c.sessionId)!==void 0}}async function hJ({logger:e,timelineLane:t,videoOutputDir:o,videoStartTimes:n,videoActivations:r,finishedAt:i}){if(!(!t||!o))try{for(let a of await Un__default.promises.readdir(o)){if(!BNt.includes(Cn__default.extname(a)))continue;let s=r?.filter(l=>l.videoName===a).map(l=>l.timestamp).sort((l,c)=>l-c);await t.attachVideo({sourcePath:Cn__default.join(o,a),startedAt:n?.get(a),finishedAt:i,activations:s?.length?s:void 0});}}catch(a){e.warn({err:a,videoOutputDir:o},"Failed to attach explore browser videos to timeline");}}async function UNt({logger:e,timelineLane:t,entriesFilePath:o}){if(t)try{if((await Un__default.promises.stat(o)).size===0)return;await t.attachNetworkLog({sourcePath:o});}catch(n){e.warn({err:n,entriesFilePath:o},"Failed to attach explore network log to timeline");}}var zNt=2/3;function kMe(e,t){return t===void 0?{signal:e}:{signal:AbortSignal.any([e,AbortSignal.timeout(t)]),buildTimeoutMs:Math.floor(t*zNt)}}function iw(e,t){if(!e?.aborted)return W(t);let o=e.reason;return o instanceof Error&&o.name==="TimeoutError"?"AI explore exceeded its --timeout budget before completing":"AI explore was cancelled before completing"}function MMe(e){let t=e.filter(o=>o!==void 0);return t.length===0?void 0:AbortSignal.any(t)}async function Xh(e,t){try{await iY.rm(e,{recursive:!0,force:!0});}catch(o){t.warn({err:o,spoolDir:e},"Failed to clean up explorer spool dir");}}async function fJ(e){return await HNt(e),await $Nt(e),await GNt(e)}async function HNt(e){try{await simpleGit(e).version();}catch(t){throw new Error(`git is not available on PATH. Install git to use 'momentic ai explore' (${W(t)}).`,{cause:t})}}async function $Nt(e){let t;try{t=await simpleGit(e).checkIsRepo();}catch(o){throw new Error(`Failed to determine whether ${e} is a git repository: ${W(o)}`,{cause:o})}if(!t)throw new Error(`${e} is not inside a git repository. Run 'momentic ai explore' from inside a git repository.`)}async function GNt(e){let t=simpleGit(e);try{let o=(await t.revparse(["--show-toplevel"])).trim();if(o.length===0)throw new Error("git rev-parse --show-toplevel returned an empty path.");return o}catch(o){throw new Error(`Failed to resolve git repository toplevel from ${e}: ${W(o)}`,{cause:o})}}z.object({testIds:z.array(z.string().min(1)).optional().describe("Stable test ids for pending in-memory test creates or updates. Omit, or pass an empty list together with moduleIds, to target every pending test."),moduleIds:z.array(z.string().min(1)).optional().describe("Stable module ids for pending in-memory module creates or updates. Omit, or pass an empty list together with testIds, to target every pending module.")});var Qh=class extends Fc{overlay;diskProject;writtenFilePaths=new Set;constructor(t,o,n){let r=new hN(Lt);super(t,o,n,r),this.overlay=r,this.diskProject=n;}hasPendingDrafts(){return this.overlay.hasPendingChanges()}listWrittenFilePaths(){return [...this.writtenFilePaths]}async listDraftTests(t){return this.collectDraftTests(t)}async listDraftModules(t){return this.collectDraftModules(t)}async acceptDrafts(t,o){let n=ZU(await this.collectDraftTests(t),o.testIds,u=>u.test.id,"test"),r=ZU(await this.collectDraftModules(t),o.moduleIds,u=>u.module.moduleId,"module");if(n.length===0&&r.length===0)return {acceptedTests:[],acceptedModules:[]};let i=await yt(this.diskProject,true);this.assertModuleRefsSatisfied(n,r,i);let a=[];try{for(let u of [...r,...n])this.overlay.materialize(u.entity.fullFilePath),u.kind==="create"&&a.push(u.entity.fullFilePath);}catch(u){for(let d of a)VNt(d);throw new Error("Failed to persist pending changes to disk",{cause:u})}let s=[];for(let u of [...r,...n])this.overlay.discard(u.entity.fullFilePath),u.kind!=="delete"&&(this.writtenFilePaths.add(u.entity.fullFilePath),s.push(u.entity.fullFilePath));gA(s,this.diskProject.config);let l=r.map(u=>({moduleId:u.module.moduleId,relativeFilePath:u.entity.relativePath}));return {acceptedTests:n.map(u=>({testId:u.test.id,relativeFilePath:u.entity.relativePath})),acceptedModules:l}}async rejectDrafts(t,o){let n=await this.collectDraftTests(t),r=ZU(n,o.testIds,u=>u.test.id,"test"),i=ZU(await this.collectDraftModules(t),o.moduleIds,u=>u.module.moduleId,"module"),a=new Set(r.map(u=>u.test.id)),s=[];for(let u of i){let d=u.module.moduleId,m=[];for(let p of n)a.has(p.test.id)||p.kind!=="delete"&&LMe(p.test).has(d)&&m.push(p.test.name);m.length!==0&&s.push(`Cannot reject module "${d}" because it is still referenced by pending test(s) ${m.map(p=>`"${p}"`).join(", ")}.`);}if(s.length>0)throw new yo(s.join(`
3210
3210
  `));for(let u of [...r,...i])this.overlay.discard(u.entity.fullFilePath);let l=r.map(u=>({testId:u.test.id,name:u.test.name})),c=i.map(u=>({moduleId:u.module.moduleId,name:u.module.name}));return {rejectedTests:l,rejectedModules:c}}async collectDraftTests(t){let o=await this.scanEntities({disableLogging:true}),n=[];for(let r of Object.values(o.tests)){if(!this.overlay.hasPendingWrite(r.fullFilePath))continue;let i=await Nl(r.fullFilePath,t,o,this.overlay);n.push({entity:r,test:i,kind:this.overlay.isCreate(r.fullFilePath)?"create":"update"});}return n.push(...(await this.collectDeletedEntities(t)).tests),n}async collectDraftModules(t){let o=await this.scanEntities({disableLogging:true}),n=[];for(let r of Object.values(o.modules)){if(!this.overlay.hasPendingWrite(r.fullFilePath))continue;let i=await Lm({modHandle:r,momenticFiles:o,logger:t,fileSystem:this.overlay});n.push({entity:r,module:i,kind:this.overlay.isCreate(r.fullFilePath)?"create":"update"});}return n.push(...(await this.collectDeletedEntities(t)).modules),n}async collectDeletedEntities(t){let o=this.overlay.tombstonePaths();if(o.length===0)return {tests:[],modules:[]};let n=new Set(o.map(s=>Cn__default.resolve(s))),r=await yt(this.diskProject,true),i=[];for(let s of Object.values(r.tests)){if(!n.has(Cn__default.resolve(s.fullFilePath)))continue;let l=await Nl(s.fullFilePath,t,r,Lt);i.push({entity:s,test:l,kind:"delete"});}let a=[];for(let s of Object.values(r.modules)){if(!n.has(Cn__default.resolve(s.fullFilePath)))continue;let l=await Lm({modHandle:s,momenticFiles:r,logger:t,fileSystem:Lt});a.push({entity:s,module:l,kind:"delete"});}return {tests:i,modules:a}}assertModuleRefsSatisfied(t,o,n){let r=new Set(Object.keys(n.modules)),i=new Set(o.filter(l=>l.kind==="delete").map(l=>l.module.moduleId)),a=new Set(o.filter(l=>l.kind!=="delete").map(l=>l.module.moduleId)),s=[];for(let l of t)if(l.kind!=="delete")for(let c of LMe(l.test)){if(i.has(c)){s.push(`Cannot accept test "${l.test.name}" (${l.test.id}) because it references module "${c}" which is being deleted in the same call.`);continue}r.has(c)||a.has(c)||s.push(`Cannot accept test "${l.test.name}" (${l.test.id}) because it references pending module "${c}". Accept that module in the same call or reject the test first.`);}if(s.length>0)throw new yo(s.join(`
3211
3211
  `))}};function ZU(e,t,o,n){return !t||t.length===0?e:t.flatMap(r=>{let i=e.filter(a=>o(a)===r);if(i.length===0)throw new yo(`No pending draft ${n} with id "${r}".`);return i})}function LMe(e){let t=new Set;return Ys({steps:[...e.beforeSteps??[],...e.steps??[],...e.afterSteps??[]],onPresetAction:()=>{},onConditional:()=>{},onSimpleStepContainer:o=>{o.type==="RESOLVED_MODULE"&&t.add(o.moduleId);}}),t}function VNt(e){try{Lt.unlinkSync(e);}catch{}}var qNt=["**/pnpm-lock.yaml","**/yarn.lock","**/package-lock.json","**/Cargo.lock","**/Gemfile.lock","**/poetry.lock","**/uv.lock","**/go.sum","**/composer.lock"],KNt=["**/__generated__/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/out/**","**/coverage/**","**/*.snap"],YNt=["**/*.{test,spec}.{ts,tsx,js,jsx,mjs,cjs,py,go,rs,rb,java,kt}","**/__tests__/**","**/test/**","**/tests/**","**/e2e/**","**/cypress/**","**/playwright/**"],JNt=["**/*.md","**/*.mdx","**/*.rst","**/docs/**","**/README*","**/CHANGELOG*","**/LICENSE*"],XNt=["**/*.json","**/*.yaml","**/*.yml","**/*.toml","**/*.ini","**/*.env*","**/*.config.{ts,js,mjs,cjs}","**/.eslintrc*","**/.prettierrc*","**/.editorconfig","**/tsconfig*.json","**/Dockerfile*","**/Makefile","**/.gitignore","**/.dockerignore"],QNt=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".swift",".cs",".rb",".php",".cpp",".cc",".c",".h",".hpp",".scala",".clj",".ex",".exs",".vue",".svelte",".html",".css",".scss",".sass",".less",".sql",".graphql",".gql",".sh",".bash",".zsh"];function iO(e){return CDe([...e],{dot:true})}var ZNt=iO(qNt),eDt=iO(KNt),tDt=iO(YNt),oDt=iO(JNt),nDt=iO(XNt);function NMe(e,t){if(ZNt(e))return "lockfile";if(eDt(e))return "generated";if(t===true)return "binary";if(tDt(e))return "test";if(oDt(e))return "docs";if(nDt(e))return "config";let o=e.toLowerCase();for(let n of QNt)if(o.endsWith(n))return "code";return "other"}var iDt={minCombinedScore:.05,maxResults:8,maxTokens:2e3},DMe={minCombinedScore:.05,maxResults:5,maxTokens:1500},aDt=5,sDt=12;async function FMe({client:e,manifest:t,customPrompt:o,logger:n,abortSignal:r}){let i=lDt({manifest:t,customPrompt:o});if(!i)return tn;try{return await ye(uu({client:e,query:i,config:iDt,logger:n,clientName:"explorer",agentSubtype:"explorer",abortSignal:r}),{milliseconds:Ml})}catch(a){if(r.aborted)throw a;return n.warn({err:a},"Knowledge retrieval failed during explorer setup"),tn}}function lDt({manifest:e,customPrompt:t}){let o=[],n=t?.trim();n&&o.push(`User guidance: ${n}`);let r=e.commits.map(a=>a.subject.trim()).filter(a=>a.length>0).slice(0,aDt);if(r.length>0){o.push("Commit subjects:");for(let a of r)o.push(`- ${a}`);}let i=cDt(e.files);if(i.length>0){o.push("Changed UI-relevant files:");for(let a of i)o.push(`- ${a.path}`);}if(o.length!==0)return o.join(`
3212
3212
  `)}function cDt(e){return e.filter(o=>uDt(o.category)).sort((o,n)=>n.insertions+n.deletions-(o.insertions+o.deletions)||o.path.localeCompare(n.path)).slice(0,sDt)}function uDt(e){switch(e){case "code":case "config":case "docs":return true;case "test":case "lockfile":case "generated":case "binary":case "other":return false}}var dDt=FT.filter(e=>e!=="CONDITIONAL"),BMe=Kt`
@@ -4654,7 +4654,7 @@ ${a.length===0?"(none)":m}
4654
4654
  `);}var Bd="/v1/app-graph",ky=class{constructor(t,o){this.apiClient=t;this.logger=o;}async reportBillableEvents(t,o){await this.apiClient.reportBillableEvents(t,o);}async claim(t){let o=await this.apiClient.sendRequest(`${Bd}/ai-select/claim`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return tZ.parse(o)}async getPlan(t){let o=new URLSearchParams({repository:t.repository,headSha:t.headSha}),n=await this.apiClient.sendRequest(`${Bd}/ai-select/plan?${o.toString()}`,{method:"GET",retries:1,requestTimeoutMs:1e4});return nZ.parse(n)}async finalize(t){let o=await this.apiClient.sendRequest(`${Bd}/ai-select/finalize`,{method:"POST",body:t,retries:2,requestTimeoutMs:3e4});return oZ.parse(o)}async release(t){await this.apiClient.sendRequest(`${Bd}/ai-select/release`,{method:"POST",body:{selectionPlanKey:t},retries:1,requestTimeoutMs:5e3}).catch(o=>{this.logger.warn({err:o,selectionPlanKey:t},"Failed to release ai-select lock");});}async searchObservedTests(t,o){let n=await this.apiClient.sendRequest(`${Bd}/ai-select/search/observed-tests`,{signal:o,method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return V$.parse(n)}async searchSegments(t,o){let n=await this.apiClient.sendRequest(`${Bd}/ai-select/search/segments`,{signal:o,method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return V$.parse(n)}async getObservedTest(t,o){let n=await this.apiClient.sendRequest(`${Bd}/ai-select/observed-tests/${encodeURIComponent(t)}`,{signal:o,method:"GET",retries:2,requestTimeoutMs:1e4});return rZ.parse(n)}async getSegment(t,o){let n=await this.apiClient.sendRequest(`${Bd}/ai-select/segments/${encodeURIComponent(t)}`,{signal:o,method:"GET",retries:2,requestTimeoutMs:1e4});return iZ.parse(n)}async listObservedTestsForSegment(t,o){let n=await this.apiClient.sendRequest(`${Bd}/ai-select/segments/${encodeURIComponent(t)}/observed-tests`,{signal:o,method:"GET",retries:2,requestTimeoutMs:1e4});return aZ.parse(n)}async getCodeInsights(t,o){let n=await this.apiClient.sendRequest(`${Bd}/ai-select/code-insights`,{signal:o,method:"POST",body:{repository:t.repository,folderPaths:t.folderPaths},retries:1,requestTimeoutMs:1e4});return sZ.parse(n).insights}async createCodeInsight(t,o){let n=await this.apiClient.sendRequest(`${Bd}/ai-select/code-insight`,{signal:o,method:"POST",body:t,retries:1,requestTimeoutMs:15e3});return lZ.parse(n)}},IO=class extends ky{billingReporter;constructor({billingReporter:t,logger:o}){let n={sendRequest:async()=>({})};super(n,o),this.billingReporter=t;}async reportBillableEvents(t,o){await this.billingReporter.reportBillableEvents(t,o);}async searchObservedTests(t){return {results:[]}}async searchSegments(t){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(t){return {observedTests:[]}}async getCodeInsights(){return []}async createCodeInsight(){return {id:"noop"}}},pHt=2e3,b0e=12e4;async function S0e(e){let t=Date.now()+(e.timeoutMs??b0e),o=0;for(;;){o+=1;let n=await e.client.claim(e.claim);if(n.status==="claimed")return {kind:"claimed",selectionPlanKey:n.selectionPlanKey,trackId:n.trackId};if(n.status==="ready")return {kind:"ready",plan:n.plan,planId:n.planId};if(Date.now()>=t)throw new Error(`ai-select: timed out waiting for plan after ${e.timeoutMs??b0e}ms`);e.logger.info({attempt:o,claimedBy:n.claimedBy},"ai-select plan computing on another shard; polling"),await Pt(n.retryAfterMs??pHt);}}async function gHt(e){try{return await Py({repoRoot:e.repoRoot,explicitBase:"HEAD~1",logger:e.logger})}catch{return n6({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:null,logger:e.logger})}}async function T0e({params:e,reason:t}){let o=e.config?.onBaseUnavailable??"use-head";switch(o){case "fail":throw new ng(`AI selection base unavailable and ai.select.onBaseUnavailable is "fail": ${t}`);case "run-all":return {diff:null,reason:t};case "use-head":{let n=await gHt(e);return n?{diff:n,reason:t}:{diff:null,reason:`Could not assemble diff against the HEAD commit's parent: ${t}`}}default:return mt(o)}}async function x6(e){return ge({name:"ai_select.resolve_plan",root:true,attributes:{"momentic.repository":e.repository},fn:()=>fHt(e)})}async function fHt(e){let t=new ky(e.apiClient,e.logger),o=e.agentOutputStream?rt(e.agentOutputStream):rt();e.agentOutputStream&&e.agentOutputStream.write(`
4655
4655
  `);let n;try{n=await ge({name:"ai_select.assemble_diff",attributes:{"momentic.explicit_base":e.explicitBase??"auto"},fn:()=>Ho({text:"Analyzing code changes...",screen:o},()=>Py({repoRoot:e.repoRoot,explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch,logger:e.logger}))});}catch(m){let p=m instanceof ng?m.message:`Could not assemble diff against base ref: ${W(m)}.`,h=dDe({explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch}),g=h?await n6({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:h,logger:e.logger}):null;if(g)n=g;else {let f=await T0e({params:e,reason:p});if(f.diff===null)return {kind:"run-all",reason:f.reason,diff:null};n=f.diff;}}if(n.baseSha===n.headSha){let m=`Base ref "${n.baseRef}" resolves to HEAD (${n.headSha}); applying ai.select.onBaseUnavailable fallback behavior.`,p=await T0e({params:e,reason:m});if(p.diff===null)return {kind:"run-all",reason:p.reason,diff:null};n=p.diff;}if(e.logger.info({changedFiles:n.changedFiles.length},"Diff assembled"),n.changedFiles.length===0)return {kind:"run-none",reason:"No source-code changes detected between base and head.",diff:n};let r=createHash("sha256").update(e.candidateTests.map(m=>m.testPath).sort().join(`
4656
4656
  `)).digest("hex").slice(0,12),i=await Dj({client:e.apiClient,query:Nj({...e,diff:n}),environmentName:e.environmentName,logger:e.logger}),a=yHt({headSha:n.headSha,suiteHash:r,customPrompt:e.customPrompt,changeRequestDescription:e.changeRequestDescription,budgetCap:e.budgetCap,knowledgeBaseRules:i}),s=n.repoRoot,l=Cn__default.relative(s,e.repoRoot),c=l?e.candidateTests.map(m=>({...m,testPath:Cn__default.posix.join(l.split(Cn__default.sep).join("/"),m.testPath)})):e.candidateTests;if(e.dryRun){let m=await ww({apiClient:t,remoteGitClient:e.apiClient,knowledgeBaseRules:i,generator:e.generator,logger:e.logger,orgId:e.orgId,repository:e.repository,repoRoot:s,projectRoot:e.repoRoot,diff:n,candidateTests:c,allTestDefinitions:e.allTestDefinitions,importIndexCachePath:YS(s),agentOutputStream:e.agentOutputStream,budgetCap:e.budgetCap,customPrompt:e.customPrompt,changeRequestDescription:e.changeRequestDescription});return m.fallbackToRunAll?{kind:"run-all",reason:m.userSummary,diff:n}:{kind:"ready",plan:{version:2,userSummary:m.userSummary,toolCallCount:m.toolCallCount,selectedTests:m.selectedTests,anchorSegmentIds:m.anchorSegmentIds,budget:{source:e.budgetSource,cap:e.budgetCap??null},generatedAt:new Date().toISOString()},planId:`dry-run-${a}`,mode:"SELECTED",diff:n}}let u=await S0e({client:t,claim:{repository:e.repository,headSha:a,baseRef:n.baseRef,changedFiles:n.changedFiles.map(m=>m.path),diffSummary:null,budgetCap:e.budgetCap,dryRun:e.dryRun},logger:e.logger});if(u.kind==="ready"){e.logger.info({planId:u.planId,planSize:u.plan.selectedTests.length,suiteHash:r},"ai-select: reusing cached plan from server");let m=e.logger.bindings().sessionId??randomUUID();return await vh({reporter:e.apiClient,logger:e.logger,feature:"select",cached:true,result:"success",sessionId:m,agentInvocationId:m,transactionId:`ai-agent-invocation:select:${m}`}),{kind:"ready",plan:u.plan,planId:u.planId,mode:"SELECTED",diff:n}}let d=await ww({apiClient:t,remoteGitClient:e.apiClient,knowledgeBaseRules:i,generator:e.generator,logger:e.logger,orgId:e.orgId,repository:e.repository,repoRoot:s,projectRoot:e.repoRoot,diff:n,candidateTests:c,allTestDefinitions:e.allTestDefinitions,importIndexCachePath:YS(s),agentOutputStream:e.agentOutputStream,budgetCap:e.budgetCap,customPrompt:e.customPrompt,changeRequestDescription:e.changeRequestDescription});if(d.fallbackToRunAll)return await t.release(u.selectionPlanKey),{kind:"run-all",reason:d.userSummary,diff:n};try{e.logger.info({selectedCount:d.selectedTests.length,durationMs:d.totalDurationMs,suiteHash:r},"ai-select: computed fresh plan");let m=await t.finalize({selectionPlanKey:u.selectionPlanKey,repository:e.repository,headSha:a,mode:"SELECTED",userSummary:d.userSummary,toolCallCount:d.toolCallCount,selectedTests:d.selectedTests,anchorSegmentIds:d.anchorSegmentIds,budget:{source:e.budgetSource,cap:e.budgetCap}});return {kind:"ready",plan:m.plan,planId:m.planId,mode:"SELECTED",diff:n}}catch(m){return e.logger.error({err:m},"ai-select finalize failed; falling back to run-all"),await t.release(u.selectionPlanKey),{kind:"run-all",reason:`Could not record selection plan: ${W(m)}.`,diff:n}}}function yHt({headSha:e,suiteHash:t,customPrompt:o,changeRequestDescription:n,budgetCap:r,knowledgeBaseRules:i}){let a=[`${e}:${t}`];if(o!==void 0){let s=createHash("sha256").update(o).digest("hex").slice(0,12);a.push(`prompt-${s}`);}if(n!==void 0&&n.trim().length>0){let s=createHash("sha256").update(n).digest("hex").slice(0,12);a.push(`description-${s}`);}return r!==null&&a.push(`budget-${r}`),i&&a.push(`kb-${createHash("sha256").update(i).digest("hex").slice(0,12)}`),a.join(":")}async function A0e({test:e,fragment:t,entities:o,client:n,logger:r,yes:i}){gt(t.schemaVersion,qt)&&(x.error(`Patch schema version (${t.schemaVersion}) is newer than this CLI supports. Update to the latest CLI and retry.`),Je(He.Failure)),mle(t.steps).forEach(f=>{o.modules[f]||(x.error(`Patch references module ${f} which is not in this project. The patch or your local files may be out of date.`),Je(He.Failure));}),t.createdAt.getTime()<Date.now()-7*mv&&!i&&!await ki("The test patch you are applying is more than 7 days old. Are you sure you want to continue?")&&Je(He.Failure);let s=e.lastModified.getTime();t.createdAt.getTime()+60*60*1e3<s&&!i&&!await ki("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?")&&Je(He.Failure);let l=lh(e.fullFilePath),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${e.fullFilePath} is missing steps array`);let u,d;if(t.schemaVersion!==qt){let{steps:f,newVersion:y}=await hc({metadata:{id:t.id,schemaVersion:t.schemaVersion},steps:t.steps,logger:x});u=y,d=Uo.array().parse(f);}else d=Uo.array().parse(t.steps);let{stepsToSave:m}=await sr({stepLists:{steps:d}});m.beforeSteps=l.beforeSteps??void 0,m.afterSteps=l.afterSteps??void 0;let p=Rb(tl.stringify(c),tl.stringify(m),{n_surrounding:5}),h=rt(),g=ht(h);x.info(""),x.info(g.bold("Patch preview")),x.info(""),x.info(g.code(e.relativePath));for(let f of S0(p,g))x.info(` ${f}`);x.info(""),u&&x.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${u}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await ki("Do you want to apply this patch?")&&(x.dimmed("Cancelled."),Je(He.Failure)),Bb({relativeTestPath:e.relativePath,steps:m,schemaVersion:u??t.schemaVersion,project:o.project,momenticFiles:o}),x.success("Patch applied."),await n.patchTestFragment(t.id,{applied:true,appliedAt:new Date});}function vHt(e){switch(e){case "SUCCESS":return "passed";case "CANCELLED":return "skipped";case "FAILED":case "IDLE":case "RUNNING":return "failed";default:return mt(e)}}function AHt(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 mt(e)}}async function EHt(e){let{step:t,logger:o,debugDataStorage:n,folder:r,beforeSnapshot:i,afterSnapshot:a}=e,s=await Hj({logger:o,debugDataStorage:n,folder:r,label:"before",snapshotId:i});s&&t.attachments.push({name:"Screenshot before step",source:s,type:"image/jpeg"});let l=await Hj({logger:o,debugDataStorage:n,folder:r,label:"after",snapshotId:a});l&&t.attachments.push({name:"Screenshot after step",source:l,type:"image/jpeg"});}function wHt(e,t,o){let n=z.union([z.looseObject({}),z.array(z.unknown().optional())]).safeParse(o).success,r=`output-attachment-${randomUUID()}.json`;Un__default.writeFileSync(Cn__default.join(t,r),JSON.stringify(o,null,2)),e.attachments.push({name:"Step output data",source:r,type:n?"application/json":"text/plain"});}function RHt(e){let{step:t,folder:o,beforeTestContext:n,afterTestContext:r}=e;if(n){let i=`before-context-${randomUUID()}.json`;writeFileSync(Cn__default.join(o,i),w0e(n.env)),t.attachments.push({name:"Test context before step",source:i,type:"application/json"});}if(r){let i=`after-context-${randomUUID()}.json`;writeFileSync(Cn__default.join(o,i),w0e(r.env)),t.attachments.push({name:"Test context after step",source:i,type:"application/json"});}}function R0e(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 Hj(e){let{logger:t,debugDataStorage:o,folder:n,label:r,snapshotId:i}=e;if(!i)return;let a=await o.getScreenshot(t,i);if(!a)return;let s=`screenshot-${r}-${i}.jpeg`;return Un__default.writeFileSync(Cn__default.join(n,s),a),s}async function CHt(e,t,o,n){let r=o.folder,i={uuid:n.runAttemptId??randomUUID(),historyId:n.runId??randomUUID(),testCaseId:n.test.id,fullName:n.test.name,name:Yn(n.test.name),status:AHt(n.status),start:n.lastAttemptStartedAt.getTime(),stop:n.finishedAt.getTime(),parameters:[],labels:R0e({suiteName:o.suiteName,attempts:n.attempts,runId:n.runId,quarantined:n.quarantined,quarantinedReason:n.quarantinedMetadata?.quarantinedReason,quarantinedAt:n.quarantinedMetadata?.quarantinedAt}),steps:[]};for(let[l,c]of Object.entries(n.parameters))c!=null&&i.parameters.push({name:l,value:JSON.stringify(c)});n.results&&await _6(e,t,o.folder,i.steps,n.results);let a=xHt(t,r,n.runAttemptId);a.length>0&&(i.attachments=a);let s=`${n.runAttemptId}-result.json`;Un__default.writeFileSync(Cn__default.join(r,s),JSON.stringify(i,void 0,2));}async function zj(e,t,o,n){let r={name:Fn(n),start:n.startedAt.getTime(),stop:n.finishedAt.getTime(),status:vHt(n.status),labels:[],steps:[],attachments:[]};if(n.beforeUrl&&r.labels.push({name:"URL before step",value:n.beforeUrl}),n.afterUrl&&r.labels.push({name:"URL after step",value:n.afterUrl}),await EHt({step:r,logger:e,debugDataStorage:t,folder:o,beforeSnapshot:n.beforeSnapshot,afterSnapshot:n.afterSnapshot}),n.message&&(r.statusDetails={message:n.message}),n.data)if(mR.safeParse(n.data).success){let i=mR.parse(n.data),a=i.request,s={...i,request:void 0},l=`output-attachment-api-request-${randomUUID()}.json`,c=`output-attachment-api-response-${randomUUID()}.json`;Un__default.writeFileSync(Cn__default.join(o,l),JSON.stringify(a,null,2)),Un__default.writeFileSync(Cn__default.join(o,c),JSON.stringify(s,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 wHt(r,o,n.data);return r}async function _6(e,t,o,n,r){for(let i of r){let a;switch(i.type){case "PRESET_ACTION":{a=await zj(e,t,o,i);break}case "CONDITIONAL":{a=await zj(e,t,o,i),a.steps=[],i.assertionResult&&a.steps.push(await zj(e,t,o,i.assertionResult)),await _6(e,t,o,a.steps,i.results);break}case "AI_ACTION_DYNAMIC":case "AI_ACTION":case "SECTION":case "WHILE_LOOP":case "MODULE":{if(a=await zj(e,t,o,i),await _6(e,t,o,a.steps,i.results),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[s,l]of Object.entries(i.inputs))a.parameters.push({name:s,value:l});}break}}if(!a){e.warn({result:i},"Failed to convert Momentic result to Allure step");continue}a.attachments||(a.attachments=[]),RHt({step:a,folder:o,beforeTestContext:i.beforeTestContext,afterTestContext:i.afterTestContext}),n.push(a);}}function IHt(e,t){for(let{tests:o,quarantined:n}of [{tests:t.testsToSkip,quarantined:false},{tests:t.quarantinedTestsToSkip,quarantined:true}])for(let r of o){let i=n?t.quarantinedTestsMetadata[r.id]:void 0,a={uuid:createHash("sha256").update(JSON.stringify([t.projectConfigPath,t.suiteName,t.startedAt.getTime(),r.id])).digest("hex"),historyId:r.id,testCaseId:r.id,fullName:r.name,name:Yn(r.name),status:"skipped",start:t.startedAt.getTime(),stop:t.startedAt.getTime(),parameters:[],labels:R0e({suiteName:t.suiteName,attempts:0,runId:void 0,quarantined:n,quarantinedReason:i?.quarantinedReason,quarantinedAt:i?.quarantinedAt}),steps:[]};r.platform&&a.labels.push({name:"platformType",value:r.platform}),Un__default.writeFileSync(Cn__default.join(e,`${a.uuid}-result.json`),JSON.stringify(a,void 0,2));}}async function C0e(e,t,o,n,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 a=t.createDebugDataReaderForRunAttempt(i.runId,i.runAttemptId);try{await CHt(e,a,{folder:o,suiteName:n.suiteName},i);}finally{a.close();}}IHt(o,n);}function w0e(e){try{return JSON.stringify(e,void 0,2)??JSON.stringify({value:null},void 0,2)}catch(t){let o=t instanceof Error?t.message:"unknown error";return JSON.stringify({error:o},void 0,2)}}function xHt(e,t,o){let n=e.listVideoAssetPaths();if(n.length===0)return [];let r=[];for(let i of n){let a=Cn__default.basename(i),s=o?`${o}-${a}`:a;try{Un__default.copyFileSync(i,Cn__default.join(t,s));}catch{continue}let l,c=Cn__default.extname(i).toLowerCase();c===".webm"?l="video/webm":c===".mp4"?l="video/mp4":l="application/octet-stream",r.push({name:a,source:s,type:l});}return r}function $j(e){if(e.status!=="FAILED")return "none";switch(e.failureReason){case "SetupFailureError":return "setup";case "TeardownFailureError":return "teardown";default:return "main"}}function OHt(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 mt(e)}}function O0e(e){let t=Cn__default.relative(".",e);return t===""?e:t}function I0e(e,t){return Math.max(0,(e.getTime()-t.getTime())/1e3)}function PHt(e,t,o){let n=I0e(t,e),r=I0e(o,e);return {start_at:n,end_at:r,duration:Math.max(0,r-n)}}function P0e(e){let t=e.reduce((o,[n,r])=>(!r||Object.keys(o).length>=10||(o[n]=r),o),{});return Object.keys(t).length>0?t:void 0}function kHt(e){if(e.status!=="FAILED"||!e.failureReason)return;let t=Vd({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 MHt(e){if(e.status!=="FAILED")return;let t=[e.failureDetails?.classification?.summary,e.failureDetails?.classification?.rootCause,e.failureDetails?.errorMessage].filter(n=>!!n),o=e.failureDetails?.errorStack?.split(`
4657
- `).map(n=>n.trim()).filter(Boolean)||[];if(!(t.length===0&&o.length===0))return [{expanded:t,backtrace:o}]}function LHt(e){let t=e.status==="FAILED"?$j(e):void 0;return P0e([["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 NHt(e,t,o){let n=O0e(o.filePath);return {id:o.runId||randomUUID(),scope:e,name:o.testName,location:n,file_name:Cn__default.basename(n),result:OHt(o.status),failure_reason:kHt(o),failure_expanded:MHt(o),history:PHt(t,o.lastAttemptStartedAt,o.finishedAt),tags:LHt(o)}}function x0e(e,t,o,n,r){let i=O0e(t);return {id:randomUUID(),scope:e,name:o,location:i,file_name:Cn__default.basename(i),result:"skipped",history:{start_at:0,end_at:0,duration:0},tags:P0e([["quarantined",r?.quarantined||"false"],["failure_recovery","false"]])}}function DHt(e,t){let o=t.map(i=>NHt(e.suiteName,e.startedAt,i)),n=e.testsToSkip.map(i=>x0e(e.suiteName,i.relativeFilePath,i.name,i.id,void 0)),r=e.quarantinedTestsToSkip.map(i=>x0e(e.suiteName,i.relativeFilePath,i.name,i.id,{quarantined:"true"}));return [...o,...n,...r]}function k0e(e,t,o){let n=DHt(t,o);Un__default.writeFileSync(Cn__default.join(e,`${t.suiteName}.buildkite.json`),JSON.stringify(n,null,2));}function Rw(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 L0e(e,t,o){let n=P6(t,o);Un__default.writeFileSync(Cn__default.join(e,`${t.suiteName}.momentic.json`),JSON.stringify(n,null,2));}function P6(e,t){let o=t.map(BHt),n=[...e.testsToSkip.map(r=>M0e(r,false)),...e.quarantinedTestsToSkip.map(r=>M0e(r,true))];return CZ.parse({version:1,runGroup:{startedAt:e.startedAt.toISOString(),finishedAt:e.finishedAt.toISOString(),durationMs:e.finishedAt.getTime()-e.startedAt.getTime()},summary:UHt(o,n),runs:o,skipped:n})}function BHt(e){let t=e.status==="PASSED"&&(e.failureRecoveryDetails?.attempts??0)>0,o=e.failureDetails?.manualClassification??e.failureDetails?.classification,n=e.status==="FAILED"?{reason:e.failureReason,message:e.failureDetails?.errorMessage}:null;return {runId:e.runId,testId:e.testId,testName:e.testName,filePath:Cn__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:n,classification:o?{reasoning:o.summary,category:o.reason,citations:o.citations}:null}}function M0e(e,t){return {testId:e.id,testName:e.name,filePath:Cn__default.relative(".",e.relativeFilePath),labels:e.labels,quarantined:t}}function UHt(e,t){return {total:e.length+t.length,executed:e.length,skipped:t.length,passed:e.filter(o=>o.status==="PASSED").length,failed:e.filter(o=>o.status==="FAILED").length,cancelled:e.filter(o=>o.status==="CANCELLED").length,quarantined:e.filter(o=>o.quarantined).length+t.filter(o=>o.quarantined).length,recovered:e.filter(o=>o.recovered).length}}function N0e(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 zHt(e,t){let o=$j(e);if(t.name(e.testName).className(e.testName).file(Cn__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(n=>{t.property("dd_tags[label]",n);})),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&&N0e(t,e.quarantinedMetadata),o==="setup"&&(t.property("setup_failed","true"),t.property("dd_tags[setup_failed]","true")),o==="main"&&(t.property("main_failed","true"),t.property("dd_tags[main_failed]","true")),o==="teardown"&&(t.property("teardown_failed","true"),t.property("dd_tags[teardown_failed]","true")),e.status==="FAILED"){let n=Vd({failureReason:e.failureReason,classification:e.failureDetails?.classification,manualClassification:e.failureDetails?.manualClassification});if(n.title){let{description:r}=n;e.runId&&(r+=` Visit https://app.momentic.ai/runs/${e.runId} for more details.`),t.failure(r,n.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 HHt(e,t,o){let{suiteId:n,suiteName:r,startedAt:i,finishedAt:a,testsToSkip:s,quarantinedTestsToSkip:l,quarantinedTestsMetadata:c}=t,u=e.testSuite().name(r);n&&u.property("id",n),u.timestamp(i).property("startedAt",i.toISOString()).property("finishedAt",a.toISOString()).time((a.getTime()-i.getTime())/1e3);for(let d of o){let m=u.testCase();zHt(d,m);}for(let d of s){let m=u.testCase();m.name(d.name).className(d.name).file(Cn__default.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&m.property("baseUrl",d.baseUrl),d.labels&&(m.property("labels",d.labels.join(",")),d.labels.forEach(p=>{m.property("dd_tags[label]",p);})),m.skipped();}for(let d of l){let m=u.testCase();m.name(d.name).className(d.name).file(Cn__default.relative(".",d.relativeFilePath)).property("id",d.id);let p=c[d.id];p&&N0e(m,p),d.baseUrl&&m.property("baseUrl",d.baseUrl),d.labels&&(m.property("labels",d.labels.join(",")),d.labels.forEach(h=>{m.property("dd_tags[label]",h);})),m.skipped();}return u}function D0e(e,t,o){let n=jHt.newBuilder();HHt(n,t,o),n.writeTo(Cn__default.join(e,`${t.suiteName}.xml`));}var $Ht="insights-collector.newrelic.com",GHt="insights-collector.eu01.nr-data.net",VHt=4e3;async function k6({logger:e,config:t,params:o,runs:n,runGroupId:r,envName:i,appUrl:a,gitMetadata:s}){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=n.map(Rw),u=P6(o,c),d=F0e({...t.attributes,runGroupId:r,environment:i,suiteName:o.suiteName,gitBranch:s.gitBranchName,gitCommit:s.gitCommitSha,gitRepository:s.githubRepository??s.gitOriginUrl,ciRunUrl:WHt()}),m=u.runs.map((g,f)=>({...d,eventType:"MomenticRun",timestamp:new Date(g.finishedAt).getTime(),...F0e({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?`${a}/runs/${g.runId}`:void 0})}));m.push({...d,eventType:"MomenticRunGroup",timestamp:new Date(o.finishedAt).getTime(),startedAt:o.startedAt.toISOString(),finishedAt:o.finishedAt.toISOString(),durationMs:u.runGroup.durationMs,runGroupUrl:`${a}/run-groups/${r}`,...u.summary,passRate:u.summary.executed>0?u.summary.passed/u.summary.executed:0});let h=`https://${t.region==="EU"?GHt:$Ht}/v1/accounts/${t.accountId}/events`;try{let g=await fetch(h,{method:"POST",headers:{"Content-Type":"application/json","Api-Key":l},body:JSON.stringify(m)});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 ${m.length} events to New Relic account ${t.accountId}`);}catch(g){e.error(`Failed to send test results to New Relic: ${W(g)}`);}}function F0e(e){let t={};for(let[o,n]of Object.entries(e))n==null||n===""||(t[o]=typeof n=="string"?n.slice(0,VHt):n);return t}function WHt(){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 B0e(e){return {title:Fn(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(B0e):[]}}async function YHt(e,t,o,n){if(n.results?.length){let r=await Hj({logger:e,debugDataStorage:t,folder:o,label:"final-state",snapshotId:n.results[n.results.length-1].afterSnapshot});return r?[{name:"Final state screenshot",path:r,contentType:"image/jpeg"}]:[]}return []}async function JHt(e,t,o,n){let r;if(n.status==="FAILED"&&n.failureReason){let i=Vd({failureReason:n.failureReason,classification:n.failureDetails?.classification,manualClassification:n.failureDetails?.manualClassification});r={value:n.failureDetails?.classification?.reason??n.failureReason,message:i.description};}return {status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"interrupted":"failed",duration:n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime(),error:r,retry:n.attempts-1,steps:n.results?.map(B0e)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await YHt(e,t,o,n)}}async function XHt(e,t,o,n){return {expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await JHt(e,t,o,n)]}}async function QHt(e,t,o,n){return {tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await XHt(e,t,o,n)],id:n.runId,file:n.filePath}}function M6(e,t){return e.reduce((o,n)=>t(n)?o+1:o,0)}async function ZHt(e,t,o,n,r){return {suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(r.map(async i=>{let a=i.runId&&i.runAttemptId?t.createDebugDataReaderForRunAttempt(i.runId,i.runAttemptId):new MC;try{return await QHt(e,a,o,i)}finally{a.close();}}))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:M6(r,i=>i.status==="PASSED"),unexpected:M6(r,i=>i.status!=="PASSED"),flaky:M6(r,i=>!!i.isFlake),skipped:0}}}async function U0e(e,t,o,n,r){let i=await ZHt(e,t,o,n,r);Un__default.writeFileSync(Cn__default.join(o,`${n.suiteName}.json`),JSON.stringify(i,null,2));}async function j0e({logger:e,callbacks:t,format:o,params:n,runs:r,folder:i}){switch(existsSync(i)&&!statSync(i).isDirectory()&&(x.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}),o){case "json":{let a=r.map(Rw);L0e(i,n,a);return}case "junit":{let a=r.map(Rw);D0e(i,n,a);return}case "buildkite-json":{let a=r.map(Rw);k0e(i,n,a);return}case "allure":case "allure-json":await C0e(e,t,i,n,r);return;case "playwright-json":await U0e(e,t,i,n,r);return;default:throw new Error(`Unknown reporter format requested: '${o}'`)}}function tT(e){let t=e??s$t();return z0e()&&t===1&&x.warn("Running with --pixel-ratio=1 on a Retina screen. Viewport calculations may be incorrect; omit the flag to auto-detect."),t}function s$t(){let e=z0e(),t=e?2:1;return x.debug(`Auto-detected device pixel ratio ${t} (Mac OS Retina: ${e}).`),t}var z0e=once(()=>{if(platform()!=="darwin")return false;try{return execSync("system_profiler SPDisplaysDataType").toString().includes("Retina")}catch{return false}});async function Wj(e,t=true,o=false){let n=d$t(e),r=await c$t.which(n[0],true),i=n.slice(1),a=l$t.exec(u$t(r),i,{delay:100,silent:o});if(t)return a;a.catch(s=>{x.warn({err:s},`Background command exited with an error: ${e}`);});}var H0e="the Momentic GitHub app is missing permission to create pull requests or write branches for this repository";function m$t(e,{context:t}){return e instanceof Lo?e.rawError.includes("Resource not accessible by integration")?`Cannot create ${t} because ${H0e}.`:e.status>=400&&e.status<500?e.rawError:`Could not create ${t} due to a GitHub error.`:`Could not create ${t}: ${W(e)}`}function $0e(e){return e instanceof Lo?e.rawError.includes("Resource not accessible by integration")?H0e:e.status>=400&&e.status<500?e.rawError:"a GitHub error occurred":W(e)}function G0e(e,t){x.error(m$t(e,t));}var bt={ArgsInvalid:"MOM_ARGS_INVALID",AuthRequired:"MOM_AUTH_REQUIRED",AuthForbidden:"MOM_AUTH_FORBIDDEN",ApiError:"MOM_API_ERROR",ApiUnavailable:"MOM_API_UNAVAILABLE",ResourceNotFound:"MOM_RESOURCE_NOT_FOUND",FeatureNotEnabled:"MOM_FEATURE_NOT_ENABLED",UsageLimitReached:"MOM_USAGE_LIMIT_REACHED",ExploreIncomplete:"MOM_EXPLORE_INCOMPLETE",ProjectLintFailed:"MOM_PROJECT_LINT_FAILED",ProjectConfigError:"MOM_PROJECT_CONFIG_ERROR",ResultsRunNotFound:"MOM_RESULTS_RUN_NOT_FOUND",UserUnclassified:"MOM_USER_UNCLASSIFIED",InternalUnhandled:"MOM_INTERNAL_UNHANDLED"},p$t={[bt.ArgsInvalid]:{group:"args",retry:"no",attribution:"user-action"},[bt.AuthRequired]:{group:"auth",retry:"no",attribution:"user-action"},[bt.AuthForbidden]:{group:"auth",retry:"no",attribution:"user-action"},[bt.ApiError]:{group:"api",retry:"case-by-case",attribution:"product"},[bt.ApiUnavailable]:{group:"api",retry:"yes",attribution:"product"},[bt.ResourceNotFound]:{group:"api",retry:"no",attribution:"user-action"},[bt.FeatureNotEnabled]:{group:"auth",retry:"no",attribution:"product"},[bt.UsageLimitReached]:{group:"auth",retry:"no",attribution:"user-action"},[bt.ExploreIncomplete]:{group:"run",retry:"case-by-case",attribution:"unknown"},[bt.ProjectLintFailed]:{group:"args",retry:"no",attribution:"user-action"},[bt.ProjectConfigError]:{group:"env",retry:"no",attribution:"user-env"},[bt.ResultsRunNotFound]:{group:"args",retry:"no",attribution:"user-action"},[bt.UserUnclassified]:{group:"internal",retry:"no",attribution:"user-action"},[bt.InternalUnhandled]:{group:"internal",retry:"case-by-case",attribution:"product"}},V0e={catalog:p$t,argsCode:bt.ArgsInvalid,userCode:bt.UserUnclassified,internalCode:bt.InternalUnhandled,extraClassifier:e=>LTe(e,{authRequired:bt.AuthRequired,authForbidden:bt.AuthForbidden,apiError:bt.ApiError,apiUnavailable:bt.ApiUnavailable,resourceNotFound:bt.ResourceNotFound,projectConfigError:bt.ProjectConfigError})};function qj(e){return W0e(e,"runs","run")}function L6(e){return W0e(e,"run-groups","run group")}function W0e(e,t,o){let n=e.trim(),r=`Invalid ${o} ID: ${e}. Expected a UUID or a URL like https://app.momentic.ai/${t}/<id>.`;if(/[\s,]/.test(n))throw new bo(bt.ArgsInvalid,`${r} To pass multiple IDs, separate them with spaces as individual arguments instead of a single quoted string.`);let i=/^https?:\/\//i.test(n)?g$t(n,t,o):n;if(!z.guid().safeParse(i).success)throw new bo(bt.ArgsInvalid,r);return i}function g$t(e,t,o){let n;try{n=new URL(e);}catch{throw new bo(bt.ArgsInvalid,`Invalid ${o} URL: ${e}`)}let r=n.pathname.split("/").filter(i=>i.length>0);if(r.length!==2||r[0]!==t)throw new bo(bt.ArgsInvalid,`Could not extract ${o} ID from URL: ${e}. Expected a URL like https://app.momentic.ai/${t}/<id>.`);return r[1]}function Kj(e){return new Promise((t,o)=>{let n=[];createReadStream(e).pipe(f$t()).on("data",r=>n.push(r)).on("end",()=>t(n)).on("error",r=>o(r));})}var To="3.62.2",q0e={packageName:"momentic",currentVersion:To,changelogUrl:"https://github.com/momentic-ai/cli/releases",updateCommand:"npx momentic@latest upgrade",runUpgrade:N3__default.existsSync(Ch.join(process.cwd(),"package.json"))?e=>installPackage(`momentic@${e}`,{silent:false,dev:true}):void 0},{checkCLIVersion:zi,getLatestCLIVersion:K0e}=HSe(q0e),Y0e=e=>ATe({...q0e,logger:e});_It("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI","POSTHOG_WEB_WRITE_KEY is not set");var{captureEvent:Ep,setAnalyticsIdentity:Yj,shutdownAnalytics:J0e}=OM({writeKey:"phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",host:"https://p.momentic.ai",platform:"cli",identity:"stashed",flushImmediately:true,onIdentify:BTe});var A$t=3e3,Jj=new Set;function X0e(e){Jj.add(e),e.finally(()=>Jj.delete(e));}async function Q0e(){if(Jj.size!==0)try{await ye(Promise.allSettled([...Jj]),{milliseconds:A$t});}catch{}}async function Xj(){try{await ye(Promise.all([Q0e(),xM(),zo.flush(),J0e(),$M(),XY(),UTe()]),{milliseconds:5e3});}catch{}}async function eFe({momenticFiles:e,project:t,logger:o}){let n;try{n=await Py({repoRoot:t.rootDir??process.cwd(),mainBranch:t.config.gitMainBranch,logger:o});}catch(i){let a="Make sure the checkout has enough git history to reach the base ref (CI checkouts are often shallow by default).";throw i instanceof ng?new ae(`Could not determine the base ref to diff against for --changed. ${a}`):new ae(`--changed could not compute the git diff: ${W(i)}. ${a}`)}let r=E$t({changedFiles:n.changedFiles,repoRoot:n.repoRoot,momenticFiles:e});return x.log(r.length===0?`No changed tests or modules vs ${n.baseRef}.`:`${r.length} changed test(s) vs ${n.baseRef}.`),r.map(i=>i.fullFilePath)}function E$t({changedFiles:e,repoRoot:t,momenticFiles:o}){let n=e.filter(u=>u.status!=="D"),r=n.filter(u=>u.path.endsWith(".test.yaml")),i=n.filter(u=>u.path.endsWith(".module.yaml")),a=Object.values(o.tests),s=new Map(a.map(u=>[u.fullFilePath,u])),l=new Map;for(let u of r){let d=s.get(Ch.resolve(t,u.path));d&&!l.has(d.id)&&l.set(d.id,{fullFilePath:d.fullFilePath,relativePath:d.relativePath,reason:"test-changed"});}let c=w$t({momenticFiles:o,changedModuleFullPaths:i.map(u=>Ch.resolve(t,u.path))});if(c.size>0)for(let u of a){if(l.has(u.id))continue;let d=zI(u.fullFilePath,o);for(let m of d)if(c.has(m)){l.set(u.id,{fullFilePath:u.fullFilePath,relativePath:u.relativePath,reason:"module-changed"});break}}return Array.from(l.values())}function w$t({momenticFiles:e,changedModuleFullPaths:t}){let o=new Set(t),n=new Set;for(let[a,s]of Object.entries(e.modules))o.has(s.fullFilePath)&&n.add(a);if(n.size===0)return n;let r=new Map;for(let[a,s]of Object.entries(e.modules))r.set(a,zI(s.fullFilePath,e));let i=true;for(;i;){i=false;for(let[a,s]of r)if(!n.has(a)){for(let l of s)if(n.has(l)){n.add(a),i=true;break}}}return n}function oFe(e,t){return t?.map(o=>{try{return new RegExp(o)}catch(n){throw new ae(`Invalid ${e} pattern '${o}': ${W(n)}. Patterns are regular expressions matched against test file paths, not globs (e.g. use 'momentic/pr/' instead of 'momentic/pr/**').`,{cause:n})}})}async function My({tests:e,changed:t,momenticFiles:o,project:n,yes:r,include:i,exclude:a,labels:s,logger:l}){let c=new Set,u=oFe("--include",i),d=oFe("--exclude",a);if(t)(await eFe({momenticFiles:o,project:n,logger:Re})).forEach(h=>c.add(h));else if(e&&e.length>0){let p=e.some(g=>Un__default.existsSync(g)),h=cwd();p?(h!==n.rootDir&&l.warn(`Test paths resolve against the current directory ('${h}'), not the project root ('${n.rootDir}'). Run from the project root or use substring filters to avoid surprises.`),e.forEach(g=>{if(!Un__default.existsSync(g))throw new ae(`Path '${g}' does not exist. Check the path or use a substring filter instead.`);let f;try{f=Un__default.statSync(g).isDirectory();}catch(b){l.warn({err:b},`Skipping path ${g} because it cannot be read`);return}let y=Cn__default.resolve(g);Object.values(o.tests).filter(b=>f?Kie(b.fullFilePath,y):b.fullFilePath===y).forEach(b=>{c.add(b.fullFilePath);});})):Object.values(o.tests).forEach(g=>{e.some(f=>g.relativePath.includes(f))&&c.add(g.fullFilePath);});}else !r&&!await ki("No test paths or substrings were provided. Do you want to run all tests?")&&(l.error("Cancelled by user."),Je(He.Failure)),Object.values(o.tests).forEach(h=>{c.add(h.fullFilePath);});for(let p of c){let h=Cn__default.relative(n.rootDir,p);u&&!u.some(g=>g.test(h))&&c.delete(p),d&&d.some(g=>g.test(h))&&c.delete(p);}let m=Array.from(c).map(async p=>{try{let h=await Nl(p,Re,o);if(Ph.gt(h.schemaVersion,qt)&&Vae(l,`Test ${p} has schema version ${h.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 g=h.labels||[];if(!s.some(y=>g.includes(y)))return null}return {...h,fullFilePath:p,relativeFilePath:Cn__default.relative(n.rootDir,p),testBundleHash:CN({absoluteTestFilePath:p,momenticFiles:o,logger:Re})}}catch(h){let g=`Failed to read and resolve test at '${p}': ${W(h)}`;throw l.error(g),wi(hi(h,gg)?new ae(g,{cause:h}):h)}});return compact(await Promise.all(m))}function nFe({testDefinitions:e,quarantinedTestsMetadata:t,onlyQuarantined:o=false,skipQuarantined:n=false,shardIndex:r=1}){let[i,a]=partition(e,c=>c.disabled),[s,l]=partition(a,c=>c.id in t);return {testsToSkip:r===1?i:[],quarantinedTestsToSkip:r===1&&n?s:[],testsToRun:o?[]:l,quarantinedTestsToRun:n?[]:s}}function rFe({testsToRun:e,quarantinedTestsToRun:t,quarantinedTestsMetadata:o,testInputMatrix:n}){let r=[],i=(a,s,l)=>{n?n.forEach((c,u)=>{r.push({inputs:c,inputIndex:u,testDefinition:a,quarantined:s,quarantinedMetadata:l});}):r.push({inputs:void 0,testDefinition:a,quarantined:s,quarantinedMetadata:l});};return e.forEach(a=>i(a,false)),t.forEach(a=>i(a,true,o[a.id])),r}var iFe=()=>process.exit(130),aFe=()=>process.exit(143);process.on("SIGINT",iFe);process.on("SIGTERM",aFe);function Cw(){process.off("SIGINT",iFe),process.off("SIGTERM",aFe);}async function sFe({orgId:e,codeEvaluator:t,logger:o,outputDefinitions:n,testContext:r}){let i={};for(let a of n){let{name:s,value:l}=a;i[s]=await Es({orgId:e,s:l,codeEvaluator:t,logger:o,context:r});}return i}var Zj=z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/),F6=Zj,_$t=F6.array().min(1).max(32).refine(e=>new Set(e).size===e.length,{message:"service IDs must be unique"}).refine(e=>e.every((t,o)=>o===0||e[o-1]<t),{message:"service IDs must be sorted"}),Qj=z.discriminatedUnion("mode",[z.object({mode:z.literal("playwright")}).strict(),z.object({mode:z.literal("private-service"),connectorId:Zj,serviceIds:_$t.optional()}).strict()]),cFe=z.record(z.string().regex(/^[a-z0-9]([-.a-z0-9_]{0,61}[a-z0-9])?$/),z.string()),B6=z.union([z.guid(),z.string().regex(/^[a-f0-9]{64}$/)]),U6=z.object({allocationRequestId:z.guid().default(randomUUID$1),concurrencyKey:z.string().regex(/^[A-Za-z0-9][A-Za-z0-9:_-]{0,255}$/).optional(),maxConcurrentSessions:z.number().int().positive().optional(),maxSessionTtlSeconds:z.number().int().min(1).max(3600).default(3600),metadata:cFe.optional(),network:Qj.default({mode:"playwright"}),principalId:B6,tokenVersion:z.literal(2)}).strict(),uFe=z.object({accessToken:z.string().min(1),expiresAt:z.iso.datetime(),tokenType:z.literal("Bearer")}),lFe=z.object({host:z.string().trim().min(1).max(253),port:z.number().int().min(1).max(65535)}).strict(),O$t=z.object({browserAddress:lFe,id:F6,target:lFe}).strict(),P$t=z.object({id:F6,mode:z.literal("localhost")}).strict(),k$t=z.union([O$t,P$t]),dFe=z.object({services:k$t.array().min(1).max(32)}).strict().superRefine(({services:e},t)=>{let o=e.filter(n=>"mode"in n);new Set(e.map(({id:n})=>n)).size!==e.length&&t.addIssue({code:"custom",message:"service IDs must be unique"}),o.length>1&&t.addIssue({code:"custom",message:"only one localhost namespace service is allowed"}),o.length===1&&e.length>1&&t.addIssue({code:"custom",message:"localhost cannot be combined with explicit services"});}),M$t=z.object({algorithm:z.literal("RSA-OAEP-256"),chunks:z.string().min(1).array().min(1).max(128)});U6.omit({tokenVersion:true}).partial({principalId:true});var mFe=z.object({metadata:cFe.optional(),browser:z.literal("chromium").default("chromium"),network:Qj.default({mode:"playwright"}),playwrightVersion:z.string().default("1.60"),ttlSeconds:z.number().int().min(1).max(3600).default(3600),waitTimeoutMs:z.number().int().min(0).max(1e4).default(5e3)}).strict(),L$t=z.discriminatedUnion("mode",[Qj.options[0].strip(),Qj.options[1].strip()]),j6=z.object({id:z.string(),status:z.string(),browser:z.string().optional(),playwrightVersion:z.string().optional(),network:L$t.default({mode:"playwright"}),connectToken:z.string().optional(),connectTokenExpiresAt:z.string().optional(),wsEndpoint:z.string().optional(),statusUrl:z.string().optional(),createdAt:z.string().optional(),queuedAt:z.string().nullable().optional(),assignedAt:z.string().nullable().optional(),readyAt:z.string().nullable().optional(),connectedAt:z.string().nullable().optional(),expiresAt:z.string().nullable().optional(),endedAt:z.string().nullable().optional(),failureCode:z.string().nullable().optional(),terminalReason:z.string().nullable().optional()}),pFe=j6.extend({connectToken:z.string(),status:z.literal("READY"),wsEndpoint:z.string()}),hFe=z.object({connectorId:z.string(),state:z.string()}),gFe=z.object({encryptedEnrollmentCredential:M$t});var ig=class extends Error{constructor(o,n,r){super(`Browser Fleet request failed (${n??"HTTP_ERROR"}, ${o})`);this.status=o;this.code=n;this.retryAfterMs=r;this.name="BrowserFleetAPIError";}},oT=class extends Error{constructor(t){super("Browser Fleet request failed",{cause:t}),this.name="BrowserFleetConnectionError";}},ez=class extends Error{constructor(o){super(`Browser Fleet session ${o.id} did not become ready (${o.failureCode??o.status})`);this.session=o;this.name="BrowserFleetSessionError";}},Cs=class extends Error{constructor(o,n){super(o);this.sessionId=n;this.name="BrowserFleetResponseError";}},tz=class extends Error{constructor(o){super(`Browser Fleet Connector did not become active (${o.state})`);this.connector=o;this.name="BrowserFleetConnectorError";}};function oz(e){return `/v1/private-connectors/${encodeURIComponent(Zj.parse(e))}`}function fFe(e){let t=hFe.safeParse(e);if(!t.success)throw new Cs("Browser Fleet returned a malformed Connector response");return t.data}var nz=class{constructor(t,o){this.transport=t;this.principalId=o;}async reconcile(t,o,n={}){let r=o.principalId===void 0?this.principalId:o.principalId,i=await this.transport.request(oz(t),{body:JSON.stringify(dFe.parse(o.desiredState)),headers:{"Content-Type":"application/json",...r?{"X-Browser-Fleet-Principal-Id":B6.parse(r)}:{}},method:"PUT"},n,true);return fFe(i.body)}async retrieve(t,o={}){let n=await this.transport.request(oz(t),{},o,true);return fFe(n.body)}async waitUntilActive(t,o={}){let n=o.timeoutMs===null?void 0:AbortSignal.timeout(o.timeoutMs??45e3),r=o.signal&&n?AbortSignal.any([o.signal,n]):o.signal??n;for(;;){r?.throwIfAborted();let i=await this.retrieve(t,{...o,signal:r});if(i.state==="ACTIVE")return i;if(i.state!=="PROVISIONING")throw new tz(i);await setTimeout$1(500,void 0,{signal:r});}}async createEnrollmentCredential(t,o,n={}){let r=await this.transport.request(`${oz(t)}/enrollment-credentials`,{body:JSON.stringify(o),headers:{"Content-Type":"application/json"},method:"POST"},n,true),i=gFe.safeParse(r.body);if(!i.success)throw new Cs("Browser Fleet returned a malformed enrollment response");return i.data.encryptedEnrollmentCredential}async delete(t,o={}){await this.transport.request(oz(t),{method:"DELETE"},o,true);}};var F$t=z.object({id:z.string()}),B$t=1e4,U$t=2e4;function SFe(e){return e+Math.random()*Math.min(4e3,e*4)}var rz=class{constructor(t,o){this.transport=t;this.accessToken=o;}async create(t={},o={}){return (await this.createResponse(this.creationParams(t),{...o,idempotencyKey:this.idempotencyKey(o)})).session}async retrieve(t,o={}){return (await this.requestSession(`/${encodeURIComponent(t)}`,{},o)).session}async delete(t,o={}){await this.transport.request(`/v1/sessions/${encodeURIComponent(t)}`,{method:"DELETE"},o);}async createAndWait(t={},o={}){o.signal?.throwIfAborted();let n=this.creationParams(t),r={...o,idempotencyKey:this.idempotencyKey(o)},i=o.allocationTimeoutMs??9e4,a=Date.now()+i,s=new AbortController,l=setTimeout(()=>s.abort(new DOMException("Browser Fleet allocation timed out","TimeoutError")),i),c=o.signal?AbortSignal.any([o.signal,s.signal]):s.signal,u={...r,signal:c},d;try{let m=await this.retry(()=>this.createResponse(n,u),a,c);for(d=m.session;(d.status==="QUEUED"||d.status==="PROVISIONING")&&Date.now()<a&&(await setTimeout$1(Math.min(SFe(m.retryAfterMs),a-Date.now()),void 0,{signal:c}),!(Date.now()>=a));){let h=d.id;m=await this.retry(()=>this.requestSession(`/${encodeURIComponent(h)}`,{},u),a,c),d=m.session;}if(c.throwIfAborted(),d.status!=="READY")throw new ez(d);let p=pFe.safeParse(d);if(!p.success)throw new Cs("Browser Fleet returned a malformed session response",d.id);return p.data}catch(m){let p=d?.id??(m instanceof Cs?m.sessionId:void 0);if(!p&&c.aborted)try{p=(await this.createResponse(n,{...r,signal:AbortSignal.timeout(U$t)})).session.id;}catch(h){h instanceof Cs&&(p=h.sessionId);}throw p&&await this.delete(p,{signal:AbortSignal.timeout(B$t)}).catch(()=>{}),m}finally{clearTimeout(l);}}idempotencyKey(t){if(t.idempotencyKey!==void 0)return t.idempotencyKey;if(typeof this.accessToken=="object")return this.accessToken.allocationRequestId;if(this.accessToken)throw new Error("Pass the token object or an explicit idempotencyKey when using a raw access token");return randomUUID$1()}creationParams(t){let o=typeof this.accessToken=="object"?this.accessToken:void 0;return mFe.parse({...t,network:t.network===void 0?o?.network:t.network,ttlSeconds:t.ttlSeconds===void 0?o?.maxSessionTtlSeconds:t.ttlSeconds})}createResponse(t,o){return this.requestSession("",{body:JSON.stringify(t),headers:{...o.headers,"Content-Type":"application/json","Idempotency-Key":o.idempotencyKey},method:"POST"},o)}async requestSession(t,o,n){let r=await this.transport.request(`/v1/sessions${t}`,o,n),i=j6.safeParse(r.body);if(!i.success)throw new Cs("Browser Fleet returned a malformed session response",F$t.safeParse(r.body).data?.id);return {session:i.data,retryAfterMs:r.retryAfterMs}}async retry(t,o,n){for(;;)try{return await t()}catch(r){if(n.throwIfAborted(),!(r instanceof oT||r instanceof ig&&(r.status===408||r.status===429||r.status>=500))||Date.now()>=o)throw r;let a=r instanceof ig?r.retryAfterMs:500;await setTimeout$1(Math.min(SFe(a),o-Date.now()),void 0,{signal:n});}}};var iz=class{constructor(t,o={}){this.transport=t;this.defaults=o;}async create({principalId:t=this.defaults.principalId,concurrencyKey:o=this.defaults.concurrencyKey,maxConcurrentSessions:n=this.defaults.maxConcurrentSessions,...r}={},i={}){let{concurrencyKey:a,maxConcurrentSessions:s,...l}=U6.parse({...r,principalId:t,concurrencyKey:o,maxConcurrentSessions:n,tokenVersion:2}),c=m=>this.transport.request("/v1/token",{body:JSON.stringify({...l,metadata:m}),headers:{"Content-Type":"application/json",...a===void 0?{}:{"X-Browser-Fleet-Concurrency-Key":a},...s===void 0?{}:{"X-Browser-Fleet-Max-Concurrent-Sessions":String(s)}},method:"POST"},i),u;try{u=await c(l.metadata);}catch(m){if(!(m instanceof ig)||m.status!==400||!l.metadata)throw m;u=await c(void 0);}let d=uFe.safeParse(u.body);if(!d.success)throw new Cs("Browser Fleet returned a malformed token response");return {...d.data,allocationRequestId:l.allocationRequestId,network:l.network,maxSessionTtlSeconds:l.maxSessionTtlSeconds}}};var TFe=64*1024;function z$t(e){if(!e)return 500;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let o=Date.parse(e);return Number.isNaN(o)?500:Math.max(0,o-Date.now())}async function vFe(e){let t=Number(e.headers.get("Content-Length"));if(Number.isFinite(t)&&t>TFe)throw await e.body?.cancel(),new Cs("Browser Fleet response is too large");if(!e.body)return;let o=e.body.getReader(),n=[],r=0;for(let i=await o.read();!i.done;i=await o.read()){if(r+=i.value.byteLength,r>TFe)throw await o.cancel(),new Cs("Browser Fleet response is too large");n.push(i.value);}if(r!==0)return JSON.parse(new TextDecoder().decode(Buffer$1.concat(n,r)))}var az=class{baseUrl;authorization;controlAuthorization;fetch;requestTimeoutMs;constructor({accessToken:t,apiKey:o=process.env.BROWSER_FLEET_API_KEY,baseUrl:n=process.env.BROWSER_FLEET_BASE_URL,controlApiKey:r,fetch:i=globalThis.fetch,requestTimeoutMs:a=15e3}){if(!n)throw new Error("Browser Fleet base URL is not configured");this.baseUrl=n.replace(/\/$/,"");let s=(typeof t=="object"?t.accessToken:t)??o;this.authorization=s?`Bearer ${s}`:void 0,this.controlAuthorization=r?`Bearer ${r}`:void 0,this.fetch=i,this.requestTimeoutMs=a;}async request(t,o,n={},r=false){let i=r?this.controlAuthorization:this.authorization;if(!i)throw new Error(`Browser Fleet ${r?"control":"session"} API key is not configured`);let a=n.timeoutMs===void 0?this.requestTimeoutMs:n.timeoutMs,s=a===null?void 0:AbortSignal.timeout(a),l=n.signal&&s?AbortSignal.any([n.signal,s]):n.signal??s;l?.throwIfAborted();let c;try{c=await this.fetch(`${this.baseUrl}${t}`,{...o,headers:{...o.headers,Authorization:i},redirect:"error",signal:l});}catch(d){throw n.signal?.aborted?d:new oT(d)}let u=z$t(c.headers.get("Retry-After"));if(!c.ok){let d=await vFe(c).catch(()=>{});n.signal?.throwIfAborted();let m=typeof d=="object"&&d!==null&&"code"in d&&typeof d.code=="string"?d.code:void 0;throw new ig(c.status,m,u)}try{return {body:await vFe(c),retryAfterMs:u}}catch(d){throw n.signal?.aborted||d instanceof Cs?d:new oT(d)}}};var xO=class{baseUrl;sessions;tokens;privateConnectors;constructor(t={}){let o=new az(t);this.baseUrl=o.baseUrl,this.sessions=new rz(o,t.accessToken),this.tokens=new iz(o,{principalId:t.principalId,concurrencyKey:t.concurrencyKey,maxConcurrentSessions:t.maxConcurrentSessions}),this.privateConnectors=new nz(o,t.principalId);}};var AFe=new Set;function EFe(e){return ge({name:"cli.setup_browser_and_controller",attributes:{"momentic.remote_browser":e.localBrowserConfig.remoteBrowser===true},fn:async t=>{let o=await H$t(e);return t?.setAttribute("momentic.browser_execution_mode",o.controller.browser.executionMode),o}})}async function H$t({baseUrl:e,envName:t,devicePixelRatio:o,apiClient:n,test:r,storageClient:i,codeEvaluator:a,generator:s,orgId:l,variables:c,logger:u,customHeaders:d,testInputs:m,localBrowserConfig:p,aiSettings:h,visualDiffScreenshotStorage:g,tracer:f,runId:y,runAttemptId:b,runGroupId:S,browserTypeOverride:A,attemptedRemoteBrowserProviders:T,browserFleetRegion:v,abortSignal:R}){let I={baseUrl:n.baseUrl,apiKey:n.apiKey,logger:Re,mode:n.mode,runner:n.runner},{controller:C,context:O}=await J_({baseUrl:e,envName:t,test:r,variables:c,logger:u,orgId:l,localBrowserConfig:p,aiSettings:h,customHeaders:d,codeEvaluator:a,storage:i,enricher:new Ah(I,s),generator:s,visualDiffScreenshotStorage:g,devicePixelRatio:o,browserTypeOverride:A,callbacks:{onNetworkPage:P=>f.onNetworkPage(P),onNetworkLogs:P=>f.onNetworkLogs(P)},videoOptions:f.videoOutputPath?{videoOutputPath:f.videoOutputPath,onVideoPageChange:({videoName:P,timestamp:k})=>{f.setActiveVideo(P,k);}}:void 0,validateBrowserType:P=>{Jg(P)||(Re.warn({browserType:P,testName:r.name},"Browser required by test does not appear to be installed"),!AFe.has(P)&&(AFe.add(P),x.warn(`Browser ${P} does not appear to be installed. Run '${Ig(P)}' if you hit launch errors.`)));},createRemoteBrowserConnection:p.remoteBrowser?async()=>{let P=Date.now(),k,N=T?.slice(-1),M=crypto.randomUUID(),L=async()=>{let G=await n.createRemoteBrowserConnection({attemptedProviders:N,envName:t,runAttemptId:b,runGroupId:S,runId:y,testId:r.id,testName:r.name});return k=G.provider,G.provider&&T?.push(G.provider),G};try{if(!v&&N?.includes("SELF_HOSTED"))return await L();let G=await n.tryCreateBrowserFleetAccessToken({allocationRequestId:M,browserFleetRegion:v,envName:t,runAttemptId:b,runGroupId:S,runId:y,testId:r.id,testName:r.name},R);if(!G){if(v)throw new Error(`Browser Fleet region ${v} is unavailable for this run`);return await L()}k=G.provider,T?.push(G.provider);let X=await new xO({accessToken:G.accessToken,baseUrl:G.fleetApiUrl,requestTimeoutMs:15e3}).sessions.createAndWait({network:G.network,ttlSeconds:3600,waitTimeoutMs:1e4},{allocationTimeoutMs:9e4,idempotencyKey:M,signal:R});return {accessToken:X.connectToken,endpointType:"PLAYWRIGHT",operatingSystem:"linux",provider:G.provider,wsEndpoint:X.wsEndpoint}}catch(G){throw R?.aborted?G:new zu("Browser Fleet session allocation failed",{cause:G})}finally{zo.distribution("test_event_duration",Date.now()-P,["name:remote-browser-allocation",`provider:${k??"unknown"}`]);}}:void 0});try{await Q_({orgId:l,test:r,testInputs:m,codeEvaluator:a,logger:u,context:O});}catch(P){try{await C.browser.cleanup();}catch(k){u.error({err:k},"Failed to clean up browser after test input resolution failed");}throw P instanceof X_?new bo(bt.UserUnclassified,P.message,{cause:P}):P}return {controller:C,context:O}}function wFe({testAdvancedSettings:e,orgSettings:t,logger:o}){if(e.failureRecovery===false||e.failureRecovery===void 0&&!t?.failureRecovery)return false;if(!ms){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return o.warn(n),x.debug(n),false}return true}async function RFe({attemptInputs:e,attemptFixtures:t,attemptMetadata:o,runFixtures:n,recordVideo:r,stepCallbacks:i}){let{orgId:a,userId:s,runId:l}=o,{runTracer:c,runGroupTracer:u,project:d,apiClient:m}=n,{controller:p,context:h,codeEvaluator:g,storageClient:f,cacheStorage:y,logger:b,usageTracker:S,tracer:A}=t,{test:T,orgSettings:v}=e;b.info(`Running test '${T.name}' locally (run link: https://app.momentic.ai/runs/${l})`);let R={controller:p,storage:f,cacheStorage:y,usageTracker:S,context:h,logger:b,codeEvaluator:g},I={orgId:a,userId:s,runId:l,testMetadata:T,steps:T.steps,beforeSteps:T.beforeSteps,afterSteps:T.afterSteps,orgSettings:v},C={collectDebugData:true,reinitializeBrowser:true,disableHealing:!await wFe({testAdvancedSettings:T.advanced,orgSettings:v.ai,logger:b})};return cke({fixtures:R,inputs:I,options:C,callbacks:{step:i??{},test:{onTestComplete:async P=>{await p.browser.cleanup({saveRemoteVideos:r!=="on-fail"||P?.status!=="PASSED"}),await g.dispose(),b.debug("Test completion cleanup finished");}}},testParams:{attemptTracer:A},runParams:{runTracer:c,runGroupTracer:u,project:d,apiClient:m,captureEvent:Ep,abortSignal:n.abortSignal}})}async function CFe(e){let{testDefinition:t,traceMetadata:o}=e;return ge({name:"cli.test_run",newTrace:true,serviceName:"cli",attributes:{"momentic.org_id":e.orgId,"momentic.run_group_id":o.runGroupId,"momentic.run_id":e.runId,"momentic.test_id":t.id,"momentic.parallel":o.parallel,"momentic.worker_count":o.workerCount,"momentic.worker_index":o.workerIndex,"momentic.remote_browser_run":o.remoteBrowser},fn:async n=>{let r=await V$t(e);return n?.setAttributes({"momentic.test_status":r.status,"momentic.test_attempts":r.attempts}),r}})}async function V$t(e){let{testDefinition:t,logger:o}=e,n=new Date;try{return await W$t(e)}catch(r){Tm(r);let{customHeaders:i,envName:a,testInputs:s,urlOverride:l}=e,c={customHeaders:i,envName:a,testInputs:s,urlOverride:l},u="Fatal error running test";return o.error({err:r},u),x.error({err:r},u),IFe({err:Gi(r),parameters:c,test:t,failureReason:ie.reasonFor(r,"UnknownError"),startedAt:n,lastAttemptStartedAt:n,attempts:0,quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata})}}async function W$t(e){let{testDefinition:t,snapshot:o,project:n,apiClient:r,orgId:i,userId:a,urlOverride:s,runGroupTracer:l,logger:c,gitMetadata:u,cacheOptions:d,runId:m,testInputs:p,quarantined:h,quarantinedMetadata:g,usageTracker:f}=e,y=o?{...n.config,...o.metadata.config}:n.config,b=new LA(r,i),S=Rh({logger:c,orgId:i,client:r,gitMetadata:u,regenerateCache:d.regenerateCache,alwaysSaveCache:d.alwaysSaveCache,noCache:o?true:d.noCache,isolateCachesByEnvironment:n.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:d.bustOldestCachePercentage}),A,T,v;o?(A={envName:o.metadata.environment.envName,resolvedEnv:o.metadata.environment.resolvedEnv,environmentVariables:{...o.metadata.environment.variables},baseUrl:o.metadata.environment.baseUrl},T={steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps}):(A=rS({test:t,envNameOverride:e.envName,urlOverride:s,resolveEnv:K=>yu(K,n,c)}),{stepListsWithCaches:T,restoredStepLists:v}=await du({cacheStorage:S,logger:c,schemaVersion:t.schemaVersion,stepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,environment:A.envName,useSnapshotIdentityCache:n.config.fileFormat==="v2"}));let{envName:R,resolvedEnv:I,environmentVariables:C,baseUrl:O}=A,P=T.steps,k=T.beforeSteps??void 0,N=T.afterSteps??void 0,M=QR(t),L=M||(e.recordVideo??false);M&&e.recordVideo!==true&&c.info("Enabling video recording because the test defines run assertions");let G=await l.startRun({logger:c,runId:m,originalSteps:v??{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,testName:t.name,directory:dirname(t.relativeFilePath),testDescription:t.description??void 0,testLabels:t.labels,baseUrl:O,environmentName:R,schemaVersion:t.schemaVersion,testBundleHash:t.testBundleHash,resolvedInputs:p,quarantined:h,quarantinedReason:g?.quarantinedReason,aiSettings:y.ai,recordVideoOverride:M?true:void 0}),X=c.child(G.loggerBindings||{});Object.entries(G.envVarBindings||{}).forEach(([K,ee])=>{C[K]=ee;});let B=await K$t({...e,recordVideo:L,effectiveConfig:y,variables:C,envName:R,resolvedEnv:I,baseUrl:O,storageClient:b,tracer:G,runGroupTracer:l,logger:X,cacheStorage:S,stepsWithCaches:P,beforeStepsWithCaches:k,afterStepsWithCaches:N,usageTracker:f});return await G.finish({logger:c,status:B.status,finishedAt:B.finishedAt,failureDetails:B.failureDetails,failureReason:B.failureReason,isFlake:B.isFlake,failureRecoveryDetails:B.failureRecoveryDetails,runAssertionResults:B.runAssertionResults,usage:f.getUsageSummary()}),q$t({apiClient:r,classificationEnabled:y.ai?.classification?.enabled===true,runId:m,environment:R,status:B.status,logger:X}),{runId:G.runId,...B}}function q$t({apiClient:e,classificationEnabled:t,runId:o,environment:n,status:r,logger:i}){if(!t||r!=="PASSED"&&r!=="FAILED")return;let a=e.recordRunOutcomeForFailureRate({runId:o,environment:n,status:r==="PASSED"?"PASSED":"FAILED"}).catch(s=>{i.debug({err:s,runId:o},"Failed to report run outcome for failure rate");});X0e(a);}async function K$t(e){let{testDefinition:t,effectiveConfig:o,stepsWithCaches:n,beforeStepsWithCaches:r,afterStepsWithCaches:i,project:a,regenerateGoldenFiles:s,apiClient:l,generator:c,baseUrl:u,storageClient:d,orgId:m,userId:p,envName:h,urlOverride:g,customHeaders:f,testInputs:y,variables:b,resolvedEnv:S,retriesOverride:A,devicePixelRatio:T,logUpdate:v,tracer:R,runGroupTracer:I,logger:C,cacheStorage:O,gitMetadata:P,quarantined:k,quarantinedMetadata:N,usageTracker:M}=e,L=o,G=L.ai?.aiFailureAnalysis??false,X=new Date,B=new FA(a,l,s),K={envName:h,urlOverride:g,customHeaders:f,testInputs:y},ee={...L.browser||{},...S?.browser||{},...t.advanced||{},...e.remoteBrowserOverride?{remoteBrowser:true}:{}},z=ee.remoteBrowser===true,F=[],j,te=Math.abs(A??t.retries??o.retries??1),Ae=[],Se=[];C.info({...P,labels:t.labels,name:t.name,cwd:process.cwd()},"Starting test run using CLI");for(let De=0;De<=te;De++){let at=randomUUID(),Q=await R.startAttempt(at),Ce=C.child(Q.loggerBindings||{}),Ee={...t,steps:cloneDeep(n),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)};De!==0&&v("RETRY",`attempt ${De+1}/${te+1}`);let Rt=new Date,lt=kS({tools:new wh({httpClient:new ol({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:Ce,mode:l.mode,runner:l.runner}),fakerSeed:L.advanced?.fakerConstantSeed?PC:void 0})}),de;try{let{controller:Ke,context:Yt}=await EFe({tracer:Q,runId:R.runId,runAttemptId:at,runGroupId:e.traceMetadata.runGroupId,baseUrl:u,envName:h,apiClient:l,devicePixelRatio:T,logger:Ce,storageClient:d,codeEvaluator:lt,test:Ee,generator:c,orgId:m,variables:b,customHeaders:f,testInputs:y,localBrowserConfig:ee,browserTypeOverride:e.browserTypeOverride,attemptedRemoteBrowserProviders:F,browserFleetRegion:e.browserFleetRegion,abortSignal:e.abortSignal,aiSettings:{...L.ai||{},...Ee.advanced||{}},visualDiffScreenshotStorage:B});e.abortSignal&&(e.abortSignal.aborted?Ke.executeAbortController.abort():(de=()=>{Ke.executeAbortController.abort();},e.abortSignal.addEventListener("abort",de,{once:!0}))),j=await RFe({attemptMetadata:{attemptNumber:De+1,orgId:m,userId:p,runId:R.runId},attemptFixtures:{logger:Ce,storageClient:d,cacheStorage:O,usageTracker:M,codeEvaluator:lt,context:Yt,controller:Ke,tracer:Q},attemptInputs:{test:Ee,orgSettings:L},runFixtures:{runTracer:R,runGroupTracer:I,project:a,apiClient:l,abortSignal:e.abortSignal},recordVideo:e.recordVideo??!1,stepCallbacks:{onStepStart:e.onStepStart,onStepEnd:e.onStepEnd,onSectionStart:e.onSectionStart}});let pt=new Date,pe={logger:C,cacheStorage:O,orgId:m,testId:t.id,environment:h,originalStepsWithCaches:{steps:cloneDeep(n),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)},updatedStepsWithCaches:{steps:Ee.steps,beforeSteps:Ee.beforeSteps,afterSteps:Ee.afterSteps}};await Pb({logger:C,cacheStorage:O,orgId:m,testId:t.id,environment:h,stepLists:pe.updatedStepsWithCaches,useSnapshotIdentityCache:a.config.fileFormat==="v2"}),j?.status==="PASSED"||j?.status==="CANCELLED"&&o.advanced?.saveCacheOnCancel?await kb(pe):j?.status==="FAILED"&&De===te&&await qv(pe),await Q.finish({logger:Ce,result:j});let ve;if(j.status==="PASSED"&&QR(t)){e.onStepStart?.(SZ);let Co=await IIe({runAssertions:t.runAssertions??[],orgId:m,project:a,generator:c,apiClient:l,runTracer:R,runGroupTracer:I,logger:Ce,testPlatform:"web",captureEvent:Ep,abortSignal:e.abortSignal});pt=new Date,Co&&(Se.push(Co),ve=TZ(Co.evaluations));}let dt=Se.length>0?{attempts:Se}:void 0;Ae.unshift(ve!==void 0?"FAILED":j.status);let Ze=await sFe({orgId:m,codeEvaluator:lt,logger:Ce,outputDefinitions:t.outputs??[],testContext:Yt}),an=wZ(Ae),ct=De+1;if(j.status!=="FAILED"&&ve===void 0)return {...j,runAttemptId:at,parameters:K,test:Ee,filePath:Ee.relativeFilePath,startedAt:X,lastAttemptStartedAt:Rt,finishedAt:pt,attempts:ct,baseUrl:u,outputs:Ze,isFlake:an,runAssertionResults:dt,quarantined:k,quarantinedMetadata:N,usedRemoteBrowser:z};let lo=j.failedStepResult,mi=ve??(lo?.message||"Unknown failure"),Or=ve?"AssertionFailureError":lo?.failureReason??SP(mi)??"UnknownError",Pr=Ce.child({failureReason:Or,errorMessage:mi,numAttempts:(te+1).toString(),name:Ee.name});if(De<te){Pr.warn(`Retrying failed execution attempt for run: ${mi}`);continue}Pr.error({usedRemoteBrowser:z},`Test failed after all exhausting attempts: ${mi}`);let Oa=new Error(mi),Os={errorMessage:mi,errorStack:Oa.stack},mo;if(L.ai?.classification?.enabled===!0){let Co=lo?.failureClassification;Co||(e.onStepStart?.(xp),Co=await CB({runTracer:R,runGroupTracer:I,outputDir:e.outputDir,orgId:m,project:a,generator:c,apiClient:l,logger:C,testPlatform:"web",aiSettings:L.ai,captureEvent:Ep,abortSignal:e.abortSignal,failedStepMessage:ve??lo?.message,runAssertionResults:dt})),Co&&(mo=Co.classification.category,Or=Co.classification.category,Os.classification={reason:Co.classification.category,secondaryCategories:Co.classification.secondaryCategories,summary:Co.classification.reasoning,recoverable:Co.classification.recoverable,confidence:Co.classification.confidence,action:Co.action,citations:Co.classification.citations,cache:Co.classification.cache,source:"v2"});}else if(G){let Co;try{if(j.results&&j.results.length>0){e.onStepStart?.(xp);let{classification:Qo,aiFailureReason:it}=await Lce({logger:Ce,browserStateStorage:Q,generator:c,fullResults:j,failureReason:Or,error:Oa,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Co=Qo,mo=it;}}catch(Qo){Ce.warn({err:Qo},"Failed to classify test results");}Co&&(Os.classification=Co,Or=mo??Or,Os.classification.source="v1");}return {...j,status:"FAILED",runAttemptId:at,parameters:K,failureDetails:Os,failureReason:Or,test:Ee,filePath:Ee.relativeFilePath,startedAt:X,lastAttemptStartedAt:Rt,finishedAt:pt,attempts:De+1,baseUrl:u,outputs:Ze,runAssertionResults:dt,quarantined:k,quarantinedMetadata:N,usedRemoteBrowser:z}}catch(Ke){let Yt=`Encountered fatal platform error while running test '${Ee.name}'`;return Ce.error({err:Ke},Yt),x.error({err:Ke},Yt),await Q.finish({logger:Ce,result:{status:"FAILED"}}),IFe({err:Gi(Ke),parameters:K,test:Ee,failureReason:ie.reasonFor(Ke,"InternalPlatformError"),startedAt:X,lastAttemptStartedAt:Rt,attempts:De+1,quarantined:k,quarantinedMetadata:N,runAttemptId:at,baseUrl:u,usedRemoteBrowser:z})}finally{de&&e.abortSignal?.removeEventListener("abort",de);}}throw new Error("This code should not be reachable")}function IFe({err:e,parameters:t,test:o,failureReason:n,startedAt:r,lastAttemptStartedAt:i,attempts:a,quarantined:s,quarantinedMetadata:l,runAttemptId:c,baseUrl:u,usedRemoteBrowser:d}){return {status:"FAILED",results:[],parameters:t,test:o,filePath:o.relativeFilePath,failureReason:n,failureDetails:{errorMessage:e.message,errorStack:e.stack},startedAt:r,lastAttemptStartedAt:i,finishedAt:new Date,attempts:a,outputs:{},quarantined:s,quarantinedMetadata:l,runAttemptId:c,baseUrl:u,usedRemoteBrowser:d}}var xFe=3e4;async function _w({timeoutMinutes:e,cancel:t,run:o}){let n=()=>void t("SIGINT received"),r=()=>void t("SIGTERM received");Cw(),process.once("SIGINT",n),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 o()}finally{process.off("SIGINT",n),process.off("SIGTERM",r),clearTimeout(i);}}var xw=class{constructor(t){this.params=t;}runQueue={};runResults=[];cancelledRunsById=new Map;cancelled=false;cancellationReason;async cancel(t,o=true){if(this.cancelled)return;this.cancelled=true,this.cancellationReason=t;for(let r of Object.values(this.runQueue))r.done||r.abortController.abort();o&&await ye(Promise.allSettled(Object.values(this.runQueue).map(r=>r.promise)),{milliseconds:xFe}).catch(()=>{this.params.runGroupLogger.warn(`Graceful shutdown timeout of ${xFe}ms reached while waiting for running tests to settle.`);});let n=new Set(this.runResults.map(r=>r.runId).filter(r=>!!r));for(let r of Object.values(this.runQueue)){if(r.done||n.has(r.activeRun.runId))continue;let{activeRun:i}=r,a={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,a);}}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:o,reporter:n,runGroupTracer:r,runGroupLogger:i,logger:a,project:s,client:l,generator:c,orgId:u,userId:d,devicePixelRatio:m,outputDir:p,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:b,gitMetadata:S,cacheOptions:A,browserTypeOverride:T,remoteBrowserOverride:v,browserFleetRegion:R,onResult:I,onFatal:C}=this.params,O=0,P=true;for(;P;){let k=Object.values(this.runQueue);if(k.length===o&&await Promise.race(k.map(X=>X.promise)),this.cancelled){P=false;continue}let N=await t();if(N===void 0){P=false;continue}let M=`test-${O++}`,L={...N,startedAt:new Date},G=new AbortController;this.runQueue[M]={done:false,activeRun:L,abortController:G,promise:(async({inputs:X,quarantined:B,quarantinedMetadata:K,testDefinition:ee,snapshot:z,runId:F})=>{let j=ee.relativeFilePath.includes("..")?ee.fullFilePath:ee.relativeFilePath;n.onTestBegin(j);let te=i.child({testId:ee.id,runId:F}),Ae=new ih({logger:te,reporter:new Th(l),runType:"test-run",platform:"WEB",runId:F,runGroupId:r.runGroupMetadata.id,envName:f,testMetadata:ee,suiteMetadata:void 0,runner:"test-runner"});try{let Se=await CFe({testDefinition:ee,snapshot:z,project:s,testInputs:X,quarantined:B,quarantinedMetadata:K,orgId:u,userId:d,runId:F,devicePixelRatio:m,apiClient:l,runGroupTracer:r,outputDir:p,generator:c,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:b,logUpdate:(De,at)=>n.onTestStatus(j,De,at),...pTe(n,j),logger:te,gitMetadata:S,cacheOptions:A,usageTracker:Ae,browserTypeOverride:T,remoteBrowserOverride:v,browserFleetRegion:R,recordVideo:this.params.recordVideo,abortSignal:G.signal,traceMetadata:this.params.traceMetadata});n.onTestEnd(j,Se.status,{recovered:Se.status==="PASSED"&&!!Se.failureRecoveryDetails?.attempts}),this.runResults.push(Se),I?.(Se);}catch(Se){let De=`Encountered unexpected fatal error when running test '${ee.name}'`;te.error({err:Se},De),x.error({err:Se},De),Tm(Se),C?.(Se),await this.cancel("Fatal error occurred",false);}finally{let Se=this.runQueue[M];Se&&(Se.done=true),await Ae.flush(a),delete this.runQueue[M];}})(L)};}return await Promise.allSettled(Object.values(this.runQueue).map(k=>k.promise)),{runResults:this.runResults,cancelledRunsById:this.cancelledRunsById,cancelled:this.cancelled,cancellationReason:this.cancellationReason}}};function sz(e){return createHash("sha1").update(e).digest("hex")}var J$t=["tab","view","mode","step"],X$t=[/^[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 Q$t(e){return X$t.some(t=>t.test(e))}function _Fe(e,t={}){let o;try{o=new URL(e);}catch{return e}let n=new Set(t.queryAllowlist??J$t),i=o.pathname.split("/").map(c=>c.length>0&&Q$t(c)?"{id}":c).join("/"),a=[],s=Array.from(o.searchParams.keys()).sort();for(let c of s){if(!n.has(c))continue;let u=o.searchParams.getAll(c).sort();for(let d of u)a.push(`${encodeURIComponent(c)}=${encodeURIComponent(d)}`);}let l=a.length>0?`?${a.join("&")}`:"";return `${o.protocol}//${o.host}${i}${l}`}var z6=new Set(["id","name","role","type","href","for","placeholder","aria-label","data-testid"]),Z$t=/^[A-Za-z0-9_-]{16,256}$|^:r[0-9a-z]{1,32}:$/,e1t=[/\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],OFe=new Set(["h1","h2","h3","h4","h5","h6"]),t1t=new Set(["input","select","textarea"]);function o1t(e){let t=e;for(let o of e1t)t=t.replace(o,"{id}");return t}function PFe(e){return o1t(e).toLowerCase().replace(/\s+/g," ").trim().replace(/[.,:;!?]+$/u,"").replace(/\s*\d+\s*$/u,"").trim()}function n1t(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 r1t(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":Z$t.test(t)?"@gen":PFe(t)}function kFe(e,t,o){let n=e.tag.toLowerCase(),r=(e.role??e.attributes?.role)?.toLowerCase(),i=Math.min(Math.floor(t/4),6),a=`<${n}@${i}`;if(r!==void 0&&(a+=` role=${r}`),e.attributes!==void 0){let l=Object.keys(e.attributes).filter(c=>z6.has(c.toLowerCase())).sort();for(let c of l){let u=c.toLowerCase();if(u==="role")continue;let d=e.attributes[c];if(d===void 0)continue;let m=r1t(u,d);a+=` ${u}=${m}`;}}o.tokens.push(a);let s=e.text?.trim();s!==void 0&&s.length>0&&(r==="button"||r==="link"||r==="heading"||n==="button"||n==="a"||n==="label"||OFe.has(n)?o.tokens.push(`label=${PFe(s)}`):o.tokens.push(n1t(s))),(n==="button"||r==="button")&&(o.counts.buttons+=1),(n==="a"||r==="link")&&(o.counts.links+=1),(t1t.has(n)||r==="textbox"||r==="combobox")&&(o.counts.formFields+=1),(OFe.has(n)||r==="heading")&&(o.counts.headings+=1);for(let l of e.children??[])kFe(l,t+1,o);}function MFe(e){let t={tokens:[],counts:{buttons:0,links:0,formFields:0,headings:0}};return kFe(e,0,t),{tokens:t.tokens,counts:t.counts}}function LFe(e,t){let o=new TextEncoder().encode(e),n=o.length,r=Math.floor(n/4),i=t>>>0,a=3432918353,s=461845907;for(let d=0;d<r;d++){let m=d*4,p=o[m]|o[m+1]<<8|o[m+2]<<16|o[m+3]<<24;p=Math.imul(p,a),p=p<<15|p>>>17,p=Math.imul(p,s),i^=p,i=i<<13|i>>>19,i=Math.imul(i,5)+3864292196;}let l=0,c=n&3,u=r*4;return c===3&&(l^=o[u+2]<<16),c>=2&&(l^=o[u+1]<<8),c>=1&&(l^=o[u],l=Math.imul(l,a),l=l<<15|l>>>17,l=Math.imul(l,s),i^=l),i^=n,i^=i>>>16,i=Math.imul(i,2246822507),i^=i>>>13,i=Math.imul(i,3266489909),i^=i>>>16,i>>>0}var lz=128,i1t=4294967295,a1t=(()=>{let e=[];for(let t=0;t<lz;t++)e.push(LFe(`perm:${t}`,0));return e})();function NFe(e){let t=new Uint32Array(lz);for(let n=0;n<lz;n++)t[n]=i1t;let o=new Set(e);for(let n of o)for(let r=0;r<lz;r++){let i=LFe(n,a1t[r]);i<t[r]&&(t[r]=i);}return t}var l1t=32;function cz(e){let t=_Fe(e.url,{queryAllowlist:e.queryAllowlist}),{tokens:o,counts:n}=MFe(e.dom),r=[`url:${t}`,`counts:buttons=${n.buttons}`,`counts:links=${n.links}`,`counts:formFields=${n.formFields}`,`counts:headings=${n.headings}`,...o],i=NFe(r),a=Buffer.from(i.buffer,i.byteOffset,i.byteLength);return {fingerprintHash:createHash$1("sha256").update(a).digest("hex").slice(0,l1t),minhash:Array.from(i),canonicalUrl:t}}var c1t=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]),wr="\uFFFD",H;(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";})(H||(H={}));var yl={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function uz(e){return e>=55296&&e<=57343}function DFe(e){return e>=56320&&e<=57343}function FFe(e,t){return (e-55296)*1024+9216+t}function dz(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function mz(e){return e>=64976&&e<=65007||c1t.has(e)}var Te;(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";})(Te||(Te={}));var d1t=65536,pz=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=d1t,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,o){let{line:n,col:r,offset:i}=this,a=r+o,s=i+o;return {code:t,startLine:n,endLine:n,startCol:a,endCol:a,startOffset:s,endOffset:s}}_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 o=this.html.charCodeAt(this.pos+1);if(DFe(o))return this.pos++,this._addGap(),FFe(t,o)}else if(!this.lastChunkWritten)return this.endOfChunkHit=true,H.EOF;return this._err(Te.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,o){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=false,this.lastChunkWritten=o;}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=false;}startsWith(t,o){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,false;if(o)return this.html.startsWith(t,this.pos);for(let n=0;n<t.length;n++)if((this.html.charCodeAt(this.pos+n)|32)!==t.charCodeAt(n))return false;return true}peek(t){let o=this.pos+t;if(o>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,H.EOF;let n=this.html.charCodeAt(o);return n===H.CARRIAGE_RETURN?H.LINE_FEED:n}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,H.EOF;let t=this.html.charCodeAt(this.pos);return t===H.CARRIAGE_RETURN?(this.isEol=true,this.skipNextNewLine=true,H.LINE_FEED):t===H.LINE_FEED&&(this.isEol=true,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=false,this._addGap(),this.advance()):(this.skipNextNewLine=false,uz(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===H.LINE_FEED||t===H.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){dz(t)?this._err(Te.controlCharacterInInputStream):mz(t)&&this._err(Te.noncharacterInInputStream);}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=false;}};var hn;(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";})(hn||(hn={}));function hz(e,t){for(let o=e.attrs.length-1;o>=0;o--)if(e.attrs[o].name===t)return e.attrs[o].value;return null}var p1t=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 BFe(e){return e>=55296&&e<=57343||e>1114111?65533:p1t.get(e)??e}function UFe(e){let t=atob(e),o=t.length&-2,n=new Uint16Array(o/2);for(let r=0,i=0;r<o;r+=2){let a=t.charCodeAt(r),s=t.charCodeAt(r+1);n[i++]=a|s<<8;}return n}var H6=UFe("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 Is;(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";})(Is||(Is={}));var Xr;(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";})(Xr||(Xr={}));var jFe=32;function $6(e){return e>=Xr.ZERO&&e<=Xr.NINE}function h1t(e){return e>=Xr.UPPER_A&&e<=Xr.UPPER_F||e>=Xr.LOWER_A&&e<=Xr.LOWER_F}function g1t(e){return e>=Xr.UPPER_A&&e<=Xr.UPPER_Z||e>=Xr.LOWER_A&&e<=Xr.LOWER_Z||$6(e)}function f1t(e){return e===Xr.EQUALS||g1t(e)}var _a;(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";})(_a||(_a={}));var wp;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute";})(wp||(wp={}));var gz=class{decodeTree;emitCodePoint;errors;constructor(t,o,n){this.decodeTree=t,this.emitCodePoint=o,this.errors=n;}state=_a.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=wp.Strict;runConsumed=0;startEntity(t){this.decodeMode=t,this.state=_a.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0;}write(t,o){switch(this.state){case _a.EntityStart:return t.charCodeAt(o)===Xr.NUM?(this.state=_a.NumericStart,this.consumed+=1,this.stateNumericStart(t,o+1)):(this.state=_a.NamedEntity,this.stateNamedEntity(t,o));case _a.NumericStart:return this.stateNumericStart(t,o);case _a.NumericDecimal:return this.stateNumericDecimal(t,o);case _a.NumericHex:return this.stateNumericHex(t,o);case _a.NamedEntity:return this.stateNamedEntity(t,o)}}stateNumericStart(t,o){return o>=t.length?-1:(t.charCodeAt(o)|jFe)===Xr.LOWER_X?(this.state=_a.NumericHex,this.consumed+=1,this.stateNumericHex(t,o+1)):(this.state=_a.NumericDecimal,this.stateNumericDecimal(t,o))}stateNumericHex(t,o){for(;o<t.length;){let n=t.charCodeAt(o);if($6(n)||h1t(n)){let r=n<=Xr.NINE?n-Xr.ZERO:(n|jFe)-Xr.LOWER_A+10;this.result=this.result*16+r,this.consumed++,o++;}else return this.emitNumericEntity(n,3)}return -1}stateNumericDecimal(t,o){for(;o<t.length;){let n=t.charCodeAt(o);if($6(n))this.result=this.result*10+(n-Xr.ZERO),this.consumed++,o++;else return this.emitNumericEntity(n,2)}return -1}emitNumericEntity(t,o){if(this.consumed<=o)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===Xr.SEMI)this.consumed+=1;else if(this.decodeMode===wp.Strict)return 0;return this.emitCodePoint(BFe(this.result),this.consumed),this.errors&&(t!==Xr.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,o){let{decodeTree:n}=this,r=n[this.treeIndex],i=(r&Is.VALUE_LENGTH)>>14;for(;o<t.length;){if(i===0&&r&Is.FLAG13){let s=(r&Is.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let l=r&Is.JUMP_TABLE;if(t.charCodeAt(o)!==l)return this.result===0?0:this.emitNotTerminatedNamedEntity();o++,this.excess++,this.runConsumed++;}for(;this.runConsumed<s;){if(o>=t.length)return -1;let l=this.runConsumed-1,c=n[this.treeIndex+1+(l>>1)],u=l%2===0?c&255:c>>8&255;if(t.charCodeAt(o)!==u)return this.runConsumed=0,this.result===0?0:this.emitNotTerminatedNamedEntity();o++,this.excess++,this.runConsumed++;}this.runConsumed=0,this.treeIndex+=1+(s>>1),r=n[this.treeIndex],i=(r&Is.VALUE_LENGTH)>>14;}if(o>=t.length)break;let a=t.charCodeAt(o);if(a===Xr.SEMI&&i!==0&&r&Is.FLAG13)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=y1t(n,r,this.treeIndex+Math.max(1,i),a),this.treeIndex<0)return this.result===0||this.decodeMode===wp.Attribute&&(i===0||f1t(a))?0:this.emitNotTerminatedNamedEntity();if(r=n[this.treeIndex],i=(r&Is.VALUE_LENGTH)>>14,i!==0){if(a===Xr.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==wp.Strict&&!(r&Is.FLAG13)&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0);}o++,this.excess++;}return -1}emitNotTerminatedNamedEntity(){let{result:t,decodeTree:o}=this,n=(o[t]&Is.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,n,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,o,n){let{decodeTree:r}=this;return this.emitCodePoint(o===1?r[t]&~(Is.VALUE_LENGTH|Is.FLAG13):r[t+1],n),o===3&&this.emitCodePoint(r[t+2],n),n}end(){switch(this.state){case _a.NamedEntity:return this.result!==0&&(this.decodeMode!==wp.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case _a.NumericDecimal:return this.emitNumericEntity(0,2);case _a.NumericHex:return this.emitNumericEntity(0,3);case _a.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case _a.EntityStart:return 0}}};function y1t(e,t,o,n){let r=(t&Is.BRANCH_LENGTH)>>7,i=t&Is.JUMP_TABLE;if(r===0)return i!==0&&n===i?o:-1;if(i){let c=n-i;return c<0||c>=r?-1:e[o+c]-1}let a=r+1>>1,s=0,l=r-1;for(;s<=l;){let c=s+l>>>1,u=c>>1,m=e[o+u]>>(c&1)*8&255;if(m<n)s=c+1;else if(m>n)l=c-1;else return e[o+a+c]}return -1}var Ne;(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/";})(Ne||(Ne={}));var ag;(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";})(ag||(ag={}));var bl;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks";})(bl||(bl={}));var le;(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";})(le||(le={}));var w;(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";})(w||(w={}));var b1t=new Map([[le.A,w.A],[le.ADDRESS,w.ADDRESS],[le.ANNOTATION_XML,w.ANNOTATION_XML],[le.APPLET,w.APPLET],[le.AREA,w.AREA],[le.ARTICLE,w.ARTICLE],[le.ASIDE,w.ASIDE],[le.B,w.B],[le.BASE,w.BASE],[le.BASEFONT,w.BASEFONT],[le.BGSOUND,w.BGSOUND],[le.BIG,w.BIG],[le.BLOCKQUOTE,w.BLOCKQUOTE],[le.BODY,w.BODY],[le.BR,w.BR],[le.BUTTON,w.BUTTON],[le.CAPTION,w.CAPTION],[le.CENTER,w.CENTER],[le.CODE,w.CODE],[le.COL,w.COL],[le.COLGROUP,w.COLGROUP],[le.DD,w.DD],[le.DESC,w.DESC],[le.DETAILS,w.DETAILS],[le.DIALOG,w.DIALOG],[le.DIR,w.DIR],[le.DIV,w.DIV],[le.DL,w.DL],[le.DT,w.DT],[le.EM,w.EM],[le.EMBED,w.EMBED],[le.FIELDSET,w.FIELDSET],[le.FIGCAPTION,w.FIGCAPTION],[le.FIGURE,w.FIGURE],[le.FONT,w.FONT],[le.FOOTER,w.FOOTER],[le.FOREIGN_OBJECT,w.FOREIGN_OBJECT],[le.FORM,w.FORM],[le.FRAME,w.FRAME],[le.FRAMESET,w.FRAMESET],[le.H1,w.H1],[le.H2,w.H2],[le.H3,w.H3],[le.H4,w.H4],[le.H5,w.H5],[le.H6,w.H6],[le.HEAD,w.HEAD],[le.HEADER,w.HEADER],[le.HGROUP,w.HGROUP],[le.HR,w.HR],[le.HTML,w.HTML],[le.I,w.I],[le.IMG,w.IMG],[le.IMAGE,w.IMAGE],[le.INPUT,w.INPUT],[le.IFRAME,w.IFRAME],[le.KEYGEN,w.KEYGEN],[le.LABEL,w.LABEL],[le.LI,w.LI],[le.LINK,w.LINK],[le.LISTING,w.LISTING],[le.MAIN,w.MAIN],[le.MALIGNMARK,w.MALIGNMARK],[le.MARQUEE,w.MARQUEE],[le.MATH,w.MATH],[le.MENU,w.MENU],[le.META,w.META],[le.MGLYPH,w.MGLYPH],[le.MI,w.MI],[le.MO,w.MO],[le.MN,w.MN],[le.MS,w.MS],[le.MTEXT,w.MTEXT],[le.NAV,w.NAV],[le.NOBR,w.NOBR],[le.NOFRAMES,w.NOFRAMES],[le.NOEMBED,w.NOEMBED],[le.NOSCRIPT,w.NOSCRIPT],[le.OBJECT,w.OBJECT],[le.OL,w.OL],[le.OPTGROUP,w.OPTGROUP],[le.OPTION,w.OPTION],[le.P,w.P],[le.PARAM,w.PARAM],[le.PLAINTEXT,w.PLAINTEXT],[le.PRE,w.PRE],[le.RB,w.RB],[le.RP,w.RP],[le.RT,w.RT],[le.RTC,w.RTC],[le.RUBY,w.RUBY],[le.S,w.S],[le.SCRIPT,w.SCRIPT],[le.SEARCH,w.SEARCH],[le.SECTION,w.SECTION],[le.SELECT,w.SELECT],[le.SOURCE,w.SOURCE],[le.SMALL,w.SMALL],[le.SPAN,w.SPAN],[le.STRIKE,w.STRIKE],[le.STRONG,w.STRONG],[le.STYLE,w.STYLE],[le.SUB,w.SUB],[le.SUMMARY,w.SUMMARY],[le.SUP,w.SUP],[le.TABLE,w.TABLE],[le.TBODY,w.TBODY],[le.TEMPLATE,w.TEMPLATE],[le.TEXTAREA,w.TEXTAREA],[le.TFOOT,w.TFOOT],[le.TD,w.TD],[le.TH,w.TH],[le.THEAD,w.THEAD],[le.TITLE,w.TITLE],[le.TR,w.TR],[le.TRACK,w.TRACK],[le.TT,w.TT],[le.U,w.U],[le.UL,w.UL],[le.SVG,w.SVG],[le.VAR,w.VAR],[le.WBR,w.WBR],[le.XMP,w.XMP]]);function nT(e){var t;return (t=b1t.get(e))!==null&&t!==void 0?t:w.UNKNOWN}var Ge=w,zFe={[Ne.HTML]:new Set([Ge.ADDRESS,Ge.APPLET,Ge.AREA,Ge.ARTICLE,Ge.ASIDE,Ge.BASE,Ge.BASEFONT,Ge.BGSOUND,Ge.BLOCKQUOTE,Ge.BODY,Ge.BR,Ge.BUTTON,Ge.CAPTION,Ge.CENTER,Ge.COL,Ge.COLGROUP,Ge.DD,Ge.DETAILS,Ge.DIR,Ge.DIV,Ge.DL,Ge.DT,Ge.EMBED,Ge.FIELDSET,Ge.FIGCAPTION,Ge.FIGURE,Ge.FOOTER,Ge.FORM,Ge.FRAME,Ge.FRAMESET,Ge.H1,Ge.H2,Ge.H3,Ge.H4,Ge.H5,Ge.H6,Ge.HEAD,Ge.HEADER,Ge.HGROUP,Ge.HR,Ge.HTML,Ge.IFRAME,Ge.IMG,Ge.INPUT,Ge.LI,Ge.LINK,Ge.LISTING,Ge.MAIN,Ge.MARQUEE,Ge.MENU,Ge.META,Ge.NAV,Ge.NOEMBED,Ge.NOFRAMES,Ge.NOSCRIPT,Ge.OBJECT,Ge.OL,Ge.P,Ge.PARAM,Ge.PLAINTEXT,Ge.PRE,Ge.SCRIPT,Ge.SECTION,Ge.SELECT,Ge.SOURCE,Ge.STYLE,Ge.SUMMARY,Ge.TABLE,Ge.TBODY,Ge.TD,Ge.TEMPLATE,Ge.TEXTAREA,Ge.TFOOT,Ge.TH,Ge.THEAD,Ge.TITLE,Ge.TR,Ge.TRACK,Ge.UL,Ge.WBR,Ge.XMP]),[Ne.MATHML]:new Set([Ge.MI,Ge.MO,Ge.MN,Ge.MS,Ge.MTEXT,Ge.ANNOTATION_XML]),[Ne.SVG]:new Set([Ge.TITLE,Ge.FOREIGN_OBJECT,Ge.DESC]),[Ne.XLINK]:new Set,[Ne.XML]:new Set,[Ne.XMLNS]:new Set},_O=new Set([Ge.H1,Ge.H2,Ge.H3,Ge.H4,Ge.H5,Ge.H6]);new Set([le.STYLE,le.SCRIPT,le.XMP,le.IFRAME,le.NOEMBED,le.NOFRAMES,le.PLAINTEXT]);var V;(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";})(V||(V={}));var xs={DATA:V.DATA,RCDATA:V.RCDATA,RAWTEXT:V.RAWTEXT,SCRIPT_DATA:V.SCRIPT_DATA,PLAINTEXT:V.PLAINTEXT,CDATA_SECTION:V.CDATA_SECTION};function T1t(e){return e>=H.DIGIT_0&&e<=H.DIGIT_9}function OO(e){return e>=H.LATIN_CAPITAL_A&&e<=H.LATIN_CAPITAL_Z}function v1t(e){return e>=H.LATIN_SMALL_A&&e<=H.LATIN_SMALL_Z}function Ly(e){return v1t(e)||OO(e)}function HFe(e){return Ly(e)||T1t(e)}function fz(e){return e+32}function GFe(e){return e===H.SPACE||e===H.LINE_FEED||e===H.TABULATION||e===H.FORM_FEED}function $Fe(e){return GFe(e)||e===H.SOLIDUS||e===H.GREATER_THAN_SIGN}function A1t(e){return e===H.NULL?Te.nullCharacterReference:e>1114111?Te.characterReferenceOutsideUnicodeRange:uz(e)?Te.surrogateCharacterReference:mz(e)?Te.noncharacterCharacterReference:dz(e)||e===H.CARRIAGE_RETURN?Te.controlCharacterReference:null}var PO=class{constructor(t,o){this.options=t,this.handler=o,this.paused=false,this.inLoop=false,this.inForeignNode=false,this.lastStartTagName="",this.active=false,this.state=V.DATA,this.returnState=V.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new pz(o),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new gz(H6,(n,r)=>{this.preprocessor.pos=this.entityStartPos+r-1,this._flushCodePointConsumedAsCharacterReference(n);},o.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(Te.missingSemicolonAfterCharacterReference,1);},absenceOfDigitsInNumericCharacterReference:n=>{this._err(Te.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+n);},validateNumericCharacterReference:n=>{let r=A1t(n);r&&this._err(r,1);}}:void 0);}_err(t,o=0){var n,r;(r=(n=this.handler).onParseError)===null||r===void 0||r.call(n,this.preprocessor.getError(t,o));}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,o,n){this.active=true,this.preprocessor.write(t,o),this._runParsingLoop(),this.paused||n?.();}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 o=0;o<t;o++)this.preprocessor.advance();}_consumeSequenceIfMatch(t,o){return this.preprocessor.startsWith(t,o)?(this._advanceBy(t.length-1),true):false}_createStartTagToken(){this.currentToken={type:hn.START_TAG,tagName:"",tagID:w.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(1)};}_createEndTagToken(){this.currentToken={type:hn.END_TAG,tagName:"",tagID:w.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(2)};}_createCommentToken(t){this.currentToken={type:hn.COMMENT,data:"",location:this.getCurrentLocation(t)};}_createDoctypeToken(t){this.currentToken={type:hn.DOCTYPE,name:t,forceQuirks:false,publicId:null,systemId:null,location:this.currentLocation};}_createCharacterToken(t,o){this.currentCharacterToken={type:t,chars:o,location:this.currentLocation};}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0);}_leaveAttrName(){var t,o;let n=this.currentToken;if(hz(n,this.currentAttr.name)===null){if(n.attrs.push(this.currentAttr),n.location&&this.currentLocation){let r=(t=(o=n.location).attrs)!==null&&t!==void 0?t:o.attrs=Object.create(null);r[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue();}}else this._err(Te.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=nT(t.tagName),t.type===hn.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(Te.endTagWithAttributes),t.selfClosing&&this._err(Te.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 hn.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case hn.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case hn.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:hn.EOF,location:t}),this.active=false;}_appendCharToCurrentCharacterToken(t,o){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=o;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,o);}_emitCodePoint(t){let o=GFe(t)?hn.WHITESPACE_CHARACTER:t===H.NULL?hn.NULL_CHARACTER:hn.CHARACTER;this._appendCharToCurrentCharacterToken(o,t<65536?String.fromCharCode(t):String.fromCodePoint(t));}_emitChars(t){this._appendCharToCurrentCharacterToken(hn.CHARACTER,t);}_startCharacterReference(){this.returnState=this.state,this.state=V.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?wp.Attribute:wp.Legacy);}_isCharacterReferenceInAttribute(){return this.returnState===V.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===V.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===V.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t);}_callState(t){switch(this.state){case V.DATA:{this._stateData(t);break}case V.RCDATA:{this._stateRcdata(t);break}case V.RAWTEXT:{this._stateRawtext(t);break}case V.SCRIPT_DATA:{this._stateScriptData(t);break}case V.PLAINTEXT:{this._statePlaintext(t);break}case V.TAG_OPEN:{this._stateTagOpen(t);break}case V.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case V.TAG_NAME:{this._stateTagName(t);break}case V.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case V.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case V.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case V.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case V.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case V.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case V.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case V.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case V.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case V.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case V.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case V.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case V.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case V.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case V.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case V.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case V.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case V.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case V.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case V.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case V.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case V.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case V.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case V.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case V.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case V.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case V.BOGUS_COMMENT:{this._stateBogusComment(t);break}case V.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case V.COMMENT_START:{this._stateCommentStart(t);break}case V.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case V.COMMENT:{this._stateComment(t);break}case V.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case V.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case V.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case V.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case V.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case V.COMMENT_END:{this._stateCommentEnd(t);break}case V.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case V.DOCTYPE:{this._stateDoctype(t);break}case V.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case V.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case V.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case V.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case V.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case V.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case V.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case V.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case V.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case V.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case V.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case V.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case V.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case V.CDATA_SECTION:{this._stateCdataSection(t);break}case V.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case V.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case V.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case V.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case H.LESS_THAN_SIGN:{this.state=V.TAG_OPEN;break}case H.AMPERSAND:{this._startCharacterReference();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitCodePoint(t);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRcdata(t){switch(t){case H.AMPERSAND:{this._startCharacterReference();break}case H.LESS_THAN_SIGN:{this.state=V.RCDATA_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRawtext(t){switch(t){case H.LESS_THAN_SIGN:{this.state=V.RAWTEXT_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptData(t){switch(t){case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_statePlaintext(t){switch(t){case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateTagOpen(t){if(Ly(t))this._createStartTagToken(),this.state=V.TAG_NAME,this._stateTagName(t);else switch(t){case H.EXCLAMATION_MARK:{this.state=V.MARKUP_DECLARATION_OPEN;break}case H.SOLIDUS:{this.state=V.END_TAG_OPEN;break}case H.QUESTION_MARK:{this._err(Te.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=V.BOGUS_COMMENT,this._stateBogusComment(t);break}case H.EOF:{this._err(Te.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(Te.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=V.DATA,this._stateData(t);}}_stateEndTagOpen(t){if(Ly(t))this._createEndTagToken(),this.state=V.TAG_NAME,this._stateTagName(t);else switch(t){case H.GREATER_THAN_SIGN:{this._err(Te.missingEndTagName),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(Te.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=V.BOGUS_COMMENT,this._stateBogusComment(t);}}_stateTagName(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BEFORE_ATTRIBUTE_NAME;break}case H.SOLIDUS:{this.state=V.SELF_CLOSING_START_TAG;break}case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentTagToken();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.tagName+=wr;break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:o.tagName+=String.fromCodePoint(OO(t)?fz(t):t);}}_stateRcdataLessThanSign(t){t===H.SOLIDUS?this.state=V.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=V.RCDATA,this._stateRcdata(t));}_stateRcdataEndTagOpen(t){Ly(t)?(this.state=V.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=V.RCDATA,this._stateRcdata(t));}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,false))return !this._ensureHibernation();this._createEndTagToken();let o=this.currentToken;switch(o.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=V.BEFORE_ATTRIBUTE_NAME,false;case H.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=V.SELF_CLOSING_START_TAG,false;case H.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=V.DATA,false;default:return !this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=V.RCDATA,this._stateRcdata(t));}_stateRawtextLessThanSign(t){t===H.SOLIDUS?this.state=V.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=V.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagOpen(t){Ly(t)?(this.state=V.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=V.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=V.RAWTEXT,this._stateRawtext(t));}_stateScriptDataLessThanSign(t){switch(t){case H.SOLIDUS:{this.state=V.SCRIPT_DATA_END_TAG_OPEN;break}case H.EXCLAMATION_MARK:{this.state=V.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=V.SCRIPT_DATA,this._stateScriptData(t);}}_stateScriptDataEndTagOpen(t){Ly(t)?(this.state=V.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=V.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=V.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStart(t){t===H.HYPHEN_MINUS?(this.state=V.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=V.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStartDash(t){t===H.HYPHEN_MINUS?(this.state=V.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=V.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscaped(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataEscapedDash(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.state=V.SCRIPT_DATA_ESCAPED,this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=V.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedDashDash(t){switch(t){case H.HYPHEN_MINUS:{this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case H.GREATER_THAN_SIGN:{this.state=V.SCRIPT_DATA,this._emitChars(">");break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.state=V.SCRIPT_DATA_ESCAPED,this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=V.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedLessThanSign(t){t===H.SOLIDUS?this.state=V.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Ly(t)?(this._emitChars("<"),this.state=V.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=V.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagOpen(t){Ly(t)?(this.state=V.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=V.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=V.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(yl.SCRIPT,false)&&$Fe(this.preprocessor.peek(yl.SCRIPT.length))){this._emitCodePoint(t);for(let o=0;o<yl.SCRIPT.length;o++)this._emitCodePoint(this._consume());this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED;}else this._ensureHibernation()||(this.state=V.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscaped(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDash(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case H.HYPHEN_MINUS:{this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case H.GREATER_THAN_SIGN:{this.state=V.SCRIPT_DATA,this._emitChars(">");break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedLessThanSign(t){t===H.SOLIDUS?(this.state=V.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(yl.SCRIPT,false)&&$Fe(this.preprocessor.peek(yl.SCRIPT.length))){this._emitCodePoint(t);for(let o=0;o<yl.SCRIPT.length;o++)this._emitCodePoint(this._consume());this.state=V.SCRIPT_DATA_ESCAPED;}else this._ensureHibernation()||(this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateBeforeAttributeName(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.SOLIDUS:case H.GREATER_THAN_SIGN:case H.EOF:{this.state=V.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case H.EQUALS_SIGN:{this._err(Te.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=V.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=V.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateAttributeName(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:case H.SOLIDUS:case H.GREATER_THAN_SIGN:case H.EOF:{this._leaveAttrName(),this.state=V.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case H.EQUALS_SIGN:{this._leaveAttrName(),this.state=V.BEFORE_ATTRIBUTE_VALUE;break}case H.QUOTATION_MARK:case H.APOSTROPHE:case H.LESS_THAN_SIGN:{this._err(Te.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.currentAttr.name+=wr;break}default:this.currentAttr.name+=String.fromCodePoint(OO(t)?fz(t):t);}}_stateAfterAttributeName(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.SOLIDUS:{this.state=V.SELF_CLOSING_START_TAG;break}case H.EQUALS_SIGN:{this.state=V.BEFORE_ATTRIBUTE_VALUE;break}case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentTagToken();break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=V.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateBeforeAttributeValue(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.QUOTATION_MARK:{this.state=V.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case H.APOSTROPHE:{this.state=V.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingAttributeValue),this.state=V.DATA,this.emitCurrentTagToken();break}default:this.state=V.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t);}}_stateAttributeValueDoubleQuoted(t){switch(t){case H.QUOTATION_MARK:{this.state=V.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case H.AMPERSAND:{this._startCharacterReference();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.currentAttr.value+=wr;break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueSingleQuoted(t){switch(t){case H.APOSTROPHE:{this.state=V.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case H.AMPERSAND:{this._startCharacterReference();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.currentAttr.value+=wr;break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueUnquoted(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this._leaveAttrValue(),this.state=V.BEFORE_ATTRIBUTE_NAME;break}case H.AMPERSAND:{this._startCharacterReference();break}case H.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=V.DATA,this.emitCurrentTagToken();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.currentAttr.value+=wr;break}case H.QUOTATION_MARK:case H.APOSTROPHE:case H.LESS_THAN_SIGN:case H.EQUALS_SIGN:case H.GRAVE_ACCENT:{this._err(Te.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAfterAttributeValueQuoted(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this._leaveAttrValue(),this.state=V.BEFORE_ATTRIBUTE_NAME;break}case H.SOLIDUS:{this._leaveAttrValue(),this.state=V.SELF_CLOSING_START_TAG;break}case H.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=V.DATA,this.emitCurrentTagToken();break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this._err(Te.missingWhitespaceBetweenAttributes),this.state=V.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateSelfClosingStartTag(t){switch(t){case H.GREATER_THAN_SIGN:{let o=this.currentToken;o.selfClosing=true,this.state=V.DATA,this.emitCurrentTagToken();break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this._err(Te.unexpectedSolidusInTag),this.state=V.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateBogusComment(t){let o=this.currentToken;switch(t){case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentComment(o);break}case H.EOF:{this.emitCurrentComment(o),this._emitEOFToken();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.data+=wr;break}default:o.data+=String.fromCodePoint(t);}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(yl.DASH_DASH,true)?(this._createCommentToken(yl.DASH_DASH.length+1),this.state=V.COMMENT_START):this._consumeSequenceIfMatch(yl.DOCTYPE,false)?(this.currentLocation=this.getCurrentLocation(yl.DOCTYPE.length+1),this.state=V.DOCTYPE):this._consumeSequenceIfMatch(yl.CDATA_START,true)?this.inForeignNode?this.state=V.CDATA_SECTION:(this._err(Te.cdataInHtmlContent),this._createCommentToken(yl.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=V.BOGUS_COMMENT):this._ensureHibernation()||(this._err(Te.incorrectlyOpenedComment),this._createCommentToken(2),this.state=V.BOGUS_COMMENT,this._stateBogusComment(t));}_stateCommentStart(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.COMMENT_START_DASH;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptClosingOfEmptyComment),this.state=V.DATA;let o=this.currentToken;this.emitCurrentComment(o);break}default:this.state=V.COMMENT,this._stateComment(t);}}_stateCommentStartDash(t){let o=this.currentToken;switch(t){case H.HYPHEN_MINUS:{this.state=V.COMMENT_END;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptClosingOfEmptyComment),this.state=V.DATA,this.emitCurrentComment(o);break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+="-",this.state=V.COMMENT,this._stateComment(t);}}_stateComment(t){let o=this.currentToken;switch(t){case H.HYPHEN_MINUS:{this.state=V.COMMENT_END_DASH;break}case H.LESS_THAN_SIGN:{o.data+="<",this.state=V.COMMENT_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.data+=wr;break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+=String.fromCodePoint(t);}}_stateCommentLessThanSign(t){let o=this.currentToken;switch(t){case H.EXCLAMATION_MARK:{o.data+="!",this.state=V.COMMENT_LESS_THAN_SIGN_BANG;break}case H.LESS_THAN_SIGN:{o.data+="<";break}default:this.state=V.COMMENT,this._stateComment(t);}}_stateCommentLessThanSignBang(t){t===H.HYPHEN_MINUS?this.state=V.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=V.COMMENT,this._stateComment(t));}_stateCommentLessThanSignBangDash(t){t===H.HYPHEN_MINUS?this.state=V.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=V.COMMENT_END_DASH,this._stateCommentEndDash(t));}_stateCommentLessThanSignBangDashDash(t){t!==H.GREATER_THAN_SIGN&&t!==H.EOF&&this._err(Te.nestedComment),this.state=V.COMMENT_END,this._stateCommentEnd(t);}_stateCommentEndDash(t){let o=this.currentToken;switch(t){case H.HYPHEN_MINUS:{this.state=V.COMMENT_END;break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+="-",this.state=V.COMMENT,this._stateComment(t);}}_stateCommentEnd(t){let o=this.currentToken;switch(t){case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentComment(o);break}case H.EXCLAMATION_MARK:{this.state=V.COMMENT_END_BANG;break}case H.HYPHEN_MINUS:{o.data+="-";break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+="--",this.state=V.COMMENT,this._stateComment(t);}}_stateCommentEndBang(t){let o=this.currentToken;switch(t){case H.HYPHEN_MINUS:{o.data+="--!",this.state=V.COMMENT_END_DASH;break}case H.GREATER_THAN_SIGN:{this._err(Te.incorrectlyClosedComment),this.state=V.DATA,this.emitCurrentComment(o);break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+="--!",this.state=V.COMMENT,this._stateComment(t);}}_stateDoctype(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BEFORE_DOCTYPE_NAME;break}case H.GREATER_THAN_SIGN:{this.state=V.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case H.EOF:{this._err(Te.eofInDoctype),this._createDoctypeToken(null);let o=this.currentToken;o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingWhitespaceBeforeDoctypeName),this.state=V.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);}}_stateBeforeDoctypeName(t){if(OO(t))this._createDoctypeToken(String.fromCharCode(fz(t))),this.state=V.DOCTYPE_NAME;else switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.NULL:{this._err(Te.unexpectedNullCharacter),this._createDoctypeToken(wr),this.state=V.DOCTYPE_NAME;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypeName),this._createDoctypeToken(null);let o=this.currentToken;o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),this._createDoctypeToken(null);let o=this.currentToken;o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=V.DOCTYPE_NAME;}}_stateDoctypeName(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.AFTER_DOCTYPE_NAME;break}case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.name+=wr;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.name+=String.fromCodePoint(OO(t)?fz(t):t);}}_stateAfterDoctypeName(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(yl.PUBLIC,false)?this.state=V.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(yl.SYSTEM,false)?this.state=V.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(Te.invalidCharacterSequenceAfterDoctypeName),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t));}}_stateAfterDoctypePublicKeyword(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case H.QUOTATION_MARK:{this._err(Te.missingWhitespaceAfterDoctypePublicKeyword),o.publicId="",this.state=V.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{this._err(Te.missingWhitespaceAfterDoctypePublicKeyword),o.publicId="",this.state=V.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypePublicIdentifier),o.forceQuirks=true,this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypePublicIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypePublicIdentifier(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.QUOTATION_MARK:{o.publicId="",this.state=V.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{o.publicId="",this.state=V.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypePublicIdentifier),o.forceQuirks=true,this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypePublicIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypePublicIdentifierDoubleQuoted(t){let o=this.currentToken;switch(t){case H.QUOTATION_MARK:{this.state=V.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.publicId+=wr;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptDoctypePublicIdentifier),o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.publicId+=String.fromCodePoint(t);}}_stateDoctypePublicIdentifierSingleQuoted(t){let o=this.currentToken;switch(t){case H.APOSTROPHE:{this.state=V.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.publicId+=wr;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptDoctypePublicIdentifier),o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.publicId+=String.fromCodePoint(t);}}_stateAfterDoctypePublicIdentifier(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.QUOTATION_MARK:{this._err(Te.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{this._err(Te.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.GREATER_THAN_SIGN:{this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.QUOTATION_MARK:{o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateAfterDoctypeSystemKeyword(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case H.QUOTATION_MARK:{this._err(Te.missingWhitespaceAfterDoctypeSystemKeyword),o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{this._err(Te.missingWhitespaceAfterDoctypeSystemKeyword),o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypeSystemIdentifier(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.QUOTATION_MARK:{o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypeSystemIdentifierDoubleQuoted(t){let o=this.currentToken;switch(t){case H.QUOTATION_MARK:{this.state=V.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.systemId+=wr;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptDoctypeSystemIdentifier),o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.systemId+=String.fromCodePoint(t);}}_stateDoctypeSystemIdentifierSingleQuoted(t){let o=this.currentToken;switch(t){case H.APOSTROPHE:{this.state=V.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.systemId+=wr;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptDoctypeSystemIdentifier),o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.systemId+=String.fromCodePoint(t);}}_stateAfterDoctypeSystemIdentifier(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.GREATER_THAN_SIGN:{this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBogusDoctype(t){let o=this.currentToken;switch(t){case H.GREATER_THAN_SIGN:{this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.NULL:{this._err(Te.unexpectedNullCharacter);break}case H.EOF:{this.emitCurrentDoctype(o),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case H.RIGHT_SQUARE_BRACKET:{this.state=V.CDATA_SECTION_BRACKET;break}case H.EOF:{this._err(Te.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateCdataSectionBracket(t){t===H.RIGHT_SQUARE_BRACKET?this.state=V.CDATA_SECTION_END:(this._emitChars("]"),this.state=V.CDATA_SECTION,this._stateCdataSection(t));}_stateCdataSectionEnd(t){switch(t){case H.GREATER_THAN_SIGN:{this.state=V.DATA;break}case H.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=V.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(H.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&HFe(this.preprocessor.peek(1))?V.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState;}_stateAmbiguousAmpersand(t){HFe(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===H.SEMICOLON&&this._err(Te.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t));}};var KFe=new Set([w.DD,w.DT,w.LI,w.OPTGROUP,w.OPTION,w.P,w.RB,w.RP,w.RT,w.RTC]),VFe=new Set([...KFe,w.CAPTION,w.COLGROUP,w.TBODY,w.TD,w.TFOOT,w.TH,w.THEAD,w.TR]),yz=new Set([w.APPLET,w.CAPTION,w.HTML,w.MARQUEE,w.OBJECT,w.TABLE,w.TD,w.TEMPLATE,w.TH]),E1t=new Set([...yz,w.OL,w.UL]),w1t=new Set([...yz,w.BUTTON]),WFe=new Set([w.ANNOTATION_XML,w.MI,w.MN,w.MO,w.MS,w.MTEXT]),qFe=new Set([w.DESC,w.FOREIGN_OBJECT,w.TITLE]),R1t=new Set([w.TR,w.TEMPLATE,w.HTML]),C1t=new Set([w.TBODY,w.TFOOT,w.THEAD,w.TEMPLATE,w.HTML]),I1t=new Set([w.TABLE,w.TEMPLATE,w.HTML]),x1t=new Set([w.TD,w.TH]),bz=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,o,n){this.treeAdapter=o,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=w.UNKNOWN,this.current=t;}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===w.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===Ne.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop];}push(t,o){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=o,this.currentTagId=o,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,o,true);}pop(){let t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,true);}replace(t,o){let n=this._indexOf(t);this.items[n]=o,n===this.stackTop&&(this.current=o);}insertAfter(t,o,n){let r=this._indexOf(t)+1;this.items.splice(r,0,o),this.tagIDs.splice(r,0,n),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 o=this.stackTop+1;do o=this.tagIDs.lastIndexOf(t,o-1);while(o>0&&this.treeAdapter.getNamespaceURI(this.items[o])!==Ne.HTML);this.shortenToLength(Math.max(o,0));}shortenToLength(t){for(;this.stackTop>=t;){let o=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(o,this.stackTop<t);}}popUntilElementPopped(t){let o=this._indexOf(t);this.shortenToLength(Math.max(o,0));}popUntilPopped(t,o){let n=this._indexOfTagNames(t,o);this.shortenToLength(Math.max(n,0));}popUntilNumberedHeaderPopped(){this.popUntilPopped(_O,Ne.HTML);}popUntilTableCellPopped(){this.popUntilPopped(x1t,Ne.HTML);}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1);}_indexOfTagNames(t,o){for(let n=this.stackTop;n>=0;n--)if(t.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===o)return n;return -1}clearBackTo(t,o){let n=this._indexOfTagNames(t,o);this.shortenToLength(n+1);}clearBackToTableContext(){this.clearBackTo(I1t,Ne.HTML);}clearBackToTableBodyContext(){this.clearBackTo(C1t,Ne.HTML);}clearBackToTableRowContext(){this.clearBackTo(R1t,Ne.HTML);}remove(t){let o=this._indexOf(t);o>=0&&(o===this.stackTop?this.pop():(this.items.splice(o,1),this.tagIDs.splice(o,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,false)));}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===w.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){let o=this._indexOf(t)-1;return o>=0?this.items[o]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===w.HTML}hasInDynamicScope(t,o){for(let n=this.stackTop;n>=0;n--){let r=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case Ne.HTML:{if(r===t)return true;if(o.has(r))return false;break}case Ne.SVG:{if(qFe.has(r))return false;break}case Ne.MATHML:{if(WFe.has(r))return false;break}}}return true}hasInScope(t){return this.hasInDynamicScope(t,yz)}hasInListItemScope(t){return this.hasInDynamicScope(t,E1t)}hasInButtonScope(t){return this.hasInDynamicScope(t,w1t)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){let o=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case Ne.HTML:{if(_O.has(o))return true;if(yz.has(o))return false;break}case Ne.SVG:{if(qFe.has(o))return false;break}case Ne.MATHML:{if(WFe.has(o))return false;break}}}return true}hasInTableScope(t){for(let o=this.stackTop;o>=0;o--)if(this.treeAdapter.getNamespaceURI(this.items[o])===Ne.HTML)switch(this.tagIDs[o]){case t:return true;case w.TABLE:case w.HTML:return false}return true}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===Ne.HTML)switch(this.tagIDs[t]){case w.TBODY:case w.THEAD:case w.TFOOT:return true;case w.TABLE:case w.HTML:return false}return true}hasInSelectScope(t){for(let o=this.stackTop;o>=0;o--)if(this.treeAdapter.getNamespaceURI(this.items[o])===Ne.HTML)switch(this.tagIDs[o]){case t:return true;case w.OPTION:case w.OPTGROUP:break;default:return false}return true}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&KFe.has(this.currentTagId);)this.pop();}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&VFe.has(this.currentTagId);)this.pop();}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&VFe.has(this.currentTagId);)this.pop();}};var jd;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element";})(jd||(jd={}));var YFe={type:jd.Marker},Sz=class{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null;}_getNoahArkConditionCandidates(t,o){let n=[],r=o.length,i=this.treeAdapter.getTagName(t),a=this.treeAdapter.getNamespaceURI(t);for(let s=0;s<this.entries.length;s++){let l=this.entries[s];if(l.type===jd.Marker)break;let{element:c}=l;if(this.treeAdapter.getTagName(c)===i&&this.treeAdapter.getNamespaceURI(c)===a){let u=this.treeAdapter.getAttrList(c);u.length===r&&n.push({idx:s,attrs:u});}}return n}_ensureNoahArkCondition(t){if(this.entries.length<3)return;let o=this.treeAdapter.getAttrList(t),n=this._getNoahArkConditionCandidates(t,o);if(n.length<3)return;let r=new Map(o.map(a=>[a.name,a.value])),i=0;for(let a=0;a<n.length;a++){let s=n[a];s.attrs.every(l=>r.get(l.name)===l.value)&&(i+=1,i>=3&&this.entries.splice(s.idx,1));}}insertMarker(){this.entries.unshift(YFe);}pushElement(t,o){this._ensureNoahArkCondition(t),this.entries.unshift({type:jd.Element,element:t,token:o});}insertElementAfterBookmark(t,o){let n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:jd.Element,element:t,token:o});}removeEntry(t){let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1);}clearToLastMarker(){let t=this.entries.indexOf(YFe);t===-1?this.entries.length=0:this.entries.splice(0,t+1);}getElementEntryInScopeWithTagName(t){let o=this.entries.find(n=>n.type===jd.Marker||this.treeAdapter.getTagName(n.element)===t);return o&&o.type===jd.Element?o:null}getElementEntry(t){return this.entries.find(o=>o.type===jd.Element&&o.element===t)}};var zd={createDocument(){return {nodeName:"#document",mode:bl.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return {nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,o){return {nodeName:e,tagName:e,attrs:o,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,o){let n=e.childNodes.indexOf(o);e.childNodes.splice(n,0,t),t.parentNode=e;},setTemplateContent(e,t){e.content=t;},getTemplateContent(e){return e.content},setDocumentType(e,t,o,n){let r=e.childNodes.find(i=>i.nodeName==="#documentType");if(r)r.name=t,r.publicId=o,r.systemId=n;else {let i={nodeName:"#documentType",name:t,publicId:o,systemId:n,parentNode:null};zd.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 o=e.childNodes[e.childNodes.length-1];if(zd.isTextNode(o)){o.value+=t;return}}zd.appendChild(e,zd.createTextNode(t));},insertTextBefore(e,t,o){let n=e.childNodes[e.childNodes.indexOf(o)-1];n&&zd.isTextNode(n)?n.value+=t:zd.insertBefore(e,zd.createTextNode(t),o);},adoptAttributes(e,t){let o=new Set(e.attrs.map(n=>n.name));for(let n=0;n<t.length;n++)o.has(t[n].name)||e.attrs.push(t[n]);},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 XFe="html",_1t="about:legacy-compat",O1t="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",QFe=["+//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//"],P1t=[...QFe,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],k1t=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),ZFe=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],M1t=[...ZFe,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function JFe(e,t){return t.some(o=>e.startsWith(o))}function eBe(e){return e.name===XFe&&e.publicId===null&&(e.systemId===null||e.systemId===_1t)}function tBe(e){if(e.name!==XFe)return bl.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===O1t)return bl.QUIRKS;let{publicId:o}=e;if(o!==null){if(o=o.toLowerCase(),k1t.has(o))return bl.QUIRKS;let n=t===null?P1t:QFe;if(JFe(o,n))return bl.QUIRKS;if(n=t===null?ZFe:M1t,JFe(o,n))return bl.LIMITED_QUIRKS}return bl.NO_QUIRKS}var oBe={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},N1t="definitionurl",D1t="definitionURL",F1t=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])),B1t=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:Ne.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:Ne.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:Ne.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:Ne.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:Ne.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:Ne.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:Ne.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:Ne.XML}],["xml:space",{prefix:"xml",name:"space",namespace:Ne.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:Ne.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:Ne.XMLNS}]]),U1t=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])),j1t=new Set([w.B,w.BIG,w.BLOCKQUOTE,w.BODY,w.BR,w.CENTER,w.CODE,w.DD,w.DIV,w.DL,w.DT,w.EM,w.EMBED,w.H1,w.H2,w.H3,w.H4,w.H5,w.H6,w.HEAD,w.HR,w.I,w.IMG,w.LI,w.LISTING,w.MENU,w.META,w.NOBR,w.OL,w.P,w.PRE,w.RUBY,w.S,w.SMALL,w.SPAN,w.STRONG,w.STRIKE,w.SUB,w.SUP,w.TABLE,w.TT,w.U,w.UL,w.VAR]);function nBe(e){let t=e.tagID;return t===w.FONT&&e.attrs.some(({name:n})=>n===ag.COLOR||n===ag.SIZE||n===ag.FACE)||j1t.has(t)}function G6(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===N1t){e.attrs[t].name=D1t;break}}function V6(e){for(let t=0;t<e.attrs.length;t++){let o=F1t.get(e.attrs[t].name);o!=null&&(e.attrs[t].name=o);}}function Tz(e){for(let t=0;t<e.attrs.length;t++){let o=B1t.get(e.attrs[t].name);o&&(e.attrs[t].prefix=o.prefix,e.attrs[t].name=o.name,e.attrs[t].namespace=o.namespace);}}function rBe(e){let t=U1t.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=nT(e.tagName));}function z1t(e,t){return t===Ne.MATHML&&(e===w.MI||e===w.MO||e===w.MN||e===w.MS||e===w.MTEXT)}function H1t(e,t,o){if(t===Ne.MATHML&&e===w.ANNOTATION_XML){for(let n=0;n<o.length;n++)if(o[n].name===ag.ENCODING){let r=o[n].value.toLowerCase();return r===oBe.TEXT_HTML||r===oBe.APPLICATION_XML}}return t===Ne.SVG&&(e===w.FOREIGN_OBJECT||e===w.DESC||e===w.TITLE)}function iBe(e,t,o,n){return (!n||n===Ne.HTML)&&H1t(e,t,o)||(!n||n===Ne.MATHML)&&z1t(e,t)}var $1t="hidden",G1t=8,V1t=3,Y;(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";})(Y||(Y={}));var W1t={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},uBe=new Set([w.TABLE,w.TBODY,w.TFOOT,w.THEAD,w.TR]),sBe={scriptingEnabled:true,sourceCodeLocationInfo:false,treeAdapter:zd,onParseError:null},UO=class{constructor(t,o,n=null,r=null){this.fragmentContext=n,this.scriptHandler=r,this.currentToken=null,this.stopped=false,this.insertionMode=Y.INITIAL,this.originalInsertionMode=Y.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={...sBe,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=true),this.document=o??this.treeAdapter.createDocument(),this.tokenizer=new PO(this.options,this),this.activeFormattingElements=new Sz(this.treeAdapter),this.fragmentContextID=n?nT(this.treeAdapter.getTagName(n)):w.UNKNOWN,this._setContextModes(n??this.document,this.fragmentContextID),this.openElements=new bz(this.document,this.treeAdapter,this);}static parse(t,o){let n=new this(o);return n.tokenizer.write(t,true),n.document}static getFragmentParser(t,o){let n={...sBe,...o};t??(t=n.treeAdapter.createElement(le.TEMPLATE,Ne.HTML,[]));let r=n.treeAdapter.createElement("documentmock",Ne.HTML,[]),i=new this(n,r,t);return i.fragmentContextID===w.TEMPLATE&&i.tmplInsertionModeStack.unshift(Y.IN_TEMPLATE),i._initTokenizerForFragmentParsing(),i._insertFakeRootElement(),i._resetInsertionMode(),i._findFormInFragmentContext(),i}getFragment(){let t=this.treeAdapter.getFirstChild(this.document),o=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,o),o}_err(t,o,n){var r;if(!this.onParseError)return;let i=(r=t.location)!==null&&r!==void 0?r:W1t,a={code:o,startLine:i.startLine,startCol:i.startCol,startOffset:i.startOffset,endLine:n?i.startLine:i.endLine,endCol:n?i.startCol:i.endCol,endOffset:n?i.startOffset:i.endOffset};this.onParseError(a);}onItemPush(t,o,n){var r,i;(i=(r=this.treeAdapter).onItemPush)===null||i===void 0||i.call(r,t),n&&this.openElements.stackTop>0&&this._setContextModes(t,o);}onItemPop(t,o){var n,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(r=(n=this.treeAdapter).onItemPop)===null||r===void 0||r.call(n,t,this.openElements.current),o){let i,a;this.openElements.stackTop===0&&this.fragmentContext?(i=this.fragmentContext,a=this.fragmentContextID):{current:i,currentTagId:a}=this.openElements,this._setContextModes(i,a);}}_setContextModes(t,o){let n=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===Ne.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&t!==void 0&&o!==void 0&&!this._isIntegrationPoint(o,t);}_switchToTextParsing(t,o){this._insertElement(t,Ne.HTML),this.tokenizer.state=o,this.originalInsertionMode=this.insertionMode,this.insertionMode=Y.TEXT;}switchToPlaintextParsing(){this.insertionMode=Y.TEXT,this.originalInsertionMode=Y.IN_BODY,this.tokenizer.state=xs.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)===le.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t);}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==Ne.HTML))switch(this.fragmentContextID){case w.TITLE:case w.TEXTAREA:{this.tokenizer.state=xs.RCDATA;break}case w.STYLE:case w.XMP:case w.IFRAME:case w.NOEMBED:case w.NOFRAMES:case w.NOSCRIPT:{this.tokenizer.state=xs.RAWTEXT;break}case w.SCRIPT:{this.tokenizer.state=xs.SCRIPT_DATA;break}case w.PLAINTEXT:{this.tokenizer.state=xs.PLAINTEXT;break}}}_setDocumentType(t){let o=t.name||"",n=t.publicId||"",r=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,o,n,r),t.location){let a=this.treeAdapter.getChildNodes(this.document).find(s=>this.treeAdapter.isDocumentTypeNode(s));a&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location);}}_attachElementToTree(t,o){if(this.options.sourceCodeLocationInfo){let n=o&&{...o,startTag:o};this.treeAdapter.setNodeSourceCodeLocation(t,n);}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else {let n=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(n??this.document,t);}}_appendElement(t,o){let n=this.treeAdapter.createElement(t.tagName,o,t.attrs);this._attachElementToTree(n,t.location);}_insertElement(t,o){let n=this.treeAdapter.createElement(t.tagName,o,t.attrs);this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID);}_insertFakeElement(t,o){let n=this.treeAdapter.createElement(t,Ne.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,o);}_insertTemplate(t){let o=this.treeAdapter.createElement(t.tagName,Ne.HTML,t.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(o,n),this._attachElementToTree(o,t.location),this.openElements.push(o,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null);}_insertFakeRootElement(){let t=this.treeAdapter.createElement(le.HTML,Ne.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,w.HTML);}_appendCommentNode(t,o){let n=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(o,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,t.location);}_insertCharacters(t){let o,n;if(this._shouldFosterParentOnInsertion()?({parent:o,beforeElement:n}=this._findFosterParentingLocation(),n?this.treeAdapter.insertTextBefore(o,t.chars,n):this.treeAdapter.insertText(o,t.chars)):(o=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(o,t.chars)),!t.location)return;let r=this.treeAdapter.getChildNodes(o),i=n?r.lastIndexOf(n):r.length,a=r[i-1];if(this.treeAdapter.getNodeSourceCodeLocation(a)){let{endLine:l,endCol:c,endOffset:u}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(a,{endLine:l,endCol:c,endOffset:u});}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location);}_adoptNodes(t,o){for(let n=this.treeAdapter.getFirstChild(t);n;n=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(o,n);}_setEndLocation(t,o){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&o.location){let n=o.location,r=this.treeAdapter.getTagName(t),i=o.type===hn.END_TAG&&r===o.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,i);}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return false;let o,n;return this.openElements.stackTop===0&&this.fragmentContext?(o=this.fragmentContext,n=this.fragmentContextID):{current:o,currentTagId:n}=this.openElements,t.tagID===w.SVG&&this.treeAdapter.getTagName(o)===le.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(o)===Ne.MATHML?false:this.tokenizer.inForeignNode||(t.tagID===w.MGLYPH||t.tagID===w.MALIGNMARK)&&n!==void 0&&!this._isIntegrationPoint(n,o,Ne.HTML)}_processToken(t){switch(t.type){case hn.CHARACTER:{this.onCharacter(t);break}case hn.NULL_CHARACTER:{this.onNullCharacter(t);break}case hn.COMMENT:{this.onComment(t);break}case hn.DOCTYPE:{this.onDoctype(t);break}case hn.START_TAG:{this._processStartTag(t);break}case hn.END_TAG:{this.onEndTag(t);break}case hn.EOF:{this.onEof(t);break}case hn.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,o,n){let r=this.treeAdapter.getNamespaceURI(o),i=this.treeAdapter.getAttrList(o);return iBe(t,r,i,n)}_reconstructActiveFormattingElements(){let t=this.activeFormattingElements.entries.length;if(t){let o=this.activeFormattingElements.entries.findIndex(r=>r.type===jd.Marker||this.openElements.contains(r.element)),n=o===-1?t-1:o-1;for(let r=n;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=Y.IN_ROW;}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(w.P),this.openElements.popUntilTagNamePopped(w.P);}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case w.TR:{this.insertionMode=Y.IN_ROW;return}case w.TBODY:case w.THEAD:case w.TFOOT:{this.insertionMode=Y.IN_TABLE_BODY;return}case w.CAPTION:{this.insertionMode=Y.IN_CAPTION;return}case w.COLGROUP:{this.insertionMode=Y.IN_COLUMN_GROUP;return}case w.TABLE:{this.insertionMode=Y.IN_TABLE;return}case w.BODY:{this.insertionMode=Y.IN_BODY;return}case w.FRAMESET:{this.insertionMode=Y.IN_FRAMESET;return}case w.SELECT:{this._resetInsertionModeForSelect(t);return}case w.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case w.HTML:{this.insertionMode=this.headElement?Y.AFTER_HEAD:Y.BEFORE_HEAD;return}case w.TD:case w.TH:{if(t>0){this.insertionMode=Y.IN_CELL;return}break}case w.HEAD:{if(t>0){this.insertionMode=Y.IN_HEAD;return}break}}this.insertionMode=Y.IN_BODY;}_resetInsertionModeForSelect(t){if(t>0)for(let o=t-1;o>0;o--){let n=this.openElements.tagIDs[o];if(n===w.TEMPLATE)break;if(n===w.TABLE){this.insertionMode=Y.IN_SELECT_IN_TABLE;return}}this.insertionMode=Y.IN_SELECT;}_isElementCausesFosterParenting(t){return uBe.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 o=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case w.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(o)===Ne.HTML)return {parent:this.treeAdapter.getTemplateContent(o),beforeElement:null};break}case w.TABLE:{let n=this.treeAdapter.getParentNode(o);return n?{parent:n,beforeElement:o}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return {parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){let o=this._findFosterParentingLocation();o.beforeElement?this.treeAdapter.insertBefore(o.parent,t,o.beforeElement):this.treeAdapter.appendChild(o.parent,t);}_isSpecialElement(t,o){let n=this.treeAdapter.getNamespaceURI(t);return zFe[n].has(o)}onCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){A2t(this,t);return}switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{LO(this,t);break}case Y.BEFORE_HEAD:{NO(this,t);break}case Y.IN_HEAD:{DO(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{FO(this,t);break}case Y.AFTER_HEAD:{BO(this,t);break}case Y.IN_BODY:case Y.IN_CAPTION:case Y.IN_CELL:case Y.IN_TEMPLATE:{mBe(this,t);break}case Y.TEXT:case Y.IN_SELECT:case Y.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case Y.IN_TABLE:case Y.IN_TABLE_BODY:case Y.IN_ROW:{W6(this,t);break}case Y.IN_TABLE_TEXT:{bBe(this,t);break}case Y.IN_COLUMN_GROUP:{Az(this,t);break}case Y.AFTER_BODY:{Ez(this,t);break}case Y.AFTER_AFTER_BODY:{vz(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){v2t(this,t);return}switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{LO(this,t);break}case Y.BEFORE_HEAD:{NO(this,t);break}case Y.IN_HEAD:{DO(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{FO(this,t);break}case Y.AFTER_HEAD:{BO(this,t);break}case Y.TEXT:{this._insertCharacters(t);break}case Y.IN_TABLE:case Y.IN_TABLE_BODY:case Y.IN_ROW:{W6(this,t);break}case Y.IN_COLUMN_GROUP:{Az(this,t);break}case Y.AFTER_BODY:{Ez(this,t);break}case Y.AFTER_AFTER_BODY:{vz(this,t);break}}}onComment(t){if(this.skipNextNewLine=false,this.currentNotInHTML){q6(this,t);return}switch(this.insertionMode){case Y.INITIAL:case Y.BEFORE_HTML:case Y.BEFORE_HEAD:case Y.IN_HEAD:case Y.IN_HEAD_NO_SCRIPT:case Y.AFTER_HEAD:case Y.IN_BODY:case Y.IN_TABLE:case Y.IN_CAPTION:case Y.IN_COLUMN_GROUP:case Y.IN_TABLE_BODY:case Y.IN_ROW:case Y.IN_CELL:case Y.IN_SELECT:case Y.IN_SELECT_IN_TABLE:case Y.IN_TEMPLATE:case Y.IN_FRAMESET:case Y.AFTER_FRAMESET:{q6(this,t);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}case Y.AFTER_BODY:{Z1t(this,t);break}case Y.AFTER_AFTER_BODY:case Y.AFTER_AFTER_FRAMESET:{eGt(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=false,this.insertionMode){case Y.INITIAL:{tGt(this,t);break}case Y.BEFORE_HEAD:case Y.IN_HEAD:case Y.IN_HEAD_NO_SCRIPT:case Y.AFTER_HEAD:{this._err(t,Te.misplacedDoctype);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}}}onStartTag(t){this.skipNextNewLine=false,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,Te.nonVoidHtmlElementStartTagWithTrailingSolidus);}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?E2t(this,t):this._startTagOutsideForeignContent(t);}_startTagOutsideForeignContent(t){switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{oGt(this,t);break}case Y.BEFORE_HEAD:{rGt(this,t);break}case Y.IN_HEAD:{Hd(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{sGt(this,t);break}case Y.AFTER_HEAD:{cGt(this,t);break}case Y.IN_BODY:{_s(this,t);break}case Y.IN_TABLE:{Ow(this,t);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}case Y.IN_CAPTION:{i2t(this,t);break}case Y.IN_COLUMN_GROUP:{X6(this,t);break}case Y.IN_TABLE_BODY:{Cz(this,t);break}case Y.IN_ROW:{Iz(this,t);break}case Y.IN_CELL:{l2t(this,t);break}case Y.IN_SELECT:{vBe(this,t);break}case Y.IN_SELECT_IN_TABLE:{u2t(this,t);break}case Y.IN_TEMPLATE:{m2t(this,t);break}case Y.AFTER_BODY:{h2t(this,t);break}case Y.IN_FRAMESET:{g2t(this,t);break}case Y.AFTER_FRAMESET:{y2t(this,t);break}case Y.AFTER_AFTER_BODY:{S2t(this,t);break}case Y.AFTER_AFTER_FRAMESET:{T2t(this,t);break}}}onEndTag(t){this.skipNextNewLine=false,this.currentToken=t,this.currentNotInHTML?w2t(this,t):this._endTagOutsideForeignContent(t);}_endTagOutsideForeignContent(t){switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{nGt(this,t);break}case Y.BEFORE_HEAD:{iGt(this,t);break}case Y.IN_HEAD:{aGt(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{lGt(this,t);break}case Y.AFTER_HEAD:{uGt(this,t);break}case Y.IN_BODY:{Rz(this,t);break}case Y.TEXT:{YGt(this,t);break}case Y.IN_TABLE:{jO(this,t);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}case Y.IN_CAPTION:{a2t(this,t);break}case Y.IN_COLUMN_GROUP:{s2t(this,t);break}case Y.IN_TABLE_BODY:{K6(this,t);break}case Y.IN_ROW:{TBe(this,t);break}case Y.IN_CELL:{c2t(this,t);break}case Y.IN_SELECT:{ABe(this,t);break}case Y.IN_SELECT_IN_TABLE:{d2t(this,t);break}case Y.IN_TEMPLATE:{p2t(this,t);break}case Y.AFTER_BODY:{wBe(this,t);break}case Y.IN_FRAMESET:{f2t(this,t);break}case Y.AFTER_FRAMESET:{b2t(this,t);break}case Y.AFTER_AFTER_BODY:{vz(this,t);break}}}onEof(t){switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{LO(this,t);break}case Y.BEFORE_HEAD:{NO(this,t);break}case Y.IN_HEAD:{DO(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{FO(this,t);break}case Y.AFTER_HEAD:{BO(this,t);break}case Y.IN_BODY:case Y.IN_TABLE:case Y.IN_CAPTION:case Y.IN_COLUMN_GROUP:case Y.IN_TABLE_BODY:case Y.IN_ROW:case Y.IN_CELL:case Y.IN_SELECT:case Y.IN_SELECT_IN_TABLE:{fBe(this,t);break}case Y.TEXT:{JGt(this,t);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}case Y.IN_TEMPLATE:{EBe(this,t);break}case Y.AFTER_BODY:case Y.IN_FRAMESET:case Y.AFTER_FRAMESET:case Y.AFTER_AFTER_BODY:case Y.AFTER_AFTER_FRAMESET:{J6(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=false,t.chars.charCodeAt(0)===H.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 Y.IN_HEAD:case Y.IN_HEAD_NO_SCRIPT:case Y.AFTER_HEAD:case Y.TEXT:case Y.IN_COLUMN_GROUP:case Y.IN_SELECT:case Y.IN_SELECT_IN_TABLE:case Y.IN_FRAMESET:case Y.AFTER_FRAMESET:{this._insertCharacters(t);break}case Y.IN_BODY:case Y.IN_CAPTION:case Y.IN_CELL:case Y.IN_TEMPLATE:case Y.AFTER_BODY:case Y.AFTER_AFTER_BODY:case Y.AFTER_AFTER_FRAMESET:{dBe(this,t);break}case Y.IN_TABLE:case Y.IN_TABLE_BODY:case Y.IN_ROW:{W6(this,t);break}case Y.IN_TABLE_TEXT:{yBe(this,t);break}}}};function q1t(e,t){let o=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return o?e.openElements.contains(o.element)?e.openElements.hasInScope(t.tagID)||(o=null):(e.activeFormattingElements.removeEntry(o),o=null):gBe(e,t),o}function K1t(e,t){let o=null,n=e.openElements.stackTop;for(;n>=0;n--){let r=e.openElements.items[n];if(r===t.element)break;e._isSpecialElement(r,e.openElements.tagIDs[n])&&(o=r);}return o||(e.openElements.shortenToLength(Math.max(n,0)),e.activeFormattingElements.removeEntry(t)),o}function Y1t(e,t,o){let n=t,r=e.openElements.getCommonAncestor(t);for(let i=0,a=r;a!==o;i++,a=r){r=e.openElements.getCommonAncestor(a);let s=e.activeFormattingElements.getElementEntry(a),l=s&&i>=V1t;!s||l?(l&&e.activeFormattingElements.removeEntry(s),e.openElements.remove(a)):(a=J1t(e,s),n===t&&(e.activeFormattingElements.bookmark=s),e.treeAdapter.detachNode(n),e.treeAdapter.appendChild(a,n),n=a);}return n}function J1t(e,t){let o=e.treeAdapter.getNamespaceURI(t.element),n=e.treeAdapter.createElement(t.token.tagName,o,t.token.attrs);return e.openElements.replace(t.element,n),t.element=n,n}function X1t(e,t,o){let n=e.treeAdapter.getTagName(t),r=nT(n);if(e._isElementCausesFosterParenting(r))e._fosterParentElement(o);else {let i=e.treeAdapter.getNamespaceURI(t);r===w.TEMPLATE&&i===Ne.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,o);}}function Q1t(e,t,o){let n=e.treeAdapter.getNamespaceURI(o.element),{token:r}=o,i=e.treeAdapter.createElement(r.tagName,n,r.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,r),e.activeFormattingElements.removeEntry(o),e.openElements.remove(o.element),e.openElements.insertAfter(t,i,r.tagID);}function Y6(e,t){for(let o=0;o<G1t;o++){let n=q1t(e,t);if(!n)break;let r=K1t(e,n);if(!r)break;e.activeFormattingElements.bookmark=n;let i=Y1t(e,r,n.element),a=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(i),a&&X1t(e,a,i),Q1t(e,r,n);}}function q6(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode);}function Z1t(e,t){e._appendCommentNode(t,e.openElements.items[0]);}function eGt(e,t){e._appendCommentNode(t,e.document);}function J6(e,t){if(e.stopped=true,t.location){let o=e.fragmentContext?0:2;for(let n=e.openElements.stackTop;n>=o;n--)e._setEndLocation(e.openElements.items[n],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){let n=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(n);if(r&&!r.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){let i=e.openElements.items[1],a=e.treeAdapter.getNodeSourceCodeLocation(i);a&&!a.endTag&&e._setEndLocation(i,t);}}}}function tGt(e,t){e._setDocumentType(t);let o=t.forceQuirks?bl.QUIRKS:tBe(t);eBe(t)||e._err(t,Te.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,o),e.insertionMode=Y.BEFORE_HTML;}function kO(e,t){e._err(t,Te.missingDoctype,true),e.treeAdapter.setDocumentMode(e.document,bl.QUIRKS),e.insertionMode=Y.BEFORE_HTML,e._processToken(t);}function oGt(e,t){t.tagID===w.HTML?(e._insertElement(t,Ne.HTML),e.insertionMode=Y.BEFORE_HEAD):LO(e,t);}function nGt(e,t){let o=t.tagID;(o===w.HTML||o===w.HEAD||o===w.BODY||o===w.BR)&&LO(e,t);}function LO(e,t){e._insertFakeRootElement(),e.insertionMode=Y.BEFORE_HEAD,e._processToken(t);}function rGt(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.HEAD:{e._insertElement(t,Ne.HTML),e.headElement=e.openElements.current,e.insertionMode=Y.IN_HEAD;break}default:NO(e,t);}}function iGt(e,t){let o=t.tagID;o===w.HEAD||o===w.BODY||o===w.HTML||o===w.BR?NO(e,t):e._err(t,Te.endTagWithoutMatchingOpenElement);}function NO(e,t){e._insertFakeElement(le.HEAD,w.HEAD),e.headElement=e.openElements.current,e.insertionMode=Y.IN_HEAD,e._processToken(t);}function Hd(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.BASE:case w.BASEFONT:case w.BGSOUND:case w.LINK:case w.META:{e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;break}case w.TITLE:{e._switchToTextParsing(t,xs.RCDATA);break}case w.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,xs.RAWTEXT):(e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_HEAD_NO_SCRIPT);break}case w.NOFRAMES:case w.STYLE:{e._switchToTextParsing(t,xs.RAWTEXT);break}case w.SCRIPT:{e._switchToTextParsing(t,xs.SCRIPT_DATA);break}case w.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=false,e.insertionMode=Y.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(Y.IN_TEMPLATE);break}case w.HEAD:{e._err(t,Te.misplacedStartTagForHeadElement);break}default:DO(e,t);}}function aGt(e,t){switch(t.tagID){case w.HEAD:{e.openElements.pop(),e.insertionMode=Y.AFTER_HEAD;break}case w.BODY:case w.BR:case w.HTML:{DO(e,t);break}case w.TEMPLATE:{rT(e,t);break}default:e._err(t,Te.endTagWithoutMatchingOpenElement);}}function rT(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==w.TEMPLATE&&e._err(t,Te.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(w.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,Te.endTagWithoutMatchingOpenElement);}function DO(e,t){e.openElements.pop(),e.insertionMode=Y.AFTER_HEAD,e._processToken(t);}function sGt(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.BASEFONT:case w.BGSOUND:case w.HEAD:case w.LINK:case w.META:case w.NOFRAMES:case w.STYLE:{Hd(e,t);break}case w.NOSCRIPT:{e._err(t,Te.nestedNoscriptInHead);break}default:FO(e,t);}}function lGt(e,t){switch(t.tagID){case w.NOSCRIPT:{e.openElements.pop(),e.insertionMode=Y.IN_HEAD;break}case w.BR:{FO(e,t);break}default:e._err(t,Te.endTagWithoutMatchingOpenElement);}}function FO(e,t){let o=t.type===hn.EOF?Te.openElementsLeftAfterEof:Te.disallowedContentInNoscriptInHead;e._err(t,o),e.openElements.pop(),e.insertionMode=Y.IN_HEAD,e._processToken(t);}function cGt(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.BODY:{e._insertElement(t,Ne.HTML),e.framesetOk=false,e.insertionMode=Y.IN_BODY;break}case w.FRAMESET:{e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_FRAMESET;break}case w.BASE:case w.BASEFONT:case w.BGSOUND:case w.LINK:case w.META:case w.NOFRAMES:case w.SCRIPT:case w.STYLE:case w.TEMPLATE:case w.TITLE:{e._err(t,Te.abandonedHeadElementChild),e.openElements.push(e.headElement,w.HEAD),Hd(e,t),e.openElements.remove(e.headElement);break}case w.HEAD:{e._err(t,Te.misplacedStartTagForHeadElement);break}default:BO(e,t);}}function uGt(e,t){switch(t.tagID){case w.BODY:case w.HTML:case w.BR:{BO(e,t);break}case w.TEMPLATE:{rT(e,t);break}default:e._err(t,Te.endTagWithoutMatchingOpenElement);}}function BO(e,t){e._insertFakeElement(le.BODY,w.BODY),e.insertionMode=Y.IN_BODY,wz(e,t);}function wz(e,t){switch(t.type){case hn.CHARACTER:{mBe(e,t);break}case hn.WHITESPACE_CHARACTER:{dBe(e,t);break}case hn.COMMENT:{q6(e,t);break}case hn.START_TAG:{_s(e,t);break}case hn.END_TAG:{Rz(e,t);break}case hn.EOF:{fBe(e,t);break}}}function dBe(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t);}function mBe(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=false;}function dGt(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs);}function mGt(e,t){let o=e.openElements.tryPeekProperlyNestedBodyElement();o&&e.openElements.tmplCount===0&&(e.framesetOk=false,e.treeAdapter.adoptAttributes(o,t.attrs));}function pGt(e,t){let o=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&o&&(e.treeAdapter.detachNode(o),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_FRAMESET);}function hGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML);}function gGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&_O.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,Ne.HTML);}function fGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML),e.skipNextNewLine=true,e.framesetOk=false;}function yGt(e,t){let o=e.openElements.tmplCount>0;(!e.formElement||o)&&(e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML),o||(e.formElement=e.openElements.current));}function bGt(e,t){e.framesetOk=false;let o=t.tagID;for(let n=e.openElements.stackTop;n>=0;n--){let r=e.openElements.tagIDs[n];if(o===w.LI&&r===w.LI||(o===w.DD||o===w.DT)&&(r===w.DD||r===w.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==w.ADDRESS&&r!==w.DIV&&r!==w.P&&e._isSpecialElement(e.openElements.items[n],r))break}e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML);}function SGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML),e.tokenizer.state=xs.PLAINTEXT;}function TGt(e,t){e.openElements.hasInScope(w.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(w.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.framesetOk=false;}function vGt(e,t){let o=e.activeFormattingElements.getElementEntryInScopeWithTagName(le.A);o&&(Y6(e,t),e.openElements.remove(o.element),e.activeFormattingElements.removeEntry(o)),e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function AGt(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function EGt(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(w.NOBR)&&(Y6(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,Ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function wGt(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=false;}function RGt(e,t){e.treeAdapter.getDocumentMode(e.document)!==bl.QUIRKS&&e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML),e.framesetOk=false,e.insertionMode=Y.IN_TABLE;}function pBe(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Ne.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function hBe(e){let t=hz(e,ag.TYPE);return t!=null&&t.toLowerCase()===$1t}function CGt(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Ne.HTML),hBe(t)||(e.framesetOk=false),t.ackSelfClosing=true;}function IGt(e,t){e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;}function xGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._appendElement(t,Ne.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function _Gt(e,t){t.tagName=le.IMG,t.tagID=w.IMG,pBe(e,t);}function OGt(e,t){e._insertElement(t,Ne.HTML),e.skipNextNewLine=true,e.tokenizer.state=xs.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=false,e.insertionMode=Y.TEXT;}function PGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=false,e._switchToTextParsing(t,xs.RAWTEXT);}function kGt(e,t){e.framesetOk=false,e._switchToTextParsing(t,xs.RAWTEXT);}function lBe(e,t){e._switchToTextParsing(t,xs.RAWTEXT);}function MGt(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.framesetOk=false,e.insertionMode=e.insertionMode===Y.IN_TABLE||e.insertionMode===Y.IN_CAPTION||e.insertionMode===Y.IN_TABLE_BODY||e.insertionMode===Y.IN_ROW||e.insertionMode===Y.IN_CELL?Y.IN_SELECT_IN_TABLE:Y.IN_SELECT;}function LGt(e,t){e.openElements.currentTagId===w.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML);}function NGt(e,t){e.openElements.hasInScope(w.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,Ne.HTML);}function DGt(e,t){e.openElements.hasInScope(w.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(w.RTC),e._insertElement(t,Ne.HTML);}function FGt(e,t){e._reconstructActiveFormattingElements(),G6(t),Tz(t),t.selfClosing?e._appendElement(t,Ne.MATHML):e._insertElement(t,Ne.MATHML),t.ackSelfClosing=true;}function BGt(e,t){e._reconstructActiveFormattingElements(),V6(t),Tz(t),t.selfClosing?e._appendElement(t,Ne.SVG):e._insertElement(t,Ne.SVG),t.ackSelfClosing=true;}function cBe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML);}function _s(e,t){switch(t.tagID){case w.I:case w.S:case w.B:case w.U:case w.EM:case w.TT:case w.BIG:case w.CODE:case w.FONT:case w.SMALL:case w.STRIKE:case w.STRONG:{AGt(e,t);break}case w.A:{vGt(e,t);break}case w.H1:case w.H2:case w.H3:case w.H4:case w.H5:case w.H6:{gGt(e,t);break}case w.P:case w.DL:case w.OL:case w.UL:case w.DIV:case w.DIR:case w.NAV:case w.MAIN:case w.MENU:case w.ASIDE:case w.CENTER:case w.FIGURE:case w.FOOTER:case w.HEADER:case w.HGROUP:case w.DIALOG:case w.DETAILS:case w.ADDRESS:case w.ARTICLE:case w.SEARCH:case w.SECTION:case w.SUMMARY:case w.FIELDSET:case w.BLOCKQUOTE:case w.FIGCAPTION:{hGt(e,t);break}case w.LI:case w.DD:case w.DT:{bGt(e,t);break}case w.BR:case w.IMG:case w.WBR:case w.AREA:case w.EMBED:case w.KEYGEN:{pBe(e,t);break}case w.HR:{xGt(e,t);break}case w.RB:case w.RTC:{NGt(e,t);break}case w.RT:case w.RP:{DGt(e,t);break}case w.PRE:case w.LISTING:{fGt(e,t);break}case w.XMP:{PGt(e,t);break}case w.SVG:{BGt(e,t);break}case w.HTML:{dGt(e,t);break}case w.BASE:case w.LINK:case w.META:case w.STYLE:case w.TITLE:case w.SCRIPT:case w.BGSOUND:case w.BASEFONT:case w.TEMPLATE:{Hd(e,t);break}case w.BODY:{mGt(e,t);break}case w.FORM:{yGt(e,t);break}case w.NOBR:{EGt(e,t);break}case w.MATH:{FGt(e,t);break}case w.TABLE:{RGt(e,t);break}case w.INPUT:{CGt(e,t);break}case w.PARAM:case w.TRACK:case w.SOURCE:{IGt(e,t);break}case w.IMAGE:{_Gt(e,t);break}case w.BUTTON:{TGt(e,t);break}case w.APPLET:case w.OBJECT:case w.MARQUEE:{wGt(e,t);break}case w.IFRAME:{kGt(e,t);break}case w.SELECT:{MGt(e,t);break}case w.OPTION:case w.OPTGROUP:{LGt(e,t);break}case w.NOEMBED:case w.NOFRAMES:{lBe(e,t);break}case w.FRAMESET:{pGt(e,t);break}case w.TEXTAREA:{OGt(e,t);break}case w.NOSCRIPT:{e.options.scriptingEnabled?lBe(e,t):cBe(e,t);break}case w.PLAINTEXT:{SGt(e,t);break}case w.COL:case w.TH:case w.TD:case w.TR:case w.HEAD:case w.FRAME:case w.TBODY:case w.TFOOT:case w.THEAD:case w.CAPTION:case w.COLGROUP:break;default:cBe(e,t);}}function UGt(e,t){if(e.openElements.hasInScope(w.BODY)&&(e.insertionMode=Y.AFTER_BODY,e.options.sourceCodeLocationInfo)){let o=e.openElements.tryPeekProperlyNestedBodyElement();o&&e._setEndLocation(o,t);}}function jGt(e,t){e.openElements.hasInScope(w.BODY)&&(e.insertionMode=Y.AFTER_BODY,wBe(e,t));}function zGt(e,t){let o=t.tagID;e.openElements.hasInScope(o)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o));}function HGt(e){let t=e.openElements.tmplCount>0,{formElement:o}=e;t||(e.formElement=null),(o||t)&&e.openElements.hasInScope(w.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(w.FORM):o&&e.openElements.remove(o));}function $Gt(e){e.openElements.hasInButtonScope(w.P)||e._insertFakeElement(le.P,w.P),e._closePElement();}function GGt(e){e.openElements.hasInListItemScope(w.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(w.LI),e.openElements.popUntilTagNamePopped(w.LI));}function VGt(e,t){let o=t.tagID;e.openElements.hasInScope(o)&&(e.openElements.generateImpliedEndTagsWithExclusion(o),e.openElements.popUntilTagNamePopped(o));}function WGt(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped());}function qGt(e,t){let o=t.tagID;e.openElements.hasInScope(o)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o),e.activeFormattingElements.clearToLastMarker());}function KGt(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(le.BR,w.BR),e.openElements.pop(),e.framesetOk=false;}function gBe(e,t){let o=t.tagName,n=t.tagID;for(let r=e.openElements.stackTop;r>0;r--){let i=e.openElements.items[r],a=e.openElements.tagIDs[r];if(n===a&&(n!==w.UNKNOWN||e.treeAdapter.getTagName(i)===o)){e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.stackTop>=r&&e.openElements.shortenToLength(r);break}if(e._isSpecialElement(i,a))break}}function Rz(e,t){switch(t.tagID){case w.A:case w.B:case w.I:case w.S:case w.U:case w.EM:case w.TT:case w.BIG:case w.CODE:case w.FONT:case w.NOBR:case w.SMALL:case w.STRIKE:case w.STRONG:{Y6(e,t);break}case w.P:{$Gt(e);break}case w.DL:case w.UL:case w.OL:case w.DIR:case w.DIV:case w.NAV:case w.PRE:case w.MAIN:case w.MENU:case w.ASIDE:case w.BUTTON:case w.CENTER:case w.FIGURE:case w.FOOTER:case w.HEADER:case w.HGROUP:case w.DIALOG:case w.ADDRESS:case w.ARTICLE:case w.DETAILS:case w.SEARCH:case w.SECTION:case w.SUMMARY:case w.LISTING:case w.FIELDSET:case w.BLOCKQUOTE:case w.FIGCAPTION:{zGt(e,t);break}case w.LI:{GGt(e);break}case w.DD:case w.DT:{VGt(e,t);break}case w.H1:case w.H2:case w.H3:case w.H4:case w.H5:case w.H6:{WGt(e);break}case w.BR:{KGt(e);break}case w.BODY:{UGt(e,t);break}case w.HTML:{jGt(e,t);break}case w.FORM:{HGt(e);break}case w.APPLET:case w.OBJECT:case w.MARQUEE:{qGt(e,t);break}case w.TEMPLATE:{rT(e,t);break}default:gBe(e,t);}}function fBe(e,t){e.tmplInsertionModeStack.length>0?EBe(e,t):J6(e,t);}function YGt(e,t){var o;t.tagID===w.SCRIPT&&((o=e.scriptHandler)===null||o===void 0||o.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode;}function JGt(e,t){e._err(t,Te.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t);}function W6(e,t){if(e.openElements.currentTagId!==void 0&&uBe.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=false,e.originalInsertionMode=e.insertionMode,e.insertionMode=Y.IN_TABLE_TEXT,t.type){case hn.CHARACTER:{bBe(e,t);break}case hn.WHITESPACE_CHARACTER:{yBe(e,t);break}}else zO(e,t);}function XGt(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_CAPTION;}function QGt(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_COLUMN_GROUP;}function ZGt(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(le.COLGROUP,w.COLGROUP),e.insertionMode=Y.IN_COLUMN_GROUP,X6(e,t);}function e2t(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_TABLE_BODY;}function t2t(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(le.TBODY,w.TBODY),e.insertionMode=Y.IN_TABLE_BODY,Cz(e,t);}function o2t(e,t){e.openElements.hasInTableScope(w.TABLE)&&(e.openElements.popUntilTagNamePopped(w.TABLE),e._resetInsertionMode(),e._processStartTag(t));}function n2t(e,t){hBe(t)?e._appendElement(t,Ne.HTML):zO(e,t),t.ackSelfClosing=true;}function r2t(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,Ne.HTML),e.formElement=e.openElements.current,e.openElements.pop());}function Ow(e,t){switch(t.tagID){case w.TD:case w.TH:case w.TR:{t2t(e,t);break}case w.STYLE:case w.SCRIPT:case w.TEMPLATE:{Hd(e,t);break}case w.COL:{ZGt(e,t);break}case w.FORM:{r2t(e,t);break}case w.TABLE:{o2t(e,t);break}case w.TBODY:case w.TFOOT:case w.THEAD:{e2t(e,t);break}case w.INPUT:{n2t(e,t);break}case w.CAPTION:{XGt(e,t);break}case w.COLGROUP:{QGt(e,t);break}default:zO(e,t);}}function jO(e,t){switch(t.tagID){case w.TABLE:{e.openElements.hasInTableScope(w.TABLE)&&(e.openElements.popUntilTagNamePopped(w.TABLE),e._resetInsertionMode());break}case w.TEMPLATE:{rT(e,t);break}case w.BODY:case w.CAPTION:case w.COL:case w.COLGROUP:case w.HTML:case w.TBODY:case w.TD:case w.TFOOT:case w.TH:case w.THEAD:case w.TR:break;default:zO(e,t);}}function zO(e,t){let o=e.fosterParentingEnabled;e.fosterParentingEnabled=true,wz(e,t),e.fosterParentingEnabled=o;}function yBe(e,t){e.pendingCharacterTokens.push(t);}function bBe(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=true;}function MO(e,t){let o=0;if(e.hasNonWhitespacePendingCharacterToken)for(;o<e.pendingCharacterTokens.length;o++)zO(e,e.pendingCharacterTokens[o]);else for(;o<e.pendingCharacterTokens.length;o++)e._insertCharacters(e.pendingCharacterTokens[o]);e.insertionMode=e.originalInsertionMode,e._processToken(t);}var SBe=new Set([w.CAPTION,w.COL,w.COLGROUP,w.TBODY,w.TD,w.TFOOT,w.TH,w.THEAD,w.TR]);function i2t(e,t){let o=t.tagID;SBe.has(o)?e.openElements.hasInTableScope(w.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(w.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=Y.IN_TABLE,Ow(e,t)):_s(e,t);}function a2t(e,t){let o=t.tagID;switch(o){case w.CAPTION:case w.TABLE:{e.openElements.hasInTableScope(w.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(w.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=Y.IN_TABLE,o===w.TABLE&&jO(e,t));break}case w.BODY:case w.COL:case w.COLGROUP:case w.HTML:case w.TBODY:case w.TD:case w.TFOOT:case w.TH:case w.THEAD:case w.TR:break;default:Rz(e,t);}}function X6(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.COL:{e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;break}case w.TEMPLATE:{Hd(e,t);break}default:Az(e,t);}}function s2t(e,t){switch(t.tagID){case w.COLGROUP:{e.openElements.currentTagId===w.COLGROUP&&(e.openElements.pop(),e.insertionMode=Y.IN_TABLE);break}case w.TEMPLATE:{rT(e,t);break}case w.COL:break;default:Az(e,t);}}function Az(e,t){e.openElements.currentTagId===w.COLGROUP&&(e.openElements.pop(),e.insertionMode=Y.IN_TABLE,e._processToken(t));}function Cz(e,t){switch(t.tagID){case w.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_ROW;break}case w.TH:case w.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(le.TR,w.TR),e.insertionMode=Y.IN_ROW,Iz(e,t);break}case w.CAPTION:case w.COL:case w.COLGROUP:case w.TBODY:case w.TFOOT:case w.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE,Ow(e,t));break}default:Ow(e,t);}}function K6(e,t){let o=t.tagID;switch(t.tagID){case w.TBODY:case w.TFOOT:case w.THEAD:{e.openElements.hasInTableScope(o)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE);break}case w.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE,jO(e,t));break}case w.BODY:case w.CAPTION:case w.COL:case w.COLGROUP:case w.HTML:case w.TD:case w.TH:case w.TR:break;default:jO(e,t);}}function Iz(e,t){switch(t.tagID){case w.TH:case w.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_CELL,e.activeFormattingElements.insertMarker();break}case w.CAPTION:case w.COL:case w.COLGROUP:case w.TBODY:case w.TFOOT:case w.THEAD:case w.TR:{e.openElements.hasInTableScope(w.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE_BODY,Cz(e,t));break}default:Ow(e,t);}}function TBe(e,t){switch(t.tagID){case w.TR:{e.openElements.hasInTableScope(w.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE_BODY);break}case w.TABLE:{e.openElements.hasInTableScope(w.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE_BODY,K6(e,t));break}case w.TBODY:case w.TFOOT:case w.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(w.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE_BODY,K6(e,t));break}case w.BODY:case w.CAPTION:case w.COL:case w.COLGROUP:case w.HTML:case w.TD:case w.TH:break;default:jO(e,t);}}function l2t(e,t){let o=t.tagID;SBe.has(o)?(e.openElements.hasInTableScope(w.TD)||e.openElements.hasInTableScope(w.TH))&&(e._closeTableCell(),Iz(e,t)):_s(e,t);}function c2t(e,t){let o=t.tagID;switch(o){case w.TD:case w.TH:{e.openElements.hasInTableScope(o)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=Y.IN_ROW);break}case w.TABLE:case w.TBODY:case w.TFOOT:case w.THEAD:case w.TR:{e.openElements.hasInTableScope(o)&&(e._closeTableCell(),TBe(e,t));break}case w.BODY:case w.CAPTION:case w.COL:case w.COLGROUP:case w.HTML:break;default:Rz(e,t);}}function vBe(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.OPTION:{e.openElements.currentTagId===w.OPTION&&e.openElements.pop(),e._insertElement(t,Ne.HTML);break}case w.OPTGROUP:{e.openElements.currentTagId===w.OPTION&&e.openElements.pop(),e.openElements.currentTagId===w.OPTGROUP&&e.openElements.pop(),e._insertElement(t,Ne.HTML);break}case w.HR:{e.openElements.currentTagId===w.OPTION&&e.openElements.pop(),e.openElements.currentTagId===w.OPTGROUP&&e.openElements.pop(),e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;break}case w.INPUT:case w.KEYGEN:case w.TEXTAREA:case w.SELECT:{e.openElements.hasInSelectScope(w.SELECT)&&(e.openElements.popUntilTagNamePopped(w.SELECT),e._resetInsertionMode(),t.tagID!==w.SELECT&&e._processStartTag(t));break}case w.SCRIPT:case w.TEMPLATE:{Hd(e,t);break}}}function ABe(e,t){switch(t.tagID){case w.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===w.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===w.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===w.OPTGROUP&&e.openElements.pop();break}case w.OPTION:{e.openElements.currentTagId===w.OPTION&&e.openElements.pop();break}case w.SELECT:{e.openElements.hasInSelectScope(w.SELECT)&&(e.openElements.popUntilTagNamePopped(w.SELECT),e._resetInsertionMode());break}case w.TEMPLATE:{rT(e,t);break}}}function u2t(e,t){let o=t.tagID;o===w.CAPTION||o===w.TABLE||o===w.TBODY||o===w.TFOOT||o===w.THEAD||o===w.TR||o===w.TD||o===w.TH?(e.openElements.popUntilTagNamePopped(w.SELECT),e._resetInsertionMode(),e._processStartTag(t)):vBe(e,t);}function d2t(e,t){let o=t.tagID;o===w.CAPTION||o===w.TABLE||o===w.TBODY||o===w.TFOOT||o===w.THEAD||o===w.TR||o===w.TD||o===w.TH?e.openElements.hasInTableScope(o)&&(e.openElements.popUntilTagNamePopped(w.SELECT),e._resetInsertionMode(),e.onEndTag(t)):ABe(e,t);}function m2t(e,t){switch(t.tagID){case w.BASE:case w.BASEFONT:case w.BGSOUND:case w.LINK:case w.META:case w.NOFRAMES:case w.SCRIPT:case w.STYLE:case w.TEMPLATE:case w.TITLE:{Hd(e,t);break}case w.CAPTION:case w.COLGROUP:case w.TBODY:case w.TFOOT:case w.THEAD:{e.tmplInsertionModeStack[0]=Y.IN_TABLE,e.insertionMode=Y.IN_TABLE,Ow(e,t);break}case w.COL:{e.tmplInsertionModeStack[0]=Y.IN_COLUMN_GROUP,e.insertionMode=Y.IN_COLUMN_GROUP,X6(e,t);break}case w.TR:{e.tmplInsertionModeStack[0]=Y.IN_TABLE_BODY,e.insertionMode=Y.IN_TABLE_BODY,Cz(e,t);break}case w.TD:case w.TH:{e.tmplInsertionModeStack[0]=Y.IN_ROW,e.insertionMode=Y.IN_ROW,Iz(e,t);break}default:e.tmplInsertionModeStack[0]=Y.IN_BODY,e.insertionMode=Y.IN_BODY,_s(e,t);}}function p2t(e,t){t.tagID===w.TEMPLATE&&rT(e,t);}function EBe(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(w.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):J6(e,t);}function h2t(e,t){t.tagID===w.HTML?_s(e,t):Ez(e,t);}function wBe(e,t){var o;if(t.tagID===w.HTML){if(e.fragmentContext||(e.insertionMode=Y.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===w.HTML){e._setEndLocation(e.openElements.items[0],t);let n=e.openElements.items[1];n&&!(!((o=e.treeAdapter.getNodeSourceCodeLocation(n))===null||o===void 0)&&o.endTag)&&e._setEndLocation(n,t);}}else Ez(e,t);}function Ez(e,t){e.insertionMode=Y.IN_BODY,wz(e,t);}function g2t(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.FRAMESET:{e._insertElement(t,Ne.HTML);break}case w.FRAME:{e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;break}case w.NOFRAMES:{Hd(e,t);break}}}function f2t(e,t){t.tagID===w.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==w.FRAMESET&&(e.insertionMode=Y.AFTER_FRAMESET));}function y2t(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.NOFRAMES:{Hd(e,t);break}}}function b2t(e,t){t.tagID===w.HTML&&(e.insertionMode=Y.AFTER_AFTER_FRAMESET);}function S2t(e,t){t.tagID===w.HTML?_s(e,t):vz(e,t);}function vz(e,t){e.insertionMode=Y.IN_BODY,wz(e,t);}function T2t(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.NOFRAMES:{Hd(e,t);break}}}function v2t(e,t){t.chars=wr,e._insertCharacters(t);}function A2t(e,t){e._insertCharacters(t),e.framesetOk=false;}function RBe(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==Ne.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop();}function E2t(e,t){if(nBe(t))RBe(e),e._startTagOutsideForeignContent(t);else {let o=e._getAdjustedCurrentElement(),n=e.treeAdapter.getNamespaceURI(o);n===Ne.MATHML?G6(t):n===Ne.SVG&&(rBe(t),V6(t)),Tz(t),t.selfClosing?e._appendElement(t,n):e._insertElement(t,n),t.ackSelfClosing=true;}}function w2t(e,t){if(t.tagID===w.P||t.tagID===w.BR){RBe(e),e._endTagOutsideForeignContent(t);return}for(let o=e.openElements.stackTop;o>0;o--){let n=e.openElements.items[o];if(e.treeAdapter.getNamespaceURI(n)===Ne.HTML){e._endTagOutsideForeignContent(t);break}let r=e.treeAdapter.getTagName(n);if(r.toLowerCase()===t.tagName){t.tagName=r,e.openElements.shortenToLength(o);break}}}new Set([le.AREA,le.BASE,le.BASEFONT,le.BGSOUND,le.BR,le.COL,le.EMBED,le.FRAME,le.HR,le.IMG,le.INPUT,le.KEYGEN,le.LINK,le.META,le.PARAM,le.SOURCE,le.TRACK,le.WBR]);function CBe(e,t,o){typeof e=="string"&&(o=t,t=e,e=null);let n=UO.getFragmentParser(e,o);return n.tokenizer.write(t,true),n.getFragment()}var R2t=5e3,kw=1024;function Pw(e){return typeof e.tagName=="string"&&Array.isArray(e.attrs)}function xz(e){return e.nodeName==="#text"}function _z(e,t){let o=CBe(e),n={nodesLeft:R2t};for(let a of o.childNodes)if(Pw(a)&&a.tagName.toLowerCase()==="body"){let s=t(a,n);if(s!==void 0)return s}let r=[];for(let a of o.childNodes){if(n.nodesLeft<=0)break;if(Pw(a)){let s=t(a,n);s!==void 0&&r.push(s);}}let i={tag:"body"};return r.length>0&&(i.children=r),i}var C2t=new Set(["html","head","meta","link","template","script","style","noscript","path","br","polygon","defs"]),I2t=new Set(["input","textarea","select","button","a","img","video","audio","canvas","svg","label","h1","h2","h3","h4","ol","ul","li","table","tr","td","th","form","nav","main","footer","section","article","dialog","option"]);function x2t(e,t){return I2t.has(t)?true:e.attrs.some(({name:o})=>z6.has(o.toLowerCase()))}function IBe(e,t){if(t.nodesLeft<=0)return;let o=e.tagName.toLowerCase();if(C2t.has(o))return;let n,r;for(let{name:c,value:u}of e.attrs){let d=c.toLowerCase();if(d==="role"){r=u;continue}n===void 0&&(n={}),n[d]=u;}let i,a=[];for(let c of e.childNodes){if(t.nodesLeft<=0)break;if(xz(c)){let u=c.value;if(u&&u.trim().length>0){let d=u.length>kw?u.slice(0,kw):u;i=i===void 0?d:`${i} ${d}`;}}else if(Pw(c)){let u=IBe(c,t);u!==void 0&&a.push(u);}}let s=o==="body"||x2t(e,o);if(!s&&a.length===0&&i===void 0)return;if(!s&&a.length===1&&i===void 0)return a[0];t.nodesLeft-=1;let l={tag:o};return r!==void 0&&(l.role=r),n!==void 0&&(l.attributes=n),i!==void 0&&(l.text=i),a.length>0&&(l.children=a),l}function Q6(e){return _z(e,IBe)}function xBe(e,t){if(t.nodesLeft<=0)return;t.nodesLeft-=1;let o=e.tagName.toLowerCase(),n,r;for(let{name:l,value:c}of e.attrs){let u=l.toLowerCase();if(u==="role"){r=c;continue}n===void 0&&(n={}),n[u]=c;}let i,a=[];for(let l of e.childNodes){if(t.nodesLeft<=0)break;if(xz(l)){let c=l.value;if(c&&c.trim().length>0){let u=c.length>kw?c.slice(0,kw):c;i=i===void 0?u:`${i} ${u}`;}}else if(Pw(l)){let c=xBe(l,t);c!==void 0&&a.push(c);}}let s={tag:o};return r!==void 0&&(s.role=r),n!==void 0&&(s.attributes=n),i!==void 0&&(s.text=i),a.length>0&&(s.children=a),s}function Z6(e){return _z(e,xBe)}var _2t=new Set(["PRESET_ACTION","AI_ACTION_DYNAMIC"]),iT=class{constructor(t,o,n,r,i,a){this.orgId=t;this.testId=o;this.testName=n;this.diskStorage=r;this.parentFlushResults=i;this.appGraphSink=a;}children=[];finished=false;stepFrequenciesByType={};currentResults=[];async getScreenshot(t,o){return this.diskStorage.readFile(`${Ks}/${o}.jpeg`)}async getHtmlSnapshot(t,o){return this.diskStorage.readFile(`${Ks}/${o}.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,o]of Object.entries(this.stepFrequenciesByType))zo.increment("test_step_execution",o,[`type:${t}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}flushResults(t){return this.currentResults=t,this.parentFlushResults(t)}async startStep(t,o){let{logger:n,step:r,parentStepIdChain:i}=t;this.recordStepStat(r);let a={step:r,status:"RUNNING",startedAt:new Date},s=[...o];this.currentResults=s;let l=new eX(this.orgId,this.testId,this.testName,a,this.diskStorage,n,c=>this.flushResults([...s,c]),i??[],this.appGraphSink);return this.children.push(l),l}async finish(t){this.finished||(this.finished=true,await Promise.all(this.children.map(o=>o.finishInternal({status:FZ(t.status),finishedAt:t.finishedAt}))),this.sendFinalizedStepStats());}};function O2t(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 mt(e)}}function Oz(e){return e.some(t=>t.status==="FAILED")?"FAILED":e.some(t=>t.status==="CANCELLED")?"CANCELLED":"RUNNING"}var eX=class{constructor(t,o,n,r,i,a,s,l,c){this.orgId=t;this.testId=o;this.testName=n;this.metadata=r;this.diskStorage=i;this.logger=a;this.parentFlushResults=s;this.parentStepIdChain=l;this.appGraphSink=c;this.interactionTracer=new cp({storeTraceAsset:u=>this.storeTraceAsset(u)}),lp.initializeRootTracerContext(this.interactionTracer);}children=[];finished=false;interactionTracer;pendingAssetWrites=Promise.resolve();async attachBeforeScreenshot(t){let{snapshotId:o,screenshot:n}=t;if(n){this.metadata.beforeSnapshotId=o;try{await this.diskStorage.storeFileAsync({name:`${Ks}/${o}.jpeg`,contents:n});}catch(r){this.logger.warn({err:r,snapshotId:o},"Failed to store before-step screenshot");}}}async attachAfterScreenshot(t){let{snapshotId:o,screenshot:n}=t;if(n){this.metadata.afterSnapshotId=o;try{await this.diskStorage.storeFileAsync({name:`${Ks}/${o}.jpeg`,contents:n});}catch(r){this.logger.warn({err:r,snapshotId:o},"Failed to store after-step screenshot");}}}attachBeforeHtmlSnapshot(t){let{snapshotId:o,html:n}=t;this.metadata.beforeSnapshotId=o,this.queueAssetWrite(`${o}.html`,n);}attachAfterHtmlSnapshot(t){let{snapshotId:o,html:n,fingerprintHtml:r,url:i,logger:a}=t;this.metadata.afterSnapshotId=o,this.queueAssetWrite(`${o}.html`,n),this.appGraphSink&&_2t.has(this.metadata.step.type)&&this.appGraphSink({html:r??n,archivalHtml:n,url:i,stepId:this.metadata.step.id,parentStepIdChain:[...this.parentStepIdChain],logger:a});}recordTargetAutoHeal(t){let{healType:o}=t,n=o==="AI"?"ai-target-heal":"cache-heal";zo.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:o,healedAt:new Date};}storeTraceAsset(t){this.queueAssetWrite(`${t.snapshotId}.${t.extension??"jpeg"}`,t.data);}queueAssetWrite(t,o){this.pendingAssetWrites=this.pendingAssetWrites.then(async()=>{try{await this.diskStorage.storeFileAsync({name:`${Ks}/${t}`,contents:o});}catch(n){this.logger.warn({err:n,name:t},"Failed to store run trace asset");}});}async finishInternal(t){this.finished||(this.finished=true,this.interactionTracer.finish(),await Promise.all(this.children.map(o=>o.finish({status:O2t(t.status),finishedAt:t.finishedAt})).concat(this.pendingAssetWrites)));}recordStepDuration(t,o,n){KM({durationMs:o,executor:"cli",logger:this.logger,orgId:this.orgId,resolvedStep:t,status:n});}async finish(t){!this.finished&&t.resolvedStep!==void 0&&t.durationMs!==void 0&&this.recordStepDuration(t.resolvedStep,t.durationMs,t.step.status),await this.finishInternal(t.step),t.step.trace=this.interactionTracer.getRootSpan();}getResultBuilderForCurrentStep(){let t=this.metadata.step;switch(t.type){case "RESOLVED_MODULE":return o=>({...t,status:Oz(o),startedAt:this.metadata.startedAt,finishedAt:new Date,results:o,type:"MODULE"});case "CONDITIONAL":return o=>({...t,blocks:t.blocks.map(r=>({assertion:r.assertion,steps:gc(r.steps)})),elseSteps:t.elseSteps?gc(t.elseSteps):void 0,status:Oz(o),startedAt:this.metadata.startedAt,finishedAt:new Date,results:o});case "WHILE_LOOP":return o=>({...t,steps:gc(t.steps),status:Oz(o),startedAt:this.metadata.startedAt,finishedAt:new Date,results:o});case "AI_ACTION":case "AI_ACTION_DYNAMIC":case "PRESET_ACTION":case "SECTION":return o=>({...t,status:Oz(o),startedAt:this.metadata.startedAt,finishedAt:new Date,results:o});default:return mt(t)}}async startSubSteps(){let t=this.getResultBuilderForCurrentStep(),o=new iT(this.orgId,this.testId,this.testName,this.diskStorage,n=>{let r=t(n);return this.parentFlushResults(r)});return this.children.push(o),o}};var Pz=class{constructor(t,o,n,r,i,a,s,l){this.orgId=t;this.testId=o;this.testName=n;this.runAttemptId=r;this.metadata=i;this.diskStorage=a;this.recordVideo=s;this.progressHandle=l;this.diskStorage.mkdir(Ks),this.harWriter=new Zf(this.diskStorage.createFileStream(`${Ks}/har-pages.log`),this.diskStorage.createFileStream(`${Ks}/har-entries.log`)),this.resourceUsageStream=this.diskStorage.createFileStream(`${Ks}/resource-usage.ndjson`),this.resourceUsageSampler=fae({keepSamples:false,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
4657
+ `).map(n=>n.trim()).filter(Boolean)||[];if(!(t.length===0&&o.length===0))return [{expanded:t,backtrace:o}]}function LHt(e){let t=e.status==="FAILED"?$j(e):void 0;return P0e([["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 NHt(e,t,o){let n=O0e(o.filePath);return {id:o.runId||randomUUID(),scope:e,name:o.testName,location:n,file_name:Cn__default.basename(n),result:OHt(o.status),failure_reason:kHt(o),failure_expanded:MHt(o),history:PHt(t,o.lastAttemptStartedAt,o.finishedAt),tags:LHt(o)}}function x0e(e,t,o,n,r){let i=O0e(t);return {id:randomUUID(),scope:e,name:o,location:i,file_name:Cn__default.basename(i),result:"skipped",history:{start_at:0,end_at:0,duration:0},tags:P0e([["quarantined",r?.quarantined||"false"],["failure_recovery","false"]])}}function DHt(e,t){let o=t.map(i=>NHt(e.suiteName,e.startedAt,i)),n=e.testsToSkip.map(i=>x0e(e.suiteName,i.relativeFilePath,i.name,i.id,void 0)),r=e.quarantinedTestsToSkip.map(i=>x0e(e.suiteName,i.relativeFilePath,i.name,i.id,{quarantined:"true"}));return [...o,...n,...r]}function k0e(e,t,o){let n=DHt(t,o);Un__default.writeFileSync(Cn__default.join(e,`${t.suiteName}.buildkite.json`),JSON.stringify(n,null,2));}function Rw(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 L0e(e,t,o){let n=P6(t,o);Un__default.writeFileSync(Cn__default.join(e,`${t.suiteName}.momentic.json`),JSON.stringify(n,null,2));}function P6(e,t){let o=t.map(BHt),n=[...e.testsToSkip.map(r=>M0e(r,false)),...e.quarantinedTestsToSkip.map(r=>M0e(r,true))];return CZ.parse({version:1,runGroup:{startedAt:e.startedAt.toISOString(),finishedAt:e.finishedAt.toISOString(),durationMs:e.finishedAt.getTime()-e.startedAt.getTime()},summary:UHt(o,n),runs:o,skipped:n})}function BHt(e){let t=e.status==="PASSED"&&(e.failureRecoveryDetails?.attempts??0)>0,o=e.failureDetails?.manualClassification??e.failureDetails?.classification,n=e.status==="FAILED"?{reason:e.failureReason,message:e.failureDetails?.errorMessage}:null;return {runId:e.runId,testId:e.testId,testName:e.testName,filePath:Cn__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:n,classification:o?{reasoning:o.summary,category:o.reason,citations:o.citations}:null}}function M0e(e,t){return {testId:e.id,testName:e.name,filePath:Cn__default.relative(".",e.relativeFilePath),labels:e.labels,quarantined:t}}function UHt(e,t){return {total:e.length+t.length,executed:e.length,skipped:t.length,passed:e.filter(o=>o.status==="PASSED").length,failed:e.filter(o=>o.status==="FAILED").length,cancelled:e.filter(o=>o.status==="CANCELLED").length,quarantined:e.filter(o=>o.quarantined).length+t.filter(o=>o.quarantined).length,recovered:e.filter(o=>o.recovered).length}}function N0e(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 zHt(e,t){let o=$j(e);if(t.name(e.testName).className(e.testName).file(Cn__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(n=>{t.property("dd_tags[label]",n);})),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&&N0e(t,e.quarantinedMetadata),o==="setup"&&(t.property("setup_failed","true"),t.property("dd_tags[setup_failed]","true")),o==="main"&&(t.property("main_failed","true"),t.property("dd_tags[main_failed]","true")),o==="teardown"&&(t.property("teardown_failed","true"),t.property("dd_tags[teardown_failed]","true")),e.status==="FAILED"){let n=Vd({failureReason:e.failureReason,classification:e.failureDetails?.classification,manualClassification:e.failureDetails?.manualClassification});if(n.title){let{description:r}=n;e.runId&&(r+=` Visit https://app.momentic.ai/runs/${e.runId} for more details.`),t.failure(r,n.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 HHt(e,t,o){let{suiteId:n,suiteName:r,startedAt:i,finishedAt:a,testsToSkip:s,quarantinedTestsToSkip:l,quarantinedTestsMetadata:c}=t,u=e.testSuite().name(r);n&&u.property("id",n),u.timestamp(i).property("startedAt",i.toISOString()).property("finishedAt",a.toISOString()).time((a.getTime()-i.getTime())/1e3);for(let d of o){let m=u.testCase();zHt(d,m);}for(let d of s){let m=u.testCase();m.name(d.name).className(d.name).file(Cn__default.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&m.property("baseUrl",d.baseUrl),d.labels&&(m.property("labels",d.labels.join(",")),d.labels.forEach(p=>{m.property("dd_tags[label]",p);})),m.skipped();}for(let d of l){let m=u.testCase();m.name(d.name).className(d.name).file(Cn__default.relative(".",d.relativeFilePath)).property("id",d.id);let p=c[d.id];p&&N0e(m,p),d.baseUrl&&m.property("baseUrl",d.baseUrl),d.labels&&(m.property("labels",d.labels.join(",")),d.labels.forEach(h=>{m.property("dd_tags[label]",h);})),m.skipped();}return u}function D0e(e,t,o){let n=jHt.newBuilder();HHt(n,t,o),n.writeTo(Cn__default.join(e,`${t.suiteName}.xml`));}var $Ht="insights-collector.newrelic.com",GHt="insights-collector.eu01.nr-data.net",VHt=4e3;async function k6({logger:e,config:t,params:o,runs:n,runGroupId:r,envName:i,appUrl:a,gitMetadata:s}){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=n.map(Rw),u=P6(o,c),d=F0e({...t.attributes,runGroupId:r,environment:i,suiteName:o.suiteName,gitBranch:s.gitBranchName,gitCommit:s.gitCommitSha,gitRepository:s.githubRepository??s.gitOriginUrl,ciRunUrl:WHt()}),m=u.runs.map((g,f)=>({...d,eventType:"MomenticRun",timestamp:new Date(g.finishedAt).getTime(),...F0e({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?`${a}/runs/${g.runId}`:void 0})}));m.push({...d,eventType:"MomenticRunGroup",timestamp:new Date(o.finishedAt).getTime(),startedAt:o.startedAt.toISOString(),finishedAt:o.finishedAt.toISOString(),durationMs:u.runGroup.durationMs,runGroupUrl:`${a}/run-groups/${r}`,...u.summary,passRate:u.summary.executed>0?u.summary.passed/u.summary.executed:0});let h=`https://${t.region==="EU"?GHt:$Ht}/v1/accounts/${t.accountId}/events`;try{let g=await fetch(h,{method:"POST",headers:{"Content-Type":"application/json","Api-Key":l},body:JSON.stringify(m)});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 ${m.length} events to New Relic account ${t.accountId}`);}catch(g){e.error(`Failed to send test results to New Relic: ${W(g)}`);}}function F0e(e){let t={};for(let[o,n]of Object.entries(e))n==null||n===""||(t[o]=typeof n=="string"?n.slice(0,VHt):n);return t}function WHt(){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 B0e(e){return {title:Fn(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(B0e):[]}}async function YHt(e,t,o,n){if(n.results?.length){let r=await Hj({logger:e,debugDataStorage:t,folder:o,label:"final-state",snapshotId:n.results[n.results.length-1].afterSnapshot});return r?[{name:"Final state screenshot",path:r,contentType:"image/jpeg"}]:[]}return []}async function JHt(e,t,o,n){let r;if(n.status==="FAILED"&&n.failureReason){let i=Vd({failureReason:n.failureReason,classification:n.failureDetails?.classification,manualClassification:n.failureDetails?.manualClassification});r={value:n.failureDetails?.classification?.reason??n.failureReason,message:i.description};}return {status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"interrupted":"failed",duration:n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime(),error:r,retry:n.attempts-1,steps:n.results?.map(B0e)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await YHt(e,t,o,n)}}async function XHt(e,t,o,n){return {expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await JHt(e,t,o,n)]}}async function QHt(e,t,o,n){return {tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await XHt(e,t,o,n)],id:n.runId,file:n.filePath}}function M6(e,t){return e.reduce((o,n)=>t(n)?o+1:o,0)}async function ZHt(e,t,o,n,r){return {suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(r.map(async i=>{let a=i.runId&&i.runAttemptId?t.createDebugDataReaderForRunAttempt(i.runId,i.runAttemptId):new MC;try{return await QHt(e,a,o,i)}finally{a.close();}}))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:M6(r,i=>i.status==="PASSED"),unexpected:M6(r,i=>i.status!=="PASSED"),flaky:M6(r,i=>!!i.isFlake),skipped:0}}}async function U0e(e,t,o,n,r){let i=await ZHt(e,t,o,n,r);Un__default.writeFileSync(Cn__default.join(o,`${n.suiteName}.json`),JSON.stringify(i,null,2));}async function j0e({logger:e,callbacks:t,format:o,params:n,runs:r,folder:i}){switch(existsSync(i)&&!statSync(i).isDirectory()&&(x.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}),o){case "json":{let a=r.map(Rw);L0e(i,n,a);return}case "junit":{let a=r.map(Rw);D0e(i,n,a);return}case "buildkite-json":{let a=r.map(Rw);k0e(i,n,a);return}case "allure":case "allure-json":await C0e(e,t,i,n,r);return;case "playwright-json":await U0e(e,t,i,n,r);return;default:throw new Error(`Unknown reporter format requested: '${o}'`)}}function tT(e){let t=e??s$t();return z0e()&&t===1&&x.warn("Running with --pixel-ratio=1 on a Retina screen. Viewport calculations may be incorrect; omit the flag to auto-detect."),t}function s$t(){let e=z0e(),t=e?2:1;return x.debug(`Auto-detected device pixel ratio ${t} (Mac OS Retina: ${e}).`),t}var z0e=once(()=>{if(platform()!=="darwin")return false;try{return execSync("system_profiler SPDisplaysDataType").toString().includes("Retina")}catch{return false}});async function Wj(e,t=true,o=false){let n=d$t(e),r=await c$t.which(n[0],true),i=n.slice(1),a=l$t.exec(u$t(r),i,{delay:100,silent:o});if(t)return a;a.catch(s=>{x.warn({err:s},`Background command exited with an error: ${e}`);});}var H0e="the Momentic GitHub app is missing permission to create pull requests or write branches for this repository";function m$t(e,{context:t}){return e instanceof Lo?e.rawError.includes("Resource not accessible by integration")?`Cannot create ${t} because ${H0e}.`:e.status>=400&&e.status<500?e.rawError:`Could not create ${t} due to a GitHub error.`:`Could not create ${t}: ${W(e)}`}function $0e(e){return e instanceof Lo?e.rawError.includes("Resource not accessible by integration")?H0e:e.status>=400&&e.status<500?e.rawError:"a GitHub error occurred":W(e)}function G0e(e,t){x.error(m$t(e,t));}var bt={ArgsInvalid:"MOM_ARGS_INVALID",AuthRequired:"MOM_AUTH_REQUIRED",AuthForbidden:"MOM_AUTH_FORBIDDEN",ApiError:"MOM_API_ERROR",ApiUnavailable:"MOM_API_UNAVAILABLE",ResourceNotFound:"MOM_RESOURCE_NOT_FOUND",FeatureNotEnabled:"MOM_FEATURE_NOT_ENABLED",UsageLimitReached:"MOM_USAGE_LIMIT_REACHED",ExploreIncomplete:"MOM_EXPLORE_INCOMPLETE",ProjectLintFailed:"MOM_PROJECT_LINT_FAILED",ProjectConfigError:"MOM_PROJECT_CONFIG_ERROR",ResultsRunNotFound:"MOM_RESULTS_RUN_NOT_FOUND",UserUnclassified:"MOM_USER_UNCLASSIFIED",InternalUnhandled:"MOM_INTERNAL_UNHANDLED"},p$t={[bt.ArgsInvalid]:{group:"args",retry:"no",attribution:"user-action"},[bt.AuthRequired]:{group:"auth",retry:"no",attribution:"user-action"},[bt.AuthForbidden]:{group:"auth",retry:"no",attribution:"user-action"},[bt.ApiError]:{group:"api",retry:"case-by-case",attribution:"product"},[bt.ApiUnavailable]:{group:"api",retry:"yes",attribution:"product"},[bt.ResourceNotFound]:{group:"api",retry:"no",attribution:"user-action"},[bt.FeatureNotEnabled]:{group:"auth",retry:"no",attribution:"product"},[bt.UsageLimitReached]:{group:"auth",retry:"no",attribution:"user-action"},[bt.ExploreIncomplete]:{group:"run",retry:"case-by-case",attribution:"unknown"},[bt.ProjectLintFailed]:{group:"args",retry:"no",attribution:"user-action"},[bt.ProjectConfigError]:{group:"env",retry:"no",attribution:"user-env"},[bt.ResultsRunNotFound]:{group:"args",retry:"no",attribution:"user-action"},[bt.UserUnclassified]:{group:"internal",retry:"no",attribution:"user-action"},[bt.InternalUnhandled]:{group:"internal",retry:"case-by-case",attribution:"product"}},V0e={catalog:p$t,argsCode:bt.ArgsInvalid,userCode:bt.UserUnclassified,internalCode:bt.InternalUnhandled,extraClassifier:e=>LTe(e,{authRequired:bt.AuthRequired,authForbidden:bt.AuthForbidden,apiError:bt.ApiError,apiUnavailable:bt.ApiUnavailable,resourceNotFound:bt.ResourceNotFound,projectConfigError:bt.ProjectConfigError})};function qj(e){return W0e(e,"runs","run")}function L6(e){return W0e(e,"run-groups","run group")}function W0e(e,t,o){let n=e.trim(),r=`Invalid ${o} ID: ${e}. Expected a UUID or a URL like https://app.momentic.ai/${t}/<id>.`;if(/[\s,]/.test(n))throw new bo(bt.ArgsInvalid,`${r} To pass multiple IDs, separate them with spaces as individual arguments instead of a single quoted string.`);let i=/^https?:\/\//i.test(n)?g$t(n,t,o):n;if(!z.guid().safeParse(i).success)throw new bo(bt.ArgsInvalid,r);return i}function g$t(e,t,o){let n;try{n=new URL(e);}catch{throw new bo(bt.ArgsInvalid,`Invalid ${o} URL: ${e}`)}let r=n.pathname.split("/").filter(i=>i.length>0);if(r.length!==2||r[0]!==t)throw new bo(bt.ArgsInvalid,`Could not extract ${o} ID from URL: ${e}. Expected a URL like https://app.momentic.ai/${t}/<id>.`);return r[1]}function Kj(e){return new Promise((t,o)=>{let n=[];createReadStream(e).pipe(f$t()).on("data",r=>n.push(r)).on("end",()=>t(n)).on("error",r=>o(r));})}var To="3.62.3",q0e={packageName:"momentic",currentVersion:To,changelogUrl:"https://github.com/momentic-ai/cli/releases",updateCommand:"npx momentic@latest upgrade",runUpgrade:N3__default.existsSync(Ch.join(process.cwd(),"package.json"))?e=>installPackage(`momentic@${e}`,{silent:false,dev:true}):void 0},{checkCLIVersion:zi,getLatestCLIVersion:K0e}=HSe(q0e),Y0e=e=>ATe({...q0e,logger:e});_It("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI","POSTHOG_WEB_WRITE_KEY is not set");var{captureEvent:Ep,setAnalyticsIdentity:Yj,shutdownAnalytics:J0e}=OM({writeKey:"phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",host:"https://p.momentic.ai",platform:"cli",identity:"stashed",flushImmediately:true,onIdentify:BTe});var A$t=3e3,Jj=new Set;function X0e(e){Jj.add(e),e.finally(()=>Jj.delete(e));}async function Q0e(){if(Jj.size!==0)try{await ye(Promise.allSettled([...Jj]),{milliseconds:A$t});}catch{}}async function Xj(){try{await ye(Promise.all([Q0e(),xM(),zo.flush(),J0e(),$M(),XY(),UTe()]),{milliseconds:5e3});}catch{}}async function eFe({momenticFiles:e,project:t,logger:o}){let n;try{n=await Py({repoRoot:t.rootDir??process.cwd(),mainBranch:t.config.gitMainBranch,logger:o});}catch(i){let a="Make sure the checkout has enough git history to reach the base ref (CI checkouts are often shallow by default).";throw i instanceof ng?new ae(`Could not determine the base ref to diff against for --changed. ${a}`):new ae(`--changed could not compute the git diff: ${W(i)}. ${a}`)}let r=E$t({changedFiles:n.changedFiles,repoRoot:n.repoRoot,momenticFiles:e});return x.log(r.length===0?`No changed tests or modules vs ${n.baseRef}.`:`${r.length} changed test(s) vs ${n.baseRef}.`),r.map(i=>i.fullFilePath)}function E$t({changedFiles:e,repoRoot:t,momenticFiles:o}){let n=e.filter(u=>u.status!=="D"),r=n.filter(u=>u.path.endsWith(".test.yaml")),i=n.filter(u=>u.path.endsWith(".module.yaml")),a=Object.values(o.tests),s=new Map(a.map(u=>[u.fullFilePath,u])),l=new Map;for(let u of r){let d=s.get(Ch.resolve(t,u.path));d&&!l.has(d.id)&&l.set(d.id,{fullFilePath:d.fullFilePath,relativePath:d.relativePath,reason:"test-changed"});}let c=w$t({momenticFiles:o,changedModuleFullPaths:i.map(u=>Ch.resolve(t,u.path))});if(c.size>0)for(let u of a){if(l.has(u.id))continue;let d=zI(u.fullFilePath,o);for(let m of d)if(c.has(m)){l.set(u.id,{fullFilePath:u.fullFilePath,relativePath:u.relativePath,reason:"module-changed"});break}}return Array.from(l.values())}function w$t({momenticFiles:e,changedModuleFullPaths:t}){let o=new Set(t),n=new Set;for(let[a,s]of Object.entries(e.modules))o.has(s.fullFilePath)&&n.add(a);if(n.size===0)return n;let r=new Map;for(let[a,s]of Object.entries(e.modules))r.set(a,zI(s.fullFilePath,e));let i=true;for(;i;){i=false;for(let[a,s]of r)if(!n.has(a)){for(let l of s)if(n.has(l)){n.add(a),i=true;break}}}return n}function oFe(e,t){return t?.map(o=>{try{return new RegExp(o)}catch(n){throw new ae(`Invalid ${e} pattern '${o}': ${W(n)}. Patterns are regular expressions matched against test file paths, not globs (e.g. use 'momentic/pr/' instead of 'momentic/pr/**').`,{cause:n})}})}async function My({tests:e,changed:t,momenticFiles:o,project:n,yes:r,include:i,exclude:a,labels:s,logger:l}){let c=new Set,u=oFe("--include",i),d=oFe("--exclude",a);if(t)(await eFe({momenticFiles:o,project:n,logger:Re})).forEach(h=>c.add(h));else if(e&&e.length>0){let p=e.some(g=>Un__default.existsSync(g)),h=cwd();p?(h!==n.rootDir&&l.warn(`Test paths resolve against the current directory ('${h}'), not the project root ('${n.rootDir}'). Run from the project root or use substring filters to avoid surprises.`),e.forEach(g=>{if(!Un__default.existsSync(g))throw new ae(`Path '${g}' does not exist. Check the path or use a substring filter instead.`);let f;try{f=Un__default.statSync(g).isDirectory();}catch(b){l.warn({err:b},`Skipping path ${g} because it cannot be read`);return}let y=Cn__default.resolve(g);Object.values(o.tests).filter(b=>f?Kie(b.fullFilePath,y):b.fullFilePath===y).forEach(b=>{c.add(b.fullFilePath);});})):Object.values(o.tests).forEach(g=>{e.some(f=>g.relativePath.includes(f))&&c.add(g.fullFilePath);});}else !r&&!await ki("No test paths or substrings were provided. Do you want to run all tests?")&&(l.error("Cancelled by user."),Je(He.Failure)),Object.values(o.tests).forEach(h=>{c.add(h.fullFilePath);});for(let p of c){let h=Cn__default.relative(n.rootDir,p);u&&!u.some(g=>g.test(h))&&c.delete(p),d&&d.some(g=>g.test(h))&&c.delete(p);}let m=Array.from(c).map(async p=>{try{let h=await Nl(p,Re,o);if(Ph.gt(h.schemaVersion,qt)&&Vae(l,`Test ${p} has schema version ${h.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 g=h.labels||[];if(!s.some(y=>g.includes(y)))return null}return {...h,fullFilePath:p,relativeFilePath:Cn__default.relative(n.rootDir,p),testBundleHash:CN({absoluteTestFilePath:p,momenticFiles:o,logger:Re})}}catch(h){let g=`Failed to read and resolve test at '${p}': ${W(h)}`;throw l.error(g),wi(hi(h,gg)?new ae(g,{cause:h}):h)}});return compact(await Promise.all(m))}function nFe({testDefinitions:e,quarantinedTestsMetadata:t,onlyQuarantined:o=false,skipQuarantined:n=false,shardIndex:r=1}){let[i,a]=partition(e,c=>c.disabled),[s,l]=partition(a,c=>c.id in t);return {testsToSkip:r===1?i:[],quarantinedTestsToSkip:r===1&&n?s:[],testsToRun:o?[]:l,quarantinedTestsToRun:n?[]:s}}function rFe({testsToRun:e,quarantinedTestsToRun:t,quarantinedTestsMetadata:o,testInputMatrix:n}){let r=[],i=(a,s,l)=>{n?n.forEach((c,u)=>{r.push({inputs:c,inputIndex:u,testDefinition:a,quarantined:s,quarantinedMetadata:l});}):r.push({inputs:void 0,testDefinition:a,quarantined:s,quarantinedMetadata:l});};return e.forEach(a=>i(a,false)),t.forEach(a=>i(a,true,o[a.id])),r}var iFe=()=>process.exit(130),aFe=()=>process.exit(143);process.on("SIGINT",iFe);process.on("SIGTERM",aFe);function Cw(){process.off("SIGINT",iFe),process.off("SIGTERM",aFe);}async function sFe({orgId:e,codeEvaluator:t,logger:o,outputDefinitions:n,testContext:r}){let i={};for(let a of n){let{name:s,value:l}=a;i[s]=await Es({orgId:e,s:l,codeEvaluator:t,logger:o,context:r});}return i}var Zj=z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/),F6=Zj,_$t=F6.array().min(1).max(32).refine(e=>new Set(e).size===e.length,{message:"service IDs must be unique"}).refine(e=>e.every((t,o)=>o===0||e[o-1]<t),{message:"service IDs must be sorted"}),Qj=z.discriminatedUnion("mode",[z.object({mode:z.literal("playwright")}).strict(),z.object({mode:z.literal("private-service"),connectorId:Zj,serviceIds:_$t.optional()}).strict()]),cFe=z.record(z.string().regex(/^[a-z0-9]([-.a-z0-9_]{0,61}[a-z0-9])?$/),z.string()),B6=z.union([z.guid(),z.string().regex(/^[a-f0-9]{64}$/)]),U6=z.object({allocationRequestId:z.guid().default(randomUUID$1),concurrencyKey:z.string().regex(/^[A-Za-z0-9][A-Za-z0-9:_-]{0,255}$/).optional(),maxConcurrentSessions:z.number().int().positive().optional(),maxSessionTtlSeconds:z.number().int().min(1).max(3600).default(3600),metadata:cFe.optional(),network:Qj.default({mode:"playwright"}),principalId:B6,tokenVersion:z.literal(2)}).strict(),uFe=z.object({accessToken:z.string().min(1),expiresAt:z.iso.datetime(),tokenType:z.literal("Bearer")}),lFe=z.object({host:z.string().trim().min(1).max(253),port:z.number().int().min(1).max(65535)}).strict(),O$t=z.object({browserAddress:lFe,id:F6,target:lFe}).strict(),P$t=z.object({id:F6,mode:z.literal("localhost")}).strict(),k$t=z.union([O$t,P$t]),dFe=z.object({services:k$t.array().min(1).max(32)}).strict().superRefine(({services:e},t)=>{let o=e.filter(n=>"mode"in n);new Set(e.map(({id:n})=>n)).size!==e.length&&t.addIssue({code:"custom",message:"service IDs must be unique"}),o.length>1&&t.addIssue({code:"custom",message:"only one localhost namespace service is allowed"}),o.length===1&&e.length>1&&t.addIssue({code:"custom",message:"localhost cannot be combined with explicit services"});}),M$t=z.object({algorithm:z.literal("RSA-OAEP-256"),chunks:z.string().min(1).array().min(1).max(128)});U6.omit({tokenVersion:true}).partial({principalId:true});var mFe=z.object({metadata:cFe.optional(),browser:z.literal("chromium").default("chromium"),network:Qj.default({mode:"playwright"}),playwrightVersion:z.string().default("1.60"),ttlSeconds:z.number().int().min(1).max(3600).default(3600),waitTimeoutMs:z.number().int().min(0).max(1e4).default(5e3)}).strict(),L$t=z.discriminatedUnion("mode",[Qj.options[0].strip(),Qj.options[1].strip()]),j6=z.object({id:z.string(),status:z.string(),browser:z.string().optional(),playwrightVersion:z.string().optional(),network:L$t.default({mode:"playwright"}),connectToken:z.string().optional(),connectTokenExpiresAt:z.string().optional(),wsEndpoint:z.string().optional(),statusUrl:z.string().optional(),createdAt:z.string().optional(),queuedAt:z.string().nullable().optional(),assignedAt:z.string().nullable().optional(),readyAt:z.string().nullable().optional(),connectedAt:z.string().nullable().optional(),expiresAt:z.string().nullable().optional(),endedAt:z.string().nullable().optional(),failureCode:z.string().nullable().optional(),terminalReason:z.string().nullable().optional()}),pFe=j6.extend({connectToken:z.string(),status:z.literal("READY"),wsEndpoint:z.string()}),hFe=z.object({connectorId:z.string(),state:z.string()}),gFe=z.object({encryptedEnrollmentCredential:M$t});var ig=class extends Error{constructor(o,n,r){super(`Browser Fleet request failed (${n??"HTTP_ERROR"}, ${o})`);this.status=o;this.code=n;this.retryAfterMs=r;this.name="BrowserFleetAPIError";}},oT=class extends Error{constructor(t){super("Browser Fleet request failed",{cause:t}),this.name="BrowserFleetConnectionError";}},ez=class extends Error{constructor(o){super(`Browser Fleet session ${o.id} did not become ready (${o.failureCode??o.status})`);this.session=o;this.name="BrowserFleetSessionError";}},Cs=class extends Error{constructor(o,n){super(o);this.sessionId=n;this.name="BrowserFleetResponseError";}},tz=class extends Error{constructor(o){super(`Browser Fleet Connector did not become active (${o.state})`);this.connector=o;this.name="BrowserFleetConnectorError";}};function oz(e){return `/v1/private-connectors/${encodeURIComponent(Zj.parse(e))}`}function fFe(e){let t=hFe.safeParse(e);if(!t.success)throw new Cs("Browser Fleet returned a malformed Connector response");return t.data}var nz=class{constructor(t,o){this.transport=t;this.principalId=o;}async reconcile(t,o,n={}){let r=o.principalId===void 0?this.principalId:o.principalId,i=await this.transport.request(oz(t),{body:JSON.stringify(dFe.parse(o.desiredState)),headers:{"Content-Type":"application/json",...r?{"X-Browser-Fleet-Principal-Id":B6.parse(r)}:{}},method:"PUT"},n,true);return fFe(i.body)}async retrieve(t,o={}){let n=await this.transport.request(oz(t),{},o,true);return fFe(n.body)}async waitUntilActive(t,o={}){let n=o.timeoutMs===null?void 0:AbortSignal.timeout(o.timeoutMs??45e3),r=o.signal&&n?AbortSignal.any([o.signal,n]):o.signal??n;for(;;){r?.throwIfAborted();let i=await this.retrieve(t,{...o,signal:r});if(i.state==="ACTIVE")return i;if(i.state!=="PROVISIONING")throw new tz(i);await setTimeout$1(500,void 0,{signal:r});}}async createEnrollmentCredential(t,o,n={}){let r=await this.transport.request(`${oz(t)}/enrollment-credentials`,{body:JSON.stringify(o),headers:{"Content-Type":"application/json"},method:"POST"},n,true),i=gFe.safeParse(r.body);if(!i.success)throw new Cs("Browser Fleet returned a malformed enrollment response");return i.data.encryptedEnrollmentCredential}async delete(t,o={}){await this.transport.request(oz(t),{method:"DELETE"},o,true);}};var F$t=z.object({id:z.string()}),B$t=1e4,U$t=2e4;function SFe(e){return e+Math.random()*Math.min(4e3,e*4)}var rz=class{constructor(t,o){this.transport=t;this.accessToken=o;}async create(t={},o={}){return (await this.createResponse(this.creationParams(t),{...o,idempotencyKey:this.idempotencyKey(o)})).session}async retrieve(t,o={}){return (await this.requestSession(`/${encodeURIComponent(t)}`,{},o)).session}async delete(t,o={}){await this.transport.request(`/v1/sessions/${encodeURIComponent(t)}`,{method:"DELETE"},o);}async createAndWait(t={},o={}){o.signal?.throwIfAborted();let n=this.creationParams(t),r={...o,idempotencyKey:this.idempotencyKey(o)},i=o.allocationTimeoutMs??9e4,a=Date.now()+i,s=new AbortController,l=setTimeout(()=>s.abort(new DOMException("Browser Fleet allocation timed out","TimeoutError")),i),c=o.signal?AbortSignal.any([o.signal,s.signal]):s.signal,u={...r,signal:c},d;try{let m=await this.retry(()=>this.createResponse(n,u),a,c);for(d=m.session;(d.status==="QUEUED"||d.status==="PROVISIONING")&&Date.now()<a&&(await setTimeout$1(Math.min(SFe(m.retryAfterMs),a-Date.now()),void 0,{signal:c}),!(Date.now()>=a));){let h=d.id;m=await this.retry(()=>this.requestSession(`/${encodeURIComponent(h)}`,{},u),a,c),d=m.session;}if(c.throwIfAborted(),d.status!=="READY")throw new ez(d);let p=pFe.safeParse(d);if(!p.success)throw new Cs("Browser Fleet returned a malformed session response",d.id);return p.data}catch(m){let p=d?.id??(m instanceof Cs?m.sessionId:void 0);if(!p&&c.aborted)try{p=(await this.createResponse(n,{...r,signal:AbortSignal.timeout(U$t)})).session.id;}catch(h){h instanceof Cs&&(p=h.sessionId);}throw p&&await this.delete(p,{signal:AbortSignal.timeout(B$t)}).catch(()=>{}),m}finally{clearTimeout(l);}}idempotencyKey(t){if(t.idempotencyKey!==void 0)return t.idempotencyKey;if(typeof this.accessToken=="object")return this.accessToken.allocationRequestId;if(this.accessToken)throw new Error("Pass the token object or an explicit idempotencyKey when using a raw access token");return randomUUID$1()}creationParams(t){let o=typeof this.accessToken=="object"?this.accessToken:void 0;return mFe.parse({...t,network:t.network===void 0?o?.network:t.network,ttlSeconds:t.ttlSeconds===void 0?o?.maxSessionTtlSeconds:t.ttlSeconds})}createResponse(t,o){return this.requestSession("",{body:JSON.stringify(t),headers:{...o.headers,"Content-Type":"application/json","Idempotency-Key":o.idempotencyKey},method:"POST"},o)}async requestSession(t,o,n){let r=await this.transport.request(`/v1/sessions${t}`,o,n),i=j6.safeParse(r.body);if(!i.success)throw new Cs("Browser Fleet returned a malformed session response",F$t.safeParse(r.body).data?.id);return {session:i.data,retryAfterMs:r.retryAfterMs}}async retry(t,o,n){for(;;)try{return await t()}catch(r){if(n.throwIfAborted(),!(r instanceof oT||r instanceof ig&&(r.status===408||r.status===429||r.status>=500))||Date.now()>=o)throw r;let a=r instanceof ig?r.retryAfterMs:500;await setTimeout$1(Math.min(SFe(a),o-Date.now()),void 0,{signal:n});}}};var iz=class{constructor(t,o={}){this.transport=t;this.defaults=o;}async create({principalId:t=this.defaults.principalId,concurrencyKey:o=this.defaults.concurrencyKey,maxConcurrentSessions:n=this.defaults.maxConcurrentSessions,...r}={},i={}){let{concurrencyKey:a,maxConcurrentSessions:s,...l}=U6.parse({...r,principalId:t,concurrencyKey:o,maxConcurrentSessions:n,tokenVersion:2}),c=m=>this.transport.request("/v1/token",{body:JSON.stringify({...l,metadata:m}),headers:{"Content-Type":"application/json",...a===void 0?{}:{"X-Browser-Fleet-Concurrency-Key":a},...s===void 0?{}:{"X-Browser-Fleet-Max-Concurrent-Sessions":String(s)}},method:"POST"},i),u;try{u=await c(l.metadata);}catch(m){if(!(m instanceof ig)||m.status!==400||!l.metadata)throw m;u=await c(void 0);}let d=uFe.safeParse(u.body);if(!d.success)throw new Cs("Browser Fleet returned a malformed token response");return {...d.data,allocationRequestId:l.allocationRequestId,network:l.network,maxSessionTtlSeconds:l.maxSessionTtlSeconds}}};var TFe=64*1024;function z$t(e){if(!e)return 500;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let o=Date.parse(e);return Number.isNaN(o)?500:Math.max(0,o-Date.now())}async function vFe(e){let t=Number(e.headers.get("Content-Length"));if(Number.isFinite(t)&&t>TFe)throw await e.body?.cancel(),new Cs("Browser Fleet response is too large");if(!e.body)return;let o=e.body.getReader(),n=[],r=0;for(let i=await o.read();!i.done;i=await o.read()){if(r+=i.value.byteLength,r>TFe)throw await o.cancel(),new Cs("Browser Fleet response is too large");n.push(i.value);}if(r!==0)return JSON.parse(new TextDecoder().decode(Buffer$1.concat(n,r)))}var az=class{baseUrl;authorization;controlAuthorization;fetch;requestTimeoutMs;constructor({accessToken:t,apiKey:o=process.env.BROWSER_FLEET_API_KEY,baseUrl:n=process.env.BROWSER_FLEET_BASE_URL,controlApiKey:r,fetch:i=globalThis.fetch,requestTimeoutMs:a=15e3}){if(!n)throw new Error("Browser Fleet base URL is not configured");this.baseUrl=n.replace(/\/$/,"");let s=(typeof t=="object"?t.accessToken:t)??o;this.authorization=s?`Bearer ${s}`:void 0,this.controlAuthorization=r?`Bearer ${r}`:void 0,this.fetch=i,this.requestTimeoutMs=a;}async request(t,o,n={},r=false){let i=r?this.controlAuthorization:this.authorization;if(!i)throw new Error(`Browser Fleet ${r?"control":"session"} API key is not configured`);let a=n.timeoutMs===void 0?this.requestTimeoutMs:n.timeoutMs,s=a===null?void 0:AbortSignal.timeout(a),l=n.signal&&s?AbortSignal.any([n.signal,s]):n.signal??s;l?.throwIfAborted();let c;try{c=await this.fetch(`${this.baseUrl}${t}`,{...o,headers:{...o.headers,Authorization:i},redirect:"error",signal:l});}catch(d){throw n.signal?.aborted?d:new oT(d)}let u=z$t(c.headers.get("Retry-After"));if(!c.ok){let d=await vFe(c).catch(()=>{});n.signal?.throwIfAborted();let m=typeof d=="object"&&d!==null&&"code"in d&&typeof d.code=="string"?d.code:void 0;throw new ig(c.status,m,u)}try{return {body:await vFe(c),retryAfterMs:u}}catch(d){throw n.signal?.aborted||d instanceof Cs?d:new oT(d)}}};var xO=class{baseUrl;sessions;tokens;privateConnectors;constructor(t={}){let o=new az(t);this.baseUrl=o.baseUrl,this.sessions=new rz(o,t.accessToken),this.tokens=new iz(o,{principalId:t.principalId,concurrencyKey:t.concurrencyKey,maxConcurrentSessions:t.maxConcurrentSessions}),this.privateConnectors=new nz(o,t.principalId);}};var AFe=new Set;function EFe(e){return ge({name:"cli.setup_browser_and_controller",attributes:{"momentic.remote_browser":e.localBrowserConfig.remoteBrowser===true},fn:async t=>{let o=await H$t(e);return t?.setAttribute("momentic.browser_execution_mode",o.controller.browser.executionMode),o}})}async function H$t({baseUrl:e,envName:t,devicePixelRatio:o,apiClient:n,test:r,storageClient:i,codeEvaluator:a,generator:s,orgId:l,variables:c,logger:u,customHeaders:d,testInputs:m,localBrowserConfig:p,aiSettings:h,visualDiffScreenshotStorage:g,tracer:f,runId:y,runAttemptId:b,runGroupId:S,browserTypeOverride:A,attemptedRemoteBrowserProviders:T,browserFleetRegion:v,abortSignal:R}){let I={baseUrl:n.baseUrl,apiKey:n.apiKey,logger:Re,mode:n.mode,runner:n.runner},{controller:C,context:O}=await J_({baseUrl:e,envName:t,test:r,variables:c,logger:u,orgId:l,localBrowserConfig:p,aiSettings:h,customHeaders:d,codeEvaluator:a,storage:i,enricher:new Ah(I,s),generator:s,visualDiffScreenshotStorage:g,devicePixelRatio:o,browserTypeOverride:A,callbacks:{onNetworkPage:P=>f.onNetworkPage(P),onNetworkLogs:P=>f.onNetworkLogs(P)},videoOptions:f.videoOutputPath?{videoOutputPath:f.videoOutputPath,onVideoPageChange:({videoName:P,timestamp:k})=>{f.setActiveVideo(P,k);}}:void 0,validateBrowserType:P=>{Jg(P)||(Re.warn({browserType:P,testName:r.name},"Browser required by test does not appear to be installed"),!AFe.has(P)&&(AFe.add(P),x.warn(`Browser ${P} does not appear to be installed. Run '${Ig(P)}' if you hit launch errors.`)));},createRemoteBrowserConnection:p.remoteBrowser?async()=>{let P=Date.now(),k,N=T?.slice(-1),M=crypto.randomUUID(),L=async()=>{let G=await n.createRemoteBrowserConnection({attemptedProviders:N,envName:t,runAttemptId:b,runGroupId:S,runId:y,testId:r.id,testName:r.name});return k=G.provider,G.provider&&T?.push(G.provider),G};try{if(!v&&N?.includes("SELF_HOSTED"))return await L();let G=await n.tryCreateBrowserFleetAccessToken({allocationRequestId:M,browserFleetRegion:v,envName:t,runAttemptId:b,runGroupId:S,runId:y,testId:r.id,testName:r.name},R);if(!G){if(v)throw new Error(`Browser Fleet region ${v} is unavailable for this run`);return await L()}k=G.provider,T?.push(G.provider);let X=await new xO({accessToken:G.accessToken,baseUrl:G.fleetApiUrl,requestTimeoutMs:15e3}).sessions.createAndWait({network:G.network,ttlSeconds:3600,waitTimeoutMs:1e4},{allocationTimeoutMs:9e4,idempotencyKey:M,signal:R});return {accessToken:X.connectToken,endpointType:"PLAYWRIGHT",operatingSystem:"linux",provider:G.provider,wsEndpoint:X.wsEndpoint}}catch(G){throw R?.aborted?G:new zu("Browser Fleet session allocation failed",{cause:G})}finally{zo.distribution("test_event_duration",Date.now()-P,["name:remote-browser-allocation",`provider:${k??"unknown"}`]);}}:void 0});try{await Q_({orgId:l,test:r,testInputs:m,codeEvaluator:a,logger:u,context:O});}catch(P){try{await C.browser.cleanup();}catch(k){u.error({err:k},"Failed to clean up browser after test input resolution failed");}throw P instanceof X_?new bo(bt.UserUnclassified,P.message,{cause:P}):P}return {controller:C,context:O}}function wFe({testAdvancedSettings:e,orgSettings:t,logger:o}){if(e.failureRecovery===false||e.failureRecovery===void 0&&!t?.failureRecovery)return false;if(!ms){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return o.warn(n),x.debug(n),false}return true}async function RFe({attemptInputs:e,attemptFixtures:t,attemptMetadata:o,runFixtures:n,recordVideo:r,stepCallbacks:i}){let{orgId:a,userId:s,runId:l}=o,{runTracer:c,runGroupTracer:u,project:d,apiClient:m}=n,{controller:p,context:h,codeEvaluator:g,storageClient:f,cacheStorage:y,logger:b,usageTracker:S,tracer:A}=t,{test:T,orgSettings:v}=e;b.info(`Running test '${T.name}' locally (run link: https://app.momentic.ai/runs/${l})`);let R={controller:p,storage:f,cacheStorage:y,usageTracker:S,context:h,logger:b,codeEvaluator:g},I={orgId:a,userId:s,runId:l,testMetadata:T,steps:T.steps,beforeSteps:T.beforeSteps,afterSteps:T.afterSteps,orgSettings:v},C={collectDebugData:true,reinitializeBrowser:true,disableHealing:!await wFe({testAdvancedSettings:T.advanced,orgSettings:v.ai,logger:b})};return cke({fixtures:R,inputs:I,options:C,callbacks:{step:i??{},test:{onTestComplete:async P=>{await p.browser.cleanup({saveRemoteVideos:r!=="on-fail"||P?.status!=="PASSED"}),await g.dispose(),b.debug("Test completion cleanup finished");}}},testParams:{attemptTracer:A},runParams:{runTracer:c,runGroupTracer:u,project:d,apiClient:m,captureEvent:Ep,abortSignal:n.abortSignal}})}async function CFe(e){let{testDefinition:t,traceMetadata:o}=e;return ge({name:"cli.test_run",newTrace:true,serviceName:"cli",attributes:{"momentic.org_id":e.orgId,"momentic.run_group_id":o.runGroupId,"momentic.run_id":e.runId,"momentic.test_id":t.id,"momentic.parallel":o.parallel,"momentic.worker_count":o.workerCount,"momentic.worker_index":o.workerIndex,"momentic.remote_browser_run":o.remoteBrowser},fn:async n=>{let r=await V$t(e);return n?.setAttributes({"momentic.test_status":r.status,"momentic.test_attempts":r.attempts}),r}})}async function V$t(e){let{testDefinition:t,logger:o}=e,n=new Date;try{return await W$t(e)}catch(r){Tm(r);let{customHeaders:i,envName:a,testInputs:s,urlOverride:l}=e,c={customHeaders:i,envName:a,testInputs:s,urlOverride:l},u="Fatal error running test";return o.error({err:r},u),x.error({err:r},u),IFe({err:Gi(r),parameters:c,test:t,failureReason:ie.reasonFor(r,"UnknownError"),startedAt:n,lastAttemptStartedAt:n,attempts:0,quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata})}}async function W$t(e){let{testDefinition:t,snapshot:o,project:n,apiClient:r,orgId:i,userId:a,urlOverride:s,runGroupTracer:l,logger:c,gitMetadata:u,cacheOptions:d,runId:m,testInputs:p,quarantined:h,quarantinedMetadata:g,usageTracker:f}=e,y=o?{...n.config,...o.metadata.config}:n.config,b=new LA(r,i),S=Rh({logger:c,orgId:i,client:r,gitMetadata:u,regenerateCache:d.regenerateCache,alwaysSaveCache:d.alwaysSaveCache,noCache:o?true:d.noCache,isolateCachesByEnvironment:n.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:d.bustOldestCachePercentage}),A,T,v;o?(A={envName:o.metadata.environment.envName,resolvedEnv:o.metadata.environment.resolvedEnv,environmentVariables:{...o.metadata.environment.variables},baseUrl:o.metadata.environment.baseUrl},T={steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps}):(A=rS({test:t,envNameOverride:e.envName,urlOverride:s,resolveEnv:K=>yu(K,n,c)}),{stepListsWithCaches:T,restoredStepLists:v}=await du({cacheStorage:S,logger:c,schemaVersion:t.schemaVersion,stepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,environment:A.envName,useSnapshotIdentityCache:n.config.fileFormat==="v2"}));let{envName:R,resolvedEnv:I,environmentVariables:C,baseUrl:O}=A,P=T.steps,k=T.beforeSteps??void 0,N=T.afterSteps??void 0,M=QR(t),L=M||(e.recordVideo??false);M&&e.recordVideo!==true&&c.info("Enabling video recording because the test defines run assertions");let G=await l.startRun({logger:c,runId:m,originalSteps:v??{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,testName:t.name,directory:dirname(t.relativeFilePath),testDescription:t.description??void 0,testLabels:t.labels,baseUrl:O,environmentName:R,schemaVersion:t.schemaVersion,testBundleHash:t.testBundleHash,resolvedInputs:p,quarantined:h,quarantinedReason:g?.quarantinedReason,aiSettings:y.ai,recordVideoOverride:M?true:void 0}),X=c.child(G.loggerBindings||{});Object.entries(G.envVarBindings||{}).forEach(([K,ee])=>{C[K]=ee;});let B=await K$t({...e,recordVideo:L,effectiveConfig:y,variables:C,envName:R,resolvedEnv:I,baseUrl:O,storageClient:b,tracer:G,runGroupTracer:l,logger:X,cacheStorage:S,stepsWithCaches:P,beforeStepsWithCaches:k,afterStepsWithCaches:N,usageTracker:f});return await G.finish({logger:c,status:B.status,finishedAt:B.finishedAt,failureDetails:B.failureDetails,failureReason:B.failureReason,isFlake:B.isFlake,failureRecoveryDetails:B.failureRecoveryDetails,runAssertionResults:B.runAssertionResults,usage:f.getUsageSummary()}),q$t({apiClient:r,classificationEnabled:y.ai?.classification?.enabled===true,runId:m,environment:R,status:B.status,logger:X}),{runId:G.runId,...B}}function q$t({apiClient:e,classificationEnabled:t,runId:o,environment:n,status:r,logger:i}){if(!t||r!=="PASSED"&&r!=="FAILED")return;let a=e.recordRunOutcomeForFailureRate({runId:o,environment:n,status:r==="PASSED"?"PASSED":"FAILED"}).catch(s=>{i.debug({err:s,runId:o},"Failed to report run outcome for failure rate");});X0e(a);}async function K$t(e){let{testDefinition:t,effectiveConfig:o,stepsWithCaches:n,beforeStepsWithCaches:r,afterStepsWithCaches:i,project:a,regenerateGoldenFiles:s,apiClient:l,generator:c,baseUrl:u,storageClient:d,orgId:m,userId:p,envName:h,urlOverride:g,customHeaders:f,testInputs:y,variables:b,resolvedEnv:S,retriesOverride:A,devicePixelRatio:T,logUpdate:v,tracer:R,runGroupTracer:I,logger:C,cacheStorage:O,gitMetadata:P,quarantined:k,quarantinedMetadata:N,usageTracker:M}=e,L=o,G=L.ai?.aiFailureAnalysis??false,X=new Date,B=new FA(a,l,s),K={envName:h,urlOverride:g,customHeaders:f,testInputs:y},ee={...L.browser||{},...S?.browser||{},...t.advanced||{},...e.remoteBrowserOverride?{remoteBrowser:true}:{}},z=ee.remoteBrowser===true,F=[],j,te=Math.abs(A??t.retries??o.retries??1),Ae=[],Se=[];C.info({...P,labels:t.labels,name:t.name,cwd:process.cwd()},"Starting test run using CLI");for(let De=0;De<=te;De++){let at=randomUUID(),Q=await R.startAttempt(at),Ce=C.child(Q.loggerBindings||{}),Ee={...t,steps:cloneDeep(n),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)};De!==0&&v("RETRY",`attempt ${De+1}/${te+1}`);let Rt=new Date,lt=kS({tools:new wh({httpClient:new ol({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:Ce,mode:l.mode,runner:l.runner}),fakerSeed:L.advanced?.fakerConstantSeed?PC:void 0})}),de;try{let{controller:Ke,context:Yt}=await EFe({tracer:Q,runId:R.runId,runAttemptId:at,runGroupId:e.traceMetadata.runGroupId,baseUrl:u,envName:h,apiClient:l,devicePixelRatio:T,logger:Ce,storageClient:d,codeEvaluator:lt,test:Ee,generator:c,orgId:m,variables:b,customHeaders:f,testInputs:y,localBrowserConfig:ee,browserTypeOverride:e.browserTypeOverride,attemptedRemoteBrowserProviders:F,browserFleetRegion:e.browserFleetRegion,abortSignal:e.abortSignal,aiSettings:{...L.ai||{},...Ee.advanced||{}},visualDiffScreenshotStorage:B});e.abortSignal&&(e.abortSignal.aborted?Ke.executeAbortController.abort():(de=()=>{Ke.executeAbortController.abort();},e.abortSignal.addEventListener("abort",de,{once:!0}))),j=await RFe({attemptMetadata:{attemptNumber:De+1,orgId:m,userId:p,runId:R.runId},attemptFixtures:{logger:Ce,storageClient:d,cacheStorage:O,usageTracker:M,codeEvaluator:lt,context:Yt,controller:Ke,tracer:Q},attemptInputs:{test:Ee,orgSettings:L},runFixtures:{runTracer:R,runGroupTracer:I,project:a,apiClient:l,abortSignal:e.abortSignal},recordVideo:e.recordVideo??!1,stepCallbacks:{onStepStart:e.onStepStart,onStepEnd:e.onStepEnd,onSectionStart:e.onSectionStart}});let pt=new Date,pe={logger:C,cacheStorage:O,orgId:m,testId:t.id,environment:h,originalStepsWithCaches:{steps:cloneDeep(n),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)},updatedStepsWithCaches:{steps:Ee.steps,beforeSteps:Ee.beforeSteps,afterSteps:Ee.afterSteps}};await Pb({logger:C,cacheStorage:O,orgId:m,testId:t.id,environment:h,stepLists:pe.updatedStepsWithCaches,useSnapshotIdentityCache:a.config.fileFormat==="v2"}),j?.status==="PASSED"||j?.status==="CANCELLED"&&o.advanced?.saveCacheOnCancel?await kb(pe):j?.status==="FAILED"&&De===te&&await qv(pe),await Q.finish({logger:Ce,result:j});let ve;if(j.status==="PASSED"&&QR(t)){e.onStepStart?.(SZ);let Co=await IIe({runAssertions:t.runAssertions??[],orgId:m,project:a,generator:c,apiClient:l,runTracer:R,runGroupTracer:I,logger:Ce,testPlatform:"web",captureEvent:Ep,abortSignal:e.abortSignal});pt=new Date,Co&&(Se.push(Co),ve=TZ(Co.evaluations));}let dt=Se.length>0?{attempts:Se}:void 0;Ae.unshift(ve!==void 0?"FAILED":j.status);let Ze=await sFe({orgId:m,codeEvaluator:lt,logger:Ce,outputDefinitions:t.outputs??[],testContext:Yt}),an=wZ(Ae),ct=De+1;if(j.status!=="FAILED"&&ve===void 0)return {...j,runAttemptId:at,parameters:K,test:Ee,filePath:Ee.relativeFilePath,startedAt:X,lastAttemptStartedAt:Rt,finishedAt:pt,attempts:ct,baseUrl:u,outputs:Ze,isFlake:an,runAssertionResults:dt,quarantined:k,quarantinedMetadata:N,usedRemoteBrowser:z};let lo=j.failedStepResult,mi=ve??(lo?.message||"Unknown failure"),Or=ve?"AssertionFailureError":lo?.failureReason??SP(mi)??"UnknownError",Pr=Ce.child({failureReason:Or,errorMessage:mi,numAttempts:(te+1).toString(),name:Ee.name});if(De<te){Pr.warn(`Retrying failed execution attempt for run: ${mi}`);continue}Pr.error({usedRemoteBrowser:z},`Test failed after all exhausting attempts: ${mi}`);let Oa=new Error(mi),Os={errorMessage:mi,errorStack:Oa.stack},mo;if(L.ai?.classification?.enabled===!0){let Co=lo?.failureClassification;Co||(e.onStepStart?.(xp),Co=await CB({runTracer:R,runGroupTracer:I,outputDir:e.outputDir,orgId:m,project:a,generator:c,apiClient:l,logger:C,testPlatform:"web",aiSettings:L.ai,captureEvent:Ep,abortSignal:e.abortSignal,failedStepMessage:ve??lo?.message,runAssertionResults:dt})),Co&&(mo=Co.classification.category,Or=Co.classification.category,Os.classification={reason:Co.classification.category,secondaryCategories:Co.classification.secondaryCategories,summary:Co.classification.reasoning,recoverable:Co.classification.recoverable,confidence:Co.classification.confidence,action:Co.action,citations:Co.classification.citations,cache:Co.classification.cache,source:"v2"});}else if(G){let Co;try{if(j.results&&j.results.length>0){e.onStepStart?.(xp);let{classification:Qo,aiFailureReason:it}=await Lce({logger:Ce,browserStateStorage:Q,generator:c,fullResults:j,failureReason:Or,error:Oa,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Co=Qo,mo=it;}}catch(Qo){Ce.warn({err:Qo},"Failed to classify test results");}Co&&(Os.classification=Co,Or=mo??Or,Os.classification.source="v1");}return {...j,status:"FAILED",runAttemptId:at,parameters:K,failureDetails:Os,failureReason:Or,test:Ee,filePath:Ee.relativeFilePath,startedAt:X,lastAttemptStartedAt:Rt,finishedAt:pt,attempts:De+1,baseUrl:u,outputs:Ze,runAssertionResults:dt,quarantined:k,quarantinedMetadata:N,usedRemoteBrowser:z}}catch(Ke){let Yt=`Encountered fatal platform error while running test '${Ee.name}'`;return Ce.error({err:Ke},Yt),x.error({err:Ke},Yt),await Q.finish({logger:Ce,result:{status:"FAILED"}}),IFe({err:Gi(Ke),parameters:K,test:Ee,failureReason:ie.reasonFor(Ke,"InternalPlatformError"),startedAt:X,lastAttemptStartedAt:Rt,attempts:De+1,quarantined:k,quarantinedMetadata:N,runAttemptId:at,baseUrl:u,usedRemoteBrowser:z})}finally{de&&e.abortSignal?.removeEventListener("abort",de);}}throw new Error("This code should not be reachable")}function IFe({err:e,parameters:t,test:o,failureReason:n,startedAt:r,lastAttemptStartedAt:i,attempts:a,quarantined:s,quarantinedMetadata:l,runAttemptId:c,baseUrl:u,usedRemoteBrowser:d}){return {status:"FAILED",results:[],parameters:t,test:o,filePath:o.relativeFilePath,failureReason:n,failureDetails:{errorMessage:e.message,errorStack:e.stack},startedAt:r,lastAttemptStartedAt:i,finishedAt:new Date,attempts:a,outputs:{},quarantined:s,quarantinedMetadata:l,runAttemptId:c,baseUrl:u,usedRemoteBrowser:d}}var xFe=3e4;async function _w({timeoutMinutes:e,cancel:t,run:o}){let n=()=>void t("SIGINT received"),r=()=>void t("SIGTERM received");Cw(),process.once("SIGINT",n),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 o()}finally{process.off("SIGINT",n),process.off("SIGTERM",r),clearTimeout(i);}}var xw=class{constructor(t){this.params=t;}runQueue={};runResults=[];cancelledRunsById=new Map;cancelled=false;cancellationReason;async cancel(t,o=true){if(this.cancelled)return;this.cancelled=true,this.cancellationReason=t;for(let r of Object.values(this.runQueue))r.done||r.abortController.abort();o&&await ye(Promise.allSettled(Object.values(this.runQueue).map(r=>r.promise)),{milliseconds:xFe}).catch(()=>{this.params.runGroupLogger.warn(`Graceful shutdown timeout of ${xFe}ms reached while waiting for running tests to settle.`);});let n=new Set(this.runResults.map(r=>r.runId).filter(r=>!!r));for(let r of Object.values(this.runQueue)){if(r.done||n.has(r.activeRun.runId))continue;let{activeRun:i}=r,a={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,a);}}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:o,reporter:n,runGroupTracer:r,runGroupLogger:i,logger:a,project:s,client:l,generator:c,orgId:u,userId:d,devicePixelRatio:m,outputDir:p,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:b,gitMetadata:S,cacheOptions:A,browserTypeOverride:T,remoteBrowserOverride:v,browserFleetRegion:R,onResult:I,onFatal:C}=this.params,O=0,P=true;for(;P;){let k=Object.values(this.runQueue);if(k.length===o&&await Promise.race(k.map(X=>X.promise)),this.cancelled){P=false;continue}let N=await t();if(N===void 0){P=false;continue}let M=`test-${O++}`,L={...N,startedAt:new Date},G=new AbortController;this.runQueue[M]={done:false,activeRun:L,abortController:G,promise:(async({inputs:X,quarantined:B,quarantinedMetadata:K,testDefinition:ee,snapshot:z,runId:F})=>{let j=ee.relativeFilePath.includes("..")?ee.fullFilePath:ee.relativeFilePath;n.onTestBegin(j);let te=i.child({testId:ee.id,runId:F}),Ae=new ih({logger:te,reporter:new Th(l),runType:"test-run",platform:"WEB",runId:F,runGroupId:r.runGroupMetadata.id,envName:f,testMetadata:ee,suiteMetadata:void 0,runner:"test-runner"});try{let Se=await CFe({testDefinition:ee,snapshot:z,project:s,testInputs:X,quarantined:B,quarantinedMetadata:K,orgId:u,userId:d,runId:F,devicePixelRatio:m,apiClient:l,runGroupTracer:r,outputDir:p,generator:c,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:b,logUpdate:(De,at)=>n.onTestStatus(j,De,at),...pTe(n,j),logger:te,gitMetadata:S,cacheOptions:A,usageTracker:Ae,browserTypeOverride:T,remoteBrowserOverride:v,browserFleetRegion:R,recordVideo:this.params.recordVideo,abortSignal:G.signal,traceMetadata:this.params.traceMetadata});n.onTestEnd(j,Se.status,{recovered:Se.status==="PASSED"&&!!Se.failureRecoveryDetails?.attempts}),this.runResults.push(Se),I?.(Se);}catch(Se){let De=`Encountered unexpected fatal error when running test '${ee.name}'`;te.error({err:Se},De),x.error({err:Se},De),Tm(Se),C?.(Se),await this.cancel("Fatal error occurred",false);}finally{let Se=this.runQueue[M];Se&&(Se.done=true),await Ae.flush(a),delete this.runQueue[M];}})(L)};}return await Promise.allSettled(Object.values(this.runQueue).map(k=>k.promise)),{runResults:this.runResults,cancelledRunsById:this.cancelledRunsById,cancelled:this.cancelled,cancellationReason:this.cancellationReason}}};function sz(e){return createHash("sha1").update(e).digest("hex")}var J$t=["tab","view","mode","step"],X$t=[/^[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 Q$t(e){return X$t.some(t=>t.test(e))}function _Fe(e,t={}){let o;try{o=new URL(e);}catch{return e}let n=new Set(t.queryAllowlist??J$t),i=o.pathname.split("/").map(c=>c.length>0&&Q$t(c)?"{id}":c).join("/"),a=[],s=Array.from(o.searchParams.keys()).sort();for(let c of s){if(!n.has(c))continue;let u=o.searchParams.getAll(c).sort();for(let d of u)a.push(`${encodeURIComponent(c)}=${encodeURIComponent(d)}`);}let l=a.length>0?`?${a.join("&")}`:"";return `${o.protocol}//${o.host}${i}${l}`}var z6=new Set(["id","name","role","type","href","for","placeholder","aria-label","data-testid"]),Z$t=/^[A-Za-z0-9_-]{16,256}$|^:r[0-9a-z]{1,32}:$/,e1t=[/\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],OFe=new Set(["h1","h2","h3","h4","h5","h6"]),t1t=new Set(["input","select","textarea"]);function o1t(e){let t=e;for(let o of e1t)t=t.replace(o,"{id}");return t}function PFe(e){return o1t(e).toLowerCase().replace(/\s+/g," ").trim().replace(/[.,:;!?]+$/u,"").replace(/\s*\d+\s*$/u,"").trim()}function n1t(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 r1t(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":Z$t.test(t)?"@gen":PFe(t)}function kFe(e,t,o){let n=e.tag.toLowerCase(),r=(e.role??e.attributes?.role)?.toLowerCase(),i=Math.min(Math.floor(t/4),6),a=`<${n}@${i}`;if(r!==void 0&&(a+=` role=${r}`),e.attributes!==void 0){let l=Object.keys(e.attributes).filter(c=>z6.has(c.toLowerCase())).sort();for(let c of l){let u=c.toLowerCase();if(u==="role")continue;let d=e.attributes[c];if(d===void 0)continue;let m=r1t(u,d);a+=` ${u}=${m}`;}}o.tokens.push(a);let s=e.text?.trim();s!==void 0&&s.length>0&&(r==="button"||r==="link"||r==="heading"||n==="button"||n==="a"||n==="label"||OFe.has(n)?o.tokens.push(`label=${PFe(s)}`):o.tokens.push(n1t(s))),(n==="button"||r==="button")&&(o.counts.buttons+=1),(n==="a"||r==="link")&&(o.counts.links+=1),(t1t.has(n)||r==="textbox"||r==="combobox")&&(o.counts.formFields+=1),(OFe.has(n)||r==="heading")&&(o.counts.headings+=1);for(let l of e.children??[])kFe(l,t+1,o);}function MFe(e){let t={tokens:[],counts:{buttons:0,links:0,formFields:0,headings:0}};return kFe(e,0,t),{tokens:t.tokens,counts:t.counts}}function LFe(e,t){let o=new TextEncoder().encode(e),n=o.length,r=Math.floor(n/4),i=t>>>0,a=3432918353,s=461845907;for(let d=0;d<r;d++){let m=d*4,p=o[m]|o[m+1]<<8|o[m+2]<<16|o[m+3]<<24;p=Math.imul(p,a),p=p<<15|p>>>17,p=Math.imul(p,s),i^=p,i=i<<13|i>>>19,i=Math.imul(i,5)+3864292196;}let l=0,c=n&3,u=r*4;return c===3&&(l^=o[u+2]<<16),c>=2&&(l^=o[u+1]<<8),c>=1&&(l^=o[u],l=Math.imul(l,a),l=l<<15|l>>>17,l=Math.imul(l,s),i^=l),i^=n,i^=i>>>16,i=Math.imul(i,2246822507),i^=i>>>13,i=Math.imul(i,3266489909),i^=i>>>16,i>>>0}var lz=128,i1t=4294967295,a1t=(()=>{let e=[];for(let t=0;t<lz;t++)e.push(LFe(`perm:${t}`,0));return e})();function NFe(e){let t=new Uint32Array(lz);for(let n=0;n<lz;n++)t[n]=i1t;let o=new Set(e);for(let n of o)for(let r=0;r<lz;r++){let i=LFe(n,a1t[r]);i<t[r]&&(t[r]=i);}return t}var l1t=32;function cz(e){let t=_Fe(e.url,{queryAllowlist:e.queryAllowlist}),{tokens:o,counts:n}=MFe(e.dom),r=[`url:${t}`,`counts:buttons=${n.buttons}`,`counts:links=${n.links}`,`counts:formFields=${n.formFields}`,`counts:headings=${n.headings}`,...o],i=NFe(r),a=Buffer.from(i.buffer,i.byteOffset,i.byteLength);return {fingerprintHash:createHash$1("sha256").update(a).digest("hex").slice(0,l1t),minhash:Array.from(i),canonicalUrl:t}}var c1t=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]),wr="\uFFFD",H;(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";})(H||(H={}));var yl={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function uz(e){return e>=55296&&e<=57343}function DFe(e){return e>=56320&&e<=57343}function FFe(e,t){return (e-55296)*1024+9216+t}function dz(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function mz(e){return e>=64976&&e<=65007||c1t.has(e)}var Te;(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";})(Te||(Te={}));var d1t=65536,pz=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=d1t,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,o){let{line:n,col:r,offset:i}=this,a=r+o,s=i+o;return {code:t,startLine:n,endLine:n,startCol:a,endCol:a,startOffset:s,endOffset:s}}_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 o=this.html.charCodeAt(this.pos+1);if(DFe(o))return this.pos++,this._addGap(),FFe(t,o)}else if(!this.lastChunkWritten)return this.endOfChunkHit=true,H.EOF;return this._err(Te.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,o){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=false,this.lastChunkWritten=o;}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=false;}startsWith(t,o){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,false;if(o)return this.html.startsWith(t,this.pos);for(let n=0;n<t.length;n++)if((this.html.charCodeAt(this.pos+n)|32)!==t.charCodeAt(n))return false;return true}peek(t){let o=this.pos+t;if(o>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,H.EOF;let n=this.html.charCodeAt(o);return n===H.CARRIAGE_RETURN?H.LINE_FEED:n}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,H.EOF;let t=this.html.charCodeAt(this.pos);return t===H.CARRIAGE_RETURN?(this.isEol=true,this.skipNextNewLine=true,H.LINE_FEED):t===H.LINE_FEED&&(this.isEol=true,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=false,this._addGap(),this.advance()):(this.skipNextNewLine=false,uz(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===H.LINE_FEED||t===H.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){dz(t)?this._err(Te.controlCharacterInInputStream):mz(t)&&this._err(Te.noncharacterInInputStream);}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=false;}};var hn;(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";})(hn||(hn={}));function hz(e,t){for(let o=e.attrs.length-1;o>=0;o--)if(e.attrs[o].name===t)return e.attrs[o].value;return null}var p1t=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 BFe(e){return e>=55296&&e<=57343||e>1114111?65533:p1t.get(e)??e}function UFe(e){let t=atob(e),o=t.length&-2,n=new Uint16Array(o/2);for(let r=0,i=0;r<o;r+=2){let a=t.charCodeAt(r),s=t.charCodeAt(r+1);n[i++]=a|s<<8;}return n}var H6=UFe("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 Is;(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";})(Is||(Is={}));var Xr;(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";})(Xr||(Xr={}));var jFe=32;function $6(e){return e>=Xr.ZERO&&e<=Xr.NINE}function h1t(e){return e>=Xr.UPPER_A&&e<=Xr.UPPER_F||e>=Xr.LOWER_A&&e<=Xr.LOWER_F}function g1t(e){return e>=Xr.UPPER_A&&e<=Xr.UPPER_Z||e>=Xr.LOWER_A&&e<=Xr.LOWER_Z||$6(e)}function f1t(e){return e===Xr.EQUALS||g1t(e)}var _a;(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";})(_a||(_a={}));var wp;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute";})(wp||(wp={}));var gz=class{decodeTree;emitCodePoint;errors;constructor(t,o,n){this.decodeTree=t,this.emitCodePoint=o,this.errors=n;}state=_a.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=wp.Strict;runConsumed=0;startEntity(t){this.decodeMode=t,this.state=_a.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0;}write(t,o){switch(this.state){case _a.EntityStart:return t.charCodeAt(o)===Xr.NUM?(this.state=_a.NumericStart,this.consumed+=1,this.stateNumericStart(t,o+1)):(this.state=_a.NamedEntity,this.stateNamedEntity(t,o));case _a.NumericStart:return this.stateNumericStart(t,o);case _a.NumericDecimal:return this.stateNumericDecimal(t,o);case _a.NumericHex:return this.stateNumericHex(t,o);case _a.NamedEntity:return this.stateNamedEntity(t,o)}}stateNumericStart(t,o){return o>=t.length?-1:(t.charCodeAt(o)|jFe)===Xr.LOWER_X?(this.state=_a.NumericHex,this.consumed+=1,this.stateNumericHex(t,o+1)):(this.state=_a.NumericDecimal,this.stateNumericDecimal(t,o))}stateNumericHex(t,o){for(;o<t.length;){let n=t.charCodeAt(o);if($6(n)||h1t(n)){let r=n<=Xr.NINE?n-Xr.ZERO:(n|jFe)-Xr.LOWER_A+10;this.result=this.result*16+r,this.consumed++,o++;}else return this.emitNumericEntity(n,3)}return -1}stateNumericDecimal(t,o){for(;o<t.length;){let n=t.charCodeAt(o);if($6(n))this.result=this.result*10+(n-Xr.ZERO),this.consumed++,o++;else return this.emitNumericEntity(n,2)}return -1}emitNumericEntity(t,o){if(this.consumed<=o)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===Xr.SEMI)this.consumed+=1;else if(this.decodeMode===wp.Strict)return 0;return this.emitCodePoint(BFe(this.result),this.consumed),this.errors&&(t!==Xr.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,o){let{decodeTree:n}=this,r=n[this.treeIndex],i=(r&Is.VALUE_LENGTH)>>14;for(;o<t.length;){if(i===0&&r&Is.FLAG13){let s=(r&Is.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let l=r&Is.JUMP_TABLE;if(t.charCodeAt(o)!==l)return this.result===0?0:this.emitNotTerminatedNamedEntity();o++,this.excess++,this.runConsumed++;}for(;this.runConsumed<s;){if(o>=t.length)return -1;let l=this.runConsumed-1,c=n[this.treeIndex+1+(l>>1)],u=l%2===0?c&255:c>>8&255;if(t.charCodeAt(o)!==u)return this.runConsumed=0,this.result===0?0:this.emitNotTerminatedNamedEntity();o++,this.excess++,this.runConsumed++;}this.runConsumed=0,this.treeIndex+=1+(s>>1),r=n[this.treeIndex],i=(r&Is.VALUE_LENGTH)>>14;}if(o>=t.length)break;let a=t.charCodeAt(o);if(a===Xr.SEMI&&i!==0&&r&Is.FLAG13)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=y1t(n,r,this.treeIndex+Math.max(1,i),a),this.treeIndex<0)return this.result===0||this.decodeMode===wp.Attribute&&(i===0||f1t(a))?0:this.emitNotTerminatedNamedEntity();if(r=n[this.treeIndex],i=(r&Is.VALUE_LENGTH)>>14,i!==0){if(a===Xr.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==wp.Strict&&!(r&Is.FLAG13)&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0);}o++,this.excess++;}return -1}emitNotTerminatedNamedEntity(){let{result:t,decodeTree:o}=this,n=(o[t]&Is.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,n,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,o,n){let{decodeTree:r}=this;return this.emitCodePoint(o===1?r[t]&~(Is.VALUE_LENGTH|Is.FLAG13):r[t+1],n),o===3&&this.emitCodePoint(r[t+2],n),n}end(){switch(this.state){case _a.NamedEntity:return this.result!==0&&(this.decodeMode!==wp.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case _a.NumericDecimal:return this.emitNumericEntity(0,2);case _a.NumericHex:return this.emitNumericEntity(0,3);case _a.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case _a.EntityStart:return 0}}};function y1t(e,t,o,n){let r=(t&Is.BRANCH_LENGTH)>>7,i=t&Is.JUMP_TABLE;if(r===0)return i!==0&&n===i?o:-1;if(i){let c=n-i;return c<0||c>=r?-1:e[o+c]-1}let a=r+1>>1,s=0,l=r-1;for(;s<=l;){let c=s+l>>>1,u=c>>1,m=e[o+u]>>(c&1)*8&255;if(m<n)s=c+1;else if(m>n)l=c-1;else return e[o+a+c]}return -1}var Ne;(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/";})(Ne||(Ne={}));var ag;(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";})(ag||(ag={}));var bl;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks";})(bl||(bl={}));var le;(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";})(le||(le={}));var w;(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";})(w||(w={}));var b1t=new Map([[le.A,w.A],[le.ADDRESS,w.ADDRESS],[le.ANNOTATION_XML,w.ANNOTATION_XML],[le.APPLET,w.APPLET],[le.AREA,w.AREA],[le.ARTICLE,w.ARTICLE],[le.ASIDE,w.ASIDE],[le.B,w.B],[le.BASE,w.BASE],[le.BASEFONT,w.BASEFONT],[le.BGSOUND,w.BGSOUND],[le.BIG,w.BIG],[le.BLOCKQUOTE,w.BLOCKQUOTE],[le.BODY,w.BODY],[le.BR,w.BR],[le.BUTTON,w.BUTTON],[le.CAPTION,w.CAPTION],[le.CENTER,w.CENTER],[le.CODE,w.CODE],[le.COL,w.COL],[le.COLGROUP,w.COLGROUP],[le.DD,w.DD],[le.DESC,w.DESC],[le.DETAILS,w.DETAILS],[le.DIALOG,w.DIALOG],[le.DIR,w.DIR],[le.DIV,w.DIV],[le.DL,w.DL],[le.DT,w.DT],[le.EM,w.EM],[le.EMBED,w.EMBED],[le.FIELDSET,w.FIELDSET],[le.FIGCAPTION,w.FIGCAPTION],[le.FIGURE,w.FIGURE],[le.FONT,w.FONT],[le.FOOTER,w.FOOTER],[le.FOREIGN_OBJECT,w.FOREIGN_OBJECT],[le.FORM,w.FORM],[le.FRAME,w.FRAME],[le.FRAMESET,w.FRAMESET],[le.H1,w.H1],[le.H2,w.H2],[le.H3,w.H3],[le.H4,w.H4],[le.H5,w.H5],[le.H6,w.H6],[le.HEAD,w.HEAD],[le.HEADER,w.HEADER],[le.HGROUP,w.HGROUP],[le.HR,w.HR],[le.HTML,w.HTML],[le.I,w.I],[le.IMG,w.IMG],[le.IMAGE,w.IMAGE],[le.INPUT,w.INPUT],[le.IFRAME,w.IFRAME],[le.KEYGEN,w.KEYGEN],[le.LABEL,w.LABEL],[le.LI,w.LI],[le.LINK,w.LINK],[le.LISTING,w.LISTING],[le.MAIN,w.MAIN],[le.MALIGNMARK,w.MALIGNMARK],[le.MARQUEE,w.MARQUEE],[le.MATH,w.MATH],[le.MENU,w.MENU],[le.META,w.META],[le.MGLYPH,w.MGLYPH],[le.MI,w.MI],[le.MO,w.MO],[le.MN,w.MN],[le.MS,w.MS],[le.MTEXT,w.MTEXT],[le.NAV,w.NAV],[le.NOBR,w.NOBR],[le.NOFRAMES,w.NOFRAMES],[le.NOEMBED,w.NOEMBED],[le.NOSCRIPT,w.NOSCRIPT],[le.OBJECT,w.OBJECT],[le.OL,w.OL],[le.OPTGROUP,w.OPTGROUP],[le.OPTION,w.OPTION],[le.P,w.P],[le.PARAM,w.PARAM],[le.PLAINTEXT,w.PLAINTEXT],[le.PRE,w.PRE],[le.RB,w.RB],[le.RP,w.RP],[le.RT,w.RT],[le.RTC,w.RTC],[le.RUBY,w.RUBY],[le.S,w.S],[le.SCRIPT,w.SCRIPT],[le.SEARCH,w.SEARCH],[le.SECTION,w.SECTION],[le.SELECT,w.SELECT],[le.SOURCE,w.SOURCE],[le.SMALL,w.SMALL],[le.SPAN,w.SPAN],[le.STRIKE,w.STRIKE],[le.STRONG,w.STRONG],[le.STYLE,w.STYLE],[le.SUB,w.SUB],[le.SUMMARY,w.SUMMARY],[le.SUP,w.SUP],[le.TABLE,w.TABLE],[le.TBODY,w.TBODY],[le.TEMPLATE,w.TEMPLATE],[le.TEXTAREA,w.TEXTAREA],[le.TFOOT,w.TFOOT],[le.TD,w.TD],[le.TH,w.TH],[le.THEAD,w.THEAD],[le.TITLE,w.TITLE],[le.TR,w.TR],[le.TRACK,w.TRACK],[le.TT,w.TT],[le.U,w.U],[le.UL,w.UL],[le.SVG,w.SVG],[le.VAR,w.VAR],[le.WBR,w.WBR],[le.XMP,w.XMP]]);function nT(e){var t;return (t=b1t.get(e))!==null&&t!==void 0?t:w.UNKNOWN}var Ge=w,zFe={[Ne.HTML]:new Set([Ge.ADDRESS,Ge.APPLET,Ge.AREA,Ge.ARTICLE,Ge.ASIDE,Ge.BASE,Ge.BASEFONT,Ge.BGSOUND,Ge.BLOCKQUOTE,Ge.BODY,Ge.BR,Ge.BUTTON,Ge.CAPTION,Ge.CENTER,Ge.COL,Ge.COLGROUP,Ge.DD,Ge.DETAILS,Ge.DIR,Ge.DIV,Ge.DL,Ge.DT,Ge.EMBED,Ge.FIELDSET,Ge.FIGCAPTION,Ge.FIGURE,Ge.FOOTER,Ge.FORM,Ge.FRAME,Ge.FRAMESET,Ge.H1,Ge.H2,Ge.H3,Ge.H4,Ge.H5,Ge.H6,Ge.HEAD,Ge.HEADER,Ge.HGROUP,Ge.HR,Ge.HTML,Ge.IFRAME,Ge.IMG,Ge.INPUT,Ge.LI,Ge.LINK,Ge.LISTING,Ge.MAIN,Ge.MARQUEE,Ge.MENU,Ge.META,Ge.NAV,Ge.NOEMBED,Ge.NOFRAMES,Ge.NOSCRIPT,Ge.OBJECT,Ge.OL,Ge.P,Ge.PARAM,Ge.PLAINTEXT,Ge.PRE,Ge.SCRIPT,Ge.SECTION,Ge.SELECT,Ge.SOURCE,Ge.STYLE,Ge.SUMMARY,Ge.TABLE,Ge.TBODY,Ge.TD,Ge.TEMPLATE,Ge.TEXTAREA,Ge.TFOOT,Ge.TH,Ge.THEAD,Ge.TITLE,Ge.TR,Ge.TRACK,Ge.UL,Ge.WBR,Ge.XMP]),[Ne.MATHML]:new Set([Ge.MI,Ge.MO,Ge.MN,Ge.MS,Ge.MTEXT,Ge.ANNOTATION_XML]),[Ne.SVG]:new Set([Ge.TITLE,Ge.FOREIGN_OBJECT,Ge.DESC]),[Ne.XLINK]:new Set,[Ne.XML]:new Set,[Ne.XMLNS]:new Set},_O=new Set([Ge.H1,Ge.H2,Ge.H3,Ge.H4,Ge.H5,Ge.H6]);new Set([le.STYLE,le.SCRIPT,le.XMP,le.IFRAME,le.NOEMBED,le.NOFRAMES,le.PLAINTEXT]);var V;(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";})(V||(V={}));var xs={DATA:V.DATA,RCDATA:V.RCDATA,RAWTEXT:V.RAWTEXT,SCRIPT_DATA:V.SCRIPT_DATA,PLAINTEXT:V.PLAINTEXT,CDATA_SECTION:V.CDATA_SECTION};function T1t(e){return e>=H.DIGIT_0&&e<=H.DIGIT_9}function OO(e){return e>=H.LATIN_CAPITAL_A&&e<=H.LATIN_CAPITAL_Z}function v1t(e){return e>=H.LATIN_SMALL_A&&e<=H.LATIN_SMALL_Z}function Ly(e){return v1t(e)||OO(e)}function HFe(e){return Ly(e)||T1t(e)}function fz(e){return e+32}function GFe(e){return e===H.SPACE||e===H.LINE_FEED||e===H.TABULATION||e===H.FORM_FEED}function $Fe(e){return GFe(e)||e===H.SOLIDUS||e===H.GREATER_THAN_SIGN}function A1t(e){return e===H.NULL?Te.nullCharacterReference:e>1114111?Te.characterReferenceOutsideUnicodeRange:uz(e)?Te.surrogateCharacterReference:mz(e)?Te.noncharacterCharacterReference:dz(e)||e===H.CARRIAGE_RETURN?Te.controlCharacterReference:null}var PO=class{constructor(t,o){this.options=t,this.handler=o,this.paused=false,this.inLoop=false,this.inForeignNode=false,this.lastStartTagName="",this.active=false,this.state=V.DATA,this.returnState=V.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new pz(o),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new gz(H6,(n,r)=>{this.preprocessor.pos=this.entityStartPos+r-1,this._flushCodePointConsumedAsCharacterReference(n);},o.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(Te.missingSemicolonAfterCharacterReference,1);},absenceOfDigitsInNumericCharacterReference:n=>{this._err(Te.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+n);},validateNumericCharacterReference:n=>{let r=A1t(n);r&&this._err(r,1);}}:void 0);}_err(t,o=0){var n,r;(r=(n=this.handler).onParseError)===null||r===void 0||r.call(n,this.preprocessor.getError(t,o));}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,o,n){this.active=true,this.preprocessor.write(t,o),this._runParsingLoop(),this.paused||n?.();}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 o=0;o<t;o++)this.preprocessor.advance();}_consumeSequenceIfMatch(t,o){return this.preprocessor.startsWith(t,o)?(this._advanceBy(t.length-1),true):false}_createStartTagToken(){this.currentToken={type:hn.START_TAG,tagName:"",tagID:w.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(1)};}_createEndTagToken(){this.currentToken={type:hn.END_TAG,tagName:"",tagID:w.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(2)};}_createCommentToken(t){this.currentToken={type:hn.COMMENT,data:"",location:this.getCurrentLocation(t)};}_createDoctypeToken(t){this.currentToken={type:hn.DOCTYPE,name:t,forceQuirks:false,publicId:null,systemId:null,location:this.currentLocation};}_createCharacterToken(t,o){this.currentCharacterToken={type:t,chars:o,location:this.currentLocation};}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0);}_leaveAttrName(){var t,o;let n=this.currentToken;if(hz(n,this.currentAttr.name)===null){if(n.attrs.push(this.currentAttr),n.location&&this.currentLocation){let r=(t=(o=n.location).attrs)!==null&&t!==void 0?t:o.attrs=Object.create(null);r[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue();}}else this._err(Te.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=nT(t.tagName),t.type===hn.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(Te.endTagWithAttributes),t.selfClosing&&this._err(Te.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 hn.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case hn.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case hn.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:hn.EOF,location:t}),this.active=false;}_appendCharToCurrentCharacterToken(t,o){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=o;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,o);}_emitCodePoint(t){let o=GFe(t)?hn.WHITESPACE_CHARACTER:t===H.NULL?hn.NULL_CHARACTER:hn.CHARACTER;this._appendCharToCurrentCharacterToken(o,t<65536?String.fromCharCode(t):String.fromCodePoint(t));}_emitChars(t){this._appendCharToCurrentCharacterToken(hn.CHARACTER,t);}_startCharacterReference(){this.returnState=this.state,this.state=V.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?wp.Attribute:wp.Legacy);}_isCharacterReferenceInAttribute(){return this.returnState===V.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===V.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===V.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t);}_callState(t){switch(this.state){case V.DATA:{this._stateData(t);break}case V.RCDATA:{this._stateRcdata(t);break}case V.RAWTEXT:{this._stateRawtext(t);break}case V.SCRIPT_DATA:{this._stateScriptData(t);break}case V.PLAINTEXT:{this._statePlaintext(t);break}case V.TAG_OPEN:{this._stateTagOpen(t);break}case V.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case V.TAG_NAME:{this._stateTagName(t);break}case V.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case V.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case V.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case V.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case V.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case V.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case V.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case V.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case V.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case V.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case V.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case V.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case V.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case V.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case V.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case V.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case V.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case V.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case V.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case V.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case V.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case V.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case V.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case V.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case V.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case V.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case V.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case V.BOGUS_COMMENT:{this._stateBogusComment(t);break}case V.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case V.COMMENT_START:{this._stateCommentStart(t);break}case V.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case V.COMMENT:{this._stateComment(t);break}case V.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case V.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case V.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case V.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case V.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case V.COMMENT_END:{this._stateCommentEnd(t);break}case V.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case V.DOCTYPE:{this._stateDoctype(t);break}case V.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case V.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case V.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case V.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case V.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case V.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case V.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case V.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case V.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case V.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case V.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case V.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case V.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case V.CDATA_SECTION:{this._stateCdataSection(t);break}case V.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case V.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case V.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case V.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case H.LESS_THAN_SIGN:{this.state=V.TAG_OPEN;break}case H.AMPERSAND:{this._startCharacterReference();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitCodePoint(t);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRcdata(t){switch(t){case H.AMPERSAND:{this._startCharacterReference();break}case H.LESS_THAN_SIGN:{this.state=V.RCDATA_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRawtext(t){switch(t){case H.LESS_THAN_SIGN:{this.state=V.RAWTEXT_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptData(t){switch(t){case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_statePlaintext(t){switch(t){case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateTagOpen(t){if(Ly(t))this._createStartTagToken(),this.state=V.TAG_NAME,this._stateTagName(t);else switch(t){case H.EXCLAMATION_MARK:{this.state=V.MARKUP_DECLARATION_OPEN;break}case H.SOLIDUS:{this.state=V.END_TAG_OPEN;break}case H.QUESTION_MARK:{this._err(Te.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=V.BOGUS_COMMENT,this._stateBogusComment(t);break}case H.EOF:{this._err(Te.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(Te.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=V.DATA,this._stateData(t);}}_stateEndTagOpen(t){if(Ly(t))this._createEndTagToken(),this.state=V.TAG_NAME,this._stateTagName(t);else switch(t){case H.GREATER_THAN_SIGN:{this._err(Te.missingEndTagName),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(Te.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=V.BOGUS_COMMENT,this._stateBogusComment(t);}}_stateTagName(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BEFORE_ATTRIBUTE_NAME;break}case H.SOLIDUS:{this.state=V.SELF_CLOSING_START_TAG;break}case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentTagToken();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.tagName+=wr;break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:o.tagName+=String.fromCodePoint(OO(t)?fz(t):t);}}_stateRcdataLessThanSign(t){t===H.SOLIDUS?this.state=V.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=V.RCDATA,this._stateRcdata(t));}_stateRcdataEndTagOpen(t){Ly(t)?(this.state=V.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=V.RCDATA,this._stateRcdata(t));}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,false))return !this._ensureHibernation();this._createEndTagToken();let o=this.currentToken;switch(o.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=V.BEFORE_ATTRIBUTE_NAME,false;case H.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=V.SELF_CLOSING_START_TAG,false;case H.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=V.DATA,false;default:return !this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=V.RCDATA,this._stateRcdata(t));}_stateRawtextLessThanSign(t){t===H.SOLIDUS?this.state=V.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=V.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagOpen(t){Ly(t)?(this.state=V.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=V.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=V.RAWTEXT,this._stateRawtext(t));}_stateScriptDataLessThanSign(t){switch(t){case H.SOLIDUS:{this.state=V.SCRIPT_DATA_END_TAG_OPEN;break}case H.EXCLAMATION_MARK:{this.state=V.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=V.SCRIPT_DATA,this._stateScriptData(t);}}_stateScriptDataEndTagOpen(t){Ly(t)?(this.state=V.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=V.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=V.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStart(t){t===H.HYPHEN_MINUS?(this.state=V.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=V.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStartDash(t){t===H.HYPHEN_MINUS?(this.state=V.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=V.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscaped(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataEscapedDash(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.state=V.SCRIPT_DATA_ESCAPED,this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=V.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedDashDash(t){switch(t){case H.HYPHEN_MINUS:{this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case H.GREATER_THAN_SIGN:{this.state=V.SCRIPT_DATA,this._emitChars(">");break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.state=V.SCRIPT_DATA_ESCAPED,this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=V.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedLessThanSign(t){t===H.SOLIDUS?this.state=V.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Ly(t)?(this._emitChars("<"),this.state=V.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=V.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagOpen(t){Ly(t)?(this.state=V.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=V.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=V.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(yl.SCRIPT,false)&&$Fe(this.preprocessor.peek(yl.SCRIPT.length))){this._emitCodePoint(t);for(let o=0;o<yl.SCRIPT.length;o++)this._emitCodePoint(this._consume());this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED;}else this._ensureHibernation()||(this.state=V.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscaped(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDash(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case H.HYPHEN_MINUS:{this._emitChars("-");break}case H.LESS_THAN_SIGN:{this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case H.GREATER_THAN_SIGN:{this.state=V.SCRIPT_DATA,this._emitChars(">");break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(wr);break}case H.EOF:{this._err(Te.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedLessThanSign(t){t===H.SOLIDUS?(this.state=V.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(yl.SCRIPT,false)&&$Fe(this.preprocessor.peek(yl.SCRIPT.length))){this._emitCodePoint(t);for(let o=0;o<yl.SCRIPT.length;o++)this._emitCodePoint(this._consume());this.state=V.SCRIPT_DATA_ESCAPED;}else this._ensureHibernation()||(this.state=V.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateBeforeAttributeName(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.SOLIDUS:case H.GREATER_THAN_SIGN:case H.EOF:{this.state=V.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case H.EQUALS_SIGN:{this._err(Te.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=V.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=V.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateAttributeName(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:case H.SOLIDUS:case H.GREATER_THAN_SIGN:case H.EOF:{this._leaveAttrName(),this.state=V.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case H.EQUALS_SIGN:{this._leaveAttrName(),this.state=V.BEFORE_ATTRIBUTE_VALUE;break}case H.QUOTATION_MARK:case H.APOSTROPHE:case H.LESS_THAN_SIGN:{this._err(Te.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.currentAttr.name+=wr;break}default:this.currentAttr.name+=String.fromCodePoint(OO(t)?fz(t):t);}}_stateAfterAttributeName(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.SOLIDUS:{this.state=V.SELF_CLOSING_START_TAG;break}case H.EQUALS_SIGN:{this.state=V.BEFORE_ATTRIBUTE_VALUE;break}case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentTagToken();break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=V.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateBeforeAttributeValue(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.QUOTATION_MARK:{this.state=V.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case H.APOSTROPHE:{this.state=V.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingAttributeValue),this.state=V.DATA,this.emitCurrentTagToken();break}default:this.state=V.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t);}}_stateAttributeValueDoubleQuoted(t){switch(t){case H.QUOTATION_MARK:{this.state=V.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case H.AMPERSAND:{this._startCharacterReference();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.currentAttr.value+=wr;break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueSingleQuoted(t){switch(t){case H.APOSTROPHE:{this.state=V.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case H.AMPERSAND:{this._startCharacterReference();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.currentAttr.value+=wr;break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueUnquoted(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this._leaveAttrValue(),this.state=V.BEFORE_ATTRIBUTE_NAME;break}case H.AMPERSAND:{this._startCharacterReference();break}case H.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=V.DATA,this.emitCurrentTagToken();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),this.currentAttr.value+=wr;break}case H.QUOTATION_MARK:case H.APOSTROPHE:case H.LESS_THAN_SIGN:case H.EQUALS_SIGN:case H.GRAVE_ACCENT:{this._err(Te.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAfterAttributeValueQuoted(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this._leaveAttrValue(),this.state=V.BEFORE_ATTRIBUTE_NAME;break}case H.SOLIDUS:{this._leaveAttrValue(),this.state=V.SELF_CLOSING_START_TAG;break}case H.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=V.DATA,this.emitCurrentTagToken();break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this._err(Te.missingWhitespaceBetweenAttributes),this.state=V.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateSelfClosingStartTag(t){switch(t){case H.GREATER_THAN_SIGN:{let o=this.currentToken;o.selfClosing=true,this.state=V.DATA,this.emitCurrentTagToken();break}case H.EOF:{this._err(Te.eofInTag),this._emitEOFToken();break}default:this._err(Te.unexpectedSolidusInTag),this.state=V.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateBogusComment(t){let o=this.currentToken;switch(t){case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentComment(o);break}case H.EOF:{this.emitCurrentComment(o),this._emitEOFToken();break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.data+=wr;break}default:o.data+=String.fromCodePoint(t);}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(yl.DASH_DASH,true)?(this._createCommentToken(yl.DASH_DASH.length+1),this.state=V.COMMENT_START):this._consumeSequenceIfMatch(yl.DOCTYPE,false)?(this.currentLocation=this.getCurrentLocation(yl.DOCTYPE.length+1),this.state=V.DOCTYPE):this._consumeSequenceIfMatch(yl.CDATA_START,true)?this.inForeignNode?this.state=V.CDATA_SECTION:(this._err(Te.cdataInHtmlContent),this._createCommentToken(yl.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=V.BOGUS_COMMENT):this._ensureHibernation()||(this._err(Te.incorrectlyOpenedComment),this._createCommentToken(2),this.state=V.BOGUS_COMMENT,this._stateBogusComment(t));}_stateCommentStart(t){switch(t){case H.HYPHEN_MINUS:{this.state=V.COMMENT_START_DASH;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptClosingOfEmptyComment),this.state=V.DATA;let o=this.currentToken;this.emitCurrentComment(o);break}default:this.state=V.COMMENT,this._stateComment(t);}}_stateCommentStartDash(t){let o=this.currentToken;switch(t){case H.HYPHEN_MINUS:{this.state=V.COMMENT_END;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptClosingOfEmptyComment),this.state=V.DATA,this.emitCurrentComment(o);break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+="-",this.state=V.COMMENT,this._stateComment(t);}}_stateComment(t){let o=this.currentToken;switch(t){case H.HYPHEN_MINUS:{this.state=V.COMMENT_END_DASH;break}case H.LESS_THAN_SIGN:{o.data+="<",this.state=V.COMMENT_LESS_THAN_SIGN;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.data+=wr;break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+=String.fromCodePoint(t);}}_stateCommentLessThanSign(t){let o=this.currentToken;switch(t){case H.EXCLAMATION_MARK:{o.data+="!",this.state=V.COMMENT_LESS_THAN_SIGN_BANG;break}case H.LESS_THAN_SIGN:{o.data+="<";break}default:this.state=V.COMMENT,this._stateComment(t);}}_stateCommentLessThanSignBang(t){t===H.HYPHEN_MINUS?this.state=V.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=V.COMMENT,this._stateComment(t));}_stateCommentLessThanSignBangDash(t){t===H.HYPHEN_MINUS?this.state=V.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=V.COMMENT_END_DASH,this._stateCommentEndDash(t));}_stateCommentLessThanSignBangDashDash(t){t!==H.GREATER_THAN_SIGN&&t!==H.EOF&&this._err(Te.nestedComment),this.state=V.COMMENT_END,this._stateCommentEnd(t);}_stateCommentEndDash(t){let o=this.currentToken;switch(t){case H.HYPHEN_MINUS:{this.state=V.COMMENT_END;break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+="-",this.state=V.COMMENT,this._stateComment(t);}}_stateCommentEnd(t){let o=this.currentToken;switch(t){case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentComment(o);break}case H.EXCLAMATION_MARK:{this.state=V.COMMENT_END_BANG;break}case H.HYPHEN_MINUS:{o.data+="-";break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+="--",this.state=V.COMMENT,this._stateComment(t);}}_stateCommentEndBang(t){let o=this.currentToken;switch(t){case H.HYPHEN_MINUS:{o.data+="--!",this.state=V.COMMENT_END_DASH;break}case H.GREATER_THAN_SIGN:{this._err(Te.incorrectlyClosedComment),this.state=V.DATA,this.emitCurrentComment(o);break}case H.EOF:{this._err(Te.eofInComment),this.emitCurrentComment(o),this._emitEOFToken();break}default:o.data+="--!",this.state=V.COMMENT,this._stateComment(t);}}_stateDoctype(t){switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BEFORE_DOCTYPE_NAME;break}case H.GREATER_THAN_SIGN:{this.state=V.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case H.EOF:{this._err(Te.eofInDoctype),this._createDoctypeToken(null);let o=this.currentToken;o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingWhitespaceBeforeDoctypeName),this.state=V.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);}}_stateBeforeDoctypeName(t){if(OO(t))this._createDoctypeToken(String.fromCharCode(fz(t))),this.state=V.DOCTYPE_NAME;else switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.NULL:{this._err(Te.unexpectedNullCharacter),this._createDoctypeToken(wr),this.state=V.DOCTYPE_NAME;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypeName),this._createDoctypeToken(null);let o=this.currentToken;o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),this._createDoctypeToken(null);let o=this.currentToken;o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=V.DOCTYPE_NAME;}}_stateDoctypeName(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.AFTER_DOCTYPE_NAME;break}case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.name+=wr;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.name+=String.fromCodePoint(OO(t)?fz(t):t);}}_stateAfterDoctypeName(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(yl.PUBLIC,false)?this.state=V.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(yl.SYSTEM,false)?this.state=V.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(Te.invalidCharacterSequenceAfterDoctypeName),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t));}}_stateAfterDoctypePublicKeyword(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case H.QUOTATION_MARK:{this._err(Te.missingWhitespaceAfterDoctypePublicKeyword),o.publicId="",this.state=V.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{this._err(Te.missingWhitespaceAfterDoctypePublicKeyword),o.publicId="",this.state=V.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypePublicIdentifier),o.forceQuirks=true,this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypePublicIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypePublicIdentifier(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.QUOTATION_MARK:{o.publicId="",this.state=V.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{o.publicId="",this.state=V.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypePublicIdentifier),o.forceQuirks=true,this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypePublicIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypePublicIdentifierDoubleQuoted(t){let o=this.currentToken;switch(t){case H.QUOTATION_MARK:{this.state=V.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.publicId+=wr;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptDoctypePublicIdentifier),o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.publicId+=String.fromCodePoint(t);}}_stateDoctypePublicIdentifierSingleQuoted(t){let o=this.currentToken;switch(t){case H.APOSTROPHE:{this.state=V.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.publicId+=wr;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptDoctypePublicIdentifier),o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.publicId+=String.fromCodePoint(t);}}_stateAfterDoctypePublicIdentifier(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case H.GREATER_THAN_SIGN:{this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.QUOTATION_MARK:{this._err(Te.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{this._err(Te.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.GREATER_THAN_SIGN:{this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.QUOTATION_MARK:{o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateAfterDoctypeSystemKeyword(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:{this.state=V.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case H.QUOTATION_MARK:{this._err(Te.missingWhitespaceAfterDoctypeSystemKeyword),o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{this._err(Te.missingWhitespaceAfterDoctypeSystemKeyword),o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypeSystemIdentifier(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.QUOTATION_MARK:{o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case H.APOSTROPHE:{o.systemId="",this.state=V.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case H.GREATER_THAN_SIGN:{this._err(Te.missingDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.DATA,this.emitCurrentDoctype(o);break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.missingQuoteBeforeDoctypeSystemIdentifier),o.forceQuirks=true,this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypeSystemIdentifierDoubleQuoted(t){let o=this.currentToken;switch(t){case H.QUOTATION_MARK:{this.state=V.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.systemId+=wr;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptDoctypeSystemIdentifier),o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.systemId+=String.fromCodePoint(t);}}_stateDoctypeSystemIdentifierSingleQuoted(t){let o=this.currentToken;switch(t){case H.APOSTROPHE:{this.state=V.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case H.NULL:{this._err(Te.unexpectedNullCharacter),o.systemId+=wr;break}case H.GREATER_THAN_SIGN:{this._err(Te.abruptDoctypeSystemIdentifier),o.forceQuirks=true,this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:o.systemId+=String.fromCodePoint(t);}}_stateAfterDoctypeSystemIdentifier(t){let o=this.currentToken;switch(t){case H.SPACE:case H.LINE_FEED:case H.TABULATION:case H.FORM_FEED:break;case H.GREATER_THAN_SIGN:{this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.EOF:{this._err(Te.eofInDoctype),o.forceQuirks=true,this.emitCurrentDoctype(o),this._emitEOFToken();break}default:this._err(Te.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=V.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBogusDoctype(t){let o=this.currentToken;switch(t){case H.GREATER_THAN_SIGN:{this.emitCurrentDoctype(o),this.state=V.DATA;break}case H.NULL:{this._err(Te.unexpectedNullCharacter);break}case H.EOF:{this.emitCurrentDoctype(o),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case H.RIGHT_SQUARE_BRACKET:{this.state=V.CDATA_SECTION_BRACKET;break}case H.EOF:{this._err(Te.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateCdataSectionBracket(t){t===H.RIGHT_SQUARE_BRACKET?this.state=V.CDATA_SECTION_END:(this._emitChars("]"),this.state=V.CDATA_SECTION,this._stateCdataSection(t));}_stateCdataSectionEnd(t){switch(t){case H.GREATER_THAN_SIGN:{this.state=V.DATA;break}case H.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=V.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(H.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&HFe(this.preprocessor.peek(1))?V.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState;}_stateAmbiguousAmpersand(t){HFe(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===H.SEMICOLON&&this._err(Te.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t));}};var KFe=new Set([w.DD,w.DT,w.LI,w.OPTGROUP,w.OPTION,w.P,w.RB,w.RP,w.RT,w.RTC]),VFe=new Set([...KFe,w.CAPTION,w.COLGROUP,w.TBODY,w.TD,w.TFOOT,w.TH,w.THEAD,w.TR]),yz=new Set([w.APPLET,w.CAPTION,w.HTML,w.MARQUEE,w.OBJECT,w.TABLE,w.TD,w.TEMPLATE,w.TH]),E1t=new Set([...yz,w.OL,w.UL]),w1t=new Set([...yz,w.BUTTON]),WFe=new Set([w.ANNOTATION_XML,w.MI,w.MN,w.MO,w.MS,w.MTEXT]),qFe=new Set([w.DESC,w.FOREIGN_OBJECT,w.TITLE]),R1t=new Set([w.TR,w.TEMPLATE,w.HTML]),C1t=new Set([w.TBODY,w.TFOOT,w.THEAD,w.TEMPLATE,w.HTML]),I1t=new Set([w.TABLE,w.TEMPLATE,w.HTML]),x1t=new Set([w.TD,w.TH]),bz=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,o,n){this.treeAdapter=o,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=w.UNKNOWN,this.current=t;}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===w.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===Ne.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop];}push(t,o){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=o,this.currentTagId=o,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,o,true);}pop(){let t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,true);}replace(t,o){let n=this._indexOf(t);this.items[n]=o,n===this.stackTop&&(this.current=o);}insertAfter(t,o,n){let r=this._indexOf(t)+1;this.items.splice(r,0,o),this.tagIDs.splice(r,0,n),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 o=this.stackTop+1;do o=this.tagIDs.lastIndexOf(t,o-1);while(o>0&&this.treeAdapter.getNamespaceURI(this.items[o])!==Ne.HTML);this.shortenToLength(Math.max(o,0));}shortenToLength(t){for(;this.stackTop>=t;){let o=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(o,this.stackTop<t);}}popUntilElementPopped(t){let o=this._indexOf(t);this.shortenToLength(Math.max(o,0));}popUntilPopped(t,o){let n=this._indexOfTagNames(t,o);this.shortenToLength(Math.max(n,0));}popUntilNumberedHeaderPopped(){this.popUntilPopped(_O,Ne.HTML);}popUntilTableCellPopped(){this.popUntilPopped(x1t,Ne.HTML);}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1);}_indexOfTagNames(t,o){for(let n=this.stackTop;n>=0;n--)if(t.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===o)return n;return -1}clearBackTo(t,o){let n=this._indexOfTagNames(t,o);this.shortenToLength(n+1);}clearBackToTableContext(){this.clearBackTo(I1t,Ne.HTML);}clearBackToTableBodyContext(){this.clearBackTo(C1t,Ne.HTML);}clearBackToTableRowContext(){this.clearBackTo(R1t,Ne.HTML);}remove(t){let o=this._indexOf(t);o>=0&&(o===this.stackTop?this.pop():(this.items.splice(o,1),this.tagIDs.splice(o,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,false)));}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===w.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){let o=this._indexOf(t)-1;return o>=0?this.items[o]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===w.HTML}hasInDynamicScope(t,o){for(let n=this.stackTop;n>=0;n--){let r=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case Ne.HTML:{if(r===t)return true;if(o.has(r))return false;break}case Ne.SVG:{if(qFe.has(r))return false;break}case Ne.MATHML:{if(WFe.has(r))return false;break}}}return true}hasInScope(t){return this.hasInDynamicScope(t,yz)}hasInListItemScope(t){return this.hasInDynamicScope(t,E1t)}hasInButtonScope(t){return this.hasInDynamicScope(t,w1t)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){let o=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case Ne.HTML:{if(_O.has(o))return true;if(yz.has(o))return false;break}case Ne.SVG:{if(qFe.has(o))return false;break}case Ne.MATHML:{if(WFe.has(o))return false;break}}}return true}hasInTableScope(t){for(let o=this.stackTop;o>=0;o--)if(this.treeAdapter.getNamespaceURI(this.items[o])===Ne.HTML)switch(this.tagIDs[o]){case t:return true;case w.TABLE:case w.HTML:return false}return true}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===Ne.HTML)switch(this.tagIDs[t]){case w.TBODY:case w.THEAD:case w.TFOOT:return true;case w.TABLE:case w.HTML:return false}return true}hasInSelectScope(t){for(let o=this.stackTop;o>=0;o--)if(this.treeAdapter.getNamespaceURI(this.items[o])===Ne.HTML)switch(this.tagIDs[o]){case t:return true;case w.OPTION:case w.OPTGROUP:break;default:return false}return true}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&KFe.has(this.currentTagId);)this.pop();}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&VFe.has(this.currentTagId);)this.pop();}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&VFe.has(this.currentTagId);)this.pop();}};var jd;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element";})(jd||(jd={}));var YFe={type:jd.Marker},Sz=class{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null;}_getNoahArkConditionCandidates(t,o){let n=[],r=o.length,i=this.treeAdapter.getTagName(t),a=this.treeAdapter.getNamespaceURI(t);for(let s=0;s<this.entries.length;s++){let l=this.entries[s];if(l.type===jd.Marker)break;let{element:c}=l;if(this.treeAdapter.getTagName(c)===i&&this.treeAdapter.getNamespaceURI(c)===a){let u=this.treeAdapter.getAttrList(c);u.length===r&&n.push({idx:s,attrs:u});}}return n}_ensureNoahArkCondition(t){if(this.entries.length<3)return;let o=this.treeAdapter.getAttrList(t),n=this._getNoahArkConditionCandidates(t,o);if(n.length<3)return;let r=new Map(o.map(a=>[a.name,a.value])),i=0;for(let a=0;a<n.length;a++){let s=n[a];s.attrs.every(l=>r.get(l.name)===l.value)&&(i+=1,i>=3&&this.entries.splice(s.idx,1));}}insertMarker(){this.entries.unshift(YFe);}pushElement(t,o){this._ensureNoahArkCondition(t),this.entries.unshift({type:jd.Element,element:t,token:o});}insertElementAfterBookmark(t,o){let n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:jd.Element,element:t,token:o});}removeEntry(t){let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1);}clearToLastMarker(){let t=this.entries.indexOf(YFe);t===-1?this.entries.length=0:this.entries.splice(0,t+1);}getElementEntryInScopeWithTagName(t){let o=this.entries.find(n=>n.type===jd.Marker||this.treeAdapter.getTagName(n.element)===t);return o&&o.type===jd.Element?o:null}getElementEntry(t){return this.entries.find(o=>o.type===jd.Element&&o.element===t)}};var zd={createDocument(){return {nodeName:"#document",mode:bl.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return {nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,o){return {nodeName:e,tagName:e,attrs:o,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,o){let n=e.childNodes.indexOf(o);e.childNodes.splice(n,0,t),t.parentNode=e;},setTemplateContent(e,t){e.content=t;},getTemplateContent(e){return e.content},setDocumentType(e,t,o,n){let r=e.childNodes.find(i=>i.nodeName==="#documentType");if(r)r.name=t,r.publicId=o,r.systemId=n;else {let i={nodeName:"#documentType",name:t,publicId:o,systemId:n,parentNode:null};zd.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 o=e.childNodes[e.childNodes.length-1];if(zd.isTextNode(o)){o.value+=t;return}}zd.appendChild(e,zd.createTextNode(t));},insertTextBefore(e,t,o){let n=e.childNodes[e.childNodes.indexOf(o)-1];n&&zd.isTextNode(n)?n.value+=t:zd.insertBefore(e,zd.createTextNode(t),o);},adoptAttributes(e,t){let o=new Set(e.attrs.map(n=>n.name));for(let n=0;n<t.length;n++)o.has(t[n].name)||e.attrs.push(t[n]);},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 XFe="html",_1t="about:legacy-compat",O1t="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",QFe=["+//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//"],P1t=[...QFe,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],k1t=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),ZFe=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],M1t=[...ZFe,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function JFe(e,t){return t.some(o=>e.startsWith(o))}function eBe(e){return e.name===XFe&&e.publicId===null&&(e.systemId===null||e.systemId===_1t)}function tBe(e){if(e.name!==XFe)return bl.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===O1t)return bl.QUIRKS;let{publicId:o}=e;if(o!==null){if(o=o.toLowerCase(),k1t.has(o))return bl.QUIRKS;let n=t===null?P1t:QFe;if(JFe(o,n))return bl.QUIRKS;if(n=t===null?ZFe:M1t,JFe(o,n))return bl.LIMITED_QUIRKS}return bl.NO_QUIRKS}var oBe={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},N1t="definitionurl",D1t="definitionURL",F1t=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])),B1t=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:Ne.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:Ne.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:Ne.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:Ne.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:Ne.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:Ne.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:Ne.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:Ne.XML}],["xml:space",{prefix:"xml",name:"space",namespace:Ne.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:Ne.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:Ne.XMLNS}]]),U1t=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])),j1t=new Set([w.B,w.BIG,w.BLOCKQUOTE,w.BODY,w.BR,w.CENTER,w.CODE,w.DD,w.DIV,w.DL,w.DT,w.EM,w.EMBED,w.H1,w.H2,w.H3,w.H4,w.H5,w.H6,w.HEAD,w.HR,w.I,w.IMG,w.LI,w.LISTING,w.MENU,w.META,w.NOBR,w.OL,w.P,w.PRE,w.RUBY,w.S,w.SMALL,w.SPAN,w.STRONG,w.STRIKE,w.SUB,w.SUP,w.TABLE,w.TT,w.U,w.UL,w.VAR]);function nBe(e){let t=e.tagID;return t===w.FONT&&e.attrs.some(({name:n})=>n===ag.COLOR||n===ag.SIZE||n===ag.FACE)||j1t.has(t)}function G6(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===N1t){e.attrs[t].name=D1t;break}}function V6(e){for(let t=0;t<e.attrs.length;t++){let o=F1t.get(e.attrs[t].name);o!=null&&(e.attrs[t].name=o);}}function Tz(e){for(let t=0;t<e.attrs.length;t++){let o=B1t.get(e.attrs[t].name);o&&(e.attrs[t].prefix=o.prefix,e.attrs[t].name=o.name,e.attrs[t].namespace=o.namespace);}}function rBe(e){let t=U1t.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=nT(e.tagName));}function z1t(e,t){return t===Ne.MATHML&&(e===w.MI||e===w.MO||e===w.MN||e===w.MS||e===w.MTEXT)}function H1t(e,t,o){if(t===Ne.MATHML&&e===w.ANNOTATION_XML){for(let n=0;n<o.length;n++)if(o[n].name===ag.ENCODING){let r=o[n].value.toLowerCase();return r===oBe.TEXT_HTML||r===oBe.APPLICATION_XML}}return t===Ne.SVG&&(e===w.FOREIGN_OBJECT||e===w.DESC||e===w.TITLE)}function iBe(e,t,o,n){return (!n||n===Ne.HTML)&&H1t(e,t,o)||(!n||n===Ne.MATHML)&&z1t(e,t)}var $1t="hidden",G1t=8,V1t=3,Y;(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";})(Y||(Y={}));var W1t={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},uBe=new Set([w.TABLE,w.TBODY,w.TFOOT,w.THEAD,w.TR]),sBe={scriptingEnabled:true,sourceCodeLocationInfo:false,treeAdapter:zd,onParseError:null},UO=class{constructor(t,o,n=null,r=null){this.fragmentContext=n,this.scriptHandler=r,this.currentToken=null,this.stopped=false,this.insertionMode=Y.INITIAL,this.originalInsertionMode=Y.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={...sBe,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=true),this.document=o??this.treeAdapter.createDocument(),this.tokenizer=new PO(this.options,this),this.activeFormattingElements=new Sz(this.treeAdapter),this.fragmentContextID=n?nT(this.treeAdapter.getTagName(n)):w.UNKNOWN,this._setContextModes(n??this.document,this.fragmentContextID),this.openElements=new bz(this.document,this.treeAdapter,this);}static parse(t,o){let n=new this(o);return n.tokenizer.write(t,true),n.document}static getFragmentParser(t,o){let n={...sBe,...o};t??(t=n.treeAdapter.createElement(le.TEMPLATE,Ne.HTML,[]));let r=n.treeAdapter.createElement("documentmock",Ne.HTML,[]),i=new this(n,r,t);return i.fragmentContextID===w.TEMPLATE&&i.tmplInsertionModeStack.unshift(Y.IN_TEMPLATE),i._initTokenizerForFragmentParsing(),i._insertFakeRootElement(),i._resetInsertionMode(),i._findFormInFragmentContext(),i}getFragment(){let t=this.treeAdapter.getFirstChild(this.document),o=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,o),o}_err(t,o,n){var r;if(!this.onParseError)return;let i=(r=t.location)!==null&&r!==void 0?r:W1t,a={code:o,startLine:i.startLine,startCol:i.startCol,startOffset:i.startOffset,endLine:n?i.startLine:i.endLine,endCol:n?i.startCol:i.endCol,endOffset:n?i.startOffset:i.endOffset};this.onParseError(a);}onItemPush(t,o,n){var r,i;(i=(r=this.treeAdapter).onItemPush)===null||i===void 0||i.call(r,t),n&&this.openElements.stackTop>0&&this._setContextModes(t,o);}onItemPop(t,o){var n,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(r=(n=this.treeAdapter).onItemPop)===null||r===void 0||r.call(n,t,this.openElements.current),o){let i,a;this.openElements.stackTop===0&&this.fragmentContext?(i=this.fragmentContext,a=this.fragmentContextID):{current:i,currentTagId:a}=this.openElements,this._setContextModes(i,a);}}_setContextModes(t,o){let n=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===Ne.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&t!==void 0&&o!==void 0&&!this._isIntegrationPoint(o,t);}_switchToTextParsing(t,o){this._insertElement(t,Ne.HTML),this.tokenizer.state=o,this.originalInsertionMode=this.insertionMode,this.insertionMode=Y.TEXT;}switchToPlaintextParsing(){this.insertionMode=Y.TEXT,this.originalInsertionMode=Y.IN_BODY,this.tokenizer.state=xs.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)===le.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t);}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==Ne.HTML))switch(this.fragmentContextID){case w.TITLE:case w.TEXTAREA:{this.tokenizer.state=xs.RCDATA;break}case w.STYLE:case w.XMP:case w.IFRAME:case w.NOEMBED:case w.NOFRAMES:case w.NOSCRIPT:{this.tokenizer.state=xs.RAWTEXT;break}case w.SCRIPT:{this.tokenizer.state=xs.SCRIPT_DATA;break}case w.PLAINTEXT:{this.tokenizer.state=xs.PLAINTEXT;break}}}_setDocumentType(t){let o=t.name||"",n=t.publicId||"",r=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,o,n,r),t.location){let a=this.treeAdapter.getChildNodes(this.document).find(s=>this.treeAdapter.isDocumentTypeNode(s));a&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location);}}_attachElementToTree(t,o){if(this.options.sourceCodeLocationInfo){let n=o&&{...o,startTag:o};this.treeAdapter.setNodeSourceCodeLocation(t,n);}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else {let n=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(n??this.document,t);}}_appendElement(t,o){let n=this.treeAdapter.createElement(t.tagName,o,t.attrs);this._attachElementToTree(n,t.location);}_insertElement(t,o){let n=this.treeAdapter.createElement(t.tagName,o,t.attrs);this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID);}_insertFakeElement(t,o){let n=this.treeAdapter.createElement(t,Ne.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,o);}_insertTemplate(t){let o=this.treeAdapter.createElement(t.tagName,Ne.HTML,t.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(o,n),this._attachElementToTree(o,t.location),this.openElements.push(o,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null);}_insertFakeRootElement(){let t=this.treeAdapter.createElement(le.HTML,Ne.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,w.HTML);}_appendCommentNode(t,o){let n=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(o,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,t.location);}_insertCharacters(t){let o,n;if(this._shouldFosterParentOnInsertion()?({parent:o,beforeElement:n}=this._findFosterParentingLocation(),n?this.treeAdapter.insertTextBefore(o,t.chars,n):this.treeAdapter.insertText(o,t.chars)):(o=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(o,t.chars)),!t.location)return;let r=this.treeAdapter.getChildNodes(o),i=n?r.lastIndexOf(n):r.length,a=r[i-1];if(this.treeAdapter.getNodeSourceCodeLocation(a)){let{endLine:l,endCol:c,endOffset:u}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(a,{endLine:l,endCol:c,endOffset:u});}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location);}_adoptNodes(t,o){for(let n=this.treeAdapter.getFirstChild(t);n;n=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(o,n);}_setEndLocation(t,o){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&o.location){let n=o.location,r=this.treeAdapter.getTagName(t),i=o.type===hn.END_TAG&&r===o.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,i);}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return false;let o,n;return this.openElements.stackTop===0&&this.fragmentContext?(o=this.fragmentContext,n=this.fragmentContextID):{current:o,currentTagId:n}=this.openElements,t.tagID===w.SVG&&this.treeAdapter.getTagName(o)===le.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(o)===Ne.MATHML?false:this.tokenizer.inForeignNode||(t.tagID===w.MGLYPH||t.tagID===w.MALIGNMARK)&&n!==void 0&&!this._isIntegrationPoint(n,o,Ne.HTML)}_processToken(t){switch(t.type){case hn.CHARACTER:{this.onCharacter(t);break}case hn.NULL_CHARACTER:{this.onNullCharacter(t);break}case hn.COMMENT:{this.onComment(t);break}case hn.DOCTYPE:{this.onDoctype(t);break}case hn.START_TAG:{this._processStartTag(t);break}case hn.END_TAG:{this.onEndTag(t);break}case hn.EOF:{this.onEof(t);break}case hn.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,o,n){let r=this.treeAdapter.getNamespaceURI(o),i=this.treeAdapter.getAttrList(o);return iBe(t,r,i,n)}_reconstructActiveFormattingElements(){let t=this.activeFormattingElements.entries.length;if(t){let o=this.activeFormattingElements.entries.findIndex(r=>r.type===jd.Marker||this.openElements.contains(r.element)),n=o===-1?t-1:o-1;for(let r=n;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=Y.IN_ROW;}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(w.P),this.openElements.popUntilTagNamePopped(w.P);}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case w.TR:{this.insertionMode=Y.IN_ROW;return}case w.TBODY:case w.THEAD:case w.TFOOT:{this.insertionMode=Y.IN_TABLE_BODY;return}case w.CAPTION:{this.insertionMode=Y.IN_CAPTION;return}case w.COLGROUP:{this.insertionMode=Y.IN_COLUMN_GROUP;return}case w.TABLE:{this.insertionMode=Y.IN_TABLE;return}case w.BODY:{this.insertionMode=Y.IN_BODY;return}case w.FRAMESET:{this.insertionMode=Y.IN_FRAMESET;return}case w.SELECT:{this._resetInsertionModeForSelect(t);return}case w.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case w.HTML:{this.insertionMode=this.headElement?Y.AFTER_HEAD:Y.BEFORE_HEAD;return}case w.TD:case w.TH:{if(t>0){this.insertionMode=Y.IN_CELL;return}break}case w.HEAD:{if(t>0){this.insertionMode=Y.IN_HEAD;return}break}}this.insertionMode=Y.IN_BODY;}_resetInsertionModeForSelect(t){if(t>0)for(let o=t-1;o>0;o--){let n=this.openElements.tagIDs[o];if(n===w.TEMPLATE)break;if(n===w.TABLE){this.insertionMode=Y.IN_SELECT_IN_TABLE;return}}this.insertionMode=Y.IN_SELECT;}_isElementCausesFosterParenting(t){return uBe.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 o=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case w.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(o)===Ne.HTML)return {parent:this.treeAdapter.getTemplateContent(o),beforeElement:null};break}case w.TABLE:{let n=this.treeAdapter.getParentNode(o);return n?{parent:n,beforeElement:o}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return {parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){let o=this._findFosterParentingLocation();o.beforeElement?this.treeAdapter.insertBefore(o.parent,t,o.beforeElement):this.treeAdapter.appendChild(o.parent,t);}_isSpecialElement(t,o){let n=this.treeAdapter.getNamespaceURI(t);return zFe[n].has(o)}onCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){A2t(this,t);return}switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{LO(this,t);break}case Y.BEFORE_HEAD:{NO(this,t);break}case Y.IN_HEAD:{DO(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{FO(this,t);break}case Y.AFTER_HEAD:{BO(this,t);break}case Y.IN_BODY:case Y.IN_CAPTION:case Y.IN_CELL:case Y.IN_TEMPLATE:{mBe(this,t);break}case Y.TEXT:case Y.IN_SELECT:case Y.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case Y.IN_TABLE:case Y.IN_TABLE_BODY:case Y.IN_ROW:{W6(this,t);break}case Y.IN_TABLE_TEXT:{bBe(this,t);break}case Y.IN_COLUMN_GROUP:{Az(this,t);break}case Y.AFTER_BODY:{Ez(this,t);break}case Y.AFTER_AFTER_BODY:{vz(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){v2t(this,t);return}switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{LO(this,t);break}case Y.BEFORE_HEAD:{NO(this,t);break}case Y.IN_HEAD:{DO(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{FO(this,t);break}case Y.AFTER_HEAD:{BO(this,t);break}case Y.TEXT:{this._insertCharacters(t);break}case Y.IN_TABLE:case Y.IN_TABLE_BODY:case Y.IN_ROW:{W6(this,t);break}case Y.IN_COLUMN_GROUP:{Az(this,t);break}case Y.AFTER_BODY:{Ez(this,t);break}case Y.AFTER_AFTER_BODY:{vz(this,t);break}}}onComment(t){if(this.skipNextNewLine=false,this.currentNotInHTML){q6(this,t);return}switch(this.insertionMode){case Y.INITIAL:case Y.BEFORE_HTML:case Y.BEFORE_HEAD:case Y.IN_HEAD:case Y.IN_HEAD_NO_SCRIPT:case Y.AFTER_HEAD:case Y.IN_BODY:case Y.IN_TABLE:case Y.IN_CAPTION:case Y.IN_COLUMN_GROUP:case Y.IN_TABLE_BODY:case Y.IN_ROW:case Y.IN_CELL:case Y.IN_SELECT:case Y.IN_SELECT_IN_TABLE:case Y.IN_TEMPLATE:case Y.IN_FRAMESET:case Y.AFTER_FRAMESET:{q6(this,t);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}case Y.AFTER_BODY:{Z1t(this,t);break}case Y.AFTER_AFTER_BODY:case Y.AFTER_AFTER_FRAMESET:{eGt(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=false,this.insertionMode){case Y.INITIAL:{tGt(this,t);break}case Y.BEFORE_HEAD:case Y.IN_HEAD:case Y.IN_HEAD_NO_SCRIPT:case Y.AFTER_HEAD:{this._err(t,Te.misplacedDoctype);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}}}onStartTag(t){this.skipNextNewLine=false,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,Te.nonVoidHtmlElementStartTagWithTrailingSolidus);}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?E2t(this,t):this._startTagOutsideForeignContent(t);}_startTagOutsideForeignContent(t){switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{oGt(this,t);break}case Y.BEFORE_HEAD:{rGt(this,t);break}case Y.IN_HEAD:{Hd(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{sGt(this,t);break}case Y.AFTER_HEAD:{cGt(this,t);break}case Y.IN_BODY:{_s(this,t);break}case Y.IN_TABLE:{Ow(this,t);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}case Y.IN_CAPTION:{i2t(this,t);break}case Y.IN_COLUMN_GROUP:{X6(this,t);break}case Y.IN_TABLE_BODY:{Cz(this,t);break}case Y.IN_ROW:{Iz(this,t);break}case Y.IN_CELL:{l2t(this,t);break}case Y.IN_SELECT:{vBe(this,t);break}case Y.IN_SELECT_IN_TABLE:{u2t(this,t);break}case Y.IN_TEMPLATE:{m2t(this,t);break}case Y.AFTER_BODY:{h2t(this,t);break}case Y.IN_FRAMESET:{g2t(this,t);break}case Y.AFTER_FRAMESET:{y2t(this,t);break}case Y.AFTER_AFTER_BODY:{S2t(this,t);break}case Y.AFTER_AFTER_FRAMESET:{T2t(this,t);break}}}onEndTag(t){this.skipNextNewLine=false,this.currentToken=t,this.currentNotInHTML?w2t(this,t):this._endTagOutsideForeignContent(t);}_endTagOutsideForeignContent(t){switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{nGt(this,t);break}case Y.BEFORE_HEAD:{iGt(this,t);break}case Y.IN_HEAD:{aGt(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{lGt(this,t);break}case Y.AFTER_HEAD:{uGt(this,t);break}case Y.IN_BODY:{Rz(this,t);break}case Y.TEXT:{YGt(this,t);break}case Y.IN_TABLE:{jO(this,t);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}case Y.IN_CAPTION:{a2t(this,t);break}case Y.IN_COLUMN_GROUP:{s2t(this,t);break}case Y.IN_TABLE_BODY:{K6(this,t);break}case Y.IN_ROW:{TBe(this,t);break}case Y.IN_CELL:{c2t(this,t);break}case Y.IN_SELECT:{ABe(this,t);break}case Y.IN_SELECT_IN_TABLE:{d2t(this,t);break}case Y.IN_TEMPLATE:{p2t(this,t);break}case Y.AFTER_BODY:{wBe(this,t);break}case Y.IN_FRAMESET:{f2t(this,t);break}case Y.AFTER_FRAMESET:{b2t(this,t);break}case Y.AFTER_AFTER_BODY:{vz(this,t);break}}}onEof(t){switch(this.insertionMode){case Y.INITIAL:{kO(this,t);break}case Y.BEFORE_HTML:{LO(this,t);break}case Y.BEFORE_HEAD:{NO(this,t);break}case Y.IN_HEAD:{DO(this,t);break}case Y.IN_HEAD_NO_SCRIPT:{FO(this,t);break}case Y.AFTER_HEAD:{BO(this,t);break}case Y.IN_BODY:case Y.IN_TABLE:case Y.IN_CAPTION:case Y.IN_COLUMN_GROUP:case Y.IN_TABLE_BODY:case Y.IN_ROW:case Y.IN_CELL:case Y.IN_SELECT:case Y.IN_SELECT_IN_TABLE:{fBe(this,t);break}case Y.TEXT:{JGt(this,t);break}case Y.IN_TABLE_TEXT:{MO(this,t);break}case Y.IN_TEMPLATE:{EBe(this,t);break}case Y.AFTER_BODY:case Y.IN_FRAMESET:case Y.AFTER_FRAMESET:case Y.AFTER_AFTER_BODY:case Y.AFTER_AFTER_FRAMESET:{J6(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=false,t.chars.charCodeAt(0)===H.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 Y.IN_HEAD:case Y.IN_HEAD_NO_SCRIPT:case Y.AFTER_HEAD:case Y.TEXT:case Y.IN_COLUMN_GROUP:case Y.IN_SELECT:case Y.IN_SELECT_IN_TABLE:case Y.IN_FRAMESET:case Y.AFTER_FRAMESET:{this._insertCharacters(t);break}case Y.IN_BODY:case Y.IN_CAPTION:case Y.IN_CELL:case Y.IN_TEMPLATE:case Y.AFTER_BODY:case Y.AFTER_AFTER_BODY:case Y.AFTER_AFTER_FRAMESET:{dBe(this,t);break}case Y.IN_TABLE:case Y.IN_TABLE_BODY:case Y.IN_ROW:{W6(this,t);break}case Y.IN_TABLE_TEXT:{yBe(this,t);break}}}};function q1t(e,t){let o=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return o?e.openElements.contains(o.element)?e.openElements.hasInScope(t.tagID)||(o=null):(e.activeFormattingElements.removeEntry(o),o=null):gBe(e,t),o}function K1t(e,t){let o=null,n=e.openElements.stackTop;for(;n>=0;n--){let r=e.openElements.items[n];if(r===t.element)break;e._isSpecialElement(r,e.openElements.tagIDs[n])&&(o=r);}return o||(e.openElements.shortenToLength(Math.max(n,0)),e.activeFormattingElements.removeEntry(t)),o}function Y1t(e,t,o){let n=t,r=e.openElements.getCommonAncestor(t);for(let i=0,a=r;a!==o;i++,a=r){r=e.openElements.getCommonAncestor(a);let s=e.activeFormattingElements.getElementEntry(a),l=s&&i>=V1t;!s||l?(l&&e.activeFormattingElements.removeEntry(s),e.openElements.remove(a)):(a=J1t(e,s),n===t&&(e.activeFormattingElements.bookmark=s),e.treeAdapter.detachNode(n),e.treeAdapter.appendChild(a,n),n=a);}return n}function J1t(e,t){let o=e.treeAdapter.getNamespaceURI(t.element),n=e.treeAdapter.createElement(t.token.tagName,o,t.token.attrs);return e.openElements.replace(t.element,n),t.element=n,n}function X1t(e,t,o){let n=e.treeAdapter.getTagName(t),r=nT(n);if(e._isElementCausesFosterParenting(r))e._fosterParentElement(o);else {let i=e.treeAdapter.getNamespaceURI(t);r===w.TEMPLATE&&i===Ne.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,o);}}function Q1t(e,t,o){let n=e.treeAdapter.getNamespaceURI(o.element),{token:r}=o,i=e.treeAdapter.createElement(r.tagName,n,r.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,r),e.activeFormattingElements.removeEntry(o),e.openElements.remove(o.element),e.openElements.insertAfter(t,i,r.tagID);}function Y6(e,t){for(let o=0;o<G1t;o++){let n=q1t(e,t);if(!n)break;let r=K1t(e,n);if(!r)break;e.activeFormattingElements.bookmark=n;let i=Y1t(e,r,n.element),a=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(i),a&&X1t(e,a,i),Q1t(e,r,n);}}function q6(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode);}function Z1t(e,t){e._appendCommentNode(t,e.openElements.items[0]);}function eGt(e,t){e._appendCommentNode(t,e.document);}function J6(e,t){if(e.stopped=true,t.location){let o=e.fragmentContext?0:2;for(let n=e.openElements.stackTop;n>=o;n--)e._setEndLocation(e.openElements.items[n],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){let n=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(n);if(r&&!r.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){let i=e.openElements.items[1],a=e.treeAdapter.getNodeSourceCodeLocation(i);a&&!a.endTag&&e._setEndLocation(i,t);}}}}function tGt(e,t){e._setDocumentType(t);let o=t.forceQuirks?bl.QUIRKS:tBe(t);eBe(t)||e._err(t,Te.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,o),e.insertionMode=Y.BEFORE_HTML;}function kO(e,t){e._err(t,Te.missingDoctype,true),e.treeAdapter.setDocumentMode(e.document,bl.QUIRKS),e.insertionMode=Y.BEFORE_HTML,e._processToken(t);}function oGt(e,t){t.tagID===w.HTML?(e._insertElement(t,Ne.HTML),e.insertionMode=Y.BEFORE_HEAD):LO(e,t);}function nGt(e,t){let o=t.tagID;(o===w.HTML||o===w.HEAD||o===w.BODY||o===w.BR)&&LO(e,t);}function LO(e,t){e._insertFakeRootElement(),e.insertionMode=Y.BEFORE_HEAD,e._processToken(t);}function rGt(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.HEAD:{e._insertElement(t,Ne.HTML),e.headElement=e.openElements.current,e.insertionMode=Y.IN_HEAD;break}default:NO(e,t);}}function iGt(e,t){let o=t.tagID;o===w.HEAD||o===w.BODY||o===w.HTML||o===w.BR?NO(e,t):e._err(t,Te.endTagWithoutMatchingOpenElement);}function NO(e,t){e._insertFakeElement(le.HEAD,w.HEAD),e.headElement=e.openElements.current,e.insertionMode=Y.IN_HEAD,e._processToken(t);}function Hd(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.BASE:case w.BASEFONT:case w.BGSOUND:case w.LINK:case w.META:{e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;break}case w.TITLE:{e._switchToTextParsing(t,xs.RCDATA);break}case w.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,xs.RAWTEXT):(e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_HEAD_NO_SCRIPT);break}case w.NOFRAMES:case w.STYLE:{e._switchToTextParsing(t,xs.RAWTEXT);break}case w.SCRIPT:{e._switchToTextParsing(t,xs.SCRIPT_DATA);break}case w.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=false,e.insertionMode=Y.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(Y.IN_TEMPLATE);break}case w.HEAD:{e._err(t,Te.misplacedStartTagForHeadElement);break}default:DO(e,t);}}function aGt(e,t){switch(t.tagID){case w.HEAD:{e.openElements.pop(),e.insertionMode=Y.AFTER_HEAD;break}case w.BODY:case w.BR:case w.HTML:{DO(e,t);break}case w.TEMPLATE:{rT(e,t);break}default:e._err(t,Te.endTagWithoutMatchingOpenElement);}}function rT(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==w.TEMPLATE&&e._err(t,Te.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(w.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,Te.endTagWithoutMatchingOpenElement);}function DO(e,t){e.openElements.pop(),e.insertionMode=Y.AFTER_HEAD,e._processToken(t);}function sGt(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.BASEFONT:case w.BGSOUND:case w.HEAD:case w.LINK:case w.META:case w.NOFRAMES:case w.STYLE:{Hd(e,t);break}case w.NOSCRIPT:{e._err(t,Te.nestedNoscriptInHead);break}default:FO(e,t);}}function lGt(e,t){switch(t.tagID){case w.NOSCRIPT:{e.openElements.pop(),e.insertionMode=Y.IN_HEAD;break}case w.BR:{FO(e,t);break}default:e._err(t,Te.endTagWithoutMatchingOpenElement);}}function FO(e,t){let o=t.type===hn.EOF?Te.openElementsLeftAfterEof:Te.disallowedContentInNoscriptInHead;e._err(t,o),e.openElements.pop(),e.insertionMode=Y.IN_HEAD,e._processToken(t);}function cGt(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.BODY:{e._insertElement(t,Ne.HTML),e.framesetOk=false,e.insertionMode=Y.IN_BODY;break}case w.FRAMESET:{e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_FRAMESET;break}case w.BASE:case w.BASEFONT:case w.BGSOUND:case w.LINK:case w.META:case w.NOFRAMES:case w.SCRIPT:case w.STYLE:case w.TEMPLATE:case w.TITLE:{e._err(t,Te.abandonedHeadElementChild),e.openElements.push(e.headElement,w.HEAD),Hd(e,t),e.openElements.remove(e.headElement);break}case w.HEAD:{e._err(t,Te.misplacedStartTagForHeadElement);break}default:BO(e,t);}}function uGt(e,t){switch(t.tagID){case w.BODY:case w.HTML:case w.BR:{BO(e,t);break}case w.TEMPLATE:{rT(e,t);break}default:e._err(t,Te.endTagWithoutMatchingOpenElement);}}function BO(e,t){e._insertFakeElement(le.BODY,w.BODY),e.insertionMode=Y.IN_BODY,wz(e,t);}function wz(e,t){switch(t.type){case hn.CHARACTER:{mBe(e,t);break}case hn.WHITESPACE_CHARACTER:{dBe(e,t);break}case hn.COMMENT:{q6(e,t);break}case hn.START_TAG:{_s(e,t);break}case hn.END_TAG:{Rz(e,t);break}case hn.EOF:{fBe(e,t);break}}}function dBe(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t);}function mBe(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=false;}function dGt(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs);}function mGt(e,t){let o=e.openElements.tryPeekProperlyNestedBodyElement();o&&e.openElements.tmplCount===0&&(e.framesetOk=false,e.treeAdapter.adoptAttributes(o,t.attrs));}function pGt(e,t){let o=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&o&&(e.treeAdapter.detachNode(o),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_FRAMESET);}function hGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML);}function gGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&_O.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,Ne.HTML);}function fGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML),e.skipNextNewLine=true,e.framesetOk=false;}function yGt(e,t){let o=e.openElements.tmplCount>0;(!e.formElement||o)&&(e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML),o||(e.formElement=e.openElements.current));}function bGt(e,t){e.framesetOk=false;let o=t.tagID;for(let n=e.openElements.stackTop;n>=0;n--){let r=e.openElements.tagIDs[n];if(o===w.LI&&r===w.LI||(o===w.DD||o===w.DT)&&(r===w.DD||r===w.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==w.ADDRESS&&r!==w.DIV&&r!==w.P&&e._isSpecialElement(e.openElements.items[n],r))break}e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML);}function SGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML),e.tokenizer.state=xs.PLAINTEXT;}function TGt(e,t){e.openElements.hasInScope(w.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(w.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.framesetOk=false;}function vGt(e,t){let o=e.activeFormattingElements.getElementEntryInScopeWithTagName(le.A);o&&(Y6(e,t),e.openElements.remove(o.element),e.activeFormattingElements.removeEntry(o)),e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function AGt(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function EGt(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(w.NOBR)&&(Y6(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,Ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function wGt(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=false;}function RGt(e,t){e.treeAdapter.getDocumentMode(e.document)!==bl.QUIRKS&&e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._insertElement(t,Ne.HTML),e.framesetOk=false,e.insertionMode=Y.IN_TABLE;}function pBe(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Ne.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function hBe(e){let t=hz(e,ag.TYPE);return t!=null&&t.toLowerCase()===$1t}function CGt(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Ne.HTML),hBe(t)||(e.framesetOk=false),t.ackSelfClosing=true;}function IGt(e,t){e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;}function xGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._appendElement(t,Ne.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function _Gt(e,t){t.tagName=le.IMG,t.tagID=w.IMG,pBe(e,t);}function OGt(e,t){e._insertElement(t,Ne.HTML),e.skipNextNewLine=true,e.tokenizer.state=xs.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=false,e.insertionMode=Y.TEXT;}function PGt(e,t){e.openElements.hasInButtonScope(w.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=false,e._switchToTextParsing(t,xs.RAWTEXT);}function kGt(e,t){e.framesetOk=false,e._switchToTextParsing(t,xs.RAWTEXT);}function lBe(e,t){e._switchToTextParsing(t,xs.RAWTEXT);}function MGt(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML),e.framesetOk=false,e.insertionMode=e.insertionMode===Y.IN_TABLE||e.insertionMode===Y.IN_CAPTION||e.insertionMode===Y.IN_TABLE_BODY||e.insertionMode===Y.IN_ROW||e.insertionMode===Y.IN_CELL?Y.IN_SELECT_IN_TABLE:Y.IN_SELECT;}function LGt(e,t){e.openElements.currentTagId===w.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML);}function NGt(e,t){e.openElements.hasInScope(w.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,Ne.HTML);}function DGt(e,t){e.openElements.hasInScope(w.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(w.RTC),e._insertElement(t,Ne.HTML);}function FGt(e,t){e._reconstructActiveFormattingElements(),G6(t),Tz(t),t.selfClosing?e._appendElement(t,Ne.MATHML):e._insertElement(t,Ne.MATHML),t.ackSelfClosing=true;}function BGt(e,t){e._reconstructActiveFormattingElements(),V6(t),Tz(t),t.selfClosing?e._appendElement(t,Ne.SVG):e._insertElement(t,Ne.SVG),t.ackSelfClosing=true;}function cBe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Ne.HTML);}function _s(e,t){switch(t.tagID){case w.I:case w.S:case w.B:case w.U:case w.EM:case w.TT:case w.BIG:case w.CODE:case w.FONT:case w.SMALL:case w.STRIKE:case w.STRONG:{AGt(e,t);break}case w.A:{vGt(e,t);break}case w.H1:case w.H2:case w.H3:case w.H4:case w.H5:case w.H6:{gGt(e,t);break}case w.P:case w.DL:case w.OL:case w.UL:case w.DIV:case w.DIR:case w.NAV:case w.MAIN:case w.MENU:case w.ASIDE:case w.CENTER:case w.FIGURE:case w.FOOTER:case w.HEADER:case w.HGROUP:case w.DIALOG:case w.DETAILS:case w.ADDRESS:case w.ARTICLE:case w.SEARCH:case w.SECTION:case w.SUMMARY:case w.FIELDSET:case w.BLOCKQUOTE:case w.FIGCAPTION:{hGt(e,t);break}case w.LI:case w.DD:case w.DT:{bGt(e,t);break}case w.BR:case w.IMG:case w.WBR:case w.AREA:case w.EMBED:case w.KEYGEN:{pBe(e,t);break}case w.HR:{xGt(e,t);break}case w.RB:case w.RTC:{NGt(e,t);break}case w.RT:case w.RP:{DGt(e,t);break}case w.PRE:case w.LISTING:{fGt(e,t);break}case w.XMP:{PGt(e,t);break}case w.SVG:{BGt(e,t);break}case w.HTML:{dGt(e,t);break}case w.BASE:case w.LINK:case w.META:case w.STYLE:case w.TITLE:case w.SCRIPT:case w.BGSOUND:case w.BASEFONT:case w.TEMPLATE:{Hd(e,t);break}case w.BODY:{mGt(e,t);break}case w.FORM:{yGt(e,t);break}case w.NOBR:{EGt(e,t);break}case w.MATH:{FGt(e,t);break}case w.TABLE:{RGt(e,t);break}case w.INPUT:{CGt(e,t);break}case w.PARAM:case w.TRACK:case w.SOURCE:{IGt(e,t);break}case w.IMAGE:{_Gt(e,t);break}case w.BUTTON:{TGt(e,t);break}case w.APPLET:case w.OBJECT:case w.MARQUEE:{wGt(e,t);break}case w.IFRAME:{kGt(e,t);break}case w.SELECT:{MGt(e,t);break}case w.OPTION:case w.OPTGROUP:{LGt(e,t);break}case w.NOEMBED:case w.NOFRAMES:{lBe(e,t);break}case w.FRAMESET:{pGt(e,t);break}case w.TEXTAREA:{OGt(e,t);break}case w.NOSCRIPT:{e.options.scriptingEnabled?lBe(e,t):cBe(e,t);break}case w.PLAINTEXT:{SGt(e,t);break}case w.COL:case w.TH:case w.TD:case w.TR:case w.HEAD:case w.FRAME:case w.TBODY:case w.TFOOT:case w.THEAD:case w.CAPTION:case w.COLGROUP:break;default:cBe(e,t);}}function UGt(e,t){if(e.openElements.hasInScope(w.BODY)&&(e.insertionMode=Y.AFTER_BODY,e.options.sourceCodeLocationInfo)){let o=e.openElements.tryPeekProperlyNestedBodyElement();o&&e._setEndLocation(o,t);}}function jGt(e,t){e.openElements.hasInScope(w.BODY)&&(e.insertionMode=Y.AFTER_BODY,wBe(e,t));}function zGt(e,t){let o=t.tagID;e.openElements.hasInScope(o)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o));}function HGt(e){let t=e.openElements.tmplCount>0,{formElement:o}=e;t||(e.formElement=null),(o||t)&&e.openElements.hasInScope(w.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(w.FORM):o&&e.openElements.remove(o));}function $Gt(e){e.openElements.hasInButtonScope(w.P)||e._insertFakeElement(le.P,w.P),e._closePElement();}function GGt(e){e.openElements.hasInListItemScope(w.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(w.LI),e.openElements.popUntilTagNamePopped(w.LI));}function VGt(e,t){let o=t.tagID;e.openElements.hasInScope(o)&&(e.openElements.generateImpliedEndTagsWithExclusion(o),e.openElements.popUntilTagNamePopped(o));}function WGt(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped());}function qGt(e,t){let o=t.tagID;e.openElements.hasInScope(o)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o),e.activeFormattingElements.clearToLastMarker());}function KGt(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(le.BR,w.BR),e.openElements.pop(),e.framesetOk=false;}function gBe(e,t){let o=t.tagName,n=t.tagID;for(let r=e.openElements.stackTop;r>0;r--){let i=e.openElements.items[r],a=e.openElements.tagIDs[r];if(n===a&&(n!==w.UNKNOWN||e.treeAdapter.getTagName(i)===o)){e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.stackTop>=r&&e.openElements.shortenToLength(r);break}if(e._isSpecialElement(i,a))break}}function Rz(e,t){switch(t.tagID){case w.A:case w.B:case w.I:case w.S:case w.U:case w.EM:case w.TT:case w.BIG:case w.CODE:case w.FONT:case w.NOBR:case w.SMALL:case w.STRIKE:case w.STRONG:{Y6(e,t);break}case w.P:{$Gt(e);break}case w.DL:case w.UL:case w.OL:case w.DIR:case w.DIV:case w.NAV:case w.PRE:case w.MAIN:case w.MENU:case w.ASIDE:case w.BUTTON:case w.CENTER:case w.FIGURE:case w.FOOTER:case w.HEADER:case w.HGROUP:case w.DIALOG:case w.ADDRESS:case w.ARTICLE:case w.DETAILS:case w.SEARCH:case w.SECTION:case w.SUMMARY:case w.LISTING:case w.FIELDSET:case w.BLOCKQUOTE:case w.FIGCAPTION:{zGt(e,t);break}case w.LI:{GGt(e);break}case w.DD:case w.DT:{VGt(e,t);break}case w.H1:case w.H2:case w.H3:case w.H4:case w.H5:case w.H6:{WGt(e);break}case w.BR:{KGt(e);break}case w.BODY:{UGt(e,t);break}case w.HTML:{jGt(e,t);break}case w.FORM:{HGt(e);break}case w.APPLET:case w.OBJECT:case w.MARQUEE:{qGt(e,t);break}case w.TEMPLATE:{rT(e,t);break}default:gBe(e,t);}}function fBe(e,t){e.tmplInsertionModeStack.length>0?EBe(e,t):J6(e,t);}function YGt(e,t){var o;t.tagID===w.SCRIPT&&((o=e.scriptHandler)===null||o===void 0||o.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode;}function JGt(e,t){e._err(t,Te.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t);}function W6(e,t){if(e.openElements.currentTagId!==void 0&&uBe.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=false,e.originalInsertionMode=e.insertionMode,e.insertionMode=Y.IN_TABLE_TEXT,t.type){case hn.CHARACTER:{bBe(e,t);break}case hn.WHITESPACE_CHARACTER:{yBe(e,t);break}}else zO(e,t);}function XGt(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_CAPTION;}function QGt(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_COLUMN_GROUP;}function ZGt(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(le.COLGROUP,w.COLGROUP),e.insertionMode=Y.IN_COLUMN_GROUP,X6(e,t);}function e2t(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_TABLE_BODY;}function t2t(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(le.TBODY,w.TBODY),e.insertionMode=Y.IN_TABLE_BODY,Cz(e,t);}function o2t(e,t){e.openElements.hasInTableScope(w.TABLE)&&(e.openElements.popUntilTagNamePopped(w.TABLE),e._resetInsertionMode(),e._processStartTag(t));}function n2t(e,t){hBe(t)?e._appendElement(t,Ne.HTML):zO(e,t),t.ackSelfClosing=true;}function r2t(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,Ne.HTML),e.formElement=e.openElements.current,e.openElements.pop());}function Ow(e,t){switch(t.tagID){case w.TD:case w.TH:case w.TR:{t2t(e,t);break}case w.STYLE:case w.SCRIPT:case w.TEMPLATE:{Hd(e,t);break}case w.COL:{ZGt(e,t);break}case w.FORM:{r2t(e,t);break}case w.TABLE:{o2t(e,t);break}case w.TBODY:case w.TFOOT:case w.THEAD:{e2t(e,t);break}case w.INPUT:{n2t(e,t);break}case w.CAPTION:{XGt(e,t);break}case w.COLGROUP:{QGt(e,t);break}default:zO(e,t);}}function jO(e,t){switch(t.tagID){case w.TABLE:{e.openElements.hasInTableScope(w.TABLE)&&(e.openElements.popUntilTagNamePopped(w.TABLE),e._resetInsertionMode());break}case w.TEMPLATE:{rT(e,t);break}case w.BODY:case w.CAPTION:case w.COL:case w.COLGROUP:case w.HTML:case w.TBODY:case w.TD:case w.TFOOT:case w.TH:case w.THEAD:case w.TR:break;default:zO(e,t);}}function zO(e,t){let o=e.fosterParentingEnabled;e.fosterParentingEnabled=true,wz(e,t),e.fosterParentingEnabled=o;}function yBe(e,t){e.pendingCharacterTokens.push(t);}function bBe(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=true;}function MO(e,t){let o=0;if(e.hasNonWhitespacePendingCharacterToken)for(;o<e.pendingCharacterTokens.length;o++)zO(e,e.pendingCharacterTokens[o]);else for(;o<e.pendingCharacterTokens.length;o++)e._insertCharacters(e.pendingCharacterTokens[o]);e.insertionMode=e.originalInsertionMode,e._processToken(t);}var SBe=new Set([w.CAPTION,w.COL,w.COLGROUP,w.TBODY,w.TD,w.TFOOT,w.TH,w.THEAD,w.TR]);function i2t(e,t){let o=t.tagID;SBe.has(o)?e.openElements.hasInTableScope(w.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(w.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=Y.IN_TABLE,Ow(e,t)):_s(e,t);}function a2t(e,t){let o=t.tagID;switch(o){case w.CAPTION:case w.TABLE:{e.openElements.hasInTableScope(w.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(w.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=Y.IN_TABLE,o===w.TABLE&&jO(e,t));break}case w.BODY:case w.COL:case w.COLGROUP:case w.HTML:case w.TBODY:case w.TD:case w.TFOOT:case w.TH:case w.THEAD:case w.TR:break;default:Rz(e,t);}}function X6(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.COL:{e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;break}case w.TEMPLATE:{Hd(e,t);break}default:Az(e,t);}}function s2t(e,t){switch(t.tagID){case w.COLGROUP:{e.openElements.currentTagId===w.COLGROUP&&(e.openElements.pop(),e.insertionMode=Y.IN_TABLE);break}case w.TEMPLATE:{rT(e,t);break}case w.COL:break;default:Az(e,t);}}function Az(e,t){e.openElements.currentTagId===w.COLGROUP&&(e.openElements.pop(),e.insertionMode=Y.IN_TABLE,e._processToken(t));}function Cz(e,t){switch(t.tagID){case w.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_ROW;break}case w.TH:case w.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(le.TR,w.TR),e.insertionMode=Y.IN_ROW,Iz(e,t);break}case w.CAPTION:case w.COL:case w.COLGROUP:case w.TBODY:case w.TFOOT:case w.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE,Ow(e,t));break}default:Ow(e,t);}}function K6(e,t){let o=t.tagID;switch(t.tagID){case w.TBODY:case w.TFOOT:case w.THEAD:{e.openElements.hasInTableScope(o)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE);break}case w.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE,jO(e,t));break}case w.BODY:case w.CAPTION:case w.COL:case w.COLGROUP:case w.HTML:case w.TD:case w.TH:case w.TR:break;default:jO(e,t);}}function Iz(e,t){switch(t.tagID){case w.TH:case w.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,Ne.HTML),e.insertionMode=Y.IN_CELL,e.activeFormattingElements.insertMarker();break}case w.CAPTION:case w.COL:case w.COLGROUP:case w.TBODY:case w.TFOOT:case w.THEAD:case w.TR:{e.openElements.hasInTableScope(w.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE_BODY,Cz(e,t));break}default:Ow(e,t);}}function TBe(e,t){switch(t.tagID){case w.TR:{e.openElements.hasInTableScope(w.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE_BODY);break}case w.TABLE:{e.openElements.hasInTableScope(w.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE_BODY,K6(e,t));break}case w.TBODY:case w.TFOOT:case w.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(w.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Y.IN_TABLE_BODY,K6(e,t));break}case w.BODY:case w.CAPTION:case w.COL:case w.COLGROUP:case w.HTML:case w.TD:case w.TH:break;default:jO(e,t);}}function l2t(e,t){let o=t.tagID;SBe.has(o)?(e.openElements.hasInTableScope(w.TD)||e.openElements.hasInTableScope(w.TH))&&(e._closeTableCell(),Iz(e,t)):_s(e,t);}function c2t(e,t){let o=t.tagID;switch(o){case w.TD:case w.TH:{e.openElements.hasInTableScope(o)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=Y.IN_ROW);break}case w.TABLE:case w.TBODY:case w.TFOOT:case w.THEAD:case w.TR:{e.openElements.hasInTableScope(o)&&(e._closeTableCell(),TBe(e,t));break}case w.BODY:case w.CAPTION:case w.COL:case w.COLGROUP:case w.HTML:break;default:Rz(e,t);}}function vBe(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.OPTION:{e.openElements.currentTagId===w.OPTION&&e.openElements.pop(),e._insertElement(t,Ne.HTML);break}case w.OPTGROUP:{e.openElements.currentTagId===w.OPTION&&e.openElements.pop(),e.openElements.currentTagId===w.OPTGROUP&&e.openElements.pop(),e._insertElement(t,Ne.HTML);break}case w.HR:{e.openElements.currentTagId===w.OPTION&&e.openElements.pop(),e.openElements.currentTagId===w.OPTGROUP&&e.openElements.pop(),e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;break}case w.INPUT:case w.KEYGEN:case w.TEXTAREA:case w.SELECT:{e.openElements.hasInSelectScope(w.SELECT)&&(e.openElements.popUntilTagNamePopped(w.SELECT),e._resetInsertionMode(),t.tagID!==w.SELECT&&e._processStartTag(t));break}case w.SCRIPT:case w.TEMPLATE:{Hd(e,t);break}}}function ABe(e,t){switch(t.tagID){case w.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===w.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===w.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===w.OPTGROUP&&e.openElements.pop();break}case w.OPTION:{e.openElements.currentTagId===w.OPTION&&e.openElements.pop();break}case w.SELECT:{e.openElements.hasInSelectScope(w.SELECT)&&(e.openElements.popUntilTagNamePopped(w.SELECT),e._resetInsertionMode());break}case w.TEMPLATE:{rT(e,t);break}}}function u2t(e,t){let o=t.tagID;o===w.CAPTION||o===w.TABLE||o===w.TBODY||o===w.TFOOT||o===w.THEAD||o===w.TR||o===w.TD||o===w.TH?(e.openElements.popUntilTagNamePopped(w.SELECT),e._resetInsertionMode(),e._processStartTag(t)):vBe(e,t);}function d2t(e,t){let o=t.tagID;o===w.CAPTION||o===w.TABLE||o===w.TBODY||o===w.TFOOT||o===w.THEAD||o===w.TR||o===w.TD||o===w.TH?e.openElements.hasInTableScope(o)&&(e.openElements.popUntilTagNamePopped(w.SELECT),e._resetInsertionMode(),e.onEndTag(t)):ABe(e,t);}function m2t(e,t){switch(t.tagID){case w.BASE:case w.BASEFONT:case w.BGSOUND:case w.LINK:case w.META:case w.NOFRAMES:case w.SCRIPT:case w.STYLE:case w.TEMPLATE:case w.TITLE:{Hd(e,t);break}case w.CAPTION:case w.COLGROUP:case w.TBODY:case w.TFOOT:case w.THEAD:{e.tmplInsertionModeStack[0]=Y.IN_TABLE,e.insertionMode=Y.IN_TABLE,Ow(e,t);break}case w.COL:{e.tmplInsertionModeStack[0]=Y.IN_COLUMN_GROUP,e.insertionMode=Y.IN_COLUMN_GROUP,X6(e,t);break}case w.TR:{e.tmplInsertionModeStack[0]=Y.IN_TABLE_BODY,e.insertionMode=Y.IN_TABLE_BODY,Cz(e,t);break}case w.TD:case w.TH:{e.tmplInsertionModeStack[0]=Y.IN_ROW,e.insertionMode=Y.IN_ROW,Iz(e,t);break}default:e.tmplInsertionModeStack[0]=Y.IN_BODY,e.insertionMode=Y.IN_BODY,_s(e,t);}}function p2t(e,t){t.tagID===w.TEMPLATE&&rT(e,t);}function EBe(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(w.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):J6(e,t);}function h2t(e,t){t.tagID===w.HTML?_s(e,t):Ez(e,t);}function wBe(e,t){var o;if(t.tagID===w.HTML){if(e.fragmentContext||(e.insertionMode=Y.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===w.HTML){e._setEndLocation(e.openElements.items[0],t);let n=e.openElements.items[1];n&&!(!((o=e.treeAdapter.getNodeSourceCodeLocation(n))===null||o===void 0)&&o.endTag)&&e._setEndLocation(n,t);}}else Ez(e,t);}function Ez(e,t){e.insertionMode=Y.IN_BODY,wz(e,t);}function g2t(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.FRAMESET:{e._insertElement(t,Ne.HTML);break}case w.FRAME:{e._appendElement(t,Ne.HTML),t.ackSelfClosing=true;break}case w.NOFRAMES:{Hd(e,t);break}}}function f2t(e,t){t.tagID===w.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==w.FRAMESET&&(e.insertionMode=Y.AFTER_FRAMESET));}function y2t(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.NOFRAMES:{Hd(e,t);break}}}function b2t(e,t){t.tagID===w.HTML&&(e.insertionMode=Y.AFTER_AFTER_FRAMESET);}function S2t(e,t){t.tagID===w.HTML?_s(e,t):vz(e,t);}function vz(e,t){e.insertionMode=Y.IN_BODY,wz(e,t);}function T2t(e,t){switch(t.tagID){case w.HTML:{_s(e,t);break}case w.NOFRAMES:{Hd(e,t);break}}}function v2t(e,t){t.chars=wr,e._insertCharacters(t);}function A2t(e,t){e._insertCharacters(t),e.framesetOk=false;}function RBe(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==Ne.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop();}function E2t(e,t){if(nBe(t))RBe(e),e._startTagOutsideForeignContent(t);else {let o=e._getAdjustedCurrentElement(),n=e.treeAdapter.getNamespaceURI(o);n===Ne.MATHML?G6(t):n===Ne.SVG&&(rBe(t),V6(t)),Tz(t),t.selfClosing?e._appendElement(t,n):e._insertElement(t,n),t.ackSelfClosing=true;}}function w2t(e,t){if(t.tagID===w.P||t.tagID===w.BR){RBe(e),e._endTagOutsideForeignContent(t);return}for(let o=e.openElements.stackTop;o>0;o--){let n=e.openElements.items[o];if(e.treeAdapter.getNamespaceURI(n)===Ne.HTML){e._endTagOutsideForeignContent(t);break}let r=e.treeAdapter.getTagName(n);if(r.toLowerCase()===t.tagName){t.tagName=r,e.openElements.shortenToLength(o);break}}}new Set([le.AREA,le.BASE,le.BASEFONT,le.BGSOUND,le.BR,le.COL,le.EMBED,le.FRAME,le.HR,le.IMG,le.INPUT,le.KEYGEN,le.LINK,le.META,le.PARAM,le.SOURCE,le.TRACK,le.WBR]);function CBe(e,t,o){typeof e=="string"&&(o=t,t=e,e=null);let n=UO.getFragmentParser(e,o);return n.tokenizer.write(t,true),n.getFragment()}var R2t=5e3,kw=1024;function Pw(e){return typeof e.tagName=="string"&&Array.isArray(e.attrs)}function xz(e){return e.nodeName==="#text"}function _z(e,t){let o=CBe(e),n={nodesLeft:R2t};for(let a of o.childNodes)if(Pw(a)&&a.tagName.toLowerCase()==="body"){let s=t(a,n);if(s!==void 0)return s}let r=[];for(let a of o.childNodes){if(n.nodesLeft<=0)break;if(Pw(a)){let s=t(a,n);s!==void 0&&r.push(s);}}let i={tag:"body"};return r.length>0&&(i.children=r),i}var C2t=new Set(["html","head","meta","link","template","script","style","noscript","path","br","polygon","defs"]),I2t=new Set(["input","textarea","select","button","a","img","video","audio","canvas","svg","label","h1","h2","h3","h4","ol","ul","li","table","tr","td","th","form","nav","main","footer","section","article","dialog","option"]);function x2t(e,t){return I2t.has(t)?true:e.attrs.some(({name:o})=>z6.has(o.toLowerCase()))}function IBe(e,t){if(t.nodesLeft<=0)return;let o=e.tagName.toLowerCase();if(C2t.has(o))return;let n,r;for(let{name:c,value:u}of e.attrs){let d=c.toLowerCase();if(d==="role"){r=u;continue}n===void 0&&(n={}),n[d]=u;}let i,a=[];for(let c of e.childNodes){if(t.nodesLeft<=0)break;if(xz(c)){let u=c.value;if(u&&u.trim().length>0){let d=u.length>kw?u.slice(0,kw):u;i=i===void 0?d:`${i} ${d}`;}}else if(Pw(c)){let u=IBe(c,t);u!==void 0&&a.push(u);}}let s=o==="body"||x2t(e,o);if(!s&&a.length===0&&i===void 0)return;if(!s&&a.length===1&&i===void 0)return a[0];t.nodesLeft-=1;let l={tag:o};return r!==void 0&&(l.role=r),n!==void 0&&(l.attributes=n),i!==void 0&&(l.text=i),a.length>0&&(l.children=a),l}function Q6(e){return _z(e,IBe)}function xBe(e,t){if(t.nodesLeft<=0)return;t.nodesLeft-=1;let o=e.tagName.toLowerCase(),n,r;for(let{name:l,value:c}of e.attrs){let u=l.toLowerCase();if(u==="role"){r=c;continue}n===void 0&&(n={}),n[u]=c;}let i,a=[];for(let l of e.childNodes){if(t.nodesLeft<=0)break;if(xz(l)){let c=l.value;if(c&&c.trim().length>0){let u=c.length>kw?c.slice(0,kw):c;i=i===void 0?u:`${i} ${u}`;}}else if(Pw(l)){let c=xBe(l,t);c!==void 0&&a.push(c);}}let s={tag:o};return r!==void 0&&(s.role=r),n!==void 0&&(s.attributes=n),i!==void 0&&(s.text=i),a.length>0&&(s.children=a),s}function Z6(e){return _z(e,xBe)}var _2t=new Set(["PRESET_ACTION","AI_ACTION_DYNAMIC"]),iT=class{constructor(t,o,n,r,i,a){this.orgId=t;this.testId=o;this.testName=n;this.diskStorage=r;this.parentFlushResults=i;this.appGraphSink=a;}children=[];finished=false;stepFrequenciesByType={};currentResults=[];async getScreenshot(t,o){return this.diskStorage.readFile(`${Ks}/${o}.jpeg`)}async getHtmlSnapshot(t,o){return this.diskStorage.readFile(`${Ks}/${o}.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,o]of Object.entries(this.stepFrequenciesByType))zo.increment("test_step_execution",o,[`type:${t}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}flushResults(t){return this.currentResults=t,this.parentFlushResults(t)}async startStep(t,o){let{logger:n,step:r,parentStepIdChain:i}=t;this.recordStepStat(r);let a={step:r,status:"RUNNING",startedAt:new Date},s=[...o];this.currentResults=s;let l=new eX(this.orgId,this.testId,this.testName,a,this.diskStorage,n,c=>this.flushResults([...s,c]),i??[],this.appGraphSink);return this.children.push(l),l}async finish(t){this.finished||(this.finished=true,await Promise.all(this.children.map(o=>o.finishInternal({status:FZ(t.status),finishedAt:t.finishedAt}))),this.sendFinalizedStepStats());}};function O2t(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 mt(e)}}function Oz(e){return e.some(t=>t.status==="FAILED")?"FAILED":e.some(t=>t.status==="CANCELLED")?"CANCELLED":"RUNNING"}var eX=class{constructor(t,o,n,r,i,a,s,l,c){this.orgId=t;this.testId=o;this.testName=n;this.metadata=r;this.diskStorage=i;this.logger=a;this.parentFlushResults=s;this.parentStepIdChain=l;this.appGraphSink=c;this.interactionTracer=new cp({storeTraceAsset:u=>this.storeTraceAsset(u)}),lp.initializeRootTracerContext(this.interactionTracer);}children=[];finished=false;interactionTracer;pendingAssetWrites=Promise.resolve();async attachBeforeScreenshot(t){let{snapshotId:o,screenshot:n}=t;if(n){this.metadata.beforeSnapshotId=o;try{await this.diskStorage.storeFileAsync({name:`${Ks}/${o}.jpeg`,contents:n});}catch(r){this.logger.warn({err:r,snapshotId:o},"Failed to store before-step screenshot");}}}async attachAfterScreenshot(t){let{snapshotId:o,screenshot:n}=t;if(n){this.metadata.afterSnapshotId=o;try{await this.diskStorage.storeFileAsync({name:`${Ks}/${o}.jpeg`,contents:n});}catch(r){this.logger.warn({err:r,snapshotId:o},"Failed to store after-step screenshot");}}}attachBeforeHtmlSnapshot(t){let{snapshotId:o,html:n}=t;this.metadata.beforeSnapshotId=o,this.queueAssetWrite(`${o}.html`,n);}attachAfterHtmlSnapshot(t){let{snapshotId:o,html:n,fingerprintHtml:r,url:i,logger:a}=t;this.metadata.afterSnapshotId=o,this.queueAssetWrite(`${o}.html`,n),this.appGraphSink&&_2t.has(this.metadata.step.type)&&this.appGraphSink({html:r??n,archivalHtml:n,url:i,stepId:this.metadata.step.id,parentStepIdChain:[...this.parentStepIdChain],logger:a});}recordTargetAutoHeal(t){let{healType:o}=t,n=o==="AI"?"ai-target-heal":"cache-heal";zo.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:o,healedAt:new Date};}storeTraceAsset(t){this.queueAssetWrite(`${t.snapshotId}.${t.extension??"jpeg"}`,t.data);}queueAssetWrite(t,o){this.pendingAssetWrites=this.pendingAssetWrites.then(async()=>{try{await this.diskStorage.storeFileAsync({name:`${Ks}/${t}`,contents:o});}catch(n){this.logger.warn({err:n,name:t},"Failed to store run trace asset");}});}async finishInternal(t){this.finished||(this.finished=true,this.interactionTracer.finish(),await Promise.all(this.children.map(o=>o.finish({status:O2t(t.status),finishedAt:t.finishedAt})).concat(this.pendingAssetWrites)));}recordStepDuration(t,o,n){KM({durationMs:o,executor:"cli",logger:this.logger,orgId:this.orgId,resolvedStep:t,status:n});}async finish(t){!this.finished&&t.resolvedStep!==void 0&&t.durationMs!==void 0&&this.recordStepDuration(t.resolvedStep,t.durationMs,t.step.status),await this.finishInternal(t.step),t.step.trace=this.interactionTracer.getRootSpan();}getResultBuilderForCurrentStep(){let t=this.metadata.step;switch(t.type){case "RESOLVED_MODULE":return o=>({...t,status:Oz(o),startedAt:this.metadata.startedAt,finishedAt:new Date,results:o,type:"MODULE"});case "CONDITIONAL":return o=>({...t,blocks:t.blocks.map(r=>({assertion:r.assertion,steps:gc(r.steps)})),elseSteps:t.elseSteps?gc(t.elseSteps):void 0,status:Oz(o),startedAt:this.metadata.startedAt,finishedAt:new Date,results:o});case "WHILE_LOOP":return o=>({...t,steps:gc(t.steps),status:Oz(o),startedAt:this.metadata.startedAt,finishedAt:new Date,results:o});case "AI_ACTION":case "AI_ACTION_DYNAMIC":case "PRESET_ACTION":case "SECTION":return o=>({...t,status:Oz(o),startedAt:this.metadata.startedAt,finishedAt:new Date,results:o});default:return mt(t)}}async startSubSteps(){let t=this.getResultBuilderForCurrentStep(),o=new iT(this.orgId,this.testId,this.testName,this.diskStorage,n=>{let r=t(n);return this.parentFlushResults(r)});return this.children.push(o),o}};var Pz=class{constructor(t,o,n,r,i,a,s,l){this.orgId=t;this.testId=o;this.testName=n;this.runAttemptId=r;this.metadata=i;this.diskStorage=a;this.recordVideo=s;this.progressHandle=l;this.diskStorage.mkdir(Ks),this.harWriter=new Zf(this.diskStorage.createFileStream(`${Ks}/har-pages.log`),this.diskStorage.createFileStream(`${Ks}/har-entries.log`)),this.resourceUsageStream=this.diskStorage.createFileStream(`${Ks}/resource-usage.ndjson`),this.resourceUsageSampler=fae({keepSamples:false,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
4658
4658
  `),c.system.cpu&&(this.cpuUsageSum+=c.system.cpu.total,this.cpuSampleCount++);let u=c.system.memory.total-c.system.memory.free;this.memoryUsageSum+=u,this.memorySampleCount++;}});}finished=false;finishPromise;children=[];beforeResults;mainResults=[];afterResults;harWriter;resourceUsageStream;resourceUsageSampler;uiStatesStream;previousHtmlByteHash;previousFingerprint;previousArchivalHtmlByteHash;previousArchivalFingerprint;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 Cn__default.resolve(this.diskStorage.cwd(),Ks)}setActiveVideo(t,o){this.recordVideo&&(this.metadata.activeVideos=this.metadata.activeVideos||[],this.metadata.activeVideos.push({videoName:t,timestamp:o}));}setViewport(t){this.metadata.viewport=t;}onNetworkPage(t){this.finished||this.harWriter.writePage(t);}appendUiState(t){this.finished||(this.uiStatesStream||(this.uiStatesStream=this.diskStorage.createFileStream(See)),this.uiStatesStream.write(`${JSON.stringify(t)}
4659
4659
  `));}buildAppGraphSink(){return ({html:t,archivalHtml:o,url:n,stepId:r,parentStepIdChain:i,logger:a})=>{let s=sz(t),l=s===this.previousHtmlByteHash?this.previousFingerprint:void 0;if(!l){try{l=cz({url:n,dom:Z6(t)});}catch(u){a.debug({err:u,stepId:r},"Failed to compute app-graph UIState fingerprint");return}this.previousHtmlByteHash=s,this.previousFingerprint=l;}let c=this.computeArchivalFingerprint({archivalHtml:o,url:n,stepId:r,logger:a});this.appendUiState({stepId:r,parentStepIdChain:i,fingerprintHash:l.fingerprintHash,minhash:Array.from(l.minhash),canonicalUrl:l.canonicalUrl,capturedAt:Date.now(),archivalFingerprintHash:c?.fingerprintHash,archivalMinhash:c?Array.from(c.minhash):void 0});}}computeArchivalFingerprint({archivalHtml:t,url:o,stepId:n,logger:r}){let i=sz(t);if(i===this.previousArchivalHtmlByteHash)return this.previousArchivalFingerprint;try{let a=cz({url:o,dom:Q6(t)});return this.previousArchivalHtmlByteHash=i,this.previousArchivalFingerprint=a,a}catch(a){r.debug({err:a,stepId:n},"Failed to compute archival app-graph UIState fingerprint");return}}onNetworkLogs(t){this.finished||this.harWriter.writeEntries(t);}attachConsoleLogs(t){let{logs:o}=t;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(o,null,2)});}attachBrowserCrashDump(t){let{crashReportDirFetcher:o,logger:n}=t,r=o();if(!r)return;let i=new k4;i.addLocalFolder(r,void 0,a=>a!==".DS_Store"),this.diskStorage.storeFile({name:`${Ks}/${$G}`,contents:i.toBuffer()}),n.info({browserCrashZipName:$G},"Attached browser crash ZIP");}writeMetadata(t){this.diskStorage.storeFile({name:Mt,contents:JSON.stringify(t,null,2)});}flushResults(t){let{results:o,beforeResults:n,afterResults:r}=fV({results:t?.mainResults??this.mainResults,beforeResults:t?.beforeResults??this.beforeResults,afterResults:t?.afterResults??this.afterResults},ss);return this.writeMetadata({...this.metadata,results:o,beforeResults:n,afterResults:r}),this.reportProgress(n,o,r),this.harWriter.waitForPendingWrites()}reportProgress(t,o,n){try{this.progressHandle.reportCompletedSteps(CL(t??[])+CL(o)+CL(n??[]));}catch(r){ss.warn({err:r},"Failed to report run progress");}}finish(t){return this.finishPromise?(t.logger.info({runAttemptId:this.runAttemptId,callerStatus:t.result.status},"CliRunAttemptTracer.finish() called while already finishing \u2014 waiting for the original finalization"),this.finishPromise):(this.finished=true,this.finishPromise=this.finishAttempt(t),this.finishPromise)}async finishAttempt(t){let{logger:o,result:n}=t,{results:r,beforeResults:i,afterResults:a}=fV({...n,results:n.results??this.mainResults,beforeResults:n.beforeResults??this.beforeResults,afterResults:n.afterResults??this.afterResults},o),s={...this.metadata,status:n.status,finishedAt:new Date,results:r,beforeResults:i,afterResults:a};await Promise.all(this.children.map(l=>l.finish({status:s.status,finishedAt:s.finishedAt}))),this.harWriter.close();try{this.resourceUsageSampler.stop(),this.resourceUsageStream.end();}catch{}if(this.uiStatesStream)try{this.uiStatesStream.end();}catch{}this.recordVideo==="on-fail"&&n.status==="PASSED"&&(tle(o,this.videoOutputPath),s.activeVideos=void 0),this.writeMetadata(s),this.reportProgress(i,r,a);}finishBeforeStepList(t){this.beforeResults=t;}finishAfterStepList(t){this.afterResults=t;}async startBeforeStepList(t=[]){this.beforeResults=t;let o=new iT(this.orgId,this.testId,this.testName,this.diskStorage,n=>this.flushResults({beforeResults:n}),this.buildAppGraphSink());return this.children.push(o),o}async startMainStepList(t=[]){this.mainResults=t;let o=new iT(this.orgId,this.testId,this.testName,this.diskStorage,n=>this.flushResults({mainResults:n}),this.buildAppGraphSink());return this.children.push(o),o}async startAfterStepList(t=[]){this.afterResults=t;let o=new iT(this.orgId,this.testId,this.testName,this.diskStorage,n=>this.flushResults({afterResults:n}),this.buildAppGraphSink());return this.children.push(o),o}async getScreenshot(t,o){return this.diskStorage.readFile(`${Ks}/${o}.jpeg`)}async getHtmlSnapshot(t,o){return this.diskStorage.readFile(`${Ks}/${o}.html`)?.toString()}};var kz=class{constructor(t,o,n,r,i,a,s,l){this.orgId=t;this.testId=o;this.testName=n;this.runId=r;this.metadata=i;this.diskStorage=a;this.recordVideo=s;this.progressHandle=l;}children=[];finished=false;get loggerBindings(){return {runId:this.runId}}get envVarBindings(){return {[rke]:this.runId}}get runMetadata(){return this.metadata}get storageDirectoryPath(){return this.diskStorage.cwd()}async finish(t){if(this.finished)return;this.finished=true;let n=this.children[this.children.length-1]?.getResourceUsageAverages(),r={...this.metadata,schemaVersion:qt,finishedAt:t.finishedAt||new Date,status:t.status,failureDetails:t.failureDetails,failureReason:t.failureReason,flake:t.isFlake||false,failureRecoveryDetails:t.failureRecoveryDetails,avgCpuUsage:n?.avgCpuUsage,avgMemoryUsage:n?.avgMemoryUsage,runAssertionResults:t.runAssertionResults,usage:t.usage};await Promise.all(this.children.map(i=>i.finish({logger:t.logger,result:{status:r.status}}))),this.diskStorage.storeFile({name:Mt,contents:JSON.stringify(r,null,2)}),this.diskStorage.close(),this.progressHandle.setStatus(t.status);}async startAttempt(t){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.metadata.schemaVersion=qt,this.diskStorage.storeFile({name:Mt,contents:JSON.stringify(this.metadata,null,2)});let o=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n={id:t,schemaVersion:qt,runAttemptSchemaVersion:jie,startedAt:new Date,status:"RUNNING"};o.storeFile({name:Mt,contents:JSON.stringify(n,null,2)});let r=new Pz(this.orgId,this.testId,this.testName,t,n,o,this.recordVideo,this.progressHandle);return this.children.push(r),r}};var aT=class e{constructor(t,o,n,r,i,a=true,s){this.orgId=t;this.runGroupId=o;this.metadata=n;this.diskStorage=r;this.recordVideo=i;this.ownsRunGroupMetadata=a;this.progressWriter=s;}children=[];finished=false;get loggerBindings(){return {orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}get runGroupMetadata(){return this.metadata}setAiSelectMetadata(t){this.metadata={...this.metadata,aiSelect:[t]};}static async start({suiteName:t,projectName:o,relativeProjectDir:n,orgId:r,runGroupId:i,outputDir:a,gitMetadata:s,labels:l,recordVideo:c,ai:u,browser:d,ownsRunGroupMetadata:m,progressSink:p,logger:h}){let g=m??true,f={...s,suiteName:t&&Yn(t),projectName:o,relativeProjectDir:n,id:i,trigger:ic.CLI,startedAt:new Date,status:"RUNNING",cliVersion:To,labels:l??[],ai:u,browser:d},y=new bx(a,h,g);return g&&y.storeFile({name:Mt,contents:JSON.stringify(f,null,2)}),new e(r,i,f,y,c??false,g,p??new RL(a,i,h))}getLiveRunStatusCounts(){return this.progressWriter.getRunStatusCounts()}registerWorkerRun(t){this.progressWriter.registerRun(t);}updateWorkerRun(t,o){this.progressWriter.updateRun(t,o);}async finish(t){this.finished||(this.finished=true,await ge({name:"cli.finish_run_group",serviceName:"cli",fn:()=>this.finishHelper(t)}));}async finishHelper(t){let{status:o}=t,n={...this.metadata,status:o,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(r=>r.finish({logger:t.logger,status:n.status,finishedAt:n.finishedAt}))),this.ownsRunGroupMetadata&&(this.diskStorage.storeFile({name:Mt,contents:JSON.stringify(n,null,2)}),this.progressWriter.finish(o));}async startRun(t){let o=this.diskStorage.createRunArchive(t.runId,t.logger),n={stepsSnapshot:t.originalSteps.steps,beforeStepsSnapshot:t.originalSteps.beforeSteps??void 0,afterStepsSnapshot:t.originalSteps.afterSteps??void 0,runGroupId:this.runGroupId,testId:t.testId,testName:t.testName?Yn(t.testName):t.testName,directory:t.directory,testDescription:t.testDescription,labels:t.testLabels,trigger:"CLI",status:"RUNNING",healStatus:"NOT_ATTEMPTED",resolvedBaseUrl:t.baseUrl,environmentName:t.environmentName,resolvedInputs:t.resolvedInputs,cliVersion:To,schemaVersion:t.schemaVersion,testBundleHash:t.testBundleHash,startedAt:new Date,attempts:0,quarantined:t.quarantined??false,quarantinedReason:t.quarantinedReason,executionType:"WEB",aiSettings:t.aiSettings};o.storeFile({name:Mt,contents:JSON.stringify(n,null,2)});let r=this.progressWriter.registerRun({runId:t.runId,testId:t.testId,testName:t.testName,directory:t.directory,totalSteps:nle([...t.originalSteps.beforeSteps??[],...t.originalSteps.steps,...t.originalSteps.afterSteps??[]])}),i=new kz(this.orgId,t.testId,t.testName,t.runId,n,o,t.recordVideoOverride??this.recordVideo,r);return this.children.push(i),i}};async function _Be(e,t,o){if(o)return {};try{let{quarantined:n}=await t.getQuarantinedTests();return Object.fromEntries(n.map(r=>[r.testId,{quarantinedAt:r.quarantinedAt,quarantinedReason:r.quarantinedReason,quarantinedBy:r.quarantinedBy}]))}catch(n){return e.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}var Mz=class{constructor(t){this.send=t;}onBegin(t){}onTestBegin(t){this.send({type:"reporter",event:"testBegin",testRef:t});}onTestStatus(t,o,n){this.send({type:"reporter",event:"testStatus",testRef:t,status:o,note:n});}onStepStart(t,o,n){this.send({type:"reporter",event:"stepStart",testRef:t,label:o,depth:n});}onStepEnd(t,o,n){this.send({type:"reporter",event:"stepEnd",testRef:t,label:o,depth:n.depth,durationMs:n.durationMs,success:n.success});}onSectionStart(t,o){this.send({type:"reporter",event:"sectionStart",testRef:t,label:o});}onTestEnd(t,o,n){this.send({type:"reporter",event:"testEnd",testRef:t,status:o,recovered:n?.recovered});}onEnd(t){}};var HO="__run-worker";function M2t(){let e=[],t=false,o=[];return {next:()=>{let a=e.shift();return a?Promise.resolve(a):t?Promise.resolve(void 0):new Promise(s=>o.push(s))},assignTest:a=>{let s=o.shift();s?s(a):e.push(a);},markNoMoreTests:()=>{for(t=true;o.length>0;)o.shift()(void 0);}}}var tX=class{constructor(t){this.emit=t;}registerRun(t){return this.emit({type:"progressRegister",params:t}),new yI(this,t.runId)}updateRun(t,o){this.emit({type:"progressUpdate",runId:t,update:o});}finish(){}getRunStatusCounts(){}};async function oX(){let e=process.send?.bind(process);e||(x.error("Worker process started without an IPC channel."),Je(He.Failure));let t=f=>new Promise(y=>e(f,void 0,void 0,()=>y())),o=M2t(),n=[],r=await new Promise((f,y)=>{let b=false,S=()=>{process.off("message",v),process.off("disconnect",R);},A=I=>{b||(b=true,S(),y(I));},T=I=>{b||(b=true,S(),f(I));},v=I=>{if(I.type==="init"){T(I.config);return}n.push(I);},R=()=>{A(new Error("Parent process disconnected before sending init"));};process.on("message",v),process.on("disconnect",R),t({type:"ready"});}),i,a=[],s=f=>{switch(f.type){case "assignTest":o.assignTest(f.test);return;case "noMoreTests":o.markNoMoreTests();return;case "cancel":o.markNoMoreTests(),i?i.cancel(f.reason,f.waitForRunsToSettle):a.push(f);return}};process.on("message",s);for(let f of n)s(f);r.shareDiagnostics&&await su({serviceName:"cli",enabled:true});let l=new so({baseUrl:r.serverUrl??"",apiKey:r.apiKey??"",logger:Re,mode:"runner",runner:"test-runner"}),c=new ii(r.project.config.ai?.agentConfig,{baseUrl:l.baseUrl,apiKey:l.apiKey,logger:Re,mode:"runner",runner:"test-runner"}),u=await aT.start({orgId:r.orgId,runGroupId:r.runGroupId,projectName:r.project.config.name,relativeProjectDir:await BA(r.project.rootDir),outputDir:r.outputDir,gitMetadata:r.gitMetadata,recordVideo:r.recordVideo,ai:r.project.config.ai,browser:r.project.config.browser,ownsRunGroupMetadata:false,progressSink:new tX(f=>void t(f)),logger:Re}),d=Re,m=d.child(u.loggerBindings||{}),p=new Mz(f=>void t(f));i=new xw({next:o.next,parallel:r.parallel,reporter:p,runGroupTracer:u,runGroupLogger:m,logger:d,project:r.project,client:l,generator:c,orgId:r.orgId,userId:r.userId,devicePixelRatio:r.devicePixelRatio,outputDir:r.outputDir,retriesOverride:r.retriesOverride,urlOverride:r.urlOverride,envName:r.envName,customHeaders:r.customHeaders,regenerateGoldenFiles:r.regenerateGoldenFiles,gitMetadata:r.gitMetadata,cacheOptions:r.cacheOptions,browserTypeOverride:r.browserTypeOverride,remoteBrowserOverride:r.remoteBrowserOverride,browserFleetRegion:r.browserFleetRegion,recordVideo:r.recordVideo,traceMetadata:{runGroupId:r.runGroupId,parallel:r.runParallel,workerCount:r.workerCount,workerIndex:r.workerIndex,remoteBrowser:r.remoteBrowser},onResult:f=>void t({type:"result",result:f}),onFatal:f=>void t({type:"fatal",message:W(f)})});for(let f of a)s(f);let h=await _w({cancel:f=>i.cancel(f),run:()=>i.run()});process.off("message",s);let g=h.cancelled?"CANCELLED":Ek(h.runResults);await u.finish({logger:m,status:g}),await t({type:"done",cancelledRuns:[...h.cancelledRunsById.values()],cancelled:h.cancelled,cancellationReason:h.cancellationReason}),Je(He.Success);}var N2t=3e4,D2t=5e3,F2t="MOMENTIC_WORKER_PROCESSES";function OBe({parallel:e,testCount:t,override:o=process.env[F2t]}){let n=Math.max(1,Math.min(e,t));if(o===void 0||o.trim().length===0)return 1;let r=Number(o);return !Number.isFinite(r)||r<1?1:Math.min(Math.floor(r),n)}function B2t(e,t){if(t<=0)return [];let o=Math.floor(e/t),n=e-o*t;return Array.from({length:t},(r,i)=>i<n?o+1:o)}var nX=class{constructor(t){this.params=t;}runResults=[];cancelledRunsById=new Map;reportedRunIds=new Set;cancelled=false;cancellationReason;workers=[];pendingQueue=[];async cancel(t){this.cancelled||(this.cancelled=true,this.cancellationReason=t);let o={type:"cancel",reason:t,waitForRunsToSettle:true};for(let n of this.workers)this.cancelWorker(n,o);}async start(){let{engineTests:t,parallel:o,workerCount:n}=this.params,r=B2t(o,n);return this.pendingQueue=[...t],this.workers=r.map((i,a)=>this.spawnWorker({index:a,parallel:i})),await Promise.all(this.workers.map(i=>i.donePromise)),{runResults:this.runResults,cancelledRunsById:this.cancelledRunsById,cancelled:this.cancelled,cancellationReason:this.cancellationReason}}spawnWorker({index:t,parallel:o}){let n=process.argv[1];if(!n)throw new Error("Cannot fork worker: process.argv[1] is undefined.");let r=fork(n,[HO],{serialization:"advanced",stdio:["ignore","pipe","pipe","ipc"],env:process.env}),i,a=new Promise(l=>{i=l;}),s={index:t,child:r,parallel:o,inFlight:0,dispatchedTests:[],noMoreTestsSent:false,donePromise:a,resolveDone:i,settled:false,exitCode:null,exitSignal:null};return this.forwardChildLogs(r,t),r.on("message",l=>this.handleWorkerMessage(s,l)),r.on("error",l=>{this.params.logger.error({err:l,workerIndex:t},"Worker error");}),r.on("exit",(l,c)=>{s.exitCode=l,s.exitSignal=c;}),r.on("close",()=>this.handleWorkerClose(s)),s}dispatchToWorker(t){if(t.settled||this.cancelled)return;let o=Math.max(0,t.parallel-t.inFlight),n=this.pendingQueue.splice(0,Math.min(o,this.pendingQueue.length));for(let r of n)t.dispatchedTests.push(r),t.inFlight++,t.child.send({type:"assignTest",test:r});!t.noMoreTestsSent&&this.pendingQueue.length===0&&t.inFlight===0&&t.child.connected&&(t.noMoreTestsSent=true,t.child.send({type:"noMoreTests"}));}handleWorkerMessage(t,o){switch(o.type){case "ready":t.child.send({type:"init",config:{...this.params.baseConfig,workerIndex:t.index,parallel:t.parallel}}),this.dispatchToWorker(t);return;case "reporter":this.relayReporterEvent(o);return;case "result":o.result.runId&&this.reportedRunIds.add(o.result.runId),this.runResults.push(o.result),t.inFlight=Math.max(0,t.inFlight-1),this.dispatchToWorker(t);return;case "progressRegister":this.params.runGroupTracer.registerWorkerRun(o.params);return;case "progressUpdate":this.params.runGroupTracer.updateWorkerRun(o.runId,o.update);return;case "fatal":this.params.logger.error({workerIndex:t.index,message:o.message},"Worker reported a fatal error"),this.cancel("Fatal error occurred");return;case "done":for(let n of o.cancelledRuns)n.runId&&(this.reportedRunIds.add(n.runId),this.cancelledRunsById.set(n.runId,n));o.cancelled&&!this.cancelled&&(this.cancelled=true,this.cancellationReason=o.cancellationReason),this.settleWorker(t);return}}relayReporterEvent(t){let{reporter:o}=this.params;switch(t.event){case "testBegin":o.onTestBegin(t.testRef);return;case "testStatus":o.onTestStatus(t.testRef,t.status??"",t.note);return;case "stepStart":o.onStepStart(t.testRef,t.label??"",t.depth);return;case "stepEnd":o.onStepEnd(t.testRef,t.label??"",{durationMs:t.durationMs??0,success:t.success??false,depth:t.depth??0});return;case "sectionStart":o.onSectionStart(t.testRef,t.label??"");return;case "testEnd":o.onTestEnd(t.testRef,t.status??"",{recovered:t.recovered});return}}handleWorkerClose(t){t.settled||(this.params.logger.error({workerIndex:t.index,code:t.exitCode,signal:t.exitSignal},"Worker exited before reporting completion"),this.cancel("Worker process exited unexpectedly"),this.settleWorker(t));}settleWorker(t){t.settled||(t.settled=true,clearTimeout(t.cancelTimer),clearTimeout(t.forceKillTimer),this.synthesizeMissingResults(t),t.resolveDone());}cancelWorker(t,o){t.settled||(t.child.connected&&t.child.send(o),!t.cancelTimer&&(t.cancelTimer=setTimeout(()=>{t.settled||(this.params.logger.warn({workerIndex:t.index},"Worker did not exit after cancellation"),t.child.kill("SIGTERM"),t.forceKillTimer=setTimeout(()=>{t.settled||t.child.kill("SIGKILL");},D2t),t.forceKillTimer.unref());},N2t),t.cancelTimer.unref()));}synthesizeMissingResults(t){let o=this.cancellationReason??"Worker process exited unexpectedly";for(let n of t.dispatchedTests){if(this.reportedRunIds.has(n.runId))continue;this.reportedRunIds.add(n.runId);let r=new Date;this.cancelledRunsById.set(n.runId,{results:[],beforeResults:[],afterResults:[],test:n.testDefinition,filePath:n.testDefinition.relativeFilePath,startedAt:r,lastAttemptStartedAt:r,finishedAt:r,status:"CANCELLED",attempts:0,runId:n.runId,cancellationReason:o,quarantined:n.quarantined,quarantinedMetadata:n.quarantinedMetadata,parameters:{testInputs:n.inputs,envName:this.params.baseConfig.envName,urlOverride:this.params.baseConfig.urlOverride,customHeaders:this.params.baseConfig.customHeaders},outputs:{}});}}forwardChildLogs(t,o){let n=r=>{let i=r.toString().trimEnd();i.length>0&&this.params.logger.debug({workerIndex:o},i);};t.stdout?.on("data",n),t.stderr?.on("data",n);}};async function PBe(e){let t=new nX({engineTests:e.engineTests,parallel:e.parallel,workerCount:e.workerCount,reporter:e.reporter,logger:e.logger,baseConfig:e.baseConfig,runGroupTracer:e.runGroupTracer});return e.logger.info({workerCount:e.workerCount,parallel:e.parallel,testCount:e.engineTests.length},"Running local tests with a worker pool"),_w({timeoutMinutes:e.timeoutMinutes,cancel:o=>t.cancel(o),run:()=>t.start()})}async function aX({logger:e,orgId:t,waitOn:o,waitOnProxy:n,waitOnTimeout:r,log:i=true}){e.info({orgId:t},`Waiting for url: ${o} with timeout: ${r} seconds.`);let a=n?new URL(n):void 0,s;a&&(s={host:a.hostname,port:a.port?parseInt(a.port):a.protocol.startsWith("https")?443:80,auth:a.username||a.password?{username:a.username,password:a.password}:void 0}),await j2t({resources:[o],interval:2500,timeout:r*1e3,headers:{Accept:"*/*"},followRedirect:true,verbose:false,log:i,strictSSL:false,proxy:s});}async function MBe(e){let{suiteName:t,logger:o,tests:n,snapshots:r,yes:i,start:a,waitOn:s,waitOnProxy:l,client:c,project:u,retriesOverride:d,urlOverride:m,envName:p,orgId:h,userId:g,devicePixelRatio:f,customHeaders:y,testInputMatrix:b,include:S,exclude:A,labels:T,reporterDir:v=kye,outputDir:R=Ed,uploadResults:I=false,waitOnTimeout:C=60,parallel:O,shardIndex:P=1,shardCount:k=1,regenerateGoldenFiles:N,gitMetadata:M,cacheOptions:L,ignoreQuarantine:G,skipQuarantined:X,onlyQuarantined:B,runGroupId:K,recordVideo:ee,timeoutMinutes:z,workers:F,browserTypeOverride:j,remoteBrowserOverride:te,browserFleetRegion:Ae,aiSelect:Se=false,aiSelectBase:De,aiSelectBudget:at,aiSelectDryRun:Q=false,aiSelectPrompts:Ce=[],shareDiagnostics:Ee}=e,Rt=Se||Q,lt=Rt&&!r;Q||(a&&(o.info({orgId:h},`Executing start command: ${a}`),await Wj(a,false)),s&&await aX({logger:o,orgId:h,waitOn:s,waitOnProxy:l,waitOnTimeout:C}));let de=new ii(u.config.ai?.agentConfig,{baseUrl:c.baseUrl,apiKey:c.apiKey,logger:o,mode:"runner",runner:"test-runner"}),Ke=null,Yt=null,pt=[],pe=[],ve={},dt,Ze=[];if(r)dt=r.map(Be=>({inputs:void 0,testDefinition:Be.testDefinition,snapshot:Be}));else {let Be=await yt(u);Ze=await My({tests:n,momenticFiles:Be,yes:i,project:u,include:S,exclude:A,labels:T,logger:x}),lt&&x.log(`Momentic CLI v${To}`);let Zo=await H2t({envName:p,aiSelect:Rt,aiSelectBase:De,aiSelectBudget:at,aiSelectDryRun:Q,aiSelectPrompts:Ce,allTestDefinitions:Ze,client:c,gitMetadata:M,logger:o,orgId:h,project:u});Ke=Zo.selectionPlanResult,Yt=Zo.aiSelectMetadata;let pi=Zo.testDefinitions;ve=await _Be(o,c,G);let Qa=nFe({testDefinitions:pi,quarantinedTestsMetadata:ve,onlyQuarantined:B,skipQuarantined:X,shardIndex:P});pt=Qa.testsToSkip,pe=Qa.quarantinedTestsToSkip,dt=rFe({testsToRun:Qa.testsToRun,quarantinedTestsToRun:Qa.quarantinedTestsToRun,quarantinedTestsMetadata:ve,testInputMatrix:b});}let an=fse({items:dt,shardIndex:P,shardCount:k,sortKey:Be=>`${Be.testDefinition.fullFilePath}:${Be.inputIndex??0}`}),ct=an.some(Be=>QR(Be.testDefinition));ct&&hI(),o.info({tests:an.length,shardCount:k,shardIndex:P,parallel:O},"Running local tests");let lo=an.filter(Be=>Be.quarantined).length,mi=an.length-lo,Or=OBe({parallel:O,testCount:an.length,override:F!==void 0?String(F):void 0}),Pr=[...pt.map(Be=>({relativeFilePath:Be.relativeFilePath,skipped:{kind:"disabled"}})),...pe.map(Be=>({relativeFilePath:Be.relativeFilePath,quarantined:true,skipped:{kind:"quarantined",reason:ve[Be.id]?.quarantinedReason??void 0}}))],Oa=rt(),Os=te??u.config.browser?.remoteBrowser??false;x.log(ISe({cliName:lt?void 0:"Momentic CLI",cliVersion:lt?void 0:To,parallel:O,workerCount:Or,timeoutMinutes:z,runningCount:mi,quarantinedCount:lo,skippedCount:Pr.length,shardIndex:P,shardCount:k},Oa));let{live:mo,files:Co,network:Qo}=TTe({reporter:e.reporter,screen:Oa});x.log(""),mo.onBegin({parallel:O,shardCount:k,shardIndex:P,tests:[...Pr,...an.map(Be=>({relativeFilePath:Be.testDefinition.relativeFilePath,inputIndex:Be.inputIndex,quarantined:Be.quarantined}))]});let it=[],Ye=new Map,ro=false,ut,ot=new Date,Fo=async()=>{let Be=c.getAppUrl(),Zo=[...Ye.values(),...it.filter(ne=>!ne.runId||!Ye.has(ne.runId))].map(ne=>ne.status==="CANCELLED"&&!ne.cancellationReason?{...ne,cancellationReason:ut}:ne),pi=b2(Zo),Qa=Zo.filter(ne=>ne.status==="PASSED"&&!!ne.failureRecoveryDetails?.attempts).length,U={results:Zo,startTime:ot.getTime(),getPath:ne=>ne.filePath,getUrl:ne=>ne.runId?`${Be}/runs/${ne.runId}`:void 0,getFailureSummary:ne=>ne.failureReason?Vd({failureReason:ne.failureReason,classification:ne.failureDetails?.classification,manualClassification:ne.failureDetails?.manualClassification}).title??ne.failureReason:"Test failed",printFailureBody:tL,getCancellationReason:ne=>ne.cancellationReason,recoveredCount:Qa,skippedCount:Pr.length,videoRecordingActive:(!!ee||ct)&&Os};if(mo.onEnd(U),S2(U),YSe({errorMessages:Zo.map(ne=>ne.failureDetails?.errorMessage),doctorCommand:"`npx momentic doctor`"}),x.log(""),I){let ne=await Ho({text:"Uploading to Momentic\u2026",screen:Oa},()=>ge({name:"file-storage.upload_test_outputs",serviceName:"file-storage",fn:()=>yx({client:c,resultsPath:R})}));ne.success?(x.success("Uploaded to Momentic."),x.dimmed(` ${Br(ne.runGroupUrl,Oa)}`)):(x.error(`Upload failed: ${ne.error}.`),x.success(`Saved to ${R}/`),x.dimmed(` upload: npx momentic results upload ${R}`),x.dimmed(` view: npx momentic results view ${R}`)),Ep({type:"cli:results_uploaded",test_platform:"web",success:ne.success});}else if(x.success(`Saved to ${R}/`),x.dimmed(` upload: npx momentic results upload ${R}`),x.dimmed(` view: npx momentic results view ${R}`),k>1||P>1){let At=Ch.dirname(R)||".";x.dimmed(` merge shards: npx momentic results merge ${At} --output-dir ${Ch.join(At,"merged")}`);}else {let At=`${Be}/run-groups/${K}`;x.dimmed(` after upload: ${Br(At,Oa)}`);}return pi},Wn=await aT.start({suiteName:t,projectName:u.config.name,relativeProjectDir:await BA(u.rootDir),orgId:h,runGroupId:K,outputDir:R,gitMetadata:M,labels:T,recordVideo:ee,ai:u.config.ai,browser:u.config.browser,logger:o});Yt&&Wn.setAiSelectMetadata(Yt);let Po=o.child(Wn.loggerBindings||{}),Ct=an.map(Be=>({...Be,runId:randomUUID()}));if(Or>1){let Be=await PBe({engineTests:Ct,parallel:O,workerCount:Or,timeoutMinutes:z,reporter:mo,logger:Po,runGroupTracer:Wn,baseConfig:{project:u,serverUrl:c.baseUrl,apiKey:c.apiKey,orgId:h,userId:g,runGroupId:K,devicePixelRatio:f,outputDir:R,retriesOverride:d,urlOverride:m,envName:p,customHeaders:y,regenerateGoldenFiles:N,gitMetadata:M,cacheOptions:L,browserTypeOverride:j,remoteBrowserOverride:te,browserFleetRegion:Ae,recordVideo:ee,shareDiagnostics:Ee,runParallel:O,workerCount:Or,remoteBrowser:Os}});it.push(...Be.runResults);for(let[Zo,pi]of Be.cancelledRunsById)Ye.set(Zo,pi);ro=Be.cancelled,ut=Be.cancellationReason;}else {let Be=new xw({testsToRun:Ct,parallel:O,reporter:mo,runGroupTracer:Wn,runGroupLogger:Po,logger:o,project:u,client:c,generator:de,orgId:h,userId:g,devicePixelRatio:f,outputDir:R,retriesOverride:d,urlOverride:m,envName:p,customHeaders:y,regenerateGoldenFiles:N,gitMetadata:M,cacheOptions:L,browserTypeOverride:j,remoteBrowserOverride:te,browserFleetRegion:Ae,recordVideo:ee,traceMetadata:{runGroupId:K,parallel:O,workerCount:Or,workerIndex:0,remoteBrowser:Os}}),Zo=await _w({timeoutMinutes:z,cancel:pi=>Be.cancel(pi),run:()=>Be.run()});it.push(...Zo.runResults);for(let[pi,Qa]of Zo.cancelledRunsById)Ye.set(pi,Qa);ro=Zo.cancelled,ut=Zo.cancellationReason;}let qn=ro?"CANCELLED":Ek(it,{onlyQuarantined:B});await Wn.finish({logger:Po,status:qn}),Ep({type:"cli:run_completed",test_platform:"web",status:qn,test_count:it.length,duration_ms:Date.now()-ot.getTime()});for(let Be of Co)await ge({name:"reporting.write_standard_report",serviceName:"reporting",fn:()=>j0e({logger:Po,callbacks:{createDebugDataReaderForRunAttempt:(Zo,pi)=>new VD(R,Zo,pi)},format:Be,params:{projectConfigPath:u.configFilePath,suiteName:t??u.config.name,startedAt:ot,finishedAt:new Date,testsToSkip:pt,quarantinedTestsToSkip:pe,quarantinedTestsMetadata:ve},runs:it,folder:v})});if(Qo.includes("newrelic")){let Be=u.config.reporting?.newrelic;if(!Be)x.error("The newrelic reporter requires a reporting.newrelic block in momentic.config.yaml.");else try{await ge({name:"reporting.send_new_relic_report",serviceName:"reporting",fn:()=>k6({logger:x,config:{...Be,accountId:bc(Be.accountId),licenseKey:Be.licenseKey?bc(Be.licenseKey):void 0,attributes:Be.attributes?Object.fromEntries(Object.entries(Be.attributes).map(([Zo,pi])=>[Zo,bc(pi)])):void 0},params:{projectConfigPath:u.configFilePath,suiteName:t??u.config.name,startedAt:ot,finishedAt:new Date,testsToSkip:pt,quarantinedTestsToSkip:pe,quarantinedTestsMetadata:ve},runs:it,runGroupId:K,envName:p,appUrl:c.getAppUrl(),gitMetadata:M})});}catch(Zo){x.error(`Failed to send report to New Relic: ${W(Zo)}`);}}let $o=await Fo();if(z2t(),Ke){let Be=M.githubRepository??M.gitOriginUrl??"",Zo=Ke.diff?.headSha??"";if(Be.length>0&&Zo.length>0){let pi=Ke.kind==="ready"?Ke.plan.selectedTests.map(U=>U.testId):[],Qa=Ke.kind==="ready"?Ke.planId:null;o.info({event:"ai_select.run_outcome",repository:Be,headSha:Zo,runGroupId:K,planId:Qa,mode:Q?"SHADOW":"SELECTED",totalCandidates:Ze.length,selectedCount:pi.length,excludedCount:0,unobservedRunCount:Yt?.forcedTests.length??0},"ai-select run outcome");}}return $o}function z2t(){if(!Md.isEnabled()||Md.getTotalRecords()===0)return;let e=Md.getSummary(),t=Md.getTotalRecords(),o=e.reduce((n,r)=>n+r.totalMs,0);x.log(""),x.dimmed(`CDP Performance Summary (${t} calls, ${$O(o)} total)`),x.dimmed(kBe("Method",40)+Rp("Count",8)+Rp("Total",12)+Rp("Avg",12)+Rp("Min",12)+Rp("Max",12));for(let n of e)x.dimmed(kBe(n.method,40)+Rp(String(n.count),8)+Rp($O(n.totalMs),12)+Rp($O(n.avgMs),12)+Rp($O(n.minMs),12)+Rp($O(n.maxMs),12));x.log("");}function $O(e){return e>=1e3?`${(e/1e3).toFixed(2)}s`:`${e.toFixed(1)}ms`}async function H2t(e){let{aiSelect:t,aiSelectBase:o,aiSelectBudget:n,aiSelectDryRun:r,aiSelectPrompts:i,allTestDefinitions:a,client:s,gitMetadata:l,logger:c,orgId:u,project:d}=e;if(!t)return {selectionPlanResult:null,aiSelectMetadata:null,testDefinitions:a};let m=l.githubRepository??l.gitlabProjectPath??l.gitOriginUrl??"";if(m.length===0)return x.warn("AI test selection unavailable; running all tests."),x.dimmed(" Reason: could not determine repository identity from git metadata."),{selectionPlanResult:null,aiSelectMetadata:null,testDefinitions:a};let p=d.config.ai?.select,h={baseUrl:s.baseUrl,apiKey:s.apiKey,logger:c,mode:s.mode,runner:"ai-select"},g=new so(h),f=new ii(d.config.ai?.agentConfig,h),y=await jD({client:g,gitMetadata:l,logger:c}),b=n??p?.targetTests??null,S="default";n!==void 0?S="cli-flag":p?.targetTests!==void 0&&(S="config");let A;try{A=await x6({apiClient:g,generator:f,logger:c,orgId:u,repoRoot:d.rootDir??process.cwd(),repository:m,explicitBase:o,config:p,mainBranch:d.config.gitMainBranch,budgetCap:b,budgetSource:S,dryRun:r,customPrompt:RO(i),environmentName:e.envName,changeRequestDescription:y,candidateTests:a.map(C=>({testPath:C.relativeFilePath.split(Ch.sep).join("/"),testId:C.id,baseUrl:C.baseUrl??void 0,description:C.description??void 0})),allTestDefinitions:a.map(C=>({id:C.id,name:C.name,relativeFilePath:C.relativeFilePath})),agentOutputStream:process.stdout});}catch(C){c.warn({err:C},"ai-select failed; falling back to run-all");let O={kind:"run-all",reason:`AI selection failed: ${W(C)}.`,diff:null},P=rX({selectionPlanResult:O,aiSelectDryRun:r,totalCandidates:a.length,selectedCount:a.length,forcedTests:[]});return iX(P),{selectionPlanResult:O,aiSelectMetadata:P,testDefinitions:a}}let T=A.kind==="ready"&&A.diff?yO({allTestDefinitions:a,changedFiles:A.diff.changedFiles,repoRoot:A.diff.repoRoot,projectRoot:d.rootDir??process.cwd()}):[],v=A.kind==="ready"?$2t(a,A.plan.selectedTests,T,c):{tests:[],planMatchedCount:0};if(A.kind==="ready"&&!r&&a.length>0&&v.tests.length===0&&A.plan.selectedTests.length>0){c.warn({planId:A.planId,planSize:A.plan.selectedTests.length,candidateCount:a.length},"ai-select: plan matched zero in-scope tests; falling back to run-all");let C={kind:"run-all",reason:"AI-selected tests did not match any in-scope tests; running all tests instead.",diff:A.diff},O=rX({selectionPlanResult:C,aiSelectDryRun:r,totalCandidates:a.length,selectedCount:a.length,forcedTests:T});return iX(O),{selectionPlanResult:C,aiSelectMetadata:O,testDefinitions:a}}let R=a;A.kind==="ready"&&!r?R=v.tests:A.kind==="run-none"&&!r&&(R=[]);let I=rX({selectionPlanResult:A,aiSelectDryRun:r,totalCandidates:a.length,selectedCount:v.planMatchedCount,forcedTests:T});return iX(I),r&&Je(He.Success),{selectionPlanResult:A,aiSelectMetadata:I,testDefinitions:R}}function rX(e){let{selectionPlanResult:t,aiSelectDryRun:o,forcedTests:n}=e,r=n.map(a=>({name:a.test.name,testPath:a.test.relativeFilePath,status:a.status}));if(t.kind==="run-all")return {mode:"RUN_ALL",baseRef:t.diff?.baseRef??null,headSha:t.diff?.headSha??"",planId:null,totalCandidates:e.totalCandidates,selectedCount:e.totalCandidates,anchorSegmentIds:[],userSummary:"",toolCallCount:0,selectedTests:[],forcedTests:r,runAllReason:t.reason};if(t.kind==="run-none")return {mode:"RUN_NONE",baseRef:t.diff.baseRef,headSha:t.diff.headSha,planId:null,totalCandidates:e.totalCandidates,selectedCount:0,anchorSegmentIds:[],userSummary:"",toolCallCount:0,selectedTests:[],forcedTests:r,runAllReason:t.reason};let{plan:i}=t;return {mode:o?"SHADOW":"SELECTED",baseRef:t.diff.baseRef,headSha:t.diff.headSha,planId:t.planId,totalCandidates:e.totalCandidates,selectedCount:e.selectedCount,anchorSegmentIds:i.anchorSegmentIds,userSummary:i.userSummary,toolCallCount:i.toolCallCount,selectedTests:i.selectedTests.map(a=>({testId:a.testId,name:a.name,testPath:a.testPath,confidence:a.confidence,signals:a.signals,rationale:a.rationale})),forcedTests:r,runAllReason:null}}function iX(e){let t=rt(),o=ht(t),n=[],r=i=>Ka({label:"",text:i,screen:t,indent:4});switch(e.mode){case "RUN_ALL":n.push(` ${o.statusGlyph("cancel")} AI selection unavailable${o.dim(`${o.separator}running all ${e.totalCandidates} tests`)}`),e.runAllReason&&n.push(...r(e.runAllReason));break;case "RUN_NONE":n.push(` ${o.statusGlyph("skip")} No relevant tests${o.dim(`${o.separator}skipping all ${e.totalCandidates} tests`)}`),e.runAllReason&&n.push(...r(e.runAllReason));break;case "SHADOW":n.push(` ${o.statusGlyph("pass")} Dry run${o.separator}AI would have selected ${e.selectedCount} of ${e.totalCandidates} tests`),n.push(...r(e.userSummary));break;case "SELECTED":if(n.push(` ${o.statusGlyph("pass")} Selected ${e.selectedCount} of ${e.totalCandidates} tests with AI`),n.push(...r(e.userSummary)),e.forcedTests.length>0){n.push("",` ${o.statusGlyph("pass")} ${e.forcedTests.length} ${e.forcedTests.length===1?"test":"tests"} force-included${o.dim(`${o.separator}edited or added in this change`)}`);for(let i of e.forcedTests)n.push(` ${o.dim("-")} ${i.name} ${o.dim(`(${i.testPath})`)}`);}break;default:mt(e.mode);}n.push(""),x.log(n.join(`
4660
4660
  `));}function $2t(e,t,o,n){let r=new Set,i=new Set;for(let c of t)r.add(c.testId),c.testPath&&i.add(c.testPath);let a=new Set(o.map(c=>c.test.id)),s=[],l=0;for(let c of e){let u=c.relativeFilePath.split(Ch.sep).join("/"),d=r.has(c.id)||i.has(u);d&&l++,(d||a.has(c.id))&&s.push(c);}return n.info({total:e.length,selected:s.length,planSize:t.length,forcedCount:o.length},"ai-select: intersected plan with local tests"),{tests:s,planMatchedCount:l}}function kBe(e,t){return e.length>t?e.substring(0,t-1)+"\u2026":e+" ".repeat(t-e.length)}function Rp(e,t){return e.length>=t?e:" ".repeat(t-e.length)+e}var LBe=30,q2t=1e3,Nz=32;function DBe(e){let t=new Set([...e.recoveredPromotedRunIds??[],...e.quarantinedSelectedRunIds??[]]);return e.selectedForHealing.filter(o=>!t.has(o.runId))}function FBe(e){return DBe(e).length+e.failed.length}function BBe(e,t){return t?CQ({failureCount:FBe(e),totalCount:K2t(e)}):{withinBudget:true}}function K2t(e){return FBe(e)+(e.quarantinedSelectedRunIds??[]).length+e.quarantined.failed.length+e.passed.length+e.recovered.length+e.quarantined.passed.length}function Mw(){return {selectedForHealing:[],recovered:[],passed:[],failed:[],quarantined:{passed:[],failed:[]}}}async function UBe({resultsDir:e,excludePatterns:t,...o}){let n=Cn__default.resolve(e);await $d("load_target");let r=await ge({name:"heal.load_target",attributes:{"momentic.heal_target_kind":"results"},fn:async()=>X2t({resultsDir:n,logger:o.logger})}),{healableFailures:i,triageInputSummary:a}=Uz({runs:r,excludePatterns:t,skipQuarantined:o.skipQuarantined,ignoreQuarantine:o.ignoreQuarantine}),s=o.agentOutputStream?new As(o.agentOutputStream):void 0,l=Nw(o);try{let{recoveryAssessments:c,permanentRecoveryCandidates:u}=await Fz({candidates:r,excludePatterns:t,triageInputSummary:a,isCompleteRunGroup:!0,outputDir:n,output:s,timelineRecorder:l,shared:o}),d=[...i,...u];return {...await Lw({...o,healingCandidates:d,triageInputSummary:a,outputDir:n,output:s,timelineRecorder:l,source:n,isCompleteRunGroup:!0,noResultsMessage:`No failed or permanently-healable recovered test results found in ${n}.`}),recoveryAssessments:c}}finally{s?.finalize();}}async function jBe({runGroupId:e,excludePatterns:t,...o}){await $d("load_target");let n=await ge({name:"heal.load_target",attributes:{"momentic.heal_target_kind":"run-group"},fn:()=>sX({agentOutputStream:o.agentOutputStream,text:`Loading run group ${e}...`,fn:()=>J2t({apiClient:o.apiClient,logger:o.logger,runGroupId:e})})}),{healableFailures:r,triageInputSummary:i}=Uz({runs:n,excludePatterns:t,skipQuarantined:o.skipQuarantined,ignoreQuarantine:o.ignoreQuarantine}),a=o.agentOutputStream?new As(o.agentOutputStream):void 0,s=Nw(o);try{let{recoveryAssessments:l,permanentRecoveryCandidates:c}=await Fz({candidates:n,excludePatterns:t,triageInputSummary:i,isCompleteRunGroup:!0,output:a,timelineRecorder:s,shared:o});o.logger.info({runGroupId:e,healableFailureCount:r.length,permanentRecoveryCandidateCount:c.length},`Identified ${r.length+c.length} run${r.length+c.length===1?"":"s"} to heal from run group.`);let u=[...r,...c];return {...await Lw({...o,healingCandidates:u,triageInputSummary:i,output:a,timelineRecorder:s,source:`run group ${e}`,isCompleteRunGroup:!0,noResultsMessage:`No failed or permanently-healable recovered runs found in run group ${e}.`}),recoveryAssessments:l}}finally{a?.finalize();}}async function zBe({runIds:e,excludePatterns:t,...o}){await $d("load_target");let n=await ge({name:"heal.load_target",attributes:{"momentic.heal_target_kind":"run","momentic.run_count":e.length},fn:()=>sX({agentOutputStream:o.agentOutputStream,text:e.length===1?`Loading run ${e[0]}...`:`Loading ${e.length} runs...`,fn:()=>Promise.all(e.map(async c=>{let u=await o.apiClient.getRun(c);if(!u)throw new ae(`Run ${c} was not found. Check the run ID and that your API key belongs to the same organization.`);return Bz({run:u,logger:o.logger,scopeLabel:`run ${c}`})}))})}),{healableFailures:r,triageInputSummary:i}=Uz({runs:n,excludePatterns:t,skipQuarantined:o.skipQuarantined,ignoreQuarantine:o.ignoreQuarantine}),a=e.length===1?`run ${e[0]}`:`${e.length} runs`,s=o.agentOutputStream?new As(o.agentOutputStream):void 0,l=Nw(o);try{let{recoveryAssessments:c,permanentRecoveryCandidates:u}=await Fz({candidates:n,excludePatterns:t,triageInputSummary:i,isCompleteRunGroup:!1,output:s,timelineRecorder:l,shared:o});o.logger.info({runIds:e,healableFailureCount:r.length,permanentRecoveryCandidateCount:u.length},`Identified ${r.length+u.length} run${r.length+u.length===1?"":"s"} to heal.`);let d=[...r,...u];return {...await Lw({...o,healingCandidates:d,triageInputSummary:i,output:s,timelineRecorder:l,source:a,isCompleteRunGroup:!1,noResultsMessage:`No failed or permanently-healable recovered runs found for ${a}.`}),recoveryAssessments:c}}finally{s?.finalize();}}async function HBe({gitCommitSha:e,excludePatterns:t,...o}){await $d("load_target");let r=(await ge({name:"heal.load_target",attributes:{"momentic.heal_target_kind":"commit"},fn:()=>sX({agentOutputStream:o.agentOutputStream,text:`Loading runs for commit ${e}...`,fn:()=>o.apiClient.getRunsByCommit(e)})})).map(c=>Bz({run:c,logger:o.logger,scopeLabel:`commit ${e}`})),{healableFailures:i,triageInputSummary:a}=Uz({runs:r,excludePatterns:t,skipQuarantined:o.skipQuarantined,ignoreQuarantine:o.ignoreQuarantine}),s=o.agentOutputStream?new As(o.agentOutputStream):void 0,l=Nw(o);try{let{recoveryAssessments:c,permanentRecoveryCandidates:u}=await Fz({candidates:r,excludePatterns:t,triageInputSummary:a,isCompleteRunGroup:!0,output:s,timelineRecorder:l,shared:o});o.logger.info({gitCommitSha:e,healableFailureCount:i.length,permanentRecoveryCandidateCount:u.length},`Identified ${i.length+u.length} run${i.length+u.length===1?"":"s"} to heal from commit.`);let d=[...i,...u];return {...await Lw({...o,healingCandidates:d,triageInputSummary:a,output:s,timelineRecorder:l,source:`commit ${e}`,isCompleteRunGroup:!0,noResultsMessage:`No failed or permanently-healable recovered runs found for commit ${e}.`}),recoveryAssessments:c}}finally{s?.finalize();}}async function $Be({output:e,generator:t,logger:o,serverId:n,dryRun:r,categoryDefinitions:i,healingConfig:a,abortSignal:s}){if(e)return jNe({logger:o,generator:t,sessionId:n,dryRun:r,summaryContext:e.summaryContext,healResults:e.heals,bucketingIterations:e.bucketingIterations,failureMessage:e.failure?.message,triageInputSummary:e.triageInputSummary,categoryDefinitions:i,healingConfig:a,abortSignal:s})}function GBe({resultsDir:e,summary:t}){let o=Cn__default.join(Cn__default.resolve(e),Mt),n=iu.parse(JSON.parse(Un__default.readFileSync(o,"utf-8")));Un__default.writeFileSync(o,JSON.stringify({...n,healRiskSummary:t},null,2));}async function Fz({candidates:e,excludePatterns:t,triageInputSummary:o,isCompleteRunGroup:n,outputDir:r,output:i,timelineRecorder:a,shared:s}){if(!BBe(o,n).withinBudget)return {recoveryAssessments:[],permanentRecoveryCandidates:[]};let l=t?.map(p=>new RegExp(p)),c=[];for(let p of e)if(!(s.skipRecovered||!p.recoveryInput)&&!(s.skipQuarantined&&p.quarantined&&!s.ignoreQuarantine)&&!YBe({run:p,excludeRegexes:l})){if(s.ignoreQuarantine&&p.recoveryInput.quarantined){c.push({...p.recoveryInput,quarantined:false});continue}c.push(p.recoveryInput);}c.length>0&&i?.commitSection("Recovery assessment"),await $d("recovery_assessment");let u;try{u=await ge({name:"heal.recovery_assessment",attributes:{"momentic.recovery_run_count":c.length},fn:()=>$Ne({recoveryRuns:c,orgId:s.orgId,serverId:s.serverId,project:s.project,logger:s.logger,generator:s.generator,apiClient:s.apiClient,outputDir:r,abortSignal:s.healingAbortSignal,output:i,timelineRecorder:a})});}catch(p){if(!s.healingAbortSignal.aborted)throw p;s.logger.info({reason:s.healingAbortSignal.reason},"Stopped recovery assessment at the triage deadline"),u=[];}let d=new Map(c.map(p=>[p.runId,p])),m=u.flatMap(p=>{if(!p.shouldPermanentHeal)return [];let h=d.get(p.runId);return h?[{...h,source:"recovery-assessor",failureReason:p.failureReason,classification:{activeClassification:null}}]:[]});for(let p of m)o.selectedForHealing.push({runId:p.runId,testId:p.testId,testName:p.testName,classification:{activeClassification:null}}),(o.recoveredPromotedRunIds??=[]).push(p.runId);return m.length>0&&i?.commitItems(m.map(p=>`${p.testName} \u2014 queued for permanent healing.`)),{recoveryAssessments:u,permanentRecoveryCandidates:m}}async function Lw({healingCandidates:e,triageInputSummary:t,serverId:o,noResultsMessage:n,outputDir:r,limit:i,project:a,apiClient:s,generator:l,logger:c,orgId:u,apiKey:d,start:m,waitOn:p,waitOnProxy:h,waitOnTimeout:g,alwaysSaveCache:f,noCache:y,regenerateHeal:b,sessionOptions:S,timeoutMinutes:A,parallel:T,resolveGitMetadataForCache:v,resolveGitMetadata:R,source:I,sessionManager:C,dryRun:O,jsonOutput:P,abortController:k,healingAbortSignal:N,prepareCheckoutForHealing:M,healingConfig:L,reclassifyContradictions:G,output:X,timelineRecorder:B,isCompleteRunGroup:K}){if(N.throwIfAborted(),i!==void 0&&e.length>i)return {...Dz({triageInputSummary:t,err:new Error(`Found ${e.length} healing candidate${e.length===1?"":"s"}, which exceeds the configured limit of ${i}.`)}),...Ny(B)};let ee=BBe(t,K);if(!ee.withinBudget)return x.warn(ee.reason??"Skipping AI triage for this run group."),{heals:[],bucketingIterations:[],existingFixes:[],triageInputSummary:{...t,declinedForOutage:DBe(t)},healPatches:[],...Ny(B)};if(e.length===0)return x.info(n),{heals:[],bucketingIterations:[],existingFixes:[],triageInputSummary:t,healPatches:[],...Ny(B)};let z=rt();await $d("resolve_git_cache_metadata");let F=await ge({name:"heal.resolve_git_cache_metadata",fn:()=>P?v():Ho({text:"Resolving git cache context...",screen:z},v)});if(c.info({gitCacheMetadata:F},"Got local git cache metadata"),!P){let ve=ht(z),dt=[`${T} ${T===1?"worker":"workers"}`];A!==void 0&&A>0&&dt.push(`timeout=${A}m`);let Ze=[{label:"source",value:I}];F.gitBranchName&&Ze.push({label:"branch",value:F.gitBranchName});let an=[`Healing ${e.length} ${e.length===1?"test":"tests"}`,...dt].join(ve.separator);x.log(`Momentic CLI v${To}
@@ -4687,7 +4687,7 @@ _Description truncated. See the run group linked below for full details._`,r=mX-
4687
4687
  `);return `${a>0?i.slice(0,a):i}${n}${t}`}var SVt=z.object({title:z.string().describe("Plain text GitHub pull request title. No leading hash, no Markdown."),body:z.string().describe("GitHub pull request body in Markdown. If a template was supplied, every heading from the template must appear verbatim, in the same order, at the same heading level.")});async function TVt({generator:e,logger:t,bodyGuidance:o,titleGuidance:n,bodyData:r,pullRequestTemplate:i,model:a=gVt,sessionId:s}){let l=s??t.bindings().sessionId??randomUUID$1(),c={logger:t,streamType:"pull-request-generation",sessionId:l},u=e.getAzureOpenAIModelFactory(c),d=e.getOpenAIModelFactory({...c,useOpenAIResponsesWebSocket:false}),m=["You write concise GitHub pull request titles and descriptions.","Return a structured object with two fields: `title` (plain text) and `body` (Markdown).","","Template rules:","If a pull request template is supplied in the user message, you MUST use it as the structural skeleton of `body`:"," - Copy every heading from the template verbatim (same text, same `#`/`##` levels, same order)."," - Replace template comments (e.g. `<!-- ... -->`) and unchecked checklist items with content grounded in the supplied body data."," - If a section genuinely cannot be answered from the supplied body data, keep the heading and write a single short line such as `N/A, the supplied data does not cover this.`"," - Do not invent new top-level headings, do not rename the template's headings, and do not merge sections.","If no template is supplied, write a clean body with sensible default headings.","","Body generation:",o,"","Title generation:",n,"","Grounding rules:","Ground every claim in the supplied body data. Do not invent facts, reviewers, screenshots, or outcomes beyond what is supplied."].join(`
4688
4688
  `),p={bodyData:r,pullRequestTemplate:i?{name:i.name,path:i.path,body:i.body}:null},h=await sp({schema:SVt,schemaName:"PullRequest",schemaDescription:"Title and Markdown body for a GitHub pull request.",providerFallback:{logger:t,providers:[{id:"azure",model:u(a)},{id:"openai",model:d(a)}]},system:m,messages:[{role:"user",content:JSON.stringify(p,null,2)}],providerOptions:{openai:{reasoningEffort:"medium",store:false,textVerbosity:"low"},azure:{reasoningEffort:"medium",store:false,textVerbosity:"low"}}});return {title:h.title.trim(),body:h.body.trim()}}async function vVt({apiClient:e,generator:t,logger:o,owner:n,repo:r,bodyGuidance:i,titleGuidance:a,bodyData:s,fallback:l,pullRequestTemplate:c}){let u=c;if(!u)try{u=await e.getGithubPullRequestTemplate(n,r);}catch(d){o.warn({err:d,owner:n,repo:r},"Failed to retrieve GitHub pull request template"),x.warn(`Failed to retrieve GitHub pull request template; continuing without it: ${W(d)}`);}try{let d=await TVt({generator:t,logger:o,bodyGuidance:i,titleGuidance:a,bodyData:s,pullRequestTemplate:u});return {title:d.title||l.title,body:d.body||l.body}}catch(d){return o.warn({err:d,owner:n,repo:r},"Failed to generate pull request title and body"),x.warn(`Failed to generate pull request title and body; falling back to plain summary: ${W(d)}`),l}}async function $z({apiClient:e,generator:t,logger:o,owner:n,repo:r,repoRoot:i,paths:a,draft:s,agentSource:l,baseBranch:c,baseCommitSha:u,expectedHeadSha:d,expectedBaseSha:m,headBranch:p,patchBaseRef:h,coAuthorRange:g,omitBaseCommitCoAuthors:f,requestCommitAuthorsAsReviewers:y,assignCommitAuthorsAsAssignees:b,assignees:S,reviewers:A,teamReviewers:T,fallbackReviewers:v,resultsUrl:R,ciBuild:I,baseDescription:C,bodyGuidance:O,titleGuidance:P,bodyDataFields:k,bodyPrefix:N,fallback:M,pullRequestTemplate:L,titlePrefix:G,preservedMetadata:X}){let B=await kf({absoluteRepoRoot:i,repoRelativePaths:a,baseRef:h});if(!B)return {kind:"no-changes"};let K,ee;if(X)K=X.title,ee=X.body;else {let j=await vVt({apiClient:e,generator:t,logger:o,owner:n,repo:r,bodyGuidance:O,titleGuidance:P,bodyData:JSON.stringify({baseDescription:C,...k,diffPatch:B},null,2),fallback:M,pullRequestTemplate:L}),te=await rUe({apiClient:e,logger:o,agentSource:l,owner:n,repo:r,baseBranch:c,baseCommitSha:u,resultsUrl:R,ciBuild:I});K=fVt(j.title,G),ee=bVt(yVt(j.body,N),te);}let z=await Qye({absoluteRepoRoot:i,repoRelativePaths:a,baseBranch:c,baseCommitSha:u,headBranch:p,coAuthorRange:g,omitBaseCommitCoAuthors:f,requestCommitAuthorsAsReviewers:y,assignCommitAuthorsAsAssignees:b,assignees:S,reviewers:A,teamReviewers:T,fallbackReviewers:v,commitMessage:K,title:K,body:ee,draft:X?.draft??s}),F=await e.createGithubPullRequest(n,r,{...z,expectedHeadSha:d,expectedBaseSha:m});return {kind:"opened",action:F.created?"Created":"Updated",url:F.pullRequestUrl,prNumber:F.pullRequestNumber,commitSha:F.commitSha,headBranch:F.headBranch,authors:F.authors??[],assignees:F.assignees??[],reviewers:F.reviewers}}var lUe="write_file",hX=z.object({path:z.string().min(1)}),iUe="git_diff";var aUe="gpt-5.6-sol",RVt=50,CVt={openai:{reasoningEffort:"low",reasoningSummary:"auto",store:false,textVerbosity:"low"},azure:{reasoningEffort:"low",reasoningSummary:"auto",store:false,textVerbosity:"low"}};async function cUe({repoRoot:e,headBranch:t,oldHeadSha:o,sourceCommitSha:n,checkoutCommitSha:r=n,generator:i,logger:a,abortSignal:s,github:l}){let c=Ai(e,void 0,false),u=[],d,m=async()=>{u.length>0&&await gX({repoRoot:e,files:u}),d&&await c.raw(["read-tree",d]);};try{let p=await qO({git:Ai(e,s,!1),ref:t,github:l,logger:a,abortSignal:s});if(p!==void 0&&p!==o)throw new Error(`Auto-heal branch ${t} advanced from ${o} to ${p} before rebasing.`);await sT(c,o,s),await sT(c,n,s);let h=(await c.revparse(["HEAD"])).trim();if(h!==r&&h!==o)throw new Error(`Cannot rebase auto-heal branch in the checkout because HEAD is ${h}, neither expected checkout ${r} nor repair commit ${o}.`);let g=Ai(e,s,!1),f=(await c.raw(["cat-file","-p",o])).split(`
4689
4689
 
4690
- `,1)[0]?.match(/^parent (\S+)$/m)?.[1];if(!f)throw new ae("The earlier repair commit has no source parent.");await sT(c,f,s);let y=yX(await c.raw(["diff","--name-only","-z",f,o,"--"])),b=y.filter(L=>!Ih(L));if(b.length>0)throw new Error(`Cannot rebase non-Momentic auto-heal paths: ${b.join(", ")}.`);let S=await sUe({git:c,base:f,head:n});if(y.length===0)return [];let A=await dUe({repoRoot:e,paths:y}),T=await Vz({git:c,ref:n,paths:y}),v=new Map(T.map(L=>[L.path,L.content])),R=await Vz({git:c,ref:o,paths:y}),I=new Map(R.map(L=>[L.path,L.content])),C=T;r===o?C=R:r!==n&&(C=await Vz({git:c,ref:r,paths:y}));let O=new Map(C.map(L=>[L.path,L.content])),P=A.filter(L=>L.content!==v.get(L.path)&&L.content!==I.get(L.path)&&L.content!==O.get(L.path)).map(L=>L.path);if(P.length>0)throw new Error(`Cannot rebase auto-heal changes over local edits in previously healed paths: ${P.join(", ")}.`);d=(await c.raw(["write-tree"])).trim(),u=A,await c.raw(["reset",n,"--",...y]),await gX({repoRoot:e,files:T});let k=await _Vt({git:g,repoRoot:e,priorSourceSha:f,sourceCommitSha:n,oldHeadSha:o,generator:i,logger:a,abortSignal:s}),N=(await sUe({git:c,base:n})).filter(L=>y.includes(L)),M=y.filter(L=>S.includes(L)&&!k.has(L));return M.length>0&&(await uUe({repoRoot:e,priorSourceSha:f,sourceCommitSha:n,oldHeadSha:o,reviewPaths:M,conflicted:!1,generator:i,logger:a,abortSignal:s}),await mUe({repoRoot:e,paths:M})),await c.raw(["read-tree",d]),[...new Set([...N,...k,...M])]}catch(p){if(s.aborted)throw p;try{await m();}catch(h){a.error({err:h},"Failed to restore checkout after auto-heal rebasing failed");}throw p}}async function qO(e){return ge({name:"healing.fetch_branch",fn:()=>IVt(e)})}async function IVt({git:e,ref:t,github:o,logger:n,abortSignal:r}){r?.throwIfAborted();try{await e.raw(["fetch","--no-tags","origin",t]),r?.throwIfAborted();let i=(await e.revparse(["FETCH_HEAD"])).trim();return r?.throwIfAborted(),i}catch(i){r?.throwIfAborted(),n.warn({err:i,ref:t},"Could not fetch healing branch from origin");}if(o)try{let i=await o.apiClient.getGithubBranchMetadata(o.owner,o.repo,t.replace(/^refs\/heads\//,""),r);if(r?.throwIfAborted(),i.commit)return i.commit.sha}catch(i){r?.throwIfAborted(),n.warn({err:i,ref:t},"Could not read healing branch through GitHub");}n.warn({ref:t},"Continuing healing with the available checkout");}var WO=class extends ae{constructor(t){super(`Commit '${t}' is not available in this checkout. Healing can continue, but repair delivery needs this commit to preserve earlier repairs. Restore git access and rerun triage to deliver the repairs.`);}};async function sT(e,t,o){o?.throwIfAborted();try{await e.raw(["cat-file","-e",`${t}^{commit}`]),o?.throwIfAborted();}catch{throw o?.throwIfAborted(),new WO(t)}}async function xVt({checkoutDescription:e,declaredPathLabel:t,repoRoot:o,reviewPaths:n,instructions:r,userPrompt:i,extraTools:a,allowDeletion:s,sessionPrefix:l,uninspectedMessage:c,generator:u,logger:d,abortSignal:m}){let p=new Set(n),h=new Set,g={markInspected:v=>h.add(v),requireDeclared:v=>{if(!p.has(v))throw new Error(`Cannot inspect undeclared ${t}: ${v}`);h.add(v);}},f={[Jn]:tool({description:`Read a repository file from the ${e}.`,inputSchema:hX,execute:async({path:v})=>(p.has(v)&&g.markInspected(v),GO.readFile(fX({repoRoot:o,filePath:v}),"utf8").then(R=>({exists:true,content:R})).catch(R=>{if(R.code==="ENOENT")return {exists:false,content:void 0};throw R}))}),[lUe]:tool({description:`Write or delete one declared Momentic file in the ${e}.`,inputSchema:hX.extend({content:z.string().nullable()}),execute:async({path:v,content:R})=>{if(!p.has(v))throw new Error(`Cannot edit undeclared ${t}: ${v}`);return R!==null&&pUe({filePath:v,content:R}),await hUe({repoRoot:o,filePath:v,content:R??void 0}),g.markInspected(v),{written:v}}}),...a(g)},y={logger:d,streamType:"orchestrator",sessionId:`${l}-${Date.now()}`},b=u.getOpenAIModelFactory({...y,useOpenAIResponsesWebSocket:false}),S=u.getAzureOpenAIModelFactory(y);await Jo({providerFallback:{logger:d,providers:[{id:"openai",model:b(aUe)},{id:"azure",model:S(aUe)}]},providerOptions:CVt,abortSignal:m,stopWhen:isStepCount(RVt),instructions:r,messages:[{role:"user",content:i}],tools:f}).text;let T=n.filter(v=>!h.has(v));if(T.length>0)throw new Error(c(T))}async function _Vt({git:e,repoRoot:t,priorSourceSha:o,sourceCommitSha:n,oldHeadSha:r,generator:i,logger:a,abortSignal:s}){let l=(await e.revparse([`${r}^{tree}`])).trim(),c=(await e.raw(["-c","user.name=Momentic Auto-Heal","-c","user.email=autoheal@momentic.ai","commit-tree",l,"-p",o,"-m","Squashed auto-heal repairs"])).trim();try{return await e.raw(["cherry-pick","--no-commit",c]),new Set}catch(u){let d=yX(await e.raw(["diff","--name-only","--diff-filter=U","-z"]));if(d.length===0)throw u;let m=d.filter(p=>!Ih(p));if(m.length>0)throw new Error(`Cannot automatically resolve non-Momentic rebase conflicts: ${m.join(", ")}.`,{cause:u});return await gX({repoRoot:t,files:await Vz({git:e,ref:n,paths:d})}),await uUe({repoRoot:t,priorSourceSha:o,sourceCommitSha:n,oldHeadSha:r,reviewPaths:d,conflicted:true,generator:i,logger:a,abortSignal:s}),await mUe({repoRoot:t,paths:d}),await e.add(d),new Set(d)}}async function uUe({repoRoot:e,priorSourceSha:t,sourceCommitSha:o,oldHeadSha:n,reviewPaths:r,conflicted:i,generator:a,logger:s,abortSignal:l}){return xVt({repoRoot:e,reviewPaths:r,generator:a,logger:s,abortSignal:l,sessionPrefix:"heal-rebase",checkoutDescription:"rebased checkout",declaredPathLabel:"rebase path",allowDeletion:true,extraTools:c=>({[iUe]:tool({description:"Read either the authoritative source-branch change or the old heal PR patch for a declared path.",inputSchema:hX.extend({change:z.enum(["source","old_heal"])}),execute:async({path:u,change:d})=>{c.requireDeclared(u);let m=d==="source"?o:n;return Ai(e).raw(["diff",`${t}..${m}`,"--",u])}})}),instructions:Kt`
4690
+ `,1)[0]?.match(/^parent (\S+)$/m)?.[1];if(!f)throw new ae("The earlier repair commit has no source parent.");await sT(c,f,s);let y=yX(await c.raw(["diff","--name-only","-z",f,o,"--"])),b=y.filter(L=>!Ih(L));if(b.length>0)throw new Error(`Cannot rebase non-Momentic auto-heal paths: ${b.join(", ")}.`);let S=await sUe({git:c,base:f,head:n});if(y.length===0)return [];let A=await dUe({repoRoot:e,paths:y}),T=await Vz({git:c,ref:n,paths:y}),v=new Map(T.map(L=>[L.path,L.content])),R=await Vz({git:c,ref:o,paths:y}),I=new Map(R.map(L=>[L.path,L.content])),C=T;r===o?C=R:r!==n&&(C=await Vz({git:c,ref:r,paths:y}));let O=new Map(C.map(L=>[L.path,L.content])),P=A.filter(L=>L.content!==v.get(L.path)&&L.content!==I.get(L.path)&&L.content!==O.get(L.path)).map(L=>L.path);if(P.length>0)throw new ae(`Cannot rebase auto-heal changes over local edits in previously healed paths: ${P.join(", ")}. Commit or discard them, then rerun healing.`);d=(await c.raw(["write-tree"])).trim(),u=A,await c.raw(["reset",n,"--",...y]),await gX({repoRoot:e,files:T});let k=await _Vt({git:g,repoRoot:e,priorSourceSha:f,sourceCommitSha:n,oldHeadSha:o,generator:i,logger:a,abortSignal:s}),N=(await sUe({git:c,base:n})).filter(L=>y.includes(L)),M=y.filter(L=>S.includes(L)&&!k.has(L));return M.length>0&&(await uUe({repoRoot:e,priorSourceSha:f,sourceCommitSha:n,oldHeadSha:o,reviewPaths:M,conflicted:!1,generator:i,logger:a,abortSignal:s}),await mUe({repoRoot:e,paths:M})),await c.raw(["read-tree",d]),[...new Set([...N,...k,...M])]}catch(p){if(s.aborted)throw p;try{await m();}catch(h){a.error({err:h},"Failed to restore checkout after auto-heal rebasing failed");}throw p}}async function qO(e){return ge({name:"healing.fetch_branch",fn:()=>IVt(e)})}async function IVt({git:e,ref:t,github:o,logger:n,abortSignal:r}){r?.throwIfAborted();try{await e.raw(["fetch","--no-tags","origin",t]),r?.throwIfAborted();let i=(await e.revparse(["FETCH_HEAD"])).trim();return r?.throwIfAborted(),i}catch(i){r?.throwIfAborted(),n.warn({err:i,ref:t},"Could not fetch healing branch from origin");}if(o)try{let i=await o.apiClient.getGithubBranchMetadata(o.owner,o.repo,t.replace(/^refs\/heads\//,""),r);if(r?.throwIfAborted(),i.commit)return i.commit.sha}catch(i){r?.throwIfAborted(),n.warn({err:i,ref:t},"Could not read healing branch through GitHub");}n.warn({ref:t},"Continuing healing with the available checkout");}var WO=class extends ae{constructor(t){super(`Commit '${t}' is not available in this checkout. Healing can continue, but repair delivery needs this commit to preserve earlier repairs. Restore git access and rerun triage to deliver the repairs.`);}};async function sT(e,t,o){o?.throwIfAborted();try{await e.raw(["cat-file","-e",`${t}^{commit}`]),o?.throwIfAborted();}catch{throw o?.throwIfAborted(),new WO(t)}}async function xVt({checkoutDescription:e,declaredPathLabel:t,repoRoot:o,reviewPaths:n,instructions:r,userPrompt:i,extraTools:a,allowDeletion:s,sessionPrefix:l,uninspectedMessage:c,generator:u,logger:d,abortSignal:m}){let p=new Set(n),h=new Set,g={markInspected:v=>h.add(v),requireDeclared:v=>{if(!p.has(v))throw new Error(`Cannot inspect undeclared ${t}: ${v}`);h.add(v);}},f={[Jn]:tool({description:`Read a repository file from the ${e}.`,inputSchema:hX,execute:async({path:v})=>(p.has(v)&&g.markInspected(v),GO.readFile(fX({repoRoot:o,filePath:v}),"utf8").then(R=>({exists:true,content:R})).catch(R=>{if(R.code==="ENOENT")return {exists:false,content:void 0};throw R}))}),[lUe]:tool({description:`Write or delete one declared Momentic file in the ${e}.`,inputSchema:hX.extend({content:z.string().nullable()}),execute:async({path:v,content:R})=>{if(!p.has(v))throw new Error(`Cannot edit undeclared ${t}: ${v}`);return R!==null&&pUe({filePath:v,content:R}),await hUe({repoRoot:o,filePath:v,content:R??void 0}),g.markInspected(v),{written:v}}}),...a(g)},y={logger:d,streamType:"orchestrator",sessionId:`${l}-${Date.now()}`},b=u.getOpenAIModelFactory({...y,useOpenAIResponsesWebSocket:false}),S=u.getAzureOpenAIModelFactory(y);await Jo({providerFallback:{logger:d,providers:[{id:"openai",model:b(aUe)},{id:"azure",model:S(aUe)}]},providerOptions:CVt,abortSignal:m,stopWhen:isStepCount(RVt),instructions:r,messages:[{role:"user",content:i}],tools:f}).text;let T=n.filter(v=>!h.has(v));if(T.length>0)throw new Error(c(T))}async function _Vt({git:e,repoRoot:t,priorSourceSha:o,sourceCommitSha:n,oldHeadSha:r,generator:i,logger:a,abortSignal:s}){let l=(await e.revparse([`${r}^{tree}`])).trim(),c=(await e.raw(["-c","user.name=Momentic Auto-Heal","-c","user.email=autoheal@momentic.ai","commit-tree",l,"-p",o,"-m","Squashed auto-heal repairs"])).trim();try{return await e.raw(["cherry-pick","--no-commit",c]),new Set}catch(u){let d=yX(await e.raw(["diff","--name-only","--diff-filter=U","-z"]));if(d.length===0)throw u;let m=d.filter(p=>!Ih(p));if(m.length>0)throw new Error(`Cannot automatically resolve non-Momentic rebase conflicts: ${m.join(", ")}.`,{cause:u});return await gX({repoRoot:t,files:await Vz({git:e,ref:n,paths:d})}),await uUe({repoRoot:t,priorSourceSha:o,sourceCommitSha:n,oldHeadSha:r,reviewPaths:d,conflicted:true,generator:i,logger:a,abortSignal:s}),await mUe({repoRoot:t,paths:d}),await e.add(d),new Set(d)}}async function uUe({repoRoot:e,priorSourceSha:t,sourceCommitSha:o,oldHeadSha:n,reviewPaths:r,conflicted:i,generator:a,logger:s,abortSignal:l}){return xVt({repoRoot:e,reviewPaths:r,generator:a,logger:s,abortSignal:l,sessionPrefix:"heal-rebase",checkoutDescription:"rebased checkout",declaredPathLabel:"rebase path",allowDeletion:true,extraTools:c=>({[iUe]:tool({description:"Read either the authoritative source-branch change or the old heal PR patch for a declared path.",inputSchema:hX.extend({change:z.enum(["source","old_heal"])}),execute:async({path:u,change:d})=>{c.requireDeclared(u);let m=d==="source"?o:n;return Ai(e).raw(["diff",`${t}..${m}`,"--",u])}})}),instructions:Kt`
4691
4691
  You are reviewing an auto-heal branch rebased onto current source.
4692
4692
 
4693
4693
  The current source/base version is always authoritative and must remain the foundation of every file. The old heal PR is only a stale patch containing possible improvements; it is never an alternative source version. Bias strongly toward skipping its changes. Reapply an old heal only when it is obviously beneficial because the same behavior still exists in current source and the exact improvement clearly remains applicable. If there is any doubt, keep current source and skip the old heal change.
@@ -5031,4 +5031,4 @@ smol-toml/dist/index.js:
5031
5031
  */
5032
5032
  //# sourceMappingURL=out.js.map
5033
5033
  //# sourceMappingURL=cli.js.map
5034
- //# debugId=b07a097b-31c7-5baf-866f-7f2df24b5ea7
5034
+ //# debugId=a3f68874-d6b9-5f3b-b638-b45758964ab2