@doubao-dev/cli 0.0.39 → 0.0.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/1453.js +1 -1
- package/dist/4315~0.js +1 -1
- package/dist/assets/web-sdk-debugger/__doubao_web_sdk_native_modules/applet-bridge-module-core.js +1 -1
- package/dist/assets/web-sdk-debugger/assets/framework/doubao-apps-framework.template.js +0 -0
- package/dist/assets/web-sdk-debugger/index.html +1 -1
- package/dist/assets/web-sdk-debugger/static/js/{index.07586cb0fe.js → index.abdb68a2f4.js} +3 -3
- package/dist/sdk.js +46 -46
- package/package.json +2 -2
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/13-/347/231/273/345/275/225.md +22 -8
- package/skills/doubao-agentic-service-development/references/frontend/widget-templates/props.md +12 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(()=>{"use strict";var e,t,r,n,a,i,s,o,l,d,u,c,p={33376(e,t,r){let n,a;r(52205),r(40768),r(76235),r(15254),r(42949),r(18723),r(37891);var i=r(63159);function s(e){return"object"==typeof e&&null!==e}function o(e){var t;return"string"==typeof(null==(t=e.web)?void 0:t.entry)}function l(e,t){let r=new Map;for(let n of e){let e=t(n);e&&!r.has(e)&&r.set(e,n)}return r}function d(e){return"string"==typeof e?e||void 0:(null==e?void 0:e["3x"])||(null==e?void 0:e["2x"])||(null==e?void 0:e["1x"])}r(84086),r(21301),r(32037),r(14104),r(99811),r(40009),r(13035),r(13412),r(17973),r(64955),r(91016),r(23306),r(76619),r(57857),r(9975),r(93885),r(812),r(74180),r(994),r(4267),r(74678),r(55910),r(76691),r(72919);class u{raw;appEntry;pageEntries;pageIdEntryMap;pagePathEntryMap;widgetEntries;widgetEntryMap;constructor(e){var t;let r;this.raw=e,this.appEntry="string"==typeof(r=(null==(t=e.applet.web)?void 0:t.appRuntimeEntry)??e.applet.appRuntimeEntry)&&r?{entry:r}:null,this.pageEntries=e.applet.pages.filter(o),this.pageIdEntryMap=l(this.pageEntries,e=>e.id),this.pagePathEntryMap=l(this.pageEntries,e=>{var t;return(null==(t=e.path)?void 0:t.startsWith("/"))?e.path:void 0}),this.widgetEntries=e.widgets,this.widgetEntryMap=l(this.widgetEntries,e=>e.widgetId)}get appId(){return"string"==typeof this.raw.appId?this.raw.appId:void 0}get name(){return this.raw.applet.name}get iconSrc(){return d(this.raw.applet.icons)}get versionName(){return this.raw.versionName||this.raw.versionTag||this.raw.versionCode||void 0}get pages(){return this.getPageEntries()}get widgets(){return this.getWidgetEntries()}get appRuntimeEntry(){return this.appEntry}getPageEntries(){return[...this.pageEntries]}getWidgetEntries(){return[...this.widgetEntries]}getOptionalWidgetEntry(e){return e?this.widgetEntryMap.get(e):this.widgetEntries[0]}getPageEntry(e){let t=e?e.startsWith("/")?this.pagePathEntryMap.get(e):this.pageIdEntryMap.get(e):this.pageEntries[0];if(!t)throw Error(e?`Unknown pages entry: ${e}`:"No pages entries in Web manifest");return t}getWidgetEntry(e){let t=this.getOptionalWidgetEntry(e);if(!t)throw Error(e?`Unknown widgets entry: ${e}`:"No widgets entries in Web manifest");return t}}async function c(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.fetcher??fetch,n=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!n.ok)throw Error(`Failed to load Web manifest: ${n.status} ${n.statusText}`);let a=await n.json();if(!s(a))throw Error("Invalid Web manifest: expected a JSON object");return new u(a)}function p(e,t,r){var n,a;let i="item"in t?t.item:t,s="id"in i||"widgetId"in i?"string"==typeof(null==(n=i.web)?void 0:n.entry)?i.web.entry:void 0:i.entry;if(!s)return;let o=new URL(e,r??(null==(a=globalThis.location)?void 0:a.href)??"http://localhost/");return o.pathname=o.pathname.replace(/\/base\/manifest\.json$/,"/"),new URL(s,o).toString()}function h(){let e=Error("Widget host call was cancelled");return e.name="AbortError",e}function m(e){if(e.aborted)throw h()}function g(e,t){return m(t),new Promise((r,n)=>{let a=!1,i=e=>{a||(a=!0,t.removeEventListener("abort",s),e())},s=()=>i(()=>n(h()));t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(e).then(e=>i(()=>r(e)),e=>i(()=>n(e)))})}function f(e){return(null==e?void 0:e.type)==="call"}function v(e){return(null==e?void 0:e.type)==="callback"}function y(e){return(null==e?void 0:e.type)==="event"}r(67548),r(70954),r(98803),r(79162),r(15385),r(39342),r(69152),r(61955),r(82689),r(84847),r(16285),r(20602),r(33307),r(94341),r(7270),r(44997),r(50364),r(79780),r(80372),r(72498),r(37928),r(25597),r(92321);class _ extends Error{errNo;errMsg;constructor(e,t,r=e){super(e),this.errNo=t,this.errMsg=r,Object.setPrototypeOf(this,new.target.prototype),this.name="BridgeAPIError"}}function b(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function w(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t;return{type:"callback",callbackId:e.callbackId,params:{code:0,msg:t,errNo:r,errMsg:n}}}function S(e){return e instanceof Error?e.message:String(e)}function x(e,t){return t instanceof _?w(e,t.message,t.errNo,t.errMsg):w(e,S(t))}class I{registry=new Map;eventSources=new Map;eventSourceCleanups=new Map;eventSourceRetainCounts=new Map;eventControllers=new Set;handlers={};constructor(e){e&&this.registerMany(e)}register(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.registry.has(e))throw Error(`Bridge API handler ${e} is already registered`);let n=this.registry.get(e),a="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,a),this.handlers[e]=a.handler,()=>{if(this.registry.get(e)===a){if(n){this.registry.set(e,n),this.handlers[e]=n.handler;return}this.registry.delete(e),delete this.handlers[e]}}}registerMany(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[n,a]of Object.entries(e))r.push(this.register(n,a,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}get(e){var t;return null==(t=this.registry.get(e))?void 0:t.handler}getSyncResults(e){let t={};for(let[r,n]of this.registry)n.syncResult&&this.canIUse(r,e)&&(t[r]="function"==typeof n.syncResult?n.syncResult({...e,apiRegistry:this}):n.syncResult);return t}registerEventSource(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.eventSources.has(e))throw Error(`Bridge event source ${e} is already registered`);let n=this.eventSources.get(e),a="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,a),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,a),()=>{if(this.eventSources.get(e)===a){if(this.stopEventSource(e),n){this.eventSources.set(e,n),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,n);return}this.eventSources.delete(e)}}}registerEventSources(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[n,a]of Object.entries(e))r.push(this.registerEventSource(n,a,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}canIUse(e,t){let r=this.registry.get(e);if(r)return"function"==typeof r.canIUse?r.canIUse({...t,apiRegistry:this}):r.canIUse;let n=this.eventSources.get(e);return!!n&&("function"==typeof n.canIUse?n.canIUse({...t,apiRegistry:this}):n.canIUse??!0)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;if(!f(e))return;let n={...t,apiRegistry:this};if(this.canIUse(e.name,n))return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!f(e))return;let n=t[e.name];if(!n)return w(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=n(e,r);if(t instanceof Promise)return t.catch(t=>x(e,t));return t??w(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return x(e,t)}}(e,this.handlers,n);if(!r)return w(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=r(e.name);return t instanceof Promise?t.then(()=>b(e,{})).catch(t=>x(e,t)):b(e,{})}catch(t){return x(e,t)}}getSupportedNames(e){return[...new Set([...this.registry.keys(),...this.eventSources.keys()])].filter(t=>this.canIUse(t,e))}emitEvent(e,t){let r=!1;for(let n of this.eventControllers)r=n.emit(e,t)||r;return r}createEventController(e){return new k(this,e)}fork(){let e=new I(this.getRegistrations());return e.registerEventSources(this.getEventSources()),e}getRegistrations(){return Object.fromEntries(this.registry)}getEventSources(){return Object.fromEntries(this.eventSources)}attachEventController(e){return this.eventControllers.add(e),()=>{this.eventControllers.delete(e)}}retainEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(this.eventSourceRetainCounts.set(e,t+1),t>0)return;let r=this.eventSources.get(e);r&&this.startEventSource(e,r)}releaseEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(t<=1){this.eventSourceRetainCounts.delete(e),this.stopEventSource(e);return}this.eventSourceRetainCounts.set(e,t-1)}startEventSource(e,t){this.stopEventSource(e);let r=t.source(t=>{this.emitEvent(e,t)});"function"==typeof r&&this.eventSourceCleanups.set(e,r)}stopEventSource(e){var t;null==(t=this.eventSourceCleanups.get(e))||t(),this.eventSourceCleanups.delete(e)}}class k{apiRegistry;dispatch;cleanupRegistry;subscribedEventNames=new Set;constructor(e,t){this.apiRegistry=e,this.dispatch=t,this.cleanupRegistry=this.apiRegistry.attachEventController(this)}subscribe(e){this.subscribedEventNames.has(e)||(this.subscribedEventNames.add(e),this.apiRegistry.retainEventSource(e))}unsubscribe(e){this.subscribedEventNames.delete(e)&&this.apiRegistry.releaseEventSource(e)}isSubscribed(e){return this.subscribedEventNames.has(e)}emit(e,t){return!!this.isSubscribed(e)&&(this.dispatch(e,t),!0)}destroy(){for(let e of this.subscribedEventNames)this.apiRegistry.releaseEventSource(e);this.subscribedEventNames.clear(),this.cleanupRegistry()}}let C=new I;function E(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n;return null==e?void 0:e.getPackageInfo()}async function N(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;return await (null==t?void 0:t.navigateTo(e)),!!t}async function M(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;return await (null==t?void 0:t.redirectTo(e)),!!t}async function T(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;return await (null==t?void 0:t.reLaunch(e)),!!t}function R(e){var t;let{screenWidth:r,statusBarHeight:n}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),a=Math.round(n)+4,i=Math.round(r)-12;return{bottom:a+36,height:36,left:i-84,right:i,top:a,width:84}}function A(){return(navigator.language||"zh-CN").replace("-","_")}function P(){var e,t,r;return(null==(t=(r=window).matchMedia)||null==(e=t.call(r,"(prefers-color-scheme: dark)"))?void 0:e.matches)?"dark":"light"}function j(){return"u"<typeof DoubaoAppsSDKVersion?void 0:DoubaoAppsSDKVersion}function L(){return navigator.userAgentData}function D(){var e;let t=null==(e=L())?void 0:e.brands,r=null==t?void 0:t.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==r?void 0:r.brand)return r.brand;let n=navigator.userAgent??"";return/edg\//i.test(n)?"Microsoft Edge":/chrome|crios/i.test(n)?"Chrome":/firefox|fxios/i.test(n)?"Firefox":/safari/i.test(n)?"Safari":"Browser"}function O(){var e,t;let r=null==(e=L())?void 0:e.brands,n=null==r?void 0:r.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==n?void 0:n.version)return n.version;let a=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(a))?void 0:t[1])??void 0}function U(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",n=(null==(e=L())?void 0:e.platform)??"",a=`${n} ${r} ${t}`,i=navigator.maxTouchPoints??0;return/android/i.test(a)?{platform:"android",brand:"Android"}:/iphone/i.test(a)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(a)||/mac/i.test(r)&&i>1?{platform:"ios",brand:"iPad"}:/mac/i.test(a)?{platform:"mac",brand:"Mac"}:/win/i.test(a)?{platform:"windows",brand:"Windows"}:/linux/i.test(a)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function q(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function $(){var e,t,r,n,a;let i=Math.round((null==(n=window.visualViewport)?void 0:n.width)??window.innerWidth??0),s=Math.round((null==(a=window.visualViewport)?void 0:a.height)??window.innerHeight??0),o=window.devicePixelRatio??1,l=Math.round((null==(e=window.screen)?void 0:e.width)??i),d=Math.round((null==(t=window.screen)?void 0:t.height)??s),u=Math.round((null==(r=window.visualViewport)?void 0:r.offsetTop)??0);return{pixelRatio:o,screenWidth:l,screenHeight:d,windowWidth:i,windowHeight:s,statusBarHeight:u,safeArea:{left:0,right:i,top:u,bottom:s,width:i,height:Math.max(0,s-u)},screenTop:u}}function B(){return U().platform}function F(){var e,t,r,n,a;let i=navigator.userAgent??"",s=B();return"android"===s?null==(e=/android\s+([\d.]+)/i.exec(i))?void 0:e[1]:"ios"===s?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(i))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===s?null==(a=/mac os x\s+([\d_]+)/i.exec(i))||null==(n=a[1])?void 0:n.replace(/_/g,"."):void 0}function W(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:B();return"android"===e?"Android":"ios"===e?"iOS":"mac"===e?"macOS":"windows"===e?"Windows":"linux"===e?"Linux":"Web"}function H(){return{isConnected:!0,networkType:"unknown",hasSystemProxy:!1,weakNet:!1}}function z(){let e,t=U(),r=navigator.platform||B();return{abi:r,deviceAbi:r,benchmarkLevel:-1,brand:t.brand,model:function(){let e=navigator.userAgent??"",t=B();if("android"===t){var r,n;return(null==(n=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=n[1])?void 0:r.trim())||"Android"}return"ios"===t?U().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||U().brand:D()}(),system:function(){let e=B(),t=F();if("web"!==e){let r=W(e);return t?`${r} ${t}`:r}let r=O(),n=D();return r?`${n} ${r}`:"Web"}(),platform:t.platform,cpuType:r,memorySize:"number"==typeof(e=navigator.deviceMemory)&&Number.isFinite(e)?String(Math.round(1024*e)):""}}function V(){let e=z(),t=$(),r=t.windowWidth>t.windowHeight;return{os:W(e.platform),platform:e.platform,osVersion:F(),deviceBrand:e.brand,deviceModel:e.model,deviceType:e.model,channel:"debug",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function G(){let e=$(),t=z();return{...e,brand:t.brand,model:t.model,language:A(),version:O(),system:t.system,platform:t.platform,SDKVersion:j(),theme:P(),benchmarkLevel:-1,enableDebug:!0,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait",abi:t.abi}}function J(){let e=$();return{bluetoothEnabled:!1,locationEnabled:!0,wifiEnabled:H().isConnected,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait"}}function K(){let e=H();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function X(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E();return{SDKVersion:j(),enableDebug:!0,host:{appId:q(e).appId},language:A(),version:O(),theme:P()}}function Z(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E();return{miniProgram:{appId:q(e).appId,envVersion:"develop",version:(null==e?void 0:e.versionName)??""}}}function Q(e){return null==e?void 0:e.packageInfo}C.handlers,r(49678),r(46455);let Y="doubao-web-sdk:storage:";function ee(e){return`${Y}${e}`}function et(e){if("string"!=typeof e)throw Error("key must be a string");if(0===e.length)throw Error("key must not be empty");if(e.length>1024)throw Error("key length must be less than or equal to 1024");return e}function er(e){if(en(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function en(e){return new TextEncoder().encode(e).byteLength}function ea(e){return Object.values(e).reduce((e,t)=>e+en(t),0)}function ei(e){if(e>0xa00000)throw new _("total storage size exceeded",1600002)}function es(e){let t={};for(let r=0;r<e.length;r+=1){let n=e.key(r);(null==n?void 0:n.startsWith(Y))&&(t[n.slice(Y.length)]=e.getItem(n)??"")}return t}function eo(e){var t;let r=(null==e||null==(t=e.packageInfo)?void 0:t.appId)||(null==e?void 0:e.appName)||"unknown-app",n=(null==e?void 0:e.userId)||(null==e?void 0:e.userID)||"anonymous";return`${encodeURIComponent(r)}:${encodeURIComponent(n)}`}function el(){let e=Date.now();return{entries:{"/":{type:"directory",createTime:e,lastModifiedTime:e},"/temp":{type:"directory",createTime:e,lastModifiedTime:e},"/user":{type:"directory",createTime:e,lastModifiedTime:e}}}}function ed(e){return`doubao-web-sdk:file-system:${encodeURIComponent(e)}`}async function eu(e,t){try{await (null==t?void 0:t(e.params))}catch{}}r(12021);let ec={"applet.subscribeEvent":(e,t)=>{let r=s(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.subscribe(r)}return b(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=s(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.unsubscribe(r)}return b(e,{})}};function ep(e,t){var r;let n=null==(r=globalThis.navigator)?void 0:r.clipboard;if(!n||"function"!=typeof n[t])throw Error(`${e} is not supported in this browser`);return n}function eh(e,t){let r=t instanceof Error?t.message:String(t);return`${e} failed: ${r}`}async function em(e){let t=ep("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw Error(eh("setClipboardData",e))}}async function eg(){let e=ep("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw Error(eh("getClipboardData",e))}throw Error("getClipboardData failed: clipboard did not return text")}async function ef(e){var t,r;if("string"!=typeof(null==e?void 0:e.src)||!e.src)throw Error("src must be a non-empty string");let{src:n}=e,a=await new Promise((e,t)=>{let r=new Image;r.onload=()=>e(r),r.onerror=()=>t(Error(`failed to load image: ${n}`)),r.src=n}),i=null==(t=n.match(/^data:image\/([^;,]+)/i))?void 0:t[1],s=null==(r=n.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/))?void 0:r[1];return{width:a.naturalWidth||a.width,height:a.naturalHeight||a.height,orientation:"up",path:n,type:((null==i?void 0:i.split("+")[0])??s??"").toLowerCase()}}function ev(e){return{pages:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n;return(null==e?void 0:e.getCurrentPages())??[]}(null==e?void 0:e.navigation)}}let ey={"doubao.getClipboardData":async e=>b(e,{data:await eg()}),"doubao.setClipboardData":async e=>{let{data:t}=function(e){if(!s(e)||"string"!=typeof e.data)throw Error("data must be a string");return{data:e.data}}(e.params);return await em(t),b(e,{})},...ec,"doubao.getImageInfo":async e=>b(e,await ef(e.params)),"doubao.getCurrentPages":{handler:(e,t)=>b(e,ev(t)),syncResult:ev},"doubao.navigateTo":async(e,t)=>await N(e.params,null==t?void 0:t.navigation)?b(e,{}):w(e,"No active Runtime to navigate"),"doubao.redirectTo":async(e,t)=>await M(e.params,null==t?void 0:t.navigation)?b(e,{}):w(e,"No active Runtime to redirect"),"doubao.reLaunch":async(e,t)=>await T(e.params,null==t?void 0:t.navigation)?b(e,{}):w(e,"No active Runtime to relaunch"),"doubao.navigateBack":(e,t)=>!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;return(null==t?void 0:t.navigateBack(e))??!1}(e.params??{},null==t?void 0:t.navigation)?w(e,"No pages in back stack"):b(e,{}),"doubao.exitApp":(e,t)=>!function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n;return null==e||e.exitApp(),!!e}(null==t?void 0:t.navigation)?w(e,"No active Runtime to exit app"):b(e,{}),"doubao.setStorage":e=>{var t;let r,n,{key:a,data:i}=e.params,s=(t=es(localStorage),r=et(a),er(i),n=Object.prototype.hasOwnProperty.call(t,r)?t[r]:void 0,ei(ea(t)-(void 0===n?0:en(n))+en(i)),r);return localStorage.setItem(ee(s),i),b(e,{})},"doubao.getStorage":e=>{let{key:t}=e.params;return b(e,{data:es(localStorage)[et(t)]})},"doubao.removeStorage":e=>{let{key:t}=e.params,r=et(t);return localStorage.removeItem(ee(r)),b(e,{})},"doubao.clearStorage":e=>{for(let e of Object.keys(es(localStorage)))localStorage.removeItem(ee(e));return b(e,{})},"doubao.getStorageInfo":e=>{var t;return b(e,{keys:Object.keys(t=es(localStorage)),currentSize:Math.ceil(ea(t)/1024),limitSize:10240})},"doubao.__webSyncBridgePersist":(e,t)=>{var r,n,a;let i=s(r=e.params)&&s(r.storageSnapshot)?r.storageSnapshot:void 0,o=s(n=e.params)&&"string"==typeof n.fileSystemNamespace?n.fileSystemNamespace:void 0,l=null==t?void 0:t.fileSystemNamespace,d=s(a=e.params)&&s(a.fileSystemSnapshot)?a.fileSystemSnapshot:void 0;return i&&function(e){let t=[];for(let[t,r]of Object.entries(e))et(t),er(r);ei(ea(e));for(let e=0;e<localStorage.length;e+=1){let r=localStorage.key(e);(null==r?void 0:r.startsWith(Y))&&t.push(r)}for(let e of t)localStorage.removeItem(e);for(let[t,r]of Object.entries(e))localStorage.setItem(ee(t),r)}(i),l&&o===l&&d&&localStorage.setItem(ed(l),JSON.stringify(d)),b(e,{})},"doubao.authorize":{handler:e=>b(e,{}),syncResult:{}},"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return b(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:C;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:(e,t)=>{var r;return b(e,Z(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>Z(Q(e))},"doubao.getPackageInfo":{handler:(e,t)=>{var r;return b(e,q(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>q(Q(e))},"doubao.getAppBaseInfo":{handler:(e,t)=>{var r;return b(e,X(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>X(Q(e))},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>b(e,R(null==t?void 0:t.globalProps)),syncResult:e=>R(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:e=>b(e,G()),syncResult:G},"doubao.getSystemSetting":{handler:e=>b(e,J()),syncResult:J},"doubao.getWindowInfo":{handler:e=>b(e,$()),syncResult:$},"doubao.getDeviceInfo":{handler:e=>b(e,z()),syncResult:z},"doubao.getNetworkType":{handler:e=>b(e,K()),syncResult:K}};C.registerMany(ey,{override:!0}),C.registerEventSources({onThemeChange:e=>{let t=matchMedia("(prefers-color-scheme: dark)"),r=()=>e({appTheme:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"});return t.addEventListener("change",r),()=>t.removeEventListener("change",r)}},{override:!0});class e_{router;navigation;onEmpty;runtime;callers=new Map;destroyed=!1;constructor(e,t,r,n){this.router=e,this.navigation=t,this.onEmpty=r,this.runtime=n}get apiRegistry(){var e;return(null==(e=this.runtime)?void 0:e.apiRegistry)??C}register(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>{},t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(this.destroyed)throw Error("RuntimeBridge was destroyed");let n=Symbol("caller"),a=((null==t?void 0:t.apiRegistry)??this.apiRegistry).createEventController((t,r)=>e({type:"event",name:t,params:r,timestamp:Date.now()}));return this.callers.set(n,{abortController:new AbortController,send:e,options:t,events:a,main:r}),n}createSyncBridgeData(e,t,r){var n,a;return function(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eo(e),a=arguments.length>3?arguments[3]:void 0,i=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:C;return e.getSupportedNames({apiRegistry:e})}(t);return{fileSystemNamespace:n,fileSystemSnapshot:function(e){let t=localStorage.getItem(ed(e));if(!t)return el();try{let e=JSON.parse(t);if(s(e)&&s(e.entries))return e}catch{}return el()}(n),apiResults:(r=null==e?void 0:e.packageInfo,(t??C).getSyncResults({globalProps:e,navigation:a,packageInfo:r})),storageSnapshot:es(localStorage),supportedAPIs:i}}(t,(null==(n=this.getCaller(e).options)?void 0:n.apiRegistry)??this.apiRegistry,(null==(a=this.runtime)?void 0:a.getFileSystemNamespace())??r,this.navigation)}getCaller(e){let t=this.callers.get(e);if(!t)throw Error("Caller was detached from the RuntimeBridge");return t}async handleMessage(e,t){var r;let n=this.getCaller(e);return f(t)?"applet.subscribeEvent"===t.name||"applet.unsubscribeEvent"===t.name?(await ec[t.name](t,{events:n.events}),{routed:!1}):(null==(r=t.target)?void 0:r.scope)!=="main"||"self"!==t.target.target||!this.router||n.main?{routed:!1}:this.router.call(e,t):{routed:!1}}async dispatch(e,t,r,n,a){var i,s,o;let l=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"inline",d=this.callers.get(e);if(!d)return;let u=d.options,c={containerType:a.containerType,element:a.element},p="AppletBridgeModule"===n&&"postMessage"===t;if(p){let e=function(e,t){var r,n;if(!("object"!=typeof(r=e)||null===r||Array.isArray(r))&&"event"===r.type&&"doubao.__widgetInteraction"===r.name&&!("object"!=typeof(n=r.params)||null===n||Array.isArray(n))&&"tap"===n.type&&Number.isSafeInteger(n.sequence)&&"number"==typeof n.sequence&&n.sequence>0)return eu(e,t)}(r,null==u?void 0:u.onWidgetInteraction);if(e)return await e}let h=f(r)&&("applet.subscribeEvent"===r.name||"applet.unsubscribeEvent"===r.name)?{routed:!1}:await this.handleMessage(e,r);if(h.routed)return await h.result;let m=await (null==u||null==(i=u.appletSessionMessageHandler)?void 0:i.call(u,r,c));if(null==m?void 0:m.routed)return await m.result;"iframe"!==l&&p&&y(r)&&"__bridge_ready__"===r.name&&(null==u||null==(s=u.onReady)||s.call(u));let g=p&&v(r),_="inline"===l&&"sandbox"!==a.environment;if(g&&_&&"TOOL"!==a.containerType)return d.send(r),r;let b=r=>("iframe"!==l&&"postMessage"===t&&v(r)&&this.callers.get(e)===d&&d.send(r),r);try{let e=this.runtime?this.runtime.nativeModulesCallHandler:null==u?void 0:u.nativeModulesCallHandler,i=await (null==e?void 0:e(t,r,n,c));if(g)return void 0===i&&_&&d.send(r),void 0===i?r:i;let s=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r=e.apiRegistry??C;return(n,a,i)=>{if(("AppletJSModule"!==i||"log"!==n)&&"AppletBridgeModule"===i&&"postMessage"===n)return r.dispatch(a,e,t)}}({...a,signal:d.abortController.signal,getAppletContext:null==u?void 0:u.getAppletContext,fileSystemNamespace:(null==(o=this.runtime)?void 0:o.getFileSystemNamespace())??a.fileSystemNamespace,navigation:this.navigation,apiRegistry:(null==u?void 0:u.apiRegistry)??this.apiRegistry,events:d.events,emitEvent:(e,t)=>d.events.emit(e,t)},null==u?void 0:u.onUnsupportedAPI);return b(void 0===i?await s(t,r,n):i)}catch(e){if("iframe"===l)throw e;return b(f(r)?x(r,e):void 0)}}handleMainBridgeMessage(e){var t;if(null==(t=this.router)?void 0:t.handleMainBridgeMessage(e))return!0;if(!y(e)||"__bridge_ready__"===e.name)return!1;for(let t of this.callers.values())!t.main&&t.events.isSubscribed(e.name)&&t.send(e);return!0}unregister(e){var t,r;let n=this.callers.get(e);n&&(this.callers.delete(e),n.abortController.abort(),n.events.destroy(),null==(t=this.router)||t.cancel(e),n.main||this.destroyed||[...this.callers.values()].some(e=>!e.main)||null==(r=this.onEmpty)||r.call(this))}fail(e){var t;null==(t=this.router)||t.fail(e)}destroy(){var e;if(!this.destroyed)for(let t of(this.destroyed=!0,null==(e=this.router)||e.destroy(),this.callers.keys()))this.unregister(t)}}let eb=/(?:^|[.-])[a-f\d]{8,}(?=[.-]|$)/i;function ew(e){let t=new URL(e),r=t.pathname.slice(t.pathname.lastIndexOf("/")+1),n="0.6.0";return n&&!eb.test(r)&&t.searchParams.set("__doubao_resource_reload",n),t.href}function eS(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}function ex(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function eI(e){return e.containerType??"PAGE"}function ek(e){return"WIDGET"===e?"content":"fill"}function eC(e){if("function"==typeof CustomEvent)return new CustomEvent("error",{detail:{error:e}});let t=new Event("error");return Object.defineProperty(t,"detail",{value:{error:e}}),t}class eE{container;options;sandboxUrl;targetOrigin;bridge=null;caller;connected=!1;failed=!1;handshakeTimer=null;loaded=!1;loadCount=0;port=null;preparedForRender=!1;preparedContainerType=null;renderMessage=null;view=null;constructor(e){let t=new URL(e.sandboxUrl??"https://apps-web-sdk-sandbox.doubaocdn.com/sandbox");if("https:"!==t.protocol&&!("http:"===t.protocol&&eS(t.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.container=e.container,this.options=e,this.sandboxUrl=ew(t),this.targetOrigin=t.origin}get element(){return this.view}prepare(e){this.clear();try{this.createView(e),this.preparedForRender=!0}catch(e){throw this.clear(),e}}createView(e){var t,r;if(new URL((null==(t=globalThis.location)?void 0:t.href)??"http://localhost/").origin===this.targetOrigin)return this.abortRender(Error("iframe isolation requires a cross-origin sandbox URL"));if(this.view)return this.preparedContainerType!==e?this.abortRender(Error("iframe container type cannot change after preparation")):this.view;let n=document.createElement("iframe");n.className=this.options.className??"doubao-web-container-view",n.dataset.containerType=e,n.dataset.webSizing=ek(e),n.referrerPolicy="no-referrer",n.title="Doubao app content",n.sandbox.add("allow-scripts","allow-same-origin");let a=eS((null==(r=globalThis.location)?void 0:r.hostname)??"");return a&&n.setAttribute("credentialless",""),n.setAttribute("allow",a?"picture-in-picture 'none'; local-network-access 'src'; loopback-network 'src'":"picture-in-picture 'none'"),n.src=this.sandboxUrl,n.style.display="APP"===e||"TOOL"===e?"none":"block",n.style.border="0",n.style.width="100%",n.style.height="WIDGET"===e?"0px":"100%",n.addEventListener("load",()=>this.handleLoad()),this.view=n,this.preparedContainerType=e,this.container.replaceChildren(n),n}render(e){var t,r,n,a;this.preparedForRender||this.clear(),this.preparedForRender=!1;let i=eI(e),s=new URL(ex(e),document.baseURI).href,o=e.initData??{},l={...V(),...e.globalProps??{}};this.bridge=e.bridge??(null==(t=this.options.runtime)?void 0:t.bridge)??new e_,this.caller=e.bridgeCaller??this.bridge.register(e=>this.sendBridgeMessage(e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===i);let d=this.bridge.createSyncBridgeData(this.caller,l,this.options.fileSystemNamespace);this.renderMessage={type:"render",captureWidgetTap:this.options.captureWidgetTap,resourceUrl:s,resourceRoot:(null==(r=e.applicationPackage)?void 0:r.resourceRoot)??(null==(a=this.options.runtime)||null==(n=a.packageInfo)?void 0:n.resourceRoot),containerType:i,initData:o,globalProps:l,syncBridgeData:d};try{let e=this.createView(i);return this.connected?this.postOrFail(this.renderMessage):this.loaded&&this.connect(),e}catch(e){throw this.clear(),e}}clear(){var e,t;this.connected&&this.post({type:"dispose"}),this.destroyChannel(),this.caller&&(null==(t=this.bridge)||t.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(e=this.view)||e.remove(),this.view=null,this.preparedContainerType=null,this.renderMessage=null,this.connected=!1,this.failed=!1,this.loaded=!1,this.loadCount=0,this.preparedForRender=!1,this.container.replaceChildren()}sendEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.postOrFail({type:"global-event",name:e,params:t})}sendBridgeMessage(e){this.postOrFail({type:"bridge-message",message:e})}sendGlobalEvent(e,t){this.postOrFail({type:"raw-global-event",name:e,params:t})}reload(){this.post({type:"reload"})}abortRender(e){var t,r;throw null==(t=(r=this.options).onError)||t.call(r,e,eC(e)),e}handleLoad(){this.failed||!this.view||((this.loadCount+=1,this.loadCount>1)?this.fail(Error("iframe navigated after the sandbox runtime loaded")):(this.loaded=!0,this.renderMessage&&this.connect()))}connect(){if(this.failed||!this.view||this.connected||this.port)return;let e=new MessageChannel;this.port=e.port1,e.port1.onmessage=e=>this.handleMessage(e),e.port1.onmessageerror=e=>this.fail(Error("iframe message could not be decoded"),e),e.port1.start(),this.handshakeTimer=setTimeout(()=>this.fail(Error("iframe sandbox handshake timed out")),1e4);try{var t;null==(t=this.view.contentWindow)||t.postMessage({type:"doubao-web-sdk:connect",protocolVersion:1,sdkVersion:"0.6.0"},this.targetOrigin,[e.port2])}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}handleMessage(e){var t,r,n;if(!e.data||"object"!=typeof e.data)return void this.fail(Error("iframe sandbox sent an invalid protocol message"),e);let a=e.data;if(!this.connected)return"connected"!==a.type||1!==a.protocolVersion?void this.fail(Error("iframe sandbox protocol version mismatch"),e):(this.connected=!0,this.clearHandshakeTimer(),void(this.renderMessage&&this.postOrFail(this.renderMessage)));switch(a.type){case"ready":null==(t=(r=this.options).onReady)||t.call(r);break;case"error":this.fail(Error(a.message),e);break;case"resize":(null==(n=this.renderMessage)?void 0:n.containerType)!=="WIDGET"||!Number.isFinite(a.height)||a.height<0?this.fail(Error("only Widget containers may resize the iframe"),e):this.view&&(this.view.style.height=`${a.height}px`,this.view.height=String(a.height));break;case"native-call":!Number.isSafeInteger(a.requestId)||a.requestId<=0||("AppletBridgeModule"!==a.moduleName||"postMessage"!==a.name)&&("AppletJSModule"!==a.moduleName&&"LynxConsoleModule"!==a.moduleName&&"Console"!==a.moduleName||"log"!==a.name)?this.fail(Error("iframe sandbox sent an invalid bridge call"),e):this.handleNativeCall(a);break;case"connected":this.fail(Error("iframe sandbox connected more than once"),e);break;default:this.fail(Error("iframe sandbox sent an invalid protocol message"),e)}}async handleNativeCall(e){let t;if(!this.renderMessage||!this.view)return;let r=this.bridge,n=this.caller;if(r&&n){try{t=await r.dispatch(n,e.name,e.data,e.moduleName,{containerType:this.renderMessage.containerType,element:this.view,globalProps:this.renderMessage.globalProps,fileSystemNamespace:this.renderMessage.syncBridgeData.fileSystemNamespace},"iframe")}catch(t){if(this.bridge!==r||this.caller!==n)return;this.postOrFail({type:"bridge-result",requestId:e.requestId,error:S(t)});return}this.bridge===r&&this.caller===n&&this.postOrFail({type:"bridge-result",requestId:e.requestId,result:t})}}post(e){this.connected&&this.port&&this.port.postMessage(e)}postOrFail(e){try{this.post(e)}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}fail(e){var t,r,n,a;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eC(e);this.failed||(this.failed=!0,this.destroyChannel(),this.caller&&(null==(a=this.bridge)||a.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(t=this.view)||t.remove(),this.view=null,this.renderMessage=null,null==(r=(n=this.options).onError)||r.call(n,e,i))}clearHandshakeTimer(){null!==this.handshakeTimer&&clearTimeout(this.handshakeTimer),this.handshakeTimer=null}destroyChannel(){var e;this.clearHandshakeTimer(),null==(e=this.port)||e.close(),this.port=null,this.connected=!1}}let eN={mode:"iframe",createContainer:e=>new eE(e)};function eM(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function eT(e){return new URL(e,eM()).toString()}function eR(e,t){if(!t)return e;let r=new URL(e,eM());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class eA{options;packages=new Map;resolveManifestUrl;resourceUrlVersion;constructor(e={}){this.options=e,this.resolveManifestUrl=e.resolveManifestUrl,this.resourceUrlVersion=e.resourceUrlVersion}configure(e){e.resolveManifestUrl&&(this.resolveManifestUrl=e.resolveManifestUrl),"resourceUrlVersion"in e&&(this.resourceUrlVersion=e.resourceUrlVersion)}async getPackageSource(e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1],!this.resolveManifestUrl)throw Error("PackageManager requires resolveManifestUrl");return{manifestUrl:await this.resolveManifestUrl({appId:e})}}cached(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r.signal&&m(r.signal);let n=this.packages.get(e);return(!n||r.forceReload)&&(n=t(),this.packages.set(e,n),n.catch(()=>{this.packages.get(e)===n&&this.packages.delete(e)})),r.signal?g(()=>n,r.signal):n}async fetchPackage(e,t){return{manifestUrl:e,resourceRoot:t,manifest:await c(e,{fetcher:this.options.fetcher})}}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.signal&&m(t.signal);let{manifestUrl:r,resourceRoot:n}=await this.getPackageSource(e,t),a=eT(r),i=await this.cached(a,()=>this.fetchPackage(a,n),t);if(e&&i.manifest.appId&&i.manifest.appId!==e)throw Error("Resolved package appId must match the requested application");return i}resolveWidget(e,t){let r=this.tryResolveWidgetFromPackage(e,t),n=e.manifest.appRuntimeEntry?p(e.manifestUrl,e.manifest.appRuntimeEntry):void 0;return{packageInfo:e,appId:e.manifest.appId,appName:(null==r?void 0:r.appName)??e.manifest.name,icon:(null==r?void 0:r.iconSrc)??e.manifest.iconSrc,appRuntimeEntry:n?eR(n,e.resourceUrlVersion??this.resourceUrlVersion):void 0,resourceUrl:(null==r?void 0:r.resourceUrl)??"",titleType:null==r?void 0:r.entry.titleType,boxType:null==r?void 0:r.entry.boxType}}preload(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.loadPackage(e,t)}setPackage(e){this.packages.set(eT(e.manifestUrl),Promise.resolve(e))}deletePackage(e){this.packages.delete(eT(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}resolveWidgetEntry(e,t){let r=e.manifest.name??t.name,n=p(e.manifestUrl,t);return{appId:e.manifest.appId,entry:t,iconSrc:e.manifest.iconSrc??d(t.icons),appName:r,resourceUrl:n?eR(n,e.resourceUrlVersion??this.resourceUrlVersion):void 0}}tryResolveWidgetFromPackage(e,t){let r=e.manifest.getOptionalWidgetEntry(t);if(r)return this.resolveWidgetEntry(e,r)}}class eP{send;ready;pendingCalls=new Map;destroyed=!1;nextCallbackId=1e6;constructor(e,t){this.send=e,this.ready=t}call(e,t){if(this.destroyed)return Promise.reject(Error("RuntimeRouter was destroyed"));let r=this.nextCallbackId++,n={...t,callbackId:r};return new Promise((a,i)=>{this.pendingCalls.set(r,{callbackId:t.callbackId,reject:i,resolve:a,caller:e}),(async()=>{try{await this.ready(),this.pendingCalls.has(r)&&this.send(n)}catch(t){let e=this.pendingCalls.get(r);if(!e)return;this.pendingCalls.delete(r),e.reject(t instanceof Error?t:Error(String(t)))}})()})}handleMainBridgeMessage(e){if(v(e)){let t=this.pendingCalls.get(e.callbackId);return!!t&&(this.pendingCalls.delete(e.callbackId),t.resolve({routed:!0,result:{...e,callbackId:t.callbackId}}),!0)}return!1}cancel(e){for(let[t,r]of this.pendingCalls)r.caller===e&&(this.pendingCalls.delete(t),r.reject(Error("Caller was detached from the RuntimeBridge")))}destroy(){this.destroyed||(this.destroyed=!0,this.fail(Error("RuntimeRouter was destroyed")))}fail(e){for(let t of this.pendingCalls.values())t.reject(e);this.pendingCalls.clear()}}let ej="onDestroy",eL="onShow";function eD(e,t){let r=function(e){let{pageId:t,viewData:r}=function(e){if(!e)throw Error("route url must be a non-empty string");let t=e.indexOf("?"),r=-1===t?e:e.slice(0,t);if(!r)throw Error("route url must include a page path");let n={};return new URLSearchParams(-1===t?"":e.slice(t+1)).forEach((e,t)=>{n[t]=e}),{pageId:r,viewData:n}}(e.url),n=JSON.stringify(r);return{pageId:t,initData:{viewData:r,viewContext:{}},globalProps:{__LOCATION__:e.url,__RENDER_DATA__:n,__VIEW_CONTEXT__:{}}}}(e);return{...r,entry:t.getPageEntry(r.pageId)}}function eO(e,t){var r;let n=Object.entries((null==(r=t.initData)?void 0:r.viewData)??{}).map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`}).join("&");return{route:`${e}${n?`?${n}`:""}`}}function eU(e,t){return{packageInfo:t,...e}}function eq(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function e$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return eU(t,eq(e))}function eB(e){if(s(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return s(t)?t:{}}catch{return{}}}class eF{pageHost;className;onError;appGlobalProps;appInitData;getRuntimeGlobalProps;configuredFileSystemNamespace;runtimeKernel;packageSnapshot;packageLoading;packageSource;lifecycle=new AbortController;get packageInfo(){if(this.destroyed)throw Error("Runtime was destroyed");if(!this.packageSnapshot)throw Error("Runtime package is not loaded");return this.packageSnapshot}get manifest(){return this.packageInfo.manifest}get manifestUrl(){return this.packageInfo.manifestUrl}pageCapsule;resolvedFileSystemNamespace;appRuntime=null;appStart=null;bridge;packageManager;sandboxUrl;viewContext;appGroupId;destroyed=!1;pendingAppEvents=[];clearingAppRuntime=!1;appCallController=new AbortController;apiContextOwner={};stack=[];pendingPages=[];nextPageIndex=0;constructor(e,t=eN,r){this.sandboxUrl=e.sandboxUrl,this.packageManager=e.packageManager??new eA({resolveManifestUrl:()=>this.manifestUrl});let n=new eP(e=>this.sendAppBridgeMessage(e),async()=>{if(await this.ensureAppRuntime(),!this.appStart)throw Error("No Web entry configured for app runtime");return this.appStart.promise});this.appGroupId=e.appGroupId,this.viewContext=e.viewContext,this.pageHost=e.pageHost,this.runtimeKernel=t,"manifest"in e?(this.packageSnapshot={manifest:e.manifest,manifestUrl:String(e.manifestUrl),resourceRoot:e.resourceRoot,resourceUrlVersion:""},e.packageManager||this.packageManager.setPackage(this.packageSnapshot)):this.packageSource=e,this.pageCapsule=e.pageCapsule,this.className=e.className,this.onError=e.onError,this.appGlobalProps=e.appGlobalProps,this.appInitData=e.appInitData,this.getRuntimeGlobalProps=e.getRuntimeGlobalProps,this.configuredFileSystemNamespace=e.fileSystemNamespace,this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace(),this.updateEmptyState(),this.bridge=new e_(n,{getCurrentPages:()=>this.getCurrentPages(),getPackageInfo:()=>this.getPackageInfo(),navigateTo:e=>this.navigateToBridgePage(e),redirectTo:e=>this.redirectToBridgePage(e),reLaunch:e=>this.reLaunchBridgePage(e),navigateBack:e=>this.navigateBackBridgePage(e),exitApp:()=>this.exitBridgeApp()},r,{apiRegistry:e.apiRegistry,getFileSystemNamespace:()=>this.fileSystemNamespace,nativeModulesCallHandler:e.nativeModulesCallHandler})}async loadPackage(){var e,t;if(this.destroyed)throw new DOMException("Runtime was destroyed","AbortError");let r=(null==(e=this.packageSource)?void 0:e.signal)?AbortSignal.any([this.lifecycle.signal,this.packageSource.signal]):this.lifecycle.signal;if(!this.packageSnapshot){if(!this.packageLoading){let e=this.packageSource,n=this.packageManager.loadPackage(e.appId,{signal:r,versionTag:e.versionTag??(null==(t=e.viewContext)?void 0:t.versionTag)}).then(e=>{m(r),this.destroyed||this.packageSnapshot||(this.packageSnapshot={...e,resourceUrlVersion:""},this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace())}).catch(e=>{throw this.packageLoading===n&&(this.packageLoading=void 0),e});this.packageLoading=n}let e=this.packageLoading;await g(()=>e,r)}return m(r),this.packageInfo}get fileSystemNamespace(){return this.resolvedFileSystemNamespace}get isDestroyed(){return this.destroyed}get pages(){return this.stack.map(e=>this.toStackEntry(e))}get currentPage(){let e=this.getCurrentStackItem();return e?this.toStackEntry(e):null}setManifest(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.manifestUrl;this.clear(),this.packageSnapshot={...this.packageSnapshot,manifest:e,manifestUrl:String(r),resourceUrlVersion:(null==(t=this.packageSnapshot)?void 0:t.resourceUrlVersion)??"1"},this.packageManager.setPackage(this.packageSnapshot),this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace()}async pushPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.packageSnapshot||await this.loadPackage(),this.pushLoadedPage(e)}async pushLoadedPage(e,t){var r,n;let a;if(this.destroyed)throw Error("Runtime was destroyed");if(!this.pageHost)throw Error("Opening Pages requires a Runtime pageHost");let i=this.resolvePageEntry(e),o=p(this.manifestUrl,i);if(!o)throw Error(`No Web entry configured for page entry: ${i.id}`);let l=this.lifecycle.signal;if(this.startAppRuntime(),this.appStart&&await this.appStart.promise,m(l),"all"===t)this.clearPages();else if("current"===t){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}let d={...e,globalProps:{...e.globalProps,...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}},u=eR(o,this.packageInfo.resourceUrlVersion),c=e.pageCapsule??this.pageCapsule,h=`page-${++this.nextPageIndex}`,g=(a=eB(null==(n=d.globalProps)?void 0:n.__VIEW_CONTEXT__),{...s(d.initData)?eB(d.initData.viewContext):{},...a,viewId:h,pageName:i.id,pageUrl:i.path}),f=null,v=this.pageHost.createPage({className:this.className,runtime:this,onError:this.onError,onReady:()=>{f&&this.stack.includes(f)&&(f.isReady=!0,this.flushPageLifecycleEvents(f))}},this.runtimeKernel,()=>this.exitBridgeApp());void 0!==e.pageCapsule&&(this.pageCapsule=e.pageCapsule),this.pendingPages.push(eO(i.path,e));try{let t,r,n=v.render({resourceUrl:u,groupId:this.manifest.appId,initData:s(d.initData)?{...d.initData,viewContext:g}:{viewContext:g},globalProps:(t=null==c?void 0:c.statusBarHeight,r="number"==typeof t&&Number.isFinite(t)?{statusBarHeight:t}:{},{...d.globalProps,...r,__VIEW_CONTEXT__:g}),pageCapsule:c}),a=this.getCurrentStackItem();return a&&(this.sendPageLifecycleEvent(a,"onHide"),a.page.setVisible(!1)),f={id:h,pageId:i.id,route:i.path,resourceUrl:u,entry:i,element:n,isReady:!1,options:{...e,entry:i,pageCapsule:c},pendingLifecycleEvents:[],page:v},this.stack.push(f),this.updateEmptyState(),this.sendPageLifecycleEvent(f,eL),this.sendAppEvent("onPageOpened",{viewId:f.id}),this.toStackEntry(f)}catch(e){throw v.clear(),this.updateEmptyState(),e}finally{this.pendingPages.pop()}}async replacePage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"current"))}async reLaunchPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"all"))}popPage(){let e=this.stack.pop();return e?this.removeStackItem(e,!0):null}clear(){this.lifecycle.abort(),this.lifecycle=new AbortController,this.packageLoading=void 0,this.clearPages(),this.clearAppRuntime(),this.packageSnapshot&&(this.packageSnapshot={...this.packageSnapshot,resourceUrlVersion:String(Number(this.packageSnapshot.resourceUrlVersion??0)+1)})}async restart(){if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");await this.withPageTransition(async()=>{let e=this.stack.map(e=>{let{options:t}=e;return t});for(let t of(this.clear(),e))await this.pushLoadedPage(t)})}reload(){var e;null==(e=this.getCurrentStackItem())||e.page.reload()}destroy(){var e;this.destroyed||(this.destroyed=!0,this.bridge.destroy(),this.clear(),null==(e=this.pageHost)||e.destroy())}clearPages(){for(;this.stack.length>0;){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}}async withPageTransition(e){let t=this.bridge.register();try{return await e()}finally{this.bridge.unregister(t)}}removeStackItem(e,t){let r=this.toStackEntry(e);this.sendPageLifecycleEvent(e,ej),e.page.clear();let n=this.getCurrentStackItem();return t&&n&&(n.page.setVisible(!0),this.sendPageLifecycleEvent(n,eL)),this.updateEmptyState(),r}async ensureAppRuntime(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.packageSnapshot||await this.loadPackage(),this.startAppRuntime(e)}startAppRuntime(){var e,t,r;let n,a,i,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.destroyed)throw Error("Runtime was destroyed");if(this.clearingAppRuntime)throw Error("Runtime is being cleared");if(null==(e=this.appStart)?void 0:e.error)throw this.appStart.error;if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let o=p(this.manifestUrl,this.manifest.appRuntimeEntry);if(!o)throw Error("No Web entry configured for app runtime");let l=eR(o,this.packageInfo.resourceUrlVersion),d=new Promise((e,t)=>{n=e,a=t});d.catch(()=>{});let u={promise:d,resolve:n,reject:a,error:void 0};this.appStart=u;let c=e=>{var t;this.appStart!==u||this.destroyed||this.clearingAppRuntime||((null==(t=this.appRuntime)?void 0:t.isReady)||(u.error=e,u.reject(e)),this.bridge.fail(e))},h=this.appCallController.signal;try{i=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document.body,n=document.createElement("div");n.className="doubao-runtime-app",n.hidden=!0,n.style.display="none";let a=t.createContainer({...e,container:n});return{render:e=>(r.append(n),a.render(e)),clear(){a.clear(),n.remove()},sendEvent:a.sendEvent.bind(a),sendBridgeMessage:a.sendBridgeMessage.bind(a)}}({runtime:this,sandboxUrl:this.sandboxUrl,className:this.className,onError:(e,t)=>{var r;this.appStart!==u||this.destroyed||this.clearingAppRuntime||(c(e),null==(r=this.onError)||r.call(this,e,t))},appletSessionMessageHandler:(e,t)=>{var r;return this.appStart!==u||this.destroyed||this.clearingAppRuntime||this.bridge.handleMainBridgeMessage(e)?{routed:!0}:(null==(r=s.appletSessionMessageHandler)?void 0:r.call(s,e,t))??{routed:!1}},getAppletContext:()=>({owner:this.apiContextOwner,signal:h,source:"app",viewContext:s.viewContext??this.viewContext}),onReady:()=>{var e;let t=this.appRuntime;this.clearingAppRuntime||!t||t.container!==i||t.isReady||u.error||(t.isReady=!0,this.flushAppEvents(),u.resolve(),null==(e=s.onReady)||e.call(s))}},this.runtimeKernel,null==(t=this.pageHost)?void 0:t.container),this.appRuntime={container:i,isReady:!1,pendingEvents:[{name:"onForeground",params:{}},...this.pendingAppEvents.splice(0)]};let e=void 0!==s.groupId?s.groupId:this.appGroupId;i.render({bridge:this.bridge,resourceUrl:l,groupId:null===e?void 0:e??this.manifest.appId,containerType:"APP",initData:this.appInitData??{},globalProps:{...e$(this.manifest,this.appGlobalProps),...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}})}catch(e){throw c(e instanceof Error?e:Error(String(e))),this.appRuntime=null,null==i||i.clear(),e}}clearAppRuntime(){var e;if(this.clearingAppRuntime)return;this.clearingAppRuntime=!0;let t=Error(this.destroyed?"Runtime was destroyed":"Runtime was cleared");null==(e=this.appStart)||e.reject(t),this.bridge.fail(t),this.pendingAppEvents=[];let r=this.appRuntime;(null==r?void 0:r.isReady)&&(r.container.sendEvent("onBackground"),r.container.sendEvent(ej)),null==r||r.container.clear(),this.appCallController.abort(),this.appCallController=new AbortController,this.appRuntime=null,this.appStart=null,this.clearingAppRuntime=!1}sendAppEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.appRuntime;if(!this.destroyed&&!this.clearingAppRuntime){if(!r)return void this.pendingAppEvents.push({name:e,params:t});if(!r.isReady)return void r.pendingEvents.push({name:e,params:t});r.container.sendEvent(e,t)}}sendAppBridgeMessage(e){if(!this.clearingAppRuntime){var t;null==(t=this.appRuntime)||t.container.sendBridgeMessage(e)}}flushAppEvents(){let e=this.appRuntime;if(null==e?void 0:e.isReady)for(let t of e.pendingEvents.splice(0))e.container.sendEvent(t.name,t.params)}sendPageLifecycleEvent(e,t){let r,n=(r={viewId:e.id,pageName:e.pageId,pageUrl:e.route},{viewId:e.id,eventName:JSON.stringify(r)});e.isReady?e.page.sendEvent(t,n):e.pendingLifecycleEvents.push({name:t,params:n})}flushPageLifecycleEvents(e){if(e.isReady)for(let t of e.pendingLifecycleEvents.splice(0))e.page.sendEvent(t.name,t.params)}resolvePageEntry(e){return e.entry??this.manifest.getPageEntry(e.pageId)}resolveRoutePageOptions(e){return eD(e,this.manifest)}getCurrentStackItem(){return this.stack[this.stack.length-1]??null}updateEmptyState(){var e;null==(e=this.pageHost)||e.setEmpty(0===this.stack.length)}getCurrentPages(){return[...this.stack.map(e=>eO(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?eq(this.manifest):{appId:null==(e=this.packageSource)?void 0:e.appId}}resolveFileSystemNamespace(){return void 0!==this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:eo({...this.appGlobalProps,packageInfo:this.getPackageInfo()})}async navigateToBridgePage(e){this.packageSnapshot||await this.loadPackage(),await this.pushLoadedPage(this.resolveRoutePageOptions(e))}async redirectToBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.resolveRoutePageOptions(e);await this.replacePage(t)}async reLaunchBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.resolveRoutePageOptions(e);await this.reLaunchPage(t)}navigateBackBridgePage(e){if(this.stack.length<=1)return!1;let t=Math.min(Math.max(1,Math.floor(e.delta??1)),this.stack.length-1);for(let e=0;e<t;e+=1)this.popPage();return!0}exitBridgeApp(){this.clear()}toStackEntry(e){return{id:e.id,pageId:e.pageId,route:e.route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class eW{kernel;autoRelease;runtimes=new Map;packageManagers=new WeakMap;nextPackageManagerId=0;constructor(e,t=!1){this.kernel=e,this.autoRelease=t}acquire(e){var t,r,n,a,i,s,o,l,d,c;let p=e.fileSystemNamespace??eo({...e.appGlobalProps,packageInfo:{appId:e.appId}}),h=new URL(e.appRuntimeEntry,null==(t=globalThis.location)?void 0:t.href).href,m=e.packageManager;m&&!this.packageManagers.has(m)&&this.packageManagers.set(m,this.nextPackageManagerId++);let g=[m?this.packageManagers.get(m):"",String(e.sandboxUrl??""),(null==(r=e.packageInfo)?void 0:r.manifestUrl)??"",(null==(n=e.packageInfo)?void 0:n.resourceRoot)??"",e.appId,(null==(a=e.viewContext)?void 0:a.conversationId)??"",p,e.versionTag??(null==(i=e.viewContext)?void 0:i.versionTag)??"",h].join("\0"),f=this.runtimes.get(g);if(f&&!f.isDestroyed)return f;let v=new eF({packageManager:m,pageHost:e.pageHost,sandboxUrl:e.sandboxUrl,manifest:(null==(s=e.packageInfo)?void 0:s.manifest)??new u({manifestVersion:"3.0",packageName:e.appId,appId:e.appId,versionCode:"",applet:{appletId:e.appId,digest:"",appRuntimeEntry:h,pages:[]},widgets:[]}),manifestUrl:(null==(o=e.packageInfo)?void 0:o.manifestUrl)??h,resourceRoot:null==(l=e.packageInfo)?void 0:l.resourceRoot,registerPageController:!1,appGroupId:null,apiRegistry:e.apiRegistry??C,className:e.className,fileSystemNamespace:p,nativeModulesCallHandler:e.nativeModulesCallHandler,appInitData:e.appInitData,appGlobalProps:eU(e.appGlobalProps??{},{appId:e.appId}),getRuntimeGlobalProps:e.getRuntimeGlobalProps,viewContext:{appId:e.appId,conversationId:null==(d=e.viewContext)?void 0:d.conversationId,versionTag:e.versionTag??(null==(c=e.viewContext)?void 0:c.versionTag)},onError:e.onError},this.kernel??eN,this.autoRelease?()=>this.release(v):void 0);return this.runtimes.set(g,v),v}release(e){for(let[t,r]of this.runtimes)if(r===e){this.runtimes.delete(t),e.destroy();return}}destroy(){let e=[...this.runtimes.values()];for(let t of(this.runtimes.clear(),e))t.destroy()}}function eH(e,t){return class extends e{hostOptions;prepared=!1;constructor(e){super({...e,sandboxUrl:e.runtime?e.runtime.sandboxUrl:e.sandboxUrl}),this.hostOptions=e}prepare(e){super.prepare(e),this.prepared=!0}clear(){this.prepared=!1,super.clear()}render(e){var r,n,a,i,s;this.prepared||this.clear(),this.prepared=!1;let{application:o,applicationPackage:l,appRuntimeEntry:d,...u}=e,c=(null==o?void 0:o.appId)??(null==(n=u.globalProps)||null==(r=n.packageInfo)?void 0:r.appId),p=(null==o?void 0:o.appRuntimeEntry)??d,h=(null==o?void 0:o.viewContext)??(null==(a=u.globalProps)?void 0:a.__VIEW_CONTEXT__),m=this.hostOptions.runtime??(c&&p?(this.hostOptions.runtimeManager??t()).acquire({appId:c,appRuntimeEntry:p,packageInfo:l,packageManager:this.hostOptions.packageManager,sandboxUrl:this.hostOptions.sandboxUrl,apiRegistry:this.hostOptions.apiRegistry,nativeModulesCallHandler:this.hostOptions.nativeModulesCallHandler,versionTag:(null==o?void 0:o.versionTag)??(null==h?void 0:h.versionTag),viewContext:h,fileSystemNamespace:this.hostOptions.fileSystemNamespace,appGlobalProps:{userId:null==(i=u.globalProps)?void 0:i.userId,userID:null==(s=u.globalProps)?void 0:s.userID}}):void 0),g=null==m?void 0:m.bridge.register();try{return super.render({...u,applicationPackage:l,bridge:(null==m?void 0:m.bridge)??u.bridge})}catch(e){throw this.clear(),e}finally{g&&(null==m||m.bridge.unregister(g))}}}}new eW(void 0,!0),r(52452),r(51237),r(25907),r(92151);var ez=r(65703);let eV="embed-webview",eG="__channel_ack__",eJ=new WeakMap,eK=e=>({url:e});function eX(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function eZ(e){return"string"==typeof e?e:JSON.stringify(e??{})}let eQ=globalThis.HTMLElement??class{};r(31178);let eY="region-to-decode";function e0(e){if("string"==typeof e)try{e=JSON.parse(e)}catch{return null}if(!e||"object"!=typeof e)return null;let{x:t,y:r,width:n,height:a}=e;return![t,r,n,a].every(Number.isFinite)||t<0||r<0||n<=0||a<=0?null:{x:t,y:r,width:n,height:a}}class e1{element;static observedAttributes=[];image;attributes=new MutationObserver(()=>this.update());resize;viewSize;cropStyle;constructor(e){var t;this.element=e,this.image=(null==(t=e.shadowRoot)?void 0:t.querySelector("#img"))??null,Object.defineProperty(e,eY,{configurable:!0,get:()=>e0(e.getAttribute(eY)),set:t=>{let r=e0(t);r?e.setAttribute(eY,JSON.stringify(r)):e.removeAttribute(eY)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[eY,"src","mode","auto-size"]}),this.update()}clearCrop=()=>{var e;null==(e=this.cropStyle)||e.remove(),this.cropStyle=void 0};stopRendering(){var e,t,r;null==(e=this.resize)||e.disconnect(),this.resize=void 0,this.viewSize=void 0,null==(t=this.image)||t.removeEventListener("load",this.update),null==(r=this.image)||r.removeEventListener("error",this.clearCrop),this.clearCrop()}update=()=>{var e,t,r;let n=e0(this.element.getAttribute(eY)),a=this.image;if(!n||!a)return void this.stopRendering();this.resize||(this.resize=new ResizeObserver(e=>{let[t]=e;this.viewSize=t.contentRect,this.update()}),this.resize.observe(this.element),a.addEventListener("load",this.update),a.addEventListener("error",this.clearCrop));let i=a.naturalWidth,s=a.naturalHeight,o=this.element.getAttribute("src"),l=this.element.getRootNode().host,d=o?(null==l||null==(e=l.resolveResource)?void 0:e.call(l,o))??o:o;if(!a.complete||!i||!s||a.getAttribute("src")!==d)return void this.clearCrop();let u=Math.min(n.width,i-n.x),c=Math.min(n.height,s-n.y),p=getComputedStyle(this.element),h=Number.parseFloat(p.paddingLeft)||0,m=Number.parseFloat(p.paddingTop)||0,g=(null==(t=this.viewSize)?void 0:t.width)??this.element.clientWidth-h-(Number.parseFloat(p.paddingRight)||0),f=(null==(r=this.viewSize)?void 0:r.height)??this.element.clientHeight-m-(Number.parseFloat(p.paddingBottom)||0);if(u<=0||c<=0||g<=0||f<=0)return void this.clearCrop();let v=g/u,y=f/c,_=this.element.getAttribute("mode");"aspectFit"===_?v=y=Math.min(v,y):"aspectFill"===_?v=y=Math.max(v,y):"center"===_&&(v=y=1);let b=h+(g-u*v)/2-n.x*v,w=m+(f-c*y)/2-n.y*y;this.cropStyle||(this.cropStyle=this.element.ownerDocument.createElement("style"),this.cropStyle.setAttribute("data-doubao-image-region",""),this.element.shadowRoot.append(this.cropStyle)),this.cropStyle.textContent=`#img {
|
|
1
|
+
(()=>{"use strict";var e,t,r,n,a,i,s,o,l,d,u,c,p={33376(e,t,r){let n,a;r(52205),r(40768),r(76235),r(15254),r(42949),r(18723),r(37891);var i=r(63159);function s(e){return"object"==typeof e&&null!==e}function o(e){var t;return"string"==typeof(null==(t=e.web)?void 0:t.entry)}function l(e,t){let r=new Map;for(let n of e){let e=t(n);e&&!r.has(e)&&r.set(e,n)}return r}function d(e){return"string"==typeof e?e||void 0:(null==e?void 0:e["3x"])||(null==e?void 0:e["2x"])||(null==e?void 0:e["1x"])}r(84086),r(21301),r(32037),r(14104),r(99811),r(40009),r(13035),r(13412),r(17973),r(64955),r(91016),r(23306),r(76619),r(57857),r(9975),r(93885),r(812),r(74180),r(994),r(4267),r(74678),r(55910),r(76691),r(72919);class u{raw;appEntry;pageEntries;pageIdEntryMap;pagePathEntryMap;widgetEntries;widgetEntryMap;constructor(e){var t;let r;this.raw=e,this.appEntry="string"==typeof(r=(null==(t=e.applet.web)?void 0:t.appRuntimeEntry)??e.applet.appRuntimeEntry)&&r?{entry:r}:null,this.pageEntries=e.applet.pages.filter(o),this.pageIdEntryMap=l(this.pageEntries,e=>e.id),this.pagePathEntryMap=l(this.pageEntries,e=>{var t;return(null==(t=e.path)?void 0:t.startsWith("/"))?e.path:void 0}),this.widgetEntries=e.widgets,this.widgetEntryMap=l(this.widgetEntries,e=>e.widgetId)}get appId(){return"string"==typeof this.raw.appId?this.raw.appId:void 0}get name(){return this.raw.applet.name}get iconSrc(){return d(this.raw.applet.icons)}get versionName(){return this.raw.versionName||this.raw.versionTag||this.raw.versionCode||void 0}get pages(){return this.getPageEntries()}get widgets(){return this.getWidgetEntries()}get appRuntimeEntry(){return this.appEntry}getPageEntries(){return[...this.pageEntries]}getWidgetEntries(){return[...this.widgetEntries]}getOptionalWidgetEntry(e){return e?this.widgetEntryMap.get(e):this.widgetEntries[0]}getPageEntry(e){let t=e?e.startsWith("/")?this.pagePathEntryMap.get(e):this.pageIdEntryMap.get(e):this.pageEntries[0];if(!t)throw Error(e?`Unknown pages entry: ${e}`:"No pages entries in Web manifest");return t}getWidgetEntry(e){let t=this.getOptionalWidgetEntry(e);if(!t)throw Error(e?`Unknown widgets entry: ${e}`:"No widgets entries in Web manifest");return t}}async function c(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.fetcher??fetch,n=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!n.ok)throw Error(`Failed to load Web manifest: ${n.status} ${n.statusText}`);let a=await n.json();if(!s(a))throw Error("Invalid Web manifest: expected a JSON object");return new u(a)}function p(e,t,r){var n,a;let i="item"in t?t.item:t,s="id"in i||"widgetId"in i?"string"==typeof(null==(n=i.web)?void 0:n.entry)?i.web.entry:void 0:i.entry;if(!s)return;let o=new URL(e,r??(null==(a=globalThis.location)?void 0:a.href)??"http://localhost/");return o.pathname=o.pathname.replace(/\/base\/manifest\.json$/,"/"),new URL(s,o).toString()}function h(){let e=Error("Widget host call was cancelled");return e.name="AbortError",e}function m(e){if(e.aborted)throw h()}function g(e,t){return m(t),new Promise((r,n)=>{let a=!1,i=e=>{a||(a=!0,t.removeEventListener("abort",s),e())},s=()=>i(()=>n(h()));t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(e).then(e=>i(()=>r(e)),e=>i(()=>n(e)))})}function f(e){return(null==e?void 0:e.type)==="call"}function v(e){return(null==e?void 0:e.type)==="callback"}function y(e){return(null==e?void 0:e.type)==="event"}r(67548),r(70954),r(98803),r(79162),r(15385),r(39342),r(69152),r(61955),r(82689),r(84847),r(16285),r(20602),r(33307),r(94341),r(7270),r(44997),r(50364),r(79780),r(80372),r(72498),r(37928),r(25597),r(92321);class _ extends Error{errNo;errMsg;constructor(e,t,r=e){super(e),this.errNo=t,this.errMsg=r,Object.setPrototypeOf(this,new.target.prototype),this.name="BridgeAPIError"}}function b(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function w(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t;return{type:"callback",callbackId:e.callbackId,params:{code:0,msg:t,errNo:r,errMsg:n}}}function S(e){return e instanceof Error?e.message:String(e)}function x(e,t){return t instanceof _?w(e,t.message,t.errNo,t.errMsg):w(e,S(t))}class I{registry=new Map;eventSources=new Map;eventSourceCleanups=new Map;eventSourceRetainCounts=new Map;eventControllers=new Set;handlers={};constructor(e){e&&this.registerMany(e)}register(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.registry.has(e))throw Error(`Bridge API handler ${e} is already registered`);let n=this.registry.get(e),a="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,a),this.handlers[e]=a.handler,()=>{if(this.registry.get(e)===a){if(n){this.registry.set(e,n),this.handlers[e]=n.handler;return}this.registry.delete(e),delete this.handlers[e]}}}registerMany(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[n,a]of Object.entries(e))r.push(this.register(n,a,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}get(e){var t;return null==(t=this.registry.get(e))?void 0:t.handler}getSyncResults(e){let t={};for(let[r,n]of this.registry)n.syncResult&&this.canIUse(r,e)&&(t[r]="function"==typeof n.syncResult?n.syncResult({...e,apiRegistry:this}):n.syncResult);return t}registerEventSource(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.eventSources.has(e))throw Error(`Bridge event source ${e} is already registered`);let n=this.eventSources.get(e),a="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,a),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,a),()=>{if(this.eventSources.get(e)===a){if(this.stopEventSource(e),n){this.eventSources.set(e,n),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,n);return}this.eventSources.delete(e)}}}registerEventSources(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[n,a]of Object.entries(e))r.push(this.registerEventSource(n,a,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}canIUse(e,t){let r=this.registry.get(e);if(r)return"function"==typeof r.canIUse?r.canIUse({...t,apiRegistry:this}):r.canIUse;let n=this.eventSources.get(e);return!!n&&("function"==typeof n.canIUse?n.canIUse({...t,apiRegistry:this}):n.canIUse??!0)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;if(!f(e))return;let n={...t,apiRegistry:this};if(this.canIUse(e.name,n))return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!f(e))return;let n=t[e.name];if(!n)return w(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=n(e,r);if(t instanceof Promise)return t.catch(t=>x(e,t));return t??w(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return x(e,t)}}(e,this.handlers,n);if(!r)return w(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=r(e.name);return t instanceof Promise?t.then(()=>b(e,{})).catch(t=>x(e,t)):b(e,{})}catch(t){return x(e,t)}}getSupportedNames(e){return[...new Set([...this.registry.keys(),...this.eventSources.keys()])].filter(t=>this.canIUse(t,e))}emitEvent(e,t){let r=!1;for(let n of this.eventControllers)r=n.emit(e,t)||r;return r}createEventController(e){return new k(this,e)}fork(){let e=new I(this.getRegistrations());return e.registerEventSources(this.getEventSources()),e}getRegistrations(){return Object.fromEntries(this.registry)}getEventSources(){return Object.fromEntries(this.eventSources)}attachEventController(e){return this.eventControllers.add(e),()=>{this.eventControllers.delete(e)}}retainEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(this.eventSourceRetainCounts.set(e,t+1),t>0)return;let r=this.eventSources.get(e);r&&this.startEventSource(e,r)}releaseEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(t<=1){this.eventSourceRetainCounts.delete(e),this.stopEventSource(e);return}this.eventSourceRetainCounts.set(e,t-1)}startEventSource(e,t){this.stopEventSource(e);let r=t.source(t=>{this.emitEvent(e,t)});"function"==typeof r&&this.eventSourceCleanups.set(e,r)}stopEventSource(e){var t;null==(t=this.eventSourceCleanups.get(e))||t(),this.eventSourceCleanups.delete(e)}}class k{apiRegistry;dispatch;cleanupRegistry;subscribedEventNames=new Set;constructor(e,t){this.apiRegistry=e,this.dispatch=t,this.cleanupRegistry=this.apiRegistry.attachEventController(this)}subscribe(e){this.subscribedEventNames.has(e)||(this.subscribedEventNames.add(e),this.apiRegistry.retainEventSource(e))}unsubscribe(e){this.subscribedEventNames.delete(e)&&this.apiRegistry.releaseEventSource(e)}isSubscribed(e){return this.subscribedEventNames.has(e)}emit(e,t){return!!this.isSubscribed(e)&&(this.dispatch(e,t),!0)}destroy(){for(let e of this.subscribedEventNames)this.apiRegistry.releaseEventSource(e);this.subscribedEventNames.clear(),this.cleanupRegistry()}}let C=new I;function E(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n;return null==e?void 0:e.getPackageInfo()}async function N(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;return await (null==t?void 0:t.navigateTo(e)),!!t}async function M(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;return await (null==t?void 0:t.redirectTo(e)),!!t}async function T(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;return await (null==t?void 0:t.reLaunch(e)),!!t}function R(e){var t;let{screenWidth:r,statusBarHeight:n}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),a=Math.round(n)+4,i=Math.round(r)-12;return{bottom:a+36,height:36,left:i-84,right:i,top:a,width:84}}function A(){return(navigator.language||"zh-CN").replace("-","_")}function P(){var e,t,r;return(null==(t=(r=window).matchMedia)||null==(e=t.call(r,"(prefers-color-scheme: dark)"))?void 0:e.matches)?"dark":"light"}function j(){return"u"<typeof DoubaoAppsSDKVersion?void 0:DoubaoAppsSDKVersion}function L(){return navigator.userAgentData}function D(){var e;let t=null==(e=L())?void 0:e.brands,r=null==t?void 0:t.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==r?void 0:r.brand)return r.brand;let n=navigator.userAgent??"";return/edg\//i.test(n)?"Microsoft Edge":/chrome|crios/i.test(n)?"Chrome":/firefox|fxios/i.test(n)?"Firefox":/safari/i.test(n)?"Safari":"Browser"}function O(){var e,t;let r=null==(e=L())?void 0:e.brands,n=null==r?void 0:r.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==n?void 0:n.version)return n.version;let a=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(a))?void 0:t[1])??void 0}function U(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",n=(null==(e=L())?void 0:e.platform)??"",a=`${n} ${r} ${t}`,i=navigator.maxTouchPoints??0;return/android/i.test(a)?{platform:"android",brand:"Android"}:/iphone/i.test(a)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(a)||/mac/i.test(r)&&i>1?{platform:"ios",brand:"iPad"}:/mac/i.test(a)?{platform:"mac",brand:"Mac"}:/win/i.test(a)?{platform:"windows",brand:"Windows"}:/linux/i.test(a)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function q(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function $(){var e,t,r,n,a;let i=Math.round((null==(n=window.visualViewport)?void 0:n.width)??window.innerWidth??0),s=Math.round((null==(a=window.visualViewport)?void 0:a.height)??window.innerHeight??0),o=window.devicePixelRatio??1,l=Math.round((null==(e=window.screen)?void 0:e.width)??i),d=Math.round((null==(t=window.screen)?void 0:t.height)??s),u=Math.round((null==(r=window.visualViewport)?void 0:r.offsetTop)??0);return{pixelRatio:o,screenWidth:l,screenHeight:d,windowWidth:i,windowHeight:s,statusBarHeight:u,safeArea:{left:0,right:i,top:u,bottom:s,width:i,height:Math.max(0,s-u)},screenTop:u}}function B(){return U().platform}function F(){var e,t,r,n,a;let i=navigator.userAgent??"",s=B();return"android"===s?null==(e=/android\s+([\d.]+)/i.exec(i))?void 0:e[1]:"ios"===s?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(i))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===s?null==(a=/mac os x\s+([\d_]+)/i.exec(i))||null==(n=a[1])?void 0:n.replace(/_/g,"."):void 0}function W(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:B();return"android"===e?"Android":"ios"===e?"iOS":"mac"===e?"macOS":"windows"===e?"Windows":"linux"===e?"Linux":"Web"}function H(){return{isConnected:!0,networkType:"unknown",hasSystemProxy:!1,weakNet:!1}}function z(){let e,t=U(),r=navigator.platform||B();return{abi:r,deviceAbi:r,benchmarkLevel:-1,brand:t.brand,model:function(){let e=navigator.userAgent??"",t=B();if("android"===t){var r,n;return(null==(n=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=n[1])?void 0:r.trim())||"Android"}return"ios"===t?U().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||U().brand:D()}(),system:function(){let e=B(),t=F();if("web"!==e){let r=W(e);return t?`${r} ${t}`:r}let r=O(),n=D();return r?`${n} ${r}`:"Web"}(),platform:t.platform,cpuType:r,memorySize:"number"==typeof(e=navigator.deviceMemory)&&Number.isFinite(e)?String(Math.round(1024*e)):""}}function V(){let e=z(),t=$(),r=t.windowWidth>t.windowHeight;return{os:W(e.platform),platform:e.platform,osVersion:F(),deviceBrand:e.brand,deviceModel:e.model,deviceType:e.model,channel:"debug",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function G(){let e=$(),t=z();return{...e,brand:t.brand,model:t.model,language:A(),version:O(),system:t.system,platform:t.platform,SDKVersion:j(),theme:P(),benchmarkLevel:-1,enableDebug:!0,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait",abi:t.abi}}function J(){let e=$();return{bluetoothEnabled:!1,locationEnabled:!0,wifiEnabled:H().isConnected,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait"}}function K(){let e=H();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function X(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E();return{SDKVersion:j(),enableDebug:!0,host:{appId:q(e).appId},language:A(),version:O(),theme:P()}}function Z(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E();return{miniProgram:{appId:q(e).appId,envVersion:"develop",version:(null==e?void 0:e.versionName)??""}}}function Q(e){return null==e?void 0:e.packageInfo}C.handlers,r(49678),r(46455);let Y="doubao-web-sdk:storage:";function ee(e){return`${Y}${e}`}function et(e){if("string"!=typeof e)throw Error("key must be a string");if(0===e.length)throw Error("key must not be empty");if(e.length>1024)throw Error("key length must be less than or equal to 1024");return e}function er(e){if(en(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function en(e){return new TextEncoder().encode(e).byteLength}function ea(e){return Object.values(e).reduce((e,t)=>e+en(t),0)}function ei(e){if(e>0xa00000)throw new _("total storage size exceeded",1600002)}function es(e){let t={};for(let r=0;r<e.length;r+=1){let n=e.key(r);(null==n?void 0:n.startsWith(Y))&&(t[n.slice(Y.length)]=e.getItem(n)??"")}return t}function eo(e){var t;let r=(null==e||null==(t=e.packageInfo)?void 0:t.appId)||(null==e?void 0:e.appName)||"unknown-app",n=(null==e?void 0:e.userId)||(null==e?void 0:e.userID)||"anonymous";return`${encodeURIComponent(r)}:${encodeURIComponent(n)}`}function el(){let e=Date.now();return{entries:{"/":{type:"directory",createTime:e,lastModifiedTime:e},"/temp":{type:"directory",createTime:e,lastModifiedTime:e},"/user":{type:"directory",createTime:e,lastModifiedTime:e}}}}function ed(e){return`doubao-web-sdk:file-system:${encodeURIComponent(e)}`}async function eu(e,t){try{await (null==t?void 0:t(e.params))}catch{}}r(12021);let ec={"applet.subscribeEvent":(e,t)=>{let r=s(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.subscribe(r)}return b(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=s(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.unsubscribe(r)}return b(e,{})}};function ep(e,t){var r;let n=null==(r=globalThis.navigator)?void 0:r.clipboard;if(!n||"function"!=typeof n[t])throw Error(`${e} is not supported in this browser`);return n}function eh(e,t){let r=t instanceof Error?t.message:String(t);return`${e} failed: ${r}`}async function em(e){let t=ep("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw Error(eh("setClipboardData",e))}}async function eg(){let e=ep("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw Error(eh("getClipboardData",e))}throw Error("getClipboardData failed: clipboard did not return text")}async function ef(e){var t,r;if("string"!=typeof(null==e?void 0:e.src)||!e.src)throw Error("src must be a non-empty string");let{src:n}=e,a=await new Promise((e,t)=>{let r=new Image;r.onload=()=>e(r),r.onerror=()=>t(Error(`failed to load image: ${n}`)),r.src=n}),i=null==(t=n.match(/^data:image\/([^;,]+)/i))?void 0:t[1],s=null==(r=n.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/))?void 0:r[1];return{width:a.naturalWidth||a.width,height:a.naturalHeight||a.height,orientation:"up",path:n,type:((null==i?void 0:i.split("+")[0])??s??"").toLowerCase()}}function ev(e){return{pages:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n;return(null==e?void 0:e.getCurrentPages())??[]}(null==e?void 0:e.navigation)}}let ey={"doubao.getClipboardData":async e=>b(e,{data:await eg()}),"doubao.setClipboardData":async e=>{let{data:t}=function(e){if(!s(e)||"string"!=typeof e.data)throw Error("data must be a string");return{data:e.data}}(e.params);return await em(t),b(e,{})},...ec,"doubao.getImageInfo":async e=>b(e,await ef(e.params)),"doubao.getCurrentPages":{handler:(e,t)=>b(e,ev(t)),syncResult:ev},"doubao.navigateTo":async(e,t)=>await N(e.params,null==t?void 0:t.navigation)?b(e,{}):w(e,"No active Runtime to navigate"),"doubao.redirectTo":async(e,t)=>await M(e.params,null==t?void 0:t.navigation)?b(e,{}):w(e,"No active Runtime to redirect"),"doubao.reLaunch":async(e,t)=>await T(e.params,null==t?void 0:t.navigation)?b(e,{}):w(e,"No active Runtime to relaunch"),"doubao.navigateBack":(e,t)=>!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;return(null==t?void 0:t.navigateBack(e))??!1}(e.params??{},null==t?void 0:t.navigation)?w(e,"No pages in back stack"):b(e,{}),"doubao.exitApp":(e,t)=>!function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n;return null==e||e.exitApp(),!!e}(null==t?void 0:t.navigation)?w(e,"No active Runtime to exit app"):b(e,{}),"doubao.setStorage":e=>{var t;let r,n,{key:a,data:i}=e.params,s=(t=es(localStorage),r=et(a),er(i),n=Object.prototype.hasOwnProperty.call(t,r)?t[r]:void 0,ei(ea(t)-(void 0===n?0:en(n))+en(i)),r);return localStorage.setItem(ee(s),i),b(e,{})},"doubao.getStorage":e=>{let{key:t}=e.params;return b(e,{data:es(localStorage)[et(t)]})},"doubao.removeStorage":e=>{let{key:t}=e.params,r=et(t);return localStorage.removeItem(ee(r)),b(e,{})},"doubao.clearStorage":e=>{for(let e of Object.keys(es(localStorage)))localStorage.removeItem(ee(e));return b(e,{})},"doubao.getStorageInfo":e=>{var t;return b(e,{keys:Object.keys(t=es(localStorage)),currentSize:Math.ceil(ea(t)/1024),limitSize:10240})},"doubao.__webSyncBridgePersist":(e,t)=>{var r,n,a;let i=s(r=e.params)&&s(r.storageSnapshot)?r.storageSnapshot:void 0,o=s(n=e.params)&&"string"==typeof n.fileSystemNamespace?n.fileSystemNamespace:void 0,l=null==t?void 0:t.fileSystemNamespace,d=s(a=e.params)&&s(a.fileSystemSnapshot)?a.fileSystemSnapshot:void 0;return i&&function(e){let t=[];for(let[t,r]of Object.entries(e))et(t),er(r);ei(ea(e));for(let e=0;e<localStorage.length;e+=1){let r=localStorage.key(e);(null==r?void 0:r.startsWith(Y))&&t.push(r)}for(let e of t)localStorage.removeItem(e);for(let[t,r]of Object.entries(e))localStorage.setItem(ee(t),r)}(i),l&&o===l&&d&&localStorage.setItem(ed(l),JSON.stringify(d)),b(e,{})},"doubao.authorize":{handler:e=>b(e,{}),syncResult:{}},"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return b(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:C;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:(e,t)=>{var r;return b(e,Z(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>Z(Q(e))},"doubao.getPackageInfo":{handler:(e,t)=>{var r;return b(e,q(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>q(Q(e))},"doubao.getAppBaseInfo":{handler:(e,t)=>{var r;return b(e,X(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>X(Q(e))},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>b(e,R(null==t?void 0:t.globalProps)),syncResult:e=>R(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:e=>b(e,G()),syncResult:G},"doubao.getSystemSetting":{handler:e=>b(e,J()),syncResult:J},"doubao.getWindowInfo":{handler:e=>b(e,$()),syncResult:$},"doubao.getDeviceInfo":{handler:e=>b(e,z()),syncResult:z},"doubao.getNetworkType":{handler:e=>b(e,K()),syncResult:K}};C.registerMany(ey,{override:!0}),C.registerEventSources({onThemeChange:e=>{let t=matchMedia("(prefers-color-scheme: dark)"),r=()=>e({appTheme:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"});return t.addEventListener("change",r),()=>t.removeEventListener("change",r)}},{override:!0});class e_{router;navigation;onEmpty;runtime;callers=new Map;destroyed=!1;constructor(e,t,r,n){this.router=e,this.navigation=t,this.onEmpty=r,this.runtime=n}get apiRegistry(){var e;return(null==(e=this.runtime)?void 0:e.apiRegistry)??C}register(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>{},t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(this.destroyed)throw Error("RuntimeBridge was destroyed");let n=Symbol("caller"),a=((null==t?void 0:t.apiRegistry)??this.apiRegistry).createEventController((t,r)=>e({type:"event",name:t,params:r,timestamp:Date.now()}));return this.callers.set(n,{abortController:new AbortController,send:e,options:t,events:a,main:r}),n}createSyncBridgeData(e,t,r){var n,a;return function(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eo(e),a=arguments.length>3?arguments[3]:void 0,i=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:C;return e.getSupportedNames({apiRegistry:e})}(t);return{fileSystemNamespace:n,fileSystemSnapshot:function(e){let t=localStorage.getItem(ed(e));if(!t)return el();try{let e=JSON.parse(t);if(s(e)&&s(e.entries))return e}catch{}return el()}(n),apiResults:(r=null==e?void 0:e.packageInfo,(t??C).getSyncResults({globalProps:e,navigation:a,packageInfo:r})),storageSnapshot:es(localStorage),supportedAPIs:i}}(t,(null==(n=this.getCaller(e).options)?void 0:n.apiRegistry)??this.apiRegistry,(null==(a=this.runtime)?void 0:a.getFileSystemNamespace())??r,this.navigation)}getCaller(e){let t=this.callers.get(e);if(!t)throw Error("Caller was detached from the RuntimeBridge");return t}async handleMessage(e,t){var r;let n=this.getCaller(e);return f(t)?"applet.subscribeEvent"===t.name||"applet.unsubscribeEvent"===t.name?(await ec[t.name](t,{events:n.events}),{routed:!1}):(null==(r=t.target)?void 0:r.scope)!=="main"||"self"!==t.target.target||!this.router||n.main?{routed:!1}:this.router.call(e,t):{routed:!1}}async dispatch(e,t,r,n,a){var i,s,o;let l=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"inline",d=this.callers.get(e);if(!d)return;let u=d.options,c={containerType:a.containerType,element:a.element},p="AppletBridgeModule"===n&&"postMessage"===t;if(p){let e=function(e,t){var r,n;if(!("object"!=typeof(r=e)||null===r||Array.isArray(r))&&"event"===r.type&&"doubao.__widgetInteraction"===r.name&&!("object"!=typeof(n=r.params)||null===n||Array.isArray(n))&&"tap"===n.type&&Number.isSafeInteger(n.sequence)&&"number"==typeof n.sequence&&n.sequence>0)return eu(e,t)}(r,null==u?void 0:u.onWidgetInteraction);if(e)return await e}let h=f(r)&&("applet.subscribeEvent"===r.name||"applet.unsubscribeEvent"===r.name)?{routed:!1}:await this.handleMessage(e,r);if(h.routed)return await h.result;let m=await (null==u||null==(i=u.appletSessionMessageHandler)?void 0:i.call(u,r,c));if(null==m?void 0:m.routed)return await m.result;"iframe"!==l&&p&&y(r)&&"__bridge_ready__"===r.name&&(null==u||null==(s=u.onReady)||s.call(u));let g=p&&v(r),_="inline"===l&&"sandbox"!==a.environment;if(g&&_&&"TOOL"!==a.containerType)return d.send(r),r;let b=r=>("iframe"!==l&&"postMessage"===t&&v(r)&&this.callers.get(e)===d&&d.send(r),r);try{let e=this.runtime?this.runtime.nativeModulesCallHandler:null==u?void 0:u.nativeModulesCallHandler,i=await (null==e?void 0:e(t,r,n,c));if(g){let e=void 0===i?r:i;if("sandbox"===a.environment||void 0===i&&_)return b(e);return e}let s=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r=e.apiRegistry??C;return(n,a,i)=>{if(("AppletJSModule"!==i||"log"!==n)&&"AppletBridgeModule"===i&&"postMessage"===n)return r.dispatch(a,e,t)}}({...a,signal:d.abortController.signal,getAppletContext:null==u?void 0:u.getAppletContext,fileSystemNamespace:(null==(o=this.runtime)?void 0:o.getFileSystemNamespace())??a.fileSystemNamespace,navigation:this.navigation,apiRegistry:(null==u?void 0:u.apiRegistry)??this.apiRegistry,events:d.events,emitEvent:(e,t)=>d.events.emit(e,t)},null==u?void 0:u.onUnsupportedAPI);return b(void 0===i?await s(t,r,n):i)}catch(e){if("iframe"===l)throw e;return b(f(r)?x(r,e):void 0)}}handleMainBridgeMessage(e){var t;if(null==(t=this.router)?void 0:t.handleMainBridgeMessage(e))return!0;if(!y(e)||"__bridge_ready__"===e.name)return!1;for(let t of this.callers.values())!t.main&&t.events.isSubscribed(e.name)&&t.send(e);return!0}unregister(e){var t,r;let n=this.callers.get(e);n&&(this.callers.delete(e),n.abortController.abort(),n.events.destroy(),null==(t=this.router)||t.cancel(e),n.main||this.destroyed||[...this.callers.values()].some(e=>!e.main)||null==(r=this.onEmpty)||r.call(this))}fail(e){var t;null==(t=this.router)||t.fail(e)}destroy(){var e;if(!this.destroyed)for(let t of(this.destroyed=!0,null==(e=this.router)||e.destroy(),this.callers.keys()))this.unregister(t)}}let eb=/(?:^|[.-])[a-f\d]{8,}(?=[.-]|$)/i;function ew(e){let t=new URL(e),r=t.pathname.slice(t.pathname.lastIndexOf("/")+1),n="0.6.0";return n&&!eb.test(r)&&t.searchParams.set("__doubao_resource_reload",n),t.href}function eS(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}function ex(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function eI(e){return e.containerType??"PAGE"}function ek(e){return"WIDGET"===e?"content":"fill"}function eC(e){if("function"==typeof CustomEvent)return new CustomEvent("error",{detail:{error:e}});let t=new Event("error");return Object.defineProperty(t,"detail",{value:{error:e}}),t}class eE{container;options;sandboxUrl;targetOrigin;bridge=null;caller;connected=!1;failed=!1;handshakeTimer=null;loaded=!1;loadCount=0;port=null;preparedForRender=!1;preparedContainerType=null;renderMessage=null;view=null;constructor(e){let t=new URL(e.sandboxUrl??"https://apps-web-sdk-sandbox.doubaocdn.com/sandbox");if("https:"!==t.protocol&&!("http:"===t.protocol&&eS(t.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.container=e.container,this.options=e,this.sandboxUrl=ew(t),this.targetOrigin=t.origin}get element(){return this.view}prepare(e){this.clear();try{this.createView(e),this.preparedForRender=!0}catch(e){throw this.clear(),e}}createView(e){var t,r;if(new URL((null==(t=globalThis.location)?void 0:t.href)??"http://localhost/").origin===this.targetOrigin)return this.abortRender(Error("iframe isolation requires a cross-origin sandbox URL"));if(this.view)return this.preparedContainerType!==e?this.abortRender(Error("iframe container type cannot change after preparation")):this.view;let n=document.createElement("iframe");n.className=this.options.className??"doubao-web-container-view",n.dataset.containerType=e,n.dataset.webSizing=ek(e),n.referrerPolicy="no-referrer",n.title="Doubao app content",n.sandbox.add("allow-scripts","allow-same-origin");let a=eS((null==(r=globalThis.location)?void 0:r.hostname)??"");return a&&n.setAttribute("credentialless",""),n.setAttribute("allow",a?"picture-in-picture 'none'; local-network-access 'src'; loopback-network 'src'":"picture-in-picture 'none'"),n.src=this.sandboxUrl,n.style.display="APP"===e||"TOOL"===e?"none":"block",n.style.border="0",n.style.width="100%",n.style.height="WIDGET"===e?"0px":"100%",n.addEventListener("load",()=>this.handleLoad()),this.view=n,this.preparedContainerType=e,this.container.replaceChildren(n),n}render(e){var t,r,n,a;this.preparedForRender||this.clear(),this.preparedForRender=!1;let i=eI(e),s=new URL(ex(e),document.baseURI).href,o=e.initData??{},l={...V(),...e.globalProps??{}};this.bridge=e.bridge??(null==(t=this.options.runtime)?void 0:t.bridge)??new e_,this.caller=e.bridgeCaller??this.bridge.register(e=>this.sendBridgeMessage(e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===i);let d=this.bridge.createSyncBridgeData(this.caller,l,this.options.fileSystemNamespace);this.renderMessage={type:"render",captureWidgetTap:this.options.captureWidgetTap,resourceUrl:s,resourceRoot:(null==(r=e.applicationPackage)?void 0:r.resourceRoot)??(null==(a=this.options.runtime)||null==(n=a.packageInfo)?void 0:n.resourceRoot),containerType:i,initData:o,globalProps:l,syncBridgeData:d};try{let e=this.createView(i);return this.connected?this.postOrFail(this.renderMessage):this.loaded&&this.connect(),e}catch(e){throw this.clear(),e}}clear(){var e,t;this.connected&&this.post({type:"dispose"}),this.destroyChannel(),this.caller&&(null==(t=this.bridge)||t.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(e=this.view)||e.remove(),this.view=null,this.preparedContainerType=null,this.renderMessage=null,this.connected=!1,this.failed=!1,this.loaded=!1,this.loadCount=0,this.preparedForRender=!1,this.container.replaceChildren()}sendEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.postOrFail({type:"global-event",name:e,params:t})}sendBridgeMessage(e){this.postOrFail({type:"bridge-message",message:e})}sendGlobalEvent(e,t){this.postOrFail({type:"raw-global-event",name:e,params:t})}reload(){this.post({type:"reload"})}abortRender(e){var t,r;throw null==(t=(r=this.options).onError)||t.call(r,e,eC(e)),e}handleLoad(){this.failed||!this.view||((this.loadCount+=1,this.loadCount>1)?this.fail(Error("iframe navigated after the sandbox runtime loaded")):(this.loaded=!0,this.renderMessage&&this.connect()))}connect(){if(this.failed||!this.view||this.connected||this.port)return;let e=new MessageChannel;this.port=e.port1,e.port1.onmessage=e=>this.handleMessage(e),e.port1.onmessageerror=e=>this.fail(Error("iframe message could not be decoded"),e),e.port1.start(),this.handshakeTimer=setTimeout(()=>this.fail(Error("iframe sandbox handshake timed out")),1e4);try{var t;null==(t=this.view.contentWindow)||t.postMessage({type:"doubao-web-sdk:connect",protocolVersion:1,sdkVersion:"0.6.0"},this.targetOrigin,[e.port2])}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}handleMessage(e){var t,r,n;if(!e.data||"object"!=typeof e.data)return void this.fail(Error("iframe sandbox sent an invalid protocol message"),e);let a=e.data;if(!this.connected)return"connected"!==a.type||1!==a.protocolVersion?void this.fail(Error("iframe sandbox protocol version mismatch"),e):(this.connected=!0,this.clearHandshakeTimer(),void(this.renderMessage&&this.postOrFail(this.renderMessage)));switch(a.type){case"ready":null==(t=(r=this.options).onReady)||t.call(r);break;case"error":this.fail(Error(a.message),e);break;case"resize":(null==(n=this.renderMessage)?void 0:n.containerType)!=="WIDGET"||!Number.isFinite(a.height)||a.height<0?this.fail(Error("only Widget containers may resize the iframe"),e):this.view&&(this.view.style.height=`${a.height}px`,this.view.height=String(a.height));break;case"native-call":!Number.isSafeInteger(a.requestId)||a.requestId<=0||("AppletBridgeModule"!==a.moduleName||"postMessage"!==a.name)&&("AppletJSModule"!==a.moduleName&&"LynxConsoleModule"!==a.moduleName&&"Console"!==a.moduleName||"log"!==a.name)?this.fail(Error("iframe sandbox sent an invalid bridge call"),e):this.handleNativeCall(a);break;case"connected":this.fail(Error("iframe sandbox connected more than once"),e);break;default:this.fail(Error("iframe sandbox sent an invalid protocol message"),e)}}async handleNativeCall(e){let t;if(!this.renderMessage||!this.view)return;let r=this.bridge,n=this.caller;if(r&&n){try{t=await r.dispatch(n,e.name,e.data,e.moduleName,{containerType:this.renderMessage.containerType,element:this.view,globalProps:this.renderMessage.globalProps,fileSystemNamespace:this.renderMessage.syncBridgeData.fileSystemNamespace},"iframe")}catch(t){if(this.bridge!==r||this.caller!==n)return;this.postOrFail({type:"bridge-result",requestId:e.requestId,error:S(t)});return}this.bridge===r&&this.caller===n&&this.postOrFail({type:"bridge-result",requestId:e.requestId,result:t})}}post(e){this.connected&&this.port&&this.port.postMessage(e)}postOrFail(e){try{this.post(e)}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}fail(e){var t,r,n,a;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eC(e);this.failed||(this.failed=!0,this.destroyChannel(),this.caller&&(null==(a=this.bridge)||a.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(t=this.view)||t.remove(),this.view=null,this.renderMessage=null,null==(r=(n=this.options).onError)||r.call(n,e,i))}clearHandshakeTimer(){null!==this.handshakeTimer&&clearTimeout(this.handshakeTimer),this.handshakeTimer=null}destroyChannel(){var e;this.clearHandshakeTimer(),null==(e=this.port)||e.close(),this.port=null,this.connected=!1}}let eN={mode:"iframe",createContainer:e=>new eE(e)};function eM(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function eT(e){return new URL(e,eM()).toString()}function eR(e,t){if(!t)return e;let r=new URL(e,eM());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class eA{options;packages=new Map;resolveManifestUrl;resourceUrlVersion;constructor(e={}){this.options=e,this.resolveManifestUrl=e.resolveManifestUrl,this.resourceUrlVersion=e.resourceUrlVersion}configure(e){e.resolveManifestUrl&&(this.resolveManifestUrl=e.resolveManifestUrl),"resourceUrlVersion"in e&&(this.resourceUrlVersion=e.resourceUrlVersion)}async getPackageSource(e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1],!this.resolveManifestUrl)throw Error("PackageManager requires resolveManifestUrl");return{manifestUrl:await this.resolveManifestUrl({appId:e})}}cached(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r.signal&&m(r.signal);let n=this.packages.get(e);return(!n||r.forceReload)&&(n=t(),this.packages.set(e,n),n.catch(()=>{this.packages.get(e)===n&&this.packages.delete(e)})),r.signal?g(()=>n,r.signal):n}async fetchPackage(e,t){return{manifestUrl:e,resourceRoot:t,manifest:await c(e,{fetcher:this.options.fetcher})}}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.signal&&m(t.signal);let{manifestUrl:r,resourceRoot:n}=await this.getPackageSource(e,t),a=eT(r),i=await this.cached(a,()=>this.fetchPackage(a,n),t);if(e&&i.manifest.appId&&i.manifest.appId!==e)throw Error("Resolved package appId must match the requested application");return i}resolveWidget(e,t){let r=this.tryResolveWidgetFromPackage(e,t),n=e.manifest.appRuntimeEntry?p(e.manifestUrl,e.manifest.appRuntimeEntry):void 0;return{packageInfo:e,appId:e.manifest.appId,appName:(null==r?void 0:r.appName)??e.manifest.name,icon:(null==r?void 0:r.iconSrc)??e.manifest.iconSrc,appRuntimeEntry:n?eR(n,e.resourceUrlVersion??this.resourceUrlVersion):void 0,resourceUrl:(null==r?void 0:r.resourceUrl)??"",titleType:null==r?void 0:r.entry.titleType,boxType:null==r?void 0:r.entry.boxType}}preload(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.loadPackage(e,t)}setPackage(e){this.packages.set(eT(e.manifestUrl),Promise.resolve(e))}deletePackage(e){this.packages.delete(eT(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}resolveWidgetEntry(e,t){let r=e.manifest.name??t.name,n=p(e.manifestUrl,t);return{appId:e.manifest.appId,entry:t,iconSrc:e.manifest.iconSrc??d(t.icons),appName:r,resourceUrl:n?eR(n,e.resourceUrlVersion??this.resourceUrlVersion):void 0}}tryResolveWidgetFromPackage(e,t){let r=e.manifest.getOptionalWidgetEntry(t);if(r)return this.resolveWidgetEntry(e,r)}}class eP{send;ready;pendingCalls=new Map;destroyed=!1;nextCallbackId=1e6;constructor(e,t){this.send=e,this.ready=t}call(e,t){if(this.destroyed)return Promise.reject(Error("RuntimeRouter was destroyed"));let r=this.nextCallbackId++,n={...t,callbackId:r};return new Promise((a,i)=>{this.pendingCalls.set(r,{callbackId:t.callbackId,reject:i,resolve:a,caller:e}),(async()=>{try{await this.ready(),this.pendingCalls.has(r)&&this.send(n)}catch(t){let e=this.pendingCalls.get(r);if(!e)return;this.pendingCalls.delete(r),e.reject(t instanceof Error?t:Error(String(t)))}})()})}handleMainBridgeMessage(e){if(v(e)){let t=this.pendingCalls.get(e.callbackId);return!!t&&(this.pendingCalls.delete(e.callbackId),t.resolve({routed:!0,result:{...e,callbackId:t.callbackId}}),!0)}return!1}cancel(e){for(let[t,r]of this.pendingCalls)r.caller===e&&(this.pendingCalls.delete(t),r.reject(Error("Caller was detached from the RuntimeBridge")))}destroy(){this.destroyed||(this.destroyed=!0,this.fail(Error("RuntimeRouter was destroyed")))}fail(e){for(let t of this.pendingCalls.values())t.reject(e);this.pendingCalls.clear()}}let ej="onDestroy",eL="onShow";function eD(e,t){let r=function(e){let{pageId:t,viewData:r}=function(e){if(!e)throw Error("route url must be a non-empty string");let t=e.indexOf("?"),r=-1===t?e:e.slice(0,t);if(!r)throw Error("route url must include a page path");let n={};return new URLSearchParams(-1===t?"":e.slice(t+1)).forEach((e,t)=>{n[t]=e}),{pageId:r,viewData:n}}(e.url),n=JSON.stringify(r);return{pageId:t,initData:{viewData:r,viewContext:{}},globalProps:{__LOCATION__:e.url,__RENDER_DATA__:n,__VIEW_CONTEXT__:{}}}}(e);return{...r,entry:t.getPageEntry(r.pageId)}}function eO(e,t){var r;let n=Object.entries((null==(r=t.initData)?void 0:r.viewData)??{}).map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`}).join("&");return{route:`${e}${n?`?${n}`:""}`}}function eU(e,t){return{packageInfo:t,...e}}function eq(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function e$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return eU(t,eq(e))}function eB(e){if(s(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return s(t)?t:{}}catch{return{}}}class eF{pageHost;className;onError;appGlobalProps;appInitData;getRuntimeGlobalProps;configuredFileSystemNamespace;runtimeKernel;packageSnapshot;packageLoading;packageSource;lifecycle=new AbortController;get packageInfo(){if(this.destroyed)throw Error("Runtime was destroyed");if(!this.packageSnapshot)throw Error("Runtime package is not loaded");return this.packageSnapshot}get manifest(){return this.packageInfo.manifest}get manifestUrl(){return this.packageInfo.manifestUrl}pageCapsule;resolvedFileSystemNamespace;appRuntime=null;appStart=null;bridge;packageManager;sandboxUrl;viewContext;appGroupId;destroyed=!1;pendingAppEvents=[];clearingAppRuntime=!1;appCallController=new AbortController;apiContextOwner={};stack=[];pendingPages=[];nextPageIndex=0;constructor(e,t=eN,r){this.sandboxUrl=e.sandboxUrl,this.packageManager=e.packageManager??new eA({resolveManifestUrl:()=>this.manifestUrl});let n=new eP(e=>this.sendAppBridgeMessage(e),async()=>{if(await this.ensureAppRuntime(),!this.appStart)throw Error("No Web entry configured for app runtime");return this.appStart.promise});this.appGroupId=e.appGroupId,this.viewContext=e.viewContext,this.pageHost=e.pageHost,this.runtimeKernel=t,"manifest"in e?(this.packageSnapshot={manifest:e.manifest,manifestUrl:String(e.manifestUrl),resourceRoot:e.resourceRoot,resourceUrlVersion:""},e.packageManager||this.packageManager.setPackage(this.packageSnapshot)):this.packageSource=e,this.pageCapsule=e.pageCapsule,this.className=e.className,this.onError=e.onError,this.appGlobalProps=e.appGlobalProps,this.appInitData=e.appInitData,this.getRuntimeGlobalProps=e.getRuntimeGlobalProps,this.configuredFileSystemNamespace=e.fileSystemNamespace,this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace(),this.updateEmptyState(),this.bridge=new e_(n,{getCurrentPages:()=>this.getCurrentPages(),getPackageInfo:()=>this.getPackageInfo(),navigateTo:e=>this.navigateToBridgePage(e),redirectTo:e=>this.redirectToBridgePage(e),reLaunch:e=>this.reLaunchBridgePage(e),navigateBack:e=>this.navigateBackBridgePage(e),exitApp:()=>this.exitBridgeApp()},r,{apiRegistry:e.apiRegistry,getFileSystemNamespace:()=>this.fileSystemNamespace,nativeModulesCallHandler:e.nativeModulesCallHandler})}async loadPackage(){var e,t;if(this.destroyed)throw new DOMException("Runtime was destroyed","AbortError");let r=(null==(e=this.packageSource)?void 0:e.signal)?AbortSignal.any([this.lifecycle.signal,this.packageSource.signal]):this.lifecycle.signal;if(!this.packageSnapshot){if(!this.packageLoading){let e=this.packageSource,n=this.packageManager.loadPackage(e.appId,{signal:r,versionTag:e.versionTag??(null==(t=e.viewContext)?void 0:t.versionTag)}).then(e=>{m(r),this.destroyed||this.packageSnapshot||(this.packageSnapshot={...e,resourceUrlVersion:""},this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace())}).catch(e=>{throw this.packageLoading===n&&(this.packageLoading=void 0),e});this.packageLoading=n}let e=this.packageLoading;await g(()=>e,r)}return m(r),this.packageInfo}get fileSystemNamespace(){return this.resolvedFileSystemNamespace}get isDestroyed(){return this.destroyed}get pages(){return this.stack.map(e=>this.toStackEntry(e))}get currentPage(){let e=this.getCurrentStackItem();return e?this.toStackEntry(e):null}setManifest(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.manifestUrl;this.clear(),this.packageSnapshot={...this.packageSnapshot,manifest:e,manifestUrl:String(r),resourceUrlVersion:(null==(t=this.packageSnapshot)?void 0:t.resourceUrlVersion)??"1"},this.packageManager.setPackage(this.packageSnapshot),this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace()}async pushPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.packageSnapshot||await this.loadPackage(),this.pushLoadedPage(e)}async pushLoadedPage(e,t){var r,n;let a;if(this.destroyed)throw Error("Runtime was destroyed");if(!this.pageHost)throw Error("Opening Pages requires a Runtime pageHost");let i=this.resolvePageEntry(e),o=p(this.manifestUrl,i);if(!o)throw Error(`No Web entry configured for page entry: ${i.id}`);let l=this.lifecycle.signal;if(this.startAppRuntime(),this.appStart&&await this.appStart.promise,m(l),"all"===t)this.clearPages();else if("current"===t){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}let d={...e,globalProps:{...e.globalProps,...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}},u=eR(o,this.packageInfo.resourceUrlVersion),c=e.pageCapsule??this.pageCapsule,h=`page-${++this.nextPageIndex}`,g=(a=eB(null==(n=d.globalProps)?void 0:n.__VIEW_CONTEXT__),{...s(d.initData)?eB(d.initData.viewContext):{},...a,viewId:h,pageName:i.id,pageUrl:i.path}),f=null,v=this.pageHost.createPage({className:this.className,runtime:this,onError:this.onError,onReady:()=>{f&&this.stack.includes(f)&&(f.isReady=!0,this.flushPageLifecycleEvents(f))}},this.runtimeKernel,()=>this.exitBridgeApp());void 0!==e.pageCapsule&&(this.pageCapsule=e.pageCapsule),this.pendingPages.push(eO(i.path,e));try{let t,r,n=v.render({resourceUrl:u,groupId:this.manifest.appId,initData:s(d.initData)?{...d.initData,viewContext:g}:{viewContext:g},globalProps:(t=null==c?void 0:c.statusBarHeight,r="number"==typeof t&&Number.isFinite(t)?{statusBarHeight:t}:{},{...d.globalProps,...r,__VIEW_CONTEXT__:g}),pageCapsule:c}),a=this.getCurrentStackItem();return a&&(this.sendPageLifecycleEvent(a,"onHide"),a.page.setVisible(!1)),f={id:h,pageId:i.id,route:i.path,resourceUrl:u,entry:i,element:n,isReady:!1,options:{...e,entry:i,pageCapsule:c},pendingLifecycleEvents:[],page:v},this.stack.push(f),this.updateEmptyState(),this.sendPageLifecycleEvent(f,eL),this.sendAppEvent("onPageOpened",{viewId:f.id}),this.toStackEntry(f)}catch(e){throw v.clear(),this.updateEmptyState(),e}finally{this.pendingPages.pop()}}async replacePage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"current"))}async reLaunchPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"all"))}popPage(){let e=this.stack.pop();return e?this.removeStackItem(e,!0):null}clear(){this.lifecycle.abort(),this.lifecycle=new AbortController,this.packageLoading=void 0,this.clearPages(),this.clearAppRuntime(),this.packageSnapshot&&(this.packageSnapshot={...this.packageSnapshot,resourceUrlVersion:String(Number(this.packageSnapshot.resourceUrlVersion??0)+1)})}async restart(){if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");await this.withPageTransition(async()=>{let e=this.stack.map(e=>{let{options:t}=e;return t});for(let t of(this.clear(),e))await this.pushLoadedPage(t)})}reload(){var e;null==(e=this.getCurrentStackItem())||e.page.reload()}destroy(){var e;this.destroyed||(this.destroyed=!0,this.bridge.destroy(),this.clear(),null==(e=this.pageHost)||e.destroy())}clearPages(){for(;this.stack.length>0;){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}}async withPageTransition(e){let t=this.bridge.register();try{return await e()}finally{this.bridge.unregister(t)}}removeStackItem(e,t){let r=this.toStackEntry(e);this.sendPageLifecycleEvent(e,ej),e.page.clear();let n=this.getCurrentStackItem();return t&&n&&(n.page.setVisible(!0),this.sendPageLifecycleEvent(n,eL)),this.updateEmptyState(),r}async ensureAppRuntime(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.packageSnapshot||await this.loadPackage(),this.startAppRuntime(e)}startAppRuntime(){var e,t,r;let n,a,i,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.destroyed)throw Error("Runtime was destroyed");if(this.clearingAppRuntime)throw Error("Runtime is being cleared");if(null==(e=this.appStart)?void 0:e.error)throw this.appStart.error;if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let o=p(this.manifestUrl,this.manifest.appRuntimeEntry);if(!o)throw Error("No Web entry configured for app runtime");let l=eR(o,this.packageInfo.resourceUrlVersion),d=new Promise((e,t)=>{n=e,a=t});d.catch(()=>{});let u={promise:d,resolve:n,reject:a,error:void 0};this.appStart=u;let c=e=>{var t;this.appStart!==u||this.destroyed||this.clearingAppRuntime||((null==(t=this.appRuntime)?void 0:t.isReady)||(u.error=e,u.reject(e)),this.bridge.fail(e))},h=this.appCallController.signal;try{i=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document.body,n=document.createElement("div");n.className="doubao-runtime-app",n.hidden=!0,n.style.display="none";let a=t.createContainer({...e,container:n});return{render:e=>(r.append(n),a.render(e)),clear(){a.clear(),n.remove()},sendEvent:a.sendEvent.bind(a),sendBridgeMessage:a.sendBridgeMessage.bind(a)}}({runtime:this,sandboxUrl:this.sandboxUrl,className:this.className,onError:(e,t)=>{var r;this.appStart!==u||this.destroyed||this.clearingAppRuntime||(c(e),null==(r=this.onError)||r.call(this,e,t))},appletSessionMessageHandler:(e,t)=>{var r;return this.appStart!==u||this.destroyed||this.clearingAppRuntime||this.bridge.handleMainBridgeMessage(e)?{routed:!0}:(null==(r=s.appletSessionMessageHandler)?void 0:r.call(s,e,t))??{routed:!1}},getAppletContext:()=>({owner:this.apiContextOwner,signal:h,source:"app",viewContext:s.viewContext??this.viewContext}),onReady:()=>{var e;let t=this.appRuntime;this.clearingAppRuntime||!t||t.container!==i||t.isReady||u.error||(t.isReady=!0,this.flushAppEvents(),u.resolve(),null==(e=s.onReady)||e.call(s))}},this.runtimeKernel,null==(t=this.pageHost)?void 0:t.container),this.appRuntime={container:i,isReady:!1,pendingEvents:[{name:"onForeground",params:{}},...this.pendingAppEvents.splice(0)]};let e=void 0!==s.groupId?s.groupId:this.appGroupId;i.render({bridge:this.bridge,resourceUrl:l,groupId:null===e?void 0:e??this.manifest.appId,containerType:"APP",initData:this.appInitData??{},globalProps:{...e$(this.manifest,this.appGlobalProps),...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}})}catch(e){throw c(e instanceof Error?e:Error(String(e))),this.appRuntime=null,null==i||i.clear(),e}}clearAppRuntime(){var e;if(this.clearingAppRuntime)return;this.clearingAppRuntime=!0;let t=Error(this.destroyed?"Runtime was destroyed":"Runtime was cleared");null==(e=this.appStart)||e.reject(t),this.bridge.fail(t),this.pendingAppEvents=[];let r=this.appRuntime;(null==r?void 0:r.isReady)&&(r.container.sendEvent("onBackground"),r.container.sendEvent(ej)),null==r||r.container.clear(),this.appCallController.abort(),this.appCallController=new AbortController,this.appRuntime=null,this.appStart=null,this.clearingAppRuntime=!1}sendAppEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.appRuntime;if(!this.destroyed&&!this.clearingAppRuntime){if(!r)return void this.pendingAppEvents.push({name:e,params:t});if(!r.isReady)return void r.pendingEvents.push({name:e,params:t});r.container.sendEvent(e,t)}}sendAppBridgeMessage(e){if(!this.clearingAppRuntime){var t;null==(t=this.appRuntime)||t.container.sendBridgeMessage(e)}}flushAppEvents(){let e=this.appRuntime;if(null==e?void 0:e.isReady)for(let t of e.pendingEvents.splice(0))e.container.sendEvent(t.name,t.params)}sendPageLifecycleEvent(e,t){let r,n=(r={viewId:e.id,pageName:e.pageId,pageUrl:e.route},{viewId:e.id,eventName:JSON.stringify(r)});e.isReady?e.page.sendEvent(t,n):e.pendingLifecycleEvents.push({name:t,params:n})}flushPageLifecycleEvents(e){if(e.isReady)for(let t of e.pendingLifecycleEvents.splice(0))e.page.sendEvent(t.name,t.params)}resolvePageEntry(e){return e.entry??this.manifest.getPageEntry(e.pageId)}resolveRoutePageOptions(e){return eD(e,this.manifest)}getCurrentStackItem(){return this.stack[this.stack.length-1]??null}updateEmptyState(){var e;null==(e=this.pageHost)||e.setEmpty(0===this.stack.length)}getCurrentPages(){return[...this.stack.map(e=>eO(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?eq(this.manifest):{appId:null==(e=this.packageSource)?void 0:e.appId}}resolveFileSystemNamespace(){return void 0!==this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:eo({...this.appGlobalProps,packageInfo:this.getPackageInfo()})}async navigateToBridgePage(e){this.packageSnapshot||await this.loadPackage(),await this.pushLoadedPage(this.resolveRoutePageOptions(e))}async redirectToBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.resolveRoutePageOptions(e);await this.replacePage(t)}async reLaunchBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.resolveRoutePageOptions(e);await this.reLaunchPage(t)}navigateBackBridgePage(e){if(this.stack.length<=1)return!1;let t=Math.min(Math.max(1,Math.floor(e.delta??1)),this.stack.length-1);for(let e=0;e<t;e+=1)this.popPage();return!0}exitBridgeApp(){this.clear()}toStackEntry(e){return{id:e.id,pageId:e.pageId,route:e.route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class eW{kernel;autoRelease;runtimes=new Map;packageManagers=new WeakMap;nextPackageManagerId=0;constructor(e,t=!1){this.kernel=e,this.autoRelease=t}acquire(e){var t,r,n,a,i,s,o,l,d,c;let p=e.fileSystemNamespace??eo({...e.appGlobalProps,packageInfo:{appId:e.appId}}),h=new URL(e.appRuntimeEntry,null==(t=globalThis.location)?void 0:t.href).href,m=e.packageManager;m&&!this.packageManagers.has(m)&&this.packageManagers.set(m,this.nextPackageManagerId++);let g=[m?this.packageManagers.get(m):"",String(e.sandboxUrl??""),(null==(r=e.packageInfo)?void 0:r.manifestUrl)??"",(null==(n=e.packageInfo)?void 0:n.resourceRoot)??"",e.appId,(null==(a=e.viewContext)?void 0:a.conversationId)??"",p,e.versionTag??(null==(i=e.viewContext)?void 0:i.versionTag)??"",h].join("\0"),f=this.runtimes.get(g);if(f&&!f.isDestroyed)return f;let v=new eF({packageManager:m,pageHost:e.pageHost,sandboxUrl:e.sandboxUrl,manifest:(null==(s=e.packageInfo)?void 0:s.manifest)??new u({manifestVersion:"3.0",packageName:e.appId,appId:e.appId,versionCode:"",applet:{appletId:e.appId,digest:"",appRuntimeEntry:h,pages:[]},widgets:[]}),manifestUrl:(null==(o=e.packageInfo)?void 0:o.manifestUrl)??h,resourceRoot:null==(l=e.packageInfo)?void 0:l.resourceRoot,registerPageController:!1,appGroupId:null,apiRegistry:e.apiRegistry??C,className:e.className,fileSystemNamespace:p,nativeModulesCallHandler:e.nativeModulesCallHandler,appInitData:e.appInitData,appGlobalProps:eU(e.appGlobalProps??{},{appId:e.appId}),getRuntimeGlobalProps:e.getRuntimeGlobalProps,viewContext:{appId:e.appId,conversationId:null==(d=e.viewContext)?void 0:d.conversationId,versionTag:e.versionTag??(null==(c=e.viewContext)?void 0:c.versionTag)},onError:e.onError},this.kernel??eN,this.autoRelease?()=>this.release(v):void 0);return this.runtimes.set(g,v),v}release(e){for(let[t,r]of this.runtimes)if(r===e){this.runtimes.delete(t),e.destroy();return}}destroy(){let e=[...this.runtimes.values()];for(let t of(this.runtimes.clear(),e))t.destroy()}}function eH(e,t){return class extends e{hostOptions;prepared=!1;constructor(e){super({...e,sandboxUrl:e.runtime?e.runtime.sandboxUrl:e.sandboxUrl}),this.hostOptions=e}prepare(e){super.prepare(e),this.prepared=!0}clear(){this.prepared=!1,super.clear()}render(e){var r,n,a,i,s;this.prepared||this.clear(),this.prepared=!1;let{application:o,applicationPackage:l,appRuntimeEntry:d,...u}=e,c=(null==o?void 0:o.appId)??(null==(n=u.globalProps)||null==(r=n.packageInfo)?void 0:r.appId),p=(null==o?void 0:o.appRuntimeEntry)??d,h=(null==o?void 0:o.viewContext)??(null==(a=u.globalProps)?void 0:a.__VIEW_CONTEXT__),m=this.hostOptions.runtime??(c&&p?(this.hostOptions.runtimeManager??t()).acquire({appId:c,appRuntimeEntry:p,packageInfo:l,packageManager:this.hostOptions.packageManager,sandboxUrl:this.hostOptions.sandboxUrl,apiRegistry:this.hostOptions.apiRegistry,nativeModulesCallHandler:this.hostOptions.nativeModulesCallHandler,versionTag:(null==o?void 0:o.versionTag)??(null==h?void 0:h.versionTag),viewContext:h,fileSystemNamespace:this.hostOptions.fileSystemNamespace,appGlobalProps:{userId:null==(i=u.globalProps)?void 0:i.userId,userID:null==(s=u.globalProps)?void 0:s.userID}}):void 0),g=null==m?void 0:m.bridge.register();try{return super.render({...u,applicationPackage:l,bridge:(null==m?void 0:m.bridge)??u.bridge})}catch(e){throw this.clear(),e}finally{g&&(null==m||m.bridge.unregister(g))}}}}new eW(void 0,!0),r(52452),r(51237),r(25907),r(92151);var ez=r(65703);let eV="embed-webview",eG="__channel_ack__",eJ=new WeakMap,eK=e=>({url:e});function eX(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function eZ(e){return"string"==typeof e?e:JSON.stringify(e??{})}let eQ=globalThis.HTMLElement??class{};r(31178);let eY="region-to-decode";function e0(e){if("string"==typeof e)try{e=JSON.parse(e)}catch{return null}if(!e||"object"!=typeof e)return null;let{x:t,y:r,width:n,height:a}=e;return![t,r,n,a].every(Number.isFinite)||t<0||r<0||n<=0||a<=0?null:{x:t,y:r,width:n,height:a}}class e1{element;static observedAttributes=[];image;attributes=new MutationObserver(()=>this.update());resize;viewSize;cropStyle;constructor(e){var t;this.element=e,this.image=(null==(t=e.shadowRoot)?void 0:t.querySelector("#img"))??null,Object.defineProperty(e,eY,{configurable:!0,get:()=>e0(e.getAttribute(eY)),set:t=>{let r=e0(t);r?e.setAttribute(eY,JSON.stringify(r)):e.removeAttribute(eY)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[eY,"src","mode","auto-size"]}),this.update()}clearCrop=()=>{var e;null==(e=this.cropStyle)||e.remove(),this.cropStyle=void 0};stopRendering(){var e,t,r;null==(e=this.resize)||e.disconnect(),this.resize=void 0,this.viewSize=void 0,null==(t=this.image)||t.removeEventListener("load",this.update),null==(r=this.image)||r.removeEventListener("error",this.clearCrop),this.clearCrop()}update=()=>{var e,t,r;let n=e0(this.element.getAttribute(eY)),a=this.image;if(!n||!a)return void this.stopRendering();this.resize||(this.resize=new ResizeObserver(e=>{let[t]=e;this.viewSize=t.contentRect,this.update()}),this.resize.observe(this.element),a.addEventListener("load",this.update),a.addEventListener("error",this.clearCrop));let i=a.naturalWidth,s=a.naturalHeight,o=this.element.getAttribute("src"),l=this.element.getRootNode().host,d=o?(null==l||null==(e=l.resolveResource)?void 0:e.call(l,o))??o:o;if(!a.complete||!i||!s||a.getAttribute("src")!==d)return void this.clearCrop();let u=Math.min(n.width,i-n.x),c=Math.min(n.height,s-n.y),p=getComputedStyle(this.element),h=Number.parseFloat(p.paddingLeft)||0,m=Number.parseFloat(p.paddingTop)||0,g=(null==(t=this.viewSize)?void 0:t.width)??this.element.clientWidth-h-(Number.parseFloat(p.paddingRight)||0),f=(null==(r=this.viewSize)?void 0:r.height)??this.element.clientHeight-m-(Number.parseFloat(p.paddingBottom)||0);if(u<=0||c<=0||g<=0||f<=0)return void this.clearCrop();let v=g/u,y=f/c,_=this.element.getAttribute("mode");"aspectFit"===_?v=y=Math.min(v,y):"aspectFill"===_?v=y=Math.max(v,y):"center"===_&&(v=y=1);let b=h+(g-u*v)/2-n.x*v,w=m+(f-c*y)/2-n.y*y;this.cropStyle||(this.cropStyle=this.element.ownerDocument.createElement("style"),this.cropStyle.setAttribute("data-doubao-image-region",""),this.element.shadowRoot.append(this.cropStyle)),this.cropStyle.textContent=`#img {
|
|
2
2
|
position: absolute !important;
|
|
3
3
|
margin: 0 !important;
|
|
4
4
|
padding: 0 !important;
|
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
object-fit: fill !important;
|
|
17
17
|
clip-path: inset(${n.y*y}px ${(i-n.x-u)*v}px
|
|
18
18
|
${(s-n.y-c)*y}px ${n.x*v}px) !important;
|
|
19
|
-
}`};dispose(){this.attributes.disconnect(),this.stopRendering()}}let e2=new Set;var e3=r(37474);let e4=new WeakMap;function e5(e,t,r){let n=new Map;for(let a of t){let t=Reflect.get(e,a);n.set(a,Object.getOwnPropertyDescriptor(e,a)),Object.defineProperty(e,a,{configurable:!0,writable:!0,value(){for(var e=arguments.length,n=Array(e),a=0;a<e;a++)n[a]=arguments[a];return r(),Reflect.apply(t,this,n)}})}return()=>{for(let[t,r]of n)r?Object.defineProperty(e,t,r):Reflect.deleteProperty(e,t)}}class e6{element;placeholder=document.createComment("map-marker");parent;cleanupElement;constructor(e){this.element=e;let t=e.parentNode;if(!t)throw Error("Web Map Marker requires a component parent");this.parent=t;let r=e4.get(t);if(!r){let e=new Set;r={portals:e,cleanup:e5(t,["appendChild","insertBefore","removeChild","replaceChild","append","prepend","replaceChildren"],()=>{for(let t of e)t.restore()})},e4.set(t,r)}r.portals.add(this),this.cleanupElement=e5(e,["remove","replaceWith","before","after"],()=>{for(let e of r.portals)e.restore()})}get connected(){return this.element.parentNode===this.parent?this.element.isConnected:this.placeholder.isConnected}mount(e){if(this.element.parentNode!==e){if(this.element.parentNode!==this.parent)throw Error("Web Map Marker component parent changed");Node.prototype.insertBefore.call(this.parent,this.placeholder,this.element),e.appendChild(this.element)}}restore(){this.placeholder.parentNode===this.parent&&Node.prototype.replaceChild.call(this.parent,this.element,this.placeholder)}destroy(){this.restore(),this.cleanupElement();let e=e4.get(this.parent);null==e||e.portals.delete(this),(null==e?void 0:e.portals.size)===0&&(e.cleanup(),e4.delete(this.parent))}}class e8{element;namespace;map;onError;onClick;content=document.createElement("div");portal;originalStyles=new Map;styleObserver=new MutationObserver(()=>this.syncZIndex());marker;defaultZIndex;positionKey;optionsKey;waitingForPosition=!1;syncing=!1;disposed=!1;constructor(e,t,r,n,a){this.element=e,this.namespace=t,this.map=r,this.onError=n,this.onClick=a,this.portal=new e6(e),this.content.style.cssText="width:0;height:0;overflow:visible;",this.styleObserver.observe(e,{attributes:!0,attributeFilter:["style","class"]})}get connected(){return this.portal.connected}sync(e){if(!this.disposed&&!this.syncing){this.syncing=!0;try{if(!e.position&&!e.containerPosition){var t;this.portal.restore(),null==(t=this.marker)||t.destroy(),this.marker=void 0,this.optionsKey=void 0,this.positionKey=void 0,this.waitingForPosition=!0,this.style("visibility","hidden");return}this.waitingForPosition&&(this.style("visibility",this.originalStyles.get("visibility")??""),this.waitingForPosition=!1),this.style("position","relative"),"inline"===getComputedStyle(this.element).display&&this.style("display","inline-block"),this.element.style.width||this.style("width","max-content"),this.style("transform",`translate(${-100*e.anchor[0]}%, ${-100*e.anchor[1]}%)`);let r="amap"===this.namespace.getProvider(),n={content:this.content,containerPosition:e.containerPosition?[e.containerPosition.x,e.containerPosition.y]:null,anchor:r?"top-left":0,angle:e.rotation,opacity:e.alpha,clickable:e.clickable,draggable:e.draggable,bubble:!e.clickable,animation:e.animate??(r?{scale:{from:1,to:1,duration:0}}:null)},a=JSON.stringify(e.position);this.marker&&a===this.positionKey||(n.position=e.position&&[e.position.longitude,e.position.latitude]),this.portal.mount(this.content);let i=JSON.stringify(e);if(this.marker&&this.optionsKey===i)return void this.syncZIndex();this.optionsKey=i,this.marker?this.marker.setOptions(n):(this.marker=new this.namespace.Marker(n),this.defaultZIndex=this.marker.getzIndex(),this.marker.on("click",this.onClick)),this.syncZIndex(),this.marker.getMap()!==this.map&&this.marker.setMap(this.map),this.positionKey=a}catch(e){this.onError(e)}finally{this.syncing=!1}}}syncZIndex(){if(this.marker&&!this.disposed)try{let e=Number.parseInt(getComputedStyle(this.element).zIndex,10),t=Number.isFinite(e)?e:this.defaultZIndex;void 0!==t&&t!==this.marker.getzIndex()&&this.marker.setzIndex(t)}catch(e){this.onError(e)}}style(e,t){this.originalStyles.has(e)||this.originalStyles.set(e,this.element.style.getPropertyValue(e)),this.element.style.getPropertyValue(e)!==t&&this.element.style.setProperty(e,t)}destroy(){var e;if(!this.disposed)for(let[t,r]of(this.disposed=!0,this.styleObserver.disconnect(),this.portal.destroy(),null==(e=this.marker)||e.destroy(),this.originalStyles))this.element.style.setProperty(t,r)}}let e7=e=>{let{longitude:t,latitude:r}=e;return[t,r]};function e9(e,t,r,n,a){let i=new Set(t.map(e=>{let{id:t}=e;return t}));for(let[t,r]of e)i.has(t)||(r.destroy(),e.delete(t));for(let i of t)try{let t=r(i),a=e.get(i.id);if(a){let{id:e,...r}=t;a.setOptions(r)}else e.set(i.id,n(t,i))}catch(e){a(e)}}class te{namespace;map;onError;onPolylineClick;polylines=new Map;polygons=new Map;circles=new Map;arcs=new Map;routeLabels=new Map;warnings=new Set;constructor(e,t,r,n){this.namespace=e,this.map=t,this.onError=r,this.onPolylineClick=n}warn(e){this.warnings.has(e)||(this.warnings.add(e),this.onError(Error(`Web Map 暂不支持 ${e}`)))}add(e){e.on("warning",e=>{this.onError(e.error??Error(e.reason??e.feature??"Web Map 覆盖物降级"))});try{return this.map.add(e),e}catch(t){throw e.destroy(),t}}sync(e){var t;let r=function(e){let t=new Map,r=new Set;for(let a of e){var n;if(!a.id.startsWith("__doubao_polyline_arrow__:"))continue;let i=null==(n=a.edgeTextureAssets)?void 0:n.find(e=>{let{id:t}=e;return"__doubao_polyline_arrow_texture__"===t});if(i)try{let n=decodeURIComponent(a.id.slice(26));e.some(e=>e.id===n)&&(t.set(n,{iconPath:i.url}),r.add(a))}catch{}}return e.filter(e=>!r.has(e)).map(e=>({...e,arrow:t.get(e.id)??e.arrow}))}(e.polyline??[]),n=this.namespace.supports("Polyline.edgeTexture").supported,a=this.namespace.supports("RouteLabel").supported;!n&&r.some(e=>{var t,r;return(null==(t=e.edgeTexture)?void 0:t.length)||(null==(r=e.edgeTextureAssets)?void 0:r.length)})&&this.warn("当前图商的 polyline 纹理"),!a&&(null==(t=e.routeLabel)?void 0:t.length)&&this.warn("当前图商的 routeLabel"),r.some(e=>e.collideDetection)&&this.warn("polyline POI 碰撞避让"),e9(this.polylines,r,e=>{var t;return{id:e.id,path:e.points.map(e7),strokeColors:e.edgeColor??[],arrow:e.arrow??null,edgeTexture:n?e.edgeTexture??[]:[],edgeTextureAssets:n?e.edgeTextureAssets??[]:[],strokeColor:(null==(t=e.edgeColor)?void 0:t[0])??"#0066ff",strokeWeight:e.width??2,strokeStyle:e.dottedLine?"dashed":"solid",lineCap:"line_cap_round"===e.lineCapType?"round":"butt",lineJoin:"line_join_round"===e.lineJoinType?"round":"line_join_miter"===e.lineJoinType?"miter":"bevel",zIndex:e.zIndex??0}},(e,t)=>{let r=new this.namespace.Polyline(e);return r.on("click",()=>this.onPolylineClick(t.id)),this.add(r)},this.onError),e9(this.polygons,e.polygons??[],e=>({id:e.id,path:e.points.map(e7),fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,strokeStyle:e.dottedLine?"dashed":"solid",zIndex:e.zIndex}),e=>{let t=new this.namespace.Polygon(e);return this.add(t)},this.onError),e9(this.circles,e.circles??[],e=>({id:e.id,center:e7(e.center),radius:e.radius,fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,zIndex:e.zIndex}),e=>{let t=new this.namespace.Circle(e);return this.add(t)},this.onError),e9(this.arcs,e.arcs??[],e=>({id:e.id,path:[e7(e.start),e7(e.mid??e.middle),e7(e.end)],strokeColor:e.color??"#0066ff",strokeWeight:e.width??2,zIndex:e.zIndex}),e=>{let t=new this.namespace.Arc(e);return this.add(t)},this.onError),e9(this.routeLabels,a?e.routeLabel??[]:[],e=>({id:e.id,path:e.points.map(e7),text:e.text,textColor:e.textColor??"#000000",fontSize:e.fontSize??12,fontWeight:e.fontWeight??"normal",borderColor:e.borderColor??"#cccccc",borderWidth:e.borderWidth??0,zIndex:e.zIndex??0}),e=>this.add(new this.namespace.RouteLabel(e)),this.onError)}destroy(){for(let e of[this.polylines,this.polygons,this.circles,this.arcs,this.routeLabels]){for(let t of e.values())t.destroy();e.clear()}}}let tt={baidu:{provider:"baidu",security:{baidu:{serviceHost:"https://api.doubao-dev.com/_BMapService/"}}},amap:{provider:"amap",key:{amap:"f57928bd7156da61d512795ec5c0c968"},security:{amap:{serviceHost:"https://api.doubao-dev.com/_AMapService"}}}},tr=new WeakMap,tn=new WeakMap,ta=new WeakMap,ti=new WeakMap;function ts(e,t,r){if(t in r)return r[t];let n=e.getAttribute(t);if(n)try{return JSON.parse(n)}catch{return}}function to(e,t,r){let n=Number(e.getAttribute(t));return Number.isFinite(n)&&e.hasAttribute(t)?n:r}function tl(e,t,r){let n=e.getAttribute(t);return null===n?r:"false"!==n&&"0"!==n}function td(e){let{longitude:t,latitude:r}=e;return[t,r]}function tu(e){return{longitude:e.lng,latitude:e.lat}}function tc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!1}))}function tp(e,t){let r=t instanceof Error?t:Error(String(t));console.error("[Doubao Map]",r.message),e.dispatchEvent(new CustomEvent("error",{detail:{error:r}}))}function th(e){return tr.get(e)??{}}function tm(e){return tn.get(e)??{}}function tg(e){let t=ti.get(e);if(t)return t;let r=e.closest("map");return r?ta.get(r):void 0}class tf{element;map;namespace;syncingMarkers=!1;overlays;markers=new Map;cleanupTileLoad;surface;resize;sizeFrame=0;loading=!1;initializationBlocked=!1;disposed=!1;ready=!1;lastAttributes="";lastOverlays="";lastStyle="";lastLogoPosition="";warnings=new Set;constructor(e){var t;if(this.element=e,ta.set(e,this),this.installMethods(),"inline"===getComputedStyle(e).display&&(e.style.display="block"),"static"===getComputedStyle(e).position&&(e.style.position="relative"),e.style.overflow="hidden",this.resize="function"==typeof ResizeObserver?new ResizeObserver(()=>this.initialize()):void 0,null==(t=this.resize)||t.observe(e),!this.resize){let e=()=>{this.disposed||this.map||this.loading||this.initializationBlocked||(this.initialize(),this.sizeFrame=requestAnimationFrame(e))};this.sizeFrame=requestAnimationFrame(e)}this.initialize()}warn(e){this.warnings.has(e)||(this.warnings.add(e),tp(this.element,Error(`Web Map 暂不支持 ${e}`)))}getMapConfig(){let e=ts(this.element,"extra-params",th(this.element));return tt[(null==e?void 0:e.useAliMap)===!0?"amap":"baidu"]}initialize(){var e;if(this.disposed||this.loading||this.initializationBlocked||this.map||this.element.clientWidth<=0||this.element.clientHeight<=0)return;let t=this.getMapConfig(),r=(null==(e=this.element.ownerDocument.location)?void 0:e.hostname)??"";if("baidu"===t.provider&&(eS(r)||"[::1]"===r||r.endsWith(".localhost"))){this.initializationBlocked=!0,tp(this.element,Error("当前豆包百度地图账号未授权本地域名,请使用获准域名的 sandbox 调试地图。"));return}this.loading=!0;let n=document.createElement("div");n.dataset.doubaoMapSurface="",n.style.cssText="position:absolute;inset:0;width:100%;height:100%;",this.element.prepend(n),this.surface=n,Promise.resolve().then(()=>e3.H3.load(t)).then(e=>{this.disposed||this.createMap(e,n)}).catch(e=>{this.disposed||tp(this.element,e),n.remove(),this.surface=void 0}).finally(()=>{this.loading=!1})}createMap(e,t){let r=this.element,n=ts(r,"center",th(r)),a=ts(r,"scale-range",th(r));try{let i=new e.Map(t,{center:n&&td(n),zoom:to(r,"scale",16),zooms:a??[3,20],rotation:to(r,"rotate",0),logoPosition:r.getAttribute("logo-position")||"bottom-left",eventContext:!0,enableNativeInteraction:tl(r,"native-interaction-enabled",!0),showScale:tl(r,"enable-scale-controls",!1),zoomEnable:tl(r,"enable-scale",!0),dragEnable:tl(r,"enable-drag",!0),rotateEnable:tl(r,"enable-rotate",!1)});this.map=i,this.namespace=e,this.overlays=new te(e,i,e=>tp(r,e),e=>tc(r,"clickpolyline",{id:e}));let s=!1,o=()=>{this.disposed||s||(s=!0,tc(r,"maptileload"))};if("baidu"===e.getProvider()){let e=i.getNative();e.addEventListener("firsttileloaded",o),this.cleanupTileLoad=()=>e.removeEventListener("firsttileloaded",o)}let l=()=>{this.disposed||this.ready||(this.ready=!0,tc(r,"mapload"),"amap"===e.getProvider()&&o(),this.update(!0))};i.on("complete",l),i.on("click",e=>{e.lnglat&&tc(r,"clickmap",{point:tu(e.lnglat)})}),i.on("error",e=>tp(r,e)),i.on("warning",e=>{tp(r,Error(e.reason??e.feature??"Web Map 能力降级"))});let d=(e,t,n)=>{if(!i.isReady())return;let a=t.context,s=(null==a?void 0:a.bounds)??i.getBounds();tc(r,"regionchange",{type:(null==a?void 0:a.phase)??e,...n?{causedBy:n}:{},center:tu((null==a?void 0:a.center)??i.getCenter()),scale:(null==a?void 0:a.zoom)??i.getZoom(),rotate:(null==a?void 0:a.rotation)??i.getRotation(),region:{southwest:tu(s.getSouthWest()),northeast:tu(s.getNorthEast())}})};i.on("movestart",e=>d("begin",e,"drag")),i.on("moveend",e=>d("end",e,"drag")),i.on("zoomstart",e=>d("begin",e,"scale")),i.on("zoomend",e=>d("end",e,"scale")),"baidu"!==e.getProvider()&&(i.on("rotatestart",e=>d("begin",e)),i.on("rotateend",e=>d("end",e))),i.isReady()&&l()}catch(e){var i,s,o;null==(i=this.cleanupTileLoad)||i.call(this),null==(s=this.overlays)||s.destroy(),null==(o=this.map)||o.destroy(),this.map=void 0,t.remove(),tp(r,e)}}update(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.ready||!this.map||this.disposed)return;let n=this.element,a=this.map,i=th(n),s=JSON.stringify({center:ts(n,"center",i),scale:n.getAttribute("scale"),scales:ts(n,"scale-range",i),rotate:n.getAttribute("rotate"),showScale:n.getAttribute("enable-scale-controls"),enableScale:n.getAttribute("enable-scale"),enableDrag:n.getAttribute("enable-drag"),enableRotate:n.getAttribute("enable-rotate"),nativeInteraction:n.getAttribute("native-interaction-enabled")});if(r||s!==this.lastAttributes){this.lastAttributes=s;try{let e=ts(n,"scale-range",i);e&&a.setZooms(e);let t=ts(n,"center",i);t?a.setZoomAndCenter(to(n,"scale",16),td(t)):a.setZoom(to(n,"scale",16)),a.setRotation(to(n,"rotate",0)),a.setShowScale(tl(n,"enable-scale-controls",!1)),a.setNativeInteractionEnabled(tl(n,"native-interaction-enabled",!0)),a.setStatus({zoomEnable:tl(n,"enable-scale",!0),dragEnable:tl(n,"enable-drag",!0),rotateEnable:tl(n,"enable-rotate",!1)})}catch(e){tp(n,e)}}let o=n.getAttribute("map-style")||"normal-light";if(o!==this.lastStyle){this.lastStyle=o;try{a.setMapStyle((null==(e=this.namespace)?void 0:e.getProvider())==="baidu"?{styleId:o}:o)}catch(e){tp(n,e)}}tl(n,"enable-tilt",!1)&&this.warn("地图倾斜");let l=n.getAttribute("logo-position")||"bottom-left";if(l!==this.lastLogoPosition){this.lastLogoPosition=l;try{a.setLogoPosition(l)}catch(e){tp(n,e)}}let d={polyline:ts(n,"polyline",i),polygons:ts(n,"polygons",i),circles:ts(n,"circles",i),arcs:ts(n,"arcs",i),routeLabel:ts(n,"route-label",i)},u=JSON.stringify(d);(r||u!==this.lastOverlays)&&(this.lastOverlays=u,null==(t=this.overlays)||t.sync(d)),this.updateMarkers()}updateMarkers(){let e=this.map,t=this.namespace;if((null==e?void 0:e.isReady())&&t&&!this.syncingMarkers){this.syncingMarkers=!0;try{let r=new Set([...this.element.querySelectorAll("map-marker")].filter(e=>e.closest("map")===this.element));for(let[e,t]of this.markers)r.has(e)&&t.connected||(r.delete(e),t.destroy(),this.markers.delete(e),ti.delete(e));for(let n of r){let r=tm(n);tl(n,"enable-collide-with-poi",!1)&&this.warn("marker POI 碰撞避让");let a=ts(n,"container-position",r),i=tl(n,"enable-drag",!1),s=!a&&"amap"===t.getProvider();i&&!s&&this.warn(a?"固定屏幕位置的 marker 拖动":"百度自定义内容 marker 拖动");let o=tl(n,"enable-click",!0);i&&!o&&this.warn("关闭点击时的 marker 拖动");let l=this.markers.get(n);l||(l=new e8(n,t,e,e=>tp(this.element,e),()=>tc(n,"clickmarker")),this.markers.set(n,l),ti.set(n,this)),l.sync({position:ts(n,"position",r),containerPosition:a,anchor:ts(n,"anchor",r)??[.5,1],rotation:to(n,"rotation",0),alpha:to(n,"alpha",1),clickable:o,draggable:i&&s&&o,animate:ts(n,"animate",r)})}}finally{this.syncingMarkers=!1}}}getMap(){var e;if(!(null==(e=this.map)?void 0:e.isReady()))throw Error("Web Map 尚未加载完成");return this.map}installMethods(){Object.assign(this.element,{setCenter:e=>{let{center:t,animated:r,duration:n}=e;return this.getMap().setCenter(td(t),!1===r,n)},getCenter:()=>tu(this.getMap().getCenter()),setScale:e=>{let{scale:t,animated:r,duration:n}=e;return this.getMap().setZoom(t,!1===r,n)},getScale:()=>({scale:this.getMap().getZoom()}),getBound:()=>{let e=this.getMap().getBounds();return{southwest:tu(e.getSouthWest()),northeast:tu(e.getNorthEast())}},setBound:e=>{let{southwest:t,northeast:r,animated:n,duration:a}=e;return this.getMap().setBounds([t.longitude,t.latitude,r.longitude,r.latitude],!1===n,void 0,a)},fitPoints:e=>{let{points:t,padding:r=[0,0,0,0],animated:n,duration:a}=e;return this.getMap().setFitView(t.map(td),!1===n,[r[2]??0,r[3]??0,r[0]??0,r[1]??0],void 0,a)},setAnchor:e=>{let{position:t}=e;return this.getMap().setAnchor([t.x,t.y])},latLngToPx:e=>{let{latLng:t}=e,r=this.getMap().lngLatToContainer(td(t));return{x:r.x,y:r.y}},pxToLatLng:e=>{let{x:t,y:r}=e;return{latLng:tu(this.getMap().containerToLngLat([t,r]))}}})}dispose(){var e,t,r,n,a;if(!this.disposed){for(let[r,n]of(this.disposed=!0,null==(e=this.resize)||e.disconnect(),cancelAnimationFrame(this.sizeFrame),null==(t=this.cleanupTileLoad)||t.call(this),this.markers))ti.delete(r),n.destroy();this.markers.clear(),null==(r=this.overlays)||r.destroy(),null==(n=this.map)||n.destroy(),null==(a=this.surface)||a.remove(),ta.delete(this.element)}}}class tv{element;static observedAttributes=[];constructor(e){this.element=e}forwardLinkEvent=e=>{this.element.dispatchEvent(new CustomEvent("link",{detail:e.detail,bubbles:!0,composed:!0}))};connectedCallback(){this.element.addEventListener("bindlink",this.forwardLinkEvent);let e=this.element.markdownStyle??{};this.element.markdownStyle={...e,link:{...e.link,textDecoration:"none"},orderedList:{...e.orderedList,paddingLeft:0},unorderedList:{...e.unorderedList,paddingLeft:0}}}}function ty(e){var t;null==(t=e.registerPlugin)||t.call(e,tv)}let t_="x-video-engine",tb=globalThis.HTMLElement??class{};if("object"!=typeof customElements||customElements.get(eV)||customElements.define(eV,class e extends eQ{static observedAttributes=["src"];#e=null;#t=null;#r=!1;messageOrigin;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#n(),this.#a()}disconnectedCallback(){var e;this.#r=!1,this.#i(),null==(e=this.#e)||e.remove(),this.#e=null,window.removeEventListener("message",this.#s)}attributeChangedCallback(e){"src"===e&&this.#r&&this.#a()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#a(!0)}postMessage(e){let t=s(e)?e.data:void 0;this.#o({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=s(e)&&"string"==typeof e.func?e.func:"";if(t)try{if(this.messageOrigin){var r,n;null==(n=this.#e)||null==(r=n.contentWindow)||r.postMessage({type:"__doubao_web_view_eval__",code:t},this.messageOrigin);return}let e=this.#l();null==e||e.eval(t)}catch{}}onGoBack(){return{consumed:!1}}#n(){if(this.#e)return this.#e;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("iframe");return t.style.cssText="display:block;width:100%;height:100%;border:none;",t.addEventListener("load",this.#d),t.addEventListener("error",this.#u),e.replaceChildren(t),this.#e=t,window.addEventListener("message",this.#s),t}#a(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#n(),r=this.getAttribute("src");if(!r)return;let n=eK(r);this.messageOrigin="window"===n.messageTransport?new URL(n.url,document.baseURI).origin:void 0,(e||t.getAttribute("src")!==n.url)&&(this.#i(),t.toggleAttribute("credentialless",!0===n.credentialless),t.src=n.url)}#i(){var e;null==(e=this.#t)||e.close(),this.#t=null}#l(){try{var e;let t=(null==(e=this.#e)?void 0:e.contentWindow)??null;return null==t||t.document,t}catch{return null}}#d=()=>{this.messageOrigin||(this.#c(),this.#p(),this.#h()),this.#m("load",{url:this.getAttribute("src")??""})};#u=()=>{this.#m("error",{errorMsg:`Failed to load ${this.getAttribute("src")??""}`,errorCode:-1})};#s=e=>{if(!this.#e||e.source!==this.#e.contentWindow||this.messageOrigin&&e.origin!==this.messageOrigin||e.data===eG)return;let t=eX(e.data);this.#g(t)||this.#f(eZ(e.data))};#c(){var e;this.#i();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==eG&&this.#g(eX(e.data))},this.#t=r.port1,t.postMessage("__channel_init__","*",[r.port2])}#p(){let e=this.#l();e&&!e.AppletBridgeModule&&(e.AppletBridgeModule={postMessage:e=>(this.#g(eX(e)),Promise.resolve({})),postMessageSync:e=>{let t=eX(e);return f(t)?w(t,"Sync AppletBridgeModule APIs are not supported in Doubao Web SDK web-view"):void 0}})}#h(){let e=this.#l();e&&this.#f(JSON.stringify({type:"__doubao_web_view_set_title__",title:e.document.title||""}))}#g(e){if(s(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!f(e))return!1;if("doubao.postMessage"===e.name){let t=s(e.params)?e.params.data:void 0;return this.#f(eZ(t)),this.#o(b(e,{})),!0}return this.#v(e),!0}async #v(e){let t=function(e){let t=e;for(;t;){if(t instanceof Element){let e=eJ.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#o(w(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#o(r??w(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#o(e){var t,r,n;let a=JSON.stringify(e);if(this.messageOrigin){null==(n=this.#e)||null==(r=n.contentWindow)||r.postMessage({type:"__doubao_web_view_message__",payload:a},this.messageOrigin);return}if(this.#t)return void this.#t.postMessage(a);let i=this.#l();null==i||null==(t=i.onWebViewMessage)||t.call(i,a)}#f(e){this.#m("message",{msg:e,data:e})}#m(e,t){for(let r of[e,`bind${e}`])this.dispatchEvent(new CustomEvent(r,{bubbles:!0,composed:!0,detail:t}))}}),"object"==typeof customElements&&!a){let e=customElements.get("x-markdown");e?(ty(e),a=Promise.resolve()):a=customElements.whenDefined("x-markdown").then(e=>{ty(e)})}if("object"!=typeof customElements||customElements.get(t_)||customElements.define(t_,class e extends tb{static observedAttributes=["play-url","video-model","vid","auto-prepare","initial-time","objectfit","muted","loop","volume","speed"];video=null;prepared=!1;firstFrame=!1;stopped=!0;playbackState=-1;playRequest=0;connectedCallback(){if(this.video)return;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("style");t.textContent=":host{display:block;width:100%;height:100%}video{display:block;width:100%;height:100%}";let r=document.createElement("video");this.video=r,r.playsInline=!0,e.replaceChildren(t,r);let n=(e,t)=>r.addEventListener(e,e=>{e.stopPropagation(),this.video===r&&this.isConnected&&t()});n("loadedmetadata",()=>{r.currentTime=this.numberAttribute("initial-time",0)/1e3}),n("canplay",()=>this.notifyPrepared()),n("loadeddata",()=>{this.firstFrame||(this.firstFrame=!0,this.emit("firstframe"))}),n("playing",()=>{this.stopped=!1,this.setPlaybackState(1)}),n("pause",()=>this.setPlaybackState(2*!this.stopped)),n("seeked",()=>this.emit("seek")),n("timeupdate",()=>this.emit("timeupdate",{current:1e3*r.currentTime,total:Number.isFinite(r.duration)?1e3*r.duration:0})),n("ended",()=>{this.stopped=!0,this.setPlaybackState(0),this.emit("completion")}),n("error",()=>{var e,t;return this.reportError((null==(e=r.error)?void 0:e.message)||"Video resource could not be played",null==(t=r.error)?void 0:t.code)}),document.addEventListener("visibilitychange",this.handleVisibility),this.syncAttributes(),this.syncSource()}disconnectedCallback(){var e;let t=this.video;this.video=null,this.playRequest++,document.removeEventListener("visibilitychange",this.handleVisibility),t&&(t.pause(),t.removeAttribute("src"),t.load()),null==(e=this.shadowRoot)||e.replaceChildren()}attributeChangedCallback(e,t,r){this.video&&t!==r&&(["play-url","video-model","vid"].includes(e)?this.syncSource():(this.syncAttributes(),"auto-prepare"!==e||this.booleanAttribute("auto-prepare",!0)||(this.video.preload="none")))}booleanAttribute(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getAttribute(e);return null===r?t:"false"!==r&&"0"!==r}numberAttribute(e,t){let r=this.getAttribute(e),n=null===r||""===r.trim()?0/0:Number(r);return Number.isFinite(n)&&n>=0?n:t}syncAttributes(){let e=this.video;e.muted=this.booleanAttribute("muted"),e.loop=this.booleanAttribute("loop"),e.volume=Math.min(1,this.numberAttribute("volume",1));try{e.playbackRate=this.numberAttribute("speed",1)||1,e.defaultPlaybackRate=e.playbackRate}catch(e){this.reportError(String(e))}let t=this.getAttribute("objectfit")??"contain";e.style.objectFit=["contain","cover","fill"].includes(t)?t:"contain",this.booleanAttribute("auto-prepare",!0)&&(e.preload="auto",e.controls=!0)}syncSource(){let e=this.video,t=this.getAttribute("play-url")||"";t&&e.getAttribute("src")===t||(this.playRequest++,this.prepared=this.firstFrame=!1,this.stopped=!0,this.playbackState=-1,e.pause(),e.preload=this.booleanAttribute("auto-prepare",!0)?"auto":"none",e.controls="auto"===e.preload,t?e.src=t:e.removeAttribute("src"),e.load(),queueMicrotask(()=>{this.isConnected&&this.video===e&&(this.getAttribute("play-url")||"")===t&&(t?this.emit("redirect"):(this.getAttribute("video-model")||this.getAttribute("vid"))&&this.reportError("Web VideoEngine requires play-url; video-model and vid are not supported"))}))}notifyPrepared(){var e;this.prepared||(null==(e=this.video)?void 0:e.preload)!=="auto"||(this.prepared=!0,this.emit("canplay"))}emit(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:"error"!==e}))}setPlaybackState(e){this.playbackState!==e&&(this.playbackState=e,this.emit("playbackstatechanged",{playbackState:e}))}reportError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;this.emit("error",{errorCode:t,errorMsg:e})}getMedia(){var e;if(!(null==(e=this.video)?void 0:e.getAttribute("src")))throw Error("Web VideoEngine requires play-url");return this.video}handleVisibility=()=>{var e;document.hidden&&this.booleanAttribute("pause-on-hide")&&(null==(e=this.video)?void 0:e.getAttribute("src"))&&this.pause()};prepare(){let e=this.getMedia();e.preload="auto",e.controls=!0,this.prepared=!1,e.readyState>=3?queueMicrotask(()=>{this.video===e&&this.notifyPrepared()}):e.load()}play(){let e=this.getMedia();this.stopped=!1;let t=++this.playRequest;e.play().catch(r=>{this.video===e&&t===this.playRequest&&this.reportError(String(r))})}pause(){let e=this.getMedia();this.playRequest++,this.stopped=!1,e.pause(),this.setPlaybackState(2)}stop(){let e=this.getMedia();this.playRequest++,this.stopped=!0,e.pause(),e.currentTime=0,this.setPlaybackState(0)}seek(e){if(!e||!Number.isFinite(e.position)||e.position<0)throw Error("seek.position must be a non-negative number in milliseconds");let t=this.getMedia(),r=Math.min(e.position/1e3,Number.isFinite(t.duration)?t.duration:1/0);e.play||this.pause(),t.currentTime===r?queueMicrotask(()=>{this.video===t&&this.emit("seek")}):t.currentTime=r,e.play&&this.play()}getDuration(){let e=this.getMedia().duration;if(!Number.isFinite(e))throw Error("Video duration is not available yet");return{duration:1e3*e}}}),"object"==typeof customElements)for(let e of["x-image","filter-image"]){if(e2.has(e))continue;e2.add(e);let t=e=>{if(!(eY in e.prototype)){var t;null==(t=e.registerPlugin)||t.call(e,e1)}},r=customElements.get(e);r?t(r):customElements.whenDefined(e).then(t)}if("object"==typeof document&&"object"==typeof customElements){let e=document.createElement("map").constructor.prototype;for(let t of["center","scale-range","polyline","polygons","circles","arcs","route-label","extra-params"])t in e||Object.defineProperty(e,t,{configurable:!0,get(){return th(this)[t]},set(e){var r;let n=tr.get(this)??{};n[t]=e,tr.set(this,n),null==(r=ta.get(this))||r.update()}});!function(){if(customElements.get("map-marker"))return;class e extends HTMLElement{static observedAttributes=["position","anchor","alpha","rotation","enable-click","enable-drag","animate","container-position"];connectedCallback(){queueMicrotask(()=>{var e;return null==(e=tg(this))?void 0:e.updateMarkers()})}attributeChangedCallback(){var e;null==(e=tg(this))||e.updateMarkers()}refreshMarker(){var e;null==(e=tg(this))||e.updateMarkers()}}for(let t of["position","anchor","animate","container-position"])Object.defineProperty(e.prototype,t,{configurable:!0,get(){return tm(this)[t]},set(e){var r;let n=tn.get(this)??{};n[t]=e,tn.set(this,n),null==(r=tg(this))||r.updateMarkers()}});customElements.define("map-marker",e)}()}function tw(e,t){"function"==typeof(null==e?void 0:e.sendGlobalEvent)&&e.sendGlobalEvent("__APPLET_BRIDGE__",[t])}class tS{container;className;options;runtimeContext;bridge=null;caller;cleanupWidgetTapCapture=null;cleanupWebMapHost=null;view=null;constructor(e,t={environment:"direct"}){let r=e.container;if(!r)throw Error("Container requires a container element");this.container=r,this.className=e.className??"doubao-web-container-view",this.options=e,this.runtimeContext=t}get element(){return this.view}prepare(){this.clear()}render(e){var t,r,n,a,i,s,o,l,d;let u,c,p,h,m,g,f,y,_,b,w,S,x,I,k,C,E;this.clear();let N=document.createElement("lynx-view"),M="sandbox"===this.runtimeContext.environment?this.runtimeContext.resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(n=this.options.runtime)||null==(r=n.packageInfo)?void 0:r.resourceRoot);M&&(N.resolveResource=e=>{let t=e.startsWith("/base/")?e.slice(1):e;return t?new URL(t,M).href:t}),N.injectStyleRules=['[doubao-component="popup"] > .popup-container { top: 0; left: 0; z-index: 1000; }'];let T=eI(e),R=ek(T);N.className=this.className,e.groupId&&N.setAttribute("lynx-group-id",e.groupId),N.dataset.containerType=T,N.dataset.webSizing=R,N.style.display="APP"===T||"TOOL"===T?"none":"block",N.style.width="100%",N.style.height="content"===R?"auto":"100%","content"===R&&N.setAttribute("height","auto"),N.url=ex(e),N.initData=e.initData??{};let A={...V(),...e.globalProps??{}};this.bridge=e.bridge??(null==(a=this.options.runtime)?void 0:a.bridge)??new e_,this.caller=e.bridgeCaller??this.bridge.register(e=>tw(N,e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===T);let P=this.bridge,j=this.caller,L="sandbox"===this.runtimeContext.environment?this.runtimeContext.syncBridgeData:P.createSyncBridgeData(j,A,this.options.fileSystemNamespace);i=this.runtimeContext.environment,u=new URL("./__doubao_web_sdk_native_modules/",(null==(s=globalThis.document)?void 0:s.baseURI)??(null==(o=globalThis.location)?void 0:o.href)??"http://localhost/").href,c=ew(new URL("applet-bridge-module.js",u)),p=ew(new URL("applet-js-module.js",u)),g={AppletBridgeModule:((m=new URLSearchParams((h=new URL(c)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...L,fileSystemSnapshot:el()})),h.hash=m.toString(),h.href),AppletJSModule:p},"direct"===i&&(g.LynxConsoleModule=ew(new URL("console-module.js",u)),"APP"===T&&(g.LynxDevToolSetModule=p)),N.nativeModulesMap=g,(0,ez.B)(N),N.globalProps={...A,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:L};let D={containerType:T,element:N,globalProps:A,fileSystemNamespace:L.fileSystemNamespace,environment:this.runtimeContext.environment};return N.onNativeModulesCall=(e,t,r)=>P.dispatch(j,e,t,r,D),l=async e=>{let t=await P.dispatch(j,"postMessage",e,"AppletBridgeModule",D);return v(t)?t:void 0},eJ.set(N,l),N.transformVW=!0,N.transformVH="content"!==R,N.transformREM=!0,N.addEventListener("error",e=>{var t,r;let n;null==(t=(r=this.options).onError)||t.call(r,(null==(n=e.detail)?void 0:n.error)instanceof Error?n.error:Error(String((null==n?void 0:n.error)??n??"Unknown Container runtime error")),e)}),"WIDGET"===T&&this.options.captureWidgetTap&&(this.cleanupWidgetTapCapture=(d=this.options.onWidgetInteraction,f=0,y=e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();var t={sequence:f+=1,type:"tap"};try{Promise.resolve(null==d?void 0:d(t)).catch(()=>void 0)}catch{}},N.addEventListener("click",y,!0),()=>N.removeEventListener("click",y,!0))),this.view=N,this.container.replaceChildren(N),this.cleanupWebMapHost=(b=new Map,w=new Set,S=[],x=0,I=!1,k=e=>{for(let t of e.querySelectorAll("*"))"map"!==t.localName||ta.has(t)||w.add(new tf(t)),t.shadowRoot&&C(t.shadowRoot);for(let e of w)e.element.isConnected||(e.dispose(),w.delete(e))},C=e=>{if(b.has(e)||I)return;let t=new MutationObserver(t=>{if(!(t.some(e=>{let t=e.target;return t instanceof Element&&t.closest("[data-doubao-map-surface]")})&&t.every(e=>e.target instanceof Element&&e.target.closest("[data-doubao-map-surface]"))))for(let n of(k(e),t)){let e=n.target,t=e instanceof Element?e.closest("map"):null;if(t){var r;null==(r=ta.get(t))||r.update()}}});t.observe(e,{childList:!0,subtree:!0,attributes:!0}),b.set(e,t),k(e)},(E=()=>{if(I)return;let e=N.shadowRoot??N;if(C(e),N.shadowRoot&&_!==e)for(let t of(_=e,[0,16,100,500,2e3,1e4]))S.push(setTimeout(()=>{I||k(e)},t));else N.shadowRoot||(x=requestAnimationFrame(E))})(),()=>{for(let e of(I=!0,cancelAnimationFrame(x),S))clearTimeout(e);for(let e of b.values())e.disconnect();for(let e of w)e.dispose()}),N}clear(){var e,t,r,n;null==(e=this.cleanupWebMapHost)||e.call(this),this.cleanupWebMapHost=null,null==(t=this.cleanupWidgetTapCapture)||t.call(this),this.cleanupWidgetTapCapture=null,this.caller&&(null==(n=this.bridge)||n.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(r=this.view)||r.remove(),this.view=null,this.container.replaceChildren()}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=this.view,tw(t,{type:"event",name:e,params:r,timestamp:Date.now()})}sendBridgeMessage(e){tw(this.view,e)}sendGlobalEvent(e,t){var r,n;null==(n=this.view)||null==(r=n.sendGlobalEvent)||r.call(n,e,t)}reload(){var e,t;null==(t=this.view)||null==(e=t.reload)||e.call(t)}}let tx=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
19
|
+
}`};dispose(){this.attributes.disconnect(),this.stopRendering()}}let e2=new Set;var e3=r(37474);let e4=new WeakMap;function e5(e,t,r){let n=new Map;for(let a of t){let t=Reflect.get(e,a);n.set(a,Object.getOwnPropertyDescriptor(e,a)),Object.defineProperty(e,a,{configurable:!0,writable:!0,value(){for(var e=arguments.length,n=Array(e),a=0;a<e;a++)n[a]=arguments[a];return r(),Reflect.apply(t,this,n)}})}return()=>{for(let[t,r]of n)r?Object.defineProperty(e,t,r):Reflect.deleteProperty(e,t)}}class e6{element;placeholder=document.createComment("map-marker");parent;cleanupElement;constructor(e){this.element=e;let t=e.parentNode;if(!t)throw Error("Web Map Marker requires a component parent");this.parent=t;let r=e4.get(t);if(!r){let e=new Set;r={portals:e,cleanup:e5(t,["appendChild","insertBefore","removeChild","replaceChild","append","prepend","replaceChildren"],()=>{for(let t of e)t.restore()})},e4.set(t,r)}r.portals.add(this),this.cleanupElement=e5(e,["remove","replaceWith","before","after"],()=>{for(let e of r.portals)e.restore()})}get connected(){return this.element.parentNode===this.parent?this.element.isConnected:this.placeholder.isConnected}mount(e){if(this.element.parentNode!==e){if(this.element.parentNode!==this.parent)throw Error("Web Map Marker component parent changed");Node.prototype.insertBefore.call(this.parent,this.placeholder,this.element),e.appendChild(this.element)}}restore(){this.placeholder.parentNode===this.parent&&Node.prototype.replaceChild.call(this.parent,this.element,this.placeholder)}destroy(){this.restore(),this.cleanupElement();let e=e4.get(this.parent);null==e||e.portals.delete(this),(null==e?void 0:e.portals.size)===0&&(e.cleanup(),e4.delete(this.parent))}}class e8{element;namespace;map;onError;onClick;content=document.createElement("div");portal;originalStyles=new Map;styleObserver=new MutationObserver(()=>this.syncZIndex());marker;defaultZIndex;positionKey;optionsKey;waitingForPosition=!1;syncing=!1;disposed=!1;constructor(e,t,r,n,a){this.element=e,this.namespace=t,this.map=r,this.onError=n,this.onClick=a,this.portal=new e6(e),this.content.style.cssText="width:0;height:0;overflow:visible;",this.styleObserver.observe(e,{attributes:!0,attributeFilter:["style","class"]})}get connected(){return this.portal.connected}sync(e){if(!this.disposed&&!this.syncing){this.syncing=!0;try{if(!e.position&&!e.containerPosition){var t;this.portal.restore(),null==(t=this.marker)||t.destroy(),this.marker=void 0,this.optionsKey=void 0,this.positionKey=void 0,this.waitingForPosition=!0,this.style("visibility","hidden");return}this.waitingForPosition&&(this.style("visibility",this.originalStyles.get("visibility")??""),this.waitingForPosition=!1),this.style("position","relative"),"inline"===getComputedStyle(this.element).display&&this.style("display","inline-block"),this.element.style.width||this.style("width","max-content"),this.style("transform",`translate(${-100*e.anchor[0]}%, ${-100*e.anchor[1]}%)`);let r="amap"===this.namespace.getProvider(),n={content:this.content,containerPosition:e.containerPosition?[e.containerPosition.x,e.containerPosition.y]:null,anchor:r?"top-left":0,angle:e.rotation,opacity:e.alpha,clickable:e.clickable,draggable:e.draggable,bubble:!e.clickable,animation:e.animate??(r?{scale:{from:1,to:1,duration:0}}:null)},a=JSON.stringify(e.position);this.marker&&a===this.positionKey||(n.position=e.position&&[e.position.longitude,e.position.latitude]),this.portal.mount(this.content);let i=JSON.stringify(e);if(this.marker&&this.optionsKey===i)return void this.syncZIndex();this.optionsKey=i,this.marker?this.marker.setOptions(n):(this.marker=new this.namespace.Marker(n),this.defaultZIndex=this.marker.getzIndex(),this.marker.on("click",this.onClick)),this.syncZIndex(),this.marker.getMap()!==this.map&&this.marker.setMap(this.map),this.positionKey=a}catch(e){this.onError(e)}finally{this.syncing=!1}}}syncZIndex(){if(this.marker&&!this.disposed)try{let e=Number.parseInt(getComputedStyle(this.element).zIndex,10),t=Number.isFinite(e)?e:this.defaultZIndex;void 0!==t&&t!==this.marker.getzIndex()&&this.marker.setzIndex(t)}catch(e){this.onError(e)}}style(e,t){this.originalStyles.has(e)||this.originalStyles.set(e,this.element.style.getPropertyValue(e)),this.element.style.getPropertyValue(e)!==t&&this.element.style.setProperty(e,t)}destroy(){var e;if(!this.disposed)for(let[t,r]of(this.disposed=!0,this.styleObserver.disconnect(),this.portal.destroy(),null==(e=this.marker)||e.destroy(),this.originalStyles))this.element.style.setProperty(t,r)}}let e7=e=>{let{longitude:t,latitude:r}=e;return[t,r]};function e9(e,t,r,n,a){let i=new Set(t.map(e=>{let{id:t}=e;return t}));for(let[t,r]of e)i.has(t)||(r.destroy(),e.delete(t));for(let i of t)try{let t=r(i),a=e.get(i.id);if(a){let{id:e,...r}=t;a.setOptions(r)}else e.set(i.id,n(t,i))}catch(e){a(e)}}class te{namespace;map;onError;onPolylineClick;polylines=new Map;polygons=new Map;circles=new Map;arcs=new Map;routeLabels=new Map;warnings=new Set;constructor(e,t,r,n){this.namespace=e,this.map=t,this.onError=r,this.onPolylineClick=n}warn(e){this.warnings.has(e)||(this.warnings.add(e),this.onError(Error(`Web Map 暂不支持 ${e}`)))}add(e){e.on("warning",e=>{this.onError(e.error??Error(e.reason??e.feature??"Web Map 覆盖物降级"))});try{return this.map.add(e),e}catch(t){throw e.destroy(),t}}sync(e){var t;let r=function(e){let t=new Map,r=new Set;for(let a of e){var n;if(!a.id.startsWith("__doubao_polyline_arrow__:"))continue;let i=null==(n=a.edgeTextureAssets)?void 0:n.find(e=>{let{id:t}=e;return"__doubao_polyline_arrow_texture__"===t});if(i)try{let n=decodeURIComponent(a.id.slice(26));e.some(e=>e.id===n)&&(t.set(n,{iconPath:i.url}),r.add(a))}catch{}}return e.filter(e=>!r.has(e)).map(e=>({...e,arrow:t.get(e.id)??e.arrow}))}(e.polyline??[]),n=this.namespace.supports("Polyline.edgeTexture").supported,a=this.namespace.supports("RouteLabel").supported;!n&&r.some(e=>{var t,r;return(null==(t=e.edgeTexture)?void 0:t.length)||(null==(r=e.edgeTextureAssets)?void 0:r.length)})&&this.warn("当前图商的 polyline 纹理"),!a&&(null==(t=e.routeLabel)?void 0:t.length)&&this.warn("当前图商的 routeLabel"),r.some(e=>e.collideDetection)&&this.warn("polyline POI 碰撞避让"),e9(this.polylines,r,e=>{var t;return{id:e.id,path:e.points.map(e7),strokeColors:e.edgeColor??[],arrow:e.arrow??null,edgeTexture:n?e.edgeTexture??[]:[],edgeTextureAssets:n?e.edgeTextureAssets??[]:[],strokeColor:(null==(t=e.edgeColor)?void 0:t[0])??"#0066ff",strokeWeight:e.width??2,strokeStyle:e.dottedLine?"dashed":"solid",lineCap:"line_cap_round"===e.lineCapType?"round":"butt",lineJoin:"line_join_round"===e.lineJoinType?"round":"line_join_miter"===e.lineJoinType?"miter":"bevel",zIndex:e.zIndex??0}},(e,t)=>{let r=new this.namespace.Polyline(e);return r.on("click",()=>this.onPolylineClick(t.id)),this.add(r)},this.onError),e9(this.polygons,e.polygons??[],e=>({id:e.id,path:e.points.map(e7),fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,strokeStyle:e.dottedLine?"dashed":"solid",zIndex:e.zIndex}),e=>{let t=new this.namespace.Polygon(e);return this.add(t)},this.onError),e9(this.circles,e.circles??[],e=>({id:e.id,center:e7(e.center),radius:e.radius,fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,zIndex:e.zIndex}),e=>{let t=new this.namespace.Circle(e);return this.add(t)},this.onError),e9(this.arcs,e.arcs??[],e=>({id:e.id,path:[e7(e.start),e7(e.mid??e.middle),e7(e.end)],strokeColor:e.color??"#0066ff",strokeWeight:e.width??2,zIndex:e.zIndex}),e=>{let t=new this.namespace.Arc(e);return this.add(t)},this.onError),e9(this.routeLabels,a?e.routeLabel??[]:[],e=>({id:e.id,path:e.points.map(e7),text:e.text,textColor:e.textColor??"#000000",fontSize:e.fontSize??12,fontWeight:e.fontWeight??"normal",borderColor:e.borderColor??"#cccccc",borderWidth:e.borderWidth??0,zIndex:e.zIndex??0}),e=>this.add(new this.namespace.RouteLabel(e)),this.onError)}destroy(){for(let e of[this.polylines,this.polygons,this.circles,this.arcs,this.routeLabels]){for(let t of e.values())t.destroy();e.clear()}}}let tt={baidu:{provider:"baidu",security:{baidu:{serviceHost:"https://api.doubao-dev.com/_BMapService/"}}},amap:{provider:"amap",key:{amap:"f57928bd7156da61d512795ec5c0c968"},security:{amap:{serviceHost:"https://api.doubao-dev.com/_AMapService"}}}},tr=new WeakMap,tn=new WeakMap,ta=new WeakMap,ti=new WeakMap;function ts(e,t,r){if(t in r)return r[t];let n=e.getAttribute(t);if(n)try{return JSON.parse(n)}catch{return}}function to(e,t,r){let n=Number(e.getAttribute(t));return Number.isFinite(n)&&e.hasAttribute(t)?n:r}function tl(e,t,r){let n=e.getAttribute(t);return null===n?r:"false"!==n&&"0"!==n}function td(e){let{longitude:t,latitude:r}=e;return[t,r]}function tu(e){return{longitude:e.lng,latitude:e.lat}}function tc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!1}))}function tp(e,t){let r=t instanceof Error?t:Error(String(t));console.error("[Doubao Map]",r.message),e.dispatchEvent(new CustomEvent("error",{detail:{error:r}}))}function th(e){return tr.get(e)??{}}function tm(e){return tn.get(e)??{}}function tg(e){let t=ti.get(e);if(t)return t;let r=e.closest("map");return r?ta.get(r):void 0}class tf{element;map;namespace;syncingMarkers=!1;overlays;markers=new Map;cleanupTileLoad;surface;resize;sizeFrame=0;loading=!1;initializationBlocked=!1;disposed=!1;ready=!1;lastAttributes="";lastOverlays="";lastStyle="";lastLogoPosition="";warnings=new Set;constructor(e){var t;if(this.element=e,ta.set(e,this),this.installMethods(),"inline"===getComputedStyle(e).display&&(e.style.display="block"),"static"===getComputedStyle(e).position&&(e.style.position="relative"),e.style.overflow="hidden",this.resize="function"==typeof ResizeObserver?new ResizeObserver(()=>this.initialize()):void 0,null==(t=this.resize)||t.observe(e),!this.resize){let e=()=>{this.disposed||this.map||this.loading||this.initializationBlocked||(this.initialize(),this.sizeFrame=requestAnimationFrame(e))};this.sizeFrame=requestAnimationFrame(e)}this.initialize()}warn(e){this.warnings.has(e)||(this.warnings.add(e),tp(this.element,Error(`Web Map 暂不支持 ${e}`)))}getMapConfig(){let e=ts(this.element,"extra-params",th(this.element));return tt[(null==e?void 0:e.useAliMap)===!0?"amap":"baidu"]}initialize(){var e;if(this.disposed||this.loading||this.initializationBlocked||this.map||this.element.clientWidth<=0||this.element.clientHeight<=0)return;let t=this.getMapConfig(),r=(null==(e=this.element.ownerDocument.location)?void 0:e.hostname)??"";if("baidu"===t.provider&&(eS(r)||"[::1]"===r||r.endsWith(".localhost"))){this.initializationBlocked=!0,tp(this.element,Error("当前豆包百度地图账号未授权本地域名,请使用获准域名的 sandbox 调试地图。"));return}this.loading=!0;let n=document.createElement("div");n.dataset.doubaoMapSurface="",n.style.cssText="position:absolute;inset:0;width:100%;height:100%;",this.element.prepend(n),this.surface=n,Promise.resolve().then(()=>e3.H3.load(t)).then(e=>{this.disposed||this.createMap(e,n)}).catch(e=>{this.disposed||tp(this.element,e),n.remove(),this.surface=void 0}).finally(()=>{this.loading=!1})}createMap(e,t){let r=this.element,n=ts(r,"center",th(r)),a=ts(r,"scale-range",th(r));try{let i=new e.Map(t,{center:n&&td(n),zoom:to(r,"scale",16),zooms:a??[3,20],rotation:to(r,"rotate",0),logoPosition:r.getAttribute("logo-position")||"bottom-left",eventContext:!0,enableNativeInteraction:tl(r,"native-interaction-enabled",!0),showScale:tl(r,"enable-scale-controls",!1),zoomEnable:tl(r,"enable-scale",!0),dragEnable:tl(r,"enable-drag",!0),rotateEnable:tl(r,"enable-rotate",!1)});this.map=i,this.namespace=e,this.overlays=new te(e,i,e=>tp(r,e),e=>tc(r,"clickpolyline",{id:e}));let s=!1,o=()=>{this.disposed||s||(s=!0,tc(r,"maptileload"))};if("baidu"===e.getProvider()){let e=i.getNative();e.addEventListener("firsttileloaded",o),this.cleanupTileLoad=()=>e.removeEventListener("firsttileloaded",o)}let l=()=>{this.disposed||this.ready||(this.ready=!0,tc(r,"mapload"),"amap"===e.getProvider()&&o(),this.update(!0))};i.on("complete",l),i.on("click",e=>{e.lnglat&&tc(r,"clickmap",{point:tu(e.lnglat)})}),i.on("error",e=>tp(r,e)),i.on("warning",e=>{tp(r,Error(e.reason??e.feature??"Web Map 能力降级"))});let d=(e,t,n)=>{if(!i.isReady())return;let a=t.context,s=(null==a?void 0:a.bounds)??i.getBounds();tc(r,"regionchange",{type:(null==a?void 0:a.phase)??e,...n?{causedBy:n}:{},center:tu((null==a?void 0:a.center)??i.getCenter()),scale:(null==a?void 0:a.zoom)??i.getZoom(),rotate:(null==a?void 0:a.rotation)??i.getRotation(),region:{southwest:tu(s.getSouthWest()),northeast:tu(s.getNorthEast())}})};i.on("movestart",e=>d("begin",e,"drag")),i.on("moveend",e=>d("end",e,"drag")),i.on("zoomstart",e=>d("begin",e,"scale")),i.on("zoomend",e=>d("end",e,"scale")),"baidu"!==e.getProvider()&&(i.on("rotatestart",e=>d("begin",e)),i.on("rotateend",e=>d("end",e))),i.isReady()&&l()}catch(e){var i,s,o;null==(i=this.cleanupTileLoad)||i.call(this),null==(s=this.overlays)||s.destroy(),null==(o=this.map)||o.destroy(),this.map=void 0,t.remove(),tp(r,e)}}update(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.ready||!this.map||this.disposed)return;let n=this.element,a=this.map,i=th(n),s=JSON.stringify({center:ts(n,"center",i),scale:n.getAttribute("scale"),scales:ts(n,"scale-range",i),rotate:n.getAttribute("rotate"),showScale:n.getAttribute("enable-scale-controls"),enableScale:n.getAttribute("enable-scale"),enableDrag:n.getAttribute("enable-drag"),enableRotate:n.getAttribute("enable-rotate"),nativeInteraction:n.getAttribute("native-interaction-enabled")});if(r||s!==this.lastAttributes){this.lastAttributes=s;try{let e=ts(n,"scale-range",i);e&&a.setZooms(e);let t=ts(n,"center",i);t?a.setZoomAndCenter(to(n,"scale",16),td(t)):a.setZoom(to(n,"scale",16)),a.setRotation(to(n,"rotate",0)),a.setShowScale(tl(n,"enable-scale-controls",!1)),a.setNativeInteractionEnabled(tl(n,"native-interaction-enabled",!0)),a.setStatus({zoomEnable:tl(n,"enable-scale",!0),dragEnable:tl(n,"enable-drag",!0),rotateEnable:tl(n,"enable-rotate",!1)})}catch(e){tp(n,e)}}let o=n.getAttribute("map-style")||"normal-light";if(o!==this.lastStyle){this.lastStyle=o;try{a.setMapStyle((null==(e=this.namespace)?void 0:e.getProvider())==="baidu"?{styleId:o}:o)}catch(e){tp(n,e)}}tl(n,"enable-tilt",!1)&&this.warn("地图倾斜");let l=n.getAttribute("logo-position")||"bottom-left";if(l!==this.lastLogoPosition){this.lastLogoPosition=l;try{a.setLogoPosition(l)}catch(e){tp(n,e)}}let d={polyline:ts(n,"polyline",i),polygons:ts(n,"polygons",i),circles:ts(n,"circles",i),arcs:ts(n,"arcs",i),routeLabel:ts(n,"route-label",i)},u=JSON.stringify(d);(r||u!==this.lastOverlays)&&(this.lastOverlays=u,null==(t=this.overlays)||t.sync(d)),this.updateMarkers()}updateMarkers(){let e=this.map,t=this.namespace;if((null==e?void 0:e.isReady())&&t&&!this.syncingMarkers){this.syncingMarkers=!0;try{let r=new Set([...this.element.querySelectorAll("map-marker")].filter(e=>e.closest("map")===this.element));for(let[e,t]of this.markers)r.has(e)&&t.connected||(r.delete(e),t.destroy(),this.markers.delete(e),ti.delete(e));for(let n of r){let r=tm(n);tl(n,"enable-collide-with-poi",!1)&&this.warn("marker POI 碰撞避让");let a=ts(n,"container-position",r),i=tl(n,"enable-drag",!1),s=!a&&"amap"===t.getProvider();i&&!s&&this.warn(a?"固定屏幕位置的 marker 拖动":"百度自定义内容 marker 拖动");let o=tl(n,"enable-click",!0);i&&!o&&this.warn("关闭点击时的 marker 拖动");let l=this.markers.get(n);l||(l=new e8(n,t,e,e=>tp(this.element,e),()=>tc(n,"clickmarker")),this.markers.set(n,l),ti.set(n,this)),l.sync({position:ts(n,"position",r),containerPosition:a,anchor:ts(n,"anchor",r)??[.5,1],rotation:to(n,"rotation",0),alpha:to(n,"alpha",1),clickable:o,draggable:i&&s&&o,animate:ts(n,"animate",r)})}}finally{this.syncingMarkers=!1}}}getMap(){var e;if(!(null==(e=this.map)?void 0:e.isReady()))throw Error("Web Map 尚未加载完成");return this.map}installMethods(){Object.assign(this.element,{setCenter:e=>{let{center:t,animated:r,duration:n}=e;return this.getMap().setCenter(td(t),!1===r,n)},getCenter:()=>tu(this.getMap().getCenter()),setScale:e=>{let{scale:t,animated:r,duration:n}=e;return this.getMap().setZoom(t,!1===r,n)},getScale:()=>({scale:this.getMap().getZoom()}),getBound:()=>{let e=this.getMap().getBounds();return{southwest:tu(e.getSouthWest()),northeast:tu(e.getNorthEast())}},setBound:e=>{let{southwest:t,northeast:r,animated:n,duration:a}=e;return this.getMap().setBounds([t.longitude,t.latitude,r.longitude,r.latitude],!1===n,void 0,a)},fitPoints:e=>{let{points:t,padding:r=[0,0,0,0],animated:n,duration:a}=e;return this.getMap().setFitView(t.map(td),!1===n,[r[2]??0,r[3]??0,r[0]??0,r[1]??0],void 0,a)},setAnchor:e=>{let{position:t}=e;return this.getMap().setAnchor([t.x,t.y])},latLngToPx:e=>{let{latLng:t}=e,r=this.getMap().lngLatToContainer(td(t));return{x:r.x,y:r.y}},pxToLatLng:e=>{let{x:t,y:r}=e;return{latLng:tu(this.getMap().containerToLngLat([t,r]))}}})}dispose(){var e,t,r,n,a;if(!this.disposed){for(let[r,n]of(this.disposed=!0,null==(e=this.resize)||e.disconnect(),cancelAnimationFrame(this.sizeFrame),null==(t=this.cleanupTileLoad)||t.call(this),this.markers))ti.delete(r),n.destroy();this.markers.clear(),null==(r=this.overlays)||r.destroy(),null==(n=this.map)||n.destroy(),null==(a=this.surface)||a.remove(),ta.delete(this.element)}}}class tv{element;static observedAttributes=[];constructor(e){this.element=e}forwardLinkEvent=e=>{this.element.dispatchEvent(new CustomEvent("link",{detail:e.detail,bubbles:!0,composed:!0}))};connectedCallback(){this.element.addEventListener("bindlink",this.forwardLinkEvent);let e=this.element.markdownStyle??{};this.element.markdownStyle={...e,link:{...e.link,textDecoration:"none"},orderedList:{...e.orderedList,paddingLeft:0},unorderedList:{...e.unorderedList,paddingLeft:0}}}}function ty(e){var t;null==(t=e.registerPlugin)||t.call(e,tv)}let t_="x-video-engine",tb=globalThis.HTMLElement??class{};if("object"!=typeof customElements||customElements.get(eV)||customElements.define(eV,class e extends eQ{static observedAttributes=["src"];#e=null;#t=null;#r=!1;messageOrigin;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#n(),this.#a()}disconnectedCallback(){var e;this.#r=!1,this.#i(),null==(e=this.#e)||e.remove(),this.#e=null,window.removeEventListener("message",this.#s)}attributeChangedCallback(e){"src"===e&&this.#r&&this.#a()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#a(!0)}postMessage(e){let t=s(e)?e.data:void 0;this.#o({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=s(e)&&"string"==typeof e.func?e.func:"";if(t)try{if(this.messageOrigin){var r,n;null==(n=this.#e)||null==(r=n.contentWindow)||r.postMessage({type:"__doubao_web_view_eval__",code:t},this.messageOrigin);return}let e=this.#l();null==e||e.eval(t)}catch{}}onGoBack(){return{consumed:!1}}#n(){if(this.#e)return this.#e;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("iframe");return t.style.cssText="display:block;width:100%;height:100%;border:none;",t.addEventListener("load",this.#d),t.addEventListener("error",this.#u),e.replaceChildren(t),this.#e=t,window.addEventListener("message",this.#s),t}#a(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#n(),r=this.getAttribute("src");if(!r)return;let n=eK(r);this.messageOrigin="window"===n.messageTransport?new URL(n.url,document.baseURI).origin:void 0,(e||t.getAttribute("src")!==n.url)&&(this.#i(),t.toggleAttribute("credentialless",!0===n.credentialless),t.src=n.url)}#i(){var e;null==(e=this.#t)||e.close(),this.#t=null}#l(){try{var e;let t=(null==(e=this.#e)?void 0:e.contentWindow)??null;return null==t||t.document,t}catch{return null}}#d=()=>{this.messageOrigin||(this.#c(),this.#p(),this.#h()),this.#m("load",{url:this.getAttribute("src")??""})};#u=()=>{this.#m("error",{errorMsg:`Failed to load ${this.getAttribute("src")??""}`,errorCode:-1})};#s=e=>{if(!this.#e||e.source!==this.#e.contentWindow||this.messageOrigin&&e.origin!==this.messageOrigin||e.data===eG)return;let t=eX(e.data);this.#g(t)||this.#f(eZ(e.data))};#c(){var e;this.#i();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==eG&&this.#g(eX(e.data))},this.#t=r.port1,t.postMessage("__channel_init__","*",[r.port2])}#p(){let e=this.#l();e&&!e.AppletBridgeModule&&(e.AppletBridgeModule={postMessage:e=>(this.#g(eX(e)),Promise.resolve({})),postMessageSync:e=>{let t=eX(e);return f(t)?w(t,"Sync AppletBridgeModule APIs are not supported in Doubao Web SDK web-view"):void 0}})}#h(){let e=this.#l();e&&this.#f(JSON.stringify({type:"__doubao_web_view_set_title__",title:e.document.title||""}))}#g(e){if(s(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!f(e))return!1;if("doubao.postMessage"===e.name){let t=s(e.params)?e.params.data:void 0;return this.#f(eZ(t)),this.#o(b(e,{})),!0}return this.#v(e),!0}async #v(e){let t=function(e){let t=e;for(;t;){if(t instanceof Element){let e=eJ.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#o(w(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#o(r??w(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#o(e){var t,r,n;let a=JSON.stringify(e);if(this.messageOrigin){null==(n=this.#e)||null==(r=n.contentWindow)||r.postMessage({type:"__doubao_web_view_message__",payload:a},this.messageOrigin);return}if(this.#t)return void this.#t.postMessage(a);let i=this.#l();null==i||null==(t=i.onWebViewMessage)||t.call(i,a)}#f(e){this.#m("message",{msg:e,data:e})}#m(e,t){for(let r of[e,`bind${e}`])this.dispatchEvent(new CustomEvent(r,{bubbles:!0,composed:!0,detail:t}))}}),"object"==typeof customElements&&!a){let e=customElements.get("x-markdown");e?(ty(e),a=Promise.resolve()):a=customElements.whenDefined("x-markdown").then(e=>{ty(e)})}if("object"!=typeof customElements||customElements.get(t_)||customElements.define(t_,class e extends tb{static observedAttributes=["play-url","video-model","vid","auto-prepare","initial-time","objectfit","muted","loop","volume","speed"];video=null;prepared=!1;firstFrame=!1;stopped=!0;playbackState=-1;playRequest=0;connectedCallback(){if(this.video)return;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("style");t.textContent=":host{display:block;width:100%;height:100%}video{display:block;width:100%;height:100%}";let r=document.createElement("video");this.video=r,r.playsInline=!0,e.replaceChildren(t,r);let n=(e,t)=>r.addEventListener(e,e=>{e.stopPropagation(),this.video===r&&this.isConnected&&t()});n("loadedmetadata",()=>{r.currentTime=this.numberAttribute("initial-time",0)/1e3}),n("canplay",()=>this.notifyPrepared()),n("loadeddata",()=>{this.firstFrame||(this.firstFrame=!0,this.emit("firstframe"))}),n("playing",()=>{this.stopped=!1,this.setPlaybackState(1)}),n("pause",()=>this.setPlaybackState(2*!this.stopped)),n("seeked",()=>this.emit("seek")),n("timeupdate",()=>this.emit("timeupdate",{current:1e3*r.currentTime,total:Number.isFinite(r.duration)?1e3*r.duration:0})),n("ended",()=>{this.stopped=!0,this.setPlaybackState(0),this.emit("completion")}),n("error",()=>{var e,t;return this.reportError((null==(e=r.error)?void 0:e.message)||"Video resource could not be played",null==(t=r.error)?void 0:t.code)}),document.addEventListener("visibilitychange",this.handleVisibility),this.syncAttributes(),this.syncSource()}disconnectedCallback(){var e;let t=this.video;this.video=null,this.playRequest++,document.removeEventListener("visibilitychange",this.handleVisibility),t&&(t.pause(),t.removeAttribute("src"),t.load()),null==(e=this.shadowRoot)||e.replaceChildren()}attributeChangedCallback(e,t,r){this.video&&t!==r&&(["play-url","video-model","vid"].includes(e)?this.syncSource():(this.syncAttributes(),"auto-prepare"!==e||this.booleanAttribute("auto-prepare",!0)||(this.video.preload="none")))}booleanAttribute(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getAttribute(e);return null===r?t:"false"!==r&&"0"!==r}numberAttribute(e,t){let r=this.getAttribute(e),n=null===r||""===r.trim()?0/0:Number(r);return Number.isFinite(n)&&n>=0?n:t}syncAttributes(){let e=this.video;e.muted=this.booleanAttribute("muted"),e.loop=this.booleanAttribute("loop"),e.volume=Math.min(1,this.numberAttribute("volume",1));try{e.playbackRate=this.numberAttribute("speed",1)||1,e.defaultPlaybackRate=e.playbackRate}catch(e){this.reportError(String(e))}let t=this.getAttribute("objectfit")??"contain";e.style.objectFit=["contain","cover","fill"].includes(t)?t:"contain",this.booleanAttribute("auto-prepare",!0)&&(e.preload="auto",e.controls=!0)}syncSource(){let e=this.video,t=this.getAttribute("play-url")||"";t&&e.getAttribute("src")===t||(this.playRequest++,this.prepared=this.firstFrame=!1,this.stopped=!0,this.playbackState=-1,e.pause(),e.preload=this.booleanAttribute("auto-prepare",!0)?"auto":"none",e.controls="auto"===e.preload,t?e.src=t:e.removeAttribute("src"),e.load(),queueMicrotask(()=>{this.isConnected&&this.video===e&&(this.getAttribute("play-url")||"")===t&&(t?this.emit("redirect"):(this.getAttribute("video-model")||this.getAttribute("vid"))&&this.reportError("Web VideoEngine requires play-url; video-model and vid are not supported"))}))}notifyPrepared(){var e;this.prepared||(null==(e=this.video)?void 0:e.preload)!=="auto"||(this.prepared=!0,this.emit("canplay"))}emit(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:"error"!==e}))}setPlaybackState(e){this.playbackState!==e&&(this.playbackState=e,this.emit("playbackstatechanged",{playbackState:e}))}reportError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;this.emit("error",{errorCode:t,errorMsg:e})}getMedia(){var e;if(!(null==(e=this.video)?void 0:e.getAttribute("src")))throw Error("Web VideoEngine requires play-url");return this.video}handleVisibility=()=>{var e;document.hidden&&this.booleanAttribute("pause-on-hide")&&(null==(e=this.video)?void 0:e.getAttribute("src"))&&this.pause()};prepare(){let e=this.getMedia();e.preload="auto",e.controls=!0,this.prepared=!1,e.readyState>=3?queueMicrotask(()=>{this.video===e&&this.notifyPrepared()}):e.load()}play(){let e=this.getMedia();this.stopped=!1;let t=++this.playRequest;e.play().catch(r=>{this.video===e&&t===this.playRequest&&this.reportError(String(r))})}pause(){let e=this.getMedia();this.playRequest++,this.stopped=!1,e.pause(),this.setPlaybackState(2)}stop(){let e=this.getMedia();this.playRequest++,this.stopped=!0,e.pause(),e.currentTime=0,this.setPlaybackState(0)}seek(e){if(!e||!Number.isFinite(e.position)||e.position<0)throw Error("seek.position must be a non-negative number in milliseconds");let t=this.getMedia(),r=Math.min(e.position/1e3,Number.isFinite(t.duration)?t.duration:1/0);e.play||this.pause(),t.currentTime===r?queueMicrotask(()=>{this.video===t&&this.emit("seek")}):t.currentTime=r,e.play&&this.play()}getDuration(){let e=this.getMedia().duration;if(!Number.isFinite(e))throw Error("Video duration is not available yet");return{duration:1e3*e}}}),"object"==typeof customElements)for(let e of["x-image","filter-image"]){if(e2.has(e))continue;e2.add(e);let t=e=>{if(!(eY in e.prototype)){var t;null==(t=e.registerPlugin)||t.call(e,e1)}},r=customElements.get(e);r?t(r):customElements.whenDefined(e).then(t)}if("object"==typeof document&&"object"==typeof customElements){let e=document.createElement("map").constructor.prototype;for(let t of["center","scale-range","polyline","polygons","circles","arcs","route-label","extra-params"])t in e||Object.defineProperty(e,t,{configurable:!0,get(){return th(this)[t]},set(e){var r;let n=tr.get(this)??{};n[t]=e,tr.set(this,n),null==(r=ta.get(this))||r.update()}});!function(){if(customElements.get("map-marker"))return;class e extends HTMLElement{static observedAttributes=["position","anchor","alpha","rotation","enable-click","enable-drag","animate","container-position"];connectedCallback(){queueMicrotask(()=>{var e;return null==(e=tg(this))?void 0:e.updateMarkers()})}attributeChangedCallback(){var e;null==(e=tg(this))||e.updateMarkers()}refreshMarker(){var e;null==(e=tg(this))||e.updateMarkers()}}for(let t of["position","anchor","animate","container-position"])Object.defineProperty(e.prototype,t,{configurable:!0,get(){return tm(this)[t]},set(e){var r;let n=tn.get(this)??{};n[t]=e,tn.set(this,n),null==(r=tg(this))||r.updateMarkers()}});customElements.define("map-marker",e)}()}function tw(e,t){"function"==typeof(null==e?void 0:e.sendGlobalEvent)&&e.sendGlobalEvent("__APPLET_BRIDGE__",[t])}class tS{container;className;options;runtimeContext;bridge=null;caller;cleanupWidgetTapCapture=null;cleanupWebMapHost=null;view=null;constructor(e,t={environment:"direct"}){let r=e.container;if(!r)throw Error("Container requires a container element");this.container=r,this.className=e.className??"doubao-web-container-view",this.options=e,this.runtimeContext=t}get element(){return this.view}prepare(){this.clear()}render(e){var t,r,n,a,i,s,o,l,d;let u,c,p,h,m,g,f,y,_,b,w,S,x,I,k,C,E;this.clear();let N=document.createElement("lynx-view"),M="sandbox"===this.runtimeContext.environment?this.runtimeContext.resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(n=this.options.runtime)||null==(r=n.packageInfo)?void 0:r.resourceRoot);M&&(N.resolveResource=e=>{let t=e.startsWith("/base/")?e.slice(1):e;return t?new URL(t,M).href:t}),N.injectStyleRules=['[doubao-component="popup"] > .popup-container { top: 0; left: 0; z-index: 1000; }'];let T=eI(e),R=ek(T);N.className=this.className,e.groupId&&N.setAttribute("lynx-group-id",e.groupId),N.dataset.containerType=T,N.dataset.webSizing=R,N.style.display="APP"===T||"TOOL"===T?"none":"block",N.style.width="100%",N.style.height="content"===R?"auto":"100%","content"===R&&N.setAttribute("height","auto"),N.url=ex(e),N.initData=e.initData??{};let A={...V(),...e.globalProps??{}};this.bridge=e.bridge??(null==(a=this.options.runtime)?void 0:a.bridge)??new e_,this.caller=e.bridgeCaller??this.bridge.register(e=>tw(N,e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===T);let P=this.bridge,j=this.caller,L="sandbox"===this.runtimeContext.environment?this.runtimeContext.syncBridgeData:P.createSyncBridgeData(j,A,this.options.fileSystemNamespace);i=this.runtimeContext.environment,u=new URL("./__doubao_web_sdk_native_modules/",(null==(s=globalThis.document)?void 0:s.baseURI)??(null==(o=globalThis.location)?void 0:o.href)??"http://localhost/").href,c=ew(new URL("applet-bridge-module.js",u)),p=ew(new URL("applet-js-module.js",u)),g={AppletBridgeModule:((m=new URLSearchParams((h=new URL(c)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...L,fileSystemSnapshot:el()})),h.hash=m.toString(),h.href),AppletJSModule:p},"direct"===i&&(g.LynxConsoleModule=ew(new URL("console-module.js",u)),"APP"===T&&(g.LynxDevToolSetModule=p)),N.nativeModulesMap=g,(0,ez.B)(N),N.globalProps={...A,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:L};let D={containerType:T,element:N,globalProps:A,fileSystemNamespace:L.fileSystemNamespace,environment:this.runtimeContext.environment};return N.onNativeModulesCall=(e,t,r)=>P.dispatch(j,e,t,r,D),l=async e=>{let t=await P.dispatch(j,"postMessage",e,"AppletBridgeModule",D);return v(t)?t:void 0},eJ.set(N,l),N.transformVW=!0,N.transformVH="content"!==R,N.transformREM=!1,N.addEventListener("error",e=>{var t,r;let n;null==(t=(r=this.options).onError)||t.call(r,(null==(n=e.detail)?void 0:n.error)instanceof Error?n.error:Error(String((null==n?void 0:n.error)??n??"Unknown Container runtime error")),e)}),"WIDGET"===T&&this.options.captureWidgetTap&&(this.cleanupWidgetTapCapture=(d=this.options.onWidgetInteraction,f=0,y=e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();var t={sequence:f+=1,type:"tap"};try{Promise.resolve(null==d?void 0:d(t)).catch(()=>void 0)}catch{}},N.addEventListener("click",y,!0),()=>N.removeEventListener("click",y,!0))),this.view=N,this.container.replaceChildren(N),this.cleanupWebMapHost=(b=new Map,w=new Set,S=[],x=0,I=!1,k=e=>{for(let t of e.querySelectorAll("*"))"map"!==t.localName||ta.has(t)||w.add(new tf(t)),t.shadowRoot&&C(t.shadowRoot);for(let e of w)e.element.isConnected||(e.dispose(),w.delete(e))},C=e=>{if(b.has(e)||I)return;let t=new MutationObserver(t=>{if(!(t.some(e=>{let t=e.target;return t instanceof Element&&t.closest("[data-doubao-map-surface]")})&&t.every(e=>e.target instanceof Element&&e.target.closest("[data-doubao-map-surface]"))))for(let n of(k(e),t)){let e=n.target,t=e instanceof Element?e.closest("map"):null;if(t){var r;null==(r=ta.get(t))||r.update()}}});t.observe(e,{childList:!0,subtree:!0,attributes:!0}),b.set(e,t),k(e)},(E=()=>{if(I)return;let e=N.shadowRoot??N;if(C(e),N.shadowRoot&&_!==e)for(let t of(_=e,[0,16,100,500,2e3,1e4]))S.push(setTimeout(()=>{I||k(e)},t));else N.shadowRoot||(x=requestAnimationFrame(E))})(),()=>{for(let e of(I=!0,cancelAnimationFrame(x),S))clearTimeout(e);for(let e of b.values())e.disconnect();for(let e of w)e.dispose()}),N}clear(){var e,t,r,n;null==(e=this.cleanupWebMapHost)||e.call(this),this.cleanupWebMapHost=null,null==(t=this.cleanupWidgetTapCapture)||t.call(this),this.cleanupWidgetTapCapture=null,this.caller&&(null==(n=this.bridge)||n.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(r=this.view)||r.remove(),this.view=null,this.container.replaceChildren()}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=this.view,tw(t,{type:"event",name:e,params:r,timestamp:Date.now()})}sendBridgeMessage(e){tw(this.view,e)}sendGlobalEvent(e,t){var r,n;null==(n=this.view)||null==(r=n.sendGlobalEvent)||r.call(n,e,t)}reload(){var e,t;null==(t=this.view)||null==(e=t.reload)||e.call(t)}}let tx=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
20
20
|
<path d="M3.74902 7.91113C4.90234 7.91131 5.83691 8.84664 5.83691 10C5.83674 11.1532 4.90223 12.0877 3.74902 12.0879C2.59566 12.0879 1.66033 11.1533 1.66016 10C1.66016 8.84653 2.59555 7.91113 3.74902 7.91113ZM9.99805 7.91113C11.1514 7.91131 12.0859 8.84664 12.0859 10C12.0858 11.1532 11.1513 12.0877 9.99805 12.0879C8.84469 12.0879 7.90936 11.1533 7.90918 10C7.90918 8.84653 8.84458 7.91113 9.99805 7.91113ZM16.249 7.91113C17.4023 7.91131 18.3369 8.84664 18.3369 10C18.3367 11.1532 17.4022 12.0877 16.249 12.0879C15.0957 12.0879 14.1603 11.1533 14.1602 10C14.1602 8.84653 15.0956 7.91113 16.249 7.91113Z" fill="black"/>
|
|
21
21
|
</svg>`,tI=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
22
22
|
<path d="M9.99622 18.176C8.86678 18.176 7.8086 17.9623 6.82166 17.5348C5.83472 17.1126 4.96653 16.5267 4.21709 15.7773C3.46765 15.0331 2.87919 14.1676 2.45169 13.1806C2.02947 12.1884 1.81836 11.1276 1.81836 9.99817C1.81836 8.86873 2.02947 7.81055 2.45169 6.82361C2.87919 5.8314 3.46765 4.96057 4.21709 4.21113C4.96653 3.46169 5.83472 2.87586 6.82166 2.45364C7.8086 2.03142 8.86678 1.82031 9.99622 1.82031C11.1257 1.82031 12.1838 2.03142 13.1708 2.45364C14.163 2.87586 15.0338 3.46169 15.7833 4.21113C16.5327 4.96057 17.1185 5.8314 17.5408 6.82361C17.9682 7.81055 18.182 8.86873 18.182 9.99817C18.182 11.1276 17.9682 12.1884 17.5408 13.1806C17.1185 14.1676 16.5327 15.0331 15.7833 15.7773C15.0338 16.5267 14.163 17.1126 13.1708 17.5348C12.1838 17.9623 11.1257 18.176 9.99622 18.176ZM9.99622 16.561C10.904 16.561 11.7537 16.3895 12.5454 16.0465C13.337 15.7087 14.0337 15.239 14.6354 14.6373C15.2423 14.0356 15.7147 13.339 16.0524 12.5473C16.3902 11.7557 16.5591 10.9059 16.5591 9.99817C16.5591 9.0904 16.3902 8.24068 16.0524 7.44902C15.7147 6.65208 15.2423 5.95542 14.6354 5.35904C14.0337 4.75738 13.337 4.28766 12.5454 3.94988C11.7537 3.60683 10.904 3.4353 9.99622 3.4353C9.09373 3.4353 8.24401 3.60683 7.44707 3.94988C6.65541 4.28766 5.95875 4.75738 5.35708 5.35904C4.75542 5.95542 4.28306 6.65208 3.94001 7.44902C3.60224 8.24068 3.43335 9.0904 3.43335 9.99817C3.43335 10.9059 3.60224 11.7557 3.94001 12.5473C4.28306 13.339 4.75542 14.0356 5.35708 14.6373C5.95875 15.239 6.65541 15.7087 7.44707 16.0465C8.24401 16.3895 9.09373 16.561 9.99622 16.561ZM10.0041 13.0856C9.43414 13.0856 8.91164 12.9458 8.43665 12.6661C7.96693 12.3863 7.59221 12.0116 7.31249 11.5419C7.03277 11.0722 6.89291 10.5523 6.89291 9.98234C6.89291 9.41234 7.03277 8.89248 7.31249 8.42277C7.59221 7.95305 7.96693 7.57833 8.43665 7.29861C8.91164 7.01361 9.43414 6.87111 10.0041 6.87111C10.5741 6.87111 11.0914 7.01361 11.5558 7.29861C12.0255 7.57833 12.4002 7.95305 12.68 8.42277C12.9597 8.89248 13.0995 9.41234 13.0995 9.98234C13.0995 10.5523 12.9597 11.0722 12.68 11.5419C12.4002 12.0116 12.0255 12.3863 11.5558 12.6661C11.0914 12.9458 10.5741 13.0856 10.0041 13.0856Z" fill="black"/>
|
|
23
|
-
</svg>`,tk="doubao-apps-page",tC={body:`${tk}__body`,capsule:`${tk}__capsule`,capsuleAction:`${tk}__capsule-action`,capsuleCloseIcon:`${tk}__capsule-close-icon`,capsuleMoreIcon:`${tk}__capsule-more-icon`,root:tk};class tE{host;options;runtimeKernel;container=null;root=null;constructor(e,t){if(!e.container)throw Error("Page requires a container element");this.host=e.container,this.options=e,this.runtimeKernel=t}get element(){var e;return(null==(e=this.container)?void 0:e.element)??null}render(e){var t,r;let n;this.clear();let a=document.createElement("div");a.className=tC.root,void 0!==(n=null==(t=e.pageCapsule)?void 0:t.statusBarHeight)&&a.style.setProperty("--doubao-page-capsule-top",`${n+4}px`);let i=document.createElement("div");i.className=tC.body,a.append(i,this.createCapsule()),this.host.replaceChildren(a),this.root=a;try{return this.container=this.runtimeKernel.createContainer({...this.options,sandboxUrl:this.options.runtime?this.options.runtime.sandboxUrl:this.options.sandboxUrl,container:i,className:this.options.className,onError:this.options.onError,onReady:this.options.onReady}),this.container.render({bridge:null==(r=this.options.runtime)?void 0:r.bridge,resourceUrl:function(e){if(!e.resourceUrl)throw Error("Page.render requires a resourceUrl");return e.resourceUrl}(e),groupId:e.groupId,containerType:"PAGE",initData:e.initData,globalProps:e.globalProps})}catch(e){throw this.clear(),e}}clear(){var e,t;null==(e=this.container)||e.clear(),this.container=null,null==(t=this.root)||t.remove(),this.root=null,this.host.replaceChildren()}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};null==(t=this.container)||t.sendEvent(e,r)}reload(){var e;null==(e=this.container)||e.reload()}dispatchCapsuleEvent(e,t){t.stopPropagation(),this.host.dispatchEvent(new CustomEvent(e,{bubbles:!0}))}createCapsuleSvg(e){let t=document.createElement("template");t.innerHTML=e.trim();let r=t.content.firstElementChild;if(!r||"svg"!==r.tagName.toLowerCase())throw Error("Invalid Page capsule icon SVG");return r}createCapsuleAction(e,t,r,n){let a=this.createCapsuleSvg(r);return a.classList.add(tC.capsuleAction,e),a.setAttribute("role","button"),a.setAttribute("aria-label",t),a.setAttribute("tabindex","0"),a.setAttribute("focusable","true"),a.addEventListener("click",e=>{this.dispatchCapsuleEvent(n,e)}),a.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),this.dispatchCapsuleEvent(n,e))}),a}createCapsuleMoreIcon(){return this.createCapsuleAction(tC.capsuleMoreIcon,"More",tx,"doubao:page-capsule-more")}createCapsuleCloseIcon(){return this.createCapsuleAction(tC.capsuleCloseIcon,"Close app",tI,"doubao:page-capsule-close")}createCapsule(){let e=document.createElement("div");return e.className=tC.capsule,e.style.display="flex",e.style.flexDirection="row",e.setAttribute("role","group"),e.setAttribute("aria-label","Page actions"),e.append(this.createCapsuleMoreIcon(),this.createCapsuleCloseIcon()),e}}let tN=/\{\{\s*([^{}\s]+)\s*\}\}/g;function tM(e){return"string"==typeof e?e:JSON.stringify(e)}function tT(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={...e.input||{},...function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};for(let[n,a]of Object.entries(e.variables||{}))Object.prototype.hasOwnProperty.call(t,n)?r[n]=t[n]:null!==a&&(r[n]=a);return{...r,...t}}(e,t)};if("page"===e.type){let t=function(e,t){var r;let n=new Set(Array.from(e.url.matchAll(tN),e=>e[1])),a=(r=e.url,r.replace(tN,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;let n=tM(t[r]);return void 0===n?e:encodeURIComponent(n)})),i=a.indexOf("#"),s=i<0?a:a.slice(0,i),o=i<0?"":a.slice(i),l=s.indexOf("?"),d=new Set(new URLSearchParams(l<0?"":s.slice(l+1)).keys()),u=new URLSearchParams;for(let[e,r]of Object.entries(t)){if(n.has(e)||d.has(e))continue;let t=tM(r);void 0!==t&&u.set(e,t)}let c=u.toString();if(!c)return a;let p=l<0?"?":s.endsWith("?")||s.endsWith("&")?"":"&";return`${s}${p}${c}${o}`}(e,r);return{type:"page",unresolvedVariables:function(e){let t=new Set;for(let r of e.matchAll(tN))t.add(r[1]);return Array.from(t)}(t),url:t}}return"widget"===e.type?{type:"widget",id:e.id,resolvedInput:r,botId:e.botId}:{type:"tool",id:e.id,resolvedInput:r}}function tR(e){var t;let{addProtocolToBareHost:r=!1,allowRootRelative:n=!1,defaultProtocol:a="http"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(/^https?:\/\//i.test(e))return e;if(e.startsWith("//"))return`${tP(a,e.slice(2))}:${e}`;if(n&&e.startsWith("/"))return e;return/^(?:\[[^\]]+\]|[a-z0-9.-]+):\d+(?:[/?#]|$)/i.test(e)||r&&(t=e,/^(?:\[[^\]]+\]|[a-z0-9.-]+)(?:[/?#]|$)/i.test(t))?`${tP(a,e)}://${e}`:e}function tA(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=String(e??"").trim();if(!r)return;let n=tR(r,t);try{let e=t.baseUrl?new URL(n,t.baseUrl):new URL(n);if("http:"!==e.protocol&&"https:"!==e.protocol)return;return e.toString()}catch{return}}function tP(e,t){return"function"==typeof e?e(t):e}function tj(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var tL=r(70851);function tD(e,t){if(e.appId&&t&&e.appId!==t)throw Error("Resolved Widget appId must match the trusted Widget identity");return t??e.appId}let tO="__doubao_apps__expired-widget",tU="doubao-apps-widget",tq=1,t$={body:`${tU}__body`,default:`${tU}--default`,floatingHeader:`${tU}--floating-header`,embedded:`${tU}--embedded`,header:`${tU}__header`,icon:`${tU}__icon`,placeholder:`${tU}__placeholder`,placeholderContent:`${tU}__placeholder-content`,root:tU,title:`${tU}__title`};class tB{container;options;runtimeKernel;identity;viewContext;root=null;body=null;title=null;icon=null;runtimeContainer=null;runtimeFallbackOptions={};apiContextOwner={};appTheme;hostCallController=null;constructor(e,t){var r,n;let a,i,o,l,d,u;if(!e.container)throw Error("Widget requires a container element");if(!e.runtime)throw Error("Widget requires a Runtime");this.container=e.container,this.options=e,this.runtimeKernel=t,this.appTheme="light"===(a=s(r=e.globalProps)?r.appTheme:void 0)||"dark"===a?a:void 0,this.identity=(n=`widget-${tq++}`,i=e.viewContext,o=e.appId??(null==i?void 0:i.appId),l=e.widgetId??(null==i?void 0:i.widgetId),d=(null==i?void 0:i.widgetInstanceId)??n,u=i?{...i,appId:o??i.appId,widgetId:l,widgetInstanceId:d}:void 0,{appId:o,versionTag:null==i?void 0:i.versionTag,viewContext:u,widgetId:l,widgetInstanceId:d}),this.viewContext=this.identity.viewContext}get element(){var e;return(null==(e=this.runtimeContainer)?void 0:e.element)??this.root}setAppTheme(e){var t;this.appTheme=e,this.root&&(this.root.dataset.appTheme=e),null==(t=this.runtimeContainer)||t.sendEvent("onThemeChange",{appTheme:e})}async render(){var e;this.clear(),this.hostCallController=new AbortController;let t=this.hostCallController.signal;try{await g(()=>this.options.runtime.loadPackage(),t)}catch(e){if(m(t),s(e)&&"AbortError"===e.name)throw e;return this.renderFallback()}if(m(t),"iframe"===(e={identity:this.identity,mode:this.runtimeKernel.mode}).mode&&e.identity.widgetId!==tO&&e.identity.appId&&e.identity.widgetId)try{this.prepareIframeRuntime()}catch{return this.renderFallback()}let r=function(e){let t;m(e.signal);let{packageInfo:r,packageManager:n}=e.options.runtime,{manifest:a}=r;if(tD(e.identity,a.appId),e.identity.widgetId===tO){var i,s;let t;return{kind:"expired",options:{appName:a.name??e.identity.appId,icon:a.iconSrc,placeholderText:"string"==typeof(t=null==(i=e.options.initData)||null==(s=i.viewData)?void 0:s.title)&&t.trim().length>0?t:void 0}}}try{let a=n.resolveWidget(r,e.identity.widgetId);if(m(e.signal),t={appName:a.appName,icon:a.icon},!a.resourceUrl)return{kind:"fallback",options:t};return{kind:"runtime",options:{appId:tD(e.identity,a.appId),boxType:a.boxType,...t,resourceUrl:a.resourceUrl,renderMode:a.renderMode??"standard",titleType:a.titleType??2*(!1===a.showHeader)}}}catch{return m(e.signal),{kind:"fallback",options:t}}}({identity:this.identity,mode:this.runtimeKernel.mode,options:this.options,signal:t});if("expired"===r.kind)return this.renderPlaceholderCard(r.options);if("fallback"===r.kind)return this.renderFallback(r.options);try{return this.renderResource(r.options)}catch{return m(t),this.renderFallback({appName:r.options.appName,icon:r.options.icon})}}getShellClassName(e){let{boxType:t,floatingHeader:r,renderMode:n}=e,a="embedded"===n;return(0,tL.$)(t$.root,{[t$.default]:4!==t&&!a,[t$.floatingHeader]:r,[t$.embedded]:a},this.options.className)}renderShell(e){var t;let r=document.createElement("section");r.className=this.getShellClassName(e),this.appTheme&&(r.dataset.appTheme=this.appTheme);let n="number"==typeof(t=this.options.contentMaxWidth)&&Number.isFinite(t)?`${t}px`:"string"==typeof t&&t.trim().length>0?t:void 0;n&&(r.style.maxWidth=n);let a=document.createElement("div");a.className=t$.body;let i=null;if(e.showHeader){(i=document.createElement("header")).className=t$.header,i.hidden="iframe"===this.runtimeKernel.mode;let e=document.createElement("img");e.alt="",e.className=t$.icon,e.height=16,e.width=16;let t=document.createElement("div");t.className=t$.title,i.append(e,t),r.append(i),this.icon=e,this.title=t}return r.append(a),this.container.replaceChildren(r),this.root=r,this.body=a,this.updateHeader(e.appName,e.icon),{body:a,header:i,root:r}}renderPlaceholderCard(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.clear();let{body:t,header:r,root:n}=this.renderShell({appName:e.appName??this.identity.widgetId??this.identity.appId??"",icon:e.icon,renderMode:"standard",showHeader:!0});r&&(r.hidden=!1);let a=document.createElement("div");a.className=t$.placeholder;let i=document.createElement("div");return i.className=t$.placeholderContent,i.textContent=e.placeholderText??this.options.fallbackText??"",a.append(i),t.append(a),n}renderFallback(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.renderPlaceholderCard({...e,placeholderText:this.options.fallbackText})}handleRuntimeError(e,t,r){try{var n,a;null==(n=(a=this.options).onError)||n.call(a,e,t)}finally{this.renderFallback({appName:r.appName,icon:r.icon})}}renderResource(e){var t,r;let n={...this.options.globalProps,__GEN_UI_CODE__:this.options.genUICode??(null==(t=this.options.globalProps)?void 0:t.__GEN_UI_CODE__),appTheme:this.appTheme,packageInfo:{...null==(r=this.options.globalProps)?void 0:r.packageInfo,appId:e.appId,iconSrc:e.icon,name:e.appName}};this.runtimeFallbackOptions={appName:e.appName,icon:e.icon};let{body:a,root:i}=this.updateOrRenderResourceShell(e);return"iframe"===this.runtimeKernel.mode&&(i.style.background="transparent",i.style.borderWidth="0"),this.runtimeContainer??=this.createRuntimeContainer(a),this.runtimeContainer.render({bridge:this.options.runtime.bridge,containerType:"WIDGET",resourceUrl:e.resourceUrl,initData:this.options.initData,globalProps:{...n,__VIEW_CONTEXT__:this.viewContext??{}}})}createRuntimeContainer(e){var t,r;let n=(null==(t=this.viewContext)||null==(r=t.shareInfo)?void 0:r.mode)==="share_page";return this.runtimeKernel.createContainer({...this.options,getAppletContext:()=>({owner:this.options.invocationOwner??this.apiContextOwner,signal:this.getHostCallSignal(),source:"widget",viewContext:this.viewContext}),sandboxUrl:this.options.runtime.sandboxUrl,captureWidgetTap:n||void 0,container:e,onUnsupportedAPI:this.options.onUnsupportedAPI,onError:(e,t)=>{this.handleRuntimeError(e,t,this.runtimeFallbackOptions)},onReady:()=>{var e,t,r;null==(e=this.root)||e.style.removeProperty("background"),null==(t=this.root)||t.style.removeProperty("border-width"),(null==(r=this.title)?void 0:r.parentElement)&&(this.title.parentElement.hidden=!1)},onWidgetInteraction:n&&this.options.onWidgetInteraction?e=>this.handleWidgetInteraction(e):void 0})}prepareIframeRuntime(){let{body:e,root:t}=this.renderShell({renderMode:"standard",showHeader:!0});t.style.background="transparent",t.style.borderWidth="0",this.runtimeFallbackOptions={},this.runtimeContainer=this.createRuntimeContainer(e),this.runtimeContainer.prepare("WIDGET")}updateOrRenderResourceShell(e){var t,r,n;let a={appName:e.appName,boxType:e.boxType,floatingHeader:1===e.titleType,icon:e.icon,renderMode:e.renderMode,showHeader:"embedded"!==e.renderMode&&2!==e.titleType};return this.root&&this.body?(this.root.className=this.getShellClassName(a),a.showHeader||(null==(n=this.title)||null==(r=n.parentElement)||r.remove(),this.icon=null,this.title=null),this.updateHeader(e.appName,e.icon),{body:this.body,header:(null==(t=this.title)?void 0:t.parentElement)??null,root:this.root}):this.renderShell(a)}clear(){var e,t,r;null==(e=this.hostCallController)||e.abort(),this.hostCallController=null,this.apiContextOwner={},null==(t=this.runtimeContainer)||t.clear(),this.runtimeContainer=null,this.runtimeFallbackOptions={},null==(r=this.root)||r.remove(),this.root=null,this.body=null,this.title=null,this.icon=null,this.container.replaceChildren()}reload(){var e;null==(e=this.runtimeContainer)||e.reload()}destroy(){this.clear()}getHostCallSignal(){if(this.hostCallController)return this.hostCallController.signal;let e=new AbortController;return e.abort(),e.signal}async handleWidgetInteraction(e){let t=this.options.onWidgetInteraction;if(!t)return;let r=this.getHostCallSignal();m(r),await t(e),m(r)}updateHeader(e,t){this.title&&(this.title.textContent=e??""),this.icon&&(t?(this.icon.src=t,this.icon.hidden=!1):(this.icon.removeAttribute("src"),this.icon.hidden=!0))}}let tF={mode:"inline",createContainer:e=>new tS(e)},tW=new eW(tF,!0);class tH{options;emptyState;cleanupEmptyState;constructor(e){this.options=e}get container(){return this.options.container}createPage(e,t,r){let n=document.createElement("div");n.className="doubao-runtime-page",Object.assign(n.style,{display:"block",width:"100%",height:"100%"}),n.addEventListener("doubao:page-capsule-close",e=>{e.stopPropagation(),r()});let a=this.container,i=new tE({...e,container:n},t);return{render:e=>(a.append(n),i.render(e)),setVisible(e){n.style.display=e?"block":"none"},clear(){i.clear(),n.remove()},sendEvent:i.sendEvent.bind(i),reload:i.reload.bind(i)}}setEmpty(e){let t=this.options.mountEmptyState;!this.emptyState&&t&&(this.emptyState=document.createElement("div"),this.emptyState.className="doubao-runtime-empty",this.container.append(this.emptyState),this.cleanupEmptyState=t(this.emptyState)??void 0),this.emptyState&&(this.emptyState.hidden=!e)}destroy(){var e,t;null==(e=this.cleanupEmptyState)||e.call(this),this.cleanupEmptyState=void 0,null==(t=this.emptyState)||t.remove(),this.emptyState=void 0}}class tz extends eH(tS,()=>tW){}class tV extends tB{constructor(e){super(e,tF)}}class tG extends eF{constructor(e){super(e,tF)}}var tJ=r(75541);function tK(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function tX(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function tZ(e,t){let r=t.trim();r&&!e.includes(r)&&e.push(r)}function tQ(e){let t=[];return!function e(t,r,n){if(!("object"!=typeof t||null===t||n.has(t))){if(n.add(t),Array.isArray(t))return void t.forEach(t=>e(t,r,n));if(tj(t))for(let[a,i]of Object.entries(t))"response_headers"===a.toLowerCase()&&function(e,t){if(tj(e)){for(let[r,n]of Object.entries(e))if("x-tt-logid"===r.toLowerCase()&&"string"==typeof n)return void tZ(t,n)}}(i,r),"log_ids"===a.toLowerCase()&&function(e,t){if("string"==typeof e)return tZ(t,e);if(Array.isArray(e))for(let r of e)"string"==typeof r&&tZ(t,r)}(i,r),e(i,r,n)}}(e,t,new WeakSet),t}function tY(e,t){if(!e.startsWith("sslocal://"))return{url:e};let r=new URL(e).searchParams,n=r.get("app_id"),a=r.get("path"),i=r.get("query"),s=r.get("route_mode")??void 0;if(!t)throw Error("当前调试应用缺少 AppID");if(n!==t)throw Error(`任务目标应用 ${n} 与当前应用 ${t} 不一致`);if(!a)throw Error("任务目标缺少 path");if(void 0!==s&&"navigate"!==s&&"redirect"!==s&&"relaunch"!==s)throw Error(`不支持的任务导航模式: ${s}`);return{url:i?`${a}?${i}`:a,routeMode:s}}function t0(e){return tj(e)?tj(e.viewData)?e:{...e,viewData:e}:{viewData:{}}}function t1(e){if("string"==typeof e&&e.trim())try{return JSON.parse(e)}catch{return}}function t2(e){if(tj(e))return e;let t=t1(e);return tj(t)?t:void 0}function t3(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return"{}"}}function t4(e){return e instanceof Error?e.message:String(e)}function t5(e){let t=null==e?void 0:e.toLowerCase();switch(t){case"agent":case"api":case"mcp":case"card":case"resource":case"runtime":case"debug":return t;case"tool":return"agent";default:return"runtime"}}function t6(e){let[t,...r]=e.trim().split(":"),n=t.replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(t8).join(" ");return 0===r.length?n||e:`${n}: ${r.join(":").trim()}`}function t8(e){let t=function(e){switch(e.toLowerCase()){case"api":return"API";case"mcp":return"MCP";case"sse":return"SSE";case"ack":return"ACK";case"http":return"HTTP";case"json":return"JSON";case"id":return"ID";default:return""}}(e);if(t)return t;if(/^[A-Z0-9]+$/.test(e))return e;let r=e.toLowerCase();return`${r.slice(0,1).toUpperCase()}${r.slice(1)}`}r(78872),r(60972),r(45249),r(20789),r(62839),r(66876);let t7=new Set(["local_mcp_missing","local_mcp_tools_load_failed","simulator_chat_fetch_failed","simulator_query_failed","stream_error","tool_executor_missing","tool_result_submit_failed"]),t9={query:0,"tool-call":10,"tool-result":20,"agent-processing":25,card:30,"agent-response":40,error:50};function re(e,t){return{category:"api",detail:{query:t},key:"query",phase:"request",payload:{event:"query",query:t},source:e,sources:[e],title:"Query"}}function rt(e,t){let r=e.steps.get(t.key);if(!r)return void e.steps.set(t.key,t);let n=function(e,t){if("error"===t.phase)return!0;if(e.key.startsWith("card:")){let r=ri(e.source.payload);return rr(ri(t.source.payload))>rr(r)}return!1}(r,t),a=n?t:r,i=n?r:t;e.steps.set(t.key,{...r,category:"error"===t.phase?t.category:a.category,detail:ru(a.detail,i.detail),phase:"error"===t.phase?t.phase:a.phase,payload:ru(a.payload,i.payload),source:a.source,sources:[...new Map([...r.sources,...t.sources].map(e=>[e.id,e])).values()],title:"error"===t.phase||n?t.title:r.title})}function rr(e){return"simulator_card_render_failed"===e||"simulator_card_runtime_error"===e||"simulator_card_render_skipped"===e?3:"simulator_card_rendered"===e?2:+("card_delta"===e)}function rn(e){let t=rh([...e.steps.values()]);return t.map((r,n)=>{var a,i,s,o,l,d,u;let c,p,h,m,g,f,v,y,_,b,w;return a=r,i=e,s=t,o=n,y=rc(a.sources.flatMap(tQ)),_=rc(a.sources.map(e=>e.payload.request_id||"")),w=void 0===(b=(l=a,d=s,u=o,c=l.payload.elapsed_ms??l.detail.elapsed_ms,h=(null==(p=l.key.startsWith("agent-processing:")?d.slice(u+1).find(e=>/^(tool-call|card|error):/.test(e.key)||"agent-response"===e.key):d[u+1])?void 0:p.source.timestamp)??l.source.timestamp,m=Number.isFinite(l.source.timestamp)&&Number.isFinite(h)?Math.max(0,h-l.source.timestamp):void 0,f=(g=l.key.startsWith("tool-call:")?l.key.replace("tool-call:","tool-result:"):l.key.startsWith("tool-result:")?l.key.replace("tool-result:","tool-call:"):void 0)?d.find(e=>e.key===g):void 0,void 0!==(v=l.key.startsWith("tool-call:")&&f?f.payload.elapsed_ms??f.detail.elapsed_ms:void 0)?v:l.key.startsWith("tool-result:")&&f?void 0:void 0!==c?void 0===m?c:Math.max(c,m):m))?a.detail:{...a.detail,elapsed_ms:b},{id:a.source.id,order:a.source.order,timestamp:a.source.timestamp,display:{category:a.category,detail:w,phase:a.phase,title:a.title},payload:{request_id:1===_.length?_[0]:void 0,request_ids:_.length>1?_:void 0,...a.payload,trace_id:i.id,run_status:i.status,elapsed_ms:b,log_ids:y.length>0?y:void 0}}})}function ra(e,t){let r=rp(t.payload),n=r?e.runs.find(e=>e.id===r):void 0;if(!n){if(!r)return;n={id:r,order:t.order??e.runs.length,startedAt:t.timestamp,steps:new Map},e.runs.push(n)}return n.startedAt=Math.min(n.startedAt,t.timestamp),n.order=Math.min(n.order,t.order??n.order),n}function ri(e){return e.event||""}function rs(e,t){return ro(e)||[rp(e)||t.id,e.tool_name||"unknown-tool"].filter(Boolean).join(":")}function ro(e){return e.tool_call_id||""}function rl(e){let t=e.tool_name||ro(e);return t?`: ${t}`:""}function rd(e){let t={};for(let[r,n]of Object.entries(e))null!=n&&""!==n&&(t[r]=n);return t}function ru(e,t){return Object.fromEntries([...Object.entries(t),...Object.entries(e).filter(e=>{let[,t]=e;return void 0!==t})])}function rc(e){return[...new Set(e.filter(e=>!!e))]}function rp(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}function rh(e){return[...e].sort((e,t)=>e.source.timestamp-t.source.timestamp||(e.source.order??0)-(t.source.order??0)||t9[e.key.split(":")[0]]-t9[t.key.split(":")[0]]||e.key.localeCompare(t.key))}function rm(e,t){return e.startedAt-t.startedAt||e.order-t.order||e.id.localeCompare(t.id)}function rg(e,t){return e.timestamp-t.timestamp||(e.order??0)-(t.order??0)||e.id.localeCompare(t.id)}function rf(e){try{return rv(e,2)}catch{var t=e;if("string"==typeof t){let e=t.trim();if(!e)return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}if(void 0===t)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}}function rv(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=new WeakSet;return JSON.stringify(e,(e,t)=>{if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if("function"==typeof t)return`[Function ${t.name||"anonymous"}]`;if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t},t)}function ry(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=Date.now();return{stored_at:new Date(r).toISOString(),stored_at_ms:r,snapshot:r_(e,t),debug_snapshot:r_(e,{...t,debug:!0,includeRuntimeRoot:!1})}}function r_(e){var t,r;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=n.debug&&!n.traceId?(t=e,r=!1!==n.includeRuntimeRoot,tj(t)&&!r&&tj(t.runtime_snapshot)?{...t,runtime_snapshot:rw(t.runtime_snapshot,!1)}:t):function(e,t){var r;if(!tj(e))return e;let n=tj(e.simulator)?e.simulator:{},a=Array.isArray(n.messages)?n.messages.filter(e=>rS(e,t.traceId)):void 0,i=Array.isArray(n.tool_calls)?n.tool_calls.filter(e=>rS(e,t.traceId)):void 0,s=rw(e.runtime_snapshot,!1!==t.includeRuntimeRoot);return{...rN(e,["exported_at","client_id","command_id","context","render_targets"]),runtime_snapshot:tj(s)?s:void 0,simulator:tj(e.simulator)?{...rN(n,["stream_status","active_request_id","active_reply_message_id"]),error:n.error?rE(n.error):void 0,selected_card:n.selected_card?rC(n.selected_card):void 0,answer_finish:n.answer_finish?tj(r=n.answer_finish)?rN(r,["messageId","status","finishReason","usage","createdAtMs"]):r:void 0,messages:null==a?void 0:a.map(rx),tool_calls:null==i?void 0:i.map(rk),trace_events:Array.isArray(n.trace_events)?rb(n.trace_events,{debug:t.debug,messages:a,traceId:t.traceId}):void 0}:void 0,widget_runtime_trace_events:Array.isArray(e.widget_runtime_trace_events)?rb(e.widget_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,page_runtime_trace_events:Array.isArray(e.page_runtime_trace_events)?rb(e.page_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,runtime_console:tj(e.runtime_console)?e.runtime_console:void 0}}(e,n),i=tQ(e);return i.length>0&&tj(a)?{...a,log_ids:i}:a}function rb(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.debug&&!t.traceId)return e;if(t.debug){var r,n;return r=e,(n=t.traceId)?r.filter(e=>rp(e.payload)===n):r}let a=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r={runs:[]};for(let t of[...e].sort(rg))!function(e,t){var r,n;let a=t.payload,i=ri(a);if("tool_result_report_started"===i){let r=ra(e,t);if(!r)return;rt(r,function(e){let t=e.payload,r=rd({tool_call_id:ro(t),tool_name:t.tool_name});return{category:"agent",detail:r,key:`agent-processing:${rs(t,e)}`,phase:"request",payload:{event:"agent_processing",...r},source:e,sources:[e],title:`Agent Processing${rl(t)}`}}(t));return}if(!((r=i).startsWith("tool_result_report_")||"tool_result_ack"===r)){if("simulator_chat_fetch_started"===i){let r=function(e){var t,r,n;return e.query||(null==(t=e.request)?void 0:t.query)||(null==(n=e.request)||null==(r=n.message)?void 0:r.content)||""}(a);if(!r)return;let n=ra(e,t);if(!n)return;rt(n,re(t,r));return}if("tool_call"===i||"local_mcp_call_started"===i){let r=ra(e,t);if(!r)return;rt(r,function(e){let t=e.payload,r=rd({tool_call_id:ro(t),tool_name:t.tool_name,arguments:t.arguments,arguments_json:t.arguments_json});return{category:"agent",detail:r,key:`tool-call:${rs(t,e)}`,phase:"request",payload:{event:"tool_call",...r},source:e,sources:[e],title:`Tool Call${rl(t)}`}}(t));return}if("local_mcp_call_succeeded"===i||"local_mcp_call_failed"===i){let r=ra(e,t);if(!r)return;rt(r,function(e){let t=e.payload,r="local_mcp_call_failed"===ri(t),n=t.result??t.structured_result??t1(t.structured_result_json)??t.structured_result_json,a=t.raw_mcp_result??t1(t.raw_mcp_result_json)??t.raw_mcp_result_json,i=t.raw_result_text===t.raw_mcp_result_json?void 0:t.raw_result_text,s=rd({tool_call_id:ro(t),tool_name:t.tool_name,status:t.status,result:n,raw_result_text:i,raw_mcp_result:a,elapsed_ms:t.elapsed_ms,error:t.error});return{category:"mcp",detail:s,key:`tool-result:${rs(t,e)}`,phase:r?"error":"response",payload:{event:r?"tool_result_failed":"tool_result",...s},source:e,sources:[e],title:`${r?"Tool Result Failed":"Tool Result"}${rl(t)}`}}(t));return}if("card_delta"===(n=i)||"simulator_card_rendered"===n||"simulator_card_render_failed"===n||"simulator_card_runtime_error"===n||"simulator_card_render_skipped"===n){let r=ra(e,t);if(!r)return;rt(r,function(e){var t,r;let n=e.payload,a=ri(n),i="error"in n||a.endsWith("_failed")||a.endsWith("_error"),s=rd({card_id:n.card_id,widget_id:n.widget_id,card_type:n.card_type,entity_id:n.entity_id,source_tool_call_id:n.source_tool_call_id,elapsed_ms:n.elapsed_ms,error:n.error,summary:n.summary});return{category:"card",detail:s,key:`card:${t=n,r=e,t.card_id||t.source_tool_call_id||[rp(t)||r.id,t.widget_id||r.id].filter(Boolean).join(":")}`,phase:i?"error":"response",payload:{event:i?"card_render_failed":"card_delta"===a?"card_received":"card_rendered",...s},source:e,sources:[e],title:i?"Card Render Failed":"card_delta"===a?"Card Received":"Card Rendered"}}(t));return}if(function(e,t){let r=e.phase,n=e.status;return t7.has(t)||"error"===r||t.endsWith("_failed")||t.endsWith("_missing")||t.endsWith("_aborted")||t.endsWith("_error")||"failed"===n||"error"===n||"number"==typeof n&&n>=400}(a,i)){let r=ra(e,t);if(!r)return;rt(r,function(e){var t,r;let n=e.payload,a=n.detail??{},i=n.event_count??a.event_count,s=rd({elapsed_ms:n.elapsed_ms??a.elapsed_ms,endpoint:n.endpoint??a.endpoint,error:n.error??a.error,event_count:i,message:n.message??a.message,reason:n.reason??a.reason,status:n.status??a.status,summary:n.summary??a.summary??("simulator_chat_sse_read_failed"===ri(n)&&0===i?"对话流未收到任何事件,未触发 MCP tool 与 tool/report;请结合 log_id 排查生成或下发 tool_call 前的服务端/链路异常。":void 0),response:n.response??a.response,response_text:n.response_text??a.response_text});return{category:(null==(t=e.display)?void 0:t.category)||"runtime",detail:s,key:`error:${e.id}`,phase:"error",payload:{event:ri(n)||"trace_error",...s},source:e,sources:[e],title:(null==(r=e.display)?void 0:r.title)||n.title||"Trace Error"}}(t))}}}(r,t);for(let e of t)!function(e,t){var r,n,a,i,s;let o=(n=t,{id:`trace-message-${n.messageId}`,timestamp:n.createdAtMs,payload:rd({message_id:n.messageId,request_id:n.requestId,trace_id:n.traceId})}),l=ra(e,o);if(!l)return;let d=(null==(r=t.blocks)?void 0:r.some(e=>"image"===e.type))??!1,u=t.text.trim()||(d?"[图片]":"");"assistant"===t.role&&t.status&&(a=l,i=t.status,s=t.createdAtMs,void 0!==a.statusUpdatedAt&&s<a.statusUpdatedAt||(a.status=i,a.statusUpdatedAt=s)),"user"===t.role&&u&&!l.steps.has("query")&&rt(l,re(o,u)),"assistant"===t.role&&t.text.trim()&&rt(l,function(e,t){let r=rh([...e.steps.values()]).at(-1),n=Math.max(t.createdAtMs,((null==r?void 0:r.source.timestamp)??t.createdAtMs)+.1),a={id:`trace-agent-response-${t.messageId}`,order:(null==r?void 0:r.source.order)===void 0?void 0:r.source.order+.1,timestamp:n,payload:rd({message_id:t.messageId,request_id:t.requestId,trace_id:t.traceId})};return{category:"agent",detail:{text:t.text},key:"agent-response",phase:"finish",payload:{event:"agent_response",message_id:t.messageId,text:t.text},source:a,sources:[a],title:"Agent Response"}}(l,t))}(r,e);return r}(e,t.messages);return(t.traceId?a.runs.filter(e=>e.id===t.traceId):a.runs).sort(rm).flatMap(rn)}(e,t)}function rw(e,t){if(!tj(e)||t)return e;let{root:r,...n}=e;return n}function rS(e,t){if(!t)return!0;if(!tj(e))return!1;let r=tj(e.trace)?e.trace:{};return e.traceId===t||r.trace_id===t}function rx(e){return tj(e)?{...rN(e,["messageId","localMessageId","requestId","traceId","role","contentType","status","createdAtMs"]),text:"string"==typeof e.text?rM(e.text):void 0,blocks:Array.isArray(e.blocks)?e.blocks.map(rI):void 0,toolCalls:Array.isArray(e.toolCalls)?e.toolCalls:void 0,toolResults:Array.isArray(e.toolResults)?e.toolResults:void 0}:e}function rI(e){return tj(e)?"card"===e.type?{...rN(e,["blockId","type"]),card:rC(e.card)}:"image"===e.type&&tj(e.image)?{...rN(e,["blockId","type"]),image:rN(e.image,["resource_uri","mime_type","size_bytes","width","height","sha256","name"])}:{...rN(e,["blockId","type"]),text:"string"==typeof e.text?rM(e.text):void 0}:e}function rk(e){return tj(e)?{...rN(e,["requestId","runId","replyMessageId","toolCallId","toolName","serverId","appKey","status","createdAtMs","updatedAtMs","requiresUserApproval","timeoutMs","deadlineMs","progress","message","resultSummary","structuredResultSummary","isMiniApp"]),arguments:e.arguments,argumentsJson:void 0===e.arguments&&e.argumentsJson?e.argumentsJson:void 0,error:e.error?rE(e.error):void 0}:e}function rC(e){return tj(e)?rN(e,["reply_message_id","block_id","card_id","widget_id","card_type","app_id","entity_id","title","fallback_text"]):e}function rE(e){return tj(e)?rN(e,["code","message","user_message","retryable","stage","details","name","stack"]):e}function rN(e,t){let r={};for(let n of t)void 0!==e[n]&&(r[n]=e[n]);return r}function rM(e){return e.length>1e3?`${e.slice(0,1e3)}...`:e}let rT=[1e3,2e3,4e3,8e3,16e3];class rR{clientId=crypto.randomUUID();socket;status="disconnected";listeners=new Set;retryTimer;retryIndex=0;sandboxSnapshot;snapshot;sentRuntime;snapshotErrorReported=!1;subscribe(e){return this.listeners.add(e),e({type:"status",status:this.status}),void 0!==this.sandboxSnapshot&&e({type:"sandbox",data:this.sandboxSnapshot}),()=>{this.listeners.delete(e)}}start(){this.stop(),this.retryIndex=0,this.connect()}stop(){clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.socket;this.socket=void 0,null==e||e.close(),this.sandboxSnapshot=void 0,this.setStatus("disconnected")}emit(e){for(let t of this.listeners)t(e)}setStatus(e){this.status!==e&&(this.status=e,this.emit({type:"status",status:e}))}connect(){let e;this.setStatus(this.retryIndex?"reconnecting":"connecting");let t=new URL("/__wsd_connection",window.location.href);t.protocol="https:"===t.protocol?"wss:":"ws:",t.searchParams.set("clientId",this.clientId);let r=new WebSocket(t);this.socket=r,r.onopen=()=>{this.socket===r&&(e=Date.now(),this.sentRuntime=void 0,this.sendSnapshot(),this.setStatus("connected"))},r.onmessage=e=>{let t;if(this.socket===r){try{t=JSON.parse(e.data)}catch{r.close(4e3,"Invalid debugger message");return}if(tj(t))if("control"===t.type){let e=function(e){if(!tj(e)||"string"!=typeof e.commandId)return null;if("render_page"===e.type&&"string"==typeof e.url)return{commandId:e.commandId,type:e.type,url:e.url};if("render_widget"===e.type&&"string"==typeof e.widgetId&&tj(e.structuredContent))return{commandId:e.commandId,type:e.type,widgetId:e.widgetId,structuredContent:e.structuredContent};if("set_viewport"===e.type&&tK(e.width)&&tK(e.height))return{commandId:e.commandId,type:e.type,width:e.width,height:e.height};if("submit_chat_query"===e.type&&"string"==typeof e.query&&e.query.trim())return{commandId:e.commandId,type:e.type,query:e.query.trim()};if("cancel_chat_query"===e.type)return{commandId:e.commandId,type:e.type};if("execute_sandbox_tool_call"===e.type){var t;let r="object"==typeof(t=e.toolCall)&&(null==t?void 0:t.tool_call)?t:void 0;return r?{commandId:e.commandId,toolCall:r,type:e.type}:null}if("get_computed_style"===e.type&&"string"==typeof e.uid)return void 0===e.properties||Array.isArray(e.properties)&&e.properties.every(e=>"string"==typeof e)?{commandId:e.commandId,type:e.type,uid:e.uid,properties:e.properties}:null;if("take_snapshot"===e.type&&("current"===e.target||"page"===e.target||"widget"===e.target))return{commandId:e.commandId,type:e.type,target:e.target};if("get_element_rect"===e.type&&"string"==typeof e.uid)return{commandId:e.commandId,type:e.type,uid:e.uid};if("take_screenshot"===e.type){let t=e.format??"png",r=e.quality;return void 0!==e.uid&&"string"!=typeof e.uid||"png"!==t&&"jpeg"!==t&&"webp"!==t||void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<0||r>100)?null:{commandId:e.commandId,type:e.type,format:t,uid:"string"==typeof e.uid?e.uid:void 0,quality:"number"==typeof r?r:void 0}}return"scroll_to"===e.type?(void 0===e.uid||"string"==typeof e.uid&&e.uid.trim())&&(void 0===e.x||tX(e.x))&&(void 0===e.y||tX(e.y))?{commandId:e.commandId,type:e.type,uid:"string"==typeof e.uid?e.uid:void 0,x:"number"==typeof e.x?e.x:void 0,y:"number"==typeof e.y?e.y:void 0}:null:null}(t.data);e&&this.emit({type:"control",data:e})}else"sandbox"===t.type&&(this.sandboxSnapshot=t.data,this.emit({type:"sandbox",data:t.data}))}},r.onclose=t=>{if(this.socket!==r)return;this.socket=void 0,this.sandboxSnapshot=void 0,void 0!==e&&Date.now()-e>=3e4&&(this.retryIndex=0);let n=rT[this.retryIndex++];void 0===n||1008===t.code||1009===t.code?this.setStatus("disconnected"):(this.setStatus("reconnecting"),this.retryTimer=setTimeout(()=>this.connect(),n))}}send(e){var t;if(new TextEncoder().encode(e).byteLength>0xa00000)throw Error("本地调试消息超过 10MiB,无法发送");if((null==(t=this.socket)?void 0:t.readyState)!==WebSocket.OPEN)throw Error("本地调试服务未连接");if(this.socket.bufferedAmount>0xa00000)throw this.socket.close(4e3,"Debugger connection is too slow"),Error("本地调试服务发送缓冲区已满");this.socket.send(e)}async reportResult(e){this.send(JSON.stringify({type:"control_result",data:e}))}async clearSandboxLogs(){this.send(JSON.stringify({type:"clear_sandbox_logs"}))}publishSnapshot(e,t){this.snapshot={payload:e,runtime:t},this.sendSnapshot()}sendSnapshot(){var e;if(!this.snapshot||(null==(e=this.socket)?void 0:e.readyState)!==WebSocket.OPEN)return;let{payload:t,runtime:r}=this.snapshot;try{let e=ry(t,{includeRuntimeRoot:r!==this.sentRuntime});this.send(rv({type:"snapshot",data:e})),this.sentRuntime=r,this.snapshotErrorReported=!1}catch(e){this.snapshotErrorReported||console.warn("调试快照上传失败,控制连接保持可用:",e),this.snapshotErrorReported=!0}}}var rA=r(64865),rP=r(11855);function rj(e){return e instanceof Map?Array.from(e.entries(),e=>{let[t,r]=e;return[String(t),r]}):!e||"object"!=typeof e||Array.isArray(e)||e instanceof ArrayBuffer?void 0:Object.entries(e)}function rL(e){return e.map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(null===r?"null":r&&"object"==typeof r?JSON.stringify(r)??String(r):String(r))}`}).join("&")}function rD(e){let t=new Uint8Array(e),r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}function rO(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"json";if("arraybuffer"===t)return e;let r=new TextDecoder().decode(e);if("string"===t||0===r.length)return r;try{return JSON.parse(r)}catch{return rD(e)}}function rU(e){let t={};return e.forEach((e,r)=>{t[r]=e}),t}function rq(e){var t;let r,n=(e.method??"GET").toUpperCase();if("GET"!==n&&"POST"!==n)throw Error(`Unsupported request method: ${n}`);let a="string"==typeof e.url?e.url:"",i=((r=new Headers(e.header)).has("content-type")||r.set("content-type","application/json"),r);return{body:"POST"===n?function(e,t){if(null!=e){if("string"==typeof e||e instanceof ArrayBuffer)return e;if(t.includes("application/x-www-form-urlencoded")){let t=rj(e);if(t)return rL(t)}return t.includes("application/json")||"object"==typeof e?JSON.stringify(e):String(e)}}(e.data,(null==(t=i.get("content-type"))?void 0:t.toLowerCase())??""):void 0,headers:rU(i),method:n,url:"GET"===n?function(e,t){let r=rj(t);if(!(null==r?void 0:r.length))return e;let n=e.indexOf("#"),a=-1===n?"":e.slice(n),i=-1===n?e:e.slice(0,n),s=i.endsWith("?")||i.endsWith("&")?"":i.includes("?")?"&":"?";return`${i}${s}${rL(r)}${a}`}(a,e.data):a}}async function r$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rq(e);if(!e.url)throw Error("url must be a non-empty string");let r=await fetch(t.url,{body:t.body,headers:t.headers,method:t.method}),n=rO(await r.arrayBuffer(),e.dataType);return{statusCode:r.status,header:rU(r.headers),data:n}}r(20303),r(99166),r(6106),r(22742),r(37553),r(62148),r(89055),r(12205),r(65850),r(65135),r(5876),r(94359),r(28016),r(38641),r(82247),r(11839),r(56109),r(63589);let rB=["connection","content-length","host","origin","referer"],rF="/__web_artifacts/base/manifest.json",rW="/app_developer";function rH(e){return!e.debugHidden}r(95600);let rz={chat:"chat","image-upload":"images/upload","tool-report":"tool/report"};function rV(e){let t=tR(String(e??rW).trim(),{addProtocolToBareHost:!0,allowRootRelative:!0,defaultProtocol:rG}).replace(/\/+$/,"");if(t.startsWith("/"))return t;try{let e=new URL(t);if(""===e.pathname||"/"===e.pathname)return e.pathname="/app_developer",e.toString().replace(/\/+$/,"")}catch{}return t}function rG(e){return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\])(?::|\/|$)/i.test(e)?"http":"https"}function rJ(e){var t;let r="function"==typeof(null==(t=globalThis.crypto)?void 0:t.randomUUID)?globalThis.crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2);return`${e}_${Date.now().toString(36)}${r.slice(0,10)}`}function rK(e,t){return`${rV(e)}/api/simulator/${rz[t]}`}function rX(e){if(e.type&&!e.type.startsWith("image/"))throw Error("仅支持图片文件");if(e.size>0xa00000)throw Error("图片不能超过 10 MiB")}var rZ=r(75585);let rQ=["ack","message_start","text_delta","tool_call","tool_status","card_delta","content_block","stream_error","message_finish","reply_finish","answer_finish","trace_event","heartbeat"];async function rY(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=e.getReader(),a=new TextDecoder,i={...r,fallbackSeq:0},s=(0,rZ.C)({onEvent:e=>{let r=function(e,t){var r,n,a;let i,s,o,l,d,u,c=void 0===(l=t1(r=e.data))&&r.trim()?r:l,p=tj(c)?{...c,event:c.event||e.event}:{event:e.event||"message",data:c},{eventType:h,payload:m}=function(e){var t;for(let t of rQ){let r=e[t];if(tj(r))return{eventType:t,payload:r};if("content_block"===t&&Array.isArray(r))return{eventType:t,payload:{content_block:r}}}return{eventType:"string"==typeof(t=e.event)&&t?t.toLowerCase():"message",payload:e}}(p),g=tj(m)?m:{},f="number"==typeof p.sequence&&Number.isFinite(p.sequence)?p.sequence:t.fallbackSeq+=1,v=e.id||("string"==typeof p.id?p.id:"")||`evt_${f.toString().padStart(4,"0")}`,y=function(e,t,r){let n=("string"==typeof e.request_id?e.request_id:"")||("ack"===r&&"string"==typeof t.request_id?t.request_id:"");if("ack"===r&&!n)throw Error("Invalid simulator SSE ACK: missing request_id");return n||("string"==typeof e.id?e.id:"")}(p,g,h),_=("string"==typeof p.reply_message_id?p.reply_message_id:"")||("string"==typeof g.message_id?g.message_id:"")||t.replyMessageId;return{event_id:v,event_type:h,seq:f,request_id:y,query_message_id:("string"==typeof p.query_message_id?p.query_message_id:"")||("string"==typeof g.query_message_id?g.query_message_id:""),reply_message_id:_,created_at_ms:"number"==typeof p.timestamp_ms&&Number.isFinite(p.timestamp_ms)?p.timestamp_ms:Date.now(),received_at_ms:Date.now(),trace:(d=tj(p.trace)?p.trace:{},{trace_id:"string"==typeof(u=t.trace??{}).trace_id?u.trace_id:"string"==typeof d.trace_id?d.trace_id:rJ("trace"),span_id:"string"==typeof d.span_id?d.span_id:rJ("span_sse"),parent_span_id:"string"==typeof d.parent_span_id?d.parent_span_id:"string"==typeof u.span_id?u.span_id:void 0,component:"string"==typeof d.component?d.component:"app_developer_simulator",stage:"string"==typeof d.stage?d.stage:h,sampled:"boolean"==typeof d.sampled?d.sampled:"boolean"!=typeof u.sampled||u.sampled,baggage:{...tj(u.baggage)?u.baggage:{},...tj(d.baggage)?d.baggage:{}}}),payload:(n=g,0===(o=Array.isArray(s=tj(i=null==(a=t.trace)?void 0:a.baggage)?i.log_ids:void 0)?s.filter(e=>"string"==typeof e&&e.trim().length>0):"string"==typeof s&&s.trim()?[s]:[]).length||void 0!==n.log_ids?n:{...n,log_ids:o})}}(e,i);r.reply_message_id&&(i.replyMessageId=r.reply_message_id),t(r)}});for(;;){let{done:e,value:t}=await n.read();if(t&&s.feed(a.decode(t,{stream:!e})),e)break}let o=a.decode();o&&s.feed(o),s.feed("\n\n")}let r0="x-tt-logid";class r1 extends Error{responseDebug;constructor(e,t){super(e),this.responseDebug=t,this.name="SimulatorHttpError"}}function r2(e){return e.headers.get(r0)}function r3(e){let t={},r=r2(e);return r&&(t[r0]=r),t}function r4(e){return tj(e.trace)?e.trace:{}}async function r5(e,t){let r=r2(t),n=r3(t),a=await t.text().catch(()=>""),i={status:t.status,status_text:t.statusText,response_headers:Object.keys(n).length>0?n:void 0,log_ids:r?[r]:void 0,response_text:a};return new r1(`${e}: ${t.status} ${t.statusText}`,i)}function r6(e){return e instanceof r1?e.responseDebug:void 0}function r8(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},a=arguments.length>4?arguments[4]:void 0,i=r4(e),s=Date.now();return{event_id:rJ("evt_client_debug"),event_type:"debug",seq:0,request_id:"string"==typeof e.idempotency_key?e.idempotency_key:"client_debug",created_at_ms:s,received_at_ms:s,trace:{trace_id:"string"==typeof i.trace_id?i.trace_id:rJ("trace"),component:"string"==typeof i.component?i.component:"simulator_web_tester",stage:"string"==typeof i.stage?i.stage:"query",sampled:"boolean"!=typeof i.sampled||i.sampled,baggage:a??(tj(i.baggage)?i.baggage:{})},payload:{event:t,category:"api",elapsed_ms:Date.now()-r,...n}}}async function r7(e){var t;let{endpoint:r,fetcher:n,file:a,signal:i}=e;rX(a);let s=new FormData;s.append("image",a);let o=await (n??fetch)(rK(r,"image-upload"),{method:"POST",headers:{Accept:"application/json"},body:s,signal:i});if(!o.ok)throw await r5("Simulator image upload failed",o);let l=await o.json();if(0!==l.code)throw new r1(l.message||`Simulator image upload failed with code ${l.code}`,{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});let d=null==(t=l.data)?void 0:t.image;if(!(null==d?void 0:d.resource_uri))throw new r1("Simulator image upload response is missing image.resource_uri",{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});return d}async function r9(e){let t,{endpoint:r,fetcher:n,onEvent:a,onSubmitted:i,request:s,signal:o}=e,l=Date.now(),d=rK(r,"chat");a(r8(s,"simulator_chat_fetch_started",l,{endpoint:"chat",phase:"request",request:s,request_json:t3(s),url:d}));let u=setTimeout(()=>{a(r8(s,"simulator_chat_fetch_waiting_for_headers",l,{endpoint:"chat",phase:"wait",url:d,wait_ms:5e3}))},5e3);try{let e=(n??fetch)(d,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(s),signal:o});null==i||i(),t=await e}catch(e){throw clearTimeout(u),a(r8(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",url:d,error:t4(e)})),e}clearTimeout(u);let c=r2(t),p=r3(t),h=r4(s),m={...tj(h.baggage)?h.baggage:{}};if(c&&(m[r0]=c,m.log_ids=[c]),a(r8(s,"simulator_chat_headers_received",l,{event:"simulator_chat_response_meta",endpoint:"chat",phase:"response",status:t.status,status_text:t.statusText,log_ids:c?[c]:void 0,response_headers:Object.keys(p).length>0?p:void 0},m)),!t.ok){let e=await r5("Simulator query failed",t);throw a(r8(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",error:e.message,...e.responseDebug},m)),e}if(!t.body)throw Error("Simulator query response has no SSE body");let g=0,f=!1,v=setTimeout(()=>{f||a(r8(s,"simulator_chat_sse_waiting_for_first_event",l,{endpoint:"chat",wait_ms:5e3},m))},5e3);try{await rY(t.body,e=>{g+=1,f||(f=!0,clearTimeout(v)),a(e)},{trace:{...h,baggage:m}})}catch(e){throw clearTimeout(v),a(r8(s,"simulator_chat_sse_read_failed",l,{endpoint:"chat",phase:"error",event_count:g,error:t4(e)},m)),e}clearTimeout(v)}async function ne(e){let{endpoint:t,fetcher:r,result:n,signal:a}=e,i=await (r??fetch)(rK(t,"tool-report"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(n),signal:a});if(!i.ok)throw await r5("Simulator tool result failed",i);let s=await nt(i),o=r2(i);return{...s,response_headers:o?{...tj(s.response_headers)?s.response_headers:{},[r0]:o}:s.response_headers,log_ids:o?[o]:s.log_ids}}async function nt(e){let t=await e.text().catch(()=>"");if(!t.trim())return{};try{let e=JSON.parse(t);return tj(e)?e:{response_body:e}}catch{return{response_text:t}}}let nr={label:"Request",tone:"request"},nn={label:"Response",tone:"response"},na={simulator_query_prepare_started:{debugOnly:!0,title:"Query Prepare Started"},simulator_query_mcp_resolved:{debugOnly:!0,title:"MCP Ready"},simulator_query_aborted:{title:"Query Aborted"},simulator_query_failed:{title:"Query Failed"},simulator_query_cancel_requested:{title:"Query Cancel Requested"},simulator_chat_fetch_started:{badge:nr,title:"Chat"},simulator_chat_fetch_waiting_for_headers:{title:"Chat Waiting"},simulator_chat_response_meta:{badge:nn,title:"Chat"},simulator_chat_fetch_failed:{badge:nn,title:"Chat Failed"},simulator_chat_sse_waiting_for_first_event:{title:"Chat Waiting"},simulator_chat_sse_read_failed:{title:"Chat Stream Failed"},simulator_query_stream_returned:{title:"Chat Complete"},local_mcp_tools_load_started:{badge:nr,debugOnly:!0,title:"MCP Load"},local_mcp_tools_loaded:{badge:nn,debugOnly:!0,title:"MCP Load"},local_mcp_tools_load_failed:{badge:nn,title:"MCP Load Failed"},local_mcp_missing:{title:"MCP Missing"},local_mcp_call_started:{badge:nr,title:e=>`MCP Tool${e}`},local_mcp_call_succeeded:{badge:nn,title:e=>`MCP Tool${e}`},local_mcp_call_failed:{badge:nn,title:e=>`MCP Tool Failed${e}`},tool_result_report_started:{badge:nr,title:e=>`Report Tool Result${e}`},tool_result_report_response_received:{badge:nn,title:e=>`Report Tool Result${e}`},tool_result_report_failed:{badge:nn,title:e=>`Report Tool Result Failed${e}`},tool_result_ack:{title:"Report ACK"},tool_result_submit_skipped:{title:e=>`Report Tool Result Skipped${e}`},tool_result_submit_failed:{badge:nn,title:e=>`Report Tool Result Failed${e}`},tool_executor_missing:{title:e=>`Tool Executor Missing${e}`},tool_call_ignored:{title:e=>`Tool Call Ignored${e}`},tool_call_event_skipped:{title:e=>`Tool Call Skipped${e}`},tool_call_request_id_mismatch:{title:e=>`Tool Call Request Mismatch${e}`},tool_call_server_id_fallback:{title:e=>`Tool Call Server Fallback${e}`},simulator_card_rendered:{title:"Card Rendered"},simulator_card_render_skipped:{title:"Card Render Skipped"},simulator_card_render_failed:{title:"Card Render Failed"},simulator_card_runtime_error:{title:"Card Render Failed"},simulator_manifest_load_started:{badge:nr,debugOnly:!0,title:"Manifest Load"},simulator_manifest_loaded:{badge:nn,debugOnly:!0,title:"Manifest Load"},simulator_manifest_load_failed:{badge:nn,title:"Manifest Load Failed"},simulator_manifest_fetch_started:{badge:nr,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_succeeded:{badge:nn,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_failed:{badge:nn,title:"Manifest Fetch Failed"},simulator_manifest_missing:{title:"Manifest Missing"},simulator_skill_load_started:{badge:nr,debugOnly:!0,title:"Skill Load"},simulator_skill_loaded:{badge:nn,debugOnly:!0,title:"Skill Load"},simulator_skill_empty:{badge:nn,debugOnly:!0,title:"Skill Empty"},simulator_skill_load_failed:{badge:nn,title:"Skill Load Failed"},simulator_skill_fetch_started:{badge:nr,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_succeeded:{badge:nn,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_failed:{badge:nn,title:"Skill Fetch Failed"},simulator_skill_missing:{title:"Skill Missing"},simulator_resources_check_started:{debugOnly:!0,title:"Resource Check Started"},simulator_resources_check_completed:{debugOnly:!0,title:"Resource Check Completed"},simulator_resource_reload_completed:{title:"Resource Reloaded"}};function ni(e){if(!tj(e))return;let t=ns(e);return{category:t.category,debugOnly:t.debugOnly,detail:t.detail,leftBadges:t.transportBadge?[t.transportBadge]:void 0,phase:t.phase,title:t.title}}function ns(e){var t,r;let n=e.event||"",a=na[n],i=e.detail??e.data??e,s=e.title?t6(e.title):function(e,t){var r;let n=null==(r=na[e])?void 0:r.title;if("function"==typeof n){let e;return n((e=t.tool_name||t.tool_call_id)?`: ${e}`:"")}return n||(e?t6(e):"Agent Trace Event")}(n,e),o=e.category?t5(e.category):(t=n).startsWith("local_mcp_")?"mcp":t.startsWith("tool_result_report_")||"tool_result_ack"===t?"api":t.startsWith("tool_result_")||t.startsWith("tool_call_")||"tool_executor_missing"===t?"agent":t.startsWith("simulator_card_")?"card":t.startsWith("simulator_manifest_")||t.startsWith("simulator_skill_")||t.startsWith("simulator_resource_")||t.startsWith("simulator_resources_")?"resource":t.startsWith("simulator_chat_")?"api":t.startsWith("simulator_query_")?"agent":"runtime",l=e.phase||("local_mcp_missing"===(r=n)?"error":/(started|starting)$/.test(r)?"request":/(completed|loaded|resolved|received|returned|succeeded|rendered)$/.test(r)?"response":/(failed|error|aborted|rejected)$/.test(r)?"error":/(empty|skipped|ignored|mismatch|fallback|cancel_requested)$/.test(r)?"status":"tool_result_ack"===r?"ack":"event");return{category:o,debugOnly:(null==a?void 0:a.debugOnly)===!0,detail:i,eventName:n,phase:l,title:s,transportBadge:null==a?void 0:a.badge}}function no(e){return e.blocks.some(e=>"card"===e.type&&"permission_apply"===e.card.card_type)}function nl(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{messages:r,streamStatus:n}=e.getState().simulator,a=function(e,t){let r=t?e.findIndex(e=>e.messageId===t):e.findLastIndex(no);if(-1===r)return;let n=e[r];if(no(n))for(let t=r-1;t>=0;t--){let r=e[t],a="user"===r.role?r.blocks.filter(e=>"image"===e.type).map(e=>e.image):[];if("user"===r.role&&(r.text.trim()||a.length>0))return{followUpContent:r.followUpContent,images:a.length>0?a:void 0,messageIds:[r.messageId,n.messageId],query:r.text.trim()}}}(r,t.grantingMessageId);if(!a)return{status:"not_found"};if("streaming"===n)return{status:"streaming"};e.removeSimulatorMessages(a.messageIds);let i=t.noLogin?{noLogin:!0}:{};return{completion:a.followUpContent?e.sendSimulatorFollowUpMessage(a.followUpContent,i):e.sendSimulatorQuery(a.query,{images:a.images,...i}),status:"started",target:a}}function nd(e){if(!tj(e))return;let t="string"==typeof e.grantingName?e.grantingName:"";if(t){var r;let n;return{grantingName:t,permissionStatus:"string"==typeof e.permissionStatus?e.permissionStatus:"pending",priorityLevel:"number"==typeof e.priorityLevel?e.priorityLevel:0,relatedData:{...n=t2(r=e.relatedData)??(tj(r)?r:{}),bizLoginDescription:"string"==typeof n.bizLoginDescription?n.bizLoginDescription:"",bizPrivacyContent:"string"==typeof n.bizPrivacyContent?n.bizPrivacyContent:"",mobileMask:"string"==typeof n.mobileMask?n.mobileMask:"",privacyURL:"string"==typeof n.privacyURL?n.privacyURL:"",scopeDescription:"string"==typeof n.scopeDescription?n.scopeDescription:"",scopeName:"string"==typeof n.scopeName?n.scopeName:"",termsOfServiceURL:"string"==typeof n.termsOfServiceURL?n.termsOfServiceURL:""},required:!1!==e.required}}}function nu(e){let t=t2(e);if(!t)return;let r=Array.isArray(t.grantingList)?t.grantingList.map(nd).filter(e=>!!e):[];if(0!==r.length)return{cardStatus:"string"==typeof t.cardStatus?t.cardStatus:"unexpired",doubaoAppletIcon:"string"==typeof t.doubaoAppletIcon?t.doubaoAppletIcon:"",doubaoAppletKey:"string"==typeof t.doubaoAppletKey?t.doubaoAppletKey:"",doubaoAppletName:"string"==typeof t.doubaoAppletName&&t.doubaoAppletName?t.doubaoAppletName:"应用插件",doubaoAppletVersion:"string"==typeof t.doubaoAppletVersion?t.doubaoAppletVersion:"",grantingList:r,raw:t}}function nc(e){var t;switch(null==(t=e.grantingList[0])?void 0:t.grantingName){case"permission":return"权限申请";case"privacy":return"隐私协议提示";default:return"登录授权"}}r(66249);let np="miniapp_packet_10066";function nh(e,t,r,n,a){let i=e.find(e=>e.messageId===t);return i?n&&!i.requestId||a&&!i.traceId?e.map(e=>e===i?{...e,requestId:e.requestId||n,traceId:e.traceId||a}:e):e:[...e,{messageId:t,requestId:n,traceId:a,role:"assistant",contentType:"mixed",text:"",blocks:[],status:"streaming",createdAtMs:r}]}function nm(e,t,r){return e.map(e=>e.messageId===t?r(e):e)}function ng(e,t,r,n){let a={blockId:t,type:"card",card:r};if("replace"===n){let n=r.card_id,i=e.map(e=>e.blockId===t||"card"===e.type&&n&&e.card.card_id===n?a:e);return i.some(e=>e===a)?i:[...e,a]}return e.some(e=>e.blockId===t)?e.map(e=>e.blockId===t?a:e):[...e,a]}function nf(e,t,r){let n=!1,a=!1,i=e.map(e=>{let i=!1,s=e.blocks.map(e=>{if("card"!==e.type||e.card.card_id!==t)return e;n=!0;let s=r(e.card);return s?(a=!0,i=!0,{...e,card:s}):e});return i?{...e,blocks:s}:e});return{messages:a?i:e,found:n,updated:a}}function nv(e){return"debug"===e.event_type?e.payload.data??e.payload:e.payload}function ny(e){let t=e.payload.tool_name||e.payload.tool_call_id,r=e.payload.status;switch(e.event_type){case"ack":return"Chat ACK";case"tool_call":return`Tool Call${t?`: ${t}`:""}`;case"tool_status":return`Tool Status${t?`: ${t}`:""}${r?` (${r})`:""}`;case"card_delta":return"Card Received";case"answer_finish":return"Answer Finished";case"message_finish":return"Message Finished";case"reply_finish":return"Reply Finished";case"stream_error":return"Stream Error";case"trace_event":return t6(e.payload.title||"Agent Trace");case"heartbeat":return"Heartbeat";default:return t6(e.event_type)}}function n_(e){let t=e.payload.category;if(t)return t5(t);switch(e.event_type){case"tool_call":case"tool_status":case"trace_event":default:return"agent";case"card_delta":return"card";case"debug":return"debug"}}function nb(e){switch(e){case"ack":return"accepted";case"message_start":return"message_start";case"text_delta":return"text_delta";case"tool_call":return"request";case"tool_status":return"response";case"card_delta":return"card_delta";case"message_finish":case"reply_finish":case"answer_finish":return"finish";case"stream_error":return"error";case"trace_event":return"trace";default:return e}}function nw(e){return"u">typeof DOMException&&e instanceof DOMException?"AbortError"===e.name:e instanceof Error&&"AbortError"===e.name}function nS(e,t){if(tj(e)&&"code"in e&&"message"in e)return e;let r=tj(e)&&tj(e.responseDebug)?e.responseDebug:void 0,n=t2(null==r?void 0:r.response_text),a="string"==typeof(null==n?void 0:n.message)&&n.message.trim()?n.message.trim():"string"==typeof(null==r?void 0:r.response_text)&&r.response_text.trim()?r.response_text.trim():"";return{code:("string"==typeof(null==n?void 0:n.code)||"number"==typeof(null==n?void 0:n.code)?String(n.code):void 0)??"INTERNAL_ERROR",message:a||t4(e),retryable:!1,stage:t,details:r?{response:r,response_body:n}:void 0}}function nx(e,t){if(e||t)return{...e,...t}}function nI(e,t){var r;let n=(null==(r=e.traceEvents.at(-1))?void 0:r.order)??e.traceEvents.length;return{...e,traceEvents:[...e.traceEvents,{...t,order:n+1}].slice(-200)}}function nk(e,t,r){var n;let a=function(e){let t=tj(e.card)?e.card:{},r=tj(t.state)?t.state:{},n=e.card_id,a=r.widget_id;if("update_state"!==e.op||"miniapp_history_refresh"!==t.card_type||"fixed_style"!==r.refresh_to||!n||!a)return;let i=r.url||r.schema,s=r.title,o=r.detailText;return{cardId:n,state:r,widgetData:{url:i,title:s,detailText:o},widgetId:a}}(t);if(a){let t=nf(e.messages,a.cardId,e=>{let t=e.state??{};if("fixed"!==t.lifecycle_state)return{...e,render_data:{viewData:a.widgetData},widget_id:a.widgetId,state:{...t,...a.state,lifecycle_state:"fixed"}}});return{state:{...e,messages:t.messages},cardRefresh:{cardId:a.cardId,status:t.updated?"updated":t.found?"already_fixed":"not_found"}}}let i=function(e){let t=e.card;if(!tj(t)||t.card_type!==np)return;let r=e.card_id||t.card_id,n=t2(t.props_json),a=tj(null==n?void 0:n._meta)?n._meta:void 0,i=tj(t.render_data)?t.render_data:void 0,s=tj(null==i?void 0:i.ext)?i.ext:void 0;if(!r||!n||!a||!i||!s||!0!==a.skip_response_validate||"2"!==i.packet_type||"1"!==s._auth_request||"none"!==s.auth_require||"1"!==s.from_mcp||"1"!==s.is_mini_app||"string"!=typeof n.direct_return)return;let o=t2(n.direct_return);if((null==o?void 0:o.mcp_channel)==="flow_miniapp"&&Array.isArray(o.chunk_messages))for(let t of o.chunk_messages){if(!tj(t)||!0!==t.IsFinish||2!==t.MessageType||1005!==t.ContentType||"string"!=typeof t.Content)continue;let n=t2(t.Content);if((null==n?void 0:n.command_type)==="require_location"&&tj(n.require_location))return{cardId:r,appKey:s.app_key,sourceToolCallId:e.source_tool_call_id,toolName:s.tool_name}}}((null==r?void 0:r.payload)??{});if(i&&r)return{state:e,locationDirective:{...i,requestId:r.request_id,queryMessageId:r.query_message_id,replyMessageId:r.reply_message_id??e.activeReplyMessageId}};let s=(null==r?void 0:r.reply_message_id)??e.activeReplyMessageId,o=function(e){var t,r;let n,a=e.card;if(!tj(a))return{};let i=t2(a.props_json)??{},s=function(e){let t,r;if(e.card_type!==np)return;let n=t2(e.props_json)||t2(e.render_data_json)||(tj(e.render_data)?t2(e.render_data.content_for_display):void 0)||{};return n.permission_data||((r=(Array.isArray(null==(t=tj(n.structuredContent)?n.structuredContent:void 0)?void 0:t.entity_list)?t.entity_list:[]).find(e=>tj(e)&&(Array.isArray(e.grantingList)||tj(e._meta)&&!0===e._meta.is_permission)))&&tj(r)?JSON.stringify(r):void 0)}(a),o=nu(s),l=tj(i.extra)?i.extra:{},d=Object.keys(i).length>0?(n=t2(i.widget_data))?{viewData:n}:tj(i.viewData)?{viewData:i.viewData}:{viewData:i}:void 0,u={...tj(a.source)?a.source:{},tool_call_id:e.source_tool_call_id||(null==(t=a.source)?void 0:t.tool_call_id),entity_ids:Array.isArray(e.source_entity_ids)?e.source_entity_ids:null==(r=a.source)?void 0:r.entity_ids};return{...{card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type,app_id:e.app_id},...a,widget_id:i.widget_id||a.widget_id||e.widget_id,app_id:i.applet_id||a.app_id||e.app_id,entity_id:i.entity_id||a.entity_id,source:u,card_type:o?"permission_apply":a.card_type||e.card_type,fallback_text:o?a.fallback_text||"需要授权后继续":a.fallback_text,render_data:o?{grantingData:o,permissionData:s}:d||a.render_data,title:o?a.title||nc(o):a.title,debug:{...tj(a.debug)?a.debug:{},props_json:a.props_json,output_template:l["doubao/outputTemplate"]}}}(t),l=t.block_id||o.card_id||(n=`card_${(null==r?void 0:r.seq)??0}`,o.card_id||o.title||n),d=t.op||"append";if("append"!==d&&"replace"!==d)return{state:e};if(o.card_id){let t=nf(e.messages,o.card_id,e=>{let t,n,a,i;return r?o:(t=nx(e.state,o.state),n=nx(e.source,o.source),a=nx(e.debug,o.debug),i=Object.fromEntries(Object.entries(o).filter(e=>{let[,t]=e;return void 0!==t})),{...e,...i,state:t,source:n,debug:a})});if(t.found)return{state:{...e,messages:t.messages},cardRefresh:{cardId:o.card_id,status:"updated"}}}if(!s)return{state:e};let u=nh(e.messages,s,(null==r?void 0:r.created_at_ms)??Date.now(),null==r?void 0:r.request_id,null==r?void 0:r.trace.trace_id);return{state:{...e,messages:nm(u,s,e=>({...e,contentType:"mixed",blocks:ng(e.blocks,l,o,d)}))}}}function nC(e,t){let r="completed"===t?"completed":"cancelled"===t?"interrupted":"failed";return e.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:r}:e)}function nE(e,t,r){return{...e,toolCalls:e.toolCalls.map(e=>e.toolCallId===t?{...e,...r}:e)}}function nN(e,t){let r={tool_call_id:t.toolCallId,tool_name:t.toolName,arguments_summary:t.arguments&&Object.keys(t.arguments).length>0?t.arguments:void 0,status:t.status},n=e.findIndex(e=>e.tool_call_id===t.toolCallId);return n<0?[...e,r]:e.map((e,t)=>t===n?r:e)}var nM=r(33680);function nT(e,t){var r,n;return null==e||null==(n=e.tools)||null==(r=n[t])?void 0:r.output}function nR(e,t,r){if(!tj(e)||!Array.isArray(e.structuredContent))return e;let n=nT(t,r);if(!n||"entities"!==n.kind)return e;if(!e.structuredContent.every(tj))throw Error(`Tool "${r}" structuredContent items must be objects`);return{...e,structuredContent:{entities:e.structuredContent.map(e=>({...e,entity_type:r}))}}}function nA(e,t){let r;if(!tj(e)||!Array.isArray(e.content))throw Error("MCP tool result must be an object with a content array");let n=void 0===(r=e.structuredContent)?{}:r,a=t3(e),i=e.content.filter(tj).map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"),s=!0===e.isError;return{status:s?"failed":"succeeded",result:n,error:s?{code:t.businessErrorCode,message:tj(n)&&"string"==typeof n.message?n.message:i||a,retryable:!1,stage:"tool_execute",details:tj(n)?n:{structuredContent:n}}:void 0,raw_result_text:i,raw_mcp_result_json:a,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:t.source,protocol:t.protocol,mcp_output:e}}}let nP="client_tool",nj="__bridge_ready__",nL="lynxview";function nD(e,t){null==e||e({category:"mcp",source:"client_tool",...t})}class nO{runtimeUrl;container;errorListeners=new Set;host;messageListeners=new Set;view=null;constructor(e,t){this.runtimeUrl=e,this.host=function(){var e;if(!(null==(e=globalThis.document)?void 0:e.body))throw Error("Client Tool LynxView runtime requires document.body");let t=document.createElement("div");return t.dataset.doubaoClientToolRuntime="true",t.style.display="none",document.body.append(t),t}(),this.container=new tz({className:"doubao-client-tool-runtime-view",container:this.host,nativeModulesCallHandler:this.handleNativeModulesCall,onError:e=>this.emitError(e),onReady:()=>this.emitMessage({type:"event",name:nj})}),this.view=this.container.render({containerType:"TOOL",globalProps:t,initData:{},resourceUrl:e}),this.view.style.display="none"}addEventListener(e,t){"message"===e?this.messageListeners.add(t):this.errorListeners.add(t)}removeEventListener(e,t){"message"===e?this.messageListeners.delete(t):this.errorListeners.delete(t)}postMessage(e){this.container.sendGlobalEvent("__APPLET_BRIDGE__",[e])}terminate(){this.messageListeners.clear(),this.errorListeners.clear(),this.container.clear(),this.host.remove(),this.view=null}handleNativeModulesCall=(e,t,r)=>{if("AppletBridgeModule"===r&&"postMessage"===e&&tj(t)&&nq(t))return this.emitMessage(t),t};emitMessage(e){let t={data:e};for(let e of this.messageListeners)e(t)}emitError(e){let t=new ErrorEvent("error",{error:e,message:e.message});for(let e of this.errorListeners)e(t)}}function nU(e){return Object.assign(Error(e),{name:"AbortError"})}function nq(e){return"callback"===e.type&&"number"==typeof e.callbackId}class n${runtimeUrl;runtime;onTraceEvent;callbackId=1;ready=!1;readyPromise;rejectReady;resolveReady;pendingCallbacks=new Map;constructor(e,t,r){this.runtimeUrl=e,this.runtime=t,this.onTraceEvent=r,this.runtime.addEventListener("message",this.handleMessage),this.runtime.addEventListener("error",this.handleError)}async invokeTool(e){await this.ensureReady(e.signal);let{signal:t,...r}=e;return this.call("applet.invokeTool",r,{signal:t})}dispose(){var e;let t=Error("Client Tool runtime was disposed");for(let r of(this.runtime.removeEventListener("message",this.handleMessage),this.runtime.removeEventListener("error",this.handleError),this.runtime.terminate(),null==(e=this.rejectReady)||e.call(this,t),this.pendingCallbacks.values()))r.reject(t);this.pendingCallbacks.clear()}ensureReady(e){if(null==e?void 0:e.aborted)return Promise.reject(nU("Client Tool call aborted"));if(this.ready)return Promise.resolve();let t=this.readyPromise??(this.readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}));return e?new Promise((r,n)=>{let a=()=>{e.removeEventListener("abort",a),n(nU("Client Tool call aborted"))};e.addEventListener("abort",a,{once:!0}),t.then(()=>{e.removeEventListener("abort",a),r()},t=>{e.removeEventListener("abort",a),n(t)}),e.aborted&&a()}):t}call(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.callbackId;return this.callbackId+=1,new Promise((a,i)=>{let{signal:s}=r;if(null==s?void 0:s.aborted)return void i(nU("Client Tool call aborted"));let o=()=>{null==s||s.removeEventListener("abort",l)},l=()=>{this.pendingCallbacks.delete(n),i(nU("Client Tool call aborted"))};null==s||s.addEventListener("abort",l,{once:!0}),this.pendingCallbacks.set(n,{reject:e=>{o(),i(e)},resolve:e=>{o(),a(e)}}),this.runtime.postMessage({type:"call",name:e,params:t,callbackId:n,target:{scope:"main",target:"self"}})})}handleMessage=e=>{var t;let r,n=tj(r="string"==typeof e.data?t1(e.data):e.data)?r:void 0;if(!n)return;if("event"===n.type&&n.name===nj){this.ready=!0,null==(t=this.resolveReady)||t.call(this),nD(this.onTraceEvent,{event:"client_tool_runtime_ready",runtime_url:this.runtimeUrl});return}if(!nq(n))return;let a=this.pendingCallbacks.get(n.callbackId);if(a){this.pendingCallbacks.delete(n.callbackId);try{a.resolve(function(e){let t=tj(e.params)?e.params:{};if(1===t.code)return t.data;throw Error("string"==typeof t.msg&&t.msg||`Client Tool runtime callback failed with code ${String(t.code)}`)}(n))}catch(e){a.reject(e)}}};handleError=e=>{var t;let r=Error(e.message||"Client Tool runtime failed");for(let e of(null==(t=this.rejectReady)||t.call(this,r),this.pendingCallbacks.values()))e.reject(r);this.pendingCallbacks.clear()}}function nB(e,t,r){return{status:"failed",result:{error:t},error:{code:e,message:t,retryable:r,stage:"tool_execute"},raw_result_text:t,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:"client_tool",protocol:nL}}}let nF="simulator_web_tester";function nW(e){var t,r,n;let a=(t=e.messages,r=e.toolCalls,n=e.historyMaxTurns,t.slice(-Math.max(0,2*n)).map(e=>{var t,n,a;let i,s,o,l=(t=e,(i=r.filter(e=>e.replyMessageId===t.messageId&&nV(e.status)).map(e=>({tool_call_id:e.toolCallId,tool_name:e.toolName,arguments_summary:e.arguments&&Object.keys(e.arguments).length>0?e.arguments:void 0,status:e.status}))).length>0?i:(t.toolCalls??[]).filter(e=>nV(e.status))),d=(n=e,(s=r.filter(e=>e.replyMessageId===n.messageId&&nV(e.status)).map(e=>{var t;let r=e.resultSummary?e.resultSummary:(null==(t=e.error)?void 0:t.message)?e.error.message:e.message;return{tool_call_id:e.toolCallId,tool_name:e.toolName,result_summary:r,structured_summary:e.structuredResultSummary,is_mini_app:e.isMiniApp}})).length>0?s:n.toolResults??[]),u=nz(e.blocks.flatMap(e=>"image"===e.type?[e.image]:[]));return{role:"assistant"===e.role?"ASSISTANT":"USER",content:(o=(a=e).text?a.text:a.blocks.filter(e=>"text"===e.type).map(e=>e.text).join(""))||e.blocks.map(e=>{var t;return"image"===e.type?e.image.name?`[图片:${e.image.name}]`:"[图片]":"card"===e.type?(t=e.card).fallback_text||t.title||t.card_type||t.card_id||"卡片":e.text}).filter(Boolean).join("\n"),parts:u.length>0?u:void 0,tool_calls:l.length>0?l.map(e=>({tool_call_id:e.tool_call_id,tool_name:e.tool_name,arguments:e.arguments_summary,status:e.status})):void 0,tool_results:d.length>0?d.map(e=>({tool_call_id:e.tool_call_id,tool_name:e.tool_name,result_summary:e.result_summary,structured_summary:e.structured_summary,is_mini_app:e.is_mini_app})):void 0}})),i=nH(e.messages),s=e.simulatorManifest||e.options.manifest||{},o=s.app_key||"",l=e.options.appKey||e.simulatorAppKey||o||e.manifestAppId||"web-sdk-debugger",d=e.options.appName||e.simulatorAppName||e.manifestAppName||l,u=(e.options.skills??e.simulatorSkills??[]).map(e=>e.content),c=e.options.mcpServers??e.simulatorMcpServers,p=function(e,t){let r=e.raw_manifest_yaml||"",n=t.find(e=>e.server_id===nP&&e.tools.length>0);if(!n||!e.tools||null!=e.mcp_server)return r;let a=function(e){if(!e.trim())throw Error("Client Tool simulator manifest requires raw_manifest_yaml");let t=(0,nM.qg)(e);if(!tj(t))throw Error("Client Tool raw_manifest_yaml must contain a YAML object");return t}(r);return null!=a.mcp_server?r:(0,nM.As)({...a,mcp_server:{end_point:n.server_id,description:n.description||n.name}})}(s,c);return{app_id:l,scene:"miniapp_simulator_web_tester",history_messages:a,card_snapshots:i,trace:{trace_id:e.traceId,component:nF,stage:"query",sampled:!0},client:{platform:"web",locale:"zh-CN",timezone:function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"Asia/Shanghai"}}()},ext:{web_tester:"true",stateless_context:"client_history",skill_source:u.length>0?"local_file":"none",no_login:e.options.noLogin?"true":void 0},max_step:e.options.maxStep??e.simulatorMaxStep??20,protocol_version:"v2",idempotency_key:e.idempotencyKey,mini_apps:[{app_key:l,app_name:d,skills:u,manifest:{app_key:l,app_name:d,raw_manifest_yaml:p},mcp_servers:c.map(e=>({server_id:e.server_id,name:e.name,description:e.description||"",tools:e.tools.map(e=>({name:e.name,description:e.description||"",input_schema_json:t3(e.input_schema_json)}))}))}],web_capabilities:{supports_debug_event:!0}}}function nH(e){let t=new Map;for(let r of e)for(let e of r.blocks){if("card"!==e.type)continue;let r=function(e){var t,r,n;let a=t2(null==(t=e.debug)?void 0:t.props_json),i=e.card_id,s=(null==a?void 0:a.applet_id)||e.app_id,o=(null==a?void 0:a.entity_id)||e.entity_id;if(i&&s)return{card_id:i,app_key:s,business_entity_ids:o?[o]:void 0,lifecycle_state:(null==(r=e.state)?void 0:r.lifecycle_state)==="fixed"||(null==(n=e.state)?void 0:n.lifecycle_state)===2?2:1,refresh_key:e.refresh_key}}(e.card);r&&t.set(r.card_id,r)}return[...t.values()]}function nz(e){return e.map(e=>({type:"image",image:{resource_uri:e.resource_uri}}))}function nV(e){return["succeeded","failed","timeout","cancelled","rejected"].includes(e)}function nG(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"tool_execute",n=arguments.length>3?arguments[3]:void 0;return{code:e,message:t,user_message:t,retryable:!1,stage:r,details:n}}async function nJ(e){let t,r,n,a,i,s,{executor:o,input:l,record:d,signal:u}=e,c=(t=void 0===d.deadlineMs?void 0:d.deadlineMs-Date.now(),r=d.timeoutMs,void 0===(n=void 0===t?r:void 0===r?t:Math.min(t,r))?void 0:Math.max(0,n)),p=nG("TOOL_EXEC_CANCELLED","Tool execution cancelled"),h=void 0===c?void 0:new AbortController,m=(null==h?void 0:h.signal)??u;if(null==u?void 0:u.aborted)throw p;if(h&&u){let e=()=>{h.abort()};u.addEventListener("abort",e,{once:!0}),i=()=>u.removeEventListener("abort",e)}let g=[Promise.resolve(o({...l,signal:m}))];if(void 0!==c&&h){let e=nG("TOOL_EXEC_TIMEOUT",`Tool execution timed out after ${c}ms`);g.push(new Promise((t,r)=>{a=setTimeout(()=>{h.abort(),r(e)},c)}))}u&&g.push(new Promise((e,t)=>{let r=()=>{t(p)};u.addEventListener("abort",r,{once:!0}),s=()=>u.removeEventListener("abort",r)}));try{return await Promise.race(g)}finally{a&&clearTimeout(a),null==i||i(),null==s||s()}}function nK(e){return e?String(e):rF}function nX(e,t,r){return r?{type:e,message:t,error:r}:{type:e,message:t}}let nZ={simulator_manifest_load_failed:"Manifest",simulator_skill_load_failed:"Skill",local_mcp_tools_load_failed:"MCP",simulator_chat_fetch_failed:"对话接口"};function nQ(e){return new Set(e.flatMap(e=>e.blocks.flatMap(e=>"image"===e.type&&e.image.previewUrl?[e.image.previewUrl]:[])))}function nY(e,t){return e?{kind:"pages",item:e,routeUrl:t}:null}function n0(e,t){if(!t)return null;try{return nY(eD({url:t},e).entry,t)}catch{return null}}function n1(e){var t,r;return e.raw_result_text||(null==(t=e.error)?void 0:t.message)||(void 0===(r=e.result)?"":"string"==typeof r?r.slice(0,1e3):t3(r).slice(0,1e3))||e.status}function n2(e,t){return e.app_key||e.appKey||e.appId||e.packageName||t}function n3(e,t){var r;return e.name||e.appName||e.app_name||(null==(r=e.applet)?void 0:r.name)||t}function n4(e,t){let r=e.applet??{},n=t.applet??{},a=r.tools??[],i=n.tools??[],s=new Map,o=t.name||t.appName||t.app_name||n.name||"";if(i.length>0)for(let e of[...a,...i])e.id&&s.set(e.id,e);return{...e,manifest_version:t.manifest_version??e.manifest_version,app_key:t.app_key??e.app_key,name:t.name??e.name,appName:t.appName??e.appName,app_name:t.app_name??e.app_name,mcp_server:t.mcp_server??e.mcp_server,tools:t.tools??e.tools,entities:t.entities??e.entities,tool_card_binding:t.tool_card_binding??e.tool_card_binding,raw_manifest_yaml:t.raw_manifest_yaml??e.raw_manifest_yaml,applet:{...r,name:o||r.name,tools:i.length>0?[...s.values()]:a}}}class n5{fetcher;simulatorFetcher;historyMaxTurns;simulatorAppKey;simulatorAppName;simulatorSkills;simulatorManifest;simulatorMaxStep;simulatorMcpServers;simulatorMcpServerProvider;simulatorToolExecutor;sandboxToolCallExecutions=new Map;listeners=new Set;activeSimulatorRun=null;lastResolvedSimulatorMcpServers=[];receivedSimulatorLocationDirectiveCardIds=new Set;resourceUrlVersion;hasSimulatorManifestStateValue=!1;simulatorManifestStateValue;simulatorManifestStatePromise;simulatorRunSeq=0;destroyed=!1;state;constructor(e={}){let t=nK(e.manifestUrl);this.fetcher=e.fetcher,this.simulatorFetcher=e.simulatorFetch,this.historyMaxTurns=e.historyMaxTurns??6,this.simulatorAppKey=e.appKey,this.simulatorAppName=e.appName,this.simulatorSkills=e.skills,this.simulatorManifest=e.simulatorManifest,this.simulatorMaxStep=e.maxStep,"function"==typeof e.mcpServers?(this.simulatorMcpServers=[],this.simulatorMcpServerProvider=e.mcpServers):this.simulatorMcpServers=e.mcpServers??[],this.simulatorToolExecutor=e.toolExecutor,this.state={manifestUrl:t,manifest:new u({manifestVersion:"3.0",packageName:"",appId:"",versionCode:"",applet:{appletId:"",appRuntimeEntry:"",digest:"",pages:[]},widgets:[]}),pages:[],widgets:[],pageSelection:null,widgetSelection:null,simulator:{endpoint:rV(e.simulatorEndpoint),messages:[],streamStatus:"idle",toolCalls:[],traceEvents:[]},status:nX("idle","Idle")}}clearSimulatorManifestStateValue(){this.hasSimulatorManifestStateValue=!1,this.simulatorManifestStateValue=void 0,this.simulatorManifestStatePromise=void 0}takeSimulatorManifestStateValue(){if(!this.hasSimulatorManifestStateValue)return{found:!1,value:void 0};let e=this.simulatorManifestStateValue;return this.clearSimulatorManifestStateValue(),{found:!0,value:e}}async loadSimulatorManifestForState(){if(void 0!==this.simulatorManifest)return"function"!=typeof this.simulatorManifest?this.simulatorManifest:this.hasSimulatorManifestStateValue?this.simulatorManifestStateValue:(this.simulatorManifestStatePromise||(this.simulatorManifestStatePromise=Promise.resolve(this.simulatorManifest()).then(e=>(this.hasSimulatorManifestStateValue=!0,this.simulatorManifestStateValue=e,e)).finally(()=>{this.simulatorManifestStatePromise=void 0})),this.simulatorManifestStatePromise)}async mergeSimulatorManifestForState(e){if(void 0===this.simulatorManifest)return e;try{let t=await this.loadSimulatorManifestForState();if(!t)return e;return new u(n4(e.raw,t))}catch(t){return console.warn("[web-sdk-debugger] Failed to merge simulator manifest for debug state",t),e}}async loadManifest(e){this.assertActive();let t=this.state.manifestUrl,r=nK(e??this.state.manifestUrl);this.setState({...this.state,manifestUrl:r,resourceUrlVersion:this.resourceUrlVersion,status:nX("loading",`Loading manifest ${r}`)});try{var n,a,i,s,o,l;let e,t,d,u,p,h=await c(r,{fetcher:this.fetcher}),m=await this.mergeSimulatorManifestForState(h),g=m.pages,f=m.widgets,v=n0(m,null==(n=this.state.pageSelection)?void 0:n.routeUrl)??(s=m,o=g,l=this.state.pageSelection,e=o.filter(rH),t=null==l?void 0:l.item.path,d=function(e,t){if(t)try{return e.getPageEntry(t)}catch{return}}(s,s.raw.applet.appletEntry),nY((t?e.find(e=>e.path===t):void 0)??(d&&rH(d)?d:void 0)??e.find(e=>"index"===e.id||"/pages/index"===e.path||"/pages/index/index"===e.path)??e[0])),y=(a=this.state.widgetSelection,u=f.filter(rH),(i=((p=null==a?void 0:a.item.widgetId)?u.find(e=>e.widgetId===p):void 0)??u[0])?{kind:"widgets",item:i}:null);return this.setState({...this.state,manifestUrl:r,manifest:m,pages:g,widgets:f,resourceUrlVersion:this.resourceUrlVersion,pageSelection:v,widgetSelection:y,status:nX("ready",v||y?`Loaded manifest ${r}`:`Manifest has no entries ${r}`)}),this.state}catch(r){let e=r instanceof Error?r:Error(String(r));throw this.setState({...this.state,manifestUrl:t,status:nX("error",`Load failed: ${e.message}`,e)}),e}}navigateToPage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.assertActive();try{let r=n0(this.state.manifest,e);if(!r)throw Error(`Unknown pages route: ${e}`);this.setState({...this.state,pageSelection:{...r,routeMode:t.routeMode},status:nX("ready",`Navigated page ${r.item.path}`)})}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.setState({...this.state,status:nX("error",e.message,e)}),e}}selectWidget(e){this.assertActive();let t=this.state.widgets.find(t=>t.widgetId===e);if(!t){let t=Error(`Unknown widgets entry: ${e}`);throw this.setState({...this.state,status:nX("error",t.message,t)}),t}this.setState({...this.state,widgetSelection:{kind:"widgets",item:t},status:nX("ready",`Selected widget ${t.widgetId}`)})}async reloadResources(){if(this.assertActive(),"streaming"===this.state.simulator.streamStatus)throw Error("Cannot refresh card resources while simulator query is streaming");let e=this.state.manifestUrl,t=rJ("reload");this.resourceUrlVersion=t,this.clearSimulatorManifestStateValue();let r=await this.loadManifest(e);return void 0!==this.simulatorSkills&&await this.resolveSimulatorSkillsForQuery(t,{}),this.appendSimulatorDebugEvent({category:"resource",event:"simulator_resource_reload_completed",manifest_url:e,resource_url_version:t,summary:"Card resources refreshed"}),r}async sendSimulatorQuery(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.assertActive();let r=e.trim(),n=(t.images??[]).filter(e=>e.resource_uri);if(r||0!==n.length)return this.sendSimulatorChat({kind:"message",queryText:r},t)}sendSimulatorFollowUpMessage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((r,n)=>{let a=Error("Simulator follow-up message was cancelled before submission");this.sendSimulatorChat({kind:"follow_up",content:e},t,r,()=>n(a)).then(()=>n(a),n)})}async sendSimulatorChat(e,t,r,n){this.assertActive(),this.cancelSimulatorQuery();let a=rJ("local_msg"),i=rJ("idem"),s=rJ("trace"),o=Date.now(),l=this.state.simulator,d=this.state.manifest.raw,u="message"===e.kind?(t.images??[]).filter(e=>e.resource_uri):[],c="message"===e.kind?{messageId:a,localMessageId:a,traceId:s,role:"user",contentType:u.length>0?"mixed":"text",text:e.queryText,blocks:[...u.map(e=>({blockId:rJ("block_image"),type:"image",image:e})),...e.queryText?[{blockId:rJ("block_text"),type:"text",text:e.queryText}]:[]],status:"completed",createdAtMs:o}:void 0,p=this.createSimulatorRun(s);p.onCancelledBeforeSubmission=n,this.activeSimulatorRun=p,this.setState({...this.state,simulator:{...l,activeRequestId:void 0,activeReplyMessageId:void 0,error:void 0,locationDirective:void 0,messages:c?[...l.messages,c]:l.messages,streamStatus:"streaming"}}),this.appendSimulatorDebugEvent({event:"simulator_query_prepare_started",trace_id:s,previous_active_request_id:l.activeRequestId,previous_stream_status:l.streamStatus,history_message_count:l.messages.length,query_preview:"message"===e.kind?e.queryText.slice(0,80)||"[图片]":"send_follow_up_message",image_count:u.length});try{var h,m;let n,u=await this.resolveSimulatorManifestForQuery(s,t,d,p.streamAbortController.signal),c=n2(u,this.state.manifest.appId),g=n3(u,this.state.manifest.name);if(!this.isSimulatorRunCurrent(p))return;let f=await this.resolveSimulatorSkillsForQuery(s,t,p.streamAbortController.signal);if(!this.isSimulatorRunCurrent(p))return;let v={signal:p.streamAbortController.signal,trace:{trace_id:s,component:"web_sdk_debugger",stage:"query_prepare",sampled:!0},appKey:t.appKey||this.simulatorAppKey||c,appName:t.appName||this.simulatorAppName||g,manifest:u},y=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider(v):this.simulatorMcpServers;if(this.lastResolvedSimulatorMcpServers=y,!this.isSimulatorRunCurrent(p))return;this.appendSimulatorDebugEvent({event:"simulator_query_mcp_resolved",trace_id:s,elapsed_ms:Date.now()-o,mcp_server_count:y.length,mcp_servers:y.map(e=>({server_id:e.server_id,tool_count:e.tools.length,tools:e.tools.map(e=>e.name)}))});let _={historyMaxTurns:this.historyMaxTurns,idempotencyKey:i,localMessageId:a,manifestAppId:this.state.manifest.appId,manifestAppName:g,messages:l.messages,toolCalls:l.toolCalls,options:t,simulatorAppKey:this.simulatorAppKey,simulatorAppName:this.simulatorAppName,simulatorSkills:f,simulatorManifest:u,simulatorMaxStep:this.simulatorMaxStep,simulatorMcpServers:y,traceId:s},b="message"===e.kind?(h={..._,queryText:e.queryText},n=nz(h.options.images??[]),{...nW(h),message:{role:"USER",content:h.queryText,local_message_id:h.localMessageId,parts:n.length>0?n:void 0}}):(m={..._,content:e.content},{...nW(m),input_event:{event_type:"send_follow_up_message",params:{content:m.content},local_message_id:m.localMessageId}});if(await r9({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,onSubmitted:()=>{p.onCancelledBeforeSubmission=void 0,null==r||r()},request:b,signal:p.streamAbortController.signal,onEvent:t=>this.handleSimulatorEvent(t,p,"follow_up"===e.kind?e.content:void 0)}),!this.isSimulatorRunCurrent(p))return;"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,streamStatus:"completed"}}),this.appendSimulatorDebugEvent({event:"simulator_query_stream_returned",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus,active_request_id:this.state.simulator.activeRequestId})}catch(n){if(nw(n))return void this.appendSimulatorDebugEvent({event:"simulator_query_aborted",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus});if(!this.isSimulatorRunCurrent(p))return;let e=nS(n,"query_stream"),t=this.getSimulatorQueryFailureDiagnosis(s,n),r=t?{...e,message:t.summary,user_message:t.summary,details:{...e.details,diagnosis:t,original_error:e.message}}:e;throw this.appendSimulatorDebugEvent({event:"simulator_query_failed",trace_id:s,elapsed_ms:Date.now()-o,error:r}),this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,error:r,streamStatus:"error"}}),n}finally{this.finishSimulatorStream(p)}}pushMessages(e){if(this.assertActive(),!Array.isArray(e))throw Error("Messages must be an array");if(0===e.length)return;let t=structuredClone(e).map(e=>{let t=(e.blocks??[]).map(e=>({...e,blockId:e.blockId??rJ("block"),..."card"===e.type?{card:{...e.card,card_id:e.card.card_id??rJ("card")}}:{}}));return{...e,messageId:e.messageId??rJ("message"),createdAtMs:e.createdAtMs??Date.now(),text:e.text??"",contentType:e.contentType??(t.some(e=>"text"!==e.type)?"mixed":"text"),blocks:t}}),r=new Set(this.state.simulator.messages.map(e=>e.messageId));for(let e of t){if(r.has(e.messageId))throw Error(`Duplicate messageId: ${e.messageId}`);r.add(e.messageId)}this.updateSimulatorState(e=>({...e,messages:[...e.messages,...t]}))}removeSimulatorMessages(e){this.assertActive();let t=new Set(e.filter(Boolean));if(0===t.size)return;let r=nQ(this.state.simulator.messages.filter(e=>t.has(e.messageId)));this.updateSimulatorState(e=>({...e,activeReplyMessageId:e.activeReplyMessageId&&t.has(e.activeReplyMessageId)?void 0:e.activeReplyMessageId,messages:e.messages.filter(e=>!t.has(e.messageId)),selectedCard:e.selectedCard&&t.has(e.selectedCard.reply_message_id)?void 0:e.selectedCard})),queueMicrotask(()=>{let e=nQ(this.state.simulator.messages);for(let t of r)e.has(t)||URL.revokeObjectURL(t)})}applySimulatorCardDelta(e){this.assertActive(),this.updateSimulatorState(t=>nk(t,tj(e.card_delta)?e.card_delta:e).state)}consumeSimulatorLocationDirective(e){this.assertActive(),this.updateSimulatorState(t=>{var r;return(null==(r=t.locationDirective)?void 0:r.cardId)===e?{...t,locationDirective:void 0}:t})}cancelSimulatorQuery(){this.assertActive();let e=this.state.simulator.activeRequestId,t=this.activeSimulatorRun;t&&(this.appendSimulatorDebugEvent({event:"simulator_query_cancel_requested",request_id:e,trace_id:t.traceId,stream_status:this.state.simulator.streamStatus}),this.abortSimulatorRun(t)),"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,activeReplyMessageId:void 0,toolCalls:this.state.simulator.toolCalls.map(t=>e&&t.requestId===e&&"running"===t.status?{...t,status:"cancelled",updatedAtMs:Date.now()}:t),streamStatus:"cancelled"}})}async callSimulatorTool(e){if(this.assertActive(),!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");let t=e.toolName.trim();if(!t)throw Error("toolName must be a non-empty string");let r=rJ("req_tool"),n=rJ("reply_tool"),a=rJ("tool_call"),i=rJ("trace"),s={trace_id:i,component:"web_sdk_debugger",stage:"direct_tool_call",sampled:!0},o=Date.now(),l=await this.resolveDirectToolCallServerId(t,e.serverId,s),d={requestId:r,replyMessageId:n,toolCallId:a,toolName:t,serverId:l,appKey:this.simulatorAppKey||n2(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.params,argumentsJson:e.params?function(e){try{return JSON.stringify(e??{})}catch{return""}}(e.params):void 0,status:"running",createdAtMs:o,updatedAtMs:o,trace:s,timeoutMs:e.timeoutMs};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,d]})),this.appendSimulatorDebugEvent({event:"direct_tool_call_started",request_id:r,trace_id:i,tool_call_id:a,tool_name:t,server_id:l,arguments:e.params,arguments_json:d.argumentsJson});let u=Date.now(),c=await this.runSimulatorToolCall(d);return this.updateToolCall(a,{status:c.status,updatedAtMs:Date.now(),error:c.error,resultSummary:n1(c),structuredResultSummary:c.result,isMiniApp:c.miniapp&&"boolean"==typeof c.miniapp.is_mini_app?c.miniapp.is_mini_app:void 0}),this.appendSimulatorDebugEvent({event:"direct_tool_call_completed",request_id:r,trace_id:i,tool_call_id:a,tool_name:t,server_id:l,status:c.status,elapsed_ms:Date.now()-u,result:c.result,error:c.error,raw_result_text:c.raw_result_text}),c}executeSandboxToolCall(e){this.assertActive();let t=`${e.request_id}\0${e.tool_call.tool_call_id}`,r=this.sandboxToolCallExecutions.get(t);if(r)return r;let n=this.executeSandboxToolCallOnce(e);return this.sandboxToolCallExecutions.set(t,n),n}async submitToolResult(e,t){let r,n,a,i;this.assertActive();let s=Date.now(),o=(n=void 0===e.result?e.error?{error:e.error.message}:{}:e.result,a=e.raw_mcp_result_json,i=e.raw_result_text||t3(e.error?{error:e.error.message,detail:e.error}:n),{request_id:e.requestId,tool_call_id:e.toolCallId,server_id:e.serverId,tool_name:e.toolName,status:function(e){switch(e){case"succeeded":return"SUCCESS";case"timeout":return"TIMEOUT";case"cancelled":return"CANCELLED";case"rejected":return"REJECTED";default:return"FAILED"}}(e.status),app_key:e.appKey,result:{tool_call_id:e.toolCallId,content:i,structured_json:t3(n)},raw_result_text:i,raw_mcp_result_json:a||"",miniapp:e.miniapp,timing:e.timing,trace:{trace_id:e.trace.trace_id,component:nF,stage:"tool_report",sampled:e.trace.sampled??!0},ext:{reported_by:nF}});this.appendSimulatorDebugEvent({event:"tool_result_report_started",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:e.serverId,status:o.status,report_request:o,endpoint:this.state.simulator.endpoint});try{r=await ne({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,result:o,signal:t})}catch(r){let t=r6(r);throw this.appendSimulatorDebugEvent({event:"tool_result_report_failed",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,error:t4(r),response:t}),r}this.appendSimulatorDebugEvent({event:"tool_result_report_response_received",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,response:r});let l=function(e){let t=e.code,r=!1===e.accepted,n=void 0!==t&&0!==t&&"0"!==t;if(!r&&!n)return;let a="string"==typeof e.message&&e.message?e.message:n?`Simulator tool result rejected with code ${String(t)}`:"Simulator tool result was not accepted",i=tQ(e)[0];return nG("TOOL_RESULT_REJECTED",i?`${a} (x-tt-logid: ${i})`:a,"tool_result_submit",{gateway_response:e,gateway_code:n?t:void 0,gateway_accepted:!r&&void 0,"x-tt-logid":i})}(r);if(this.appendSimulatorDebugEvent({event:"tool_result_ack",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,accepted:r.accepted,next_action:r.next_action,error:l,response:r}),l)throw l;return r}selectSimulatorCard(e){this.assertActive(),this.updateSimulatorState(t=>({...t,selectedCard:e}))}updateSimulatorWidget(e){let t;if(this.assertActive(),"string"!=typeof e.widgetInstanceId||!e.widgetInstanceId.trim())return{status:"invalid_params",message:"widgetInstanceId must be a non-empty string"};if(void 0!==e.widgetId&&("string"!=typeof e.widgetId||!e.widgetId.trim()))return{status:"invalid_params",message:"widgetId must be a non-empty string when provided"};try{t=JSON.parse(e.widgetData)}catch{return{status:"invalid_widget_data",message:"widgetData must be a JSON object"}}if(!tj(t))return{status:"invalid_widget_data",message:"widgetData must be a JSON object"};let r=nf(this.state.simulator.messages,e.widgetInstanceId,r=>({...r,widget_id:e.widgetId||r.widget_id,render_data:t}));return r.found?(this.updateSimulatorState(e=>({...e,messages:r.messages})),{status:"updated"}):{status:"not_found",message:`Widget instance ${e.widgetInstanceId} was not found`}}appendSimulatorTraceEvent(e){this.assertActive(),this.appendSimulatorDebugEvent(e)}async approveSimulatorToolCall(e){this.assertActive();let t=this.getSimulatorToolCall(e);if(!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");if("pending_approval"!==t.status)return;let r=this.getSimulatorToolCallRun(t);if(void 0!==t.runId&&!r)return void this.cancelStaleSimulatorToolCall(t);let n={...t,status:"running",updatedAtMs:Date.now()};null==r||r.pendingApprovalToolCallIds.delete(e),this.updateToolCall(e,{status:n.status,updatedAtMs:n.updatedAtMs}),await this.executeSimulatorToolCall(n,r)}async rejectSimulatorToolCall(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Tool call rejected by user";this.assertActive();let r=this.getSimulatorToolCall(e);if("pending_approval"!==r.status)return;let n=this.getSimulatorToolCallRun(r);if(void 0!==r.runId&&!n)return void this.cancelStaleSimulatorToolCall(r);let a=this.createToolExecutorInput(r),i=nG("TOOL_EXEC_REJECTED",t),s=Date.now();null==n||n.pendingApprovalToolCallIds.delete(e);try{await this.submitExecutedToolResult(a,{status:"rejected",error:i},s,null==n?void 0:n.streamAbortController.signal),this.updateToolCall(e,{status:"rejected",updatedAtMs:Date.now(),error:i,resultSummary:t})}catch(a){if(n&&!this.isSimulatorRunCurrent(n))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:r.requestId,trace_id:r.trace.trace_id,tool_call_id:r.toolCallId,tool_name:r.toolName,reason:"stale_or_cancelled_run"});let t=nS(a,"tool_result_submit");throw this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:r.trace.trace_id,tool_call_id:e,summary:t4(a)}),this.updateToolCall(e,{status:"failed",updatedAtMs:Date.now(),error:t}),a}finally{n&&this.releaseSimulatorRun(n)}}getState(){return this.state}subscribe(e){return this.assertActive(),this.listeners.add(e),()=>{this.listeners.delete(e)}}getResourceUrl(e){return(this.assertActive(),e)?p(this.state.manifestUrl,e)??null:null}destroy(){var e,t;if(!this.destroyed){for(let r of(this.cancelSimulatorQuery(),null==(t=this.simulatorToolExecutor)||null==(e=t.dispose)||e.call(t),nQ(this.state.simulator.messages)))URL.revokeObjectURL(r);this.destroyed=!0,this.sandboxToolCallExecutions.clear(),this.listeners.clear()}}createSimulatorRun(e){return{id:this.simulatorRunSeq+=1,traceId:e,streamAbortController:new AbortController,streamDone:!1,cancelled:!1,pendingApprovalToolCallIds:new Set,toolAbortControllers:new Set}}isSimulatorRunCurrent(e){return!this.destroyed&&this.activeSimulatorRun===e&&!e.cancelled}abortSimulatorRun(e){var t;for(let r of(e.cancelled=!0,null==(t=e.onCancelledBeforeSubmission)||t.call(e),e.onCancelledBeforeSubmission=void 0,e.streamAbortController.abort(),e.toolAbortControllers))r.abort();this.activeSimulatorRun===e&&(this.activeSimulatorRun=null)}finishSimulatorStream(e){e.streamDone=!0,this.releaseSimulatorRun(e)}releaseSimulatorRun(e){this.activeSimulatorRun===e&&(e.cancelled||e.streamDone&&0===e.pendingApprovalToolCallIds.size&&0===e.toolAbortControllers.size)&&(this.activeSimulatorRun=null)}handleSimulatorEvent(e,t,r){let n="tool_call"===e.event_type;if(!this.isSimulatorRunCurrent(t)){n&&this.appendSimulatorDebugEvent({event:"tool_call_event_skipped",request_id:e.request_id,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",reason:"stale_or_cancelled_run",summary:"Tool call event arrived after its simulator run was cancelled and was not executed"});return}let a=this.state.simulator.activeRequestId;if(a&&e.request_id!==a&&"ack"!==e.event_type&&"debug"!==e.event_type){if(!n&&"tool_status"!==e.event_type)return;this.appendSimulatorDebugEvent({event:"tool_call_request_id_mismatch",request_id:e.request_id,active_request_id:a,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",event_type:e.event_type,summary:"Tool call event request_id differs from the acknowledged request_id"})}let{state:i,toolCall:s,cardRefresh:o,locationDirective:l}=function(e,t,r){var n,a,i,s,o,l,d,u,c,p,h,m;let g,f,v,y,_,b,w,S,x={...e,activeReplyMessageId:t.reply_message_id??e.activeReplyMessageId},I=!function(e){switch(e.event_type){case"ack":case"tool_call":case"tool_status":case"card_delta":case"content_block":case"answer_finish":case"message_finish":case"reply_finish":case"stream_error":case"trace_event":case"debug":return!0;default:return!1}}(t)?x:nI(x,(S=t.received_at_ms??Date.now(),{display:"debug"===(n=t).event_type?ni(n.payload)??{category:"debug",detail:nv(n),phase:"event",title:"Debug"}:{category:n_(n),detail:nv(n),phase:nb(n.event_type),title:ny(n)},id:t.event_id,timestamp:S,payload:(a=t,i=S,g=n_(a),f=nb(a.event_type),v={event:a.event_type,category:g,phase:f,received_at_ms:i,server_timestamp_ms:a.created_at_ms,title:ny(a),detail:nv(a),trace:a.trace},"debug"===a.event_type?{...v,event:a.payload.event||"debug",title:t6(a.payload.title||a.payload.event||"Debug Event"),summary:a.payload.summary,elapsed_ms:a.payload.elapsed_ms,redaction_level:a.payload.redaction_level}:"heartbeat"===a.event_type?{...v,server_time_ms:a.payload.server_time_ms,message:a.payload.message}:"answer_finish"===a.event_type?{...v,status:a.payload.status,finish_reason:a.payload.finish_reason,usage:a.payload.usage}:{...v,...a.payload})}));switch(t.event_type){case"ack":return{state:function(e,t,r){let n=t.payload.local_message_id,a=t.payload.query_message_id,i=t.payload.message_id,s=tj(t.payload.query_message)?t.payload.query_message:void 0,o=(null==s?void 0:s.content)||"",l=e.messages;if(n&&a){let e=l.find(e=>e.localMessageId===n);e?l=l.map(t=>t===e?{...t,messageId:a,followUpContent:r}:t):o&&(l=[...l,{messageId:a,localMessageId:n,requestId:t.request_id,traceId:t.trace.trace_id,followUpContent:r,role:"user",contentType:"text",text:o,blocks:[{blockId:`block_text_${a}`,type:"text",text:o}],status:"completed",createdAtMs:t.created_at_ms}])}return{...e,activeRequestId:t.request_id,activeReplyMessageId:i||e.activeReplyMessageId,messages:l}}(I,t,r.followUpContent)};case"message_start":return{state:(s=I,y=(o=t).payload.message_id||o.reply_message_id||rJ("reply"),{...s,activeReplyMessageId:y,messages:nh(s.messages,y,o.created_at_ms,o.request_id,o.trace.trace_id)})};case"text_delta":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let n=t.payload.block_id||`block_text_${t.seq}`,a=t.payload.delta||"",i=t.payload.op||"append";if("append"!==i&&"replace"!==i)return e;let s=nh(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:nm(s,r,e=>({...e,text:"replace"===i?a:`${e.text}${a}`,blocks:function(e,t,r,n){if(!e.find(e=>"text"===e.type&&e.blockId===t)){let a=e[e.length-1];return"append"===n&&(null==a?void 0:a.type)==="text"?e.map(e=>e===a?{...e,text:`${e.text}${r}`}:e):[...e,{blockId:t,type:"text",text:r}]}return e.map(e=>"text"===e.type&&e.blockId===t?{...e,text:"replace"===n?r:`${e.text}${r}`}:e)}(e.blocks,n,a,i)}))}}(I,t)};case"card_delta":return nk(I,t.payload,t);case"content_block":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let n=function(e,t){for(let[r,n]of(Array.isArray(e.content_block)?e.content_block:Array.isArray(e.contentBlock)?e.contentBlock:[]).entries()){let a=function(e){if(!tj(e))return;let t=tj(e.content)?e.content:e,r=tj(t.permission_apply_block)?t.permission_apply_block:tj(t.permissionApplyBlock)?t.permissionApplyBlock:void 0;return r?("string"==typeof r.permission_data?r.permission_data:"")||("string"==typeof r.permissionData?r.permissionData:""):""}(n),i=nu(a);if(!i)continue;let s=(tj(n)&&"string"==typeof n.block_id?n.block_id:"")||(tj(n)&&"string"==typeof n.blockId?n.blockId:"")||`permission_apply_${t.seq}_${r}`;return{blockId:s,card:{card_id:s,card_type:"permission_apply",fallback_text:"需要授权后继续",render_data:{grantingData:i,permissionData:a},title:nc(i)},op:e.op||"append"}}}(t.payload,t);if(!n||"append"!==n.op&&"replace"!==n.op)return e;let a=nh(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:nm(a,r,e=>({...e,contentType:"mixed",blocks:ng(e.blocks,n.blockId,n.card,n.op)}))}}(I,t)};case"tool_call":return function(e,t,r){let n=t.payload.tool_call_id,a=t.payload.tool_name,i=t.payload.server_id||"",s=t.payload.arguments_json||"",o=t.reply_message_id??e.activeReplyMessageId??rJ("reply");if(!n||!a)return{state:nI(e,{id:rJ("trace"),timestamp:Date.now(),payload:{event:"tool_call_ignored",request_id:t.request_id,trace_id:t.trace.trace_id,tool_call_id:n,tool_name:a,reason:n?"missing_tool_name":"missing_tool_call_id",tool_call_payload:t.payload,summary:"Tool call event is missing required fields and cannot be executed"}})};let l=t.payload.requires_user_approval??!1,d=l?"pending_approval":r.hasToolExecutor?"running":"pending",u={requestId:t.request_id,runId:r.runId,replyMessageId:o,toolCallId:n,toolName:a,serverId:i,appKey:t.payload.app_key,arguments:tj(t.payload.arguments)?t.payload.arguments:t2(s),argumentsJson:s,mcpHeaders:function(e){if(!tj(e))return;let t=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1]));return Object.keys(t).length>0?t:void 0}(t.payload.headers),status:d,createdAtMs:t.created_at_ms,updatedAtMs:t.created_at_ms,trace:t.trace,requiresUserApproval:l,timeoutMs:t.payload.timeout_ms,deadlineMs:t.payload.deadline_ms},c=nm(nh(e.messages,o,t.created_at_ms,t.request_id,t.trace.trace_id),o,e=>({...e,toolCalls:nN(e.toolCalls??[],u)})),p={...e,messages:c,toolCalls:[...e.toolCalls.filter(e=>e.toolCallId!==n),u]};return r.hasToolExecutor?{state:p,toolCall:u}:{state:nI(p,{id:rJ("trace"),timestamp:Date.now(),payload:{event:"tool_executor_missing",request_id:u.requestId,trace_id:u.trace.trace_id,tool_call_id:n,tool_name:a,summary:"No local simulator tool executor is configured"}})}}(I,t,r);case"tool_status":return{state:function(e,t){let r=t.payload.tool_call_id,n=function(e){switch(e){case"SUCCESS":return"succeeded";case"FAILED":return"failed";case"RUNNING":return"running";case"TIMEOUT":return"timeout";case"CANCELLED":return"cancelled";case"REJECTED":return"rejected";default:return""}}(t.payload.status||"");if(!r||!n)return e;let a=t.payload.progress,i=t.payload.message,s=t.payload.error?nS(t.payload.error,"tool_execute"):void 0,o=nE(e,r,{status:n,updatedAtMs:t.created_at_ms,progress:a,message:i,error:s}),l=o.toolCalls.find(e=>e.toolCallId===r);return l?{...o,messages:nm(o.messages,l.replyMessageId,e=>({...e,toolCalls:nN(e.toolCalls??[],l)}))}:o}(I,t)};case"trace_event":case"debug":default:return{state:I};case"heartbeat":return{state:(l=I,d=t,{...l,lastHeartbeatMs:d.payload.server_time_ms??d.created_at_ms})};case"answer_finish":return{state:(u=I,c=t,{...u,answerFinish:{messageId:c.reply_message_id,status:c.payload.status,finishReason:c.payload.finish_reason,usage:tj(c.payload.usage)?c.payload.usage:void 0,createdAtMs:c.created_at_ms,trace:c.trace,payload:c.payload}})};case"message_finish":return{state:function(e,t){let r=t.payload.message_id||t.reply_message_id;if(!r)return e;let n=t.payload.status||"completed";return{...e,messages:nm(e.messages,r,e=>({...e,status:function(e){switch(e){case"completed":case"finished":default:return"completed";case"cancelled":case"interrupted":return"interrupted";case"failed":case"error":return"failed"}}(n)}))}}(I,t)};case"reply_finish":return{state:(p=I,b="completed"===(_=t.payload.status||"completed")||"finished"===_?"completed":"cancelled"===_?"cancelled":"error",{...p,activeRequestId:void 0,activeReplyMessageId:void 0,messages:nC(p.messages,b),streamStatus:b})};case"stream_error":return{state:(h=I,w=nS((m=t).payload.error??m.payload,m.payload.stage||"stream"),{...h,activeRequestId:void 0,error:w,messages:nC(h.messages,"error"),streamStatus:"error"})}}}(this.state.simulator,e,{followUpContent:r,hasToolExecutor:!!this.simulatorToolExecutor,runId:t.id}),d=l&&!this.receivedSimulatorLocationDirectiveCardIds.has(l.cardId)?l:void 0;if(d&&this.receivedSimulatorLocationDirectiveCardIds.add(d.cardId),this.updateSimulatorState(()=>d?{...i,locationDirective:d}:i),d?this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_received",card_id:d.cardId,request_id:d.requestId,source_tool_call_id:d.sourceToolCallId,tool_name:d.toolName,trace_id:e.trace.trace_id}):l&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_loop_prevented",card_id:l.cardId,reason:"duplicate_card_id",request_id:l.requestId,tool_name:l.toolName,trace_id:e.trace.trace_id}),(null==o?void 0:o.status)==="not_found"&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_history_card_refresh_skipped",reason:"card_not_found",request_id:e.request_id,trace_id:e.trace.trace_id,card_id:o.cardId}),s){let e=this.withFallbackToolCallServerId(s);e.requiresUserApproval?t.pendingApprovalToolCallIds.add(e.toolCallId):this.executeSimulatorToolCall(e,t)}}async executeSandboxToolCallOnce(e){let t=e.tool_call,r=Date.now(),n={trace_id:`bridge_${e.request_id}`,component:"sandbox_bridge",stage:"calltool_execute",sampled:!0},a={appKey:t.app_key,arguments:JSON.parse(t.arguments_json),argumentsJson:t.arguments_json,createdAtMs:r,deadlineMs:t.deadline_ms,mcpHeaders:t.headers,replyMessageId:`bridge_reply_${e.request_id}`,requestId:e.request_id,serverId:t.server_id,status:"running",timeoutMs:t.timeout_ms,toolCallId:t.tool_call_id,toolName:t.tool_name,trace:n,updatedAtMs:r};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,a]})),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_started",request_id:a.requestId,trace_id:n.trace_id,tool_call_id:a.toolCallId,app_key:a.appKey,server_id:a.serverId,tool_name:a.toolName,arguments_json:a.argumentsJson,deadline_ms:a.deadlineMs,timeout_ms:a.timeoutMs});let i=Date.now(),s=t.deadline_ms<=i?{status:"timeout",error:nG("TOOL_EXEC_TIMEOUT","Sandbox tool call deadline has expired")}:await this.runSimulatorToolCall(a),o=this.createToolExecutorInput(a);try{await this.submitSandboxToolResultWithRetry(o,s,i)}catch(t){let e=nS(t,"tool_result_submit");throw this.updateToolCall(a.toolCallId,{error:e,resultSummary:e.message,status:"failed",updatedAtMs:Date.now()}),t}return this.updateToolCall(a.toolCallId,{error:s.error,isMiniApp:s.miniapp&&"boolean"==typeof s.miniapp.is_mini_app?s.miniapp.is_mini_app:void 0,resultSummary:n1(s),status:s.status,structuredResultSummary:s.result,updatedAtMs:Date.now()}),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_reported",request_id:a.requestId,trace_id:n.trace_id,tool_call_id:a.toolCallId,app_key:a.appKey,server_id:a.serverId,tool_name:a.toolName,status:s.status,elapsed_ms:Date.now()-i,raw_mcp_result_json:s.raw_mcp_result_json}),{reported:!0,requestId:a.requestId,toolCallId:a.toolCallId}}withFallbackToolCallServerId(e){var t,r;if(e.serverId)return e;let n=this.lastResolvedSimulatorMcpServers,a=(null==(t=n.find(t=>t.tools.some(t=>t.name===e.toolName)))?void 0:t.server_id)||(null==(r=n[0])?void 0:r.server_id)||"local_mcp";return this.appendSimulatorDebugEvent({event:"tool_call_server_id_fallback",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:a,summary:"Tool call event has no server_id; falling back to a locally resolved MCP server"}),this.updateToolCall(e.toolCallId,{serverId:a}),{...e,serverId:a}}async runSimulatorToolCall(e,t){if(!this.simulatorToolExecutor){let e=nG("TOOL_EXECUTOR_UNAVAILABLE","No local simulator tool executor is configured");return{error:e,result:{error:e.message},status:"failed"}}try{return await nJ({executor:this.simulatorToolExecutor,input:this.createToolExecutorInput(e),record:e,signal:t})}catch(t){let e=nS(t,"tool_execute");return{status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||nw(t)?"cancelled":"failed",error:e}}}async executeSimulatorToolCall(e,t){if(t&&!this.isSimulatorRunCurrent(t))return;let r=Date.now(),n=this.createToolExecutorInput(e),a=t?new AbortController:void 0;t&&a&&t.toolAbortControllers.add(a);let i=await this.runSimulatorToolCall(e,null==a?void 0:a.signal);try{if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});if(await this.submitExecutedToolResult(n,i,r,null==a?void 0:a.signal),t&&!this.isSimulatorRunCurrent(t))return;this.updateToolCall(e.toolCallId,{status:i.status,updatedAtMs:Date.now(),error:i.error,resultSummary:n1(i),structuredResultSummary:i.result,isMiniApp:i.miniapp&&"boolean"==typeof i.miniapp.is_mini_app?i.miniapp.is_mini_app:void 0})}catch(n){if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});let r=nS(n,"tool_result_submit");this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,summary:t4(n),error:r}),this.updateToolCall(e.toolCallId,{status:"failed",updatedAtMs:Date.now(),error:r}),this.failActiveSimulatorStream(r)}finally{t&&a&&(t.toolAbortControllers.delete(a),this.releaseSimulatorRun(t))}}uploadSimulatorImage(e,t){return this.assertActive(),r7({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,file:e,signal:t})}createToolExecutorInput(e){let t={trace_id:e.trace.trace_id,span_id:rJ("span_tool_execute"),parent_span_id:e.trace.span_id,component:"local_mcp",stage:"tool_execute",sampled:e.trace.sampled};return{requestId:e.requestId,replyMessageId:e.replyMessageId,toolCallId:e.toolCallId,toolName:e.toolName,serverId:e.serverId,appKey:e.appKey||this.simulatorAppKey||n2(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.arguments,argumentsJson:e.argumentsJson,headers:e.mcpHeaders,manifest:this.state.manifest.raw,timeoutMs:e.timeoutMs,deadlineMs:e.deadlineMs,trace:t}}async resolveSimulatorManifestForQuery(e,t,r,n){let a=Date.now(),i=void 0!==t.manifest,s=i?"query_option":void 0===this.simulatorManifest?"loaded_manifest":"debugger_option";this.appendSimulatorDebugEvent({event:"simulator_manifest_load_started",trace_id:e,source:s});try{let o=i?{found:!1,value:void 0}:this.takeSimulatorManifestStateValue(),l=i?t.manifest:o.found?o.value:"function"==typeof this.simulatorManifest?await this.simulatorManifest(n):this.simulatorManifest,d=l?n4(r,l):r;return this.appendSimulatorDebugEvent({event:"simulator_manifest_loaded",trace_id:e,elapsed_ms:Date.now()-a,source:s,manifest:d}),d}catch(t){return n.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_manifest_load_failed",trace_id:e,elapsed_ms:Date.now()-a,error:t4(t),source:s}),r}}async resolveSimulatorSkillsForQuery(e,t,r){let n=Date.now(),a=void 0===t.skills?"debugger_option":"query_option";this.appendSimulatorDebugEvent({event:"simulator_skill_load_started",trace_id:e,source:a});try{let i=t.skills??("function"==typeof this.simulatorSkills?await this.simulatorSkills(r):this.simulatorSkills)??[];return this.appendSimulatorDebugEvent({event:i.length>0?"simulator_skill_loaded":"simulator_skill_empty",trace_id:e,elapsed_ms:Date.now()-n,skills_length:i.reduce((e,t)=>e+t.content.length,0),skill_paths:i.map(e=>e.relativePath),source:a}),i}catch(t){return null==r||r.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_skill_load_failed",trace_id:e,elapsed_ms:Date.now()-n,error:t4(t),source:a}),[]}}async resolveDirectToolCallServerId(e,t,r){var n;let a=null==t?void 0:t.trim();if(a)return a;let i=this.state.manifest.raw,s=this.simulatorAppKey||n2(i,this.state.manifest.appId),o=this.simulatorAppName||n3(i,this.state.manifest.name),l=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider({trace:r,appKey:s,appName:o,manifest:i}):this.simulatorMcpServers,d=l.find(t=>t.tools.some(t=>t.name===e));return(null==d?void 0:d.server_id)??(null==(n=l[0])?void 0:n.server_id)??"local_mcp"}getSimulatorToolCall(e){let t=this.state.simulator.toolCalls.find(t=>t.toolCallId===e);if(!t)throw Error(`Unknown simulator tool call: ${e}`);return t}getSimulatorToolCallRun(e){let t=this.activeSimulatorRun;if(t&&this.isSimulatorRunCurrent(t))return void 0===e.runId||e.runId===t.id?t:void 0}cancelStaleSimulatorToolCall(e){let t=nG("TOOL_EXEC_CANCELLED","Tool call cancelled because its simulator run is no longer active");this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"}),this.updateToolCall(e.toolCallId,{status:"cancelled",updatedAtMs:Date.now(),error:t,resultSummary:t.message})}async submitSandboxToolResultWithRetry(e,t,r){let n;for(let a=1;a<=2;a+=1)try{await this.submitExecutedToolResult(e,t,r,void 0,a);return}catch(t){if(n=t,2===a||void 0!==e.deadlineMs&&Date.now()>=e.deadlineMs)throw t;this.appendSimulatorDebugEvent({event:"sandbox_tool_result_report_retry",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,attempt:a+1,error:t4(t)})}throw n}async submitExecutedToolResult(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,i=Date.now();await this.submitToolResult({...e,...t,timing:{started_at_ms:r,ended_at_ms:i,duration_ms:i-r,attempt:a}},n)}updateToolCall(e,t){this.updateSimulatorState(r=>nE(r,e,t))}failActiveSimulatorStream(e){this.activeSimulatorRun&&this.abortSimulatorRun(this.activeSimulatorRun),this.updateSimulatorState(t=>({...t,activeRequestId:void 0,activeReplyMessageId:void 0,error:e,messages:t.messages.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:"failed"}:e),streamStatus:"error"}))}getSimulatorQueryFailureDiagnosis(e,t){let r=new Set;for(let t of this.state.simulator.traceEvents){let n=t.payload,a=nZ["string"==typeof n.event?n.event:""];a&&function(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}(n)===e&&"Failed to fetch"===(n.error||"")&&r.add(a)}if(r.size>=3)return{code:"DEBUG_SERVER_UNREACHABLE",confidence:"high",failed_services:[...r],summary:"调试 Dev Server 或本机网络不可达",suggestion:"检查调试 Dev Server 是否运行,以及浏览器能否访问当前调试端口。"};let n=r6(t),a="number"==typeof(null==n?void 0:n.status)?n.status:void 0;return 404===a?{code:"SIMULATOR_ENDPOINT_NOT_FOUND",confidence:"high",status:a,summary:"模拟器接口未配置或路由不存在",suggestion:"检查 simulator、manifest、skill 或 MCP 的接口地址与代理路由。"}:void 0!==a&&a>=500?{code:"SIMULATOR_ENDPOINT_SERVER_ERROR",confidence:"high",status:a,summary:`模拟器接口服务异常(HTTP ${a})`,suggestion:"接口已可达,但服务端或其上游依赖异常;请查看响应内容和服务端日志。"}:"Failed to fetch"===t4(t)?{code:"SIMULATOR_ENDPOINT_UNREACHABLE",confidence:"unknown",summary:"无法连接模拟器接口",suggestion:"可能是接口服务未启动、端口不可达、浏览器网络异常或 CORS 被拦截。"}:void 0}appendSimulatorDebugEvent(e){let t=tQ(e),r={display:ni(e),id:rJ("trace"),timestamp:Date.now(),payload:function(e,t){if(!tj(e))return{};let r=ns(e);return{...e,category:r.category,detail:r.detail,phase:r.phase,title:r.title,log_ids:t.length>0?t:void 0}}(e,t)};this.updateSimulatorState(e=>{var t;return{...e,traceEvents:[...e.traceEvents,{...r,order:((null==(t=e.traceEvents.at(-1))?void 0:t.order)??e.traceEvents.length)+1}].slice(-200)}})}updateSimulatorState(e){this.setState({...this.state,simulator:e(this.state.simulator)})}setState(e){for(let t of(this.state=e,this.listeners))t(this.state)}assertActive(){if(this.destroyed)throw Error("WebSdkDebugger has been destroyed")}}let n6="iphone-13",n8=[{key:n6,label:"iPhone 13",width:390,height:844,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-17-pro-max",label:"iPhone 17 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17-pro",label:"iPhone 17 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17",label:"iPhone 17",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-air",label:"iPhone Air",width:420,height:912,density:3,radius:52,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro-max",label:"iPhone 16 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro",label:"iPhone 16 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-plus",label:"iPhone 16 Plus",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16",label:"iPhone 16",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16e",label:"iPhone 16e",width:390,height:844,density:3,radius:44,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-15",label:"iPhone 15",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-14-plus",label:"iPhone 14 Plus",width:428,height:926,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-13-mini",label:"iPhone 13 mini",width:375,height:812,density:3,radius:44,homeIndicator:!0,statusBarHeight:50,safeArea:{top:50,bottom:34,left:0,right:0}},{key:"iphone-se",label:"iPhone SE",width:375,height:667,density:2,radius:0,homeIndicator:!1,statusBarHeight:20,safeArea:{top:20,bottom:0,left:0,right:0}},{key:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-8",label:"Pixel 8",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-7",label:"Pixel 7",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24",label:"Galaxy S24",width:360,height:780,density:3,radius:32,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24-ultra",label:"Galaxy S24 Ultra",width:384,height:854,density:3.75,radius:18,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-cover",label:"Galaxy Z Fold 5 Cover",width:344,height:882,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-inner",label:"Galaxy Z Fold 5 Inner",width:690,height:829,density:2.625,radius:24,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"ipad-mini",label:"iPad mini",width:744,height:1133,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}},{key:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}}],n7=[{key:"100",label:"100%",scale:1},{key:"85",label:"85%",scale:.85},{key:"75",label:"75%",scale:.75},{key:"50",label:"50%",scale:.5},{key:"fit",label:"自适应",scale:.88}],n9={key:"mobile-393",label:"393px",width:393,density:3};function ae(e){let t=/^custom-([1-9]\d{0,3})x([1-9]\d{0,3})$/.exec(e);if(t){let r=Number(t[1]),n=Number(t[2]);return{key:e,label:`自定义 ${r} \xd7 ${n}`,width:r,height:n,density:1,radius:0,homeIndicator:!1,statusBarHeight:0,safeArea:{top:0,bottom:0,left:0,right:0}}}return n8.find(t=>t.key===e)??n8.find(e=>e.key===n6)??n8[0]}let at="devtools_web";function ar(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n9,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{debugger:"web-sdk",density:e.density,screenWidth:e.width,containerWidth:e.width,devicePlatform:"iOS",deviceBrand:"Apple",deviceModel:`Widget preview ${e.label}`,screenOrientation:"portrait",...t,platform:at}}function an(e,t){try{let e=t.trim()?JSON.parse(t):{};if(tj(e))return e;throw Error("expected a JSON object")}catch(t){throw Error(`${e}: ${t.message}`)}}function aa(e){return e??document.body}async function ai(e,t){var r;let n,a=aa(t),i=new CustomEvent("doubao:multi-media-broadcast",{bubbles:!0,composed:!0,detail:e});a.dispatchEvent(i),window.dispatchEvent(new CustomEvent("doubao:multi-media-broadcast",{detail:e}));let s=(r=e.mediaId,n=Array.from(aa(t).querySelectorAll("audio,video")),r?n.filter(e=>e.id===r||e.dataset.mediaId===r):n);return await Promise.all(s.map(t=>"play"===e.action?t.play():Promise.resolve(t.pause()))),{affected:s.length}}let as=[],ao=new Map,al=!1;function ad(e){for(let t of e)URL.revokeObjectURL(t),ao.delete(t)}function au(){for(let e of as.splice(0))ad(e)}async function ac(e){var t;if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let r=await (t=e.src,new Promise((e,r)=>{let n=new Image;n.onload=()=>e(n),n.onerror=()=>r(Error(`failed to load image: ${t}`)),n.src=t})),n=document.createElement("canvas"),a=e.compressedWidth??r.naturalWidth??r.width,i=e.compressedHeight??r.naturalHeight??r.height;n.width=a,n.height=i;let s=n.getContext("2d");if(!s)throw Error("canvas 2d context is not available");return s.drawImage(r,0,0,a,i),{tempFilePath:n.toDataURL("image/jpeg",Math.min(100,Math.max(0,e.quality??80))/100)}}let ap={enableHighAccuracy:!0,maximumAge:0,timeout:1e4};function ah(){return{browserAuthorization:"unknown",message:"未配置",tone:"muted",userAuthorization:"unknown"}}function am(e){let{longitude:t,latitude:r}=e;if(!Number.isFinite(t)||!Number.isFinite(r)||t<-180||t>180||r<-90||r>90)throw Error("Invalid location coordinates")}let ag=new class{browserAuthorization="unknown";browserLocation;browserWatchId;locationListeners=new Set;locationUpdateRequests=new Map;manualLocation;pendingBrowserRequest;revision=0;snapshot=ah();snapshotListeners=new Set;updatesActive=!1;userAuthorization="unknown";watchRevision=0;getSnapshot=()=>this.snapshot;subscribe=e=>(this.snapshotListeners.add(e),()=>this.snapshotListeners.delete(e));subscribeLocation=e=>(this.locationListeners.add(e),()=>this.locationListeners.delete(e));isLocationScope(e){return"scope.userLocation"===e||"scope.userFuzzyLocation"===e||"scope.userLocationBackground"===e}updateUserAuthorization(e){this.userAuthorization=e?"granted":"denied",this.updateSnapshot({userAuthorization:this.userAuthorization}),!e&&this.locationUpdateRequests.size>0&&(this.stopLocationUpdates(),this.emitLocation({status:"user_unauthorized"}))}async requestLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ap;if("granted"!==this.userAuthorization)return{status:"user_unauthorized"};let t=this.getConfiguredLocation();return t||("denied"===this.browserAuthorization?this.createBrowserUnauthorizedResult():this.locateWithBrowser(e))}async requestLocationForHostDirective(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ap;return this.getConfiguredLocation()??this.locateWithBrowser(e)}async requestBrowserLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ap;return this.manualLocation=void 0,this.locateWithBrowser(e)}setManualLocation(e){am(e),this.revision+=1,this.pendingBrowserRequest=void 0,this.clearBrowserWatch(),this.manualLocation={...e,accuracy:0,source:"manual",speed:0,timestamp:Date.now()},this.browserAuthorization="granted",this.updateSnapshot({...e,browserAuthorization:"granted",errorMessage:void 0,message:"已配置(手动坐标)",source:"manual",tone:"success",updatedAtMs:Date.now()}),this.updatesActive&&this.emitLocation({location:this.manualLocation,status:"success"})}setConfigurationError(e){this.updateSnapshot({errorMessage:e,message:"定位失败",tone:"error",updatedAtMs:Date.now()})}async startLocationUpdates(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ap,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{signal:r,authorize:n}=t;if(null==r?void 0:r.aborted)throw new DOMException("Location updates were stopped","AbortError");this.releaseLocationUpdate(r);let a={active:!1,stop:()=>this.releaseLocationUpdate(r)};this.locationUpdateRequests.set(r,a),null==r||r.addEventListener("abort",a.stop,{once:!0});let i=()=>{if(this.locationUpdateRequests.get(r)!==a)throw new DOMException("Location updates were stopped","AbortError")};try{n&&await n(),i();let t=await this.requestLocation(e);i();let s="granted"===this.userAuthorization?this.getConfiguredLocation()??t:{status:"user_unauthorized"};if("success"!==s.status)return this.releaseLocationUpdate(r),this.emitLocation(s),s;return a.active=!0,this.updatesActive=!0,this.emitLocation(s),i(),this.manualLocation||"browser"!==s.location.source||void 0!==this.browserWatchId||this.startBrowserWatch(e),s}catch(e){throw this.locationUpdateRequests.get(r)===a&&this.releaseLocationUpdate(r),e}}stopLocationUpdates(){for(let e of this.locationUpdateRequests.keys())this.releaseLocationUpdate(e);this.updatesActive=!1,this.clearBrowserWatch()}releaseLocationUpdate(e){let t=this.locationUpdateRequests.get(e);t&&(this.locationUpdateRequests.delete(e),null==e||e.removeEventListener("abort",t.stop),this.updatesActive=[...this.locationUpdateRequests.values()].some(e=>e.active),this.updatesActive||this.clearBrowserWatch())}createBusinessLocationInfo(e){let t=function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}}();return{latitude:e.latitude,longitude:e.longitude,city:"",city_code:"",client_time_zone:t,country:"",country_code:"",district:"",impr_time:String(Math.floor(Date.now()/1e3)),province:"",region:"",time_zone:t,town:""}}reset(){this.revision+=1,this.stopLocationUpdates(),this.browserAuthorization="unknown",this.browserLocation=void 0,this.manualLocation=void 0,this.pendingBrowserRequest=void 0,this.userAuthorization="unknown",this.snapshot=ah(),this.emitSnapshot()}getConfiguredLocation(){return this.manualLocation?{location:{...this.manualLocation,timestamp:Date.now()},status:"success"}:"granted"===this.browserAuthorization&&this.browserLocation?{location:this.browserLocation,status:"success"}:void 0}locateWithBrowser(e){if(this.pendingBrowserRequest)return this.pendingBrowserRequest;let t=++this.revision;this.browserAuthorization="pending",this.updateSnapshot({browserAuthorization:"pending",errorMessage:void 0,latitude:void 0,longitude:void 0,message:"定位中...",source:void 0,tone:"pending",updatedAtMs:Date.now()});let r=this.getBrowserPosition(e).then(e=>{let r=this.toBrowserLocation(e);return t===this.revision&&(this.browserAuthorization="granted",this.browserLocation=r,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:r.latitude,longitude:r.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()})),{location:r,status:"success"}}).catch(e=>this.handleBrowserError(e,t)).finally(()=>{this.pendingBrowserRequest===r&&(this.pendingBrowserRequest=void 0)});return this.pendingBrowserRequest=r,r}getBrowserPosition(e){let t="u"<typeof navigator?void 0:navigator.geolocation;return t?new Promise((r,n)=>{t.getCurrentPosition(r,n,e)}):Promise.reject(Error("Geolocation is not available in the current browser"))}toBrowserLocation(e){return{...function(e,t){var r,n,a,i;if(am({latitude:t,longitude:e}),e<72.004||e>137.8347||t<.8293||t>55.8271)return{latitude:t,longitude:e};let s=-100+2*(r=e-105)+3*(n=t-35)+.2*n*n+.1*r*n+.2*Math.sqrt(Math.abs(r))+(20*Math.sin(6*r*Math.PI)+20*Math.sin(2*r*Math.PI))*2/3+(20*Math.sin(n*Math.PI)+40*Math.sin(n/3*Math.PI))*2/3+(160*Math.sin(n/12*Math.PI)+320*Math.sin(n*Math.PI/30))*2/3,o=300+(a=e-105)+2*(i=t-35)+.1*a*a+.1*a*i+.1*Math.sqrt(Math.abs(a))+(20*Math.sin(6*a*Math.PI)+20*Math.sin(2*a*Math.PI))*2/3+(20*Math.sin(a*Math.PI)+40*Math.sin(a/3*Math.PI))*2/3+(150*Math.sin(a/12*Math.PI)+300*Math.sin(a/30*Math.PI))*2/3,l=t/180*Math.PI,d=Math.sin(l),u=Math.sqrt(d=1-.006693421622965943*d*d);return{latitude:t+(s=180*s/(6335552.717000426/(d*u)*Math.PI)),longitude:e+(o=180*o/(6378245/u*Math.cos(l)*Math.PI))}}(e.coords.longitude,e.coords.latitude),accuracy:e.coords.accuracy??0,altitude:e.coords.altitude??void 0,altitudeAccuracy:e.coords.altitudeAccuracy??void 0,heading:e.coords.heading??void 0,source:"browser",speed:e.coords.speed??0,timestamp:e.timestamp||Date.now()}}handleBrowserError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.revision,r=e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0,n=1===r?"denied":"unknown",a=function(e){switch(e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0){case 1:return"浏览器定位权限被拒绝,请在浏览器设置中允许位置访问后重试";case 2:return"暂时无法获取浏览器位置,请检查设备定位服务后重试";case 3:return"获取浏览器位置超时,请重试";default:return e instanceof Error&&e.message.includes("not available")?"当前浏览器不支持定位,请手动配置坐标":"获取浏览器位置失败,请重试"}}(e);return console.error("Browser geolocation failed",e),t===this.revision&&(this.browserAuthorization=n,this.browserLocation=void 0,this.updateSnapshot({browserAuthorization:n,errorMessage:a,latitude:void 0,longitude:void 0,message:"定位失败",source:void 0,tone:"error",updatedAtMs:Date.now()})),{code:r,message:a,status:"browser_unauthorized"}}createBrowserUnauthorizedResult(){return{message:this.snapshot.errorMessage||"浏览器未授权定位,请在 Sandbox 面板配置位置",status:"browser_unauthorized"}}startBrowserWatch(e){this.clearBrowserWatch();let t=++this.watchRevision,r="u"<typeof navigator?void 0:navigator.geolocation;r?this.browserWatchId=r.watchPosition(e=>{if(t!==this.watchRevision||!this.updatesActive)return;let r=this.toBrowserLocation(e);this.browserAuthorization="granted",this.browserLocation=r,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:r.latitude,longitude:r.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()}),this.emitLocation({location:r,status:"success"})},e=>{t===this.watchRevision&&this.updatesActive&&this.emitLocation(this.handleBrowserError(e))},e):this.emitLocation(this.handleBrowserError(Error("Geolocation is not available in the current browser")))}clearBrowserWatch(){if(this.watchRevision+=1,void 0===this.browserWatchId)return;let e="u"<typeof navigator?void 0:navigator.geolocation;null==e||e.clearWatch(this.browserWatchId),this.browserWatchId=void 0}updateSnapshot(e){this.snapshot={...this.snapshot,...e,browserAuthorization:this.browserAuthorization,userAuthorization:this.userAuthorization},this.emitSnapshot()}emitSnapshot(){for(let e of this.snapshotListeners)e()}emitLocation(e){for(let t of this.locationListeners)t(e)}},af=new Map,av={"scope.userLocation":{description:"将使用你的位置信息,用于提供定位及位置相关服务。",title:"申请获取你的位置信息"},"scope.userFuzzyLocation":{description:"将使用你的大致位置信息,用于提供位置相关服务。",title:"申请获取你的模糊位置信息"},"scope.userLocationBackground":{description:"将在应用插件进入后台后继续使用你的位置信息。",title:"申请获取你的后台位置信息"},"scope.record":{description:"将使用你的麦克风,用于录制音频内容或进行语音输入。",title:"申请获取你的麦克风权限"},"scope.bluetooth":{description:"将使用你的蓝牙,用于发现和连接附近设备。",title:"申请获取你的蓝牙权限"},"scope.camera":{description:"将使用你的相机,用于拍摄照片或视频。",title:"申请获取你的相机权限"},"scope.addPhoneContact":{description:"将使用你的通讯录,用于添加或更新联系人。",title:"申请获取你的通讯录读写权限"},"scope.addPhoneCalendar":{description:"将使用你的日历,用于添加或更新日程。",title:"申请获取你的日历读写权限"}};function ay(e,t){return`${e||"unknown-app"}:${t}`}function a_(e){return av[e]??{description:"需要获得你的授权后才能继续使用此功能。",title:`申请获取你的${e.replace(/^scope\./,"")||"相关"}权限`}}async function ab(e){var t;let{appId:r,appIcon:n,appName:a,presenter:i,scope:s,skipDialogIfDenied:o=!1}=e,l=r||"unknown-app",d=af.get(ay(l,s));if("granted"===d)return!0;if("denied"===d&&o)return!1;if(!i)return"denied"!==d;let u=await i({appId:l,appIcon:n,appName:a||"应用插件",scope:s,...a_(s)});return t=u?"granted":"denied",af.set(ay(l,s),t),u}let aw="location_api_not_implemented";function aS(e,t){return w(e,"user_unauthorized"===t.status?"user permission denied":t.message)}async function ax(e){let t=await ab({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.userLocation",skipDialogIfDenied:!0});return ag.updateUserAuthorization(t),t}let aI=new Set,ak=new WeakSet,aC=0;function aE(){return navigator.connection}function aN(){var e;let t,r=aE(),n=null==r?void 0:r.effectiveType;return{isConnected:!1!==navigator.onLine,networkType:(t=null==(e=aE())?void 0:e.effectiveType,!1===navigator.onLine?"none":"slow-2g"===t||"2g"===t?"2g":"3g"===t||"4g"===t?t:"unknown"),signalStrength:null==r?void 0:r.downlink,hasSystemProxy:!1,weakNet:"slow-2g"===n||"2g"===n}}function aM(){return{timestamp:performance.now()/1e3,wallTime:Date.now()/1e3}}function aT(e){for(let t of aI)try{t(e)}catch(e){console.error("Failed to record doubao.request in Chrome DevTools",e)}}function aR(){let e=aN();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}async function aA(e,t,r){let n=await ab({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:t,skipDialogIfDenied:r});return ag.isLocationScope(t)&&ag.updateUserAuthorization(n),n}let aP="app_id_missing",aj="cashier_unavailable",aL="create_order_failed",aD="developer_order_exists",aO="login_credential_invalid",aU="login_credential_missing",aq="login_authorization_failed",a$="login_authorization_unsupported",aB="login_state_invalid",aF="login_session_unavailable",aW="payment_amount_invalid",aH="payment_authorization_invalid",az="payment_cancelled",aV="payment_data_invalid",aG="payment_data_missing",aJ="payment_data_unavailable",aK="payment_data_unavailable_with_sign",aX="payment_data_unsupported",aZ="payment_failed",aQ="payment_method_unavailable",aY="payment_order_invalid",a0="payment_parameter_missing",a1="payment_params_invalid",a2="payment_params_unavailable",a3="payment_sign_params_invalid",a4="payment_sign_params_unavailable",a5="payment_incomplete",a6="privacy_state_unavailable",a8="privacy_authorization_failed",a7="pre_order_failed",a9="phone_authorization_failed",ie="request_format_invalid",it="request_params_invalid",ir="sandbox_resource_not_found",ia="sandbox_service_unavailable",ii="sandbox_session_expired",is="sandbox_session_forbidden",io="sign_order_failed",il="sign_order_already_exists",id="sign_order_not_found",iu="sign_order_params_invalid",ic="sign_order_status_invalid",ip="sign_order_create_failed",ih="sign_page_params_invalid",im="sign_page_unavailable",ig="sign_page_data_unavailable",iv="请求暂时无法完成,请稍后重试;如持续失败,请提供 log_id";function iy(e,t){return!t||e.includes(t)?e:`${e}(log_id: ${t})`}class i_ extends Error{code;details;logId;constructor(e,t={},r){super(iI(e,t,r)),this.code=e,this.details=t,this.logId=r,this.name="SandboxError"}}class ib extends Error{remoteCode;options;constructor(e,t,r={}){super(t),this.remoteCode=e,this.options=r,this.name="SandboxRemoteError"}}let iw={[aP]:"当前未配置应用 ID,请先完成应用配置。",[aj]:"无法打开模拟器收银台,请刷新模拟器后重试。",[aL]:"暂时无法创建订单,请检查签名参数后稍后重试;如持续失败,请提供 log_id",[aD]:"开发者订单号已存在,请查询原订单",[aO]:"登录失败:登录凭证已过期或已使用,请重新发起登录。",[aU]:"登录失败:成功登录回调未携带业务登录凭证,请检查登录实现。",[aq]:"暂时无法完成登录授权,请重新发起授权",[a$]:"当前 Sandbox 无法完成该授权请求,请检查授权方式和会话配置",[aB]:"用户登录状态已失效,请重新登录",[aF]:"登录失败:模拟器会话不可用,请登录开发者账号后重新打开模拟器。",[aW]:"支付金额无效,请使用最小货币单位的整数,并由业务服务端生成金额。",[aH]:"支付授权校验失败,请确认 data 和 dbAuthorization 使用同一个 dev.key 生成,并且模拟器配置了匹配的 dev.csr。",[az]:"已取消支付。",[aV]:"支付数据格式无效,请检查业务服务端生成的 pay_data。",[aJ]:"无法打开收银台:模拟器未返回支付数据,请检查订单状态和预下单响应。",[aK]:"无法打开支付签约收银台:模拟器未返回支付数据,请检查签约参数和订单状态。",[aX]:"当前支付数据不支持模拟器收银台,请检查模拟器支付配置。",[aZ]:iv,[aQ]:"支付数据中没有可用的支付方式,请检查模拟器支付配置。",[aY]:"订单不存在或不属于当前应用",[a1]:"请求参数不正确,请检查订单信息和金额",[a2]:"暂时无法获取支付参数,请检查订单号后重试;如持续失败,请提供 log_id",[a3]:"请求参数不正确,请检查订单号和签约信息",[a4]:"暂时无法获取支付参数,请稍后重试;如持续失败,请提供 log_id",[a5]:"模拟支付未完成,请检查支付方式和订单状态后重试;如持续失败,请提供 log_id",[a6]:"暂时无法读取或保存授权状态,请稍后重试",[a8]:"隐私授权失败:请刷新模拟器后重试。",[a7]:"预下单失败:模拟器未返回订单 ID,请检查业务服务端预下单响应。",[a9]:"手机号授权失败:无法获取手机号授权凭证,请重试或使用其他登录方式。",[ie]:"请求格式不正确,请检查后重试",[it]:"请求参数不正确,请检查必填字段和字段格式",[ir]:"未找到沙箱会话或相关资源,请重新创建后重试",[ia]:"沙箱服务暂时不可用,请稍后重试;如持续失败,请提供 log_id",[ii]:"沙箱会话已过期,请重新启动调试会话",[is]:"当前沙箱会话无权访问该应用,请检查应用和会话是否匹配",[io]:"创建签约订单失败:模拟器未返回签约订单 ID,请检查签约参数。",[il]:"开发者签约单号已存在,请查询原签约单",[id]:"签约单不存在或不属于当前应用",[iu]:"签约单参数无效,请检查单号、应用和有效期",[ic]:"当前签约单状态不允许继续签约",[ip]:"暂时无法创建签约单,请检查签名参数后重试;如持续失败,请提供 log_id",[ih]:"签约单参数无效,请检查单号、应用和有效期",[im]:"暂时无法获取签约页,请稍后重试;如持续失败,请提供 log_id",[ig]:"打开签约页面失败:模拟器未返回签约数据,请检查签约订单状态。"},iS={id:"支付方式 ID",name:"支付方式名称",pay_order_no:"支付订单号",pay_status:"支付状态",trade_no:"交易号"},ix={data:"业务服务端生成的 data",dbAuthorization:"业务服务端生成的 dbAuthorization",orderId:"requestOrder 返回的 orderId",signData:"业务服务端生成的 signData",signDbAuthorization:"业务服务端生成的 signDbAuthorization"};function iI(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return iy(function(e,t){if(e===aG){let e=t.field?iS[t.field]:"必要字段";return`支付数据缺少${e},请检查业务服务端生成的 pay_data。`}if(e===a0){let e=t.key?ix[t.key]:"该参数";return`缺少支付参数,请提供${e}。`}return iw[e]}(e,t),r)}function ik(e){if("number"==typeof e&&Number.isInteger(e))return e;if("string"==typeof e&&e.trim()){let t=Number(e);return Number.isInteger(t)?t:void 0}}let iC={400:it,401:ii,403:is,404:ir,500:ia};function iE(e,t){return 400===t?ie:void 0===e?void 0:iC[e]}let iN={[aK]:a3,[io]:iu,[ig]:ih},iM={[a7]:aL,[aK]:a4,[io]:ip,[ig]:im};function iT(e,t,r){switch(e){case 500:return"payment"===r?a5:ia;case 4201:return aH;case 0x1dcd6501:return iN[t]??a1;case 0x1dcdb322:return aD;case 5e8:return iM[t]??a2;case 0x1dcdb325:return t===ig?id:aY;case 0x1dcdb327:return il;case 0x1dcdb328:return ic;default:return void 0===e||0===e?t:aZ}}let iR={[-1]:aF,4001:aO,2001:a8,502:aq,402:aB,501:a6,400:it};function iA(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("code"===r.errorField){let t=iE(e,r.httpStatus);if(t)return t}return"data.error_code"===r.errorField&&40001===e?a$:"err_code"===r.errorField&&401===e?it:1001===e?"phone"===t?a9:aO:void 0===e?ia:iR[e]??ia}function iP(e,t){return e instanceof i_?e:e instanceof ib?new i_(iA(e.remoteCode,t,e.options),{},e.options.logId):new i_(ia)}function ij(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:iv,r=arguments.length>2?arguments[2]:void 0;if(e instanceof i_)return iI(e.code,e.details,e.logId??r);if(e instanceof ib){let t="code"===e.options.errorField?iE(e.remoteCode,e.options.httpStatus):void 0,n=iT(e.remoteCode,aZ,e.options.operation);return iI(e.options.operation?n:t??n,{},e.options.logId??r)}return iy(t,r)}function iL(e,t){let r=e.err_code;if(r)throw new i_(iA(r,t,{errorField:"err_code"}),{},e.log_id)}function iD(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:{code:ik(e.code),logId:"string"==typeof e.log_id?e.log_id:void 0}}function iO(e,t){let{code:r,logId:n}=iD(e);if(r)throw new ib(r,`Sandbox 请求失败,错误码为 ${String(r)}。`,{errorField:"code",httpStatus:t,logId:n})}let iU="web-sdk-debugger",iq=[{id:"douyin",name:"抖音支付"}];async function i$(e){let t=await fetch("/__web_sdk_sandbox_proxy__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({})),{code:n,logId:a}=iD(r);if(!t.ok)throw new ib(n,`Sandbox 代理请求失败,HTTP 状态码为 ${t.status}。`,{errorField:"code",httpStatus:t.status,logId:a});return iO(r,t.status),r}let iB=new class{request=()=>{throw Error("FlowAppDeveloperOpenGatewayService.request is undefined")};baseURL="";constructor(e){this.request=(null==e?void 0:e.request)||this.request,this.baseURL=(null==e?void 0:e.baseURL)||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}FetchPackageDownLoadInfo(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/packet`);return this.request({url:r,method:"POST"},t)}GetArtifactStatus(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/artifact`);return this.request({url:r,method:"POST"},t)}GetUserBasicInfo(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/user/basic"),a={user_name:r.user_name,user_id:r.user_id};return this.request({url:n,method:"GET",params:a},t)}GetConfigRoleList(e,t){let r=this.genBaseURL("/app_developer/api/config/role/role_list");return this.request({url:r,method:"GET"},t)}RoleListByAppid(e,t){let r=this.genBaseURL("/app_developer/api/user/role/role_list");return this.request({url:r,method:"GET"},t)}UpdateUserName(e,t){let r=this.genBaseURL("/app_developer/api/user/basic/update_user_name"),n={user_name:e.user_name};return this.request({url:r,method:"PUT",data:n},t)}GetInviteMemberList(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/member/member_list"),a={app_key:r.app_key,user_name:r.user_name,page_size:r.page_size,page_num:r.page_num};return this.request({url:n,method:"GET",params:a},t)}SendInviteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/invite/send_invite`),n={role_code:e.role_code,target_user_id:e.target_user_id};return this.request({url:r,method:"POST",data:n},t)}UpdateAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta/update`),n={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:n},t)}SubmitRelease(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/release`);return this.request({url:r,method:"POST"},t)}ActivateDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/activate"),n={user_code:e.user_code,client_name:e.client_name};return this.request({url:r,method:"POST",data:n},t)}GetPlatformCert(e,t){let r=this.genBaseURL("/app_developer/api/platform/cert");return this.request({url:r,method:"GET"},t)}UploadCsr(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_csr`),n={csr_pem:e.csr_pem};return this.request({url:r,method:"POST",data:n},t)}GetAppCert(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/cert`);return this.request({url:r,method:"GET"},t)}CreateApp(e,t){let r=this.genBaseURL("/app_developer/api/apps"),n={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:n},t)}UploadIcon(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_icon`);return this.request({url:r,method:"POST"},t)}SubmitAudit(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/submit_audit`);return this.request({url:r,method:"POST"},t)}IssueDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/code"),n={client_name:e.client_name};return this.request({url:r,method:"POST",data:n},t)}GetAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),n={offset:e.offset,limit:e.limit,keyword:e.keyword};return this.request({url:r,method:"GET",params:n},t)}UpdateAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),n={action:e.action,subject:e.subject};return this.request({url:r,method:"POST",data:n},t)}ExchangeDeviceToken(e,t){let r=this.genBaseURL("/app_developer/oauth/token"),n={device_code:e.device_code};return this.request({url:r,method:"POST",data:n},t)}ListApps(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/apps"),a={app_limit:r.app_limit,app_offset:r.app_offset,key_word:r.key_word,app_key:r.app_key};return this.request({url:n,method:"GET",params:a},t)}GetAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta`),n={limit:e.limit,offset:e.offset,status:e.status};return this.request({url:r,method:"GET",params:n},t)}ToolList(e,t){let r=this.genBaseURL("/developer/api/tools/list"),n={mcp_server_url:e.mcp_server_url,mcp_config:e.mcp_config};return this.request({url:r,method:"GET",params:n},t)}GetMiniAppVersionArtifact(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/artifact`);return this.request({url:r,method:"GET"},t)}UploadMiniAppVersionDraftPackage(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/upload`),n={source_type:e.source_type};return this.request({url:r,method:"POST",params:n},t)}SubmitMiniAppVersionDraft(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/submit`),n={project_config_version:e.project_config_version,app_version_tag:e.app_version_tag};return this.request({url:r,method:"POST",data:n},t)}ListMiniAppVersions(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions`),n={page:e.page,page_size:e.page_size,id:e.id};return this.request({url:r,method:"GET",params:n},t)}VerifyYAML(e,t){let r=this.genBaseURL("/app_developer/api/yaml/verify"),n={yaml:e.yaml,mode:e.mode,yaml_type:e.yaml_type};return this.request({url:r,method:"POST",data:n},t)}GetMiniAppVersionYAML(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest`);return this.request({url:r,method:"GET"},t)}GetMiniAppVersionStructuredManifest(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest_struct`);return this.request({url:r,method:"GET"},t)}QrcodeInfo(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_info"),n={app_key:e.app_key};return this.request({url:r,method:"POST",data:n},t)}GetMiniAppVersionDraftPackageDownloadURL(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/download_url`),n={source_type_list:e.source_type_list};return this.request({url:r,method:"GET",params:n},t)}GetSubMerchantList(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_list"),n={org_id:e.org_id};return this.request({url:r,method:"GET",params:n},t)}AppBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/app_bind_sub_merchant`),n={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"PUT",data:n},t)}CreateSubMerchant(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/create_sub_merchant"),n={org_id:e.org_id,sub_merchant_name:e.sub_merchant_name};return this.request({url:r,method:"POST",data:n},t)}UnBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/unbind_sub_merchant`),n={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"POST",data:n},t)}GetSubMerchantCaijingUrl(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_url"),n={sub_merchant_uid:e.sub_merchant_uid};return this.request({url:r,method:"POST",data:n},t)}GetAppBindSubMerchants(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/get_bind_sub_merchants`);return this.request({url:r,method:"GET"},t)}GetAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/get_callback_conf`),n={source:e.source};return this.request({url:r,method:"GET",params:n},t)}UpdateAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/update_callback_conf`),n={source:e.source,callback_address:e.callback_address};return this.request({url:r,method:"PUT",data:n},t)}CreateOrganization(e,t){let r=this.genBaseURL("/app_developer/api/organization"),n={name:e.name};return this.request({url:r,method:"POST",data:n},t)}UpdateOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/update`),n={name:e.name};return this.request({url:r,method:"POST",data:n},t)}FinishMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/finish`),n={upload_token:e.upload_token,size:e.size,sha256:e.sha256};return this.request({url:r,method:"POST",data:n},t)}DeleteOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/delete`);return this.request({url:r,method:"POST"},t)}GetOrganizationToken(e,t){let r=this.genBaseURL("/app_developer/api/organization/get_token"),n={org_code:e.org_code};return this.request({url:r,method:"POST",data:n},t)}StartMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/start`),n={sha256:e.sha256};return this.request({url:r,method:"POST",data:n},t)}ListOrganizations(e,t){let r=this.genBaseURL("/app_developer/api/organizations/list");return this.request({url:r,method:"GET"},t)}CreateAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_create`),n={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}DeleteAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/delete`),n={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}VerifyAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_verify`),n={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}CreateAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/create`),n={domain:e.domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}GetAppDomainList(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/list`);return this.request({url:r,method:"GET"},t)}SandboxGetAwemeCommonLoginInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/auth/get_aweme_common_login_info"),n={app_key:e.app_key};return this.request({url:r,method:"POST",data:n},t)}SandboxUpdateMessageCardWidgetData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/update_message_card_widget_data"),n={mixture_card_id:e.mixture_card_id,message_id:e.message_id,widget_id:e.widget_id,widget_data:e.widget_data};return this.request({url:r,method:"POST",data:n},t)}SandboxCreateSignOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/create_sign_order"),n={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:n},t)}SandboxGetOrderPaymentWithSign(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment_with_sign"),n={order_id:e.order_id,sign_data:e.sign_data,sign_db_authorization:e.sign_db_authorization,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:n},t)}SandboxRequestOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/request_order"),n={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:n},t)}SandboxGetSignPageData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_sign_page_data"),n={auth_order_id:e.auth_order_id,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:n},t)}SandboxGetMessageInfoByMixtureCardID(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/get_message_info_by_mixture_card_id"),n={mixture_card_id:e.mixture_card_id};return this.request({url:r,method:"POST",data:n},t)}SandboxGetOrderPayment(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment"),n={order_id:e.order_id,app_key:e.app_key,platform_signed_pt_code:e.platform_signed_pt_code,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:n},t)}SandboxApiGetUserAppsPermissionDetail(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/detail"),n={applets_list:e.applets_list};return this.request({url:r,method:"POST",data:n},t)}SandboxApiPostUserAppsPermission(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/post"),n={applet_id:e.applet_id,update_scope_info:e.update_scope_info,using_scope_infos:e.using_scope_infos};return this.request({url:r,method:"POST",data:n},t)}SandboxApiGetUserAppsPermissionRecord(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/record"),n={applet_id:e.applet_id};return this.request({url:r,method:"POST",data:n},t)}SandboxApiExchangeCode(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/jsb/oauth/token"),a={app_key:r.app_key,code:r.code,device_id:r.device_id,version_tag:r.version_tag};return this.request({url:n,method:"POST",data:a},t)}SandboxApiGetPhoneMask(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/phone_mask");return this.request({url:r,method:"POST"},t)}SandboxApiCheckPrivacyOrLoginStatus(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy_login/check"),a={app_key:r.app_key,version_tag:r.version_tag,check_type:r.check_type};return this.request({url:n,method:"POST",data:a},t)}SandboxApiAcceptPrivacy(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy/accept"),a={app_key:r.app_key,request_id:r.request_id,device_id:r.device_id};return this.request({url:n,method:"POST",data:a},t)}SandboxApiDeleteDataObtainedByTicket(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/ticket_revoke"),n={applet_id:e.applet_id,scope_name:e.scope_name,permission_ticket_type:e.permission_ticket_type};return this.request({url:r,method:"POST",data:n},t)}ListPublicNoticeTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates`),n={category:e.category,subscription_type:e.subscription_type,keyword:e.keyword,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:n},t)}SandboxIssueLoginCode(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/passport/open/auth"),n={client_key:e.client_key,aid:e.aid,scope:e.scope,source:e.source,exchange_type:e.exchange_type};return this.request({url:r,method:"POST",data:n},t)}GetSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/get"),n={sandbox_session_id:e.sandbox_session_id};return this.request({url:r,method:"POST",data:n},t)}UpdateSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/update"),n={sandbox_session_id:e.sandbox_session_id,phone_num:e.phone_num,csr_pem:e.csr_pem,location_info:e.location_info};return this.request({url:r,method:"POST",data:n},t)}SandboxPay(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/payment/pay"),n={trade_no:e.trade_no,pay_type:e.pay_type};return this.request({url:r,method:"POST",data:n},t)}CheckDeveloperAccessWhitelist(e,t){let r=this.genBaseURL("/app_developer/api/user/whitelist/check"),n={invite_code:(e||{}).invite_code};return this.request({url:r,method:"POST",data:n},t)}OIDCGet(e,t){let r=this.genBaseURL("/app_developer/api/oidc_get");return this.request({url:r,method:"GET"},t)}OIDCCallback(e,t){let r=this.genBaseURL("/app_developer/api/oidc_callback"),n={code:e.code,nonce:e.nonce,state:e.state};return this.request({url:r,method:"GET",params:n},t)}AuditDetail(e,t){let r=this.genBaseURL("/app_developer/api/apps/audit/detail"),n={audit_id:e.audit_id,audit_type:e.audit_type};return this.request({url:r,method:"POST",data:n},t)}ListBusinessTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates`),n={biz_type:e.biz_type,status:e.status,sync_status:e.sync_status,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:n},t)}GetBusinessTemplatesYaml(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/yaml`),n={status:e.status};return this.request({url:r,method:"GET",params:n},t)}DeleteBusinessTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/${e.biz_type}/${e.template_key}/delete`);return this.request({url:r,method:"POST"},t)}GetPublicNoticeTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates/${e.public_template_key}`);return this.request({url:r,method:"GET"},t)}PullSandboxNotices(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/resources/notices/pull"),a={notice_ids:r.notice_ids,cursor:r.cursor,limit:r.limit};return this.request({url:n,method:"POST",data:a},t)}RemoveSandboxTaskFromUser(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/remove_from_user"),n={task_id:e.task_id};return this.request({url:r,method:"POST",data:n},t)}PullSandboxTasks(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/pull"),a={task_ids:r.task_ids,cursor:r.cursor,limit:r.limit};return this.request({url:n,method:"POST",data:a},t)}CreateSandboxSession(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/create"),n={sandbox_project_id:e.sandbox_project_id,app_id:e.app_id,bridge_origins:e.bridge_origins,manifest:e.manifest};return this.request({url:r,method:"POST",data:n},t)}PreviewTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/preview`),n={object_key:e.object_key};return this.request({url:r,method:"GET",params:n},t)}QrcodeShort(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_short"),n={url:e.url,ttl:e.ttl};return this.request({url:r,method:"POST",data:n},t)}GetQrcodeURL(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_url"),n={token:e.token};return this.request({url:r,method:"POST",data:n},t)}DownloadTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/download`),n={object_key:e.object_key};return this.request({url:r,method:"GET",params:n},t)}SandboxCallMcpTool(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/call_mcp_tool"),n={tool_name:e.tool_name,tool_args_json:e.tool_args_json,widget_instance_id:e.widget_instance_id,artifact_version_code:e.artifact_version_code,app_key:e.app_key,widget_id:e.widget_id,scene:e.scene,skip_widget_update:e.skip_widget_update};return this.request({url:r,method:"POST",data:n},t)}DeleteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/delete`),n={user_id:e.user_id};return this.request({url:r,method:"POST",data:n},t)}SubmitSandboxEventReport(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/bridge/events/report"),n={event_id:e.event_id,data:e.data},a={"X-DBX-Sandbox-Session-ID":e["X-DBX-Sandbox-Session-ID"]};return this.request({url:r,method:"POST",data:n,headers:a},t)}UploadSimulatorImage(e,t){let r=this.genBaseURL("/app_developer/api/simulator/images/upload"),n={image:e.image};return this.request({url:r,method:"POST",data:n},t)}}({baseURL:"",request:i$});function iF(e,t){if(!e.data)throw Error(e.message||`${t} returned empty data`);return e.data}async function iW(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return iF(await iB.PullSandboxNotices(e),"PullSandboxNotices")}async function iH(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return iF(await iB.PullSandboxTasks(e),"PullSandboxTasks")}async function iz(e){return iF(await iB.RemoveSandboxTaskFromUser({task_id:e}),"RemoveSandboxTaskFromUser").removed_task}async function iV(e,t){return i$({data:{event_id:e,data:t},method:"POST",url:"/app_developer/api/sandbox/bridge/events/report"})}async function iG(e){let{appletId:t,granted:r,scopeName:n}=e;if(!t.trim())throw Error("appletId is required");if(!n.trim())throw Error("scopeName is required");let a=await iB.SandboxApiPostUserAppsPermission({applet_id:t,update_scope_info:{grant_status:r?1:2,scope_name:n}});if(0!==a.err_code)throw Error(a.err_msg||`Sandbox post Agentic Service permission failed with code ${String(a.err_code)}`)}async function iJ(e){let{appKey:t,params:r,scene:n}=e;if(!t.trim())throw Error("callTool requires a simulator app context");if("widget"===n&&(!e.widgetId.trim()||!e.widgetInstanceId.trim()))throw Error("callTool requires a simulator conversation card context");let{skipWidgetUpdate:a,toolArgs:i,toolName:s}=function(e){if(!tj(e)||"string"!=typeof e.toolName||!e.toolName.trim()||!tj(e.toolArgs)||void 0!==e.skipWidgetUpdate&&"boolean"!=typeof e.skipWidgetUpdate)throw Error("callTool requires a non-empty toolName, an object toolArgs, and an optional boolean skipWidgetUpdate");return{skipWidgetUpdate:e.skipWidgetUpdate??!1,toolName:e.toolName.trim(),toolArgs:e.toolArgs}}(r),o=await iB.SandboxCallMcpTool({app_key:t,scene:"page"===n?2:1,skip_widget_update:a,tool_args_json:JSON.stringify(i),tool_name:s,..."widget"===n?{widget_id:e.widgetId,widget_instance_id:e.widgetInstanceId}:{}}),l=ik(o.err_code);if(void 0!==l&&0!==l)throw new ib(l,o.err_msg||`callTool failed with code ${l}`,{errorField:"err_code",logId:o.log_id});if(!o.result)throw Error(o.err_msg||"callTool returned an empty result");if(1!==o.result.output_kind&&2!==o.result.output_kind)throw Error("callTool returned an invalid output kind");let d=o.result.card_update_error,u=o.result.tool_error,c=o.result.tool_result_json,p=d?{cardUpdateError:{code:d.code,message:d.message,phase:"render"}}:{};if(u){let e=ik(u.code);if(void 0!==c||void 0===e||"string"!=typeof u.message||!u.message.trim())throw Error("callTool returned an invalid Tool error");return{toolError:{code:e,message:u.message},...p}}if(void 0===c)throw Error("callTool returned neither a Tool result nor a Tool error");return{toolResult:function(e){let t=JSON.parse(e);if(!tj(t))throw Error("callTool returned an invalid ToolResult");return t}(c),...p}}function iK(e){var t;let r=(null==(t=e.getAppId)?void 0:t.call(e))||e.appId;if(!r)throw new i_(aP);return r}function iX(e,t){var r;let n=null==e||null==(r=e[t])?void 0:r.trim();if(!n)throw new i_(a0,{key:t});return n}function iZ(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments.length>4?arguments[4]:void 0,i=ik(t.err_code),s=a?(a instanceof ib?a.remoteCode:void 0)??(void 0!==i&&0!==i?i:void 0)??-1:i??-1,o=(a instanceof ib?a.options.logId:void 0)??t.log_id,l=a?ij(a,iI(r),o):iI(iT(i,r),{},o),d={code:n?s:void 0,errNo:String(s),errMsg:l,errLogId:o};return{type:"callback",callbackId:e.callbackId,params:{code:0,data:d,errNo:s,errMsg:l,msg:l}}}async function iQ(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return await t()}catch(t){return iZ(e,{},aZ,r,t)}}async function iY(e,t){let r=function(e){let t;try{t=JSON.parse(e)}catch{throw new i_(aV)}if(!t||"object"!=typeof t||Array.isArray(t))throw new i_(aV);let r=t;if("sandbox_cashier"!==r.type)throw new i_(aX);let n="string"==typeof r.total_amount?r.total_amount.trim():"";if(!n||!/^\d+$/.test(n))throw new i_(aW);let a="string"==typeof r.pay_order_no?r.pay_order_no.trim():"",i="string"==typeof r.pay_status?r.pay_status.trim():"",s="string"==typeof r.trade_no?r.trade_no.trim():"";if(!a||!i||!s)throw new i_(aG,{field:a?i?"trade_no":"pay_status":"pay_order_no"});return{paymentTypes:function(e){if(!Array.isArray(e)||0===e.length)throw new i_(aQ);let t=e.map(e=>{if(!tj(e))throw new i_(aV);let t="string"==typeof e.id?e.id.trim():"",r="string"==typeof e.name?e.name.trim():"";if(!t||!r)throw new i_(aG,{field:t?"name":"id"});return{id:t,name:r}});if(new Set(t.map(e=>{let{id:t}=e;return t})).size!==t.length)throw new i_(aV);return t}(r.pay_types??iq),payOrderNo:a,payStatus:i,totalAmount:n,tradeNo:s,type:"sandbox_cashier"}}(e);if(!t.showSandboxCashier)throw new i_(aj);if(!await t.showSandboxCashier(r,async e=>{if(!r.paymentTypes.some(t=>{let{id:r}=t;return r===e}))throw new i_(aQ);try{await iB.SandboxPay({trade_no:r.tradeNo,pay_type:e})}catch(e){if(e instanceof ib&&"code"===e.options.errorField&&500===e.remoteCode)throw new ib(e.remoteCode,e.message,{...e.options,operation:"payment"});throw e}}))throw new i_(az)}async function i0(e,t){let r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"user_info",a=t?"phone":"login";try{r=await iB.SandboxIssueLoginCode({aid:"482431",client_key:iK(e),scope:n,source:"jsb",exchange_type:t})}catch(e){throw iP(e,a)}var i,s,o=ik(null==(i=r.data)?void 0:i.error_code),l=iD(r).logId;if(o)throw new i_(iA(o,a,{errorField:"data.error_code"}),{},l);let d=null==(s=r.data)?void 0:s.code;if(!d)throw new i_(ia);return d}async function i1(e){try{let t=void 0!==e.locationInfo,r=await iB.UpdateSandboxBusinessInfo({csr_pem:e.csrPem||(t?"":void 0),location_info:e.locationInfo,phone_num:e.phoneNum,sandbox_session_id:""});return iO(r),r}catch(r){let e=r instanceof ib?r.options.logId:r&&"object"==typeof r&&"logId"in r&&"string"==typeof r.logId?r.logId:void 0,t=Error(iy(r instanceof Error?r.message:String(r),e));throw t.logId=e,t}}async function i2(e){return i1(e)}async function i3(e){return i1({csrPem:"",locationInfo:e,phoneNum:""})}async function i4(e){let t=await fetch("/__web_sdk_sandbox_session_recreate__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({}));if(!t.ok)throw Error((null==r?void 0:r.message)||`Sandbox session recreate failed with status ${t.status}`);return r}let i5=["aztec","codabar","code_39","code_93","code_128","data_matrix","ean_8","ean_13","itf","pdf417","qr_code","upc_a","upc_e"],i6={barCode:["codabar","code_39","code_93","code_128","ean_8","ean_13","itf","upc_a","upc_e"],datamatrix:["data_matrix"],pdf417:["pdf417"],qrCode:["qr_code"]};async function i8(e){let t=e.getSupportedFormats;return"function"==typeof t?new Set(await t()):null}function i7(e){var t,r;return{characterSet:"UTF-8",path:"",rawData:(t=e.rawValue,"function"!=typeof btoa||"u"<typeof TextEncoder?t:btoa(String.fromCharCode(...new TextEncoder().encode(t)))),result:e.rawValue,scanType:(r=e.format,i5.includes(r)?"pdf417"===r?"PDF_417":r.toUpperCase():"QR_CODE")}}async function i9(e,t){if("function"==typeof createImageBitmap){let r=await createImageBitmap(t);try{return e.detect(r)}finally{r.close()}}let r=new Image,n=URL.createObjectURL(t);try{return await new Promise((e,t)=>{r.onload=()=>e(),r.onerror=()=>t(Error("Failed to load selected image")),r.src=n}),e.detect(r)}finally{URL.revokeObjectURL(n)}}function se(e,t,r,n,a){return t()?Promise.resolve():new Promise((i,s)=>{let o=0,l=()=>{for(let t of(window.clearTimeout(o),r))e.removeEventListener(t,d);e.removeEventListener("error",u)},d=()=>{t()&&(l(),i())},u=()=>{l(),s(Error(a))};for(let t of(o=window.setTimeout(()=>{l(),s(Error(a))},n),r))e.addEventListener(t,d);e.addEventListener("error",u)})}async function st(e,t){e.srcObject=t,await se(e,()=>e.readyState>=HTMLMediaElement.HAVE_METADATA,["loadedmetadata"],3e3,"Camera stream started, but video metadata was not loaded"),await e.play(),await se(e,()=>e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA,["loadeddata","canplay","playing"],3e3,"Camera stream started, but no video frame was rendered")}async function sr(e,t){var r;let n,a=globalThis.BarcodeDetector;if(!a)throw Error("BarcodeDetector is not supported in this browser");let i=await i8(a),s=[...new Set((null==(r=e.scanType)?void 0:r.length)?e.scanType.flatMap(e=>i6[e]):i5)].filter(e=>!i||i.has(e));if(0===s.length)throw Error("Requested scanType is not supported in this browser");let o=new a({formats:s}),l=!1,d=!1,u=0,c=null,p=null,h=()=>{null==c||c.getTracks().forEach(e=>e.stop()),c=null,p&&(p.srcObject=null)},m=()=>{l||(l=!0,window.cancelAnimationFrame(u),h(),null==n||n.close())};try{return await new Promise((r,a)=>{let i=e=>{m(),e()},s=e=>{if(!l&&!d){if(!p||p.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){e&&(null==n||n.setMessage("摄像头画面还未准备好"));return}d=!0,o.detect(p).then(t=>{let a=t[0];a?i(()=>r(i7(a))):e&&(null==n||n.setMessage("未识别到二维码或条形码"))}).catch(t=>{e&&(null==n||n.setMessage(t instanceof Error?t.message:String(t)))}).finally(()=>{d=!1})}};n=t({allowImageUpload:!e.onlyFromCamera,onCancel:()=>i(()=>a(Error("scanCode canceled"))),onCapture:()=>s(!0),onFile:e=>{l||(null==n||n.setMessage("正在识别图片..."),i9(o,e).then(e=>{let t=e[0];t?i(()=>r(i7(t))):null==n||n.setMessage("未识别到二维码或条形码,请换一张图片重试")}).catch(e=>{null==n||n.setMessage(e instanceof Error?e.message:String(e))}))},onVideoReady:t=>{var r;if(!p&&!l){if(p=t,!(null==(r=navigator.mediaDevices)?void 0:r.getUserMedia))return e.onlyFromCamera?void i(()=>a(Error("Camera is not available in this browser"))):void(null==n||n.setMessage("无法使用摄像头,请从相册选择二维码或条形码图片"));navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:{ideal:"environment"}}}).then(e=>l?void e.getTracks().forEach(e=>e.stop()):(c=e,st(t,e))).then(()=>{if(l)return;let e=()=>{l||(s(!1),u=window.requestAnimationFrame(e))};e()}).catch(t=>{if(l)return;let r=t instanceof Error?t.message:String(t);if(h(),e.onlyFromCamera){null==n||n.setMessage(r),i(()=>a(t instanceof Error?t:Error(r)));return}null==n||n.setMessage(`无法使用摄像头,请从相册选择二维码或条形码图片:${r}`)})}}})})}catch(e){throw m(),e}}function sn(){throw Error("Simulator UI presenter is unavailable")}function sa(){return{hideLoading:sn,hideToast:sn,showActionSheet:async()=>sn(),showBottomSheet:async()=>sn(),showLoading:sn,showModal:async()=>sn(),showToast:sn}}let si="doubao-web-sdk-debugger-vibration-style",ss="doubao-web-sdk-debugger-screen-vibrating",so={heavy:4,light:1,medium:2},sl=0,sd=null;function su(e){e.classList.remove(ss),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-distance"),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-duration")}function sc(e,t,r){if(!("function"==typeof navigator.vibrate&&navigator.vibrate(e)&&function(){let e=navigator.maxTouchPoints??0;if(e<=0)return!1;let t=navigator.platform??"",r=navigator.userAgent??"";return/android|iphone|ipad|ipod|mobile/i.test(`${t} ${r}`)||/mac/i.test(t)&&e>1}())){let n;(function(){if(document.getElementById(si))return;let e=document.createElement("style");e.id=si,e.textContent=`
|
|
23
|
+
</svg>`,tk="doubao-apps-page",tC={body:`${tk}__body`,capsule:`${tk}__capsule`,capsuleAction:`${tk}__capsule-action`,capsuleCloseIcon:`${tk}__capsule-close-icon`,capsuleMoreIcon:`${tk}__capsule-more-icon`,root:tk};class tE{host;options;runtimeKernel;container=null;root=null;constructor(e,t){if(!e.container)throw Error("Page requires a container element");this.host=e.container,this.options=e,this.runtimeKernel=t}get element(){var e;return(null==(e=this.container)?void 0:e.element)??null}render(e){var t,r;let n;this.clear();let a=document.createElement("div");a.className=tC.root,void 0!==(n=null==(t=e.pageCapsule)?void 0:t.statusBarHeight)&&a.style.setProperty("--doubao-page-capsule-top",`${n+4}px`);let i=document.createElement("div");i.className=tC.body,a.append(i,this.createCapsule()),this.host.replaceChildren(a),this.root=a;try{return this.container=this.runtimeKernel.createContainer({...this.options,sandboxUrl:this.options.runtime?this.options.runtime.sandboxUrl:this.options.sandboxUrl,container:i,className:this.options.className,onError:this.options.onError,onReady:this.options.onReady}),this.container.render({bridge:null==(r=this.options.runtime)?void 0:r.bridge,resourceUrl:function(e){if(!e.resourceUrl)throw Error("Page.render requires a resourceUrl");return e.resourceUrl}(e),groupId:e.groupId,containerType:"PAGE",initData:e.initData,globalProps:e.globalProps})}catch(e){throw this.clear(),e}}clear(){var e,t;null==(e=this.container)||e.clear(),this.container=null,null==(t=this.root)||t.remove(),this.root=null,this.host.replaceChildren()}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};null==(t=this.container)||t.sendEvent(e,r)}reload(){var e;null==(e=this.container)||e.reload()}dispatchCapsuleEvent(e,t){t.stopPropagation(),this.host.dispatchEvent(new CustomEvent(e,{bubbles:!0}))}createCapsuleSvg(e){let t=document.createElement("template");t.innerHTML=e.trim();let r=t.content.firstElementChild;if(!r||"svg"!==r.tagName.toLowerCase())throw Error("Invalid Page capsule icon SVG");return r}createCapsuleAction(e,t,r,n){let a=this.createCapsuleSvg(r);return a.classList.add(tC.capsuleAction,e),a.setAttribute("role","button"),a.setAttribute("aria-label",t),a.setAttribute("tabindex","0"),a.setAttribute("focusable","true"),a.addEventListener("click",e=>{this.dispatchCapsuleEvent(n,e)}),a.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),this.dispatchCapsuleEvent(n,e))}),a}createCapsuleMoreIcon(){return this.createCapsuleAction(tC.capsuleMoreIcon,"More",tx,"doubao:page-capsule-more")}createCapsuleCloseIcon(){return this.createCapsuleAction(tC.capsuleCloseIcon,"Close app",tI,"doubao:page-capsule-close")}createCapsule(){let e=document.createElement("div");return e.className=tC.capsule,e.style.display="flex",e.style.flexDirection="row",e.setAttribute("role","group"),e.setAttribute("aria-label","Page actions"),e.append(this.createCapsuleMoreIcon(),this.createCapsuleCloseIcon()),e}}let tN=/\{\{\s*([^{}\s]+)\s*\}\}/g;function tM(e){return"string"==typeof e?e:JSON.stringify(e)}function tT(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={...e.input||{},...function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};for(let[n,a]of Object.entries(e.variables||{}))Object.prototype.hasOwnProperty.call(t,n)?r[n]=t[n]:null!==a&&(r[n]=a);return{...r,...t}}(e,t)};if("page"===e.type){let t=function(e,t){var r;let n=new Set(Array.from(e.url.matchAll(tN),e=>e[1])),a=(r=e.url,r.replace(tN,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;let n=tM(t[r]);return void 0===n?e:encodeURIComponent(n)})),i=a.indexOf("#"),s=i<0?a:a.slice(0,i),o=i<0?"":a.slice(i),l=s.indexOf("?"),d=new Set(new URLSearchParams(l<0?"":s.slice(l+1)).keys()),u=new URLSearchParams;for(let[e,r]of Object.entries(t)){if(n.has(e)||d.has(e))continue;let t=tM(r);void 0!==t&&u.set(e,t)}let c=u.toString();if(!c)return a;let p=l<0?"?":s.endsWith("?")||s.endsWith("&")?"":"&";return`${s}${p}${c}${o}`}(e,r);return{type:"page",unresolvedVariables:function(e){let t=new Set;for(let r of e.matchAll(tN))t.add(r[1]);return Array.from(t)}(t),url:t}}return"widget"===e.type?{type:"widget",id:e.id,resolvedInput:r,botId:e.botId}:{type:"tool",id:e.id,resolvedInput:r}}function tR(e){var t;let{addProtocolToBareHost:r=!1,allowRootRelative:n=!1,defaultProtocol:a="http"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(/^https?:\/\//i.test(e))return e;if(e.startsWith("//"))return`${tP(a,e.slice(2))}:${e}`;if(n&&e.startsWith("/"))return e;return/^(?:\[[^\]]+\]|[a-z0-9.-]+):\d+(?:[/?#]|$)/i.test(e)||r&&(t=e,/^(?:\[[^\]]+\]|[a-z0-9.-]+)(?:[/?#]|$)/i.test(t))?`${tP(a,e)}://${e}`:e}function tA(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=String(e??"").trim();if(!r)return;let n=tR(r,t);try{let e=t.baseUrl?new URL(n,t.baseUrl):new URL(n);if("http:"!==e.protocol&&"https:"!==e.protocol)return;return e.toString()}catch{return}}function tP(e,t){return"function"==typeof e?e(t):e}function tj(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var tL=r(70851);function tD(e,t){if(e.appId&&t&&e.appId!==t)throw Error("Resolved Widget appId must match the trusted Widget identity");return t??e.appId}let tO="__doubao_apps__expired-widget",tU="doubao-apps-widget",tq=1,t$={body:`${tU}__body`,default:`${tU}--default`,floatingHeader:`${tU}--floating-header`,embedded:`${tU}--embedded`,header:`${tU}__header`,icon:`${tU}__icon`,placeholder:`${tU}__placeholder`,placeholderContent:`${tU}__placeholder-content`,root:tU,title:`${tU}__title`};class tB{container;options;runtimeKernel;identity;viewContext;root=null;body=null;title=null;icon=null;runtimeContainer=null;runtimeFallbackOptions={};apiContextOwner={};appTheme;hostCallController=null;constructor(e,t){var r,n;let a,i,o,l,d,u;if(!e.container)throw Error("Widget requires a container element");if(!e.runtime)throw Error("Widget requires a Runtime");this.container=e.container,this.options=e,this.runtimeKernel=t,this.appTheme="light"===(a=s(r=e.globalProps)?r.appTheme:void 0)||"dark"===a?a:void 0,this.identity=(n=`widget-${tq++}`,i=e.viewContext,o=e.appId??(null==i?void 0:i.appId),l=e.widgetId??(null==i?void 0:i.widgetId),d=(null==i?void 0:i.widgetInstanceId)??n,u=i?{...i,appId:o??i.appId,widgetId:l,widgetInstanceId:d}:void 0,{appId:o,versionTag:null==i?void 0:i.versionTag,viewContext:u,widgetId:l,widgetInstanceId:d}),this.viewContext=this.identity.viewContext}get element(){var e;return(null==(e=this.runtimeContainer)?void 0:e.element)??this.root}setAppTheme(e){var t;this.appTheme=e,this.root&&(this.root.dataset.appTheme=e),null==(t=this.runtimeContainer)||t.sendEvent("onThemeChange",{appTheme:e})}async render(){var e;this.clear(),this.hostCallController=new AbortController;let t=this.hostCallController.signal;try{await g(()=>this.options.runtime.loadPackage(),t)}catch(e){if(m(t),s(e)&&"AbortError"===e.name)throw e;return this.renderFallback()}if(m(t),"iframe"===(e={identity:this.identity,mode:this.runtimeKernel.mode}).mode&&e.identity.widgetId!==tO&&e.identity.appId&&e.identity.widgetId)try{this.prepareIframeRuntime()}catch{return this.renderFallback()}let r=function(e){let t;m(e.signal);let{packageInfo:r,packageManager:n}=e.options.runtime,{manifest:a}=r;if(tD(e.identity,a.appId),e.identity.widgetId===tO){var i,s;let t;return{kind:"expired",options:{appName:a.name??e.identity.appId,icon:a.iconSrc,placeholderText:"string"==typeof(t=null==(i=e.options.initData)||null==(s=i.viewData)?void 0:s.title)&&t.trim().length>0?t:void 0}}}try{let a=n.resolveWidget(r,e.identity.widgetId);if(m(e.signal),t={appName:a.appName,icon:a.icon},!a.resourceUrl)return{kind:"fallback",options:t};return{kind:"runtime",options:{appId:tD(e.identity,a.appId),boxType:a.boxType,...t,resourceUrl:a.resourceUrl,renderMode:a.renderMode??"standard",titleType:a.titleType??2*(!1===a.showHeader)}}}catch{return m(e.signal),{kind:"fallback",options:t}}}({identity:this.identity,mode:this.runtimeKernel.mode,options:this.options,signal:t});if("expired"===r.kind)return this.renderPlaceholderCard(r.options);if("fallback"===r.kind)return this.renderFallback(r.options);try{return this.renderResource(r.options)}catch{return m(t),this.renderFallback({appName:r.options.appName,icon:r.options.icon})}}getShellClassName(e){let{boxType:t,floatingHeader:r,renderMode:n}=e,a="embedded"===n;return(0,tL.$)(t$.root,{[t$.default]:4!==t&&!a,[t$.floatingHeader]:r,[t$.embedded]:a},this.options.className)}renderShell(e){var t;let r=document.createElement("section");r.className=this.getShellClassName(e),this.appTheme&&(r.dataset.appTheme=this.appTheme);let n="number"==typeof(t=this.options.contentMaxWidth)&&Number.isFinite(t)?`${t}px`:"string"==typeof t&&t.trim().length>0?t:void 0;n&&(r.style.maxWidth=n);let a=document.createElement("div");a.className=t$.body;let i=null;if(e.showHeader){(i=document.createElement("header")).className=t$.header,i.hidden="iframe"===this.runtimeKernel.mode;let e=document.createElement("img");e.alt="",e.className=t$.icon,e.height=16,e.width=16;let t=document.createElement("div");t.className=t$.title,i.append(e,t),r.append(i),this.icon=e,this.title=t}return r.append(a),this.container.replaceChildren(r),this.root=r,this.body=a,this.updateHeader(e.appName,e.icon),{body:a,header:i,root:r}}renderPlaceholderCard(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.clear();let{body:t,header:r,root:n}=this.renderShell({appName:e.appName??this.identity.widgetId??this.identity.appId??"",icon:e.icon,renderMode:"standard",showHeader:!0});r&&(r.hidden=!1);let a=document.createElement("div");a.className=t$.placeholder;let i=document.createElement("div");return i.className=t$.placeholderContent,i.textContent=e.placeholderText??this.options.fallbackText??"",a.append(i),t.append(a),n}renderFallback(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.renderPlaceholderCard({...e,placeholderText:this.options.fallbackText})}handleRuntimeError(e,t,r){try{var n,a;null==(n=(a=this.options).onError)||n.call(a,e,t)}finally{this.renderFallback({appName:r.appName,icon:r.icon})}}renderResource(e){var t,r;let n={...this.options.globalProps,__GEN_UI_DATA__:this.options.genUIData??(null==(t=this.options.globalProps)?void 0:t.__GEN_UI_DATA__),appTheme:this.appTheme,packageInfo:{...null==(r=this.options.globalProps)?void 0:r.packageInfo,appId:e.appId,iconSrc:e.icon,name:e.appName}};this.runtimeFallbackOptions={appName:e.appName,icon:e.icon};let{body:a,root:i}=this.updateOrRenderResourceShell(e);return"iframe"===this.runtimeKernel.mode&&(i.style.background="transparent",i.style.borderWidth="0"),this.runtimeContainer??=this.createRuntimeContainer(a),this.runtimeContainer.render({bridge:this.options.runtime.bridge,containerType:"WIDGET",resourceUrl:e.resourceUrl,initData:this.options.initData,globalProps:{...n,__VIEW_CONTEXT__:this.viewContext??{}}})}createRuntimeContainer(e){var t,r;let n=(null==(t=this.viewContext)||null==(r=t.shareInfo)?void 0:r.mode)==="share_page";return this.runtimeKernel.createContainer({...this.options,getAppletContext:()=>({owner:this.options.invocationOwner??this.apiContextOwner,signal:this.getHostCallSignal(),source:"widget",viewContext:this.viewContext}),sandboxUrl:this.options.runtime.sandboxUrl,captureWidgetTap:n||void 0,container:e,onUnsupportedAPI:this.options.onUnsupportedAPI,onError:(e,t)=>{this.handleRuntimeError(e,t,this.runtimeFallbackOptions)},onReady:()=>{var e,t,r;null==(e=this.root)||e.style.removeProperty("background"),null==(t=this.root)||t.style.removeProperty("border-width"),(null==(r=this.title)?void 0:r.parentElement)&&(this.title.parentElement.hidden=!1)},onWidgetInteraction:n&&this.options.onWidgetInteraction?e=>this.handleWidgetInteraction(e):void 0})}prepareIframeRuntime(){let{body:e,root:t}=this.renderShell({renderMode:"standard",showHeader:!0});t.style.background="transparent",t.style.borderWidth="0",this.runtimeFallbackOptions={},this.runtimeContainer=this.createRuntimeContainer(e),this.runtimeContainer.prepare("WIDGET")}updateOrRenderResourceShell(e){var t,r,n;let a={appName:e.appName,boxType:e.boxType,floatingHeader:1===e.titleType,icon:e.icon,renderMode:e.renderMode,showHeader:"embedded"!==e.renderMode&&2!==e.titleType};return this.root&&this.body?(this.root.className=this.getShellClassName(a),a.showHeader||(null==(n=this.title)||null==(r=n.parentElement)||r.remove(),this.icon=null,this.title=null),this.updateHeader(e.appName,e.icon),{body:this.body,header:(null==(t=this.title)?void 0:t.parentElement)??null,root:this.root}):this.renderShell(a)}clear(){var e,t,r;null==(e=this.hostCallController)||e.abort(),this.hostCallController=null,this.apiContextOwner={},null==(t=this.runtimeContainer)||t.clear(),this.runtimeContainer=null,this.runtimeFallbackOptions={},null==(r=this.root)||r.remove(),this.root=null,this.body=null,this.title=null,this.icon=null,this.container.replaceChildren()}reload(){var e;null==(e=this.runtimeContainer)||e.reload()}destroy(){this.clear()}getHostCallSignal(){if(this.hostCallController)return this.hostCallController.signal;let e=new AbortController;return e.abort(),e.signal}async handleWidgetInteraction(e){let t=this.options.onWidgetInteraction;if(!t)return;let r=this.getHostCallSignal();m(r),await t(e),m(r)}updateHeader(e,t){this.title&&(this.title.textContent=e??""),this.icon&&(t?(this.icon.src=t,this.icon.hidden=!1):(this.icon.removeAttribute("src"),this.icon.hidden=!0))}}let tF={mode:"inline",createContainer:e=>new tS(e)},tW=new eW(tF,!0);class tH{options;emptyState;cleanupEmptyState;constructor(e){this.options=e}get container(){return this.options.container}createPage(e,t,r){let n=document.createElement("div");n.className="doubao-runtime-page",Object.assign(n.style,{display:"block",width:"100%",height:"100%"}),n.addEventListener("doubao:page-capsule-close",e=>{e.stopPropagation(),r()});let a=this.container,i=new tE({...e,container:n},t);return{render:e=>(a.append(n),i.render(e)),setVisible(e){n.style.display=e?"block":"none"},clear(){i.clear(),n.remove()},sendEvent:i.sendEvent.bind(i),reload:i.reload.bind(i)}}setEmpty(e){let t=this.options.mountEmptyState;!this.emptyState&&t&&(this.emptyState=document.createElement("div"),this.emptyState.className="doubao-runtime-empty",this.container.append(this.emptyState),this.cleanupEmptyState=t(this.emptyState)??void 0),this.emptyState&&(this.emptyState.hidden=!e)}destroy(){var e,t;null==(e=this.cleanupEmptyState)||e.call(this),this.cleanupEmptyState=void 0,null==(t=this.emptyState)||t.remove(),this.emptyState=void 0}}class tz extends eH(tS,()=>tW){}class tV extends tB{constructor(e){super(e,tF)}}class tG extends eF{constructor(e){super(e,tF)}}var tJ=r(75541);function tK(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function tX(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function tZ(e,t){let r=t.trim();r&&!e.includes(r)&&e.push(r)}function tQ(e){let t=[];return!function e(t,r,n){if(!("object"!=typeof t||null===t||n.has(t))){if(n.add(t),Array.isArray(t))return void t.forEach(t=>e(t,r,n));if(tj(t))for(let[a,i]of Object.entries(t))"response_headers"===a.toLowerCase()&&function(e,t){if(tj(e)){for(let[r,n]of Object.entries(e))if("x-tt-logid"===r.toLowerCase()&&"string"==typeof n)return void tZ(t,n)}}(i,r),"log_ids"===a.toLowerCase()&&function(e,t){if("string"==typeof e)return tZ(t,e);if(Array.isArray(e))for(let r of e)"string"==typeof r&&tZ(t,r)}(i,r),e(i,r,n)}}(e,t,new WeakSet),t}function tY(e,t){if(!e.startsWith("sslocal://"))return{url:e};let r=new URL(e).searchParams,n=r.get("app_id"),a=r.get("path"),i=r.get("query"),s=r.get("route_mode")??void 0;if(!t)throw Error("当前调试应用缺少 AppID");if(n!==t)throw Error(`任务目标应用 ${n} 与当前应用 ${t} 不一致`);if(!a)throw Error("任务目标缺少 path");if(void 0!==s&&"navigate"!==s&&"redirect"!==s&&"relaunch"!==s)throw Error(`不支持的任务导航模式: ${s}`);return{url:i?`${a}?${i}`:a,routeMode:s}}function t0(e){return tj(e)?tj(e.viewData)?e:{...e,viewData:e}:{viewData:{}}}function t1(e){if("string"==typeof e&&e.trim())try{return JSON.parse(e)}catch{return}}function t2(e){if(tj(e))return e;let t=t1(e);return tj(t)?t:void 0}function t3(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return"{}"}}function t4(e){return e instanceof Error?e.message:String(e)}function t5(e){let t=null==e?void 0:e.toLowerCase();switch(t){case"agent":case"api":case"mcp":case"card":case"resource":case"runtime":case"debug":return t;case"tool":return"agent";default:return"runtime"}}function t6(e){let[t,...r]=e.trim().split(":"),n=t.replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(t8).join(" ");return 0===r.length?n||e:`${n}: ${r.join(":").trim()}`}function t8(e){let t=function(e){switch(e.toLowerCase()){case"api":return"API";case"mcp":return"MCP";case"sse":return"SSE";case"ack":return"ACK";case"http":return"HTTP";case"json":return"JSON";case"id":return"ID";default:return""}}(e);if(t)return t;if(/^[A-Z0-9]+$/.test(e))return e;let r=e.toLowerCase();return`${r.slice(0,1).toUpperCase()}${r.slice(1)}`}r(78872),r(60972),r(45249),r(20789),r(62839),r(66876);let t7=new Set(["local_mcp_missing","local_mcp_tools_load_failed","simulator_chat_fetch_failed","simulator_query_failed","stream_error","tool_executor_missing","tool_result_submit_failed"]),t9={query:0,"tool-call":10,"tool-result":20,"agent-processing":25,card:30,"agent-response":40,error:50};function re(e,t){return{category:"api",detail:{query:t},key:"query",phase:"request",payload:{event:"query",query:t},source:e,sources:[e],title:"Query"}}function rt(e,t){let r=e.steps.get(t.key);if(!r)return void e.steps.set(t.key,t);let n=function(e,t){if("error"===t.phase)return!0;if(e.key.startsWith("card:")){let r=ri(e.source.payload);return rr(ri(t.source.payload))>rr(r)}return!1}(r,t),a=n?t:r,i=n?r:t;e.steps.set(t.key,{...r,category:"error"===t.phase?t.category:a.category,detail:ru(a.detail,i.detail),phase:"error"===t.phase?t.phase:a.phase,payload:ru(a.payload,i.payload),source:a.source,sources:[...new Map([...r.sources,...t.sources].map(e=>[e.id,e])).values()],title:"error"===t.phase||n?t.title:r.title})}function rr(e){return"simulator_card_render_failed"===e||"simulator_card_runtime_error"===e||"simulator_card_render_skipped"===e?3:"simulator_card_rendered"===e?2:+("card_delta"===e)}function rn(e){let t=rh([...e.steps.values()]);return t.map((r,n)=>{var a,i,s,o,l,d,u;let c,p,h,m,g,f,v,y,_,b,w;return a=r,i=e,s=t,o=n,y=rc(a.sources.flatMap(tQ)),_=rc(a.sources.map(e=>e.payload.request_id||"")),w=void 0===(b=(l=a,d=s,u=o,c=l.payload.elapsed_ms??l.detail.elapsed_ms,h=(null==(p=l.key.startsWith("agent-processing:")?d.slice(u+1).find(e=>/^(tool-call|card|error):/.test(e.key)||"agent-response"===e.key):d[u+1])?void 0:p.source.timestamp)??l.source.timestamp,m=Number.isFinite(l.source.timestamp)&&Number.isFinite(h)?Math.max(0,h-l.source.timestamp):void 0,f=(g=l.key.startsWith("tool-call:")?l.key.replace("tool-call:","tool-result:"):l.key.startsWith("tool-result:")?l.key.replace("tool-result:","tool-call:"):void 0)?d.find(e=>e.key===g):void 0,void 0!==(v=l.key.startsWith("tool-call:")&&f?f.payload.elapsed_ms??f.detail.elapsed_ms:void 0)?v:l.key.startsWith("tool-result:")&&f?void 0:void 0!==c?void 0===m?c:Math.max(c,m):m))?a.detail:{...a.detail,elapsed_ms:b},{id:a.source.id,order:a.source.order,timestamp:a.source.timestamp,display:{category:a.category,detail:w,phase:a.phase,title:a.title},payload:{request_id:1===_.length?_[0]:void 0,request_ids:_.length>1?_:void 0,...a.payload,trace_id:i.id,run_status:i.status,elapsed_ms:b,log_ids:y.length>0?y:void 0}}})}function ra(e,t){let r=rp(t.payload),n=r?e.runs.find(e=>e.id===r):void 0;if(!n){if(!r)return;n={id:r,order:t.order??e.runs.length,startedAt:t.timestamp,steps:new Map},e.runs.push(n)}return n.startedAt=Math.min(n.startedAt,t.timestamp),n.order=Math.min(n.order,t.order??n.order),n}function ri(e){return e.event||""}function rs(e,t){return ro(e)||[rp(e)||t.id,e.tool_name||"unknown-tool"].filter(Boolean).join(":")}function ro(e){return e.tool_call_id||""}function rl(e){let t=e.tool_name||ro(e);return t?`: ${t}`:""}function rd(e){let t={};for(let[r,n]of Object.entries(e))null!=n&&""!==n&&(t[r]=n);return t}function ru(e,t){return Object.fromEntries([...Object.entries(t),...Object.entries(e).filter(e=>{let[,t]=e;return void 0!==t})])}function rc(e){return[...new Set(e.filter(e=>!!e))]}function rp(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}function rh(e){return[...e].sort((e,t)=>e.source.timestamp-t.source.timestamp||(e.source.order??0)-(t.source.order??0)||t9[e.key.split(":")[0]]-t9[t.key.split(":")[0]]||e.key.localeCompare(t.key))}function rm(e,t){return e.startedAt-t.startedAt||e.order-t.order||e.id.localeCompare(t.id)}function rg(e,t){return e.timestamp-t.timestamp||(e.order??0)-(t.order??0)||e.id.localeCompare(t.id)}function rf(e){try{return rv(e,2)}catch{var t=e;if("string"==typeof t){let e=t.trim();if(!e)return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}if(void 0===t)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}}function rv(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=new WeakSet;return JSON.stringify(e,(e,t)=>{if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if("function"==typeof t)return`[Function ${t.name||"anonymous"}]`;if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t},t)}function ry(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=Date.now();return{stored_at:new Date(r).toISOString(),stored_at_ms:r,snapshot:r_(e,t),debug_snapshot:r_(e,{...t,debug:!0,includeRuntimeRoot:!1})}}function r_(e){var t,r;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=n.debug&&!n.traceId?(t=e,r=!1!==n.includeRuntimeRoot,tj(t)&&!r&&tj(t.runtime_snapshot)?{...t,runtime_snapshot:rw(t.runtime_snapshot,!1)}:t):function(e,t){var r;if(!tj(e))return e;let n=tj(e.simulator)?e.simulator:{},a=Array.isArray(n.messages)?n.messages.filter(e=>rS(e,t.traceId)):void 0,i=Array.isArray(n.tool_calls)?n.tool_calls.filter(e=>rS(e,t.traceId)):void 0,s=rw(e.runtime_snapshot,!1!==t.includeRuntimeRoot);return{...rN(e,["exported_at","client_id","command_id","context","render_targets"]),runtime_snapshot:tj(s)?s:void 0,simulator:tj(e.simulator)?{...rN(n,["stream_status","active_request_id","active_reply_message_id"]),error:n.error?rE(n.error):void 0,selected_card:n.selected_card?rC(n.selected_card):void 0,answer_finish:n.answer_finish?tj(r=n.answer_finish)?rN(r,["messageId","status","finishReason","usage","createdAtMs"]):r:void 0,messages:null==a?void 0:a.map(rx),tool_calls:null==i?void 0:i.map(rk),trace_events:Array.isArray(n.trace_events)?rb(n.trace_events,{debug:t.debug,messages:a,traceId:t.traceId}):void 0}:void 0,widget_runtime_trace_events:Array.isArray(e.widget_runtime_trace_events)?rb(e.widget_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,page_runtime_trace_events:Array.isArray(e.page_runtime_trace_events)?rb(e.page_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,runtime_console:tj(e.runtime_console)?e.runtime_console:void 0}}(e,n),i=tQ(e);return i.length>0&&tj(a)?{...a,log_ids:i}:a}function rb(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.debug&&!t.traceId)return e;if(t.debug){var r,n;return r=e,(n=t.traceId)?r.filter(e=>rp(e.payload)===n):r}let a=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r={runs:[]};for(let t of[...e].sort(rg))!function(e,t){var r,n;let a=t.payload,i=ri(a);if("tool_result_report_started"===i){let r=ra(e,t);if(!r)return;rt(r,function(e){let t=e.payload,r=rd({tool_call_id:ro(t),tool_name:t.tool_name});return{category:"agent",detail:r,key:`agent-processing:${rs(t,e)}`,phase:"request",payload:{event:"agent_processing",...r},source:e,sources:[e],title:`Agent Processing${rl(t)}`}}(t));return}if(!((r=i).startsWith("tool_result_report_")||"tool_result_ack"===r)){if("simulator_chat_fetch_started"===i){let r=function(e){var t,r,n;return e.query||(null==(t=e.request)?void 0:t.query)||(null==(n=e.request)||null==(r=n.message)?void 0:r.content)||""}(a);if(!r)return;let n=ra(e,t);if(!n)return;rt(n,re(t,r));return}if("tool_call"===i||"local_mcp_call_started"===i){let r=ra(e,t);if(!r)return;rt(r,function(e){let t=e.payload,r=rd({tool_call_id:ro(t),tool_name:t.tool_name,arguments:t.arguments,arguments_json:t.arguments_json});return{category:"agent",detail:r,key:`tool-call:${rs(t,e)}`,phase:"request",payload:{event:"tool_call",...r},source:e,sources:[e],title:`Tool Call${rl(t)}`}}(t));return}if("local_mcp_call_succeeded"===i||"local_mcp_call_failed"===i){let r=ra(e,t);if(!r)return;rt(r,function(e){let t=e.payload,r="local_mcp_call_failed"===ri(t),n=t.result??t.structured_result??t1(t.structured_result_json)??t.structured_result_json,a=t.raw_mcp_result??t1(t.raw_mcp_result_json)??t.raw_mcp_result_json,i=t.raw_result_text===t.raw_mcp_result_json?void 0:t.raw_result_text,s=rd({tool_call_id:ro(t),tool_name:t.tool_name,status:t.status,result:n,raw_result_text:i,raw_mcp_result:a,elapsed_ms:t.elapsed_ms,error:t.error});return{category:"mcp",detail:s,key:`tool-result:${rs(t,e)}`,phase:r?"error":"response",payload:{event:r?"tool_result_failed":"tool_result",...s},source:e,sources:[e],title:`${r?"Tool Result Failed":"Tool Result"}${rl(t)}`}}(t));return}if("card_delta"===(n=i)||"simulator_card_rendered"===n||"simulator_card_render_failed"===n||"simulator_card_runtime_error"===n||"simulator_card_render_skipped"===n){let r=ra(e,t);if(!r)return;rt(r,function(e){var t,r;let n=e.payload,a=ri(n),i="error"in n||a.endsWith("_failed")||a.endsWith("_error"),s=rd({card_id:n.card_id,widget_id:n.widget_id,card_type:n.card_type,entity_id:n.entity_id,source_tool_call_id:n.source_tool_call_id,elapsed_ms:n.elapsed_ms,error:n.error,summary:n.summary});return{category:"card",detail:s,key:`card:${t=n,r=e,t.card_id||t.source_tool_call_id||[rp(t)||r.id,t.widget_id||r.id].filter(Boolean).join(":")}`,phase:i?"error":"response",payload:{event:i?"card_render_failed":"card_delta"===a?"card_received":"card_rendered",...s},source:e,sources:[e],title:i?"Card Render Failed":"card_delta"===a?"Card Received":"Card Rendered"}}(t));return}if(function(e,t){let r=e.phase,n=e.status;return t7.has(t)||"error"===r||t.endsWith("_failed")||t.endsWith("_missing")||t.endsWith("_aborted")||t.endsWith("_error")||"failed"===n||"error"===n||"number"==typeof n&&n>=400}(a,i)){let r=ra(e,t);if(!r)return;rt(r,function(e){var t,r;let n=e.payload,a=n.detail??{},i=n.event_count??a.event_count,s=rd({elapsed_ms:n.elapsed_ms??a.elapsed_ms,endpoint:n.endpoint??a.endpoint,error:n.error??a.error,event_count:i,message:n.message??a.message,reason:n.reason??a.reason,status:n.status??a.status,summary:n.summary??a.summary??("simulator_chat_sse_read_failed"===ri(n)&&0===i?"对话流未收到任何事件,未触发 MCP tool 与 tool/report;请结合 log_id 排查生成或下发 tool_call 前的服务端/链路异常。":void 0),response:n.response??a.response,response_text:n.response_text??a.response_text});return{category:(null==(t=e.display)?void 0:t.category)||"runtime",detail:s,key:`error:${e.id}`,phase:"error",payload:{event:ri(n)||"trace_error",...s},source:e,sources:[e],title:(null==(r=e.display)?void 0:r.title)||n.title||"Trace Error"}}(t))}}}(r,t);for(let e of t)!function(e,t){var r,n,a,i,s;let o=(n=t,{id:`trace-message-${n.messageId}`,timestamp:n.createdAtMs,payload:rd({message_id:n.messageId,request_id:n.requestId,trace_id:n.traceId})}),l=ra(e,o);if(!l)return;let d=(null==(r=t.blocks)?void 0:r.some(e=>"image"===e.type))??!1,u=t.text.trim()||(d?"[图片]":"");"assistant"===t.role&&t.status&&(a=l,i=t.status,s=t.createdAtMs,void 0!==a.statusUpdatedAt&&s<a.statusUpdatedAt||(a.status=i,a.statusUpdatedAt=s)),"user"===t.role&&u&&!l.steps.has("query")&&rt(l,re(o,u)),"assistant"===t.role&&t.text.trim()&&rt(l,function(e,t){let r=rh([...e.steps.values()]).at(-1),n=Math.max(t.createdAtMs,((null==r?void 0:r.source.timestamp)??t.createdAtMs)+.1),a={id:`trace-agent-response-${t.messageId}`,order:(null==r?void 0:r.source.order)===void 0?void 0:r.source.order+.1,timestamp:n,payload:rd({message_id:t.messageId,request_id:t.requestId,trace_id:t.traceId})};return{category:"agent",detail:{text:t.text},key:"agent-response",phase:"finish",payload:{event:"agent_response",message_id:t.messageId,text:t.text},source:a,sources:[a],title:"Agent Response"}}(l,t))}(r,e);return r}(e,t.messages);return(t.traceId?a.runs.filter(e=>e.id===t.traceId):a.runs).sort(rm).flatMap(rn)}(e,t)}function rw(e,t){if(!tj(e)||t)return e;let{root:r,...n}=e;return n}function rS(e,t){if(!t)return!0;if(!tj(e))return!1;let r=tj(e.trace)?e.trace:{};return e.traceId===t||r.trace_id===t}function rx(e){return tj(e)?{...rN(e,["messageId","localMessageId","requestId","traceId","role","contentType","status","createdAtMs"]),text:"string"==typeof e.text?rM(e.text):void 0,blocks:Array.isArray(e.blocks)?e.blocks.map(rI):void 0,toolCalls:Array.isArray(e.toolCalls)?e.toolCalls:void 0,toolResults:Array.isArray(e.toolResults)?e.toolResults:void 0}:e}function rI(e){return tj(e)?"card"===e.type?{...rN(e,["blockId","type"]),card:rC(e.card)}:"image"===e.type&&tj(e.image)?{...rN(e,["blockId","type"]),image:rN(e.image,["resource_uri","mime_type","size_bytes","width","height","sha256","name"])}:{...rN(e,["blockId","type"]),text:"string"==typeof e.text?rM(e.text):void 0}:e}function rk(e){return tj(e)?{...rN(e,["requestId","runId","replyMessageId","toolCallId","toolName","serverId","appKey","status","createdAtMs","updatedAtMs","requiresUserApproval","timeoutMs","deadlineMs","progress","message","resultSummary","structuredResultSummary","isMiniApp"]),arguments:e.arguments,argumentsJson:void 0===e.arguments&&e.argumentsJson?e.argumentsJson:void 0,error:e.error?rE(e.error):void 0}:e}function rC(e){return tj(e)?rN(e,["reply_message_id","block_id","card_id","widget_id","card_type","app_id","entity_id","title","fallback_text"]):e}function rE(e){return tj(e)?rN(e,["code","message","user_message","retryable","stage","details","name","stack"]):e}function rN(e,t){let r={};for(let n of t)void 0!==e[n]&&(r[n]=e[n]);return r}function rM(e){return e.length>1e3?`${e.slice(0,1e3)}...`:e}let rT=[1e3,2e3,4e3,8e3,16e3];class rR{clientId=crypto.randomUUID();socket;status="disconnected";listeners=new Set;retryTimer;retryIndex=0;sandboxSnapshot;snapshot;sentRuntime;snapshotErrorReported=!1;subscribe(e){return this.listeners.add(e),e({type:"status",status:this.status}),void 0!==this.sandboxSnapshot&&e({type:"sandbox",data:this.sandboxSnapshot}),()=>{this.listeners.delete(e)}}start(){this.stop(),this.retryIndex=0,this.connect()}stop(){clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.socket;this.socket=void 0,null==e||e.close(),this.sandboxSnapshot=void 0,this.setStatus("disconnected")}emit(e){for(let t of this.listeners)t(e)}setStatus(e){this.status!==e&&(this.status=e,this.emit({type:"status",status:e}))}connect(){let e;this.setStatus(this.retryIndex?"reconnecting":"connecting");let t=new URL("/__wsd_connection",window.location.href);t.protocol="https:"===t.protocol?"wss:":"ws:",t.searchParams.set("clientId",this.clientId);let r=new WebSocket(t);this.socket=r,r.onopen=()=>{this.socket===r&&(e=Date.now(),this.sentRuntime=void 0,this.sendSnapshot(),this.setStatus("connected"))},r.onmessage=e=>{let t;if(this.socket===r){try{t=JSON.parse(e.data)}catch{r.close(4e3,"Invalid debugger message");return}if(tj(t))if("control"===t.type){let e=function(e){if(!tj(e)||"string"!=typeof e.commandId)return null;if("render_page"===e.type&&"string"==typeof e.url)return{commandId:e.commandId,type:e.type,url:e.url};if("render_widget"===e.type&&"string"==typeof e.widgetId&&tj(e.structuredContent))return{commandId:e.commandId,type:e.type,widgetId:e.widgetId,structuredContent:e.structuredContent};if("set_viewport"===e.type&&tK(e.width)&&tK(e.height))return{commandId:e.commandId,type:e.type,width:e.width,height:e.height};if("submit_chat_query"===e.type&&"string"==typeof e.query&&e.query.trim())return{commandId:e.commandId,type:e.type,query:e.query.trim()};if("cancel_chat_query"===e.type)return{commandId:e.commandId,type:e.type};if("execute_sandbox_tool_call"===e.type){var t;let r="object"==typeof(t=e.toolCall)&&(null==t?void 0:t.tool_call)?t:void 0;return r?{commandId:e.commandId,toolCall:r,type:e.type}:null}if("get_computed_style"===e.type&&"string"==typeof e.uid)return void 0===e.properties||Array.isArray(e.properties)&&e.properties.every(e=>"string"==typeof e)?{commandId:e.commandId,type:e.type,uid:e.uid,properties:e.properties}:null;if("take_snapshot"===e.type&&("current"===e.target||"page"===e.target||"widget"===e.target))return{commandId:e.commandId,type:e.type,target:e.target};if("get_element_rect"===e.type&&"string"==typeof e.uid)return{commandId:e.commandId,type:e.type,uid:e.uid};if("take_screenshot"===e.type){let t=e.format??"png",r=e.quality;return void 0!==e.uid&&"string"!=typeof e.uid||"png"!==t&&"jpeg"!==t&&"webp"!==t||void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<0||r>100)?null:{commandId:e.commandId,type:e.type,format:t,uid:"string"==typeof e.uid?e.uid:void 0,quality:"number"==typeof r?r:void 0}}return"scroll_to"===e.type?(void 0===e.uid||"string"==typeof e.uid&&e.uid.trim())&&(void 0===e.x||tX(e.x))&&(void 0===e.y||tX(e.y))?{commandId:e.commandId,type:e.type,uid:"string"==typeof e.uid?e.uid:void 0,x:"number"==typeof e.x?e.x:void 0,y:"number"==typeof e.y?e.y:void 0}:null:null}(t.data);e&&this.emit({type:"control",data:e})}else"sandbox"===t.type&&(this.sandboxSnapshot=t.data,this.emit({type:"sandbox",data:t.data}))}},r.onclose=t=>{if(this.socket!==r)return;this.socket=void 0,this.sandboxSnapshot=void 0,void 0!==e&&Date.now()-e>=3e4&&(this.retryIndex=0);let n=rT[this.retryIndex++];void 0===n||1008===t.code||1009===t.code?this.setStatus("disconnected"):(this.setStatus("reconnecting"),this.retryTimer=setTimeout(()=>this.connect(),n))}}send(e){var t;if(new TextEncoder().encode(e).byteLength>0xa00000)throw Error("本地调试消息超过 10MiB,无法发送");if((null==(t=this.socket)?void 0:t.readyState)!==WebSocket.OPEN)throw Error("本地调试服务未连接");if(this.socket.bufferedAmount>0xa00000)throw this.socket.close(4e3,"Debugger connection is too slow"),Error("本地调试服务发送缓冲区已满");this.socket.send(e)}async reportResult(e){this.send(JSON.stringify({type:"control_result",data:e}))}async clearSandboxLogs(){this.send(JSON.stringify({type:"clear_sandbox_logs"}))}publishSnapshot(e,t){this.snapshot={payload:e,runtime:t},this.sendSnapshot()}sendSnapshot(){var e;if(!this.snapshot||(null==(e=this.socket)?void 0:e.readyState)!==WebSocket.OPEN)return;let{payload:t,runtime:r}=this.snapshot;try{let e=ry(t,{includeRuntimeRoot:r!==this.sentRuntime});this.send(rv({type:"snapshot",data:e})),this.sentRuntime=r,this.snapshotErrorReported=!1}catch(e){this.snapshotErrorReported||console.warn("调试快照上传失败,控制连接保持可用:",e),this.snapshotErrorReported=!0}}}var rA=r(64865),rP=r(11855);function rj(e){return e instanceof Map?Array.from(e.entries(),e=>{let[t,r]=e;return[String(t),r]}):!e||"object"!=typeof e||Array.isArray(e)||e instanceof ArrayBuffer?void 0:Object.entries(e)}function rL(e){return e.map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(null===r?"null":r&&"object"==typeof r?JSON.stringify(r)??String(r):String(r))}`}).join("&")}function rD(e){let t=new Uint8Array(e),r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}function rO(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"json";if("arraybuffer"===t)return e;let r=new TextDecoder().decode(e);if("string"===t||0===r.length)return r;try{return JSON.parse(r)}catch{return rD(e)}}function rU(e){let t={};return e.forEach((e,r)=>{t[r]=e}),t}function rq(e){var t;let r,n=(e.method??"GET").toUpperCase();if("GET"!==n&&"POST"!==n)throw Error(`Unsupported request method: ${n}`);let a="string"==typeof e.url?e.url:"",i=((r=new Headers(e.header)).has("content-type")||r.set("content-type","application/json"),r);return{body:"POST"===n?function(e,t){if(null!=e){if("string"==typeof e||e instanceof ArrayBuffer)return e;if(t.includes("application/x-www-form-urlencoded")){let t=rj(e);if(t)return rL(t)}return t.includes("application/json")||"object"==typeof e?JSON.stringify(e):String(e)}}(e.data,(null==(t=i.get("content-type"))?void 0:t.toLowerCase())??""):void 0,headers:rU(i),method:n,url:"GET"===n?function(e,t){let r=rj(t);if(!(null==r?void 0:r.length))return e;let n=e.indexOf("#"),a=-1===n?"":e.slice(n),i=-1===n?e:e.slice(0,n),s=i.endsWith("?")||i.endsWith("&")?"":i.includes("?")?"&":"?";return`${i}${s}${rL(r)}${a}`}(a,e.data):a}}async function r$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rq(e);if(!e.url)throw Error("url must be a non-empty string");let r=await fetch(t.url,{body:t.body,headers:t.headers,method:t.method}),n=rO(await r.arrayBuffer(),e.dataType);return{statusCode:r.status,header:rU(r.headers),data:n}}r(20303),r(99166),r(6106),r(22742),r(37553),r(62148),r(89055),r(12205),r(65850),r(65135),r(5876),r(94359),r(28016),r(38641),r(82247),r(11839),r(56109),r(63589);let rB=["connection","content-length","host","origin","referer"],rF="/__web_artifacts/base/manifest.json",rW="/app_developer";function rH(e){return!e.debugHidden}r(95600);let rz={chat:"chat","image-upload":"images/upload","tool-report":"tool/report"};function rV(e){let t=tR(String(e??rW).trim(),{addProtocolToBareHost:!0,allowRootRelative:!0,defaultProtocol:rG}).replace(/\/+$/,"");if(t.startsWith("/"))return t;try{let e=new URL(t);if(""===e.pathname||"/"===e.pathname)return e.pathname="/app_developer",e.toString().replace(/\/+$/,"")}catch{}return t}function rG(e){return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\])(?::|\/|$)/i.test(e)?"http":"https"}function rJ(e){var t;let r="function"==typeof(null==(t=globalThis.crypto)?void 0:t.randomUUID)?globalThis.crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2);return`${e}_${Date.now().toString(36)}${r.slice(0,10)}`}function rK(e,t){return`${rV(e)}/api/simulator/${rz[t]}`}function rX(e){if(e.type&&!e.type.startsWith("image/"))throw Error("仅支持图片文件");if(e.size>0xa00000)throw Error("图片不能超过 10 MiB")}var rZ=r(75585);let rQ=["ack","message_start","text_delta","tool_call","tool_status","card_delta","content_block","stream_error","message_finish","reply_finish","answer_finish","trace_event","heartbeat"];async function rY(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=e.getReader(),a=new TextDecoder,i={...r,fallbackSeq:0},s=(0,rZ.C)({onEvent:e=>{let r=function(e,t){var r,n,a;let i,s,o,l,d,u,c=void 0===(l=t1(r=e.data))&&r.trim()?r:l,p=tj(c)?{...c,event:c.event||e.event}:{event:e.event||"message",data:c},{eventType:h,payload:m}=function(e){var t;for(let t of rQ){let r=e[t];if(tj(r))return{eventType:t,payload:r};if("content_block"===t&&Array.isArray(r))return{eventType:t,payload:{content_block:r}}}return{eventType:"string"==typeof(t=e.event)&&t?t.toLowerCase():"message",payload:e}}(p),g=tj(m)?m:{},f="number"==typeof p.sequence&&Number.isFinite(p.sequence)?p.sequence:t.fallbackSeq+=1,v=e.id||("string"==typeof p.id?p.id:"")||`evt_${f.toString().padStart(4,"0")}`,y=function(e,t,r){let n=("string"==typeof e.request_id?e.request_id:"")||("ack"===r&&"string"==typeof t.request_id?t.request_id:"");if("ack"===r&&!n)throw Error("Invalid simulator SSE ACK: missing request_id");return n||("string"==typeof e.id?e.id:"")}(p,g,h),_=("string"==typeof p.reply_message_id?p.reply_message_id:"")||("string"==typeof g.message_id?g.message_id:"")||t.replyMessageId;return{event_id:v,event_type:h,seq:f,request_id:y,query_message_id:("string"==typeof p.query_message_id?p.query_message_id:"")||("string"==typeof g.query_message_id?g.query_message_id:""),reply_message_id:_,created_at_ms:"number"==typeof p.timestamp_ms&&Number.isFinite(p.timestamp_ms)?p.timestamp_ms:Date.now(),received_at_ms:Date.now(),trace:(d=tj(p.trace)?p.trace:{},{trace_id:"string"==typeof(u=t.trace??{}).trace_id?u.trace_id:"string"==typeof d.trace_id?d.trace_id:rJ("trace"),span_id:"string"==typeof d.span_id?d.span_id:rJ("span_sse"),parent_span_id:"string"==typeof d.parent_span_id?d.parent_span_id:"string"==typeof u.span_id?u.span_id:void 0,component:"string"==typeof d.component?d.component:"app_developer_simulator",stage:"string"==typeof d.stage?d.stage:h,sampled:"boolean"==typeof d.sampled?d.sampled:"boolean"!=typeof u.sampled||u.sampled,baggage:{...tj(u.baggage)?u.baggage:{},...tj(d.baggage)?d.baggage:{}}}),payload:(n=g,0===(o=Array.isArray(s=tj(i=null==(a=t.trace)?void 0:a.baggage)?i.log_ids:void 0)?s.filter(e=>"string"==typeof e&&e.trim().length>0):"string"==typeof s&&s.trim()?[s]:[]).length||void 0!==n.log_ids?n:{...n,log_ids:o})}}(e,i);r.reply_message_id&&(i.replyMessageId=r.reply_message_id),t(r)}});for(;;){let{done:e,value:t}=await n.read();if(t&&s.feed(a.decode(t,{stream:!e})),e)break}let o=a.decode();o&&s.feed(o),s.feed("\n\n")}let r0="x-tt-logid";class r1 extends Error{responseDebug;constructor(e,t){super(e),this.responseDebug=t,this.name="SimulatorHttpError"}}function r2(e){return e.headers.get(r0)}function r3(e){let t={},r=r2(e);return r&&(t[r0]=r),t}function r4(e){return tj(e.trace)?e.trace:{}}async function r5(e,t){let r=r2(t),n=r3(t),a=await t.text().catch(()=>""),i={status:t.status,status_text:t.statusText,response_headers:Object.keys(n).length>0?n:void 0,log_ids:r?[r]:void 0,response_text:a};return new r1(`${e}: ${t.status} ${t.statusText}`,i)}function r6(e){return e instanceof r1?e.responseDebug:void 0}function r8(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},a=arguments.length>4?arguments[4]:void 0,i=r4(e),s=Date.now();return{event_id:rJ("evt_client_debug"),event_type:"debug",seq:0,request_id:"string"==typeof e.idempotency_key?e.idempotency_key:"client_debug",created_at_ms:s,received_at_ms:s,trace:{trace_id:"string"==typeof i.trace_id?i.trace_id:rJ("trace"),component:"string"==typeof i.component?i.component:"simulator_web_tester",stage:"string"==typeof i.stage?i.stage:"query",sampled:"boolean"!=typeof i.sampled||i.sampled,baggage:a??(tj(i.baggage)?i.baggage:{})},payload:{event:t,category:"api",elapsed_ms:Date.now()-r,...n}}}async function r7(e){var t;let{endpoint:r,fetcher:n,file:a,signal:i}=e;rX(a);let s=new FormData;s.append("image",a);let o=await (n??fetch)(rK(r,"image-upload"),{method:"POST",headers:{Accept:"application/json"},body:s,signal:i});if(!o.ok)throw await r5("Simulator image upload failed",o);let l=await o.json();if(0!==l.code)throw new r1(l.message||`Simulator image upload failed with code ${l.code}`,{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});let d=null==(t=l.data)?void 0:t.image;if(!(null==d?void 0:d.resource_uri))throw new r1("Simulator image upload response is missing image.resource_uri",{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});return d}async function r9(e){let t,{endpoint:r,fetcher:n,onEvent:a,onSubmitted:i,request:s,signal:o}=e,l=Date.now(),d=rK(r,"chat");a(r8(s,"simulator_chat_fetch_started",l,{endpoint:"chat",phase:"request",request:s,request_json:t3(s),url:d}));let u=setTimeout(()=>{a(r8(s,"simulator_chat_fetch_waiting_for_headers",l,{endpoint:"chat",phase:"wait",url:d,wait_ms:5e3}))},5e3);try{let e=(n??fetch)(d,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(s),signal:o});null==i||i(),t=await e}catch(e){throw clearTimeout(u),a(r8(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",url:d,error:t4(e)})),e}clearTimeout(u);let c=r2(t),p=r3(t),h=r4(s),m={...tj(h.baggage)?h.baggage:{}};if(c&&(m[r0]=c,m.log_ids=[c]),a(r8(s,"simulator_chat_headers_received",l,{event:"simulator_chat_response_meta",endpoint:"chat",phase:"response",status:t.status,status_text:t.statusText,log_ids:c?[c]:void 0,response_headers:Object.keys(p).length>0?p:void 0},m)),!t.ok){let e=await r5("Simulator query failed",t);throw a(r8(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",error:e.message,...e.responseDebug},m)),e}if(!t.body)throw Error("Simulator query response has no SSE body");let g=0,f=!1,v=setTimeout(()=>{f||a(r8(s,"simulator_chat_sse_waiting_for_first_event",l,{endpoint:"chat",wait_ms:5e3},m))},5e3);try{await rY(t.body,e=>{g+=1,f||(f=!0,clearTimeout(v)),a(e)},{trace:{...h,baggage:m}})}catch(e){throw clearTimeout(v),a(r8(s,"simulator_chat_sse_read_failed",l,{endpoint:"chat",phase:"error",event_count:g,error:t4(e)},m)),e}clearTimeout(v)}async function ne(e){let{endpoint:t,fetcher:r,result:n,signal:a}=e,i=await (r??fetch)(rK(t,"tool-report"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(n),signal:a});if(!i.ok)throw await r5("Simulator tool result failed",i);let s=await nt(i),o=r2(i);return{...s,response_headers:o?{...tj(s.response_headers)?s.response_headers:{},[r0]:o}:s.response_headers,log_ids:o?[o]:s.log_ids}}async function nt(e){let t=await e.text().catch(()=>"");if(!t.trim())return{};try{let e=JSON.parse(t);return tj(e)?e:{response_body:e}}catch{return{response_text:t}}}let nr={label:"Request",tone:"request"},nn={label:"Response",tone:"response"},na={simulator_query_prepare_started:{debugOnly:!0,title:"Query Prepare Started"},simulator_query_mcp_resolved:{debugOnly:!0,title:"MCP Ready"},simulator_query_aborted:{title:"Query Aborted"},simulator_query_failed:{title:"Query Failed"},simulator_query_cancel_requested:{title:"Query Cancel Requested"},simulator_chat_fetch_started:{badge:nr,title:"Chat"},simulator_chat_fetch_waiting_for_headers:{title:"Chat Waiting"},simulator_chat_response_meta:{badge:nn,title:"Chat"},simulator_chat_fetch_failed:{badge:nn,title:"Chat Failed"},simulator_chat_sse_waiting_for_first_event:{title:"Chat Waiting"},simulator_chat_sse_read_failed:{title:"Chat Stream Failed"},simulator_query_stream_returned:{title:"Chat Complete"},local_mcp_tools_load_started:{badge:nr,debugOnly:!0,title:"MCP Load"},local_mcp_tools_loaded:{badge:nn,debugOnly:!0,title:"MCP Load"},local_mcp_tools_load_failed:{badge:nn,title:"MCP Load Failed"},local_mcp_missing:{title:"MCP Missing"},local_mcp_call_started:{badge:nr,title:e=>`MCP Tool${e}`},local_mcp_call_succeeded:{badge:nn,title:e=>`MCP Tool${e}`},local_mcp_call_failed:{badge:nn,title:e=>`MCP Tool Failed${e}`},tool_result_report_started:{badge:nr,title:e=>`Report Tool Result${e}`},tool_result_report_response_received:{badge:nn,title:e=>`Report Tool Result${e}`},tool_result_report_failed:{badge:nn,title:e=>`Report Tool Result Failed${e}`},tool_result_ack:{title:"Report ACK"},tool_result_submit_skipped:{title:e=>`Report Tool Result Skipped${e}`},tool_result_submit_failed:{badge:nn,title:e=>`Report Tool Result Failed${e}`},tool_executor_missing:{title:e=>`Tool Executor Missing${e}`},tool_call_ignored:{title:e=>`Tool Call Ignored${e}`},tool_call_event_skipped:{title:e=>`Tool Call Skipped${e}`},tool_call_request_id_mismatch:{title:e=>`Tool Call Request Mismatch${e}`},tool_call_server_id_fallback:{title:e=>`Tool Call Server Fallback${e}`},simulator_card_rendered:{title:"Card Rendered"},simulator_card_render_skipped:{title:"Card Render Skipped"},simulator_card_render_failed:{title:"Card Render Failed"},simulator_card_runtime_error:{title:"Card Render Failed"},simulator_manifest_load_started:{badge:nr,debugOnly:!0,title:"Manifest Load"},simulator_manifest_loaded:{badge:nn,debugOnly:!0,title:"Manifest Load"},simulator_manifest_load_failed:{badge:nn,title:"Manifest Load Failed"},simulator_manifest_fetch_started:{badge:nr,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_succeeded:{badge:nn,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_failed:{badge:nn,title:"Manifest Fetch Failed"},simulator_manifest_missing:{title:"Manifest Missing"},simulator_skill_load_started:{badge:nr,debugOnly:!0,title:"Skill Load"},simulator_skill_loaded:{badge:nn,debugOnly:!0,title:"Skill Load"},simulator_skill_empty:{badge:nn,debugOnly:!0,title:"Skill Empty"},simulator_skill_load_failed:{badge:nn,title:"Skill Load Failed"},simulator_skill_fetch_started:{badge:nr,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_succeeded:{badge:nn,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_failed:{badge:nn,title:"Skill Fetch Failed"},simulator_skill_missing:{title:"Skill Missing"},simulator_resources_check_started:{debugOnly:!0,title:"Resource Check Started"},simulator_resources_check_completed:{debugOnly:!0,title:"Resource Check Completed"},simulator_resource_reload_completed:{title:"Resource Reloaded"}};function ni(e){if(!tj(e))return;let t=ns(e);return{category:t.category,debugOnly:t.debugOnly,detail:t.detail,leftBadges:t.transportBadge?[t.transportBadge]:void 0,phase:t.phase,title:t.title}}function ns(e){var t,r;let n=e.event||"",a=na[n],i=e.detail??e.data??e,s=e.title?t6(e.title):function(e,t){var r;let n=null==(r=na[e])?void 0:r.title;if("function"==typeof n){let e;return n((e=t.tool_name||t.tool_call_id)?`: ${e}`:"")}return n||(e?t6(e):"Agent Trace Event")}(n,e),o=e.category?t5(e.category):(t=n).startsWith("local_mcp_")?"mcp":t.startsWith("tool_result_report_")||"tool_result_ack"===t?"api":t.startsWith("tool_result_")||t.startsWith("tool_call_")||"tool_executor_missing"===t?"agent":t.startsWith("simulator_card_")?"card":t.startsWith("simulator_manifest_")||t.startsWith("simulator_skill_")||t.startsWith("simulator_resource_")||t.startsWith("simulator_resources_")?"resource":t.startsWith("simulator_chat_")?"api":t.startsWith("simulator_query_")?"agent":"runtime",l=e.phase||("local_mcp_missing"===(r=n)?"error":/(started|starting)$/.test(r)?"request":/(completed|loaded|resolved|received|returned|succeeded|rendered)$/.test(r)?"response":/(failed|error|aborted|rejected)$/.test(r)?"error":/(empty|skipped|ignored|mismatch|fallback|cancel_requested)$/.test(r)?"status":"tool_result_ack"===r?"ack":"event");return{category:o,debugOnly:(null==a?void 0:a.debugOnly)===!0,detail:i,eventName:n,phase:l,title:s,transportBadge:null==a?void 0:a.badge}}function no(e){return e.blocks.some(e=>"card"===e.type&&"permission_apply"===e.card.card_type)}function nl(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{messages:r,streamStatus:n}=e.getState().simulator,a=function(e,t){let r=t?e.findIndex(e=>e.messageId===t):e.findLastIndex(no);if(-1===r)return;let n=e[r];if(no(n))for(let t=r-1;t>=0;t--){let r=e[t],a="user"===r.role?r.blocks.filter(e=>"image"===e.type).map(e=>e.image):[];if("user"===r.role&&(r.text.trim()||a.length>0))return{followUpContent:r.followUpContent,images:a.length>0?a:void 0,messageIds:[r.messageId,n.messageId],query:r.text.trim()}}}(r,t.grantingMessageId);if(!a)return{status:"not_found"};if("streaming"===n)return{status:"streaming"};e.removeSimulatorMessages(a.messageIds);let i=t.noLogin?{noLogin:!0}:{};return{completion:a.followUpContent?e.sendSimulatorFollowUpMessage(a.followUpContent,i):e.sendSimulatorQuery(a.query,{images:a.images,...i}),status:"started",target:a}}function nd(e){if(!tj(e))return;let t="string"==typeof e.grantingName?e.grantingName:"";if(t){var r;let n;return{grantingName:t,permissionStatus:"string"==typeof e.permissionStatus?e.permissionStatus:"pending",priorityLevel:"number"==typeof e.priorityLevel?e.priorityLevel:0,relatedData:{...n=t2(r=e.relatedData)??(tj(r)?r:{}),bizLoginDescription:"string"==typeof n.bizLoginDescription?n.bizLoginDescription:"",bizPrivacyContent:"string"==typeof n.bizPrivacyContent?n.bizPrivacyContent:"",mobileMask:"string"==typeof n.mobileMask?n.mobileMask:"",privacyURL:"string"==typeof n.privacyURL?n.privacyURL:"",scopeDescription:"string"==typeof n.scopeDescription?n.scopeDescription:"",scopeName:"string"==typeof n.scopeName?n.scopeName:"",termsOfServiceURL:"string"==typeof n.termsOfServiceURL?n.termsOfServiceURL:""},required:!1!==e.required}}}function nu(e){let t=t2(e);if(!t)return;let r=Array.isArray(t.grantingList)?t.grantingList.map(nd).filter(e=>!!e):[];if(0!==r.length)return{cardStatus:"string"==typeof t.cardStatus?t.cardStatus:"unexpired",doubaoAppletIcon:"string"==typeof t.doubaoAppletIcon?t.doubaoAppletIcon:"",doubaoAppletKey:"string"==typeof t.doubaoAppletKey?t.doubaoAppletKey:"",doubaoAppletName:"string"==typeof t.doubaoAppletName&&t.doubaoAppletName?t.doubaoAppletName:"应用插件",doubaoAppletVersion:"string"==typeof t.doubaoAppletVersion?t.doubaoAppletVersion:"",grantingList:r,raw:t}}function nc(e){var t;switch(null==(t=e.grantingList[0])?void 0:t.grantingName){case"permission":return"权限申请";case"privacy":return"隐私协议提示";default:return"登录授权"}}r(66249);let np="miniapp_packet_10066";function nh(e,t,r,n,a){let i=e.find(e=>e.messageId===t);return i?n&&!i.requestId||a&&!i.traceId?e.map(e=>e===i?{...e,requestId:e.requestId||n,traceId:e.traceId||a}:e):e:[...e,{messageId:t,requestId:n,traceId:a,role:"assistant",contentType:"mixed",text:"",blocks:[],status:"streaming",createdAtMs:r}]}function nm(e,t,r){return e.map(e=>e.messageId===t?r(e):e)}function ng(e,t,r,n){let a={blockId:t,type:"card",card:r};if("replace"===n){let n=r.card_id,i=e.map(e=>e.blockId===t||"card"===e.type&&n&&e.card.card_id===n?a:e);return i.some(e=>e===a)?i:[...e,a]}return e.some(e=>e.blockId===t)?e.map(e=>e.blockId===t?a:e):[...e,a]}function nf(e,t,r){let n=!1,a=!1,i=e.map(e=>{let i=!1,s=e.blocks.map(e=>{if("card"!==e.type||e.card.card_id!==t)return e;n=!0;let s=r(e.card);return s?(a=!0,i=!0,{...e,card:s}):e});return i?{...e,blocks:s}:e});return{messages:a?i:e,found:n,updated:a}}function nv(e){return"debug"===e.event_type?e.payload.data??e.payload:e.payload}function ny(e){let t=e.payload.tool_name||e.payload.tool_call_id,r=e.payload.status;switch(e.event_type){case"ack":return"Chat ACK";case"tool_call":return`Tool Call${t?`: ${t}`:""}`;case"tool_status":return`Tool Status${t?`: ${t}`:""}${r?` (${r})`:""}`;case"card_delta":return"Card Received";case"answer_finish":return"Answer Finished";case"message_finish":return"Message Finished";case"reply_finish":return"Reply Finished";case"stream_error":return"Stream Error";case"trace_event":return t6(e.payload.title||"Agent Trace");case"heartbeat":return"Heartbeat";default:return t6(e.event_type)}}function n_(e){let t=e.payload.category;if(t)return t5(t);switch(e.event_type){case"tool_call":case"tool_status":case"trace_event":default:return"agent";case"card_delta":return"card";case"debug":return"debug"}}function nb(e){switch(e){case"ack":return"accepted";case"message_start":return"message_start";case"text_delta":return"text_delta";case"tool_call":return"request";case"tool_status":return"response";case"card_delta":return"card_delta";case"message_finish":case"reply_finish":case"answer_finish":return"finish";case"stream_error":return"error";case"trace_event":return"trace";default:return e}}function nw(e){return"u">typeof DOMException&&e instanceof DOMException?"AbortError"===e.name:e instanceof Error&&"AbortError"===e.name}function nS(e,t){if(tj(e)&&"code"in e&&"message"in e)return e;let r=tj(e)&&tj(e.responseDebug)?e.responseDebug:void 0,n=t2(null==r?void 0:r.response_text),a="string"==typeof(null==n?void 0:n.message)&&n.message.trim()?n.message.trim():"string"==typeof(null==r?void 0:r.response_text)&&r.response_text.trim()?r.response_text.trim():"";return{code:("string"==typeof(null==n?void 0:n.code)||"number"==typeof(null==n?void 0:n.code)?String(n.code):void 0)??"INTERNAL_ERROR",message:a||t4(e),retryable:!1,stage:t,details:r?{response:r,response_body:n}:void 0}}function nx(e,t){if(e||t)return{...e,...t}}function nI(e,t){var r;let n=(null==(r=e.traceEvents.at(-1))?void 0:r.order)??e.traceEvents.length;return{...e,traceEvents:[...e.traceEvents,{...t,order:n+1}].slice(-200)}}function nk(e,t,r){var n;let a=function(e){let t=tj(e.card)?e.card:{},r=tj(t.state)?t.state:{},n=e.card_id,a=r.widget_id;if("update_state"!==e.op||"miniapp_history_refresh"!==t.card_type||"fixed_style"!==r.refresh_to||!n||!a)return;let i=r.url||r.schema,s=r.title,o=r.detailText;return{cardId:n,state:r,widgetData:{url:i,title:s,detailText:o},widgetId:a}}(t);if(a){let t=nf(e.messages,a.cardId,e=>{let t=e.state??{};if("fixed"!==t.lifecycle_state)return{...e,render_data:{viewData:a.widgetData},widget_id:a.widgetId,state:{...t,...a.state,lifecycle_state:"fixed"}}});return{state:{...e,messages:t.messages},cardRefresh:{cardId:a.cardId,status:t.updated?"updated":t.found?"already_fixed":"not_found"}}}let i=function(e){let t=e.card;if(!tj(t)||t.card_type!==np)return;let r=e.card_id||t.card_id,n=t2(t.props_json),a=tj(null==n?void 0:n._meta)?n._meta:void 0,i=tj(t.render_data)?t.render_data:void 0,s=tj(null==i?void 0:i.ext)?i.ext:void 0;if(!r||!n||!a||!i||!s||!0!==a.skip_response_validate||"2"!==i.packet_type||"1"!==s._auth_request||"none"!==s.auth_require||"1"!==s.from_mcp||"1"!==s.is_mini_app||"string"!=typeof n.direct_return)return;let o=t2(n.direct_return);if((null==o?void 0:o.mcp_channel)==="flow_miniapp"&&Array.isArray(o.chunk_messages))for(let t of o.chunk_messages){if(!tj(t)||!0!==t.IsFinish||2!==t.MessageType||1005!==t.ContentType||"string"!=typeof t.Content)continue;let n=t2(t.Content);if((null==n?void 0:n.command_type)==="require_location"&&tj(n.require_location))return{cardId:r,appKey:s.app_key,sourceToolCallId:e.source_tool_call_id,toolName:s.tool_name}}}((null==r?void 0:r.payload)??{});if(i&&r)return{state:e,locationDirective:{...i,requestId:r.request_id,queryMessageId:r.query_message_id,replyMessageId:r.reply_message_id??e.activeReplyMessageId}};let s=(null==r?void 0:r.reply_message_id)??e.activeReplyMessageId,o=function(e){var t,r;let n,a=e.card;if(!tj(a))return{};let i=t2(a.props_json)??{},s=function(e){let t,r;if(e.card_type!==np)return;let n=t2(e.props_json)||t2(e.render_data_json)||(tj(e.render_data)?t2(e.render_data.content_for_display):void 0)||{};return n.permission_data||((r=(Array.isArray(null==(t=tj(n.structuredContent)?n.structuredContent:void 0)?void 0:t.entity_list)?t.entity_list:[]).find(e=>tj(e)&&(Array.isArray(e.grantingList)||tj(e._meta)&&!0===e._meta.is_permission)))&&tj(r)?JSON.stringify(r):void 0)}(a),o=nu(s),l=tj(i.extra)?i.extra:{},d=Object.keys(i).length>0?(n=t2(i.widget_data))?{viewData:n}:tj(i.viewData)?{viewData:i.viewData}:{viewData:i}:void 0,u={...tj(a.source)?a.source:{},tool_call_id:e.source_tool_call_id||(null==(t=a.source)?void 0:t.tool_call_id),entity_ids:Array.isArray(e.source_entity_ids)?e.source_entity_ids:null==(r=a.source)?void 0:r.entity_ids};return{...{card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type,app_id:e.app_id},...a,widget_id:i.widget_id||a.widget_id||e.widget_id,app_id:i.applet_id||a.app_id||e.app_id,entity_id:i.entity_id||a.entity_id,source:u,card_type:o?"permission_apply":a.card_type||e.card_type,fallback_text:o?a.fallback_text||"需要授权后继续":a.fallback_text,render_data:o?{grantingData:o,permissionData:s}:d||a.render_data,title:o?a.title||nc(o):a.title,debug:{...tj(a.debug)?a.debug:{},props_json:a.props_json,output_template:l["doubao/outputTemplate"]}}}(t),l=t.block_id||o.card_id||(n=`card_${(null==r?void 0:r.seq)??0}`,o.card_id||o.title||n),d=t.op||"append";if("append"!==d&&"replace"!==d)return{state:e};if(o.card_id){let t=nf(e.messages,o.card_id,e=>{let t,n,a,i;return r?o:(t=nx(e.state,o.state),n=nx(e.source,o.source),a=nx(e.debug,o.debug),i=Object.fromEntries(Object.entries(o).filter(e=>{let[,t]=e;return void 0!==t})),{...e,...i,state:t,source:n,debug:a})});if(t.found)return{state:{...e,messages:t.messages},cardRefresh:{cardId:o.card_id,status:"updated"}}}if(!s)return{state:e};let u=nh(e.messages,s,(null==r?void 0:r.created_at_ms)??Date.now(),null==r?void 0:r.request_id,null==r?void 0:r.trace.trace_id);return{state:{...e,messages:nm(u,s,e=>({...e,contentType:"mixed",blocks:ng(e.blocks,l,o,d)}))}}}function nC(e,t){let r="completed"===t?"completed":"cancelled"===t?"interrupted":"failed";return e.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:r}:e)}function nE(e,t,r){return{...e,toolCalls:e.toolCalls.map(e=>e.toolCallId===t?{...e,...r}:e)}}function nN(e,t){let r={tool_call_id:t.toolCallId,tool_name:t.toolName,arguments_summary:t.arguments&&Object.keys(t.arguments).length>0?t.arguments:void 0,status:t.status},n=e.findIndex(e=>e.tool_call_id===t.toolCallId);return n<0?[...e,r]:e.map((e,t)=>t===n?r:e)}var nM=r(33680);function nT(e,t){var r,n;return null==e||null==(n=e.tools)||null==(r=n[t])?void 0:r.output}function nR(e,t,r){if(!tj(e)||!Array.isArray(e.structuredContent))return e;let n=nT(t,r);if(!n||"entities"!==n.kind)return e;if(!e.structuredContent.every(tj))throw Error(`Tool "${r}" structuredContent items must be objects`);return{...e,structuredContent:{entities:e.structuredContent.map(e=>({...e,entity_type:r}))}}}function nA(e,t){let r;if(!tj(e)||!Array.isArray(e.content))throw Error("MCP tool result must be an object with a content array");let n=void 0===(r=e.structuredContent)?{}:r,a=t3(e),i=e.content.filter(tj).map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"),s=!0===e.isError;return{status:s?"failed":"succeeded",result:n,error:s?{code:t.businessErrorCode,message:tj(n)&&"string"==typeof n.message?n.message:i||a,retryable:!1,stage:"tool_execute",details:tj(n)?n:{structuredContent:n}}:void 0,raw_result_text:i,raw_mcp_result_json:a,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:t.source,protocol:t.protocol,mcp_output:e}}}let nP="client_tool",nj="__bridge_ready__",nL="lynxview";function nD(e,t){null==e||e({category:"mcp",source:"client_tool",...t})}class nO{runtimeUrl;container;errorListeners=new Set;host;messageListeners=new Set;view=null;constructor(e,t){this.runtimeUrl=e,this.host=function(){var e;if(!(null==(e=globalThis.document)?void 0:e.body))throw Error("Client Tool LynxView runtime requires document.body");let t=document.createElement("div");return t.dataset.doubaoClientToolRuntime="true",t.style.display="none",document.body.append(t),t}(),this.container=new tz({className:"doubao-client-tool-runtime-view",container:this.host,nativeModulesCallHandler:this.handleNativeModulesCall,onError:e=>this.emitError(e),onReady:()=>this.emitMessage({type:"event",name:nj})}),this.view=this.container.render({containerType:"TOOL",globalProps:t,initData:{},resourceUrl:e}),this.view.style.display="none"}addEventListener(e,t){"message"===e?this.messageListeners.add(t):this.errorListeners.add(t)}removeEventListener(e,t){"message"===e?this.messageListeners.delete(t):this.errorListeners.delete(t)}postMessage(e){this.container.sendGlobalEvent("__APPLET_BRIDGE__",[e])}terminate(){this.messageListeners.clear(),this.errorListeners.clear(),this.container.clear(),this.host.remove(),this.view=null}handleNativeModulesCall=(e,t,r)=>{if("AppletBridgeModule"===r&&"postMessage"===e&&tj(t)&&nq(t))return this.emitMessage(t),t};emitMessage(e){let t={data:e};for(let e of this.messageListeners)e(t)}emitError(e){let t=new ErrorEvent("error",{error:e,message:e.message});for(let e of this.errorListeners)e(t)}}function nU(e){return Object.assign(Error(e),{name:"AbortError"})}function nq(e){return"callback"===e.type&&"number"==typeof e.callbackId}class n${runtimeUrl;runtime;onTraceEvent;callbackId=1;ready=!1;readyPromise;rejectReady;resolveReady;pendingCallbacks=new Map;constructor(e,t,r){this.runtimeUrl=e,this.runtime=t,this.onTraceEvent=r,this.runtime.addEventListener("message",this.handleMessage),this.runtime.addEventListener("error",this.handleError)}async invokeTool(e){await this.ensureReady(e.signal);let{signal:t,...r}=e;return this.call("applet.invokeTool",r,{signal:t})}dispose(){var e;let t=Error("Client Tool runtime was disposed");for(let r of(this.runtime.removeEventListener("message",this.handleMessage),this.runtime.removeEventListener("error",this.handleError),this.runtime.terminate(),null==(e=this.rejectReady)||e.call(this,t),this.pendingCallbacks.values()))r.reject(t);this.pendingCallbacks.clear()}ensureReady(e){if(null==e?void 0:e.aborted)return Promise.reject(nU("Client Tool call aborted"));if(this.ready)return Promise.resolve();let t=this.readyPromise??(this.readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}));return e?new Promise((r,n)=>{let a=()=>{e.removeEventListener("abort",a),n(nU("Client Tool call aborted"))};e.addEventListener("abort",a,{once:!0}),t.then(()=>{e.removeEventListener("abort",a),r()},t=>{e.removeEventListener("abort",a),n(t)}),e.aborted&&a()}):t}call(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.callbackId;return this.callbackId+=1,new Promise((a,i)=>{let{signal:s}=r;if(null==s?void 0:s.aborted)return void i(nU("Client Tool call aborted"));let o=()=>{null==s||s.removeEventListener("abort",l)},l=()=>{this.pendingCallbacks.delete(n),i(nU("Client Tool call aborted"))};null==s||s.addEventListener("abort",l,{once:!0}),this.pendingCallbacks.set(n,{reject:e=>{o(),i(e)},resolve:e=>{o(),a(e)}}),this.runtime.postMessage({type:"call",name:e,params:t,callbackId:n,target:{scope:"main",target:"self"}})})}handleMessage=e=>{var t;let r,n=tj(r="string"==typeof e.data?t1(e.data):e.data)?r:void 0;if(!n)return;if("event"===n.type&&n.name===nj){this.ready=!0,null==(t=this.resolveReady)||t.call(this),nD(this.onTraceEvent,{event:"client_tool_runtime_ready",runtime_url:this.runtimeUrl});return}if(!nq(n))return;let a=this.pendingCallbacks.get(n.callbackId);if(a){this.pendingCallbacks.delete(n.callbackId);try{a.resolve(function(e){let t=tj(e.params)?e.params:{};if(1===t.code)return t.data;throw Error("string"==typeof t.msg&&t.msg||`Client Tool runtime callback failed with code ${String(t.code)}`)}(n))}catch(e){a.reject(e)}}};handleError=e=>{var t;let r=Error(e.message||"Client Tool runtime failed");for(let e of(null==(t=this.rejectReady)||t.call(this,r),this.pendingCallbacks.values()))e.reject(r);this.pendingCallbacks.clear()}}function nB(e,t,r){return{status:"failed",result:{error:t},error:{code:e,message:t,retryable:r,stage:"tool_execute"},raw_result_text:t,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:"client_tool",protocol:nL}}}let nF="simulator_web_tester";function nW(e){var t,r,n;let a=(t=e.messages,r=e.toolCalls,n=e.historyMaxTurns,t.slice(-Math.max(0,2*n)).map(e=>{var t,n,a;let i,s,o,l=(t=e,(i=r.filter(e=>e.replyMessageId===t.messageId&&nV(e.status)).map(e=>({tool_call_id:e.toolCallId,tool_name:e.toolName,arguments_summary:e.arguments&&Object.keys(e.arguments).length>0?e.arguments:void 0,status:e.status}))).length>0?i:(t.toolCalls??[]).filter(e=>nV(e.status))),d=(n=e,(s=r.filter(e=>e.replyMessageId===n.messageId&&nV(e.status)).map(e=>{var t;let r=e.resultSummary?e.resultSummary:(null==(t=e.error)?void 0:t.message)?e.error.message:e.message;return{tool_call_id:e.toolCallId,tool_name:e.toolName,result_summary:r,structured_summary:e.structuredResultSummary,is_mini_app:e.isMiniApp}})).length>0?s:n.toolResults??[]),u=nz(e.blocks.flatMap(e=>"image"===e.type?[e.image]:[]));return{role:"assistant"===e.role?"ASSISTANT":"USER",content:(o=(a=e).text?a.text:a.blocks.filter(e=>"text"===e.type).map(e=>e.text).join(""))||e.blocks.map(e=>{var t;return"image"===e.type?e.image.name?`[图片:${e.image.name}]`:"[图片]":"card"===e.type?(t=e.card).fallback_text||t.title||t.card_type||t.card_id||"卡片":e.text}).filter(Boolean).join("\n"),parts:u.length>0?u:void 0,tool_calls:l.length>0?l.map(e=>({tool_call_id:e.tool_call_id,tool_name:e.tool_name,arguments:e.arguments_summary,status:e.status})):void 0,tool_results:d.length>0?d.map(e=>({tool_call_id:e.tool_call_id,tool_name:e.tool_name,result_summary:e.result_summary,structured_summary:e.structured_summary,is_mini_app:e.is_mini_app})):void 0}})),i=nH(e.messages),s=e.simulatorManifest||e.options.manifest||{},o=s.app_key||"",l=e.options.appKey||e.simulatorAppKey||o||e.manifestAppId||"web-sdk-debugger",d=e.options.appName||e.simulatorAppName||e.manifestAppName||l,u=(e.options.skills??e.simulatorSkills??[]).map(e=>e.content),c=e.options.mcpServers??e.simulatorMcpServers,p=function(e,t){let r=e.raw_manifest_yaml||"",n=t.find(e=>e.server_id===nP&&e.tools.length>0);if(!n||!e.tools||null!=e.mcp_server)return r;let a=function(e){if(!e.trim())throw Error("Client Tool simulator manifest requires raw_manifest_yaml");let t=(0,nM.qg)(e);if(!tj(t))throw Error("Client Tool raw_manifest_yaml must contain a YAML object");return t}(r);return null!=a.mcp_server?r:(0,nM.As)({...a,mcp_server:{end_point:n.server_id,description:n.description||n.name}})}(s,c);return{app_id:l,scene:"miniapp_simulator_web_tester",history_messages:a,card_snapshots:i,trace:{trace_id:e.traceId,component:nF,stage:"query",sampled:!0},client:{platform:"web",locale:"zh-CN",timezone:function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"Asia/Shanghai"}}()},ext:{web_tester:"true",stateless_context:"client_history",skill_source:u.length>0?"local_file":"none",no_login:e.options.noLogin?"true":void 0},max_step:e.options.maxStep??e.simulatorMaxStep??20,protocol_version:"v2",idempotency_key:e.idempotencyKey,mini_apps:[{app_key:l,app_name:d,skills:u,manifest:{app_key:l,app_name:d,raw_manifest_yaml:p},mcp_servers:c.map(e=>({server_id:e.server_id,name:e.name,description:e.description||"",tools:e.tools.map(e=>({name:e.name,description:e.description||"",input_schema_json:t3(e.input_schema_json)}))}))}],web_capabilities:{supports_debug_event:!0}}}function nH(e){let t=new Map;for(let r of e)for(let e of r.blocks){if("card"!==e.type)continue;let r=function(e){var t,r,n;let a=t2(null==(t=e.debug)?void 0:t.props_json),i=e.card_id,s=(null==a?void 0:a.applet_id)||e.app_id,o=(null==a?void 0:a.entity_id)||e.entity_id;if(i&&s)return{card_id:i,app_key:s,business_entity_ids:o?[o]:void 0,lifecycle_state:(null==(r=e.state)?void 0:r.lifecycle_state)==="fixed"||(null==(n=e.state)?void 0:n.lifecycle_state)===2?2:1,refresh_key:e.refresh_key}}(e.card);r&&t.set(r.card_id,r)}return[...t.values()]}function nz(e){return e.map(e=>({type:"image",image:{resource_uri:e.resource_uri}}))}function nV(e){return["succeeded","failed","timeout","cancelled","rejected"].includes(e)}function nG(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"tool_execute",n=arguments.length>3?arguments[3]:void 0;return{code:e,message:t,user_message:t,retryable:!1,stage:r,details:n}}async function nJ(e){let t,r,n,a,i,s,{executor:o,input:l,record:d,signal:u}=e,c=(t=void 0===d.deadlineMs?void 0:d.deadlineMs-Date.now(),r=d.timeoutMs,void 0===(n=void 0===t?r:void 0===r?t:Math.min(t,r))?void 0:Math.max(0,n)),p=nG("TOOL_EXEC_CANCELLED","Tool execution cancelled"),h=void 0===c?void 0:new AbortController,m=(null==h?void 0:h.signal)??u;if(null==u?void 0:u.aborted)throw p;if(h&&u){let e=()=>{h.abort()};u.addEventListener("abort",e,{once:!0}),i=()=>u.removeEventListener("abort",e)}let g=[Promise.resolve(o({...l,signal:m}))];if(void 0!==c&&h){let e=nG("TOOL_EXEC_TIMEOUT",`Tool execution timed out after ${c}ms`);g.push(new Promise((t,r)=>{a=setTimeout(()=>{h.abort(),r(e)},c)}))}u&&g.push(new Promise((e,t)=>{let r=()=>{t(p)};u.addEventListener("abort",r,{once:!0}),s=()=>u.removeEventListener("abort",r)}));try{return await Promise.race(g)}finally{a&&clearTimeout(a),null==i||i(),null==s||s()}}function nK(e){return e?String(e):rF}function nX(e,t,r){return r?{type:e,message:t,error:r}:{type:e,message:t}}let nZ={simulator_manifest_load_failed:"Manifest",simulator_skill_load_failed:"Skill",local_mcp_tools_load_failed:"MCP",simulator_chat_fetch_failed:"对话接口"};function nQ(e){return new Set(e.flatMap(e=>e.blocks.flatMap(e=>"image"===e.type&&e.image.previewUrl?[e.image.previewUrl]:[])))}function nY(e,t){return e?{kind:"pages",item:e,routeUrl:t}:null}function n0(e,t){if(!t)return null;try{return nY(eD({url:t},e).entry,t)}catch{return null}}function n1(e){var t,r;return e.raw_result_text||(null==(t=e.error)?void 0:t.message)||(void 0===(r=e.result)?"":"string"==typeof r?r.slice(0,1e3):t3(r).slice(0,1e3))||e.status}function n2(e,t){return e.app_key||e.appKey||e.appId||e.packageName||t}function n3(e,t){var r;return e.name||e.appName||e.app_name||(null==(r=e.applet)?void 0:r.name)||t}function n4(e,t){let r=e.applet??{},n=t.applet??{},a=r.tools??[],i=n.tools??[],s=new Map,o=t.name||t.appName||t.app_name||n.name||"";if(i.length>0)for(let e of[...a,...i])e.id&&s.set(e.id,e);return{...e,manifest_version:t.manifest_version??e.manifest_version,app_key:t.app_key??e.app_key,name:t.name??e.name,appName:t.appName??e.appName,app_name:t.app_name??e.app_name,mcp_server:t.mcp_server??e.mcp_server,tools:t.tools??e.tools,entities:t.entities??e.entities,tool_card_binding:t.tool_card_binding??e.tool_card_binding,raw_manifest_yaml:t.raw_manifest_yaml??e.raw_manifest_yaml,applet:{...r,name:o||r.name,tools:i.length>0?[...s.values()]:a}}}class n5{fetcher;simulatorFetcher;historyMaxTurns;simulatorAppKey;simulatorAppName;simulatorSkills;simulatorManifest;simulatorMaxStep;simulatorMcpServers;simulatorMcpServerProvider;simulatorToolExecutor;sandboxToolCallExecutions=new Map;listeners=new Set;activeSimulatorRun=null;lastResolvedSimulatorMcpServers=[];receivedSimulatorLocationDirectiveCardIds=new Set;resourceUrlVersion;hasSimulatorManifestStateValue=!1;simulatorManifestStateValue;simulatorManifestStatePromise;simulatorRunSeq=0;destroyed=!1;state;constructor(e={}){let t=nK(e.manifestUrl);this.fetcher=e.fetcher,this.simulatorFetcher=e.simulatorFetch,this.historyMaxTurns=e.historyMaxTurns??6,this.simulatorAppKey=e.appKey,this.simulatorAppName=e.appName,this.simulatorSkills=e.skills,this.simulatorManifest=e.simulatorManifest,this.simulatorMaxStep=e.maxStep,"function"==typeof e.mcpServers?(this.simulatorMcpServers=[],this.simulatorMcpServerProvider=e.mcpServers):this.simulatorMcpServers=e.mcpServers??[],this.simulatorToolExecutor=e.toolExecutor,this.state={manifestUrl:t,manifest:new u({manifestVersion:"3.0",packageName:"",appId:"",versionCode:"",applet:{appletId:"",appRuntimeEntry:"",digest:"",pages:[]},widgets:[]}),pages:[],widgets:[],pageSelection:null,widgetSelection:null,simulator:{endpoint:rV(e.simulatorEndpoint),messages:[],streamStatus:"idle",toolCalls:[],traceEvents:[]},status:nX("idle","Idle")}}clearSimulatorManifestStateValue(){this.hasSimulatorManifestStateValue=!1,this.simulatorManifestStateValue=void 0,this.simulatorManifestStatePromise=void 0}takeSimulatorManifestStateValue(){if(!this.hasSimulatorManifestStateValue)return{found:!1,value:void 0};let e=this.simulatorManifestStateValue;return this.clearSimulatorManifestStateValue(),{found:!0,value:e}}async loadSimulatorManifestForState(){if(void 0!==this.simulatorManifest)return"function"!=typeof this.simulatorManifest?this.simulatorManifest:this.hasSimulatorManifestStateValue?this.simulatorManifestStateValue:(this.simulatorManifestStatePromise||(this.simulatorManifestStatePromise=Promise.resolve(this.simulatorManifest()).then(e=>(this.hasSimulatorManifestStateValue=!0,this.simulatorManifestStateValue=e,e)).finally(()=>{this.simulatorManifestStatePromise=void 0})),this.simulatorManifestStatePromise)}async mergeSimulatorManifestForState(e){if(void 0===this.simulatorManifest)return e;try{let t=await this.loadSimulatorManifestForState();if(!t)return e;return new u(n4(e.raw,t))}catch(t){return console.warn("[web-sdk-debugger] Failed to merge simulator manifest for debug state",t),e}}async loadManifest(e){this.assertActive();let t=this.state.manifestUrl,r=nK(e??this.state.manifestUrl);this.setState({...this.state,manifestUrl:r,resourceUrlVersion:this.resourceUrlVersion,status:nX("loading",`Loading manifest ${r}`)});try{var n,a,i,s,o,l;let e,t,d,u,p,h=await c(r,{fetcher:this.fetcher}),m=await this.mergeSimulatorManifestForState(h),g=m.pages,f=m.widgets,v=n0(m,null==(n=this.state.pageSelection)?void 0:n.routeUrl)??(s=m,o=g,l=this.state.pageSelection,e=o.filter(rH),t=null==l?void 0:l.item.path,d=function(e,t){if(t)try{return e.getPageEntry(t)}catch{return}}(s,s.raw.applet.appletEntry),nY((t?e.find(e=>e.path===t):void 0)??(d&&rH(d)?d:void 0)??e.find(e=>"index"===e.id||"/pages/index"===e.path||"/pages/index/index"===e.path)??e[0])),y=(a=this.state.widgetSelection,u=f.filter(rH),(i=((p=null==a?void 0:a.item.widgetId)?u.find(e=>e.widgetId===p):void 0)??u[0])?{kind:"widgets",item:i}:null);return this.setState({...this.state,manifestUrl:r,manifest:m,pages:g,widgets:f,resourceUrlVersion:this.resourceUrlVersion,pageSelection:v,widgetSelection:y,status:nX("ready",v||y?`Loaded manifest ${r}`:`Manifest has no entries ${r}`)}),this.state}catch(r){let e=r instanceof Error?r:Error(String(r));throw this.setState({...this.state,manifestUrl:t,status:nX("error",`Load failed: ${e.message}`,e)}),e}}navigateToPage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.assertActive();try{let r=n0(this.state.manifest,e);if(!r)throw Error(`Unknown pages route: ${e}`);this.setState({...this.state,pageSelection:{...r,routeMode:t.routeMode},status:nX("ready",`Navigated page ${r.item.path}`)})}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.setState({...this.state,status:nX("error",e.message,e)}),e}}selectWidget(e){this.assertActive();let t=this.state.widgets.find(t=>t.widgetId===e);if(!t){let t=Error(`Unknown widgets entry: ${e}`);throw this.setState({...this.state,status:nX("error",t.message,t)}),t}this.setState({...this.state,widgetSelection:{kind:"widgets",item:t},status:nX("ready",`Selected widget ${t.widgetId}`)})}async reloadResources(){if(this.assertActive(),"streaming"===this.state.simulator.streamStatus)throw Error("Cannot refresh card resources while simulator query is streaming");let e=this.state.manifestUrl,t=rJ("reload");this.resourceUrlVersion=t,this.clearSimulatorManifestStateValue();let r=await this.loadManifest(e);return void 0!==this.simulatorSkills&&await this.resolveSimulatorSkillsForQuery(t,{}),this.appendSimulatorDebugEvent({category:"resource",event:"simulator_resource_reload_completed",manifest_url:e,resource_url_version:t,summary:"Card resources refreshed"}),r}async sendSimulatorQuery(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.assertActive();let r=e.trim(),n=(t.images??[]).filter(e=>e.resource_uri);if(r||0!==n.length)return this.sendSimulatorChat({kind:"message",queryText:r},t)}sendSimulatorFollowUpMessage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((r,n)=>{let a=Error("Simulator follow-up message was cancelled before submission");this.sendSimulatorChat({kind:"follow_up",content:e},t,r,()=>n(a)).then(()=>n(a),n)})}async sendSimulatorChat(e,t,r,n){this.assertActive(),this.cancelSimulatorQuery();let a=rJ("local_msg"),i=rJ("idem"),s=rJ("trace"),o=Date.now(),l=this.state.simulator,d=this.state.manifest.raw,u="message"===e.kind?(t.images??[]).filter(e=>e.resource_uri):[],c="message"===e.kind?{messageId:a,localMessageId:a,traceId:s,role:"user",contentType:u.length>0?"mixed":"text",text:e.queryText,blocks:[...u.map(e=>({blockId:rJ("block_image"),type:"image",image:e})),...e.queryText?[{blockId:rJ("block_text"),type:"text",text:e.queryText}]:[]],status:"completed",createdAtMs:o}:void 0,p=this.createSimulatorRun(s);p.onCancelledBeforeSubmission=n,this.activeSimulatorRun=p,this.setState({...this.state,simulator:{...l,activeRequestId:void 0,activeReplyMessageId:void 0,error:void 0,locationDirective:void 0,messages:c?[...l.messages,c]:l.messages,streamStatus:"streaming"}}),this.appendSimulatorDebugEvent({event:"simulator_query_prepare_started",trace_id:s,previous_active_request_id:l.activeRequestId,previous_stream_status:l.streamStatus,history_message_count:l.messages.length,query_preview:"message"===e.kind?e.queryText.slice(0,80)||"[图片]":"send_follow_up_message",image_count:u.length});try{var h,m;let n,u=await this.resolveSimulatorManifestForQuery(s,t,d,p.streamAbortController.signal),c=n2(u,this.state.manifest.appId),g=n3(u,this.state.manifest.name);if(!this.isSimulatorRunCurrent(p))return;let f=await this.resolveSimulatorSkillsForQuery(s,t,p.streamAbortController.signal);if(!this.isSimulatorRunCurrent(p))return;let v={signal:p.streamAbortController.signal,trace:{trace_id:s,component:"web_sdk_debugger",stage:"query_prepare",sampled:!0},appKey:t.appKey||this.simulatorAppKey||c,appName:t.appName||this.simulatorAppName||g,manifest:u},y=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider(v):this.simulatorMcpServers;if(this.lastResolvedSimulatorMcpServers=y,!this.isSimulatorRunCurrent(p))return;this.appendSimulatorDebugEvent({event:"simulator_query_mcp_resolved",trace_id:s,elapsed_ms:Date.now()-o,mcp_server_count:y.length,mcp_servers:y.map(e=>({server_id:e.server_id,tool_count:e.tools.length,tools:e.tools.map(e=>e.name)}))});let _={historyMaxTurns:this.historyMaxTurns,idempotencyKey:i,localMessageId:a,manifestAppId:this.state.manifest.appId,manifestAppName:g,messages:l.messages,toolCalls:l.toolCalls,options:t,simulatorAppKey:this.simulatorAppKey,simulatorAppName:this.simulatorAppName,simulatorSkills:f,simulatorManifest:u,simulatorMaxStep:this.simulatorMaxStep,simulatorMcpServers:y,traceId:s},b="message"===e.kind?(h={..._,queryText:e.queryText},n=nz(h.options.images??[]),{...nW(h),message:{role:"USER",content:h.queryText,local_message_id:h.localMessageId,parts:n.length>0?n:void 0}}):(m={..._,content:e.content},{...nW(m),input_event:{event_type:"send_follow_up_message",params:{content:m.content},local_message_id:m.localMessageId}});if(await r9({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,onSubmitted:()=>{p.onCancelledBeforeSubmission=void 0,null==r||r()},request:b,signal:p.streamAbortController.signal,onEvent:t=>this.handleSimulatorEvent(t,p,"follow_up"===e.kind?e.content:void 0)}),!this.isSimulatorRunCurrent(p))return;"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,streamStatus:"completed"}}),this.appendSimulatorDebugEvent({event:"simulator_query_stream_returned",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus,active_request_id:this.state.simulator.activeRequestId})}catch(n){if(nw(n))return void this.appendSimulatorDebugEvent({event:"simulator_query_aborted",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus});if(!this.isSimulatorRunCurrent(p))return;let e=nS(n,"query_stream"),t=this.getSimulatorQueryFailureDiagnosis(s,n),r=t?{...e,message:t.summary,user_message:t.summary,details:{...e.details,diagnosis:t,original_error:e.message}}:e;throw this.appendSimulatorDebugEvent({event:"simulator_query_failed",trace_id:s,elapsed_ms:Date.now()-o,error:r}),this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,error:r,streamStatus:"error"}}),n}finally{this.finishSimulatorStream(p)}}pushMessages(e){if(this.assertActive(),!Array.isArray(e))throw Error("Messages must be an array");if(0===e.length)return;let t=structuredClone(e).map(e=>{let t=(e.blocks??[]).map(e=>({...e,blockId:e.blockId??rJ("block"),..."card"===e.type?{card:{...e.card,card_id:e.card.card_id??rJ("card")}}:{}}));return{...e,messageId:e.messageId??rJ("message"),createdAtMs:e.createdAtMs??Date.now(),text:e.text??"",contentType:e.contentType??(t.some(e=>"text"!==e.type)?"mixed":"text"),blocks:t}}),r=new Set(this.state.simulator.messages.map(e=>e.messageId));for(let e of t){if(r.has(e.messageId))throw Error(`Duplicate messageId: ${e.messageId}`);r.add(e.messageId)}this.updateSimulatorState(e=>({...e,messages:[...e.messages,...t]}))}removeSimulatorMessages(e){this.assertActive();let t=new Set(e.filter(Boolean));if(0===t.size)return;let r=nQ(this.state.simulator.messages.filter(e=>t.has(e.messageId)));this.updateSimulatorState(e=>({...e,activeReplyMessageId:e.activeReplyMessageId&&t.has(e.activeReplyMessageId)?void 0:e.activeReplyMessageId,messages:e.messages.filter(e=>!t.has(e.messageId)),selectedCard:e.selectedCard&&t.has(e.selectedCard.reply_message_id)?void 0:e.selectedCard})),queueMicrotask(()=>{let e=nQ(this.state.simulator.messages);for(let t of r)e.has(t)||URL.revokeObjectURL(t)})}applySimulatorCardDelta(e){this.assertActive(),this.updateSimulatorState(t=>nk(t,tj(e.card_delta)?e.card_delta:e).state)}consumeSimulatorLocationDirective(e){this.assertActive(),this.updateSimulatorState(t=>{var r;return(null==(r=t.locationDirective)?void 0:r.cardId)===e?{...t,locationDirective:void 0}:t})}cancelSimulatorQuery(){this.assertActive();let e=this.state.simulator.activeRequestId,t=this.activeSimulatorRun;t&&(this.appendSimulatorDebugEvent({event:"simulator_query_cancel_requested",request_id:e,trace_id:t.traceId,stream_status:this.state.simulator.streamStatus}),this.abortSimulatorRun(t)),"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,activeReplyMessageId:void 0,toolCalls:this.state.simulator.toolCalls.map(t=>e&&t.requestId===e&&"running"===t.status?{...t,status:"cancelled",updatedAtMs:Date.now()}:t),streamStatus:"cancelled"}})}async callSimulatorTool(e){if(this.assertActive(),!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");let t=e.toolName.trim();if(!t)throw Error("toolName must be a non-empty string");let r=rJ("req_tool"),n=rJ("reply_tool"),a=rJ("tool_call"),i=rJ("trace"),s={trace_id:i,component:"web_sdk_debugger",stage:"direct_tool_call",sampled:!0},o=Date.now(),l=await this.resolveDirectToolCallServerId(t,e.serverId,s),d={requestId:r,replyMessageId:n,toolCallId:a,toolName:t,serverId:l,appKey:this.simulatorAppKey||n2(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.params,argumentsJson:e.params?function(e){try{return JSON.stringify(e??{})}catch{return""}}(e.params):void 0,status:"running",createdAtMs:o,updatedAtMs:o,trace:s,timeoutMs:e.timeoutMs};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,d]})),this.appendSimulatorDebugEvent({event:"direct_tool_call_started",request_id:r,trace_id:i,tool_call_id:a,tool_name:t,server_id:l,arguments:e.params,arguments_json:d.argumentsJson});let u=Date.now(),c=await this.runSimulatorToolCall(d);return this.updateToolCall(a,{status:c.status,updatedAtMs:Date.now(),error:c.error,resultSummary:n1(c),structuredResultSummary:c.result,isMiniApp:c.miniapp&&"boolean"==typeof c.miniapp.is_mini_app?c.miniapp.is_mini_app:void 0}),this.appendSimulatorDebugEvent({event:"direct_tool_call_completed",request_id:r,trace_id:i,tool_call_id:a,tool_name:t,server_id:l,status:c.status,elapsed_ms:Date.now()-u,result:c.result,error:c.error,raw_result_text:c.raw_result_text}),c}executeSandboxToolCall(e){this.assertActive();let t=`${e.request_id}\0${e.tool_call.tool_call_id}`,r=this.sandboxToolCallExecutions.get(t);if(r)return r;let n=this.executeSandboxToolCallOnce(e);return this.sandboxToolCallExecutions.set(t,n),n}async submitToolResult(e,t){let r,n,a,i;this.assertActive();let s=Date.now(),o=(n=void 0===e.result?e.error?{error:e.error.message}:{}:e.result,a=e.raw_mcp_result_json,i=e.raw_result_text||t3(e.error?{error:e.error.message,detail:e.error}:n),{request_id:e.requestId,tool_call_id:e.toolCallId,server_id:e.serverId,tool_name:e.toolName,status:function(e){switch(e){case"succeeded":return"SUCCESS";case"timeout":return"TIMEOUT";case"cancelled":return"CANCELLED";case"rejected":return"REJECTED";default:return"FAILED"}}(e.status),app_key:e.appKey,result:{tool_call_id:e.toolCallId,content:i,structured_json:t3(n)},raw_result_text:i,raw_mcp_result_json:a||"",miniapp:e.miniapp,timing:e.timing,trace:{trace_id:e.trace.trace_id,component:nF,stage:"tool_report",sampled:e.trace.sampled??!0},ext:{reported_by:nF}});this.appendSimulatorDebugEvent({event:"tool_result_report_started",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:e.serverId,status:o.status,report_request:o,endpoint:this.state.simulator.endpoint});try{r=await ne({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,result:o,signal:t})}catch(r){let t=r6(r);throw this.appendSimulatorDebugEvent({event:"tool_result_report_failed",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,error:t4(r),response:t}),r}this.appendSimulatorDebugEvent({event:"tool_result_report_response_received",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,response:r});let l=function(e){let t=e.code,r=!1===e.accepted,n=void 0!==t&&0!==t&&"0"!==t;if(!r&&!n)return;let a="string"==typeof e.message&&e.message?e.message:n?`Simulator tool result rejected with code ${String(t)}`:"Simulator tool result was not accepted",i=tQ(e)[0];return nG("TOOL_RESULT_REJECTED",i?`${a} (x-tt-logid: ${i})`:a,"tool_result_submit",{gateway_response:e,gateway_code:n?t:void 0,gateway_accepted:!r&&void 0,"x-tt-logid":i})}(r);if(this.appendSimulatorDebugEvent({event:"tool_result_ack",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,accepted:r.accepted,next_action:r.next_action,error:l,response:r}),l)throw l;return r}selectSimulatorCard(e){this.assertActive(),this.updateSimulatorState(t=>({...t,selectedCard:e}))}updateSimulatorWidget(e){let t;if(this.assertActive(),"string"!=typeof e.widgetInstanceId||!e.widgetInstanceId.trim())return{status:"invalid_params",message:"widgetInstanceId must be a non-empty string"};if(void 0!==e.widgetId&&("string"!=typeof e.widgetId||!e.widgetId.trim()))return{status:"invalid_params",message:"widgetId must be a non-empty string when provided"};try{t=JSON.parse(e.widgetData)}catch{return{status:"invalid_widget_data",message:"widgetData must be a JSON object"}}if(!tj(t))return{status:"invalid_widget_data",message:"widgetData must be a JSON object"};let r=nf(this.state.simulator.messages,e.widgetInstanceId,r=>({...r,widget_id:e.widgetId||r.widget_id,render_data:t}));return r.found?(this.updateSimulatorState(e=>({...e,messages:r.messages})),{status:"updated"}):{status:"not_found",message:`Widget instance ${e.widgetInstanceId} was not found`}}appendSimulatorTraceEvent(e){this.assertActive(),this.appendSimulatorDebugEvent(e)}async approveSimulatorToolCall(e){this.assertActive();let t=this.getSimulatorToolCall(e);if(!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");if("pending_approval"!==t.status)return;let r=this.getSimulatorToolCallRun(t);if(void 0!==t.runId&&!r)return void this.cancelStaleSimulatorToolCall(t);let n={...t,status:"running",updatedAtMs:Date.now()};null==r||r.pendingApprovalToolCallIds.delete(e),this.updateToolCall(e,{status:n.status,updatedAtMs:n.updatedAtMs}),await this.executeSimulatorToolCall(n,r)}async rejectSimulatorToolCall(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Tool call rejected by user";this.assertActive();let r=this.getSimulatorToolCall(e);if("pending_approval"!==r.status)return;let n=this.getSimulatorToolCallRun(r);if(void 0!==r.runId&&!n)return void this.cancelStaleSimulatorToolCall(r);let a=this.createToolExecutorInput(r),i=nG("TOOL_EXEC_REJECTED",t),s=Date.now();null==n||n.pendingApprovalToolCallIds.delete(e);try{await this.submitExecutedToolResult(a,{status:"rejected",error:i},s,null==n?void 0:n.streamAbortController.signal),this.updateToolCall(e,{status:"rejected",updatedAtMs:Date.now(),error:i,resultSummary:t})}catch(a){if(n&&!this.isSimulatorRunCurrent(n))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:r.requestId,trace_id:r.trace.trace_id,tool_call_id:r.toolCallId,tool_name:r.toolName,reason:"stale_or_cancelled_run"});let t=nS(a,"tool_result_submit");throw this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:r.trace.trace_id,tool_call_id:e,summary:t4(a)}),this.updateToolCall(e,{status:"failed",updatedAtMs:Date.now(),error:t}),a}finally{n&&this.releaseSimulatorRun(n)}}getState(){return this.state}subscribe(e){return this.assertActive(),this.listeners.add(e),()=>{this.listeners.delete(e)}}getResourceUrl(e){return(this.assertActive(),e)?p(this.state.manifestUrl,e)??null:null}destroy(){var e,t;if(!this.destroyed){for(let r of(this.cancelSimulatorQuery(),null==(t=this.simulatorToolExecutor)||null==(e=t.dispose)||e.call(t),nQ(this.state.simulator.messages)))URL.revokeObjectURL(r);this.destroyed=!0,this.sandboxToolCallExecutions.clear(),this.listeners.clear()}}createSimulatorRun(e){return{id:this.simulatorRunSeq+=1,traceId:e,streamAbortController:new AbortController,streamDone:!1,cancelled:!1,pendingApprovalToolCallIds:new Set,toolAbortControllers:new Set}}isSimulatorRunCurrent(e){return!this.destroyed&&this.activeSimulatorRun===e&&!e.cancelled}abortSimulatorRun(e){var t;for(let r of(e.cancelled=!0,null==(t=e.onCancelledBeforeSubmission)||t.call(e),e.onCancelledBeforeSubmission=void 0,e.streamAbortController.abort(),e.toolAbortControllers))r.abort();this.activeSimulatorRun===e&&(this.activeSimulatorRun=null)}finishSimulatorStream(e){e.streamDone=!0,this.releaseSimulatorRun(e)}releaseSimulatorRun(e){this.activeSimulatorRun===e&&(e.cancelled||e.streamDone&&0===e.pendingApprovalToolCallIds.size&&0===e.toolAbortControllers.size)&&(this.activeSimulatorRun=null)}handleSimulatorEvent(e,t,r){let n="tool_call"===e.event_type;if(!this.isSimulatorRunCurrent(t)){n&&this.appendSimulatorDebugEvent({event:"tool_call_event_skipped",request_id:e.request_id,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",reason:"stale_or_cancelled_run",summary:"Tool call event arrived after its simulator run was cancelled and was not executed"});return}let a=this.state.simulator.activeRequestId;if(a&&e.request_id!==a&&"ack"!==e.event_type&&"debug"!==e.event_type){if(!n&&"tool_status"!==e.event_type)return;this.appendSimulatorDebugEvent({event:"tool_call_request_id_mismatch",request_id:e.request_id,active_request_id:a,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",event_type:e.event_type,summary:"Tool call event request_id differs from the acknowledged request_id"})}let{state:i,toolCall:s,cardRefresh:o,locationDirective:l}=function(e,t,r){var n,a,i,s,o,l,d,u,c,p,h,m;let g,f,v,y,_,b,w,S,x={...e,activeReplyMessageId:t.reply_message_id??e.activeReplyMessageId},I=!function(e){switch(e.event_type){case"ack":case"tool_call":case"tool_status":case"card_delta":case"content_block":case"answer_finish":case"message_finish":case"reply_finish":case"stream_error":case"trace_event":case"debug":return!0;default:return!1}}(t)?x:nI(x,(S=t.received_at_ms??Date.now(),{display:"debug"===(n=t).event_type?ni(n.payload)??{category:"debug",detail:nv(n),phase:"event",title:"Debug"}:{category:n_(n),detail:nv(n),phase:nb(n.event_type),title:ny(n)},id:t.event_id,timestamp:S,payload:(a=t,i=S,g=n_(a),f=nb(a.event_type),v={event:a.event_type,category:g,phase:f,received_at_ms:i,server_timestamp_ms:a.created_at_ms,title:ny(a),detail:nv(a),trace:a.trace},"debug"===a.event_type?{...v,event:a.payload.event||"debug",title:t6(a.payload.title||a.payload.event||"Debug Event"),summary:a.payload.summary,elapsed_ms:a.payload.elapsed_ms,redaction_level:a.payload.redaction_level}:"heartbeat"===a.event_type?{...v,server_time_ms:a.payload.server_time_ms,message:a.payload.message}:"answer_finish"===a.event_type?{...v,status:a.payload.status,finish_reason:a.payload.finish_reason,usage:a.payload.usage}:{...v,...a.payload})}));switch(t.event_type){case"ack":return{state:function(e,t,r){let n=t.payload.local_message_id,a=t.payload.query_message_id,i=t.payload.message_id,s=tj(t.payload.query_message)?t.payload.query_message:void 0,o=(null==s?void 0:s.content)||"",l=e.messages;if(n&&a){let e=l.find(e=>e.localMessageId===n);e?l=l.map(t=>t===e?{...t,messageId:a,followUpContent:r}:t):o&&(l=[...l,{messageId:a,localMessageId:n,requestId:t.request_id,traceId:t.trace.trace_id,followUpContent:r,role:"user",contentType:"text",text:o,blocks:[{blockId:`block_text_${a}`,type:"text",text:o}],status:"completed",createdAtMs:t.created_at_ms}])}return{...e,activeRequestId:t.request_id,activeReplyMessageId:i||e.activeReplyMessageId,messages:l}}(I,t,r.followUpContent)};case"message_start":return{state:(s=I,y=(o=t).payload.message_id||o.reply_message_id||rJ("reply"),{...s,activeReplyMessageId:y,messages:nh(s.messages,y,o.created_at_ms,o.request_id,o.trace.trace_id)})};case"text_delta":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let n=t.payload.block_id||`block_text_${t.seq}`,a=t.payload.delta||"",i=t.payload.op||"append";if("append"!==i&&"replace"!==i)return e;let s=nh(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:nm(s,r,e=>({...e,text:"replace"===i?a:`${e.text}${a}`,blocks:function(e,t,r,n){if(!e.find(e=>"text"===e.type&&e.blockId===t)){let a=e[e.length-1];return"append"===n&&(null==a?void 0:a.type)==="text"?e.map(e=>e===a?{...e,text:`${e.text}${r}`}:e):[...e,{blockId:t,type:"text",text:r}]}return e.map(e=>"text"===e.type&&e.blockId===t?{...e,text:"replace"===n?r:`${e.text}${r}`}:e)}(e.blocks,n,a,i)}))}}(I,t)};case"card_delta":return nk(I,t.payload,t);case"content_block":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let n=function(e,t){for(let[r,n]of(Array.isArray(e.content_block)?e.content_block:Array.isArray(e.contentBlock)?e.contentBlock:[]).entries()){let a=function(e){if(!tj(e))return;let t=tj(e.content)?e.content:e,r=tj(t.permission_apply_block)?t.permission_apply_block:tj(t.permissionApplyBlock)?t.permissionApplyBlock:void 0;return r?("string"==typeof r.permission_data?r.permission_data:"")||("string"==typeof r.permissionData?r.permissionData:""):""}(n),i=nu(a);if(!i)continue;let s=(tj(n)&&"string"==typeof n.block_id?n.block_id:"")||(tj(n)&&"string"==typeof n.blockId?n.blockId:"")||`permission_apply_${t.seq}_${r}`;return{blockId:s,card:{card_id:s,card_type:"permission_apply",fallback_text:"需要授权后继续",render_data:{grantingData:i,permissionData:a},title:nc(i)},op:e.op||"append"}}}(t.payload,t);if(!n||"append"!==n.op&&"replace"!==n.op)return e;let a=nh(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:nm(a,r,e=>({...e,contentType:"mixed",blocks:ng(e.blocks,n.blockId,n.card,n.op)}))}}(I,t)};case"tool_call":return function(e,t,r){let n=t.payload.tool_call_id,a=t.payload.tool_name,i=t.payload.server_id||"",s=t.payload.arguments_json||"",o=t.reply_message_id??e.activeReplyMessageId??rJ("reply");if(!n||!a)return{state:nI(e,{id:rJ("trace"),timestamp:Date.now(),payload:{event:"tool_call_ignored",request_id:t.request_id,trace_id:t.trace.trace_id,tool_call_id:n,tool_name:a,reason:n?"missing_tool_name":"missing_tool_call_id",tool_call_payload:t.payload,summary:"Tool call event is missing required fields and cannot be executed"}})};let l=t.payload.requires_user_approval??!1,d=l?"pending_approval":r.hasToolExecutor?"running":"pending",u={requestId:t.request_id,runId:r.runId,replyMessageId:o,toolCallId:n,toolName:a,serverId:i,appKey:t.payload.app_key,arguments:tj(t.payload.arguments)?t.payload.arguments:t2(s),argumentsJson:s,mcpHeaders:function(e){if(!tj(e))return;let t=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1]));return Object.keys(t).length>0?t:void 0}(t.payload.headers),status:d,createdAtMs:t.created_at_ms,updatedAtMs:t.created_at_ms,trace:t.trace,requiresUserApproval:l,timeoutMs:t.payload.timeout_ms,deadlineMs:t.payload.deadline_ms},c=nm(nh(e.messages,o,t.created_at_ms,t.request_id,t.trace.trace_id),o,e=>({...e,toolCalls:nN(e.toolCalls??[],u)})),p={...e,messages:c,toolCalls:[...e.toolCalls.filter(e=>e.toolCallId!==n),u]};return r.hasToolExecutor?{state:p,toolCall:u}:{state:nI(p,{id:rJ("trace"),timestamp:Date.now(),payload:{event:"tool_executor_missing",request_id:u.requestId,trace_id:u.trace.trace_id,tool_call_id:n,tool_name:a,summary:"No local simulator tool executor is configured"}})}}(I,t,r);case"tool_status":return{state:function(e,t){let r=t.payload.tool_call_id,n=function(e){switch(e){case"SUCCESS":return"succeeded";case"FAILED":return"failed";case"RUNNING":return"running";case"TIMEOUT":return"timeout";case"CANCELLED":return"cancelled";case"REJECTED":return"rejected";default:return""}}(t.payload.status||"");if(!r||!n)return e;let a=t.payload.progress,i=t.payload.message,s=t.payload.error?nS(t.payload.error,"tool_execute"):void 0,o=nE(e,r,{status:n,updatedAtMs:t.created_at_ms,progress:a,message:i,error:s}),l=o.toolCalls.find(e=>e.toolCallId===r);return l?{...o,messages:nm(o.messages,l.replyMessageId,e=>({...e,toolCalls:nN(e.toolCalls??[],l)}))}:o}(I,t)};case"trace_event":case"debug":default:return{state:I};case"heartbeat":return{state:(l=I,d=t,{...l,lastHeartbeatMs:d.payload.server_time_ms??d.created_at_ms})};case"answer_finish":return{state:(u=I,c=t,{...u,answerFinish:{messageId:c.reply_message_id,status:c.payload.status,finishReason:c.payload.finish_reason,usage:tj(c.payload.usage)?c.payload.usage:void 0,createdAtMs:c.created_at_ms,trace:c.trace,payload:c.payload}})};case"message_finish":return{state:function(e,t){let r=t.payload.message_id||t.reply_message_id;if(!r)return e;let n=t.payload.status||"completed";return{...e,messages:nm(e.messages,r,e=>({...e,status:function(e){switch(e){case"completed":case"finished":default:return"completed";case"cancelled":case"interrupted":return"interrupted";case"failed":case"error":return"failed"}}(n)}))}}(I,t)};case"reply_finish":return{state:(p=I,b="completed"===(_=t.payload.status||"completed")||"finished"===_?"completed":"cancelled"===_?"cancelled":"error",{...p,activeRequestId:void 0,activeReplyMessageId:void 0,messages:nC(p.messages,b),streamStatus:b})};case"stream_error":return{state:(h=I,w=nS((m=t).payload.error??m.payload,m.payload.stage||"stream"),{...h,activeRequestId:void 0,error:w,messages:nC(h.messages,"error"),streamStatus:"error"})}}}(this.state.simulator,e,{followUpContent:r,hasToolExecutor:!!this.simulatorToolExecutor,runId:t.id}),d=l&&!this.receivedSimulatorLocationDirectiveCardIds.has(l.cardId)?l:void 0;if(d&&this.receivedSimulatorLocationDirectiveCardIds.add(d.cardId),this.updateSimulatorState(()=>d?{...i,locationDirective:d}:i),d?this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_received",card_id:d.cardId,request_id:d.requestId,source_tool_call_id:d.sourceToolCallId,tool_name:d.toolName,trace_id:e.trace.trace_id}):l&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_loop_prevented",card_id:l.cardId,reason:"duplicate_card_id",request_id:l.requestId,tool_name:l.toolName,trace_id:e.trace.trace_id}),(null==o?void 0:o.status)==="not_found"&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_history_card_refresh_skipped",reason:"card_not_found",request_id:e.request_id,trace_id:e.trace.trace_id,card_id:o.cardId}),s){let e=this.withFallbackToolCallServerId(s);e.requiresUserApproval?t.pendingApprovalToolCallIds.add(e.toolCallId):this.executeSimulatorToolCall(e,t)}}async executeSandboxToolCallOnce(e){let t=e.tool_call,r=Date.now(),n={trace_id:`bridge_${e.request_id}`,component:"sandbox_bridge",stage:"calltool_execute",sampled:!0},a={appKey:t.app_key,arguments:JSON.parse(t.arguments_json),argumentsJson:t.arguments_json,createdAtMs:r,deadlineMs:t.deadline_ms,mcpHeaders:t.headers,replyMessageId:`bridge_reply_${e.request_id}`,requestId:e.request_id,serverId:t.server_id,status:"running",timeoutMs:t.timeout_ms,toolCallId:t.tool_call_id,toolName:t.tool_name,trace:n,updatedAtMs:r};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,a]})),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_started",request_id:a.requestId,trace_id:n.trace_id,tool_call_id:a.toolCallId,app_key:a.appKey,server_id:a.serverId,tool_name:a.toolName,arguments_json:a.argumentsJson,deadline_ms:a.deadlineMs,timeout_ms:a.timeoutMs});let i=Date.now(),s=t.deadline_ms<=i?{status:"timeout",error:nG("TOOL_EXEC_TIMEOUT","Sandbox tool call deadline has expired")}:await this.runSimulatorToolCall(a),o=this.createToolExecutorInput(a);try{await this.submitSandboxToolResultWithRetry(o,s,i)}catch(t){let e=nS(t,"tool_result_submit");throw this.updateToolCall(a.toolCallId,{error:e,resultSummary:e.message,status:"failed",updatedAtMs:Date.now()}),t}return this.updateToolCall(a.toolCallId,{error:s.error,isMiniApp:s.miniapp&&"boolean"==typeof s.miniapp.is_mini_app?s.miniapp.is_mini_app:void 0,resultSummary:n1(s),status:s.status,structuredResultSummary:s.result,updatedAtMs:Date.now()}),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_reported",request_id:a.requestId,trace_id:n.trace_id,tool_call_id:a.toolCallId,app_key:a.appKey,server_id:a.serverId,tool_name:a.toolName,status:s.status,elapsed_ms:Date.now()-i,raw_mcp_result_json:s.raw_mcp_result_json}),{reported:!0,requestId:a.requestId,toolCallId:a.toolCallId}}withFallbackToolCallServerId(e){var t,r;if(e.serverId)return e;let n=this.lastResolvedSimulatorMcpServers,a=(null==(t=n.find(t=>t.tools.some(t=>t.name===e.toolName)))?void 0:t.server_id)||(null==(r=n[0])?void 0:r.server_id)||"local_mcp";return this.appendSimulatorDebugEvent({event:"tool_call_server_id_fallback",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:a,summary:"Tool call event has no server_id; falling back to a locally resolved MCP server"}),this.updateToolCall(e.toolCallId,{serverId:a}),{...e,serverId:a}}async runSimulatorToolCall(e,t){if(!this.simulatorToolExecutor){let e=nG("TOOL_EXECUTOR_UNAVAILABLE","No local simulator tool executor is configured");return{error:e,result:{error:e.message},status:"failed"}}try{return await nJ({executor:this.simulatorToolExecutor,input:this.createToolExecutorInput(e),record:e,signal:t})}catch(t){let e=nS(t,"tool_execute");return{status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||nw(t)?"cancelled":"failed",error:e}}}async executeSimulatorToolCall(e,t){if(t&&!this.isSimulatorRunCurrent(t))return;let r=Date.now(),n=this.createToolExecutorInput(e),a=t?new AbortController:void 0;t&&a&&t.toolAbortControllers.add(a);let i=await this.runSimulatorToolCall(e,null==a?void 0:a.signal);try{if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});if(await this.submitExecutedToolResult(n,i,r,null==a?void 0:a.signal),t&&!this.isSimulatorRunCurrent(t))return;this.updateToolCall(e.toolCallId,{status:i.status,updatedAtMs:Date.now(),error:i.error,resultSummary:n1(i),structuredResultSummary:i.result,isMiniApp:i.miniapp&&"boolean"==typeof i.miniapp.is_mini_app?i.miniapp.is_mini_app:void 0})}catch(n){if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});let r=nS(n,"tool_result_submit");this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,summary:t4(n),error:r}),this.updateToolCall(e.toolCallId,{status:"failed",updatedAtMs:Date.now(),error:r}),this.failActiveSimulatorStream(r)}finally{t&&a&&(t.toolAbortControllers.delete(a),this.releaseSimulatorRun(t))}}uploadSimulatorImage(e,t){return this.assertActive(),r7({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,file:e,signal:t})}createToolExecutorInput(e){let t={trace_id:e.trace.trace_id,span_id:rJ("span_tool_execute"),parent_span_id:e.trace.span_id,component:"local_mcp",stage:"tool_execute",sampled:e.trace.sampled};return{requestId:e.requestId,replyMessageId:e.replyMessageId,toolCallId:e.toolCallId,toolName:e.toolName,serverId:e.serverId,appKey:e.appKey||this.simulatorAppKey||n2(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.arguments,argumentsJson:e.argumentsJson,headers:e.mcpHeaders,manifest:this.state.manifest.raw,timeoutMs:e.timeoutMs,deadlineMs:e.deadlineMs,trace:t}}async resolveSimulatorManifestForQuery(e,t,r,n){let a=Date.now(),i=void 0!==t.manifest,s=i?"query_option":void 0===this.simulatorManifest?"loaded_manifest":"debugger_option";this.appendSimulatorDebugEvent({event:"simulator_manifest_load_started",trace_id:e,source:s});try{let o=i?{found:!1,value:void 0}:this.takeSimulatorManifestStateValue(),l=i?t.manifest:o.found?o.value:"function"==typeof this.simulatorManifest?await this.simulatorManifest(n):this.simulatorManifest,d=l?n4(r,l):r;return this.appendSimulatorDebugEvent({event:"simulator_manifest_loaded",trace_id:e,elapsed_ms:Date.now()-a,source:s,manifest:d}),d}catch(t){return n.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_manifest_load_failed",trace_id:e,elapsed_ms:Date.now()-a,error:t4(t),source:s}),r}}async resolveSimulatorSkillsForQuery(e,t,r){let n=Date.now(),a=void 0===t.skills?"debugger_option":"query_option";this.appendSimulatorDebugEvent({event:"simulator_skill_load_started",trace_id:e,source:a});try{let i=t.skills??("function"==typeof this.simulatorSkills?await this.simulatorSkills(r):this.simulatorSkills)??[];return this.appendSimulatorDebugEvent({event:i.length>0?"simulator_skill_loaded":"simulator_skill_empty",trace_id:e,elapsed_ms:Date.now()-n,skills_length:i.reduce((e,t)=>e+t.content.length,0),skill_paths:i.map(e=>e.relativePath),source:a}),i}catch(t){return null==r||r.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_skill_load_failed",trace_id:e,elapsed_ms:Date.now()-n,error:t4(t),source:a}),[]}}async resolveDirectToolCallServerId(e,t,r){var n;let a=null==t?void 0:t.trim();if(a)return a;let i=this.state.manifest.raw,s=this.simulatorAppKey||n2(i,this.state.manifest.appId),o=this.simulatorAppName||n3(i,this.state.manifest.name),l=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider({trace:r,appKey:s,appName:o,manifest:i}):this.simulatorMcpServers,d=l.find(t=>t.tools.some(t=>t.name===e));return(null==d?void 0:d.server_id)??(null==(n=l[0])?void 0:n.server_id)??"local_mcp"}getSimulatorToolCall(e){let t=this.state.simulator.toolCalls.find(t=>t.toolCallId===e);if(!t)throw Error(`Unknown simulator tool call: ${e}`);return t}getSimulatorToolCallRun(e){let t=this.activeSimulatorRun;if(t&&this.isSimulatorRunCurrent(t))return void 0===e.runId||e.runId===t.id?t:void 0}cancelStaleSimulatorToolCall(e){let t=nG("TOOL_EXEC_CANCELLED","Tool call cancelled because its simulator run is no longer active");this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"}),this.updateToolCall(e.toolCallId,{status:"cancelled",updatedAtMs:Date.now(),error:t,resultSummary:t.message})}async submitSandboxToolResultWithRetry(e,t,r){let n;for(let a=1;a<=2;a+=1)try{await this.submitExecutedToolResult(e,t,r,void 0,a);return}catch(t){if(n=t,2===a||void 0!==e.deadlineMs&&Date.now()>=e.deadlineMs)throw t;this.appendSimulatorDebugEvent({event:"sandbox_tool_result_report_retry",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,attempt:a+1,error:t4(t)})}throw n}async submitExecutedToolResult(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,i=Date.now();await this.submitToolResult({...e,...t,timing:{started_at_ms:r,ended_at_ms:i,duration_ms:i-r,attempt:a}},n)}updateToolCall(e,t){this.updateSimulatorState(r=>nE(r,e,t))}failActiveSimulatorStream(e){this.activeSimulatorRun&&this.abortSimulatorRun(this.activeSimulatorRun),this.updateSimulatorState(t=>({...t,activeRequestId:void 0,activeReplyMessageId:void 0,error:e,messages:t.messages.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:"failed"}:e),streamStatus:"error"}))}getSimulatorQueryFailureDiagnosis(e,t){let r=new Set;for(let t of this.state.simulator.traceEvents){let n=t.payload,a=nZ["string"==typeof n.event?n.event:""];a&&function(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}(n)===e&&"Failed to fetch"===(n.error||"")&&r.add(a)}if(r.size>=3)return{code:"DEBUG_SERVER_UNREACHABLE",confidence:"high",failed_services:[...r],summary:"调试 Dev Server 或本机网络不可达",suggestion:"检查调试 Dev Server 是否运行,以及浏览器能否访问当前调试端口。"};let n=r6(t),a="number"==typeof(null==n?void 0:n.status)?n.status:void 0;return 404===a?{code:"SIMULATOR_ENDPOINT_NOT_FOUND",confidence:"high",status:a,summary:"模拟器接口未配置或路由不存在",suggestion:"检查 simulator、manifest、skill 或 MCP 的接口地址与代理路由。"}:void 0!==a&&a>=500?{code:"SIMULATOR_ENDPOINT_SERVER_ERROR",confidence:"high",status:a,summary:`模拟器接口服务异常(HTTP ${a})`,suggestion:"接口已可达,但服务端或其上游依赖异常;请查看响应内容和服务端日志。"}:"Failed to fetch"===t4(t)?{code:"SIMULATOR_ENDPOINT_UNREACHABLE",confidence:"unknown",summary:"无法连接模拟器接口",suggestion:"可能是接口服务未启动、端口不可达、浏览器网络异常或 CORS 被拦截。"}:void 0}appendSimulatorDebugEvent(e){let t=tQ(e),r={display:ni(e),id:rJ("trace"),timestamp:Date.now(),payload:function(e,t){if(!tj(e))return{};let r=ns(e);return{...e,category:r.category,detail:r.detail,phase:r.phase,title:r.title,log_ids:t.length>0?t:void 0}}(e,t)};this.updateSimulatorState(e=>{var t;return{...e,traceEvents:[...e.traceEvents,{...r,order:((null==(t=e.traceEvents.at(-1))?void 0:t.order)??e.traceEvents.length)+1}].slice(-200)}})}updateSimulatorState(e){this.setState({...this.state,simulator:e(this.state.simulator)})}setState(e){for(let t of(this.state=e,this.listeners))t(this.state)}assertActive(){if(this.destroyed)throw Error("WebSdkDebugger has been destroyed")}}let n6="iphone-13",n8=[{key:n6,label:"iPhone 13",width:390,height:844,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-17-pro-max",label:"iPhone 17 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17-pro",label:"iPhone 17 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17",label:"iPhone 17",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-air",label:"iPhone Air",width:420,height:912,density:3,radius:52,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro-max",label:"iPhone 16 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro",label:"iPhone 16 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-plus",label:"iPhone 16 Plus",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16",label:"iPhone 16",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16e",label:"iPhone 16e",width:390,height:844,density:3,radius:44,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-15",label:"iPhone 15",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-14-plus",label:"iPhone 14 Plus",width:428,height:926,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-13-mini",label:"iPhone 13 mini",width:375,height:812,density:3,radius:44,homeIndicator:!0,statusBarHeight:50,safeArea:{top:50,bottom:34,left:0,right:0}},{key:"iphone-se",label:"iPhone SE",width:375,height:667,density:2,radius:0,homeIndicator:!1,statusBarHeight:20,safeArea:{top:20,bottom:0,left:0,right:0}},{key:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-8",label:"Pixel 8",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-7",label:"Pixel 7",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24",label:"Galaxy S24",width:360,height:780,density:3,radius:32,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24-ultra",label:"Galaxy S24 Ultra",width:384,height:854,density:3.75,radius:18,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-cover",label:"Galaxy Z Fold 5 Cover",width:344,height:882,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-inner",label:"Galaxy Z Fold 5 Inner",width:690,height:829,density:2.625,radius:24,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"ipad-mini",label:"iPad mini",width:744,height:1133,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}},{key:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}}],n7=[{key:"100",label:"100%",scale:1},{key:"85",label:"85%",scale:.85},{key:"75",label:"75%",scale:.75},{key:"50",label:"50%",scale:.5},{key:"fit",label:"自适应",scale:.88}],n9={key:"mobile-393",label:"393px",width:393,density:3};function ae(e){let t=/^custom-([1-9]\d{0,3})x([1-9]\d{0,3})$/.exec(e);if(t){let r=Number(t[1]),n=Number(t[2]);return{key:e,label:`自定义 ${r} \xd7 ${n}`,width:r,height:n,density:1,radius:0,homeIndicator:!1,statusBarHeight:0,safeArea:{top:0,bottom:0,left:0,right:0}}}return n8.find(t=>t.key===e)??n8.find(e=>e.key===n6)??n8[0]}let at="devtools_web";function ar(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n9,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{debugger:"web-sdk",density:e.density,screenWidth:e.width,containerWidth:e.width,devicePlatform:"iOS",deviceBrand:"Apple",deviceModel:`Widget preview ${e.label}`,screenOrientation:"portrait",...t,platform:at}}function an(e,t){try{let e=t.trim()?JSON.parse(t):{};if(tj(e))return e;throw Error("expected a JSON object")}catch(t){throw Error(`${e}: ${t.message}`)}}function aa(e){return e??document.body}async function ai(e,t){var r;let n,a=aa(t),i=new CustomEvent("doubao:multi-media-broadcast",{bubbles:!0,composed:!0,detail:e});a.dispatchEvent(i),window.dispatchEvent(new CustomEvent("doubao:multi-media-broadcast",{detail:e}));let s=(r=e.mediaId,n=Array.from(aa(t).querySelectorAll("audio,video")),r?n.filter(e=>e.id===r||e.dataset.mediaId===r):n);return await Promise.all(s.map(t=>"play"===e.action?t.play():Promise.resolve(t.pause()))),{affected:s.length}}let as=[],ao=new Map,al=!1;function ad(e){for(let t of e)URL.revokeObjectURL(t),ao.delete(t)}function au(){for(let e of as.splice(0))ad(e)}async function ac(e){var t;if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let r=await (t=e.src,new Promise((e,r)=>{let n=new Image;n.onload=()=>e(n),n.onerror=()=>r(Error(`failed to load image: ${t}`)),n.src=t})),n=document.createElement("canvas"),a=e.compressedWidth??r.naturalWidth??r.width,i=e.compressedHeight??r.naturalHeight??r.height;n.width=a,n.height=i;let s=n.getContext("2d");if(!s)throw Error("canvas 2d context is not available");return s.drawImage(r,0,0,a,i),{tempFilePath:n.toDataURL("image/jpeg",Math.min(100,Math.max(0,e.quality??80))/100)}}let ap={enableHighAccuracy:!0,maximumAge:0,timeout:1e4};function ah(){return{browserAuthorization:"unknown",message:"未配置",tone:"muted",userAuthorization:"unknown"}}function am(e){let{longitude:t,latitude:r}=e;if(!Number.isFinite(t)||!Number.isFinite(r)||t<-180||t>180||r<-90||r>90)throw Error("Invalid location coordinates")}let ag=new class{browserAuthorization="unknown";browserLocation;browserWatchId;locationListeners=new Set;locationUpdateRequests=new Map;manualLocation;pendingBrowserRequest;revision=0;snapshot=ah();snapshotListeners=new Set;updatesActive=!1;userAuthorization="unknown";watchRevision=0;getSnapshot=()=>this.snapshot;subscribe=e=>(this.snapshotListeners.add(e),()=>this.snapshotListeners.delete(e));subscribeLocation=e=>(this.locationListeners.add(e),()=>this.locationListeners.delete(e));isLocationScope(e){return"scope.userLocation"===e||"scope.userFuzzyLocation"===e||"scope.userLocationBackground"===e}updateUserAuthorization(e){this.userAuthorization=e?"granted":"denied",this.updateSnapshot({userAuthorization:this.userAuthorization}),!e&&this.locationUpdateRequests.size>0&&(this.stopLocationUpdates(),this.emitLocation({status:"user_unauthorized"}))}async requestLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ap;if("granted"!==this.userAuthorization)return{status:"user_unauthorized"};let t=this.getConfiguredLocation();return t||("denied"===this.browserAuthorization?this.createBrowserUnauthorizedResult():this.locateWithBrowser(e))}async requestLocationForHostDirective(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ap;return this.getConfiguredLocation()??this.locateWithBrowser(e)}async requestBrowserLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ap;return this.manualLocation=void 0,this.locateWithBrowser(e)}setManualLocation(e){am(e),this.revision+=1,this.pendingBrowserRequest=void 0,this.clearBrowserWatch(),this.manualLocation={...e,accuracy:0,source:"manual",speed:0,timestamp:Date.now()},this.browserAuthorization="granted",this.updateSnapshot({...e,browserAuthorization:"granted",errorMessage:void 0,message:"已配置(手动坐标)",source:"manual",tone:"success",updatedAtMs:Date.now()}),this.updatesActive&&this.emitLocation({location:this.manualLocation,status:"success"})}setConfigurationError(e){this.updateSnapshot({errorMessage:e,message:"定位失败",tone:"error",updatedAtMs:Date.now()})}async startLocationUpdates(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ap,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{signal:r,authorize:n}=t;if(null==r?void 0:r.aborted)throw new DOMException("Location updates were stopped","AbortError");this.releaseLocationUpdate(r);let a={active:!1,stop:()=>this.releaseLocationUpdate(r)};this.locationUpdateRequests.set(r,a),null==r||r.addEventListener("abort",a.stop,{once:!0});let i=()=>{if(this.locationUpdateRequests.get(r)!==a)throw new DOMException("Location updates were stopped","AbortError")};try{n&&await n(),i();let t=await this.requestLocation(e);i();let s="granted"===this.userAuthorization?this.getConfiguredLocation()??t:{status:"user_unauthorized"};if("success"!==s.status)return this.releaseLocationUpdate(r),this.emitLocation(s),s;return a.active=!0,this.updatesActive=!0,this.emitLocation(s),i(),this.manualLocation||"browser"!==s.location.source||void 0!==this.browserWatchId||this.startBrowserWatch(e),s}catch(e){throw this.locationUpdateRequests.get(r)===a&&this.releaseLocationUpdate(r),e}}stopLocationUpdates(){for(let e of this.locationUpdateRequests.keys())this.releaseLocationUpdate(e);this.updatesActive=!1,this.clearBrowserWatch()}releaseLocationUpdate(e){let t=this.locationUpdateRequests.get(e);t&&(this.locationUpdateRequests.delete(e),null==e||e.removeEventListener("abort",t.stop),this.updatesActive=[...this.locationUpdateRequests.values()].some(e=>e.active),this.updatesActive||this.clearBrowserWatch())}createBusinessLocationInfo(e){let t=function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}}();return{latitude:e.latitude,longitude:e.longitude,city:"",city_code:"",client_time_zone:t,country:"",country_code:"",district:"",impr_time:String(Math.floor(Date.now()/1e3)),province:"",region:"",time_zone:t,town:""}}reset(){this.revision+=1,this.stopLocationUpdates(),this.browserAuthorization="unknown",this.browserLocation=void 0,this.manualLocation=void 0,this.pendingBrowserRequest=void 0,this.userAuthorization="unknown",this.snapshot=ah(),this.emitSnapshot()}getConfiguredLocation(){return this.manualLocation?{location:{...this.manualLocation,timestamp:Date.now()},status:"success"}:"granted"===this.browserAuthorization&&this.browserLocation?{location:this.browserLocation,status:"success"}:void 0}locateWithBrowser(e){if(this.pendingBrowserRequest)return this.pendingBrowserRequest;let t=++this.revision;this.browserAuthorization="pending",this.updateSnapshot({browserAuthorization:"pending",errorMessage:void 0,latitude:void 0,longitude:void 0,message:"定位中...",source:void 0,tone:"pending",updatedAtMs:Date.now()});let r=this.getBrowserPosition(e).then(e=>{let r=this.toBrowserLocation(e);return t===this.revision&&(this.browserAuthorization="granted",this.browserLocation=r,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:r.latitude,longitude:r.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()})),{location:r,status:"success"}}).catch(e=>this.handleBrowserError(e,t)).finally(()=>{this.pendingBrowserRequest===r&&(this.pendingBrowserRequest=void 0)});return this.pendingBrowserRequest=r,r}getBrowserPosition(e){let t="u"<typeof navigator?void 0:navigator.geolocation;return t?new Promise((r,n)=>{t.getCurrentPosition(r,n,e)}):Promise.reject(Error("Geolocation is not available in the current browser"))}toBrowserLocation(e){return{...function(e,t){var r,n,a,i;if(am({latitude:t,longitude:e}),e<72.004||e>137.8347||t<.8293||t>55.8271)return{latitude:t,longitude:e};let s=-100+2*(r=e-105)+3*(n=t-35)+.2*n*n+.1*r*n+.2*Math.sqrt(Math.abs(r))+(20*Math.sin(6*r*Math.PI)+20*Math.sin(2*r*Math.PI))*2/3+(20*Math.sin(n*Math.PI)+40*Math.sin(n/3*Math.PI))*2/3+(160*Math.sin(n/12*Math.PI)+320*Math.sin(n*Math.PI/30))*2/3,o=300+(a=e-105)+2*(i=t-35)+.1*a*a+.1*a*i+.1*Math.sqrt(Math.abs(a))+(20*Math.sin(6*a*Math.PI)+20*Math.sin(2*a*Math.PI))*2/3+(20*Math.sin(a*Math.PI)+40*Math.sin(a/3*Math.PI))*2/3+(150*Math.sin(a/12*Math.PI)+300*Math.sin(a/30*Math.PI))*2/3,l=t/180*Math.PI,d=Math.sin(l),u=Math.sqrt(d=1-.006693421622965943*d*d);return{latitude:t+(s=180*s/(6335552.717000426/(d*u)*Math.PI)),longitude:e+(o=180*o/(6378245/u*Math.cos(l)*Math.PI))}}(e.coords.longitude,e.coords.latitude),accuracy:e.coords.accuracy??0,altitude:e.coords.altitude??void 0,altitudeAccuracy:e.coords.altitudeAccuracy??void 0,heading:e.coords.heading??void 0,source:"browser",speed:e.coords.speed??0,timestamp:e.timestamp||Date.now()}}handleBrowserError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.revision,r=e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0,n=1===r?"denied":"unknown",a=function(e){switch(e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0){case 1:return"浏览器定位权限被拒绝,请在浏览器设置中允许位置访问后重试";case 2:return"暂时无法获取浏览器位置,请检查设备定位服务后重试";case 3:return"获取浏览器位置超时,请重试";default:return e instanceof Error&&e.message.includes("not available")?"当前浏览器不支持定位,请手动配置坐标":"获取浏览器位置失败,请重试"}}(e);return console.error("Browser geolocation failed",e),t===this.revision&&(this.browserAuthorization=n,this.browserLocation=void 0,this.updateSnapshot({browserAuthorization:n,errorMessage:a,latitude:void 0,longitude:void 0,message:"定位失败",source:void 0,tone:"error",updatedAtMs:Date.now()})),{code:r,message:a,status:"browser_unauthorized"}}createBrowserUnauthorizedResult(){return{message:this.snapshot.errorMessage||"浏览器未授权定位,请在 Sandbox 面板配置位置",status:"browser_unauthorized"}}startBrowserWatch(e){this.clearBrowserWatch();let t=++this.watchRevision,r="u"<typeof navigator?void 0:navigator.geolocation;r?this.browserWatchId=r.watchPosition(e=>{if(t!==this.watchRevision||!this.updatesActive)return;let r=this.toBrowserLocation(e);this.browserAuthorization="granted",this.browserLocation=r,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:r.latitude,longitude:r.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()}),this.emitLocation({location:r,status:"success"})},e=>{t===this.watchRevision&&this.updatesActive&&this.emitLocation(this.handleBrowserError(e))},e):this.emitLocation(this.handleBrowserError(Error("Geolocation is not available in the current browser")))}clearBrowserWatch(){if(this.watchRevision+=1,void 0===this.browserWatchId)return;let e="u"<typeof navigator?void 0:navigator.geolocation;null==e||e.clearWatch(this.browserWatchId),this.browserWatchId=void 0}updateSnapshot(e){this.snapshot={...this.snapshot,...e,browserAuthorization:this.browserAuthorization,userAuthorization:this.userAuthorization},this.emitSnapshot()}emitSnapshot(){for(let e of this.snapshotListeners)e()}emitLocation(e){for(let t of this.locationListeners)t(e)}},af=new Map,av={"scope.userLocation":{description:"将使用你的位置信息,用于提供定位及位置相关服务。",title:"申请获取你的位置信息"},"scope.userFuzzyLocation":{description:"将使用你的大致位置信息,用于提供位置相关服务。",title:"申请获取你的模糊位置信息"},"scope.userLocationBackground":{description:"将在应用插件进入后台后继续使用你的位置信息。",title:"申请获取你的后台位置信息"},"scope.record":{description:"将使用你的麦克风,用于录制音频内容或进行语音输入。",title:"申请获取你的麦克风权限"},"scope.bluetooth":{description:"将使用你的蓝牙,用于发现和连接附近设备。",title:"申请获取你的蓝牙权限"},"scope.camera":{description:"将使用你的相机,用于拍摄照片或视频。",title:"申请获取你的相机权限"},"scope.addPhoneContact":{description:"将使用你的通讯录,用于添加或更新联系人。",title:"申请获取你的通讯录读写权限"},"scope.addPhoneCalendar":{description:"将使用你的日历,用于添加或更新日程。",title:"申请获取你的日历读写权限"}};function ay(e,t){return`${e||"unknown-app"}:${t}`}function a_(e){return av[e]??{description:"需要获得你的授权后才能继续使用此功能。",title:`申请获取你的${e.replace(/^scope\./,"")||"相关"}权限`}}async function ab(e){var t;let{appId:r,appIcon:n,appName:a,presenter:i,scope:s,skipDialogIfDenied:o=!1}=e,l=r||"unknown-app",d=af.get(ay(l,s));if("granted"===d)return!0;if("denied"===d&&o)return!1;if(!i)return"denied"!==d;let u=await i({appId:l,appIcon:n,appName:a||"应用插件",scope:s,...a_(s)});return t=u?"granted":"denied",af.set(ay(l,s),t),u}let aw="location_api_not_implemented";function aS(e,t){return w(e,"user_unauthorized"===t.status?"user permission denied":t.message)}async function ax(e){let t=await ab({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.userLocation",skipDialogIfDenied:!0});return ag.updateUserAuthorization(t),t}let aI=new Set,ak=new WeakSet,aC=0;function aE(){return navigator.connection}function aN(){var e;let t,r=aE(),n=null==r?void 0:r.effectiveType;return{isConnected:!1!==navigator.onLine,networkType:(t=null==(e=aE())?void 0:e.effectiveType,!1===navigator.onLine?"none":"slow-2g"===t||"2g"===t?"2g":"3g"===t||"4g"===t?t:"unknown"),signalStrength:null==r?void 0:r.downlink,hasSystemProxy:!1,weakNet:"slow-2g"===n||"2g"===n}}function aM(){return{timestamp:performance.now()/1e3,wallTime:Date.now()/1e3}}function aT(e){for(let t of aI)try{t(e)}catch(e){console.error("Failed to record doubao.request in Chrome DevTools",e)}}function aR(){let e=aN();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}async function aA(e,t,r){let n=await ab({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:t,skipDialogIfDenied:r});return ag.isLocationScope(t)&&ag.updateUserAuthorization(n),n}let aP="app_id_missing",aj="cashier_unavailable",aL="create_order_failed",aD="developer_order_exists",aO="login_credential_invalid",aU="login_credential_missing",aq="login_authorization_failed",a$="login_authorization_unsupported",aB="login_state_invalid",aF="login_session_unavailable",aW="payment_amount_invalid",aH="payment_authorization_invalid",az="payment_cancelled",aV="payment_data_invalid",aG="payment_data_missing",aJ="payment_data_unavailable",aK="payment_data_unavailable_with_sign",aX="payment_data_unsupported",aZ="payment_failed",aQ="payment_method_unavailable",aY="payment_order_invalid",a0="payment_parameter_missing",a1="payment_params_invalid",a2="payment_params_unavailable",a3="payment_sign_params_invalid",a4="payment_sign_params_unavailable",a5="payment_incomplete",a6="privacy_state_unavailable",a8="privacy_authorization_failed",a7="pre_order_failed",a9="phone_authorization_failed",ie="request_format_invalid",it="request_params_invalid",ir="sandbox_resource_not_found",ia="sandbox_service_unavailable",ii="sandbox_session_expired",is="sandbox_session_forbidden",io="sign_order_failed",il="sign_order_already_exists",id="sign_order_not_found",iu="sign_order_params_invalid",ic="sign_order_status_invalid",ip="sign_order_create_failed",ih="sign_page_params_invalid",im="sign_page_unavailable",ig="sign_page_data_unavailable",iv="请求暂时无法完成,请稍后重试;如持续失败,请提供 log_id";function iy(e,t){return!t||e.includes(t)?e:`${e}(log_id: ${t})`}class i_ extends Error{code;details;logId;constructor(e,t={},r){super(iI(e,t,r)),this.code=e,this.details=t,this.logId=r,this.name="SandboxError"}}class ib extends Error{remoteCode;options;constructor(e,t,r={}){super(t),this.remoteCode=e,this.options=r,this.name="SandboxRemoteError"}}let iw={[aP]:"当前未配置应用 ID,请先完成应用配置。",[aj]:"无法打开模拟器收银台,请刷新模拟器后重试。",[aL]:"暂时无法创建订单,请检查签名参数后稍后重试;如持续失败,请提供 log_id",[aD]:"开发者订单号已存在,请查询原订单",[aO]:"登录失败:登录凭证已过期或已使用,请重新发起登录。",[aU]:"登录失败:成功登录回调未携带业务登录凭证,请检查登录实现。",[aq]:"暂时无法完成登录授权,请重新发起授权",[a$]:"当前 Sandbox 无法完成该授权请求,请检查授权方式和会话配置",[aB]:"用户登录状态已失效,请重新登录",[aF]:"登录失败:模拟器会话不可用,请登录开发者账号后重新打开模拟器。",[aW]:"支付金额无效,请使用最小货币单位的整数,并由业务服务端生成金额。",[aH]:"支付授权校验失败,请确认 data 和 dbAuthorization 使用同一个 dev.key 生成,并且模拟器配置了匹配的 dev.csr。",[az]:"已取消支付。",[aV]:"支付数据格式无效,请检查业务服务端生成的 pay_data。",[aJ]:"无法打开收银台:模拟器未返回支付数据,请检查订单状态和预下单响应。",[aK]:"无法打开支付签约收银台:模拟器未返回支付数据,请检查签约参数和订单状态。",[aX]:"当前支付数据不支持模拟器收银台,请检查模拟器支付配置。",[aZ]:iv,[aQ]:"支付数据中没有可用的支付方式,请检查模拟器支付配置。",[aY]:"订单不存在或不属于当前应用",[a1]:"请求参数不正确,请检查订单信息和金额",[a2]:"暂时无法获取支付参数,请检查订单号后重试;如持续失败,请提供 log_id",[a3]:"请求参数不正确,请检查订单号和签约信息",[a4]:"暂时无法获取支付参数,请稍后重试;如持续失败,请提供 log_id",[a5]:"模拟支付未完成,请检查支付方式和订单状态后重试;如持续失败,请提供 log_id",[a6]:"暂时无法读取或保存授权状态,请稍后重试",[a8]:"隐私授权失败:请刷新模拟器后重试。",[a7]:"预下单失败:模拟器未返回订单 ID,请检查业务服务端预下单响应。",[a9]:"手机号授权失败:无法获取手机号授权凭证,请重试或使用其他登录方式。",[ie]:"请求格式不正确,请检查后重试",[it]:"请求参数不正确,请检查必填字段和字段格式",[ir]:"未找到沙箱会话或相关资源,请重新创建后重试",[ia]:"沙箱服务暂时不可用,请稍后重试;如持续失败,请提供 log_id",[ii]:"沙箱会话已过期,请重新启动调试会话",[is]:"当前沙箱会话无权访问该应用,请检查应用和会话是否匹配",[io]:"创建签约订单失败:模拟器未返回签约订单 ID,请检查签约参数。",[il]:"开发者签约单号已存在,请查询原签约单",[id]:"签约单不存在或不属于当前应用",[iu]:"签约单参数无效,请检查单号、应用和有效期",[ic]:"当前签约单状态不允许继续签约",[ip]:"暂时无法创建签约单,请检查签名参数后重试;如持续失败,请提供 log_id",[ih]:"签约单参数无效,请检查单号、应用和有效期",[im]:"暂时无法获取签约页,请稍后重试;如持续失败,请提供 log_id",[ig]:"打开签约页面失败:模拟器未返回签约数据,请检查签约订单状态。"},iS={id:"支付方式 ID",name:"支付方式名称",pay_order_no:"支付订单号",pay_status:"支付状态",trade_no:"交易号"},ix={data:"业务服务端生成的 data",dbAuthorization:"业务服务端生成的 dbAuthorization",orderId:"requestOrder 返回的 orderId",signData:"业务服务端生成的 signData",signDbAuthorization:"业务服务端生成的 signDbAuthorization"};function iI(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return iy(function(e,t){if(e===aG){let e=t.field?iS[t.field]:"必要字段";return`支付数据缺少${e},请检查业务服务端生成的 pay_data。`}if(e===a0){let e=t.key?ix[t.key]:"该参数";return`缺少支付参数,请提供${e}。`}return iw[e]}(e,t),r)}function ik(e){if("number"==typeof e&&Number.isInteger(e))return e;if("string"==typeof e&&e.trim()){let t=Number(e);return Number.isInteger(t)?t:void 0}}let iC={400:it,401:ii,403:is,404:ir,500:ia};function iE(e,t){return 400===t?ie:void 0===e?void 0:iC[e]}let iN={[aK]:a3,[io]:iu,[ig]:ih},iM={[a7]:aL,[aK]:a4,[io]:ip,[ig]:im};function iT(e,t,r){switch(e){case 500:return"payment"===r?a5:ia;case 4201:return aH;case 0x1dcd6501:return iN[t]??a1;case 0x1dcdb322:return aD;case 5e8:return iM[t]??a2;case 0x1dcdb325:return t===ig?id:aY;case 0x1dcdb327:return il;case 0x1dcdb328:return ic;default:return void 0===e||0===e?t:aZ}}let iR={[-1]:aF,4001:aO,2001:a8,502:aq,402:aB,501:a6,400:it};function iA(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("code"===r.errorField){let t=iE(e,r.httpStatus);if(t)return t}return"data.error_code"===r.errorField&&40001===e?a$:"err_code"===r.errorField&&401===e?it:1001===e?"phone"===t?a9:aO:void 0===e?ia:iR[e]??ia}function iP(e,t){return e instanceof i_?e:e instanceof ib?new i_(iA(e.remoteCode,t,e.options),{},e.options.logId):new i_(ia)}function ij(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:iv,r=arguments.length>2?arguments[2]:void 0;if(e instanceof i_)return iI(e.code,e.details,e.logId??r);if(e instanceof ib){let t="code"===e.options.errorField?iE(e.remoteCode,e.options.httpStatus):void 0,n=iT(e.remoteCode,aZ,e.options.operation);return iI(e.options.operation?n:t??n,{},e.options.logId??r)}return iy(t,r)}function iL(e,t){let r=e.err_code;if(r)throw new i_(iA(r,t,{errorField:"err_code"}),{},e.log_id)}function iD(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:{code:ik(e.code),logId:"string"==typeof e.log_id?e.log_id:void 0}}function iO(e,t){let{code:r,logId:n}=iD(e);if(r)throw new ib(r,`Sandbox 请求失败,错误码为 ${String(r)}。`,{errorField:"code",httpStatus:t,logId:n})}let iU="web-sdk-debugger",iq=[{id:"douyin",name:"抖音支付"}];async function i$(e){let t=await fetch("/__web_sdk_sandbox_proxy__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({})),{code:n,logId:a}=iD(r);if(!t.ok)throw new ib(n,`Sandbox 代理请求失败,HTTP 状态码为 ${t.status}。`,{errorField:"code",httpStatus:t.status,logId:a});return iO(r,t.status),r}let iB=new class{request=()=>{throw Error("FlowAppDeveloperOpenGatewayService.request is undefined")};baseURL="";constructor(e){this.request=(null==e?void 0:e.request)||this.request,this.baseURL=(null==e?void 0:e.baseURL)||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}FetchPackageDownLoadInfo(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/packet`);return this.request({url:r,method:"POST"},t)}GetArtifactStatus(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/artifact`);return this.request({url:r,method:"POST"},t)}GetUserBasicInfo(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/user/basic"),a={user_name:r.user_name,user_id:r.user_id};return this.request({url:n,method:"GET",params:a},t)}GetConfigRoleList(e,t){let r=this.genBaseURL("/app_developer/api/config/role/role_list");return this.request({url:r,method:"GET"},t)}RoleListByAppid(e,t){let r=this.genBaseURL("/app_developer/api/user/role/role_list");return this.request({url:r,method:"GET"},t)}UpdateUserName(e,t){let r=this.genBaseURL("/app_developer/api/user/basic/update_user_name"),n={user_name:e.user_name};return this.request({url:r,method:"PUT",data:n},t)}GetInviteMemberList(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/member/member_list"),a={app_key:r.app_key,user_name:r.user_name,page_size:r.page_size,page_num:r.page_num};return this.request({url:n,method:"GET",params:a},t)}SendInviteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/invite/send_invite`),n={role_code:e.role_code,target_user_id:e.target_user_id};return this.request({url:r,method:"POST",data:n},t)}UpdateAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta/update`),n={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:n},t)}SubmitRelease(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/release`);return this.request({url:r,method:"POST"},t)}ActivateDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/activate"),n={user_code:e.user_code,client_name:e.client_name};return this.request({url:r,method:"POST",data:n},t)}GetPlatformCert(e,t){let r=this.genBaseURL("/app_developer/api/platform/cert");return this.request({url:r,method:"GET"},t)}UploadCsr(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_csr`),n={csr_pem:e.csr_pem};return this.request({url:r,method:"POST",data:n},t)}GetAppCert(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/cert`);return this.request({url:r,method:"GET"},t)}CreateApp(e,t){let r=this.genBaseURL("/app_developer/api/apps"),n={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:n},t)}UploadIcon(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_icon`);return this.request({url:r,method:"POST"},t)}SubmitAudit(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/submit_audit`);return this.request({url:r,method:"POST"},t)}IssueDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/code"),n={client_name:e.client_name};return this.request({url:r,method:"POST",data:n},t)}GetAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),n={offset:e.offset,limit:e.limit,keyword:e.keyword};return this.request({url:r,method:"GET",params:n},t)}UpdateAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),n={action:e.action,subject:e.subject};return this.request({url:r,method:"POST",data:n},t)}ExchangeDeviceToken(e,t){let r=this.genBaseURL("/app_developer/oauth/token"),n={device_code:e.device_code};return this.request({url:r,method:"POST",data:n},t)}ListApps(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/apps"),a={app_limit:r.app_limit,app_offset:r.app_offset,key_word:r.key_word,app_key:r.app_key};return this.request({url:n,method:"GET",params:a},t)}GetAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta`),n={limit:e.limit,offset:e.offset,status:e.status};return this.request({url:r,method:"GET",params:n},t)}ToolList(e,t){let r=this.genBaseURL("/developer/api/tools/list"),n={mcp_server_url:e.mcp_server_url,mcp_config:e.mcp_config};return this.request({url:r,method:"GET",params:n},t)}GetMiniAppVersionArtifact(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/artifact`);return this.request({url:r,method:"GET"},t)}UploadMiniAppVersionDraftPackage(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/upload`),n={source_type:e.source_type};return this.request({url:r,method:"POST",params:n},t)}SubmitMiniAppVersionDraft(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/submit`),n={project_config_version:e.project_config_version,app_version_tag:e.app_version_tag};return this.request({url:r,method:"POST",data:n},t)}ListMiniAppVersions(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions`),n={page:e.page,page_size:e.page_size,id:e.id};return this.request({url:r,method:"GET",params:n},t)}VerifyYAML(e,t){let r=this.genBaseURL("/app_developer/api/yaml/verify"),n={yaml:e.yaml,mode:e.mode,yaml_type:e.yaml_type};return this.request({url:r,method:"POST",data:n},t)}GetMiniAppVersionYAML(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest`);return this.request({url:r,method:"GET"},t)}GetMiniAppVersionStructuredManifest(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest_struct`);return this.request({url:r,method:"GET"},t)}QrcodeInfo(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_info"),n={app_key:e.app_key};return this.request({url:r,method:"POST",data:n},t)}GetMiniAppVersionDraftPackageDownloadURL(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/download_url`),n={source_type_list:e.source_type_list};return this.request({url:r,method:"GET",params:n},t)}GetSubMerchantList(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_list"),n={org_id:e.org_id};return this.request({url:r,method:"GET",params:n},t)}AppBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/app_bind_sub_merchant`),n={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"PUT",data:n},t)}CreateSubMerchant(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/create_sub_merchant"),n={org_id:e.org_id,sub_merchant_name:e.sub_merchant_name};return this.request({url:r,method:"POST",data:n},t)}UnBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/unbind_sub_merchant`),n={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"POST",data:n},t)}GetSubMerchantCaijingUrl(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_url"),n={sub_merchant_uid:e.sub_merchant_uid};return this.request({url:r,method:"POST",data:n},t)}GetAppBindSubMerchants(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/get_bind_sub_merchants`);return this.request({url:r,method:"GET"},t)}GetAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/get_callback_conf`),n={source:e.source};return this.request({url:r,method:"GET",params:n},t)}UpdateAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/update_callback_conf`),n={source:e.source,callback_address:e.callback_address};return this.request({url:r,method:"PUT",data:n},t)}CreateOrganization(e,t){let r=this.genBaseURL("/app_developer/api/organization"),n={name:e.name};return this.request({url:r,method:"POST",data:n},t)}UpdateOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/update`),n={name:e.name};return this.request({url:r,method:"POST",data:n},t)}FinishMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/finish`),n={upload_token:e.upload_token,size:e.size,sha256:e.sha256};return this.request({url:r,method:"POST",data:n},t)}DeleteOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/delete`);return this.request({url:r,method:"POST"},t)}GetOrganizationToken(e,t){let r=this.genBaseURL("/app_developer/api/organization/get_token"),n={org_code:e.org_code};return this.request({url:r,method:"POST",data:n},t)}StartMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/start`),n={sha256:e.sha256};return this.request({url:r,method:"POST",data:n},t)}ListOrganizations(e,t){let r=this.genBaseURL("/app_developer/api/organizations/list");return this.request({url:r,method:"GET"},t)}CreateAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_create`),n={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}DeleteAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/delete`),n={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}VerifyAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_verify`),n={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}CreateAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/create`),n={domain:e.domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}GetAppDomainList(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/list`);return this.request({url:r,method:"GET"},t)}SandboxGetAwemeCommonLoginInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/auth/get_aweme_common_login_info"),n={app_key:e.app_key};return this.request({url:r,method:"POST",data:n},t)}SandboxUpdateMessageCardWidgetData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/update_message_card_widget_data"),n={mixture_card_id:e.mixture_card_id,message_id:e.message_id,widget_id:e.widget_id,widget_data:e.widget_data};return this.request({url:r,method:"POST",data:n},t)}SandboxCreateSignOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/create_sign_order"),n={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:n},t)}SandboxGetOrderPaymentWithSign(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment_with_sign"),n={order_id:e.order_id,sign_data:e.sign_data,sign_db_authorization:e.sign_db_authorization,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:n},t)}SandboxRequestOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/request_order"),n={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:n},t)}SandboxGetSignPageData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_sign_page_data"),n={auth_order_id:e.auth_order_id,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:n},t)}SandboxGetMessageInfoByMixtureCardID(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/get_message_info_by_mixture_card_id"),n={mixture_card_id:e.mixture_card_id};return this.request({url:r,method:"POST",data:n},t)}SandboxGetOrderPayment(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment"),n={order_id:e.order_id,app_key:e.app_key,platform_signed_pt_code:e.platform_signed_pt_code,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:n},t)}SandboxApiGetUserAppsPermissionDetail(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/detail"),n={applets_list:e.applets_list};return this.request({url:r,method:"POST",data:n},t)}SandboxApiPostUserAppsPermission(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/post"),n={applet_id:e.applet_id,update_scope_info:e.update_scope_info,using_scope_infos:e.using_scope_infos};return this.request({url:r,method:"POST",data:n},t)}SandboxApiGetUserAppsPermissionRecord(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/record"),n={applet_id:e.applet_id};return this.request({url:r,method:"POST",data:n},t)}SandboxApiExchangeCode(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/jsb/oauth/token"),a={app_key:r.app_key,code:r.code,device_id:r.device_id,version_tag:r.version_tag};return this.request({url:n,method:"POST",data:a},t)}SandboxApiGetPhoneMask(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/phone_mask");return this.request({url:r,method:"POST"},t)}SandboxApiCheckPrivacyOrLoginStatus(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy_login/check"),a={app_key:r.app_key,version_tag:r.version_tag,check_type:r.check_type};return this.request({url:n,method:"POST",data:a},t)}SandboxApiAcceptPrivacy(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy/accept"),a={app_key:r.app_key,request_id:r.request_id,device_id:r.device_id};return this.request({url:n,method:"POST",data:a},t)}SandboxApiDeleteDataObtainedByTicket(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/ticket_revoke"),n={applet_id:e.applet_id,scope_name:e.scope_name,permission_ticket_type:e.permission_ticket_type};return this.request({url:r,method:"POST",data:n},t)}ListPublicNoticeTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates`),n={category:e.category,subscription_type:e.subscription_type,keyword:e.keyword,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:n},t)}SandboxIssueLoginCode(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/passport/open/auth"),n={client_key:e.client_key,aid:e.aid,scope:e.scope,source:e.source,exchange_type:e.exchange_type};return this.request({url:r,method:"POST",data:n},t)}GetSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/get"),n={sandbox_session_id:e.sandbox_session_id};return this.request({url:r,method:"POST",data:n},t)}UpdateSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/update"),n={sandbox_session_id:e.sandbox_session_id,phone_num:e.phone_num,csr_pem:e.csr_pem,location_info:e.location_info};return this.request({url:r,method:"POST",data:n},t)}SandboxPay(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/payment/pay"),n={trade_no:e.trade_no,pay_type:e.pay_type};return this.request({url:r,method:"POST",data:n},t)}CheckDeveloperAccessWhitelist(e,t){let r=this.genBaseURL("/app_developer/api/user/whitelist/check"),n={invite_code:(e||{}).invite_code};return this.request({url:r,method:"POST",data:n},t)}OIDCGet(e,t){let r=this.genBaseURL("/app_developer/api/oidc_get");return this.request({url:r,method:"GET"},t)}OIDCCallback(e,t){let r=this.genBaseURL("/app_developer/api/oidc_callback"),n={code:e.code,nonce:e.nonce,state:e.state};return this.request({url:r,method:"GET",params:n},t)}AuditDetail(e,t){let r=this.genBaseURL("/app_developer/api/apps/audit/detail"),n={audit_id:e.audit_id,audit_type:e.audit_type};return this.request({url:r,method:"POST",data:n},t)}ListBusinessTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates`),n={biz_type:e.biz_type,status:e.status,sync_status:e.sync_status,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:n},t)}GetBusinessTemplatesYaml(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/yaml`),n={status:e.status};return this.request({url:r,method:"GET",params:n},t)}DeleteBusinessTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/${e.biz_type}/${e.template_key}/delete`);return this.request({url:r,method:"POST"},t)}GetPublicNoticeTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates/${e.public_template_key}`);return this.request({url:r,method:"GET"},t)}PullSandboxNotices(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/resources/notices/pull"),a={notice_ids:r.notice_ids,cursor:r.cursor,limit:r.limit};return this.request({url:n,method:"POST",data:a},t)}RemoveSandboxTaskFromUser(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/remove_from_user"),n={task_id:e.task_id};return this.request({url:r,method:"POST",data:n},t)}PullSandboxTasks(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/pull"),a={task_ids:r.task_ids,cursor:r.cursor,limit:r.limit};return this.request({url:n,method:"POST",data:a},t)}CreateSandboxSession(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/create"),n={sandbox_project_id:e.sandbox_project_id,app_id:e.app_id,bridge_origins:e.bridge_origins,manifest:e.manifest};return this.request({url:r,method:"POST",data:n},t)}PreviewTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/preview`),n={object_key:e.object_key};return this.request({url:r,method:"GET",params:n},t)}QrcodeShort(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_short"),n={url:e.url,ttl:e.ttl};return this.request({url:r,method:"POST",data:n},t)}GetQrcodeURL(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_url"),n={token:e.token};return this.request({url:r,method:"POST",data:n},t)}DownloadTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/download`),n={object_key:e.object_key};return this.request({url:r,method:"GET",params:n},t)}SandboxCallMcpTool(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/call_mcp_tool"),n={tool_name:e.tool_name,tool_args_json:e.tool_args_json,widget_instance_id:e.widget_instance_id,artifact_version_code:e.artifact_version_code,app_key:e.app_key,widget_id:e.widget_id,scene:e.scene,skip_widget_update:e.skip_widget_update};return this.request({url:r,method:"POST",data:n},t)}DeleteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/delete`),n={user_id:e.user_id};return this.request({url:r,method:"POST",data:n},t)}SubmitSandboxEventReport(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/bridge/events/report"),n={event_id:e.event_id,data:e.data},a={"X-DBX-Sandbox-Session-ID":e["X-DBX-Sandbox-Session-ID"]};return this.request({url:r,method:"POST",data:n,headers:a},t)}UploadSimulatorImage(e,t){let r=this.genBaseURL("/app_developer/api/simulator/images/upload"),n={image:e.image};return this.request({url:r,method:"POST",data:n},t)}}({baseURL:"",request:i$});function iF(e,t){if(!e.data)throw Error(e.message||`${t} returned empty data`);return e.data}async function iW(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return iF(await iB.PullSandboxNotices(e),"PullSandboxNotices")}async function iH(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return iF(await iB.PullSandboxTasks(e),"PullSandboxTasks")}async function iz(e){return iF(await iB.RemoveSandboxTaskFromUser({task_id:e}),"RemoveSandboxTaskFromUser").removed_task}async function iV(e,t){return i$({data:{event_id:e,data:t},method:"POST",url:"/app_developer/api/sandbox/bridge/events/report"})}async function iG(e){let{appletId:t,granted:r,scopeName:n}=e;if(!t.trim())throw Error("appletId is required");if(!n.trim())throw Error("scopeName is required");let a=await iB.SandboxApiPostUserAppsPermission({applet_id:t,update_scope_info:{grant_status:r?1:2,scope_name:n}});if(0!==a.err_code)throw Error(a.err_msg||`Sandbox post Agentic Service permission failed with code ${String(a.err_code)}`)}async function iJ(e){let{appKey:t,params:r,scene:n}=e;if(!t.trim())throw Error("callTool requires a simulator app context");if("widget"===n&&(!e.widgetId.trim()||!e.widgetInstanceId.trim()))throw Error("callTool requires a simulator conversation card context");let{skipWidgetUpdate:a,toolArgs:i,toolName:s}=function(e){if(!tj(e)||"string"!=typeof e.toolName||!e.toolName.trim()||!tj(e.toolArgs)||void 0!==e.skipWidgetUpdate&&"boolean"!=typeof e.skipWidgetUpdate)throw Error("callTool requires a non-empty toolName, an object toolArgs, and an optional boolean skipWidgetUpdate");return{skipWidgetUpdate:e.skipWidgetUpdate??!1,toolName:e.toolName.trim(),toolArgs:e.toolArgs}}(r),o=await iB.SandboxCallMcpTool({app_key:t,scene:"page"===n?2:1,skip_widget_update:a,tool_args_json:JSON.stringify(i),tool_name:s,..."widget"===n?{widget_id:e.widgetId,widget_instance_id:e.widgetInstanceId}:{}}),l=ik(o.err_code);if(void 0!==l&&0!==l)throw new ib(l,o.err_msg||`callTool failed with code ${l}`,{errorField:"err_code",logId:o.log_id});if(!o.result)throw Error(o.err_msg||"callTool returned an empty result");if(1!==o.result.output_kind&&2!==o.result.output_kind)throw Error("callTool returned an invalid output kind");let d=o.result.card_update_error,u=o.result.tool_error,c=o.result.tool_result_json,p=d?{cardUpdateError:{code:d.code,message:d.message,phase:"render"}}:{};if(u){let e=ik(u.code);if(void 0!==c||void 0===e||"string"!=typeof u.message||!u.message.trim())throw Error("callTool returned an invalid Tool error");return{toolError:{code:e,message:u.message},...p}}if(void 0===c)throw Error("callTool returned neither a Tool result nor a Tool error");return{toolResult:function(e){let t=JSON.parse(e);if(!tj(t))throw Error("callTool returned an invalid ToolResult");return t}(c),...p}}function iK(e){var t;let r=(null==(t=e.getAppId)?void 0:t.call(e))||e.appId;if(!r)throw new i_(aP);return r}function iX(e,t){var r;let n=null==e||null==(r=e[t])?void 0:r.trim();if(!n)throw new i_(a0,{key:t});return n}function iZ(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments.length>4?arguments[4]:void 0,i=ik(t.err_code),s=a?(a instanceof ib?a.remoteCode:void 0)??(void 0!==i&&0!==i?i:void 0)??-1:i??-1,o=(a instanceof ib?a.options.logId:void 0)??t.log_id,l=a?ij(a,iI(r),o):iI(iT(i,r),{},o),d={code:n?s:void 0,errNo:String(s),errMsg:l,errLogId:o};return{type:"callback",callbackId:e.callbackId,params:{code:0,data:d,errNo:s,errMsg:l,msg:l}}}async function iQ(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return await t()}catch(t){return iZ(e,{},aZ,r,t)}}async function iY(e,t){let r=function(e){let t;try{t=JSON.parse(e)}catch{throw new i_(aV)}if(!t||"object"!=typeof t||Array.isArray(t))throw new i_(aV);let r=t;if("sandbox_cashier"!==r.type)throw new i_(aX);let n="string"==typeof r.total_amount?r.total_amount.trim():"";if(!n||!/^\d+$/.test(n))throw new i_(aW);let a="string"==typeof r.pay_order_no?r.pay_order_no.trim():"",i="string"==typeof r.pay_status?r.pay_status.trim():"",s="string"==typeof r.trade_no?r.trade_no.trim():"";if(!a||!i||!s)throw new i_(aG,{field:a?i?"trade_no":"pay_status":"pay_order_no"});return{paymentTypes:function(e){if(!Array.isArray(e)||0===e.length)throw new i_(aQ);let t=e.map(e=>{if(!tj(e))throw new i_(aV);let t="string"==typeof e.id?e.id.trim():"",r="string"==typeof e.name?e.name.trim():"";if(!t||!r)throw new i_(aG,{field:t?"name":"id"});return{id:t,name:r}});if(new Set(t.map(e=>{let{id:t}=e;return t})).size!==t.length)throw new i_(aV);return t}(r.pay_types??iq),payOrderNo:a,payStatus:i,totalAmount:n,tradeNo:s,type:"sandbox_cashier"}}(e);if(!t.showSandboxCashier)throw new i_(aj);if(!await t.showSandboxCashier(r,async e=>{if(!r.paymentTypes.some(t=>{let{id:r}=t;return r===e}))throw new i_(aQ);try{await iB.SandboxPay({trade_no:r.tradeNo,pay_type:e})}catch(e){if(e instanceof ib&&"code"===e.options.errorField&&500===e.remoteCode)throw new ib(e.remoteCode,e.message,{...e.options,operation:"payment"});throw e}}))throw new i_(az)}async function i0(e,t){let r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"user_info",a=t?"phone":"login";try{r=await iB.SandboxIssueLoginCode({aid:"482431",client_key:iK(e),scope:n,source:"jsb",exchange_type:t})}catch(e){throw iP(e,a)}var i,s,o=ik(null==(i=r.data)?void 0:i.error_code),l=iD(r).logId;if(o)throw new i_(iA(o,a,{errorField:"data.error_code"}),{},l);let d=null==(s=r.data)?void 0:s.code;if(!d)throw new i_(ia);return d}async function i1(e){try{let t=void 0!==e.locationInfo,r=await iB.UpdateSandboxBusinessInfo({csr_pem:e.csrPem||(t?"":void 0),location_info:e.locationInfo,phone_num:e.phoneNum,sandbox_session_id:""});return iO(r),r}catch(r){let e=r instanceof ib?r.options.logId:r&&"object"==typeof r&&"logId"in r&&"string"==typeof r.logId?r.logId:void 0,t=Error(iy(r instanceof Error?r.message:String(r),e));throw t.logId=e,t}}async function i2(e){return i1(e)}async function i3(e){return i1({csrPem:"",locationInfo:e,phoneNum:""})}async function i4(e){let t=await fetch("/__web_sdk_sandbox_session_recreate__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({}));if(!t.ok)throw Error((null==r?void 0:r.message)||`Sandbox session recreate failed with status ${t.status}`);return r}let i5=["aztec","codabar","code_39","code_93","code_128","data_matrix","ean_8","ean_13","itf","pdf417","qr_code","upc_a","upc_e"],i6={barCode:["codabar","code_39","code_93","code_128","ean_8","ean_13","itf","upc_a","upc_e"],datamatrix:["data_matrix"],pdf417:["pdf417"],qrCode:["qr_code"]};async function i8(e){let t=e.getSupportedFormats;return"function"==typeof t?new Set(await t()):null}function i7(e){var t,r;return{characterSet:"UTF-8",path:"",rawData:(t=e.rawValue,"function"!=typeof btoa||"u"<typeof TextEncoder?t:btoa(String.fromCharCode(...new TextEncoder().encode(t)))),result:e.rawValue,scanType:(r=e.format,i5.includes(r)?"pdf417"===r?"PDF_417":r.toUpperCase():"QR_CODE")}}async function i9(e,t){if("function"==typeof createImageBitmap){let r=await createImageBitmap(t);try{return e.detect(r)}finally{r.close()}}let r=new Image,n=URL.createObjectURL(t);try{return await new Promise((e,t)=>{r.onload=()=>e(),r.onerror=()=>t(Error("Failed to load selected image")),r.src=n}),e.detect(r)}finally{URL.revokeObjectURL(n)}}function se(e,t,r,n,a){return t()?Promise.resolve():new Promise((i,s)=>{let o=0,l=()=>{for(let t of(window.clearTimeout(o),r))e.removeEventListener(t,d);e.removeEventListener("error",u)},d=()=>{t()&&(l(),i())},u=()=>{l(),s(Error(a))};for(let t of(o=window.setTimeout(()=>{l(),s(Error(a))},n),r))e.addEventListener(t,d);e.addEventListener("error",u)})}async function st(e,t){e.srcObject=t,await se(e,()=>e.readyState>=HTMLMediaElement.HAVE_METADATA,["loadedmetadata"],3e3,"Camera stream started, but video metadata was not loaded"),await e.play(),await se(e,()=>e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA,["loadeddata","canplay","playing"],3e3,"Camera stream started, but no video frame was rendered")}async function sr(e,t){var r;let n,a=globalThis.BarcodeDetector;if(!a)throw Error("BarcodeDetector is not supported in this browser");let i=await i8(a),s=[...new Set((null==(r=e.scanType)?void 0:r.length)?e.scanType.flatMap(e=>i6[e]):i5)].filter(e=>!i||i.has(e));if(0===s.length)throw Error("Requested scanType is not supported in this browser");let o=new a({formats:s}),l=!1,d=!1,u=0,c=null,p=null,h=()=>{null==c||c.getTracks().forEach(e=>e.stop()),c=null,p&&(p.srcObject=null)},m=()=>{l||(l=!0,window.cancelAnimationFrame(u),h(),null==n||n.close())};try{return await new Promise((r,a)=>{let i=e=>{m(),e()},s=e=>{if(!l&&!d){if(!p||p.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){e&&(null==n||n.setMessage("摄像头画面还未准备好"));return}d=!0,o.detect(p).then(t=>{let a=t[0];a?i(()=>r(i7(a))):e&&(null==n||n.setMessage("未识别到二维码或条形码"))}).catch(t=>{e&&(null==n||n.setMessage(t instanceof Error?t.message:String(t)))}).finally(()=>{d=!1})}};n=t({allowImageUpload:!e.onlyFromCamera,onCancel:()=>i(()=>a(Error("scanCode canceled"))),onCapture:()=>s(!0),onFile:e=>{l||(null==n||n.setMessage("正在识别图片..."),i9(o,e).then(e=>{let t=e[0];t?i(()=>r(i7(t))):null==n||n.setMessage("未识别到二维码或条形码,请换一张图片重试")}).catch(e=>{null==n||n.setMessage(e instanceof Error?e.message:String(e))}))},onVideoReady:t=>{var r;if(!p&&!l){if(p=t,!(null==(r=navigator.mediaDevices)?void 0:r.getUserMedia))return e.onlyFromCamera?void i(()=>a(Error("Camera is not available in this browser"))):void(null==n||n.setMessage("无法使用摄像头,请从相册选择二维码或条形码图片"));navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:{ideal:"environment"}}}).then(e=>l?void e.getTracks().forEach(e=>e.stop()):(c=e,st(t,e))).then(()=>{if(l)return;let e=()=>{l||(s(!1),u=window.requestAnimationFrame(e))};e()}).catch(t=>{if(l)return;let r=t instanceof Error?t.message:String(t);if(h(),e.onlyFromCamera){null==n||n.setMessage(r),i(()=>a(t instanceof Error?t:Error(r)));return}null==n||n.setMessage(`无法使用摄像头,请从相册选择二维码或条形码图片:${r}`)})}}})})}catch(e){throw m(),e}}function sn(){throw Error("Simulator UI presenter is unavailable")}function sa(){return{hideLoading:sn,hideToast:sn,showActionSheet:async()=>sn(),showBottomSheet:async()=>sn(),showLoading:sn,showModal:async()=>sn(),showToast:sn}}let si="doubao-web-sdk-debugger-vibration-style",ss="doubao-web-sdk-debugger-screen-vibrating",so={heavy:4,light:1,medium:2},sl=0,sd=null;function su(e){e.classList.remove(ss),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-distance"),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-duration")}function sc(e,t,r){if(!("function"==typeof navigator.vibrate&&navigator.vibrate(e)&&function(){let e=navigator.maxTouchPoints??0;if(e<=0)return!1;let t=navigator.platform??"",r=navigator.userAgent??"";return/android|iphone|ipad|ipod|mobile/i.test(`${t} ${r}`)||/mac/i.test(t)&&e>1}())){let n;(function(){if(document.getElementById(si))return;let e=document.createElement("style");e.id=si,e.textContent=`
|
|
24
24
|
@keyframes doubao-web-sdk-debugger-screen-vibrate {
|
|
25
25
|
0%, 100% { transform: translate3d(0, 0, 0); }
|
|
26
26
|
12.5% { transform: translate3d(calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0, 0); }
|