@mearl/native-host 2.16.4 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +7 -7
  2. package/package.json +6 -6
package/dist/index.js CHANGED
@@ -38,10 +38,10 @@ Verify:
38
38
  mearl get_requests --payload '{"count":1}'
39
39
  `),success2?0:1}var DEFAULT_EXTENSION_ID,__filename,__dirname,ALL_MODES,init_install=__esm({"src/install.ts"(){"use strict";init_nativeHost();DEFAULT_EXTENSION_ID="aoehhjnofngknnjefamjbplchbolghkm",__filename=fileURLToPath2(import.meta.url),__dirname=path17.dirname(__filename),ALL_MODES=["skills","mcp"]}});import net4 from"node:net";import fs18 from"node:fs";import http4 from"node:http";import os10 from"node:os";import path18 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";import{spawn as spawn2}from"node:child_process";import{randomUUID as randomUUID2}from"node:crypto";import{closeSync as closeSync3,existsSync as existsSync4,mkdirSync as mkdirSync2,openSync as openSync3}from"node:fs";import{join as join4}from"node:path";function isAlive(pid){if(!pid||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(error48){return error48.code==="EPERM"}}import{join}from"node:path";import{homedir}from"node:os";import{createHash}from"node:crypto";var DAEMON_HOME=join(homedir(),".mearl");function hashKey(key){return createHash("sha256").update(key).digest("hex").slice(0,16)}function keyedDir(subdir){return join(DAEMON_HOME,subdir)}function keyedConfigFile(subdir,key){return join(keyedDir(subdir),`${hashKey(key)}.json`)}import{closeSync,existsSync,linkSync,openSync,statSync,mkdirSync,readFileSync,writeFileSync,renameSync,rmSync,readdirSync}from"node:fs";import{dirname,join as join2}from"node:path";import{randomUUID}from"node:crypto";var LOCK_WAIT_MS=10,LOCK_TIMEOUT_MS=5e3,OWNER_WRITE_GRACE_MS=1e3,lockWaitBuffer=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));function ensureDir(dir){existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}function pauseForLock(){Atomics.wait(lockWaitBuffer,0,0,LOCK_WAIT_MS)}function readRecordUnlocked(file2){try{if(!existsSync(file2))return null;let parsed=JSON.parse(readFileSync(file2,"utf-8"));return parsed&&typeof parsed.pid=="number"?parsed:null}catch{return null}}function removeRecordUnlocked(file2){rmSync(file2,{force:!0})}function writeRecordUnlocked(file2,record2){let tmp=`${file2}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(tmp,JSON.stringify(record2),{mode:384}),renameSync(tmp,file2)}catch(error48){try{rmSync(tmp,{force:!0})}catch{}throw error48}}function removeStaleLock(lockDir){let ownerFile=join2(lockDir,"owner.json"),owner=readRecordUnlocked(ownerFile);if(owner){if(isAlive(owner.pid))return!1}else try{if(Date.now()-statSync(lockDir).mtimeMs<OWNER_WRITE_GRACE_MS)return!1}catch{return!0}try{return rmSync(lockDir,{recursive:!0,force:!0}),!0}catch{return!1}}function withRecordLock(file2,operation){ensureDir(dirname(file2));let lockDir=`${file2}.registry.lock`,ownerFile=join2(lockDir,"owner.json"),token=randomUUID(),deadline=Date.now()+LOCK_TIMEOUT_MS;for(;;){try{mkdirSync(lockDir,{mode:448})}catch(error48){if(error48.code!=="EEXIST")throw error48;if(!removeStaleLock(lockDir)){if(Date.now()>=deadline)throw new Error(`Timed out waiting for registry lock: ${file2}`,{cause:error48});pauseForLock()}continue}let ownerFd=null;try{ownerFd=openSync(ownerFile,"wx",384),writeFileSync(ownerFd,JSON.stringify({pid:process.pid,token}))}catch(error48){if(ownerFd!==null&&closeSync(ownerFd),ownerFd=null,error48.code==="EEXIST"){if(Date.now()>=deadline)throw new Error(`Timed out acquiring registry lock: ${file2}`,{cause:error48});pauseForLock();continue}throw error48}finally{ownerFd!==null&&closeSync(ownerFd)}try{return operation()}finally{readRecordUnlocked(ownerFile)?.token===token&&rmSync(lockDir,{recursive:!0,force:!0})}}}function writeRecord(file2,record2){withRecordLock(file2,()=>writeRecordUnlocked(file2,record2))}function claimRecord(file2,record2){return withRecordLock(file2,()=>{let candidate=`${file2}.${process.pid}.${randomUUID()}.claim`;try{return writeFileSync(candidate,JSON.stringify(record2),{mode:384}),linkSync(candidate,file2),!0}catch(error48){if(error48.code==="EEXIST")return!1;throw error48}finally{rmSync(candidate,{force:!0})}})}function readRecord(file2){return readRecordUnlocked(file2)}function removeRecord(file2){try{withRecordLock(file2,()=>removeRecordUnlocked(file2))}catch{}}function removeRecordIfPid(file2,pid){try{return withRecordLock(file2,()=>readRecordUnlocked(file2)?.pid!==pid?!1:(removeRecordUnlocked(file2),!0))}catch{return!1}}function writeRecordIfPid(file2,pid,record2){return withRecordLock(file2,()=>readRecordUnlocked(file2)?.pid!==pid?!1:(writeRecordUnlocked(file2,record2),!0))}function removeInvalidRecord(file2){try{return withRecordLock(file2,()=>!existsSync(file2)||readRecordUnlocked(file2)?!1:(removeRecordUnlocked(file2),!0))}catch{return!1}}function listRecordFiles(dir){try{return readdirSync(dir).filter(name=>name.endsWith(".json")).map(name=>join2(dir,name))}catch{return[]}}function readLiveRecords(dir){let out=[];for(let file2 of listRecordFiles(dir)){let rec=readRecord(file2);rec&&isAlive(rec.pid)?out.push(rec):rec?removeRecordIfPid(file2,rec.pid):removeInvalidRecord(file2)}return out}import{existsSync as existsSync2,statSync as statSync2,renameSync as renameSync2,readFileSync as readFileSync2}from"node:fs";var DEFAULT_MAX_LOG_BYTES=5*1024*1024;function rotateLogIfNeeded(logFile,maxBytes=DEFAULT_MAX_LOG_BYTES){try{if(!existsSync2(logFile)||statSync2(logFile).size<maxBytes)return;renameSync2(logFile,`${logFile}.1`)}catch{}}import{spawn}from"node:child_process";import{closeSync as closeSync2,openSync as openSync2}from"node:fs";import{dirname as dirname2}from"node:path";import{existsSync as existsSync3,readFileSync as readFileSync3,renameSync as renameSync3,rmSync as rmSync2,statSync as statSync3,writeFileSync as writeFileSync2}from"node:fs";import{isAbsolute,join as join3,relative,resolve,sep}from"node:path";var PROVIDER_ACTIONS=["tab_checkpoint","capture_checkpoint","get_requests","get_logs","get_events","set_mock","get_mocks","set_rule","get_rules","send_request","send_mtop_request","browser_release","page_screenshot","page_selected_element","tab_open","tab_close","tab_list","page_click","page_drag","page_type","page_scroll","page_hover","page_eval","page_snapshot","page_press","page_wait","page_navigate","page_upload","page_frames","set_device_emulation","set_app_profile","set_timezone","get_cookie","set_cookie","request_domain_permission","run_actions"],providerActionSet=new Set(PROVIDER_ACTIONS);function isProviderAction(value){return typeof value=="string"&&providerActionSet.has(value)}var LIFECYCLE_OPERATIONS=new Set(["start","close","detach","deleteData","access","syncCookies"]);function isJsonValue(value,depth=0){return depth>32?!1:value===null||["string","boolean"].includes(typeof value)?!0:typeof value=="number"?Number.isFinite(value):Array.isArray(value)?value.every(item=>isJsonValue(item,depth+1)):typeof value=="object"&&Object.values(value).every(item=>isJsonValue(item,depth+1))}function isOptionalString(value){return value===void 0||typeof value=="string"}function isOptionalFiniteNumber(value){return value===void 0||typeof value=="number"&&Number.isFinite(value)}function isOptionalCount(value){return value===void 0||Number.isInteger(value)&&Number(value)>=0}function isProviderInputSchema(value,depth=0){if(!value||typeof value!="object"||Array.isArray(value)||depth>32)return!1;let schema=value;if(!isOptionalString(schema.title)||!isOptionalString(schema.description)||schema.component!==void 0&&!["cookie-sync","switch"].includes(String(schema.component))||schema.default!==void 0&&!isJsonValue(schema.default)||schema.formDefault!==void 0&&!isJsonValue(schema.formDefault)||schema.formHidden!==void 0&&typeof schema.formHidden!="boolean"||schema.formWidth!==void 0&&!["half","full"].includes(String(schema.formWidth))||schema.formHideOptional!==void 0&&typeof schema.formHideOptional!="boolean"||schema.formVisibleWhen!==void 0&&(!schema.formVisibleWhen||typeof schema.formVisibleWhen!="object"||Array.isArray(schema.formVisibleWhen)||typeof schema.formVisibleWhen.field!="string"||!schema.formVisibleWhen.field||typeof schema.formVisibleWhen.empty!="boolean"))return!1;if(schema.type==="string"){let validPattern=!0;if(schema.pattern!==void 0)try{new RegExp(String(schema.pattern))}catch{validPattern=!1}if(!((schema.enum===void 0||Array.isArray(schema.enum)&&schema.enum.every(item=>typeof item=="string"))&&(schema.secret===void 0||typeof schema.secret=="boolean")&&isOptionalCount(schema.minLength)&&isOptionalCount(schema.maxLength)&&(schema.minLength===void 0||schema.maxLength===void 0||Number(schema.minLength)<=Number(schema.maxLength))&&isOptionalString(schema.pattern)&&validPattern&&isOptionalString(schema.placeholder)))return!1}else if(schema.type==="number"){if(!((schema.integer===void 0||typeof schema.integer=="boolean")&&isOptionalFiniteNumber(schema.minimum)&&isOptionalFiniteNumber(schema.maximum)&&(schema.minimum===void 0||schema.maximum===void 0||Number(schema.minimum)<=Number(schema.maximum))))return!1}else if(schema.type!=="boolean")if(schema.type==="array"){if(!isProviderInputSchema(schema.items,depth+1)||!isOptionalCount(schema.minItems)||!isOptionalCount(schema.maxItems)||schema.minItems!==void 0&&schema.maxItems!==void 0&&Number(schema.minItems)>Number(schema.maxItems))return!1}else{if(schema.type!=="object"||!schema.properties||typeof schema.properties!="object"||Array.isArray(schema.properties)||schema.additionalProperties!==void 0&&typeof schema.additionalProperties!="boolean")return!1;let properties=schema.properties;if(!Object.values(properties).every(item=>isProviderInputSchema(item,depth+1))||Object.values(properties).some(item=>{let condition=item.formVisibleWhen;return condition!==void 0&&!(String(condition.field)in properties)})||schema.not!==void 0&&(!isProviderInputSchema(schema.not,depth+1)||schema.not.type!=="object")||schema.oneOf!==void 0&&(!Array.isArray(schema.oneOf)||schema.oneOf.length===0||schema.oneOf.some(branch=>!isProviderInputSchema(branch,depth+1)||branch.type!=="object"))||schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(item=>typeof item!="string"||!(item in properties))||new Set(schema.required).size!==schema.required.length))return!1}if(schema.component==="cookie-sync"&&schema.type!=="object"||schema.component==="switch"&&schema.type!=="boolean")return!1;if(schema.default!==void 0)try{validateSchemaValue(value,schema.default,"default")}catch{return!1}if(schema.formDefault!==void 0)try{validateSchemaValue(value,schema.formDefault,"formDefault")}catch{return!1}return!0}function fail(path19,message){throw new Error(`${path19} ${message}`)}function validateSchemaValue(schema,value,path19){if(schema.type==="string"){typeof value!="string"&&fail(path19,"must be a string"),schema.enum&&!schema.enum.includes(value)&&fail(path19,"has an unsupported value"),schema.minLength!==void 0&&value.length<schema.minLength&&fail(path19,`must contain at least ${schema.minLength} characters`),schema.maxLength!==void 0&&value.length>schema.maxLength&&fail(path19,`must contain at most ${schema.maxLength} characters`),schema.pattern!==void 0&&!new RegExp(schema.pattern).test(value)&&fail(path19,"has an invalid format");return}if(schema.type==="number"){(typeof value!="number"||!Number.isFinite(value))&&fail(path19,"must be a number"),schema.integer&&!Number.isInteger(value)&&fail(path19,"must be an integer"),schema.minimum!==void 0&&value<schema.minimum&&fail(path19,`must be at least ${schema.minimum}`),schema.maximum!==void 0&&value>schema.maximum&&fail(path19,`must be at most ${schema.maximum}`);return}if(schema.type==="boolean"){typeof value!="boolean"&&fail(path19,"must be a boolean");return}if(schema.type==="array"){Array.isArray(value)||fail(path19,"must be an array"),schema.minItems!==void 0&&value.length<schema.minItems&&fail(path19,`must contain at least ${schema.minItems} items`),schema.maxItems!==void 0&&value.length>schema.maxItems&&fail(path19,`must contain at most ${schema.maxItems} items`),value.forEach((item,index)=>validateSchemaValue(schema.items,item,`${path19}[${index}]`));return}validateObject(schema,value,path19)}function validateObject(schema,value,path19){(!value||typeof value!="object"||Array.isArray(value))&&fail(path19,"must be an object");let input=value;for(let key of schema.required??[])input[key]===void 0&&fail(`${path19}.${key}`,"is required");if(schema.not){let matches=!1;try{validateObject(schema.not,input,path19),matches=!0}catch{}matches&&fail(path19,"matches a forbidden field combination")}if(schema.oneOf&&schema.oneOf.filter(branch=>{try{return validateObject(branch,input,path19),!0}catch{return!1}}).length!==1&&fail(path19,"must match exactly one launch form"),schema.additionalProperties!==!0)for(let key of Object.keys(input))schema.properties[key]||fail(`${path19}.${key}`,"is not supported");for(let[key,item]of Object.entries(input)){let property=schema.properties[key];property&&validateSchemaValue(property,item,`${path19}.${key}`)}}function validateProviderInput(schema,value){validateObject(schema,value,"options")}function validateProviderBrowser(browser){if(!browser||typeof browser!="object")throw new Error("Provider returned no browser");if(typeof browser.browserId!="string"||!browser.browserId.trim())throw new Error("Provider browserId is required");if(typeof browser.name!="string"||!browser.name.trim())throw new Error(`Provider browser ${browser.browserId} needs a name`);if(!["connected","pairing","running_disconnected","stopped"].includes(browser.status))throw new Error(`Provider browser ${browser.browserId} has an invalid status`);if(!["ephemeral","persistent"].includes(browser.persistence))throw new Error(`Provider browser ${browser.browserId} has invalid persistence`);if(browser.ownership!==void 0&&!["owned","attached"].includes(browser.ownership))throw new Error(`Provider browser ${browser.browserId} has invalid ownership`);if(!browser.control||!["provider","host","none"].includes(browser.control.kind))throw new Error(`Provider browser ${browser.browserId} has invalid control`);if(!Array.isArray(browser.operations)||new Set(browser.operations).size!==browser.operations.length||browser.operations.some(operation=>!LIFECYCLE_OPERATIONS.has(operation)))throw new Error(`Provider browser ${browser.browserId} has invalid lifecycle operations`);if(browser.status==="pairing"){if(browser.pairing?.kind!=="qr"||typeof browser.pairing.url!="string"||!browser.pairing.url.trim())throw new Error(`Pairing browser ${browser.browserId} needs a pairing URL`)}else if(browser.pairing)throw new Error(`Pairing metadata requires a pairing state: ${browser.browserId}`);if(browser.pairing&&(!isOptionalString(browser.pairing.code)||!isOptionalString(browser.pairing.label)))throw new Error(`Provider browser ${browser.browserId} has invalid pairing metadata`);if(browser.lastFocusedAt!==void 0&&(!Number.isFinite(browser.lastFocusedAt)||browser.lastFocusedAt<0))throw new Error(`Provider browser ${browser.browserId} has an invalid lastFocusedAt`);if(browser.status==="stopped"&&browser.control.kind!=="none")throw new Error(`Stopped Provider browser ${browser.browserId} cannot expose live control`);if(browser.status==="connected"&&browser.control.kind==="none")throw new Error(`Connected Provider browser ${browser.browserId} must expose control`);let capabilities=browser.control.kind==="provider"||browser.control.kind==="host"?browser.control.capabilities:void 0;if(browser.control.kind==="provider"||capabilities){if(!Array.isArray(capabilities?.actions))throw new Error(`Provider browser ${browser.browserId} needs action capabilities`);if(capabilities.actions.some(action=>!isProviderAction(action))||new Set(capabilities.actions).size!==capabilities.actions.length)throw new Error(`Provider browser ${browser.browserId} has invalid action capabilities`);if(!["native","reconstructed","none"].includes(capabilities.screenshot))throw new Error(`Provider browser ${browser.browserId} has invalid screenshot capabilities`);if(capabilities.actions.includes("page_screenshot")===(capabilities.screenshot==="none"))throw new Error(`Provider browser ${browser.browserId} has inconsistent screenshot capabilities`)}if(browser.control.kind==="host"&&(!["extension","cdp"].includes(browser.control.transport)||typeof browser.control.browserId!="string"||!browser.control.browserId.trim()))throw new Error(`Provider browser ${browser.browserId} has invalid host control`);if(browser.references!==void 0&&(!Array.isArray(browser.references)||browser.references.some(reference=>!reference||typeof reference.kind!="string"||!reference.kind.trim()||typeof reference.id!="string"||!reference.id.trim()||!isOptionalString(reference.label))||new Set(browser.references.map(reference=>`${reference.kind}:${reference.id}`)).size!==browser.references.length))throw new Error(`Provider browser ${browser.browserId} has invalid references`);if(browser.details!==void 0&&(!browser.details||typeof browser.details!="object"||Array.isArray(browser.details)||!isJsonValue(browser.details)))throw new Error(`Provider browser ${browser.browserId} has invalid details`);if(browser.details){let details=browser.details,strings=value=>Array.isArray(value)&&value.every(item=>typeof item=="string");if(details.headless!==void 0&&typeof details.headless!="boolean"||details.createdAt!==void 0&&(typeof details.createdAt!="string"||!Number.isFinite(Date.parse(details.createdAt)))||details.cdpPort!==void 0&&(!Number.isInteger(details.cdpPort)||details.cdpPort<1||details.cdpPort>65535)||details.copiedCookies!==void 0&&(!details.copiedCookies||!strings(details.copiedCookies.domains)||!Number.isInteger(details.copiedCookies.count)||details.copiedCookies.count<0))throw new Error(`Provider browser ${browser.browserId} has invalid common details`)}}function validateDefinition(definition){let{providerId,name,version:version2,protocolVersion}=definition.descriptor;if(!providerId?.trim())throw new Error("providerId is required");if(!name?.trim())throw new Error("provider name is required");if(!version2?.trim())throw new Error("provider version is required");if(protocolVersion!==void 0&&protocolVersion!==2)throw new Error(`Unsupported provider protocol ${protocolVersion}; expected ${2}`);if(!definition.browserType.name?.trim())throw new Error("provider browser type name is required");if(!isProviderInputSchema(definition.browserType.inputSchema)||definition.browserType.inputSchema.type!=="object")throw new Error("Provider input schema is invalid");if(definition.browserType.documentationUrl!==void 0&&(typeof definition.browserType.documentationUrl!="string"||!/^https?:\/\//.test(definition.browserType.documentationUrl)))throw new Error("Provider documentation URL must use HTTP(S)");let configuration=definition.browserType.configuration;if(configuration&&(!isProviderInputSchema(configuration.inputSchema)||configuration.inputSchema.type!=="object"))throw new Error("Provider configuration schema is invalid")}function createProviderRuntime(definition){validateDefinition(definition);let publishedBrowsers=[],validateRuntimeBrowser=browser=>{validateProviderBrowser(browser);let implementations={start:definition.start,detach:definition.detach,access:definition.getAccess,syncCookies:definition.syncCookies};for(let[operation,implementation]of Object.entries(implementations))if(browser.operations.includes(operation)&&!implementation)throw new Error(`Provider browser ${browser.browserId} advertises ${operation} without implementing it`)},listBrowsers=async(context={})=>{let browsers=definition.listBrowsers?await definition.listBrowsers(context):publishedBrowsers,seen=new Set;for(let browser of browsers){if(validateRuntimeBrowser(browser),seen.has(browser.browserId))throw new Error(`Duplicate provider browserId: ${browser.browserId}`);seen.add(browser.browserId)}return browsers},requireBrowser=async(browserId,operation,context)=>{let browser=(await listBrowsers(context)).find(item=>item.browserId===browserId);if(!browser)throw new Error(`Provider browser not found: ${browserId}`);if(!browser.operations.includes(operation))throw new Error(`Provider browser ${browserId} does not support ${operation}`);return browser};return{definition,listBrowsers,updateBrowsers(browsers){if(browsers.forEach(validateRuntimeBrowser),new Set(browsers.map(browser=>browser.browserId)).size!==browsers.length)throw new Error("Provider browser ids must be unique");publishedBrowsers=[...browsers]},async launch(options,context={}){validateProviderInput(definition.browserType.inputSchema,options);let browser=await definition.launch(options,context);return validateRuntimeBrowser(browser),browser},async start(request,context={}){if(await requireBrowser(request.browserId,"start",context),!definition.start)throw new Error("Provider does not implement start");let browser=await definition.start(request,context);return validateRuntimeBrowser(browser),browser},async close(request,context={}){return await requireBrowser(request.browserId,request.deleteData?"deleteData":"close",context),definition.close(request,context)},async detach(request,context={}){if(await requireBrowser(request.browserId,"detach",context),!definition.detach)throw new Error("Provider does not implement detach");return definition.detach(request,context)},async syncCookies(request,context={}){if(await requireBrowser(request.browserId,"syncCookies",context),!definition.syncCookies)throw new Error("Provider does not implement cookie sync");if(!request.scope||typeof request.scope!="object"||Array.isArray(request.scope)||!isJsonValue(request.scope))throw new Error("Cookie sync scope must be a JSON object");return definition.syncCookies(request,context)},async getAccess(request,context={}){if(await requireBrowser(request.browserId,"access",context),!definition.getAccess)throw new Error("Provider does not expose browser access");let access=await definition.getAccess(request,context);if(!access||typeof access.kind!="string"||!access.kind.trim()||typeof access.url!="string")throw new Error("Provider returned an invalid browser access result");let url2=new URL(access.url);if(!["http:","https:"].includes(url2.protocol)||access.sensitive!==!0)throw new Error("Provider returned an invalid browser access result");return{...access,url:url2.toString()}},async configure(options,context={}){let configuration=definition.browserType.configuration;if(!configuration||!definition.configure)throw new Error("Provider does not support configuration");return validateProviderInput(configuration.inputSchema,options),definition.configure(options,context)},async invokeAction(actionContext){let browser=(await listBrowsers({controlSource:actionContext.controlSource})).find(item=>item.browserId===actionContext.browserId);if(!browser)throw new Error(`Provider browser not found: ${actionContext.browserId}`);if(browser.status!=="connected")throw new Error(`Provider browser ${actionContext.browserId} is not connected`);if(browser.control.kind!=="provider")throw new Error(`Provider browser ${actionContext.browserId} uses host control`);if(!browser.control.capabilities.actions.includes(actionContext.action))throw new Error(`Provider browser ${actionContext.browserId} does not support ${actionContext.action}`);if(!definition.handleAction)throw new Error("Provider does not implement browser actions");return definition.handleAction(actionContext)}}}var INSTALLED_PROVIDERS_SUBDIR="providers/installed",LIVE_PROVIDERS_SUBDIR="providers/live",STARTING_PROVIDERS_SUBDIR="providers/starting";var PROVIDER_START_TOKEN_ENV="MEARL_PROVIDER_START_TOKEN",RESERVED_PROVIDER_IDS=new Set(["local"]);function providerBrowserKey(providerId,browserId){let redundantPrefix=`managed:${providerId}:`,scopedBrowserId=browserId.toLowerCase().startsWith(redundantPrefix.toLowerCase())?browserId.slice(redundantPrefix.length):browserId,encodedBrowserId=encodeURIComponent(scopedBrowserId).replace(/%3A/gi,":");return`provider:${encodeURIComponent(providerId)}:${encodedBrowserId}`}function liveProviderFile(providerId){return keyedConfigFile(LIVE_PROVIDERS_SUBDIR,providerId)}function startingProviderFile(providerId){return keyedConfigFile(STARTING_PROVIDERS_SUBDIR,providerId)}function claimProviderStart(providerId,token,pid=process.pid){let file2=startingProviderFile(providerId),existing=readRecord(file2);return existing&&isAlive(existing.pid)?existing.token===token:(existing?removeRecordIfPid(file2,existing.pid):removeInvalidRecord(file2),claimRecord(file2,{pid,providerId,token,startedAt:new Date().toISOString()}))}function readProviderStart(providerId){let record2=readRecord(startingProviderFile(providerId));return record2&&isAlive(record2.pid)?record2:null}function transferProviderStart(providerId,token,pid){let file2=startingProviderFile(providerId),record2=readRecord(file2);return!record2||record2.token!==token?!1:writeRecordIfPid(file2,record2.pid,{...record2,pid})}function releaseProviderStart(providerId,token){let file2=startingProviderFile(providerId),record2=readRecord(file2);return record2?.token===token?removeRecordIfPid(file2,record2.pid):!1}function validateInstalledProviderManifest(manifest){if(!manifest||typeof manifest.providerId!="string"||!manifest.providerId.trim()||typeof manifest.name!="string"||!manifest.name.trim()||typeof manifest.version!="string"||!manifest.version.trim())return"manifest is incomplete";if(manifest.protocolVersion!==2)return`protocol ${manifest.protocolVersion} is unsupported`;if(RESERVED_PROVIDER_IDS.has(manifest.providerId))return`providerId ${manifest.providerId} is reserved for a built-in Provider`;if(!isProviderBrowserType(manifest.browserType))return"browserType is invalid";if(typeof manifest.packageName!="string"||!manifest.packageName.trim())return"packageName is required";if(typeof manifest.packageRoot!="string"||!isAbsolute(manifest.packageRoot))return"packageRoot must be an absolute path";if(typeof manifest.entryPath!="string"||!isAbsolute(manifest.entryPath))return"entryPath must be an absolute path";let entryRelative=relative(manifest.packageRoot,manifest.entryPath);return entryRelative===""||isAbsolute(entryRelative)||entryRelative===".."||entryRelative.startsWith(`..${sep}`)?"entryPath must be a file inside packageRoot":isFile(manifest.entryPath)?null:"entryPath does not exist or is not a file"}function isFile(filePath){try{return statSync3(filePath).isFile()}catch{return!1}}function isProviderBrowserType(value){if(!value||typeof value!="object")return!1;let browserType=value;return typeof browserType.name!="string"||!browserType.name.trim()||browserType.documentationUrl!==void 0&&(typeof browserType.documentationUrl!="string"||!/^https?:\/\//.test(browserType.documentationUrl))||browserType.help!==void 0&&(!Array.isArray(browserType.help)||browserType.help.some(item=>typeof item!="string"||!item.trim()))||!isProviderObjectSchema(browserType.inputSchema)?!1:browserType.configuration===void 0||!!browserType.configuration&&typeof browserType.configuration=="object"&&isProviderObjectSchema(browserType.configuration.inputSchema)}function isProviderObjectSchema(value){return isProviderInputSchema(value)&&value.type==="object"}function listInstalledProviders(){let manifests=[];for(let file2 of listRecordFiles(keyedDir(INSTALLED_PROVIDERS_SUBDIR)))try{let parsed=JSON.parse(readFileSync3(file2,"utf8"));parsed&&typeof parsed.providerId=="string"&&typeof parsed.packageName=="string"&&manifests.push(parsed)}catch{}return manifests.sort((a,b)=>a.providerId.localeCompare(b.providerId))}function readLiveProvider(providerId){let record2=readRecord(liveProviderFile(providerId));return record2&&isAlive(record2.pid)?record2:null}function listLiveProviders(){return readLiveRecords(keyedDir(LIVE_PROVIDERS_SUBDIR))}var PROVIDER_LOGS_SUBDIR="providers/logs";function providerLogFile(providerId){let hash2=hashKey(providerId);return join4(keyedDir(PROVIDER_LOGS_SUBDIR),`${hash2}.log`)}function liveProviderIds(){return new Set(listLiveProviders().map(record2=>record2.providerId))}function delay(ms){return new Promise(resolve2=>setTimeout(resolve2,ms))}async function spawnProvider(manifest,logFile,startToken){mkdirSync2(keyedDir(PROVIDER_LOGS_SUBDIR),{recursive:!0,mode:448}),rotateLogIfNeeded(logFile);let output=openSync3(logFile,"a");try{return await new Promise((resolve2,reject)=>{let child=spawn2(process.execPath,[manifest.entryPath],{cwd:manifest.packageRoot,env:{...process.env,[PROVIDER_START_TOKEN_ENV]:startToken},detached:!0,stdio:["ignore",output,output],windowsHide:!0});child.once("error",reject),child.once("spawn",()=>{child.removeAllListeners("error"),child.on("error",()=>{}),child.unref(),child.pid?resolve2(child.pid):reject(new Error("spawned process has no pid"))})})}finally{closeSync3(output)}}async function ensureInstalledProvidersRunning(){let warnings=[],installed=listInstalledProviders(),live=liveProviderIds(),starting=new Map;for(let manifest of installed){if(live.has(manifest.providerId))continue;let invalid=validateInstalledProviderManifest(manifest);if(invalid){warnings.push(`provider ${manifest.providerId||"(unknown)"}: ${invalid}`);continue}let startToken=randomUUID2();if(!claimProviderStart(manifest.providerId,startToken)){if(readLiveProvider(manifest.providerId))continue;readProviderStart(manifest.providerId)?starting.set(manifest.providerId,null):warnings.push(`provider ${manifest.providerId}: failed to acquire startup ownership`);continue}if(readLiveProvider(manifest.providerId)){releaseProviderStart(manifest.providerId,startToken);continue}let logFile=providerLogFile(manifest.providerId);try{let childPid=await spawnProvider(manifest,logFile,startToken);transferProviderStart(manifest.providerId,startToken,childPid),starting.set(manifest.providerId,startToken)}catch(error48){releaseProviderStart(manifest.providerId,startToken),warnings.push(`provider ${manifest.providerId}: ${error48 instanceof Error?error48.message:String(error48)}`)}}if(starting.size===0)return warnings;let deadline=Date.now()+2e3,remaining=[...starting.keys()];for(;remaining.length>0&&Date.now()<deadline;){await delay(100);let current=liveProviderIds();remaining=remaining.filter(providerId=>!current.has(providerId))}for(let[providerId,token]of starting)!remaining.includes(providerId)&&token&&releaseProviderStart(providerId,token);for(let providerId of remaining){let logFile=providerLogFile(providerId);warnings.push(`provider ${providerId}: did not become ready within 2s${existsSync4(logFile)?`; see ${logFile}`:""}`)}return await delay(100),warnings}import{StringDecoder}from"node:string_decoder";var Utf8LineBuffer=class{constructor(maxBufferBytes){this.maxBufferBytes=maxBufferBytes}buffer="";decoder=new StringDecoder("utf8");push(chunk){if(this.buffer+=this.decoder.write(chunk),Buffer.byteLength(this.buffer,"utf8")>this.maxBufferBytes)return this.buffer="",{lines:[],overflow:!0};let lines=[],newlineIndex;for(;(newlineIndex=this.buffer.indexOf(`
40
40
  `))!==-1;)lines.push(this.buffer.slice(0,newlineIndex)),this.buffer=this.buffer.slice(newlineIndex+1);return{lines,overflow:!1}}};import http2 from"node:http";import WebSocket from"ws";var CdpChildSession=class{constructor(parent,sessionId){this.parent=parent;this.sessionId=sessionId}sendCommand(method,params,timeoutMs=3e4){return this.parent.sendCommandInSession(this.sessionId,method,params,timeoutMs)}on(method,callback){return this.parent.onSession(this.sessionId,method,callback)}createChildSession(sessionId){return this.parent.createChildSession(sessionId)}get closed(){return this.parent.closed}close(){}},CdpClient=class _CdpClient{constructor(socket){this.socket=socket;socket.on("message",data=>this.consumeMessage(data)),socket.on("close",()=>this.handleClosed()),socket.on("error",()=>this.handleClosed())}nextId=1;pending=new Map;eventHandlers=new Map;sessionEventHandlers=new Map;_closed=!1;static connect(wsUrl){return new Promise((resolve2,reject)=>{let url2;try{url2=new URL(wsUrl)}catch{reject(new Error("Invalid CDP WebSocket URL"));return}if(url2.protocol!=="ws:"&&url2.protocol!=="wss:"){reject(new Error(`Unsupported CDP WebSocket protocol: ${url2.protocol}`));return}let socket=new WebSocket(url2,{handshakeTimeout:5e3,maxPayload:64*1024*1024,perMessageDeflate:!1}),settled=!1,fail2=error48=>{settled||(settled=!0,socket.terminate(),reject(error48))};socket.once("open",()=>{settled||(settled=!0,resolve2(new _CdpClient(socket)))}),socket.once("error",fail2),socket.once("unexpected-response",(_request,response)=>{response.resume(),fail2(new Error(`CDP WebSocket upgrade failed with status ${response.statusCode??0}`))})})}createChildSession(sessionId){return new CdpChildSession(this,sessionId)}sendCommandInSession(sessionId,method,params,timeoutMs=3e4){return this.sendRequest(method,params,timeoutMs,sessionId)}onSession(sessionId,method,callback){this.sessionEventHandlers.has(sessionId)||this.sessionEventHandlers.set(sessionId,new Map);let sessionMap=this.sessionEventHandlers.get(sessionId);return sessionMap.has(method)||sessionMap.set(method,new Set),sessionMap.get(method).add(callback),()=>sessionMap.get(method)?.delete(callback)}sendCommand(method,params,timeoutMs=3e4){return this.sendRequest(method,params,timeoutMs)}on(method,callback){return this.eventHandlers.has(method)||this.eventHandlers.set(method,new Set),this.eventHandlers.get(method).add(callback),()=>this.eventHandlers.get(method)?.delete(callback)}close(){this._closed||(this._closed=!0,this.socket.terminate(),this.rejectPending("CDP connection closed"))}get closed(){return this._closed}sendRequest(method,params,timeoutMs,sessionId){return new Promise((resolve2,reject)=>{if(this._closed||this.socket.readyState!==WebSocket.OPEN){reject(new Error("CDP client is closed"));return}let id=this.nextId++,timer=setTimeout(()=>{this.pending.delete(id),reject(new Error(`CDP command timeout: ${method}`))},timeoutMs);this.pending.set(id,{resolve:resolve2,reject,timer,sessionId}),this.socket.send(JSON.stringify({id,method,params:params??{},...sessionId?{sessionId}:{}}),error48=>{if(!error48)return;let pending=this.pending.get(id);pending&&(clearTimeout(pending.timer),this.pending.delete(id),pending.reject(error48))})})}consumeMessage(data){try{let text=Array.isArray(data)?Buffer.concat(data).toString("utf8"):Buffer.isBuffer(data)?data.toString("utf8"):Buffer.from(data).toString("utf8");this.handleMessage(JSON.parse(text))}catch{}}handleMessage(msg){if(msg.id!==void 0){let pending=this.pending.get(msg.id);if(!pending)return;clearTimeout(pending.timer),this.pending.delete(msg.id),msg.error?pending.reject(new Error(msg.error.message??JSON.stringify(msg.error))):pending.resolve(msg.result??{});return}if(!msg.method)return;let handlers=msg.sessionId?this.sessionEventHandlers.get(msg.sessionId)?.get(msg.method):this.eventHandlers.get(msg.method);if(handlers)for(let callback of handlers)try{callback(msg.params)}catch{}}handleClosed(){this._closed||(this._closed=!0,this.rejectPending("CDP connection closed"))}rejectPending(message){for(let[id,pending]of this.pending)clearTimeout(pending.timer),pending.reject(new Error(message)),this.pending.delete(id)}};import{TextDecoder as TextDecoder2}from"node:util";function md5(input){function rotateLeft(v,s){return v<<s|v>>>32-s}function addUnsigned(x,y){let lsw=(x&65535)+(y&65535);return(x>>16)+(y>>16)+(lsw>>16)<<16|lsw&65535}function cmn(q,a2,b2,x,s,t){return addUnsigned(rotateLeft(addUnsigned(addUnsigned(a2,q),addUnsigned(x,t)),s),b2)}function ff(a2,b2,c2,d2,x,s,t){return cmn(b2&c2|~b2&d2,a2,b2,x,s,t)}function gg(a2,b2,c2,d2,x,s,t){return cmn(b2&d2|c2&~d2,a2,b2,x,s,t)}function hh(a2,b2,c2,d2,x,s,t){return cmn(b2^c2^d2,a2,b2,x,s,t)}function ii(a2,b2,c2,d2,x,s,t){return cmn(c2^(b2|~d2),a2,b2,x,s,t)}let str=input.replace(/\r\n/g,`
41
- `),encoded="";for(let n=0;n<str.length;n++){let c2=str.charCodeAt(n);c2<128?encoded+=String.fromCharCode(c2):c2<2048?(encoded+=String.fromCharCode(c2>>6|192),encoded+=String.fromCharCode(c2&63|128)):(encoded+=String.fromCharCode(c2>>12|224),encoded+=String.fromCharCode(c2>>6&63|128),encoded+=String.fromCharCode(c2&63|128))}str=encoded;let len=str.length,nw=(len+8>>>6)+1<<4,words=new Array(nw).fill(0);for(let i=0;i<len;i++)words[i>>2]|=str.charCodeAt(i)<<i%4*8;words[len>>2]|=128<<len%4*8,words[nw-2]=len<<3,words[nw-1]=len>>>29;let a=1732584193,b=4023233417,c=2562383102,d=271733878;for(let k=0;k<words.length;k+=16){let aa=a,bb=b,cc=c,dd=d;a=ff(a,b,c,d,words[k],7,3614090360),d=ff(d,a,b,c,words[k+1],12,3905402710),c=ff(c,d,a,b,words[k+2],17,606105819),b=ff(b,c,d,a,words[k+3],22,3250441966),a=ff(a,b,c,d,words[k+4],7,4118548399),d=ff(d,a,b,c,words[k+5],12,1200080426),c=ff(c,d,a,b,words[k+6],17,2821735955),b=ff(b,c,d,a,words[k+7],22,4249261313),a=ff(a,b,c,d,words[k+8],7,1770035416),d=ff(d,a,b,c,words[k+9],12,2336552879),c=ff(c,d,a,b,words[k+10],17,4294925233),b=ff(b,c,d,a,words[k+11],22,2304563134),a=ff(a,b,c,d,words[k+12],7,1804603682),d=ff(d,a,b,c,words[k+13],12,4254626195),c=ff(c,d,a,b,words[k+14],17,2792965006),b=ff(b,c,d,a,words[k+15],22,1236535329),a=gg(a,b,c,d,words[k+1],5,4129170786),d=gg(d,a,b,c,words[k+6],9,3225465664),c=gg(c,d,a,b,words[k+11],14,643717713),b=gg(b,c,d,a,words[k],20,3921069994),a=gg(a,b,c,d,words[k+5],5,3593408605),d=gg(d,a,b,c,words[k+10],9,38016083),c=gg(c,d,a,b,words[k+15],14,3634488961),b=gg(b,c,d,a,words[k+4],20,3889429448),a=gg(a,b,c,d,words[k+9],5,568446438),d=gg(d,a,b,c,words[k+14],9,3275163606),c=gg(c,d,a,b,words[k+3],14,4107603335),b=gg(b,c,d,a,words[k+8],20,1163531501),a=gg(a,b,c,d,words[k+13],5,2850285829),d=gg(d,a,b,c,words[k+2],9,4243563512),c=gg(c,d,a,b,words[k+7],14,1735328473),b=gg(b,c,d,a,words[k+12],20,2368359562),a=hh(a,b,c,d,words[k+5],4,4294588738),d=hh(d,a,b,c,words[k+8],11,2272392833),c=hh(c,d,a,b,words[k+11],16,1839030562),b=hh(b,c,d,a,words[k+14],23,4259657740),a=hh(a,b,c,d,words[k+1],4,2763975236),d=hh(d,a,b,c,words[k+4],11,1272893353),c=hh(c,d,a,b,words[k+7],16,4139469664),b=hh(b,c,d,a,words[k+10],23,3200236656),a=hh(a,b,c,d,words[k+13],4,681279174),d=hh(d,a,b,c,words[k],11,3936430074),c=hh(c,d,a,b,words[k+3],16,3572445317),b=hh(b,c,d,a,words[k+6],23,76029189),a=hh(a,b,c,d,words[k+9],4,3654602809),d=hh(d,a,b,c,words[k+12],11,3873151461),c=hh(c,d,a,b,words[k+15],16,530742520),b=hh(b,c,d,a,words[k+2],23,3299628645),a=ii(a,b,c,d,words[k],6,4096336452),d=ii(d,a,b,c,words[k+7],10,1126891415),c=ii(c,d,a,b,words[k+14],15,2878612391),b=ii(b,c,d,a,words[k+5],21,4237533241),a=ii(a,b,c,d,words[k+12],6,1700485571),d=ii(d,a,b,c,words[k+3],10,2399980690),c=ii(c,d,a,b,words[k+10],15,4293915773),b=ii(b,c,d,a,words[k+1],21,2240044497),a=ii(a,b,c,d,words[k+8],6,1873313359),d=ii(d,a,b,c,words[k+15],10,4264355552),c=ii(c,d,a,b,words[k+6],15,2734768916),b=ii(b,c,d,a,words[k+13],21,1309151649),a=ii(a,b,c,d,words[k+4],6,4149444226),d=ii(d,a,b,c,words[k+11],10,3174756917),c=ii(c,d,a,b,words[k+2],15,718787259),b=ii(b,c,d,a,words[k+9],21,3951481745),a=addUnsigned(a,aa),b=addUnsigned(b,bb),c=addUnsigned(c,cc),d=addUnsigned(d,dd)}let hex3=v=>{let s="";for(let i=0;i<=3;i++){let byte=v>>>i*8&255;s+=("0"+byte.toString(16)).slice(-2)}return s};return(hex3(a)+hex3(b)+hex3(c)+hex3(d)).toLowerCase()}function extractMtopToken(cookieMap,isMopen){if(isMopen){let mTk=cookieMap.get("m_tk"),tbToken=cookieMap.get("_tb_token_");if(mTk)return mTk.split("_")[0]||"";if(tbToken)return tbToken;throw new Error("Missing m_tk or _tb_token_ cookie. Please ensure the user is logged in.")}let h5Tk=cookieMap.get("_m_h5_tk");if(h5Tk)return h5Tk.split("_")[0]||"";throw new Error("Missing _m_h5_tk cookie. Please ensure the user is logged in.")}function computeMtopSign(params){let{api,version:version2,timestamp,appKey,token,dataStr,isMopen}=params;return md5(isMopen?`${api}&${version2}&${timestamp}&${appKey}&${token}&${md5(dataStr)}`:`${token}&${timestamp}&${appKey}&${dataStr}`)}var MTOP_HOST_MAP={online:"h5api.m.taobao.com",pre:"h5api.wapa.taobao.com"};function buildCookieHeaderValue(cookieMap){return[...cookieMap.entries()].map(([k,v])=>`${k}=${v}`).join("; ")}function parseSseDataValue(value){try{return JSON.parse(value)}catch{return value}}function createSseEventParser(){let buffer="",eventName="",lastEventId,dataLines=[],hasData=!1,dispatch=()=>{if(!hasData)return eventName="",dataLines=[],[];let rawData=dataLines.join(`
41
+ `),encoded="";for(let n=0;n<str.length;n++){let c2=str.charCodeAt(n);c2<128?encoded+=String.fromCharCode(c2):c2<2048?(encoded+=String.fromCharCode(c2>>6|192),encoded+=String.fromCharCode(c2&63|128)):(encoded+=String.fromCharCode(c2>>12|224),encoded+=String.fromCharCode(c2>>6&63|128),encoded+=String.fromCharCode(c2&63|128))}str=encoded;let len=str.length,nw=(len+8>>>6)+1<<4,words=new Array(nw).fill(0);for(let i=0;i<len;i++)words[i>>2]|=str.charCodeAt(i)<<i%4*8;words[len>>2]|=128<<len%4*8,words[nw-2]=len<<3,words[nw-1]=len>>>29;let a=1732584193,b=4023233417,c=2562383102,d=271733878;for(let k=0;k<words.length;k+=16){let aa=a,bb=b,cc=c,dd=d;a=ff(a,b,c,d,words[k],7,3614090360),d=ff(d,a,b,c,words[k+1],12,3905402710),c=ff(c,d,a,b,words[k+2],17,606105819),b=ff(b,c,d,a,words[k+3],22,3250441966),a=ff(a,b,c,d,words[k+4],7,4118548399),d=ff(d,a,b,c,words[k+5],12,1200080426),c=ff(c,d,a,b,words[k+6],17,2821735955),b=ff(b,c,d,a,words[k+7],22,4249261313),a=ff(a,b,c,d,words[k+8],7,1770035416),d=ff(d,a,b,c,words[k+9],12,2336552879),c=ff(c,d,a,b,words[k+10],17,4294925233),b=ff(b,c,d,a,words[k+11],22,2304563134),a=ff(a,b,c,d,words[k+12],7,1804603682),d=ff(d,a,b,c,words[k+13],12,4254626195),c=ff(c,d,a,b,words[k+14],17,2792965006),b=ff(b,c,d,a,words[k+15],22,1236535329),a=gg(a,b,c,d,words[k+1],5,4129170786),d=gg(d,a,b,c,words[k+6],9,3225465664),c=gg(c,d,a,b,words[k+11],14,643717713),b=gg(b,c,d,a,words[k],20,3921069994),a=gg(a,b,c,d,words[k+5],5,3593408605),d=gg(d,a,b,c,words[k+10],9,38016083),c=gg(c,d,a,b,words[k+15],14,3634488961),b=gg(b,c,d,a,words[k+4],20,3889429448),a=gg(a,b,c,d,words[k+9],5,568446438),d=gg(d,a,b,c,words[k+14],9,3275163606),c=gg(c,d,a,b,words[k+3],14,4107603335),b=gg(b,c,d,a,words[k+8],20,1163531501),a=gg(a,b,c,d,words[k+13],5,2850285829),d=gg(d,a,b,c,words[k+2],9,4243563512),c=gg(c,d,a,b,words[k+7],14,1735328473),b=gg(b,c,d,a,words[k+12],20,2368359562),a=hh(a,b,c,d,words[k+5],4,4294588738),d=hh(d,a,b,c,words[k+8],11,2272392833),c=hh(c,d,a,b,words[k+11],16,1839030562),b=hh(b,c,d,a,words[k+14],23,4259657740),a=hh(a,b,c,d,words[k+1],4,2763975236),d=hh(d,a,b,c,words[k+4],11,1272893353),c=hh(c,d,a,b,words[k+7],16,4139469664),b=hh(b,c,d,a,words[k+10],23,3200236656),a=hh(a,b,c,d,words[k+13],4,681279174),d=hh(d,a,b,c,words[k],11,3936430074),c=hh(c,d,a,b,words[k+3],16,3572445317),b=hh(b,c,d,a,words[k+6],23,76029189),a=hh(a,b,c,d,words[k+9],4,3654602809),d=hh(d,a,b,c,words[k+12],11,3873151461),c=hh(c,d,a,b,words[k+15],16,530742520),b=hh(b,c,d,a,words[k+2],23,3299628645),a=ii(a,b,c,d,words[k],6,4096336452),d=ii(d,a,b,c,words[k+7],10,1126891415),c=ii(c,d,a,b,words[k+14],15,2878612391),b=ii(b,c,d,a,words[k+5],21,4237533241),a=ii(a,b,c,d,words[k+12],6,1700485571),d=ii(d,a,b,c,words[k+3],10,2399980690),c=ii(c,d,a,b,words[k+10],15,4293915773),b=ii(b,c,d,a,words[k+1],21,2240044497),a=ii(a,b,c,d,words[k+8],6,1873313359),d=ii(d,a,b,c,words[k+15],10,4264355552),c=ii(c,d,a,b,words[k+6],15,2734768916),b=ii(b,c,d,a,words[k+13],21,1309151649),a=ii(a,b,c,d,words[k+4],6,4149444226),d=ii(d,a,b,c,words[k+11],10,3174756917),c=ii(c,d,a,b,words[k+2],15,718787259),b=ii(b,c,d,a,words[k+9],21,3951481745),a=addUnsigned(a,aa),b=addUnsigned(b,bb),c=addUnsigned(c,cc),d=addUnsigned(d,dd)}let hex3=v=>{let s="";for(let i=0;i<=3;i++){let byte=v>>>i*8&255;s+=("0"+byte.toString(16)).slice(-2)}return s};return(hex3(a)+hex3(b)+hex3(c)+hex3(d)).toLowerCase()}function extractMtopToken(cookieMap,isMopen){if(isMopen){let mTk=cookieMap.get("m_tk"),tbToken=cookieMap.get("_tb_token_");if(mTk)return mTk.split("_")[0]||"";if(tbToken)return tbToken;throw new Error("Missing m_tk or _tb_token_ cookie. Please ensure the user is logged in.")}let h5Tk=cookieMap.get("_m_h5_tk");if(h5Tk)return h5Tk.split("_")[0]||"";throw new Error("Missing _m_h5_tk cookie. Please ensure the user is logged in.")}function computeMtopSign(params){let{api,version:version2,timestamp,appKey,token,dataStr,isMopen}=params;return md5(isMopen?`${api}&${version2}&${timestamp}&${appKey}&${token}&${md5(dataStr)}`:`${token}&${timestamp}&${appKey}&${dataStr}`)}var MTOP_HOST_MAP={prod:"h5api.m.taobao.com",pre:"h5api.wapa.taobao.com"};function buildCookieHeaderValue(cookieMap){return[...cookieMap.entries()].map(([k,v])=>`${k}=${v}`).join("; ")}function parseSseDataValue(value){try{return JSON.parse(value)}catch{return value}}function createSseEventParser(){let buffer="",eventName="",lastEventId,dataLines=[],hasData=!1,dispatch=()=>{if(!hasData)return eventName="",dataLines=[],[];let rawData=dataLines.join(`
42
42
  `);if(eventName=eventName||"message",dataLines=[],hasData=!1,rawData==="[DONE]")return eventName="",[];let event={event:eventName,data:parseSseDataValue(rawData),...lastEventId!==void 0?{eventId:lastEventId}:{}};return eventName="",[event]},consumeLine=line=>{if(line==="")return dispatch();if(line.startsWith(":"))return[];let separator=line.indexOf(":"),field=separator===-1?line:line.slice(0,separator),value=separator===-1?"":line.slice(separator+1);return value.startsWith(" ")&&(value=value.slice(1)),field==="data"?(dataLines.push(value),hasData=!0):field==="event"?eventName=value:field==="id"&&!value.includes("\0")&&(lastEventId=value),[]},drain=final=>{let events=[];for(;buffer.length>0;){let newlineIndex=-1;for(let index=0;index<buffer.length;index++)if(buffer[index]===`
43
43
  `||buffer[index]==="\r"){newlineIndex=index;break}if(newlineIndex===-1){final&&(events.push(...consumeLine(buffer)),buffer="");break}if(buffer[newlineIndex]==="\r"&&newlineIndex===buffer.length-1&&!final)break;let line=buffer.slice(0,newlineIndex),separatorLength=buffer[newlineIndex]==="\r"&&buffer[newlineIndex+1]===`
44
- `?2:1;buffer=buffer.slice(newlineIndex+separatorLength),events.push(...consumeLine(line))}return final&&events.push(...dispatch()),events};return{push(chunk){return buffer+=chunk,drain(!1)},finish(){return drain(!0)}}}function resolveMtopRequest(data){let{api,data:requestData={},version:version2="1.0",method="GET",appKey="12574478",env="online",timeout=1e4,headers:customHeaders={},ttid}=data;if(!api||typeof api!="string"||api.trim()==="")throw new Error('Invalid api: api must be a non-empty string (e.g. "mtop.trade.order.create")');let baseHost=MTOP_HOST_MAP[env.toLowerCase()];if(!baseHost)throw new Error(`Invalid env: "${env}". Supported values: ${Object.keys(MTOP_HOST_MAP).join(", ")}`);let normalizedMethod=method.toUpperCase();if(normalizedMethod!=="GET"&&normalizedMethod!=="POST")throw new Error(`Invalid method: ${method}. mtop only supports GET or POST`);if(!Number.isFinite(timeout)||timeout<=0)throw new Error("Invalid timeout: timeout must be a positive number");return{api,requestData,dataStr:typeof requestData=="string"?requestData:JSON.stringify(requestData),version:version2,normalizedMethod,appKey,gatewayUrl:new URL(`https://${baseHost}/h5/${api}/${version2}/`),customHeaders,ttid,timeout,isMopen:api.startsWith("mopen.")}}function prepareSignedMtopRequest(resolved,cookieMap,stream=!1,timestamp=Date.now()){let token=extractMtopToken(cookieMap,resolved.isMopen),sign=computeMtopSign({api:resolved.api,version:resolved.version,timestamp,appKey:resolved.appKey,token,dataStr:resolved.dataStr,isMopen:resolved.isMopen}),targetUrl=new URL(resolved.gatewayUrl),queryParams={jsv:"2.7.2",appKey:resolved.appKey,t:timestamp.toString(),sign,api:resolved.api,v:resolved.version,type:"originaljson",dataType:"json"};stream&&(queryParams.xAcceptStream="true"),resolved.ttid&&(queryParams.ttid=resolved.ttid),resolved.normalizedMethod==="GET"&&(queryParams.data=resolved.dataStr);for(let[name,value]of Object.entries(queryParams))targetUrl.searchParams.set(name,value);let requestHeaders={Accept:stream?"text/event-stream":"application/json",...resolved.customHeaders},body;return resolved.normalizedMethod==="POST"&&(body=new URLSearchParams({data:resolved.dataStr}).toString(),requestHeaders["Content-Type"]="application/x-www-form-urlencoded"),{...resolved,targetUrl,requestHeaders,cookieHeader:buildCookieHeaderValue(cookieMap),body}}function parseMtopResponseText(text){try{return JSON.parse(text)}catch{let jsonpMatch=text.match(/^[^(]*\((.*)\)\s*;?\s*$/s);if(!jsonpMatch?.[1])return text;try{return JSON.parse(jsonpMatch[1])}catch{return text}}}function summarizeMtopStreamError(body){if(body&&typeof body=="object"){let record2=body;if(Array.isArray(record2.ret))return record2.ret.map(String).join(", ");if(typeof record2.message=="string")return record2.message}return((typeof body=="string"?body:JSON.stringify(body))??String(body)).slice(0,500)}async function consumeMtopSseResponse(response,onReceive){let contentType=response.headers.get("content-type")??"";if(!response.ok||!response.body||!contentType.includes("text/event-stream")){let body=parseMtopResponseText(await response.text());throw new Error(`Unexpected MTOP stream response: ${summarizeMtopStreamError(body)}`)}let reader=response.body.getReader(),decoder=new TextDecoder,parser=createSseEventParser(),lastData=null,emit=async(text,finished=!1)=>{let events=[...parser.push(text),...finished?parser.finish():[]];for(let event of events)lastData=event.data,await onReceive(event)};for(;;){let{done,value}=await reader.read();if(done)return await emit(decoder.decode(),!0),lastData;await emit(decoder.decode(value,{stream:!0}))}}function parseRequestData(data){if(typeof data!="string")return data;try{return JSON.parse(data)}catch{return data}}function parseQueryString(url2){let queryString=[];try{new URL(url2).searchParams.forEach((value,name)=>queryString.push({name,value}))}catch{}return queryString}function redactSensitiveHeaders(headers){let sensitiveNames=new Set(["authorization","cookie","proxy-authorization"]);return headers.map(header=>sensitiveNames.has(header.name.toLowerCase())?{...header,value:"<redacted>"}:header)}function createMtopStreamCapture(data){let timestampMs2=data.timestampMs??Date.now(),url2=data.url??`mtop://${data.api}/`;return{startTimeMs:timestampMs2,request:{id:data.id,timestamp:new Date(timestampMs2).toISOString(),timestampMs:timestampMs2,method:data.method,url:url2,apiName:data.api,status:0,statusText:"SSE Streaming",headers:redactSensitiveHeaders(data.requestHeaders??[]),responseHeaders:[],queryString:parseQueryString(url2),postData:parseRequestData(data.requestData??null),responseBody:[],isProxy:!0,proxyRequestUrl:null,proxyData:null,isSSE:!0,isPending:!0,...data.tabId!==void 0?{tabId:data.tabId}:{},source:"mtop",resourceType:"fetch",captureSequence:data.captureSequence}}}function updateMtopStreamCaptureResponse(capture,response){capture.request.status=response.status,capture.request.statusText=response.statusText,capture.request.responseHeaders=response.responseHeaders}function appendMtopStreamCaptureChunk(capture,data,timestampMs2=Date.now()){return Array.isArray(capture.request.responseBody)?(capture.request.responseBody.push({event:"message",data,timestamp:timestampMs2,duration:capture.lastMessageTimeMs===void 0?0:timestampMs2-capture.lastMessageTimeMs}),capture.lastMessageTimeMs=timestampMs2,!0):!1}function finishMtopStreamCapture(capture,options={}){let timestampMs2=options.timestampMs??Date.now();if(capture.request.isPending=!1,capture.request.duration=Math.max(0,timestampMs2-capture.startTimeMs),options.error){capture.request.statusText=options.error,Array.isArray(capture.request.responseBody)&&capture.request.responseBody.length===0&&(capture.request.responseBody={error:options.error});return}capture.request.status===0&&(capture.request.status=200),(!capture.request.statusText||capture.request.statusText==="SSE Streaming")&&(capture.request.statusText="OK")}function isAppProfileUserInfoUrl(url2){try{let target=new URL(url2);return(target.protocol==="http:"||target.protocol==="https:")&&(target.hostname==="taobao.com"||target.hostname.endsWith(".taobao.com"))}catch{return!1}}function decodeCookieValue(raw){let value=raw;for(let index=0;index<2;index+=1)try{let decoded=decodeURIComponent(value);if(decoded===value)break;value=decoded}catch{break}return value.replace(/\\u([0-9a-f]{4})/gi,(_match,hex3)=>String.fromCharCode(Number.parseInt(hex3,16)))}function firstCookieValue(cookies,name){let value=cookies.find(cookie=>cookie.name===name&&cookie.value&&cookie.value!=="null")?.value;return value?decodeCookieValue(value):""}function resolveAppProfileUserInfo(url2,cookies){if(!isAppProfileUserInfoUrl(url2))return{};let userId=firstCookieValue(cookies,"unb"),userName=["_w_tb_nick","_nk_","snk","tracknick"].map(name=>firstCookieValue(cookies,name)).find(Boolean);return{...userId&&{userId},...userName&&{userName}}}var APLUS_URL_PATTERN=/\.mmstat\.com\//,RUM_URL_PATTERN=/\.rum\.aliyuncs\.com\//,ARMS_URL_PATTERN=/arms-retcode\.aliyuncs\.com\//;function isTrackingUrl(url2){return APLUS_URL_PATTERN.test(url2)||RUM_URL_PATTERN.test(url2)||ARMS_URL_PATTERN.test(url2)||/retcode\.alicdn\.com|beacon\.taobao\.com|tbsec\./i.test(url2)}var aplusCounter=0,armsCounter=0,rumCounter=0;function formatTimestamp(ms){let d=new Date(ms),pad=n=>String(n).padStart(2,"0");return`${d.getFullYear()}/${pad(d.getMonth()+1)}/${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`}function parseParams(value){let params={};return value.split("&").forEach(pair=>{let eqIndex=pair.indexOf("=");if(eqIndex===-1)return;let rawKey=pair.slice(0,eqIndex),rawValue=pair.slice(eqIndex+1);try{params[decodeURIComponent(rawKey)]=rawValue}catch{params[rawKey]=rawValue}}),params}function decodeParamValue(value){try{return decodeURIComponent(value)}catch{return value}}function parseJsonParamValue(value){try{return JSON.parse(value)}catch{let decoded=decodeParamValue(value);if(decoded===value)return;try{return JSON.parse(decoded)}catch{return}}}function parseUrlParams(search){let encodedParams=parseParams(search.startsWith("?")?search.slice(1):search);return Object.fromEntries(Object.entries(encodedParams).map(([key,value])=>[key,decodeParamValue(value)]))}function extractSpmFromUrl(spmOrUrl){if(!/^https?:\/\//i.test(spmOrUrl))return spmOrUrl;try{return new URL(spmOrUrl).searchParams.get("spm")??spmOrUrl}catch{return spmOrUrl}}function resolveAplusSpm(eventType,raw){let expSpm=(Array.isArray(raw.expdata)?raw.expdata:[])[0]?.spm||"",gokeyParams=parseParams(raw.gokey||""),gokeySpm=decodeParamValue(gokeyParams.spm||""),rawSpmUrl=raw["spm-url"]||decodeParamValue(gokeyParams["spm-url"]||""),spmUrl=extractSpmFromUrl(rawSpmUrl),pointSpm;switch(eventType){case"CLK":pointSpm=gokeySpm||expSpm;break;case"EXP":pointSpm=expSpm;break;case"PV":pointSpm=spmUrl;break;default:pointSpm=gokeySpm||expSpm}return{mainSpm:pointSpm,highlightSpm:pointSpm}}function parseAplusRequest(url2,options={}){if(!APLUS_URL_PATTERN.test(url2))return null;let urlObj;try{urlObj=new URL(url2)}catch{return null}let params=parseUrlParams(urlObj.search),gmkey=params.gmkey??"UNKNOWN",urlPathName=urlObj.pathname.slice(1),eventType=urlPathName.split(".")[1]==="selfdefine"?"SDF":gmkey,gokeyRaw=params.gokey??"",gokeyParams=parseParams(gokeyRaw),expdata=[];if(gokeyParams.expdata){let parsedExpdata=parseJsonParamValue(gokeyParams.expdata);Array.isArray(parsedExpdata)&&(expdata=parsedExpdata.map(item=>{if(!item?.exargs||typeof item.exargs!="object")return item;let decoded={};for(let[key,value]of Object.entries(item.exargs)){if(typeof value!="string"){decoded[key]=value;continue}let parsedValue=parseJsonParamValue(value);decoded[key]=parsedValue===void 0?value:parsedValue}return{...item,exargs:decoded}}))}let rawBizArgs=gokeyParams.bizArgs,parsedBizArgs=rawBizArgs===void 0?void 0:parseJsonParamValue(rawBizArgs),bizArgs=parsedBizArgs===void 0?rawBizArgs:parsedBizArgs,pageUrl=params._p_url??(gokeyParams._p_url?decodeParamValue(gokeyParams._p_url):""),{gokey:rawGokey,...topLevelParams}=params,rawData={...topLevelParams,_path:urlPathName,_url:url2,gokey:rawGokey,...expdata.length>0?{expdata}:{},...bizArgs!==void 0?{bizArgs}:{}},spm=resolveAplusSpm(eventType,rawData).mainSpm,pathName=urlPathName.split(".").slice(1).join("."),eventName=eventType==="SDF"?pathName:spm||pathName||pageUrl,now=options.now??Date.now();return{id:`aplus-${options.sequence??++aplusCounter}-${now}`,source:"aplus",batchId:0,batchTimestampMs:now,batchTimestamp:formatTimestamp(now),event_type:eventType,name:eventName,url:url2,timestamp:now,_raw:rawData,_context:{requestUrl:url2,app:{},user:{...params.uidaplus?{uidaplus:params.uidaplus}:{},...params._gr_uid_?{_gr_uid_:params._gr_uid_}:{}},session:{},view:{...params["spm-url"]?{"spm-url":params["spm-url"]}:{},...params["spm-pre"]?{"spm-pre":params["spm-pre"]}:{},...params["spm-cnt"]?{"spm-cnt":params["spm-cnt"]}:{},...pageUrl?{page_url:pageUrl}:{}},properties:{},os:{},net:{}}}}var RUM_TYPE_ALIAS={cst:"custom"},I18N_TRACKER_TYPE_MAP={"i18n-tracker-exp":"EXP","i18n-tracker-clk":"CLK"};function parseRumBody(postData){if(!postData)return null;if(typeof postData=="object")return postData;try{return JSON.parse(postData)}catch{return null}}function tryConvertI18nTracker(event,base){let normalizedType=RUM_TYPE_ALIAS[event.type]??event.type;if(event.event_type!=="action"||normalizedType!=="custom")return null;let snapshots;try{snapshots=typeof event.snapshots=="string"?JSON.parse(event.snapshots):event.snapshots}catch{return null}if(!snapshots||typeof snapshots!="object")return null;let eventType=I18N_TRACKER_TYPE_MAP[snapshots.message];if(!eventType)return null;let spm=[snapshots.c1??"",snapshots.c2??""].filter(Boolean).join("."),exargs={};typeof snapshots.c3=="string"&&snapshots.c3.split("&").forEach(pair=>{let eqIndex=pair.indexOf("=");if(eqIndex===-1)return;let key=pair.slice(0,eqIndex),rawValue=pair.slice(eqIndex+1);try{exargs[key]=JSON.parse(decodeURIComponent(rawValue))}catch{exargs[key]=rawValue}});let dataAttrs=snapshots.trackerInfo?.dataAttrs;if(dataAttrs&&typeof dataAttrs=="object"&&dataAttrs["data-biz-args"]&&!exargs.bizArgs)try{exargs.bizArgs=JSON.parse(dataAttrs["data-biz-args"])}catch{exargs.bizArgs=dataAttrs["data-biz-args"]}return{...base,event_type:eventType,name:spm,_raw:{...event,expdata:[{spm,...Object.keys(exargs).length>0?{exargs}:{}}],"spm-url":spm}}}function parseRumRequest(url2,postData,options={}){if(!RUM_URL_PATTERN.test(url2))return[];let parsed=parseRumBody(postData),rawEvents=Array.isArray(parsed?.events)?parsed.events:[];if(rawEvents.length===0)return[];let now=options.now??Date.now(),batchId=options.sequence??++rumCounter,context={requestUrl:url2,app:parsed?.app??{},user:parsed?.user??{},session:parsed?.session??{},view:parsed?.view??{},properties:parsed?.properties??{},os:parsed?.os??{},net:parsed?.net??{}};return rawEvents.flatMap((rawEvent,index)=>{if(!rawEvent||typeof rawEvent!="object"||Array.isArray(rawEvent))return[];let event=rawEvent,normalizedType=RUM_TYPE_ALIAS[event.type]??event.type,base={id:`${batchId}-${event.event_id??index}`,batchId,batchTimestampMs:now,batchTimestamp:formatTimestamp(now),type:normalizedType,url:event.url,timestamp:event.timestamp??now,success:event.success,status_code:event.status_code,method:event.method,duration:event.duration,source:"rum",_context:context},converted=tryConvertI18nTracker(event,base);return converted?[converted]:[{...base,event_type:event.event_type??"unknown",name:event.name,_raw:event}]})}function parseArmsRequest(url2,options={}){if(!ARMS_URL_PATTERN.test(url2))return null;let urlObj;try{urlObj=new URL(url2)}catch{return null}let params={};urlObj.searchParams.forEach((value,key)=>{params[key]=value});let eventType=(params.t??"unknown").toLowerCase(),page=params.page??"",now=options.now??Date.now(),sequence=options.sequence??++armsCounter,parsedTimestamp2=params.begin?Number.parseInt(params.begin,10):now,timestamp=Number.isFinite(parsedTimestamp2)?parsedTimestamp2:now;return{id:`arms-${sequence}-${now}`,source:"arms",batchId:0,batchTimestampMs:now,batchTimestamp:formatTimestamp(now),event_type:eventType,name:page||url2,url:url2,timestamp,_raw:{...params,_url:url2},_context:{requestUrl:url2,app:{...params.pid?{pid:params.pid}:{},...params.release?{release:params.release}:{},...params.environment?{environment:params.environment}:{},...params._v?{sdk_version:params._v}:{}},user:{...params.uid?{uid:params.uid}:{}},session:{...params.sid?{sid:params.sid}:{}},view:{...page?{page}:{},...params.tag?{tag:params.tag}:{}},properties:{},os:{},net:{...params.ct?{ct:params.ct}:{}}}}}function parseTrackingRequest(url2,postData,options={}){let rumEvents=parseRumRequest(url2,postData,options);if(rumEvents.length>0)return rumEvents;let aplusEvent=parseAplusRequest(url2,options);if(aplusEvent)return[aplusEvent];let armsEvent=parseArmsRequest(url2,options);return armsEvent?[armsEvent]:[]}var CURSOR_PREFIX="mearl-capture-v1";function createCaptureGeneration(){return crypto.randomUUID()}function encodeCaptureCursor(cursor){return`${CURSOR_PREFIX}:${cursor.tabId}:${cursor.generation}:${cursor.scope}:${cursor.sequence}`}function decodeCaptureCursor(value){let match=value.match(/^mearl-capture-v1:(\d+):([^:]+):(all|logs|requests|events):(\d+)$/);if(!match)throw new Error("Invalid capture cursor");let tabId=Number(match[1]),sequence=Number(match[4]);if(!Number.isSafeInteger(tabId)||!Number.isSafeInteger(sequence))throw new Error("Invalid capture cursor");return{tabId,generation:match[2],scope:match[3],sequence}}function captureCheckpoint(state){return encodeCaptureCursor({tabId:state.tabId,generation:state.generation,sequence:state.currentSequence,scope:"all"})}function nextCaptureSequence(state){return state.currentSequence+=1,state.currentSequence}function resolveAfterSequence(after,state,scope){if(!after)return 0;let cursor=decodeCaptureCursor(after);if(cursor.tabId!==state.tabId)throw new Error(`Capture cursor belongs to tab ${cursor.tabId}, not tab ${state.tabId}`);if(cursor.generation!==state.generation)throw new Error("Capture cursor expired because the tab collector was restarted");if(cursor.scope!=="all"&&cursor.scope!==scope)throw new Error(`Capture cursor is scoped to ${cursor.scope}, not ${scope}`);if(cursor.sequence>state.currentSequence)throw new Error("Capture cursor is ahead of the current collector state");return cursor.sequence}function queryCapturedEntries(buffer,state,options,matches,droppedThroughSequence=0,scope="all"){let{after,since,now=Date.now()}=options,limit=Math.max(1,Math.floor(options.limit??100)),afterSequence=resolveAfterSequence(after,state,scope),sinceTimestampMs=since===void 0?void 0:now-since*1e3,matched=buffer.filter(entry=>entry.captureSequence>afterSequence&&(sinceTimestampMs===void 0||entry.timestampMs>=sinceTimestampMs)&&matches(entry)),hasMore=matched.length>limit,entries=after?matched.slice(0,limit):matched.slice(-limit),nextSequence=after&&hasMore&&entries.length>0?entries[entries.length-1].captureSequence:state.currentSequence;return{entries,totalMatched:matched.length,nextCursor:encodeCaptureCursor({tabId:state.tabId,generation:state.generation,sequence:nextSequence,scope}),hasMore,gap:after!==void 0&&afterSequence<droppedThroughSequence}}var TRACKING_CAPTURE_ARMED_HINT="Event capture is active, but this tab has no captured history yet. Reload the current tab or repeat the triggering action, then call get_events again.";function compileTextPattern(value){try{return{regex:new RegExp(value,"i"),fallback:""}}catch{return{regex:null,fallback:value.toLowerCase()}}}function matchesTextPattern(value,pattern){return value?pattern.regex?pattern.regex.test(value):value.toLowerCase().includes(pattern.fallback):!1}function compactEventUrl(value){if(value)try{let url2=new URL(value);return url2.origin==="null"?value.split(/[?#]/,1)[0]:`${url2.origin}${url2.pathname}`}catch{return value.split(/[?#]/,1)[0]}}function formatTrackingEvent(event,includeRaw=!1){let{captureSequence:_discardedCaptureSequence,...publicEvent}=event;if(includeRaw)return publicEvent;let{_raw:_discardedRaw,_context,url:url2,...summary}=publicEvent,compactUrl=compactEventUrl(url2??_context.requestUrl);return{...summary,...compactUrl?{url:compactUrl}:{}}}function matchesTrackingEvent(event,options){let{source="all",event_type,filter}=options;if(source!=="all"&&event.source!==source||event_type&&!matchesTextPattern(event.event_type,compileTextPattern(event_type)))return!1;if(filter){let pattern=compileTextPattern(filter);if(!matchesTextPattern(event.name,pattern)&&!matchesTextPattern(event.url,pattern))return!1}return!0}function queryTrackingEvents(buffer,options={}){let{source="all",event_type,filter,since,limit=20,now=Date.now()}=options,events=[...buffer].reverse();if(source!=="all"&&(events=events.filter(event=>event.source===source)),since!==void 0){let sinceTimestamp=now-since*1e3;events=events.filter(event=>event.batchTimestampMs>=sinceTimestamp)}if(event_type){let pattern=compileTextPattern(event_type);events=events.filter(event=>matchesTextPattern(event.event_type,pattern))}if(filter){let pattern=compileTextPattern(filter);events=events.filter(event=>matchesTextPattern(event.name,pattern)||matchesTextPattern(event.url,pattern))}return{events:events.slice(0,limit),totalMatched:events.length,totalInBuffer:buffer.length}}function appendCapturedTrackingBatch(buffer,events,maxSize){if(events.length===0)return[];let captureSequence=events[0].captureSequence,insertionIndex=Number.isSafeInteger(captureSequence)?buffer.findIndex(event=>Number.isSafeInteger(event.captureSequence)&&event.captureSequence>captureSequence):-1;if(buffer.splice(insertionIndex<0?buffer.length:insertionIndex,0,...events),buffer.length<=maxSize)return[];let removeCount=buffer.length-maxSize,boundarySequence=buffer[removeCount-1]?.captureSequence;for(;boundarySequence!==void 0&&buffer[removeCount]?.captureSequence===boundarySequence;)removeCount+=1;return buffer.splice(0,removeCount)}function queryCapturedTrackingEvents(buffer,state,options={},droppedThroughSequence=0){let limit=Math.max(1,Math.floor(options.limit??20));if(!options.after){let snapshot=queryTrackingEvents(buffer,options);return{...snapshot,nextCursor:encodeCaptureCursor({tabId:state.tabId,generation:state.generation,sequence:state.currentSequence,scope:"events"}),hasMore:snapshot.totalMatched>limit,gap:!1}}let sinceTimestampMs=options.since===void 0?void 0:(options.now??Date.now())-options.since*1e3,batchesBySequence=new Map;for(let event of buffer){if(!Number.isSafeInteger(event.captureSequence)||sinceTimestampMs!==void 0&&event.batchTimestampMs<sinceTimestampMs||!matchesTrackingEvent(event,options))continue;let captureSequence=event.captureSequence,batch=batchesBySequence.get(captureSequence);batch?batch.events.push(event):batchesBySequence.set(captureSequence,{captureSequence,timestampMs:event.batchTimestampMs,events:[event]})}let batches=[...batchesBySequence.values()].sort((left,right)=>left.captureSequence-right.captureSequence),captured=queryCapturedEntries(batches,state,{after:options.after,limit:Number.MAX_SAFE_INTEGER},()=>!0,droppedThroughSequence,"events"),selected=[],selectedCount=0;for(let batch of captured.entries){if(selected.length>0&&selectedCount+batch.events.length>limit)break;selected.push(batch),selectedCount+=batch.events.length}let hasMore=selected.length<captured.entries.length,nextSequence=hasMore?selected[selected.length-1].captureSequence:state.currentSequence;return{events:selected.flatMap(batch=>batch.events),totalMatched:captured.entries.reduce((total,batch)=>total+batch.events.length,0),totalInBuffer:buffer.length,nextCursor:encodeCaptureCursor({tabId:state.tabId,generation:state.generation,sequence:nextSequence,scope:"events"}),hasMore,gap:captured.gap}}function parsePath(path19){if(path19.length>1e3)throw new Error("Path too long: maximum 1000 characters allowed");let keys=[],current="";for(let i=0;i<path19.length;i++){let char=path19[i];if(char===".")current&&(keys.push(current),current="");else if(char==="["){current&&(keys.push(current),current="");let j=i+1;for(;j<path19.length&&path19[j]!=="]";)j++;if(j<path19.length){let index=parseInt(path19.substring(i+1,j),10);if(!isNaN(index)){if(index<0||index>1e5)throw new Error(`Array index out of safe range: ${index}`);keys.push(index)}i=j}}else current+=char}if(current&&keys.push(current),keys.length>50)throw new Error("Path too deep: maximum 50 levels allowed");return keys}function getValueByPath(obj,path19){let keys=parsePath(path19),current=obj;for(let key of keys){if(current==null)return;current=current[key]}return current}function setValueByPath(obj,path19,value){let keys=parsePath(path19),current=obj;for(let i=0;i<keys.length-1;i++){let key=keys[i],nextKey=keys[i+1];(current[key]===null||current[key]===void 0)&&(current[key]=typeof nextKey=="number"?[]:{}),current=current[key]}current[keys[keys.length-1]]=value}function getStructure(data,maxDepth=5,currentDepth=0){if(currentDepth>=maxDepth)return"<max depth reached>";if(data===null)return"null";if(data===void 0)return"undefined";let type=typeof data;if(type==="string"||type==="number"||type==="boolean")return type;if(Array.isArray(data))return data.length===0?"array[0]":{_type:`array[${data.length}]`,_sample:getStructure(data[0],maxDepth,currentDepth+1)};if(type==="object"){let structure={};for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&(structure[key]=getStructure(data[key],maxDepth,currentDepth+1));return structure}return type}function truncateData(data,maxSize){let str=JSON.stringify(data);if(str.length<=maxSize)return data;let truncated=str.substring(0,maxSize);return`<truncated: ${str.length} bytes, showing first ${maxSize} chars>
44
+ `?2:1;buffer=buffer.slice(newlineIndex+separatorLength),events.push(...consumeLine(line))}return final&&events.push(...dispatch()),events};return{push(chunk){return buffer+=chunk,drain(!1)},finish(){return drain(!0)}}}function resolveMtopRequest(data){let{api,data:requestData={},version:version2="1.0",method="GET",appKey="12574478",env="prod",timeout=1e4,headers:customHeaders={},ttid}=data;if(!api||typeof api!="string"||api.trim()==="")throw new Error('Invalid api: api must be a non-empty string (e.g. "mtop.trade.order.create")');let baseHost=MTOP_HOST_MAP[env.toLowerCase()];if(!baseHost)throw new Error(`Invalid env: "${env}". Supported values: ${Object.keys(MTOP_HOST_MAP).join(", ")}`);let normalizedMethod=method.toUpperCase();if(normalizedMethod!=="GET"&&normalizedMethod!=="POST")throw new Error(`Invalid method: ${method}. mtop only supports GET or POST`);if(!Number.isFinite(timeout)||timeout<=0)throw new Error("Invalid timeout: timeout must be a positive number");return{api,requestData,dataStr:typeof requestData=="string"?requestData:JSON.stringify(requestData),version:version2,normalizedMethod,appKey,gatewayUrl:new URL(`https://${baseHost}/h5/${api}/${version2}/`),customHeaders,ttid,timeout,isMopen:api.startsWith("mopen.")}}function prepareSignedMtopRequest(resolved,cookieMap,stream=!1,timestamp=Date.now()){let token=extractMtopToken(cookieMap,resolved.isMopen),sign=computeMtopSign({api:resolved.api,version:resolved.version,timestamp,appKey:resolved.appKey,token,dataStr:resolved.dataStr,isMopen:resolved.isMopen}),targetUrl=new URL(resolved.gatewayUrl),queryParams={jsv:"2.7.2",appKey:resolved.appKey,t:timestamp.toString(),sign,api:resolved.api,v:resolved.version,type:"originaljson",dataType:"json"};stream&&(queryParams.xAcceptStream="true"),resolved.ttid&&(queryParams.ttid=resolved.ttid),resolved.normalizedMethod==="GET"&&(queryParams.data=resolved.dataStr);for(let[name,value]of Object.entries(queryParams))targetUrl.searchParams.set(name,value);let requestHeaders={Accept:stream?"text/event-stream":"application/json",...resolved.customHeaders},body;return resolved.normalizedMethod==="POST"&&(body=new URLSearchParams({data:resolved.dataStr}).toString(),requestHeaders["Content-Type"]="application/x-www-form-urlencoded"),{...resolved,targetUrl,requestHeaders,cookieHeader:buildCookieHeaderValue(cookieMap),body}}function parseMtopResponseText(text){try{return JSON.parse(text)}catch{let jsonpMatch=text.match(/^[^(]*\((.*)\)\s*;?\s*$/s);if(!jsonpMatch?.[1])return text;try{return JSON.parse(jsonpMatch[1])}catch{return text}}}function summarizeMtopStreamError(body){if(body&&typeof body=="object"){let record2=body;if(Array.isArray(record2.ret))return record2.ret.map(String).join(", ");if(typeof record2.message=="string")return record2.message}return((typeof body=="string"?body:JSON.stringify(body))??String(body)).slice(0,500)}async function consumeMtopSseResponse(response,onReceive){let contentType=response.headers.get("content-type")??"";if(!response.ok||!response.body||!contentType.includes("text/event-stream")){let body=parseMtopResponseText(await response.text());throw new Error(`Unexpected MTOP stream response: ${summarizeMtopStreamError(body)}`)}let reader=response.body.getReader(),decoder=new TextDecoder,parser=createSseEventParser(),lastData=null,emit=async(text,finished=!1)=>{let events=[...parser.push(text),...finished?parser.finish():[]];for(let event of events)lastData=event.data,await onReceive(event)};for(;;){let{done,value}=await reader.read();if(done)return await emit(decoder.decode(),!0),lastData;await emit(decoder.decode(value,{stream:!0}))}}function parseRequestData(data){if(typeof data!="string")return data;try{return JSON.parse(data)}catch{return data}}function parseQueryString(url2){let queryString=[];try{new URL(url2).searchParams.forEach((value,name)=>queryString.push({name,value}))}catch{}return queryString}function redactSensitiveHeaders(headers){let sensitiveNames=new Set(["authorization","cookie","proxy-authorization"]);return headers.map(header=>sensitiveNames.has(header.name.toLowerCase())?{...header,value:"<redacted>"}:header)}function createMtopStreamCapture(data){let timestampMs2=data.timestampMs??Date.now(),url2=data.url??`mtop://${data.api}/`;return{startTimeMs:timestampMs2,request:{id:data.id,timestamp:new Date(timestampMs2).toISOString(),timestampMs:timestampMs2,method:data.method,url:url2,apiName:data.api,status:0,statusText:"SSE Streaming",headers:redactSensitiveHeaders(data.requestHeaders??[]),responseHeaders:[],queryString:parseQueryString(url2),postData:parseRequestData(data.requestData??null),responseBody:[],isProxy:!0,proxyRequestUrl:null,proxyData:null,isSSE:!0,isPending:!0,...data.tabId!==void 0?{tabId:data.tabId}:{},source:"mtop",resourceType:"fetch",captureSequence:data.captureSequence}}}function updateMtopStreamCaptureResponse(capture,response){capture.request.status=response.status,capture.request.statusText=response.statusText,capture.request.responseHeaders=response.responseHeaders}function appendMtopStreamCaptureChunk(capture,data,timestampMs2=Date.now()){return Array.isArray(capture.request.responseBody)?(capture.request.responseBody.push({event:"message",data,timestamp:timestampMs2,duration:capture.lastMessageTimeMs===void 0?0:timestampMs2-capture.lastMessageTimeMs}),capture.lastMessageTimeMs=timestampMs2,!0):!1}function finishMtopStreamCapture(capture,options={}){let timestampMs2=options.timestampMs??Date.now();if(capture.request.isPending=!1,capture.request.duration=Math.max(0,timestampMs2-capture.startTimeMs),options.error){capture.request.statusText=options.error,Array.isArray(capture.request.responseBody)&&capture.request.responseBody.length===0&&(capture.request.responseBody={error:options.error});return}capture.request.status===0&&(capture.request.status=200),(!capture.request.statusText||capture.request.statusText==="SSE Streaming")&&(capture.request.statusText="OK")}function isAppProfileUserInfoUrl(url2){try{let target=new URL(url2);return(target.protocol==="http:"||target.protocol==="https:")&&(target.hostname==="taobao.com"||target.hostname.endsWith(".taobao.com"))}catch{return!1}}function decodeCookieValue(raw){let value=raw;for(let index=0;index<2;index+=1)try{let decoded=decodeURIComponent(value);if(decoded===value)break;value=decoded}catch{break}return value.replace(/\\u([0-9a-f]{4})/gi,(_match,hex3)=>String.fromCharCode(Number.parseInt(hex3,16)))}function firstCookieValue(cookies,name){let value=cookies.find(cookie=>cookie.name===name&&cookie.value&&cookie.value!=="null")?.value;return value?decodeCookieValue(value):""}function resolveAppProfileUserInfo(url2,cookies){if(!isAppProfileUserInfoUrl(url2))return{};let userId=firstCookieValue(cookies,"unb"),userName=["_w_tb_nick","_nk_","snk","tracknick"].map(name=>firstCookieValue(cookies,name)).find(Boolean);return{...userId&&{userId},...userName&&{userName}}}var APLUS_URL_PATTERN=/\.mmstat\.com\//,RUM_URL_PATTERN=/\.rum\.aliyuncs\.com\//,ARMS_URL_PATTERN=/arms-retcode\.aliyuncs\.com\//;function isTrackingUrl(url2){return APLUS_URL_PATTERN.test(url2)||RUM_URL_PATTERN.test(url2)||ARMS_URL_PATTERN.test(url2)||/retcode\.alicdn\.com|beacon\.taobao\.com|tbsec\./i.test(url2)}var aplusCounter=0,armsCounter=0,rumCounter=0;function formatTimestamp(ms){let d=new Date(ms),pad=n=>String(n).padStart(2,"0");return`${d.getFullYear()}/${pad(d.getMonth()+1)}/${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`}function parseParams(value){let params={};return value.split("&").forEach(pair=>{let eqIndex=pair.indexOf("=");if(eqIndex===-1)return;let rawKey=pair.slice(0,eqIndex),rawValue=pair.slice(eqIndex+1);try{params[decodeURIComponent(rawKey)]=rawValue}catch{params[rawKey]=rawValue}}),params}function decodeParamValue(value){try{return decodeURIComponent(value)}catch{return value}}function parseJsonParamValue(value){try{return JSON.parse(value)}catch{let decoded=decodeParamValue(value);if(decoded===value)return;try{return JSON.parse(decoded)}catch{return}}}function parseUrlParams(search){let encodedParams=parseParams(search.startsWith("?")?search.slice(1):search);return Object.fromEntries(Object.entries(encodedParams).map(([key,value])=>[key,decodeParamValue(value)]))}function extractSpmFromUrl(spmOrUrl){if(!/^https?:\/\//i.test(spmOrUrl))return spmOrUrl;try{return new URL(spmOrUrl).searchParams.get("spm")??spmOrUrl}catch{return spmOrUrl}}function resolveAplusSpm(eventType,raw){let expSpm=(Array.isArray(raw.expdata)?raw.expdata:[])[0]?.spm||"",gokeyParams=parseParams(raw.gokey||""),gokeySpm=decodeParamValue(gokeyParams.spm||""),rawSpmUrl=raw["spm-url"]||decodeParamValue(gokeyParams["spm-url"]||""),spmUrl=extractSpmFromUrl(rawSpmUrl),pointSpm;switch(eventType){case"CLK":pointSpm=gokeySpm||expSpm;break;case"EXP":pointSpm=expSpm;break;case"PV":pointSpm=spmUrl;break;default:pointSpm=gokeySpm||expSpm}return{mainSpm:pointSpm,highlightSpm:pointSpm}}function parseAplusRequest(url2,options={}){if(!APLUS_URL_PATTERN.test(url2))return null;let urlObj;try{urlObj=new URL(url2)}catch{return null}let params=parseUrlParams(urlObj.search),gmkey=params.gmkey??"UNKNOWN",urlPathName=urlObj.pathname.slice(1),eventType=urlPathName.split(".")[1]==="selfdefine"?"SDF":gmkey,gokeyRaw=params.gokey??"",gokeyParams=parseParams(gokeyRaw),expdata=[];if(gokeyParams.expdata){let parsedExpdata=parseJsonParamValue(gokeyParams.expdata);Array.isArray(parsedExpdata)&&(expdata=parsedExpdata.map(item=>{if(!item?.exargs||typeof item.exargs!="object")return item;let decoded={};for(let[key,value]of Object.entries(item.exargs)){if(typeof value!="string"){decoded[key]=value;continue}let parsedValue=parseJsonParamValue(value);decoded[key]=parsedValue===void 0?value:parsedValue}return{...item,exargs:decoded}}))}let rawBizArgs=gokeyParams.bizArgs,parsedBizArgs=rawBizArgs===void 0?void 0:parseJsonParamValue(rawBizArgs),bizArgs=parsedBizArgs===void 0?rawBizArgs:parsedBizArgs,pageUrl=params._p_url??(gokeyParams._p_url?decodeParamValue(gokeyParams._p_url):""),{gokey:rawGokey,...topLevelParams}=params,rawData={...topLevelParams,_path:urlPathName,_url:url2,gokey:rawGokey,...expdata.length>0?{expdata}:{},...bizArgs!==void 0?{bizArgs}:{}},spm=resolveAplusSpm(eventType,rawData).mainSpm,pathName=urlPathName.split(".").slice(1).join("."),eventName=eventType==="SDF"?pathName:spm||pathName||pageUrl,now=options.now??Date.now();return{id:`aplus-${options.sequence??++aplusCounter}-${now}`,source:"aplus",batchId:0,batchTimestampMs:now,batchTimestamp:formatTimestamp(now),event_type:eventType,name:eventName,url:url2,timestamp:now,_raw:rawData,_context:{requestUrl:url2,app:{},user:{...params.uidaplus?{uidaplus:params.uidaplus}:{},...params._gr_uid_?{_gr_uid_:params._gr_uid_}:{}},session:{},view:{...params["spm-url"]?{"spm-url":params["spm-url"]}:{},...params["spm-pre"]?{"spm-pre":params["spm-pre"]}:{},...params["spm-cnt"]?{"spm-cnt":params["spm-cnt"]}:{},...pageUrl?{page_url:pageUrl}:{}},properties:{},os:{},net:{}}}}var RUM_TYPE_ALIAS={cst:"custom"},I18N_TRACKER_TYPE_MAP={"i18n-tracker-exp":"EXP","i18n-tracker-clk":"CLK"};function parseRumBody(postData){if(!postData)return null;if(typeof postData=="object")return postData;try{return JSON.parse(postData)}catch{return null}}function tryConvertI18nTracker(event,base){let normalizedType=RUM_TYPE_ALIAS[event.type]??event.type;if(event.event_type!=="action"||normalizedType!=="custom")return null;let snapshots;try{snapshots=typeof event.snapshots=="string"?JSON.parse(event.snapshots):event.snapshots}catch{return null}if(!snapshots||typeof snapshots!="object")return null;let eventType=I18N_TRACKER_TYPE_MAP[snapshots.message];if(!eventType)return null;let spm=[snapshots.c1??"",snapshots.c2??""].filter(Boolean).join("."),exargs={};typeof snapshots.c3=="string"&&snapshots.c3.split("&").forEach(pair=>{let eqIndex=pair.indexOf("=");if(eqIndex===-1)return;let key=pair.slice(0,eqIndex),rawValue=pair.slice(eqIndex+1);try{exargs[key]=JSON.parse(decodeURIComponent(rawValue))}catch{exargs[key]=rawValue}});let dataAttrs=snapshots.trackerInfo?.dataAttrs;if(dataAttrs&&typeof dataAttrs=="object"&&dataAttrs["data-biz-args"]&&!exargs.bizArgs)try{exargs.bizArgs=JSON.parse(dataAttrs["data-biz-args"])}catch{exargs.bizArgs=dataAttrs["data-biz-args"]}return{...base,event_type:eventType,name:spm,_raw:{...event,expdata:[{spm,...Object.keys(exargs).length>0?{exargs}:{}}],"spm-url":spm}}}function parseRumRequest(url2,postData,options={}){if(!RUM_URL_PATTERN.test(url2))return[];let parsed=parseRumBody(postData),rawEvents=Array.isArray(parsed?.events)?parsed.events:[];if(rawEvents.length===0)return[];let now=options.now??Date.now(),batchId=options.sequence??++rumCounter,context={requestUrl:url2,app:parsed?.app??{},user:parsed?.user??{},session:parsed?.session??{},view:parsed?.view??{},properties:parsed?.properties??{},os:parsed?.os??{},net:parsed?.net??{}};return rawEvents.flatMap((rawEvent,index)=>{if(!rawEvent||typeof rawEvent!="object"||Array.isArray(rawEvent))return[];let event=rawEvent,normalizedType=RUM_TYPE_ALIAS[event.type]??event.type,base={id:`${batchId}-${event.event_id??index}`,batchId,batchTimestampMs:now,batchTimestamp:formatTimestamp(now),type:normalizedType,url:event.url,timestamp:event.timestamp??now,success:event.success,status_code:event.status_code,method:event.method,duration:event.duration,source:"rum",_context:context},converted=tryConvertI18nTracker(event,base);return converted?[converted]:[{...base,event_type:event.event_type??"unknown",name:event.name,_raw:event}]})}function parseArmsRequest(url2,options={}){if(!ARMS_URL_PATTERN.test(url2))return null;let urlObj;try{urlObj=new URL(url2)}catch{return null}let params={};urlObj.searchParams.forEach((value,key)=>{params[key]=value});let eventType=(params.t??"unknown").toLowerCase(),page=params.page??"",now=options.now??Date.now(),sequence=options.sequence??++armsCounter,parsedTimestamp2=params.begin?Number.parseInt(params.begin,10):now,timestamp=Number.isFinite(parsedTimestamp2)?parsedTimestamp2:now;return{id:`arms-${sequence}-${now}`,source:"arms",batchId:0,batchTimestampMs:now,batchTimestamp:formatTimestamp(now),event_type:eventType,name:page||url2,url:url2,timestamp,_raw:{...params,_url:url2},_context:{requestUrl:url2,app:{...params.pid?{pid:params.pid}:{},...params.release?{release:params.release}:{},...params.environment?{environment:params.environment}:{},...params._v?{sdk_version:params._v}:{}},user:{...params.uid?{uid:params.uid}:{}},session:{...params.sid?{sid:params.sid}:{}},view:{...page?{page}:{},...params.tag?{tag:params.tag}:{}},properties:{},os:{},net:{...params.ct?{ct:params.ct}:{}}}}}function parseTrackingRequest(url2,postData,options={}){let rumEvents=parseRumRequest(url2,postData,options);if(rumEvents.length>0)return rumEvents;let aplusEvent=parseAplusRequest(url2,options);if(aplusEvent)return[aplusEvent];let armsEvent=parseArmsRequest(url2,options);return armsEvent?[armsEvent]:[]}var CURSOR_PREFIX="mearl-capture-v1";function createCaptureGeneration(){return crypto.randomUUID()}function encodeCaptureCursor(cursor){return`${CURSOR_PREFIX}:${cursor.tabId}:${cursor.generation}:${cursor.scope}:${cursor.sequence}`}function decodeCaptureCursor(value){let match=value.match(/^mearl-capture-v1:(\d+):([^:]+):(all|logs|requests|events):(\d+)$/);if(!match)throw new Error("Invalid capture cursor");let tabId=Number(match[1]),sequence=Number(match[4]);if(!Number.isSafeInteger(tabId)||!Number.isSafeInteger(sequence))throw new Error("Invalid capture cursor");return{tabId,generation:match[2],scope:match[3],sequence}}function captureCheckpoint(state){return encodeCaptureCursor({tabId:state.tabId,generation:state.generation,sequence:state.currentSequence,scope:"all"})}function nextCaptureSequence(state){return state.currentSequence+=1,state.currentSequence}function resolveAfterSequence(after,state,scope){if(!after)return 0;let cursor=decodeCaptureCursor(after);if(cursor.tabId!==state.tabId)throw new Error(`Capture cursor belongs to tab ${cursor.tabId}, not tab ${state.tabId}`);if(cursor.generation!==state.generation)throw new Error("Capture cursor expired because the tab collector was restarted");if(cursor.scope!=="all"&&cursor.scope!==scope)throw new Error(`Capture cursor is scoped to ${cursor.scope}, not ${scope}`);if(cursor.sequence>state.currentSequence)throw new Error("Capture cursor is ahead of the current collector state");return cursor.sequence}function queryCapturedEntries(buffer,state,options,matches,droppedThroughSequence=0,scope="all"){let{after,since,now=Date.now()}=options,limit=Math.max(1,Math.floor(options.limit??100)),afterSequence=resolveAfterSequence(after,state,scope),sinceTimestampMs=since===void 0?void 0:now-since*1e3,matched=buffer.filter(entry=>entry.captureSequence>afterSequence&&(sinceTimestampMs===void 0||entry.timestampMs>=sinceTimestampMs)&&matches(entry)),hasMore=matched.length>limit,entries=after?matched.slice(0,limit):matched.slice(-limit),nextSequence=after&&hasMore&&entries.length>0?entries[entries.length-1].captureSequence:state.currentSequence;return{entries,totalMatched:matched.length,nextCursor:encodeCaptureCursor({tabId:state.tabId,generation:state.generation,sequence:nextSequence,scope}),hasMore,gap:after!==void 0&&afterSequence<droppedThroughSequence}}var TRACKING_CAPTURE_ARMED_HINT="Event capture is active, but this tab has no captured history yet. Reload the current tab or repeat the triggering action, then call get_events again.";function compileTextPattern(value){try{return{regex:new RegExp(value,"i"),fallback:""}}catch{return{regex:null,fallback:value.toLowerCase()}}}function matchesTextPattern(value,pattern){return value?pattern.regex?pattern.regex.test(value):value.toLowerCase().includes(pattern.fallback):!1}function compactEventUrl(value){if(value)try{let url2=new URL(value);return url2.origin==="null"?value.split(/[?#]/,1)[0]:`${url2.origin}${url2.pathname}`}catch{return value.split(/[?#]/,1)[0]}}function formatTrackingEvent(event,includeRaw=!1){let{captureSequence:_discardedCaptureSequence,...publicEvent}=event;if(includeRaw)return publicEvent;let{_raw:_discardedRaw,_context,url:url2,...summary}=publicEvent,compactUrl=compactEventUrl(url2??_context.requestUrl);return{...summary,...compactUrl?{url:compactUrl}:{}}}function matchesTrackingEvent(event,options){let{source="all",event_type,filter}=options;if(source!=="all"&&event.source!==source||event_type&&!matchesTextPattern(event.event_type,compileTextPattern(event_type)))return!1;if(filter){let pattern=compileTextPattern(filter);if(!matchesTextPattern(event.name,pattern)&&!matchesTextPattern(event.url,pattern))return!1}return!0}function queryTrackingEvents(buffer,options={}){let{source="all",event_type,filter,since,limit=20,now=Date.now()}=options,events=[...buffer].reverse();if(source!=="all"&&(events=events.filter(event=>event.source===source)),since!==void 0){let sinceTimestamp=now-since*1e3;events=events.filter(event=>event.batchTimestampMs>=sinceTimestamp)}if(event_type){let pattern=compileTextPattern(event_type);events=events.filter(event=>matchesTextPattern(event.event_type,pattern))}if(filter){let pattern=compileTextPattern(filter);events=events.filter(event=>matchesTextPattern(event.name,pattern)||matchesTextPattern(event.url,pattern))}return{events:events.slice(0,limit),totalMatched:events.length,totalInBuffer:buffer.length}}function appendCapturedTrackingBatch(buffer,events,maxSize){if(events.length===0)return[];let captureSequence=events[0].captureSequence,insertionIndex=Number.isSafeInteger(captureSequence)?buffer.findIndex(event=>Number.isSafeInteger(event.captureSequence)&&event.captureSequence>captureSequence):-1;if(buffer.splice(insertionIndex<0?buffer.length:insertionIndex,0,...events),buffer.length<=maxSize)return[];let removeCount=buffer.length-maxSize,boundarySequence=buffer[removeCount-1]?.captureSequence;for(;boundarySequence!==void 0&&buffer[removeCount]?.captureSequence===boundarySequence;)removeCount+=1;return buffer.splice(0,removeCount)}function queryCapturedTrackingEvents(buffer,state,options={},droppedThroughSequence=0){let limit=Math.max(1,Math.floor(options.limit??20));if(!options.after){let snapshot=queryTrackingEvents(buffer,options);return{...snapshot,nextCursor:encodeCaptureCursor({tabId:state.tabId,generation:state.generation,sequence:state.currentSequence,scope:"events"}),hasMore:snapshot.totalMatched>limit,gap:!1}}let sinceTimestampMs=options.since===void 0?void 0:(options.now??Date.now())-options.since*1e3,batchesBySequence=new Map;for(let event of buffer){if(!Number.isSafeInteger(event.captureSequence)||sinceTimestampMs!==void 0&&event.batchTimestampMs<sinceTimestampMs||!matchesTrackingEvent(event,options))continue;let captureSequence=event.captureSequence,batch=batchesBySequence.get(captureSequence);batch?batch.events.push(event):batchesBySequence.set(captureSequence,{captureSequence,timestampMs:event.batchTimestampMs,events:[event]})}let batches=[...batchesBySequence.values()].sort((left,right)=>left.captureSequence-right.captureSequence),captured=queryCapturedEntries(batches,state,{after:options.after,limit:Number.MAX_SAFE_INTEGER},()=>!0,droppedThroughSequence,"events"),selected=[],selectedCount=0;for(let batch of captured.entries){if(selected.length>0&&selectedCount+batch.events.length>limit)break;selected.push(batch),selectedCount+=batch.events.length}let hasMore=selected.length<captured.entries.length,nextSequence=hasMore?selected[selected.length-1].captureSequence:state.currentSequence;return{events:selected.flatMap(batch=>batch.events),totalMatched:captured.entries.reduce((total,batch)=>total+batch.events.length,0),totalInBuffer:buffer.length,nextCursor:encodeCaptureCursor({tabId:state.tabId,generation:state.generation,sequence:nextSequence,scope:"events"}),hasMore,gap:captured.gap}}function parsePath(path19){if(path19.length>1e3)throw new Error("Path too long: maximum 1000 characters allowed");let keys=[],current="";for(let i=0;i<path19.length;i++){let char=path19[i];if(char===".")current&&(keys.push(current),current="");else if(char==="["){current&&(keys.push(current),current="");let j=i+1;for(;j<path19.length&&path19[j]!=="]";)j++;if(j<path19.length){let index=parseInt(path19.substring(i+1,j),10);if(!isNaN(index)){if(index<0||index>1e5)throw new Error(`Array index out of safe range: ${index}`);keys.push(index)}i=j}}else current+=char}if(current&&keys.push(current),keys.length>50)throw new Error("Path too deep: maximum 50 levels allowed");return keys}function getValueByPath(obj,path19){let keys=parsePath(path19),current=obj;for(let key of keys){if(current==null)return;current=current[key]}return current}function setValueByPath(obj,path19,value){let keys=parsePath(path19),current=obj;for(let i=0;i<keys.length-1;i++){let key=keys[i],nextKey=keys[i+1];(current[key]===null||current[key]===void 0)&&(current[key]=typeof nextKey=="number"?[]:{}),current=current[key]}current[keys[keys.length-1]]=value}function getStructure(data,maxDepth=5,currentDepth=0){if(currentDepth>=maxDepth)return"<max depth reached>";if(data===null)return"null";if(data===void 0)return"undefined";let type=typeof data;if(type==="string"||type==="number"||type==="boolean")return type;if(Array.isArray(data))return data.length===0?"array[0]":{_type:`array[${data.length}]`,_sample:getStructure(data[0],maxDepth,currentDepth+1)};if(type==="object"){let structure={};for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&(structure[key]=getStructure(data[key],maxDepth,currentDepth+1));return structure}return type}function truncateData(data,maxSize){let str=JSON.stringify(data);if(str.length<=maxSize)return data;let truncated=str.substring(0,maxSize);return`<truncated: ${str.length} bytes, showing first ${maxSize} chars>
45
45
  ${truncated}...`}function extractFields(data,fields){if(fields.length>100)throw new Error("Too many fields: maximum 100 fields allowed");let result={};for(let fieldPath of fields)try{result[fieldPath]=getValueByPath(data,fieldPath)}catch(error48){result[fieldPath]=`<error: ${error48 instanceof Error?error48.message:"field not found"}>`}return result}function serializeRequest(request,options={}){let{includeBody=!0,includeHeaders=!1,maxBodySize=5e4,fields,keysOnly=!1}=options,result={id:request.id,timestamp:request.timestamp,timestampMs:request.timestampMs,method:request.method,url:request.url,apiName:request.apiName,status:request.status,statusText:request.statusText,queryString:request.queryString,duration:request.duration,captureSequence:request.captureSequence,isPending:request.isPending,isSSE:request.isSSE,source:request.source,resourceType:request.resourceType};return includeHeaders&&(result.headers=request.headers,result.responseHeaders=request.responseHeaders),keysOnly?(result.postDataStructure=request.postData?getStructure(request.postData):null,result.responseBodyStructure=request.responseBody?getStructure(request.responseBody):null,result):(includeBody&&request.postData!==null&&request.postData!==void 0?result.postData=truncateData(request.postData,maxBodySize):includeBody?result.postData=request.postData:result.postData="<omitted>",includeBody&&request.responseBody!==null&&request.responseBody!==void 0?result.responseBody=truncateData(request.responseBody,maxBodySize):includeBody?result.responseBody=request.responseBody:result.responseBody="<omitted>",fields&&fields.length>0&&(result.extractedFields=extractFields(request.responseBody,fields)),result)}var textEncoder=new TextEncoder;function byteLength(value){return textEncoder.encode(value).byteLength}function serializeForStorage(value){if(typeof value=="string")return value;try{return JSON.stringify(value)}catch{return String(value)}}function truncateUtf8(value,maxBytes){if(byteLength(value)<=maxBytes)return value;let low=0,high=Math.min(value.length,maxBytes);for(;low<high;){let middle=Math.ceil((low+high)/2);byteLength(value.slice(0,middle))<=maxBytes?low=middle:high=middle-1}return value.slice(0,low)}function limitBufferedField(value,maxBytes){if(value==null)return value;let serialized=serializeForStorage(value),originalBytes=byteLength(serialized);if(originalBytes<=maxBytes)return value;let marker=`<truncated: ${originalBytes} bytes, buffered preview>
46
46
  `;if(byteLength(marker)+3>maxBytes)return truncateUtf8(`${marker}...`,maxBytes);let previewBudget=Math.max(0,maxBytes-byteLength(marker)-3);return`${marker}${truncateUtf8(serialized,previewBudget)}...`}function estimateRequestBufferBytes(request){try{return byteLength(JSON.stringify(request))}catch{return byteLength(String(request))}}function createRequestBufferAccounting(){return{sizes:[],totalBytes:0}}function synchronizeAccounting(requests,accounting){accounting.sizes.length!==requests.length&&(accounting.sizes=requests.map(estimateRequestBufferBytes),accounting.totalBytes=accounting.sizes.reduce((total,size)=>total+size,0))}function applyFieldLimits(request,maxFieldBytes){request.postData=limitBufferedField(request.postData,maxFieldBytes),request.responseBody=limitBufferedField(request.responseBody,maxFieldBytes)}function trimRequestBuffer(requests,accounting,maxEntries,maxBytes){let removed=[];for(;requests.length>1&&(requests.length>maxEntries||accounting.totalBytes>maxBytes);){let request=requests.shift();request&&removed.push(request),accounting.totalBytes-=accounting.sizes.shift()??0}return removed}function appendRequestToBuffer(requests,accounting,request,limits={}){let{maxEntries=500,maxBytes=33554432,maxFieldBytes=8388608}=limits;synchronizeAccounting(requests,accounting),applyFieldLimits(request,maxFieldBytes);let size=estimateRequestBufferBytes(request);return requests.push(request),accounting.sizes.push(size),accounting.totalBytes+=size,trimRequestBuffer(requests,accounting,maxEntries,maxBytes)}function refreshRequestInBuffer(requests,accounting,request,limits={}){let{maxEntries=500,maxBytes=33554432,maxFieldBytes=8388608}=limits,index=requests.indexOf(request);if(index===-1)return[];synchronizeAccounting(requests,accounting),applyFieldLimits(request,maxFieldBytes);let previousSize=accounting.sizes[index]??0,nextSize=estimateRequestBufferBytes(request);return accounting.sizes[index]=nextSize,accounting.totalBytes+=nextSize-previousSize,trimRequestBuffer(requests,accounting,maxEntries,maxBytes)}var ALLOWED_ORIGINS=["*://localhost/*","*://127.0.0.1/*","*://*.alibaba.com/*","*://*.alibaba-inc.com/*","*://*.taobao.com/*","*://*.antfin.com/*","*://*.tmall.com/*","*://*.fliggy.com/*","*://*.alitrip.com/*","*://*.aliexpress.com/*","*://*.atatech.org/*","*://*.dingtalk.com/*","*://*.ele.me/*","*://*.effirst.com/*","*://*.example.com/*","*://*.figma.com/*"],ALLOWED_ORIGINS_LIST=[...ALLOWED_ORIGINS];function typeIntoElement(el,inputValue,shouldClear){if(!el)return{typed:!1,tag:"",error:"Element is null"};if(!el.isConnected)return{typed:!1,tag:"",error:"Element is detached from the document"};let tagName=el.tagName?el.tagName.toLowerCase():"",isInput=el instanceof HTMLInputElement,isTextArea=el instanceof HTMLTextAreaElement,isFormField=isInput||isTextArea,htmlEl=el,isEditable=!isFormField&&(htmlEl.isContentEditable||el.getAttribute("contenteditable")==="true");if(!isFormField&&!isEditable)return{typed:!1,tag:tagName,error:"Element <"+tagName+"> is neither an input/textarea nor contenteditable"};if(isFormField){let f=el;if(f.disabled)return{typed:!1,tag:tagName,error:"Element is disabled"};if(f.readOnly)return{typed:!1,tag:tagName,error:"Element is readOnly"}}if(htmlEl.scrollIntoView({block:"center",behavior:"instant"}),htmlEl.focus(),isFormField){let f=el,proto=isTextArea?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,nativeSetter=Object.getOwnPropertyDescriptor(proto,"value")?.set,setVal=v=>{nativeSetter?nativeSetter.call(f,v):f.value=v};return shouldClear&&f.value!==""&&(setVal(""),f.dispatchEvent(new Event("input",{bubbles:!0}))),setVal(inputValue),f.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,data:inputValue,inputType:"insertText"})),f.dispatchEvent(new InputEvent("input",{bubbles:!0,data:inputValue,inputType:"insertText"})),f.dispatchEvent(new Event("change",{bubbles:!0})),{typed:!0,tag:tagName}}let selection=window.getSelection();if(shouldClear){if(selection){let range=document.createRange();range.selectNodeContents(htmlEl),selection.removeAllRanges(),selection.addRange(range)}let cleared;try{cleared=document.execCommand("delete")}catch{cleared=!1}cleared||(htmlEl.textContent="")}else if(selection){let range=document.createRange();range.selectNodeContents(htmlEl),range.collapse(!1),selection.removeAllRanges(),selection.addRange(range)}htmlEl.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,data:inputValue,inputType:"insertText"}));let inserted;try{inserted=document.execCommand("insertText",!1,inputValue)}catch{inserted=!1}return inserted||(htmlEl.textContent=(htmlEl.textContent??"")+inputValue),htmlEl.dispatchEvent(new InputEvent("input",{bubbles:!0,data:inputValue,inputType:"insertText"})),{typed:!0,tag:tagName}}var UNSUPPORTED_NATIVE_SELECTOR_PSEUDOS=[":has-text",":text(",":text-is(",":text-matches(",":visible",":hidden",":nth-match(",":light(",":above(",":below(",":near(",":left-of(",":right-of(",":contains("],INVALID_NATIVE_SELECTOR_HINT='Only native CSS is supported (no Playwright extensions like :has-text/:visible). Use page_snapshot to get an "@eN" ref for complex matching.';function validatePageElementSelector(selector,toolName){if(!selector||typeof selector!="string")throw new Error(`${toolName}: "selector" must be a non-empty string. Pass a native CSS selector (e.g. "[aria-label='提交']") or a snapshot ref like "@e3". Note: the field name is "selector", not "ref".`);if(/^e\d+$/.test(selector))throw new Error(`${toolName}: selector "${selector}" looks like a snapshot ref but is missing the "@" prefix. Use "@${selector}" instead. If you don't have refs yet, call page_snapshot first.`);for(let pseudo of UNSUPPORTED_NATIVE_SELECTOR_PSEUDOS)if(selector.includes(pseudo))throw new Error(`${toolName}: selector contains unsupported pseudo "${pseudo}". Only native CSS selectors are supported (no Playwright/jQuery extensions). For text-based matching, run page_snapshot and use the returned "@eN" ref. For attribute matching, prefer "[aria-label='...']", "[title='...']", "[data-testid='...']" etc.`)}function resolvePageScrollInput(data){let{direction,distance,selector,containerPolicy="self"}=data;if(typeof direction!="string"||!["up","down","top","bottom"].includes(direction))throw new Error("Invalid direction: must be one of up, down, top, bottom");if(distance!==void 0&&(typeof distance!="number"||!Number.isFinite(distance)))throw new Error('"distance" must be a finite number');if(selector!==void 0&&validatePageElementSelector(selector,"page_scroll"),containerPolicy!=="self"&&containerPolicy!=="nearest")throw new Error('"containerPolicy" must be one of self, nearest');return{direction,distance:Math.abs(distance??600),containerPolicy,...selector!==void 0?{selector}:{}}}function scrollElementInPage(direction,distance,targetLabel,containerPolicy="self"){let element=this?.nodeType===3?this.parentElement:this;if(element?.nodeType===9&&(element=element.scrollingElement),!element||element.isConnected===!1)return{error:"Cannot resolve scroll container: "+targetLabel};let startingElement=element,ancestorDistance=0;function scrollMetrics(candidate){let scrollTop=Number(candidate?.scrollTop),scrollHeight=Number(candidate?.scrollHeight),clientHeight=Number(candidate?.clientHeight);if(!Number.isFinite(scrollTop)||!Number.isFinite(scrollHeight)||!Number.isFinite(clientHeight))return null;let ownerDocument=candidate.ownerDocument,isRootScroller=!!ownerDocument&&candidate===ownerDocument.scrollingElement,maxScrollTop=Math.max(0,scrollHeight-clientHeight),overflowAllowsScroll=!0;try{let overflowY=ownerDocument?.defaultView?.getComputedStyle(candidate).overflowY;!isRootScroller&&(overflowY==="visible"||overflowY==="clip")&&(overflowAllowsScroll=!1)}catch{}return{scrollTop,scrollHeight,clientHeight,maxScrollTop,isRootScroller,usable:isRootScroller||maxScrollTop>0&&overflowAllowsScroll}}let metrics=scrollMetrics(element);if(!metrics)return{error:"Element is not scrollable: "+targetLabel};if(!metrics.usable&&containerPolicy==="nearest"){let candidate=element.parentElement;for(;candidate;){ancestorDistance+=1;let candidateMetrics=scrollMetrics(candidate);if(candidateMetrics?.usable){element=candidate,metrics=candidateMetrics;break}candidate=candidate.parentElement}}if(!metrics.usable&&!metrics.isRootScroller)return{error:"Element is not scrollable: "+targetLabel+(containerPolicy==="nearest"?" (no scrollable ancestor found)":"")};let targetTop;switch(direction){case"top":targetTop=0;break;case"bottom":targetTop=metrics.maxScrollTop;break;case"up":targetTop=Math.max(0,metrics.scrollTop-Math.abs(distance));break;default:targetTop=Math.min(metrics.maxScrollTop,metrics.scrollTop+Math.abs(distance));break}if(typeof element.scrollTo=="function")try{element.scrollTo({top:targetTop,left:Number(element.scrollLeft)||0,behavior:"instant"})}catch{element.scrollTop=targetTop}else element.scrollTop=targetTop;let actualScrollTop=Number(element.scrollTop);return!metrics.isRootScroller&&targetTop!==metrics.scrollTop&&actualScrollTop===metrics.scrollTop?{error:"Element is not scrollable: "+targetLabel}:{scrollY:Math.round(actualScrollTop),scrollHeight:metrics.scrollHeight,clientHeight:metrics.clientHeight,maxScrollY:Math.round(metrics.maxScrollTop),scrollYBefore:Math.round(metrics.scrollTop),scrollYAfter:Math.round(actualScrollTop),moved:actualScrollTop!==metrics.scrollTop,atTop:actualScrollTop<=0,atBottom:actualScrollTop>=metrics.maxScrollTop,target:targetLabel,resolvedContainer:element===startingElement?"self":"nearest-scrollable-ancestor",ancestorDistance}}var SCROLL_ELEMENT_IN_PAGE_SOURCE=scrollElementInPage.toString();function buildPageScrollExpression(input){return`(() => {
47
47
  const dir = ${JSON.stringify(input.direction)};
@@ -75,7 +75,7 @@ ${truncated}...`}function extractFields(data,fields){if(fields.length>100)throw
75
75
  `};function createControlledFaviconDataUrl(source){let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128" data-control-source="${source}">
76
76
  ${BASE_ICON}
77
77
  ${SOURCE_BADGES[source]}
78
- </svg>`;return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`}var enabledDomains=new WeakMap;function ensureCdpDomain(client2,domain2,params={}){let domains=enabledDomains.get(client2);domains||(domains=new Map,enabledDomains.set(client2,domains));let existing=domains.get(domain2);if(existing)return existing;let enabling=client2.sendCommand(`${domain2}.enable`,params).then(()=>{}).catch(error48=>{throw domains?.get(domain2)===enabling&&domains.delete(domain2),error48});return domains.set(domain2,enabling),enabling}var MAX_LOGS=500,MAX_EVENTS=500,COLLECTED_RESOURCE_TYPES=new Set(["xhr","fetch","document","eventsource"]);function createBuffers(tabId=0){return{requests:[],logs:[],events:[],pending:new Map,sseStreams:new Map,requestCounter:0,requestBufferAccounting:createRequestBufferAccounting(),capture:{tabId,generation:createCaptureGeneration(),currentSequence:0,droppedRequestsThroughSequence:0,droppedLogsThroughSequence:0,droppedEventsThroughSequence:0}}}function parseQueryString2(url2){try{let u=new URL(url2),result=[];return u.searchParams.forEach((value,name)=>result.push({name,value})),result}catch{return[]}}function headersObjToArray(obj){return Object.entries(obj).map(([name,value])=>({name,value:String(value)}))}function getHeaderValue(headers,targetName){let target=targetName.toLowerCase(),entry=Object.entries(headers).find(([name])=>name.toLowerCase()===target);return entry?String(entry[1]):""}function extractMtopApiName(url2,postData){try{let u=new URL(url2),pathMatch=u.pathname.match(/\/h5\/([\w.]+)\//);if(pathMatch)return pathMatch[1];let proxyMatch=u.searchParams.get("requestUrl")?.match(/\b(?:mtop|mopen)\.[\w.]+/);if(proxyMatch)return proxyMatch[0]}catch{}let urlMatch=url2.match(/\b(?:mtop|mopen)\.[\w.]+/);if(urlMatch)return urlMatch[0];if(!postData)return null;try{let parsed=JSON.parse(postData),proxyMatch=(typeof parsed?.requestUrl=="string"?parsed.requestUrl:void 0)?.match(/\b(?:mtop|mopen)\.[\w.]+/);if(proxyMatch)return proxyMatch[0]}catch{let proxyMatch=new URLSearchParams(postData).get("requestUrl")?.match(/\b(?:mtop|mopen)\.[\w.]+/);if(proxyMatch)return proxyMatch[0]}return null}function requestDisplayName(url2){try{return new URL(url2).pathname}catch{return url2}}function parsePostData(postData){if(!postData)return null;try{return JSON.parse(postData)}catch{try{let params={};return new URLSearchParams(postData).forEach((v,k)=>params[k]=v),params}catch{return postData}}}function appendTrackingEvents(buffers,url2,postData,batchSequence,captureSequence){let events=parseTrackingRequest(url2,postData,{sequence:batchSequence,now:Date.now()}).map(event=>({...event,captureSequence}));if(events.length===0)return!1;let removed=appendCapturedTrackingBatch(buffers.events,events,MAX_EVENTS);for(let event of removed)event.captureSequence!==void 0&&(buffers.capture.droppedEventsThroughSequence=Math.max(buffers.capture.droppedEventsThroughSequence,event.captureSequence));return!0}function recordDroppedRequests(buffers,removed){for(let request of removed)request.captureSequence!==void 0&&(buffers.capture.droppedRequestsThroughSequence=Math.max(buffers.capture.droppedRequestsThroughSequence,request.captureSequence))}function appendCapturedRequest(buffers,request){recordDroppedRequests(buffers,appendRequestToBuffer(buffers.requests,buffers.requestBufferAccounting,request))}function refreshCapturedRequest(buffers,request){recordDroppedRequests(buffers,refreshRequestInBuffer(buffers.requests,buffers.requestBufferAccounting,request))}function recordCdpMtopStreamStart(buffers,data){let capture=createMtopStreamCapture({...data,id:++buffers.requestCounter,tabId:buffers.capture.tabId,captureSequence:nextCaptureSequence(buffers.capture)});return appendCapturedRequest(buffers,capture.request),capture}function recordCdpMtopStreamResponse(buffers,capture,response){updateMtopStreamCaptureResponse(capture,response),refreshCapturedRequest(buffers,capture.request)}function recordCdpMtopStreamChunk(buffers,capture,data,timestampMs2=Date.now()){appendMtopStreamCaptureChunk(capture,data,timestampMs2)&&refreshCapturedRequest(buffers,capture.request)}function recordCdpMtopStreamEnd(buffers,capture,options={}){finishMtopStreamCapture(capture,options),refreshCapturedRequest(buffers,capture.request)}function requestEventTimestamp(partial2,monotonicTimestamp){return monotonicTimestamp!==void 0&&partial2.startTs!==void 0?Math.round(partial2.timestampMs+(monotonicTimestamp-partial2.startTs)*1e3):Date.now()}function ensurePageSseStream(buffers,partial2,mode){partial2.isSSE=!0,Array.isArray(partial2.responseBody)||(partial2.responseBody=[]);let existing=buffers.sseStreams.get(partial2.requestId);if(existing)return existing;let stream={parser:createSseEventParser(),decoder:new TextDecoder2,mode};return buffers.sseStreams.set(partial2.requestId,stream),stream}function appendPageSseEvents(buffers,partial2,stream,events,timestampMs2){if(Array.isArray(partial2.responseBody)){for(let event of events)partial2.responseBody.push({event:event.event,data:event.data,...event.eventId!==void 0?{eventId:event.eventId}:{},timestamp:timestampMs2,duration:stream.lastMessageTimeMs===void 0?0:timestampMs2-stream.lastMessageTimeMs}),stream.lastMessageTimeMs=timestampMs2;events.length>0&&refreshCapturedRequest(buffers,partial2)}}function consumePageSseBytes(buffers,partial2,stream,bytes,timestampMs2){let text=stream.decoder.decode(bytes,{stream:!0});appendPageSseEvents(buffers,partial2,stream,stream.parser.push(text),timestampMs2)}function finishPageSseStream(buffers,partial2,stream,timestampMs2){let tail=stream.decoder.decode(),events=[...stream.parser.push(tail),...stream.parser.finish()];appendPageSseEvents(buffers,partial2,stream,events,timestampMs2)}function replaceWithParsedSseBody(partial2,body,timestampMs2){let parser=createSseEventParser();partial2.responseBody=[...parser.push(body),...parser.finish()].map(event=>({event:event.event,data:event.data,...event.eventId!==void 0?{eventId:event.eventId}:{},timestamp:timestampMs2,duration:0}))}function appendCapturedLog(buffers,log2){if(buffers.logs.push({...log2,captureSequence:nextCaptureSequence(buffers.capture)}),buffers.logs.length>MAX_LOGS){let removed=buffers.logs.shift();removed&&(buffers.capture.droppedLogsThroughSequence=removed.captureSequence)}}async function setupBufferListeners(client2,buffers){client2.on("Network.requestWillBeSent",params=>{let url2=params.request?.url??"";if(!url2.startsWith("http"))return;if(isTrackingUrl(url2)){let batchSequence=++buffers.requestCounter,captureSequence2=nextCaptureSequence(buffers.capture);!appendTrackingEvents(buffers,url2,params.request?.postData,batchSequence,captureSequence2)&&params.request?.hasPostData&&!params.request?.postData&&client2.sendCommand("Network.getRequestPostData",{requestId:params.requestId},1e4).then(result=>appendTrackingEvents(buffers,url2,result?.postData,batchSequence,captureSequence2)).catch(()=>{});return}let resourceType=String(params.type??"").toLowerCase(),mtopApiName=extractMtopApiName(url2,params.request?.postData),isMtop=mtopApiName!==null;if(!isMtop&&!COLLECTED_RESOURCE_TYPES.has(resourceType))return;let ts=params.timestamp,timestampMs2=params.wallTime!==void 0?Math.floor(params.wallTime*1e3):Date.now(),redirected=buffers.pending.get(params.requestId);redirected&&params.redirectResponse&&(redirected.status=params.redirectResponse.status??0,redirected.statusText=params.redirectResponse.statusText??"",redirected.duration=ts!==void 0&&redirected.startTs!==void 0?Math.round((ts-redirected.startTs)*1e3):void 0,redirected.isPending=!1,refreshCapturedRequest(buffers,redirected),buffers.pending.delete(params.requestId),buffers.sseStreams.delete(params.requestId));let id=++buffers.requestCounter,captureSequence=nextCaptureSequence(buffers.capture),partial2={id,requestId:params.requestId,timestamp:new Date(timestampMs2).toISOString(),timestampMs:timestampMs2,method:params.request?.method??"GET",url:url2,apiName:mtopApiName??requestDisplayName(url2),headers:headersObjToArray(params.request?.headers??{}),postData:parsePostData(params.request?.postData),queryString:parseQueryString2(url2),status:0,statusText:"",responseHeaders:[],responseBody:resourceType==="eventsource"?[]:null,isProxy:!1,proxyRequestUrl:null,proxyData:null,startTs:ts,captureSequence,isPending:!0,isSSE:resourceType==="eventsource",source:isMtop?"mtop":"requests",resourceType};buffers.pending.set(params.requestId,partial2),appendCapturedRequest(buffers,partial2)}),client2.on("Network.responseReceived",params=>{let partial2=buffers.pending.get(params.requestId);if(!partial2)return;partial2.status=params.response?.status??0,partial2.statusText=params.response?.statusText??"",partial2.responseHeaders=headersObjToArray(params.response?.headers??{});let contentType=getHeaderValue(params.response?.headers??{},"content-type");if(partial2.resourceType==="eventsource"||contentType.toLowerCase().includes("text/event-stream")){let mode=partial2.resourceType==="eventsource"?"eventsource":"resource",stream=ensurePageSseStream(buffers,partial2,mode);mode==="resource"&&client2.sendCommand("Network.streamResourceContent",{requestId:params.requestId},1e4).then(result=>{buffers.sseStreams.get(params.requestId)===stream&&typeof result?.bufferedData=="string"&&result.bufferedData&&consumePageSseBytes(buffers,partial2,stream,Buffer.from(result.bufferedData,"base64"),requestEventTimestamp(partial2,params.timestamp))}).catch(()=>{buffers.sseStreams.get(params.requestId)===stream&&(stream.mode="fallback")})}refreshCapturedRequest(buffers,partial2)}),client2.on("Network.dataReceived",params=>{let partial2=buffers.pending.get(params.requestId),stream=buffers.sseStreams.get(params.requestId);!partial2||stream?.mode!=="resource"||typeof params.data!="string"||consumePageSseBytes(buffers,partial2,stream,Buffer.from(params.data,"base64"),requestEventTimestamp(partial2,params.timestamp))}),client2.on("Network.eventSourceMessageReceived",params=>{let partial2=buffers.pending.get(params.requestId);if(!partial2)return;let stream=ensurePageSseStream(buffers,partial2,"eventsource");appendPageSseEvents(buffers,partial2,stream,[{event:typeof params.eventName=="string"&&params.eventName?params.eventName:"message",data:parseSseDataValue(String(params.data??"")),...typeof params.eventId=="string"&&params.eventId?{eventId:params.eventId}:{}}],requestEventTimestamp(partial2,params.timestamp))}),client2.on("Network.loadingFinished",params=>{let partial2=buffers.pending.get(params.requestId);if(!partial2)return;buffers.pending.delete(params.requestId);let endTs=params.timestamp,duration3=endTs!==void 0&&partial2.startTs!==void 0?Math.round((endTs-partial2.startTs)*1e3):void 0,stream=buffers.sseStreams.get(params.requestId);stream?.mode==="resource"&&finishPageSseStream(buffers,partial2,stream,requestEventTimestamp(partial2,params.timestamp)),buffers.sseStreams.delete(params.requestId),partial2.duration=duration3,partial2.isPending=!1,refreshCapturedRequest(buffers,partial2),!(partial2.isSSE&&Array.isArray(partial2.responseBody)&&partial2.responseBody.length>0)&&client2.sendCommand("Network.getResponseBody",{requestId:params.requestId},1e4).then(result=>{let responseBody=result.base64Encoded?Buffer.from(result.body,"base64").toString("utf-8"):result.body;if(partial2.isSSE&&typeof responseBody=="string"){replaceWithParsedSseBody(partial2,responseBody,requestEventTimestamp(partial2,params.timestamp)),refreshCapturedRequest(buffers,partial2);return}if(partial2.responseBody=responseBody,typeof partial2.responseBody=="string")try{partial2.responseBody=JSON.parse(partial2.responseBody)}catch{}refreshCapturedRequest(buffers,partial2)}).catch(()=>{})}),client2.on("Network.loadingFailed",params=>{let partial2=buffers.pending.get(params.requestId);partial2&&(buffers.pending.delete(params.requestId),buffers.sseStreams.delete(params.requestId),partial2.status=0,partial2.statusText=params.errorText??"Failed",partial2.duration=params.timestamp!==void 0&&partial2.startTs!==void 0?Math.round((params.timestamp-partial2.startTs)*1e3):void 0,partial2.isPending=!1,partial2.isSSE&&Array.isArray(partial2.responseBody)&&partial2.responseBody.length===0&&(partial2.responseBody={error:partial2.statusText}),refreshCapturedRequest(buffers,partial2))}),client2.on("Runtime.consoleAPICalled",params=>{let level={warning:"warn",debug:"debug",info:"info",error:"error",assert:"error"}[params.type]??"log",args=(params.args??[]).map(arg=>arg.type==="string"?arg.value:arg.value!==void 0?String(arg.value):arg.description!==void 0?arg.description:JSON.stringify(arg));appendCapturedLog(buffers,{level,message:args.join(" "),timestampMs:params.timestamp??Date.now(),source:params.stackTrace?.callFrames?.[0]?.url?`${params.stackTrace.callFrames[0].url.split("/").pop()||params.stackTrace.callFrames[0].url}:${params.stackTrace.callFrames[0].lineNumber+1}`:"console",args,origin:"console"})}),client2.on("Runtime.exceptionThrown",params=>{let details=params.exceptionDetails??{},exception=details.exception,message=exception?.description??(exception?.value!==void 0?String(exception.value):void 0)??details.text??"Uncaught exception",topFrame=details.stackTrace?.callFrames?.[0],url2=topFrame?.url||details.url,lineNumber=topFrame?.lineNumber??details.lineNumber,source=url2?`${url2.split("/").pop()||url2}${lineNumber!==void 0?`:${lineNumber+1}`:""}`:void 0;appendCapturedLog(buffers,{level:"error",message,timestampMs:params.timestamp??Date.now(),...source?{source}:{},args:[message],origin:"exception"})}),client2.on("Log.entryAdded",params=>{let entry=params.entry??{},levelMap={verbose:"log",info:"info",warning:"warn",error:"error"},args=(entry.args??[]).map(arg=>arg.value!==void 0?String(arg.value):arg.description??`[${arg.type||"Object"}]`),message=entry.text||args.join(" ");appendCapturedLog(buffers,{level:levelMap[entry.level]??entry.level??"log",message,timestampMs:entry.timestamp??Date.now(),source:entry.url?`${entry.url.split("/").pop()||entry.url}${entry.lineNumber!==void 0?`:${entry.lineNumber+1}`:""}`:entry.source??"other",args:args.length>0?args:[message],origin:"browser"})}),await Promise.all([ensureCdpDomain(client2,"Network",{maxTotalBufferSize:10*1024*1024,maxPostDataSize:5*1024*1024}),ensureCdpDomain(client2,"Runtime"),ensureCdpDomain(client2,"Log")])}import fs from"node:fs";import http from"node:http";import os from"node:os";import path from"node:path";function chromeUserDataDir(){let platform=process.platform,home=os.homedir();return platform==="darwin"?path.join(home,"Library","Application Support","Google","Chrome"):platform==="win32"?path.join(process.env.LOCALAPPDATA??home,"Google","Chrome","User Data"):path.join(home,".config","google-chrome")}function readDevToolsActivePort(userDataDir=chromeUserDataDir()){try{let filePath=path.join(userDataDir,"DevToolsActivePort"),lines=fs.readFileSync(filePath,"utf8").trim().split(`
78
+ </svg>`;return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`}var JSONP_CALLBACK_RE=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,JSONP_CONTENT_TYPE="application/javascript; charset=utf-8";function getJsonpCallback(url2){try{let searchParams=new URL(url2).searchParams,callback=searchParams.get("callback")??searchParams.get("jsonp");return callback&&JSONP_CALLBACK_RE.test(callback)?callback:null}catch{return null}}function serializeMockResponse(requestUrl,responseData){let callback=getJsonpCallback(requestUrl);if(!callback)return{body:typeof responseData=="string"?responseData:JSON.stringify(responseData)??"null",isJsonp:!1};let json2=JSON.stringify(responseData)??"null";if(typeof responseData=="string")try{JSON.parse(responseData),json2=responseData}catch{}return{body:`${callback}(${json2});`,isJsonp:!0}}function prepareMockResponseHeaders(headers,isJsonp){let stripped=(headers??[]).filter(header=>!["content-encoding","content-length"].includes(header.name.toLowerCase()));if(!isJsonp)return stripped;let index=stripped.findIndex(header=>header.name.toLowerCase()==="content-type");if(index===-1)return[...stripped,{name:"content-type",value:JSONP_CONTENT_TYPE}];let result=[...stripped];return result[index]={...result[index],value:JSONP_CONTENT_TYPE},result}var enabledDomains=new WeakMap;function ensureCdpDomain(client2,domain2,params={}){let domains=enabledDomains.get(client2);domains||(domains=new Map,enabledDomains.set(client2,domains));let existing=domains.get(domain2);if(existing)return existing;let enabling=client2.sendCommand(`${domain2}.enable`,params).then(()=>{}).catch(error48=>{throw domains?.get(domain2)===enabling&&domains.delete(domain2),error48});return domains.set(domain2,enabling),enabling}var MAX_LOGS=500,MAX_EVENTS=500,COLLECTED_RESOURCE_TYPES=new Set(["xhr","fetch","document","eventsource"]);function createBuffers(tabId=0){return{requests:[],logs:[],events:[],pending:new Map,sseStreams:new Map,requestCounter:0,requestBufferAccounting:createRequestBufferAccounting(),capture:{tabId,generation:createCaptureGeneration(),currentSequence:0,droppedRequestsThroughSequence:0,droppedLogsThroughSequence:0,droppedEventsThroughSequence:0}}}function parseQueryString2(url2){try{let u=new URL(url2),result=[];return u.searchParams.forEach((value,name)=>result.push({name,value})),result}catch{return[]}}function headersObjToArray(obj){return Object.entries(obj).map(([name,value])=>({name,value:String(value)}))}function getHeaderValue(headers,targetName){let target=targetName.toLowerCase(),entry=Object.entries(headers).find(([name])=>name.toLowerCase()===target);return entry?String(entry[1]):""}function extractMtopApiName(url2,postData){try{let u=new URL(url2),pathMatch=u.pathname.match(/\/h5\/([\w.]+)\//);if(pathMatch)return pathMatch[1];let proxyMatch=u.searchParams.get("requestUrl")?.match(/\b(?:mtop|mopen)\.[\w.]+/);if(proxyMatch)return proxyMatch[0]}catch{}let urlMatch=url2.match(/\b(?:mtop|mopen)\.[\w.]+/);if(urlMatch)return urlMatch[0];if(!postData)return null;try{let parsed=JSON.parse(postData),proxyMatch=(typeof parsed?.requestUrl=="string"?parsed.requestUrl:void 0)?.match(/\b(?:mtop|mopen)\.[\w.]+/);if(proxyMatch)return proxyMatch[0]}catch{let proxyMatch=new URLSearchParams(postData).get("requestUrl")?.match(/\b(?:mtop|mopen)\.[\w.]+/);if(proxyMatch)return proxyMatch[0]}return null}function requestDisplayName(url2){try{return new URL(url2).pathname}catch{return url2}}function parsePostData(postData){if(!postData)return null;try{return JSON.parse(postData)}catch{try{let params={};return new URLSearchParams(postData).forEach((v,k)=>params[k]=v),params}catch{return postData}}}function appendTrackingEvents(buffers,url2,postData,batchSequence,captureSequence){let events=parseTrackingRequest(url2,postData,{sequence:batchSequence,now:Date.now()}).map(event=>({...event,captureSequence}));if(events.length===0)return!1;let removed=appendCapturedTrackingBatch(buffers.events,events,MAX_EVENTS);for(let event of removed)event.captureSequence!==void 0&&(buffers.capture.droppedEventsThroughSequence=Math.max(buffers.capture.droppedEventsThroughSequence,event.captureSequence));return!0}function recordDroppedRequests(buffers,removed){for(let request of removed)request.captureSequence!==void 0&&(buffers.capture.droppedRequestsThroughSequence=Math.max(buffers.capture.droppedRequestsThroughSequence,request.captureSequence))}function appendCapturedRequest(buffers,request){recordDroppedRequests(buffers,appendRequestToBuffer(buffers.requests,buffers.requestBufferAccounting,request))}function refreshCapturedRequest(buffers,request){recordDroppedRequests(buffers,refreshRequestInBuffer(buffers.requests,buffers.requestBufferAccounting,request))}function recordCdpMtopStreamStart(buffers,data){let capture=createMtopStreamCapture({...data,id:++buffers.requestCounter,tabId:buffers.capture.tabId,captureSequence:nextCaptureSequence(buffers.capture)});return appendCapturedRequest(buffers,capture.request),capture}function recordCdpMtopStreamResponse(buffers,capture,response){updateMtopStreamCaptureResponse(capture,response),refreshCapturedRequest(buffers,capture.request)}function recordCdpMtopStreamChunk(buffers,capture,data,timestampMs2=Date.now()){appendMtopStreamCaptureChunk(capture,data,timestampMs2)&&refreshCapturedRequest(buffers,capture.request)}function recordCdpMtopStreamEnd(buffers,capture,options={}){finishMtopStreamCapture(capture,options),refreshCapturedRequest(buffers,capture.request)}function requestEventTimestamp(partial2,monotonicTimestamp){return monotonicTimestamp!==void 0&&partial2.startTs!==void 0?Math.round(partial2.timestampMs+(monotonicTimestamp-partial2.startTs)*1e3):Date.now()}function ensurePageSseStream(buffers,partial2,mode){partial2.isSSE=!0,Array.isArray(partial2.responseBody)||(partial2.responseBody=[]);let existing=buffers.sseStreams.get(partial2.requestId);if(existing)return existing;let stream={parser:createSseEventParser(),decoder:new TextDecoder2,mode};return buffers.sseStreams.set(partial2.requestId,stream),stream}function appendPageSseEvents(buffers,partial2,stream,events,timestampMs2){if(Array.isArray(partial2.responseBody)){for(let event of events)partial2.responseBody.push({event:event.event,data:event.data,...event.eventId!==void 0?{eventId:event.eventId}:{},timestamp:timestampMs2,duration:stream.lastMessageTimeMs===void 0?0:timestampMs2-stream.lastMessageTimeMs}),stream.lastMessageTimeMs=timestampMs2;events.length>0&&refreshCapturedRequest(buffers,partial2)}}function consumePageSseBytes(buffers,partial2,stream,bytes,timestampMs2){let text=stream.decoder.decode(bytes,{stream:!0});appendPageSseEvents(buffers,partial2,stream,stream.parser.push(text),timestampMs2)}function finishPageSseStream(buffers,partial2,stream,timestampMs2){let tail=stream.decoder.decode(),events=[...stream.parser.push(tail),...stream.parser.finish()];appendPageSseEvents(buffers,partial2,stream,events,timestampMs2)}function replaceWithParsedSseBody(partial2,body,timestampMs2){let parser=createSseEventParser();partial2.responseBody=[...parser.push(body),...parser.finish()].map(event=>({event:event.event,data:event.data,...event.eventId!==void 0?{eventId:event.eventId}:{},timestamp:timestampMs2,duration:0}))}function appendCapturedLog(buffers,log2){if(buffers.logs.push({...log2,captureSequence:nextCaptureSequence(buffers.capture)}),buffers.logs.length>MAX_LOGS){let removed=buffers.logs.shift();removed&&(buffers.capture.droppedLogsThroughSequence=removed.captureSequence)}}async function setupBufferListeners(client2,buffers){client2.on("Network.requestWillBeSent",params=>{let url2=params.request?.url??"";if(!url2.startsWith("http"))return;if(isTrackingUrl(url2)){let batchSequence=++buffers.requestCounter,captureSequence2=nextCaptureSequence(buffers.capture);!appendTrackingEvents(buffers,url2,params.request?.postData,batchSequence,captureSequence2)&&params.request?.hasPostData&&!params.request?.postData&&client2.sendCommand("Network.getRequestPostData",{requestId:params.requestId},1e4).then(result=>appendTrackingEvents(buffers,url2,result?.postData,batchSequence,captureSequence2)).catch(()=>{});return}let resourceType=String(params.type??"").toLowerCase(),mtopApiName=extractMtopApiName(url2,params.request?.postData),isMtop=mtopApiName!==null;if(!isMtop&&!COLLECTED_RESOURCE_TYPES.has(resourceType))return;let ts=params.timestamp,timestampMs2=params.wallTime!==void 0?Math.floor(params.wallTime*1e3):Date.now(),redirected=buffers.pending.get(params.requestId);redirected&&params.redirectResponse&&(redirected.status=params.redirectResponse.status??0,redirected.statusText=params.redirectResponse.statusText??"",redirected.duration=ts!==void 0&&redirected.startTs!==void 0?Math.round((ts-redirected.startTs)*1e3):void 0,redirected.isPending=!1,refreshCapturedRequest(buffers,redirected),buffers.pending.delete(params.requestId),buffers.sseStreams.delete(params.requestId));let id=++buffers.requestCounter,captureSequence=nextCaptureSequence(buffers.capture),partial2={id,requestId:params.requestId,timestamp:new Date(timestampMs2).toISOString(),timestampMs:timestampMs2,method:params.request?.method??"GET",url:url2,apiName:mtopApiName??requestDisplayName(url2),headers:headersObjToArray(params.request?.headers??{}),postData:parsePostData(params.request?.postData),queryString:parseQueryString2(url2),status:0,statusText:"",responseHeaders:[],responseBody:resourceType==="eventsource"?[]:null,isProxy:!1,proxyRequestUrl:null,proxyData:null,startTs:ts,captureSequence,isPending:!0,isSSE:resourceType==="eventsource",source:isMtop?"mtop":"requests",resourceType};buffers.pending.set(params.requestId,partial2),appendCapturedRequest(buffers,partial2)}),client2.on("Network.responseReceived",params=>{let partial2=buffers.pending.get(params.requestId);if(!partial2)return;partial2.status=params.response?.status??0,partial2.statusText=params.response?.statusText??"",partial2.responseHeaders=headersObjToArray(params.response?.headers??{});let contentType=getHeaderValue(params.response?.headers??{},"content-type");if(partial2.resourceType==="eventsource"||contentType.toLowerCase().includes("text/event-stream")){let mode=partial2.resourceType==="eventsource"?"eventsource":"resource",stream=ensurePageSseStream(buffers,partial2,mode);mode==="resource"&&client2.sendCommand("Network.streamResourceContent",{requestId:params.requestId},1e4).then(result=>{buffers.sseStreams.get(params.requestId)===stream&&typeof result?.bufferedData=="string"&&result.bufferedData&&consumePageSseBytes(buffers,partial2,stream,Buffer.from(result.bufferedData,"base64"),requestEventTimestamp(partial2,params.timestamp))}).catch(()=>{buffers.sseStreams.get(params.requestId)===stream&&(stream.mode="fallback")})}refreshCapturedRequest(buffers,partial2)}),client2.on("Network.dataReceived",params=>{let partial2=buffers.pending.get(params.requestId),stream=buffers.sseStreams.get(params.requestId);!partial2||stream?.mode!=="resource"||typeof params.data!="string"||consumePageSseBytes(buffers,partial2,stream,Buffer.from(params.data,"base64"),requestEventTimestamp(partial2,params.timestamp))}),client2.on("Network.eventSourceMessageReceived",params=>{let partial2=buffers.pending.get(params.requestId);if(!partial2)return;let stream=ensurePageSseStream(buffers,partial2,"eventsource");appendPageSseEvents(buffers,partial2,stream,[{event:typeof params.eventName=="string"&&params.eventName?params.eventName:"message",data:parseSseDataValue(String(params.data??"")),...typeof params.eventId=="string"&&params.eventId?{eventId:params.eventId}:{}}],requestEventTimestamp(partial2,params.timestamp))}),client2.on("Network.loadingFinished",params=>{let partial2=buffers.pending.get(params.requestId);if(!partial2)return;buffers.pending.delete(params.requestId);let endTs=params.timestamp,duration3=endTs!==void 0&&partial2.startTs!==void 0?Math.round((endTs-partial2.startTs)*1e3):void 0,stream=buffers.sseStreams.get(params.requestId);stream?.mode==="resource"&&finishPageSseStream(buffers,partial2,stream,requestEventTimestamp(partial2,params.timestamp)),buffers.sseStreams.delete(params.requestId),partial2.duration=duration3,partial2.isPending=!1,refreshCapturedRequest(buffers,partial2),!(partial2.isSSE&&Array.isArray(partial2.responseBody)&&partial2.responseBody.length>0)&&client2.sendCommand("Network.getResponseBody",{requestId:params.requestId},1e4).then(result=>{let responseBody=result.base64Encoded?Buffer.from(result.body,"base64").toString("utf-8"):result.body;if(partial2.isSSE&&typeof responseBody=="string"){replaceWithParsedSseBody(partial2,responseBody,requestEventTimestamp(partial2,params.timestamp)),refreshCapturedRequest(buffers,partial2);return}if(partial2.responseBody=responseBody,typeof partial2.responseBody=="string")try{partial2.responseBody=JSON.parse(partial2.responseBody)}catch{}refreshCapturedRequest(buffers,partial2)}).catch(()=>{})}),client2.on("Network.loadingFailed",params=>{let partial2=buffers.pending.get(params.requestId);partial2&&(buffers.pending.delete(params.requestId),buffers.sseStreams.delete(params.requestId),partial2.status=0,partial2.statusText=params.errorText??"Failed",partial2.duration=params.timestamp!==void 0&&partial2.startTs!==void 0?Math.round((params.timestamp-partial2.startTs)*1e3):void 0,partial2.isPending=!1,partial2.isSSE&&Array.isArray(partial2.responseBody)&&partial2.responseBody.length===0&&(partial2.responseBody={error:partial2.statusText}),refreshCapturedRequest(buffers,partial2))}),client2.on("Runtime.consoleAPICalled",params=>{let level={warning:"warn",debug:"debug",info:"info",error:"error",assert:"error"}[params.type]??"log",args=(params.args??[]).map(arg=>arg.type==="string"?arg.value:arg.value!==void 0?String(arg.value):arg.description!==void 0?arg.description:JSON.stringify(arg));appendCapturedLog(buffers,{level,message:args.join(" "),timestampMs:params.timestamp??Date.now(),source:params.stackTrace?.callFrames?.[0]?.url?`${params.stackTrace.callFrames[0].url.split("/").pop()||params.stackTrace.callFrames[0].url}:${params.stackTrace.callFrames[0].lineNumber+1}`:"console",args,origin:"console"})}),client2.on("Runtime.exceptionThrown",params=>{let details=params.exceptionDetails??{},exception=details.exception,message=exception?.description??(exception?.value!==void 0?String(exception.value):void 0)??details.text??"Uncaught exception",topFrame=details.stackTrace?.callFrames?.[0],url2=topFrame?.url||details.url,lineNumber=topFrame?.lineNumber??details.lineNumber,source=url2?`${url2.split("/").pop()||url2}${lineNumber!==void 0?`:${lineNumber+1}`:""}`:void 0;appendCapturedLog(buffers,{level:"error",message,timestampMs:params.timestamp??Date.now(),...source?{source}:{},args:[message],origin:"exception"})}),client2.on("Log.entryAdded",params=>{let entry=params.entry??{},levelMap={verbose:"log",info:"info",warning:"warn",error:"error"},args=(entry.args??[]).map(arg=>arg.value!==void 0?String(arg.value):arg.description??`[${arg.type||"Object"}]`),message=entry.text||args.join(" ");appendCapturedLog(buffers,{level:levelMap[entry.level]??entry.level??"log",message,timestampMs:entry.timestamp??Date.now(),source:entry.url?`${entry.url.split("/").pop()||entry.url}${entry.lineNumber!==void 0?`:${entry.lineNumber+1}`:""}`:entry.source??"other",args:args.length>0?args:[message],origin:"browser"})}),await Promise.all([ensureCdpDomain(client2,"Network",{maxTotalBufferSize:10*1024*1024,maxPostDataSize:5*1024*1024}),ensureCdpDomain(client2,"Runtime"),ensureCdpDomain(client2,"Log")])}import fs from"node:fs";import http from"node:http";import os from"node:os";import path from"node:path";function chromeUserDataDir(){let platform=process.platform,home=os.homedir();return platform==="darwin"?path.join(home,"Library","Application Support","Google","Chrome"):platform==="win32"?path.join(process.env.LOCALAPPDATA??home,"Google","Chrome","User Data"):path.join(home,".config","google-chrome")}function readDevToolsActivePort(userDataDir=chromeUserDataDir()){try{let filePath=path.join(userDataDir,"DevToolsActivePort"),lines=fs.readFileSync(filePath,"utf8").trim().split(`
79
79
  `).map(l=>l.trim()),port=parseInt(lines[0],10),browserWsPath=lines[1]??"/devtools/browser";return isNaN(port)?null:{port,browserWsPath}}catch{return null}}async function discoverTargets(port=9222){return new Promise((resolve2,reject)=>{let req=http.get(`http://localhost:${port}/json`,res=>{let data="";res.on("data",chunk=>data+=chunk),res.on("end",()=>{try{resolve2(JSON.parse(data))}catch(e){reject(new Error(`Failed to parse CDP targets: ${e}`))}})});req.on("error",reject),req.setTimeout(3e3,()=>{req.destroy(),reject(new Error("CDP discover timeout"))})})}var initializers=[];function registerPageSessionInitializer(initializer3){initializers.push(initializer3)}async function initializePageSession(session){for(let initializer3 of initializers)await initializer3(session)}function isImplicitlySelectablePageUrl(url2){return!url2.startsWith("chrome-extension://")&&!url2.startsWith("about:")&&!url2.startsWith("chrome://")}var CdpSession=class{port;userDataDir;endpointUrl;endpointResolver;browserClient=null;browserClientPromise=null;pageSessions=new Map;tabIdMap=new Map;nextTabId=1e3;constructor(options=9222){if(typeof options=="number"){this.port=options;return}this.port=options.port??9222,this.userDataDir=options.userDataDir,this.endpointUrl=options.endpointUrl,this.endpointResolver=options.endpointResolver}async getBrowserClient(){if(this.browserClient&&!this.browserClient.closed)return this.browserClient;this.browserClientPromise||(this.browserClientPromise=this.connectBrowserClient());let pending=this.browserClientPromise;try{return await pending}finally{this.browserClientPromise===pending&&(this.browserClientPromise=null)}}async getPageSession(virtualTabId){let targetId;if(virtualTabId!==void 0&&(targetId=this.tabIdMap.get(virtualTabId),!targetId))throw new Error(`Tab ${virtualTabId} not found. Open a tab first with tab_open.`);if(targetId){let existing2=this.pageSessions.get(targetId);if(existing2&&!existing2.client.closed)return existing2}let target=targetId?await this.findTargetById(targetId):await this.findDefaultPageTarget();if(!target)throw new Error(virtualTabId?`CDP target for tab ${virtualTabId} is no longer available`:"No implicitly selectable page target found. about:, chrome:, and extension pages are excluded; pass a tabId returned by tab_open or open a web page.");let existing=this.pageSessions.get(target.id);return existing&&!existing.client.closed?existing:this.createPageSession(target)}async registerTarget(targetId){let virtualId=this.nextTabId++;this.tabIdMap.set(virtualId,targetId);let target=await this.findTargetById(targetId);return target&&await this.createPageSession(target),virtualId}async ensureTargetRegistered(targetId){for(let[virtualId2,registeredTargetId]of this.tabIdMap)if(registeredTargetId===targetId)return virtualId2;let virtualId=this.nextTabId++;return this.tabIdMap.set(virtualId,targetId),virtualId}async connectBrowserClient(){let wsUrl=await this.resolveBrowserWsUrl();if(!wsUrl)throw new Error("No browser-level WebSocket URL available from CDP");let client2=await CdpClient.connect(wsUrl);return this.browserClient=client2,client2.on("Target.targetDestroyed",params=>{for(let[virtualId,targetId]of this.tabIdMap)if(targetId===params.targetId){this.tabIdMap.delete(virtualId);break}this.pageSessions.delete(params.targetId)}),client2}async createPageSession(target){let client2;try{let browser=await this.getBrowserClient(),{sessionId}=await browser.sendCommand("Target.attachToTarget",{targetId:target.id,flatten:!0},5e3);client2=browser.createChildSession(sessionId)}catch(error48){if(this.isRemote())throw new Error(`Failed to attach to remote CDP target ${target.id}: ${error48 instanceof Error?error48.message:String(error48)}`,{cause:error48});client2=await CdpClient.connect(target.webSocketDebuggerUrl)}let tabId;for(let[virtualId,registeredTargetId]of this.tabIdMap)if(registeredTargetId===target.id){tabId=virtualId;break}tabId===void 0&&(tabId=this.nextTabId++,this.tabIdMap.set(tabId,target.id));let buffers=createBuffers(tabId);await setupBufferListeners(client2,buffers);let session={tabId,client:client2,buffers,targetId:target.id,url:target.url};this.pageSessions.set(target.id,session),client2.on("Inspector.detached",()=>{this.pageSessions.delete(target.id)});try{await initializePageSession(session)}catch(error48){throw this.pageSessions.delete(target.id),client2.close(),error48}return session}async findTargetById(targetId){if(this.isRemote())return this.findTargetByIdViaCdp(targetId);try{return(await discoverTargets(this.effectivePort())).find(t=>t.id===targetId&&t.webSocketDebuggerUrl)??null}catch{return this.findTargetByIdViaCdp(targetId)}}async findDefaultPageTarget(){if(this.isRemote())return this.findDefaultPageTargetViaCdp();try{return(await discoverTargets(this.effectivePort())).find(t=>t.type==="page"&&t.webSocketDebuggerUrl&&isImplicitlySelectablePageUrl(t.url))??null}catch{return this.findDefaultPageTargetViaCdp()}}effectivePort(){return readDevToolsActivePort(this.userDataDir)?.port??this.port}async resolveBrowserWsUrl(){let configuredEndpoint=this.endpointResolver?await this.endpointResolver():this.endpointUrl;if(configuredEndpoint){let url2=new URL(configuredEndpoint);if(url2.protocol!=="ws:"&&url2.protocol!=="wss:")throw new Error(`Unsupported CDP endpoint protocol: ${url2.protocol}`);return url2.toString()}let fileInfo=readDevToolsActivePort(this.userDataDir);if(fileInfo)return`ws://localhost:${fileInfo.port}${fileInfo.browserWsPath}`;try{return(await this.fetchVersionInfo()).webSocketDebuggerUrl??null}catch{return null}}pageWsUrl(targetId){return`ws://localhost:${this.effectivePort()}/devtools/page/${targetId}`}isRemote(){return!!(this.endpointUrl||this.endpointResolver)}async findTargetByIdViaCdp(targetId){try{let info=(await(await this.getBrowserClient()).sendCommand("Target.getTargets",{})).targetInfos.find(t=>t.targetId===targetId);return info?{id:info.targetId,title:info.title??"",type:info.type??"page",url:info.url??"",webSocketDebuggerUrl:this.pageWsUrl(info.targetId)}:null}catch{return null}}async findDefaultPageTargetViaCdp(){try{let info=(await(await this.getBrowserClient()).sendCommand("Target.getTargets",{})).targetInfos.find(t=>t.type==="page"&&isImplicitlySelectablePageUrl(t.url));return info?{id:info.targetId,title:info.title??"",type:info.type??"page",url:info.url??"",webSocketDebuggerUrl:this.pageWsUrl(info.targetId)}:null}catch{return null}}fetchVersionInfo(){return new Promise((resolve2,reject)=>{let req=http2.get(`http://localhost:${this.port}/json/version`,res=>{let data="";res.on("data",chunk=>data+=chunk),res.on("end",()=>{try{resolve2(JSON.parse(data))}catch(e){reject(new Error(`Failed to parse CDP version info: ${e}`))}})});req.on("error",reject),req.setTimeout(3e3,()=>{req.destroy(),reject(new Error("CDP version info timeout"))})})}async probeAvailability(){try{return await(await this.getBrowserClient()).sendCommand("Target.getTargets",{},3e3),{available:!0}}catch(error48){return this.browserClient?.close(),this.browserClient=null,{available:!1,error:(error48 instanceof Error?error48.message:String(error48)).trim()||"CDP connection failed"}}}async isAvailable(){return(await this.probeAvailability()).available}hasActiveConnections(){return this.browserClient!==null&&!this.browserClient.closed||Array.from(this.pageSessions.values()).some(session=>!session.client.closed)}listOpenPageSessions(){return Array.from(this.pageSessions.values()).filter(session=>!session.client.closed)}listRegisteredTabIds(targetIds){return Array.from(this.tabIdMap.entries()).filter(([,targetId])=>!targetIds||targetIds.has(targetId)).map(([tabId])=>tabId)}close(){this.browserClient?.close(),this.browserClient=null;for(let session of this.pageSessions.values())session.client.close();this.pageSessions.clear(),this.tabIdMap.clear()}};var injectedSessions=new WeakMap,indicatorQueues=new WeakMap;function enqueueIndicatorOperation(session,operation){let queued=(indicatorQueues.get(session)??Promise.resolve()).catch(()=>{}).then(operation);return indicatorQueues.set(session,queued),queued.finally(()=>{indicatorQueues.get(session)===queued&&indicatorQueues.delete(session)})}function createFaviconScript(controlSource){let iconDataUrl=createControlledFaviconDataUrl(controlSource);return`(() => {
80
80
  if (window !== window.top) return;
81
81
  const ICON = ${JSON.stringify(iconDataUrl)};
@@ -147,7 +147,7 @@ ${SOURCE_BADGES[source]}
147
147
  for (const icon of state.originalIcons || []) document.head.appendChild(icon);
148
148
  }
149
149
  delete window.__mearlControlledFavicon__;
150
- })();`;async function ensureControlledIndicator(session,controlSource="local"){return enqueueIndicatorOperation(session,async()=>{let current=injectedSessions.get(session);if(current?.controlSource!==controlSource){injectedSessions.set(session,{identifier:null,controlSource});try{await ensureCdpDomain(session.client,"Page"),current?.identifier&&await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:current.identifier}).catch(()=>{});let result=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:createFaviconScript(controlSource),runImmediately:!0});injectedSessions.set(session,{identifier:result?.identifier??null,controlSource})}catch{injectedSessions.delete(session)}}})}async function releaseControlledIndicator(session){return enqueueIndicatorOperation(session,async()=>{let current=injectedSessions.get(session);injectedSessions.delete(session),current?.identifier&&await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:current.identifier}).catch(()=>{}),await session.client.sendCommand("Runtime.evaluate",{expression:RESTORE_FAVICON_SCRIPT}).catch(()=>{})})}var actionMap=new Map;function registerActions(actions){for(let action of actions){if(actionMap.has(action.name))throw new Error(`CDP action "${action.name}" is already registered`);actionMap.set(action.name,action)}}function getRegisteredActionNames(){return[...actionMap.keys()]}async function dispatchCdpAction(cdpSession2,action,data,controlSource="local"){let entry=actionMap.get(action);if(!entry)throw new Error(`Action "${action}" is not supported in CDP mode`);if(entry.session==="browser")return entry.handler(cdpSession2,data,controlSource);let tabId=typeof data?.tabId=="number"?data.tabId:void 0,pageSession=await cdpSession2.getPageSession(tabId);return await ensureControlledIndicator(pageSession,controlSource),entry.handler(pageSession,data,controlSource)}var mockStore=new Map,fetchInterceptEnabled=new Set;function clearCdpMockState(){mockStore.clear(),fetchInterceptEnabled.clear()}function tryParseJson(value){try{return JSON.parse(value)}catch{return value}}function isSubset(subset,superset){return subset===superset?!0:subset==null||superset==null?subset===superset:typeof subset!="object"||typeof superset!="object"?String(subset)===String(superset):Array.isArray(subset)?Array.isArray(superset)&&JSON.stringify(subset)===JSON.stringify(superset):Object.entries(subset).every(([key,value])=>key in superset?isSubset(value,superset[key]):!1)}function matchesConditions(mock,request){if(!mock.conditions||Object.keys(mock.conditions).length===0)return!0;let requestData={};try{new URL(request.url??"").searchParams.forEach((value,key)=>{requestData[key]=tryParseJson(value)})}catch{}if(request.postData)try{let json2=JSON.parse(request.postData);typeof json2=="object"&&json2!==null&&Object.assign(requestData,json2)}catch{try{new URLSearchParams(request.postData).forEach((value,key)=>{requestData[key]=tryParseJson(value)})}catch{}}return isSubset(mock.conditions,requestData)?!0:requestData.data&&typeof requestData.data=="object"?isSubset(mock.conditions,requestData.data):!1}function findMatchedMock(url2,postData){for(let list of mockStore.values())for(let mock of list)if(mock.enabled&&(url2.includes(`/${mock.apiName}/`)||url2.includes(mock.apiName))&&matchesConditions(mock,{url:url2,postData}))return mock;return null}function sameConditions(a,b){let aKeys=a?Object.keys(a):[],bKeys=b?Object.keys(b):[];return aKeys.length===0||bKeys.length===0?aKeys.length===0&&bKeys.length===0:aKeys.length!==bKeys.length?!1:aKeys.every(k=>JSON.stringify(a[k])===JSON.stringify(b[k]))}function stripEncodingHeaders(headers){if(!headers)return[];let stripped=new Set(["content-encoding","content-length"]);return headers.filter(header=>!stripped.has(header.name.toLowerCase()))}function ensureCorsHeaders(headers,request){let origin=Object.entries(request.headers??{}).find(([name])=>name.toLowerCase()==="origin")?.[1];if(!origin)return headers;let result=[...headers],hasHeader=name=>result.some(header=>header.name.toLowerCase()===name.toLowerCase());return hasHeader("access-control-allow-origin")||result.push({name:"access-control-allow-origin",value:origin}),hasHeader("access-control-allow-credentials")||result.push({name:"access-control-allow-credentials",value:"true"}),result}async function ensureMockInterception(session){fetchInterceptEnabled.has(session.targetId)||(await session.client.sendCommand("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"},{urlPattern:"*",requestStage:"Response"}]}),fetchInterceptEnabled.add(session.targetId),session.client.on("Fetch.requestPaused",async params=>{let url2=params.request?.url??"",isResponseStage=params.responseStatusCode!=null||params.responseErrorReason!=null,passthrough=()=>session.client.sendCommand(isResponseStage?"Fetch.continueResponse":"Fetch.continueRequest",{requestId:params.requestId}).catch(()=>{});if(params.request?.method==="OPTIONS"){await passthrough();return}let matchedMock=findMatchedMock(url2,params.request?.postData),fulfillMock=async(mock,responseCode,responseHeaders)=>{let responseBody=JSON.stringify(mock.responseData),base64Body=Buffer.from(responseBody,"utf-8").toString("base64");await session.client.sendCommand("Fetch.fulfillRequest",{requestId:params.requestId,responseCode,responseHeaders,body:base64Body})};if(!matchedMock){await passthrough();return}try{if(!isResponseStage){matchedMock.duration!==void 0?(matchedMock.duration>0&&await new Promise(r=>setTimeout(r,matchedMock.duration)),await fulfillMock(matchedMock,200,ensureCorsHeaders([{name:"content-type",value:"application/json; charset=utf-8"},{name:"x-mock-by",value:"mearl-cdp"}],params.request))):await passthrough();return}await fulfillMock(matchedMock,params.responseStatusCode??200,stripEncodingHeaders(params.responseHeaders))}catch{await passthrough()}}))}async function cdpSetMock(session,data){let{apiName,mockData,fields,enabled,duration:duration3,conditions}=data;if(!apiName||typeof apiName!="string"||apiName.trim()==="")throw new Error("Invalid apiName");if(enabled===!1)return mockStore.delete(apiName),{success:!0,affectedCount:1,message:`Mock disabled for ${apiName}`};if(mockData===void 0&&(!fields||fields.length===0))throw new Error("Either mockData or fields must be provided");if(fields&&fields.length>100)throw new Error("Too many fields: maximum 100 fields allowed");let normConditions=conditions&&Object.keys(conditions).length>0?conditions:void 0,finalMockData=mockData;if(fields&&fields.length>0){let conditionMatcher={apiName,responseData:null,conditions:normConditions,enabled:!0},baseRequest=[...session.buffers.requests].reverse().find(request=>request.method!=="OPTIONS"&&request.responseBody!==null&&request.responseBody!==void 0&&(request.apiName?.includes(apiName)||request.url?.includes(apiName))&&matchesConditions(conditionMatcher,{url:request.url,postData:typeof request.postData=="string"?request.postData:void 0}));finalMockData=baseRequest?.responseBody?JSON.parse(JSON.stringify(baseRequest.responseBody)):{};for(let field of fields)setValueByPath(finalMockData,field.path,field.value)}let entry={apiName,responseData:finalMockData,duration:duration3,conditions:normConditions,enabled:!0},list=mockStore.get(apiName)??[],idx=list.findIndex(m=>sameConditions(m.conditions,normConditions));return idx>=0?list[idx]=entry:list.push(entry),mockStore.set(apiName,list),await ensureMockInterception(session),{success:!0,affectedCount:1,message:`Mock set for ${apiName}`}}function cdpGetMocks(_session,data){let matcher=data?.apiName?new RegExp(data.apiName,"i"):null,mocks=[...mockStore.values()].flat().filter(m=>!matcher||matcher.test(m.apiName)).map(m=>({apiName:m.apiName,responseData:m.responseData,duration:m.duration??0,conditions:m.conditions,disabled:!m.enabled}));return{mocks,count:mocks.length}}registerActions([{name:"set_mock",session:"page",handler:cdpSetMock},{name:"get_mocks",session:"page",handler:async(s,d)=>cdpGetMocks(s,d)}]);var WINDVANE="WindVane/8.7.0",WV_BRIDGE={global:"WindVane",style:"windvane"},MEGA_BRIDGE={global:"__megability_bridge__",style:"mega"},WV_NATIVE_BACK={event:"wvBackClickEvent",controlFunction:"_windvane_backControl"},FLIGGY_NATIVE_BACK={event:"WV.Back"},ALIPAY_NATIVE_BACK={event:"back"},FLIGGY_OVERLAY={enabledParam:"_fli_overlay",topRatioParam:"_fli_overlay_ratio",radiusParam:"_fli_overlay_radius",maskAlphaParam:"_fli_overlay_mask_alpha",tapCloseParam:"_fli_overlay_tap_close",tapCloseSelectors:["#qwen-titlebar .qwen-titlebar-icon-wrapper:last-child"],silentTapClose:!0,defaultTopRatio:.2,defaultRadius:0,defaultMaskAlpha:.3,defaultTapClose:!0},TAOBAO_OVERLAY={enabledParam:"useWebdialog",topRatioParam:"topRatio",heightRatioParam:"height_pct",radiusParam:"cornerRadius",maskAlphaParam:"maskAlpha",tapCloseParam:"tapEnable",tapCloseSelectors:["#qwen-titlebar .qwen-titlebar-icon-wrapper:last-child"],defaultTopRatio:.2,defaultRadius:6,defaultMaskAlpha:.5,defaultTapClose:!0},FLIGGY_IMAGE_PICKER={schemes:["page://ask_take_photo"],api:"mtop.trip.serverless.api.gateway",version:"2.0",fcId:"240417431173407785",fcGroup:"fl-images",uploadUrlFunction:"uploadByTokenUrl",prefix:"temp",region:"CN"},FLIGGY_LAYER_URL_PROXY={sourceHostPrefix:"edith.",pathPrefix:"/proxy/",targetHostSuffixes:["wapa.taobao.com"],defaultTargetHost:"market.wapa.taobao.com"},FLIGGY_ROOT_CONTAINER={statusBarHeightCookie:{name:"_fli_barHeight",domain:"taobao.com",path:"/"}},FLIGGY_TITLE_BAR_HIDDEN_PATHNAMES=["/app/trip/rx-home/pages/home","/app/trip/rx-trip-ai/pages/home"],FLIGGY_STATUS_BAR_BACKGROUND_COLORS={"/app/trip/rx-home/pages/home":"#fff","/app/trip/rx-trip-ai/pages/home":"#dbdbff"};function emptyActions(){return{open:[],close:[],title:[],navigationBar:[],statusBar:[],systemInfo:[],mtop:[],kvGet:[],kvSet:[],kvDelete:[],pageContext:[],responses:{},behaviors:{},noop:[],silent:[]}}function mergeActions(...maps){let out=emptyActions();for(let m of maps)out.open.push(...m.open),out.close.push(...m.close),out.title.push(...m.title),out.navigationBar.push(...m.navigationBar??[]),out.statusBar.push(...m.statusBar??[]),out.systemInfo.push(...m.systemInfo),out.mtop.push(...m.mtop),out.kvGet.push(...m.kvGet??[]),out.kvSet.push(...m.kvSet??[]),out.kvDelete.push(...m.kvDelete??[]),out.pageContext.push(...m.pageContext??[]),Object.assign(out.responses,m.responses??{}),Object.assign(out.behaviors,m.behaviors??{}),out.noop.push(...m.noop),out.silent.push(...m.silent??[]);return out}var APP_BRIDGE_BEHAVIORS=["navigate","closeAll","closeBackData","postMessage","notifySubscribe","notifyUnsubscribe","notifyPost","sharedFileRead","sharedFileWrite","sharedDataGet","sharedDataSet","legacyBroadcastCreate","legacyBroadcastPost","legacyBroadcastClose","memoryGet","memorySet","memoryDelete","availabilityMap","userInfo","networkInfo","geolocation","permission","prefetch","fptTrack","mtopStream","previewFile","toast","unsupportedNativeInput","payment","userTrack","calendar","networkQualityMonitor","beaconRequest","voiceRecognition"],APP_BRIDGE_BEHAVIOR_SET=new Set(APP_BRIDGE_BEHAVIORS),BRIDGE_ACTION_ARRAY_KEYS=["open","close","title","navigationBar","statusBar","systemInfo","mtop","kvGet","kvSet","kvDelete","pageContext","noop"];function isJsonValue2(value,seen=new Set){if(value===null||typeof value=="string"||typeof value=="boolean")return!0;if(typeof value=="number")return Number.isFinite(value);if(typeof value!="object"||seen.has(value))return!1;seen.add(value);let valid=Array.isArray(value)?value.every(item=>isJsonValue2(item,seen)):Object.values(value).every(item=>isJsonValue2(item,seen));return seen.delete(value),valid}function validateAppBridgeConfig(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("bridgeConfig must be an object");let root=value;if(Object.keys(root).some(key=>key!=="methods"))throw new Error('bridgeConfig only supports the "methods" field');if(!root.methods||typeof root.methods!="object"||Array.isArray(root.methods))throw new Error("bridgeConfig.methods must be an object");let entries=Object.entries(root.methods);if(entries.length>200)throw new Error("bridgeConfig supports at most 200 methods");let methods2={};for(let[method,rawConfig]of entries){if(!method.trim()||method.length>200)throw new Error("bridgeConfig method names must contain 1-200 characters");if(method==="__proto__"||method==="prototype"||method==="constructor")throw new Error(`bridgeConfig method name "${method}" is reserved`);if(!rawConfig||typeof rawConfig!="object"||Array.isArray(rawConfig))throw new Error(`bridgeConfig.methods.${method} must be an object`);let methodConfig=rawConfig,supportedKeys=new Set(["behavior","response","noop","silent"]);if(Object.keys(methodConfig).some(key=>!supportedKeys.has(key)))throw new Error(`bridgeConfig.methods.${method} contains an unsupported field`);if("behavior"in methodConfig&&typeof methodConfig.behavior!="string")throw new Error(`bridgeConfig.methods.${method}.behavior must be a string`);let hasBehavior=typeof methodConfig.behavior=="string",hasResponse=Object.prototype.hasOwnProperty.call(methodConfig,"response"),hasNoop=methodConfig.noop===!0;if(Number(hasBehavior)+Number(hasResponse)+Number(hasNoop)!==1)throw new Error(`bridgeConfig.methods.${method} must define exactly one of behavior, response, or noop=true`);if(hasBehavior&&!APP_BRIDGE_BEHAVIOR_SET.has(methodConfig.behavior))throw new Error(`bridgeConfig.methods.${method} has an unsupported behavior`);if(hasResponse&&!isJsonValue2(methodConfig.response))throw new Error(`bridgeConfig.methods.${method}.response must be valid JSON data`);if("noop"in methodConfig&&methodConfig.noop!==!0)throw new Error(`bridgeConfig.methods.${method}.noop must be true when provided`);if("silent"in methodConfig&&typeof methodConfig.silent!="boolean")throw new Error(`bridgeConfig.methods.${method}.silent must be a boolean`);methods2[method]={...hasBehavior&&{behavior:methodConfig.behavior},...hasResponse&&{response:JSON.parse(JSON.stringify(methodConfig.response))},...hasNoop&&{noop:!0},...methodConfig.silent===!0&&{silent:!0}}}let normalized={methods:methods2};if(JSON.stringify(normalized).length>65536)throw new Error("bridgeConfig must not exceed 64 KiB");return normalized}function applyAppBridgeConfig(actions,config2){let out=mergeActions(actions);if(!config2)return out;let{methods:methods2}=validateAppBridgeConfig(config2);for(let[method,methodConfig]of Object.entries(methods2)){for(let key of BRIDGE_ACTION_ARRAY_KEYS){let values=out[key];values&&(out[key]=values.filter(value=>value!==method))}out.silent=(out.silent??[]).filter(value=>value!==method),delete out.responses?.[method],delete out.behaviors?.[method],methodConfig.behavior?out.behaviors[method]=methodConfig.behavior:Object.prototype.hasOwnProperty.call(methodConfig,"response")?out.responses[method]=methodConfig.response:methodConfig.noop&&out.noop.push(method),methodConfig.silent&&out.silent.push(method)}return out}var WV_ACTIONS={open:["WVNative.openWindow","Base.openBrowser","EtaoJsbridgeUtil.openWindow","TMBridge.pushWindow","Third.openThirdWeb"],close:["WebAppInterface.pop","Triver.pop","TMBridge.popWindow","EleWVHybridAPI.popWindow","Third.closeWebView"],title:["WebAppInterface.setCustomPageTitle"],navigationBar:["Triver.setNavigationBarStyle"],statusBar:["WebAppInterface.setStatusBarStyle","Application.setStatusBarStyle"],systemInfo:["WVNativeDetector.getModelInfo"],mtop:["MtopWVPlugin.send"],behaviors:{"WVLocation.getLocation":"geolocation","WVNetwork.getNetworkType":"networkInfo","WVFile.read":"sharedFileRead","WVFile.write":"sharedFileWrite","SharedData.getSharedData":"sharedDataGet","SharedData.setSharedData":"sharedDataSet","WVBroadcast.createChannel":"legacyBroadcastCreate","WVBroadcast.postMessage":"legacyBroadcastPost","WVBroadcast.close":"legacyBroadcastClose"},noop:["WVNative.enableHookNativeBack","WVNative.forbidPanGesture","WVNative.setGestureBack","WVTBUserTrack.toUT","WVTBUserTrack.toUT2"],silent:["WVNetwork.getNetworkType","WVNativeDetector.getModelInfo","WVTBUserTrack.toUT","WVTBUserTrack.toUT2"]},COMMON_SCHEME_RULES=[{match:"page:",param:"params"},{match:"taobaotravel:",param:"params"},{match:"alipays://platformapi/starth5app",param:"url"},{match:"alipays://platformapi/startapp",param:"page"},{match:"eleme://web",param:"url"},{match:"amapuri://webview/",param:"url"}],FEIZHU_WECHAT_HOST_SUFFIXES=["feizhu.com"],WECHAT_SCHEME_RULES=[{match:"/pages/main/webview",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,param:"url",useCurrentOrigin:!0},...COMMON_SCHEME_RULES],WECHAT_MINI_PROGRAM={paymentRoutes:[{pathname:"/pages/utils/common-pay/index",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,paymentParamsParam:"signStr",successUrlParams:["backUrl","successUrl"],failureUrlParams:["unSuccessUrl","errorUrl"],successResultParam:"__paymentRes",forwardParams:["ttid"],useCurrentOrigin:!0}],nativeRoutes:[{pathname:"/pages/utils/webview-bridge/index",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,actions:["navigateMiniProgram","subscribeMessage"]}],messageRules:[{type:"BACK_DATA",action:"stageBackData",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES},{type:"BACK_MINI_APP",action:"closeAll",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES}]},WECHAT_TITLE_BAR_HOST_STYLES=[{hostSuffix:"feizhu.com",titleBarBackgroundColor:"#ffe033",statusBarBackgroundColor:"#ffe033"}],FLIGGY_SCHEME_RULES=[{match:"fliggy://order/detail",targetPath:"/app/trip/rx-flight-detail/pages/index",targetHostPrefix:"market",targetParams:{titleBarHidden:"2"}},...COMMON_SCHEME_RULES],WV_ACTIVE_EVENTS=["WV.Event.APP.Active"],FLIGGY_AI_UI_NOOPS=["handleLiveActivity","ai_ask_scroll_position","ai_ask_input_status","ai_ask_set_keyboard_tags","ai_ask_h5_awaken_input","ai_ask_reset_input","ai_ask_hide_input","home_ai_page_scroll","ai_ask_hide_keyboard","ai_ask_clear_keyboard_tags","ai_ask_init_mask","ai_ask_hide_mask","ai_ask_transfer_to_wenwen","ai_ask_transfer_to_mask","close_loading_view","open_loading_view","set_ai_ask_container_status","to_set_notifaction","home_refresh","ai_ask_page_load_success","ai_ask_set_session_info","ai_ask_input_set_mention_url","ai_ask_input_set_scene","ai_float_brain_panel_back_to_top_panel_page","ai_float_brain_panel_set_tools"],APP_PROFILES={fliggy:{name:"fliggy",label:"飞猪",appName:"LX",defaultAppVersion:"10.0.0",uaTokens:["AliTrip/{v}",WINDVANE],globals:{},bridges:[WV_BRIDGE,{global:"alitripBridge",style:"fliggy"},{global:"core",style:"fliggy"},{global:"methodChannel",style:"callback"}],activeEvents:WV_ACTIVE_EVENTS,actions:mergeActions(WV_ACTIONS,{...emptyActions(),open:["goto","ai_float_brain_panel_collapse_and_open_url"],close:[],title:["set_webview_title"],navigationBar:["set_ui"],statusBar:["set_status_bar_style"],systemInfo:["client_info"],kvGet:["get_kvcache"],kvSet:["set_kvcache"],kvDelete:["del_kvcache"],pageContext:["ai_float_brain_panel_get_page_context"],responses:{is_open_push:{is_open:!1},get_unread_message:{style:"POINT",count:0},get_v10_ab_info:{v10Version:!0},get_ai_ask_container_status:{status:"FULL"},ai_ask_get_keyboard_height:{height:0},get_idfa:{},get_caid:{},get_theme_conf:{},cppay_app_install:{result:""}},behaviors:{"page://goto":"navigate","page://close":"closeBackData",back:"closeBackData",user_info:"userInfo",ai_ask_get_memory_cache:"memoryGet",ai_ask_set_memory_cache:"memorySet",ai_ask_del_memory_cache:"memoryDelete",channelJudgeJsBridge:"availabilityMap",networktype:"networkInfo",network_quality_monitor:"networkQualityMonitor",request:"beaconRequest",voice_recognition:"voiceRecognition",store_calendar_event:"calendar",remove_calendar_event:"calendar",check_batch_calendar:"calendar",search_batch_calendar_events:"calendar",lbs:"geolocation",permission:"permission",cacheFetch:"prefetch",fptTrack:"fptTrack",toUT:"userTrack","WVTBUserTrack.toUT":"userTrack","WVTBUserTrack.toUT2":"userTrack",mtop_stream:"mtopStream",ai_ask_preview_file:"previewFile",toast:"toast",ai_ask_input_bridge:"unsupportedNativeInput",cppay:"payment",minipay:"payment",union_pay:"payment"},noop:["swipe_back","track_error_with_alarm","cacheUpdate","long_press_save_image",...FLIGGY_AI_UI_NOOPS],silent:["native://biz/mtop_normal_sign","toUT","get_idfa","get_caid","channelJudgeJsBridge","get_unread_message","get_v10_ab_info","lbs","networktype","network_quality_monitor","request","long_press_save_image","set_status_bar_style","get_theme_conf","cacheFetch","cppay_app_install","track_error_with_alarm",...FLIGGY_AI_UI_NOOPS]}),schemes:FLIGGY_SCHEME_RULES,imagePicker:FLIGGY_IMAGE_PICKER,geolocation:{reverseGeocodeApi:"mtop.trip.common.getCityCodeByLatitudeAndLongitude",version:"1.0"},layerUrlProxy:FLIGGY_LAYER_URL_PROXY,rootContainer:FLIGGY_ROOT_CONTAINER,titleBarHiddenPathnames:FLIGGY_TITLE_BAR_HIDDEN_PATHNAMES,statusBarBackgroundColors:FLIGGY_STATUS_BAR_BACKGROUND_COLORS,urlSyncHostSuffixes:["m.taobao.com","wapa.taobao.com"],overlay:FLIGGY_OVERLAY,popBeforeOpenParam:"_fli_popBeforeOpen",nativeBack:FLIGGY_NATIVE_BACK,forceH5Mtop:!0},taobao:{name:"taobao",label:"手机淘宝",appName:"TB",defaultAppVersion:"10.65.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE,MEGA_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,overlay:TAOBAO_OVERLAY,nativeBack:WV_NATIVE_BACK},wechat:{name:"wechat",label:"微信",appName:"WeChat",defaultAppVersion:"8.0.58",uaFamily:"wechatMiniProgram",uaTokens:[],globals:{__wxjs_environment:"miniprogram"},bridges:[{global:"wx",style:"wechat"},{global:"wx.miniProgram",style:"wechatMiniProgram",persistent:!0}],activeEvents:[],actions:{...emptyActions(),open:["navigateTo","redirectTo","switchTab","reLaunch"],close:["navigateBack"],behaviors:{postMessage:"postMessage",getLocation:"geolocation"}},schemes:WECHAT_SCHEME_RULES,miniProgram:WECHAT_MINI_PROGRAM,titleBarHostStyles:WECHAT_TITLE_BAR_HOST_STYLES},tmall:{name:"tmall",label:"天猫",appName:"TM",defaultAppVersion:"15.22.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},alipay:{name:"alipay",label:"支付宝",appName:"AP",defaultAppVersion:"10.8.0",uaTokens:["AlipayClient/{v}"],globals:{},bridges:[{global:"AlipayJSBridge",style:"alipay"}],activeEvents:[],actions:{open:["pushWindow","startApp"],close:["popWindow"],title:["setTitle"],navigationBar:["hideBackButton","showBackButton"],systemInfo:["getSystemInfo"],mtop:[],behaviors:{getNetworkType:"networkInfo",addNotifyListener:"notifySubscribe",removeNotifyListener:"notifyUnsubscribe",postNotification:"notifyPost"},noop:["postWebViewMessage","setGestureBack"],silent:["getNetworkType"]},schemes:COMMON_SCHEME_RULES,nativeBack:ALIPAY_NATIVE_BACK},koubei:{name:"koubei",label:"口碑",appName:"KB",defaultAppVersion:"9.5.0",uaTokens:["KoubeiClient/{v}"],globals:{},bridges:[{global:"AlipayJSBridge",style:"alipay"}],activeEvents:[],actions:{open:["pushWindow","startApp"],close:["popWindow"],title:["setTitle"],navigationBar:["hideBackButton","showBackButton"],systemInfo:["getSystemInfo"],mtop:[],behaviors:{getNetworkType:"networkInfo",addNotifyListener:"notifySubscribe",removeNotifyListener:"notifyUnsubscribe",postNotification:"notifyPost"},noop:["postWebViewMessage","setGestureBack"],silent:["getNetworkType"]},schemes:COMMON_SCHEME_RULES,nativeBack:ALIPAY_NATIVE_BACK},"taobao-tj":{name:"taobao-tj",label:"淘宝特价版",appName:"LT",defaultAppVersion:"10.32.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},"taobao-live":{name:"taobao-live",label:"淘宝直播",appName:"TAOBAOLIVEAPP",defaultAppVersion:"3.10.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},xianyu:{name:"xianyu",label:"闲鱼",appName:"FM",defaultAppVersion:"7.15.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},etao:{name:"etao",label:"一淘",appName:"ET",defaultAppVersion:"9.27.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},eleme:{name:"eleme",label:"饿了么",appName:"ELMC",defaultAppVersion:"11.12.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},damai:{name:"damai",label:"大麦",appName:"DM",defaultAppVersion:"8.9.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},btrip:{name:"btrip",label:"阿里商旅",appName:"BLX",defaultAppVersion:"9.12.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE,{global:"methodChannel",style:"btrip"}],activeEvents:WV_ACTIVE_EVENTS,actions:mergeActions(WV_ACTIONS,{...emptyActions(),open:["goto"],behaviors:{back:"closeBackData"}}),schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},amap:{name:"amap",label:"高德地图",appName:"amap",defaultAppVersion:"13.8.0",uaTokens:[],globals:{},bridges:[{global:"AmapApp.bridge",style:"amap"}],activeEvents:[],actions:{open:["loadSchema","infoH5JsAction"],close:[],title:["setWebViewTitle"],systemInfo:[],mtop:[],noop:["interceptNativeBackEvent"]},schemes:COMMON_SCHEME_RULES,nativeBack:{handler:"onNativeBackEvent"}},qianwen:{name:"qianwen",label:"千问",appName:"TONGYI",defaultAppVersion:"3.20.0",uaTokens:[],globals:{},bridges:[{global:"ucapi",style:"invoke"}],activeEvents:[],actions:{open:["biz.openPageUrl","webdialog.show"],close:["biz.closeWebPage","webdialog.pop"],title:[],systemInfo:[],mtop:[],behaviors:{"base.postmessage":"postMessage","biz.popToRootWindow":"closeAll","biz.popToTopChatWindow":"closeAll"},noop:[]},schemes:COMMON_SCHEME_RULES,messageEvent:"QKEVT_OnReceiveMessage"},lingyou:{name:"lingyou",label:"翎游",appName:"hongtu",defaultAppVersion:"1.5.0",uaTokens:["hongtu/{v}"],globals:{},bridges:[{global:"WKWebViewJavascriptBridge",style:"callHandler"},{global:"WebViewJavascriptBridge",style:"callHandler"}],activeEvents:[],actions:{...emptyActions(),open:["jumpPage"],close:["closePage"],title:["setPageTitle"]},schemes:COMMON_SCHEME_RULES},didi:{name:"didi",label:"滴滴出行",appName:"didi.passenger",defaultAppVersion:"6.9.0",uaTokens:["didi.passenger/{v}"],globals:{},bridges:[{global:"didiBridge",style:"didi"},{global:"Fusion",style:"didi"}],activeEvents:[],actions:{...emptyActions(),open:["openPage"],close:["closePage"]},schemes:COMMON_SCHEME_RULES},easybike:{name:"easybike",label:"易到用车",appName:"easybike",defaultAppVersion:"9.0.0",uaTokens:["app=easybike;"],globals:{},bridges:[{global:"webkit.messageHandlers.callNative",style:"easybikeNative"},{global:"AppFunctions",style:"easybikeNative"}],activeEvents:[],actions:mergeActions(WV_ACTIONS,{...emptyActions(),close:["business/hitch.closeWebView"]}),schemes:COMMON_SCHEME_RULES}};function buildAppProfileUa(profile,options={}){let os11=options.os??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileOs:void 0)??"ios",version2=options.appVersion??profile.defaultAppVersion,deviceModel=options.deviceModel??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileModel:void 0)??"Pixel 11";if(profile.uaFamily==="wechatMiniProgram")return os11==="android"?`Mozilla/5.0 (Linux; Android 17; ${deviceModel}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/152.0.0.0 Mobile MicroMessenger/${version2} WeChat/arm64 NetType/WIFI Language/zh_CN miniProgram`:`Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/${version2} NetType/WIFI Language/zh_CN miniProgram`;let tokens=profile.uaTokens.map(t=>t.replaceAll("{v}",version2)).filter(Boolean),tail=tokens.length>0?` ${tokens.join(" ")}`:"";return os11==="android"?`Mozilla/5.0 (Linux; Android 17; ${deviceModel}) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/152.0.0.0 Mobile Safari/537.36 AliApp(${profile.appName}/${version2})${tail}`:`Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) AliApp(${profile.appName}/${version2})${tail}`}function resolveAppProfile(name,options={}){let profile=APP_PROFILES[name];if(!profile)throw new Error(`Unknown app profile "${name}". Available: ${Object.keys(APP_PROFILES).join(", ")}`);let os11=options.os??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileOs:void 0)??"ios",version2=options.appVersion??profile.defaultAppVersion,recommendedPreset=os11==="android"?"pixel-11":"iphone-17-pro",devicePreset=options.devicePreset??recommendedPreset,emulation=resolveEmulationConfig({enabled:!0,preset:devicePreset,orientation:options.orientation}),deviceModel=options.deviceModel??DEVICE_PRESETS[devicePreset].appProfileModel,globals={...profile.globals,__APP_NAME__:profile.appName,__APP_VERSION__:version2,__FLI_DEVICE_MODEL__:deviceModel,__DEVICE_MODEL__:deviceModel},ua=buildAppProfileUa(profile,{...options,os:os11,deviceModel});return{profile:profile.name,label:profile.label,ua,injected:{profile:profile.name,label:profile.label,globals,bridges:profile.bridges,activeEvents:profile.activeEvents,maxTouchPoints:5,statusBarHeight:emulation.safeAreaInsets.top,safeAreaInsets:emulation.safeAreaInsets,deviceAppearance:{preset:devicePreset,orientation:emulation.orientation,cutout:emulation.appearance.cutout},language:"zh-Hans",userAgent:ua,navigatorPlatform:os11==="android"?"Linux armv8l":"iPhone",platform:os11==="android"?"Android":"iOS",systemVersion:os11==="android"?"17":"26.0",clientType:os11==="android"?"android":"iphone",actions:applyAppBridgeConfig(profile.actions,options.bridgeConfig),schemes:profile.schemes,...profile.miniProgram&&{miniProgram:profile.miniProgram},...profile.imagePicker&&{imagePicker:profile.imagePicker},...profile.geolocation&&{geolocation:profile.geolocation},...profile.overlay&&{overlay:profile.overlay},...profile.popBeforeOpenParam&&{popBeforeOpenParam:profile.popBeforeOpenParam},...profile.messageEvent&&{messageEvent:profile.messageEvent},...profile.nativeBack&&{nativeBack:profile.nativeBack},...profile.layerUrlProxy&&{layerUrlProxy:profile.layerUrlProxy},...profile.urlSyncHostSuffixes&&{urlSyncHostSuffixes:profile.urlSyncHostSuffixes},...profile.forceH5Mtop&&{forceH5Mtop:!0},simulateSystemBars:!1,rootContainer:{enabled:!1,...profile.rootContainer?.statusBarHeightCookie&&{initialCookies:[{...profile.rootContainer.statusBarHeightCookie,value:String(emulation.safeAreaInsets.top)}]}},titleBar:{navigationBarHeight:os11==="android"?48:44,backgroundColor:"#ffffff",textColor:"#0f131a",...profile.titleBarHiddenPathnames&&{hiddenPathnames:profile.titleBarHiddenPathnames},...profile.statusBarBackgroundColors&&{statusBarBackgroundColors:profile.statusBarBackgroundColors},...profile.titleBarHostStyles&&{hostStyles:profile.titleBarHostStyles}}},recommendedPreset}}function installAppProfileEnvironment(config2){let w=window;if(w.__mearlAppProfile__)return null;w.__mearlAppProfile__=config2.profile;let SRC="mearl-app-bridge",TAG=`[AppBridge:${config2.label}]`,ROOT_FRAME_NAME="__mearl_root__",LAYER_FRAME_NAME="__mearl_layer__",isTop=window===window.top,isRootFrame=!isTop&&window.name===ROOT_FRAME_NAME,isLayerFrame=!isTop&&window.name===LAYER_FRAME_NAME,isContainerFrame=isTop||isRootFrame||isLayerFrame,usesRootContainer=isTop&&config2.rootContainer?.enabled===!0,simulateSystemBars=config2.simulateSystemBars!==!1,safeAreaInsets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0},log2=(...args)=>console.info(TAG,...args);for(let[key,value]of Object.entries(config2.globals))try{w[key]=value}catch{}typeof w.__STATUS_BAR_HEIGHT__!="number"&&(w.__STATUS_BAR_HEIGHT__=config2.statusBarHeight),typeof w.__SAFE_AREA_INSET_BOTTOM__!="number"&&(w.__SAFE_AREA_INSET_BOTTOM__=safeAreaInsets.bottom);let applySafeAreaCssVariables=()=>{let root=document.documentElement;if(!root)return!1;try{return root.style.setProperty("--safe-area-inset-top",`${safeAreaInsets.top}px`),root.style.setProperty("--safe-area-inset-right",`${safeAreaInsets.right}px`),root.style.setProperty("--safe-area-inset-bottom",`${safeAreaInsets.bottom}px`),root.style.setProperty("--safe-area-inset-left",`${safeAreaInsets.left}px`),!0}catch{return!1}};if(!applySafeAreaCssVariables()){let observer=new MutationObserver(()=>{applySafeAreaCssVariables()&&observer.disconnect()});observer.observe(document,{childList:!0})}if(config2.forceH5Mtop){let downstreamMtopParamsHandler=w.MTOP_PARAMS_HANDLER,forceH5Mtop=params=>{let resolved=params;if(typeof downstreamMtopParamsHandler=="function")try{resolved=downstreamMtopParamsHandler.call(window,params)??params}catch{resolved=params}return{...resolved&&typeof resolved=="object"?resolved:{},useNative:!1}};try{Object.defineProperty(w,"MTOP_PARAMS_HANDLER",{configurable:!0,get:()=>forceH5Mtop,set:handler=>{handler!==forceH5Mtop&&(downstreamMtopParamsHandler=handler)}})}catch{w.MTOP_PARAMS_HANDLER=forceH5Mtop}}for(let[key,value]of[["userAgent",config2.userAgent],["platform",config2.navigatorPlatform],["vendor","Apple Computer, Inc."],["appVersion",config2.userAgent.replace(/^Mozilla\//,"")]])try{Object.defineProperty(navigator,key,{get:()=>value,configurable:!0})}catch{}try{Object.defineProperty(navigator,"maxTouchPoints",{get:()=>config2.maxTouchPoints})}catch{}return{w,SRC,TAG,ROOT_FRAME_NAME,LAYER_FRAME_NAME,isTop,isRootFrame,isLayerFrame,isContainerFrame,usesRootContainer,simulateSystemBars,safeAreaInsets,log:log2}}function installAppProfileSystemBars(config2,environment,host){let{SRC,isTop,isContainerFrame,simulateSystemBars,safeAreaInsets}=environment,externalDeviceChrome=config2.externalDeviceChrome===!0,titleBarMode="auto",titleBarRoot=null,titleBarSpacer=null,systemStatusView=null,systemBottomRoot=null,systemBottomSurface=null,rootTitleBarView=null,titleBarTitleVisible=!0,titleBarBackVisible=!0,titleBarBackground=config2.titleBar?.backgroundColor??"#ffffff",titleBarTextColor=config2.titleBar?.textColor??"#111111",titleBarStateExplicit=!1,presentedRootTitleBarState=null,normalizeProxyPathPrefix=prefix=>{let withLeadingSlash=prefix.startsWith("/")?prefix:`/${prefix}`;return withLeadingSlash.endsWith("/")?withLeadingSlash:`${withLeadingSlash}/`},matchesProxyTarget=(hostname3,suffixes)=>suffixes.some(suffix=>hostname3===suffix||hostname3.endsWith(`.${suffix}`)),normalizePathname=pathname=>{let withLeadingSlash=pathname.startsWith("/")?pathname:`/${pathname}`;return withLeadingSlash.length>1&&withLeadingSlash.endsWith("/")?withLeadingSlash.slice(0,-1):withLeadingSlash},businessPathname=href=>{try{let current=new URL(href,location.href),proxy=config2.layerUrlProxy;if(!proxy)return normalizePathname(current.pathname);let prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(!current.pathname.startsWith(prefix))return normalizePathname(current.pathname);let rest=current.pathname.slice(prefix.length),slash=rest.indexOf("/"),hostName=slash===-1?rest:rest.slice(0,slash),pathname=slash===-1?"/":rest.slice(slash),hostname3=new URL(`${current.protocol}//${hostName}`).hostname;return matchesProxyTarget(hostname3,proxy.targetHostSuffixes)?normalizePathname(pathname):normalizePathname(current.pathname)}catch{return null}},matchesConfiguredPathname=(href,pathnames)=>{let pathname=businessPathname(href);return pathname!==null&&pathnames.some(configuredPathname=>normalizePathname(configuredPathname)===pathname)},configuredHostStyle=(href=location.href)=>{try{let hostname3=new URL(href,location.href).hostname.toLowerCase();return(config2.titleBar?.hostStyles??[]).find(rule=>{let suffix=rule.hostSuffix.trim().replace(/^\.+/,"").toLowerCase();return suffix!==""&&(hostname3===suffix||hostname3.endsWith(`.${suffix}`))})}catch{return}},configuredTitleBarBackground=(href,fallback)=>configuredHostStyle(href)?.titleBarBackgroundColor??fallback,supportsWindVaneNavigationMeta=config2.bridges.some(bridge=>bridge.style==="windvane"),isTruthyParam=value=>value==="1"||value?.toLowerCase()==="true"||value?.toUpperCase()==="YES",isTransparentColor=value=>{let normalized=value.replace(/\s/g,"").toLowerCase();return normalized==="transparent"||normalized==="#0000"||normalized==="#00000000"||normalized==="rgba(0,0,0,0)"},fixedContainerTitleBarMode=()=>config2.profile==="wechat"?"normal":null,pageRequestedTitleBarMode=(href=location.href,includeMeta=!0)=>{try{let params=new URL(href,location.href).searchParams,webviewOptions=new URLSearchParams(params.get("__webview_options__")??""),option=key=>params.get(key)??webviewOptions.get(key);if(config2.profile==="fliggy"||config2.profile==="taobao"){let hidden=option("titleBarHidden");if(hidden==="1")return"status-inset";if(hidden==="2")return"status"}if(config2.profile==="taobao"&&option("disableNav")?.toUpperCase()==="YES")return isTruthyParam(option("status_bar_transparent"))?"status":"status-inset";if(config2.profile==="alipay"||config2.profile==="koubei"){if(option("showTitleBar")?.toUpperCase()==="NO")return"status-inset";let transparentTitle=option("transparentTitle")?.toLowerCase();if(transparentTitle&&["always","auto","custom"].includes(transparentTitle))return"overlay"}let overlayParam=config2.overlay?.enabledParam;return overlayParam&&isTruthyParam(params.get(overlayParam))?"status":!includeMeta||!supportsWindVaneNavigationMeta?null:document.getElementById("WV.Meta.Nav.HideNavBar")?.getAttribute("value")==="HideStatusBar"?"status":null}catch{return null}},pageRequestsHiddenTitleBar=(href=location.href)=>matchesConfiguredPathname(href,config2.titleBar?.hiddenPathnames??[]),configuredStatusBarBackground=(href=location.href)=>{let colors=config2.titleBar?.statusBarBackgroundColors??{},pathname=businessPathname(href);return pathname===null?null:Object.entries(colors).find(([configuredPathname])=>normalizePathname(configuredPathname)===pathname)?.[1]??configuredHostStyle(href)?.statusBarBackgroundColor??null},pageRequestsHiddenStatusBar=(href=location.href)=>{try{let params=new URL(href,location.href).searchParams;return isTruthyParam(params.get("statusBarHidden"))||isTruthyParam(params.get("hideStatusBar"))?!0:/(?:^|&)showStatusBar=NO(?:&|$)/i.test(params.get("__webview_options__")??"")}catch{return!1}},resolveTitleBarMode=(href,fallback,includeMeta)=>{let fixedMode=fixedContainerTitleBarMode();if(fixedMode)return fixedMode;if(titleBarMode!=="auto")return titleBarMode;if(pageRequestsHiddenStatusBar(href))return"hidden";if(pageRequestsHiddenTitleBar(href))return"status-inset";let requestedMode=pageRequestedTitleBarMode(href,includeMeta);return requestedMode||fallback},resolveStatusBarBackground=(href,mode,navigationBarBackground)=>configuredStatusBarBackground(href)??(mode==="normal"||mode==="status-inset"?navigationBarBackground:"transparent"),ownTitleBarState=()=>{let mode=resolveTitleBarMode(location.href,"normal",!0),background=configuredTitleBarBackground(location.href,titleBarBackground);return{mode,title:document.title||config2.label,titleVisible:titleBarTitleVisible,backVisible:titleBarBackVisible,background,statusBarBackground:resolveStatusBarBackground(location.href,mode,background),textColor:titleBarTextColor}},initialLayerTitleBarState=url2=>{let mode=fixedContainerTitleBarMode()??(pageRequestsHiddenStatusBar(url2)?"hidden":pageRequestsHiddenTitleBar(url2)?"status-inset":pageRequestedTitleBarMode(url2,!1)??"normal"),background=configuredTitleBarBackground(url2,config2.titleBar?.backgroundColor??"#ffffff");return{mode,title:config2.label,titleVisible:!0,backVisible:!0,background,statusBarBackground:mode==="status-inset"?background:resolveStatusBarBackground(url2,mode,background),textColor:config2.titleBar?.textColor??"#111111"}},parseReportedTitleBarState=value=>{if(!value||typeof value!="object")return null;let state=value;return!["normal","overlay","status","status-inset","hidden"].includes(String(state.mode))||typeof state.title!="string"||typeof state.titleVisible!="boolean"||typeof state.backVisible!="boolean"||typeof state.background!="string"||typeof state.textColor!="string"?null:{...state,statusBarBackground:typeof state.statusBarBackground=="string"?state.statusBarBackground:state.mode==="normal"||state.mode==="status-inset"?String(state.background):"transparent"}},resolvedTitleBarState=layer=>layer?layer.titleBarState??initialLayerTitleBarState(layer.url):presentedRootTitleBarState??ownTitleBarState(),resolvedRootTitleBarState=(fallback=ownTitleBarState())=>presentedRootTitleBarState??(host.getRootFrame()?{...fallback,statusBarBackground:configuredHostStyle(location.href)?.statusBarBackgroundColor??config2.titleBar?.backgroundColor??"#ffffff"}:fallback),renderNavigationBarView=(view,state)=>{let visible=state.mode==="normal"||state.mode==="overlay";view.root.style.display=visible?"block":"none",view.surface.style.visibility=visible?"visible":"hidden",view.surface.style.background=state.mode==="overlay"?"transparent":state.background,view.surface.style.borderBottom="none",view.surface.style.color=state.textColor,view.title.textContent=state.title,view.title.style.display=state.titleVisible?"block":"none",view.back.style.display=state.backVisible?"flex":"none",view.back.style.color=state.textColor},topFullLayer=()=>{let layers=host.getLayers();for(let index=layers.length-1;index>=0;index-=1)if(!layers[index].overlay&&!layers[index].closing)return layers[index]},activeTitleBarState=()=>{let layer=topFullLayer();return layer?resolvedTitleBarState(layer):resolvedRootTitleBarState()},syncActiveSystemBars=()=>{let state=activeTitleBarState();if(externalDeviceChrome&&isTop&&window.postMessage({source:"mearl-app-profile-runtime",type:"device-chrome-state",state:{statusBarBackground:state.statusBarBackground,textColor:state.textColor,bridgeConfig:{profile:config2.profile,actions:config2.actions}}},"*"),systemStatusView){let visible=state.mode!=="hidden";systemStatusView.root.style.display=visible?"block":"none",systemStatusView.surface.style.visibility=visible?"visible":"hidden",systemStatusView.surface.style.background=state.statusBarBackground,systemStatusView.surface.style.color=state.textColor}systemBottomRoot&&systemBottomSurface&&(systemBottomRoot.style.display=safeAreaInsets.bottom>0?"block":"none",systemBottomSurface.style.color=state.textColor)},syncLayerViewport=(layer,state)=>{if(layer.overlay)return;if(!simulateSystemBars){layer.frame.style.top="0px",layer.frame.style.height="100%";return}let totalHeight=config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0),offset=state.mode==="normal"?totalHeight:state.mode==="status-inset"?config2.statusBarHeight:0;layer.frame.style.top=`${offset}px`,layer.frame.style.height=offset>0?`calc(100% - ${offset}px)`:"100%",layer.frame.setAttribute("data-mearl-app-viewport-mode",state.mode),layer.frame.style.setProperty("--mearl-app-navigation-bar-height",`${config2.titleBar?.navigationBarHeight??0}px`),layer.frame.style.opacity=state.mode==="status-inset"&&!layer.titleBarStateReady?"0":"1",layer.titleBarView&&renderNavigationBarView(layer.titleBarView,state),topFullLayer()===layer&&syncActiveSystemBars()},syncRootFrameViewport=state=>{let rootFrame=host.getRootFrame();if(!rootFrame)return;if(!simulateSystemBars){rootFrame.style.top="0px",rootFrame.style.height="100%";return}let totalHeight=config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0),offset=state.mode==="normal"?totalHeight:state.mode==="status-inset"?config2.statusBarHeight:0;rootFrame.style.top=`${offset}px`,rootFrame.style.height=offset>0?`calc(100% - ${offset}px)`:"100%",rootFrame.setAttribute("data-mearl-app-viewport-mode",state.mode),rootFrame.style.setProperty("--mearl-app-navigation-bar-height",`${config2.titleBar?.navigationBarHeight??0}px`),rootFrame.style.opacity=state.mode==="status-inset"&&presentedRootTitleBarState===null&&!rootFrame.hasAttribute("data-mearl-webview-ready")?"0":"1"},syncSimulatedTitleBar=()=>{let ownState=ownTitleBarState();if(!isTop){if(isContainerFrame){if(!titleBarStateExplicit&&document.readyState==="loading")return;window.top?.postMessage({source:SRC,type:"titleBarState",state:ownState,explicit:titleBarStateExplicit},"*")}return}if(!titleBarRoot||!titleBarSpacer||!rootTitleBarView)return;let rootFrame=host.getRootFrame();!rootFrame&&host.getLayers().length===0&&host.getClosingLayerCount()===0&&(presentedRootTitleBarState=ownState);let state=resolvedRootTitleBarState(ownState);renderNavigationBarView(rootTitleBarView,state);let spacerHeight=state.mode==="normal"?config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0):state.mode==="status-inset"?config2.statusBarHeight:0;titleBarSpacer.style.display=!rootFrame&&spacerHeight>0?"block":"none",titleBarSpacer.style.height=`${spacerHeight}px`,titleBarSpacer.style.minHeight=`${spacerHeight}px`,syncRootFrameViewport(state),syncActiveSystemBars()},applyNavigationBarState=(api,params)=>{titleBarStateExplicit=!0;let p=params&&typeof params=="object"?params:{},displayValue=p.titlebar_display??p.titlebarDisplay??p.titleBarDisplay,display=typeof displayValue=="string"?displayValue.toLowerCase():"";api==="hideBackButton"&&(titleBarBackVisible=!1),api==="showBackButton"&&(titleBarBackVisible=!0),display==="hide"&&(titleBarMode="status"),display==="show"&&(titleBarMode="normal"),(p.isImmersive===!0||p.isTransparent===!0)&&(titleBarMode="overlay"),p.isImmersive===!1&&p.isTransparent===!1&&(titleBarMode="normal"),typeof p.isTitleVisible=="boolean"&&(titleBarTitleVisible=p.isTitleVisible),typeof p.title=="string"&&(document.title=p.title),typeof p.backgroundColor=="string"&&(titleBarBackground=p.backgroundColor,isTransparentColor(p.backgroundColor)&&(titleBarMode="overlay")),typeof p.barTextStyle=="string"&&(titleBarTextColor=p.barTextStyle==="white"?"#ffffff":"#111111"),syncSimulatedTitleBar()},applyStatusBarState=params=>{titleBarStateExplicit=!0;let p=params&&typeof params=="object"?params:{},style=typeof p.style=="string"?p.style.toLowerCase():"";style&&(titleBarTextColor=style==="white"||style.includes("light")?"#ffffff":"#111111"),syncSimulatedTitleBar()},createNavigationBarView=(placement,onBack)=>{let titleBar=config2.titleBar,root=document.createElement("div");root.setAttribute("data-mearl-app-titlebar",config2.profile),root.setAttribute("data-mearl-titlebar-owner",placement);let splitRoot=placement==="root"&&config2.rootContainer?.splitScreen===!0;splitRoot&&root.setAttribute("data-mearl-split-pane","left-titlebar"),root.style.cssText=`${placement==="root"?"position:fixed":"position:absolute"};left:0;${splitRoot?"right:auto;width:50%;":"right:0;"}top:${config2.statusBarHeight}px;height:${titleBar.navigationBarHeight}px;z-index:${placement==="root"?"2147482900":"2"};overflow:hidden;box-sizing:border-box;font-family:"PingFang SC",-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;`;let shadow=root.attachShadow({mode:"open"});shadow.innerHTML=`<style>
150
+ })();`;async function ensureControlledIndicator(session,controlSource="local"){return enqueueIndicatorOperation(session,async()=>{let current=injectedSessions.get(session);if(current?.controlSource!==controlSource){injectedSessions.set(session,{identifier:null,controlSource});try{await ensureCdpDomain(session.client,"Page"),current?.identifier&&await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:current.identifier}).catch(()=>{});let result=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:createFaviconScript(controlSource),runImmediately:!0});injectedSessions.set(session,{identifier:result?.identifier??null,controlSource})}catch{injectedSessions.delete(session)}}})}async function releaseControlledIndicator(session){return enqueueIndicatorOperation(session,async()=>{let current=injectedSessions.get(session);injectedSessions.delete(session),current?.identifier&&await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:current.identifier}).catch(()=>{}),await session.client.sendCommand("Runtime.evaluate",{expression:RESTORE_FAVICON_SCRIPT}).catch(()=>{})})}var actionMap=new Map;function registerActions(actions){for(let action of actions){if(actionMap.has(action.name))throw new Error(`CDP action "${action.name}" is already registered`);actionMap.set(action.name,action)}}function getRegisteredActionNames(){return[...actionMap.keys()]}async function dispatchCdpAction(cdpSession2,action,data,controlSource="local"){let entry=actionMap.get(action);if(!entry)throw new Error(`Action "${action}" is not supported in CDP mode`);if(entry.session==="browser")return entry.handler(cdpSession2,data,controlSource);let tabId=typeof data?.tabId=="number"?data.tabId:void 0,pageSession=await cdpSession2.getPageSession(tabId);return await ensureControlledIndicator(pageSession,controlSource),entry.handler(pageSession,data,controlSource)}var interceptionStates=new WeakMap;function continuePausedRequest(session,params,isResponseStage){return session.client.sendCommand(isResponseStage?"Fetch.continueResponse":"Fetch.continueRequest",{requestId:params.requestId}).catch(()=>{})}function createInterceptionState(session){let handlers=new Map,disposeListener=session.client.on("Fetch.requestPaused",async params=>{let isResponseStage=params.responseStatusCode!=null||params.responseErrorReason!=null,orderedHandlers=[...handlers.values()].sort((a,b)=>b.priority-a.priority);for(let{handler}of orderedHandlers)try{if(await handler({session,params,isResponseStage}))return}catch{}await continuePausedRequest(session,params,isResponseStage)}),state={handlers,setupPromise:Promise.resolve(),disposeListener};return state.setupPromise=session.client.sendCommand("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"},{urlPattern:"*",requestStage:"Response"}]}).catch(error48=>{throw disposeListener(),interceptionStates.get(session)===state&&interceptionStates.delete(session),error48}),state}async function registerCdpFetchPauseHandler(session,key,priority,handler){let state=interceptionStates.get(session);state||(state=createInterceptionState(session),interceptionStates.set(session,state)),state.handlers.set(key,{priority,handler}),await state.setupPromise}async function unregisterCdpFetchPauseHandler(session,key){let state=interceptionStates.get(session);state&&(state.handlers.delete(key),!(state.handlers.size>0)&&(await state.setupPromise.catch(()=>{}),!(interceptionStates.get(session)!==state||state.handlers.size>0)&&(interceptionStates.delete(session),state.disposeListener(),await session.client.sendCommand("Fetch.disable",{}).catch(()=>{}))))}function clearCdpFetchInterceptionState(sessions){if(!sessions){interceptionStates=new WeakMap;return}for(let session of sessions)interceptionStates.get(session)?.disposeListener(),interceptionStates.delete(session)}function ensureCorsHeaders(headers,request){let origin=Object.entries(request.headers??{}).find(([name])=>name.toLowerCase()==="origin")?.[1];if(!origin)return headers;let result=[...headers],setHeader2=(name,value)=>{let existing=result.find(header=>header.name.toLowerCase()===name);existing?existing.value=value:result.push({name,value})};return setHeader2("access-control-allow-origin",origin),setHeader2("access-control-allow-credentials","true"),result}var mockStore=new Map;function clearCdpMockState(){mockStore.clear()}function tryParseJson(value){try{return JSON.parse(value)}catch{return value}}function isSubset(subset,superset){return subset===superset?!0:subset==null||superset==null?subset===superset:typeof subset!="object"||typeof superset!="object"?String(subset)===String(superset):Array.isArray(subset)?Array.isArray(superset)&&JSON.stringify(subset)===JSON.stringify(superset):Object.entries(subset).every(([key,value])=>key in superset?isSubset(value,superset[key]):!1)}function matchesConditions(mock,request){if(!mock.conditions||Object.keys(mock.conditions).length===0)return!0;let requestData={};try{new URL(request.url??"").searchParams.forEach((value,key)=>{requestData[key]=tryParseJson(value)})}catch{}if(request.postData)try{let json2=JSON.parse(request.postData);typeof json2=="object"&&json2!==null&&Object.assign(requestData,json2)}catch{try{new URLSearchParams(request.postData).forEach((value,key)=>{requestData[key]=tryParseJson(value)})}catch{}}return isSubset(mock.conditions,requestData)?!0:requestData.data&&typeof requestData.data=="object"?isSubset(mock.conditions,requestData.data):!1}function findMatchedMock(url2,postData){for(let list of mockStore.values())for(let mock of list)if(mock.enabled&&(url2.includes(`/${mock.apiName}/`)||url2.includes(mock.apiName))&&matchesConditions(mock,{url:url2,postData}))return mock;return null}function sameConditions(a,b){let aKeys=a?Object.keys(a):[],bKeys=b?Object.keys(b):[];return aKeys.length===0||bKeys.length===0?aKeys.length===0&&bKeys.length===0:aKeys.length!==bKeys.length?!1:aKeys.every(k=>JSON.stringify(a[k])===JSON.stringify(b[k]))}async function handleMockRequest({session,params,isResponseStage}){let url2=params.request?.url??"";if(params.request?.method==="OPTIONS")return!1;let matchedMock=findMatchedMock(url2,params.request?.postData),fulfillMock=async(mock,responseCode,responseHeaders)=>{let{body:responseBody}=serializeMockResponse(url2,mock.responseData),base64Body=Buffer.from(responseBody,"utf-8").toString("base64");await session.client.sendCommand("Fetch.fulfillRequest",{requestId:params.requestId,responseCode,responseHeaders,body:base64Body})};if(!matchedMock)return!1;try{if(!isResponseStage){if(matchedMock.duration!==void 0){matchedMock.duration>0&&await new Promise(r=>setTimeout(r,matchedMock.duration));let{isJsonp:isJsonp2}=serializeMockResponse(url2,matchedMock.responseData),responseHeaders=prepareMockResponseHeaders([{name:"content-type",value:"application/json; charset=utf-8"},{name:"x-mock-by",value:"mearl-cdp"}],isJsonp2);await fulfillMock(matchedMock,200,ensureCorsHeaders(responseHeaders,params.request))}else return!1;return!0}if(matchedMock.duration!==void 0)return!1;let{isJsonp}=serializeMockResponse(url2,matchedMock.responseData);return await fulfillMock(matchedMock,params.responseStatusCode??200,ensureCorsHeaders(prepareMockResponseHeaders(params.responseHeaders,isJsonp),params.request)),!0}catch{return!1}}async function ensureMockInterception(session){await registerCdpFetchPauseHandler(session,"mock",100,handleMockRequest)}async function cdpSetMock(session,data){let{apiName,mockData,fields,enabled,duration:duration3,conditions}=data;if(!apiName||typeof apiName!="string"||apiName.trim()==="")throw new Error("Invalid apiName");if(enabled===!1)return mockStore.delete(apiName),{success:!0,affectedCount:1,message:`Mock disabled for ${apiName}`};if(mockData===void 0&&(!fields||fields.length===0))throw new Error("Either mockData or fields must be provided");if(fields&&fields.length>100)throw new Error("Too many fields: maximum 100 fields allowed");let normConditions=conditions&&Object.keys(conditions).length>0?conditions:void 0,finalMockData=mockData;if(fields&&fields.length>0){let conditionMatcher={apiName,responseData:null,conditions:normConditions,enabled:!0},baseRequest=[...session.buffers.requests].reverse().find(request=>request.method!=="OPTIONS"&&request.responseBody!==null&&request.responseBody!==void 0&&(request.apiName?.includes(apiName)||request.url?.includes(apiName))&&matchesConditions(conditionMatcher,{url:request.url,postData:typeof request.postData=="string"?request.postData:void 0}));finalMockData=baseRequest?.responseBody?JSON.parse(JSON.stringify(baseRequest.responseBody)):{};for(let field of fields)setValueByPath(finalMockData,field.path,field.value)}let entry={apiName,responseData:finalMockData,duration:duration3,conditions:normConditions,enabled:!0},list=mockStore.get(apiName)??[],idx=list.findIndex(m=>sameConditions(m.conditions,normConditions));return idx>=0?list[idx]=entry:list.push(entry),mockStore.set(apiName,list),await ensureMockInterception(session),{success:!0,affectedCount:1,message:`Mock set for ${apiName}`}}function cdpGetMocks(_session,data){let matcher=data?.apiName?new RegExp(data.apiName,"i"):null,mocks=[...mockStore.values()].flat().filter(m=>!matcher||matcher.test(m.apiName)).map(m=>({apiName:m.apiName,responseData:m.responseData,duration:m.duration??0,conditions:m.conditions,disabled:!m.enabled}));return{mocks,count:mocks.length}}registerActions([{name:"set_mock",session:"page",handler:cdpSetMock},{name:"get_mocks",session:"page",handler:async(s,d)=>cdpGetMocks(s,d)}]);var WINDVANE="WindVane/8.7.0",WV_BRIDGE={global:"WindVane",style:"windvane"},MEGA_BRIDGE={global:"__megability_bridge__",style:"mega"},WV_NATIVE_BACK={event:"wvBackClickEvent",controlFunction:"_windvane_backControl"},FLIGGY_NATIVE_BACK={event:"WV.Back"},ALIPAY_NATIVE_BACK={event:"back"},FLIGGY_OVERLAY={enabledParam:"_fli_overlay",topRatioParam:"_fli_overlay_ratio",radiusParam:"_fli_overlay_radius",maskAlphaParam:"_fli_overlay_mask_alpha",tapCloseParam:"_fli_overlay_tap_close",tapCloseSelectors:["#qwen-titlebar .qwen-titlebar-icon-wrapper:last-child"],silentTapClose:!0,defaultTopRatio:.2,defaultRadius:0,defaultMaskAlpha:.3,defaultTapClose:!0},TAOBAO_OVERLAY={enabledParam:"useWebdialog",topRatioParam:"topRatio",heightRatioParam:"height_pct",radiusParam:"cornerRadius",maskAlphaParam:"maskAlpha",tapCloseParam:"tapEnable",tapCloseSelectors:["#qwen-titlebar .qwen-titlebar-icon-wrapper:last-child"],defaultTopRatio:.2,defaultRadius:6,defaultMaskAlpha:.5,defaultTapClose:!0},FLIGGY_IMAGE_PICKER={schemes:["page://ask_take_photo"],api:"mtop.trip.serverless.api.gateway",version:"2.0",fcId:"240417431173407785",fcGroup:"fl-images",uploadUrlFunction:"uploadByTokenUrl",prefix:"temp",region:"CN"},FLIGGY_LAYER_URL_PROXY={sourceHostPrefix:"edith.",pathPrefix:"/proxy/",targetHostSuffixes:["wapa.taobao.com"],defaultTargetHost:"market.wapa.taobao.com"},FLIGGY_ROOT_CONTAINER={statusBarHeightCookie:{name:"_fli_barHeight",domain:"taobao.com",path:"/"}},FLIGGY_TITLE_BAR_HIDDEN_PATHNAMES=["/app/trip/rx-home/pages/home","/app/trip/rx-trip-ai/pages/home"],FLIGGY_STATUS_BAR_BACKGROUND_COLORS={"/app/trip/rx-home/pages/home":"#fff","/app/trip/rx-trip-ai/pages/home":"#dbdbff"};function emptyActions(){return{open:[],close:[],title:[],navigationBar:[],statusBar:[],systemInfo:[],mtop:[],kvGet:[],kvSet:[],kvDelete:[],pageContext:[],responses:{},behaviors:{},noop:[],silent:[]}}function mergeActions(...maps){let out=emptyActions();for(let m of maps)out.open.push(...m.open),out.close.push(...m.close),out.title.push(...m.title),out.navigationBar.push(...m.navigationBar??[]),out.statusBar.push(...m.statusBar??[]),out.systemInfo.push(...m.systemInfo),out.mtop.push(...m.mtop),out.kvGet.push(...m.kvGet??[]),out.kvSet.push(...m.kvSet??[]),out.kvDelete.push(...m.kvDelete??[]),out.pageContext.push(...m.pageContext??[]),Object.assign(out.responses,m.responses??{}),Object.assign(out.behaviors,m.behaviors??{}),out.noop.push(...m.noop),out.silent.push(...m.silent??[]);return out}var APP_BRIDGE_BEHAVIORS=["navigate","closeAll","closeBackData","postMessage","notifySubscribe","notifyUnsubscribe","notifyPost","sharedFileRead","sharedFileWrite","sharedDataGet","sharedDataSet","legacyBroadcastCreate","legacyBroadcastPost","legacyBroadcastClose","memoryGet","memorySet","memoryDelete","availabilityMap","userInfo","networkInfo","geolocation","permission","prefetch","fptTrack","mtopStream","previewFile","toast","unsupportedNativeInput","payment","userTrack","calendar","networkQualityMonitor","beaconRequest","voiceRecognition"],APP_BRIDGE_BEHAVIOR_SET=new Set(APP_BRIDGE_BEHAVIORS),BRIDGE_ACTION_ARRAY_KEYS=["open","close","title","navigationBar","statusBar","systemInfo","mtop","kvGet","kvSet","kvDelete","pageContext","noop"];function isJsonValue2(value,seen=new Set){if(value===null||typeof value=="string"||typeof value=="boolean")return!0;if(typeof value=="number")return Number.isFinite(value);if(typeof value!="object"||seen.has(value))return!1;seen.add(value);let valid=Array.isArray(value)?value.every(item=>isJsonValue2(item,seen)):Object.values(value).every(item=>isJsonValue2(item,seen));return seen.delete(value),valid}function validateAppBridgeConfig(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("bridgeConfig must be an object");let root=value;if(Object.keys(root).some(key=>key!=="methods"))throw new Error('bridgeConfig only supports the "methods" field');if(!root.methods||typeof root.methods!="object"||Array.isArray(root.methods))throw new Error("bridgeConfig.methods must be an object");let entries=Object.entries(root.methods);if(entries.length>200)throw new Error("bridgeConfig supports at most 200 methods");let methods2={};for(let[method,rawConfig]of entries){if(!method.trim()||method.length>200)throw new Error("bridgeConfig method names must contain 1-200 characters");if(method==="__proto__"||method==="prototype"||method==="constructor")throw new Error(`bridgeConfig method name "${method}" is reserved`);if(!rawConfig||typeof rawConfig!="object"||Array.isArray(rawConfig))throw new Error(`bridgeConfig.methods.${method} must be an object`);let methodConfig=rawConfig,supportedKeys=new Set(["behavior","response","noop","silent"]);if(Object.keys(methodConfig).some(key=>!supportedKeys.has(key)))throw new Error(`bridgeConfig.methods.${method} contains an unsupported field`);if("behavior"in methodConfig&&typeof methodConfig.behavior!="string")throw new Error(`bridgeConfig.methods.${method}.behavior must be a string`);let hasBehavior=typeof methodConfig.behavior=="string",hasResponse=Object.prototype.hasOwnProperty.call(methodConfig,"response"),hasNoop=methodConfig.noop===!0;if(Number(hasBehavior)+Number(hasResponse)+Number(hasNoop)!==1)throw new Error(`bridgeConfig.methods.${method} must define exactly one of behavior, response, or noop=true`);if(hasBehavior&&!APP_BRIDGE_BEHAVIOR_SET.has(methodConfig.behavior))throw new Error(`bridgeConfig.methods.${method} has an unsupported behavior`);if(hasResponse&&!isJsonValue2(methodConfig.response))throw new Error(`bridgeConfig.methods.${method}.response must be valid JSON data`);if("noop"in methodConfig&&methodConfig.noop!==!0)throw new Error(`bridgeConfig.methods.${method}.noop must be true when provided`);if("silent"in methodConfig&&typeof methodConfig.silent!="boolean")throw new Error(`bridgeConfig.methods.${method}.silent must be a boolean`);methods2[method]={...hasBehavior&&{behavior:methodConfig.behavior},...hasResponse&&{response:JSON.parse(JSON.stringify(methodConfig.response))},...hasNoop&&{noop:!0},...methodConfig.silent===!0&&{silent:!0}}}let normalized={methods:methods2};if(JSON.stringify(normalized).length>65536)throw new Error("bridgeConfig must not exceed 64 KiB");return normalized}function applyAppBridgeConfig(actions,config2){let out=mergeActions(actions);if(!config2)return out;let{methods:methods2}=validateAppBridgeConfig(config2);for(let[method,methodConfig]of Object.entries(methods2)){for(let key of BRIDGE_ACTION_ARRAY_KEYS){let values=out[key];values&&(out[key]=values.filter(value=>value!==method))}out.silent=(out.silent??[]).filter(value=>value!==method),delete out.responses?.[method],delete out.behaviors?.[method],methodConfig.behavior?out.behaviors[method]=methodConfig.behavior:Object.prototype.hasOwnProperty.call(methodConfig,"response")?out.responses[method]=methodConfig.response:methodConfig.noop&&out.noop.push(method),methodConfig.silent&&out.silent.push(method)}return out}var WV_ACTIONS={open:["WVNative.openWindow","Base.openBrowser","EtaoJsbridgeUtil.openWindow","TMBridge.pushWindow","Third.openThirdWeb"],close:["WebAppInterface.pop","Triver.pop","TMBridge.popWindow","EleWVHybridAPI.popWindow","Third.closeWebView"],title:["WebAppInterface.setCustomPageTitle"],navigationBar:["Triver.setNavigationBarStyle"],statusBar:["WebAppInterface.setStatusBarStyle","Application.setStatusBarStyle"],systemInfo:["WVNativeDetector.getModelInfo"],mtop:["MtopWVPlugin.send"],behaviors:{"WVLocation.getLocation":"geolocation","WVNetwork.getNetworkType":"networkInfo","WVFile.read":"sharedFileRead","WVFile.write":"sharedFileWrite","SharedData.getSharedData":"sharedDataGet","SharedData.setSharedData":"sharedDataSet","WVBroadcast.createChannel":"legacyBroadcastCreate","WVBroadcast.postMessage":"legacyBroadcastPost","WVBroadcast.close":"legacyBroadcastClose"},noop:["WVNative.enableHookNativeBack","WVNative.forbidPanGesture","WVNative.setGestureBack","WVTBUserTrack.toUT","WVTBUserTrack.toUT2"],silent:["WVNetwork.getNetworkType","WVNativeDetector.getModelInfo","WVTBUserTrack.toUT","WVTBUserTrack.toUT2"]},COMMON_SCHEME_RULES=[{match:"page:",param:"params"},{match:"taobaotravel:",param:"params"},{match:"alipays://platformapi/starth5app",param:"url"},{match:"alipays://platformapi/startapp",param:"page"},{match:"eleme://web",param:"url"},{match:"amapuri://webview/",param:"url"}],FEIZHU_WECHAT_HOST_SUFFIXES=["feizhu.com"],WECHAT_SCHEME_RULES=[{match:"/pages/main/webview",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,param:"url",useCurrentOrigin:!0},...COMMON_SCHEME_RULES],WECHAT_MINI_PROGRAM={paymentRoutes:[{pathname:"/pages/utils/common-pay/index",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,paymentParamsParam:"signStr",successUrlParams:["backUrl","successUrl"],failureUrlParams:["unSuccessUrl","errorUrl"],successResultParam:"__paymentRes",forwardParams:["ttid"],useCurrentOrigin:!0}],nativeRoutes:[{pathname:"/pages/utils/webview-bridge/index",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,actions:["navigateMiniProgram","subscribeMessage"]}],messageRules:[{type:"BACK_DATA",action:"stageBackData",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES},{type:"BACK_MINI_APP",action:"closeAll",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES}]},WECHAT_TITLE_BAR_HOST_STYLES=[{hostSuffix:"feizhu.com",titleBarBackgroundColor:"#ffe033",statusBarBackgroundColor:"#ffe033"}],FLIGGY_SCHEME_RULES=[{match:"fliggy://order/detail",targetPath:"/app/trip/rx-flight-detail/pages/index",targetHostPrefix:"market",targetParams:{titleBarHidden:"2"}},...COMMON_SCHEME_RULES],WV_ACTIVE_EVENTS=["WV.Event.APP.Active"],FLIGGY_AI_UI_NOOPS=["handleLiveActivity","ai_ask_scroll_position","ai_ask_input_status","ai_ask_set_keyboard_tags","ai_ask_h5_awaken_input","ai_ask_reset_input","ai_ask_hide_input","home_ai_page_scroll","ai_ask_hide_keyboard","ai_ask_clear_keyboard_tags","ai_ask_init_mask","ai_ask_hide_mask","ai_ask_transfer_to_wenwen","ai_ask_transfer_to_mask","close_loading_view","open_loading_view","set_ai_ask_container_status","to_set_notifaction","home_refresh","ai_ask_page_load_success","ai_ask_set_session_info","ai_ask_input_set_mention_url","ai_ask_input_set_scene","ai_float_brain_panel_back_to_top_panel_page","ai_float_brain_panel_set_tools"],APP_PROFILES={fliggy:{name:"fliggy",label:"飞猪",appName:"LX",defaultAppVersion:"10.0.0",uaTokens:["AliTrip/{v}",WINDVANE],globals:{},bridges:[WV_BRIDGE,{global:"alitripBridge",style:"fliggy"},{global:"core",style:"fliggy"},{global:"methodChannel",style:"callback"}],activeEvents:WV_ACTIVE_EVENTS,actions:mergeActions(WV_ACTIONS,{...emptyActions(),open:["goto","ai_float_brain_panel_collapse_and_open_url"],close:[],title:["set_webview_title"],navigationBar:["set_ui"],statusBar:["set_status_bar_style"],systemInfo:["client_info"],kvGet:["get_kvcache"],kvSet:["set_kvcache"],kvDelete:["del_kvcache"],pageContext:["ai_float_brain_panel_get_page_context"],responses:{is_open_push:{is_open:!1},get_unread_message:{style:"POINT",count:0},get_v10_ab_info:{v10Version:!0},get_ai_ask_container_status:{status:"FULL"},ai_ask_get_keyboard_height:{height:0},get_idfa:{},get_caid:{},get_theme_conf:{},cppay_app_install:{result:""}},behaviors:{"page://goto":"navigate","page://close":"closeBackData",back:"closeBackData",user_info:"userInfo",ai_ask_get_memory_cache:"memoryGet",ai_ask_set_memory_cache:"memorySet",ai_ask_del_memory_cache:"memoryDelete",channelJudgeJsBridge:"availabilityMap",networktype:"networkInfo",network_quality_monitor:"networkQualityMonitor",request:"beaconRequest",voice_recognition:"voiceRecognition",store_calendar_event:"calendar",remove_calendar_event:"calendar",check_batch_calendar:"calendar",search_batch_calendar_events:"calendar",lbs:"geolocation",permission:"permission",cacheFetch:"prefetch",fptTrack:"fptTrack",toUT:"userTrack","WVTBUserTrack.toUT":"userTrack","WVTBUserTrack.toUT2":"userTrack",mtop_stream:"mtopStream",ai_ask_preview_file:"previewFile",toast:"toast",ai_ask_input_bridge:"unsupportedNativeInput",cppay:"payment",minipay:"payment",union_pay:"payment"},noop:["swipe_back","track_error_with_alarm","cacheUpdate","long_press_save_image",...FLIGGY_AI_UI_NOOPS],silent:["native://biz/mtop_normal_sign","toUT","get_idfa","get_caid","channelJudgeJsBridge","get_unread_message","get_v10_ab_info","lbs","networktype","network_quality_monitor","request","long_press_save_image","set_status_bar_style","get_theme_conf","cacheFetch","cppay_app_install","track_error_with_alarm",...FLIGGY_AI_UI_NOOPS]}),schemes:FLIGGY_SCHEME_RULES,imagePicker:FLIGGY_IMAGE_PICKER,geolocation:{reverseGeocodeApi:"mtop.trip.common.getCityCodeByLatitudeAndLongitude",version:"1.0"},layerUrlProxy:FLIGGY_LAYER_URL_PROXY,rootContainer:FLIGGY_ROOT_CONTAINER,titleBarHiddenPathnames:FLIGGY_TITLE_BAR_HIDDEN_PATHNAMES,statusBarBackgroundColors:FLIGGY_STATUS_BAR_BACKGROUND_COLORS,urlSyncHostSuffixes:["m.taobao.com","wapa.taobao.com"],overlay:FLIGGY_OVERLAY,popBeforeOpenParam:"_fli_popBeforeOpen",nativeBack:FLIGGY_NATIVE_BACK,forceH5Mtop:!0},taobao:{name:"taobao",label:"手机淘宝",appName:"TB",defaultAppVersion:"10.65.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE,MEGA_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,overlay:TAOBAO_OVERLAY,nativeBack:WV_NATIVE_BACK},wechat:{name:"wechat",label:"微信",appName:"WeChat",defaultAppVersion:"8.0.58",uaFamily:"wechatMiniProgram",uaTokens:[],globals:{__wxjs_environment:"miniprogram"},bridges:[{global:"wx",style:"wechat"},{global:"wx.miniProgram",style:"wechatMiniProgram",persistent:!0}],activeEvents:[],actions:{...emptyActions(),open:["navigateTo","redirectTo","switchTab","reLaunch"],close:["navigateBack"],behaviors:{postMessage:"postMessage",getLocation:"geolocation"}},schemes:WECHAT_SCHEME_RULES,miniProgram:WECHAT_MINI_PROGRAM,titleBarHostStyles:WECHAT_TITLE_BAR_HOST_STYLES},tmall:{name:"tmall",label:"天猫",appName:"TM",defaultAppVersion:"15.22.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},alipay:{name:"alipay",label:"支付宝",appName:"AP",defaultAppVersion:"10.8.0",uaTokens:["AlipayClient/{v}"],globals:{},bridges:[{global:"AlipayJSBridge",style:"alipay"}],activeEvents:[],actions:{open:["pushWindow","startApp"],close:["popWindow"],title:["setTitle"],navigationBar:["hideBackButton","showBackButton"],systemInfo:["getSystemInfo"],mtop:[],behaviors:{getNetworkType:"networkInfo",addNotifyListener:"notifySubscribe",removeNotifyListener:"notifyUnsubscribe",postNotification:"notifyPost"},noop:["postWebViewMessage","setGestureBack"],silent:["getNetworkType"]},schemes:COMMON_SCHEME_RULES,nativeBack:ALIPAY_NATIVE_BACK},koubei:{name:"koubei",label:"口碑",appName:"KB",defaultAppVersion:"9.5.0",uaTokens:["KoubeiClient/{v}"],globals:{},bridges:[{global:"AlipayJSBridge",style:"alipay"}],activeEvents:[],actions:{open:["pushWindow","startApp"],close:["popWindow"],title:["setTitle"],navigationBar:["hideBackButton","showBackButton"],systemInfo:["getSystemInfo"],mtop:[],behaviors:{getNetworkType:"networkInfo",addNotifyListener:"notifySubscribe",removeNotifyListener:"notifyUnsubscribe",postNotification:"notifyPost"},noop:["postWebViewMessage","setGestureBack"],silent:["getNetworkType"]},schemes:COMMON_SCHEME_RULES,nativeBack:ALIPAY_NATIVE_BACK},"taobao-tj":{name:"taobao-tj",label:"淘宝特价版",appName:"LT",defaultAppVersion:"10.32.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},"taobao-live":{name:"taobao-live",label:"淘宝直播",appName:"TAOBAOLIVEAPP",defaultAppVersion:"3.10.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},xianyu:{name:"xianyu",label:"闲鱼",appName:"FM",defaultAppVersion:"7.15.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},etao:{name:"etao",label:"一淘",appName:"ET",defaultAppVersion:"9.27.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},eleme:{name:"eleme",label:"饿了么",appName:"ELMC",defaultAppVersion:"11.12.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},damai:{name:"damai",label:"大麦",appName:"DM",defaultAppVersion:"8.9.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},btrip:{name:"btrip",label:"阿里商旅",appName:"BLX",defaultAppVersion:"9.12.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE,{global:"methodChannel",style:"btrip"}],activeEvents:WV_ACTIVE_EVENTS,actions:mergeActions(WV_ACTIONS,{...emptyActions(),open:["goto"],behaviors:{back:"closeBackData"}}),schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},amap:{name:"amap",label:"高德地图",appName:"amap",defaultAppVersion:"13.8.0",uaTokens:[],globals:{},bridges:[{global:"AmapApp.bridge",style:"amap"}],activeEvents:[],actions:{open:["loadSchema","infoH5JsAction"],close:[],title:["setWebViewTitle"],systemInfo:[],mtop:[],noop:["interceptNativeBackEvent"]},schemes:COMMON_SCHEME_RULES,nativeBack:{handler:"onNativeBackEvent"}},qianwen:{name:"qianwen",label:"千问",appName:"TONGYI",defaultAppVersion:"3.20.0",uaTokens:[],globals:{},bridges:[{global:"ucapi",style:"invoke"}],activeEvents:[],actions:{open:["biz.openPageUrl","webdialog.show"],close:["biz.closeWebPage","webdialog.pop"],title:[],systemInfo:[],mtop:[],behaviors:{"base.postmessage":"postMessage","biz.popToRootWindow":"closeAll","biz.popToTopChatWindow":"closeAll"},noop:[]},schemes:COMMON_SCHEME_RULES,messageEvent:"QKEVT_OnReceiveMessage"},lingyou:{name:"lingyou",label:"翎游",appName:"hongtu",defaultAppVersion:"1.5.0",uaTokens:["hongtu/{v}"],globals:{},bridges:[{global:"WKWebViewJavascriptBridge",style:"callHandler"},{global:"WebViewJavascriptBridge",style:"callHandler"}],activeEvents:[],actions:{...emptyActions(),open:["jumpPage"],close:["closePage"],title:["setPageTitle"]},schemes:COMMON_SCHEME_RULES},didi:{name:"didi",label:"滴滴出行",appName:"didi.passenger",defaultAppVersion:"6.9.0",uaTokens:["didi.passenger/{v}"],globals:{},bridges:[{global:"didiBridge",style:"didi"},{global:"Fusion",style:"didi"}],activeEvents:[],actions:{...emptyActions(),open:["openPage"],close:["closePage"]},schemes:COMMON_SCHEME_RULES},easybike:{name:"easybike",label:"易到用车",appName:"easybike",defaultAppVersion:"9.0.0",uaTokens:["app=easybike;"],globals:{},bridges:[{global:"webkit.messageHandlers.callNative",style:"easybikeNative"},{global:"AppFunctions",style:"easybikeNative"}],activeEvents:[],actions:mergeActions(WV_ACTIONS,{...emptyActions(),close:["business/hitch.closeWebView"]}),schemes:COMMON_SCHEME_RULES}};function buildAppProfileUa(profile,options={}){let os11=options.os??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileOs:void 0)??"ios",version2=options.appVersion??profile.defaultAppVersion,deviceModel=options.deviceModel??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileModel:void 0)??"Pixel 11";if(profile.uaFamily==="wechatMiniProgram")return os11==="android"?`Mozilla/5.0 (Linux; Android 17; ${deviceModel}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/152.0.0.0 Mobile MicroMessenger/${version2} WeChat/arm64 NetType/WIFI Language/zh_CN miniProgram`:`Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/${version2} NetType/WIFI Language/zh_CN miniProgram`;let tokens=profile.uaTokens.map(t=>t.replaceAll("{v}",version2)).filter(Boolean),tail=tokens.length>0?` ${tokens.join(" ")}`:"";return os11==="android"?`Mozilla/5.0 (Linux; Android 17; ${deviceModel}) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/152.0.0.0 Mobile Safari/537.36 AliApp(${profile.appName}/${version2})${tail}`:`Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) AliApp(${profile.appName}/${version2})${tail}`}function resolveAppProfile(name,options={}){let profile=APP_PROFILES[name];if(!profile)throw new Error(`Unknown app profile "${name}". Available: ${Object.keys(APP_PROFILES).join(", ")}`);let os11=options.os??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileOs:void 0)??"ios",version2=options.appVersion??profile.defaultAppVersion,recommendedPreset=os11==="android"?"pixel-11":"iphone-17-pro",devicePreset=options.devicePreset??recommendedPreset,emulation=resolveEmulationConfig({enabled:!0,preset:devicePreset,orientation:options.orientation}),deviceModel=options.deviceModel??DEVICE_PRESETS[devicePreset].appProfileModel,globals={...profile.globals,__APP_NAME__:profile.appName,__APP_VERSION__:version2,__FLI_DEVICE_MODEL__:deviceModel,__DEVICE_MODEL__:deviceModel},ua=buildAppProfileUa(profile,{...options,os:os11,deviceModel});return{profile:profile.name,label:profile.label,ua,injected:{profile:profile.name,label:profile.label,globals,bridges:profile.bridges,activeEvents:profile.activeEvents,maxTouchPoints:5,statusBarHeight:emulation.safeAreaInsets.top,safeAreaInsets:emulation.safeAreaInsets,deviceAppearance:{preset:devicePreset,orientation:emulation.orientation,cutout:emulation.appearance.cutout},language:"zh-Hans",userAgent:ua,navigatorPlatform:os11==="android"?"Linux armv8l":"iPhone",platform:os11==="android"?"Android":"iOS",systemVersion:os11==="android"?"17":"26.0",clientType:os11==="android"?"android":"iphone",actions:applyAppBridgeConfig(profile.actions,options.bridgeConfig),schemes:profile.schemes,...profile.miniProgram&&{miniProgram:profile.miniProgram},...profile.imagePicker&&{imagePicker:profile.imagePicker},...profile.geolocation&&{geolocation:profile.geolocation},...profile.overlay&&{overlay:profile.overlay},...profile.popBeforeOpenParam&&{popBeforeOpenParam:profile.popBeforeOpenParam},...profile.messageEvent&&{messageEvent:profile.messageEvent},...profile.nativeBack&&{nativeBack:profile.nativeBack},...profile.layerUrlProxy&&{layerUrlProxy:profile.layerUrlProxy},...profile.urlSyncHostSuffixes&&{urlSyncHostSuffixes:profile.urlSyncHostSuffixes},...profile.forceH5Mtop&&{forceH5Mtop:!0},simulateSystemBars:!1,rootContainer:{enabled:!1,...profile.rootContainer?.statusBarHeightCookie&&{initialCookies:[{...profile.rootContainer.statusBarHeightCookie,value:String(emulation.safeAreaInsets.top)}]}},titleBar:{navigationBarHeight:os11==="android"?48:44,backgroundColor:"#ffffff",textColor:"#0f131a",...profile.titleBarHiddenPathnames&&{hiddenPathnames:profile.titleBarHiddenPathnames},...profile.statusBarBackgroundColors&&{statusBarBackgroundColors:profile.statusBarBackgroundColors},...profile.titleBarHostStyles&&{hostStyles:profile.titleBarHostStyles}}},recommendedPreset}}function installAppProfileEnvironment(config2){let w=window;if(w.__mearlAppProfile__)return null;w.__mearlAppProfile__=config2.profile;let SRC="mearl-app-bridge",TAG=`[AppBridge:${config2.label}]`,ROOT_FRAME_NAME="__mearl_root__",LAYER_FRAME_NAME="__mearl_layer__",isTop=window===window.top,isRootFrame=!isTop&&window.name===ROOT_FRAME_NAME,isLayerFrame=!isTop&&window.name===LAYER_FRAME_NAME,isContainerFrame=isTop||isRootFrame||isLayerFrame,usesRootContainer=isTop&&config2.rootContainer?.enabled===!0,simulateSystemBars=config2.simulateSystemBars!==!1,safeAreaInsets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0},log2=(...args)=>console.info(TAG,...args);for(let[key,value]of Object.entries(config2.globals))try{w[key]=value}catch{}typeof w.__STATUS_BAR_HEIGHT__!="number"&&(w.__STATUS_BAR_HEIGHT__=config2.statusBarHeight),typeof w.__SAFE_AREA_INSET_BOTTOM__!="number"&&(w.__SAFE_AREA_INSET_BOTTOM__=safeAreaInsets.bottom);let applySafeAreaCssVariables=()=>{let root=document.documentElement;if(!root)return!1;try{return root.style.setProperty("--safe-area-inset-top",`${safeAreaInsets.top}px`),root.style.setProperty("--safe-area-inset-right",`${safeAreaInsets.right}px`),root.style.setProperty("--safe-area-inset-bottom",`${safeAreaInsets.bottom}px`),root.style.setProperty("--safe-area-inset-left",`${safeAreaInsets.left}px`),!0}catch{return!1}};if(!applySafeAreaCssVariables()){let observer=new MutationObserver(()=>{applySafeAreaCssVariables()&&observer.disconnect()});observer.observe(document,{childList:!0})}if(config2.forceH5Mtop){let downstreamMtopParamsHandler=w.MTOP_PARAMS_HANDLER,forceH5Mtop=params=>{let resolved=params;if(typeof downstreamMtopParamsHandler=="function")try{resolved=downstreamMtopParamsHandler.call(window,params)??params}catch{resolved=params}return{...resolved&&typeof resolved=="object"?resolved:{},useNative:!1}};try{Object.defineProperty(w,"MTOP_PARAMS_HANDLER",{configurable:!0,get:()=>forceH5Mtop,set:handler=>{handler!==forceH5Mtop&&(downstreamMtopParamsHandler=handler)}})}catch{w.MTOP_PARAMS_HANDLER=forceH5Mtop}}for(let[key,value]of[["userAgent",config2.userAgent],["platform",config2.navigatorPlatform],["vendor","Apple Computer, Inc."],["appVersion",config2.userAgent.replace(/^Mozilla\//,"")]])try{Object.defineProperty(navigator,key,{get:()=>value,configurable:!0})}catch{}try{Object.defineProperty(navigator,"maxTouchPoints",{get:()=>config2.maxTouchPoints})}catch{}return{w,SRC,TAG,ROOT_FRAME_NAME,LAYER_FRAME_NAME,isTop,isRootFrame,isLayerFrame,isContainerFrame,usesRootContainer,simulateSystemBars,safeAreaInsets,log:log2}}function installAppProfileSystemBars(config2,environment,host){let{SRC,isTop,isContainerFrame,simulateSystemBars,safeAreaInsets}=environment,externalDeviceChrome=config2.externalDeviceChrome===!0,titleBarMode="auto",titleBarRoot=null,titleBarSpacer=null,systemStatusView=null,systemBottomRoot=null,systemBottomSurface=null,rootTitleBarView=null,titleBarTitleVisible=!0,titleBarBackVisible=!0,titleBarBackground=config2.titleBar?.backgroundColor??"#ffffff",titleBarTextColor=config2.titleBar?.textColor??"#111111",titleBarStateExplicit=!1,presentedRootTitleBarState=null,normalizeProxyPathPrefix=prefix=>{let withLeadingSlash=prefix.startsWith("/")?prefix:`/${prefix}`;return withLeadingSlash.endsWith("/")?withLeadingSlash:`${withLeadingSlash}/`},matchesProxyTarget=(hostname3,suffixes)=>suffixes.some(suffix=>hostname3===suffix||hostname3.endsWith(`.${suffix}`)),normalizePathname=pathname=>{let withLeadingSlash=pathname.startsWith("/")?pathname:`/${pathname}`;return withLeadingSlash.length>1&&withLeadingSlash.endsWith("/")?withLeadingSlash.slice(0,-1):withLeadingSlash},businessPathname=href=>{try{let current=new URL(href,location.href),proxy=config2.layerUrlProxy;if(!proxy)return normalizePathname(current.pathname);let prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(!current.pathname.startsWith(prefix))return normalizePathname(current.pathname);let rest=current.pathname.slice(prefix.length),slash=rest.indexOf("/"),hostName=slash===-1?rest:rest.slice(0,slash),pathname=slash===-1?"/":rest.slice(slash),hostname3=new URL(`${current.protocol}//${hostName}`).hostname;return matchesProxyTarget(hostname3,proxy.targetHostSuffixes)?normalizePathname(pathname):normalizePathname(current.pathname)}catch{return null}},matchesConfiguredPathname=(href,pathnames)=>{let pathname=businessPathname(href);return pathname!==null&&pathnames.some(configuredPathname=>normalizePathname(configuredPathname)===pathname)},configuredHostStyle=(href=location.href)=>{try{let hostname3=new URL(href,location.href).hostname.toLowerCase();return(config2.titleBar?.hostStyles??[]).find(rule=>{let suffix=rule.hostSuffix.trim().replace(/^\.+/,"").toLowerCase();return suffix!==""&&(hostname3===suffix||hostname3.endsWith(`.${suffix}`))})}catch{return}},configuredTitleBarBackground=(href,fallback)=>configuredHostStyle(href)?.titleBarBackgroundColor??fallback,supportsWindVaneNavigationMeta=config2.bridges.some(bridge=>bridge.style==="windvane"),isTruthyParam=value=>value==="1"||value?.toLowerCase()==="true"||value?.toUpperCase()==="YES",isTransparentColor=value=>{let normalized=value.replace(/\s/g,"").toLowerCase();return normalized==="transparent"||normalized==="#0000"||normalized==="#00000000"||normalized==="rgba(0,0,0,0)"},fixedContainerTitleBarMode=()=>config2.profile==="wechat"?"normal":null,pageRequestedTitleBarMode=(href=location.href,includeMeta=!0)=>{try{let params=new URL(href,location.href).searchParams,webviewOptions=new URLSearchParams(params.get("__webview_options__")??""),option=key=>params.get(key)??webviewOptions.get(key);if(config2.profile==="fliggy"||config2.profile==="taobao"){let hidden=option("titleBarHidden");if(hidden==="1")return"status-inset";if(hidden==="2")return"status"}if(config2.profile==="taobao"&&option("disableNav")?.toUpperCase()==="YES")return isTruthyParam(option("status_bar_transparent"))?"status":"status-inset";if(config2.profile==="alipay"||config2.profile==="koubei"){if(option("showTitleBar")?.toUpperCase()==="NO")return"status-inset";let transparentTitle=option("transparentTitle")?.toLowerCase();if(transparentTitle&&["always","auto","custom"].includes(transparentTitle))return"overlay"}let overlayParam=config2.overlay?.enabledParam;return overlayParam&&isTruthyParam(params.get(overlayParam))?"status":!includeMeta||!supportsWindVaneNavigationMeta?null:document.getElementById("WV.Meta.Nav.HideNavBar")?.getAttribute("value")==="HideStatusBar"?"status":null}catch{return null}},pageRequestsHiddenTitleBar=(href=location.href)=>matchesConfiguredPathname(href,config2.titleBar?.hiddenPathnames??[]),configuredStatusBarBackground=(href=location.href)=>{let colors=config2.titleBar?.statusBarBackgroundColors??{},pathname=businessPathname(href);return pathname===null?null:Object.entries(colors).find(([configuredPathname])=>normalizePathname(configuredPathname)===pathname)?.[1]??configuredHostStyle(href)?.statusBarBackgroundColor??null},pageRequestsHiddenStatusBar=(href=location.href)=>{try{let params=new URL(href,location.href).searchParams;return isTruthyParam(params.get("statusBarHidden"))||isTruthyParam(params.get("hideStatusBar"))?!0:/(?:^|&)showStatusBar=NO(?:&|$)/i.test(params.get("__webview_options__")??"")}catch{return!1}},resolveTitleBarMode=(href,fallback,includeMeta)=>{let fixedMode=fixedContainerTitleBarMode();if(fixedMode)return fixedMode;if(titleBarMode!=="auto")return titleBarMode;if(pageRequestsHiddenStatusBar(href))return"hidden";if(pageRequestsHiddenTitleBar(href))return"status-inset";let requestedMode=pageRequestedTitleBarMode(href,includeMeta);return requestedMode||fallback},resolveStatusBarBackground=(href,mode,navigationBarBackground)=>configuredStatusBarBackground(href)??(mode==="normal"||mode==="status-inset"?navigationBarBackground:"transparent"),ownTitleBarState=()=>{let mode=resolveTitleBarMode(location.href,"normal",!0),background=configuredTitleBarBackground(location.href,titleBarBackground);return{mode,title:document.title||config2.label,titleVisible:titleBarTitleVisible,backVisible:titleBarBackVisible,background,statusBarBackground:resolveStatusBarBackground(location.href,mode,background),textColor:titleBarTextColor}},initialLayerTitleBarState=url2=>{let mode=fixedContainerTitleBarMode()??(pageRequestsHiddenStatusBar(url2)?"hidden":pageRequestsHiddenTitleBar(url2)?"status-inset":pageRequestedTitleBarMode(url2,!1)??"normal"),background=configuredTitleBarBackground(url2,config2.titleBar?.backgroundColor??"#ffffff");return{mode,title:config2.label,titleVisible:!0,backVisible:!0,background,statusBarBackground:mode==="status-inset"?background:resolveStatusBarBackground(url2,mode,background),textColor:config2.titleBar?.textColor??"#111111"}},parseReportedTitleBarState=value=>{if(!value||typeof value!="object")return null;let state=value;return!["normal","overlay","status","status-inset","hidden"].includes(String(state.mode))||typeof state.title!="string"||typeof state.titleVisible!="boolean"||typeof state.backVisible!="boolean"||typeof state.background!="string"||typeof state.textColor!="string"?null:{...state,statusBarBackground:typeof state.statusBarBackground=="string"?state.statusBarBackground:state.mode==="normal"||state.mode==="status-inset"?String(state.background):"transparent"}},resolvedTitleBarState=layer=>layer?layer.titleBarState??initialLayerTitleBarState(layer.url):presentedRootTitleBarState??ownTitleBarState(),resolvedRootTitleBarState=(fallback=ownTitleBarState())=>presentedRootTitleBarState??(host.getRootFrame()?{...fallback,statusBarBackground:configuredHostStyle(location.href)?.statusBarBackgroundColor??config2.titleBar?.backgroundColor??"#ffffff"}:fallback),renderNavigationBarView=(view,state)=>{let visible=state.mode==="normal"||state.mode==="overlay";view.root.style.display=visible?"block":"none",view.surface.style.visibility=visible?"visible":"hidden",view.surface.style.background=state.mode==="overlay"?"transparent":state.background,view.surface.style.borderBottom="none",view.surface.style.color=state.textColor,view.title.textContent=state.title,view.title.style.display=state.titleVisible?"block":"none",view.back.style.display=state.backVisible?"flex":"none",view.back.style.color=state.textColor},topFullLayer=()=>{let layers=host.getLayers();for(let index=layers.length-1;index>=0;index-=1)if(!layers[index].overlay&&!layers[index].closing)return layers[index]},activeTitleBarState=()=>{let layer=topFullLayer();return layer?resolvedTitleBarState(layer):resolvedRootTitleBarState()},syncActiveSystemBars=()=>{let state=activeTitleBarState();if(externalDeviceChrome&&isTop&&window.postMessage({source:"mearl-app-profile-runtime",type:"device-chrome-state",state:{statusBarBackground:state.statusBarBackground,textColor:state.textColor,bridgeConfig:{profile:config2.profile,actions:config2.actions}}},"*"),systemStatusView){let visible=state.mode!=="hidden";systemStatusView.root.style.display=visible?"block":"none",systemStatusView.surface.style.visibility=visible?"visible":"hidden",systemStatusView.surface.style.background=state.statusBarBackground,systemStatusView.surface.style.color=state.textColor}systemBottomRoot&&systemBottomSurface&&(systemBottomRoot.style.display=safeAreaInsets.bottom>0?"block":"none",systemBottomSurface.style.color=state.textColor)},syncLayerViewport=(layer,state)=>{if(layer.overlay)return;if(!simulateSystemBars){layer.frame.style.top="0px",layer.frame.style.height="100%";return}let totalHeight=config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0),offset=state.mode==="normal"?totalHeight:state.mode==="status-inset"?config2.statusBarHeight:0;layer.frame.style.top=`${offset}px`,layer.frame.style.height=offset>0?`calc(100% - ${offset}px)`:"100%",layer.frame.setAttribute("data-mearl-app-viewport-mode",state.mode),layer.frame.style.setProperty("--mearl-app-navigation-bar-height",`${config2.titleBar?.navigationBarHeight??0}px`),layer.frame.style.opacity=state.mode==="status-inset"&&!layer.titleBarStateReady?"0":"1",layer.titleBarView&&renderNavigationBarView(layer.titleBarView,state),topFullLayer()===layer&&syncActiveSystemBars()},syncRootFrameViewport=state=>{let rootFrame=host.getRootFrame();if(!rootFrame)return;if(!simulateSystemBars){rootFrame.style.top="0px",rootFrame.style.height="100%";return}let totalHeight=config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0),offset=state.mode==="normal"?totalHeight:state.mode==="status-inset"?config2.statusBarHeight:0;rootFrame.style.top=`${offset}px`,rootFrame.style.height=offset>0?`calc(100% - ${offset}px)`:"100%",rootFrame.setAttribute("data-mearl-app-viewport-mode",state.mode),rootFrame.style.setProperty("--mearl-app-navigation-bar-height",`${config2.titleBar?.navigationBarHeight??0}px`),rootFrame.style.opacity=state.mode==="status-inset"&&presentedRootTitleBarState===null&&!rootFrame.hasAttribute("data-mearl-webview-ready")?"0":"1"},syncSimulatedTitleBar=()=>{let ownState=ownTitleBarState();if(!isTop){if(isContainerFrame){if(!titleBarStateExplicit&&document.readyState==="loading")return;window.top?.postMessage({source:SRC,type:"titleBarState",state:ownState,explicit:titleBarStateExplicit},"*")}return}if(!titleBarRoot||!titleBarSpacer||!rootTitleBarView)return;let rootFrame=host.getRootFrame();!rootFrame&&host.getLayers().length===0&&host.getClosingLayerCount()===0&&(presentedRootTitleBarState=ownState);let state=resolvedRootTitleBarState(ownState);renderNavigationBarView(rootTitleBarView,state);let spacerHeight=state.mode==="normal"?config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0):state.mode==="status-inset"?config2.statusBarHeight:0;titleBarSpacer.style.display=!rootFrame&&spacerHeight>0?"block":"none",titleBarSpacer.style.height=`${spacerHeight}px`,titleBarSpacer.style.minHeight=`${spacerHeight}px`,syncRootFrameViewport(state),syncActiveSystemBars()},applyNavigationBarState=(api,params)=>{titleBarStateExplicit=!0;let p=params&&typeof params=="object"?params:{},displayValue=p.titlebar_display??p.titlebarDisplay??p.titleBarDisplay,display=typeof displayValue=="string"?displayValue.toLowerCase():"";api==="hideBackButton"&&(titleBarBackVisible=!1),api==="showBackButton"&&(titleBarBackVisible=!0),display==="hide"&&(titleBarMode="status"),display==="show"&&(titleBarMode="normal"),(p.isImmersive===!0||p.isTransparent===!0)&&(titleBarMode="overlay"),p.isImmersive===!1&&p.isTransparent===!1&&(titleBarMode="normal"),typeof p.isTitleVisible=="boolean"&&(titleBarTitleVisible=p.isTitleVisible),typeof p.title=="string"&&(document.title=p.title),typeof p.backgroundColor=="string"&&(titleBarBackground=p.backgroundColor,isTransparentColor(p.backgroundColor)&&(titleBarMode="overlay")),typeof p.barTextStyle=="string"&&(titleBarTextColor=p.barTextStyle==="white"?"#ffffff":"#111111"),syncSimulatedTitleBar()},applyStatusBarState=params=>{titleBarStateExplicit=!0;let p=params&&typeof params=="object"?params:{},style=typeof p.style=="string"?p.style.toLowerCase():"";style&&(titleBarTextColor=style==="white"||style.includes("light")?"#ffffff":"#111111"),syncSimulatedTitleBar()},createNavigationBarView=(placement,onBack)=>{let titleBar=config2.titleBar,root=document.createElement("div");root.setAttribute("data-mearl-app-titlebar",config2.profile),root.setAttribute("data-mearl-titlebar-owner",placement);let splitRoot=placement==="root"&&config2.rootContainer?.splitScreen===!0;splitRoot&&root.setAttribute("data-mearl-split-pane","left-titlebar"),root.style.cssText=`${placement==="root"?"position:fixed":"position:absolute"};left:0;${splitRoot?"right:auto;width:50%;":"right:0;"}top:${config2.statusBarHeight}px;height:${titleBar.navigationBarHeight}px;z-index:${placement==="root"?"2147482900":"2"};overflow:hidden;box-sizing:border-box;font-family:"PingFang SC",-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;`;let shadow=root.attachShadow({mode:"open"});shadow.innerHTML=`<style>
151
151
  :host{all:initial}#surface{position:relative;width:100%;height:100%;box-sizing:border-box;color:#0f131a;-webkit-font-smoothing:antialiased;text-rendering:geometricPrecision}
152
152
  #nav{height:100%;position:relative;display:grid;align-items:start}#back{appearance:none;border:0;background:transparent;position:absolute;left:9px;top:0;width:28px;height:42px;display:flex;align-items:center;justify-content:center;padding:0;color:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent}
153
153
  #back svg{width:24px;height:24px;fill:none;stroke:currentColor;stroke-width:1.75;stroke-linecap:round;stroke-linejoin:round}#title{position:absolute;left:80px;right:80px;top:0;height:42px;box-sizing:border-box;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:10px 0;text-align:center;font-size:18px;font-weight:700;line-height:22px}
@@ -175,7 +175,7 @@ ${SOURCE_BADGES[source]}
175
175
  #surface[data-platform="android"]{font-family:Roboto,"Noto Sans SC",sans-serif}
176
176
  #surface[data-platform="android"] #status{padding:0 12px;font-size:12px;font-weight:500;letter-spacing:0}
177
177
  #surface[data-platform="android"] #indicators{gap:5px;transform:scale(.86);transform-origin:right center}
178
- </style><div id="surface" data-platform="${config2.platform.toLowerCase()}" data-cutout="${String(cutoutKind!=="none")}" data-cutout-kind="${cutoutKind}"><div id="status"><span id="time"></span>${cutoutMarkup}<span id="indicators" aria-hidden="true"><svg id="signal" viewBox="0 0 18 12"><rect x="0" y="8" width="3" height="4" rx="1"/><rect x="5" y="6" width="3" height="6" rx="1"/><rect x="10" y="3" width="3" height="9" rx="1"/><rect x="15" y="0" width="3" height="12" rx="1"/></svg><svg id="wifi" viewBox="1 3.8 22 17.2"><path d="M2 8.82a15 15 0 0 1 20 0"/><path d="M5 12.859a10 10 0 0 1 14 0"/><path d="M8.5 16.429a5 5 0 0 1 7 0"/><path d="M12 20h.01"/></svg><svg id="battery" viewBox="0 0 28 13"><rect id="battery-outline" x=".65" y=".65" width="23" height="11.7" rx="3.1"/><rect id="battery-level" x="2.35" y="2.35" width="19.6" height="8.3" rx="1.7"/><path id="battery-cap" d="M25 4.1c1.1.35 1.7 1.15 1.7 2.4s-.6 2.05-1.7 2.4z"/></svg></span></div></div>`;let surface=shadow.getElementById("surface"),time3=shadow.getElementById("time"),cutout=shadow.getElementById("device-cutout"),cutoutStatusPath=shadow.querySelector("#cutout-check path"),localizedScreenshotText=config2.language.toLowerCase().startsWith("zh")?{idle:"截图",copied:"已复制",downloaded:"已下载",failed:"截图失败"}:{idle:"Screenshot",copied:"Copied",downloaded:"Downloaded",failed:"Capture failed"},setCutoutState=state=>{cutout&&(cutout.dataset.state=state,cutout.setAttribute("aria-label",localizedScreenshotText[state]),cutout.title=localizedScreenshotText[state],cutoutStatusPath&&cutoutStatusPath.setAttribute("d",state==="failed"?"M5.5 5.5l9 9m0-9-9 9":"m4.5 10.5 3.2 3.2 7.8-7.8"))},screenshotPending=!1,screenshotBlob=data=>{let binary=atob(data),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return new Blob([bytes],{type:"image/png"})},downloadScreenshot=blob=>{let link=document.createElement("a"),objectUrl=URL.createObjectURL(blob);link.href=objectUrl,link.download=`mearl-screenshot-${new Date().toISOString().replace(/[:.]/g,"-")}.png`,link.style.display="none",document.body.appendChild(link),link.click(),link.remove(),window.setTimeout(()=>URL.revokeObjectURL(objectUrl),1e3)},captureScreenshot=async()=>{if(!cutout||screenshotPending||cutout.dataset.state!=="idle")return;screenshotPending=!0,cutout.setAttribute("aria-busy","true");let requestId=Date.now()*1e3+Math.floor(Math.random()*1e3),timeoutTimer=0,onResponse=null,image=new Promise((resolve2,reject)=>{let cleanup=()=>{timeoutTimer&&window.clearTimeout(timeoutTimer),onResponse&&window.removeEventListener("message",onResponse)};onResponse=event=>{if(event.source!==window)return;let message=event.data;if(!message||message.source!=="mearl-content"||message.type!=="APP_BRIDGE_SCREENSHOT_RESPONSE"||message.requestId!==requestId)return;cleanup();let result=message.result;result?.success===!0&&typeof result.data=="string"?resolve2({data:result.data}):reject(new Error(String(result?.error??"screenshot failed")))},window.addEventListener("message",onResponse),timeoutTimer=window.setTimeout(()=>{cleanup(),reject(new Error("screenshot timeout"))},35e3)}).then(result=>screenshotBlob(result.data)),clipboardWrite=null;if(navigator.clipboard?.write&&typeof ClipboardItem<"u")try{clipboardWrite=navigator.clipboard.write([new ClipboardItem({"image/png":image})]),clipboardWrite.catch(()=>{})}catch{clipboardWrite=null}window.postMessage({source:SRC,type:"screenshot",requestId},"*");try{let blob=await image;if(clipboardWrite)try{await clipboardWrite,setCutoutState("copied")}catch{downloadScreenshot(blob),setCutoutState("downloaded")}else downloadScreenshot(blob),setCutoutState("downloaded")}catch{setCutoutState("failed")}finally{screenshotPending=!1,cutout.setAttribute("aria-busy","false")}window.setTimeout(()=>{screenshotPending||setCutoutState("idle")},1600)};hasDynamicIsland&&cutout&&(setCutoutState("idle"),cutout.addEventListener("click",()=>void captureScreenshot()));let updateTime=()=>{let now=new Date;time3&&(time3.textContent=`${String(now.getHours()).padStart(2,"0")}:${String(now.getMinutes()).padStart(2,"0")}`)};return window.addEventListener("mearl:page-time-change",updateTime),updateTime(),{root,surface,timeTimer:window.setInterval(updateTime,3e4)}},install=()=>{let titleBar=config2.titleBar;if(!titleBar||!isContainerFrame||!simulateSystemBars)return;let observeState=()=>{new MutationObserver(syncSimulatedTitleBar).observe(document.head??document.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["content","value"]}),window.addEventListener("popstate",syncSimulatedTitleBar),window.addEventListener("hashchange",syncSimulatedTitleBar),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",syncSimulatedTitleBar,{once:!0});try{let pushState=history.pushState.bind(history),replaceState=history.replaceState.bind(history);history.pushState=function(...args){pushState(...args),syncSimulatedTitleBar()},history.replaceState=function(...args){replaceState(...args),syncSimulatedTitleBar()}}catch{}};if(!isTop){observeState(),syncSimulatedTitleBar();return}let mount=()=>{if(titleBarRoot||!document.body)return;let totalHeight=config2.statusBarHeight+titleBar.navigationBarHeight,navigationView=createNavigationBarView("root",host.requestNativeBack),statusView=externalDeviceChrome||config2.statusBarHeight<=0?null:createStatusBarView(),spacer=document.createElement("div");if(spacer.setAttribute("data-mearl-app-titlebar-spacer",""),spacer.style.cssText=`display:block;width:100%;height:${totalHeight}px;min-height:${totalHeight}px;flex:none;`,spacer.style.setProperty("--mearl-app-navigation-bar-height",`${titleBar.navigationBarHeight}px`),document.body.insertBefore(spacer,document.body.firstChild),document.body.appendChild(navigationView.root),statusView&&document.body.appendChild(statusView.root),!externalDeviceChrome&&safeAreaInsets.bottom>0){let bottomRoot=document.createElement("div");bottomRoot.setAttribute("data-mearl-app-system-bottom",config2.profile),bottomRoot.style.cssText=`position:fixed;left:0;right:0;bottom:0;height:${safeAreaInsets.bottom}px;z-index:2147483600;box-sizing:border-box;pointer-events:none;color:#111111;`;let bottomShadow=bottomRoot.attachShadow({mode:"open"});bottomShadow.innerHTML=`<style>:host{all:initial}#surface{appearance:none;border:0;padding:0;width:166px;max-width:100%;height:24px;position:absolute;left:50%;bottom:0;transform:translateX(-50%);display:block;box-sizing:border-box;pointer-events:auto;color:#111;background:transparent;cursor:pointer;-webkit-tap-highlight-color:transparent}#surface:focus-visible{outline:2px solid #2563eb;outline-offset:-2px}#indicator{position:absolute;left:50%;bottom:8px;transform:translateX(-50%);width:134px;height:5px;border-radius:999px;background:currentColor;opacity:.92;transition:transform 120ms ease,opacity 120ms ease}#surface:hover #indicator{opacity:1;transform:translateX(-50%) scaleX(1.05)}#surface[data-platform="android"] #indicator{bottom:6px;width:108px;height:4px;opacity:.82}</style><button id="surface" type="button" aria-label="打开桥模拟配置" title="桥模拟配置" data-platform="${config2.platform.toLowerCase()}"><span id="indicator" aria-hidden="true"></span></button>`,document.body.appendChild(bottomRoot),systemBottomRoot=bottomRoot,systemBottomSurface=bottomShadow.getElementById("surface"),systemBottomSurface?.addEventListener("click",()=>{window.postMessage({source:SRC,type:"showBridgeConfig",profile:config2.profile,actions:config2.actions},"*")})}rootTitleBarView=navigationView,systemStatusView=statusView,titleBarRoot=navigationView.root,titleBarSpacer=spacer,syncSimulatedTitleBar(),observeState()};document.body?mount():document.addEventListener("DOMContentLoaded",mount,{once:!0})},service={initialLayerTitleBarState,resolvedTitleBarState,parseReportedTitleBarState,setPresentedRootTitleBarState:state=>{presentedRootTitleBarState=state,syncSimulatedTitleBar()},markStateExplicit:()=>{titleBarStateExplicit=!0},applyNavigationBarState,applyStatusBarState,createNavigationBarView,destroyNavigationBarView:view=>view?.root.remove(),syncLayerViewport,syncActiveSystemBars,syncSimulatedTitleBar};return install(),service}function installAppProfilePageTransport(config2,environment){let{SRC,TAG,log:log2}=environment,appToast=null,appToastHideTimer=null,appToastRemoveTimer=null;function showAppToast(params){let p=params&&typeof params=="object"?params:{},messageValue=[p.message,p.msg,p.content,p.text].find(value=>typeof value=="string"&&value.trim().length>0);if(typeof messageValue!="string")return"missing message";let durationValue=Number(p.milliseconds??p.duration),duration3=Number.isFinite(durationValue)&&durationValue>0?durationValue:2e3,hideAfter=Math.min(6e4,Math.max(300,Math.round(duration3)));appToastHideTimer!==null&&window.clearTimeout(appToastHideTimer),appToastRemoveTimer!==null&&window.clearTimeout(appToastRemoveTimer);let toast=appToast?.isConnected===!0?appToast:document.createElement("div");return toast!==appToast&&(appToast=toast,toast.setAttribute("data-mearl-app-toast",""),toast.setAttribute("role","status"),toast.setAttribute("aria-live","polite"),Object.assign(toast.style,{position:"fixed",left:"50%",top:"50%",zIndex:"2147483647",maxWidth:"calc(100vw - 64px)",boxSizing:"border-box",padding:"14px 20px",borderRadius:"12px",background:"rgba(20, 20, 20, 0.88)",color:"#ffffff",fontFamily:'-apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif',fontSize:"16px",fontWeight:"400",lineHeight:"24px",textAlign:"center",whiteSpace:"pre-wrap",overflowWrap:"anywhere",pointerEvents:"none",opacity:"0",transform:"translate(-50%, -50%) scale(0.96)",transition:"opacity 180ms ease, transform 180ms ease"}),(document.body??document.documentElement).appendChild(toast)),toast.textContent=messageValue,toast.style.opacity="0",toast.style.transform="translate(-50%, -50%) scale(0.96)",toast.offsetWidth,toast.style.opacity="1",toast.style.transform="translate(-50%, -50%) scale(1)",appToastHideTimer=window.setTimeout(()=>{appToastHideTimer=null,toast.style.opacity="0",toast.style.transform="translate(-50%, -50%) scale(0.96)",appToastRemoveTimer=window.setTimeout(()=>{appToastRemoveTimer=null,appToast===toast&&(appToast=null),toast.remove()},180)},hideAfter),null}let bridgeRequestSeq=0,pendingMtop={},pendingMtopStreams={},pendingUserInfo={};function degradedUserInfo(fallback,reason){let result={...fallback};try{Object.defineProperties(result,{__mearlDegraded:{enumerable:!1,value:!0},__mearlDegradedReason:{enumerable:!1,value:reason}})}catch{}return console.warn(TAG,"userInfo 降级:",reason),result}function callMtop(params,succ,fail2){let id=++bridgeRequestSeq;pendingMtop[id]={succ,fail:fail2};let post=params.post,rawTimeout=params.timeout??params.timer,timeout=typeof rawTimeout=="number"?rawTimeout:typeof rawTimeout=="string"&&rawTimeout.trim()!==""?Number(rawTimeout):void 0,payload={...params,data:params.data!==void 0?params.data:params.param??{},method:params.method??(post===!0||post===1||post==="1"||post==="true"?"POST":"GET"),env:params.env??(/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"online"),...Number.isFinite(timeout)&&{timeout}};window.postMessage({source:SRC,type:"mtop",requestId:id,payload},"*"),log2("mtop 代发 →",params.api)}function callMtopAsync(params){return new Promise((resolve2,reject)=>callMtop(params,resolve2,reject))}function callMtopStream(params,succ,fail2){let sessionId=typeof params.id=="string"?params.id:String(params.id??""),request=params.request&&typeof params.request=="object"?params.request:null;if(!sessionId||!request||typeof request.api!="string"){fail2?.("invalid mtop_stream params");return}let requestId=++bridgeRequestSeq;pendingMtopStreams[requestId]={sessionId},window.postMessage({source:SRC,type:"mtopStream",requestId,payload:{...request,timeout:params.timeout,method:params.method??request.method,env:/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"online"}},"*"),succ?.({}),log2("mtop 流式代发 →",request.api)}function callUserInfo(fallback,succ){if(fallback.userId){succ?.(fallback);return}let requestId=++bridgeRequestSeq,timer=setTimeout(()=>{let pending=pendingUserInfo[requestId];pending&&(delete pendingUserInfo[requestId],pending.succ?.(degradedUserInfo(pending.fallback,"native relay timeout")))},1e3);pendingUserInfo[requestId]={fallback,succ,timer},window.postMessage({source:SRC,type:"userInfo",requestId},"*")}function emitMtopStreamEvent(sessionId,eventType,data){let detail=data&&typeof data=="object"?{...data,eventType}:{data,eventType};document.dispatchEvent(new CustomEvent(`mtop_stream${sessionId}`,{detail}))}function createUploadId(){try{if(typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`${Date.now()}-${Math.random().toString(36).slice(2)}`}function pickDirectUploadTarget(response){if(!response||typeof response!="object")return null;let data=response.data;if(data?.success===!1)return null;let result=data?.result,target=Array.isArray(result?.urls)?result.urls[0]:void 0;if(!target||typeof target!="object")return null;let item=target;if(typeof item.put!="string"||!item.put||typeof item.get!="string"||!item.get)return null;let rawHeaders=item.putHeaders&&typeof item.putHeaders=="object"?item.putHeaders:{},putHeaders=Object.fromEntries(Object.entries(rawHeaders).map(([key,value])=>[key,String(value)]));return{put:item.put,get:item.get,putHeaders}}async function uploadImage(file2){let uploader=config2.imagePicker;if(!uploader)throw new Error("图片上传能力未配置");let env=/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"online",response=await callMtopAsync({api:uploader.api,v:uploader.version,method:"POST",env,timeout:6e4,data:{fcId:uploader.fcId,fcGroup:uploader.fcGroup,fcName:uploader.uploadUrlFunction,fcData:JSON.stringify({requestType:"url",mimes:[file2.type||"image/jpeg"],prefix:uploader.prefix,region:uploader.region,uploadNumber:1}),fcConfig:JSON.stringify({timeout:6e4,disasterRecover:!0})}}),target=pickDirectUploadTarget(response);if(!target)throw new Error("获取图片上传地址失败");let uploadUrl=`${target.put}${target.put.includes("?")?"&":"?"}getAvatar=1`,uploadResponse=await fetch(uploadUrl,{method:"PUT",headers:target.putHeaders,body:file2});if(uploadResponse.status!==200)throw new Error(`图片直传失败: HTTP ${uploadResponse.status}`);return target.get}function openImagePicker(callbackCommandFn){let input=document.createElement("input");input.type="file",input.accept="image/*",input.style.display="none";let settled=!1,finish=()=>{settled=!0,input.remove()};input.addEventListener("cancel",finish,{once:!0}),input.addEventListener("change",()=>{let file2=input.files?.[0];if(!file2){finish();return}if(!file2.type.startsWith("image/")){finish(),console.error(TAG,"仅支持选择图片文件");return}uploadImage(file2).then(pic=>{typeof callbackCommandFn=="function"&&callbackCommandFn({pic,uuid:createUploadId(),timeStamp:Date.now()}),log2("图片选择并上传完成:",pic)}).catch(error48=>console.error(TAG,"图片上传失败:",error48)).finally(finish)},{once:!0}),(document.body??document.documentElement).appendChild(input),input.click(),window.addEventListener("focus",()=>{setTimeout(()=>{!settled&&!input.files?.length&&finish()},1e3)},{once:!0})}function showPaymentDialog(api,params,succeed,failed){document.querySelector('[data-mearl-payment-dialog="true"]')?.remove();let overlay=document.createElement("div");overlay.setAttribute("data-mearl-payment-dialog","true"),Object.assign(overlay.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)"});let card=document.createElement("div");Object.assign(card.style,{background:"#fff",borderRadius:"12px",padding:"24px",width:"300px",textAlign:"center",fontFamily:"system-ui, sans-serif"});let title=document.createElement("div");Object.assign(title.style,{fontSize:"17px",fontWeight:"600",marginBottom:"8px"}),title.textContent="支付确认";let desc=document.createElement("div");Object.assign(desc.style,{fontSize:"14px",color:"#666",marginBottom:"20px"}),desc.textContent=`模拟 ${api} 支付,请选择操作`;let btnRow=document.createElement("div");Object.assign(btnRow.style,{display:"flex",gap:"12px"});let btnBase=(text,bg,color,action)=>{let btn=document.createElement("button");return btn.textContent=text,btn.setAttribute("data-mearl-action",action),Object.assign(btn.style,{flex:"1",padding:"10px 0",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:"500",cursor:"pointer",background:bg,color}),btn},confirmBtn=btnBase("完成支付","#1677ff","#fff","payment-confirm"),cancelBtn=btnBase("取消支付","#f5f5f5","#333","payment-cancel"),cleanup=()=>{overlay.remove()};confirmBtn.addEventListener("click",()=>{cleanup(),log2("用户完成支付",api),succeed(api==="wx.requestPayment"?{errMsg:"requestPayment:ok"}:{ResultStatus:"9000",resultStatus:"9000"})}),cancelBtn.addEventListener("click",()=>{cleanup(),log2("用户取消支付",api),failed(api==="wx.requestPayment"?{errMsg:"requestPayment:fail cancel"}:{ResultStatus:"6001",resultStatus:"6001"})}),btnRow.appendChild(cancelBtn),btnRow.appendChild(confirmBtn),card.appendChild(title),card.appendChild(desc),card.appendChild(btnRow),overlay.appendChild(card),(document.body??document.documentElement).appendChild(overlay)}function showMiniProgramActionDialog(action,params,confirmed,cancelled){document.querySelector('[data-mearl-mini-program-dialog="true"]')?.remove();let overlay=document.createElement("div");overlay.setAttribute("data-mearl-mini-program-dialog","true"),overlay.setAttribute("data-mearl-mini-program-action",action),Object.assign(overlay.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)"});let card=document.createElement("div");Object.assign(card.style,{background:"#fff",borderRadius:"12px",padding:"24px",width:"300px",textAlign:"center",fontFamily:"system-ui, sans-serif"});let title=document.createElement("div");Object.assign(title.style,{fontSize:"17px",fontWeight:"600",marginBottom:"8px"}),title.textContent=action==="navigateMiniProgram"?"打开其他小程序":"订阅消息";let desc=document.createElement("div");Object.assign(desc.style,{fontSize:"14px",color:"#666",marginBottom:"20px"});let targetTitle=params.title?.trim()||"其他";desc.textContent=action==="navigateMiniProgram"?`即将打开“${targetTitle}”小程序,是否继续?`:"模拟微信订阅消息授权,请选择操作";let btnRow=document.createElement("div");Object.assign(btnRow.style,{display:"flex",gap:"12px"});let createButton=(text,background,color,actionName)=>{let button=document.createElement("button");return button.textContent=text,button.setAttribute("data-mearl-action",actionName),Object.assign(button.style,{flex:"1",padding:"10px 0",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:"500",cursor:"pointer",background,color}),button},confirmButton=createButton(action==="navigateMiniProgram"?"确定":"允许","#1677ff","#fff","mini-program-confirm"),cancelButton=createButton("取消","#f5f5f5","#333","mini-program-cancel"),cleanup=()=>overlay.remove();confirmButton.addEventListener("click",()=>{cleanup();let result=action==="navigateMiniProgram"?{errMsg:"navigateToMiniProgram:ok"}:{result:"SUCCESS",data:{totalCount:1,acceptCount:1}};log2("用户确认小程序原生能力",action,params.appId??params.scene??""),confirmed(result)}),cancelButton.addEventListener("click",()=>{cleanup();let result=action==="navigateMiniProgram"?{errMsg:"navigateToMiniProgram:fail cancel"}:{result:"CLOSE_BY_USER"};log2("用户取消小程序原生能力",action),cancelled(result)}),btnRow.appendChild(cancelButton),btnRow.appendChild(confirmButton),card.appendChild(title),card.appendChild(desc),card.appendChild(btnRow),overlay.appendChild(card),(document.body??document.documentElement).appendChild(overlay)}function handleMessage(msg){if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_MTOP_RESPONSE"){let pending=pendingMtop[msg.requestId];if(!pending)return!0;delete pendingMtop[msg.requestId];let result=msg.result;return result?.success?pending.succ?.(result.response):pending.fail?.(result?.error??"mtop delegate failed"),!0}if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_USER_INFO_RESPONSE"){let requestId=msg.requestId,pending=pendingUserInfo[requestId];if(!pending)return!0;delete pendingUserInfo[requestId],clearTimeout(pending.timer);let result=msg.result,response=result?.success&&result.response&&typeof result.response=="object"?result.response:{};return pending.succ?.(result?.success?{...pending.fallback,...response}:degradedUserInfo(pending.fallback,typeof result?.error=="string"&&result.error?result.error:"native relay failed")),!0}if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_MTOP_STREAM_EVENT"){let requestId=msg.requestId,pending=pendingMtopStreams[requestId];if(!pending)return!0;let eventType=msg.eventType;return emitMtopStreamEvent(pending.sessionId,eventType,msg.data),(eventType==="onFinish"||eventType==="onError")&&delete pendingMtopStreams[requestId],!0}return!1}return{showAppToast,callMtop,callMtopStream,callUserInfo,openImagePicker,showPaymentDialog,showMiniProgramActionDialog,handleMessage}}function installAppProfileBridgeProtocol(config2,environment,host){let{w,SRC,TAG,isTop,log:log2}=environment,{pageTransport,systemBars,requestOpen,requestClose,requestCloseAll,requestContainerData}=host,{showAppToast,callMtop,callMtopStream,callUserInfo,openImagePicker,showPaymentDialog,showMiniProgramActionDialog}=pageTransport,{applyNavigationBarState,applyStatusBarState,syncSimulatedTitleBar}=systemBars,NOT_IMPLEMENTED_PAYLOAD=JSON.stringify({ret:["HY_FAILED"],msg:"not implemented"}),FPT_STORAGE_KEY=`__mearl_app_fpt__:${config2.profile}`,CALENDAR_STORAGE_KEY=`__mearl_app_calendar_events__:${config2.profile}`,unsupportedNativeInputNotified=!1,stopNetworkQualityMonitor=null,voiceRecognition=null,voiceRecognitionSession=0,voiceRecognitionTranscript="",voiceRecognitionInterimTranscript="",voiceRecognitionStopping=!1,voiceRecognitionRunning=!1,simulatedPageHidden=!1,simulatedVisibilityInstalled=!1,hasPendingMiniProgramBackData=!1,pendingMiniProgramBackData,notificationListeners=new Map,megaListenerSeq=0,megaBroadcastListeners=new Map,megaLifeCycleListeners=new Set,megaPageCloseListeners=new Set,megaSystemBackListener=null,megaKVMutationVersion=0,MEGA_KV_TOTAL_SIZE=5*1024*1024,MEGA_KV_STORAGE_KEY=`__mearl_mega_kv__:${config2.profile}`;function readMegaKVStorage(){let storage=new Map;try{let parsed=JSON.parse(localStorage.getItem(MEGA_KV_STORAGE_KEY)??"{}");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return storage;for(let[bizId,rawEntries]of Object.entries(parsed)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,value]of Object.entries(rawEntries))typeof value=="string"&&entries.set(key,value);storage.set(bizId,entries)}}catch{}return storage}let megaKVStorage=readMegaKVStorage();function megaKVSnapshot(){let snapshot={};for(let[bizId,values]of megaKVStorage)snapshot[bizId]=Object.fromEntries(values);return snapshot}function persistMegaKVStorage(){try{localStorage.setItem(MEGA_KV_STORAGE_KEY,JSON.stringify(megaKVSnapshot()))}catch{}}function replaceMegaKVStorage(value){if(!(!value||typeof value!="object"||Array.isArray(value))){megaKVStorage.clear();for(let[bizId,rawEntries]of Object.entries(value)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,entryValue]of Object.entries(rawEntries))typeof entryValue=="string"&&entries.set(key,entryValue);megaKVStorage.set(bizId,entries)}persistMegaKVStorage()}}function applyMegaKVMutation(payload){let operation=typeof payload.operation=="string"?payload.operation:"",bizId=typeof payload.bizId=="string"?payload.bizId:"",key=typeof payload.key=="string"?payload.key:"";if(bizId){if(operation==="set"&&key&&typeof payload.value=="string"){let entries=megaKVStorage.get(bizId)??new Map;entries.set(key,payload.value),megaKVStorage.set(bizId,entries)}else if(operation==="remove"&&key){let entries=megaKVStorage.get(bizId);entries?.delete(key),entries?.size===0&&megaKVStorage.delete(bizId)}else if(operation==="clear")megaKVStorage.delete(bizId);else return;megaKVMutationVersion+=1,persistMegaKVStorage()}}function emitMegaCallback(callback,value){callback&&setTimeout(()=>callback(value),0)}function megaBroadcastBizId(value){return typeof value=="string"&&value?value:"__MEGA_GLOBAL_MESSAGE__"}function dispatchMegaBroadcast(payload){let bizId=megaBroadcastBizId(payload.bizId),eventName=typeof payload.eventName=="string"?payload.eventName:"";if(eventName)for(let listener of Array.from(megaBroadcastListeners.values()))listener.bizId!==bizId||listener.eventName!==eventName||(listener.once&&megaBroadcastListeners.delete(listener.id),emitMegaCallback(listener.callback,{statusCode:1,type:"onEvent",data:{detail:payload.detail}}),listener.once&&emitMegaCallback(listener.callback,{statusCode:99,type:"finish"}))}let documentPrototype=typeof Document=="function"?Document.prototype:null,nativeHiddenDescriptor=documentPrototype?Object.getOwnPropertyDescriptor(documentPrototype,"hidden"):void 0,nativeVisibilityDescriptor=documentPrototype?Object.getOwnPropertyDescriptor(documentPrototype,"visibilityState"):void 0;function installSimulatedVisibilityState(){if(!simulatedVisibilityInstalled){simulatedVisibilityInstalled=!0;try{Object.defineProperty(document,"hidden",{configurable:!0,get:()=>simulatedPageHidden||!!(nativeHiddenDescriptor?.get?.call(document)??!1)}),Object.defineProperty(document,"visibilityState",{configurable:!0,get:()=>simulatedPageHidden?"hidden":nativeVisibilityDescriptor?.get?.call(document)??"visible"})}catch{}}}function dispatchPageTransitionEvent(type){try{let event=typeof PageTransitionEvent=="function"?new PageTransitionEvent(type,{persisted:!1}):new Event(type);window.dispatchEvent(event)}catch{}}function dispatchActiveEvents(){for(let name of config2.activeEvents)try{document.dispatchEvent(new Event(name))}catch{}}function handlePageVisibility(hidden){if(hidden===simulatedPageHidden)return;installSimulatedVisibilityState(),simulatedPageHidden=hidden;let lifeCycleType=hidden?"onPageDisappear":"onPageAppear";for(let callback of megaLifeCycleListeners)emitMegaCallback(callback,{statusCode:1,type:lifeCycleType,data:{pageId:location.href}});try{document.dispatchEvent(new Event("visibilitychange"))}catch{}if(hidden){try{window.dispatchEvent(new Event("blur"))}catch{}dispatchPageTransitionEvent("pagehide");return}dispatchPageTransitionEvent("pageshow");try{window.dispatchEvent(new Event("focus"))}catch{}dispatchActiveEvents()}function resolveWindowFunction(path19){let parts=path19.split(".").filter(Boolean),owner=w;for(let index=0;index<parts.length-1;index+=1){let next=owner[parts[index]];if(!next||typeof next!="object")return null;owner=next}let fn=owner[parts[parts.length-1]];return typeof fn=="function"?fn.bind(owner):null}function handleNativeBack(){let megaHandled=!1;for(let callback of megaPageCloseListeners)megaHandled=!0,emitMegaCallback(callback,{statusCode:1,type:"onClose",data:{}});if(megaSystemBackListener&&(megaHandled=!0,emitMegaCallback(megaSystemBackListener,{statusCode:1,type:"onSuccess",data:{}})),megaHandled)return!0;let nativeBack=config2.nativeBack;if(!nativeBack)return!1;if(nativeBack.handler){let handler=resolveWindowFunction(nativeBack.handler);if(!handler)return!1;try{return handler(),!0}catch{return!1}}let controlled=!1;if(nativeBack.controlFunction){let control=resolveWindowFunction(nativeBack.controlFunction);if(!control)return!1;try{controlled=control()===!0}catch{return!1}if(!controlled)return!1}if(!nativeBack.event)return controlled;try{let event=new Event(nativeBack.event,{cancelable:!0});return document.dispatchEvent(event),controlled||event.defaultPrevented}catch{return controlled}}function handleAppMessage(message){if(!message||typeof message!="object")return;let payload=message;if(payload.kind==="megaBroadcast"){dispatchMegaBroadcast(payload);return}if(payload.kind==="megaKVStorage"){applyMegaKVMutation(payload);return}if(payload.kind==="legacyBroadcast"&&typeof payload.instanceId=="string"){try{let event=new CustomEvent(`Broadcast.Message.${payload.instanceId}`,{detail:payload.message});Object.defineProperty(event,"param",{configurable:!0,value:payload.message}),document.dispatchEvent(event)}catch{}return}if(payload.kind==="notification"&&typeof payload.name=="string"){let listener=notificationListeners.get(payload.name);listener&&setTimeout(()=>listener(payload.data),0);return}if(!(payload.kind!=="message"||!config2.messageEvent))try{document.dispatchEvent(new CustomEvent(config2.messageEvent,{detail:{data:payload.data}}))}catch{}}function sendAppMessage(message){if(isTop){handleAppMessage(message);return}window.top?.postMessage({source:SRC,type:"appMessageToOpener",message},"*")}function applyRuntimeResponses(responses){let current=config2.actions.responses??{};for(let[api,response]of Object.entries(responses))!response||typeof response!="object"||Array.isArray(response)||(current[api]=response);config2.actions.responses=current}function parseFpt(value){let entries=[],normalized=value.trim();if(!normalized)return entries;let pattern=/([0-9A-Za-z._-]+)\(([0-9A-Za-z._-]+)\)/g,consumed="";for(let match of normalized.matchAll(pattern))consumed+=match[0],entries.push([match[1],match[2]]);return consumed===normalized?entries:[]}function setFptEntry(entries,key,value){entries.delete(key),entries.set(key,value)}function readInitialFptEntries(){let entries=new Map;try{for(let[key,value]of parseFpt(sessionStorage.getItem(FPT_STORAGE_KEY)??""))setFptEntry(entries,key,value)}catch{}try{let currentFpt=new URL(location.href).searchParams.get("fpt")??"";for(let[key,value]of parseFpt(currentFpt))setFptEntry(entries,key,value)}catch{}return entries}let fptEntries=readInitialFptEntries();function serializeFpt(entries){return Array.from(entries,([key,value])=>`${key}(${value})`).join("")}function persistFpt(){try{let value=serializeFpt(fptEntries);value?sessionStorage.setItem(FPT_STORAGE_KEY,value):sessionStorage.removeItem(FPT_STORAGE_KEY)}catch{}}function decorateUrlWithFpt(rawUrl){let targetUrl=mapScheme(rawUrl)??rawUrl;if(fptEntries.size===0)return targetUrl;try{let url2=new URL(targetUrl,location.href);if(url2.protocol!=="http:"&&url2.protocol!=="https:")return targetUrl;let merged=new Map(fptEntries);for(let[key,value]of parseFpt(url2.searchParams.get("fpt")??""))setFptEntry(merged,key,value);return url2.searchParams.set("fpt",serializeFpt(merged)),url2.href}catch{return targetUrl}}function classify(api){let a=config2.actions;return a.open.includes(api)?"open":a.close.includes(api)?"close":a.title.includes(api)?"title":a.navigationBar?.includes(api)?"navigationBar":a.statusBar?.includes(api)?"statusBar":a.systemInfo.includes(api)?"systemInfo":a.mtop.includes(api)?"mtop":a.kvGet?.includes(api)?"kvGet":a.kvSet?.includes(api)?"kvSet":a.kvDelete?.includes(api)?"kvDelete":a.pageContext?.includes(api)?"pageContext":a.responses&&Object.prototype.hasOwnProperty.call(a.responses,api)?"response":a.behaviors&&Object.prototype.hasOwnProperty.call(a.behaviors,api)?a.behaviors[api]:a.noop.includes(api)?"noop":"unknown"}function pickUrl(params){if(!params||typeof params!="object")return null;let p=params,candidates=[p.url,p.data?.url,p.param?.url,p.value?.params?.url];for(let c of candidates)if(typeof c=="string"&&c)return c;return null}function pickCloseData(params){if(params&&typeof params=="object"){let p=params;if("data"in p&&p.data!==void 0)return p.data;if(Object.keys(p).length>0)return p}}function decodeCookieValue2(raw){let value=raw;for(let i=0;i<2;i+=1)try{let decoded=decodeURIComponent(value);if(decoded===value)break;value=decoded}catch{break}return value.replace(/\\u([0-9a-f]{4})/gi,(_match,hex3)=>String.fromCharCode(Number.parseInt(hex3,16)))}function readCookie(name){let prefix=`${name}=`,pair=document.cookie.split(";").map(value=>value.trim()).find(value=>value.startsWith(prefix));return pair?decodeCookieValue2(pair.slice(prefix.length)):""}function readUserCookie(name){let pageUserCookie=w.userCookie;if(!pageUserCookie||typeof pageUserCookie!="object")return"";let value=pageUserCookie[name];return typeof value=="string"?decodeCookieValue2(value):""}function readFirstUserCookie(names){for(let name of names){let value=readCookie(name)||readUserCookie(name);if(value&&value!=="null")return value}return""}let cbSeq=0,callbacks={};function stashCallback(fn){if(typeof fn!="function")return 0;let id=++cbSeq;return callbacks[id]=fn,id}function extractQuery(url2,param){let q=url2.indexOf("?");if(q===-1)return null;for(let pair of url2.slice(q+1).split("&")){let eq=pair.indexOf("=");if(eq>0&&pair.slice(0,eq)===param)return pair.slice(eq+1)}return null}function matchesHostSuffix(hostname3,suffixes){if(!suffixes?.length)return!0;let normalizedHost=hostname3.toLowerCase().replace(/\.$/,"");return suffixes.some(value=>{let suffix=value.toLowerCase().replace(/^\./,"").replace(/\.$/,"");return normalizedHost===suffix||normalizedHost.endsWith(`.${suffix}`)})}function matchesRouteHost(rawUrl,suffixes){if(!suffixes?.length)return!0;try{let parsed=new URL(rawUrl,location.href),hostname3=parsed.protocol==="http:"||parsed.protocol==="https:"?parsed.hostname:location.hostname;return matchesHostSuffix(hostname3,suffixes)}catch{return matchesHostSuffix(location.hostname,suffixes)}}function resolveSchemeValue(raw,depth){if(depth>3)return null;let value=raw;try{value=decodeURIComponent(raw)}catch{}if(value.startsWith("{"))try{let found=pickUrl(JSON.parse(value));if(!found)return null;value=found}catch{return null}if(/^https?:/i.test(value))return value;if(/^[a-z][a-z0-9+.-]*:/i.test(value))return mapScheme(value,depth+1);let nestedUrl=extractQuery(value,"url");return nestedUrl?resolveSchemeValue(nestedUrl,depth+1):null}function mapScheme(url2,depth=0){if(depth>3)return null;let lower=url2.toLowerCase();for(let rule of config2.schemes){if(!matchesRouteHost(url2,rule.hostSuffixes))continue;let normalizedMatch=rule.match.toLowerCase(),matchedUrl=url2;if(!lower.startsWith(normalizedMatch)){if(!normalizedMatch.startsWith("/"))continue;try{let parsed=new URL(url2,location.href);if(matchedUrl=`${parsed.pathname}${parsed.search}${parsed.hash}`,!matchedUrl.toLowerCase().startsWith(normalizedMatch))continue}catch{continue}}if(rule.targetPath){let suffix=matchedUrl.slice(rule.match.length);if(suffix&&!suffix.startsWith("?")&&!suffix.startsWith("#"))continue;try{let source=new URL(matchedUrl),origin=location.origin;if(rule.targetHostPrefix){let hostname3=location.hostname.toLowerCase(),domainSuffix=hostname3==="wapa.taobao.com"||hostname3.endsWith(".wapa.taobao.com")?"wapa.taobao.com":hostname3==="m.taobao.com"||hostname3.endsWith(".m.taobao.com")?"m.taobao.com":"";domainSuffix&&(origin=`https://${rule.targetHostPrefix}.${domainSuffix}`)}let target=new URL(rule.targetPath,`${origin}/`);target.search=source.search,target.hash=source.hash;for(let[key,value]of Object.entries(rule.targetParams??{}))target.searchParams.has(key)||target.searchParams.set(key,value);return target.href}catch{return null}}if(!rule.param)continue;let raw=extractQuery(matchedUrl,rule.param);if(!raw)return null;let resolved=resolveSchemeValue(raw,depth);if(!resolved||!rule.useCurrentOrigin)return resolved;try{let target=new URL(resolved);return`${location.origin}${target.pathname}${target.search}${target.hash}`}catch{return resolved}}return null}function firstRouteParam(params,names){for(let name of names){let value=params.get(name);if(value)return value}return""}function resolvePaymentCallbackUrl(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam){if(!rawUrl)return null;try{let target=new URL(rawUrl,location.href);for(let name of forwardParams){let value=paymentPageUrl.searchParams.get(name);value&&!target.searchParams.get(name)&&target.searchParams.set(name,value)}resultParam&&target.searchParams.set(resultParam.name,JSON.stringify(resultParam.value));let resolved=useCurrentOrigin&&(target.protocol==="http:"||target.protocol==="https:")?`${location.origin}${target.pathname}${target.search}${target.hash}`:target.href;return decorateUrlWithFpt(resolved)}catch{return null}}function openPaymentCallback(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam){let target=resolvePaymentCallbackUrl(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam);target&&requestOpen(target,0,!1)}function handleMiniProgramPaymentRoute(rawUrl){let paymentPageUrl;try{paymentPageUrl=new URL(rawUrl,location.href)}catch{return!1}let normalizedPathname=paymentPageUrl.pathname.replace(/\/+$/,"")||"/",rule=config2.miniProgram?.paymentRoutes?.find(candidate=>(candidate.pathname.replace(/\/+$/,"")||"/")===normalizedPathname&&matchesHostSuffix(paymentPageUrl.hostname,candidate.hostSuffixes));if(!rule)return!1;let successUrl=firstRouteParam(paymentPageUrl.searchParams,rule.successUrlParams),failureUrl=firstRouteParam(paymentPageUrl.searchParams,rule.failureUrlParams),forwardParams=rule.forwardParams??[],useCurrentOrigin=rule.useCurrentOrigin===!0,paymentParams;try{let parsed=JSON.parse(paymentPageUrl.searchParams.get(rule.paymentParamsParam)??"");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error;paymentParams=parsed,paymentParams.timeStamp!==void 0&&(paymentParams.timeStamp=String(paymentParams.timeStamp))}catch{return log2("微信支付参数解析失败,执行失败回跳",rawUrl),openPaymentCallback(failureUrl,paymentPageUrl,useCurrentOrigin,forwardParams),!0}return showPaymentDialog("wx.requestPayment",paymentParams,result=>{openPaymentCallback(successUrl,paymentPageUrl,useCurrentOrigin,forwardParams,rule.successResultParam?{name:rule.successResultParam,value:result}:void 0)},()=>{openPaymentCallback(failureUrl,paymentPageUrl,useCurrentOrigin,forwardParams)}),!0}function finishMiniProgramNativeRoute(action,result,storageId){handleResume({data:action==="subscribeMessage"?result:void 0,storageId,callbackId:0,final:!0})}function handleMiniProgramNativeRoute(rawUrl){let nativePageUrl;try{nativePageUrl=new URL(rawUrl,location.href)}catch{return!1}let normalizedPathname=nativePageUrl.pathname.replace(/\/+$/,"")||"/",action=nativePageUrl.searchParams.get("action");if(action!=="navigateMiniProgram"&&action!=="subscribeMessage"||!config2.miniProgram?.nativeRoutes?.find(candidate=>(candidate.pathname.replace(/\/+$/,"")||"/")===normalizedPathname&&candidate.actions.includes(action)&&matchesHostSuffix(nativePageUrl.hostname,candidate.hostSuffixes)))return!1;let params={};nativePageUrl.searchParams.forEach((value,name)=>{params[name]=value});let storageId=nativePageUrl.searchParams.get("__storage_id");return handlePageVisibility(!0),showMiniProgramActionDialog(action,params,result=>finishMiniProgramNativeRoute(action,result,storageId),result=>finishMiniProgramNativeRoute(action,result,storageId)),!0}function handleMiniProgramPostMessage(data){let rules=config2.miniProgram?.messageRules;if(!rules?.length)return!1;let messages=Array.isArray(data)?data:[data],handled=!1;for(let value of messages){if(!value||typeof value!="object"||Array.isArray(value))continue;let message=value;if(typeof message.type!="string")continue;let rule=rules.find(candidate=>candidate.type===message.type&&matchesHostSuffix(location.hostname,candidate.hostSuffixes));rule&&(handled=!0,rule.action==="stageBackData"?(pendingMiniProgramBackData=message.data,hasPendingMiniProgramBackData=!0):rule.action==="closeAll"&&(isTop?requestCloseAll(message.data)||requestClose(message.data):window.top?.postMessage({source:SRC,type:"closeAll",data:message.data},"*")))}return handled}function matchesImagePickerScheme(url2){let lower=url2.toLowerCase();return config2.imagePicker?.schemes.some(scheme=>lower.startsWith(scheme))===!0}function handleMaybeScheme(url2){if(typeof url2!="string"||!url2||!/^[a-z][a-z0-9+.-]*:/i.test(url2)||/^(https?|about|blob|data|javascript):/i.test(url2))return!1;let mapped=mapScheme(url2);return mapped?(log2("scheme 映射为 H5 open:",url2,"→",mapped),requestOpen(decorateUrlWithFpt(mapped),0,!1)):log2("外部 scheme 已拦截(真机表现为唤端):",url2),!0}function handleResume(msg){let{data,storageId,callbackId,final,gotoEvent,silent}=msg;if(gotoEvent&&dispatchGotoEvent(data),callbackId&&callbacks[callbackId]){if(!silent)try{callbacks[callbackId]({backdata:data})}catch(e){console.error(TAG,"callbackCommand 执行失败",e)}final&&delete callbacks[callbackId]}if(data&&typeof data=="object"&&storageId)try{let d={...data};d.__$data=!0,d.__$storageId=String(storageId),localStorage.setItem("XPI_BACK_LISTENER_DATA_STORAGE",JSON.stringify(d))}catch{}simulatedPageHidden?handlePageVisibility(!1):dispatchActiveEvents()}function dispatchGotoEvent(data){if(data!==void 0)try{document.dispatchEvent(new CustomEvent("WV.GotoEvent",{detail:{data}}))}catch{}}function sendUserTrack(params){if(!params||typeof params!="object")return;let p=params,logkey=typeof p.logkey=="string"?p.logkey:"",gmkey=typeof p.gmkey=="string"?p.gmkey:typeof p.event=="string"?p.event:"",gokey=typeof p.gokey=="string"?p.gokey:"";if(!/^\/[0-9A-Za-z._/-]+$/.test(logkey)||!/^[0-9A-Za-z_-]+$/.test(gmkey))return;let pageWindow=w,aplus=pageWindow.goldlog??pageWindow.aplus;if(typeof aplus?.send!="function")return;let configuredHost=aplus.getMetaInfo?.("aplus-rhost-g"),host2=(typeof configuredHost=="string"?configuredHost:"gm.mmstat.com").replace(/^https?:\/\//i,"").replace(/^\/\//,"").split("/")[0];if(!(!host2||!/^[0-9A-Za-z.-]+$/.test(host2)))try{aplus.send(`//${host2}${logkey}`,`gmkey=${encodeURIComponent(gmkey)}&gokey=${gokey}&ts=${Date.now()}`,"GET")}catch{}}function readNetworkState(){let connection=navigator.connection;return navigator.onLine?connection?.type==="wifi"?"wifi":connection?.effectiveType??"unknown":"fail"}function networkTypeNumber(state){return{wifi:2,"slow-2g":3,"2g":3,"3g":4,"4g":5,"5g":6,fail:7}[state]??0}function emitVoiceRecognitionEvent(name,detail){try{document.dispatchEvent(new CustomEvent(name,{detail}))}catch{}}function browserSpeechRecognitionConstructor(){let candidate=w.SpeechRecognition??w.webkitSpeechRecognition;return typeof candidate=="function"?candidate:null}function voiceRecognitionLanguage(){let language=config2.language||navigator.language||"zh-CN";return/^zh-hans$/i.test(language)?"zh-CN":/^zh-hant$/i.test(language)?"zh-TW":language}function localVoiceRecognitionLanguage(language){return/^zh-(cn|hans)$/i.test(language)?"cmn-Hans-CN":/^zh-(tw|hant)$/i.test(language)?"cmn-Hant-TW":language}function detachVoiceRecognition(recognition){recognition.onstart=null,recognition.onresult=null,recognition.onerror=null,recognition.onend=null,recognition.onspeechstart=null,recognition.onspeechend=null}function finishVoiceRecognition(recognition,status){if(voiceRecognition!==recognition)return;let content=voiceRecognitionInterimTranscript.trim()||voiceRecognitionTranscript.trim();voiceRecognition=null,voiceRecognitionSession+=1,voiceRecognitionRunning=!1,voiceRecognitionStopping=!1,voiceRecognitionInterimTranscript="",detachVoiceRecognition(recognition),emitVoiceRecognitionEvent("WV.Voicetone",{tone:0}),emitVoiceRecognitionEvent("WV.VoiceRecog",{content,finished:!0,status})}function cancelVoiceRecognition(notifyPage){let recognition=voiceRecognition;if(recognition){voiceRecognition=null,voiceRecognitionSession+=1,voiceRecognitionRunning=!1,voiceRecognitionStopping=!1,voiceRecognitionInterimTranscript="",detachVoiceRecognition(recognition);try{recognition.abort()}catch{}emitVoiceRecognitionEvent("WV.Voicetone",{tone:0}),notifyPage&&emitVoiceRecognitionEvent("WV.VoiceRecogFailed",{status:2})}}function startVoiceRecognition(succeed,failed){cancelVoiceRecognition(!1);let SpeechRecognition=browserSpeechRecognitionConstructor();if(!SpeechRecognition){let error48={error_code:-1,error_message:"speech recognition unavailable"};emitVoiceRecognitionEvent("WV.VoiceRecogFailed",{status:-1,...error48}),failed(error48);return}let recognition=new SpeechRecognition,session=++voiceRecognitionSession;voiceRecognition=recognition,voiceRecognitionTranscript="",voiceRecognitionInterimTranscript="",voiceRecognitionStopping=!1,voiceRecognitionRunning=!1,recognition.continuous=!0,recognition.interimResults=!0,recognition.maxAlternatives=1,recognition.lang=voiceRecognitionLanguage();let isCurrent=()=>voiceRecognition===recognition&&voiceRecognitionSession===session,recognitionFailed=!1,failRecognition=(message,code)=>{if(!isCurrent()||recognitionFailed)return;recognitionFailed=!0;let error48={error_code:-1,error_message:message,error:code};voiceRecognition=null,voiceRecognitionSession+=1,voiceRecognitionRunning=!1,voiceRecognitionStopping=!1,detachVoiceRecognition(recognition);try{recognition.abort()}catch{}emitVoiceRecognitionEvent("WV.Voicetone",{tone:0}),emitVoiceRecognitionEvent("WV.VoiceRecogFailed",{status:-1,...error48}),failed(error48)},beginRecognition=()=>{if(isCurrent())try{recognition.start(),voiceRecognitionRunning=!0,succeed({})}catch(error48){failRecognition(error48 instanceof Error?error48.message:"speech recognition start failed","start-failed")}};recognition.onstart=()=>{isCurrent()&&(voiceRecognitionRunning=!0)},recognition.onspeechstart=()=>{isCurrent()&&emitVoiceRecognitionEvent("WV.Voicetone",{tone:10})},recognition.onspeechend=()=>{isCurrent()&&emitVoiceRecognitionEvent("WV.Voicetone",{tone:0})},recognition.onresult=event=>{if(!isCurrent()||!event.results)return;let interimTranscript="",startIndex=Math.max(0,event.resultIndex??0);for(let index=startIndex;index<event.results.length;index+=1){let result=event.results[index],transcript=result?.[0]?.transcript??"";result?.isFinal?voiceRecognitionTranscript+=transcript:interimTranscript+=transcript}let content=`${voiceRecognitionTranscript}${interimTranscript}`.trim();voiceRecognitionInterimTranscript=content,content&&emitVoiceRecognitionEvent("WV.VoiceRecogPartial",{content})},recognition.onerror=event=>{if(!isCurrent())return;let code=event.error??"unknown";code!=="no-speech"&&(code==="aborted"&&voiceRecognitionStopping||failRecognition(event.message||`speech recognition failed: ${code}`,code))},recognition.onend=()=>{if(isCurrent()){if(voiceRecognitionRunning=!1,voiceRecognitionStopping){finishVoiceRecognition(recognition,1);return}setTimeout(()=>{if(!(!isCurrent()||voiceRecognitionStopping))try{recognition.start(),voiceRecognitionRunning=!0}catch(error48){failRecognition(error48 instanceof Error?error48.message:"speech recognition restart failed","restart-failed")}},0)}};let localLanguage=localVoiceRecognitionLanguage(recognition.lang);if(typeof recognition.processLocally=="boolean"&&typeof SpeechRecognition.available=="function"){SpeechRecognition.available({langs:[localLanguage],processLocally:!0}).then(availability=>{if(isCurrent()){if(availability==="available"){recognition.lang=localLanguage,recognition.processLocally=!0,beginRecognition();return}if((availability==="downloadable"||availability==="downloading")&&typeof SpeechRecognition.install=="function"){showAppToast({message:"正在准备语音识别,首次使用可能需要一些时间",milliseconds:3e3}),SpeechRecognition.install({langs:[localLanguage],processLocally:!0}).then(installed=>{if(!installed){isCurrent()&&beginRecognition();return}if(!isCurrent()){showAppToast({message:"语音识别已准备好,请再试一次",milliseconds:3e3});return}recognition.lang=localLanguage,recognition.processLocally=!0,beginRecognition()}).catch(()=>beginRecognition());return}beginRecognition()}}).catch(()=>beginRecognition());return}beginRecognition()}function calendarTimestamp(value){if(typeof value=="number"&&Number.isFinite(value))return value;if(typeof value!="string"||!value.trim())return null;let numeric=Number(value);if(Number.isFinite(numeric)&&numeric>0)return numeric;let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}function calendarEventFromParams(params){let p=params&&typeof params=="object"?params:{},stringValue=(...values)=>values.find(value=>typeof value=="string")??"";return{title:stringValue(p.calendar_title,p.title),startTime:calendarTimestamp(p.calendar_start_ms??p.start_time??p.calendar_start_datetime),endTime:calendarTimestamp(p.calendar_end_ms??p.end_time??p.calendar_end_datetime),url:stringValue(p.calendar_url,p.url),note:stringValue(p.calendar_note,p.note),location:stringValue(p.calendar_location,p.location)}}function readCalendarEvents(){try{let parsed=JSON.parse(localStorage.getItem(CALENDAR_STORAGE_KEY)??"[]");return Array.isArray(parsed)?parsed.filter(event=>event!==null&&typeof event=="object"&&typeof event.title=="string"):[]}catch{return[]}}function writeCalendarEvents(events){try{return localStorage.setItem(CALENDAR_STORAGE_KEY,JSON.stringify(events)),!0}catch{return!1}}function sameCalendarEvent(stored,candidate){return candidate.url?stored.url===candidate.url:!!candidate.title&&stored.title===candidate.title&&(candidate.startTime===null||stored.startTime===candidate.startTime)&&(candidate.endTime===null||stored.endTime===candidate.endTime)}function calendarEventResponse(event){return{title:event.title,start_time:event.startTime,end_time:event.endTime,url:event.url,note:event.note,location:event.location}}function dispatch(api,params,onSuccess,onFailure,callbackCommandFn){let succeed=value=>{onSuccess&&setTimeout(()=>onSuccess(value),0)},failed=reason=>{onFailure&&setTimeout(()=>onFailure(reason),0)},kind=classify(api),silent=config2.actions.silent?.includes(api)===!0;if(silent||log2("桥调用",api,`(${kind})`,params??""),kind==="open"||kind==="navigate"){let p=params&&typeof params=="object"?params:{},navigationData=p.data&&typeof p.data=="object"?p.data:void 0;if(kind==="navigate"&&navigationData?.type==="back"){isTop?requestCloseAll(navigationData.data,!0)||dispatchGotoEvent(navigationData.data):window.top?.postMessage({source:SRC,type:"closeAll",data:navigationData.data,gotoEvent:!0},"*"),succeed({});return}let url2=pickUrl(params);if(!url2){failed("missing url");return}if(matchesImagePickerScheme(url2)){openImagePicker(callbackCommandFn),succeed({});return}if(handleMiniProgramPaymentRoute(url2)){succeed({});return}if(handleMiniProgramNativeRoute(url2)){succeed({});return}let wd=p.useWebdialog===!0||p.useWebdialog==="true"||p.useWebdialog===1||p.useWebdialog==="1";requestOpen(decorateUrlWithFpt(url2),stashCallback(callbackCommandFn),wd,p),succeed({});return}if(kind==="closeAll"){isTop?requestCloseAll(void 0):window.top?.postMessage({source:SRC,type:"closeAll"},"*"),succeed({});return}if(kind==="closeBackData"){let p=params&&typeof params=="object"?params:{};requestClose(Object.prototype.hasOwnProperty.call(p,"backdata")?p.backdata:pickCloseData(p)),succeed({});return}if(kind==="close"){if(api==="navigateBack"&&hasPendingMiniProgramBackData){let data=pendingMiniProgramBackData;pendingMiniProgramBackData=void 0,hasPendingMiniProgramBackData=!1,requestClose(data)}else requestClose(pickCloseData(params));succeed({});return}if(kind==="postMessage"){let p=params&&typeof params=="object"?params:{},data=p.data??p;handleMiniProgramPostMessage(data)||sendAppMessage({kind:"message",data}),succeed({});return}if(kind==="notifySubscribe"){let p=params&&typeof params=="object"?params:{};if(typeof p.name!="string"||!p.name){failed("missing notification name");return}onSuccess&&notificationListeners.set(p.name,onSuccess);return}if(kind==="notifyUnsubscribe"){let p=params&&typeof params=="object"?params:{};typeof p.name=="string"&&notificationListeners.delete(p.name),succeed({});return}if(kind==="notifyPost"){let p=params&&typeof params=="object"?params:{};if(typeof p.name!="string"||!p.name){failed("missing notification name");return}sendAppMessage({kind:"notification",name:p.name,data:p.data}),succeed({});return}if(kind==="sharedFileRead"||kind==="sharedFileWrite"||kind==="sharedDataGet"||kind==="sharedDataSet"){requestContainerData(kind,params&&typeof params=="object"?params:{},succeed,failed);return}if(kind==="legacyBroadcastCreate"||kind==="legacyBroadcastPost"||kind==="legacyBroadcastClose"){requestContainerData(kind,params&&typeof params=="object"?params:{},succeed,failed);return}if(kind==="title"){let title=params&&typeof params=="object"?params.title??params.name:void 0;if(typeof title=="string"&&title){systemBars.markStateExplicit();try{document.title=title,syncSimulatedTitleBar()}catch{}isTop||window.top?.postMessage({source:SRC,type:"title",title},"*")}succeed({});return}if(kind==="navigationBar"){applyNavigationBarState(api,params),succeed({});return}if(kind==="statusBar"){applyStatusBarState(params),succeed({});return}if(kind==="systemInfo"){let model=config2.globals.__DEVICE_MODEL__||"iPhone",info={language:config2.language,model,systemVersion:config2.systemVersion,statusBarHeight:config2.statusBarHeight,platform:config2.platform,brand:config2.platform==="iOS"?"Apple":"Android",client_version:config2.globals.__APP_VERSION__??"",client_type:config2.clientType};succeed(api==="WVNativeDetector.getModelInfo"?{...info,platform:model}:info);return}if(kind==="mtop"){callMtop(params??{},onSuccess,onFailure);return}if(kind==="mtopStream"){callMtopStream(params??{},succeed,failed);return}if(kind==="kvGet"||kind==="kvSet"||kind==="kvDelete"){let p=params&&typeof params=="object"?params:{},key=typeof p.key=="string"?p.key:"";if(!key){failed("missing key");return}try{let storageKey=`__mearl_app_kv__:${key}`;if(kind==="kvGet"){let stored=localStorage.getItem(storageKey);stored!==null?succeed(stored):failed(JSON.stringify({ret:["HY_FAILED"],msg:"key not found"}))}else if(kind==="kvSet"){let value=typeof p.value=="string"?p.value:p.value===void 0?"":JSON.stringify(p.value);localStorage.setItem(storageKey,value),succeed({})}else localStorage.removeItem(storageKey),succeed({})}catch{failed(JSON.stringify({ret:["HY_FAILED"],msg:"kv storage unavailable"}))}return}if(kind==="pageContext"){succeed({pageContext:void 0});return}if(kind==="memoryGet"||kind==="memorySet"||kind==="memoryDelete"){let p=params&&typeof params=="object"?params:{},key=typeof p.key=="string"?p.key:"";if(!key){failed({error_message:"missing key"});return}try{let storageKey=`__mearl_app_memory__:${key}`;if(kind==="memoryGet"){let value=sessionStorage.getItem(storageKey);succeed(value===null?{}:{value})}else if(kind==="memorySet"){let value=typeof p.value=="string"?p.value:p.value===void 0?"":JSON.stringify(p.value);sessionStorage.setItem(storageKey,value),succeed({key,success:!0})}else sessionStorage.removeItem(storageKey),succeed({key,success:!0})}catch{failed({error_message:"memory cache unavailable"})}return}if(kind==="availabilityMap"){let p=params&&typeof params=="object"?params:{},channels=Array.isArray(p.data)?p.data.filter(value=>typeof value=="string"):[];succeed({res:"success",data:Object.fromEntries(channels.map(channel=>[channel,!1]))});return}if(kind==="userInfo"){let userId=readFirstUserCookie(["unb"]),userName=readFirstUserCookie(["_w_tb_nick","_nk_","snk","tracknick"]);callUserInfo({...userId&&{userId},...userName&&{userName}},succeed);return}if(kind==="networkInfo"){let state=readNetworkState();if(api==="WVNetwork.getNetworkType"){succeed({type:{wifi:"WIFI","slow-2g":"2G","2g":"2G","3g":"3G","4g":"4G"}[state]??"UNKNOWN"});return}if(config2.profile==="alipay"||config2.profile==="koubei"){succeed({networkAvailable:state!=="fail",networkType:{wifi:"WIFI","slow-2g":"2G","2g":"2G","3g":"3G","4g":"4G",fail:"NOTREACHABLE"}[state]??"UNKNOWN"});return}let type=networkTypeNumber(state);succeed({type,state:state==="slow-2g"?"2g":state});return}if(kind==="networkQualityMonitor"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"";if(action==="add_notify_network_quality"){if(!stopNetworkQualityMonitor){let notify=()=>{try{document.dispatchEvent(new CustomEvent("WV.NETWORK_TYPE_CHANGED",{detail:{new_network_type:networkTypeNumber(readNetworkState())}}))}catch{}},connection=navigator.connection;window.addEventListener("online",notify),window.addEventListener("offline",notify),connection?.addEventListener?.("change",notify),stopNetworkQualityMonitor=()=>{window.removeEventListener("online",notify),window.removeEventListener("offline",notify),connection?.removeEventListener?.("change",notify)}}succeed({});return}if(action==="remove_notify_network_quality"){stopNetworkQualityMonitor?.(),stopNetworkQualityMonitor=null,succeed({});return}failed({error_message:"unsupported network quality monitor action"});return}if(kind==="voiceRecognition"){let status=Number((params&&typeof params=="object"?params:{}).status);if(status===0){startVoiceRecognition(succeed,failed);return}if(status===1){let recognition=voiceRecognition;if(recognition)if(voiceRecognitionStopping=!0,voiceRecognitionRunning)try{recognition.stop()}catch{finishVoiceRecognition(recognition,1)}else finishVoiceRecognition(recognition,1);succeed({});return}if(status===2){cancelVoiceRecognition(!0),succeed({});return}failed({error_code:-1,error_message:"unsupported voice recognition status"});return}if(kind==="beaconRequest"){let url2=pickUrl(params);if(!url2){failed({error_message:"missing url"});return}try{let resolved=new URL(url2,location.href);if(resolved.protocol!=="http:"&&resolved.protocol!=="https:"){failed({error_message:"unsupported request protocol"});return}let image=new Image;image.referrerPolicy="no-referrer-when-downgrade",image.src=resolved.href,succeed({})}catch{failed({error_message:"invalid url"})}return}if(kind==="calendar"){let p=params&&typeof params=="object"?params:{},events=readCalendarEvents();if(api==="store_calendar_event"){let event=calendarEventFromParams(p);if(!event.title||event.startTime===null){failed({error_message:"calendar title and start time are required"});return}let next=events.filter(stored=>!sameCalendarEvent(stored,event));if(next.push(event),!writeCalendarEvents(next)){failed({error_message:"calendar storage unavailable"});return}succeed({success:!0});return}if(api==="remove_calendar_event"){let candidate=calendarEventFromParams(p),next=events.filter(stored=>!sameCalendarEvent(stored,candidate));if(!writeCalendarEvents(next)){failed({error_message:"calendar storage unavailable"});return}succeed({success:!0,removed:events.length-next.length});return}if(api==="check_batch_calendar"){let batch=Array.isArray(p.batch)?p.batch:[];succeed({batch:batch.map(item=>{let candidate=calendarEventFromParams(item);return{...item&&typeof item=="object"?item:{},success:events.some(stored=>sameCalendarEvent(stored,candidate))}})});return}let urls=Array.isArray(p.urls)?p.urls.filter(value=>typeof value=="string"):typeof p.url=="string"?[p.url]:[],titles=Array.isArray(p.calendar_titles)?p.calendar_titles.filter(value=>typeof value=="string"):typeof p.calendar_title=="string"?[p.calendar_title]:[],matched=events.filter(event=>(urls.length===0||urls.includes(event.url))&&(titles.length===0||titles.includes(event.title)));succeed({events:matched.map(calendarEventResponse)});return}if(kind==="geolocation"){let p=params&&typeof params=="object"?params:{},windvane=api==="WVLocation.getLocation",wechat=api==="getLocation"&&config2.bridges.some(bridge=>bridge.style==="wechat"),failLocation=(errorCode,errorMsg)=>{failed({errorCode,errorMsg,...windvane&&{ret:["HY_FAILED"],errMsg:errorCode===1?"PERMISSION_DENIED":"POSITION_UNAVAILABLE",message:errorMsg},...wechat&&{errMsg:`getLocation:fail ${errorMsg}`}})};if(wechat&&p.type&&p.type!=="wgs84"){failLocation(2,`unsupported coordinate type: ${String(p.type)}`);return}if(!navigator.geolocation){failLocation(2,"geolocation unavailable");return}let locate=()=>navigator.geolocation.getCurrentPosition(position=>{let{latitude,longitude,accuracy,altitude,altitudeAccuracy,heading,speed}=position.coords,coords={latitude,longitude,accuracy,altitude,altitudeAccuracy,heading,speed};if(api==="lbs"){let provider=config2.geolocation;if(!provider){failLocation(2,"reverse geocoding unavailable");return}callMtop({api:provider.reverseGeocodeApi,v:provider.version,data:{latitude,longitude,includeGJ:1},timeout:5e3},value=>{let response=value??{},address=response.data??{};if(!Array.isArray(response.ret)||!response.ret.some(ret=>typeof ret=="string"&&ret.startsWith("SUCCESS::"))||typeof address.cityName!="string"||!address.cityName.trim()||typeof address.cityCode!="string"||!address.cityCode.trim()){failLocation(2,"reverse geocoding returned no city");return}succeed({...coords,timestamp:position.timestamp,country:address.country,province:address.province,district:address.district,city:address.cityName,cityName:address.cityName,cityCode:address.cityCode,divisionId:address.divisionId,iataCode:address.iataCode,address:address.detail})},()=>failLocation(2,"reverse geocoding failed"));return}succeed(windvane?{ret:["HY_SUCCESS"],coords,timestamp:position.timestamp}:{...coords,timestamp:position.timestamp,...wechat&&{errMsg:"getLocation:ok"}})},error48=>failLocation(error48.code,error48.message),{enableHighAccuracy:p.enableHighAccuracy===!0||p.enableHighAcuracy===!0,timeout:1e4,maximumAge:p.useCache===!1?0:3e5});navigator.permissions?.query?navigator.permissions.query({name:"geolocation"}).then(status=>{status.state==="granted"?locate():failLocation(1,"location permission not granted")}).catch(locate):locate();return}if(kind==="permission"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"",permission=typeof p.permission=="string"?p.permission:"",permissionFailed=message=>failed({error_code:-1,error_message:message});if(permission==="album"||permission==="MODIFY_AUDIO_SETTINGS"){action==="check"||action==="request"?succeed({}):permissionFailed("unsupported permission action");return}let browserPermission=permission==="mic"?"microphone":permission==="camera"?"camera":permission==="lbs"?"geolocation":"";if(!browserPermission){permissionFailed("unsupported permission");return}if(action==="check"&&navigator.permissions?.query){navigator.permissions.query({name:browserPermission}).then(status=>{status.state==="granted"?succeed({}):permissionFailed("permission not granted")}).catch(()=>permissionFailed("permission check failed"));return}if(action==="request"&&(permission==="mic"||permission==="camera")){if(!navigator.mediaDevices?.getUserMedia){permissionFailed("media permission unavailable");return}navigator.mediaDevices.getUserMedia({audio:permission==="mic",video:permission==="camera"}).then(stream=>{for(let track of stream.getTracks())track.stop();succeed({})}).catch(()=>permissionFailed("permission denied"));return}if(action==="request"&&permission==="lbs"&&navigator.geolocation){navigator.geolocation.getCurrentPosition(()=>succeed({}),()=>permissionFailed("permission denied"),{timeout:1e4});return}permissionFailed("unsupported permission action");return}if(kind==="prefetch"){let p=params&&typeof params=="object"?params:{},url2=typeof p.url=="string"?p.url:"";if(!url2){failed({code:-1,errorMsg:"url is empty"});return}let resolvedUrl;try{resolvedUrl=new URL(url2,location.href).href}catch{failed({code:-1,errorMsg:"invalid url"});return}if(!Array.from(document.querySelectorAll('link[rel="prefetch"]')).some(link=>link.href===resolvedUrl)){let link=document.createElement("link");link.rel="prefetch",link.href=url2,(document.head??document.documentElement).appendChild(link)}succeed({});return}if(kind==="fptTrack"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"",actionParams=p.params&&typeof p.params=="object"?p.params:{},key=typeof actionParams.key=="string"?actionParams.key:"";if(action==="setFpt"){let value=typeof actionParams.value=="string"?actionParams.value:"";if(!key||!value||!/^[0-9A-Za-z._-]+$/.test(key)||!/^[0-9A-Za-z._-]+$/.test(value)||`${key}(${value})`.length>100){failed({error_message:"invalid fpt key or value"});return}setFptEntry(fptEntries,key,value),persistFpt()}else action==="deleteFpt"&&key&&(fptEntries.delete(key),persistFpt());succeed({});return}if(kind==="previewFile"){let p=params&&typeof params=="object"?params:{},fileUrl=typeof p.file_url=="string"?p.file_url:"",remoteUrl=typeof p.file_remote_url=="string"?p.file_remote_url:"",url2=(fileUrl.startsWith("http")?fileUrl:remoteUrl)||fileUrl||remoteUrl;url2?(requestOpen(url2,0,!1),succeed({})):failed({code:-1,errorMsg:"file_url is empty"});return}if(kind==="toast"){let error48=showAppToast(params);error48?failed({error_message:error48}):succeed({});return}if(kind==="unsupportedNativeInput"){let containerType="";try{containerType=new URL(location.href).searchParams.get("containerType")??""}catch{}!unsupportedNativeInputNotified&&(containerType==="h5_dx"||containerType==="flutter_h5")&&(unsupportedNativeInputNotified=!0,showAppToast({message:"当前页面使用原生输入框,请移除 URL 中的 containerType 参数以正常操作",milliseconds:4e3})),succeed({});return}if(kind==="payment"){log2("桥调用支付,等待用户确认",api,params),showPaymentDialog(api,params,succeed,failed);return}if(kind==="userTrack"){sendUserTrack(params),succeed({});return}if(kind==="response"){succeed(config2.actions.responses?.[api]);return}if(kind==="noop"){succeed({});return}silent||log2("未覆盖桥方法,回调 failure(页面库将走 H5 兜底):",api),failed(NOT_IMPLEMENTED_PAYLOAD)}let MEGA_SUPPORTED_APIS={stdPop:["showWeex2","showWeex","showH5","changeSize","close"],broadcast:["addEventListener","dispatchEvent","removeEventListener"],kvStorage:["setItem","getItem","removeItem","getAllKeys","clear","getCurrentInfo","getCurrentInfoAndKeys"],LifeCycle:["addPageLifeCycleListener","removePageLifeCycleListener"],Container:["interceptPageClose","disableInterceptPageClose"],navigator:["openURL","close","replace","setSystemBackBlockListener","removeSystemBackBlockListener"],NavBar:["setTitle"],Router:["popPage"]};function isMegaApiSupported(ability,api){return typeof ability=="string"&&typeof api=="string"&&MEGA_SUPPORTED_APIS[ability]?.includes(api)===!0}function megaParams(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:{}}function megaError(callback,statusCode,message){emitMegaCallback(callback,{statusCode,type:"result",data:{errorMessage:typeof message=="string"?message:String(message??"")}})}function cloneMegaDetail(value){if(value===void 0)return{success:!0,value:void 0};try{return{success:!0,value:JSON.parse(JSON.stringify(value))}}catch{return{success:!1}}}function megaSuccess(data={}){return{statusCode:0,type:"result",data}}function megaFailure(message){return{statusCode:500,type:"result",data:{errorMessage:message}}}function megaKVParams(params){return{bizId:typeof params.bizID=="string"?params.bizID:typeof params.bizId=="string"?params.bizId:"",key:typeof params.key=="string"?params.key:"",value:typeof params.value=="string"?params.value:null}}function megaStringByteLength(value){try{return typeof TextEncoder=="function"?new TextEncoder().encode(value).length:value.length}catch{return value.length}}function megaKVUsedSize(entries){let size=0;for(let value of entries.values())size+=megaStringByteLength(value);return size}function reportMegaKVMutation(operation,bizId,key="",value,onSuccess,onFailure){requestContainerData("megaKVMutation",{operation,bizId,key,...value===void 0?{}:{value}},()=>onSuccess?.(),reason=>{log2("KVStorage 容器同步失败:",reason),onFailure?.(reason)})}function completeMegaKVMutation(operation,bizId,key,value,synchronous,callback){let result=megaSuccess();return reportMegaKVMutation(operation,bizId,key,value,synchronous?void 0:()=>emitMegaCallback(callback,result),synchronous?void 0:reason=>emitMegaCallback(callback,megaFailure(String(reason??"container sync failed")))),synchronous?result:null}function executeMegaKVStorage(api,params,synchronous,callback){let{bizId,key,value}=megaKVParams(params);if(!bizId)return megaFailure("missing bizID");let entries=megaKVStorage.get(bizId)??new Map;if(api==="setItem"){if(!key)return megaFailure("missing key");if(value===null||value==="")return megaFailure("missing value");let previousSize=megaStringByteLength(entries.get(key)??"");return megaKVUsedSize(entries)-previousSize+megaStringByteLength(value)>MEGA_KV_TOTAL_SIZE?megaFailure("KVStorage quota exceeded"):(entries.set(key,value),megaKVStorage.set(bizId,entries),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("set",bizId,key,value,synchronous,callback))}if(api==="getItem"){if(!key)return megaFailure("missing key");let result=entries.get(key)??"";return megaSuccess(synchronous?{result}:result)}if(api==="removeItem")return key?(entries.delete(key),entries.size===0&&megaKVStorage.delete(bizId),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("remove",bizId,key,void 0,synchronous,callback)):megaFailure("missing key");if(api==="getAllKeys"){let result=Array.from(entries.keys());return megaSuccess(synchronous?{result}:result)}if(api==="clear")return megaKVStorage.delete(bizId),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("clear",bizId,"",void 0,synchronous,callback);if(api==="getCurrentInfo"||api==="getCurrentInfoAndKeys"){let data={totalSize:MEGA_KV_TOTAL_SIZE,freeSize:Math.max(MEGA_KV_TOTAL_SIZE-megaKVUsedSize(entries),0)};return api==="getCurrentInfoAndKeys"&&(data.keys=Array.from(entries.keys())),megaSuccess(data)}return{statusCode:405,type:"result",data:{}}}function handleMegaLifeCycle(api,callback){if(api==="addPageLifeCycleListener"){callback&&megaLifeCycleListeners.add(callback),emitMegaCallback(callback,megaSuccess());return}if(api==="removePageLifeCycleListener"){let listeners=Array.from(megaLifeCycleListeners);megaLifeCycleListeners.clear(),emitMegaCallback(callback,megaSuccess());for(let listener of listeners)emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`LifeCycle.${api} is not supported`)}function handleMegaContainer(api,callback){if(api==="interceptPageClose"){callback&&megaPageCloseListeners.add(callback),emitMegaCallback(callback,megaSuccess());return}if(api==="disableInterceptPageClose"){let listeners=Array.from(megaPageCloseListeners);megaPageCloseListeners.clear(),emitMegaCallback(callback,megaSuccess());for(let listener of listeners)emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`Container.${api} is not supported`)}function megaNavigationUrl(params){let rawUrl=pickUrl(params);if(!rawUrl)return null;if(!params.extQuery||typeof params.extQuery!="object"||Array.isArray(params.extQuery))return rawUrl;try{let target=new URL(rawUrl,location.href);for(let[key,value]of Object.entries(params.extQuery))value!=null&&target.searchParams.set(key,String(value));return target.href}catch{return rawUrl}}function handleMegaNavigator(api,params,callback){if(api==="openURL"||api==="replace"){let url2=megaNavigationUrl(params);if(!url2){megaError(callback,500,"missing url");return}let callbackId=api==="openURL"&&callback?stashCallback(value=>{let backdata=value&&typeof value=="object"?value.backdata:void 0;emitMegaCallback(callback,{statusCode:1,type:"onResult",data:{result:!0,...backdata===void 0?{}:{data:backdata}}}),emitMegaCallback(callback,{statusCode:99,type:"finish",data:{}})}):0;requestOpen(url2,callbackId,!1,{...params,...api==="replace"?{__mearlReplace:!0}:{}}),emitMegaCallback(callback,megaSuccess());return}if(api==="close"){emitMegaCallback(callback,megaSuccess()),requestClose(void 0);return}if(api==="setSystemBackBlockListener"){megaSystemBackListener&&megaSystemBackListener!==callback&&emitMegaCallback(megaSystemBackListener,{statusCode:99,type:"finish",data:{}}),megaSystemBackListener=callback??null,emitMegaCallback(callback,megaSuccess());return}if(api==="removeSystemBackBlockListener"){let listener=megaSystemBackListener;megaSystemBackListener=null,emitMegaCallback(callback,megaSuccess()),listener&&emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`navigator.${api} is not supported`)}function handleMegaNavBar(api,params,callback){if(api!=="setTitle"){megaError(callback,405,`NavBar.${api} is not supported`);return}applyNavigationBarState(api,params),emitMegaCallback(callback,megaSuccess())}function handleMegaRouter(api,callback){if(api!=="popPage"){megaError(callback,405,`Router.${api} is not supported`);return}emitMegaCallback(callback,megaSuccess()),requestClose(void 0)}function handleMegaStdPop(api,params,callback){if(api==="showH5"||api==="showWeex2"||api==="showWeex"){let url2=pickUrl(params),popId=typeof params.popId=="string"?params.popId.trim():"";if(!url2||!popId){megaError(callback,500,url2?"missing popId":"missing url");return}let callbackId=stashCallback(value=>{let result=value&&typeof value=="object"&&"backdata"in value?value.backdata:void 0;emitMegaCallback(callback,{statusCode:1,type:"onClose",data:result}),emitMegaCallback(callback,{statusCode:99,type:"finish"})});requestOpen(url2,callbackId,!0,{...params,__mearlMegaPopId:popId}),emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});return}if(api==="close"){let popId=typeof params.popId=="string"?params.popId.trim():"";if(!popId){megaError(callback,500,"missing popId");return}let cloned=cloneMegaDetail(params.result);if(!cloned.success){megaError(callback,500,"result is not serializable");return}requestContainerData("megaPopClose",{popId,result:cloned.value},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}if(api==="changeSize"){let popId=typeof params.popId=="string"?params.popId.trim():"";if(!popId){megaError(callback,500,"missing popId");return}requestContainerData("megaPopResize",{...params,popId},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}megaError(callback,405,`stdPop.${api} is not supported`)}function handleMegaBroadcast(api,params,callback){let bizId=megaBroadcastBizId(params.bizId),eventName=typeof params.eventName=="string"?params.eventName.trim():"";if(!eventName){megaError(callback,500,"missing eventName");return}if(api==="addEventListener"){if(!callback)return;let id=`mearl-mega-listener-${++megaListenerSeq}`;megaBroadcastListeners.set(id,{id,bizId,eventName,once:params.once===!0,callback}),emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),emitMegaCallback(callback,{statusCode:1,type:"onAdd",data:{listenerId:id}});return}if(api==="dispatchEvent"){let detail=cloneMegaDetail(params.detail);if(!detail.success){megaError(callback,500,"detail is not serializable");return}requestContainerData("megaBroadcast",{message:{kind:"megaBroadcast",bizId,eventName,detail:detail.value}},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}if(api==="removeEventListener"){let listenerId=typeof params.listenerId=="string"?params.listenerId:"",removed=[];for(let listener of Array.from(megaBroadcastListeners.values()))listener.bizId!==bizId||listener.eventName!==eventName||listenerId&&listener.id!==listenerId||(megaBroadcastListeners.delete(listener.id),removed.push(listener));emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});for(let listener of removed)emitMegaCallback(listener.callback,{statusCode:99,type:"finish"});return}megaError(callback,405,`broadcast.${api} is not supported`)}function makeMegaBridge(){return{asyncCall:(ability,api,rawParams,callback)=>{let params=megaParams(rawParams);if(ability==="ability"&&api==="available"){emitMegaCallback(callback,{statusCode:0,type:isMegaApiSupported(params.ability,params.api)?"YES":"NO",data:{}});return}if(ability==="ability"&&api==="batchFinishTrace"){emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});return}if(!isMegaApiSupported(ability,api)){megaError(callback,405,`${ability}.${api} is not supported`);return}if(ability==="stdPop")handleMegaStdPop(api,params,callback);else if(ability==="broadcast")handleMegaBroadcast(api,params,callback);else if(ability==="kvStorage"){let result=executeMegaKVStorage(api,params,!1,callback);result&&emitMegaCallback(callback,result)}else ability==="LifeCycle"?handleMegaLifeCycle(api,callback):ability==="Container"?handleMegaContainer(api,callback):ability==="navigator"?handleMegaNavigator(api,params,callback):ability==="NavBar"?handleMegaNavBar(api,params,callback):handleMegaRouter(api,callback)},syncCall:(ability,api,rawParams)=>{let params=megaParams(rawParams);return ability==="ability"&&api==="available"?{statusCode:0,type:isMegaApiSupported(params.ability,params.api)?"YES":"NO",data:{}}:ability==="kvStorage"&&isMegaApiSupported(ability,api)?executeMegaKVStorage(api,params,!0)??megaFailure("container sync pending"):{statusCode:405,type:"result",data:{}}}}}function makeBridge(style){if(style==="mega")return makeMegaBridge();if(style==="easybikeNative"){let callNative=rawPayload=>{let payload;try{payload=typeof rawPayload=="string"?JSON.parse(rawPayload):rawPayload??{}}catch{return}let classMap=typeof payload.classMap=="string"?payload.classMap:"",method=typeof payload.method=="string"?payload.method:"",callbackId=typeof payload.callbackId=="string"||typeof payload.callbackId=="number"?String(payload.callbackId):"",params;try{params=typeof payload.params=="string"?payload.params?JSON.parse(payload.params):{}:payload.params??{}}catch{params={}}let complete=(code,data,msg="")=>{let callback=resolveWindowFunction("callBack");callbackId&&callback&&callback({callbackId,code,data,msg})};dispatch(`${classMap}.${method}`,params,value=>complete(0,value),error48=>complete(1,void 0,typeof error48=="string"?error48:String(error48??"")))};return{postMessage:callNative,callNative}}if(style==="windvane"){let call=(api,params,success2,failure)=>{let onSuccess=typeof success2=="function"?success2:void 0,onFailure=typeof failure=="function"?failure:void 0;if(onSuccess||onFailure){dispatch(api,params,onSuccess,onFailure);return}return new Promise((resolve2,reject)=>dispatch(api,params,resolve2,reject))};return{isAvailable:!0,version:"8.7.0",call2:call,call:(cls,method,params,succ,fail2)=>call(`${cls}.${method}`,params,succ,fail2)}}if(style==="fliggy"||style==="alipay"||style==="callback"){let bridge={call:(api,params,succ,fail2)=>{typeof params=="function"&&(fail2=succ,succ=params,params=void 0);let p=params&&typeof params=="object"?params:{},successFn=succ??(typeof p.success_callback=="function"?p.success_callback:void 0)??(typeof p.successCallback=="function"?p.successCallback:void 0),failureFn=fail2??(typeof p.fail_callback=="function"?p.fail_callback:void 0)??(typeof p.failure_callback=="function"?p.failure_callback:void 0)??(typeof p.failCallback=="function"?p.failCallback:void 0)??(typeof p.failureCallback=="function"?p.failureCallback:void 0);dispatch(api,p,res=>successFn?.(res),err=>{failureFn?failureFn(err):successFn?.({error:err})},p.callbackCommand??p.callback_command)},pushBack:(prefixOrApi,apiOrParams,paramsOrSucc,succ)=>{let api=prefixOrApi,params=apiOrParams,success2=paramsOrSucc;typeof apiOrParams=="string"&&(api=apiOrParams,params=paramsOrSucc,success2=succ);let p=params??{},successFn=(typeof success2=="function"?success2:void 0)??(typeof p.successCallback=="function"?p.successCallback:void 0);return dispatch(api,p,res=>successFn?.(res),void 0,p.callbackCommand??p.callback_command),bridge},sendUriScheme:uri=>(handleMaybeScheme(uri),bridge)};if(style==="fliggy"){let normalizedAppName=(config2.globals.__APP_NAME__??"").toUpperCase(),os11=config2.clientType==="iphone"?"ios":"android",isAliApp=name=>normalizedAppName===name.toUpperCase();Object.assign(bridge,{version:"1.0.21",device:{os:os11,OS:config2.platform,type:os11,version:config2.systemVersion,model:config2.globals.__DEVICE_MODEL__??""},platform:os11,isAliApp,isTmall:isAliApp("TM"),isTaobao:isAliApp("TB"),isAlipay:isAliApp("AP"),isAlitrip:isAliApp("LX"),isKoubei:isAliApp("KB"),isElm:isAliApp("ELMC"),isGaode:isAliApp("amap"),isUC:/UCBrowser/i.test(config2.userAgent),isWeibo:/Weibo/i.test(config2.userAgent),isWeixin:/MicroMessenger/i.test(config2.userAgent),isWindVane:config2.bridges.some(item=>item.style==="windvane"),isAlipayClient:/AlipayClient/i.test(config2.userAgent)})}return bridge}if(style==="btrip")return{call:(api,params)=>dispatch(api,params??{},void 0,void 0)};if(style==="invoke")return{invoke:(api,params)=>{let p=params??{};dispatch(api,p,p.success,p.fail)}};if(style==="callHandler")return{callHandler:(api,params)=>dispatch(api,params??{},void 0,void 0)};if(style==="amap")return{ready:cb=>cb?.(),send:(msg,cb)=>{let m=msg??{};dispatch(typeof m.action=="string"?m.action:"",m,res=>cb?.(res),err=>cb?.({error:err}))}};if(style==="didi")return{openPage:params=>dispatch("openPage",params??{},void 0,void 0),closePage:params=>dispatch("closePage",params??{},void 0,void 0)};if(style==="wechat"||style==="wechatMiniProgram"){let invoke2=(api,params)=>{let p=params&&typeof params=="object"?params:{};dispatch(api,p,value=>{p.success?.(value),p.complete?.(value)},error48=>{p.fail?.(error48),p.complete?.(error48)})};return style==="wechat"?{ready:callback=>{callback&&setTimeout(callback,0)},getLocation:params=>invoke2("getLocation",params)}:{navigateTo:params=>invoke2("navigateTo",params),redirectTo:params=>invoke2("redirectTo",params),switchTab:params=>invoke2("switchTab",params),reLaunch:params=>invoke2("reLaunch",params),navigateBack:params=>invoke2("navigateBack",params),postMessage:params=>invoke2("postMessage",params),getEnv:callback=>{callback&&setTimeout(()=>callback({miniprogram:!0}),0)}}}return{}}function setGlobal(path19,value){let parts=path19.split("."),obj=w;for(let i=0;i<parts.length-1;i++){let cur=obj[parts[i]];(!cur||typeof cur!="object")&&(obj[parts[i]]={}),obj=obj[parts[i]]}obj[parts[parts.length-1]]=value}function setPersistentGlobal(path19,value){let parts=path19.split(".").filter(Boolean);if(parts.length<2){setGlobal(path19,value);return}let[rootKey,...nestedParts]=parts,isObjectLike=candidate=>typeof candidate=="object"&&candidate!==null||typeof candidate=="function",attachBridge=candidate=>{let root=isObjectLike(candidate)?candidate:{},obj=root;for(let index=0;index<nestedParts.length-1;index+=1){let key=nestedParts[index],child=obj[key];if(!isObjectLike(child))try{obj[key]={}}catch{return root}obj=obj[key]}let leaf=nestedParts[nestedParts.length-1];try{Object.defineProperty(obj,leaf,{configurable:!1,enumerable:!0,get:()=>value,set:()=>{}})}catch{try{obj[leaf]=value}catch{}}return root},currentRoot=attachBridge(w[rootKey]);try{Object.defineProperty(w,rootKey,{configurable:!1,enumerable:!0,get:()=>currentRoot,set:next=>{currentRoot=attachBridge(next)}})}catch{w[rootKey]=currentRoot}}if(config2.bridges.some(spec=>spec.style==="mega")){let hydrationVersion=megaKVMutationVersion;requestContainerData("megaKVSnapshot",{},value=>{let entries=value&&typeof value=="object"?value.entries:void 0;megaKVMutationVersion===hydrationVersion&&replaceMegaKVStorage(entries)},()=>{})}for(let spec of config2.bridges)try{let bridge=makeBridge(spec.style);spec.persistent?setPersistentGlobal(spec.global,bridge):setGlobal(spec.global,bridge)}catch(e){console.error(TAG,"桥安装失败:",spec.global,e)}return{mapScheme,handleMaybeScheme,handleAppMessage,handleNativeBack,handleResume,handlePageVisibility,applyRuntimeResponses}}function installAppProfileContainerStack(config2,environment,links){let{SRC,TAG,simulateSystemBars,ROOT_FRAME_NAME,LAYER_FRAME_NAME,isTop,isRootFrame,isLayerFrame,isContainerFrame,usesRootContainer,log:log2}=environment,{pageTransport}=links,initialLayerTitleBarState=url2=>links.getSystemBars().initialLayerTitleBarState(url2),resolvedTitleBarState=layer=>links.getSystemBars().resolvedTitleBarState(layer),parseReportedTitleBarState=value=>links.getSystemBars().parseReportedTitleBarState(value),createSimulatedNavigationBarView=(placement,onBack)=>links.getSystemBars().createNavigationBarView(placement,onBack),destroySimulatedNavigationBarView=view=>links.getSystemBars().destroyNavigationBarView(view),syncLayerViewport=(layer,state)=>links.getSystemBars().syncLayerViewport(layer,state),syncActiveSystemBars=()=>links.getSystemBars().syncActiveSystemBars(),syncSimulatedTitleBar=()=>links.getSystemBars().syncSimulatedTitleBar(),rootContainerActive=!1,rootFrame=null,rootBusinessUrl=location.href,splitScreenActive=usesRootContainer&&config2.rootContainer?.splitScreen===!0,webViewEnvironmentRequestSeq=0,simulatedPageHidden=!1,runtimeResponses=null;function syncSimulatorStateToWindow(target){target&&(target.postMessage({source:SRC,type:"requestTitleBarState"},"*"),runtimeResponses&&target.postMessage({source:SRC,type:"runtimeResponses",profile:config2.profile,responses:runtimeResponses},"*"),simulatedPageHidden&&target.postMessage({source:SRC,type:"simulatorVisibility",hidden:!0},"*"))}function startPreparedWebViewNavigation(frame,target,canCommit,registerCleanup){let insets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0};if(!usesRootContainer||!Object.values(insets).some(value=>value>0)){canCommit()&&(frame.src=target);return}let requestId=++webViewEnvironmentRequestSeq,settled=!1,fallbackTimer=0,cleanup=()=>{settled||(settled=!0,clearTimeout(fallbackTimer),window.removeEventListener("message",handleResponse),registerCleanup?.(null))},commitNavigation=fallbackReason=>{cleanup(),fallbackReason&&console.warn(TAG,"WebView 环境准备未完成,降级提交导航",{target,requestId,reason:fallbackReason}),canCommit()&&(frame.src=target)},handleResponse=event=>{if(event.source!==window||event.data?.source!=="mearl-content"||event.data?.type!=="APP_BRIDGE_PREPARE_WEBVIEW_RESPONSE"||event.data?.requestId!==requestId)return;let result=event.data.result;result?.success===!0?commitNavigation():commitNavigation(String(result?.error??"unknown preparation failure"))};registerCleanup?.(cleanup),window.addEventListener("message",handleResponse),fallbackTimer=setTimeout(()=>commitNavigation("preparation timed out after 500ms"),500);try{window.postMessage({source:SRC,type:"prepareWebView",requestId},"*")}catch(error48){commitNavigation(error48 instanceof Error?error48.message:String(error48))}}function installRootContainer(){if(!usesRootContainer||!/^https?:$/i.test(location.protocol))return;let shellRoot,frame;try{for(let cookie of config2.rootContainer?.initialCookies??[]){if(!cookie.name)continue;let parts=[`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,`Path=${cookie.path??"/"}`];cookie.domain&&parts.push(`Domain=${cookie.domain}`),document.cookie=parts.join("; ")}shellRoot=document.createElement("html");let shellHead=document.createElement("head"),charset=document.createElement("meta"),viewport=document.createElement("meta"),title=document.createElement("title"),shellBody=document.createElement("body");frame=document.createElement("iframe"),shellRoot.setAttribute("data-mearl-app-shell",""),shellBody.setAttribute("data-mearl-app-shell",""),charset.setAttribute("charset","utf-8"),viewport.name="viewport",viewport.content="width=device-width,initial-scale=1,viewport-fit=cover",shellHead.append(charset,viewport,title),shellRoot.append(shellHead,shellBody),shellRoot.style.cssText="width:100%;height:100%;margin:0;overflow:hidden;background:#fff;",shellBody.style.cssText="width:100%;height:100%;margin:0;overflow:hidden;background:#fff;",frame.name=ROOT_FRAME_NAME,frame.setAttribute("data-mearl-root-webview",config2.profile),frame.setAttribute("allow","microphone; on-device-speech-recognition"),splitScreenActive&&frame.setAttribute("data-mearl-split-pane","left"),frame.style.cssText=splitScreenActive?"position:fixed;left:0;right:auto;top:0;bottom:0;width:50%;height:100%;border:0;border-right:1px solid rgba(15,23,42,.14);box-sizing:border-box;display:block;background:#fff;z-index:0;opacity:1;":"position:fixed;left:0;right:0;top:0;bottom:0;width:100%;height:100%;border:0;display:block;background:#fff;z-index:0;opacity:1;",frame.addEventListener("load",()=>{let committedSrc=frame.getAttribute("src");!committedSrc||committedSrc==="about:blank"||(syncSimulatorStateToWindow(frame.contentWindow),requestAnimationFrame(()=>{rootFrame!==frame||!frame.isConnected||(frame.setAttribute("data-mearl-webview-ready",""),syncSimulatedTitleBar())}))}),shellBody.appendChild(frame);let currentRoot=document.documentElement;currentRoot?document.replaceChild(shellRoot,currentRoot):document.appendChild(shellRoot)}catch(error48){console.warn(TAG,"根 WebView 容器创建失败,保留当前页面",error48),rootFrame=null;return}rootFrame=frame,rootContainerActive=!0;try{typeof window.stop=="function"&&window.stop()}catch(error48){console.warn(TAG,"停止外层文档加载失败,继续启动根 WebView",error48)}try{startPreparedWebViewNavigation(frame,rootBusinessUrl,()=>rootFrame===frame&&frame.isConnected)}catch(error48){console.warn(TAG,"根 WebView 环境准备启动失败,直接提交业务导航",error48),rootFrame===frame&&frame.isConnected&&(frame.src=rootBusinessUrl)}}installRootContainer();function normalizeProxyPathPrefix(prefix){let withLeadingSlash=prefix.startsWith("/")?prefix:`/${prefix}`;return withLeadingSlash.endsWith("/")?withLeadingSlash:`${withLeadingSlash}/`}function matchesProxyTarget(hostname3,suffixes){return suffixes.some(suffix=>hostname3===suffix||hostname3.endsWith(`.${suffix}`))}function mapLayerFrameUrl(url2){let proxy=config2.layerUrlProxy;if(!proxy||!location.hostname.startsWith(proxy.sourceHostPrefix))return url2;try{let target=new URL(url2,location.href);if(!/^https?:$/.test(target.protocol))return url2;let prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(target.hostname===location.hostname){if(target.pathname.startsWith(prefix))return url2;let derivedHost=location.pathname.startsWith(prefix)?location.pathname.slice(prefix.length).split("/")[0]:proxy.defaultTargetHost;return!derivedHost||!matchesProxyTarget(derivedHost,proxy.targetHostSuffixes)?url2:`${location.origin}${prefix}${derivedHost}${target.pathname}${target.search}${target.hash}`}return matchesProxyTarget(target.hostname,proxy.targetHostSuffixes)?`${location.origin}${prefix}${target.host}${target.pathname}${target.search}${target.hash}`:url2}catch{return url2}}function restoreLayerBusinessUrl(url2){let proxy=config2.layerUrlProxy;if(!proxy)return url2;try{let current=new URL(url2,location.href),prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(current.origin!==location.origin||!current.pathname.startsWith(prefix))return url2;let rest=current.pathname.slice(prefix.length),slash=rest.indexOf("/"),host=slash===-1?rest:rest.slice(0,slash);if(!host)return url2;let hostname3=new URL(`${current.protocol}//${host}`).hostname;if(!matchesProxyTarget(hostname3,proxy.targetHostSuffixes))return url2;let pathname=slash===-1?"/":rest.slice(slash);return`${current.protocol}//${host}${pathname}${current.search}${current.hash}`}catch{return url2}}let ANIM_MS=config2.animationMs??300;function boolParam(value,fallback){return value===!0||value===1||value==="1"||value==="true"?!0:value===!1||value===0||value==="0"||value==="false"?!1:value===""?!0:fallback}function numberParam(value,fallback,min,max){let parsed=typeof value=="number"?value:Number(value);return Number.isFinite(parsed)?Math.min(Math.max(parsed,min),max):fallback}function resolveOverlayPresentation(url2,params,explicitWebdialog){let query=null;try{query=new URL(url2,location.href).searchParams}catch{}let records=[],addRecord=value=>{value&&typeof value=="object"&&!Array.isArray(value)&&records.push(value)};addRecord(params?.pageParams),addRecord(params?.page_params),addRecord(params?.popConfig),addRecord(params?.data),addRecord(params?.param),addRecord(params);let read=key=>{for(let record2 of records)if(Object.prototype.hasOwnProperty.call(record2,key))return record2[key];return query?.has(key)?query.get(key):void 0},protocol=config2.overlay;if(!explicitWebdialog&&(!protocol||!boolParam(read(protocol.enabledParam),!1)))return null;let configuredTopRatio=protocol?read(protocol.topRatioParam):void 0,configuredHeightRatio=protocol?.heightRatioParam?read(protocol.heightRatioParam):void 0,configuredMaxHeight=read("maxHeight")??configuredHeightRatio,defaultTopRatio=protocol?.defaultTopRatio??.2;return{topRatio:configuredTopRatio!==void 0?numberParam(configuredTopRatio,defaultTopRatio,0,1):configuredMaxHeight!==void 0?1-numberParam(configuredMaxHeight,1-defaultTopRatio,0,1):defaultTopRatio,widthRatio:numberParam(read("maxWidth"),1,0,1),radius:numberParam((protocol?read(protocol.radiusParam):void 0)??read("cornerRadius"),protocol?.defaultRadius??0,0,50),maskAlpha:numberParam(protocol?read(protocol.maskAlphaParam):void 0,protocol?.defaultMaskAlpha??.3,0,1),tapClose:boolParam((protocol?read(protocol.tapCloseParam):void 0)??read("tapEnable"),protocol?.defaultTapClose??!0)}}function requestsPopBeforeOpen(url2,params){if(params?.__mearlReplace===!0)return!0;let key=config2.popBeforeOpenParam;if(!key)return!1;let records=[params?.pageParams,params?.page_params,params?.data,params?.param,params];for(let value of records){if(!value||typeof value!="object"||Array.isArray(value))continue;let record2=value;if(Object.prototype.hasOwnProperty.call(record2,key))return boolParam(record2[key],!1)}try{let query=new URL(url2,location.href).searchParams;return query.has(key)&&boolParam(query.get(key),!1)}catch{return!1}}let layers=[],forwardStack=[],layerSeq=0,enteringLayerCount=0,closingLayerCount=0,explicitLayerTitleBarStates=new Map,rootScrollStyles=null,pendingClose=null,nativeBackRequestSeq=0,pendingNativeBack=null,containerDataRequestSeq=0,containerDataCallbacks=new Map,sharedFiles=new Map,sharedData=new Map,legacyBroadcastChannels=new Set,MEGA_KV_STORAGE_KEY=`__mearl_mega_kv__:${config2.profile}`;function readMegaKVStorage(){let storage=new Map;try{let parsed=JSON.parse(localStorage.getItem(MEGA_KV_STORAGE_KEY)??"{}");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return storage;for(let[bizId,rawEntries]of Object.entries(parsed)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,value]of Object.entries(rawEntries))typeof value=="string"&&entries.set(key,value);storage.set(bizId,entries)}}catch{}return storage}let megaKVStorage=readMegaKVStorage();function megaKVSnapshot(){let snapshot={};for(let[bizId,values]of megaKVStorage)snapshot[bizId]=Object.fromEntries(values);return snapshot}function persistMegaKVStorage(){try{localStorage.setItem(MEGA_KV_STORAGE_KEY,JSON.stringify(megaKVSnapshot()))}catch{}}let PENDING_CLOSE_TIMEOUT_MS=400,pendingHistoryDepth=null,pendingSplitRootOpen=null;function clearPendingClose(){pendingClose&&(clearTimeout(pendingClose.timer),pendingClose=null)}function clearPendingNativeBack(){pendingNativeBack&&(clearTimeout(pendingNativeBack.timer),pendingNativeBack=null)}function clearPendingHistoryDepth(){pendingHistoryDepth&&(clearTimeout(pendingHistoryDepth.timer),pendingHistoryDepth=null)}function syncHistoryAfterDirectClose(){clearPendingHistoryDepth();let depth=layers.length,timer=setTimeout(()=>{pendingHistoryDepth=null,console.warn(TAG,"WebView 已出栈,但浏览器历史未在预期时间内同步",{depth})},PENDING_CLOSE_TIMEOUT_MS);pendingHistoryDepth={depth,timer},history.back()}function armPendingClose(data,retries){clearPendingClose();let timer=setTimeout(()=>{pendingClose=null,log2("close 未等到 popstate,直接关栈顶兜底"),closeToDepth(Math.max(layers.length-1,0),data,!0)},PENDING_CLOSE_TIMEOUT_MS);pendingClose={data,retries,timer},history.back()}function parseStorageId(url2){try{return new URL(url2,location.href).searchParams.get("__storage_id")}catch{return null}}function titleBarStateCacheKey(url2){try{let parsed=new URL(url2,location.href);return parsed.hash="",parsed.href}catch{return url2}}function cacheExplicitTitleBarState(layer,state){explicitLayerTitleBarStates.set(titleBarStateCacheKey(layer.entryUrl),state),explicitLayerTitleBarStates.set(titleBarStateCacheKey(layer.url),state)}function readDepth(state){if(state&&typeof state=="object"){let d=state.__mearl_layer__;if(typeof d=="number")return d}return null}function mapUrlForSync(url2){let suffixes=config2.urlSyncHostSuffixes??[];try{let u=new URL(url2,location.href);if(!/^https?:$/.test(u.protocol)||!(suffixes.length===0||suffixes.some(s=>u.host===s||u.host.endsWith(`.${s}`))))return;if(u.origin===location.origin)return u.pathname+u.search+u.hash;let proxy=config2.layerUrlProxy;return proxy&&location.hostname.startsWith(proxy.sourceHostPrefix)&&matchesProxyTarget(u.hostname,proxy.targetHostSuffixes)?`${normalizeProxyPathPrefix(proxy.pathPrefix)}${u.host}${u.pathname}${u.search}${u.hash}`:u.pathname+u.search+u.hash}catch{return}}function createLayerEl(overlay,id){let el=document.createElement("div");el.setAttribute("data-mearl-layer",String(id)),splitScreenActive&&el.setAttribute("data-mearl-split-pane","right"),el.style.cssText=splitScreenActive?`position:fixed;left:50%;right:0;top:0;bottom:0;width:50%;z-index:${2147483e3+id%100*2};`:`position:fixed;inset:0;z-index:${2147483e3+id%100*2};`;let frame=document.createElement("iframe");if(frame.name=LAYER_FRAME_NAME,frame.setAttribute("allow","microphone; on-device-speech-recognition"),frame.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-modals allow-downloads allow-popups"),frame.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0;display:block;background:#fff;z-index:0;opacity:1;",overlay){el.style.pointerEvents="none";let mask=document.createElement("div");mask.style.cssText=`position:absolute;inset:0;background:rgba(0,0,0,${overlay.maskAlpha});opacity:0;pointer-events:auto;`;let sheet=document.createElement("div"),width=overlay.widthRatio*100,left=(1-overlay.widthRatio)/2*100;return sheet.style.cssText=`position:absolute;left:${left}%;right:auto;bottom:0;width:${width}%;height:${(1-overlay.topRatio)*100}%;background:#fff;border-radius:${overlay.radius}px ${overlay.radius}px 0 0;overflow:hidden;pointer-events:auto;`,sheet.appendChild(frame),el.appendChild(mask),el.appendChild(sheet),{el,frame,animEl:sheet,mask}}return el.style.background="#fff",el.appendChild(frame),{el,frame,animEl:el,mask:null}}function setLayerInteractive(layer,interactive){layer.frame.style.pointerEvents=interactive?"":"none",layer.titleBarView&&(layer.titleBarView.root.style.pointerEvents=interactive?"":"none"),interactive?(layer.frame.removeAttribute("inert"),layer.frame.removeAttribute("aria-hidden"),layer.frame.removeAttribute("tabindex")):(layer.frame.setAttribute("inert",""),layer.frame.setAttribute("aria-hidden","true"),layer.frame.setAttribute("tabindex","-1"),layer.frame.blur()),layer.overlay?(layer.el.style.pointerEvents="none",layer.animEl.style.pointerEvents=interactive?"auto":"none",layer.mask&&(layer.mask.style.pointerEvents=interactive?"auto":"none")):layer.el.style.pointerEvents=interactive?"":"none"}function setRootFrameInteractive(interactive){rootFrame&&(rootFrame.style.pointerEvents=interactive?"":"none",interactive?(rootFrame.removeAttribute("inert"),rootFrame.removeAttribute("aria-hidden"),rootFrame.removeAttribute("tabindex")):(rootFrame.setAttribute("inert",""),rootFrame.setAttribute("aria-hidden","true"),rootFrame.setAttribute("tabindex","-1"),rootFrame.blur()))}function blockClosingLayerInteractions(layer){setLayerInteractive(layer,!1),layer.el.style.pointerEvents="auto"}function syncRootScrollLock(locked){let body=document.body;if(locked&&!rootScrollStyles){rootScrollStyles={html:document.documentElement.style.overflow,body:body?.style.overflow??null},document.documentElement.style.overflow="hidden",body&&(body.style.overflow="hidden");return}!locked&&rootScrollStyles&&(document.documentElement.style.overflow=rootScrollStyles.html,body&&rootScrollStyles.body!==null&&(body.style.overflow=rootScrollStyles.body),rootScrollStyles=null)}function syncLayerInteractivity(){let activeLayer=closingLayerCount===0&&enteringLayerCount===0?layers[layers.length-1]:void 0;for(let layer of layers)setLayerInteractive(layer,layer===activeLayer),!activeLayer&&layer===layers[layers.length-1]&&(layer.el.style.pointerEvents="auto");setRootFrameInteractive(splitScreenActive?pendingSplitRootOpen===null:layers.length===0&&enteringLayerCount===0&&closingLayerCount===0),syncRootScrollLock(layers.length>0||enteringLayerCount>0||closingLayerCount>0)}function finishLayerEntry(layer){layer.entering&&(layer.entering=!1,layer.enterTimer!==null&&clearTimeout(layer.enterTimer),layer.enterTimer=null,layer.enterTransitionEnd&&(layer.animEl.removeEventListener("transitionend",layer.enterTransitionEnd),layer.enterTransitionEnd=null),enteringLayerCount=Math.max(enteringLayerCount-1,0),syncLayerInteractivity())}function animateIn(layer){let t=layer.animEl;if(t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",t.offsetWidth,t.style.transition=`transform ${ANIM_MS}ms ease`,t.style.transform="translate(0px, 0px)",layer.mask&&(layer.mask.style.transition=`opacity ${ANIM_MS}ms ease`,layer.mask.style.opacity="1"),ANIM_MS<=0){finishLayerEntry(layer);return}layer.enterTransitionEnd=event=>{event.target===t&&event.propertyName==="transform"&&finishLayerEntry(layer)},t.addEventListener("transitionend",layer.enterTransitionEnd),layer.enterTimer=setTimeout(()=>finishLayerEntry(layer),ANIM_MS+60)}function animateOut(layer,done){let t=layer.animEl;if(ANIM_MS<=0){t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",layer.mask&&(layer.mask.style.opacity="0"),setTimeout(done,0);return}let settled=!1,fallbackTimer=0,finish=()=>{settled||(settled=!0,t.removeEventListener("transitionend",onTransitionEnd),clearTimeout(fallbackTimer),done())},onTransitionEnd=event=>{event.target===t&&event.propertyName==="transform"&&finish()};t.addEventListener("transitionend",onTransitionEnd),t.style.transition=`transform ${ANIM_MS}ms ease`,t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",layer.mask&&(layer.mask.style.opacity="0"),fallbackTimer=setTimeout(finish,ANIM_MS+60)}function startLayerNavigation(layer,target){startPreparedWebViewNavigation(layer.frame,target,()=>!layer.closing&&layer.el.isConnected,cleanup=>{layer.navigationPreparationCleanup=cleanup})}function setPageVisibility(target,hidden){if(target===window){links.getBridgeProtocol().handlePageVisibility(hidden);return}try{target.postMessage({source:SRC,type:"simulatorVisibility",hidden},"*")}catch{}}function openLayer(url2,callbackId,overlay,openerWin,pushHistory,popId=null,animateEntry=!0){clearPendingClose();let target=url2;if(!/^https?:/i.test(target)){let mapped=links.getBridgeProtocol().mapScheme(target);if(!mapped)return log2("open 失败,scheme 未映射:",url2),null;target=mapped}location.protocol==="https:"&&target.startsWith("http:")&&(target="https:"+target.slice(5));let presentation=overlay??resolveOverlayPresentation(target,void 0,!1);log2("open →",presentation?"(webdialog) ":"",target);let parts=createLayerEl(presentation,++layerSeq),restoredTitleBarState=explicitLayerTitleBarStates.get(titleBarStateCacheKey(target)),layer={id:layerSeq,win:parts.frame.contentWindow,frame:parts.frame,entryUrl:target,url:target,overlay:presentation,openerWin,callbackId,storageId:parseStorageId(target),popId,el:parts.el,animEl:parts.animEl,mask:parts.mask,entering:animateEntry,enterTimer:null,enterTransitionEnd:null,closing:!1,navigationPreparationCleanup:null,titleBarState:restoredTitleBarState??initialLayerTitleBarState(target),titleBarStateExplicit:restoredTitleBarState!==void 0,titleBarStateReady:restoredTitleBarState!==void 0,titleBarView:null};if(popId&&layer.el.setAttribute("data-mearl-pop-id",popId),layer.mask&&presentation?.tapClose&&layer.mask.addEventListener("click",()=>requestOverlayClose(layer)),!presentation&&simulateSystemBars&&config2.titleBar&&(layer.titleBarView=createSimulatedNavigationBarView("layer",()=>requestNativeBack()),layer.titleBarView.root.setAttribute("data-mearl-layer-titlebar",String(layer.id)),parts.el.appendChild(layer.titleBarView.root)),layers.push(layer),splitScreenActive&&rootFrame?.contentWindow===openerWin||setPageVisibility(openerWin,!0),animateEntry&&(enteringLayerCount+=1),syncLayerViewport(layer,layer.titleBarState),syncLayerInteractivity(),parts.frame.addEventListener("load",()=>{layer.win=parts.frame.contentWindow,parts.frame.name=LAYER_FRAME_NAME;let committedSrc=parts.frame.getAttribute("src");!committedSrc||committedSrc==="about:blank"||(syncSimulatorStateToWindow(parts.frame.contentWindow),requestAnimationFrame(()=>{layer.titleBarStateReady||layer.closing||!layer.el.isConnected||(layer.titleBarStateReady=!0,syncLayerViewport(layer,resolvedTitleBarState(layer)))}))}),(document.body??document.documentElement).appendChild(parts.el),layer.win=parts.frame.contentWindow,startLayerNavigation(layer,mapLayerFrameUrl(target)),animateEntry&&animateIn(layer),pushHistory){forwardStack.length=0;try{history.pushState({__mearl_layer__:layers.length},"",mapUrlForSync(target))}catch{}}return layer}function replaceLayer(sourceLayer,url2,callbackId,overlay,popId=null){if(sourceLayer.closing||layers[layers.length-1]!==sourceLayer){openLayer(url2,callbackId,overlay,sourceLayer.win??window,!0,popId);return}let replacement=openLayer(url2,callbackId,overlay,sourceLayer.openerWin,!1,popId);if(!replacement)return;sourceLayer.navigationPreparationCleanup?.(),sourceLayer.navigationPreparationCleanup=null,sourceLayer.entering&&(sourceLayer.entering=!1,enteringLayerCount=Math.max(enteringLayerCount-1,0),sourceLayer.enterTimer!==null&&clearTimeout(sourceLayer.enterTimer),sourceLayer.enterTransitionEnd&&sourceLayer.animEl.removeEventListener("transitionend",sourceLayer.enterTransitionEnd));let sourceIndex=layers.indexOf(sourceLayer);sourceIndex>=0&&layers.splice(sourceIndex,1),destroySimulatedNavigationBarView(sourceLayer.titleBarView),sourceLayer.el.remove(),forwardStack.length=0,syncLayerInteractivity(),syncActiveSystemBars();try{history.replaceState({__mearl_layer__:layers.length},"",mapUrlForSync(replacement.url))}catch{}}function closeLayer(layer,data,final,gotoEvent=!1,resumeOpener=!0,silent=!1,immediate=!1){if(layer.closing)return;layer.navigationPreparationCleanup?.(),layer.navigationPreparationCleanup=null,layer.entering&&(layer.entering=!1,enteringLayerCount=Math.max(enteringLayerCount-1,0),layer.enterTimer!==null&&clearTimeout(layer.enterTimer),layer.enterTimer=null,layer.enterTransitionEnd&&(layer.animEl.removeEventListener("transitionend",layer.enterTransitionEnd),layer.enterTransitionEnd=null)),layer.closing=!0;let idx=layers.indexOf(layer);idx>=0&&layers.splice(idx,1),closingLayerCount+=1,blockClosingLayerInteractions(layer),syncLayerInteractivity(),syncActiveSystemBars(),final?forwardStack.length=0:forwardStack.push({url:layer.url,overlay:layer.overlay,openerWin:layer.openerWin,callbackId:layer.callbackId,storageId:layer.storageId,popId:layer.popId}),log2("close ←",layer.url,data===void 0?"":data);let finishClose=()=>{if(destroySimulatedNavigationBarView(layer.titleBarView),layer.el.remove(),closingLayerCount=Math.max(closingLayerCount-1,0),syncLayerInteractivity(),syncActiveSystemBars(),!!resumeOpener)if(layer.openerWin===window)links.getBridgeProtocol().handleResume({data,storageId:layer.storageId,callbackId:layer.callbackId,final,gotoEvent,silent});else try{layer.openerWin.postMessage({source:SRC,type:"resume",data,storageId:layer.storageId,callbackId:layer.callbackId,final,gotoEvent,silent},"*")}catch{}};immediate?finishClose():animateOut(layer,finishClose)}function closeToDepth(depth,data,final){for(;layers.length>depth;){let revealsTarget=layers.length===depth+1;closeLayer(layers[layers.length-1],revealsTarget?data:void 0,final,!1,revealsTarget)}}function closeAllLayers(data,gotoEvent=!1,silent=!1,immediate=!1){let depth=layers.length;for(;layers.length>0;){let isRootmostLayer=layers.length===1;closeLayer(layers[layers.length-1],isRootmostLayer?data:void 0,!0,isRootmostLayer&&gotoEvent,isRootmostLayer,silent,immediate)}if(depth>0)try{history.go(-depth)}catch{}return depth>0}function openFromSplitRoot(url2,callbackId,overlay,openerWin,popId){if(pendingSplitRootOpen){pendingSplitRootOpen={url:url2,callbackId,overlay,openerWin,popId};return}if(layers.length===0){openLayer(url2,callbackId,overlay,openerWin,!0,popId);return}pendingSplitRootOpen={url:url2,callbackId,overlay,openerWin,popId},closeAllLayers(void 0,!1,!0,!0)}function finishPendingSplitRootOpen(){let pending=pendingSplitRootOpen;pending&&(pendingSplitRootOpen=null,openLayer(pending.url,pending.callbackId,pending.overlay,pending.openerWin,!0,pending.popId,!1))}function requestOverlayClose(layer){if(!(layer.closing||layers[layers.length-1]!==layer)){if(!config2.overlay?.silentTapClose){for(let selector of config2.overlay?.tapCloseSelectors??[])try{let control=layer.frame.contentDocument?.querySelector(selector);if(typeof control?.click!="function")continue;control.click();return}catch{}requestCloseOnTop(void 0);return}pendingClose||pendingHistoryDepth||(closeLayer(layer,void 0,!0,!1,!0,!0),syncHistoryAfterDirectClose())}}function forwardToDepth(depth){for(;layers.length<depth&&forwardStack.length>0;){let entry=forwardStack.pop();openLayer(entry.url,entry.callbackId,entry.overlay,entry.openerWin,!1,entry.popId)}}function requestCloseOnTop(data){if(layers.length===0){history.back();return}if(rootContainerActive){closeLayer(layers[layers.length-1],data,!0),syncHistoryAfterDirectClose();return}armPendingClose(data,8)}function isActiveBusinessWindow(target){let topLayer=layers[layers.length-1];return topLayer?topLayer.frame.contentWindow===target:rootFrame?rootFrame.contentWindow===target:target===window}function finishNativeBack(requestId,target,handled){pendingNativeBack?.requestId!==requestId||pendingNativeBack.target!==target||(clearPendingNativeBack(),!handled&&isActiveBusinessWindow(target)&&requestCloseOnTop(void 0))}function requestNativeBack(){if(!isTop||pendingNativeBack)return;let target=layers[layers.length-1]?.frame.contentWindow??rootFrame?.contentWindow??window;if(!target||target===window){links.getBridgeProtocol().handleNativeBack()||requestCloseOnTop(void 0);return}let requestId=++nativeBackRequestSeq,timer=setTimeout(()=>finishNativeBack(requestId,target,!1),120);pendingNativeBack={requestId,target,timer};try{target.postMessage({source:SRC,type:"nativeBack",requestId},"*")}catch{finishNativeBack(requestId,target,!1)}}function layerForWindow(source){if(source)for(let layer of layers){if(layer.win===source)return layer;let currentWindow=layer.frame.contentWindow;if(currentWindow&&currentWindow===source)return layer.win=currentWindow,layer}}if(isTop){if(!rootContainerActive){let rawPushState=history.pushState.bind(history),rawReplaceState=history.replaceState.bind(history),withDepth=state=>state==null?{__mearl_layer__:layers.length}:typeof state=="object"&&!Array.isArray(state)?{...state,__mearl_layer__:layers.length}:state;try{history.pushState=function(...args){rawPushState(withDepth(args[0]),args[1],args[2])},history.replaceState=function(...args){rawReplaceState(withDepth(args[0]),args[1],args[2])}}catch{}}try{readDepth(history.state)===null&&history.replaceState({__mearl_layer__:0},"")}catch{}window.addEventListener("popstate",e=>{let depth=readDepth(e.state);if(pendingSplitRootOpen&&depth===0){finishPendingSplitRootOpen();return}if(pendingHistoryDepth){let expectedDepth=pendingHistoryDepth.depth;if(clearPendingHistoryDepth(),depth===expectedDepth)return;console.warn(TAG,"浏览器历史深度与 WebView 出栈事务不一致",{expectedDepth,actualDepth:depth})}if(rootContainerActive){if(depth===null)return;depth<layers.length?closeToDepth(depth,void 0,!1):depth>layers.length&&forwardToDepth(depth);return}if(pendingClose){if(depth!==null&&depth<layers.length){let{data}=pendingClose;clearPendingClose(),closeToDepth(depth,data,!0)}else if(pendingClose.retries>0)armPendingClose(pendingClose.data,pendingClose.retries-1);else{let{data}=pendingClose;clearPendingClose(),closeToDepth(layers.length-1,data,!0)}return}depth!==null&&(depth<layers.length?closeToDepth(depth,void 0,!1):depth>layers.length&&forwardToDepth(depth))})}function broadcastAppMessage(message){links.getBridgeProtocol().handleAppMessage(message);let targets=[rootFrame?.contentWindow??null,...layers.filter(layer=>!layer.closing).map(layer=>layer.frame.contentWindow)];for(let target of targets)if(!(!target||target===window))try{target.postMessage({source:SRC,type:"appMessage",message},"*")}catch{}}function closeMegaPop(popId,data){let index=layers.findIndex(layer=>layer.popId===popId&&!layer.closing);if(index<0)return!1;let closingDepth=layers.length-index;closeToDepth(index,data,!0);try{history.go(-closingDepth)}catch{}return!0}function resizeMegaPop(popId,params){let layer=layers.find(candidate=>candidate.popId===popId&&!candidate.closing);if(!layer?.overlay)return!1;if(params.maxHeight!==void 0){let maxHeight=numberParam(params.maxHeight,1-layer.overlay.topRatio,0,1);layer.overlay.topRatio=1-maxHeight,layer.animEl.style.height=`${maxHeight*100}%`}if(params.maxWidth!==void 0){let maxWidth=numberParam(params.maxWidth,1,0,1);layer.overlay.widthRatio=maxWidth,layer.animEl.style.width=`${maxWidth*100}%`,layer.animEl.style.left=`${(1-maxWidth)/2*100}%`,layer.animEl.style.right="auto"}return params.animated===!0&&(layer.animEl.style.transition="height 200ms ease, width 200ms ease, left 200ms ease"),!0}function executeContainerData(action,params){if(action==="sharedFileRead"||action==="sharedFileWrite"){let fileName=typeof params.fileName=="string"?params.fileName:"";if(!fileName)return{success:!1,value:"missing fileName"};if(action==="sharedFileRead")return{success:!0,value:{data:sharedFiles.get(fileName)??""}};let data=typeof params.data=="string"?params.data:String(params.data??"");return sharedFiles.set(fileName,data),{success:!0,value:{}}}if(action==="sharedDataGet"){let keys=Array.isArray(params.keys)?params.keys.filter(key=>typeof key=="string"):[],data={};for(let key of keys)sharedData.has(key)&&(data[key]=sharedData.get(key));return{success:!0,value:{data}}}if(action==="sharedDataSet"){if(!params.data||typeof params.data!="object"||Array.isArray(params.data))return{success:!1,value:"missing shared data"};for(let[key,value]of Object.entries(params.data))value==null?sharedData.delete(key):sharedData.set(key,value);return{success:!0,value:{}}}if(action==="megaBroadcast")return!params.message||typeof params.message!="object"||Array.isArray(params.message)?{success:!1,value:"missing broadcast message"}:(broadcastAppMessage(params.message),{success:!0,value:{}});if(action==="megaKVSnapshot")return{success:!0,value:{entries:megaKVSnapshot()}};if(action==="megaKVMutation"){let operation=typeof params.operation=="string"?params.operation:"",bizId=typeof params.bizId=="string"?params.bizId:"";if(!bizId)return{success:!1,value:"missing bizID"};let key=typeof params.key=="string"?params.key:"";if((operation==="set"||operation==="remove")&&!key)return{success:!1,value:"missing key"};if(operation==="set"){if(typeof params.value!="string")return{success:!1,value:"missing value"};let entries=megaKVStorage.get(bizId)??new Map;entries.set(key,params.value),megaKVStorage.set(bizId,entries)}else if(operation==="remove"){let entries=megaKVStorage.get(bizId);entries?.delete(key),entries?.size===0&&megaKVStorage.delete(bizId)}else if(operation==="clear")megaKVStorage.delete(bizId);else return{success:!1,value:"unsupported KVStorage operation"};return persistMegaKVStorage(),broadcastAppMessage({kind:"megaKVStorage",operation,bizId,key,value:params.value}),{success:!0,value:{}}}if(action==="legacyBroadcastCreate"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?(legacyBroadcastChannels.add(instanceId),{success:!0,value:{}}):{success:!1,value:"missing instanceId"}}if(action==="legacyBroadcastPost"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?legacyBroadcastChannels.has(instanceId)?(broadcastAppMessage({kind:"legacyBroadcast",instanceId,message:params.message}),{success:!0,value:{}}):{success:!1,value:"broadcast channel not found"}:{success:!1,value:"missing instanceId"}}if(action==="legacyBroadcastClose"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?(legacyBroadcastChannels.delete(instanceId),{success:!0,value:{}}):{success:!1,value:"missing instanceId"}}if(action==="megaPopClose"){let popId=typeof params.popId=="string"?params.popId:"";return popId?closeMegaPop(popId,params.result)?{success:!0,value:{}}:{success:!1,value:"popId not found"}:{success:!1,value:"missing popId"}}if(action==="megaPopResize"){let popId=typeof params.popId=="string"?params.popId:"";return popId?resizeMegaPop(popId,params)?{success:!0,value:{}}:{success:!1,value:"popId not found"}:{success:!1,value:"missing popId"}}return{success:!1,value:"unsupported container data action"}}function requestContainerData(action,params,onSuccess,onFailure){if(isTop){let result=executeContainerData(action,params);setTimeout(()=>result.success?onSuccess(result.value):onFailure(result.value),0);return}let requestId=++containerDataRequestSeq;containerDataCallbacks.set(requestId,{success:onSuccess,failure:onFailure});try{window.top?.postMessage({source:SRC,type:"containerDataRequest",requestId,action,params},"*")}catch(error48){containerDataCallbacks.delete(requestId),onFailure(error48 instanceof Error?error48.message:String(error48))}}function requestOpen(url2,callbackId,webdialog,params){let overlay=resolveOverlayPresentation(url2,params,webdialog),popBeforeOpen=requestsPopBeforeOpen(url2,params),popId=typeof params?.__mearlMegaPopId=="string"?params.__mearlMegaPopId:null;isTop?openLayer(url2,callbackId,overlay,window,!0,popId):window.top?.postMessage({source:SRC,type:"open",url:url2,callbackId,overlay,popBeforeOpen,popId},"*")}function requestClose(data){let payload;try{payload=data===void 0?void 0:JSON.parse(JSON.stringify(data))}catch{payload=void 0}isTop?requestCloseOnTop(payload):window.top?.postMessage({source:SRC,type:"close",data:payload},"*")}if(window.addEventListener("message",event=>{let msg=event.data;if(!(!msg||typeof msg!="object")){if(msg.source==="mearl-content"&&(msg.type==="APP_BRIDGE_SIMULATOR_VISIBILITY"||msg.type==="APP_BRIDGE_RUNTIME_RESPONSES")){if(!isTop||event.source!==window)return;if(msg.type==="APP_BRIDGE_SIMULATOR_VISIBILITY"&&typeof msg.hidden=="boolean"){simulatedPageHidden=msg.hidden,links.getBridgeProtocol().handlePageVisibility(msg.hidden);let lifecycleMessage={source:SRC,type:"simulatorVisibility",hidden:msg.hidden};rootFrame?.contentWindow?.postMessage(lifecycleMessage,"*");for(let layer of layers)layer.closing||layer.frame.contentWindow?.postMessage(lifecycleMessage,"*")}else if(msg.type==="APP_BRIDGE_RUNTIME_RESPONSES"&&msg.profile===config2.profile&&msg.responses&&typeof msg.responses=="object"&&!Array.isArray(msg.responses)){let responses=msg.responses;runtimeResponses={...runtimeResponses??{},...responses},links.getBridgeProtocol().applyRuntimeResponses(responses);let configMessage={source:SRC,type:"runtimeResponses",profile:config2.profile,responses};rootFrame?.contentWindow?.postMessage(configMessage,"*");for(let layer of layers)layer.closing||layer.frame.contentWindow?.postMessage(configMessage,"*")}return}if(msg.source===SRC){if(isTop){let sourceLayer=layerForWindow(event.source),sourceIsRoot=!!(rootFrame?.contentWindow&&rootFrame.contentWindow===event.source);if(!sourceLayer&&!sourceIsRoot)return;if(msg.type==="open"&&typeof msg.url=="string"){let rawOverlay=msg.overlay&&typeof msg.overlay=="object"?msg.overlay:void 0,overlay=rawOverlay?{topRatio:numberParam(rawOverlay.topRatio,.2,0,1),widthRatio:numberParam(rawOverlay.widthRatio,1,0,1),radius:numberParam(rawOverlay.radius,0,0,50),maskAlpha:numberParam(rawOverlay.maskAlpha,.3,0,1),tapClose:boolParam(rawOverlay.tapClose,!0)}:resolveOverlayPresentation(msg.url,void 0,!1),callbackId=typeof msg.callbackId=="number"?msg.callbackId:0,popId=typeof msg.popId=="string"&&msg.popId?msg.popId:null;splitScreenActive&&sourceIsRoot?openFromSplitRoot(msg.url,callbackId,overlay,event.source??window,popId):msg.popBeforeOpen===!0&&sourceLayer?replaceLayer(sourceLayer,msg.url,callbackId,overlay,popId):openLayer(msg.url,callbackId,overlay,event.source??window,!0,popId)}else if(msg.type==="close")requestCloseOnTop(msg.data);else if(msg.type==="closeAll"){let gotoEvent=msg.gotoEvent===!0;if(gotoEvent&&sourceIsRoot&&layers.length===0&&msg.data!==void 0)try{event.source.postMessage({source:SRC,type:"resume",data:msg.data,storageId:null,callbackId:0,final:!0,gotoEvent:!0},"*")}catch{}else closeAllLayers(msg.data,gotoEvent)}else if(msg.type==="appMessageToOpener"&&sourceLayer){let target=sourceLayer.openerWin;if(target===window)links.getBridgeProtocol().handleAppMessage(msg.message);else try{target.postMessage({source:SRC,type:"appMessage",message:msg.message},"*")}catch{}}else if(msg.type==="containerDataRequest"&&typeof msg.requestId=="number"&&typeof msg.action=="string"&&msg.params&&typeof msg.params=="object"&&!Array.isArray(msg.params)&&event.source){let result=executeContainerData(msg.action,msg.params);try{event.source.postMessage({source:SRC,type:"containerDataResponse",requestId:msg.requestId,success:result.success,value:result.value},"*")}catch{}}else if(msg.type==="nativeBackResult"&&typeof msg.requestId=="number"&&typeof msg.handled=="boolean"&&event.source)finishNativeBack(msg.requestId,event.source,msg.handled);else if(msg.type==="urlChanged"&&typeof msg.url=="string"){let topLayer=layers[layers.length-1];if(sourceIsRoot&&!topLayer){rootBusinessUrl=msg.url;let mapped=mapUrlForSync(msg.url);if(mapped)try{history.replaceState({__mearl_layer__:0},"",mapped)}catch{}}else if(topLayer&&!topLayer.closing&&sourceLayer===topLayer){topLayer.url=msg.url,topLayer.titleBarStateExplicit&&topLayer.titleBarState&&cacheExplicitTitleBarState(topLayer,topLayer.titleBarState);let mapped=mapUrlForSync(msg.url);if(mapped)try{history.replaceState({__mearl_layer__:layers.length},"",mapped)}catch{}}}else if(msg.type==="title"&&typeof msg.title=="string"){let topLayer=layers[layers.length-1];if(sourceIsRoot&&!topLayer)try{document.title=msg.title,syncSimulatedTitleBar()}catch{}else if(topLayer&&sourceLayer===topLayer){document.title=msg.title;let state=resolvedTitleBarState(topLayer);topLayer.titleBarState={...state,title:msg.title},syncLayerViewport(topLayer,topLayer.titleBarState)}}else if(msg.type==="titleBarState"){let state=parseReportedTitleBarState(msg.state);if(state&&sourceIsRoot)links.getSystemBars().setPresentedRootTitleBarState(state);else if(state&&sourceLayer){let explicit=msg.explicit===!0;sourceLayer.titleBarStateReady=!0,explicit?(sourceLayer.titleBarState=state,sourceLayer.titleBarStateExplicit=!0,cacheExplicitTitleBarState(sourceLayer,state)):sourceLayer.titleBarStateExplicit||(sourceLayer.titleBarState=state);let resolvedState=sourceLayer.titleBarState??state;syncLayerViewport(sourceLayer,resolvedState)}}}else if(msg.type==="requestTitleBarState"){if(event.source!==window.top)return;syncSimulatedTitleBar()}else if(msg.type==="simulatorVisibility"&&typeof msg.hidden=="boolean"){if(event.source!==window.top)return;links.getBridgeProtocol().handlePageVisibility(msg.hidden)}else if(msg.type==="appMessage"){if(event.source!==window.top)return;links.getBridgeProtocol().handleAppMessage(msg.message)}else if(msg.type==="nativeBack"&&typeof msg.requestId=="number"){if(event.source!==window.top)return;let handled=links.getBridgeProtocol().handleNativeBack();window.top?.postMessage({source:SRC,type:"nativeBackResult",requestId:msg.requestId,handled},"*")}else if(msg.type==="containerDataResponse"&&typeof msg.requestId=="number"){if(event.source!==window.top)return;let callback=containerDataCallbacks.get(msg.requestId);if(!callback)return;containerDataCallbacks.delete(msg.requestId),msg.success===!0?callback.success(msg.value):callback.failure(msg.value)}else if(msg.type==="runtimeResponses"&&msg.profile===config2.profile&&msg.responses&&typeof msg.responses=="object"&&!Array.isArray(msg.responses)){if(event.source!==window.top)return;links.getBridgeProtocol().applyRuntimeResponses(msg.responses)}else if(msg.type==="resume"){if(event.source!==window.top)return;links.getBridgeProtocol().handleResume({data:msg.data,storageId:msg.storageId??null,callbackId:typeof msg.callbackId=="number"?msg.callbackId:0,final:msg.final===!0,gotoEvent:msg.gotoEvent===!0,silent:msg.silent===!0})}else event.source!==window.top&&window.top?.postMessage(msg,"*");return}pageTransport.handleMessage(msg)}}),!isTop&&isContainerFrame){let reportUrl=()=>{try{window.top?.postMessage({source:SRC,type:"urlChanged",url:restoreLayerBusinessUrl(location.href)},"*")}catch{}};try{let origPushState=history.pushState.bind(history),origReplaceState=history.replaceState.bind(history);history.pushState=function(...args){origPushState(...args),reportUrl()},history.replaceState=function(...args){origReplaceState(...args),reportUrl()},window.addEventListener("popstate",reportUrl),window.addEventListener("hashchange",reportUrl)}catch{}}if(isContainerFrame){let requestProxyLocationOpen=url2=>{if(links.getBridgeProtocol().handleMaybeScheme(url2))return!0;try{let current=new URL(restoreLayerBusinessUrl(location.href)),target=new URL(url2,current);return!/^https?:$/.test(target.protocol)||target.origin===current.origin&&target.pathname===current.pathname&&target.search===current.search?!1:(requestOpen(target.href,0,!1),!0)}catch{return!1}};Object.defineProperty(window,"__PROXY_LOCATION__",{value:{get href(){return location.href},set href(url2){requestProxyLocationOpen(url2)||(location.href=mapLayerFrameUrl(url2))},replace(url2){links.getBridgeProtocol().handleMaybeScheme(url2)||location.replace(mapLayerFrameUrl(url2))},assign(url2){requestProxyLocationOpen(url2)||location.assign(mapLayerFrameUrl(url2))}},writable:!1,configurable:!0})}if(isContainerFrame){document.addEventListener("click",event=>{let el=event.target;for(;el&&el.tagName!=="A";)el=el.parentElement;if(!el)return;let href=el.getAttribute("href");if(href){if(links.getBridgeProtocol().handleMaybeScheme(href)){event.preventDefault(),event.stopPropagation();return}/^https?:/i.test(href)&&el.getAttribute("target")==="_blank"&&(event.preventDefault(),event.stopPropagation(),requestOpen(href,0,!1))}},!0);let origOpen=window.open;window.open=function(url2,target,features){let urlStr=typeof url2=="string"?url2:url2 instanceof URL?url2.href:"";return links.getBridgeProtocol().handleMaybeScheme(urlStr)?null:/^https?:/i.test(urlStr)?(requestOpen(urlStr,0,!1),null):origOpen?origOpen.call(window,url2,target,features):null};try{let proto=Location.prototype,origAssign=proto.assign,origReplace=proto.replace;origAssign&&(proto.assign=function(url2){if(links.getBridgeProtocol().handleMaybeScheme(url2))return;let upgraded=location.protocol==="https:"&&url2.startsWith("http:")?"https:"+url2.slice(5):url2;origAssign.call(this,upgraded)}),origReplace&&(proto.replace=function(url2){if(links.getBridgeProtocol().handleMaybeScheme(url2))return;let upgraded=location.protocol==="https:"&&url2.startsWith("http:")?"https:"+url2.slice(5):url2;origReplace.call(this,upgraded)})}catch{}}return log2("容器环境已就绪",isTop?"(top)":isRootFrame?"(root)":isLayerFrame?"(layer)":"(iframe,仅桥)"),{getRootFrame:()=>rootFrame,getLayers:()=>layers,getClosingLayerCount:()=>closingLayerCount,requestOpen,requestClose,requestNativeBack,requestContainerData,closeAllLayers}}var APP_PROFILE_RUNTIME_FACTORIES={environment:installAppProfileEnvironment,containerStack:installAppProfileContainerStack,bridgeProtocol:installAppProfileBridgeProtocol,pageTransport:installAppProfilePageTransport,systemBars:installAppProfileSystemBars};function buildAppProfileRuntimeCallSource(configExpression){return`(${installAppProfileRuntime.toString()})(${configExpression},{environment:${installAppProfileEnvironment.toString()},pageTransport:${installAppProfilePageTransport.toString()},containerStack:${installAppProfileContainerStack.toString()},systemBars:${installAppProfileSystemBars.toString()},bridgeProtocol:${installAppProfileBridgeProtocol.toString()}})`}function installAppProfileRuntime(config2,factories=APP_PROFILE_RUNTIME_FACTORIES){let environment=factories.environment(config2);if(!environment)return;let pageTransport=factories.pageTransport(config2,environment),containerStack=factories.containerStack(config2,environment,{pageTransport,getSystemBars:()=>systemBars,getBridgeProtocol:()=>bridgeProtocol}),systemBars=factories.systemBars(config2,environment,{getRootFrame:containerStack.getRootFrame,getLayers:containerStack.getLayers,getClosingLayerCount:containerStack.getClosingLayerCount,requestClose:containerStack.requestClose,requestNativeBack:containerStack.requestNativeBack}),bridgeProtocol=factories.bridgeProtocol(config2,environment,{pageTransport,systemBars,requestOpen:containerStack.requestOpen,requestClose:containerStack.requestClose,requestCloseAll:containerStack.closeAllLayers,requestContainerData:containerStack.requestContainerData})}import https from"node:https";import http3 from"node:http";function installDeviceChromeView(root,config2,options={}){let ownerDocument=root.ownerDocument,browser=ownerDocument.defaultView??window,NativeDate=browser.Date,nativeNow=NativeDate.now.bind(NativeDate),labels={screenshot:"Screenshot",copied:"Copied",downloaded:"Downloaded",captureFailed:"Capture failed",bottomAction:"App simulation settings",...options.labels},state={statusBarVisible:!0,statusBarBackground:"#ffffff",textColor:"#0f131a",bottomActionEnabled:!1,timeOffsetMs:null,...options.initialState},normalizedBarHeight=value=>Number.isFinite(value)?Math.min(200,Math.max(0,Math.round(value))):0,statusBarHeight=normalizedBarHeight(config2.statusBarHeight),bottomBarHeight=normalizedBarHeight(config2.bottomBarHeight),cutout=config2.platform==="ios"?config2.cutout:"none",cutoutMarkup=cutout==="none"?"":cutout==="dynamic-island"?`<button id="device-cutout" type="button" data-kind="${cutout}" data-state="idle"><svg id="cutout-camera" viewBox="0 0 20 20" aria-hidden="true"><path d="M6.5 5.5 7.7 3.8h4.6l1.2 1.7h2.2c1 0 1.8.8 1.8 1.8v7c0 1-.8 1.8-1.8 1.8H4.3c-1 0-1.8-.8-1.8-1.8v-7c0-1 .8-1.8 1.8-1.8z"/><circle cx="10" cy="10.5" r="3.2"/></svg><svg id="cutout-check" viewBox="0 0 20 20" aria-hidden="true"><path d="m4.5 10.5 3.2 3.2 7.8-7.8"/></svg></button>`:`<span id="device-cutout" data-kind="${cutout}" aria-hidden="true"></span>`;root.innerHTML=`<style>
178
+ </style><div id="surface" data-platform="${config2.platform.toLowerCase()}" data-cutout="${String(cutoutKind!=="none")}" data-cutout-kind="${cutoutKind}"><div id="status"><span id="time"></span>${cutoutMarkup}<span id="indicators" aria-hidden="true"><svg id="signal" viewBox="0 0 18 12"><rect x="0" y="8" width="3" height="4" rx="1"/><rect x="5" y="6" width="3" height="6" rx="1"/><rect x="10" y="3" width="3" height="9" rx="1"/><rect x="15" y="0" width="3" height="12" rx="1"/></svg><svg id="wifi" viewBox="1 3.8 22 17.2"><path d="M2 8.82a15 15 0 0 1 20 0"/><path d="M5 12.859a10 10 0 0 1 14 0"/><path d="M8.5 16.429a5 5 0 0 1 7 0"/><path d="M12 20h.01"/></svg><svg id="battery" viewBox="0 0 28 13"><rect id="battery-outline" x=".65" y=".65" width="23" height="11.7" rx="3.1"/><rect id="battery-level" x="2.35" y="2.35" width="19.6" height="8.3" rx="1.7"/><path id="battery-cap" d="M25 4.1c1.1.35 1.7 1.15 1.7 2.4s-.6 2.05-1.7 2.4z"/></svg></span></div></div>`;let surface=shadow.getElementById("surface"),time3=shadow.getElementById("time"),cutout=shadow.getElementById("device-cutout"),cutoutStatusPath=shadow.querySelector("#cutout-check path"),localizedScreenshotText=config2.language.toLowerCase().startsWith("zh")?{idle:"截图",copied:"已复制",downloaded:"已下载",failed:"截图失败"}:{idle:"Screenshot",copied:"Copied",downloaded:"Downloaded",failed:"Capture failed"},setCutoutState=state=>{cutout&&(cutout.dataset.state=state,cutout.setAttribute("aria-label",localizedScreenshotText[state]),cutout.title=localizedScreenshotText[state],cutoutStatusPath&&cutoutStatusPath.setAttribute("d",state==="failed"?"M5.5 5.5l9 9m0-9-9 9":"m4.5 10.5 3.2 3.2 7.8-7.8"))},screenshotPending=!1,screenshotBlob=data=>{let binary=atob(data),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return new Blob([bytes],{type:"image/png"})},downloadScreenshot=blob=>{let link=document.createElement("a"),objectUrl=URL.createObjectURL(blob);link.href=objectUrl,link.download=`mearl-screenshot-${new Date().toISOString().replace(/[:.]/g,"-")}.png`,link.style.display="none",document.body.appendChild(link),link.click(),link.remove(),window.setTimeout(()=>URL.revokeObjectURL(objectUrl),1e3)},captureScreenshot=async()=>{if(!cutout||screenshotPending||cutout.dataset.state!=="idle")return;screenshotPending=!0,cutout.setAttribute("aria-busy","true");let requestId=Date.now()*1e3+Math.floor(Math.random()*1e3),timeoutTimer=0,onResponse=null,image=new Promise((resolve2,reject)=>{let cleanup=()=>{timeoutTimer&&window.clearTimeout(timeoutTimer),onResponse&&window.removeEventListener("message",onResponse)};onResponse=event=>{if(event.source!==window)return;let message=event.data;if(!message||message.source!=="mearl-content"||message.type!=="APP_BRIDGE_SCREENSHOT_RESPONSE"||message.requestId!==requestId)return;cleanup();let result=message.result;result?.success===!0&&typeof result.data=="string"?resolve2({data:result.data}):reject(new Error(String(result?.error??"screenshot failed")))},window.addEventListener("message",onResponse),timeoutTimer=window.setTimeout(()=>{cleanup(),reject(new Error("screenshot timeout"))},35e3)}).then(result=>screenshotBlob(result.data)),clipboardWrite=null;if(navigator.clipboard?.write&&typeof ClipboardItem<"u")try{clipboardWrite=navigator.clipboard.write([new ClipboardItem({"image/png":image})]),clipboardWrite.catch(()=>{})}catch{clipboardWrite=null}window.postMessage({source:SRC,type:"screenshot",requestId},"*");try{let blob=await image;if(clipboardWrite)try{await clipboardWrite,setCutoutState("copied")}catch{downloadScreenshot(blob),setCutoutState("downloaded")}else downloadScreenshot(blob),setCutoutState("downloaded")}catch{setCutoutState("failed")}finally{screenshotPending=!1,cutout.setAttribute("aria-busy","false")}window.setTimeout(()=>{screenshotPending||setCutoutState("idle")},1600)};hasDynamicIsland&&cutout&&(setCutoutState("idle"),cutout.addEventListener("click",()=>void captureScreenshot()));let updateTime=()=>{let now=new Date;time3&&(time3.textContent=`${String(now.getHours()).padStart(2,"0")}:${String(now.getMinutes()).padStart(2,"0")}`)};return window.addEventListener("mearl:page-time-change",updateTime),updateTime(),{root,surface,timeTimer:window.setInterval(updateTime,3e4)}},install=()=>{let titleBar=config2.titleBar;if(!titleBar||!isContainerFrame||!simulateSystemBars)return;let observeState=()=>{new MutationObserver(syncSimulatedTitleBar).observe(document.head??document.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["content","value"]}),window.addEventListener("popstate",syncSimulatedTitleBar),window.addEventListener("hashchange",syncSimulatedTitleBar),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",syncSimulatedTitleBar,{once:!0});try{let pushState=history.pushState.bind(history),replaceState=history.replaceState.bind(history);history.pushState=function(...args){pushState(...args),syncSimulatedTitleBar()},history.replaceState=function(...args){replaceState(...args),syncSimulatedTitleBar()}}catch{}};if(!isTop){observeState(),syncSimulatedTitleBar();return}let mount=()=>{if(titleBarRoot||!document.body)return;let totalHeight=config2.statusBarHeight+titleBar.navigationBarHeight,navigationView=createNavigationBarView("root",host.requestNativeBack),statusView=externalDeviceChrome||config2.statusBarHeight<=0?null:createStatusBarView(),spacer=document.createElement("div");if(spacer.setAttribute("data-mearl-app-titlebar-spacer",""),spacer.style.cssText=`display:block;width:100%;height:${totalHeight}px;min-height:${totalHeight}px;flex:none;`,spacer.style.setProperty("--mearl-app-navigation-bar-height",`${titleBar.navigationBarHeight}px`),document.body.insertBefore(spacer,document.body.firstChild),document.body.appendChild(navigationView.root),statusView&&document.body.appendChild(statusView.root),!externalDeviceChrome&&safeAreaInsets.bottom>0){let bottomRoot=document.createElement("div");bottomRoot.setAttribute("data-mearl-app-system-bottom",config2.profile),bottomRoot.style.cssText=`position:fixed;left:0;right:0;bottom:0;height:${safeAreaInsets.bottom}px;z-index:2147483600;box-sizing:border-box;pointer-events:none;color:#111111;`;let bottomShadow=bottomRoot.attachShadow({mode:"open"});bottomShadow.innerHTML=`<style>:host{all:initial}#surface{appearance:none;border:0;padding:0;width:166px;max-width:100%;height:24px;position:absolute;left:50%;bottom:0;transform:translateX(-50%);display:block;box-sizing:border-box;pointer-events:auto;color:#111;background:transparent;cursor:pointer;-webkit-tap-highlight-color:transparent}#surface:focus-visible{outline:2px solid #2563eb;outline-offset:-2px}#indicator{position:absolute;left:50%;bottom:8px;transform:translateX(-50%);width:134px;height:5px;border-radius:999px;background:currentColor;opacity:.92;transition:transform 120ms ease,opacity 120ms ease}#surface:hover #indicator{opacity:1;transform:translateX(-50%) scaleX(1.05)}#surface[data-platform="android"] #indicator{bottom:6px;width:108px;height:4px;opacity:.82}</style><button id="surface" type="button" aria-label="打开桥模拟配置" title="桥模拟配置" data-platform="${config2.platform.toLowerCase()}"><span id="indicator" aria-hidden="true"></span></button>`,document.body.appendChild(bottomRoot),systemBottomRoot=bottomRoot,systemBottomSurface=bottomShadow.getElementById("surface"),systemBottomSurface?.addEventListener("click",()=>{window.postMessage({source:SRC,type:"showBridgeConfig",profile:config2.profile,actions:config2.actions},"*")})}rootTitleBarView=navigationView,systemStatusView=statusView,titleBarRoot=navigationView.root,titleBarSpacer=spacer,syncSimulatedTitleBar(),observeState()};document.body?mount():document.addEventListener("DOMContentLoaded",mount,{once:!0})},service={initialLayerTitleBarState,resolvedTitleBarState,parseReportedTitleBarState,setPresentedRootTitleBarState:state=>{presentedRootTitleBarState=state,syncSimulatedTitleBar()},markStateExplicit:()=>{titleBarStateExplicit=!0},applyNavigationBarState,applyStatusBarState,createNavigationBarView,destroyNavigationBarView:view=>view?.root.remove(),syncLayerViewport,syncActiveSystemBars,syncSimulatedTitleBar};return install(),service}function installAppProfilePageTransport(config2,environment){let{SRC,TAG,log:log2}=environment,appToast=null,appToastHideTimer=null,appToastRemoveTimer=null;function showAppToast(params){let p=params&&typeof params=="object"?params:{},messageValue=[p.message,p.msg,p.content,p.text].find(value=>typeof value=="string"&&value.trim().length>0);if(typeof messageValue!="string")return"missing message";let durationValue=Number(p.milliseconds??p.duration),duration3=Number.isFinite(durationValue)&&durationValue>0?durationValue:2e3,hideAfter=Math.min(6e4,Math.max(300,Math.round(duration3)));appToastHideTimer!==null&&window.clearTimeout(appToastHideTimer),appToastRemoveTimer!==null&&window.clearTimeout(appToastRemoveTimer);let toast=appToast?.isConnected===!0?appToast:document.createElement("div");return toast!==appToast&&(appToast=toast,toast.setAttribute("data-mearl-app-toast",""),toast.setAttribute("role","status"),toast.setAttribute("aria-live","polite"),Object.assign(toast.style,{position:"fixed",left:"50%",top:"50%",zIndex:"2147483647",maxWidth:"calc(100vw - 64px)",boxSizing:"border-box",padding:"14px 20px",borderRadius:"12px",background:"rgba(20, 20, 20, 0.88)",color:"#ffffff",fontFamily:'-apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif',fontSize:"16px",fontWeight:"400",lineHeight:"24px",textAlign:"center",whiteSpace:"pre-wrap",overflowWrap:"anywhere",pointerEvents:"none",opacity:"0",transform:"translate(-50%, -50%) scale(0.96)",transition:"opacity 180ms ease, transform 180ms ease"}),(document.body??document.documentElement).appendChild(toast)),toast.textContent=messageValue,toast.style.opacity="0",toast.style.transform="translate(-50%, -50%) scale(0.96)",toast.offsetWidth,toast.style.opacity="1",toast.style.transform="translate(-50%, -50%) scale(1)",appToastHideTimer=window.setTimeout(()=>{appToastHideTimer=null,toast.style.opacity="0",toast.style.transform="translate(-50%, -50%) scale(0.96)",appToastRemoveTimer=window.setTimeout(()=>{appToastRemoveTimer=null,appToast===toast&&(appToast=null),toast.remove()},180)},hideAfter),null}let bridgeRequestSeq=0,pendingMtop={},pendingMtopStreams={},pendingUserInfo={};function degradedUserInfo(fallback,reason){let result={...fallback};try{Object.defineProperties(result,{__mearlDegraded:{enumerable:!1,value:!0},__mearlDegradedReason:{enumerable:!1,value:reason}})}catch{}return console.warn(TAG,"userInfo 降级:",reason),result}function callMtop(params,succ,fail2){let id=++bridgeRequestSeq;pendingMtop[id]={succ,fail:fail2};let post=params.post,rawTimeout=params.timeout??params.timer,timeout=typeof rawTimeout=="number"?rawTimeout:typeof rawTimeout=="string"&&rawTimeout.trim()!==""?Number(rawTimeout):void 0,payload={...params,data:params.data!==void 0?params.data:params.param??{},method:params.method??(post===!0||post===1||post==="1"||post==="true"?"POST":"GET"),env:params.env??(/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"prod"),...Number.isFinite(timeout)&&{timeout}};window.postMessage({source:SRC,type:"mtop",requestId:id,payload},"*"),log2("mtop 代发 →",params.api)}function callMtopAsync(params){return new Promise((resolve2,reject)=>callMtop(params,resolve2,reject))}function callMtopStream(params,succ,fail2){let sessionId=typeof params.id=="string"?params.id:String(params.id??""),request=params.request&&typeof params.request=="object"?params.request:null;if(!sessionId||!request||typeof request.api!="string"){fail2?.("invalid mtop_stream params");return}let requestId=++bridgeRequestSeq;pendingMtopStreams[requestId]={sessionId},window.postMessage({source:SRC,type:"mtopStream",requestId,payload:{...request,timeout:params.timeout,method:params.method??request.method,env:/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"prod"}},"*"),succ?.({}),log2("mtop 流式代发 →",request.api)}function callUserInfo(fallback,succ){if(fallback.userId){succ?.(fallback);return}let requestId=++bridgeRequestSeq,timer=setTimeout(()=>{let pending=pendingUserInfo[requestId];pending&&(delete pendingUserInfo[requestId],pending.succ?.(degradedUserInfo(pending.fallback,"native relay timeout")))},1e3);pendingUserInfo[requestId]={fallback,succ,timer},window.postMessage({source:SRC,type:"userInfo",requestId},"*")}function emitMtopStreamEvent(sessionId,eventType,data){let detail=data&&typeof data=="object"?{...data,eventType}:{data,eventType};document.dispatchEvent(new CustomEvent(`mtop_stream${sessionId}`,{detail}))}function createUploadId(){try{if(typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`${Date.now()}-${Math.random().toString(36).slice(2)}`}function pickDirectUploadTarget(response){if(!response||typeof response!="object")return null;let data=response.data;if(data?.success===!1)return null;let result=data?.result,target=Array.isArray(result?.urls)?result.urls[0]:void 0;if(!target||typeof target!="object")return null;let item=target;if(typeof item.put!="string"||!item.put||typeof item.get!="string"||!item.get)return null;let rawHeaders=item.putHeaders&&typeof item.putHeaders=="object"?item.putHeaders:{},putHeaders=Object.fromEntries(Object.entries(rawHeaders).map(([key,value])=>[key,String(value)]));return{put:item.put,get:item.get,putHeaders}}async function uploadImage(file2){let uploader=config2.imagePicker;if(!uploader)throw new Error("图片上传能力未配置");let env=/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"prod",response=await callMtopAsync({api:uploader.api,v:uploader.version,method:"POST",env,timeout:6e4,data:{fcId:uploader.fcId,fcGroup:uploader.fcGroup,fcName:uploader.uploadUrlFunction,fcData:JSON.stringify({requestType:"url",mimes:[file2.type||"image/jpeg"],prefix:uploader.prefix,region:uploader.region,uploadNumber:1}),fcConfig:JSON.stringify({timeout:6e4,disasterRecover:!0})}}),target=pickDirectUploadTarget(response);if(!target)throw new Error("获取图片上传地址失败");let uploadUrl=`${target.put}${target.put.includes("?")?"&":"?"}getAvatar=1`,uploadResponse=await fetch(uploadUrl,{method:"PUT",headers:target.putHeaders,body:file2});if(uploadResponse.status!==200)throw new Error(`图片直传失败: HTTP ${uploadResponse.status}`);return target.get}function openImagePicker(callbackCommandFn){let input=document.createElement("input");input.type="file",input.accept="image/*",input.style.display="none";let settled=!1,finish=()=>{settled=!0,input.remove()};input.addEventListener("cancel",finish,{once:!0}),input.addEventListener("change",()=>{let file2=input.files?.[0];if(!file2){finish();return}if(!file2.type.startsWith("image/")){finish(),console.error(TAG,"仅支持选择图片文件");return}uploadImage(file2).then(pic=>{typeof callbackCommandFn=="function"&&callbackCommandFn({pic,uuid:createUploadId(),timeStamp:Date.now()}),log2("图片选择并上传完成:",pic)}).catch(error48=>console.error(TAG,"图片上传失败:",error48)).finally(finish)},{once:!0}),(document.body??document.documentElement).appendChild(input),input.click(),window.addEventListener("focus",()=>{setTimeout(()=>{!settled&&!input.files?.length&&finish()},1e3)},{once:!0})}function showPaymentDialog(api,params,succeed,failed){document.querySelector('[data-mearl-payment-dialog="true"]')?.remove();let overlay=document.createElement("div");overlay.setAttribute("data-mearl-payment-dialog","true"),Object.assign(overlay.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)"});let card=document.createElement("div");Object.assign(card.style,{background:"#fff",borderRadius:"12px",padding:"24px",width:"300px",textAlign:"center",fontFamily:"system-ui, sans-serif"});let title=document.createElement("div");Object.assign(title.style,{fontSize:"17px",fontWeight:"600",marginBottom:"8px"}),title.textContent="支付确认";let desc=document.createElement("div");Object.assign(desc.style,{fontSize:"14px",color:"#666",marginBottom:"20px"}),desc.textContent=`模拟 ${api} 支付,请选择操作`;let btnRow=document.createElement("div");Object.assign(btnRow.style,{display:"flex",gap:"12px"});let btnBase=(text,bg,color,action)=>{let btn=document.createElement("button");return btn.textContent=text,btn.setAttribute("data-mearl-action",action),Object.assign(btn.style,{flex:"1",padding:"10px 0",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:"500",cursor:"pointer",background:bg,color}),btn},confirmBtn=btnBase("完成支付","#1677ff","#fff","payment-confirm"),cancelBtn=btnBase("取消支付","#f5f5f5","#333","payment-cancel"),cleanup=()=>{overlay.remove()};confirmBtn.addEventListener("click",()=>{cleanup(),log2("用户完成支付",api),succeed(api==="wx.requestPayment"?{errMsg:"requestPayment:ok"}:{ResultStatus:"9000",resultStatus:"9000"})}),cancelBtn.addEventListener("click",()=>{cleanup(),log2("用户取消支付",api),failed(api==="wx.requestPayment"?{errMsg:"requestPayment:fail cancel"}:{ResultStatus:"6001",resultStatus:"6001"})}),btnRow.appendChild(cancelBtn),btnRow.appendChild(confirmBtn),card.appendChild(title),card.appendChild(desc),card.appendChild(btnRow),overlay.appendChild(card),(document.body??document.documentElement).appendChild(overlay)}function showMiniProgramActionDialog(action,params,confirmed,cancelled){document.querySelector('[data-mearl-mini-program-dialog="true"]')?.remove();let overlay=document.createElement("div");overlay.setAttribute("data-mearl-mini-program-dialog","true"),overlay.setAttribute("data-mearl-mini-program-action",action),Object.assign(overlay.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)"});let card=document.createElement("div");Object.assign(card.style,{background:"#fff",borderRadius:"12px",padding:"24px",width:"300px",textAlign:"center",fontFamily:"system-ui, sans-serif"});let title=document.createElement("div");Object.assign(title.style,{fontSize:"17px",fontWeight:"600",marginBottom:"8px"}),title.textContent=action==="navigateMiniProgram"?"打开其他小程序":"订阅消息";let desc=document.createElement("div");Object.assign(desc.style,{fontSize:"14px",color:"#666",marginBottom:"20px"});let targetTitle=params.title?.trim()||"其他";desc.textContent=action==="navigateMiniProgram"?`即将打开“${targetTitle}”小程序,是否继续?`:"模拟微信订阅消息授权,请选择操作";let btnRow=document.createElement("div");Object.assign(btnRow.style,{display:"flex",gap:"12px"});let createButton=(text,background,color,actionName)=>{let button=document.createElement("button");return button.textContent=text,button.setAttribute("data-mearl-action",actionName),Object.assign(button.style,{flex:"1",padding:"10px 0",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:"500",cursor:"pointer",background,color}),button},confirmButton=createButton(action==="navigateMiniProgram"?"确定":"允许","#1677ff","#fff","mini-program-confirm"),cancelButton=createButton("取消","#f5f5f5","#333","mini-program-cancel"),cleanup=()=>overlay.remove();confirmButton.addEventListener("click",()=>{cleanup();let result=action==="navigateMiniProgram"?{errMsg:"navigateToMiniProgram:ok"}:{result:"SUCCESS",data:{totalCount:1,acceptCount:1}};log2("用户确认小程序原生能力",action,params.appId??params.scene??""),confirmed(result)}),cancelButton.addEventListener("click",()=>{cleanup();let result=action==="navigateMiniProgram"?{errMsg:"navigateToMiniProgram:fail cancel"}:{result:"CLOSE_BY_USER"};log2("用户取消小程序原生能力",action),cancelled(result)}),btnRow.appendChild(cancelButton),btnRow.appendChild(confirmButton),card.appendChild(title),card.appendChild(desc),card.appendChild(btnRow),overlay.appendChild(card),(document.body??document.documentElement).appendChild(overlay)}function handleMessage(msg){if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_MTOP_RESPONSE"){let pending=pendingMtop[msg.requestId];if(!pending)return!0;delete pendingMtop[msg.requestId];let result=msg.result;return result?.success?pending.succ?.(result.response):pending.fail?.(result?.error??"mtop delegate failed"),!0}if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_USER_INFO_RESPONSE"){let requestId=msg.requestId,pending=pendingUserInfo[requestId];if(!pending)return!0;delete pendingUserInfo[requestId],clearTimeout(pending.timer);let result=msg.result,response=result?.success&&result.response&&typeof result.response=="object"?result.response:{};return pending.succ?.(result?.success?{...pending.fallback,...response}:degradedUserInfo(pending.fallback,typeof result?.error=="string"&&result.error?result.error:"native relay failed")),!0}if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_MTOP_STREAM_EVENT"){let requestId=msg.requestId,pending=pendingMtopStreams[requestId];if(!pending)return!0;let eventType=msg.eventType;return emitMtopStreamEvent(pending.sessionId,eventType,msg.data),(eventType==="onFinish"||eventType==="onError")&&delete pendingMtopStreams[requestId],!0}return!1}return{showAppToast,callMtop,callMtopStream,callUserInfo,openImagePicker,showPaymentDialog,showMiniProgramActionDialog,handleMessage}}function installAppProfileBridgeProtocol(config2,environment,host){let{w,SRC,TAG,isTop,log:log2}=environment,{pageTransport,systemBars,requestOpen,requestClose,requestCloseAll,requestContainerData}=host,{showAppToast,callMtop,callMtopStream,callUserInfo,openImagePicker,showPaymentDialog,showMiniProgramActionDialog}=pageTransport,{applyNavigationBarState,applyStatusBarState,syncSimulatedTitleBar}=systemBars,NOT_IMPLEMENTED_PAYLOAD=JSON.stringify({ret:["HY_FAILED"],msg:"not implemented"}),FPT_STORAGE_KEY=`__mearl_app_fpt__:${config2.profile}`,CALENDAR_STORAGE_KEY=`__mearl_app_calendar_events__:${config2.profile}`,unsupportedNativeInputNotified=!1,stopNetworkQualityMonitor=null,voiceRecognition=null,voiceRecognitionSession=0,voiceRecognitionTranscript="",voiceRecognitionInterimTranscript="",voiceRecognitionStopping=!1,voiceRecognitionRunning=!1,simulatedPageHidden=!1,simulatedVisibilityInstalled=!1,hasPendingMiniProgramBackData=!1,pendingMiniProgramBackData,notificationListeners=new Map,megaListenerSeq=0,megaBroadcastListeners=new Map,megaLifeCycleListeners=new Set,megaPageCloseListeners=new Set,megaSystemBackListener=null,megaKVMutationVersion=0,MEGA_KV_TOTAL_SIZE=5*1024*1024,MEGA_KV_STORAGE_KEY=`__mearl_mega_kv__:${config2.profile}`;function readMegaKVStorage(){let storage=new Map;try{let parsed=JSON.parse(localStorage.getItem(MEGA_KV_STORAGE_KEY)??"{}");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return storage;for(let[bizId,rawEntries]of Object.entries(parsed)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,value]of Object.entries(rawEntries))typeof value=="string"&&entries.set(key,value);storage.set(bizId,entries)}}catch{}return storage}let megaKVStorage=readMegaKVStorage();function megaKVSnapshot(){let snapshot={};for(let[bizId,values]of megaKVStorage)snapshot[bizId]=Object.fromEntries(values);return snapshot}function persistMegaKVStorage(){try{localStorage.setItem(MEGA_KV_STORAGE_KEY,JSON.stringify(megaKVSnapshot()))}catch{}}function replaceMegaKVStorage(value){if(!(!value||typeof value!="object"||Array.isArray(value))){megaKVStorage.clear();for(let[bizId,rawEntries]of Object.entries(value)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,entryValue]of Object.entries(rawEntries))typeof entryValue=="string"&&entries.set(key,entryValue);megaKVStorage.set(bizId,entries)}persistMegaKVStorage()}}function applyMegaKVMutation(payload){let operation=typeof payload.operation=="string"?payload.operation:"",bizId=typeof payload.bizId=="string"?payload.bizId:"",key=typeof payload.key=="string"?payload.key:"";if(bizId){if(operation==="set"&&key&&typeof payload.value=="string"){let entries=megaKVStorage.get(bizId)??new Map;entries.set(key,payload.value),megaKVStorage.set(bizId,entries)}else if(operation==="remove"&&key){let entries=megaKVStorage.get(bizId);entries?.delete(key),entries?.size===0&&megaKVStorage.delete(bizId)}else if(operation==="clear")megaKVStorage.delete(bizId);else return;megaKVMutationVersion+=1,persistMegaKVStorage()}}function emitMegaCallback(callback,value){callback&&setTimeout(()=>callback(value),0)}function megaBroadcastBizId(value){return typeof value=="string"&&value?value:"__MEGA_GLOBAL_MESSAGE__"}function dispatchMegaBroadcast(payload){let bizId=megaBroadcastBizId(payload.bizId),eventName=typeof payload.eventName=="string"?payload.eventName:"";if(eventName)for(let listener of Array.from(megaBroadcastListeners.values()))listener.bizId!==bizId||listener.eventName!==eventName||(listener.once&&megaBroadcastListeners.delete(listener.id),emitMegaCallback(listener.callback,{statusCode:1,type:"onEvent",data:{detail:payload.detail}}),listener.once&&emitMegaCallback(listener.callback,{statusCode:99,type:"finish"}))}let documentPrototype=typeof Document=="function"?Document.prototype:null,nativeHiddenDescriptor=documentPrototype?Object.getOwnPropertyDescriptor(documentPrototype,"hidden"):void 0,nativeVisibilityDescriptor=documentPrototype?Object.getOwnPropertyDescriptor(documentPrototype,"visibilityState"):void 0;function installSimulatedVisibilityState(){if(!simulatedVisibilityInstalled){simulatedVisibilityInstalled=!0;try{Object.defineProperty(document,"hidden",{configurable:!0,get:()=>simulatedPageHidden||!!(nativeHiddenDescriptor?.get?.call(document)??!1)}),Object.defineProperty(document,"visibilityState",{configurable:!0,get:()=>simulatedPageHidden?"hidden":nativeVisibilityDescriptor?.get?.call(document)??"visible"})}catch{}}}function dispatchPageTransitionEvent(type){try{let event=typeof PageTransitionEvent=="function"?new PageTransitionEvent(type,{persisted:!1}):new Event(type);window.dispatchEvent(event)}catch{}}function dispatchActiveEvents(){for(let name of config2.activeEvents)try{document.dispatchEvent(new Event(name))}catch{}}function handlePageVisibility(hidden){if(hidden===simulatedPageHidden)return;installSimulatedVisibilityState(),simulatedPageHidden=hidden;let lifeCycleType=hidden?"onPageDisappear":"onPageAppear";for(let callback of megaLifeCycleListeners)emitMegaCallback(callback,{statusCode:1,type:lifeCycleType,data:{pageId:location.href}});try{document.dispatchEvent(new Event("visibilitychange"))}catch{}if(hidden){try{window.dispatchEvent(new Event("blur"))}catch{}dispatchPageTransitionEvent("pagehide");return}dispatchPageTransitionEvent("pageshow");try{window.dispatchEvent(new Event("focus"))}catch{}dispatchActiveEvents()}function resolveWindowFunction(path19){let parts=path19.split(".").filter(Boolean),owner=w;for(let index=0;index<parts.length-1;index+=1){let next=owner[parts[index]];if(!next||typeof next!="object")return null;owner=next}let fn=owner[parts[parts.length-1]];return typeof fn=="function"?fn.bind(owner):null}function handleNativeBack(){let megaHandled=!1;for(let callback of megaPageCloseListeners)megaHandled=!0,emitMegaCallback(callback,{statusCode:1,type:"onClose",data:{}});if(megaSystemBackListener&&(megaHandled=!0,emitMegaCallback(megaSystemBackListener,{statusCode:1,type:"onSuccess",data:{}})),megaHandled)return!0;let nativeBack=config2.nativeBack;if(!nativeBack)return!1;if(nativeBack.handler){let handler=resolveWindowFunction(nativeBack.handler);if(!handler)return!1;try{return handler(),!0}catch{return!1}}let controlled=!1;if(nativeBack.controlFunction){let control=resolveWindowFunction(nativeBack.controlFunction);if(!control)return!1;try{controlled=control()===!0}catch{return!1}if(!controlled)return!1}if(!nativeBack.event)return controlled;try{let event=new Event(nativeBack.event,{cancelable:!0});return document.dispatchEvent(event),controlled||event.defaultPrevented}catch{return controlled}}function handleAppMessage(message){if(!message||typeof message!="object")return;let payload=message;if(payload.kind==="megaBroadcast"){dispatchMegaBroadcast(payload);return}if(payload.kind==="megaKVStorage"){applyMegaKVMutation(payload);return}if(payload.kind==="legacyBroadcast"&&typeof payload.instanceId=="string"){try{let event=new CustomEvent(`Broadcast.Message.${payload.instanceId}`,{detail:payload.message});Object.defineProperty(event,"param",{configurable:!0,value:payload.message}),document.dispatchEvent(event)}catch{}return}if(payload.kind==="notification"&&typeof payload.name=="string"){let listener=notificationListeners.get(payload.name);listener&&setTimeout(()=>listener(payload.data),0);return}if(!(payload.kind!=="message"||!config2.messageEvent))try{document.dispatchEvent(new CustomEvent(config2.messageEvent,{detail:{data:payload.data}}))}catch{}}function sendAppMessage(message){if(isTop){handleAppMessage(message);return}window.top?.postMessage({source:SRC,type:"appMessageToOpener",message},"*")}function applyRuntimeResponses(responses){let current=config2.actions.responses??{};for(let[api,response]of Object.entries(responses))!response||typeof response!="object"||Array.isArray(response)||(current[api]=response);config2.actions.responses=current}function parseFpt(value){let entries=[],normalized=value.trim();if(!normalized)return entries;let pattern=/([0-9A-Za-z._-]+)\(([0-9A-Za-z._-]+)\)/g,consumed="";for(let match of normalized.matchAll(pattern))consumed+=match[0],entries.push([match[1],match[2]]);return consumed===normalized?entries:[]}function setFptEntry(entries,key,value){entries.delete(key),entries.set(key,value)}function readInitialFptEntries(){let entries=new Map;try{for(let[key,value]of parseFpt(sessionStorage.getItem(FPT_STORAGE_KEY)??""))setFptEntry(entries,key,value)}catch{}try{let currentFpt=new URL(location.href).searchParams.get("fpt")??"";for(let[key,value]of parseFpt(currentFpt))setFptEntry(entries,key,value)}catch{}return entries}let fptEntries=readInitialFptEntries();function serializeFpt(entries){return Array.from(entries,([key,value])=>`${key}(${value})`).join("")}function persistFpt(){try{let value=serializeFpt(fptEntries);value?sessionStorage.setItem(FPT_STORAGE_KEY,value):sessionStorage.removeItem(FPT_STORAGE_KEY)}catch{}}function decorateUrlWithFpt(rawUrl){let targetUrl=mapScheme(rawUrl)??rawUrl;if(fptEntries.size===0)return targetUrl;try{let url2=new URL(targetUrl,location.href);if(url2.protocol!=="http:"&&url2.protocol!=="https:")return targetUrl;let merged=new Map(fptEntries);for(let[key,value]of parseFpt(url2.searchParams.get("fpt")??""))setFptEntry(merged,key,value);return url2.searchParams.set("fpt",serializeFpt(merged)),url2.href}catch{return targetUrl}}function classify(api){let a=config2.actions;return a.open.includes(api)?"open":a.close.includes(api)?"close":a.title.includes(api)?"title":a.navigationBar?.includes(api)?"navigationBar":a.statusBar?.includes(api)?"statusBar":a.systemInfo.includes(api)?"systemInfo":a.mtop.includes(api)?"mtop":a.kvGet?.includes(api)?"kvGet":a.kvSet?.includes(api)?"kvSet":a.kvDelete?.includes(api)?"kvDelete":a.pageContext?.includes(api)?"pageContext":a.responses&&Object.prototype.hasOwnProperty.call(a.responses,api)?"response":a.behaviors&&Object.prototype.hasOwnProperty.call(a.behaviors,api)?a.behaviors[api]:a.noop.includes(api)?"noop":"unknown"}function pickUrl(params){if(!params||typeof params!="object")return null;let p=params,candidates=[p.url,p.data?.url,p.param?.url,p.value?.params?.url];for(let c of candidates)if(typeof c=="string"&&c)return c;return null}function pickCloseData(params){if(params&&typeof params=="object"){let p=params;if("data"in p&&p.data!==void 0)return p.data;if(Object.keys(p).length>0)return p}}function decodeCookieValue2(raw){let value=raw;for(let i=0;i<2;i+=1)try{let decoded=decodeURIComponent(value);if(decoded===value)break;value=decoded}catch{break}return value.replace(/\\u([0-9a-f]{4})/gi,(_match,hex3)=>String.fromCharCode(Number.parseInt(hex3,16)))}function readCookie(name){let prefix=`${name}=`,pair=document.cookie.split(";").map(value=>value.trim()).find(value=>value.startsWith(prefix));return pair?decodeCookieValue2(pair.slice(prefix.length)):""}function readUserCookie(name){let pageUserCookie=w.userCookie;if(!pageUserCookie||typeof pageUserCookie!="object")return"";let value=pageUserCookie[name];return typeof value=="string"?decodeCookieValue2(value):""}function readFirstUserCookie(names){for(let name of names){let value=readCookie(name)||readUserCookie(name);if(value&&value!=="null")return value}return""}let cbSeq=0,callbacks={};function stashCallback(fn){if(typeof fn!="function")return 0;let id=++cbSeq;return callbacks[id]=fn,id}function extractQuery(url2,param){let q=url2.indexOf("?");if(q===-1)return null;for(let pair of url2.slice(q+1).split("&")){let eq=pair.indexOf("=");if(eq>0&&pair.slice(0,eq)===param)return pair.slice(eq+1)}return null}function matchesHostSuffix(hostname3,suffixes){if(!suffixes?.length)return!0;let normalizedHost=hostname3.toLowerCase().replace(/\.$/,"");return suffixes.some(value=>{let suffix=value.toLowerCase().replace(/^\./,"").replace(/\.$/,"");return normalizedHost===suffix||normalizedHost.endsWith(`.${suffix}`)})}function matchesRouteHost(rawUrl,suffixes){if(!suffixes?.length)return!0;try{let parsed=new URL(rawUrl,location.href),hostname3=parsed.protocol==="http:"||parsed.protocol==="https:"?parsed.hostname:location.hostname;return matchesHostSuffix(hostname3,suffixes)}catch{return matchesHostSuffix(location.hostname,suffixes)}}function resolveSchemeValue(raw,depth){if(depth>3)return null;let value=raw;try{value=decodeURIComponent(raw)}catch{}if(value.startsWith("{"))try{let found=pickUrl(JSON.parse(value));if(!found)return null;value=found}catch{return null}if(/^https?:/i.test(value))return value;if(/^[a-z][a-z0-9+.-]*:/i.test(value))return mapScheme(value,depth+1);let nestedUrl=extractQuery(value,"url");return nestedUrl?resolveSchemeValue(nestedUrl,depth+1):null}function mapScheme(url2,depth=0){if(depth>3)return null;let lower=url2.toLowerCase();for(let rule of config2.schemes){if(!matchesRouteHost(url2,rule.hostSuffixes))continue;let normalizedMatch=rule.match.toLowerCase(),matchedUrl=url2;if(!lower.startsWith(normalizedMatch)){if(!normalizedMatch.startsWith("/"))continue;try{let parsed=new URL(url2,location.href);if(matchedUrl=`${parsed.pathname}${parsed.search}${parsed.hash}`,!matchedUrl.toLowerCase().startsWith(normalizedMatch))continue}catch{continue}}if(rule.targetPath){let suffix=matchedUrl.slice(rule.match.length);if(suffix&&!suffix.startsWith("?")&&!suffix.startsWith("#"))continue;try{let source=new URL(matchedUrl),origin=location.origin;if(rule.targetHostPrefix){let hostname3=location.hostname.toLowerCase(),domainSuffix=hostname3==="wapa.taobao.com"||hostname3.endsWith(".wapa.taobao.com")?"wapa.taobao.com":hostname3==="m.taobao.com"||hostname3.endsWith(".m.taobao.com")?"m.taobao.com":"";domainSuffix&&(origin=`https://${rule.targetHostPrefix}.${domainSuffix}`)}let target=new URL(rule.targetPath,`${origin}/`);target.search=source.search,target.hash=source.hash;for(let[key,value]of Object.entries(rule.targetParams??{}))target.searchParams.has(key)||target.searchParams.set(key,value);return target.href}catch{return null}}if(!rule.param)continue;let raw=extractQuery(matchedUrl,rule.param);if(!raw)return null;let resolved=resolveSchemeValue(raw,depth);if(!resolved||!rule.useCurrentOrigin)return resolved;try{let target=new URL(resolved);return`${location.origin}${target.pathname}${target.search}${target.hash}`}catch{return resolved}}return null}function firstRouteParam(params,names){for(let name of names){let value=params.get(name);if(value)return value}return""}function resolvePaymentCallbackUrl(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam){if(!rawUrl)return null;try{let target=new URL(rawUrl,location.href);for(let name of forwardParams){let value=paymentPageUrl.searchParams.get(name);value&&!target.searchParams.get(name)&&target.searchParams.set(name,value)}resultParam&&target.searchParams.set(resultParam.name,JSON.stringify(resultParam.value));let resolved=useCurrentOrigin&&(target.protocol==="http:"||target.protocol==="https:")?`${location.origin}${target.pathname}${target.search}${target.hash}`:target.href;return decorateUrlWithFpt(resolved)}catch{return null}}function openPaymentCallback(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam){let target=resolvePaymentCallbackUrl(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam);target&&requestOpen(target,0,!1)}function handleMiniProgramPaymentRoute(rawUrl){let paymentPageUrl;try{paymentPageUrl=new URL(rawUrl,location.href)}catch{return!1}let normalizedPathname=paymentPageUrl.pathname.replace(/\/+$/,"")||"/",rule=config2.miniProgram?.paymentRoutes?.find(candidate=>(candidate.pathname.replace(/\/+$/,"")||"/")===normalizedPathname&&matchesHostSuffix(paymentPageUrl.hostname,candidate.hostSuffixes));if(!rule)return!1;let successUrl=firstRouteParam(paymentPageUrl.searchParams,rule.successUrlParams),failureUrl=firstRouteParam(paymentPageUrl.searchParams,rule.failureUrlParams),forwardParams=rule.forwardParams??[],useCurrentOrigin=rule.useCurrentOrigin===!0,paymentParams;try{let parsed=JSON.parse(paymentPageUrl.searchParams.get(rule.paymentParamsParam)??"");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error;paymentParams=parsed,paymentParams.timeStamp!==void 0&&(paymentParams.timeStamp=String(paymentParams.timeStamp))}catch{return log2("微信支付参数解析失败,执行失败回跳",rawUrl),openPaymentCallback(failureUrl,paymentPageUrl,useCurrentOrigin,forwardParams),!0}return showPaymentDialog("wx.requestPayment",paymentParams,result=>{openPaymentCallback(successUrl,paymentPageUrl,useCurrentOrigin,forwardParams,rule.successResultParam?{name:rule.successResultParam,value:result}:void 0)},()=>{openPaymentCallback(failureUrl,paymentPageUrl,useCurrentOrigin,forwardParams)}),!0}function finishMiniProgramNativeRoute(action,result,storageId){handleResume({data:action==="subscribeMessage"?result:void 0,storageId,callbackId:0,final:!0})}function handleMiniProgramNativeRoute(rawUrl){let nativePageUrl;try{nativePageUrl=new URL(rawUrl,location.href)}catch{return!1}let normalizedPathname=nativePageUrl.pathname.replace(/\/+$/,"")||"/",action=nativePageUrl.searchParams.get("action");if(action!=="navigateMiniProgram"&&action!=="subscribeMessage"||!config2.miniProgram?.nativeRoutes?.find(candidate=>(candidate.pathname.replace(/\/+$/,"")||"/")===normalizedPathname&&candidate.actions.includes(action)&&matchesHostSuffix(nativePageUrl.hostname,candidate.hostSuffixes)))return!1;let params={};nativePageUrl.searchParams.forEach((value,name)=>{params[name]=value});let storageId=nativePageUrl.searchParams.get("__storage_id");return handlePageVisibility(!0),showMiniProgramActionDialog(action,params,result=>finishMiniProgramNativeRoute(action,result,storageId),result=>finishMiniProgramNativeRoute(action,result,storageId)),!0}function handleMiniProgramPostMessage(data){let rules=config2.miniProgram?.messageRules;if(!rules?.length)return!1;let messages=Array.isArray(data)?data:[data],handled=!1;for(let value of messages){if(!value||typeof value!="object"||Array.isArray(value))continue;let message=value;if(typeof message.type!="string")continue;let rule=rules.find(candidate=>candidate.type===message.type&&matchesHostSuffix(location.hostname,candidate.hostSuffixes));rule&&(handled=!0,rule.action==="stageBackData"?(pendingMiniProgramBackData=message.data,hasPendingMiniProgramBackData=!0):rule.action==="closeAll"&&(isTop?requestCloseAll(message.data)||requestClose(message.data):window.top?.postMessage({source:SRC,type:"closeAll",data:message.data},"*")))}return handled}function matchesImagePickerScheme(url2){let lower=url2.toLowerCase();return config2.imagePicker?.schemes.some(scheme=>lower.startsWith(scheme))===!0}function handleMaybeScheme(url2){if(typeof url2!="string"||!url2||!/^[a-z][a-z0-9+.-]*:/i.test(url2)||/^(https?|about|blob|data|javascript):/i.test(url2))return!1;let mapped=mapScheme(url2);return mapped?(log2("scheme 映射为 H5 open:",url2,"→",mapped),requestOpen(decorateUrlWithFpt(mapped),0,!1)):log2("外部 scheme 已拦截(真机表现为唤端):",url2),!0}function handleResume(msg){let{data,storageId,callbackId,final,gotoEvent,silent}=msg;if(gotoEvent&&dispatchGotoEvent(data),callbackId&&callbacks[callbackId]){if(!silent)try{callbacks[callbackId]({backdata:data})}catch(e){console.error(TAG,"callbackCommand 执行失败",e)}final&&delete callbacks[callbackId]}if(data&&typeof data=="object"&&storageId)try{let d={...data};d.__$data=!0,d.__$storageId=String(storageId),localStorage.setItem("XPI_BACK_LISTENER_DATA_STORAGE",JSON.stringify(d))}catch{}simulatedPageHidden?handlePageVisibility(!1):dispatchActiveEvents()}function dispatchGotoEvent(data){if(data!==void 0)try{document.dispatchEvent(new CustomEvent("WV.GotoEvent",{detail:{data}}))}catch{}}function sendUserTrack(params){if(!params||typeof params!="object")return;let p=params,logkey=typeof p.logkey=="string"?p.logkey:"",gmkey=typeof p.gmkey=="string"?p.gmkey:typeof p.event=="string"?p.event:"",gokey=typeof p.gokey=="string"?p.gokey:"";if(!/^\/[0-9A-Za-z._/-]+$/.test(logkey)||!/^[0-9A-Za-z_-]+$/.test(gmkey))return;let pageWindow=w,aplus=pageWindow.goldlog??pageWindow.aplus;if(typeof aplus?.send!="function")return;let configuredHost=aplus.getMetaInfo?.("aplus-rhost-g"),host2=(typeof configuredHost=="string"?configuredHost:"gm.mmstat.com").replace(/^https?:\/\//i,"").replace(/^\/\//,"").split("/")[0];if(!(!host2||!/^[0-9A-Za-z.-]+$/.test(host2)))try{aplus.send(`//${host2}${logkey}`,`gmkey=${encodeURIComponent(gmkey)}&gokey=${gokey}&ts=${Date.now()}`,"GET")}catch{}}function readNetworkState(){let connection=navigator.connection;return navigator.onLine?connection?.type==="wifi"?"wifi":connection?.effectiveType??"unknown":"fail"}function networkTypeNumber(state){return{wifi:2,"slow-2g":3,"2g":3,"3g":4,"4g":5,"5g":6,fail:7}[state]??0}function emitVoiceRecognitionEvent(name,detail){try{document.dispatchEvent(new CustomEvent(name,{detail}))}catch{}}function browserSpeechRecognitionConstructor(){let candidate=w.SpeechRecognition??w.webkitSpeechRecognition;return typeof candidate=="function"?candidate:null}function voiceRecognitionLanguage(){let language=config2.language||navigator.language||"zh-CN";return/^zh-hans$/i.test(language)?"zh-CN":/^zh-hant$/i.test(language)?"zh-TW":language}function localVoiceRecognitionLanguage(language){return/^zh-(cn|hans)$/i.test(language)?"cmn-Hans-CN":/^zh-(tw|hant)$/i.test(language)?"cmn-Hant-TW":language}function detachVoiceRecognition(recognition){recognition.onstart=null,recognition.onresult=null,recognition.onerror=null,recognition.onend=null,recognition.onspeechstart=null,recognition.onspeechend=null}function finishVoiceRecognition(recognition,status){if(voiceRecognition!==recognition)return;let content=voiceRecognitionInterimTranscript.trim()||voiceRecognitionTranscript.trim();voiceRecognition=null,voiceRecognitionSession+=1,voiceRecognitionRunning=!1,voiceRecognitionStopping=!1,voiceRecognitionInterimTranscript="",detachVoiceRecognition(recognition),emitVoiceRecognitionEvent("WV.Voicetone",{tone:0}),emitVoiceRecognitionEvent("WV.VoiceRecog",{content,finished:!0,status})}function cancelVoiceRecognition(notifyPage){let recognition=voiceRecognition;if(recognition){voiceRecognition=null,voiceRecognitionSession+=1,voiceRecognitionRunning=!1,voiceRecognitionStopping=!1,voiceRecognitionInterimTranscript="",detachVoiceRecognition(recognition);try{recognition.abort()}catch{}emitVoiceRecognitionEvent("WV.Voicetone",{tone:0}),notifyPage&&emitVoiceRecognitionEvent("WV.VoiceRecogFailed",{status:2})}}function startVoiceRecognition(succeed,failed){cancelVoiceRecognition(!1);let SpeechRecognition=browserSpeechRecognitionConstructor();if(!SpeechRecognition){let error48={error_code:-1,error_message:"speech recognition unavailable"};emitVoiceRecognitionEvent("WV.VoiceRecogFailed",{status:-1,...error48}),failed(error48);return}let recognition=new SpeechRecognition,session=++voiceRecognitionSession;voiceRecognition=recognition,voiceRecognitionTranscript="",voiceRecognitionInterimTranscript="",voiceRecognitionStopping=!1,voiceRecognitionRunning=!1,recognition.continuous=!0,recognition.interimResults=!0,recognition.maxAlternatives=1,recognition.lang=voiceRecognitionLanguage();let isCurrent=()=>voiceRecognition===recognition&&voiceRecognitionSession===session,recognitionFailed=!1,failRecognition=(message,code)=>{if(!isCurrent()||recognitionFailed)return;recognitionFailed=!0;let error48={error_code:-1,error_message:message,error:code};voiceRecognition=null,voiceRecognitionSession+=1,voiceRecognitionRunning=!1,voiceRecognitionStopping=!1,detachVoiceRecognition(recognition);try{recognition.abort()}catch{}emitVoiceRecognitionEvent("WV.Voicetone",{tone:0}),emitVoiceRecognitionEvent("WV.VoiceRecogFailed",{status:-1,...error48}),failed(error48)},beginRecognition=()=>{if(isCurrent())try{recognition.start(),voiceRecognitionRunning=!0,succeed({})}catch(error48){failRecognition(error48 instanceof Error?error48.message:"speech recognition start failed","start-failed")}};recognition.onstart=()=>{isCurrent()&&(voiceRecognitionRunning=!0)},recognition.onspeechstart=()=>{isCurrent()&&emitVoiceRecognitionEvent("WV.Voicetone",{tone:10})},recognition.onspeechend=()=>{isCurrent()&&emitVoiceRecognitionEvent("WV.Voicetone",{tone:0})},recognition.onresult=event=>{if(!isCurrent()||!event.results)return;let interimTranscript="",startIndex=Math.max(0,event.resultIndex??0);for(let index=startIndex;index<event.results.length;index+=1){let result=event.results[index],transcript=result?.[0]?.transcript??"";result?.isFinal?voiceRecognitionTranscript+=transcript:interimTranscript+=transcript}let content=`${voiceRecognitionTranscript}${interimTranscript}`.trim();voiceRecognitionInterimTranscript=content,content&&emitVoiceRecognitionEvent("WV.VoiceRecogPartial",{content})},recognition.onerror=event=>{if(!isCurrent())return;let code=event.error??"unknown";code!=="no-speech"&&(code==="aborted"&&voiceRecognitionStopping||failRecognition(event.message||`speech recognition failed: ${code}`,code))},recognition.onend=()=>{if(isCurrent()){if(voiceRecognitionRunning=!1,voiceRecognitionStopping){finishVoiceRecognition(recognition,1);return}setTimeout(()=>{if(!(!isCurrent()||voiceRecognitionStopping))try{recognition.start(),voiceRecognitionRunning=!0}catch(error48){failRecognition(error48 instanceof Error?error48.message:"speech recognition restart failed","restart-failed")}},0)}};let localLanguage=localVoiceRecognitionLanguage(recognition.lang);if(typeof recognition.processLocally=="boolean"&&typeof SpeechRecognition.available=="function"){SpeechRecognition.available({langs:[localLanguage],processLocally:!0}).then(availability=>{if(isCurrent()){if(availability==="available"){recognition.lang=localLanguage,recognition.processLocally=!0,beginRecognition();return}if((availability==="downloadable"||availability==="downloading")&&typeof SpeechRecognition.install=="function"){showAppToast({message:"正在准备语音识别,首次使用可能需要一些时间",milliseconds:3e3}),SpeechRecognition.install({langs:[localLanguage],processLocally:!0}).then(installed=>{if(!installed){isCurrent()&&beginRecognition();return}if(!isCurrent()){showAppToast({message:"语音识别已准备好,请再试一次",milliseconds:3e3});return}recognition.lang=localLanguage,recognition.processLocally=!0,beginRecognition()}).catch(()=>beginRecognition());return}beginRecognition()}}).catch(()=>beginRecognition());return}beginRecognition()}function calendarTimestamp(value){if(typeof value=="number"&&Number.isFinite(value))return value;if(typeof value!="string"||!value.trim())return null;let numeric=Number(value);if(Number.isFinite(numeric)&&numeric>0)return numeric;let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}function calendarEventFromParams(params){let p=params&&typeof params=="object"?params:{},stringValue=(...values)=>values.find(value=>typeof value=="string")??"";return{title:stringValue(p.calendar_title,p.title),startTime:calendarTimestamp(p.calendar_start_ms??p.start_time??p.calendar_start_datetime),endTime:calendarTimestamp(p.calendar_end_ms??p.end_time??p.calendar_end_datetime),url:stringValue(p.calendar_url,p.url),note:stringValue(p.calendar_note,p.note),location:stringValue(p.calendar_location,p.location)}}function readCalendarEvents(){try{let parsed=JSON.parse(localStorage.getItem(CALENDAR_STORAGE_KEY)??"[]");return Array.isArray(parsed)?parsed.filter(event=>event!==null&&typeof event=="object"&&typeof event.title=="string"):[]}catch{return[]}}function writeCalendarEvents(events){try{return localStorage.setItem(CALENDAR_STORAGE_KEY,JSON.stringify(events)),!0}catch{return!1}}function sameCalendarEvent(stored,candidate){return candidate.url?stored.url===candidate.url:!!candidate.title&&stored.title===candidate.title&&(candidate.startTime===null||stored.startTime===candidate.startTime)&&(candidate.endTime===null||stored.endTime===candidate.endTime)}function calendarEventResponse(event){return{title:event.title,start_time:event.startTime,end_time:event.endTime,url:event.url,note:event.note,location:event.location}}function dispatch(api,params,onSuccess,onFailure,callbackCommandFn){let succeed=value=>{onSuccess&&setTimeout(()=>onSuccess(value),0)},failed=reason=>{onFailure&&setTimeout(()=>onFailure(reason),0)},kind=classify(api),silent=config2.actions.silent?.includes(api)===!0;if(silent||log2("桥调用",api,`(${kind})`,params??""),kind==="open"||kind==="navigate"){let p=params&&typeof params=="object"?params:{},navigationData=p.data&&typeof p.data=="object"?p.data:void 0;if(kind==="navigate"&&navigationData?.type==="back"){isTop?requestCloseAll(navigationData.data,!0)||dispatchGotoEvent(navigationData.data):window.top?.postMessage({source:SRC,type:"closeAll",data:navigationData.data,gotoEvent:!0},"*"),succeed({});return}let url2=pickUrl(params);if(!url2){failed("missing url");return}if(matchesImagePickerScheme(url2)){openImagePicker(callbackCommandFn),succeed({});return}if(handleMiniProgramPaymentRoute(url2)){succeed({});return}if(handleMiniProgramNativeRoute(url2)){succeed({});return}let wd=p.useWebdialog===!0||p.useWebdialog==="true"||p.useWebdialog===1||p.useWebdialog==="1";requestOpen(decorateUrlWithFpt(url2),stashCallback(callbackCommandFn),wd,p),succeed({});return}if(kind==="closeAll"){isTop?requestCloseAll(void 0):window.top?.postMessage({source:SRC,type:"closeAll"},"*"),succeed({});return}if(kind==="closeBackData"){let p=params&&typeof params=="object"?params:{};requestClose(Object.prototype.hasOwnProperty.call(p,"backdata")?p.backdata:pickCloseData(p)),succeed({});return}if(kind==="close"){if(api==="navigateBack"&&hasPendingMiniProgramBackData){let data=pendingMiniProgramBackData;pendingMiniProgramBackData=void 0,hasPendingMiniProgramBackData=!1,requestClose(data)}else requestClose(pickCloseData(params));succeed({});return}if(kind==="postMessage"){let p=params&&typeof params=="object"?params:{},data=p.data??p;handleMiniProgramPostMessage(data)||sendAppMessage({kind:"message",data}),succeed({});return}if(kind==="notifySubscribe"){let p=params&&typeof params=="object"?params:{};if(typeof p.name!="string"||!p.name){failed("missing notification name");return}onSuccess&&notificationListeners.set(p.name,onSuccess);return}if(kind==="notifyUnsubscribe"){let p=params&&typeof params=="object"?params:{};typeof p.name=="string"&&notificationListeners.delete(p.name),succeed({});return}if(kind==="notifyPost"){let p=params&&typeof params=="object"?params:{};if(typeof p.name!="string"||!p.name){failed("missing notification name");return}sendAppMessage({kind:"notification",name:p.name,data:p.data}),succeed({});return}if(kind==="sharedFileRead"||kind==="sharedFileWrite"||kind==="sharedDataGet"||kind==="sharedDataSet"){requestContainerData(kind,params&&typeof params=="object"?params:{},succeed,failed);return}if(kind==="legacyBroadcastCreate"||kind==="legacyBroadcastPost"||kind==="legacyBroadcastClose"){requestContainerData(kind,params&&typeof params=="object"?params:{},succeed,failed);return}if(kind==="title"){let title=params&&typeof params=="object"?params.title??params.name:void 0;if(typeof title=="string"&&title){systemBars.markStateExplicit();try{document.title=title,syncSimulatedTitleBar()}catch{}isTop||window.top?.postMessage({source:SRC,type:"title",title},"*")}succeed({});return}if(kind==="navigationBar"){applyNavigationBarState(api,params),succeed({});return}if(kind==="statusBar"){applyStatusBarState(params),succeed({});return}if(kind==="systemInfo"){let model=config2.globals.__DEVICE_MODEL__||"iPhone",info={language:config2.language,model,systemVersion:config2.systemVersion,statusBarHeight:config2.statusBarHeight,platform:config2.platform,brand:config2.platform==="iOS"?"Apple":"Android",client_version:config2.globals.__APP_VERSION__??"",client_type:config2.clientType};succeed(api==="WVNativeDetector.getModelInfo"?{...info,platform:model}:info);return}if(kind==="mtop"){callMtop(params??{},onSuccess,onFailure);return}if(kind==="mtopStream"){callMtopStream(params??{},succeed,failed);return}if(kind==="kvGet"||kind==="kvSet"||kind==="kvDelete"){let p=params&&typeof params=="object"?params:{},key=typeof p.key=="string"?p.key:"";if(!key){failed("missing key");return}try{let storageKey=`__mearl_app_kv__:${key}`;if(kind==="kvGet"){let stored=localStorage.getItem(storageKey);stored!==null?succeed(stored):failed(JSON.stringify({ret:["HY_FAILED"],msg:"key not found"}))}else if(kind==="kvSet"){let value=typeof p.value=="string"?p.value:p.value===void 0?"":JSON.stringify(p.value);localStorage.setItem(storageKey,value),succeed({})}else localStorage.removeItem(storageKey),succeed({})}catch{failed(JSON.stringify({ret:["HY_FAILED"],msg:"kv storage unavailable"}))}return}if(kind==="pageContext"){succeed({pageContext:void 0});return}if(kind==="memoryGet"||kind==="memorySet"||kind==="memoryDelete"){let p=params&&typeof params=="object"?params:{},key=typeof p.key=="string"?p.key:"";if(!key){failed({error_message:"missing key"});return}try{let storageKey=`__mearl_app_memory__:${key}`;if(kind==="memoryGet"){let value=sessionStorage.getItem(storageKey);succeed(value===null?{}:{value})}else if(kind==="memorySet"){let value=typeof p.value=="string"?p.value:p.value===void 0?"":JSON.stringify(p.value);sessionStorage.setItem(storageKey,value),succeed({key,success:!0})}else sessionStorage.removeItem(storageKey),succeed({key,success:!0})}catch{failed({error_message:"memory cache unavailable"})}return}if(kind==="availabilityMap"){let p=params&&typeof params=="object"?params:{},channels=Array.isArray(p.data)?p.data.filter(value=>typeof value=="string"):[];succeed({res:"success",data:Object.fromEntries(channels.map(channel=>[channel,!1]))});return}if(kind==="userInfo"){let userId=readFirstUserCookie(["unb"]),userName=readFirstUserCookie(["_w_tb_nick","_nk_","snk","tracknick"]);callUserInfo({...userId&&{userId},...userName&&{userName}},succeed);return}if(kind==="networkInfo"){let state=readNetworkState();if(api==="WVNetwork.getNetworkType"){succeed({type:{wifi:"WIFI","slow-2g":"2G","2g":"2G","3g":"3G","4g":"4G"}[state]??"UNKNOWN"});return}if(config2.profile==="alipay"||config2.profile==="koubei"){succeed({networkAvailable:state!=="fail",networkType:{wifi:"WIFI","slow-2g":"2G","2g":"2G","3g":"3G","4g":"4G",fail:"NOTREACHABLE"}[state]??"UNKNOWN"});return}let type=networkTypeNumber(state);succeed({type,state:state==="slow-2g"?"2g":state});return}if(kind==="networkQualityMonitor"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"";if(action==="add_notify_network_quality"){if(!stopNetworkQualityMonitor){let notify=()=>{try{document.dispatchEvent(new CustomEvent("WV.NETWORK_TYPE_CHANGED",{detail:{new_network_type:networkTypeNumber(readNetworkState())}}))}catch{}},connection=navigator.connection;window.addEventListener("online",notify),window.addEventListener("offline",notify),connection?.addEventListener?.("change",notify),stopNetworkQualityMonitor=()=>{window.removeEventListener("online",notify),window.removeEventListener("offline",notify),connection?.removeEventListener?.("change",notify)}}succeed({});return}if(action==="remove_notify_network_quality"){stopNetworkQualityMonitor?.(),stopNetworkQualityMonitor=null,succeed({});return}failed({error_message:"unsupported network quality monitor action"});return}if(kind==="voiceRecognition"){let status=Number((params&&typeof params=="object"?params:{}).status);if(status===0){startVoiceRecognition(succeed,failed);return}if(status===1){let recognition=voiceRecognition;if(recognition)if(voiceRecognitionStopping=!0,voiceRecognitionRunning)try{recognition.stop()}catch{finishVoiceRecognition(recognition,1)}else finishVoiceRecognition(recognition,1);succeed({});return}if(status===2){cancelVoiceRecognition(!0),succeed({});return}failed({error_code:-1,error_message:"unsupported voice recognition status"});return}if(kind==="beaconRequest"){let url2=pickUrl(params);if(!url2){failed({error_message:"missing url"});return}try{let resolved=new URL(url2,location.href);if(resolved.protocol!=="http:"&&resolved.protocol!=="https:"){failed({error_message:"unsupported request protocol"});return}let image=new Image;image.referrerPolicy="no-referrer-when-downgrade",image.src=resolved.href,succeed({})}catch{failed({error_message:"invalid url"})}return}if(kind==="calendar"){let p=params&&typeof params=="object"?params:{},events=readCalendarEvents();if(api==="store_calendar_event"){let event=calendarEventFromParams(p);if(!event.title||event.startTime===null){failed({error_message:"calendar title and start time are required"});return}let next=events.filter(stored=>!sameCalendarEvent(stored,event));if(next.push(event),!writeCalendarEvents(next)){failed({error_message:"calendar storage unavailable"});return}succeed({success:!0});return}if(api==="remove_calendar_event"){let candidate=calendarEventFromParams(p),next=events.filter(stored=>!sameCalendarEvent(stored,candidate));if(!writeCalendarEvents(next)){failed({error_message:"calendar storage unavailable"});return}succeed({success:!0,removed:events.length-next.length});return}if(api==="check_batch_calendar"){let batch=Array.isArray(p.batch)?p.batch:[];succeed({batch:batch.map(item=>{let candidate=calendarEventFromParams(item);return{...item&&typeof item=="object"?item:{},success:events.some(stored=>sameCalendarEvent(stored,candidate))}})});return}let urls=Array.isArray(p.urls)?p.urls.filter(value=>typeof value=="string"):typeof p.url=="string"?[p.url]:[],titles=Array.isArray(p.calendar_titles)?p.calendar_titles.filter(value=>typeof value=="string"):typeof p.calendar_title=="string"?[p.calendar_title]:[],matched=events.filter(event=>(urls.length===0||urls.includes(event.url))&&(titles.length===0||titles.includes(event.title)));succeed({events:matched.map(calendarEventResponse)});return}if(kind==="geolocation"){let p=params&&typeof params=="object"?params:{},windvane=api==="WVLocation.getLocation",wechat=api==="getLocation"&&config2.bridges.some(bridge=>bridge.style==="wechat"),failLocation=(errorCode,errorMsg)=>{failed({errorCode,errorMsg,...windvane&&{ret:["HY_FAILED"],errMsg:errorCode===1?"PERMISSION_DENIED":"POSITION_UNAVAILABLE",message:errorMsg},...wechat&&{errMsg:`getLocation:fail ${errorMsg}`}})};if(wechat&&p.type&&p.type!=="wgs84"){failLocation(2,`unsupported coordinate type: ${String(p.type)}`);return}if(!navigator.geolocation){failLocation(2,"geolocation unavailable");return}let locate=()=>navigator.geolocation.getCurrentPosition(position=>{let{latitude,longitude,accuracy,altitude,altitudeAccuracy,heading,speed}=position.coords,coords={latitude,longitude,accuracy,altitude,altitudeAccuracy,heading,speed};if(api==="lbs"){let provider=config2.geolocation;if(!provider){failLocation(2,"reverse geocoding unavailable");return}callMtop({api:provider.reverseGeocodeApi,v:provider.version,data:{latitude,longitude,includeGJ:1},timeout:5e3},value=>{let response=value??{},address=response.data??{};if(!Array.isArray(response.ret)||!response.ret.some(ret=>typeof ret=="string"&&ret.startsWith("SUCCESS::"))||typeof address.cityName!="string"||!address.cityName.trim()||typeof address.cityCode!="string"||!address.cityCode.trim()){failLocation(2,"reverse geocoding returned no city");return}succeed({...coords,timestamp:position.timestamp,country:address.country,province:address.province,district:address.district,city:address.cityName,cityName:address.cityName,cityCode:address.cityCode,divisionId:address.divisionId,iataCode:address.iataCode,address:address.detail})},()=>failLocation(2,"reverse geocoding failed"));return}succeed(windvane?{ret:["HY_SUCCESS"],coords,timestamp:position.timestamp}:{...coords,timestamp:position.timestamp,...wechat&&{errMsg:"getLocation:ok"}})},error48=>failLocation(error48.code,error48.message),{enableHighAccuracy:p.enableHighAccuracy===!0||p.enableHighAcuracy===!0,timeout:1e4,maximumAge:p.useCache===!1?0:3e5});navigator.permissions?.query?navigator.permissions.query({name:"geolocation"}).then(status=>{status.state==="granted"?locate():failLocation(1,"location permission not granted")}).catch(locate):locate();return}if(kind==="permission"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"",permission=typeof p.permission=="string"?p.permission:"",permissionFailed=message=>failed({error_code:-1,error_message:message});if(permission==="album"||permission==="MODIFY_AUDIO_SETTINGS"){action==="check"||action==="request"?succeed({}):permissionFailed("unsupported permission action");return}let browserPermission=permission==="mic"?"microphone":permission==="camera"?"camera":permission==="lbs"?"geolocation":"";if(!browserPermission){permissionFailed("unsupported permission");return}if(action==="check"&&navigator.permissions?.query){navigator.permissions.query({name:browserPermission}).then(status=>{status.state==="granted"?succeed({}):permissionFailed("permission not granted")}).catch(()=>permissionFailed("permission check failed"));return}if(action==="request"&&(permission==="mic"||permission==="camera")){if(!navigator.mediaDevices?.getUserMedia){permissionFailed("media permission unavailable");return}navigator.mediaDevices.getUserMedia({audio:permission==="mic",video:permission==="camera"}).then(stream=>{for(let track of stream.getTracks())track.stop();succeed({})}).catch(()=>permissionFailed("permission denied"));return}if(action==="request"&&permission==="lbs"&&navigator.geolocation){navigator.geolocation.getCurrentPosition(()=>succeed({}),()=>permissionFailed("permission denied"),{timeout:1e4});return}permissionFailed("unsupported permission action");return}if(kind==="prefetch"){let p=params&&typeof params=="object"?params:{},url2=typeof p.url=="string"?p.url:"";if(!url2){failed({code:-1,errorMsg:"url is empty"});return}let resolvedUrl;try{resolvedUrl=new URL(url2,location.href).href}catch{failed({code:-1,errorMsg:"invalid url"});return}if(!Array.from(document.querySelectorAll('link[rel="prefetch"]')).some(link=>link.href===resolvedUrl)){let link=document.createElement("link");link.rel="prefetch",link.href=url2,(document.head??document.documentElement).appendChild(link)}succeed({});return}if(kind==="fptTrack"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"",actionParams=p.params&&typeof p.params=="object"?p.params:{},key=typeof actionParams.key=="string"?actionParams.key:"";if(action==="setFpt"){let value=typeof actionParams.value=="string"?actionParams.value:"";if(!key||!value||!/^[0-9A-Za-z._-]+$/.test(key)||!/^[0-9A-Za-z._-]+$/.test(value)||`${key}(${value})`.length>100){failed({error_message:"invalid fpt key or value"});return}setFptEntry(fptEntries,key,value),persistFpt()}else action==="deleteFpt"&&key&&(fptEntries.delete(key),persistFpt());succeed({});return}if(kind==="previewFile"){let p=params&&typeof params=="object"?params:{},fileUrl=typeof p.file_url=="string"?p.file_url:"",remoteUrl=typeof p.file_remote_url=="string"?p.file_remote_url:"",url2=(fileUrl.startsWith("http")?fileUrl:remoteUrl)||fileUrl||remoteUrl;url2?(requestOpen(url2,0,!1),succeed({})):failed({code:-1,errorMsg:"file_url is empty"});return}if(kind==="toast"){let error48=showAppToast(params);error48?failed({error_message:error48}):succeed({});return}if(kind==="unsupportedNativeInput"){let containerType="";try{containerType=new URL(location.href).searchParams.get("containerType")??""}catch{}!unsupportedNativeInputNotified&&(containerType==="h5_dx"||containerType==="flutter_h5")&&(unsupportedNativeInputNotified=!0,showAppToast({message:"当前页面使用原生输入框,请移除 URL 中的 containerType 参数以正常操作",milliseconds:4e3})),succeed({});return}if(kind==="payment"){log2("桥调用支付,等待用户确认",api,params),showPaymentDialog(api,params,succeed,failed);return}if(kind==="userTrack"){sendUserTrack(params),succeed({});return}if(kind==="response"){succeed(config2.actions.responses?.[api]);return}if(kind==="noop"){succeed({});return}silent||log2("未覆盖桥方法,回调 failure(页面库将走 H5 兜底):",api),failed(NOT_IMPLEMENTED_PAYLOAD)}let MEGA_SUPPORTED_APIS={stdPop:["showWeex2","showWeex","showH5","changeSize","close"],broadcast:["addEventListener","dispatchEvent","removeEventListener"],kvStorage:["setItem","getItem","removeItem","getAllKeys","clear","getCurrentInfo","getCurrentInfoAndKeys"],LifeCycle:["addPageLifeCycleListener","removePageLifeCycleListener"],Container:["interceptPageClose","disableInterceptPageClose"],navigator:["openURL","close","replace","setSystemBackBlockListener","removeSystemBackBlockListener"],NavBar:["setTitle"],Router:["popPage"]};function isMegaApiSupported(ability,api){return typeof ability=="string"&&typeof api=="string"&&MEGA_SUPPORTED_APIS[ability]?.includes(api)===!0}function megaParams(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:{}}function megaError(callback,statusCode,message){emitMegaCallback(callback,{statusCode,type:"result",data:{errorMessage:typeof message=="string"?message:String(message??"")}})}function cloneMegaDetail(value){if(value===void 0)return{success:!0,value:void 0};try{return{success:!0,value:JSON.parse(JSON.stringify(value))}}catch{return{success:!1}}}function megaSuccess(data={}){return{statusCode:0,type:"result",data}}function megaFailure(message){return{statusCode:500,type:"result",data:{errorMessage:message}}}function megaKVParams(params){return{bizId:typeof params.bizID=="string"?params.bizID:typeof params.bizId=="string"?params.bizId:"",key:typeof params.key=="string"?params.key:"",value:typeof params.value=="string"?params.value:null}}function megaStringByteLength(value){try{return typeof TextEncoder=="function"?new TextEncoder().encode(value).length:value.length}catch{return value.length}}function megaKVUsedSize(entries){let size=0;for(let value of entries.values())size+=megaStringByteLength(value);return size}function reportMegaKVMutation(operation,bizId,key="",value,onSuccess,onFailure){requestContainerData("megaKVMutation",{operation,bizId,key,...value===void 0?{}:{value}},()=>onSuccess?.(),reason=>{log2("KVStorage 容器同步失败:",reason),onFailure?.(reason)})}function completeMegaKVMutation(operation,bizId,key,value,synchronous,callback){let result=megaSuccess();return reportMegaKVMutation(operation,bizId,key,value,synchronous?void 0:()=>emitMegaCallback(callback,result),synchronous?void 0:reason=>emitMegaCallback(callback,megaFailure(String(reason??"container sync failed")))),synchronous?result:null}function executeMegaKVStorage(api,params,synchronous,callback){let{bizId,key,value}=megaKVParams(params);if(!bizId)return megaFailure("missing bizID");let entries=megaKVStorage.get(bizId)??new Map;if(api==="setItem"){if(!key)return megaFailure("missing key");if(value===null||value==="")return megaFailure("missing value");let previousSize=megaStringByteLength(entries.get(key)??"");return megaKVUsedSize(entries)-previousSize+megaStringByteLength(value)>MEGA_KV_TOTAL_SIZE?megaFailure("KVStorage quota exceeded"):(entries.set(key,value),megaKVStorage.set(bizId,entries),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("set",bizId,key,value,synchronous,callback))}if(api==="getItem"){if(!key)return megaFailure("missing key");let result=entries.get(key)??"";return megaSuccess(synchronous?{result}:result)}if(api==="removeItem")return key?(entries.delete(key),entries.size===0&&megaKVStorage.delete(bizId),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("remove",bizId,key,void 0,synchronous,callback)):megaFailure("missing key");if(api==="getAllKeys"){let result=Array.from(entries.keys());return megaSuccess(synchronous?{result}:result)}if(api==="clear")return megaKVStorage.delete(bizId),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("clear",bizId,"",void 0,synchronous,callback);if(api==="getCurrentInfo"||api==="getCurrentInfoAndKeys"){let data={totalSize:MEGA_KV_TOTAL_SIZE,freeSize:Math.max(MEGA_KV_TOTAL_SIZE-megaKVUsedSize(entries),0)};return api==="getCurrentInfoAndKeys"&&(data.keys=Array.from(entries.keys())),megaSuccess(data)}return{statusCode:405,type:"result",data:{}}}function handleMegaLifeCycle(api,callback){if(api==="addPageLifeCycleListener"){callback&&megaLifeCycleListeners.add(callback),emitMegaCallback(callback,megaSuccess());return}if(api==="removePageLifeCycleListener"){let listeners=Array.from(megaLifeCycleListeners);megaLifeCycleListeners.clear(),emitMegaCallback(callback,megaSuccess());for(let listener of listeners)emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`LifeCycle.${api} is not supported`)}function handleMegaContainer(api,callback){if(api==="interceptPageClose"){callback&&megaPageCloseListeners.add(callback),emitMegaCallback(callback,megaSuccess());return}if(api==="disableInterceptPageClose"){let listeners=Array.from(megaPageCloseListeners);megaPageCloseListeners.clear(),emitMegaCallback(callback,megaSuccess());for(let listener of listeners)emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`Container.${api} is not supported`)}function megaNavigationUrl(params){let rawUrl=pickUrl(params);if(!rawUrl)return null;if(!params.extQuery||typeof params.extQuery!="object"||Array.isArray(params.extQuery))return rawUrl;try{let target=new URL(rawUrl,location.href);for(let[key,value]of Object.entries(params.extQuery))value!=null&&target.searchParams.set(key,String(value));return target.href}catch{return rawUrl}}function handleMegaNavigator(api,params,callback){if(api==="openURL"||api==="replace"){let url2=megaNavigationUrl(params);if(!url2){megaError(callback,500,"missing url");return}let callbackId=api==="openURL"&&callback?stashCallback(value=>{let backdata=value&&typeof value=="object"?value.backdata:void 0;emitMegaCallback(callback,{statusCode:1,type:"onResult",data:{result:!0,...backdata===void 0?{}:{data:backdata}}}),emitMegaCallback(callback,{statusCode:99,type:"finish",data:{}})}):0;requestOpen(url2,callbackId,!1,{...params,...api==="replace"?{__mearlReplace:!0}:{}}),emitMegaCallback(callback,megaSuccess());return}if(api==="close"){emitMegaCallback(callback,megaSuccess()),requestClose(void 0);return}if(api==="setSystemBackBlockListener"){megaSystemBackListener&&megaSystemBackListener!==callback&&emitMegaCallback(megaSystemBackListener,{statusCode:99,type:"finish",data:{}}),megaSystemBackListener=callback??null,emitMegaCallback(callback,megaSuccess());return}if(api==="removeSystemBackBlockListener"){let listener=megaSystemBackListener;megaSystemBackListener=null,emitMegaCallback(callback,megaSuccess()),listener&&emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`navigator.${api} is not supported`)}function handleMegaNavBar(api,params,callback){if(api!=="setTitle"){megaError(callback,405,`NavBar.${api} is not supported`);return}applyNavigationBarState(api,params),emitMegaCallback(callback,megaSuccess())}function handleMegaRouter(api,callback){if(api!=="popPage"){megaError(callback,405,`Router.${api} is not supported`);return}emitMegaCallback(callback,megaSuccess()),requestClose(void 0)}function handleMegaStdPop(api,params,callback){if(api==="showH5"||api==="showWeex2"||api==="showWeex"){let url2=pickUrl(params),popId=typeof params.popId=="string"?params.popId.trim():"";if(!url2||!popId){megaError(callback,500,url2?"missing popId":"missing url");return}let callbackId=stashCallback(value=>{let result=value&&typeof value=="object"&&"backdata"in value?value.backdata:void 0;emitMegaCallback(callback,{statusCode:1,type:"onClose",data:result}),emitMegaCallback(callback,{statusCode:99,type:"finish"})});requestOpen(url2,callbackId,!0,{...params,__mearlMegaPopId:popId}),emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});return}if(api==="close"){let popId=typeof params.popId=="string"?params.popId.trim():"";if(!popId){megaError(callback,500,"missing popId");return}let cloned=cloneMegaDetail(params.result);if(!cloned.success){megaError(callback,500,"result is not serializable");return}requestContainerData("megaPopClose",{popId,result:cloned.value},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}if(api==="changeSize"){let popId=typeof params.popId=="string"?params.popId.trim():"";if(!popId){megaError(callback,500,"missing popId");return}requestContainerData("megaPopResize",{...params,popId},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}megaError(callback,405,`stdPop.${api} is not supported`)}function handleMegaBroadcast(api,params,callback){let bizId=megaBroadcastBizId(params.bizId),eventName=typeof params.eventName=="string"?params.eventName.trim():"";if(!eventName){megaError(callback,500,"missing eventName");return}if(api==="addEventListener"){if(!callback)return;let id=`mearl-mega-listener-${++megaListenerSeq}`;megaBroadcastListeners.set(id,{id,bizId,eventName,once:params.once===!0,callback}),emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),emitMegaCallback(callback,{statusCode:1,type:"onAdd",data:{listenerId:id}});return}if(api==="dispatchEvent"){let detail=cloneMegaDetail(params.detail);if(!detail.success){megaError(callback,500,"detail is not serializable");return}requestContainerData("megaBroadcast",{message:{kind:"megaBroadcast",bizId,eventName,detail:detail.value}},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}if(api==="removeEventListener"){let listenerId=typeof params.listenerId=="string"?params.listenerId:"",removed=[];for(let listener of Array.from(megaBroadcastListeners.values()))listener.bizId!==bizId||listener.eventName!==eventName||listenerId&&listener.id!==listenerId||(megaBroadcastListeners.delete(listener.id),removed.push(listener));emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});for(let listener of removed)emitMegaCallback(listener.callback,{statusCode:99,type:"finish"});return}megaError(callback,405,`broadcast.${api} is not supported`)}function makeMegaBridge(){return{asyncCall:(ability,api,rawParams,callback)=>{let params=megaParams(rawParams);if(ability==="ability"&&api==="available"){emitMegaCallback(callback,{statusCode:0,type:isMegaApiSupported(params.ability,params.api)?"YES":"NO",data:{}});return}if(ability==="ability"&&api==="batchFinishTrace"){emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});return}if(!isMegaApiSupported(ability,api)){megaError(callback,405,`${ability}.${api} is not supported`);return}if(ability==="stdPop")handleMegaStdPop(api,params,callback);else if(ability==="broadcast")handleMegaBroadcast(api,params,callback);else if(ability==="kvStorage"){let result=executeMegaKVStorage(api,params,!1,callback);result&&emitMegaCallback(callback,result)}else ability==="LifeCycle"?handleMegaLifeCycle(api,callback):ability==="Container"?handleMegaContainer(api,callback):ability==="navigator"?handleMegaNavigator(api,params,callback):ability==="NavBar"?handleMegaNavBar(api,params,callback):handleMegaRouter(api,callback)},syncCall:(ability,api,rawParams)=>{let params=megaParams(rawParams);return ability==="ability"&&api==="available"?{statusCode:0,type:isMegaApiSupported(params.ability,params.api)?"YES":"NO",data:{}}:ability==="kvStorage"&&isMegaApiSupported(ability,api)?executeMegaKVStorage(api,params,!0)??megaFailure("container sync pending"):{statusCode:405,type:"result",data:{}}}}}function makeBridge(style){if(style==="mega")return makeMegaBridge();if(style==="easybikeNative"){let callNative=rawPayload=>{let payload;try{payload=typeof rawPayload=="string"?JSON.parse(rawPayload):rawPayload??{}}catch{return}let classMap=typeof payload.classMap=="string"?payload.classMap:"",method=typeof payload.method=="string"?payload.method:"",callbackId=typeof payload.callbackId=="string"||typeof payload.callbackId=="number"?String(payload.callbackId):"",params;try{params=typeof payload.params=="string"?payload.params?JSON.parse(payload.params):{}:payload.params??{}}catch{params={}}let complete=(code,data,msg="")=>{let callback=resolveWindowFunction("callBack");callbackId&&callback&&callback({callbackId,code,data,msg})};dispatch(`${classMap}.${method}`,params,value=>complete(0,value),error48=>complete(1,void 0,typeof error48=="string"?error48:String(error48??"")))};return{postMessage:callNative,callNative}}if(style==="windvane"){let call=(api,params,success2,failure)=>{let onSuccess=typeof success2=="function"?success2:void 0,onFailure=typeof failure=="function"?failure:void 0;if(onSuccess||onFailure){dispatch(api,params,onSuccess,onFailure);return}return new Promise((resolve2,reject)=>dispatch(api,params,resolve2,reject))};return{isAvailable:!0,version:"8.7.0",call2:call,call:(cls,method,params,succ,fail2)=>call(`${cls}.${method}`,params,succ,fail2)}}if(style==="fliggy"||style==="alipay"||style==="callback"){let bridge={call:(api,params,succ,fail2)=>{typeof params=="function"&&(fail2=succ,succ=params,params=void 0);let p=params&&typeof params=="object"?params:{},successFn=succ??(typeof p.success_callback=="function"?p.success_callback:void 0)??(typeof p.successCallback=="function"?p.successCallback:void 0),failureFn=fail2??(typeof p.fail_callback=="function"?p.fail_callback:void 0)??(typeof p.failure_callback=="function"?p.failure_callback:void 0)??(typeof p.failCallback=="function"?p.failCallback:void 0)??(typeof p.failureCallback=="function"?p.failureCallback:void 0);dispatch(api,p,res=>successFn?.(res),err=>{failureFn?failureFn(err):successFn?.({error:err})},p.callbackCommand??p.callback_command)},pushBack:(prefixOrApi,apiOrParams,paramsOrSucc,succ)=>{let api=prefixOrApi,params=apiOrParams,success2=paramsOrSucc;typeof apiOrParams=="string"&&(api=apiOrParams,params=paramsOrSucc,success2=succ);let p=params??{},successFn=(typeof success2=="function"?success2:void 0)??(typeof p.successCallback=="function"?p.successCallback:void 0);return dispatch(api,p,res=>successFn?.(res),void 0,p.callbackCommand??p.callback_command),bridge},sendUriScheme:uri=>(handleMaybeScheme(uri),bridge)};if(style==="fliggy"){let normalizedAppName=(config2.globals.__APP_NAME__??"").toUpperCase(),os11=config2.clientType==="iphone"?"ios":"android",isAliApp=name=>normalizedAppName===name.toUpperCase();Object.assign(bridge,{version:"1.0.21",device:{os:os11,OS:config2.platform,type:os11,version:config2.systemVersion,model:config2.globals.__DEVICE_MODEL__??""},platform:os11,isAliApp,isTmall:isAliApp("TM"),isTaobao:isAliApp("TB"),isAlipay:isAliApp("AP"),isAlitrip:isAliApp("LX"),isKoubei:isAliApp("KB"),isElm:isAliApp("ELMC"),isGaode:isAliApp("amap"),isUC:/UCBrowser/i.test(config2.userAgent),isWeibo:/Weibo/i.test(config2.userAgent),isWeixin:/MicroMessenger/i.test(config2.userAgent),isWindVane:config2.bridges.some(item=>item.style==="windvane"),isAlipayClient:/AlipayClient/i.test(config2.userAgent)})}return bridge}if(style==="btrip")return{call:(api,params)=>dispatch(api,params??{},void 0,void 0)};if(style==="invoke")return{invoke:(api,params)=>{let p=params??{};dispatch(api,p,p.success,p.fail)}};if(style==="callHandler")return{callHandler:(api,params)=>dispatch(api,params??{},void 0,void 0)};if(style==="amap")return{ready:cb=>cb?.(),send:(msg,cb)=>{let m=msg??{};dispatch(typeof m.action=="string"?m.action:"",m,res=>cb?.(res),err=>cb?.({error:err}))}};if(style==="didi")return{openPage:params=>dispatch("openPage",params??{},void 0,void 0),closePage:params=>dispatch("closePage",params??{},void 0,void 0)};if(style==="wechat"||style==="wechatMiniProgram"){let invoke2=(api,params)=>{let p=params&&typeof params=="object"?params:{};dispatch(api,p,value=>{p.success?.(value),p.complete?.(value)},error48=>{p.fail?.(error48),p.complete?.(error48)})};return style==="wechat"?{ready:callback=>{callback&&setTimeout(callback,0)},getLocation:params=>invoke2("getLocation",params)}:{navigateTo:params=>invoke2("navigateTo",params),redirectTo:params=>invoke2("redirectTo",params),switchTab:params=>invoke2("switchTab",params),reLaunch:params=>invoke2("reLaunch",params),navigateBack:params=>invoke2("navigateBack",params),postMessage:params=>invoke2("postMessage",params),getEnv:callback=>{callback&&setTimeout(()=>callback({miniprogram:!0}),0)}}}return{}}function setGlobal(path19,value){let parts=path19.split("."),obj=w;for(let i=0;i<parts.length-1;i++){let cur=obj[parts[i]];(!cur||typeof cur!="object")&&(obj[parts[i]]={}),obj=obj[parts[i]]}obj[parts[parts.length-1]]=value}function setPersistentGlobal(path19,value){let parts=path19.split(".").filter(Boolean);if(parts.length<2){setGlobal(path19,value);return}let[rootKey,...nestedParts]=parts,isObjectLike=candidate=>typeof candidate=="object"&&candidate!==null||typeof candidate=="function",attachBridge=candidate=>{let root=isObjectLike(candidate)?candidate:{},obj=root;for(let index=0;index<nestedParts.length-1;index+=1){let key=nestedParts[index],child=obj[key];if(!isObjectLike(child))try{obj[key]={}}catch{return root}obj=obj[key]}let leaf=nestedParts[nestedParts.length-1];try{Object.defineProperty(obj,leaf,{configurable:!1,enumerable:!0,get:()=>value,set:()=>{}})}catch{try{obj[leaf]=value}catch{}}return root},currentRoot=attachBridge(w[rootKey]);try{Object.defineProperty(w,rootKey,{configurable:!1,enumerable:!0,get:()=>currentRoot,set:next=>{currentRoot=attachBridge(next)}})}catch{w[rootKey]=currentRoot}}if(config2.bridges.some(spec=>spec.style==="mega")){let hydrationVersion=megaKVMutationVersion;requestContainerData("megaKVSnapshot",{},value=>{let entries=value&&typeof value=="object"?value.entries:void 0;megaKVMutationVersion===hydrationVersion&&replaceMegaKVStorage(entries)},()=>{})}for(let spec of config2.bridges)try{let bridge=makeBridge(spec.style);spec.persistent?setPersistentGlobal(spec.global,bridge):setGlobal(spec.global,bridge)}catch(e){console.error(TAG,"桥安装失败:",spec.global,e)}return{mapScheme,handleMaybeScheme,handleAppMessage,handleNativeBack,handleResume,handlePageVisibility,applyRuntimeResponses}}function installAppProfileContainerStack(config2,environment,links){let{SRC,TAG,simulateSystemBars,ROOT_FRAME_NAME,LAYER_FRAME_NAME,isTop,isRootFrame,isLayerFrame,isContainerFrame,usesRootContainer,log:log2}=environment,{pageTransport}=links,initialLayerTitleBarState=url2=>links.getSystemBars().initialLayerTitleBarState(url2),resolvedTitleBarState=layer=>links.getSystemBars().resolvedTitleBarState(layer),parseReportedTitleBarState=value=>links.getSystemBars().parseReportedTitleBarState(value),createSimulatedNavigationBarView=(placement,onBack)=>links.getSystemBars().createNavigationBarView(placement,onBack),destroySimulatedNavigationBarView=view=>links.getSystemBars().destroyNavigationBarView(view),syncLayerViewport=(layer,state)=>links.getSystemBars().syncLayerViewport(layer,state),syncActiveSystemBars=()=>links.getSystemBars().syncActiveSystemBars(),syncSimulatedTitleBar=()=>links.getSystemBars().syncSimulatedTitleBar(),rootContainerActive=!1,rootFrame=null,rootBusinessUrl=location.href,splitScreenActive=usesRootContainer&&config2.rootContainer?.splitScreen===!0,webViewEnvironmentRequestSeq=0,simulatedPageHidden=!1,runtimeResponses=null;function syncSimulatorStateToWindow(target){target&&(target.postMessage({source:SRC,type:"requestTitleBarState"},"*"),runtimeResponses&&target.postMessage({source:SRC,type:"runtimeResponses",profile:config2.profile,responses:runtimeResponses},"*"),simulatedPageHidden&&target.postMessage({source:SRC,type:"simulatorVisibility",hidden:!0},"*"))}function startPreparedWebViewNavigation(frame,target,canCommit,registerCleanup){let insets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0};if(!usesRootContainer||!Object.values(insets).some(value=>value>0)){canCommit()&&(frame.src=target);return}let requestId=++webViewEnvironmentRequestSeq,settled=!1,fallbackTimer=0,cleanup=()=>{settled||(settled=!0,clearTimeout(fallbackTimer),window.removeEventListener("message",handleResponse),registerCleanup?.(null))},commitNavigation=fallbackReason=>{cleanup(),fallbackReason&&console.warn(TAG,"WebView 环境准备未完成,降级提交导航",{target,requestId,reason:fallbackReason}),canCommit()&&(frame.src=target)},handleResponse=event=>{if(event.source!==window||event.data?.source!=="mearl-content"||event.data?.type!=="APP_BRIDGE_PREPARE_WEBVIEW_RESPONSE"||event.data?.requestId!==requestId)return;let result=event.data.result;result?.success===!0?commitNavigation():commitNavigation(String(result?.error??"unknown preparation failure"))};registerCleanup?.(cleanup),window.addEventListener("message",handleResponse),fallbackTimer=setTimeout(()=>commitNavigation("preparation timed out after 500ms"),500);try{window.postMessage({source:SRC,type:"prepareWebView",requestId},"*")}catch(error48){commitNavigation(error48 instanceof Error?error48.message:String(error48))}}function installRootContainer(){if(!usesRootContainer||!/^https?:$/i.test(location.protocol))return;let shellRoot,frame;try{for(let cookie of config2.rootContainer?.initialCookies??[]){if(!cookie.name)continue;let parts=[`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,`Path=${cookie.path??"/"}`];cookie.domain&&parts.push(`Domain=${cookie.domain}`),document.cookie=parts.join("; ")}shellRoot=document.createElement("html");let shellHead=document.createElement("head"),charset=document.createElement("meta"),viewport=document.createElement("meta"),title=document.createElement("title"),shellBody=document.createElement("body");frame=document.createElement("iframe"),shellRoot.setAttribute("data-mearl-app-shell",""),shellBody.setAttribute("data-mearl-app-shell",""),charset.setAttribute("charset","utf-8"),viewport.name="viewport",viewport.content="width=device-width,initial-scale=1,viewport-fit=cover",shellHead.append(charset,viewport,title),shellRoot.append(shellHead,shellBody),shellRoot.style.cssText="width:100%;height:100%;margin:0;overflow:hidden;background:#fff;",shellBody.style.cssText="width:100%;height:100%;margin:0;overflow:hidden;background:#fff;",frame.name=ROOT_FRAME_NAME,frame.setAttribute("data-mearl-root-webview",config2.profile),frame.setAttribute("allow","microphone; on-device-speech-recognition"),splitScreenActive&&frame.setAttribute("data-mearl-split-pane","left"),frame.style.cssText=splitScreenActive?"position:fixed;left:0;right:auto;top:0;bottom:0;width:50%;height:100%;border:0;border-right:1px solid rgba(15,23,42,.14);box-sizing:border-box;display:block;background:#fff;z-index:0;opacity:1;":"position:fixed;left:0;right:0;top:0;bottom:0;width:100%;height:100%;border:0;display:block;background:#fff;z-index:0;opacity:1;",frame.addEventListener("load",()=>{let committedSrc=frame.getAttribute("src");!committedSrc||committedSrc==="about:blank"||(syncSimulatorStateToWindow(frame.contentWindow),requestAnimationFrame(()=>{rootFrame!==frame||!frame.isConnected||(frame.setAttribute("data-mearl-webview-ready",""),syncSimulatedTitleBar())}))}),shellBody.appendChild(frame);let currentRoot=document.documentElement;currentRoot?document.replaceChild(shellRoot,currentRoot):document.appendChild(shellRoot)}catch(error48){console.warn(TAG,"根 WebView 容器创建失败,保留当前页面",error48),rootFrame=null;return}rootFrame=frame,rootContainerActive=!0;try{typeof window.stop=="function"&&window.stop()}catch(error48){console.warn(TAG,"停止外层文档加载失败,继续启动根 WebView",error48)}try{startPreparedWebViewNavigation(frame,rootBusinessUrl,()=>rootFrame===frame&&frame.isConnected)}catch(error48){console.warn(TAG,"根 WebView 环境准备启动失败,直接提交业务导航",error48),rootFrame===frame&&frame.isConnected&&(frame.src=rootBusinessUrl)}}installRootContainer();function normalizeProxyPathPrefix(prefix){let withLeadingSlash=prefix.startsWith("/")?prefix:`/${prefix}`;return withLeadingSlash.endsWith("/")?withLeadingSlash:`${withLeadingSlash}/`}function matchesProxyTarget(hostname3,suffixes){return suffixes.some(suffix=>hostname3===suffix||hostname3.endsWith(`.${suffix}`))}function mapLayerFrameUrl(url2){let proxy=config2.layerUrlProxy;if(!proxy||!location.hostname.startsWith(proxy.sourceHostPrefix))return url2;try{let target=new URL(url2,location.href);if(!/^https?:$/.test(target.protocol))return url2;let prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(target.hostname===location.hostname){if(target.pathname.startsWith(prefix))return url2;let derivedHost=location.pathname.startsWith(prefix)?location.pathname.slice(prefix.length).split("/")[0]:proxy.defaultTargetHost;return!derivedHost||!matchesProxyTarget(derivedHost,proxy.targetHostSuffixes)?url2:`${location.origin}${prefix}${derivedHost}${target.pathname}${target.search}${target.hash}`}return matchesProxyTarget(target.hostname,proxy.targetHostSuffixes)?`${location.origin}${prefix}${target.host}${target.pathname}${target.search}${target.hash}`:url2}catch{return url2}}function restoreLayerBusinessUrl(url2){let proxy=config2.layerUrlProxy;if(!proxy)return url2;try{let current=new URL(url2,location.href),prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(current.origin!==location.origin||!current.pathname.startsWith(prefix))return url2;let rest=current.pathname.slice(prefix.length),slash=rest.indexOf("/"),host=slash===-1?rest:rest.slice(0,slash);if(!host)return url2;let hostname3=new URL(`${current.protocol}//${host}`).hostname;if(!matchesProxyTarget(hostname3,proxy.targetHostSuffixes))return url2;let pathname=slash===-1?"/":rest.slice(slash);return`${current.protocol}//${host}${pathname}${current.search}${current.hash}`}catch{return url2}}let ANIM_MS=config2.animationMs??300;function boolParam(value,fallback){return value===!0||value===1||value==="1"||value==="true"?!0:value===!1||value===0||value==="0"||value==="false"?!1:value===""?!0:fallback}function numberParam(value,fallback,min,max){let parsed=typeof value=="number"?value:Number(value);return Number.isFinite(parsed)?Math.min(Math.max(parsed,min),max):fallback}function resolveOverlayPresentation(url2,params,explicitWebdialog){let query=null;try{query=new URL(url2,location.href).searchParams}catch{}let records=[],addRecord=value=>{value&&typeof value=="object"&&!Array.isArray(value)&&records.push(value)};addRecord(params?.pageParams),addRecord(params?.page_params),addRecord(params?.popConfig),addRecord(params?.data),addRecord(params?.param),addRecord(params);let read=key=>{for(let record2 of records)if(Object.prototype.hasOwnProperty.call(record2,key))return record2[key];return query?.has(key)?query.get(key):void 0},protocol=config2.overlay;if(!explicitWebdialog&&(!protocol||!boolParam(read(protocol.enabledParam),!1)))return null;let configuredTopRatio=protocol?read(protocol.topRatioParam):void 0,configuredHeightRatio=protocol?.heightRatioParam?read(protocol.heightRatioParam):void 0,configuredMaxHeight=read("maxHeight")??configuredHeightRatio,defaultTopRatio=protocol?.defaultTopRatio??.2;return{topRatio:configuredTopRatio!==void 0?numberParam(configuredTopRatio,defaultTopRatio,0,1):configuredMaxHeight!==void 0?1-numberParam(configuredMaxHeight,1-defaultTopRatio,0,1):defaultTopRatio,widthRatio:numberParam(read("maxWidth"),1,0,1),radius:numberParam((protocol?read(protocol.radiusParam):void 0)??read("cornerRadius"),protocol?.defaultRadius??0,0,50),maskAlpha:numberParam(protocol?read(protocol.maskAlphaParam):void 0,protocol?.defaultMaskAlpha??.3,0,1),tapClose:boolParam((protocol?read(protocol.tapCloseParam):void 0)??read("tapEnable"),protocol?.defaultTapClose??!0)}}function requestsPopBeforeOpen(url2,params){if(params?.__mearlReplace===!0)return!0;let key=config2.popBeforeOpenParam;if(!key)return!1;let records=[params?.pageParams,params?.page_params,params?.data,params?.param,params];for(let value of records){if(!value||typeof value!="object"||Array.isArray(value))continue;let record2=value;if(Object.prototype.hasOwnProperty.call(record2,key))return boolParam(record2[key],!1)}try{let query=new URL(url2,location.href).searchParams;return query.has(key)&&boolParam(query.get(key),!1)}catch{return!1}}let layers=[],forwardStack=[],layerSeq=0,enteringLayerCount=0,closingLayerCount=0,explicitLayerTitleBarStates=new Map,rootScrollStyles=null,pendingClose=null,nativeBackRequestSeq=0,pendingNativeBack=null,containerDataRequestSeq=0,containerDataCallbacks=new Map,sharedFiles=new Map,sharedData=new Map,legacyBroadcastChannels=new Set,MEGA_KV_STORAGE_KEY=`__mearl_mega_kv__:${config2.profile}`;function readMegaKVStorage(){let storage=new Map;try{let parsed=JSON.parse(localStorage.getItem(MEGA_KV_STORAGE_KEY)??"{}");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return storage;for(let[bizId,rawEntries]of Object.entries(parsed)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,value]of Object.entries(rawEntries))typeof value=="string"&&entries.set(key,value);storage.set(bizId,entries)}}catch{}return storage}let megaKVStorage=readMegaKVStorage();function megaKVSnapshot(){let snapshot={};for(let[bizId,values]of megaKVStorage)snapshot[bizId]=Object.fromEntries(values);return snapshot}function persistMegaKVStorage(){try{localStorage.setItem(MEGA_KV_STORAGE_KEY,JSON.stringify(megaKVSnapshot()))}catch{}}let PENDING_CLOSE_TIMEOUT_MS=400,pendingHistoryDepth=null,pendingSplitRootOpen=null;function clearPendingClose(){pendingClose&&(clearTimeout(pendingClose.timer),pendingClose=null)}function clearPendingNativeBack(){pendingNativeBack&&(clearTimeout(pendingNativeBack.timer),pendingNativeBack=null)}function clearPendingHistoryDepth(){pendingHistoryDepth&&(clearTimeout(pendingHistoryDepth.timer),pendingHistoryDepth=null)}function syncHistoryAfterDirectClose(){clearPendingHistoryDepth();let depth=layers.length,timer=setTimeout(()=>{pendingHistoryDepth=null,console.warn(TAG,"WebView 已出栈,但浏览器历史未在预期时间内同步",{depth})},PENDING_CLOSE_TIMEOUT_MS);pendingHistoryDepth={depth,timer},history.back()}function armPendingClose(data,retries){clearPendingClose();let timer=setTimeout(()=>{pendingClose=null,log2("close 未等到 popstate,直接关栈顶兜底"),closeToDepth(Math.max(layers.length-1,0),data,!0)},PENDING_CLOSE_TIMEOUT_MS);pendingClose={data,retries,timer},history.back()}function parseStorageId(url2){try{return new URL(url2,location.href).searchParams.get("__storage_id")}catch{return null}}function titleBarStateCacheKey(url2){try{let parsed=new URL(url2,location.href);return parsed.hash="",parsed.href}catch{return url2}}function cacheExplicitTitleBarState(layer,state){explicitLayerTitleBarStates.set(titleBarStateCacheKey(layer.entryUrl),state),explicitLayerTitleBarStates.set(titleBarStateCacheKey(layer.url),state)}function readDepth(state){if(state&&typeof state=="object"){let d=state.__mearl_layer__;if(typeof d=="number")return d}return null}function mapUrlForSync(url2){let suffixes=config2.urlSyncHostSuffixes??[];try{let u=new URL(url2,location.href);if(!/^https?:$/.test(u.protocol)||!(suffixes.length===0||suffixes.some(s=>u.host===s||u.host.endsWith(`.${s}`))))return;if(u.origin===location.origin)return u.pathname+u.search+u.hash;let proxy=config2.layerUrlProxy;return proxy&&location.hostname.startsWith(proxy.sourceHostPrefix)&&matchesProxyTarget(u.hostname,proxy.targetHostSuffixes)?`${normalizeProxyPathPrefix(proxy.pathPrefix)}${u.host}${u.pathname}${u.search}${u.hash}`:u.pathname+u.search+u.hash}catch{return}}function createLayerEl(overlay,id){let el=document.createElement("div");el.setAttribute("data-mearl-layer",String(id)),splitScreenActive&&el.setAttribute("data-mearl-split-pane","right"),el.style.cssText=splitScreenActive?`position:fixed;left:50%;right:0;top:0;bottom:0;width:50%;z-index:${2147483e3+id%100*2};`:`position:fixed;inset:0;z-index:${2147483e3+id%100*2};`;let frame=document.createElement("iframe");if(frame.name=LAYER_FRAME_NAME,frame.setAttribute("allow","microphone; on-device-speech-recognition"),frame.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-modals allow-downloads allow-popups"),frame.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0;display:block;background:#fff;z-index:0;opacity:1;",overlay){el.style.pointerEvents="none";let mask=document.createElement("div");mask.style.cssText=`position:absolute;inset:0;background:rgba(0,0,0,${overlay.maskAlpha});opacity:0;pointer-events:auto;`;let sheet=document.createElement("div"),width=overlay.widthRatio*100,left=(1-overlay.widthRatio)/2*100;return sheet.style.cssText=`position:absolute;left:${left}%;right:auto;bottom:0;width:${width}%;height:${(1-overlay.topRatio)*100}%;background:#fff;border-radius:${overlay.radius}px ${overlay.radius}px 0 0;overflow:hidden;pointer-events:auto;`,sheet.appendChild(frame),el.appendChild(mask),el.appendChild(sheet),{el,frame,animEl:sheet,mask}}return el.style.background="#fff",el.appendChild(frame),{el,frame,animEl:el,mask:null}}function setLayerInteractive(layer,interactive){layer.frame.style.pointerEvents=interactive?"":"none",layer.titleBarView&&(layer.titleBarView.root.style.pointerEvents=interactive?"":"none"),interactive?(layer.frame.removeAttribute("inert"),layer.frame.removeAttribute("aria-hidden"),layer.frame.removeAttribute("tabindex")):(layer.frame.setAttribute("inert",""),layer.frame.setAttribute("aria-hidden","true"),layer.frame.setAttribute("tabindex","-1"),layer.frame.blur()),layer.overlay?(layer.el.style.pointerEvents="none",layer.animEl.style.pointerEvents=interactive?"auto":"none",layer.mask&&(layer.mask.style.pointerEvents=interactive?"auto":"none")):layer.el.style.pointerEvents=interactive?"":"none"}function setRootFrameInteractive(interactive){rootFrame&&(rootFrame.style.pointerEvents=interactive?"":"none",interactive?(rootFrame.removeAttribute("inert"),rootFrame.removeAttribute("aria-hidden"),rootFrame.removeAttribute("tabindex")):(rootFrame.setAttribute("inert",""),rootFrame.setAttribute("aria-hidden","true"),rootFrame.setAttribute("tabindex","-1"),rootFrame.blur()))}function blockClosingLayerInteractions(layer){setLayerInteractive(layer,!1),layer.el.style.pointerEvents="auto"}function syncRootScrollLock(locked){let body=document.body;if(locked&&!rootScrollStyles){rootScrollStyles={html:document.documentElement.style.overflow,body:body?.style.overflow??null},document.documentElement.style.overflow="hidden",body&&(body.style.overflow="hidden");return}!locked&&rootScrollStyles&&(document.documentElement.style.overflow=rootScrollStyles.html,body&&rootScrollStyles.body!==null&&(body.style.overflow=rootScrollStyles.body),rootScrollStyles=null)}function syncLayerInteractivity(){let activeLayer=closingLayerCount===0&&enteringLayerCount===0?layers[layers.length-1]:void 0;for(let layer of layers)setLayerInteractive(layer,layer===activeLayer),!activeLayer&&layer===layers[layers.length-1]&&(layer.el.style.pointerEvents="auto");setRootFrameInteractive(splitScreenActive?pendingSplitRootOpen===null:layers.length===0&&enteringLayerCount===0&&closingLayerCount===0),syncRootScrollLock(layers.length>0||enteringLayerCount>0||closingLayerCount>0)}function finishLayerEntry(layer){layer.entering&&(layer.entering=!1,layer.enterTimer!==null&&clearTimeout(layer.enterTimer),layer.enterTimer=null,layer.enterTransitionEnd&&(layer.animEl.removeEventListener("transitionend",layer.enterTransitionEnd),layer.enterTransitionEnd=null),enteringLayerCount=Math.max(enteringLayerCount-1,0),syncLayerInteractivity())}function animateIn(layer){let t=layer.animEl;if(t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",t.offsetWidth,t.style.transition=`transform ${ANIM_MS}ms ease`,t.style.transform="translate(0px, 0px)",layer.mask&&(layer.mask.style.transition=`opacity ${ANIM_MS}ms ease`,layer.mask.style.opacity="1"),ANIM_MS<=0){finishLayerEntry(layer);return}layer.enterTransitionEnd=event=>{event.target===t&&event.propertyName==="transform"&&finishLayerEntry(layer)},t.addEventListener("transitionend",layer.enterTransitionEnd),layer.enterTimer=setTimeout(()=>finishLayerEntry(layer),ANIM_MS+60)}function animateOut(layer,done){let t=layer.animEl;if(ANIM_MS<=0){t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",layer.mask&&(layer.mask.style.opacity="0"),setTimeout(done,0);return}let settled=!1,fallbackTimer=0,finish=()=>{settled||(settled=!0,t.removeEventListener("transitionend",onTransitionEnd),clearTimeout(fallbackTimer),done())},onTransitionEnd=event=>{event.target===t&&event.propertyName==="transform"&&finish()};t.addEventListener("transitionend",onTransitionEnd),t.style.transition=`transform ${ANIM_MS}ms ease`,t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",layer.mask&&(layer.mask.style.opacity="0"),fallbackTimer=setTimeout(finish,ANIM_MS+60)}function startLayerNavigation(layer,target){startPreparedWebViewNavigation(layer.frame,target,()=>!layer.closing&&layer.el.isConnected,cleanup=>{layer.navigationPreparationCleanup=cleanup})}function setPageVisibility(target,hidden){if(target===window){links.getBridgeProtocol().handlePageVisibility(hidden);return}try{target.postMessage({source:SRC,type:"simulatorVisibility",hidden},"*")}catch{}}function openLayer(url2,callbackId,overlay,openerWin,pushHistory,popId=null,animateEntry=!0){clearPendingClose();let target=url2;if(!/^https?:/i.test(target)){let mapped=links.getBridgeProtocol().mapScheme(target);if(!mapped)return log2("open 失败,scheme 未映射:",url2),null;target=mapped}location.protocol==="https:"&&target.startsWith("http:")&&(target="https:"+target.slice(5));let presentation=overlay??resolveOverlayPresentation(target,void 0,!1);log2("open →",presentation?"(webdialog) ":"",target);let parts=createLayerEl(presentation,++layerSeq),restoredTitleBarState=explicitLayerTitleBarStates.get(titleBarStateCacheKey(target)),layer={id:layerSeq,win:parts.frame.contentWindow,frame:parts.frame,entryUrl:target,url:target,overlay:presentation,openerWin,callbackId,storageId:parseStorageId(target),popId,el:parts.el,animEl:parts.animEl,mask:parts.mask,entering:animateEntry,enterTimer:null,enterTransitionEnd:null,closing:!1,navigationPreparationCleanup:null,titleBarState:restoredTitleBarState??initialLayerTitleBarState(target),titleBarStateExplicit:restoredTitleBarState!==void 0,titleBarStateReady:restoredTitleBarState!==void 0,titleBarView:null};if(popId&&layer.el.setAttribute("data-mearl-pop-id",popId),layer.mask&&presentation?.tapClose&&layer.mask.addEventListener("click",()=>requestOverlayClose(layer)),!presentation&&simulateSystemBars&&config2.titleBar&&(layer.titleBarView=createSimulatedNavigationBarView("layer",()=>requestNativeBack()),layer.titleBarView.root.setAttribute("data-mearl-layer-titlebar",String(layer.id)),parts.el.appendChild(layer.titleBarView.root)),layers.push(layer),splitScreenActive&&rootFrame?.contentWindow===openerWin||setPageVisibility(openerWin,!0),animateEntry&&(enteringLayerCount+=1),syncLayerViewport(layer,layer.titleBarState),syncLayerInteractivity(),parts.frame.addEventListener("load",()=>{layer.win=parts.frame.contentWindow,parts.frame.name=LAYER_FRAME_NAME;let committedSrc=parts.frame.getAttribute("src");!committedSrc||committedSrc==="about:blank"||(syncSimulatorStateToWindow(parts.frame.contentWindow),requestAnimationFrame(()=>{layer.titleBarStateReady||layer.closing||!layer.el.isConnected||(layer.titleBarStateReady=!0,syncLayerViewport(layer,resolvedTitleBarState(layer)))}))}),(document.body??document.documentElement).appendChild(parts.el),layer.win=parts.frame.contentWindow,startLayerNavigation(layer,mapLayerFrameUrl(target)),animateEntry&&animateIn(layer),pushHistory){forwardStack.length=0;try{history.pushState({__mearl_layer__:layers.length},"",mapUrlForSync(target))}catch{}}return layer}function replaceLayer(sourceLayer,url2,callbackId,overlay,popId=null){if(sourceLayer.closing||layers[layers.length-1]!==sourceLayer){openLayer(url2,callbackId,overlay,sourceLayer.win??window,!0,popId);return}let replacement=openLayer(url2,callbackId,overlay,sourceLayer.openerWin,!1,popId);if(!replacement)return;sourceLayer.navigationPreparationCleanup?.(),sourceLayer.navigationPreparationCleanup=null,sourceLayer.entering&&(sourceLayer.entering=!1,enteringLayerCount=Math.max(enteringLayerCount-1,0),sourceLayer.enterTimer!==null&&clearTimeout(sourceLayer.enterTimer),sourceLayer.enterTransitionEnd&&sourceLayer.animEl.removeEventListener("transitionend",sourceLayer.enterTransitionEnd));let sourceIndex=layers.indexOf(sourceLayer);sourceIndex>=0&&layers.splice(sourceIndex,1),destroySimulatedNavigationBarView(sourceLayer.titleBarView),sourceLayer.el.remove(),forwardStack.length=0,syncLayerInteractivity(),syncActiveSystemBars();try{history.replaceState({__mearl_layer__:layers.length},"",mapUrlForSync(replacement.url))}catch{}}function closeLayer(layer,data,final,gotoEvent=!1,resumeOpener=!0,silent=!1,immediate=!1){if(layer.closing)return;layer.navigationPreparationCleanup?.(),layer.navigationPreparationCleanup=null,layer.entering&&(layer.entering=!1,enteringLayerCount=Math.max(enteringLayerCount-1,0),layer.enterTimer!==null&&clearTimeout(layer.enterTimer),layer.enterTimer=null,layer.enterTransitionEnd&&(layer.animEl.removeEventListener("transitionend",layer.enterTransitionEnd),layer.enterTransitionEnd=null)),layer.closing=!0;let idx=layers.indexOf(layer);idx>=0&&layers.splice(idx,1),closingLayerCount+=1,blockClosingLayerInteractions(layer),syncLayerInteractivity(),syncActiveSystemBars(),final?forwardStack.length=0:forwardStack.push({url:layer.url,overlay:layer.overlay,openerWin:layer.openerWin,callbackId:layer.callbackId,storageId:layer.storageId,popId:layer.popId}),log2("close ←",layer.url,data===void 0?"":data);let finishClose=()=>{if(destroySimulatedNavigationBarView(layer.titleBarView),layer.el.remove(),closingLayerCount=Math.max(closingLayerCount-1,0),syncLayerInteractivity(),syncActiveSystemBars(),!!resumeOpener)if(layer.openerWin===window)links.getBridgeProtocol().handleResume({data,storageId:layer.storageId,callbackId:layer.callbackId,final,gotoEvent,silent});else try{layer.openerWin.postMessage({source:SRC,type:"resume",data,storageId:layer.storageId,callbackId:layer.callbackId,final,gotoEvent,silent},"*")}catch{}};immediate?finishClose():animateOut(layer,finishClose)}function closeToDepth(depth,data,final){for(;layers.length>depth;){let revealsTarget=layers.length===depth+1;closeLayer(layers[layers.length-1],revealsTarget?data:void 0,final,!1,revealsTarget)}}function closeAllLayers(data,gotoEvent=!1,silent=!1,immediate=!1){let depth=layers.length;for(;layers.length>0;){let isRootmostLayer=layers.length===1;closeLayer(layers[layers.length-1],isRootmostLayer?data:void 0,!0,isRootmostLayer&&gotoEvent,isRootmostLayer,silent,immediate)}if(depth>0)try{history.go(-depth)}catch{}return depth>0}function openFromSplitRoot(url2,callbackId,overlay,openerWin,popId){if(pendingSplitRootOpen){pendingSplitRootOpen={url:url2,callbackId,overlay,openerWin,popId};return}if(layers.length===0){openLayer(url2,callbackId,overlay,openerWin,!0,popId);return}pendingSplitRootOpen={url:url2,callbackId,overlay,openerWin,popId},closeAllLayers(void 0,!1,!0,!0)}function finishPendingSplitRootOpen(){let pending=pendingSplitRootOpen;pending&&(pendingSplitRootOpen=null,openLayer(pending.url,pending.callbackId,pending.overlay,pending.openerWin,!0,pending.popId,!1))}function requestOverlayClose(layer){if(!(layer.closing||layers[layers.length-1]!==layer)){if(!config2.overlay?.silentTapClose){for(let selector of config2.overlay?.tapCloseSelectors??[])try{let control=layer.frame.contentDocument?.querySelector(selector);if(typeof control?.click!="function")continue;control.click();return}catch{}requestCloseOnTop(void 0);return}pendingClose||pendingHistoryDepth||(closeLayer(layer,void 0,!0,!1,!0,!0),syncHistoryAfterDirectClose())}}function forwardToDepth(depth){for(;layers.length<depth&&forwardStack.length>0;){let entry=forwardStack.pop();openLayer(entry.url,entry.callbackId,entry.overlay,entry.openerWin,!1,entry.popId)}}function requestCloseOnTop(data){if(layers.length===0){history.back();return}if(rootContainerActive){closeLayer(layers[layers.length-1],data,!0),syncHistoryAfterDirectClose();return}armPendingClose(data,8)}function isActiveBusinessWindow(target){let topLayer=layers[layers.length-1];return topLayer?topLayer.frame.contentWindow===target:rootFrame?rootFrame.contentWindow===target:target===window}function finishNativeBack(requestId,target,handled){pendingNativeBack?.requestId!==requestId||pendingNativeBack.target!==target||(clearPendingNativeBack(),!handled&&isActiveBusinessWindow(target)&&requestCloseOnTop(void 0))}function requestNativeBack(){if(!isTop||pendingNativeBack)return;let target=layers[layers.length-1]?.frame.contentWindow??rootFrame?.contentWindow??window;if(!target||target===window){links.getBridgeProtocol().handleNativeBack()||requestCloseOnTop(void 0);return}let requestId=++nativeBackRequestSeq,timer=setTimeout(()=>finishNativeBack(requestId,target,!1),120);pendingNativeBack={requestId,target,timer};try{target.postMessage({source:SRC,type:"nativeBack",requestId},"*")}catch{finishNativeBack(requestId,target,!1)}}function layerForWindow(source){if(source)for(let layer of layers){if(layer.win===source)return layer;let currentWindow=layer.frame.contentWindow;if(currentWindow&&currentWindow===source)return layer.win=currentWindow,layer}}if(isTop){if(!rootContainerActive){let rawPushState=history.pushState.bind(history),rawReplaceState=history.replaceState.bind(history),withDepth=state=>state==null?{__mearl_layer__:layers.length}:typeof state=="object"&&!Array.isArray(state)?{...state,__mearl_layer__:layers.length}:state;try{history.pushState=function(...args){rawPushState(withDepth(args[0]),args[1],args[2])},history.replaceState=function(...args){rawReplaceState(withDepth(args[0]),args[1],args[2])}}catch{}}try{readDepth(history.state)===null&&history.replaceState({__mearl_layer__:0},"")}catch{}window.addEventListener("popstate",e=>{let depth=readDepth(e.state);if(pendingSplitRootOpen&&depth===0){finishPendingSplitRootOpen();return}if(pendingHistoryDepth){let expectedDepth=pendingHistoryDepth.depth;if(clearPendingHistoryDepth(),depth===expectedDepth)return;console.warn(TAG,"浏览器历史深度与 WebView 出栈事务不一致",{expectedDepth,actualDepth:depth})}if(rootContainerActive){if(depth===null)return;depth<layers.length?closeToDepth(depth,void 0,!1):depth>layers.length&&forwardToDepth(depth);return}if(pendingClose){if(depth!==null&&depth<layers.length){let{data}=pendingClose;clearPendingClose(),closeToDepth(depth,data,!0)}else if(pendingClose.retries>0)armPendingClose(pendingClose.data,pendingClose.retries-1);else{let{data}=pendingClose;clearPendingClose(),closeToDepth(layers.length-1,data,!0)}return}depth!==null&&(depth<layers.length?closeToDepth(depth,void 0,!1):depth>layers.length&&forwardToDepth(depth))})}function broadcastAppMessage(message){links.getBridgeProtocol().handleAppMessage(message);let targets=[rootFrame?.contentWindow??null,...layers.filter(layer=>!layer.closing).map(layer=>layer.frame.contentWindow)];for(let target of targets)if(!(!target||target===window))try{target.postMessage({source:SRC,type:"appMessage",message},"*")}catch{}}function closeMegaPop(popId,data){let index=layers.findIndex(layer=>layer.popId===popId&&!layer.closing);if(index<0)return!1;let closingDepth=layers.length-index;closeToDepth(index,data,!0);try{history.go(-closingDepth)}catch{}return!0}function resizeMegaPop(popId,params){let layer=layers.find(candidate=>candidate.popId===popId&&!candidate.closing);if(!layer?.overlay)return!1;if(params.maxHeight!==void 0){let maxHeight=numberParam(params.maxHeight,1-layer.overlay.topRatio,0,1);layer.overlay.topRatio=1-maxHeight,layer.animEl.style.height=`${maxHeight*100}%`}if(params.maxWidth!==void 0){let maxWidth=numberParam(params.maxWidth,1,0,1);layer.overlay.widthRatio=maxWidth,layer.animEl.style.width=`${maxWidth*100}%`,layer.animEl.style.left=`${(1-maxWidth)/2*100}%`,layer.animEl.style.right="auto"}return params.animated===!0&&(layer.animEl.style.transition="height 200ms ease, width 200ms ease, left 200ms ease"),!0}function executeContainerData(action,params){if(action==="sharedFileRead"||action==="sharedFileWrite"){let fileName=typeof params.fileName=="string"?params.fileName:"";if(!fileName)return{success:!1,value:"missing fileName"};if(action==="sharedFileRead")return{success:!0,value:{data:sharedFiles.get(fileName)??""}};let data=typeof params.data=="string"?params.data:String(params.data??"");return sharedFiles.set(fileName,data),{success:!0,value:{}}}if(action==="sharedDataGet"){let keys=Array.isArray(params.keys)?params.keys.filter(key=>typeof key=="string"):[],data={};for(let key of keys)sharedData.has(key)&&(data[key]=sharedData.get(key));return{success:!0,value:{data}}}if(action==="sharedDataSet"){if(!params.data||typeof params.data!="object"||Array.isArray(params.data))return{success:!1,value:"missing shared data"};for(let[key,value]of Object.entries(params.data))value==null?sharedData.delete(key):sharedData.set(key,value);return{success:!0,value:{}}}if(action==="megaBroadcast")return!params.message||typeof params.message!="object"||Array.isArray(params.message)?{success:!1,value:"missing broadcast message"}:(broadcastAppMessage(params.message),{success:!0,value:{}});if(action==="megaKVSnapshot")return{success:!0,value:{entries:megaKVSnapshot()}};if(action==="megaKVMutation"){let operation=typeof params.operation=="string"?params.operation:"",bizId=typeof params.bizId=="string"?params.bizId:"";if(!bizId)return{success:!1,value:"missing bizID"};let key=typeof params.key=="string"?params.key:"";if((operation==="set"||operation==="remove")&&!key)return{success:!1,value:"missing key"};if(operation==="set"){if(typeof params.value!="string")return{success:!1,value:"missing value"};let entries=megaKVStorage.get(bizId)??new Map;entries.set(key,params.value),megaKVStorage.set(bizId,entries)}else if(operation==="remove"){let entries=megaKVStorage.get(bizId);entries?.delete(key),entries?.size===0&&megaKVStorage.delete(bizId)}else if(operation==="clear")megaKVStorage.delete(bizId);else return{success:!1,value:"unsupported KVStorage operation"};return persistMegaKVStorage(),broadcastAppMessage({kind:"megaKVStorage",operation,bizId,key,value:params.value}),{success:!0,value:{}}}if(action==="legacyBroadcastCreate"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?(legacyBroadcastChannels.add(instanceId),{success:!0,value:{}}):{success:!1,value:"missing instanceId"}}if(action==="legacyBroadcastPost"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?legacyBroadcastChannels.has(instanceId)?(broadcastAppMessage({kind:"legacyBroadcast",instanceId,message:params.message}),{success:!0,value:{}}):{success:!1,value:"broadcast channel not found"}:{success:!1,value:"missing instanceId"}}if(action==="legacyBroadcastClose"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?(legacyBroadcastChannels.delete(instanceId),{success:!0,value:{}}):{success:!1,value:"missing instanceId"}}if(action==="megaPopClose"){let popId=typeof params.popId=="string"?params.popId:"";return popId?closeMegaPop(popId,params.result)?{success:!0,value:{}}:{success:!1,value:"popId not found"}:{success:!1,value:"missing popId"}}if(action==="megaPopResize"){let popId=typeof params.popId=="string"?params.popId:"";return popId?resizeMegaPop(popId,params)?{success:!0,value:{}}:{success:!1,value:"popId not found"}:{success:!1,value:"missing popId"}}return{success:!1,value:"unsupported container data action"}}function requestContainerData(action,params,onSuccess,onFailure){if(isTop){let result=executeContainerData(action,params);setTimeout(()=>result.success?onSuccess(result.value):onFailure(result.value),0);return}let requestId=++containerDataRequestSeq;containerDataCallbacks.set(requestId,{success:onSuccess,failure:onFailure});try{window.top?.postMessage({source:SRC,type:"containerDataRequest",requestId,action,params},"*")}catch(error48){containerDataCallbacks.delete(requestId),onFailure(error48 instanceof Error?error48.message:String(error48))}}function requestOpen(url2,callbackId,webdialog,params){let overlay=resolveOverlayPresentation(url2,params,webdialog),popBeforeOpen=requestsPopBeforeOpen(url2,params),popId=typeof params?.__mearlMegaPopId=="string"?params.__mearlMegaPopId:null;isTop?openLayer(url2,callbackId,overlay,window,!0,popId):window.top?.postMessage({source:SRC,type:"open",url:url2,callbackId,overlay,popBeforeOpen,popId},"*")}function requestClose(data){let payload;try{payload=data===void 0?void 0:JSON.parse(JSON.stringify(data))}catch{payload=void 0}isTop?requestCloseOnTop(payload):window.top?.postMessage({source:SRC,type:"close",data:payload},"*")}if(window.addEventListener("message",event=>{let msg=event.data;if(!(!msg||typeof msg!="object")){if(msg.source==="mearl-content"&&(msg.type==="APP_BRIDGE_SIMULATOR_VISIBILITY"||msg.type==="APP_BRIDGE_RUNTIME_RESPONSES")){if(!isTop||event.source!==window)return;if(msg.type==="APP_BRIDGE_SIMULATOR_VISIBILITY"&&typeof msg.hidden=="boolean"){simulatedPageHidden=msg.hidden,links.getBridgeProtocol().handlePageVisibility(msg.hidden);let lifecycleMessage={source:SRC,type:"simulatorVisibility",hidden:msg.hidden};rootFrame?.contentWindow?.postMessage(lifecycleMessage,"*");for(let layer of layers)layer.closing||layer.frame.contentWindow?.postMessage(lifecycleMessage,"*")}else if(msg.type==="APP_BRIDGE_RUNTIME_RESPONSES"&&msg.profile===config2.profile&&msg.responses&&typeof msg.responses=="object"&&!Array.isArray(msg.responses)){let responses=msg.responses;runtimeResponses={...runtimeResponses??{},...responses},links.getBridgeProtocol().applyRuntimeResponses(responses);let configMessage={source:SRC,type:"runtimeResponses",profile:config2.profile,responses};rootFrame?.contentWindow?.postMessage(configMessage,"*");for(let layer of layers)layer.closing||layer.frame.contentWindow?.postMessage(configMessage,"*")}return}if(msg.source===SRC){if(isTop){let sourceLayer=layerForWindow(event.source),sourceIsRoot=!!(rootFrame?.contentWindow&&rootFrame.contentWindow===event.source);if(!sourceLayer&&!sourceIsRoot)return;if(msg.type==="open"&&typeof msg.url=="string"){let rawOverlay=msg.overlay&&typeof msg.overlay=="object"?msg.overlay:void 0,overlay=rawOverlay?{topRatio:numberParam(rawOverlay.topRatio,.2,0,1),widthRatio:numberParam(rawOverlay.widthRatio,1,0,1),radius:numberParam(rawOverlay.radius,0,0,50),maskAlpha:numberParam(rawOverlay.maskAlpha,.3,0,1),tapClose:boolParam(rawOverlay.tapClose,!0)}:resolveOverlayPresentation(msg.url,void 0,!1),callbackId=typeof msg.callbackId=="number"?msg.callbackId:0,popId=typeof msg.popId=="string"&&msg.popId?msg.popId:null;splitScreenActive&&sourceIsRoot?openFromSplitRoot(msg.url,callbackId,overlay,event.source??window,popId):msg.popBeforeOpen===!0&&sourceLayer?replaceLayer(sourceLayer,msg.url,callbackId,overlay,popId):openLayer(msg.url,callbackId,overlay,event.source??window,!0,popId)}else if(msg.type==="close")requestCloseOnTop(msg.data);else if(msg.type==="closeAll"){let gotoEvent=msg.gotoEvent===!0;if(gotoEvent&&sourceIsRoot&&layers.length===0&&msg.data!==void 0)try{event.source.postMessage({source:SRC,type:"resume",data:msg.data,storageId:null,callbackId:0,final:!0,gotoEvent:!0},"*")}catch{}else closeAllLayers(msg.data,gotoEvent)}else if(msg.type==="appMessageToOpener"&&sourceLayer){let target=sourceLayer.openerWin;if(target===window)links.getBridgeProtocol().handleAppMessage(msg.message);else try{target.postMessage({source:SRC,type:"appMessage",message:msg.message},"*")}catch{}}else if(msg.type==="containerDataRequest"&&typeof msg.requestId=="number"&&typeof msg.action=="string"&&msg.params&&typeof msg.params=="object"&&!Array.isArray(msg.params)&&event.source){let result=executeContainerData(msg.action,msg.params);try{event.source.postMessage({source:SRC,type:"containerDataResponse",requestId:msg.requestId,success:result.success,value:result.value},"*")}catch{}}else if(msg.type==="nativeBackResult"&&typeof msg.requestId=="number"&&typeof msg.handled=="boolean"&&event.source)finishNativeBack(msg.requestId,event.source,msg.handled);else if(msg.type==="urlChanged"&&typeof msg.url=="string"){let topLayer=layers[layers.length-1];if(sourceIsRoot&&!topLayer){rootBusinessUrl=msg.url;let mapped=mapUrlForSync(msg.url);if(mapped)try{history.replaceState({__mearl_layer__:0},"",mapped)}catch{}}else if(topLayer&&!topLayer.closing&&sourceLayer===topLayer){topLayer.url=msg.url,topLayer.titleBarStateExplicit&&topLayer.titleBarState&&cacheExplicitTitleBarState(topLayer,topLayer.titleBarState);let mapped=mapUrlForSync(msg.url);if(mapped)try{history.replaceState({__mearl_layer__:layers.length},"",mapped)}catch{}}}else if(msg.type==="title"&&typeof msg.title=="string"){let topLayer=layers[layers.length-1];if(sourceIsRoot&&!topLayer)try{document.title=msg.title,syncSimulatedTitleBar()}catch{}else if(topLayer&&sourceLayer===topLayer){document.title=msg.title;let state=resolvedTitleBarState(topLayer);topLayer.titleBarState={...state,title:msg.title},syncLayerViewport(topLayer,topLayer.titleBarState)}}else if(msg.type==="titleBarState"){let state=parseReportedTitleBarState(msg.state);if(state&&sourceIsRoot)links.getSystemBars().setPresentedRootTitleBarState(state);else if(state&&sourceLayer){let explicit=msg.explicit===!0;sourceLayer.titleBarStateReady=!0,explicit?(sourceLayer.titleBarState=state,sourceLayer.titleBarStateExplicit=!0,cacheExplicitTitleBarState(sourceLayer,state)):sourceLayer.titleBarStateExplicit||(sourceLayer.titleBarState=state);let resolvedState=sourceLayer.titleBarState??state;syncLayerViewport(sourceLayer,resolvedState)}}}else if(msg.type==="requestTitleBarState"){if(event.source!==window.top)return;syncSimulatedTitleBar()}else if(msg.type==="simulatorVisibility"&&typeof msg.hidden=="boolean"){if(event.source!==window.top)return;links.getBridgeProtocol().handlePageVisibility(msg.hidden)}else if(msg.type==="appMessage"){if(event.source!==window.top)return;links.getBridgeProtocol().handleAppMessage(msg.message)}else if(msg.type==="nativeBack"&&typeof msg.requestId=="number"){if(event.source!==window.top)return;let handled=links.getBridgeProtocol().handleNativeBack();window.top?.postMessage({source:SRC,type:"nativeBackResult",requestId:msg.requestId,handled},"*")}else if(msg.type==="containerDataResponse"&&typeof msg.requestId=="number"){if(event.source!==window.top)return;let callback=containerDataCallbacks.get(msg.requestId);if(!callback)return;containerDataCallbacks.delete(msg.requestId),msg.success===!0?callback.success(msg.value):callback.failure(msg.value)}else if(msg.type==="runtimeResponses"&&msg.profile===config2.profile&&msg.responses&&typeof msg.responses=="object"&&!Array.isArray(msg.responses)){if(event.source!==window.top)return;links.getBridgeProtocol().applyRuntimeResponses(msg.responses)}else if(msg.type==="resume"){if(event.source!==window.top)return;links.getBridgeProtocol().handleResume({data:msg.data,storageId:msg.storageId??null,callbackId:typeof msg.callbackId=="number"?msg.callbackId:0,final:msg.final===!0,gotoEvent:msg.gotoEvent===!0,silent:msg.silent===!0})}else event.source!==window.top&&window.top?.postMessage(msg,"*");return}pageTransport.handleMessage(msg)}}),!isTop&&isContainerFrame){let reportUrl=()=>{try{window.top?.postMessage({source:SRC,type:"urlChanged",url:restoreLayerBusinessUrl(location.href)},"*")}catch{}};try{let origPushState=history.pushState.bind(history),origReplaceState=history.replaceState.bind(history);history.pushState=function(...args){origPushState(...args),reportUrl()},history.replaceState=function(...args){origReplaceState(...args),reportUrl()},window.addEventListener("popstate",reportUrl),window.addEventListener("hashchange",reportUrl)}catch{}}if(isContainerFrame){let requestProxyLocationOpen=url2=>{if(links.getBridgeProtocol().handleMaybeScheme(url2))return!0;try{let current=new URL(restoreLayerBusinessUrl(location.href)),target=new URL(url2,current);return!/^https?:$/.test(target.protocol)||target.origin===current.origin&&target.pathname===current.pathname&&target.search===current.search?!1:(requestOpen(target.href,0,!1),!0)}catch{return!1}};Object.defineProperty(window,"__PROXY_LOCATION__",{value:{get href(){return location.href},set href(url2){requestProxyLocationOpen(url2)||(location.href=mapLayerFrameUrl(url2))},replace(url2){links.getBridgeProtocol().handleMaybeScheme(url2)||location.replace(mapLayerFrameUrl(url2))},assign(url2){requestProxyLocationOpen(url2)||location.assign(mapLayerFrameUrl(url2))}},writable:!1,configurable:!0})}if(isContainerFrame){document.addEventListener("click",event=>{let el=event.target;for(;el&&el.tagName!=="A";)el=el.parentElement;if(!el)return;let href=el.getAttribute("href");if(href){if(links.getBridgeProtocol().handleMaybeScheme(href)){event.preventDefault(),event.stopPropagation();return}/^https?:/i.test(href)&&el.getAttribute("target")==="_blank"&&(event.preventDefault(),event.stopPropagation(),requestOpen(href,0,!1))}},!0);let origOpen=window.open;window.open=function(url2,target,features){let urlStr=typeof url2=="string"?url2:url2 instanceof URL?url2.href:"";return links.getBridgeProtocol().handleMaybeScheme(urlStr)?null:/^https?:/i.test(urlStr)?(requestOpen(urlStr,0,!1),null):origOpen?origOpen.call(window,url2,target,features):null};try{let proto=Location.prototype,origAssign=proto.assign,origReplace=proto.replace;origAssign&&(proto.assign=function(url2){if(links.getBridgeProtocol().handleMaybeScheme(url2))return;let upgraded=location.protocol==="https:"&&url2.startsWith("http:")?"https:"+url2.slice(5):url2;origAssign.call(this,upgraded)}),origReplace&&(proto.replace=function(url2){if(links.getBridgeProtocol().handleMaybeScheme(url2))return;let upgraded=location.protocol==="https:"&&url2.startsWith("http:")?"https:"+url2.slice(5):url2;origReplace.call(this,upgraded)})}catch{}}return log2("容器环境已就绪",isTop?"(top)":isRootFrame?"(root)":isLayerFrame?"(layer)":"(iframe,仅桥)"),{getRootFrame:()=>rootFrame,getLayers:()=>layers,getClosingLayerCount:()=>closingLayerCount,requestOpen,requestClose,requestNativeBack,requestContainerData,closeAllLayers}}var APP_PROFILE_RUNTIME_FACTORIES={environment:installAppProfileEnvironment,containerStack:installAppProfileContainerStack,bridgeProtocol:installAppProfileBridgeProtocol,pageTransport:installAppProfilePageTransport,systemBars:installAppProfileSystemBars};function buildAppProfileRuntimeCallSource(configExpression){return`(${installAppProfileRuntime.toString()})(${configExpression},{environment:${installAppProfileEnvironment.toString()},pageTransport:${installAppProfilePageTransport.toString()},containerStack:${installAppProfileContainerStack.toString()},systemBars:${installAppProfileSystemBars.toString()},bridgeProtocol:${installAppProfileBridgeProtocol.toString()}})`}function installAppProfileRuntime(config2,factories=APP_PROFILE_RUNTIME_FACTORIES){let environment=factories.environment(config2);if(!environment)return;let pageTransport=factories.pageTransport(config2,environment),containerStack=factories.containerStack(config2,environment,{pageTransport,getSystemBars:()=>systemBars,getBridgeProtocol:()=>bridgeProtocol}),systemBars=factories.systemBars(config2,environment,{getRootFrame:containerStack.getRootFrame,getLayers:containerStack.getLayers,getClosingLayerCount:containerStack.getClosingLayerCount,requestClose:containerStack.requestClose,requestNativeBack:containerStack.requestNativeBack}),bridgeProtocol=factories.bridgeProtocol(config2,environment,{pageTransport,systemBars,requestOpen:containerStack.requestOpen,requestClose:containerStack.requestClose,requestCloseAll:containerStack.closeAllLayers,requestContainerData:containerStack.requestContainerData})}import https from"node:https";import http3 from"node:http";function installDeviceChromeView(root,config2,options={}){let ownerDocument=root.ownerDocument,browser=ownerDocument.defaultView??window,NativeDate=browser.Date,nativeNow=NativeDate.now.bind(NativeDate),labels={screenshot:"Screenshot",copied:"Copied",downloaded:"Downloaded",captureFailed:"Capture failed",bottomAction:"App simulation settings",...options.labels},state={statusBarVisible:!0,statusBarBackground:"#ffffff",textColor:"#0f131a",bottomActionEnabled:!1,timeOffsetMs:null,...options.initialState},normalizedBarHeight=value=>Number.isFinite(value)?Math.min(200,Math.max(0,Math.round(value))):0,statusBarHeight=normalizedBarHeight(config2.statusBarHeight),bottomBarHeight=normalizedBarHeight(config2.bottomBarHeight),cutout=config2.platform==="ios"?config2.cutout:"none",cutoutMarkup=cutout==="none"?"":cutout==="dynamic-island"?`<button id="device-cutout" type="button" data-kind="${cutout}" data-state="idle"><svg id="cutout-camera" viewBox="0 0 20 20" aria-hidden="true"><path d="M6.5 5.5 7.7 3.8h4.6l1.2 1.7h2.2c1 0 1.8.8 1.8 1.8v7c0 1-.8 1.8-1.8 1.8H4.3c-1 0-1.8-.8-1.8-1.8v-7c0-1 .8-1.8 1.8-1.8z"/><circle cx="10" cy="10.5" r="3.2"/></svg><svg id="cutout-check" viewBox="0 0 20 20" aria-hidden="true"><path d="m4.5 10.5 3.2 3.2 7.8-7.8"/></svg></button>`:`<span id="device-cutout" data-kind="${cutout}" aria-hidden="true"></span>`;root.innerHTML=`<style>
179
179
  :host {
180
180
  all: initial !important;
181
181
  position: fixed !important;
@@ -513,7 +513,7 @@ Content-Type: ${file2.contentType}\r
513
513
  \r
514
514
  `),file2.content,Buffer.from(`\r
515
515
  `))}return chunks.push(Buffer.from(`--${boundary}--\r
516
- `)),{contentType:`multipart/form-data; boundary=${boundary}`,body:Buffer.concat(chunks)}}function hasMultipartPayload(data){return data.formData!==void 0||data.files!==void 0}async function executeNodeSendRequest(data,cookieMap=new Map){let{url:url2,method="GET",headers={},params,body,formData,files,responseType="auto",timeout=3e4}=data;if(!url2||typeof url2!="string"||url2.trim()==="")throw new Error("Invalid url: url must be a non-empty string");let normalizedMethod=method.toUpperCase();if(!ALLOWED_METHODS.has(normalizedMethod))throw new Error(`Invalid method: ${method}. Allowed: ${[...ALLOWED_METHODS].join(", ")}`);if(!Number.isFinite(timeout)||timeout<=0)throw new Error("timeout must be a positive number");let targetUrl=new URL(url2);for(let[key,value]of Object.entries(params??{}))targetUrl.searchParams.set(key,String(value));let requestHeaders={Accept:"application/json, text/plain, */*","Accept-Language":"zh-CN,zh;q=0.9,en;q=0.8","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",...headers},resolvedSourceHeaders=getSendRequestSourceHeaders(targetUrl,headers);resolvedSourceHeaders.referer?setHeader(requestHeaders,"Referer",resolvedSourceHeaders.referer):removeHeader(requestHeaders,"Referer"),resolvedSourceHeaders.origin?setHeader(requestHeaders,"Origin",resolvedSourceHeaders.origin):removeHeader(requestHeaders,"Origin");let cookieHeader=[...cookieMap.entries()].map(([key,value])=>`${key}=${value}`).join("; ");cookieHeader&&setHeader(requestHeaders,"Cookie",cookieHeader);let xsrfToken=cookieMap.get("XSRF-TOKEN");xsrfToken&&!findSendRequestHeaderName(requestHeaders,"x-xsrf-token")&&setHeader(requestHeaders,"X-XSRF-TOKEN",xsrfToken);let requestBody;if(hasMultipartPayload(data)){if(body!=null)throw new Error("body cannot be combined with formData or files");if(normalizedMethod==="GET"||normalizedMethod==="HEAD")throw new Error(`${normalizedMethod} requests cannot use formData or files`);if(findSendRequestHeaderName(requestHeaders,"content-type"))throw new Error("Do not set Content-Type when using formData or files; Mearl sets the boundary");let multipart=await buildMultipartBody(formData,files);requestBody=multipart.body,setHeader(requestHeaders,"Content-Type",multipart.contentType),setHeader(requestHeaders,"Content-Length",String(multipart.body.byteLength))}else body!=null&&!["GET","HEAD"].includes(normalizedMethod)&&(typeof body=="string"?(requestBody=body,findSendRequestHeaderName(requestHeaders,"content-type")||setHeader(requestHeaders,"Content-Type","text/plain")):(requestBody=JSON.stringify(body),findSendRequestHeaderName(requestHeaders,"content-type")||setHeader(requestHeaders,"Content-Type","application/json")));let result=await nodeFetch(targetUrl.toString(),{method:normalizedMethod,headers:requestHeaders,body:requestBody,timeoutMs:timeout}),contentType=(result.headers["content-type"]??"").split(";")[0].trim().toLowerCase(),responseHeaders=Object.fromEntries(Object.entries(result.headers).filter(([name])=>name.toLowerCase()!=="set-cookie"&&name.toLowerCase()!=="set-cookie2")),responseBody,bodyType;if(responseType==="auto"&&isBinarySendRequestContentType(contentType))responseBody=result.bodyBuffer.toString("base64"),bodyType="base64";else{let trimmed=result.body.trimStart();if(responseType==="json"||responseType==="auto"&&contentType.includes("application/json")||responseType==="auto"&&(trimmed.startsWith("{")||trimmed.startsWith("[")))try{responseBody=JSON.parse(result.body),bodyType="json"}catch{if(responseType==="json")throw new Error("send_request expected a JSON response");responseBody=result.body,bodyType="text"}else responseBody=result.body,bodyType="text"}return{success:!0,status:result.status,statusText:result.statusText,headers:responseHeaders,body:responseBody,bodyType,attachedCookieCount:cookieMap.size}}async function cdpSendRequest(session,data){if(!data.url||typeof data.url!="string")throw new Error("Invalid url: url must be a non-empty string");let cookieMap=new Map;if(data.withCookies!==!1)try{cookieMap=await getCookiesForUrl(session,new URL(data.url).toString())}catch{}return executeNodeSendRequest(data,cookieMap)}async function prepareCdpMtopRequest(session,data,stream=!1){let resolved=resolveMtopRequest(data),cookieMap=await getCookiesForUrl(session,resolved.gatewayUrl.toString()),prepared=prepareSignedMtopRequest(resolved,cookieMap,stream);return{...prepared,requestHeaders:{...prepared.cookieHeader?{Cookie:prepared.cookieHeader}:{},...prepared.requestHeaders}}}async function cdpSendMtopRequest(session,data){let prepared=await prepareCdpMtopRequest(session,data),result=await nodeFetch(prepared.targetUrl.toString(),{method:prepared.normalizedMethod,headers:prepared.requestHeaders,body:prepared.body,timeoutMs:prepared.timeout});return{success:!0,response:parseMtopResponseText(result.body),requestData:prepared.requestData}}async function cdpSendMtopStreamRequest(session,data,callbacks){let prepared=await prepareCdpMtopRequest(session,data,!0),controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),prepared.timeout);try{await callbacks.onRequestPrepared?.({method:prepared.normalizedMethod,url:prepared.targetUrl.toString(),requestHeaders:Object.entries(prepared.requestHeaders).map(([name,value])=>({name,value}))});let response=await fetch(prepared.targetUrl,{method:prepared.normalizedMethod,headers:prepared.requestHeaders,body:prepared.body,signal:controller.signal}),responseHeaders=[];return response.headers.forEach((value,name)=>{name.toLowerCase()!=="set-cookie"&&responseHeaders.push({name,value})}),await callbacks.onResponse?.({status:response.status,statusText:response.statusText,responseHeaders}),{success:!0,response:await consumeMtopSseResponse(response,event=>callbacks.onReceive(event.data)),requestData:prepared.requestData}}catch(error48){throw error48 instanceof Error&&error48.name==="AbortError"?new Error(`send_mtop_stream timed out after ${prepared.timeout}ms: ${prepared.api}`,{cause:error48}):new Error(`send_mtop_stream failed: ${error48 instanceof Error?error48.message:String(error48)}`,{cause:error48})}finally{clearTimeout(timeoutId)}}registerActions([{name:"send_request",session:"page",handler:cdpSendRequest},{name:"send_mtop_request",session:"page",handler:cdpSendMtopRequest}]);var registries=new WeakMap;function getPageRefRegistry(session){let registry2=registries.get(session);if(!registry2){registry2=new BackendNodeRefRegistry,registries.set(session,registry2);let activeRegistry=registry2;session.client.on("Page.frameNavigated",params=>{params.frame?.parentId||activeRegistry.clearDocument()})}return registry2}function beginPageSnapshotRefs(session){return getPageRefRegistry(session).beginSnapshot()}function resolvePageRef(session,ref){return registries.get(session)?.resolve(ref)}function deletePageRef(session,ref){registries.get(session)?.delete(ref)}function clearPageRefsForNavigation(session){registries.get(session)?.clearDocument()}async function enrichCdpPageChangeSetWithRefs(session,observation){return enrichPageChangeSetWithRefs(observation,getPageRefRegistry(session),selectors=>resolveUniqueBackendNodeIds((method,params)=>sendCdpDeviceShellPageCommand(session,method,params),selectors),(node,backendNodeId)=>({backendNodeId,role:node.role??"",name:node.name??""}))}var APP_PROFILE_BINDING="__mearlCdpAppProfileRelay",APP_PROFILE_RESTORE_HINT="__mearlCdpAppProfileRestoreHint__",APP_PROFILE_RESTORE_STATE="__mearlCdpAppProfileState__",APP_PROFILE_RESTORE_WORLD="__mearl_cdp_app_profile_state__",APP_PROFILE_RESTORE_VERSION=1,MAX_APP_PROFILE_RESTORE_STATE_LENGTH=7e4,appProfileStates=new WeakMap;function serializeForSource2(value){return JSON.stringify(value).replace(/[\u2028\u2029]/g,character=>character==="\u2028"?"\\u2028":"\\u2029")}function installCdpAppProfileRelay(bindingName){let browser=globalThis,target=globalThis;target.__mearlCdpAppProfileRelayInstalled__||(target.__mearlCdpAppProfileRelayInstalled__=!0,browser.addEventListener("message",event=>{if(event.source!==globalThis)return;let message=event.data;if(!message||message.source!=="mearl-app-bridge")return;let requestId=message.requestId;if(typeof requestId!="number")return;if(message.type==="prepareWebView"){browser.postMessage({source:"mearl-content",type:"APP_BRIDGE_PREPARE_WEBVIEW_RESPONSE",requestId,result:{success:!0}},"*");return}if(message.type!=="mtop"&&message.type!=="mtopStream"&&message.type!=="userInfo"&&message.type!=="screenshot")return;let replyFailure=reason=>{if(browser.console?.warn("[Mearl] App bridge relay unavailable:",reason),message.type==="mtopStream"){browser.postMessage({source:"mearl-content",type:"APP_BRIDGE_MTOP_STREAM_EVENT",requestId,eventType:"onError",data:{ret:["HY_FAILED"],msg:reason}},"*");return}let responseTypes={mtop:"APP_BRIDGE_MTOP_RESPONSE",userInfo:"APP_BRIDGE_USER_INFO_RESPONSE",screenshot:"APP_BRIDGE_SCREENSHOT_RESPONSE"};browser.postMessage({source:"mearl-content",type:responseTypes[String(message.type)],requestId,result:{success:!1,error:reason}},"*")},binding=target[bindingName];if(typeof binding!="function"){replyFailure("native relay binding is unavailable");return}try{binding(JSON.stringify({type:message.type,requestId,payload:message.payload}))}catch(error48){replyFailure(error48 instanceof Error?error48.message:"native relay call failed")}}))}function installEarlyAppProfileEnvironment(config2,restoreHintName){let browser=globalThis,target=globalThis;try{Object.defineProperty(target,restoreHintName,{configurable:!0,enumerable:!1,writable:!1,value:!0})}catch{target[restoreHintName]=!0}for(let[key,value]of Object.entries(config2.globals))try{target[key]=value}catch{}let insets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0};target.__STATUS_BAR_HEIGHT__=config2.statusBarHeight,target.__SAFE_AREA_INSET_BOTTOM__=insets.bottom;for(let[key,value]of[["userAgent",config2.userAgent],["platform",config2.navigatorPlatform],["vendor","Apple Computer, Inc."],["appVersion",config2.userAgent.replace(/^Mozilla\//,"")],["maxTouchPoints",config2.maxTouchPoints]])try{Object.defineProperty(browser.navigator,key,{configurable:!0,get:()=>value})}catch{}}function installWhenDocumentElementExists(install,waitForBody=!1){let browser=globalThis,isReady=()=>!!(browser.document.documentElement&&(!waitForBody||browser.document.body));if(isReady()){install();return}let observer=new browser.MutationObserver(()=>{isReady()&&(observer.disconnect(),install())});observer.observe(browser.document,{childList:!0,subtree:waitForBody})}function buildDocumentSource(config2){return`;(() => {const config=${serializeForSource2(config2)};(${installCdpAppProfileRelay.toString()})(${JSON.stringify(APP_PROFILE_BINDING)});(${installEarlyAppProfileEnvironment.toString()})(config,${JSON.stringify(APP_PROFILE_RESTORE_HINT)});(${installWhenDocumentElementExists.toString()})(() => {${buildAppProfileRuntimeCallSource("config")};},config.rootContainer?.enabled===true&&window===window.top);})();`}function usesAppProfileSplitScreen(emulation){return emulation?.deviceShell===!0&&emulation.splitScreen===!0&&emulation.config?.orientation==="landscape"}function resolveAppProfileRuntimeConfig(baseConfig,emulation){if(!usesAppProfileSplitScreen(emulation)||!emulation?.config){let rootContainer={...baseConfig.rootContainer};return delete rootContainer.splitScreen,{...baseConfig,rootContainer:{...rootContainer,enabled:!1},simulateSystemBars:!1,externalDeviceChrome:!1}}let device=emulation.config;return{...baseConfig,statusBarHeight:24,safeAreaInsets:device.safeAreaInsets,deviceAppearance:{preset:device.presetName??baseConfig.deviceAppearance?.preset??"iphone-17-pro",orientation:device.orientation,cutout:device.appearance.cutout},rootContainer:{...baseConfig.rootContainer,enabled:!0,splitScreen:!0},simulateSystemBars:!0,externalDeviceChrome:!1}}function buildRestoreHintSource(){return`;(() => {try{Object.defineProperty(globalThis,${JSON.stringify(APP_PROFILE_RESTORE_HINT)},{configurable:true,enumerable:false,writable:false,value:true});}catch{globalThis[${JSON.stringify(APP_PROFILE_RESTORE_HINT)}]=true;}})();`}function buildRestoreStateSource(restoreState,activeDocument){return`;(() => {const state=${serializeForSource2({...restoreState,activeDocument})};try{Object.defineProperty(globalThis,${JSON.stringify(APP_PROFILE_RESTORE_STATE)},{configurable:true,enumerable:false,writable:false,value:state});}catch{globalThis[${JSON.stringify(APP_PROFILE_RESTORE_STATE)}]=state;}})();`}function snapshotCdpAppProfileEmulation(emulation){let config2=emulation?.config;if(!config2)return;let landscape=config2.orientation==="landscape";return{...config2.presetName?{preset:config2.presetName}:{},width:landscape?config2.height:config2.width,height:landscape?config2.width:config2.height,deviceScaleFactor:config2.deviceScaleFactor,scale:config2.scale??1,mobile:config2.mobile,userAgent:config2.userAgent,orientation:config2.orientation,touch:config2.touch,deviceShell:emulation.deviceShell===!0,splitScreen:emulation.splitScreen===!0}}function resolveCdpAppProfileRestoreEmulation(emulation){return resolveEmulationConfig({enabled:!0,...emulation})}async function getRestoreExecutionContext(session){let frameId=(await session.client.sendCommand("Page.getFrameTree")).frameTree?.frame?.id;if(typeof frameId!="string"||!frameId)throw new Error("Chrome did not return the main frame id");let world=await session.client.sendCommand("Page.createIsolatedWorld",{frameId,worldName:APP_PROFILE_RESTORE_WORLD,grantUniveralAccess:!1});if(typeof world.executionContextId!="number")throw new Error("Chrome did not return the App profile restore execution context");return world.executionContextId}function appProfileEmulationCommands(config2,userAgent){return buildEnableEmulationCommands(config2).map(command=>command.method==="Emulation.setUserAgentOverride"?{...command,params:{userAgent,platform:config2.platform}}:command)}async function sendCommands(client2,commands){for(let{method,params,optional:optional2}of commands)await client2.sendCommand(method,params).catch(error48=>{if(!optional2)throw error48})}async function postRuntimeMessage(client2,executionContextId,message){await client2.sendCommand("Runtime.evaluate",{expression:`window.postMessage(${serializeForSource2(message)}, '*')`,...typeof executionContextId=="number"?{contextId:executionContextId}:{}})}function listenForBridgeRequests(session,client2,state){return client2.on("Runtime.bindingCalled",params=>{if(params?.name!==APP_PROFILE_BINDING||appProfileStates.get(session)!==state)return;let request;try{request=JSON.parse(params.payload)}catch{return}if(typeof request.requestId!="number")return;let requestId=request.requestId,contextId=typeof params.executionContextId=="number"?params.executionContextId:void 0,reply=message=>postRuntimeMessage(client2,contextId,{requestId,source:"mearl-content",...message});(async()=>{if(request.type==="screenshot"){if(client2!==session.client)return;try{let result=await cdpPageScreenshot(session,{format:"png"});await reply({type:"APP_BRIDGE_SCREENSHOT_RESPONSE",result:{success:!0,...result}})}catch(error48){await reply({type:"APP_BRIDGE_SCREENSHOT_RESPONSE",result:{success:!1,error:error48 instanceof Error?error48.message:String(error48)}})}return}if(request.type==="userInfo"){try{let currentUrl=await readCdpCurrentUrl(session,"user_info"),result=await session.client.sendCommand("Network.getCookies",{urls:[currentUrl]}),response=resolveAppProfileUserInfo(currentUrl,(result.cookies??[]).map(cookie=>({name:cookie.name,value:cookie.value})));await reply({type:"APP_BRIDGE_USER_INFO_RESPONSE",result:{success:!0,response}})}catch(error48){await reply({type:"APP_BRIDGE_USER_INFO_RESPONSE",result:{success:!1,error:error48 instanceof Error?error48.message:String(error48)}})}return}let payload=request.payload??{},mtopPayload={...payload,...typeof payload.v=="string"&&payload.version===void 0?{version:payload.v}:{}},streamCapture;try{if(request.type==="mtopStream"){await cdpSendMtopStreamRequest(session,mtopPayload,{onRequestPrepared:metadata=>{streamCapture=recordCdpMtopStreamStart(session.buffers,{api:String(mtopPayload.api??""),url:metadata.url,method:metadata.method,requestHeaders:metadata.requestHeaders,requestData:mtopPayload.data??null})},onResponse:metadata=>{streamCapture&&recordCdpMtopStreamResponse(session.buffers,streamCapture,metadata)},onReceive:async data=>{streamCapture&&recordCdpMtopStreamChunk(session.buffers,streamCapture,data),await reply({type:"APP_BRIDGE_MTOP_STREAM_EVENT",eventType:"onReceive",data})}}),streamCapture&&recordCdpMtopStreamEnd(session.buffers,streamCapture),await reply({type:"APP_BRIDGE_MTOP_STREAM_EVENT",eventType:"onFinish",data:{}});return}let result=await cdpSendMtopRequest(session,mtopPayload);await reply({type:"APP_BRIDGE_MTOP_RESPONSE",result})}catch(error48){let message=error48 instanceof Error?error48.message:String(error48);request.type==="mtopStream"?(streamCapture&&recordCdpMtopStreamEnd(session.buffers,streamCapture,{error:message}),await reply({type:"APP_BRIDGE_MTOP_STREAM_EVENT",eventType:"onError",data:{ret:["HY_FAILED"],msg:message}})):await reply({type:"APP_BRIDGE_MTOP_RESPONSE",result:{success:!1,error:message}})}})().catch(()=>{})})}async function installChildTarget2(session,state,params){let sessionId=params.sessionId;if(typeof sessionId!="string")return;let child=session.client.createChildSession(sessionId);try{if(params.targetInfo?.type!=="iframe"||appProfileStates.get(session)!==state)return;await child.sendCommand("Runtime.enable");let frameName=(await child.sendCommand("Runtime.evaluate",{expression:"window.name",returnByValue:!0})).result?.value;if(frameName!=="__mearl_root__"&&frameName!=="__mearl_layer__")return;let source=buildDocumentSource(state.config);state.emulation?await sendCommands(child,appProfileEmulationCommands(state.emulation,state.config.userAgent)):await child.sendCommand("Emulation.setUserAgentOverride",{userAgent:state.config.userAgent,platform:state.config.navigatorPlatform}),await child.sendCommand("Runtime.addBinding",{name:APP_PROFILE_BINDING}),state.disposeListeners.push(listenForBridgeRequests(session,child,state)),state.childClients.push(child),await child.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source}).catch(()=>{}),await child.sendCommand("Runtime.evaluate",{expression:source})}finally{await child.sendCommand("Runtime.runIfWaitingForDebugger").catch(()=>{})}}async function disposeState(session,state){appProfileStates.get(session)===state&&appProfileStates.delete(session),setCdpDeviceShellChildEnvironmentManagedByApp(session,!1);for(let dispose of state.disposeListeners.splice(0))dispose();isCdpDeviceShellActive(session)||await session.client.sendCommand("Target.setAutoAttach",{autoAttach:!1,waitForDebuggerOnStart:!1,flatten:!0}).catch(()=>{}),await Promise.allSettled(state.documentScriptIdentifiers.map(identifier=>session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier}))),await Promise.allSettled([session.client,...state.childClients].map(client2=>client2.sendCommand("Runtime.removeBinding",{name:APP_PROFILE_BINDING})));try{let contextId=await getRestoreExecutionContext(session);await session.client.sendCommand("Runtime.evaluate",{contextId,expression:`delete globalThis[${JSON.stringify(APP_PROFILE_RESTORE_STATE)}]`})}catch{}await session.client.sendCommand("Runtime.evaluate",{expression:`delete globalThis[${JSON.stringify(APP_PROFILE_RESTORE_HINT)}]`}).catch(()=>{});let deviceEmulation=session.emulation?.config;if(deviceEmulation){let commands=buildEnableEmulationCommands(deviceEmulation);await sendCommands(session.client,commands),await Promise.allSettled(state.childClients.map(client2=>sendCommands(client2,commands)))}else await Promise.allSettled([session.client,...state.childClients].map(client2=>client2.sendCommand("Emulation.setUserAgentOverride",{userAgent:""})))}async function rollbackAppProfileInstall(session,documentScriptIdentifiers,deviceEmulation){await Promise.allSettled([...documentScriptIdentifiers.map(identifier=>session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier})),session.client.sendCommand("Runtime.removeBinding",{name:APP_PROFILE_BINDING}),session.client.sendCommand("Runtime.evaluate",{expression:`delete globalThis[${JSON.stringify(APP_PROFILE_RESTORE_HINT)}]`})]),deviceEmulation?await sendCommands(session.client,buildEnableEmulationCommands(deviceEmulation)).catch(()=>{}):await session.client.sendCommand("Emulation.setUserAgentOverride",{userAgent:""}).catch(()=>{})}function resolveCdpAppProfile(profile,options={}){let resolved=resolveAppProfile(profile,{os:options.os,appVersion:options.appVersion,deviceModel:options.deviceModel,devicePreset:options.devicePreset,orientation:options.orientation,bridgeConfig:options.bridgeConfig}),restoreOptions={os:resolved.injected.platform==="Android"?"android":"ios",appVersion:resolved.injected.globals.__APP_VERSION__??"",deviceModel:resolved.injected.globals.__DEVICE_MODEL__??"",...resolved.injected.deviceAppearance?.preset?{devicePreset:resolved.injected.deviceAppearance.preset}:{},...resolved.injected.deviceAppearance?.orientation?{orientation:resolved.injected.deviceAppearance.orientation}:{},...options.bridgeConfig?{bridgeConfig:JSON.parse(JSON.stringify(options.bridgeConfig))}:{}};return{profile:resolved,restoreState:{version:APP_PROFILE_RESTORE_VERSION,profile:resolved.profile,options:restoreOptions}}}function isFiniteNumberInRange(value,minimum,maximum){return typeof value=="number"&&Number.isFinite(value)&&value>=minimum&&value<=maximum}function isCdpAppProfileRestoreEmulation(value){if(!value||typeof value!="object"||Array.isArray(value))return!1;let emulation=value,supportedKeys=new Set(["preset","width","height","deviceScaleFactor","scale","mobile","userAgent","orientation","touch","deviceShell","splitScreen"]);return!Object.keys(emulation).some(key=>!supportedKeys.has(key))&&(emulation.preset===void 0||typeof emulation.preset=="string"&&Object.hasOwn(DEVICE_PRESETS,emulation.preset))&&isFiniteNumberInRange(emulation.width,1,1e5)&&isFiniteNumberInRange(emulation.height,1,1e5)&&isFiniteNumberInRange(emulation.deviceScaleFactor,0,100)&&isFiniteNumberInRange(emulation.scale,Number.MIN_VALUE,100)&&typeof emulation.mobile=="boolean"&&typeof emulation.userAgent=="string"&&emulation.userAgent.length<=4096&&(emulation.orientation==="portrait"||emulation.orientation==="landscape")&&typeof emulation.touch=="boolean"&&typeof emulation.deviceShell=="boolean"&&(emulation.splitScreen===void 0||typeof emulation.splitScreen=="boolean")}function parseCdpAppProfileRestoreState(value){if(!value||typeof value!="object"||Array.isArray(value))return null;try{if(JSON.stringify(value).length>MAX_APP_PROFILE_RESTORE_STATE_LENGTH)return null}catch{return null}let state=value,supportedStateKeys=new Set(["version","profile","options","emulation","activeDocument"]);if(Object.keys(state).some(key=>!supportedStateKeys.has(key))||state.version!==APP_PROFILE_RESTORE_VERSION||typeof state.profile!="string"||typeof state.activeDocument!="boolean"||state.emulation!==void 0&&!isCdpAppProfileRestoreEmulation(state.emulation)||!state.options||typeof state.options!="object"||Array.isArray(state.options))return null;let options=state.options,supportedKeys=new Set(["os","appVersion","deviceModel","devicePreset","orientation","bridgeConfig"]);return Object.keys(options).some(key=>!supportedKeys.has(key))||options.os!=="ios"&&options.os!=="android"||typeof options.appVersion!="string"||options.appVersion.length>100||typeof options.deviceModel!="string"||options.deviceModel.length>200||options.devicePreset!==void 0&&(typeof options.devicePreset!="string"||!Object.hasOwn(DEVICE_PRESETS,options.devicePreset))||options.orientation!==void 0&&options.orientation!=="portrait"&&options.orientation!=="landscape"?null:value}function restoreStateForSession(restoreState,emulation){let result={...restoreState},emulationSnapshot=snapshotCdpAppProfileEmulation(emulation);return emulationSnapshot?result.emulation=emulationSnapshot:delete result.emulation,result}async function writeCurrentRestoreState(session,restoreState){let activeProfile=await session.client.sendCommand("Runtime.evaluate",{expression:`globalThis.__mearlAppProfile__===${JSON.stringify(restoreState.profile)}`,returnByValue:!0}),contextId=await getRestoreExecutionContext(session);await session.client.sendCommand("Runtime.evaluate",{contextId,expression:buildRestoreStateSource(restoreState,activeProfile.result?.value===!0)})}async function replaceRestoreState(session,state,restoreState){let result=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:buildRestoreStateSource(restoreState,!0),worldName:APP_PROFILE_RESTORE_WORLD});if(typeof result.identifier!="string"||!result.identifier)throw new Error("Chrome did not return an app profile restore script identifier");let identifier=result.identifier;try{await writeCurrentRestoreState(session,restoreState)}catch(error48){throw await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier}).catch(()=>{}),error48}let previousIdentifier=state.restoreScriptIdentifier;state.restoreState=restoreState,state.restoreScriptIdentifier=identifier,state.documentScriptIdentifiers.push(identifier),await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:previousIdentifier}).then(()=>!0,()=>!1)&&(state.documentScriptIdentifiers=state.documentScriptIdentifiers.filter(scriptIdentifier=>scriptIdentifier!==previousIdentifier))}async function replaceAppProfileDocumentSource(session,state,config2){let result=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:buildDocumentSource(config2)});if(typeof result.identifier!="string"||!result.identifier)throw new Error("Chrome did not return an App profile bootstrap script identifier");let previousIdentifier=state.profileScriptIdentifier;state.config=config2,state.profileScriptIdentifier=result.identifier,state.documentScriptIdentifiers.push(result.identifier),await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:previousIdentifier}).then(()=>!0,()=>!1)&&(state.documentScriptIdentifiers=state.documentScriptIdentifiers.filter(identifier=>identifier!==previousIdentifier))}async function restoreCdpAppProfile(session){if(appProfileStates.has(session))return!0;let pageState=(await session.client.sendCommand("Runtime.evaluate",{expression:`({profile:typeof globalThis.__mearlAppProfile__==='string'?globalThis.__mearlAppProfile__:null,restoreHint:globalThis[${JSON.stringify(APP_PROFILE_RESTORE_HINT)}]===true})`,returnByValue:!0,silent:!0})).result?.value;if(typeof pageState?.profile!="string"&&pageState?.restoreHint!==!0)return!1;let contextId=await getRestoreExecutionContext(session),stateProbe=await session.client.sendCommand("Runtime.evaluate",{contextId,expression:`globalThis[${JSON.stringify(APP_PROFILE_RESTORE_STATE)}]??null`,returnByValue:!0}),restoreState=parseCdpAppProfileRestoreState(stateProbe.result?.value);if(!restoreState||restoreState.activeDocument&&typeof pageState?.profile=="string"&&pageState.profile!==restoreState.profile)return!1;let resolved;try{resolved=resolveCdpAppProfile(restoreState.profile,restoreState.options)}catch{return!1}let restoredEmulation;try{restoredEmulation=restoreState.emulation?resolveCdpAppProfileRestoreEmulation(restoreState.emulation):void 0}catch{return!1}let previousEmulation=session.emulation;restoredEmulation&&restoreState.emulation&&(session.emulation={mobile:restoredEmulation.mobile,touch:restoredEmulation.touch,config:restoredEmulation,deviceShell:restoreState.emulation.deviceShell,splitScreen:restoreState.emulation.splitScreen===!0});try{await applyResolvedCdpAppProfile(session,resolved),restoredEmulation&&restoreState.emulation?.deviceShell&&(await applyCdpDeviceShell(session,restoredEmulation,{rootContainerManagedByApp:usesAppProfileSplitScreen(session.emulation)}),setCdpDeviceShellChildEnvironmentManagedByApp(session,!0)),restoreState.activeDocument&&await session.client.sendCommand("Runtime.evaluate",{expression:buildDocumentSource(resolved.profile.injected)})}catch(error48){await clearCdpDeviceShell(session).catch(()=>{});let state=appProfileStates.get(session);throw state&&await disposeState(session,state),session.emulation=previousEmulation,restoredEmulation&&(previousEmulation?.config?await sendCommands(session.client,buildEnableEmulationCommands(previousEmulation.config)).catch(()=>{}):await sendCommands(session.client,buildDisableEmulationCommands()).catch(()=>{})),new Error(`Failed to restore App profile for target ${session.targetId}: ${error48 instanceof Error?error48.message:String(error48)}`,{cause:error48})}return!0}async function applyResolvedCdpAppProfile(session,resolved){let previous=appProfileStates.get(session);previous&&await disposeState(session,previous);let baseConfig=resolved.profile.injected,config2=resolveAppProfileRuntimeConfig(baseConfig,session.emulation),source=buildDocumentSource(config2),deviceEmulation=session.emulation?.config,restoreState=restoreStateForSession(resolved.restoreState,session.emulation);deviceEmulation?await sendCommands(session.client,appProfileEmulationCommands(deviceEmulation,resolved.profile.ua)):await session.client.sendCommand("Emulation.setUserAgentOverride",{userAgent:resolved.profile.ua,platform:resolved.profile.injected.navigatorPlatform}),await session.client.sendCommand("Runtime.enable"),await session.client.sendCommand("Runtime.addBinding",{name:APP_PROFILE_BINDING});let documentScriptIdentifiers=[],state;try{let script=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source});if(typeof script.identifier!="string"||!script.identifier)throw new Error("Chrome did not return an app profile bootstrap script identifier");documentScriptIdentifiers.push(script.identifier);let restoreScript=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:buildRestoreStateSource(restoreState,!0),worldName:APP_PROFILE_RESTORE_WORLD});if(typeof restoreScript.identifier!="string"||!restoreScript.identifier)throw new Error("Chrome did not return an app profile restore script identifier");documentScriptIdentifiers.push(restoreScript.identifier),await writeCurrentRestoreState(session,restoreState),await session.client.sendCommand("Runtime.evaluate",{expression:buildRestoreHintSource()});let installedState={baseConfig,config:config2,documentScriptIdentifiers,profileScriptIdentifier:script.identifier,restoreScriptIdentifier:restoreScript.identifier,restoreState,emulation:deviceEmulation,disposeListeners:[],childClients:[]};state=installedState,appProfileStates.set(session,installedState),setCdpDeviceShellChildEnvironmentManagedByApp(session,!0),installedState.disposeListeners.push(listenForBridgeRequests(session,session.client,installedState)),installedState.disposeListeners.push(session.client.on("Target.attachedToTarget",params=>{installChildTarget2(session,installedState,params).catch(()=>{})})),installedState.disposeListeners.push(session.client.on("Target.detachedFromTarget",params=>{let sessionId=params?.sessionId;typeof sessionId!="string"||appProfileStates.get(session)!==installedState||(installedState.childClients=installedState.childClients.filter(client2=>client2.sessionId!==sessionId))})),await session.client.sendCommand("Target.setAutoAttach",{autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0,filter:[{type:"iframe"},{exclude:!0}]})}catch(error48){throw state?await disposeState(session,state):await rollbackAppProfileInstall(session,documentScriptIdentifiers,deviceEmulation),error48}}async function updateCdpAppProfileDeviceEmulation(session,emulation,deviceShell=session.emulation?.deviceShell===!0,splitScreen=session.emulation?.splitScreen===!0){let state=appProfileStates.get(session);if(!state)return;let nextSessionEmulation=emulation?{mobile:emulation.mobile,touch:emulation.touch,config:emulation,deviceShell,splitScreen}:void 0,nextConfig=resolveAppProfileRuntimeConfig(state.baseConfig,nextSessionEmulation);return JSON.stringify(nextConfig)!==JSON.stringify(state.config)&&await replaceAppProfileDocumentSource(session,state,nextConfig),await replaceRestoreState(session,state,restoreStateForSession(state.restoreState,nextSessionEmulation)),state.emulation=emulation??void 0,await Promise.allSettled(state.childClients.map(client2=>emulation?sendCommands(client2,appProfileEmulationCommands(emulation,state.config.userAgent)):client2.sendCommand("Emulation.setUserAgentOverride",{userAgent:state.config.userAgent,platform:state.config.navigatorPlatform}))),{userAgent:state.config.userAgent,platform:state.config.navigatorPlatform}}function isCdpAppProfileActive(session){return appProfileStates.has(session)}async function waitForCdpAppProfileLoad(session,timeoutMs=3e4){if(isCdpDeviceShellActive(session)){await waitForCdpDeviceShellLoad(session,Math.min(timeoutMs,15e3));return}await waitForPageLoad(session,timeoutMs)}async function clearCdpAppProfile(session,reload=!0){let state=appProfileStates.get(session);if(!state)return{enabled:!1,reloaded:!1};await disposeState(session,state),session.emulation?.deviceShell&&session.emulation.config&&await applyCdpDeviceShell(session,session.emulation.config);let reloaded=!1;return reload&&(clearPageRefsForNavigation(session),await session.client.sendCommand("Page.reload",{}),await waitForCdpAppProfileLoad(session),reloaded=!0),{enabled:!1,reloaded}}async function cdpSetAppProfile(session,data){if(typeof data?.enabled!="boolean")throw new Error('set_app_profile: "enabled" is required (true to enable, false to clear)');if(!data.enabled){if(data.emulation===void 0)return clearCdpAppProfile(session,data.reload!==!1);let hadDeviceShell=await clearCdpDeviceShell(session),appResult=await clearCdpAppProfile(session,!1);await sendCommands(session.client,buildDisableEmulationCommands()),session.emulation=void 0;let reloaded2=!1;return(data.reload!==!1||hadDeviceShell)&&(clearPageRefsForNavigation(session),await session.client.sendCommand("Page.reload",{}),await waitForPageLoad(session,3e4),reloaded2=!0),{...appResult,device:{enabled:!1,deviceShell:!1,splitScreen:!1,reloaded:reloaded2},reloaded:reloaded2}}if(!data.profile||typeof data.profile!="string")throw new Error('set_app_profile: "profile" is required when enabled=true');let resolved=resolveCdpAppProfile(data.profile,{...data,devicePreset:session.emulation?.config?.presetName,orientation:session.emulation?.config?.orientation});if(data.emulation!==void 0){let emulation=resolveEmulationConfig({enabled:!0,preset:resolved.profile.recommendedPreset,...data.emulation}),targetOs=emulation.platform==="Android"||emulation.platform==="OpenHarmony"?"android":"ios",targetDeviceModel=data.deviceModel??(emulation.presetName?DEVICE_PRESETS[emulation.presetName].appProfileModel:resolved.profile.injected.globals.__DEVICE_MODEL__),appResolved=resolveCdpAppProfile(data.profile,{...data,os:targetOs,deviceModel:targetDeviceModel}),deviceShell=data.emulation.deviceShell??!0,splitScreen=deviceShell&&data.emulation.splitScreen===!0&&emulation.orientation==="landscape";session.emulation={mobile:emulation.mobile,touch:emulation.touch,config:emulation,deviceShell,splitScreen},await applyResolvedCdpAppProfile(session,appResolved);let shellChanged2=deviceShell?await applyCdpDeviceShell(session,emulation,{rootContainerManagedByApp:splitScreen}):await clearCdpDeviceShell(session);deviceShell&&setCdpDeviceShellChildEnvironmentManagedByApp(session,!0);let reloaded2=!1;return(data.reload!==!1||shellChanged2)&&(clearPageRefsForNavigation(session),await session.client.sendCommand("Page.reload",{}),deviceShell?await waitForCdpDeviceShellLoad(session):await waitForPageLoad(session,3e4),reloaded2=!0),{enabled:!0,profile:appResolved.profile.profile,label:appResolved.profile.label,userAgent:appResolved.profile.ua,os:appResolved.profile.injected.platform==="Android"?"android":"ios",device:{enabled:!0,preset:emulation.presetName,viewport:{width:emulation.width,height:emulation.height,deviceScaleFactor:emulation.deviceScaleFactor,scale:emulation.scale??1},userAgent:emulation.userAgent,mobile:emulation.mobile,touch:emulation.touch,orientation:emulation.orientation,deviceShell,splitScreen,reloaded:reloaded2},reloaded:reloaded2}}await applyResolvedCdpAppProfile(session,resolved);let shellChanged=session.emulation?.deviceShell&&session.emulation.config?await applyCdpDeviceShell(session,session.emulation.config,{rootContainerManagedByApp:usesAppProfileSplitScreen(session.emulation)}):!1,reloaded=!1;return(data.reload!==!1||shellChanged)&&(clearPageRefsForNavigation(session),await session.client.sendCommand("Page.reload",{}),await waitForCdpAppProfileLoad(session),reloaded=!0),{enabled:!0,profile:resolved.profile.profile,label:resolved.profile.label,userAgent:resolved.profile.ua,os:resolved.profile.injected.platform==="Android"?"android":"ios",reloaded}}registerPageSessionInitializer(async session=>{try{await restoreCdpAppProfile(session)}catch(error48){console.warn(`[CDP] Failed to restore App profile for target ${session.targetId}:`,error48 instanceof Error?error48.message:String(error48))}});registerActions([{name:"set_app_profile",session:"page",handler:cdpSetAppProfile}]);async function releaseCdpControl(session){let pageSessions=session.listOpenPageSessions(),targetIds=new Set(pageSessions.map(pageSession=>pageSession.targetId)),affectedTabIds=session.listRegisteredTabIds(targetIds).sort((a,b)=>a-b),hadActiveControl=session.hasActiveConnections();return await Promise.allSettled(pageSessions.map(async pageSession=>{let[,deviceShell]=await Promise.allSettled([clearCdpAppProfile(pageSession,!1),clearCdpDeviceShell(pageSession),releaseControlledIndicator(pageSession)]);deviceShell.status==="fulfilled"&&deviceShell.value&&await pageSession.client.sendCommand("Page.reload",{}).catch(()=>{})})),clearCdpMockState(),session.close(),{released:!0,hadActiveControl,affectedTabIds}}var SAMPLE_PAGE_READINESS_SRC=samplePageReadinessInPage.toString(),DISPOSE_PAGE_READINESS_SRC=disposePageReadinessObserverInPage.toString();async function startCdpNavigationObserver(cdpSession2,pageSession,urlBefore,options={}){let pageEndpoint=await resolveCdpDeviceShellPageEndpoint(pageSession),pageClient=pageEndpoint.client;await ensureCdpDomain(pageClient,"Page"),await ensureCdpDomain(pageClient,"Runtime"),options.trackNetwork&&await ensureCdpDomain(pageClient,"Network");let browserClient=null,baselineTargetIds=new Set;if(options.trackOpenedTabs)try{browserClient=await cdpSession2.getBrowserClient();let targets=await browserClient.sendCommand("Target.getTargets");for(let target of targets.targetInfos??[])baselineTargetIds.add(target.targetId)}catch{browserClient=null}let frameTree=await pageClient.sendCommand("Page.getFrameTree"),observedFrameId=pageEndpoint.frameId??frameTree.frameTree?.frame?.id,observesParentTargetSubframe=pageClient===pageSession.client&&pageEndpoint.frameId!==void 0,tracker=createNavigationSettlementTracker({urlBefore,trackNetwork:options.trackNetwork,networkAvailable:options.trackNetwork===!0,networkIdleMs:options.networkIdleMs,contentReadyAfterMs:options.contentReadyAfterMs,sampleContent:async()=>(await sendCdpDeviceShellPageCommand(pageSession,"Runtime.evaluate",{expression:`(${SAMPLE_PAGE_READINESS_SRC})(${options.networkIdleMs??500})`,returnByValue:!0})).result?.value}),removeFrameNavigated=pageClient.on("Page.frameNavigated",params=>{observedFrameId&&params.frame?.id!==observedFrameId||tracker.markStarted(params.frame?.url)}),removeWithinDocument=pageClient.on("Page.navigatedWithinDocument",params=>{observedFrameId&&params.frameId!==observedFrameId||(tracker.markStarted(params.url),tracker.markDocumentComplete(params.url))}),removeLoad=pageClient.on("Page.loadEventFired",()=>{observesParentTargetSubframe||tracker.hasStarted()&&tracker.markDocumentComplete()}),removeFrameStoppedLoading=pageClient.on("Page.frameStoppedLoading",params=>{observedFrameId&&params.frameId!==observedFrameId||tracker.hasStarted()&&tracker.markDocumentComplete()}),removeRequestStarted=options.trackNetwork?pageClient.on("Network.requestWillBeSent",params=>{isPotentialNavigationRequest(params.type??"",params.request?.url??"")&&tracker.requestStarted(params.requestId)}):()=>{},onRequestFinished=params=>tracker.requestFinished(params.requestId),removeRequestFinished=options.trackNetwork?pageClient.on("Network.loadingFinished",onRequestFinished):()=>{},removeRequestFailed=options.trackNetwork?pageClient.on("Network.loadingFailed",onRequestFinished):()=>{};return{hasStarted:tracker.hasStarted,hasNetworkActivity:tracker.hasNetworkActivity,waitForStart:tracker.waitForStart,waitForNetworkIdle:tracker.waitForNetworkIdle,waitForResult:async timeoutMs=>{let result=await tracker.waitForResult(timeoutMs);try{let pageState=await sendCdpDeviceShellPageCommand(pageSession,"Runtime.evaluate",{expression:"({ title: document.title, url: location.href })",returnByValue:!0});return{...result,title:pageState.result?.value?.title??result.title,urlAfter:pageState.result?.value?.url??result.urlAfter}}catch{return result}},getOpenedTabs:async timeoutMs=>{if(!browserClient||options.sourceTabId===void 0)return[];let candidates=((await browserClient.sendCommand("Target.getTargets")).targetInfos??[]).filter(target=>target.type==="page"&&target.openerId===pageSession.targetId&&!baselineTargetIds.has(target.targetId));return(await Promise.all(candidates.map(async candidate=>{let tabId=await cdpSession2.ensureTargetRegistered(candidate.targetId),ready=!1;try{let openedPageSession=await cdpSession2.getPageSession(tabId);await ensureCdpDomain(openedPageSession.client,"Page"),await waitForPageLoad(openedPageSession,timeoutMs),ready=!0}catch{}let targetInfo=await browserClient.sendCommand("Target.getTargetInfo",{targetId:candidate.targetId}).then(result=>result.targetInfo).catch(()=>null);return targetInfo?{tabId,openerTabId:options.sourceTabId,url:targetInfo.url??candidate.url??"",title:targetInfo.title??candidate.title??"",ready,settledBy:ready?"load":"timeout"}:null}))).filter(tab=>tab!==null)},dispose:async()=>{removeFrameNavigated(),removeWithinDocument(),removeLoad(),removeFrameStoppedLoading(),removeRequestStarted(),removeRequestFinished(),removeRequestFailed(),tracker.dispose(),await sendCdpDeviceShellPageCommand(pageSession,"Runtime.evaluate",{expression:`(${DISPOSE_PAGE_READINESS_SRC})()`,returnByValue:!1}).catch(()=>{})}}}var INSTALL_PAGE_OBSERVER_SRC=installPageObserverInPage.toString(),DISPOSE_PAGE_OBSERVER_SRC=disposePageObserverInPage.toString(),PAGE_OBSERVER_GLOBAL="__MEARL_PAGE_OBSERVER__",observationTargets=new WeakMap;function evaluationError(result){return result.exceptionDetails?result.exceptionDetails.exception?.description??result.exceptionDetails.text??"Page observation evaluation failed":null}async function startPageObservation(session){let result=await sendCdpDeviceShellPageCommand(session,"Runtime.evaluate",{expression:`(${INSTALL_PAGE_OBSERVER_SRC})()`,returnByValue:!0}),error48=evaluationError(result);if(error48)throw new Error(error48);let checkpoint=result.result?.value;if(!checkpoint||typeof checkpoint.version!="number")throw new Error("Page observer did not return a checkpoint");let endpoint=await resolveCdpDeviceShellPageEndpoint(session);return observationTargets.set(checkpoint,{...endpoint,startedAt:Date.now()}),checkpoint}async function finishPageObservation(session,checkpoint,options={}){let startedTarget=observationTargets.get(checkpoint),currentTarget=await resolveCdpDeviceShellPageEndpoint(session);if(startedTarget&&currentTarget.url&&(currentTarget.client!==startedTarget.client||currentTarget.frameId!==startedTarget.frameId||currentTarget.url!==(startedTarget.url??checkpoint.url))){let title=await sendCdpDeviceShellPageCommand(session,"Runtime.evaluate",{expression:"document.title",returnByValue:!0}).then(result2=>typeof result2.result?.value=="string"?result2.result.value:"").catch(()=>"");return{mode:"navigation",urlBefore:checkpoint.url,urlAfter:currentTarget.url,title,elapsed:Date.now()-startedTarget.startedAt,loaded:!0,ready:!0,settledBy:"load",pendingRequests:0,fullSnapshotRecommended:!0,snapshotReasons:["navigation"]}}let{quietMs,firstChangeTimeoutMs,timeoutMs}=resolvePageObservationWaitOptions(options),expression=`(() => {
516
+ `)),{contentType:`multipart/form-data; boundary=${boundary}`,body:Buffer.concat(chunks)}}function hasMultipartPayload(data){return data.formData!==void 0||data.files!==void 0}async function executeNodeSendRequest(data,cookieMap=new Map){let{url:url2,method="GET",headers={},params,body,formData,files,responseType="auto",timeout=3e4}=data;if(!url2||typeof url2!="string"||url2.trim()==="")throw new Error("Invalid url: url must be a non-empty string");let normalizedMethod=method.toUpperCase();if(!ALLOWED_METHODS.has(normalizedMethod))throw new Error(`Invalid method: ${method}. Allowed: ${[...ALLOWED_METHODS].join(", ")}`);if(!Number.isFinite(timeout)||timeout<=0)throw new Error("timeout must be a positive number");let targetUrl=new URL(url2);for(let[key,value]of Object.entries(params??{}))targetUrl.searchParams.set(key,String(value));let requestHeaders={Accept:"application/json, text/plain, */*","Accept-Language":"zh-CN,zh;q=0.9,en;q=0.8","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",...headers},resolvedSourceHeaders=getSendRequestSourceHeaders(targetUrl,headers);resolvedSourceHeaders.referer?setHeader(requestHeaders,"Referer",resolvedSourceHeaders.referer):removeHeader(requestHeaders,"Referer"),resolvedSourceHeaders.origin?setHeader(requestHeaders,"Origin",resolvedSourceHeaders.origin):removeHeader(requestHeaders,"Origin");let cookieHeader=[...cookieMap.entries()].map(([key,value])=>`${key}=${value}`).join("; ");cookieHeader&&setHeader(requestHeaders,"Cookie",cookieHeader);let xsrfToken=cookieMap.get("XSRF-TOKEN");xsrfToken&&!findSendRequestHeaderName(requestHeaders,"x-xsrf-token")&&setHeader(requestHeaders,"X-XSRF-TOKEN",xsrfToken);let requestBody;if(hasMultipartPayload(data)){if(body!=null)throw new Error("body cannot be combined with formData or files");if(normalizedMethod==="GET"||normalizedMethod==="HEAD")throw new Error(`${normalizedMethod} requests cannot use formData or files`);if(findSendRequestHeaderName(requestHeaders,"content-type"))throw new Error("Do not set Content-Type when using formData or files; Mearl sets the boundary");let multipart=await buildMultipartBody(formData,files);requestBody=multipart.body,setHeader(requestHeaders,"Content-Type",multipart.contentType),setHeader(requestHeaders,"Content-Length",String(multipart.body.byteLength))}else body!=null&&!["GET","HEAD"].includes(normalizedMethod)&&(typeof body=="string"?(requestBody=body,findSendRequestHeaderName(requestHeaders,"content-type")||setHeader(requestHeaders,"Content-Type","text/plain")):(requestBody=JSON.stringify(body),findSendRequestHeaderName(requestHeaders,"content-type")||setHeader(requestHeaders,"Content-Type","application/json")));let result=await nodeFetch(targetUrl.toString(),{method:normalizedMethod,headers:requestHeaders,body:requestBody,timeoutMs:timeout}),contentType=(result.headers["content-type"]??"").split(";")[0].trim().toLowerCase(),responseHeaders=Object.fromEntries(Object.entries(result.headers).filter(([name])=>name.toLowerCase()!=="set-cookie"&&name.toLowerCase()!=="set-cookie2")),responseBody,bodyType;if(responseType==="auto"&&isBinarySendRequestContentType(contentType))responseBody=result.bodyBuffer.toString("base64"),bodyType="base64";else{let trimmed=result.body.trimStart();if(responseType==="json"||responseType==="auto"&&contentType.includes("application/json")||responseType==="auto"&&(trimmed.startsWith("{")||trimmed.startsWith("[")))try{responseBody=JSON.parse(result.body),bodyType="json"}catch{if(responseType==="json")throw new Error("send_request expected a JSON response");responseBody=result.body,bodyType="text"}else responseBody=result.body,bodyType="text"}return{success:!0,status:result.status,statusText:result.statusText,headers:responseHeaders,body:responseBody,bodyType,attachedCookieCount:cookieMap.size}}async function cdpSendRequest(session,data){if(!data.url||typeof data.url!="string")throw new Error("Invalid url: url must be a non-empty string");let cookieMap=new Map;if(data.withCookies!==!1)try{cookieMap=await getCookiesForUrl(session,new URL(data.url).toString())}catch{}return executeNodeSendRequest(data,cookieMap)}async function prepareCdpMtopRequest(session,data,stream=!1){let resolved=resolveMtopRequest(data),cookieMap=await getCookiesForUrl(session,resolved.gatewayUrl.toString()),prepared=prepareSignedMtopRequest(resolved,cookieMap,stream);return{...prepared,requestHeaders:{...prepared.cookieHeader?{Cookie:prepared.cookieHeader}:{},...prepared.requestHeaders}}}async function cdpSendMtopRequest(session,data){let prepared=await prepareCdpMtopRequest(session,data),result=await nodeFetch(prepared.targetUrl.toString(),{method:prepared.normalizedMethod,headers:prepared.requestHeaders,body:prepared.body,timeoutMs:prepared.timeout});return{success:!0,response:parseMtopResponseText(result.body),requestData:prepared.requestData}}async function cdpSendMtopStreamRequest(session,data,callbacks){let prepared=await prepareCdpMtopRequest(session,data,!0),controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),prepared.timeout);try{await callbacks.onRequestPrepared?.({method:prepared.normalizedMethod,url:prepared.targetUrl.toString(),requestHeaders:Object.entries(prepared.requestHeaders).map(([name,value])=>({name,value}))});let response=await fetch(prepared.targetUrl,{method:prepared.normalizedMethod,headers:prepared.requestHeaders,body:prepared.body,signal:controller.signal}),responseHeaders=[];return response.headers.forEach((value,name)=>{name.toLowerCase()!=="set-cookie"&&responseHeaders.push({name,value})}),await callbacks.onResponse?.({status:response.status,statusText:response.statusText,responseHeaders}),{success:!0,response:await consumeMtopSseResponse(response,event=>callbacks.onReceive(event.data)),requestData:prepared.requestData}}catch(error48){throw error48 instanceof Error&&error48.name==="AbortError"?new Error(`send_mtop_stream timed out after ${prepared.timeout}ms: ${prepared.api}`,{cause:error48}):new Error(`send_mtop_stream failed: ${error48 instanceof Error?error48.message:String(error48)}`,{cause:error48})}finally{clearTimeout(timeoutId)}}registerActions([{name:"send_request",session:"page",handler:cdpSendRequest},{name:"send_mtop_request",session:"page",handler:cdpSendMtopRequest}]);var registries=new WeakMap;function getPageRefRegistry(session){let registry2=registries.get(session);if(!registry2){registry2=new BackendNodeRefRegistry,registries.set(session,registry2);let activeRegistry=registry2;session.client.on("Page.frameNavigated",params=>{params.frame?.parentId||activeRegistry.clearDocument()})}return registry2}function beginPageSnapshotRefs(session){return getPageRefRegistry(session).beginSnapshot()}function resolvePageRef(session,ref){return registries.get(session)?.resolve(ref)}function deletePageRef(session,ref){registries.get(session)?.delete(ref)}function clearPageRefsForNavigation(session){registries.get(session)?.clearDocument()}async function enrichCdpPageChangeSetWithRefs(session,observation){return enrichPageChangeSetWithRefs(observation,getPageRefRegistry(session),selectors=>resolveUniqueBackendNodeIds((method,params)=>sendCdpDeviceShellPageCommand(session,method,params),selectors),(node,backendNodeId)=>({backendNodeId,role:node.role??"",name:node.name??""}))}var MTOP_GATEWAY_FAMILIES=[{prod:"h5api.m.taobao.com",pre:"h5api.wapa.taobao.com"},{prod:"h5api.m.alibaba-inc.com",pre:"h5api.wapa.alibaba-inc.com"}],environments=new WeakMap;function rewriteMtopGatewayUrl(url2,target){try{let parsed=new URL(url2),family=MTOP_GATEWAY_FAMILIES.find(item=>Object.values(item).includes(parsed.hostname));return!family||parsed.hostname===family[target]?url2:(parsed.hostname=family[target],parsed.toString())}catch{return url2}}function isMtopGatewayUrl(url2){try{let host=new URL(url2).hostname;return MTOP_GATEWAY_FAMILIES.some(family=>Object.values(family).includes(host))}catch{return!1}}function hasOriginHeader(request){return Object.keys(request.headers??{}).some(name=>name.toLowerCase()==="origin")}async function handleMtopEnvironmentRequest({session,params,isResponseStage}){let target=environments.get(session);if(!target)return!1;let request=params.request??{},url2=typeof request.url=="string"?request.url:"";if(!isMtopGatewayUrl(url2))return!1;if(!isResponseStage){let rewrittenUrl=rewriteMtopGatewayUrl(url2,target);return rewrittenUrl===url2?!1:(await session.client.sendCommand("Fetch.continueRequest",{requestId:params.requestId,url:rewrittenUrl}),!0)}if(params.responseStatusCode==null||!hasOriginHeader(request))return!1;let responseHeaders=ensureCorsHeaders([...params.responseHeaders??[]],request);return await session.client.sendCommand("Fetch.continueResponse",{requestId:params.requestId,responseCode:params.responseStatusCode,...typeof params.responseStatusText=="string"&&{responsePhrase:params.responseStatusText},responseHeaders}),!0}async function setCdpMtopEnvironment(session,target){if(target!=="default"&&target!=="prod"&&target!=="pre")throw new Error('set_app_profile: "mtopEnv" must be "default", "prod", or "pre"');if(target==="default"){environments.delete(session),await unregisterCdpFetchPauseHandler(session,"mtop-environment");return}environments.set(session,target);try{await registerCdpFetchPauseHandler(session,"mtop-environment",50,handleMtopEnvironmentRequest)}catch(error48){throw environments.delete(session),error48}}function clearCdpMtopEnvironmentState(sessions){if(!sessions){environments=new WeakMap;return}for(let session of sessions)environments.delete(session)}var APP_PROFILE_BINDING="__mearlCdpAppProfileRelay",APP_PROFILE_RESTORE_HINT="__mearlCdpAppProfileRestoreHint__",APP_PROFILE_RESTORE_STATE="__mearlCdpAppProfileState__",APP_PROFILE_RESTORE_WORLD="__mearl_cdp_app_profile_state__",APP_PROFILE_RESTORE_VERSION=1,MAX_APP_PROFILE_RESTORE_STATE_LENGTH=7e4,appProfileStates=new WeakMap;function serializeForSource2(value){return JSON.stringify(value).replace(/[\u2028\u2029]/g,character=>character==="\u2028"?"\\u2028":"\\u2029")}function installCdpAppProfileRelay(bindingName){let browser=globalThis,target=globalThis;target.__mearlCdpAppProfileRelayInstalled__||(target.__mearlCdpAppProfileRelayInstalled__=!0,browser.addEventListener("message",event=>{if(event.source!==globalThis)return;let message=event.data;if(!message||message.source!=="mearl-app-bridge")return;let requestId=message.requestId;if(typeof requestId!="number")return;if(message.type==="prepareWebView"){browser.postMessage({source:"mearl-content",type:"APP_BRIDGE_PREPARE_WEBVIEW_RESPONSE",requestId,result:{success:!0}},"*");return}if(message.type!=="mtop"&&message.type!=="mtopStream"&&message.type!=="userInfo"&&message.type!=="screenshot")return;let replyFailure=reason=>{if(browser.console?.warn("[Mearl] App bridge relay unavailable:",reason),message.type==="mtopStream"){browser.postMessage({source:"mearl-content",type:"APP_BRIDGE_MTOP_STREAM_EVENT",requestId,eventType:"onError",data:{ret:["HY_FAILED"],msg:reason}},"*");return}let responseTypes={mtop:"APP_BRIDGE_MTOP_RESPONSE",userInfo:"APP_BRIDGE_USER_INFO_RESPONSE",screenshot:"APP_BRIDGE_SCREENSHOT_RESPONSE"};browser.postMessage({source:"mearl-content",type:responseTypes[String(message.type)],requestId,result:{success:!1,error:reason}},"*")},binding=target[bindingName];if(typeof binding!="function"){replyFailure("native relay binding is unavailable");return}try{binding(JSON.stringify({type:message.type,requestId,payload:message.payload}))}catch(error48){replyFailure(error48 instanceof Error?error48.message:"native relay call failed")}}))}function installEarlyAppProfileEnvironment(config2,restoreHintName){let browser=globalThis,target=globalThis;try{Object.defineProperty(target,restoreHintName,{configurable:!0,enumerable:!1,writable:!1,value:!0})}catch{target[restoreHintName]=!0}for(let[key,value]of Object.entries(config2.globals))try{target[key]=value}catch{}let insets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0};target.__STATUS_BAR_HEIGHT__=config2.statusBarHeight,target.__SAFE_AREA_INSET_BOTTOM__=insets.bottom;for(let[key,value]of[["userAgent",config2.userAgent],["platform",config2.navigatorPlatform],["vendor","Apple Computer, Inc."],["appVersion",config2.userAgent.replace(/^Mozilla\//,"")],["maxTouchPoints",config2.maxTouchPoints]])try{Object.defineProperty(browser.navigator,key,{configurable:!0,get:()=>value})}catch{}}function installWhenDocumentElementExists(install,waitForBody=!1){let browser=globalThis,isReady=()=>!!(browser.document.documentElement&&(!waitForBody||browser.document.body));if(isReady()){install();return}let observer=new browser.MutationObserver(()=>{isReady()&&(observer.disconnect(),install())});observer.observe(browser.document,{childList:!0,subtree:waitForBody})}function buildDocumentSource(config2){return`;(() => {const config=${serializeForSource2(config2)};(${installCdpAppProfileRelay.toString()})(${JSON.stringify(APP_PROFILE_BINDING)});(${installEarlyAppProfileEnvironment.toString()})(config,${JSON.stringify(APP_PROFILE_RESTORE_HINT)});(${installWhenDocumentElementExists.toString()})(() => {${buildAppProfileRuntimeCallSource("config")};},config.rootContainer?.enabled===true&&window===window.top);})();`}function usesAppProfileSplitScreen(emulation){return emulation?.deviceShell===!0&&emulation.splitScreen===!0&&emulation.config?.orientation==="landscape"}function resolveAppProfileRuntimeConfig(baseConfig,emulation){if(!usesAppProfileSplitScreen(emulation)||!emulation?.config){let rootContainer={...baseConfig.rootContainer};return delete rootContainer.splitScreen,{...baseConfig,rootContainer:{...rootContainer,enabled:!1},simulateSystemBars:!1,externalDeviceChrome:!1}}let device=emulation.config;return{...baseConfig,statusBarHeight:24,safeAreaInsets:device.safeAreaInsets,deviceAppearance:{preset:device.presetName??baseConfig.deviceAppearance?.preset??"iphone-17-pro",orientation:device.orientation,cutout:device.appearance.cutout},rootContainer:{...baseConfig.rootContainer,enabled:!0,splitScreen:!0},simulateSystemBars:!0,externalDeviceChrome:!1}}function buildRestoreHintSource(){return`;(() => {try{Object.defineProperty(globalThis,${JSON.stringify(APP_PROFILE_RESTORE_HINT)},{configurable:true,enumerable:false,writable:false,value:true});}catch{globalThis[${JSON.stringify(APP_PROFILE_RESTORE_HINT)}]=true;}})();`}function buildRestoreStateSource(restoreState,activeDocument){return`;(() => {const state=${serializeForSource2({...restoreState,activeDocument})};try{Object.defineProperty(globalThis,${JSON.stringify(APP_PROFILE_RESTORE_STATE)},{configurable:true,enumerable:false,writable:false,value:state});}catch{globalThis[${JSON.stringify(APP_PROFILE_RESTORE_STATE)}]=state;}})();`}function snapshotCdpAppProfileEmulation(emulation){let config2=emulation?.config;if(!config2)return;let landscape=config2.orientation==="landscape";return{...config2.presetName?{preset:config2.presetName}:{},width:landscape?config2.height:config2.width,height:landscape?config2.width:config2.height,deviceScaleFactor:config2.deviceScaleFactor,scale:config2.scale??1,mobile:config2.mobile,userAgent:config2.userAgent,orientation:config2.orientation,touch:config2.touch,deviceShell:emulation.deviceShell===!0,splitScreen:emulation.splitScreen===!0}}function resolveCdpAppProfileRestoreEmulation(emulation){return resolveEmulationConfig({enabled:!0,...emulation})}async function getRestoreExecutionContext(session){let frameId=(await session.client.sendCommand("Page.getFrameTree")).frameTree?.frame?.id;if(typeof frameId!="string"||!frameId)throw new Error("Chrome did not return the main frame id");let world=await session.client.sendCommand("Page.createIsolatedWorld",{frameId,worldName:APP_PROFILE_RESTORE_WORLD,grantUniveralAccess:!1});if(typeof world.executionContextId!="number")throw new Error("Chrome did not return the App profile restore execution context");return world.executionContextId}function appProfileEmulationCommands(config2,userAgent){return buildEnableEmulationCommands(config2).map(command=>command.method==="Emulation.setUserAgentOverride"?{...command,params:{userAgent,platform:config2.platform}}:command)}async function sendCommands(client2,commands){for(let{method,params,optional:optional2}of commands)await client2.sendCommand(method,params).catch(error48=>{if(!optional2)throw error48})}async function postRuntimeMessage(client2,executionContextId,message){await client2.sendCommand("Runtime.evaluate",{expression:`window.postMessage(${serializeForSource2(message)}, '*')`,...typeof executionContextId=="number"?{contextId:executionContextId}:{}})}function listenForBridgeRequests(session,client2,state){return client2.on("Runtime.bindingCalled",params=>{if(params?.name!==APP_PROFILE_BINDING||appProfileStates.get(session)!==state)return;let request;try{request=JSON.parse(params.payload)}catch{return}if(typeof request.requestId!="number")return;let requestId=request.requestId,contextId=typeof params.executionContextId=="number"?params.executionContextId:void 0,reply=message=>postRuntimeMessage(client2,contextId,{requestId,source:"mearl-content",...message});(async()=>{if(request.type==="screenshot"){if(client2!==session.client)return;try{let result=await cdpPageScreenshot(session,{format:"png"});await reply({type:"APP_BRIDGE_SCREENSHOT_RESPONSE",result:{success:!0,...result}})}catch(error48){await reply({type:"APP_BRIDGE_SCREENSHOT_RESPONSE",result:{success:!1,error:error48 instanceof Error?error48.message:String(error48)}})}return}if(request.type==="userInfo"){try{let currentUrl=await readCdpCurrentUrl(session,"user_info"),result=await session.client.sendCommand("Network.getCookies",{urls:[currentUrl]}),response=resolveAppProfileUserInfo(currentUrl,(result.cookies??[]).map(cookie=>({name:cookie.name,value:cookie.value})));await reply({type:"APP_BRIDGE_USER_INFO_RESPONSE",result:{success:!0,response}})}catch(error48){await reply({type:"APP_BRIDGE_USER_INFO_RESPONSE",result:{success:!1,error:error48 instanceof Error?error48.message:String(error48)}})}return}let payload=request.payload??{},mtopPayload={...payload,...typeof payload.v=="string"&&payload.version===void 0?{version:payload.v}:{}},streamCapture;try{if(request.type==="mtopStream"){await cdpSendMtopStreamRequest(session,mtopPayload,{onRequestPrepared:metadata=>{streamCapture=recordCdpMtopStreamStart(session.buffers,{api:String(mtopPayload.api??""),url:metadata.url,method:metadata.method,requestHeaders:metadata.requestHeaders,requestData:mtopPayload.data??null})},onResponse:metadata=>{streamCapture&&recordCdpMtopStreamResponse(session.buffers,streamCapture,metadata)},onReceive:async data=>{streamCapture&&recordCdpMtopStreamChunk(session.buffers,streamCapture,data),await reply({type:"APP_BRIDGE_MTOP_STREAM_EVENT",eventType:"onReceive",data})}}),streamCapture&&recordCdpMtopStreamEnd(session.buffers,streamCapture),await reply({type:"APP_BRIDGE_MTOP_STREAM_EVENT",eventType:"onFinish",data:{}});return}let result=await cdpSendMtopRequest(session,mtopPayload);await reply({type:"APP_BRIDGE_MTOP_RESPONSE",result})}catch(error48){let message=error48 instanceof Error?error48.message:String(error48);request.type==="mtopStream"?(streamCapture&&recordCdpMtopStreamEnd(session.buffers,streamCapture,{error:message}),await reply({type:"APP_BRIDGE_MTOP_STREAM_EVENT",eventType:"onError",data:{ret:["HY_FAILED"],msg:message}})):await reply({type:"APP_BRIDGE_MTOP_RESPONSE",result:{success:!1,error:message}})}})().catch(()=>{})})}async function installChildTarget2(session,state,params){let sessionId=params.sessionId;if(typeof sessionId!="string")return;let child=session.client.createChildSession(sessionId);try{if(params.targetInfo?.type!=="iframe"||appProfileStates.get(session)!==state)return;await child.sendCommand("Runtime.enable");let frameName=(await child.sendCommand("Runtime.evaluate",{expression:"window.name",returnByValue:!0})).result?.value;if(frameName!=="__mearl_root__"&&frameName!=="__mearl_layer__")return;let source=buildDocumentSource(state.config);state.emulation?await sendCommands(child,appProfileEmulationCommands(state.emulation,state.config.userAgent)):await child.sendCommand("Emulation.setUserAgentOverride",{userAgent:state.config.userAgent,platform:state.config.navigatorPlatform}),await child.sendCommand("Runtime.addBinding",{name:APP_PROFILE_BINDING}),state.disposeListeners.push(listenForBridgeRequests(session,child,state)),state.childClients.push(child),await child.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source}).catch(()=>{}),await child.sendCommand("Runtime.evaluate",{expression:source})}finally{await child.sendCommand("Runtime.runIfWaitingForDebugger").catch(()=>{})}}async function disposeState(session,state){appProfileStates.get(session)===state&&appProfileStates.delete(session),setCdpDeviceShellChildEnvironmentManagedByApp(session,!1);for(let dispose of state.disposeListeners.splice(0))dispose();isCdpDeviceShellActive(session)||await session.client.sendCommand("Target.setAutoAttach",{autoAttach:!1,waitForDebuggerOnStart:!1,flatten:!0}).catch(()=>{}),await Promise.allSettled(state.documentScriptIdentifiers.map(identifier=>session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier}))),await Promise.allSettled([session.client,...state.childClients].map(client2=>client2.sendCommand("Runtime.removeBinding",{name:APP_PROFILE_BINDING})));try{let contextId=await getRestoreExecutionContext(session);await session.client.sendCommand("Runtime.evaluate",{contextId,expression:`delete globalThis[${JSON.stringify(APP_PROFILE_RESTORE_STATE)}]`})}catch{}await session.client.sendCommand("Runtime.evaluate",{expression:`delete globalThis[${JSON.stringify(APP_PROFILE_RESTORE_HINT)}]`}).catch(()=>{});let deviceEmulation=session.emulation?.config;if(deviceEmulation){let commands=buildEnableEmulationCommands(deviceEmulation);await sendCommands(session.client,commands),await Promise.allSettled(state.childClients.map(client2=>sendCommands(client2,commands)))}else await Promise.allSettled([session.client,...state.childClients].map(client2=>client2.sendCommand("Emulation.setUserAgentOverride",{userAgent:""})))}async function rollbackAppProfileInstall(session,documentScriptIdentifiers,deviceEmulation){await Promise.allSettled([...documentScriptIdentifiers.map(identifier=>session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier})),session.client.sendCommand("Runtime.removeBinding",{name:APP_PROFILE_BINDING}),session.client.sendCommand("Runtime.evaluate",{expression:`delete globalThis[${JSON.stringify(APP_PROFILE_RESTORE_HINT)}]`})]),deviceEmulation?await sendCommands(session.client,buildEnableEmulationCommands(deviceEmulation)).catch(()=>{}):await session.client.sendCommand("Emulation.setUserAgentOverride",{userAgent:""}).catch(()=>{})}function resolveCdpAppProfile(profile,options={}){let resolved=resolveAppProfile(profile,{os:options.os,appVersion:options.appVersion,deviceModel:options.deviceModel,devicePreset:options.devicePreset,orientation:options.orientation,bridgeConfig:options.bridgeConfig}),restoreOptions={os:resolved.injected.platform==="Android"?"android":"ios",appVersion:resolved.injected.globals.__APP_VERSION__??"",deviceModel:resolved.injected.globals.__DEVICE_MODEL__??"",...resolved.injected.deviceAppearance?.preset?{devicePreset:resolved.injected.deviceAppearance.preset}:{},...resolved.injected.deviceAppearance?.orientation?{orientation:resolved.injected.deviceAppearance.orientation}:{},...options.bridgeConfig?{bridgeConfig:JSON.parse(JSON.stringify(options.bridgeConfig))}:{}};return{profile:resolved,restoreState:{version:APP_PROFILE_RESTORE_VERSION,profile:resolved.profile,options:restoreOptions}}}function isFiniteNumberInRange(value,minimum,maximum){return typeof value=="number"&&Number.isFinite(value)&&value>=minimum&&value<=maximum}function isCdpAppProfileRestoreEmulation(value){if(!value||typeof value!="object"||Array.isArray(value))return!1;let emulation=value,supportedKeys=new Set(["preset","width","height","deviceScaleFactor","scale","mobile","userAgent","orientation","touch","deviceShell","splitScreen"]);return!Object.keys(emulation).some(key=>!supportedKeys.has(key))&&(emulation.preset===void 0||typeof emulation.preset=="string"&&Object.hasOwn(DEVICE_PRESETS,emulation.preset))&&isFiniteNumberInRange(emulation.width,1,1e5)&&isFiniteNumberInRange(emulation.height,1,1e5)&&isFiniteNumberInRange(emulation.deviceScaleFactor,0,100)&&isFiniteNumberInRange(emulation.scale,Number.MIN_VALUE,100)&&typeof emulation.mobile=="boolean"&&typeof emulation.userAgent=="string"&&emulation.userAgent.length<=4096&&(emulation.orientation==="portrait"||emulation.orientation==="landscape")&&typeof emulation.touch=="boolean"&&typeof emulation.deviceShell=="boolean"&&(emulation.splitScreen===void 0||typeof emulation.splitScreen=="boolean")}function parseCdpAppProfileRestoreState(value){if(!value||typeof value!="object"||Array.isArray(value))return null;try{if(JSON.stringify(value).length>MAX_APP_PROFILE_RESTORE_STATE_LENGTH)return null}catch{return null}let state=value,supportedStateKeys=new Set(["version","profile","options","emulation","activeDocument"]);if(Object.keys(state).some(key=>!supportedStateKeys.has(key))||state.version!==APP_PROFILE_RESTORE_VERSION||typeof state.profile!="string"||typeof state.activeDocument!="boolean"||state.emulation!==void 0&&!isCdpAppProfileRestoreEmulation(state.emulation)||!state.options||typeof state.options!="object"||Array.isArray(state.options))return null;let options=state.options,supportedKeys=new Set(["os","appVersion","deviceModel","devicePreset","orientation","bridgeConfig"]);return Object.keys(options).some(key=>!supportedKeys.has(key))||options.os!=="ios"&&options.os!=="android"||typeof options.appVersion!="string"||options.appVersion.length>100||typeof options.deviceModel!="string"||options.deviceModel.length>200||options.devicePreset!==void 0&&(typeof options.devicePreset!="string"||!Object.hasOwn(DEVICE_PRESETS,options.devicePreset))||options.orientation!==void 0&&options.orientation!=="portrait"&&options.orientation!=="landscape"?null:value}function restoreStateForSession(restoreState,emulation){let result={...restoreState},emulationSnapshot=snapshotCdpAppProfileEmulation(emulation);return emulationSnapshot?result.emulation=emulationSnapshot:delete result.emulation,result}async function writeCurrentRestoreState(session,restoreState){let activeProfile=await session.client.sendCommand("Runtime.evaluate",{expression:`globalThis.__mearlAppProfile__===${JSON.stringify(restoreState.profile)}`,returnByValue:!0}),contextId=await getRestoreExecutionContext(session);await session.client.sendCommand("Runtime.evaluate",{contextId,expression:buildRestoreStateSource(restoreState,activeProfile.result?.value===!0)})}async function replaceRestoreState(session,state,restoreState){let result=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:buildRestoreStateSource(restoreState,!0),worldName:APP_PROFILE_RESTORE_WORLD});if(typeof result.identifier!="string"||!result.identifier)throw new Error("Chrome did not return an app profile restore script identifier");let identifier=result.identifier;try{await writeCurrentRestoreState(session,restoreState)}catch(error48){throw await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier}).catch(()=>{}),error48}let previousIdentifier=state.restoreScriptIdentifier;state.restoreState=restoreState,state.restoreScriptIdentifier=identifier,state.documentScriptIdentifiers.push(identifier),await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:previousIdentifier}).then(()=>!0,()=>!1)&&(state.documentScriptIdentifiers=state.documentScriptIdentifiers.filter(scriptIdentifier=>scriptIdentifier!==previousIdentifier))}async function replaceAppProfileDocumentSource(session,state,config2){let result=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:buildDocumentSource(config2)});if(typeof result.identifier!="string"||!result.identifier)throw new Error("Chrome did not return an App profile bootstrap script identifier");let previousIdentifier=state.profileScriptIdentifier;state.config=config2,state.profileScriptIdentifier=result.identifier,state.documentScriptIdentifiers.push(result.identifier),await session.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:previousIdentifier}).then(()=>!0,()=>!1)&&(state.documentScriptIdentifiers=state.documentScriptIdentifiers.filter(identifier=>identifier!==previousIdentifier))}async function restoreCdpAppProfile(session){if(appProfileStates.has(session))return!0;let pageState=(await session.client.sendCommand("Runtime.evaluate",{expression:`({profile:typeof globalThis.__mearlAppProfile__==='string'?globalThis.__mearlAppProfile__:null,restoreHint:globalThis[${JSON.stringify(APP_PROFILE_RESTORE_HINT)}]===true})`,returnByValue:!0,silent:!0})).result?.value;if(typeof pageState?.profile!="string"&&pageState?.restoreHint!==!0)return!1;let contextId=await getRestoreExecutionContext(session),stateProbe=await session.client.sendCommand("Runtime.evaluate",{contextId,expression:`globalThis[${JSON.stringify(APP_PROFILE_RESTORE_STATE)}]??null`,returnByValue:!0}),restoreState=parseCdpAppProfileRestoreState(stateProbe.result?.value);if(!restoreState||restoreState.activeDocument&&typeof pageState?.profile=="string"&&pageState.profile!==restoreState.profile)return!1;let resolved;try{resolved=resolveCdpAppProfile(restoreState.profile,restoreState.options)}catch{return!1}let restoredEmulation;try{restoredEmulation=restoreState.emulation?resolveCdpAppProfileRestoreEmulation(restoreState.emulation):void 0}catch{return!1}let previousEmulation=session.emulation;restoredEmulation&&restoreState.emulation&&(session.emulation={mobile:restoredEmulation.mobile,touch:restoredEmulation.touch,config:restoredEmulation,deviceShell:restoreState.emulation.deviceShell,splitScreen:restoreState.emulation.splitScreen===!0});try{await applyResolvedCdpAppProfile(session,resolved),restoredEmulation&&restoreState.emulation?.deviceShell&&(await applyCdpDeviceShell(session,restoredEmulation,{rootContainerManagedByApp:usesAppProfileSplitScreen(session.emulation)}),setCdpDeviceShellChildEnvironmentManagedByApp(session,!0)),restoreState.activeDocument&&await session.client.sendCommand("Runtime.evaluate",{expression:buildDocumentSource(resolved.profile.injected)})}catch(error48){await clearCdpDeviceShell(session).catch(()=>{});let state=appProfileStates.get(session);throw state&&await disposeState(session,state),session.emulation=previousEmulation,restoredEmulation&&(previousEmulation?.config?await sendCommands(session.client,buildEnableEmulationCommands(previousEmulation.config)).catch(()=>{}):await sendCommands(session.client,buildDisableEmulationCommands()).catch(()=>{})),new Error(`Failed to restore App profile for target ${session.targetId}: ${error48 instanceof Error?error48.message:String(error48)}`,{cause:error48})}return!0}async function applyResolvedCdpAppProfile(session,resolved){let previous=appProfileStates.get(session);previous&&await disposeState(session,previous);let baseConfig=resolved.profile.injected,config2=resolveAppProfileRuntimeConfig(baseConfig,session.emulation),source=buildDocumentSource(config2),deviceEmulation=session.emulation?.config,restoreState=restoreStateForSession(resolved.restoreState,session.emulation);deviceEmulation?await sendCommands(session.client,appProfileEmulationCommands(deviceEmulation,resolved.profile.ua)):await session.client.sendCommand("Emulation.setUserAgentOverride",{userAgent:resolved.profile.ua,platform:resolved.profile.injected.navigatorPlatform}),await session.client.sendCommand("Runtime.enable"),await session.client.sendCommand("Runtime.addBinding",{name:APP_PROFILE_BINDING});let documentScriptIdentifiers=[],state;try{let script=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source});if(typeof script.identifier!="string"||!script.identifier)throw new Error("Chrome did not return an app profile bootstrap script identifier");documentScriptIdentifiers.push(script.identifier);let restoreScript=await session.client.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:buildRestoreStateSource(restoreState,!0),worldName:APP_PROFILE_RESTORE_WORLD});if(typeof restoreScript.identifier!="string"||!restoreScript.identifier)throw new Error("Chrome did not return an app profile restore script identifier");documentScriptIdentifiers.push(restoreScript.identifier),await writeCurrentRestoreState(session,restoreState),await session.client.sendCommand("Runtime.evaluate",{expression:buildRestoreHintSource()});let installedState={baseConfig,config:config2,documentScriptIdentifiers,profileScriptIdentifier:script.identifier,restoreScriptIdentifier:restoreScript.identifier,restoreState,emulation:deviceEmulation,disposeListeners:[],childClients:[]};state=installedState,appProfileStates.set(session,installedState),setCdpDeviceShellChildEnvironmentManagedByApp(session,!0),installedState.disposeListeners.push(listenForBridgeRequests(session,session.client,installedState)),installedState.disposeListeners.push(session.client.on("Target.attachedToTarget",params=>{installChildTarget2(session,installedState,params).catch(()=>{})})),installedState.disposeListeners.push(session.client.on("Target.detachedFromTarget",params=>{let sessionId=params?.sessionId;typeof sessionId!="string"||appProfileStates.get(session)!==installedState||(installedState.childClients=installedState.childClients.filter(client2=>client2.sessionId!==sessionId))})),await session.client.sendCommand("Target.setAutoAttach",{autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0,filter:[{type:"iframe"},{exclude:!0}]})}catch(error48){throw state?await disposeState(session,state):await rollbackAppProfileInstall(session,documentScriptIdentifiers,deviceEmulation),error48}}async function updateCdpAppProfileDeviceEmulation(session,emulation,deviceShell=session.emulation?.deviceShell===!0,splitScreen=session.emulation?.splitScreen===!0){let state=appProfileStates.get(session);if(!state)return;let nextSessionEmulation=emulation?{mobile:emulation.mobile,touch:emulation.touch,config:emulation,deviceShell,splitScreen}:void 0,nextConfig=resolveAppProfileRuntimeConfig(state.baseConfig,nextSessionEmulation);return JSON.stringify(nextConfig)!==JSON.stringify(state.config)&&await replaceAppProfileDocumentSource(session,state,nextConfig),await replaceRestoreState(session,state,restoreStateForSession(state.restoreState,nextSessionEmulation)),state.emulation=emulation??void 0,await Promise.allSettled(state.childClients.map(client2=>emulation?sendCommands(client2,appProfileEmulationCommands(emulation,state.config.userAgent)):client2.sendCommand("Emulation.setUserAgentOverride",{userAgent:state.config.userAgent,platform:state.config.navigatorPlatform}))),{userAgent:state.config.userAgent,platform:state.config.navigatorPlatform}}function isCdpAppProfileActive(session){return appProfileStates.has(session)}async function waitForCdpAppProfileLoad(session,timeoutMs=3e4){if(isCdpDeviceShellActive(session)){await waitForCdpDeviceShellLoad(session,Math.min(timeoutMs,15e3));return}await waitForPageLoad(session,timeoutMs)}async function clearCdpAppProfile(session,reload=!0){let state=appProfileStates.get(session);if(!state)return{enabled:!1,reloaded:!1};await disposeState(session,state),session.emulation?.deviceShell&&session.emulation.config&&await applyCdpDeviceShell(session,session.emulation.config);let reloaded=!1;return reload&&(clearPageRefsForNavigation(session),await session.client.sendCommand("Page.reload",{}),await waitForCdpAppProfileLoad(session),reloaded=!0),{enabled:!1,reloaded}}async function cdpSetAppProfile(session,data){if(typeof data?.enabled!="boolean")throw new Error('set_app_profile: "enabled" is required (true to enable, false to clear)');if(!data.enabled){if(data.emulation===void 0){if(data.mtopEnv===void 0)return clearCdpAppProfile(session,data.reload!==!1);let appResult2=await clearCdpAppProfile(session,!1);await setCdpMtopEnvironment(session,data.mtopEnv);let reloaded3=!1;return data.reload!==!1&&(clearPageRefsForNavigation(session),await session.client.sendCommand("Page.reload",{}),await waitForCdpAppProfileLoad(session),reloaded3=!0),{...appResult2,mtopEnv:data.mtopEnv,reloaded:reloaded3}}let hadDeviceShell=await clearCdpDeviceShell(session),appResult=await clearCdpAppProfile(session,!1);await sendCommands(session.client,buildDisableEmulationCommands()),session.emulation=void 0,data.mtopEnv!==void 0&&await setCdpMtopEnvironment(session,data.mtopEnv);let reloaded2=!1;return(data.reload!==!1||hadDeviceShell)&&(clearPageRefsForNavigation(session),await session.client.sendCommand("Page.reload",{}),await waitForPageLoad(session,3e4),reloaded2=!0),{...appResult,...data.mtopEnv!==void 0&&{mtopEnv:data.mtopEnv},device:{enabled:!1,deviceShell:!1,splitScreen:!1,reloaded:reloaded2},reloaded:reloaded2}}if(!data.profile||typeof data.profile!="string")throw new Error('set_app_profile: "profile" is required when enabled=true');let resolved=resolveCdpAppProfile(data.profile,{...data,devicePreset:session.emulation?.config?.presetName,orientation:session.emulation?.config?.orientation});if(data.emulation!==void 0){let emulation=resolveEmulationConfig({enabled:!0,preset:resolved.profile.recommendedPreset,...data.emulation}),targetOs=emulation.platform==="Android"||emulation.platform==="OpenHarmony"?"android":"ios",targetDeviceModel=data.deviceModel??(emulation.presetName?DEVICE_PRESETS[emulation.presetName].appProfileModel:resolved.profile.injected.globals.__DEVICE_MODEL__),appResolved=resolveCdpAppProfile(data.profile,{...data,os:targetOs,deviceModel:targetDeviceModel}),deviceShell=data.emulation.deviceShell??!0,splitScreen=deviceShell&&data.emulation.splitScreen===!0&&emulation.orientation==="landscape";session.emulation={mobile:emulation.mobile,touch:emulation.touch,config:emulation,deviceShell,splitScreen},await applyResolvedCdpAppProfile(session,appResolved);let shellChanged2=deviceShell?await applyCdpDeviceShell(session,emulation,{rootContainerManagedByApp:splitScreen}):await clearCdpDeviceShell(session);deviceShell&&setCdpDeviceShellChildEnvironmentManagedByApp(session,!0),data.mtopEnv!==void 0&&await setCdpMtopEnvironment(session,data.mtopEnv);let reloaded2=!1;return(data.reload!==!1||shellChanged2)&&(clearPageRefsForNavigation(session),await session.client.sendCommand("Page.reload",{}),deviceShell?await waitForCdpDeviceShellLoad(session):await waitForPageLoad(session,3e4),reloaded2=!0),{enabled:!0,profile:appResolved.profile.profile,label:appResolved.profile.label,userAgent:appResolved.profile.ua,os:appResolved.profile.injected.platform==="Android"?"android":"ios",...data.mtopEnv!==void 0&&{mtopEnv:data.mtopEnv},device:{enabled:!0,preset:emulation.presetName,viewport:{width:emulation.width,height:emulation.height,deviceScaleFactor:emulation.deviceScaleFactor,scale:emulation.scale??1},userAgent:emulation.userAgent,mobile:emulation.mobile,touch:emulation.touch,orientation:emulation.orientation,deviceShell,splitScreen,reloaded:reloaded2},reloaded:reloaded2}}await applyResolvedCdpAppProfile(session,resolved);let shellChanged=session.emulation?.deviceShell&&session.emulation.config?await applyCdpDeviceShell(session,session.emulation.config,{rootContainerManagedByApp:usesAppProfileSplitScreen(session.emulation)}):!1;data.mtopEnv!==void 0&&await setCdpMtopEnvironment(session,data.mtopEnv);let reloaded=!1;return(data.reload!==!1||shellChanged)&&(clearPageRefsForNavigation(session),await session.client.sendCommand("Page.reload",{}),await waitForCdpAppProfileLoad(session),reloaded=!0),{enabled:!0,profile:resolved.profile.profile,label:resolved.profile.label,userAgent:resolved.profile.ua,os:resolved.profile.injected.platform==="Android"?"android":"ios",...data.mtopEnv!==void 0&&{mtopEnv:data.mtopEnv},reloaded}}registerPageSessionInitializer(async session=>{try{await restoreCdpAppProfile(session)}catch(error48){console.warn(`[CDP] Failed to restore App profile for target ${session.targetId}:`,error48 instanceof Error?error48.message:String(error48))}});registerActions([{name:"set_app_profile",session:"page",handler:cdpSetAppProfile}]);async function releaseCdpControl(session){let pageSessions=session.listOpenPageSessions(),targetIds=new Set(pageSessions.map(pageSession=>pageSession.targetId)),affectedTabIds=session.listRegisteredTabIds(targetIds).sort((a,b)=>a-b),hadActiveControl=session.hasActiveConnections();return await Promise.allSettled(pageSessions.map(async pageSession=>{let[,deviceShell]=await Promise.allSettled([clearCdpAppProfile(pageSession,!1),clearCdpDeviceShell(pageSession),releaseControlledIndicator(pageSession)]);deviceShell.status==="fulfilled"&&deviceShell.value&&await pageSession.client.sendCommand("Page.reload",{}).catch(()=>{})})),clearCdpMockState(),clearCdpMtopEnvironmentState(pageSessions),clearCdpFetchInterceptionState(pageSessions),session.close(),{released:!0,hadActiveControl,affectedTabIds}}var SAMPLE_PAGE_READINESS_SRC=samplePageReadinessInPage.toString(),DISPOSE_PAGE_READINESS_SRC=disposePageReadinessObserverInPage.toString();async function startCdpNavigationObserver(cdpSession2,pageSession,urlBefore,options={}){let pageEndpoint=await resolveCdpDeviceShellPageEndpoint(pageSession),pageClient=pageEndpoint.client;await ensureCdpDomain(pageClient,"Page"),await ensureCdpDomain(pageClient,"Runtime"),options.trackNetwork&&await ensureCdpDomain(pageClient,"Network");let browserClient=null,baselineTargetIds=new Set;if(options.trackOpenedTabs)try{browserClient=await cdpSession2.getBrowserClient();let targets=await browserClient.sendCommand("Target.getTargets");for(let target of targets.targetInfos??[])baselineTargetIds.add(target.targetId)}catch{browserClient=null}let frameTree=await pageClient.sendCommand("Page.getFrameTree"),observedFrameId=pageEndpoint.frameId??frameTree.frameTree?.frame?.id,observesParentTargetSubframe=pageClient===pageSession.client&&pageEndpoint.frameId!==void 0,tracker=createNavigationSettlementTracker({urlBefore,trackNetwork:options.trackNetwork,networkAvailable:options.trackNetwork===!0,networkIdleMs:options.networkIdleMs,contentReadyAfterMs:options.contentReadyAfterMs,sampleContent:async()=>(await sendCdpDeviceShellPageCommand(pageSession,"Runtime.evaluate",{expression:`(${SAMPLE_PAGE_READINESS_SRC})(${options.networkIdleMs??500})`,returnByValue:!0})).result?.value}),removeFrameNavigated=pageClient.on("Page.frameNavigated",params=>{observedFrameId&&params.frame?.id!==observedFrameId||tracker.markStarted(params.frame?.url)}),removeWithinDocument=pageClient.on("Page.navigatedWithinDocument",params=>{observedFrameId&&params.frameId!==observedFrameId||(tracker.markStarted(params.url),tracker.markDocumentComplete(params.url))}),removeLoad=pageClient.on("Page.loadEventFired",()=>{observesParentTargetSubframe||tracker.hasStarted()&&tracker.markDocumentComplete()}),removeFrameStoppedLoading=pageClient.on("Page.frameStoppedLoading",params=>{observedFrameId&&params.frameId!==observedFrameId||tracker.hasStarted()&&tracker.markDocumentComplete()}),removeRequestStarted=options.trackNetwork?pageClient.on("Network.requestWillBeSent",params=>{isPotentialNavigationRequest(params.type??"",params.request?.url??"")&&tracker.requestStarted(params.requestId)}):()=>{},onRequestFinished=params=>tracker.requestFinished(params.requestId),removeRequestFinished=options.trackNetwork?pageClient.on("Network.loadingFinished",onRequestFinished):()=>{},removeRequestFailed=options.trackNetwork?pageClient.on("Network.loadingFailed",onRequestFinished):()=>{};return{hasStarted:tracker.hasStarted,hasNetworkActivity:tracker.hasNetworkActivity,waitForStart:tracker.waitForStart,waitForNetworkIdle:tracker.waitForNetworkIdle,waitForResult:async timeoutMs=>{let result=await tracker.waitForResult(timeoutMs);try{let pageState=await sendCdpDeviceShellPageCommand(pageSession,"Runtime.evaluate",{expression:"({ title: document.title, url: location.href })",returnByValue:!0});return{...result,title:pageState.result?.value?.title??result.title,urlAfter:pageState.result?.value?.url??result.urlAfter}}catch{return result}},getOpenedTabs:async timeoutMs=>{if(!browserClient||options.sourceTabId===void 0)return[];let candidates=((await browserClient.sendCommand("Target.getTargets")).targetInfos??[]).filter(target=>target.type==="page"&&target.openerId===pageSession.targetId&&!baselineTargetIds.has(target.targetId));return(await Promise.all(candidates.map(async candidate=>{let tabId=await cdpSession2.ensureTargetRegistered(candidate.targetId),ready=!1;try{let openedPageSession=await cdpSession2.getPageSession(tabId);await ensureCdpDomain(openedPageSession.client,"Page"),await waitForPageLoad(openedPageSession,timeoutMs),ready=!0}catch{}let targetInfo=await browserClient.sendCommand("Target.getTargetInfo",{targetId:candidate.targetId}).then(result=>result.targetInfo).catch(()=>null);return targetInfo?{tabId,openerTabId:options.sourceTabId,url:targetInfo.url??candidate.url??"",title:targetInfo.title??candidate.title??"",ready,settledBy:ready?"load":"timeout"}:null}))).filter(tab=>tab!==null)},dispose:async()=>{removeFrameNavigated(),removeWithinDocument(),removeLoad(),removeFrameStoppedLoading(),removeRequestStarted(),removeRequestFinished(),removeRequestFailed(),tracker.dispose(),await sendCdpDeviceShellPageCommand(pageSession,"Runtime.evaluate",{expression:`(${DISPOSE_PAGE_READINESS_SRC})()`,returnByValue:!1}).catch(()=>{})}}}var INSTALL_PAGE_OBSERVER_SRC=installPageObserverInPage.toString(),DISPOSE_PAGE_OBSERVER_SRC=disposePageObserverInPage.toString(),PAGE_OBSERVER_GLOBAL="__MEARL_PAGE_OBSERVER__",observationTargets=new WeakMap;function evaluationError(result){return result.exceptionDetails?result.exceptionDetails.exception?.description??result.exceptionDetails.text??"Page observation evaluation failed":null}async function startPageObservation(session){let result=await sendCdpDeviceShellPageCommand(session,"Runtime.evaluate",{expression:`(${INSTALL_PAGE_OBSERVER_SRC})()`,returnByValue:!0}),error48=evaluationError(result);if(error48)throw new Error(error48);let checkpoint=result.result?.value;if(!checkpoint||typeof checkpoint.version!="number")throw new Error("Page observer did not return a checkpoint");let endpoint=await resolveCdpDeviceShellPageEndpoint(session);return observationTargets.set(checkpoint,{...endpoint,startedAt:Date.now()}),checkpoint}async function finishPageObservation(session,checkpoint,options={}){let startedTarget=observationTargets.get(checkpoint),currentTarget=await resolveCdpDeviceShellPageEndpoint(session);if(startedTarget&&currentTarget.url&&(currentTarget.client!==startedTarget.client||currentTarget.frameId!==startedTarget.frameId||currentTarget.url!==(startedTarget.url??checkpoint.url))){let title=await sendCdpDeviceShellPageCommand(session,"Runtime.evaluate",{expression:"document.title",returnByValue:!0}).then(result2=>typeof result2.result?.value=="string"?result2.result.value:"").catch(()=>"");return{mode:"navigation",urlBefore:checkpoint.url,urlAfter:currentTarget.url,title,elapsed:Date.now()-startedTarget.startedAt,loaded:!0,ready:!0,settledBy:"load",pendingRequests:0,fullSnapshotRecommended:!0,snapshotReasons:["navigation"]}}let{quietMs,firstChangeTimeoutMs,timeoutMs}=resolvePageObservationWaitOptions(options),expression=`(() => {
517
517
  const state = globalThis[${JSON.stringify(PAGE_OBSERVER_GLOBAL)}];
518
518
  if (!state || typeof state.waitSince !== 'function') {
519
519
  throw new Error('Page observer is unavailable after the action');
@@ -592,7 +592,7 @@ ${candidates}`)}let hit=hits[0],dispatchTarget;if(effectiveClickMode==="dom"||po
592
592
  remaining -= 1;
593
593
  }
594
594
  return element;
595
- }`,arguments:[{value:ancestorDepth}],returnByValue:!1});if(ancestorObjectId=ancestor.result?.objectId,!ancestorObjectId||ancestor.result?.subtype==="null")throw new Error("page_snapshot: cannot resolve an ancestor for rootRef");let ancestorBackendNodeId=(await sendCdpDeviceShellPageCommand(session,"DOM.describeNode",{objectId:ancestorObjectId})).node?.backendNodeId;if(ancestorBackendNodeId===void 0)throw new Error("page_snapshot: cannot resolve an ancestor for rootRef");return ancestorBackendNodeId}finally{ancestorObjectId&&await sendCdpDeviceShellPageCommand(session,"Runtime.releaseObject",{objectId:ancestorObjectId}).catch(()=>{}),await sendCdpDeviceShellPageCommand(session,"Runtime.releaseObject",{objectId}).catch(()=>{})}}async function getViewportBackendNodeIds(session){let[metrics,captured]=await Promise.all([sendCdpDeviceShellPageCommand(session,"Page.getLayoutMetrics",{}),sendCdpDeviceShellPageCommand(session,"DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!1})]),viewport=resolveDOMSnapshotViewportBounds(metrics);if(!viewport)throw new Error("page_snapshot: viewport metrics are unavailable");let{left,top,width,height}=viewport,right=left+width,bottom=top+height,visible=new Set;for(let document2 of captured.documents??[]){let backendNodeIds=document2.nodes?.backendNodeId??[],nodeIndexes=document2.layout?.nodeIndex??[],bounds=document2.layout?.bounds??[];for(let index=0;index<nodeIndexes.length;index+=1){let box=bounds[index],backendNodeId=backendNodeIds[nodeIndexes[index]];if(!box||backendNodeId===void 0)continue;let[x,y,boxWidth,boxHeight]=box;boxWidth<=0||boxHeight<=0||x<right&&x+boxWidth>left&&y<bottom&&y+boxHeight>top&&visible.add(backendNodeId)}}return visible}async function cdpPageSnapshot(session,data){let mode=data?.mode??"full",rootSelector=data?.rootSelector,rootRef=data?.rootRef,ancestorDepth=data?.ancestorDepth??0,query=resolvePageSnapshotQuery(data?.query);if(!["full","interactive","viewport"].includes(mode))throw new Error("page_snapshot: mode must be one of full, interactive, viewport");if(rootSelector!==void 0&&(typeof rootSelector!="string"||!rootSelector.trim()))throw new Error("page_snapshot: rootSelector must be a non-empty CSS selector");if(rootRef!==void 0&&(typeof rootRef!="string"||!/^@e\d+$/.test(rootRef)))throw new Error('page_snapshot: rootRef must be a snapshot ref like "@e3"');if(rootSelector!==void 0&&rootRef!==void 0)throw new Error("page_snapshot: rootSelector and rootRef are mutually exclusive");if(!Number.isInteger(ancestorDepth)||ancestorDepth<0||ancestorDepth>20)throw new Error("page_snapshot: ancestorDepth must be an integer between 0 and 20");if(ancestorDepth>0&&rootRef===void 0)throw new Error("page_snapshot: ancestorDepth requires rootRef");let rootBackendNodeId;if(rootSelector)rootBackendNodeId=await resolveRootBackendNodeId(session,rootSelector);else if(rootRef){let entry=resolvePageRef(session,rootRef);if(!entry)throw new Error(`Ref ${rootRef} not found. Run page_snapshot first to get fresh refs.`);rootBackendNodeId=await resolveAncestorBackendNodeId(session,entry.backendNodeId,ancestorDepth)}let snapshotRefs=beginPageSnapshotRefs(session),[result,visibleBackendNodeIds]=await Promise.all([sendCdpDeviceShellPageCommand(session,rootBackendNodeId===void 0?"Accessibility.getFullAXTree":"Accessibility.queryAXTree",rootBackendNodeId===void 0?{depth:data?.depth}:{backendNodeId:rootBackendNodeId}),mode==="viewport"||mode==="interactive"?getViewportBackendNodeIds(session):Promise.resolve(void 0)]),nodes=result.nodes??[];await reconcileAXCheckedStates(nodes,backendNodeId=>readDOMCheckedState2(session,backendNodeId));let nodeMap=new Map;for(let node of nodes)nodeMap.set(node.nodeId,node);let rootNode=nodes[0];if(!rootNode)return snapshotRefs.commit(new Set),{snapshot:"(empty page)",refs:{},elementCount:0,outputNodeCount:1,mode,...rootSelector?{rootSelector}:{},...rootRef?{rootRef,ancestorDepth}:{},...query?{query,matches:[],matchCount:0}:{}};let rawTree=buildSnapshotTree(nodeMap,rootNode.nodeId,snapshotRefs),viewportFilteredTree=mode==="interactive"?filterSnapshotTree(rawTree,"viewport",visibleBackendNodeIds):rawTree,effectiveMode=mode;mode==="interactive"&&!hasInteractiveSnapshotNode(viewportFilteredTree)&&(effectiveMode="viewport");let modeFilteredTree=mode==="interactive"?effectiveMode==="interactive"?filterSnapshotTree(viewportFilteredTree,"interactive"):viewportFilteredTree:filterSnapshotTree(rawTree,effectiveMode,visibleBackendNodeIds),queryResult=query?filterSnapshotTreeByQuery(modeFilteredTree,query):{tree:modeFilteredTree,matches:[]},limitedMatches=query?limitPageSnapshotQueryMatches(queryResult.matches):{matches:[],truncated:!1},tree=queryResult.tree,lines=[];tree&&formatSnapshotNode(tree,0,lines);let formatted=formatSnapshotWithLimits(lines.length>0?lines:[query?"(no matches)":"(empty page)"],{maxChars:data?.maxChars,maxNodes:data?.maxNodes}),refs={},outputRefKeys=new Set(Array.from(formatted.snapshot.matchAll(/(?:^|\n)\s*(@e\d+)\s/g),match=>match[1]));for(let match of limitedMatches.matches)match.ref&&outputRefKeys.add(match.ref);snapshotRefs.commit(outputRefKeys);let registry2=getPageRefRegistry(session);for(let ref of outputRefKeys){let entry=registry2.resolve(ref);entry&&(refs[ref.slice(1)]={backendNodeId:entry.backendNodeId})}return{snapshot:formatted.snapshot,refs,elementCount:countSnapshotNodes(tree),outputNodeCount:formatted.outputNodeCount,mode,...rootSelector?{rootSelector}:{},...rootRef?{rootRef,ancestorDepth}:{},...query?{query,matches:limitedMatches.matches,matchCount:queryResult.matches.length,...limitedMatches.truncated?{matchesTruncated:!0}:{}}:{},...effectiveMode!==mode?{fallbackMode:"viewport"}:{},...formatted.truncated?{truncated:!0}:{}}}async function cdpPageFrames(session,_data){let result=await session.client.sendCommand("Page.getFrameTree",{});function flattenFrameTree(tree){if(!tree)return[];let{frame,childFrames=[]}=tree;return[{frameId:frame.id,parentFrameId:frame.parentId??null,url:frame.url,name:frame.name??""},...childFrames.flatMap(flattenFrameTree)]}let frames=flattenFrameTree(result.frameTree);return{frames,count:frames.length}}registerActions([{name:"page_snapshot",session:"page",handler:cdpPageSnapshot},{name:"page_frames",session:"page",handler:cdpPageFrames}]);var MEARL_SERVICE_COOKIE_DOMAINS=["tdbank.alibaba-inc.com","ats2.alibaba-inc.com","g.alibaba-inc.com","login.alibaba-inc.com","token-hub.alibaba-inc.com","alibaba-inc.com"],MEARL_SERVICE_COOKIE_HOSTS=new Set(MEARL_SERVICE_COOKIE_DOMAINS);function normalizeCookieDomain2(input){let value=input.trim();if(!value)throw new Error("Cookie domain must be a non-empty string");let hostname3;try{hostname3=new URL(value.includes("://")?value:`https://${value}`).hostname}catch{throw new Error(`Invalid cookie domain: ${input}`)}if(hostname3=hostname3.toLowerCase().replace(/^\.+/,"").replace(/\.+$/,""),!hostname3)throw new Error(`Invalid cookie domain: ${input}`);return hostname3}function normalizeCookieDomains(inputs){if(!Array.isArray(inputs))throw new Error("copyCookieDomains must be an array of domains");return[...new Set(inputs.map(value=>normalizeCookieDomain2(String(value))))]}function isMearlServiceCookie(cookie){let domain2=normalizeCookieDomain2(cookie.domain);return MEARL_SERVICE_COOKIE_HOSTS.has(domain2)?!0:domain2.endsWith(".tdbank.alibaba-inc.com")||domain2.endsWith(".ats2.alibaba-inc.com")}function normalizeCookieCopyScope(input){let presets=input.presets??[];if(!Array.isArray(presets)||presets.some(preset=>preset!=="mearl-services"))throw new Error("copyCookieDomains.presets contains an unsupported preset");return{includeMearlServices:presets.includes("mearl-services"),domains:normalizeCookieDomains(input.domains??[])}}function resolveCookieCopyPlan(input){let includeMearlServices=!1,explicitDomains=[];if(input==="mearl-services")includeMearlServices=!0;else if(Array.isArray(input))explicitDomains=normalizeCookieDomains(input);else if(input!=null&&typeof input=="object"){let scope=normalizeCookieCopyScope(input);includeMearlServices=scope.includeMearlServices,explicitDomains=scope.domains}else if(input!==void 0)throw new Error('copyCookieDomains must be an array of domains, "mearl-services", or a scope object');return includeMearlServices?{domains:[...new Set([...MEARL_SERVICE_COOKIE_DOMAINS,...explicitDomains])],select:cookies=>cookies.filter(cookie=>isMearlServiceCookie(cookie)||explicitDomains.some(domain2=>cookieMatchesDomain(cookie.domain,domain2)))}:{domains:explicitDomains,select:cookies=>cookies}}function cookieMatchesDomain(cookieDomain,requestedDomain){let cookieHost=cookieDomain.toLowerCase().replace(/^\.+/,"");return cookieHost===requestedDomain||cookieHost.endsWith(`.${requestedDomain}`)||requestedDomain.endsWith(`.${cookieHost}`)}function toTransferableCookie(cookie){let result={name:String(cookie.name),value:String(cookie.value),domain:String(cookie.domain),path:String(cookie.path||"/"),secure:!!cookie.secure,httpOnly:!!cookie.httpOnly};return["Strict","Lax","None"].includes(cookie.sameSite)&&(result.sameSite=cookie.sameSite),typeof cookie.expires=="number"&&cookie.expires>0&&(result.expires=cookie.expires),["Low","Medium","High"].includes(cookie.priority)&&(result.priority=cookie.priority),typeof cookie.sameParty=="boolean"&&(result.sameParty=cookie.sameParty),["Unset","NonSecure","Secure"].includes(cookie.sourceScheme)&&(result.sourceScheme=cookie.sourceScheme),typeof cookie.sourcePort=="number"&&(result.sourcePort=cookie.sourcePort),cookie.partitionKey?.topLevelSite&&(result.partitionKey={topLevelSite:String(cookie.partitionKey.topLevelSite),...typeof cookie.partitionKey.hasCrossSiteAncestor=="boolean"?{hasCrossSiteAncestor:cookie.partitionKey.hasCrossSiteAncestor}:{}}),result}async function cdpExportCookies(session,domains){let requestedDomains=normalizeCookieDomains(domains);return((await(await session.getBrowserClient()).sendCommand("Storage.getCookies",{})).cookies??[]).filter(cookie=>requestedDomains.some(domain2=>cookieMatchesDomain(String(cookie.domain),domain2))).map(toTransferableCookie)}async function cdpImportCookies(session,cookies){if(cookies.length===0)return 0;let browser=await session.getBrowserClient();return cdpImportCookiesWithClient(browser,cookies)}async function cdpImportCookiesWithClient(browser,cookies){return cookies.length===0?0:(await browser.sendCommand("Storage.setCookies",{cookies}),cookies.length)}var BROWSERS_SUBDIR="browsers",STALE_RECORD_TTL_MS=5*6e4,FOCUS_WRITE_THROTTLE_MS=1e3,identity=null,logFn2=()=>{};function initBrowserRegistry(deps){logFn2=deps.log}function recordFileFor2(browserId){return keyedConfigFile(BROWSERS_SUBDIR,browserId)}function ownsRecord(browserId){let existing=readRecord(recordFileFor2(browserId));return!existing||existing.pid===process.pid||!isAlive(existing.pid)}function persist(patch){if(!identity)return;let file2=recordFileFor2(identity.browserId);if(!ownsRecord(identity.browserId))return;let previous=readRecord(file2),record2={pid:process.pid,browserId:identity.browserId,socketPath:identity.socketPath,browserName:identity.browserName,nativeHostVersion:identity.nativeHostVersion,transport:identity.transport,startedAt:identity.startedAt,lastFocusedAt:previous?.lastFocusedAt,extensionVersion:previous?.extensionVersion,...patch,updatedAt:Date.now()};try{writeRecord(file2,record2)}catch(error48){logFn2("browser-registry: failed to write record:",String(error48))}}function registerBrowser(info){let startedAt=identity?.startedAt??new Date().toISOString();identity={browserId:info.browserId,socketPath:info.socketPath,browserName:info.browserName,nativeHostVersion:info.nativeHostVersion,transport:info.transport,startedAt};let previous=readRecord(recordFileFor2(info.browserId));persist({lastFocusedAt:previous?.lastFocusedAt??info.lastFocusedAt??Date.now(),extensionVersion:info.extensionVersion}),logFn2(`browser-registry: registered ${info.browserName} (${info.browserId})`)}var lastFocusWriteAt=0,focusFlushTimer=null;function writeFocusNow(){lastFocusWriteAt=Date.now(),persist({lastFocusedAt:lastFocusWriteAt})}function touchFocus(){if(!identity)return;let elapsed=Date.now()-lastFocusWriteAt;if(elapsed>=FOCUS_WRITE_THROTTLE_MS){writeFocusNow();return}focusFlushTimer||(focusFlushTimer=setTimeout(()=>{focusFlushTimer=null,writeFocusNow()},FOCUS_WRITE_THROTTLE_MS-elapsed),focusFlushTimer.unref())}function unregisterBrowser(){if(focusFlushTimer&&(clearTimeout(focusFlushTimer),focusFlushTimer=null),!identity)return;let file2=recordFileFor2(identity.browserId),existing=readRecord(file2);existing&&existing.pid!==process.pid||removeRecord(file2)}function pruneDeadBrowsers(){let now=Date.now();for(let file2 of listRecordFiles(keyedDir(BROWSERS_SUBDIR))){let rec=readRecord(file2);if(!rec){removeRecord(file2);continue}isAlive(rec.pid)||now-(rec.updatedAt??0)>STALE_RECORD_TTL_MS&&removeRecord(file2)}}function listRegisteredBrowsers(){let records=[];for(let file2 of listRecordFiles(keyedDir(BROWSERS_SUBDIR))){let record2=readRecord(file2);record2&&isAlive(record2.pid)&&records.push(record2)}return records.sort((a,b)=>(b.lastFocusedAt??0)-(a.lastFocusedAt??0)||(b.updatedAt??0)-(a.updatedAt??0))}function providerIdentity(descriptor){return{id:descriptor.providerId,name:descriptor.name,builtin:descriptor.builtin===!0,version:descriptor.version,protocolVersion:descriptor.protocolVersion}}async function ensureDiscoverableCdpBrowser(discovery){return discovery.isPublished()?!0:await discovery.isAvailable()?(discovery.publish(),discovery.monitor(),!0):!1}function ordinaryBrowser(record2){return{browserId:record2.browserId,name:record2.browserName,type:"regular",status:record2.status==="pairing"?"pairing":"connected",extensionVersion:record2.extensionVersion,nativeHostVersion:record2.nativeHostVersion,transport:record2.transport,pairing:record2.pairing}}function externalProviderBrowser(record2){if(!record2.provider||!record2.persistence||!record2.operations)throw new Error(`Provider browser record is incomplete: ${record2.browserId}`);let status=record2.status??"connected";return{browserId:record2.browserId,name:record2.browserName,type:"managed",status,extensionVersion:record2.extensionVersion,nativeHostVersion:record2.nativeHostVersion,transport:record2.transport,provider:record2.provider,ownership:record2.ownership,persistence:record2.persistence,operations:record2.operations,pairing:record2.pairing,references:record2.references,details:record2.details}}function providerBrowserInfo(entry,route){let{browser,provider}=entry,status=route&&(route.status===void 0||route.status==="connected")?"connected":browser.status;return{browserId:browser.browserId,name:browser.name,type:"managed",status,transport:route?.transport??(browser.control.kind==="host"?browser.control.transport:provider.builtin?void 0:"provider"),extensionVersion:route?.extensionVersion,nativeHostVersion:route?.nativeHostVersion,provider,ownership:browser.ownership,persistence:browser.persistence,operations:browser.operations,pairing:browser.pairing,references:browser.references,details:browser.details}}function mergeBrowserInventory(routes,providerBrowsers){let providerById=new Map(providerBrowsers.map(entry=>[entry.browser.browserId,entry])),browsers=[];for(let route of routes){let providerEntry=providerById.get(route.browserId);providerEntry?(providerById.delete(route.browserId),browsers.push(providerBrowserInfo(providerEntry,route))):route.provider||route.transport==="provider"?browsers.push(externalProviderBrowser(route)):browsers.push(ordinaryBrowser(route))}let inactive=[...providerById.values()].sort((a,b)=>{let aCreated=String(a.browser.details?.createdAt??"");return String(b.browser.details?.createdAt??"").localeCompare(aCreated)}).map(entry=>providerBrowserInfo(entry));return browsers.push(...inactive),{count:browsers.length,connectedCount:browsers.filter(browser=>browser.status==="connected").length,browsers}}async function providerInventory(runtimes){return(await Promise.all(runtimes.map(async runtime=>{let provider=providerIdentity(runtime.definition.descriptor);return(await runtime.listBrowsers()).map(browser=>({provider,browser}))}))).flat()}async function listBrowserInventory(runtimes){return mergeBrowserInventory(listRegisteredBrowsers(),await providerInventory(runtimes))}import{randomUUID as randomUUID5}from"node:crypto";var NATIVE_HOST_VERSION="2.16.4";import fs3 from"node:fs";import os2 from"node:os";import path3 from"node:path";var MEARL_CONFIG_FILE=path3.join(os2.homedir(),".mearl","config.json");function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readMearlConfig(configFile=MEARL_CONFIG_FILE){try{let parsed=JSON.parse(fs3.readFileSync(configFile,"utf8"));return isRecord(parsed)?parsed:{}}catch{return{}}}function writeMearlConfig(config2,configFile=MEARL_CONFIG_FILE){let configDirectory=path3.dirname(configFile),temporaryFile=`${configFile}.${process.pid}.tmp`;fs3.mkdirSync(configDirectory,{recursive:!0});try{fs3.writeFileSync(temporaryFile,`${JSON.stringify(config2,null,2)}
595
+ }`,arguments:[{value:ancestorDepth}],returnByValue:!1});if(ancestorObjectId=ancestor.result?.objectId,!ancestorObjectId||ancestor.result?.subtype==="null")throw new Error("page_snapshot: cannot resolve an ancestor for rootRef");let ancestorBackendNodeId=(await sendCdpDeviceShellPageCommand(session,"DOM.describeNode",{objectId:ancestorObjectId})).node?.backendNodeId;if(ancestorBackendNodeId===void 0)throw new Error("page_snapshot: cannot resolve an ancestor for rootRef");return ancestorBackendNodeId}finally{ancestorObjectId&&await sendCdpDeviceShellPageCommand(session,"Runtime.releaseObject",{objectId:ancestorObjectId}).catch(()=>{}),await sendCdpDeviceShellPageCommand(session,"Runtime.releaseObject",{objectId}).catch(()=>{})}}async function getViewportBackendNodeIds(session){let[metrics,captured]=await Promise.all([sendCdpDeviceShellPageCommand(session,"Page.getLayoutMetrics",{}),sendCdpDeviceShellPageCommand(session,"DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!1})]),viewport=resolveDOMSnapshotViewportBounds(metrics);if(!viewport)throw new Error("page_snapshot: viewport metrics are unavailable");let{left,top,width,height}=viewport,right=left+width,bottom=top+height,visible=new Set;for(let document2 of captured.documents??[]){let backendNodeIds=document2.nodes?.backendNodeId??[],nodeIndexes=document2.layout?.nodeIndex??[],bounds=document2.layout?.bounds??[];for(let index=0;index<nodeIndexes.length;index+=1){let box=bounds[index],backendNodeId=backendNodeIds[nodeIndexes[index]];if(!box||backendNodeId===void 0)continue;let[x,y,boxWidth,boxHeight]=box;boxWidth<=0||boxHeight<=0||x<right&&x+boxWidth>left&&y<bottom&&y+boxHeight>top&&visible.add(backendNodeId)}}return visible}async function cdpPageSnapshot(session,data){let mode=data?.mode??"full",rootSelector=data?.rootSelector,rootRef=data?.rootRef,ancestorDepth=data?.ancestorDepth??0,query=resolvePageSnapshotQuery(data?.query);if(!["full","interactive","viewport"].includes(mode))throw new Error("page_snapshot: mode must be one of full, interactive, viewport");if(rootSelector!==void 0&&(typeof rootSelector!="string"||!rootSelector.trim()))throw new Error("page_snapshot: rootSelector must be a non-empty CSS selector");if(rootRef!==void 0&&(typeof rootRef!="string"||!/^@e\d+$/.test(rootRef)))throw new Error('page_snapshot: rootRef must be a snapshot ref like "@e3"');if(rootSelector!==void 0&&rootRef!==void 0)throw new Error("page_snapshot: rootSelector and rootRef are mutually exclusive");if(!Number.isInteger(ancestorDepth)||ancestorDepth<0||ancestorDepth>20)throw new Error("page_snapshot: ancestorDepth must be an integer between 0 and 20");if(ancestorDepth>0&&rootRef===void 0)throw new Error("page_snapshot: ancestorDepth requires rootRef");let rootBackendNodeId;if(rootSelector)rootBackendNodeId=await resolveRootBackendNodeId(session,rootSelector);else if(rootRef){let entry=resolvePageRef(session,rootRef);if(!entry)throw new Error(`Ref ${rootRef} not found. Run page_snapshot first to get fresh refs.`);rootBackendNodeId=await resolveAncestorBackendNodeId(session,entry.backendNodeId,ancestorDepth)}let snapshotRefs=beginPageSnapshotRefs(session),[result,visibleBackendNodeIds]=await Promise.all([sendCdpDeviceShellPageCommand(session,rootBackendNodeId===void 0?"Accessibility.getFullAXTree":"Accessibility.queryAXTree",rootBackendNodeId===void 0?{depth:data?.depth}:{backendNodeId:rootBackendNodeId}),mode==="viewport"||mode==="interactive"?getViewportBackendNodeIds(session):Promise.resolve(void 0)]),nodes=result.nodes??[];await reconcileAXCheckedStates(nodes,backendNodeId=>readDOMCheckedState2(session,backendNodeId));let nodeMap=new Map;for(let node of nodes)nodeMap.set(node.nodeId,node);let rootNode=nodes[0];if(!rootNode)return snapshotRefs.commit(new Set),{snapshot:"(empty page)",refs:{},elementCount:0,outputNodeCount:1,mode,...rootSelector?{rootSelector}:{},...rootRef?{rootRef,ancestorDepth}:{},...query?{query,matches:[],matchCount:0}:{}};let rawTree=buildSnapshotTree(nodeMap,rootNode.nodeId,snapshotRefs),viewportFilteredTree=mode==="interactive"?filterSnapshotTree(rawTree,"viewport",visibleBackendNodeIds):rawTree,effectiveMode=mode;mode==="interactive"&&!hasInteractiveSnapshotNode(viewportFilteredTree)&&(effectiveMode="viewport");let modeFilteredTree=mode==="interactive"?effectiveMode==="interactive"?filterSnapshotTree(viewportFilteredTree,"interactive"):viewportFilteredTree:filterSnapshotTree(rawTree,effectiveMode,visibleBackendNodeIds),queryResult=query?filterSnapshotTreeByQuery(modeFilteredTree,query):{tree:modeFilteredTree,matches:[]},limitedMatches=query?limitPageSnapshotQueryMatches(queryResult.matches):{matches:[],truncated:!1},tree=queryResult.tree,lines=[];tree&&formatSnapshotNode(tree,0,lines);let formatted=formatSnapshotWithLimits(lines.length>0?lines:[query?"(no matches)":"(empty page)"],{maxChars:data?.maxChars,maxNodes:data?.maxNodes}),refs={},outputRefKeys=new Set(Array.from(formatted.snapshot.matchAll(/(?:^|\n)\s*(@e\d+)\s/g),match=>match[1]));for(let match of limitedMatches.matches)match.ref&&outputRefKeys.add(match.ref);snapshotRefs.commit(outputRefKeys);let registry2=getPageRefRegistry(session);for(let ref of outputRefKeys){let entry=registry2.resolve(ref);entry&&(refs[ref.slice(1)]={backendNodeId:entry.backendNodeId})}return{snapshot:formatted.snapshot,refs,elementCount:countSnapshotNodes(tree),outputNodeCount:formatted.outputNodeCount,mode,...rootSelector?{rootSelector}:{},...rootRef?{rootRef,ancestorDepth}:{},...query?{query,matches:limitedMatches.matches,matchCount:queryResult.matches.length,...limitedMatches.truncated?{matchesTruncated:!0}:{}}:{},...effectiveMode!==mode?{fallbackMode:"viewport"}:{},...formatted.truncated?{truncated:!0}:{}}}async function cdpPageFrames(session,_data){let result=await session.client.sendCommand("Page.getFrameTree",{});function flattenFrameTree(tree){if(!tree)return[];let{frame,childFrames=[]}=tree;return[{frameId:frame.id,parentFrameId:frame.parentId??null,url:frame.url,name:frame.name??""},...childFrames.flatMap(flattenFrameTree)]}let frames=flattenFrameTree(result.frameTree);return{frames,count:frames.length}}registerActions([{name:"page_snapshot",session:"page",handler:cdpPageSnapshot},{name:"page_frames",session:"page",handler:cdpPageFrames}]);var MEARL_SERVICE_COOKIE_DOMAINS=["tdbank.alibaba-inc.com","ats2.alibaba-inc.com","g.alibaba-inc.com","login.alibaba-inc.com","token-hub.alibaba-inc.com","alibaba-inc.com"],MEARL_SERVICE_COOKIE_HOSTS=new Set(MEARL_SERVICE_COOKIE_DOMAINS);function normalizeCookieDomain2(input){let value=input.trim();if(!value)throw new Error("Cookie domain must be a non-empty string");let hostname3;try{hostname3=new URL(value.includes("://")?value:`https://${value}`).hostname}catch{throw new Error(`Invalid cookie domain: ${input}`)}if(hostname3=hostname3.toLowerCase().replace(/^\.+/,"").replace(/\.+$/,""),!hostname3)throw new Error(`Invalid cookie domain: ${input}`);return hostname3}function normalizeCookieDomains(inputs){if(!Array.isArray(inputs))throw new Error("copyCookieDomains must be an array of domains");return[...new Set(inputs.map(value=>normalizeCookieDomain2(String(value))))]}function isMearlServiceCookie(cookie){let domain2=normalizeCookieDomain2(cookie.domain);return MEARL_SERVICE_COOKIE_HOSTS.has(domain2)?!0:domain2.endsWith(".tdbank.alibaba-inc.com")||domain2.endsWith(".ats2.alibaba-inc.com")}function normalizeCookieCopyScope(input){let presets=input.presets??[];if(!Array.isArray(presets)||presets.some(preset=>preset!=="mearl-services"))throw new Error("copyCookieDomains.presets contains an unsupported preset");return{includeMearlServices:presets.includes("mearl-services"),domains:normalizeCookieDomains(input.domains??[])}}function resolveCookieCopyPlan(input){let includeMearlServices=!1,explicitDomains=[];if(input==="mearl-services")includeMearlServices=!0;else if(Array.isArray(input))explicitDomains=normalizeCookieDomains(input);else if(input!=null&&typeof input=="object"){let scope=normalizeCookieCopyScope(input);includeMearlServices=scope.includeMearlServices,explicitDomains=scope.domains}else if(input!==void 0)throw new Error('copyCookieDomains must be an array of domains, "mearl-services", or a scope object');return includeMearlServices?{domains:[...new Set([...MEARL_SERVICE_COOKIE_DOMAINS,...explicitDomains])],select:cookies=>cookies.filter(cookie=>isMearlServiceCookie(cookie)||explicitDomains.some(domain2=>cookieMatchesDomain(cookie.domain,domain2)))}:{domains:explicitDomains,select:cookies=>cookies}}function cookieMatchesDomain(cookieDomain,requestedDomain){let cookieHost=cookieDomain.toLowerCase().replace(/^\.+/,"");return cookieHost===requestedDomain||cookieHost.endsWith(`.${requestedDomain}`)||requestedDomain.endsWith(`.${cookieHost}`)}function toTransferableCookie(cookie){let result={name:String(cookie.name),value:String(cookie.value),domain:String(cookie.domain),path:String(cookie.path||"/"),secure:!!cookie.secure,httpOnly:!!cookie.httpOnly};return["Strict","Lax","None"].includes(cookie.sameSite)&&(result.sameSite=cookie.sameSite),typeof cookie.expires=="number"&&cookie.expires>0&&(result.expires=cookie.expires),["Low","Medium","High"].includes(cookie.priority)&&(result.priority=cookie.priority),typeof cookie.sameParty=="boolean"&&(result.sameParty=cookie.sameParty),["Unset","NonSecure","Secure"].includes(cookie.sourceScheme)&&(result.sourceScheme=cookie.sourceScheme),typeof cookie.sourcePort=="number"&&(result.sourcePort=cookie.sourcePort),cookie.partitionKey?.topLevelSite&&(result.partitionKey={topLevelSite:String(cookie.partitionKey.topLevelSite),...typeof cookie.partitionKey.hasCrossSiteAncestor=="boolean"?{hasCrossSiteAncestor:cookie.partitionKey.hasCrossSiteAncestor}:{}}),result}async function cdpExportCookies(session,domains){let requestedDomains=normalizeCookieDomains(domains);return((await(await session.getBrowserClient()).sendCommand("Storage.getCookies",{})).cookies??[]).filter(cookie=>requestedDomains.some(domain2=>cookieMatchesDomain(String(cookie.domain),domain2))).map(toTransferableCookie)}async function cdpImportCookies(session,cookies){if(cookies.length===0)return 0;let browser=await session.getBrowserClient();return cdpImportCookiesWithClient(browser,cookies)}async function cdpImportCookiesWithClient(browser,cookies){return cookies.length===0?0:(await browser.sendCommand("Storage.setCookies",{cookies}),cookies.length)}var BROWSERS_SUBDIR="browsers",STALE_RECORD_TTL_MS=5*6e4,FOCUS_WRITE_THROTTLE_MS=1e3,identity=null,logFn2=()=>{};function initBrowserRegistry(deps){logFn2=deps.log}function recordFileFor2(browserId){return keyedConfigFile(BROWSERS_SUBDIR,browserId)}function ownsRecord(browserId){let existing=readRecord(recordFileFor2(browserId));return!existing||existing.pid===process.pid||!isAlive(existing.pid)}function persist(patch){if(!identity)return;let file2=recordFileFor2(identity.browserId);if(!ownsRecord(identity.browserId))return;let previous=readRecord(file2),record2={pid:process.pid,browserId:identity.browserId,socketPath:identity.socketPath,browserName:identity.browserName,nativeHostVersion:identity.nativeHostVersion,transport:identity.transport,startedAt:identity.startedAt,lastFocusedAt:previous?.lastFocusedAt,extensionVersion:previous?.extensionVersion,...patch,updatedAt:Date.now()};try{writeRecord(file2,record2)}catch(error48){logFn2("browser-registry: failed to write record:",String(error48))}}function registerBrowser(info){let startedAt=identity?.startedAt??new Date().toISOString();identity={browserId:info.browserId,socketPath:info.socketPath,browserName:info.browserName,nativeHostVersion:info.nativeHostVersion,transport:info.transport,startedAt};let previous=readRecord(recordFileFor2(info.browserId));persist({lastFocusedAt:previous?.lastFocusedAt??info.lastFocusedAt??Date.now(),extensionVersion:info.extensionVersion}),logFn2(`browser-registry: registered ${info.browserName} (${info.browserId})`)}var lastFocusWriteAt=0,focusFlushTimer=null;function writeFocusNow(){lastFocusWriteAt=Date.now(),persist({lastFocusedAt:lastFocusWriteAt})}function touchFocus(){if(!identity)return;let elapsed=Date.now()-lastFocusWriteAt;if(elapsed>=FOCUS_WRITE_THROTTLE_MS){writeFocusNow();return}focusFlushTimer||(focusFlushTimer=setTimeout(()=>{focusFlushTimer=null,writeFocusNow()},FOCUS_WRITE_THROTTLE_MS-elapsed),focusFlushTimer.unref())}function unregisterBrowser(){if(focusFlushTimer&&(clearTimeout(focusFlushTimer),focusFlushTimer=null),!identity)return;let file2=recordFileFor2(identity.browserId),existing=readRecord(file2);existing&&existing.pid!==process.pid||removeRecord(file2)}function pruneDeadBrowsers(){let now=Date.now();for(let file2 of listRecordFiles(keyedDir(BROWSERS_SUBDIR))){let rec=readRecord(file2);if(!rec){removeRecord(file2);continue}isAlive(rec.pid)||now-(rec.updatedAt??0)>STALE_RECORD_TTL_MS&&removeRecord(file2)}}function listRegisteredBrowsers(){let records=[];for(let file2 of listRecordFiles(keyedDir(BROWSERS_SUBDIR))){let record2=readRecord(file2);record2&&isAlive(record2.pid)&&records.push(record2)}return records.sort((a,b)=>(b.lastFocusedAt??0)-(a.lastFocusedAt??0)||(b.updatedAt??0)-(a.updatedAt??0))}function providerIdentity(descriptor){return{id:descriptor.providerId,name:descriptor.name,builtin:descriptor.builtin===!0,version:descriptor.version,protocolVersion:descriptor.protocolVersion}}async function ensureDiscoverableCdpBrowser(discovery){return discovery.isPublished()?!0:await discovery.isAvailable()?(discovery.publish(),discovery.monitor(),!0):!1}function ordinaryBrowser(record2){return{browserId:record2.browserId,name:record2.browserName,type:"regular",status:record2.status==="pairing"?"pairing":"connected",extensionVersion:record2.extensionVersion,nativeHostVersion:record2.nativeHostVersion,transport:record2.transport,pairing:record2.pairing}}function externalProviderBrowser(record2){if(!record2.provider||!record2.persistence||!record2.operations)throw new Error(`Provider browser record is incomplete: ${record2.browserId}`);let status=record2.status??"connected";return{browserId:record2.browserId,name:record2.browserName,type:"managed",status,extensionVersion:record2.extensionVersion,nativeHostVersion:record2.nativeHostVersion,transport:record2.transport,provider:record2.provider,ownership:record2.ownership,persistence:record2.persistence,operations:record2.operations,pairing:record2.pairing,references:record2.references,details:record2.details}}function providerBrowserInfo(entry,route){let{browser,provider}=entry,status=route&&(route.status===void 0||route.status==="connected")?"connected":browser.status;return{browserId:browser.browserId,name:browser.name,type:"managed",status,transport:route?.transport??(browser.control.kind==="host"?browser.control.transport:provider.builtin?void 0:"provider"),extensionVersion:route?.extensionVersion,nativeHostVersion:route?.nativeHostVersion,provider,ownership:browser.ownership,persistence:browser.persistence,operations:browser.operations,pairing:browser.pairing,references:browser.references,details:browser.details}}function mergeBrowserInventory(routes,providerBrowsers){let providerById=new Map(providerBrowsers.map(entry=>[entry.browser.browserId,entry])),browsers=[];for(let route of routes){let providerEntry=providerById.get(route.browserId);providerEntry?(providerById.delete(route.browserId),browsers.push(providerBrowserInfo(providerEntry,route))):route.provider||route.transport==="provider"?browsers.push(externalProviderBrowser(route)):browsers.push(ordinaryBrowser(route))}let inactive=[...providerById.values()].sort((a,b)=>{let aCreated=String(a.browser.details?.createdAt??"");return String(b.browser.details?.createdAt??"").localeCompare(aCreated)}).map(entry=>providerBrowserInfo(entry));return browsers.push(...inactive),{count:browsers.length,connectedCount:browsers.filter(browser=>browser.status==="connected").length,browsers}}async function providerInventory(runtimes){return(await Promise.all(runtimes.map(async runtime=>{let provider=providerIdentity(runtime.definition.descriptor);return(await runtime.listBrowsers()).map(browser=>({provider,browser}))}))).flat()}async function listBrowserInventory(runtimes){return mergeBrowserInventory(listRegisteredBrowsers(),await providerInventory(runtimes))}import{randomUUID as randomUUID5}from"node:crypto";var NATIVE_HOST_VERSION="2.17.0";import fs3 from"node:fs";import os2 from"node:os";import path3 from"node:path";var MEARL_CONFIG_FILE=path3.join(os2.homedir(),".mearl","config.json");function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readMearlConfig(configFile=MEARL_CONFIG_FILE){try{let parsed=JSON.parse(fs3.readFileSync(configFile,"utf8"));return isRecord(parsed)?parsed:{}}catch{return{}}}function writeMearlConfig(config2,configFile=MEARL_CONFIG_FILE){let configDirectory=path3.dirname(configFile),temporaryFile=`${configFile}.${process.pid}.tmp`;fs3.mkdirSync(configDirectory,{recursive:!0});try{fs3.writeFileSync(temporaryFile,`${JSON.stringify(config2,null,2)}
596
596
  `,{mode:384}),fs3.renameSync(temporaryFile,configFile)}catch(error48){try{fs3.unlinkSync(temporaryFile)}catch{}throw error48}}var MEASUREMENT_ID="G-W84LJDZ6PH",API_SECRET="X233siI5RrGYLhlD0kBKEQ",ENDPOINT=`https://www.google-analytics.com/mp/collect?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,CLIENT_ID_PATTERN=/^\d+\.\d+$/,BUILD_CHANNEL=NATIVE_HOST_VERSION==="unknown"?"development":"production";function writeConfig(config2){try{writeMearlConfig(config2)}catch{}}var clientId=null;function createClientId(seed=randomUUID5()){let first=2166136261,second=2246822519;for(let index=0;index<seed.length;index++){let code=seed.charCodeAt(index);first=Math.imul(first^code,16777619)>>>0,second=Math.imul(second^code,3266489917)>>>0}return`${first||1}.${second||1}`}function getClientId(){if(clientId)return clientId;let config2=readMearlConfig();return config2.clientId&&CLIENT_ID_PATTERN.test(config2.clientId)?(clientId=config2.clientId,clientId):(clientId=createClientId(config2.clientId),writeConfig({...config2,clientId}),clientId)}function setAnalyticsClientId(value){return typeof value!="string"||!CLIENT_ID_PATTERN.test(value)?!1:(clientId=value,!0)}function classifyAnalyticsError(error48){let message=error48 instanceof Error?error48.message:String(error48);return/timed?\s*out|timeout/i.test(message)?"timeout":/permission|not authorized|access denied|forbidden/i.test(message)?"permission_denied":/not found|no matching|does not exist/i.test(message)?"not_found":/not connected|disconnected|unavailable|connection (?:failed|closed)/i.test(message)?"unavailable":/invalid|required|must be|unsupported/i.test(message)?"invalid_request":"execution_error"}function trackAction(action,params){let payload={client_id:getClientId(),events:[{name:"agent_action",params:{action,...params,mearl_version:NATIVE_HOST_VERSION,runtime:"native_host",build_channel:BUILD_CHANNEL}}]};fetch(ENDPOINT,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(payload),keepalive:!0}).catch(()=>{})}import{open}from"node:fs/promises";import path5 from"node:path";var TRUNCATED_MARKER=`
597
597
  … [middle truncated for Native Messaging] …
598
598
  `;function truncateUtf82(value,maxBytes){if(Buffer.byteLength(value,"utf8")<=maxBytes)return value;let markerBytes=Buffer.byteLength(TRUNCATED_MARKER,"utf8");if(maxBytes<=markerBytes)return"";let source=Buffer.from(value,"utf8"),contentBytes=maxBytes-markerBytes,headBytes=Math.ceil(contentBytes/2),tailBytes=Math.floor(contentBytes/2);do{let truncated=`${source.subarray(0,headBytes).toString("utf8")}${TRUNCATED_MARKER}${source.subarray(source.length-tailBytes).toString("utf8")}`;if(Buffer.byteLength(truncated,"utf8")<=maxBytes)return truncated;headBytes>=tailBytes?headBytes-=1:tailBytes-=1}while(headBytes>0&&tailBytes>0);return""}function sanitizeValue(value,budget,depth){if(value===null||typeof value=="boolean"||typeof value=="number")return value;if(typeof value=="string"){let available=Math.max(0,budget.remaining),next2=truncateUtf82(value,available),bytes=Buffer.byteLength(next2,"utf8");return budget.remaining=Math.max(0,budget.remaining-bytes),next2!==value&&(budget.truncated=!0),next2}if(typeof value>"u")return null;if(typeof value!="object")return String(value);if(depth>=12||budget.remaining<=0)return budget.truncated=!0,{__transportTruncated:!0};if(budget.seen.has(value))return budget.truncated=!0,"[Circular]";if(budget.seen.add(value),Array.isArray(value)){let next2=value.slice(0,160).map(entry=>sanitizeValue(entry,budget,depth+1));return value.length>160&&(budget.truncated=!0,next2.push({__transportTruncated:!0,originalLength:value.length})),next2}let entries=Object.entries(value),next={};for(let[index,[key,entry]]of entries.entries()){if(index>=160||budget.remaining<=0){budget.truncated=!0;break}budget.remaining=Math.max(0,budget.remaining-Buffer.byteLength(key,"utf8")),next[key]=sanitizeValue(entry,budget,depth+1)}return budget.truncated&&(next.__transportTruncated=!0),next}function sanitizeAgentChatEvent(event){let budget={remaining:409600,truncated:!1,seen:new WeakSet},next={...event,params:sanitizeValue(event.params,budget,0)},bytes=Buffer.byteLength(JSON.stringify(next),"utf8");return bytes<=524288?next:{...event,params:{__transportTruncated:!0,originalBytes:bytes,message:"Agent event exceeded the Native Messaging transport limit."}}}import fs4 from"node:fs";import path4 from"node:path";import{execFile}from"node:child_process";function selectedPath(stdout){return stdout.replace(/[\r\n]+$/,"")||null}var runDirectoryPickerCommand=(command,args)=>new Promise((resolve2,reject)=>{execFile(command,args,{encoding:"utf8",windowsHide:!0},(error48,stdout)=>{if(!error48){resolve2(selectedPath(stdout));return}if(error48.code===1){resolve2(null);return}reject(error48)})});function isMissingCommand(error48){return error48 instanceof Error&&error48.code==="ENOENT"}async function pickWorkspaceDirectory(platform=process.platform,run=runDirectoryPickerCommand){let directory;if(platform==="darwin")directory=await run("osascript",["-e",'POSIX path of (choose folder with prompt "Select a workspace for Agent Chat")']);else if(platform==="win32"){let script=["Add-Type -AssemblyName System.Windows.Forms;","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;","$dialog.Description = 'Select a workspace for Agent Chat';","if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {","[Console]::OutputEncoding = [System.Text.Encoding]::UTF8;","Write-Output $dialog.SelectedPath;","}"].join(" ");directory=await run("powershell.exe",["-NoProfile","-STA","-Command",script])}else if(platform==="linux")try{directory=await run("zenity",["--file-selection","--directory","--title=Select a workspace for Agent Chat"])}catch(error48){if(!isMissingCommand(error48))throw error48;try{directory=await run("kdialog",["--getexistingdirectory",".","--title","Select a workspace for Agent Chat"])}catch(fallbackError){throw isMissingCommand(fallbackError)?new Error("Install zenity or kdialog to select an Agent Chat workspace",{cause:fallbackError}):fallbackError}}else throw new Error(`Directory selection is not supported on ${platform}`);return directory?resolveWorkspaceDirectory(directory):null}function resolveWorkspaceDirectory(directory){if(typeof directory!="string"||!directory)throw new Error("Workspace directory is required");if(!path4.isAbsolute(directory))throw new Error("Workspace directory must be an absolute path");let resolved;try{resolved=fs4.realpathSync.native(directory)}catch(error48){throw new Error(`Workspace directory does not exist: ${directory}`,{cause:error48})}if(!fs4.statSync(resolved).isDirectory())throw new Error(`Workspace path is not a directory: ${directory}`);return resolved}var MAX_REPLAY_EVENTS=1e3,MAX_REPLAY_BYTES=2048*1024,MAX_REPLAY_PAGE_BYTES=524288,MAX_SKILL_FILE_BYTES=1024*1024,SUPPORTED_IMAGE_MIME_TYPES=new Set(AGENT_CHAT_SUPPORTED_IMAGE_MIME_TYPES),REPLAY_SNAPSHOT_METHODS=new Set(["thread/settings/updated"]);function createAgentDeveloperInstructions({cwd,tabId,initialPageUrl,initialPageTitle}){return[...cwd?[createAgentDirectoryContextInstructions(cwd)]:[],...tabId!==void 0?[createBrowserAgentDeveloperInstructions(tabId,{...initialPageUrl?{url:initialPageUrl}:{},...initialPageTitle?{title:initialPageTitle}:{}})]:[]].join(`