@doubao-dev/cli 0.0.19 → 0.0.20
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/2514.js +8 -8
- package/dist/2932.js +1 -1
- package/dist/318.js +1 -1
- package/dist/3494.js +284 -0
- package/dist/{1122.js.LICENSE.txt → 3494.js.LICENSE.txt} +6 -0
- package/dist/4931.js +1 -1
- package/dist/7410.js +1 -1
- package/dist/{1664.js → 8713.js} +3 -3
- package/dist/@byted-doubao-apps/create.js +1 -1
- package/dist/@byted-doubao-apps/login.js +1 -1
- package/dist/@byted-doubao-apps/login~1.js +1 -1
- package/dist/@byted-doubao-apps/template-empty/README.md +0 -2
- package/dist/@byted-doubao-apps/template-empty/package.json +3 -3
- package/dist/@byted-doubao-apps/template-starter/README.md +1 -1
- package/dist/@byted-doubao-apps/template-starter/package.json +3 -3
- package/dist/@byted-hdt/cli.js +1 -1
- package/dist/@inquirer/select.js +1 -1
- package/dist/@lynx-js/web-core-canary.js +2 -13
- package/dist/@lynx-js/web-core-canary~1.js +2 -0
- package/dist/app.js +1 -1
- package/dist/assets/web-sdk-debugger/chrome-devtools/entrypoints/devtools_app/devtools_app.js +9 -7
- package/dist/assets/web-sdk-debugger/chrome-devtools/panels/wsd-debug/WsdDebug.js +9 -7
- package/dist/assets/web-sdk-debugger/chrome-devtools/panels/wsd-debug/WsdDebugMeta.js +79 -77
- package/dist/assets/web-sdk-debugger/index.html +1 -1
- package/dist/assets/web-sdk-debugger/static/css/index.9952f4197c.css +1 -0
- package/dist/assets/web-sdk-debugger/static/js/{741.ece428827e.js → 48.8c158322ee.js} +60 -67
- package/dist/assets/web-sdk-debugger/static/js/48.8c158322ee.js.LICENSE.txt +5 -0
- package/dist/assets/web-sdk-debugger/static/js/async/257.4d55bd5ce8.js +1 -0
- package/dist/assets/web-sdk-debugger/static/js/async/{web-core-template-loader-thread.f9f3ef68b1.js → web-core-template-loader-thread.20d5b2a451.js} +2 -2
- package/dist/assets/web-sdk-debugger/static/js/async/{web-core-worker-chunk.002a4f7b9d.js → web-core-worker-chunk.71b9323071.js} +1 -1
- package/dist/assets/web-sdk-debugger/static/js/index.e5bc5f1bbd.js +26 -0
- package/dist/assets/web-sdk-debugger/static/js/{lib-polyfill.8cf763c414.js → lib-polyfill.4f00df8f2a.js} +1 -1
- package/dist/assets/web-sdk-debugger/wsd/doubao-apps-api.template.js +0 -0
- package/dist/assets/web-sdk-debugger/wsd/doubao-apps-framework.template.js +0 -0
- package/dist/auth.js +1 -1
- package/dist/browser.js +1 -1
- package/dist/csstree.esm.js +12 -0
- package/dist/dbx-demo.js +1 -1
- package/dist/dbx.js +1 -1
- package/dist/demo-server.js +1 -1
- package/dist/dev-config.js +1 -1
- package/dist/dev-service-client.js +6 -6
- package/dist/dev-shell.js +1 -1
- package/dist/dev.js +7 -7
- package/dist/eval.js +1 -1
- package/dist/gen-explore.js +1 -1
- package/dist/gen-trajectory.js +1 -1
- package/dist/get.js +1 -1
- package/dist/init.js +2 -2
- package/dist/ink.js +1 -1
- package/dist/json-file.js +1 -1
- package/dist/login.js +1 -1
- package/dist/main.js +1 -1
- package/dist/manifest-mcp-config.js +1 -1
- package/dist/ora.js +1 -1
- package/dist/portal.js +1 -1
- package/dist/project-layout.js +1 -1
- package/dist/prompt.js +1 -1
- package/dist/prompts.js +1 -1
- package/dist/report.js +1 -1
- package/dist/run-registry.js +1 -1
- package/dist/run.js +1 -1
- package/dist/sandbox.js +1 -1
- package/dist/sdk.js +67 -133
- package/dist/sdk~1.js +67 -133
- package/dist/server.js +1 -1
- package/dist/shared.js +1 -1
- package/dist/simulator-client.js +1 -1
- package/dist/skill.js +1 -1
- package/dist/skills~1.js +1 -1
- package/dist/static/assets/web-view-proxy-page-client.js +1 -0
- package/dist/static/assets/web-view-proxy-service-worker.js +1 -0
- package/dist/status.js +1 -1
- package/dist/status~1.js +1 -1
- package/dist/stop.js +1 -1
- package/dist/update.js +1 -1
- package/dist/upgrade.js +1 -1
- package/dist/upload.js +1 -1
- package/dist/validate.js +1 -1
- package/dist/workspace.js +1 -1
- package/dist/yaml.js +1 -1
- package/package.json +2 -2
- package/skills/doubao-agentic-service-development/references/dev-debug.md +6 -6
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/01-/345/237/272/347/241/200.md +105 -25
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/02-/347/263/273/347/273/237.md +118 -6
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/06-/344/272/244/344/272/222.md +18 -8
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/quick-reference.md +3 -3
- package/skills/doubao-agentic-service-development/references/frontend/examples/page-widget-basics.md +2 -3
- package/skills/doubao-agentic-service-development/references/frontend/guides/component-development.md +2 -1
- package/skills/doubao-agentic-service-development/references/frontend/guides/debugger-mcp.md +7 -1
- package/skills/doubao-agentic-service-development/references/frontend/rules/dos-and-donts.md +4 -7
- package/skills/doubao-agentic-service-development/references/frontend-dev.md +0 -1
- package/skills/doubao-agentic-service-development/references/manifest-guide.md +5 -4
- package/skills/doubao-agentic-service-development/references/mcp-protocol.md +4 -3
- package/dist/1122.js +0 -277
- package/dist/assets/web-sdk-debugger/static/css/index.fe34ed7927.css +0 -1
- package/dist/assets/web-sdk-debugger/static/js/index.da81c37197.js +0 -26
- package/dist/push-page.js +0 -1
- package/dist/push-widget.js +0 -1
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
(()=>{"use strict";var e,t,r,n,a,s,i,o,l,d,u,c,p={75047(e,t,r){let n,a;r(15254);var s=r(63159);function i(e){return"object"==typeof e&&null!==e}function o(e){return i(e.web)&&"string"==typeof e.web.entry}function l(e){return"widgetId"in e?e.widgetId:e.id}function d(e){let t=new Map;for(let r of e)for(let e of function(e){let t=[l(e)];return"path"in e&&"string"==typeof e.path&&t.push(e.path),t.filter(Boolean)}(r))t.has(e)||t.set(e,r);return t}r(52205),r(40768),r(76235),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(14104),r(42949),r(18723);class u{raw;appEntry;pageEntries;pageEntryMap;widgetEntries;widgetEntryMap;constructor(e){this.raw=e,this.appEntry=function(e){var t;let r=(null==(t=e.applet.web)?void 0:t.appRuntimeEntry)??e.applet.appRuntimeEntry;return"string"==typeof r&&r?{entry:r}:null}(e),this.pageEntries=e.applet.pages.filter(o),this.pageEntryMap=d(this.pageEntries),this.widgetEntries=e.widgets.filter(o),this.widgetEntryMap=d(this.widgetEntries)}get appId(){return"string"==typeof this.raw.appId?this.raw.appId:void 0}get name(){return this.raw.applet.name}get iconSrc(){let e=this.raw.applet.icons;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"])}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]}getPageEntry(e){let t=e?this.pageEntryMap.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=e?this.widgetEntryMap.get(e):this.widgetEntries[0];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(!i(a))throw Error("Invalid Web manifest: expected a JSON object");return new u(a)}function p(e,t,r){var n;let a="item"in t?t.item:t,s="web"in a&&i(a.web)&&"string"==typeof a.web.entry?function(e){if(i(e.web)&&"string"==typeof e.web.entry)return e.web.entry;throw Error(`No Web entry configured for manifest entry: ${l(e)}`)}(a):a.entry,o=new URL(e,r??(null==(n=globalThis.location)?void 0:n.href)??"http://localhost/");return o.pathname.endsWith("/web/manifest.json")?o.pathname=o.pathname.slice(0,-17):o.pathname.endsWith("/base/manifest.json")?o.pathname=o.pathname.slice(0,-18):o.pathname=o.pathname.replace(/\/[^/]*$/,"/"),o.search="",o.hash="",new URL(s,o).toString()}function m(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function h(e){return new URL(e,m()).toString()}function g(e,t){if(!t)return e;let r=new URL(e,m());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class f{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 getManifestUrl(e){if(!this.resolveManifestUrl)throw Error("PackageManagerService requires resolveManifestUrl");return this.resolveManifestUrl({appId:e})}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=h(await this.getManifestUrl(e)),n=this.packages.get(r);if(n&&!t.forceReload)return n;let a=c(r,{fetcher:this.options.fetcher}).then(e=>({manifest:e,manifestUrl:r}));return a.catch(()=>{this.packages.get(r)===a&&this.packages.delete(r)}),this.packages.set(r,a),a}deletePackage(e){this.packages.delete(h(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}async resolvePage(e,t){let r=await this.loadPackage(e),n=r.manifest.getPageEntry(t);return{appId:r.manifest.appId,entry:n,iconSrc:r.manifest.iconSrc,name:r.manifest.name,resourceUrl:g(p(r.manifestUrl,n),this.resourceUrlVersion)}}async resolveWidget(e,t){let r=await this.loadPackage(e),n=r.manifest.getWidgetEntry(t);return{appId:r.manifest.appId,entry:n,iconSrc:r.manifest.iconSrc,appName:r.manifest.name,resourceUrl:g(p(r.manifestUrl,n),this.resourceUrlVersion)}}}let v=new f,y={mode:"inline"};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){return i(e)&&"call"===e.type&&"string"==typeof e.name&&"number"==typeof e.callbackId}function w(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function S(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 x(e){return e instanceof Error?e.message:String(e)}function I(e,t){return t instanceof _?S(e,t.message,t.errNo,t.errMsg):S(e,x(t))}function E(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!b(e))return;let n=t[e.name];if(!n)return S(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=>I(e,t));return t??S(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return I(e,t)}}function C(){return null==n?void 0:n.getPackageInfo()}function k(e){var t;let{screenWidth:r,statusBarHeight:n}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),a=Math.round(n)+4,s=Math.round(r)-12;return{bottom:a+36,height:36,left:s-84,right:s,top:a,width:84}}r(49678),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 N{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)}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 M(this,e)}fork(){let e=new N(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 M{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)}emit(e,t){return!!this.subscribedEventNames.has(e)&&(this.dispatch(e,t),!0)}destroy(){for(let e of this.subscribedEventNames)this.apiRegistry.releaseEventSource(e);this.subscribedEventNames.clear(),this.cleanupRegistry()}}let R=new N;function T(){return(navigator.language||"zh-CN").replace("-","_")}function A(){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 P(){return"u"<typeof DoubaoAppsSDKVersion?void 0:DoubaoAppsSDKVersion}function j(){return navigator.userAgentData}function D(){var e;let t=null==(e=j())?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 L(){var e,t;let r=null==(e=j())?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 O(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",n=(null==(e=j())?void 0:e.platform)??"",a=`${n} ${r} ${t}`,s=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)&&s>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 U(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:C();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function q(){var e,t,r,n,a;let s=Math.round((null==(n=window.visualViewport)?void 0:n.width)??window.innerWidth??0),i=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)??s),d=Math.round((null==(t=window.screen)?void 0:t.height)??i),u=Math.round((null==(r=window.visualViewport)?void 0:r.offsetTop)??0);return{pixelRatio:o,screenWidth:l,screenHeight:d,windowWidth:s,windowHeight:i,statusBarHeight:u,safeArea:{left:0,right:s,top:u,bottom:i,width:s,height:Math.max(0,i-u)},screenTop:u}}function $(){return O().platform}function B(){var e,t,r,n,a;let s=navigator.userAgent??"",i=$();return"android"===i?null==(e=/android\s+([\d.]+)/i.exec(s))?void 0:e[1]:"ios"===i?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(s))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===i?null==(a=/mac os x\s+([\d_]+)/i.exec(s))||null==(n=a[1])?void 0:n.replace(/_/g,"."):void 0}function F(){return{isConnected:!0,networkType:"unknown",hasSystemProxy:!1,weakNet:!1}}function W(){let e,t=O(),r=navigator.platform||$();return{abi:r,deviceAbi:r,benchmarkLevel:-1,brand:t.brand,model:function(){let e=navigator.userAgent??"",t=$();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?O().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||O().brand:D()}(),system:function(){let e=$(),t=B();if("android"===e)return t?`Android ${t}`:"Android";if("ios"===e)return t?`iOS ${t}`:"iOS";if("mac"===e)return t?`macOS ${t}`:"macOS";if("windows"===e)return"Windows";if("linux"===e)return"Linux";let r=L(),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 H(){let e=W(),t=q(),r=t.windowWidth>t.windowHeight;return{os:e.platform,osVersion:B(),deviceBrand:e.brand,deviceModel:e.model,deviceType:e.model,channel:"debug",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function z(){let e=q(),t=W();return{...e,brand:t.brand,model:t.model,language:T(),version:L(),system:t.system,platform:t.platform,SDKVersion:P(),theme:A(),benchmarkLevel:-1,enableDebug:!0,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait",abi:t.abi}}function V(){let e=q();return{bluetoothEnabled:!1,locationEnabled:!0,wifiEnabled:F().isConnected,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait"}}function G(){let e=F();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function K(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:C();return{SDKVersion:P(),enableDebug:!0,host:{appId:U(e).appId},language:T(),version:L(),theme:A()}}function J(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:C();return{miniProgram:{appId:U(e).appId,envVersion:"develop",version:(null==e?void 0:e.versionName)??""}}}function X(e){return null==e?void 0:e.packageInfo}function Q(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 Z(e,t){let r=t instanceof Error?t.message:String(t);return`${e} failed: ${r}`}async function Y(e){let t=Q("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw Error(Z("setClipboardData",e))}}async function ee(){let e=Q("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw Error(Z("getClipboardData",e))}throw Error("getClipboardData failed: clipboard did not return text")}function et(){return{pages:(null==n?void 0:n.getCurrentPages())??[]}}R.handlers,r(46455);let er="doubao-web-sdk:storage:";function en(e){return`${er}${e}`}function ea(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 es(e){if(ei(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function ei(e){return new TextEncoder().encode(e).byteLength}function eo(e){return Object.values(e).reduce((e,t)=>e+ei(t),0)}function el(e){if(e>0xa00000)throw new _("total storage size exceeded",1600002)}function ed(e){let t={};for(let r=0;r<e.length;r+=1){let n=e.key(r);(null==n?void 0:n.startsWith(er))&&(t[n.slice(er.length)]=e.getItem(n)??"")}return t}function eu(e,t){if(!i(e))return;let r=e[t];return"string"==typeof r&&r.length>0?r:void 0}function ec(e){if(!i(e)||!i(e.packageInfo))return;let{appId:t,iconSrc:r,name:n,versionName:a}=e.packageInfo;return{appId:"string"==typeof t?t:void 0,iconSrc:"string"==typeof r?r:void 0,name:"string"==typeof n?n:void 0,versionName:"string"==typeof a?a:void 0}}function ep(e){let t=ec(e),r=(null==t?void 0:t.appId)??eu(e,"appName")??"unknown-app",n=eu(e,"userId")??eu(e,"userID")??"anonymous";return`${encodeURIComponent(r)}:${encodeURIComponent(n)}`}function em(){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 eh(e){return`doubao-web-sdk:file-system:${encodeURIComponent(e)}`}function eg(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ep(e);return{fileSystemNamespace:n,fileSystemSnapshot:function(e){let t=localStorage.getItem(eh(e));if(!t)return em();try{let e=JSON.parse(t);if(i(e)&&i(e.entries))return e}catch{}return em()}(n),apiResults:(r=ec(e),(t??R).getSyncResults({apiRegistry:t,globalProps:e,packageInfo:r})),storageSnapshot:ed(localStorage),supportedAPIs:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:R;return e.getSupportedNames({apiRegistry:e})}(t)}}r(21301);let ef={"doubao.getClipboardData":async e=>w(e,{data:await ee()}),"doubao.setClipboardData":async e=>{let{data:t}=function(e){if(!i(e)||"string"!=typeof e.data)throw Error("data must be a string");return{data:e.data}}(e.params);return await Y(t),w(e,{})},"applet.subscribeEvent":(e,t)=>{let r=i(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.subscribe(r)}return w(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=i(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.unsubscribe(r)}return w(e,{})},"doubao.getCurrentPages":{handler:e=>w(e,et()),syncResult:et},"doubao.navigateTo":e=>{var t;return(t=e.params,null==n||n.navigateTo(t),n)?w(e,{}):S(e,"No active Runtime to navigate")},"doubao.redirectTo":e=>{var t;return(t=e.params,null==n||n.redirectTo(t),n)?w(e,{}):S(e,"No active Runtime to redirect")},"doubao.reLaunch":e=>{var t;return(t=e.params,null==n||n.reLaunch(t),n)?w(e,{}):S(e,"No active Runtime to relaunch")},"doubao.navigateBack":e=>{var t;return(t=e.params??{},null==n||n.navigateBack(t),n)?w(e,{}):S(e,"No active Runtime to navigate back")},"doubao.exitApp":e=>(null==n||n.exitApp(),n)?w(e,{}):S(e,"No active Runtime to exit app"),"doubao.close":e=>{var t;return(t=e.params??{},null==n||n.close(t),n)?w(e,{}):S(e,"No active Runtime to close page")},"doubao.setStorage":e=>{var t;let r,n,{key:a,data:s}=e.params,i=(t=ed(localStorage),r=ea(a),es(s),n=Object.prototype.hasOwnProperty.call(t,r)?t[r]:void 0,el(eo(t)-(void 0===n?0:ei(n))+ei(s)),r);return localStorage.setItem(en(i),s),w(e,{})},"doubao.getStorage":e=>{let{key:t}=e.params;return w(e,{data:ed(localStorage)[ea(t)]})},"doubao.removeStorage":e=>{let{key:t}=e.params,r=ea(t);return localStorage.removeItem(en(r)),w(e,{})},"doubao.clearStorage":e=>{for(let e of Object.keys(ed(localStorage)))localStorage.removeItem(en(e));return w(e,{})},"doubao.getStorageInfo":e=>{var t;return w(e,{keys:Object.keys(t=ed(localStorage)),currentSize:Math.ceil(eo(t)/1024),limitSize:10240})},"doubao.__webSyncBridgePersist":(e,t)=>{var r,n,a;let s=i(r=e.params)&&i(r.storageSnapshot)?r.storageSnapshot:void 0,o=i(n=e.params)&&"string"==typeof n.fileSystemNamespace?n.fileSystemNamespace:void 0,l=null==t?void 0:t.fileSystemNamespace,d=i(a=e.params)&&i(a.fileSystemSnapshot)?a.fileSystemSnapshot:void 0;return s&&function(e){let t=[];for(let[t,r]of Object.entries(e))ea(t),es(r);el(eo(e));for(let e=0;e<localStorage.length;e+=1){let r=localStorage.key(e);(null==r?void 0:r.startsWith(er))&&t.push(r)}for(let e of t)localStorage.removeItem(e);for(let[t,r]of Object.entries(e))localStorage.setItem(en(t),r)}(s),l&&o===l&&d&&localStorage.setItem(eh(l),JSON.stringify(d)),w(e,{})},"doubao.authorize":{handler:e=>w(e,{}),syncResult:{}},"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return w(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:R;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:e=>w(e,J()),syncResult:e=>J(X(e))},"doubao.getPackageInfo":{handler:e=>w(e,U()),syncResult:e=>U(X(e))},"doubao.getAppBaseInfo":{handler:e=>w(e,K()),syncResult:e=>K(X(e))},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>w(e,k(null==t?void 0:t.globalProps)),syncResult:e=>k(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:e=>w(e,z()),syncResult:z},"doubao.getSystemSetting":{handler:e=>w(e,V()),syncResult:V},"doubao.getWindowInfo":{handler:e=>w(e,q()),syncResult:q},"doubao.getDeviceInfo":{handler:e=>w(e,W()),syncResult:W},"doubao.getNetworkType":{handler:e=>w(e,G()),syncResult:G}};function ev(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.apiRegistry??R;return(r,n,a)=>{if(("AppletJSModule"!==a||"log"!==r)&&"AppletBridgeModule"===a&&"postMessage"===r)return E(n,t.handlers,{...e,apiRegistry:t})}}function ey(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function e_(e){return e.containerType??"PAGE"}function eb(e){return"WIDGET"===e?"content":"fill"}function ew(){return"0.0.42-rc.5"}function eS(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}R.registerMany(ef,{override:!0}),R.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 ex{container;options;sandboxUrl;targetOrigin;bridgeEvents=null;connected=!1;failed=!1;handshakeTimer=null;loadCount=0;port=null;renderMessage=null;view=null;constructor(e,t){const r=new URL(t);if("https:"!==r.protocol&&!("http:"===r.protocol&&function(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}(r.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.container=e.container,this.options=e,this.sandboxUrl=r.href,this.targetOrigin=r.origin}get element(){return this.view}render(e){var t;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"));let r=e_(e),n=new URL(ey(e),document.baseURI).href,a=e.initData??{},s={...H(),...e.globalProps??{}},i=eg(s,this.options.apiRegistry,this.options.fileSystemNamespace);this.renderMessage={type:"render",resourceUrl:n,containerType:r,initData:a,globalProps:s,syncBridgeData:i};let o=document.createElement("iframe");o.className=this.options.className??"doubao-web-container-view",o.dataset.containerType=r,o.dataset.webSizing=eb(r),o.referrerPolicy="no-referrer",o.title="Doubao app content",o.sandbox.add("allow-scripts","allow-same-origin"),o.setAttribute("allow","picture-in-picture 'none'"),o.src=this.sandboxUrl,o.style.display="APP"===r?"none":"block",o.style.border="0",o.style.width="100%",o.style.height="WIDGET"===r?"0px":"100%",o.addEventListener("load",()=>this.handleLoad()),this.view=o,this.container.replaceChildren(o);let l=this.options.apiRegistry??R;return this.bridgeEvents=l.createEventController((e,t)=>this.postOrFail({type:"global-event",name:e,params:t})),o}clear(){var e,t;this.connected&&this.post({type:"dispose"}),this.destroyChannel(),null==(e=this.bridgeEvents)||e.destroy(),this.bridgeEvents=null,null==(t=this.view)||t.remove(),this.view=null,this.renderMessage=null,this.connected=!1,this.failed=!1,this.loadCount=0,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})}reload(){this.post({type:"reload"})}abortRender(e){var t,r;throw null==(t=(r=this.options).onError)||t.call(r,e,eS(e)),e}handleLoad(){if(this.failed||!this.view)return;if(this.loadCount+=1,this.loadCount>1)return void this.fail(Error("iframe navigated after the sandbox runtime loaded"));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);let t={type:"doubao-web-sdk:connect",protocolVersion:1,sdkVersion:ew()};try{var r;null==(r=this.view.contentWindow)||r.postMessage(t,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||a.sdkVersion!==ew()?void this.fail(Error("iframe sandbox protocol or SDK 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||"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=ev({apiRegistry:this.options.apiRegistry??R,emitEvent:(e,t)=>{var r;return(null==(r=this.bridgeEvents)?void 0:r.emit(e,t))??!1},events:this.bridgeEvents??void 0,fileSystemNamespace:this.renderMessage.syncBridgeData.fileSystemNamespace,globalProps:this.renderMessage.globalProps});try{var n,a;t=await ((null==(n=(a=this.options).nativeModulesCallHandler)?void 0:n.call(a,e.name,e.data,e.moduleName,{containerType:this.renderMessage.containerType,element:this.view}))??r(e.name,e.data,e.moduleName))}catch(t){this.postOrFail({type:"bridge-result",requestId:e.requestId,error:x(t)});return}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 s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eS(e);this.failed||(this.failed=!0,this.destroyChannel(),null==(t=this.bridgeEvents)||t.destroy(),this.bridgeEvents=null,null==(r=this.view)||r.remove(),this.view=null,this.renderMessage=null,null==(n=(a=this.options).onError)||n.call(a,e,s))}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}}r(84552);var eI=r(51238);r(74678),r(55910),r(76691),r(72919);let eE="embed-webview",eC="__channel_ack__",ek=new WeakMap,eN=e=>({url:e});function eM(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function eR(e){return"string"==typeof e?e:JSON.stringify(e??{})}let eT=globalThis.HTMLElement??class{};"object"!=typeof customElements||customElements.get(eE)||customElements.define(eE,class e extends eT{static observedAttributes=["src"];#e=null;#t=null;#r=!1;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#n(),this.#a()}disconnectedCallback(){var e;this.#r=!1,this.#s(),null==(e=this.#e)||e.remove(),this.#e=null}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=i(e)?e.data:void 0;this.#i({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=i(e)&&"string"==typeof e.func?e.func:"";if(t)try{var r;null==(r=this.#o())||r.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.#l),t.addEventListener("error",this.#d),e.replaceChildren(t),this.#e=t,window.addEventListener("message",this.#u),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=eN(r);(e||t.getAttribute("src")!==n.url)&&(this.#s(),t.toggleAttribute("credentialless",!0===n.credentialless),t.src=n.url)}#s(){var e;null==(e=this.#t)||e.close(),this.#t=null}#o(){try{var e;let t=(null==(e=this.#e)?void 0:e.contentWindow)??null;return null==t||t.document,t}catch{return null}}#l=()=>{this.#c(),this.#p(),this.#m(),this.#h("load",{url:this.getAttribute("src")??""})};#d=()=>{this.#h("error",{errorMsg:`Failed to load ${this.getAttribute("src")??""}`,errorCode:-1})};#u=e=>{if(!this.#e||e.source!==this.#e.contentWindow||e.data===eC)return;let t=eM(e.data);this.#g(t)||this.#f(eR(e.data))};#c(){var e;this.#s();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==eC&&this.#g(eM(e.data))},this.#t=r.port1,t.postMessage("__channel_init__","*",[r.port2])}#p(){let e=this.#o();e&&!e.AppletBridgeModule&&(e.AppletBridgeModule={postMessage:e=>(this.#g(eM(e)),Promise.resolve({})),postMessageSync:e=>{let t=eM(e);return b(t)?S(t,"Sync AppletBridgeModule APIs are not supported in Doubao Web SDK web-view"):void 0}})}#m(){let e=this.#o();e&&this.#f(JSON.stringify({type:"__doubao_web_view_set_title__",title:e.document.title||""}))}#g(e){if(i(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!b(e))return!1;if("doubao.postMessage"===e.name){let t=i(e.params)?e.params.data:void 0;return this.#f(eR(t)),this.#i(w(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=ek.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#i(S(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#i(r??S(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#i(e){var t;let r=JSON.stringify(e);if(this.#t)return void this.#t.postMessage(r);let n=this.#o();null==n||null==(t=n.onWebViewMessage)||t.call(n,r)}#f(e){this.#h("message",{msg:e,data:e})}#h(e,t){for(let r of[e,`bind${e}`])this.dispatchEvent(new CustomEvent(r,{bubbles:!0,composed:!0,detail:t}))}});let eA="AppletBridgeModule",eP="postMessage";function ej(e,t,r){t===eP&&(null==r?void 0:r.type)==="callback"&&"callbackId"in r&&"function"==typeof e.sendGlobalEvent&&e.sendGlobalEvent("__APPLET_BRIDGE__",[r])}function eD(e,t,r){"function"==typeof e.sendGlobalEvent&&e.sendGlobalEvent("__APPLET_BRIDGE__",[{type:"event",name:t,params:r,timestamp:Date.now()}])}class eL{container;className;options;syncBridgeData;bridgeEvents=null;view=null;constructor(e,t){const 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.syncBridgeData=t}get element(){return this.view}render(e){var t,r,n,a,s,i,o;let l,d,u,c;this.clear();let p=document.createElement("lynx-view"),m=e_(e),h=eb(m);p.className=this.className,p.dataset.containerType=m,p.dataset.webSizing=h,p.style.display="APP"===m?"none":"block",p.style.width="100%",p.style.height="content"===h?"auto":"100%","content"===h&&p.setAttribute("height","auto"),p.url=ey(e),p.initData=e.initData??{};let g={...H(),...e.globalProps??{}},f=this.syncBridgeData??eg(g,this.options.apiRegistry,this.options.fileSystemNamespace);l=new URL("./__doubao_web_sdk_native_modules/",(null==(t=globalThis.document)?void 0:t.baseURI)??(null==(r=globalThis.location)?void 0:r.href)??"http://localhost/").href,p.nativeModulesMap={AppletBridgeModule:(n=new URL("applet-bridge-module.js",l).href,(u=new URLSearchParams((d=new URL(n)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...f,fileSystemSnapshot:em()})),d.hash=u.toString(),d.href),AppletJSModule:new URL("applet-js-module.js",l).href},(0,eI.B)(p),p.globalProps={...g,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:f};let v=this.options.apiRegistry??R;return this.bridgeEvents=v.createEventController((e,t)=>eD(p,e,t)),a=this.options,s=this.bridgeEvents,i=f.fileSystemNamespace,c=ev({apiRegistry:a.apiRegistry,emitEvent:(e,t)=>s.emit(e,t),events:s,fileSystemNamespace:i,globalProps:g}),p.onNativeModulesCall=async(e,t,r)=>{var n,s,i,o;if(r===eA&&e===eP&&"event"===(n=t).type&&"__bridge_ready__"===n.name&&(null==(s=a.onReady)||s.call(a)),r===eA&&e===eP&&"callback"===(i=t).type&&"callbackId"in i)return ej(p,e,t),t;try{let n=await ((null==(o=a.nativeModulesCallHandler)?void 0:o.call(a,e,t,r,{containerType:m,element:p}))??c(e,t,r));return ej(p,e,n),n}catch(n){let r=b(t)?S(t,x(n)):void 0;return ej(p,e,r),r}},o=e=>E(e,v.handlers,{apiRegistry:v,globalProps:g}),ek.set(p,o),p.transformVW=!0,p.transformVH="content"!==h,p.transformREM=!0,p.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)}),this.view=p,this.container.replaceChildren(p),p}clear(){var e,t;null==(e=this.bridgeEvents)||e.destroy(),this.bridgeEvents=null,null==(t=this.view)||t.remove(),this.view=null,this.container.replaceChildren()}sendEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.view;r&&eD(r,e,t)}reload(){var e,t;null==(t=this.view)||null==(e=t.reload)||e.call(t)}}class eO{options;adapter=null;constructor(e){if(!e.container)throw Error("Container requires a container element");this.options=e}get element(){var e;return(null==(e=this.adapter)?void 0:e.element)??null}render(e){var t;null==(t=this.adapter)||t.clear();let r=y;this.adapter="iframe"===r.mode?new ex(this.options,r.url):new eL(this.options);try{return this.adapter.render(e)}catch(e){throw this.adapter.clear(),this.adapter=null,e}}clear(){var e;null==(e=this.adapter)||e.clear(),this.adapter=null}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};null==(t=this.adapter)||t.sendEvent(e,r)}reload(){var e;null==(e=this.adapter)||e.reload()}}let eU=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2
|
-
<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"/>
|
|
3
|
-
</svg>`,eq=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
4
|
-
<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"/>
|
|
5
|
-
</svg>`,e$="doubao-apps-page",eB={body:`${e$}__body`,capsule:`${e$}__capsule`,capsuleAction:`${e$}__capsule-action`,capsuleCloseIcon:`${e$}__capsule-close-icon`,capsuleMoreIcon:`${e$}__capsule-more-icon`,root:e$};class eF{host;options;container=null;root=null;constructor(e){if(!e.container)throw Error("Page requires a container element");this.host=e.container,this.options=e}get element(){var e;return(null==(e=this.container)?void 0:e.element)??null}render(e){var t;let r;this.clear();let n=document.createElement("div");n.className=eB.root,void 0!==(r=null==(t=e.pageCapsule)?void 0:t.statusBarHeight)&&n.style.setProperty("--doubao-page-capsule-top",`${r+4}px`);let a=document.createElement("div");return a.className=eB.body,n.append(a,this.createCapsule()),this.host.replaceChildren(n),this.root=n,this.container=new eO({apiRegistry:this.options.apiRegistry,container:a,className:this.options.className,fileSystemNamespace:this.options.fileSystemNamespace,nativeModulesCallHandler:this.options.nativeModulesCallHandler,onError:this.options.onError,onReady:this.options.onReady}),this.container.render({resourceUrl:function(e){if(!e.resourceUrl)throw Error("Page.render requires a resourceUrl");return e.resourceUrl}(e),containerType:"PAGE",initData:e.initData,globalProps:e.globalProps})}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(eB.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(eB.capsuleMoreIcon,"More",eU,"doubao:page-capsule-more")}createCapsuleCloseIcon(){return this.createCapsuleAction(eB.capsuleCloseIcon,"Close app",eq,"doubao:page-capsule-close")}createCapsule(){let e=document.createElement("div");return e.className=eB.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 eW=/\{\{\s*([^{}\s]+)\s*\}\}/g;function eH(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}}function ez(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`${eG(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))?`${eG(a,e)}://${e}`:e}function eV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=String(e??"").trim();if(!r)return;let n=ez(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 eG(e,t){return"function"==typeof e?e(t):e}function eK(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var eJ=r(70851);let eX="doubao-apps-widget",eQ={body:`${eX}__body`,header:`${eX}__header`,icon:`${eX}__icon`,root:eX,title:`${eX}__title`};class eZ{container;options;root=null;body=null;title=null;icon=null;runtimeContainer=null;renderToken=0;constructor(e){if(!e.container)throw Error("Widget requires a container element");this.container=e.container,this.options=e}get element(){var e;return(null==(e=this.runtimeContainer)?void 0:e.element)??null}async render(){this.clear();let e=this.renderToken,t=await v.resolveWidget(this.options.appId,this.options.widgetId);if(this.renderToken!==e){let e;throw(e=Error("Widget render was cancelled")).name="AbortError",e}return this.renderResource({...this.options,appId:t.appId??this.options.appId,globalProps:{...this.options.globalProps,packageInfo:{appId:t.appId,name:t.appName,iconSrc:t.iconSrc}},appName:t.appName,titleType:t.entry.titleType??0,resourceUrl:t.resourceUrl})}renderResource(e){this.clear(),++this.renderToken;let t=document.createElement("section");t.className=(0,eJ.$)(eQ.root,this.options.className);let r=document.createElement("div");r.className=eQ.body;let n=null;if(2!==e.titleType){(n=document.createElement("header")).className=eQ.header,n.hidden="iframe"===y.mode;let e=document.createElement("img");e.alt="",e.className=eQ.icon,e.height=16,e.width=16;let r=document.createElement("div");r.className=eQ.title,n.append(e,r),t.append(n),this.icon=e,this.title=r}return t.append(r),this.container.replaceChildren(t),this.root=t,this.body=r,this.updateHeader(e.appName,e.icon),this.runtimeContainer=new eO({apiRegistry:this.options.apiRegistry,container:r,fileSystemNamespace:this.options.fileSystemNamespace,nativeModulesCallHandler:this.options.nativeModulesCallHandler,onError:this.options.onError,onReady:()=>{n&&(n.hidden=!1)}}),this.runtimeContainer.render({containerType:"WIDGET",resourceUrl:e.resourceUrl,initData:e.initData,globalProps:e.globalProps})}clear(){var e,t;this.renderToken+=1,null==(e=this.runtimeContainer)||e.clear(),this.runtimeContainer=null,null==(t=this.root)||t.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()}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))}}r(84086),r(37891);let eY="onDestroy",e0="onShow";function e1(e){return e.path||e.id}function e2(e,t){e.style.display=t?"block":"none"}function e3(e,t){let r=function(e){let{pageId:t,viewData:r}=function(e){if(!e.trim())throw Error("route url must be a non-empty string");let[t,r=""]=e.trim().split("?");if(!t)throw Error("route url must include a page path");let n={};return new URLSearchParams(r).forEach((e,t)=>{n[t]=e}),{pageId:t,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 e4(e,t){return e&&"object"==typeof e?{packageInfo:t,...e}:{packageInfo:t}}function e5(e){if(i(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return i(t)?t:{}}catch{return{}}}class e6{container;className;apiRegistry;nativeModulesCallHandler;onError;appGlobalProps;appInitData;runtimeHost;configuredFileSystemNamespace;cleanupBridgeController;cleanupEmptyState;emptyState;manifest;manifestUrl;pageCapsule;fileSystemNamespace;appRuntime=null;stack=[];pendingPageRoutes=[];nextPageIndex=0;constructor(e){if(!e.container)throw Error("Runtime requires a container element");if(this.container=e.container,this.manifest=e.manifest,this.manifestUrl=e.manifestUrl,this.pageCapsule=e.pageCapsule,this.apiRegistry=e.apiRegistry,this.className=e.className,this.nativeModulesCallHandler=e.nativeModulesCallHandler,this.onError=e.onError,this.appGlobalProps=e.appGlobalProps,this.appInitData=e.appInitData,this.runtimeHost=e.runtimeHost,this.configuredFileSystemNamespace=e.fileSystemNamespace,this.fileSystemNamespace=this.resolveFileSystemNamespace(),this.emptyState=function(e){if(!(null==e?void 0:e.mountRuntimeEmptyState))return null;let t=document.createElement("div");return t.className="doubao-runtime-empty",t}(this.runtimeHost),this.emptyState){var t,r;this.container.append(this.emptyState);const e=null==(r=this.runtimeHost)||null==(t=r.mountRuntimeEmptyState)?void 0:t.call(r,this.emptyState);this.cleanupEmptyState="function"==typeof e?e:()=>{}}else this.cleanupEmptyState=()=>{};this.updateEmptyState(),this.cleanupBridgeController=function(e){return n=e,()=>{n===e&&(n=void 0)}}({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(),close:e=>this.closeBridgePage(e)})}get pages(){return this.stack.map(e=>this.toStackEntry(e))}get currentPage(){let e=this.getCurrentStackItem();return e?this.toStackEntry(e):null}setManifest(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.manifestUrl;this.clear(),this.manifest=e,this.manifestUrl=t,this.fileSystemNamespace=this.resolveFileSystemNamespace()}pushPage(){var e,t,r;let n,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=this.resolvePageEntry(s),l=p(this.manifestUrl,o),d=s.pageCapsule??this.pageCapsule,u=`page-${++this.nextPageIndex}`,c=(e=s,t=u,r=o,n=i(e.globalProps)?e5(e.globalProps.__VIEW_CONTEXT__):{},{...i(e.initData)?e5(e.initData.viewContext):{},...n,viewId:t,pageName:r.id,pageUrl:e1(r)}),m=((a=document.createElement("div")).className="doubao-runtime-page",a.style.display="block",a.style.width="100%",a.style.height="100%",a),h=null,g=new eF({apiRegistry:this.apiRegistry,className:this.className,container:m,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.nativeModulesCallHandler,onError:this.onError,onReady:()=>{h&&this.stack.includes(h)&&(h.isReady=!0,this.flushPageLifecycleEvents(h))}});void 0!==s.pageCapsule&&(this.pageCapsule=s.pageCapsule),this.ensureAppRuntime(),this.container.append(m),this.pendingPageRoutes.push(e1(o));try{let e,t,r=g.render({resourceUrl:l,initData:i(s.initData)?{...s.initData,viewContext:c}:{viewContext:c},globalProps:(e=null==d?void 0:d.statusBarHeight,t="number"==typeof e&&Number.isFinite(e)?{statusBarHeight:e}:{},i(s.globalProps)?{...s.globalProps,...t,__VIEW_CONTEXT__:c}:{...t,__VIEW_CONTEXT__:c}),pageCapsule:d}),n=this.getCurrentStackItem();return n&&(this.sendPageLifecycleEvent(n,"onHide"),e2(n.frame,!1)),h={id:u,pageId:o.id,route:e1(o),resourceUrl:l,entry:o,element:r,frame:m,isReady:!1,pendingLifecycleEvents:[],page:g},m.addEventListener("doubao:page-capsule-close",e=>{e.stopPropagation(),this.exitBridgeApp()}),this.stack.push(h),this.updateEmptyState(),this.sendPageLifecycleEvent(h,e0),this.sendAppLifecycleEvent("onPageOpened",{viewId:h.id}),this.toStackEntry(h)}catch(e){throw g.clear(),m.remove(),this.updateEmptyState(),e}finally{this.pendingPageRoutes.pop()}}replacePage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.stack.pop();return t&&this.removeStackItem(t,!1),this.pushPage(e)}popPage(){let e=this.stack.pop();return e?this.removeStackItem(e,!0):null}clear(){this.clearPages(),this.clearAppRuntime()}reload(){var e;null==(e=this.getCurrentStackItem())||e.page.reload()}destroy(){var e;this.clear(),this.cleanupEmptyState(),null==(e=this.emptyState)||e.remove(),this.cleanupBridgeController()}clearPages(){for(;this.stack.length>0;){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}}removeStackItem(e,t){let r=this.toStackEntry(e);this.sendPageLifecycleEvent(e,eY),e.page.clear(),e.frame.remove();let n=this.getCurrentStackItem();return t&&n&&(e2(n.frame,!0),this.sendPageLifecycleEvent(n,e0)),this.updateEmptyState(),r}ensureAppRuntime(){let e;if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let t=p(this.manifestUrl,this.manifest.appRuntimeEntry),r=((e=document.createElement("div")).className="doubao-runtime-app",e.hidden=!0,e.style.display="none",e),n=new eO({apiRegistry:this.apiRegistry,className:this.className,container:r,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.nativeModulesCallHandler,onError:this.onError,onReady:()=>{var e;(null==(e=this.appRuntime)?void 0:e.container)===n&&(this.appRuntime.isReady=!0,this.flushAppLifecycleEvents())}});this.container.append(r),this.appRuntime={container:n,frame:r,isReady:!1,pendingLifecycleEvents:[]};try{n.render({resourceUrl:t,containerType:"APP",initData:this.appInitData??{},globalProps:e4(this.appGlobalProps??{},this.getPackageInfo())}),this.sendAppLifecycleEvent("onForeground")}catch(e){throw this.appRuntime=null,n.clear(),r.remove(),e}}clearAppRuntime(){let e=this.appRuntime;(null==e?void 0:e.isReady)&&(this.sendAppLifecycleEvent("onBackground"),this.sendAppLifecycleEvent(eY)),null==e||e.container.clear(),null==e||e.frame.remove(),this.appRuntime=null}sendAppLifecycleEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.appRuntime;if(r){if(!r.isReady)return void r.pendingLifecycleEvents.push({name:e,params:t});r.container.sendEvent(e,t)}}flushAppLifecycleEvents(){let e=this.appRuntime;if(null==e?void 0:e.isReady)for(let t of e.pendingLifecycleEvents.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 e3(e,this.manifest)}getCurrentStackItem(){return this.stack[this.stack.length-1]??null}updateEmptyState(){this.emptyState&&(this.emptyState.hidden=this.stack.length>0)}getCurrentPages(){return[...this.stack.map(e=>({route:e.route})),...this.pendingPageRoutes.map(e=>({route:e}))]}getPackageInfo(){return{appId:this.manifest.appId,name:this.manifest.name,iconSrc:this.manifest.iconSrc,versionName:this.manifest.versionName}}resolveFileSystemNamespace(){return this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:ep(e4(this.appGlobalProps??{},this.getPackageInfo()))}navigateToBridgePage(e){this.pushPage(this.resolveRoutePageOptions(e))}redirectToBridgePage(e){let t=this.resolveRoutePageOptions(e);this.replacePage(t)}reLaunchBridgePage(e){let t=this.resolveRoutePageOptions(e);this.clearPages(),this.pushPage(t)}navigateBackBridgePage(e){let t=Math.min(Math.max(1,Math.floor(e.delta??1)),Math.max(0,this.stack.length-1));for(let e=0;e<t;e+=1)this.popPage()}exitBridgeApp(){this.clear()}closeBridgePage(e){let t=[];if(e.containerID&&t.push(e.containerID),0===t.length)return void this.popPage();for(let e of t)this.removePage(e)}removePage(e){let t=this.stack.findIndex(t=>t.id===e);if(-1===t)return null;let r=t===this.stack.length-1,[n]=this.stack.splice(t,1);return this.removeStackItem(n,r)}toStackEntry(e){return{id:e.id,pageId:e.pageId,route:e.route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}var e8=r(75541),e7=r(64865),e9=r(11855);function te(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)}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),r(32037),r(31178);let tt="/__wsd_control_results";function tr(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function tn(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}async function ta(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tt,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:fetch,n=await r(t,{body:JSON.stringify(e),headers:{"Content-Type":"application/json"},method:"POST"});if(!n.ok)throw Error(`Failed to report debugger control result: ${n.status}`)}let ts="/__web_artifacts/base/manifest.json",ti="/app_developer";function to(e){return!e.debugHidden}function tl(e){return eK(e)?eK(e.viewData)?e:{...e,viewData:e}:{viewData:{}}}function td(e){return"object"==typeof e&&null!==e}function tu(e){if("string"==typeof e&&e.trim())try{return JSON.parse(e)}catch{return}}function tc(e){if(eK(e))return e;let t=tu(e);return eK(t)?t:void 0}function tp(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return"{}"}}function tm(e){return e instanceof Error?e.message:String(e)}function th(e,t){let r=e[t];return"string"==typeof r?r:""}function tg(e,t){let r=e[t];return"number"==typeof r&&Number.isFinite(r)?r:void 0}function tf(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 tv(e){let[t,...r]=e.trim().split(":"),n=t.replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(ty).join(" ");return 0===r.length?n||e:`${n}: ${r.join(":").trim()}`}function ty(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)}`}function t_(e,t){let r=t.trim();r&&!e.includes(r)&&e.push(r)}function tb(e){let t=[];return!function e(t,r,n){if(!(!td(t)||n.has(t))){if(n.add(t),Array.isArray(t))return void t.forEach(t=>e(t,r,n));if(eK(t))for(let[a,s]of Object.entries(t))"response_headers"===a.toLowerCase()&&function(e,t){if(eK(e)){for(let[r,n]of Object.entries(e))if("x-tt-logid"===r.toLowerCase()&&"string"==typeof n)return void t_(t,n)}}(s,r),"log_ids"===a.toLowerCase()&&function(e,t){if("string"==typeof e)return t_(t,e);if(Array.isArray(e))for(let r of e)"string"==typeof r&&t_(t,r)}(s,r),e(s,r,n)}}(e,t,new WeakSet),t}function tw(e){let t=ez(String(e??ti).trim(),{addProtocolToBareHost:!0,allowRootRelative:!0,defaultProtocol:tS}).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 tS(e){return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\])(?::|\/|$)/i.test(e)?"http":"https"}function tx(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 tI(e,t){return`${tw(e)}${"chat"===t?"/api/simulator/chat":"/api/simulator/tool/report"}`}r(12021),r(20789),r(62839),r(66876),r(78872),r(60972);var tE=r(75585);let tC=["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 tk(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=e.getReader(),a=new TextDecoder,s={...r,fallbackSeq:0},i=(0,tE.C)({onEvent:e=>{let r=function(e,t){var r,n,a;let s,i,o,l,d,u,c=void 0===(l=tu(r=e.data))&&r.trim()?r:l,p=eK(c)?{...e.event&&!c.event?{event:e.event}:{},...c}:{event:e.event||"message",data:c},{eventType:m,payload:h}=function(e){var t;for(let t of tC){let r=e[t];if(eK(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=eK(h)?h:{},f=tg(p,"sequence")??(t.fallbackSeq+=1),v=e.id||th(p,"id")||`evt_${f.toString().padStart(4,"0")}`,y=function(e,t,r){let n=th(e,"request_id")||("ack"===r?th(t,"request_id"):"");if("ack"===r&&!n)throw Error("Invalid simulator SSE ACK: missing request_id");return n||th(e,"id")}(p,g,m),_=th(p,"reply_message_id")||th(g,"message_id")||t.replyMessageId;return{event_id:v,event_type:m,seq:f,request_id:y,query_message_id:th(p,"query_message_id")||th(g,"query_message_id"),reply_message_id:_,created_at_ms:tg(p,"timestamp_ms")??Date.now(),received_at_ms:Date.now(),trace:(d=eK(p.trace)?p.trace:{},{trace_id:"string"==typeof(u=t.trace??{}).trace_id?u.trace_id:"string"==typeof d.trace_id?d.trace_id:tx("trace"),span_id:"string"==typeof d.span_id?d.span_id:tx("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:m,sampled:"boolean"==typeof d.sampled?d.sampled:"boolean"!=typeof u.sampled||u.sampled,baggage:{...eK(u.baggage)?u.baggage:{},...eK(d.baggage)?d.baggage:{}}}),payload:(n=g,0===(o=Array.isArray(i=eK(s=null==(a=t.trace)?void 0:a.baggage)?s.log_ids:void 0)?i.filter(e=>"string"==typeof e&&e.trim().length>0):"string"==typeof i&&i.trim()?[i]:[]).length||void 0!==n.log_ids?n:{...n,log_ids:o})}}(e,s);r.reply_message_id&&(s.replyMessageId=r.reply_message_id),t(r)}});for(;;){let{done:e,value:t}=await n.read();if(t&&i.feed(a.decode(t,{stream:!e})),e)break}let o=a.decode();o&&i.feed(o),i.feed("\n\n")}let tN="x-tt-logid";class tM extends Error{responseDebug;constructor(e,t){super(e),this.responseDebug=t,this.name="SimulatorHttpError"}}function tR(e){return e.headers.get(tN)||void 0}function tT(e){let t={},r=tR(e);return r&&(t[tN]=r),t}function tA(e){return eK(e.trace)?e.trace:{}}async function tP(e,t){let r=tR(t),n=tT(t),a=await t.text().catch(()=>""),s={status:t.status,status_text:t.statusText,...Object.keys(n).length>0?{response_headers:n}:{},...r?{log_ids:[r]}:{},...a?{response_text:a}:{}};return new tM(`${e}: ${t.status} ${t.statusText}`,s)}function tj(e){return e instanceof tM?e.responseDebug:void 0}function tD(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},a=arguments.length>4?arguments[4]:void 0,s=tA(e),i=Date.now();return{event_id:tx("evt_client_debug"),event_type:"debug",seq:0,request_id:"string"==typeof e.idempotency_key?e.idempotency_key:"client_debug",created_at_ms:i,received_at_ms:i,trace:{trace_id:"string"==typeof s.trace_id?s.trace_id:tx("trace"),component:"string"==typeof s.component?s.component:"simulator_web_tester",stage:"string"==typeof s.stage?s.stage:"query",sampled:"boolean"!=typeof s.sampled||s.sampled,baggage:a??(eK(s.baggage)?s.baggage:{})},payload:{event:t,category:"api",elapsed_ms:Date.now()-r,...n}}}async function tL(e){let t,{endpoint:r,fetcher:n,onEvent:a,request:s,signal:i}=e,o=Date.now(),l=tI(r,"chat");a(tD(s,"simulator_chat_fetch_started",o,{endpoint:"chat",phase:"request",request:s,request_json:tp(s),url:l}));let d=setTimeout(()=>{a(tD(s,"simulator_chat_fetch_waiting_for_headers",o,{endpoint:"chat",phase:"wait",url:l,wait_ms:5e3}))},5e3);try{t=await (n??fetch)(l,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(s),signal:i})}catch(e){throw clearTimeout(d),a(tD(s,"simulator_chat_fetch_failed",o,{endpoint:"chat",phase:"error",url:l,error:tm(e)})),e}clearTimeout(d);let u=tR(t),c=tT(t),p=tA(s),m={...eK(p.baggage)?p.baggage:{}};if(u&&(m[tN]=u,m.log_ids=[u]),a(tD(s,"simulator_chat_headers_received",o,{event:"simulator_chat_response_meta",endpoint:"chat",phase:"response",status:t.status,status_text:t.statusText,...u?{log_ids:[u]}:{},...Object.keys(c).length>0?{response_headers:c}:{}},m)),!t.ok){let e=await tP("Simulator query failed",t);throw a(tD(s,"simulator_chat_fetch_failed",o,{endpoint:"chat",phase:"error",error:e.message,...e.responseDebug},m)),e}if(!t.body)throw Error("Simulator query response has no SSE body");let h=0,g=!1,f=setTimeout(()=>{g||a(tD(s,"simulator_chat_sse_waiting_for_first_event",o,{endpoint:"chat",wait_ms:5e3},m))},5e3);try{await tk(t.body,e=>{h+=1,g||(g=!0,clearTimeout(f)),a(e)},{trace:{...p,baggage:m}})}catch(e){throw clearTimeout(f),a(tD(s,"simulator_chat_sse_read_failed",o,{endpoint:"chat",phase:"error",event_count:h,error:tm(e)},m)),e}clearTimeout(f)}async function tO(e){let{endpoint:t,fetcher:r,result:n,signal:a}=e,s=await (r??fetch)(tI(t,"tool-report"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(n),signal:a});if(!s.ok)throw await tP("Simulator tool result failed",s);let i=await tU(s),o=tR(s);return{...i,...o?{response_headers:{...eK(i.response_headers)?i.response_headers:{},[tN]:o},log_ids:[o]}:{}}}async function tU(e){let t=await e.text().catch(()=>"");if(!t.trim())return{};try{let e=JSON.parse(t);return eK(e)?e:{response_body:e}}catch{return{response_text:t}}}let tq={label:"Request",tone:"request"},t$={label:"Response",tone:"response"},tB={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:tq,title:"Chat"},simulator_chat_fetch_waiting_for_headers:{title:"Chat Waiting"},simulator_chat_response_meta:{badge:t$,title:"Chat"},simulator_chat_fetch_failed:{badge:t$,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:tq,debugOnly:!0,title:"MCP Load"},local_mcp_tools_loaded:{badge:t$,debugOnly:!0,title:"MCP Load"},local_mcp_tools_load_failed:{badge:t$,title:"MCP Load Failed"},local_mcp_missing:{title:"MCP Missing"},local_mcp_call_started:{badge:tq,title:e=>`MCP Tool${e}`},local_mcp_call_succeeded:{badge:t$,title:e=>`MCP Tool${e}`},local_mcp_call_failed:{badge:t$,title:e=>`MCP Tool Failed${e}`},tool_result_report_started:{badge:tq,title:e=>`Report Tool Result${e}`},tool_result_report_response_received:{badge:t$,title:e=>`Report Tool Result${e}`},tool_result_report_failed:{badge:t$,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:t$,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:tq,debugOnly:!0,title:"Manifest Load"},simulator_manifest_loaded:{badge:t$,debugOnly:!0,title:"Manifest Load"},simulator_manifest_load_failed:{badge:t$,title:"Manifest Load Failed"},simulator_manifest_fetch_started:{badge:tq,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_succeeded:{badge:t$,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_failed:{badge:t$,title:"Manifest Fetch Failed"},simulator_manifest_missing:{title:"Manifest Missing"},simulator_skill_load_started:{badge:tq,debugOnly:!0,title:"Skill Load"},simulator_skill_loaded:{badge:t$,debugOnly:!0,title:"Skill Load"},simulator_skill_empty:{badge:t$,debugOnly:!0,title:"Skill Empty"},simulator_skill_load_failed:{badge:t$,title:"Skill Load Failed"},simulator_skill_fetch_started:{badge:tq,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_succeeded:{badge:t$,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_failed:{badge:t$,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 tF(e){try{return JSON.stringify(e??{})}catch{return""}}function tW(e){if(!eK(e))return;let t=tH(e);return{category:t.category,...t.debugOnly?{debugOnly:!0}:{},detail:t.detail,...t.transportBadge?{leftBadges:[t.transportBadge]}:{},phase:t.phase,title:t.title}}function tH(e){var t,r;let n="string"==typeof e.event?e.event:"",a=tB[n],s=e.detail??e.data??e,i="string"==typeof e.title&&e.title?tv(e.title):function(e,t){var r;let n=null==(r=tB[e])?void 0:r.title;if("function"==typeof n){let e,r,a;return n((e="string"==typeof t.tool_name&&t.tool_name?t.tool_name:"",r="string"==typeof t.tool_call_id&&t.tool_call_id?t.tool_call_id:"",(a=e||r)?`: ${a}`:""))}return n||(e?tv(e):"Agent Trace Event")}(n,e),o="string"==typeof e.category&&e.category?tf(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="string"==typeof e.phase&&e.phase?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:s,eventName:n,phase:l,title:i,transportBadge:null==a?void 0:a.badge}}function tz(e){return e.blocks.some(e=>"card"===e.type&&"permission_apply"===e.card.card_type)}function tV(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(tz);if(-1===r)return;let n=e[r];if(tz(n))for(let t=r-1;t>=0;t--){let r=e[t];if("user"===r.role&&r.text.trim())return{messageIds:[r.messageId,n.messageId],query:r.text.trim()}}}(r,t.grantingMessageId);return a?"streaming"===n?{status:"streaming"}:(e.removeSimulatorMessages(a.messageIds),{completion:t.noLogin?e.sendSimulatorQuery(a.query,{noLogin:!0}):e.sendSimulatorQuery(a.query),status:"started",target:a}):{status:"not_found"}}function tG(e){if(!eK(e))return;let t=th(e,"grantingName");if(t){var r;return{grantingName:t,permissionStatus:th(e,"permissionStatus")||"pending",priorityLevel:"number"==typeof e.priorityLevel?e.priorityLevel:0,relatedData:tc(r=e.relatedData)??(eK(r)?r:{}),required:!1!==e.required}}}function tK(e){let t=tc(e);if(!t)return;let r=Array.isArray(t.grantingList)?t.grantingList.map(tG).filter(e=>!!e):[];if(0!==r.length)return{cardStatus:th(t,"cardStatus")||"unexpired",doubaoAppletIcon:th(t,"doubaoAppletIcon"),doubaoAppletKey:th(t,"doubaoAppletKey"),doubaoAppletName:th(t,"doubaoAppletName")||"智能服务",doubaoAppletVersion:th(t,"doubaoAppletVersion"),grantingList:r,raw:t}}function tJ(e){var t;switch(null==(t=e.grantingList[0])?void 0:t.grantingName){case"permission":return"权限申请";case"privacy":return"隐私协议提示";default:return"登录授权"}}function tX(e,t,r,n,a){let s=e.find(e=>e.messageId===t);return s?n&&!s.requestId||a&&!s.traceId?e.map(e=>e===s?{...e,...n&&!e.requestId?{requestId:n}:{},...a&&!e.traceId?{traceId:a}:{}}:e):e:[...e,{messageId:t,...n?{requestId:n}:{},...a?{traceId:a}:{},role:"assistant",contentType:"mixed",text:"",blocks:[],status:"streaming",createdAtMs:r}]}function tQ(e,t,r){return e.map(e=>e.messageId===t?r(e):e)}function tZ(e,t,r,n){let a={blockId:t,type:"card",card:r};if("replace"===n){let n=r.card_id,s=e.map(e=>e.blockId===t||"card"===e.type&&n&&e.card.card_id===n?a:e);return s.some(e=>e===a)?s:[...e,a]}return e.some(e=>e.blockId===t)?e.map(e=>e.blockId===t?a:e):[...e,a]}function tY(e,t,r){let n=!1,a=!1,s=e.map(e=>{let s=!1,i=e.blocks.map(e=>{if("card"!==e.type||e.card.card_id!==t)return e;n=!0;let i=r(e.card);return i?(a=!0,s=!0,{...e,card:i}):e});return s?{...e,blocks:i}:e});return{messages:a?s:e,found:n,updated:a}}function t0(e){return"debug"===e.event_type?e.payload.data??e.payload:e.payload}function t1(e){let t=th(e.payload,"tool_name")||th(e.payload,"tool_call_id"),r=th(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 tv(th(e.payload,"title")||"Agent Trace");case"heartbeat":return"Heartbeat";default:return tv(e.event_type)}}function t2(e){let t=th(e.payload,"category");if(t)return tf(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 t3(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 t4(e){return"u">typeof DOMException&&e instanceof DOMException?"AbortError"===e.name:e instanceof Error&&"AbortError"===e.name}function t5(e,t){if(eK(e)&&"code"in e&&"message"in e)return e;let r=eK(e)&&eK(e.responseDebug)?e.responseDebug:void 0,n=tc(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||tm(e),retryable:!1,stage:t,...r?{details:{response:r,...n?{response_body:n}:{}}}:{}}}function t6(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 t8(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 t7(e,t,r){return{...e,toolCalls:e.toolCalls.map(e=>e.toolCallId===t?{...e,...r}:e)}}function t9(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)}r(66249);let re="simulator_web_tester";function rt(e){return"string"==typeof e?e.trim():""}function rr(e){return["succeeded","failed","timeout","cancelled","rejected"].includes(e)}function rn(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,...n?{details:n}:{}}}async function ra(e){let t,r,n,a,s,i,{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=rn("TOOL_EXEC_CANCELLED","Tool execution cancelled"),m=void 0===c?void 0:new AbortController,h=(null==m?void 0:m.signal)??u;if(null==u?void 0:u.aborted)throw p;if(m&&u){let e=()=>{m.abort()};u.addEventListener("abort",e,{once:!0}),s=()=>u.removeEventListener("abort",e)}let g=[Promise.resolve(o({...l,...h?{signal:h}:{}}))];if(void 0!==c&&m){let e=rn("TOOL_EXEC_TIMEOUT",`Tool execution timed out after ${c}ms`);g.push(new Promise((t,r)=>{a=setTimeout(()=>{m.abort(),r(e)},c)}))}u&&g.push(new Promise((e,t)=>{let r=()=>{t(p)};u.addEventListener("abort",r,{once:!0}),i=()=>u.removeEventListener("abort",r)}));try{return await Promise.race(g)}finally{a&&clearTimeout(a),null==s||s(),null==i||i()}}function rs(e){return e?String(e):ts}function ri(e,t,r){return r?{type:e,message:t,error:r}:{type:e,message:t}}let ro={simulator_manifest_load_failed:"Manifest",simulator_skill_load_failed:"Skill",local_mcp_tools_load_failed:"MCP",simulator_chat_fetch_failed:"对话接口"};function rl(e,t){return e?{kind:"pages",item:e,...t?{routeUrl:t}:{}}:null}function rd(e,t){if(!t)return null;try{return rl(e3({url:t},e).entry,t)}catch{return null}}function ru(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):tp(r).slice(0,1e3))||e.status}function rc(e,t){return"string"==typeof e.app_key&&e.app_key||"string"==typeof e.appKey&&e.appKey||"string"==typeof e.appId&&e.appId||"string"==typeof e.packageName&&e.packageName||t}function rp(e,t){let r=eK(e.applet)?e.applet:{};return"string"==typeof e.name&&e.name||"string"==typeof e.appName&&e.appName||"string"==typeof e.app_name&&e.app_name||"string"==typeof r.name&&r.name||t}function rm(e,t){if(!eK(t))return e;let r=eK(e.applet)?e.applet:{},n=eK(t.applet)?t.applet:{},a=Array.isArray(r.tools)?r.tools:[],s=Array.isArray(n.tools)?n.tools:[],i=new Map,o="string"==typeof t.name&&t.name||"string"==typeof t.appName&&t.appName||"string"==typeof t.app_name&&t.app_name||"string"==typeof n.name&&n.name||"";if(s.length>0)for(let e of[...a,...s])eK(e)&&"string"==typeof e.id&&e.id&&i.set(e.id,e);return{...e,..."number"==typeof t.manifest_version||"string"==typeof t.manifest_version?{manifest_version:t.manifest_version}:{},..."string"==typeof t.app_key?{app_key:t.app_key}:{},..."string"==typeof t.name?{name:t.name}:{},..."string"==typeof t.appName?{appName:t.appName}:{},..."string"==typeof t.app_name?{app_name:t.app_name}:{},...eK(t.mcp_server)?{mcp_server:t.mcp_server}:{},...eK(t.tools)?{tools:t.tools}:{},...eK(t.entities)?{entities:t.entities}:{},...eK(t.tool_card_binding)?{tool_card_binding:t.tool_card_binding}:{},..."string"==typeof t.raw_manifest_yaml?{raw_manifest_yaml:t.raw_manifest_yaml}:{},applet:{...r,...o?{name:o}:{},...s.length>0?{tools:[...i.values()]}:{}}}}class rh{fetcher;simulatorFetcher;historyMaxTurns;simulatorAppKey;simulatorAppName;simulatorSkill;simulatorManifest;simulatorMaxStep;simulatorMcpServers;simulatorMcpServerProvider;simulatorToolExecutor;listeners=new Set;activeSimulatorRun=null;lastResolvedSimulatorMcpServers=[];resourceUrlVersion;hasSimulatorManifestStateValue=!1;simulatorManifestStateValue;simulatorManifestStatePromise;simulatorRunSeq=0;destroyed=!1;state;constructor(e={}){const t=rs(e.manifestUrl);this.fetcher=e.fetcher,this.simulatorFetcher=e.simulatorFetch,this.historyMaxTurns=e.historyMaxTurns??6,this.simulatorAppKey=e.appKey,this.simulatorAppName=e.appName,this.simulatorSkill=e.skill,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:function(e){return{endpoint:tw(e),messages:[],streamStatus:"idle",toolCalls:[],traceEvents:[]}}(e.simulatorEndpoint),status:ri("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(rm(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=rs(e??this.state.manifestUrl);this.setState({...this.state,manifestUrl:r,status:ri("loading",`Loading manifest ${r}`)});try{let e,t,u,p,m,h=await c(r,{fetcher:this.fetcher}),g=await this.mergeSimulatorManifestForState(h),f=g.pages,_=g.widgets,b=rd(g,null==(i=this.state.pageSelection)?void 0:i.routeUrl)??(n=g,a=f,s=this.state.pageSelection,e=a.filter(to),t=null==s?void 0:s.item.id,u=function(e,t){if(null==t?void 0:t.trim())try{return e.getPageEntry(t)}catch{return}}(n,n.raw.applet.appletEntry),rl((t?e.find(e=>e.id===t):void 0)??(u&&to(u)?u:void 0)??e.find(e=>{var t;let r=null==(t=e.path)?void 0:t.replace(/^\/+|\/+$/g,"");return"index"===e.id||"pages/index"===r||"pages/index/index"===r})??e[0])),w=(o=this.state.widgetSelection,p=_.filter(to),(l=((m=null==o?void 0:o.item.widgetId)?p.find(e=>e.widgetId===m):void 0)??p[0])?{kind:"widgets",item:l}:null),S;var n,a,s,i,o,l,d={isolation:S?{mode:"iframe",url:S}:{mode:"inline"},resolveManifestUrl:()=>r,resourceUrlVersion:this.resourceUrlVersion};if(d.isolation){if("inline"!==d.isolation.mode&&"iframe"!==d.isolation.mode)throw Error("Runtime isolation mode must be inline or iframe");y=d.isolation}return v.configure(d),this.setState({...this.state,manifestUrl:r,manifest:g,pages:f,widgets:_,pageSelection:b,widgetSelection:w,status:ri("ready",b||w?`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:ri("error",`Load failed: ${e.message}`,e)}),e}}selectPage(e){this.assertActive();let t=this.state.pages.find(t=>t.id===e);if(!t){let t=Error(`Unknown pages entry: ${e}`);throw this.setState({...this.state,status:ri("error",t.message,t)}),t}this.setState({...this.state,pageSelection:{kind:"pages",item:t},status:ri("ready",`Selected page ${t.id}`)})}navigateToPage(e){this.assertActive();try{let t=rd(this.state.manifest,e);if(!t)throw Error(`Unknown pages route: ${e}`);this.setState({...this.state,pageSelection:t,status:ri("ready",`Navigated page ${t.item.id}`)})}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.setState({...this.state,status:ri("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:ri("error",t.message,t)}),t}this.setState({...this.state,widgetSelection:{kind:"widgets",item:t},status:ri("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=tx("reload");this.resourceUrlVersion=t,this.clearSimulatorManifestStateValue(),v.clearPackageCache(e);let r=await this.loadManifest(e);return 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();if(!r)return;this.cancelSimulatorQuery();let n=tx("local_msg"),a=tx("idem"),s=tx("trace"),i=Date.now(),o=this.state.simulator,l=this.state.manifest.raw,d={messageId:n,localMessageId:n,traceId:s,role:"user",contentType:"text",text:r,blocks:[{blockId:tx("block_text"),type:"text",text:r}],status:"completed",createdAtMs:i},u=this.createSimulatorRun(s);this.activeSimulatorRun=u,this.setState({...this.state,simulator:{...o,activeRequestId:void 0,activeReplyMessageId:void 0,error:void 0,messages:[...o.messages,d],streamStatus:"streaming"}}),this.appendSimulatorDebugEvent({event:"simulator_query_prepare_started",trace_id:s,previous_active_request_id:o.activeRequestId,previous_stream_status:o.streamStatus,history_message_count:o.messages.length,query_preview:r.slice(0,80)});try{var c,p,m,h;let e,d,g,f,v,y,_,b,w=await this.resolveSimulatorManifestForQuery(s,t,l),S=rc(w,this.state.manifest.appId),x=rp(w,this.state.manifest.name);if(!this.isSimulatorRunCurrent(u))return;let I=await this.resolveSimulatorSkillForQuery(s,t);if(!this.isSimulatorRunCurrent(u))return;let E={trace:{trace_id:s,component:"web_sdk_debugger",stage:"query_prepare",sampled:!0},appKey:t.appKey||this.simulatorAppKey||S||void 0,appName:t.appName||this.simulatorAppName||x||void 0,manifest:w},C=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider(E):this.simulatorMcpServers;if(this.lastResolvedSimulatorMcpServers=C,!this.isSimulatorRunCurrent(u))return;this.appendSimulatorDebugEvent({event:"simulator_query_mcp_resolved",trace_id:s,elapsed_ms:Date.now()-i,mcp_server_count:C.length,mcp_servers:C.map(e=>({server_id:e.server_id,tool_count:e.tools.length,tools:e.tools.map(e=>e.name)}))});let k=(p=(c={historyMaxTurns:this.historyMaxTurns,idempotencyKey:a,localMessageId:n,manifestAppId:this.state.manifest.appId,manifestAppName:x,messages:o.messages,toolCalls:o.toolCalls,options:t,queryText:r,simulatorAppKey:this.simulatorAppKey,simulatorAppName:this.simulatorAppName,simulatorSkill:I,simulatorManifest:w,simulatorMaxStep:this.simulatorMaxStep,simulatorMcpServers:C,traceId:s}).messages,m=c.toolCalls,h=c.historyMaxTurns,e=p.slice(-Math.max(0,2*h)).map(e=>{var t,r,n;let a,s,i,o=(t=e,(a=m.filter(e=>e.replyMessageId===t.messageId&&rr(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?a:(t.toolCalls??[]).filter(e=>rr(e.status))),l=(r=e,(s=m.filter(e=>e.replyMessageId===r.messageId&&rr(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,...r?{result_summary:r}:{},...e.structuredResultSummary?{structured_summary:e.structuredResultSummary}:{},...void 0===e.isMiniApp?{}:{is_mini_app:e.isMiniApp}}})).length>0?s:r.toolResults??[]);return{role:"assistant"===e.role?"ASSISTANT":"USER",content:(i=(n=e).text?n.text:n.blocks.filter(e=>"text"===e.type).map(e=>e.text).join(""))||e.blocks.filter(e=>"card"===e.type).map(e=>{var t;return(t=e.card).fallback_text||t.title||t.card_type||t.card_id||"卡片"}).join("\n"),...o.length>0?{tool_calls:o.map(e=>({tool_call_id:e.tool_call_id,tool_name:e.tool_name,arguments:e.arguments_summary,status:e.status}))}:{},...l.length>0?{tool_results:l.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}))}:{}}}),d=function(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=tc(null==(t=e.debug)?void 0:t.props_json),s=rt(e.card_id),i=rt(null==a?void 0:a.applet_id)||rt(e.app_id),o=rt(null==a?void 0:a.entity_id)||rt(e.entity_id);if(s&&i&&o)return{card_id:s,app_key:i,business_entity_ids:[o],lifecycle_state:(null==(r=e.state)?void 0:r.lifecycle_state)==="fixed"||(null==(n=e.state)?void 0:n.lifecycle_state)===2?2:1}}(e.card);r&&!t.has(r.card_id)&&t.set(r.card_id,r)}return[...t.values()]}(c.messages),g=c.simulatorManifest||c.options.manifest||{},f="string"==typeof g.app_key?g.app_key:"",v=c.options.appKey||c.simulatorAppKey||f||c.manifestAppId||"web-sdk-debugger",y=c.options.appName||c.simulatorAppName||c.manifestAppName||v,_=(c.options.skill||c.simulatorSkill||"").trim(),b=c.options.mcpServers??c.simulatorMcpServers,{app_id:v,scene:"miniapp_simulator_web_tester",history_messages:e,card_snapshots:d,message:{role:"USER",content:c.queryText,local_message_id:c.localMessageId},trace:{trace_id:c.traceId,component:re,stage:"query",sampled:!0},client:{platform:"web",locale:"zh-CN",timezone:function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"Asia/Shanghai"}}()},ext:{web_tester:"true",stateless_context:"client_history",skill_source:_?"local_file":"none",...c.options.followUpContent?{applet_follow_up_data:tp(c.options.followUpContent)}:{},...c.options.noLogin?{no_login:"true"}:{}},max_step:c.options.maxStep??c.simulatorMaxStep??20,protocol_version:"v2",idempotency_key:c.idempotencyKey,mini_apps:[{app_key:v,app_name:y,..._?{skill:_}:{},manifest:{app_key:v,app_name:y,raw_manifest_yaml:"string"==typeof g.raw_manifest_yaml?g.raw_manifest_yaml:""},mcp_servers:b.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:tp(e.input_schema_json)}))}))}],web_capabilities:{supports_debug_event:!0}});if(await tL({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,request:k,signal:u.streamAbortController.signal,onEvent:e=>this.handleSimulatorEvent(e,u)}),!this.isSimulatorRunCurrent(u))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()-i,stream_status:this.state.simulator.streamStatus,active_request_id:this.state.simulator.activeRequestId})}catch(n){if(t4(n))return void this.appendSimulatorDebugEvent({event:"simulator_query_aborted",trace_id:s,elapsed_ms:Date.now()-i,stream_status:this.state.simulator.streamStatus});if(!this.isSimulatorRunCurrent(u))return;let e=t5(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()-i,error:r}),this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,error:r,streamStatus:"error"}}),n}finally{this.finishSimulatorStream(u)}}removeSimulatorMessages(e){this.assertActive();let t=new Set(e.filter(Boolean));0!==t.size&&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}))}cancelSimulatorQuery(){this.assertActive();let e=this.state.simulator.activeRequestId,t=this.activeSimulatorRun;t&&(this.appendSimulatorDebugEvent({event:"simulator_query_cancel_requested",...e?{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){let t;if(this.assertActive(),!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");let r=e.toolName.trim();if(!r)throw Error("toolName must be a non-empty string");let n=tx("req_tool"),a=tx("reply_tool"),s=tx("tool_call"),i=tx("trace"),o={trace_id:i,component:"web_sdk_debugger",stage:"direct_tool_call",sampled:!0},l=Date.now(),d=await this.resolveDirectToolCallServerId(r,e.serverId,o),u={requestId:n,replyMessageId:a,toolCallId:s,toolName:r,serverId:d,appKey:this.simulatorAppKey||rc(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.params,argumentsJson:e.params?tF(e.params):void 0,status:"running",createdAtMs:l,updatedAtMs:l,trace:o,timeoutMs:e.timeoutMs};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,u]})),this.appendSimulatorDebugEvent({event:"direct_tool_call_started",request_id:n,trace_id:i,tool_call_id:s,tool_name:r,server_id:d,arguments:e.params,arguments_json:u.argumentsJson});let c=Date.now();try{t=await ra({executor:this.simulatorToolExecutor,input:this.createToolExecutorInput(u),record:u})}catch(r){let e=t5(r,"tool_execute");t={status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||t4(r)?"cancelled":"failed",error:e}}return this.updateToolCall(s,{status:t.status,updatedAtMs:Date.now(),error:t.error,resultSummary:ru(t),structuredResultSummary:t.result,isMiniApp:t.miniapp&&"boolean"==typeof t.miniapp.is_mini_app?t.miniapp.is_mini_app:void 0}),this.appendSimulatorDebugEvent({event:"direct_tool_call_completed",request_id:n,trace_id:i,tool_call_id:s,tool_name:r,server_id:d,status:t.status,elapsed_ms:Date.now()-c,result:t.result,error:t.error,raw_result_text:t.raw_result_text}),t}async submitToolResult(e,t){let r,n,a,s;this.assertActive();let i=Date.now(),o=(n=e.result??(e.error?{error:e.error.message}:{}),s=(a=e.raw_mcp_result_json)||e.raw_result_text||tp(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),...e.appKey?{app_key:e.appKey}:{},result:{tool_call_id:e.toolCallId,content:a||s,structured_json:tp(n)},raw_result_text:s,raw_mcp_result_json:a||"",miniapp:e.miniapp,timing:e.timing,trace:{trace_id:e.trace.trace_id,component:re,stage:"tool_report",sampled:e.trace.sampled??!0},ext:{reported_by:re}});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,report_request_json:tF(o),endpoint:this.state.simulator.endpoint});try{r=await tO({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,result:o,signal:t})}catch(r){let t=tj(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()-i,error:tm(r),...t?{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()-i,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",s=tb(e)[0];return rn("TOOL_RESULT_REJECTED",s?`${a} (x-tt-logid: ${s})`:a,"tool_result_submit",{gateway_response:e,...n?{gateway_code:t}:{},...r?{gateway_accepted:!1}:{},...s?{"x-tt-logid":s}:{}})}(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,...l?{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(!eK(t))return{status:"invalid_widget_data",message:"widgetData must be a JSON object"};let r=tY(this.state.simulator.messages,e.widgetInstanceId,r=>({...r,...e.widgetId?{widget_id:e.widgetId}:{},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),s=rn("TOOL_EXEC_REJECTED",t),i=Date.now();null==n||n.pendingApprovalToolCallIds.delete(e);try{await this.submitExecutedToolResult(a,{status:"rejected",error:s},i,null==n?void 0:n.streamAbortController.signal),this.updateToolCall(e,{status:"rejected",updatedAtMs:Date.now(),error:s,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=t5(a,"tool_result_submit");throw this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:r.trace.trace_id,tool_call_id:e,summary:tm(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}destroy(){this.destroyed||(this.cancelSimulatorQuery(),this.destroyed=!0,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){for(let t of(e.cancelled=!0,e.streamAbortController.abort(),e.toolAbortControllers))t.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){let r="tool_call"===e.event_type;if(!this.isSimulatorRunCurrent(t)){r&&this.appendSimulatorDebugEvent({event:"tool_call_event_skipped",request_id:e.request_id,trace_id:e.trace.trace_id,tool_call_id:th(e.payload,"tool_call_id"),tool_name:th(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 n=this.state.simulator.activeRequestId;if(n&&e.request_id!==n&&"ack"!==e.event_type&&"debug"!==e.event_type){if(!r&&"tool_status"!==e.event_type)return;this.appendSimulatorDebugEvent({event:"tool_call_request_id_mismatch",request_id:e.request_id,active_request_id:n,trace_id:e.trace.trace_id,tool_call_id:th(e.payload,"tool_call_id"),tool_name:th(e.payload,"tool_name"),event_type:e.event_type,summary:"Tool call event request_id differs from the acknowledged request_id"})}let{state:a,toolCall:s,cardRefresh:i}=function(e,t,r){var n,a,s,i,o,l,d,u,c,p,m,h,g,f;let v,y,_,b,w,S,x,I,E,C,k,N,M={...e,activeReplyMessageId:t.reply_message_id??e.activeReplyMessageId},R=!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)?M:t6(M,(N=t.received_at_ms??Date.now(),{display:"debug"===(n=t).event_type?tW(n.payload)??{category:"debug",detail:t0(n),phase:"event",title:"Debug"}:{category:t2(n),detail:t0(n),phase:t3(n.event_type),title:t1(n)},id:t.event_id,timestamp:N,payload:(a=t,s=N,v=t2(a),y=t3(a.event_type),_={event:a.event_type,category:v,phase:y,received_at_ms:s,server_timestamp_ms:a.created_at_ms,title:t1(a),detail:t0(a),trace:a.trace},"debug"===a.event_type?{..._,event:th(a.payload,"event")||"debug",title:tv(th(a.payload,"title")||th(a.payload,"event")||"Debug Event"),summary:th(a.payload,"summary"),elapsed_ms:tg(a.payload,"elapsed_ms"),redaction_level:th(a.payload,"redaction_level")}:"heartbeat"===a.event_type?{..._,server_time_ms:tg(a.payload,"server_time_ms"),message:th(a.payload,"message")}:"answer_finish"===a.event_type?{..._,status:th(a.payload,"status"),finish_reason:th(a.payload,"finish_reason"),usage:a.payload.usage}:{..._,...a.payload})}));switch(t.event_type){case"ack":return{state:(i=R,b=th((o=t).payload,"local_message_id"),w=th(o.payload,"query_message_id"),S=th(o.payload,"message_id"),x=b&&w?i.messages.map(e=>e.localMessageId===b?{...e,messageId:w}:e):i.messages,{...i,activeRequestId:o.request_id,...S?{activeReplyMessageId:S}:{},messages:x})};case"message_start":return{state:(l=R,I=th((d=t).payload,"message_id")||d.reply_message_id||tx("reply"),{...l,activeReplyMessageId:I,messages:tX(l.messages,I,d.created_at_ms,d.request_id,d.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=th(t.payload,"block_id")||`block_text_${t.seq}`,a=th(t.payload,"delta"),s=th(t.payload,"op")||"append";if("append"!==s&&"replace"!==s)return e;let i=tX(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:tQ(i,r,e=>({...e,text:"replace"===s?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,s)}))}}(R,t)};case"card_delta":return function(e,t){var r;let n=function(e){let t=eK(e.card)?e.card:{},r=eK(t.state)?t.state:{},n=th(e,"card_id"),a=th(r,"widget_id");if("update_state"!==th(e,"op")||"miniapp_history_refresh"!==th(t,"card_type")||"fixed_style"!==th(r,"refresh_to")||!n||!a)return;let s=th(r,"url")||th(r,"schema");return{cardId:n,state:r,widgetData:{...s?{url:s}:{},...th(r,"title")?{title:th(r,"title")}:{},...th(r,"detailText")?{detailText:th(r,"detailText")}:{}},widgetId:a}}(t.payload);if(n){let t=tY(e.messages,n.cardId,e=>{let t=eK(e.state)?e.state:{};if("fixed"!==th(t,"lifecycle_state"))return{...e,render_data:{viewData:n.widgetData},widget_id:n.widgetId,state:{...t,...n.state,lifecycle_state:"fixed"}}});return{state:{...e,messages:t.messages},cardRefresh:{cardId:n.cardId,status:t.updated?"updated":t.found?"already_fixed":"not_found"}}}let a=t.reply_message_id??e.activeReplyMessageId;if(!a)return{state:e};let s=function(e){let t,r=e.card;if(!eK(r))return{};let n=tc(r.props_json)??{},a=function(e){let t,r;if("miniapp_packet_10066"!==e.card_type)return;let n=tc(e.props_json)||tc(e.render_data_json)||(eK(e.render_data)?tc(e.render_data.content_for_display):void 0)||{};return th(n,"permission_data")||((r=(Array.isArray(null==(t=eK(n.structuredContent)?n.structuredContent:void 0)?void 0:t.entity_list)?t.entity_list:[]).find(e=>eK(e)&&(Array.isArray(e.grantingList)||eK(e._meta)&&!0===e._meta.is_permission)))&&eK(r)?JSON.stringify(r):void 0)}(r),s=tK(a),i=eK(n.extra)?n.extra:{},o=Object.keys(n).length>0?(t=tc(n.widget_data))?{viewData:t}:eK(n.viewData)?{viewData:n.viewData}:{viewData:n}:void 0,l={...eK(r.source)?r.source:{},..."string"==typeof e.source_tool_call_id?{tool_call_id:e.source_tool_call_id}:{},...Array.isArray(e.source_entity_ids)?{entity_ids:e.source_entity_ids}:{}};return{...{..."string"==typeof e.card_id?{card_id:e.card_id}:{},..."string"==typeof e.widget_id?{widget_id:e.widget_id}:{},..."string"==typeof e.card_type?{card_type:e.card_type}:{},..."string"==typeof e.app_id?{app_id:e.app_id}:{}},...r,..."string"==typeof n.widget_id?{widget_id:n.widget_id}:{},..."string"==typeof n.applet_id?{app_id:n.applet_id}:{},..."string"==typeof n.entity_id?{entity_id:n.entity_id}:{},...Object.keys(l).length>0?{source:l}:{},...s?{card_type:"permission_apply",fallback_text:r.fallback_text||"需要授权后继续",render_data:{grantingData:s,permissionData:a},title:r.title||tJ(s)}:o?{render_data:o}:{},debug:{...eK(r.debug)?r.debug:{},..."string"==typeof r.props_json?{props_json:r.props_json}:{},..."string"==typeof i["doubao/outputTemplate"]?{output_template:i["doubao/outputTemplate"]}:{}}}}(t.payload),i=th(t.payload,"block_id")||s.card_id||(r=`card_${t.seq}`,s.card_id||s.title||r),o=th(t.payload,"op")||"append";if("append"!==o&&"replace"!==o)return{state:e};let l=tX(e.messages,a,t.created_at_ms,t.request_id,t.trace.trace_id);return{state:{...e,messages:tQ(l,a,e=>({...e,contentType:"mixed",blocks:tZ(e.blocks,i,s,o)}))}}}(R,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(!eK(e))return;let t=eK(e.content)?e.content:e,r=eK(t.permission_apply_block)?t.permission_apply_block:eK(t.permissionApplyBlock)?t.permissionApplyBlock:void 0;return r?th(r,"permission_data")||th(r,"permissionData"):""}(n),s=tK(a);if(!s)continue;let i=eK(n)&&th(n,"block_id")||eK(n)&&th(n,"blockId")||`permission_apply_${t.seq}_${r}`;return{blockId:i,card:{card_id:i,card_type:"permission_apply",fallback_text:"需要授权后继续",render_data:{grantingData:s,permissionData:a},title:tJ(s)},op:th(e,"op")||"append"}}}(t.payload,t);if(!n||"append"!==n.op&&"replace"!==n.op)return e;let a=tX(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:tQ(a,r,e=>({...e,contentType:"mixed",blocks:tZ(e.blocks,n.blockId,n.card,n.op)}))}}(R,t)};case"tool_call":return function(e,t,r){let n,a=th(t.payload,"tool_call_id"),s=th(t.payload,"tool_name"),i=th(t.payload,"server_id"),o=th(t.payload,"arguments_json"),l=t.reply_message_id??e.activeReplyMessageId??tx("reply");if(!a||!s)return{state:t6(e,{id:tx("trace"),timestamp:Date.now(),payload:{event:"tool_call_ignored",request_id:t.request_id,trace_id:t.trace.trace_id,tool_call_id:a,tool_name:s,reason:a?"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 d=("boolean"==typeof(n=t.payload.requires_user_approval)?n:void 0)??!1,u=d?"pending_approval":r.hasToolExecutor?"running":"pending",c={requestId:t.request_id,...void 0===r.runId?{}:{runId:r.runId},replyMessageId:l,toolCallId:a,toolName:s,serverId:i,appKey:th(t.payload,"app_key")||void 0,arguments:eK(t.payload.arguments)?t.payload.arguments:tc(o),argumentsJson:o||void 0,mcpHeaders:function(e){if(!eK(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:u,createdAtMs:t.created_at_ms,updatedAtMs:t.created_at_ms,trace:t.trace,requiresUserApproval:d,timeoutMs:tg(t.payload,"timeout_ms"),deadlineMs:tg(t.payload,"deadline_ms")},p=tQ(tX(e.messages,l,t.created_at_ms,t.request_id,t.trace.trace_id),l,e=>({...e,toolCalls:t9(e.toolCalls??[],c)})),m={...e,messages:p,toolCalls:[...e.toolCalls.filter(e=>e.toolCallId!==a),c]};return r.hasToolExecutor?{state:m,toolCall:c}:{state:t6(m,{id:tx("trace"),timestamp:Date.now(),payload:{event:"tool_executor_missing",request_id:c.requestId,trace_id:c.trace.trace_id,tool_call_id:a,tool_name:s,summary:"No local simulator tool executor is configured"}})}}(R,t,r);case"tool_status":return{state:function(e,t){let r=th(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""}}(th(t.payload,"status"));if(!r||!n)return e;let a=tg(t.payload,"progress"),s=th(t.payload,"message"),i=t.payload.error?t5(t.payload.error,"tool_execute"):void 0,o=t7(e,r,{status:n,updatedAtMs:t.created_at_ms,...void 0===a?{}:{progress:a},...s?{message:s}:{},...i?{error:i}:{}}),l=o.toolCalls.find(e=>e.toolCallId===r);return l?{...o,messages:tQ(o.messages,l.replyMessageId,e=>({...e,toolCalls:t9(e.toolCalls??[],l)}))}:o}(R,t)};case"trace_event":case"debug":default:return{state:R};case"heartbeat":return{state:(u=R,c=t,{...u,lastHeartbeatMs:tg(c.payload,"server_time_ms")??c.created_at_ms})};case"answer_finish":return{state:(p=R,m=t,{...p,answerFinish:{messageId:m.reply_message_id,status:th(m.payload,"status"),finishReason:th(m.payload,"finish_reason"),usage:eK(m.payload.usage)?m.payload.usage:void 0,createdAtMs:m.created_at_ms,trace:m.trace,payload:m.payload}})};case"message_finish":return{state:function(e,t){let r=th(t.payload,"message_id")||t.reply_message_id;if(!r)return e;let n=th(t.payload,"status")||"completed";return{...e,messages:tQ(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)}))}}(R,t)};case"reply_finish":return{state:(h=R,C="completed"===(E=th(t.payload,"status")||"completed")||"finished"===E?"completed":"cancelled"===E?"cancelled":"error",{...h,activeRequestId:void 0,activeReplyMessageId:void 0,messages:t8(h.messages,C),streamStatus:C})};case"stream_error":return{state:(g=R,k=t5((f=t).payload.error??f.payload,th(f.payload,"stage")||"stream"),{...g,activeRequestId:void 0,error:k,messages:t8(g.messages,"error"),streamStatus:"error"})}}}(this.state.simulator,e,{hasToolExecutor:!!this.simulatorToolExecutor,runId:t.id});if(this.updateSimulatorState(()=>a),(null==i?void 0:i.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:i.cardId}),s){let e=this.withFallbackToolCallServerId(s);e.requiresUserApproval?t.pendingApprovalToolCallIds.add(e.toolCallId):this.executeSimulatorToolCall(e,t)}}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 executeSimulatorToolCall(e,t){let r;if(!this.simulatorToolExecutor)return;let n=this.simulatorToolExecutor;if(t&&!this.isSimulatorRunCurrent(t))return;let a=Date.now(),s=this.createToolExecutorInput(e),i=t?new AbortController:void 0;t&&i&&t.toolAbortControllers.add(i);try{r=await ra({executor:n,input:s,record:e,signal:null==i?void 0:i.signal})}catch(t){let e=t5(t,"tool_execute");r={status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||t4(t)?"cancelled":"failed",error:e}}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(s,r,a,null==i?void 0:i.signal),t&&!this.isSimulatorRunCurrent(t))return;this.updateToolCall(e.toolCallId,{status:r.status,updatedAtMs:Date.now(),error:r.error,resultSummary:ru(r),structuredResultSummary:r.result,isMiniApp:r.miniapp&&"boolean"==typeof r.miniapp.is_mini_app?r.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=t5(n,"tool_result_submit");this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,summary:tm(n),error:r}),this.updateToolCall(e.toolCallId,{status:"failed",updatedAtMs:Date.now(),error:r}),this.failActiveSimulatorStream(r)}finally{t&&i&&(t.toolAbortControllers.delete(i),this.releaseSimulatorRun(t))}}createToolExecutorInput(e){let t={trace_id:e.trace.trace_id,span_id:tx("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||rc(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.arguments,argumentsJson:e.argumentsJson,headers:e.mcpHeaders,timeoutMs:e.timeoutMs,deadlineMs:e.deadlineMs,trace:t}}async resolveSimulatorManifestForQuery(e,t,r){let n=Date.now(),a=void 0!==t.manifest,s=a?"query_option":void 0===this.simulatorManifest?"loaded_manifest":"debugger_option";this.appendSimulatorDebugEvent({event:"simulator_manifest_load_started",trace_id:e,source:s});try{let i=a?{found:!1,value:void 0}:this.takeSimulatorManifestStateValue(),o=a?t.manifest:i.found?i.value:"function"==typeof this.simulatorManifest?await this.simulatorManifest():this.simulatorManifest,l=o?rm(r,o):r;return this.appendSimulatorDebugEvent({event:"simulator_manifest_loaded",trace_id:e,elapsed_ms:Date.now()-n,source:s,manifest:l}),l}catch(t){return this.appendSimulatorDebugEvent({event:"simulator_manifest_load_failed",trace_id:e,elapsed_ms:Date.now()-n,error:tm(t),source:s}),r}}async resolveSimulatorSkillForQuery(e,t){let r=Date.now(),n=void 0===t.skill?"debugger_option":"query_option";this.appendSimulatorDebugEvent({event:"simulator_skill_load_started",trace_id:e,source:n});try{let a=t.skill??("function"==typeof this.simulatorSkill?await this.simulatorSkill():this.simulatorSkill)??"";return this.appendSimulatorDebugEvent({event:a.trim()?"simulator_skill_loaded":"simulator_skill_empty",trace_id:e,elapsed_ms:Date.now()-r,skill_length:a.length,source:n}),a}catch(t){return this.appendSimulatorDebugEvent({event:"simulator_skill_load_failed",trace_id:e,elapsed_ms:Date.now()-r,error:tm(t),source:n}),""}}async resolveDirectToolCallServerId(e,t,r){var n;let a=null==t?void 0:t.trim();if(a)return a;let s=this.state.manifest.raw,i=this.simulatorAppKey||rc(s,this.state.manifest.appId)||void 0,o=this.simulatorAppName||rp(s,this.state.manifest.name)||void 0,l=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider({trace:r,appKey:i,appName:o,manifest:s}):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=rn("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 submitExecutedToolResult(e,t,r,n){let a=Date.now();await this.submitToolResult({...e,...t,timing:{started_at_ms:r,ended_at_ms:a,duration_ms:a-r,attempt:1}},n)}updateToolCall(e,t){this.updateSimulatorState(r=>t7(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=eK(t.payload)?t.payload:{},a=ro["string"==typeof n.event?n.event:""];a&&function(e){let t=eK(e.trace)?e.trace:{},r=e.trace_id??t.trace_id;return"string"==typeof r?r:""}(n)===e&&"Failed to fetch"===("string"==typeof n.error?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=tj(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"===tm(t)?{code:"SIMULATOR_ENDPOINT_UNREACHABLE",confidence:"unknown",summary:"无法连接模拟器接口",suggestion:"可能是接口服务未启动、端口不可达、浏览器网络异常或 CORS 被拦截。"}:void 0}appendSimulatorDebugEvent(e){let t=tb(e),r={display:tW(e),id:tx("trace"),timestamp:Date.now(),payload:function(e,t){if(!eK(e))return e;let r=tH(e);return{...e,category:r.category,detail:r.detail,phase:r.phase,title:r.title,...t.length>0?{log_ids:t}:{}}}(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 rg="iphone-13",rf=[{key:rg,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}}],rv=[{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}],ry={key:"mobile-393",label:"393px",width:393,density:3};function r_(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 rf.find(t=>t.key===e)??rf.find(e=>e.key===rg)??rf[0]}function rb(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rf["0"],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.key.startsWith("iphone")||e.key.startsWith("ipad");return{debugger:"web-sdk",density:e.density,screenWidth:e.width,screenHeight:e.height,containerWidth:e.width,containerHeight:e.height,statusBarHeight:e.statusBarHeight,safeArea:{marginTop:e.safeArea.top,marginBottom:e.safeArea.bottom,marginLeft:e.safeArea.left,marginRight:e.safeArea.right},topHeight:e.safeArea.top,bottomHeight:e.safeArea.bottom,devicePlatform:r?"iOS":"Android",deviceBrand:r?"Apple":"Google",deviceModel:e.label,screenOrientation:"portrait",...t}}function rw(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ry,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}}function rS(e,t){try{let e=t.trim()?JSON.parse(t):{};if(eK(e))return e;throw Error("expected a JSON object")}catch(t){throw Error(`${e}: ${t.message}`)}}function rx(e){let{onReopen:t}=e;return(0,s.jsxs)("div",{className:"wsd-runtime-empty",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-runtime-empty-icon"}),(0,s.jsx)("div",{className:"wsd-runtime-empty-title",children:"页面已关闭"}),(0,s.jsx)("div",{className:"wsd-runtime-empty-description",children:"当前页面栈为空,可从调试面板重新选择页面渲染。"}),(0,s.jsx)("button",{className:"wsd-runtime-empty-action",onClick:t,type:"button",children:"重新打开当前页面"})]})}function rI(e,t){let r=(0,e8.H)(e);return r.render((0,s.jsx)(rx,{onReopen:t})),()=>r.unmount()}function rE(e){return e??document.body}async function rC(e,t){var r;let n,a=rE(t),s=new CustomEvent("doubao:multi-media-broadcast",{bubbles:!0,composed:!0,detail:e});a.dispatchEvent(s),window.dispatchEvent(new CustomEvent("doubao:multi-media-broadcast",{detail:e}));let i=(r=e.mediaId,n=Array.from(rE(t).querySelectorAll("audio,video")),r?n.filter(e=>e.id===r||e.dataset.mediaId===r):n);return await Promise.all(i.map(t=>"play"===e.action?t.play():Promise.resolve(t.pause()))),{affected:i.length}}let rk=[],rN=new Map,rM=!1;function rR(e){for(let t of e)URL.revokeObjectURL(t),rN.delete(t)}function rT(){for(let e of rk.splice(0))rR(e)}function rA(e){var t;let r=rN.get(e);if(r)return r;let n=e.match(/^data:image\/([^;,]+)/i);if(null==n?void 0:n[1])return n[1].split("+")[0].toLowerCase();let a=e.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/);return(null==a||null==(t=a[1])?void 0:t.toLowerCase())??""}function rP(e){return new Promise((t,r)=>{let n=new Image;n.onload=()=>t(n),n.onerror=()=>r(Error(`failed to load image: ${e}`)),n.src=e})}async function rj(e){if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let t=await rP(e.src);return{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height,orientation:"up",path:e.src,type:rA(e.src)}}async function rD(e){if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let t=await rP(e.src),r=document.createElement("canvas"),n=e.compressedWidth??t.naturalWidth??t.width,a=e.compressedHeight??t.naturalHeight??t.height;r.width=n,r.height=a;let s=r.getContext("2d");if(!s)throw Error("canvas 2d context is not available");return s.drawImage(t,0,0,n,a),{tempFilePath:r.toDataURL("image/jpeg",Math.min(100,Math.max(0,e.quality??80))/100)}}let rL={enableHighAccuracy:!0,maximumAge:0,timeout:1e4};function rO(){return{browserAuthorization:"unknown",message:"未配置",tone:"muted",userAuthorization:"unknown"}}function rU(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")}class rq{browserAuthorization="unknown";browserLocation;browserWatchId;locationListeners=new Set;manualLocation;pendingBrowserRequest;revision=0;snapshot=rO();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.updatesActive&&(this.stopLocationUpdates(),this.emitLocation({status:"user_unauthorized"}))}async requestLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rL;return"granted"!==this.userAuthorization?{status:"user_unauthorized"}:this.manualLocation?{location:{...this.manualLocation,timestamp:Date.now()},status:"success"}:"granted"===this.browserAuthorization&&this.browserLocation?{location:this.browserLocation,status:"success"}:"denied"===this.browserAuthorization?this.createBrowserUnauthorizedResult():this.locateWithBrowser(e)}async requestBrowserLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rL;return this.manualLocation=void 0,this.locateWithBrowser(e)}setManualLocation(e){rU(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]:rL,t=await this.requestLocation(e);return"success"!==t.status?this.emitLocation(t):(this.updatesActive=!0,this.emitLocation(t),"browser"===t.location.source&&this.startBrowserWatch(e)),t}stopLocationUpdates(){this.updatesActive=!1,this.clearBrowserWatch()}createBusinessLocationInfo(e){let t=function(){try{return 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=rO(),this.emitSnapshot()}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,s;if(rU({latitude:t,longitude:e}),e<72.004||e>137.8347||t<.8293||t>55.8271)return{latitude:t,longitude:e};let i=-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*(s=t-35)+.1*a*a+.1*a*s+.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+(i=180*i/(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)}}let r$=new rq,rB=new Map,rF={"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 rW(e,t){return`${e||"unknown-app"}:${t}`}function rH(e){return rF[e]??{description:"需要获得你的授权后才能继续使用此功能。",title:`申请获取你的${e.replace(/^scope\./,"")||"相关"}权限`}}async function rz(e){var t;let{appId:r,appIcon:n,appName:a,presenter:s,scope:i,skipDialogIfDenied:o=!1}=e,l=r||"unknown-app",d=rB.get(rW(l,i));if("granted"===d)return!0;if("denied"===d&&o)return!1;if(!s)return"denied"!==d;let u=await s({appId:l,appIcon:n,appName:a||"智能服务",scope:i,...rH(i)});return t=u?"granted":"denied",rB.set(rW(l,i),t),u}function rV(){throw Error("Simulator UI presenter is unavailable")}function rG(){return{chooseLocation:async()=>rV(),hideLoading:rV,hideToast:rV,showActionSheet:async()=>rV(),showBottomSheet:async()=>rV(),showLoading:rV,showModal:async()=>rV(),showToast:rV}}function rK(){a&&window.removeEventListener("beforeunload",a),a=void 0}function rJ(e,t){return S(e,"user_unauthorized"===t.status?"user permission denied":t.message)}async function rX(e){let t=await rz({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.userLocation",skipDialogIfDenied:!0});return r$.updateUserAuthorization(t),t}function rQ(e){let t={};return e.forEach((e,r)=>{t[r]=e}),t}function rZ(e){let t=(e.method??"GET").toUpperCase(),r=new Headers(e.header??{"content-type":"application/json"});return{body:"GET"!==t&&"HEAD"!==t?function(e,t){var r;if(null==e)return;if("string"==typeof e||e instanceof ArrayBuffer)return e;let n=(null==(r=t.get("content-type"))?void 0:r.toLowerCase())??"";if(n.includes("application/x-www-form-urlencoded")&&"object"==typeof e){let t=new URLSearchParams;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,String(n))}),t.toString()}return n.includes("application/json")||"object"==typeof e?JSON.stringify(e):String(e)}(e.data,r):void 0,headers:rQ(r),method:t,url:"string"==typeof e.url?e.url:""}}async function rY(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rZ(e);if(!e.url)throw Error("url must be a non-empty string");let r=await fetch(e.url,{body:t.body,headers:t.headers,method:t.method}),n=e.dataType??"json",a="arraybuffer"===n?await r.arrayBuffer():await r.text().then(e=>"string"===n||0===e.length?e:JSON.parse(e));return{statusCode:r.status,header:rQ(r.headers),data:a}}let r0=new Set,r1=new WeakSet,r2=0;function r3(){return navigator.connection}function r4(){var e;let t,r=r3(),n=null==r?void 0:r.effectiveType;return{isConnected:!1!==navigator.onLine,networkType:(t=null==(e=r3())?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 r5(){return{timestamp:performance.now()/1e3,wallTime:Date.now()/1e3}}function r6(e){for(let t of r0)try{t(e)}catch(e){console.error("Failed to record doubao.request in Chrome DevTools",e)}}function r8(){let e=r4();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function r7(e,t){let r=null==e?void 0:e[t];return"string"==typeof r?r.trim():""}async function r9(e,t,r){let n=await rz({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:t,skipDialogIfDenied:r});return r$.isLocationScope(t)&&r$.updateUserAuthorization(n),n}let ne="app_id_missing",nt="cashier_unavailable",nr="create_order_failed",nn="developer_order_exists",na="login_credential_invalid",ns="login_credential_missing",ni="login_authorization_failed",no="login_authorization_unsupported",nl="login_state_invalid",nd="login_session_unavailable",nu="payment_amount_invalid",nc="payment_authorization_invalid",np="payment_cancelled",nm="payment_data_invalid",nh="payment_data_missing",ng="payment_data_unavailable",nf="payment_data_unavailable_with_sign",nv="payment_data_unsupported",ny="payment_failed",n_="payment_method_unavailable",nb="payment_order_invalid",nw="payment_parameter_missing",nS="payment_params_invalid",nx="payment_params_unavailable",nI="payment_sign_params_invalid",nE="payment_sign_params_unavailable",nC="payment_incomplete",nk="privacy_state_unavailable",nN="privacy_authorization_failed",nM="pre_order_failed",nR="phone_authorization_failed",nT="request_format_invalid",nA="request_params_invalid",nP="sandbox_resource_not_found",nj="sandbox_service_unavailable",nD="sandbox_session_expired",nL="sandbox_session_forbidden",nO="sign_order_failed",nU="sign_order_already_exists",nq="sign_order_not_found",n$="sign_order_params_invalid",nB="sign_order_status_invalid",nF="sign_order_create_failed",nW="sign_page_params_invalid",nH="sign_page_unavailable",nz="sign_page_data_unavailable",nV="请求暂时无法完成,请稍后重试;如持续失败,请提供 log_id";class nG extends Error{code;details;constructor(e,t={}){super(nJ(e,t)),this.code=e,this.details=t,this.name="SandboxError"}}class nK extends Error{remoteCode;options;constructor(e,t,r={}){super(t),this.remoteCode=e,this.options=r,this.name="SandboxRemoteError"}}function nJ(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(e){case ne:return"当前未配置应用 ID,请先完成应用配置。";case nt:return"无法打开模拟器收银台,请刷新模拟器后重试。";case nr:return"暂时无法创建订单,请检查签名参数后稍后重试;如持续失败,请提供 log_id";case nn:return"开发者订单号已存在,请查询原订单";case na:return"登录失败:登录凭证已过期或已使用,请重新发起登录。";case ns:return"登录失败:成功登录回调未携带业务登录凭证,请检查登录实现。";case"login_failed":return"登录失败:无法完成模拟器登录,请检查模拟器会话后重试。";case"login_info_unavailable":return"登录信息暂时不可用,请稍后重试;如持续失败,请提供 log_id";case ni:return"暂时无法完成登录授权,请重新发起授权";case no:return"当前 Sandbox 无法完成该授权请求,请检查授权方式和会话配置";case"login_permission_denied":return"登录失败:开发者账号没有该应用的调试权限,请检查应用归属和账号状态。";case nl:return"用户登录状态已失效,请重新登录";case nd:return"登录失败:模拟器会话不可用,请登录开发者账号后重新打开模拟器。";case"payment_already_paid":return"订单已完成支付,请勿重复提交。";case nu:return"支付金额无效,请使用最小货币单位的整数,并由业务服务端生成金额。";case nc:return"支付授权校验失败,请确认 data 和 dbAuthorization 使用同一个 dev.key 生成,并且模拟器配置了匹配的 dev.csr。";case np:return"已取消支付。";case nm:return"支付数据格式无效,请检查业务服务端生成的 pay_data。";case nh:{let e=t.field?({id:"支付方式 ID",name:"支付方式名称",pay_order_no:"支付订单号",pay_status:"支付状态",trade_no:"交易号"})[t.field]||t.field:"必要字段";return`支付数据缺少${e},请检查业务服务端生成的 pay_data。`}case ng:return"无法打开收银台:模拟器未返回支付数据,请检查订单状态和预下单响应。";case nf:return"无法打开支付签约收银台:模拟器未返回支付数据,请检查签约参数和订单状态。";case nv:return"当前支付数据不支持模拟器收银台,请检查模拟器支付配置。";case ny:return nV;case"payment_login_required":return"支付需要先登录,请完成模拟器登录并绑定支付账户后重试。";case n_:return"支付数据中没有可用的支付方式,请检查模拟器支付配置。";case"payment_order_expired":return"支付订单已过期,请重新创建订单后重试。";case nb:return"订单不存在或不属于当前应用";case nw:{let e=t.key||"该参数";return`缺少支付参数,请提供${({data:"业务服务端生成的 data",dbAuthorization:"业务服务端生成的 dbAuthorization",orderId:"requestOrder 返回的 orderId",signData:"业务服务端生成的 signData",signDbAuthorization:"业务服务端生成的 signDbAuthorization"})[e]||e}。`}case nS:return"请求参数不正确,请检查订单信息和金额";case nx:return"暂时无法获取支付参数,请检查订单号后重试;如持续失败,请提供 log_id";case nI:return"请求参数不正确,请检查订单号和签约信息";case nE:return"暂时无法获取支付参数,请稍后重试;如持续失败,请提供 log_id";case nC:return"模拟支付未完成,请检查支付方式和订单状态后重试;如持续失败,请提供 log_id";case nk:return"暂时无法读取或保存授权状态,请稍后重试";case nR:return"手机号授权失败:无法获取手机号授权凭证,请重试或使用其他登录方式。";case nN:return"隐私授权失败:请刷新模拟器后重试。";case nM:return"预下单失败:模拟器未返回订单 ID,请检查业务服务端预下单响应。";case nT:return"请求格式不正确,请检查后重试";case nA:return"请求参数不正确,请检查必填字段和字段格式";case nP:return"未找到沙箱会话或相关资源,请重新创建后重试";case nj:return"沙箱服务暂时不可用,请稍后重试;如持续失败,请提供 log_id";case nD:return"沙箱会话已过期,请重新启动调试会话";case nL:return"当前沙箱会话无权访问该应用,请检查应用和会话是否匹配";case nO:return"创建签约订单失败:模拟器未返回签约订单 ID,请检查签约参数。";case nU:return"开发者签约单号已存在,请查询原签约单";case nq:return"签约单不存在或不属于当前应用";case n$:return"签约单参数无效,请检查单号、应用和有效期";case nB:return"当前签约单状态不允许继续签约";case nF:return"暂时无法创建签约单,请检查签名参数后重试;如持续失败,请提供 log_id";case nW:return"签约单参数无效,请检查单号、应用和有效期";case nH:return"暂时无法获取签约页,请稍后重试;如持续失败,请提供 log_id";case nz:return"打开签约页面失败:模拟器未返回签约数据,请检查签约订单状态。";default:return nV}}function nX(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}}function nQ(e,t){if(400===t)return nT;switch(e){case 400:return nA;case 401:return nD;case 403:return nL;case 404:return nP;case 500:return nj;default:return}}function nZ(e,t,r){switch(e){case 500:return"payment"===r?nC:nj;case 4201:return nc;case 0x1dcd6501:if(t===nM)return nS;if(t===nf)return nI;if(t===nO)return n$;if(t===nz)return nW;return nS;case 0x1dcdb322:return nn;case 5e8:if(t===nM)return nr;if(t===nf)return nE;if(t===nO)return nF;if(t===nz)return nH;return nx;case 0x1dcdb325:return t===nz?nq:nb;case 0x1dcdb327:return nU;case 0x1dcdb328:return nB;default:return void 0===e||0===e?t:ny}}function nY(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("code"===r.errorField){let t=nQ(e,r.httpStatus);if(t)return t}if("data.error_code"===r.errorField&&40001===e)return no;if("err_code"===r.errorField){if(401===e)return nA;if(402===e)return nl;if(501===e)return nk}switch(e){case -1:return nd;case 1001:return"phone"===t?nR:na;case 4001:return na;case 2001:return nN;case 502:return ni;case 402:return nl;case 501:return nk;case 400:return nA;default:return nj}}function n0(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nV;if(e instanceof nG)return nJ(e.code,e.details);if(e instanceof nK){let t="code"===e.options.errorField?nQ(e.remoteCode,e.options.httpStatus):void 0;return nJ("payment"===e.options.operation?nZ(e.remoteCode,ny,e.options.operation):t||nZ(e.remoteCode,ny))}return t}function n1(e,t){return e instanceof nG?e:new nG(e instanceof nK?nY(e.remoteCode,t,e.options):nj)}function n2(e,t){let r=nX(e.err_code);if(void 0!==r&&0!==r)throw new nG(nY(r,t,{errorField:"err_code"}))}function n3(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:{code:nX(e.code),logId:"string"==typeof e.log_id?e.log_id:void 0}}function n4(e,t){let{code:r,logId:n}=n3(e);if(void 0!==r&&0!==r)throw new nK(r,`Sandbox 请求失败,错误码为 ${String(r)}。`,{errorField:"code",httpStatus:t,logId:n})}let n5="web-sdk-debugger",n6=[{id:"douyin",name:"抖音支付"}];async function n8(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}=n3(r);if(!t.ok)throw new nK(n,`Sandbox 代理请求失败,HTTP 状态码为 ${t.status}。`,{errorField:"code",httpStatus:t.status,logId:a});return n4(r,t.status),r}let n7=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};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)}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)}}({baseURL:"",request:n8});function n9(e,t){if(!e.data)throw Error(e.message||`${t} returned empty data`);return e.data}async function ae(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return n9(await n7.PullSandboxNotices(e),"PullSandboxNotices")}async function at(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return n9(await n7.PullSandboxTasks(e),"PullSandboxTasks")}async function ar(e){return n9(await n7.RemoveSandboxTaskFromUser({task_id:e}),"RemoveSandboxTaskFromUser").removed_task}async function an(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 n7.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)}`)}function aa(e){var t;let r=(null==(t=e.getAppId)?void 0:t.call(e))||e.appId;if(!r)throw new nG(ne);return r}function as(e,t){if(!e||"object"!=typeof e)return"";let r=e[t];return"string"==typeof r?r:""}function ai(e,t){let r=as(e,t).trim();if(!r)throw new nG(nw,{key:t});return r}function ao(e,t){let r=e[t];if("string"!=typeof r||!r.trim())throw new nG(nh,{field:t});return r.trim()}function al(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments.length>4?arguments[4]:void 0,s=nX(t.err_code),i=s??(a instanceof nK?a.remoteCode:void 0)??-1,o=t.log_id??(a instanceof nK?a.options.logId:void 0),l=a?n0(a,nJ(r)):nJ(nZ(s,r)),d={...n?{code:i}:{},errNo:String(i),errMsg:l,...o?{errLogId:o}:{}};return{type:"callback",callbackId:e.callbackId,params:{code:0,data:d,errNo:i,errMsg:l,msg:l}}}async function ad(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return await t()}catch(t){return al(e,{},ny,r,t)}}async function au(e,t){let r=function(e){let t;try{t=JSON.parse(e)}catch{throw new nG(nm)}if(!t||"object"!=typeof t||Array.isArray(t))throw new nG(nm);let r=t;if("sandbox_cashier"!==r.type)throw new nG(nv);let n="string"==typeof r.total_amount?r.total_amount.trim():"";if(!n||!/^\d+$/.test(n))throw new nG(nu);return{paymentTypes:function(e){if(!Array.isArray(e)||0===e.length)throw new nG(n_);let t=e.map(e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new nG(nm);return{id:ao(e,"id"),name:ao(e,"name")}});if(new Set(t.map(e=>{let{id:t}=e;return t})).size!==t.length)throw new nG(nm);return t}(r.pay_types??n6),payOrderNo:ao(r,"pay_order_no"),payStatus:ao(r,"pay_status"),totalAmount:n,tradeNo:ao(r,"trade_no"),type:"sandbox_cashier"}}(e);if(!t.showSandboxCashier)throw new nG(nt);if(!await t.showSandboxCashier(r,async e=>{if(!r.paymentTypes.some(t=>{let{id:r}=t;return r===e}))throw new nG(n_);try{await n7.SandboxPay({trade_no:r.tradeNo,pay_type:e})}catch(e){if(e instanceof nK&&"code"===e.options.errorField&&500===e.remoteCode)throw new nK(e.remoteCode,e.message,{...e.options,operation:"payment"});throw e}}))throw new nG(np)}async function ac(e,t){let r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"user_info",a=t?"phone":"login";try{r=await n7.SandboxIssueLoginCode({aid:"482431",client_key:aa(e),scope:n,source:"jsb",...t?{exchange_type:t}:{}})}catch(e){throw n1(e,a)}var s,i,o=nX(null==(s=r.data)?void 0:s.error_code);let l=nX(o);if(void 0!==l&&0!==l)throw new nG(nY(l,a,{errorField:"data.error_code"}));let d=null==(i=r.data)?void 0:i.code;if(!d)throw new nG(nj);return d}async function ap(e){try{let t=void 0!==e.locationInfo,r=await n7.UpdateSandboxBusinessInfo({...e.csrPem||t?{csr_pem:e.csrPem??""}:{},...t?{location_info:e.locationInfo}:{},phone_num:e.phoneNum,sandbox_session_id:""});return n4(r),r}catch(t){let e=Error(t.message);throw e.logId=t instanceof nK?t.options.logId:t&&"object"==typeof t&&"logId"in t&&"string"==typeof t.logId?t.logId:void 0,e}}async function am(e){return ap(e)}async function ah(e){return ap({csrPem:"",locationInfo:e,phoneNum:""})}async function ag(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}r(45249);let af=["aztec","codabar","code_39","code_93","code_128","data_matrix","ean_8","ean_13","itf","pdf417","qr_code","upc_a","upc_e"],av={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 ay(e){let t=e.getSupportedFormats;return"function"==typeof t?new Set(await t()):null}function a_(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,af.includes(r)?"pdf417"===r?"PDF_417":r.toUpperCase():"QR_CODE")}}async function ab(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 aw(e,t,r,n,a){return t()?Promise.resolve():new Promise((s,i)=>{let o=0,l=()=>{for(let t of(window.clearTimeout(o),r))e.removeEventListener(t,d);e.removeEventListener("error",u)},d=()=>{t()&&(l(),s())},u=()=>{l(),i(Error(a))};for(let t of(o=window.setTimeout(()=>{l(),i(Error(a))},n),r))e.addEventListener(t,d);e.addEventListener("error",u)})}async function aS(e,t){e.srcObject=t,await aw(e,()=>e.readyState>=HTMLMediaElement.HAVE_METADATA,["loadedmetadata"],3e3,"Camera stream started, but video metadata was not loaded"),await e.play(),await aw(e,()=>e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA,["loadeddata","canplay","playing"],3e3,"Camera stream started, but no video frame was rendered")}async function ax(e,t){var r;let n,a=globalThis.BarcodeDetector;if(!a)throw Error("BarcodeDetector is not supported in this browser");let s=await ay(a),i=[...new Set((null==(r=e.scanType)?void 0:r.length)?e.scanType.flatMap(e=>av[e]):af)].filter(e=>!s||s.has(e));if(0===i.length)throw Error("Requested scanType is not supported in this browser");let o=new a({formats:i}),l=!1,d=!1,u=0,c=null,p=null,m=()=>{null==c||c.getTracks().forEach(e=>e.stop()),c=null,p&&(p.srcObject=null)},h=()=>{l||(l=!0,window.cancelAnimationFrame(u),m(),null==n||n.close())};try{return await new Promise((r,a)=>{let s=e=>{h(),e()},i=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?s(()=>r(a_(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:()=>s(()=>a(Error("scanCode canceled"))),onCapture:()=>i(!0),onFile:e=>{l||(null==n||n.setMessage("正在识别图片..."),ab(o,e).then(e=>{let t=e[0];t?s(()=>r(a_(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 s(()=>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,aS(t,e))).then(()=>{if(l)return;let e=()=>{l||(i(!1),u=window.requestAnimationFrame(e))};e()}).catch(t=>{if(l)return;let r=t instanceof Error?t.message:String(t);if(m(),e.onlyFromCamera){null==n||n.setMessage(r),s(()=>a(t instanceof Error?t:Error(r)));return}null==n||n.setMessage(`无法使用摄像头,请从相册选择二维码或条形码图片:${r}`)})}}})})}catch(e){throw h(),e}}let aI="doubao-web-sdk-debugger-vibration-style",aE="doubao-web-sdk-debugger-screen-vibrating",aC={heavy:4,light:1,medium:2},ak=0,aN=null;function aM(e){e.classList.remove(aE),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-distance"),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-duration")}function aR(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(aI))return;let e=document.createElement("style");e.id=aI,e.textContent=`
|
|
6
|
-
@keyframes doubao-web-sdk-debugger-screen-vibrate {
|
|
7
|
-
0%, 100% { transform: translate3d(0, 0, 0); }
|
|
8
|
-
12.5% { transform: translate3d(calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0, 0); }
|
|
9
|
-
25% { transform: translate3d(var(--doubao-web-sdk-debugger-vibrate-distance), 0, 0); }
|
|
10
|
-
37.5% { transform: translate3d(0, calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0); }
|
|
11
|
-
50% { transform: translate3d(0, var(--doubao-web-sdk-debugger-vibrate-distance), 0); }
|
|
12
|
-
62.5% { transform: translate3d(var(--doubao-web-sdk-debugger-vibrate-distance), var(--doubao-web-sdk-debugger-vibrate-distance), 0); }
|
|
13
|
-
75% { transform: translate3d(calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0); }
|
|
14
|
-
87.5% { transform: translate3d(var(--doubao-web-sdk-debugger-vibrate-distance), 0, 0); }
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
.${aE} {
|
|
18
|
-
animation: doubao-web-sdk-debugger-screen-vibrate var(--doubao-web-sdk-debugger-vibrate-duration) linear;
|
|
19
|
-
}
|
|
20
|
-
`,document.head.append(e)})(),window.clearTimeout(ak),n=r||(document.body??document.documentElement),aN&&aN!==n&&aM(aN),aN=n,aM(n),n.style.setProperty("--doubao-web-sdk-debugger-vibrate-distance",`${t}px`),n.style.setProperty("--doubao-web-sdk-debugger-vibrate-duration",`${e}ms`),n.offsetWidth,n.classList.add(aE),ak=window.setTimeout(()=>{aM(n),aN===n&&(aN=null)},e+50)}}let aT="socketStatusChanged",aA="socketDataReceived",aP=1,aj=new Map;function aD(e,t,r){var n,a;null!=e&&null!=(n=e.apiRegistry)&&n.emitEvent(t,r)||null==e||null==(a=e.emitEvent)||a.call(e,t,r)}function aL(){return{...W(),platform:"devtools_web"}}function aO(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=(null==(e=r.baseAPIRegistry)?void 0:e.fork())??new N(ef);return n.registerMany(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.uiPresenter??rG(),r=e.scanCodePresenter;return{"doubao.request":function(e){if(r1.has(e))return e;let t=(t,r)=>{let n=`wsd-request-${++r2}`,a=t.params??{},s=function(e){try{return rZ(e)}catch{return}}(a);r6({phase:"request",request:s??{headers:{},method:"string"==typeof a.method?a.method.toUpperCase():"GET",url:"string"==typeof a.url?a.url:""},requestId:n,...r5()});let i=e=>r6({errorText:e,phase:"failure",requestId:n,...r5()}),o=e=>((null==e?void 0:e.params.code)===1?r6({phase:"response",requestId:n,response:e.params.data,...r5()}):i((null==e?void 0:e.params.errMsg)??(null==e?void 0:e.params.msg)??"doubao.request failed"),e),l=e=>{throw i(e instanceof Error?e.message:String(e)),e};try{let n=e(t,r,s);return n instanceof Promise?n.then(e=>o(e),l):o(n)}catch(e){return l(e)}};return r1.add(t),t}(e.requestHandler??(async(e,t,r)=>w(e,await rY(e.params,r)))),"doubao.getDeviceInfo":{handler:e=>w(e,aL()),syncResult:aL},"doubao.getNetworkType":{handler:e=>w(e,r8()),syncResult:r8},"doubao.scanCode":async e=>{if(!r)throw Error("Simulator scan-code presenter is unavailable");return w(e,await ax(e.params,r))},"doubao.vibrateLong":async t=>(await void aR(400,3,e.vibrationContainer),w(t,{})),"doubao.vibrateShort":async t=>(await function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,{type:r="medium"}=e;aR(15,aC[r],t)}(t.params,e.vibrationContainer),w(t,{})),...(!rM&&"u">typeof window&&(window.addEventListener("pagehide",rT),rM=!0),{"doubao.chooseImage":async e=>{var t;let r,n,a,s,i;return w(e,await (a=(n=(r="string"==typeof(t=e.params).imageId?document.getElementById(t.imageId):null)instanceof HTMLInputElement?r:document.createElement("input"))!==r,s=t.count??9,n.type="file",n.accept="image/*",n.multiple=s>1,n.capture=(i=Array.isArray(t.sourceType)?t.sourceType:[]).includes("album")?"":i.includes("user")?"user":i.some(e=>"camera"===e||"environment"===e)?"environment":"",n.style.display="none",n.value="",a&&document.body.append(n),new Promise((e,t)=>{let r=()=>{n.removeEventListener("change",i),n.removeEventListener("cancel",o),a&&n.remove()},i=()=>{let a,i=Array.from(n.files??[]).slice(0,s);if(r(),0===i.length)return void t(Error("chooseImage was cancelled"));let o=[];try{a=i.map(e=>{let t=URL.createObjectURL(e);o.push(t);let r=e.type.startsWith("image/")?e.type.slice(6).split("+")[0].toLowerCase():rA(e.name);return r&&rN.set(t,r),{path:t,size:e.size,type:e.type,originalFileObj:e}})}catch(e){rR(o),t(e);return}for(rk.push(o);rk.length>20;)rR(rk.shift()??[]);e({tempFilePaths:a.map(e=>e.path),tempFiles:a})},o=()=>{r(),t(Error("chooseImage was cancelled"))};n.addEventListener("change",i,{once:!0}),n.addEventListener("cancel",o,{once:!0}),n.click()})))},"doubao.getImageInfo":async e=>w(e,await rj(e.params)),"doubao.compressImage":async e=>w(e,await rD(e.params)),"doubao.saveImageToPhotosAlbum":e=>{var t=e.params;if("string"!=typeof t.filePath||!t.filePath)throw Error("filePath must be a non-empty string");let r=document.createElement("a");return r.href=t.filePath,r.download=t.filePath.split("/").pop()||"image",r.style.display="none",document.body.append(r),r.click(),r.remove(),w(e,{})}}),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.chooseLocation??rG().chooseLocation;return{"doubao.getLocation":async t=>{var r;await rX(e);let n=await r$.requestLocation(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{enableHighAccuracy:void 0===e.mode||2===e.mode,maximumAge:"number"==typeof e.maxCacheMs&&e.maxCacheMs>=0?e.maxCacheMs:0,timeout:"number"==typeof e.timeoutMs&&e.timeoutMs>=0?e.timeoutMs:3e4}}(t.params));return"success"===n.status?w(t,{latitude:(r=n.location).latitude,longitude:r.longitude,timestamp:new Date(r.timestamp).toISOString(),speed:r.speed,accuracy:r.accuracy}):rJ(t,n)},"doubao.chooseLocation":async r=>await rX(e)?w(r,await t(r.params)):S(r,"user permission denied"),"doubao.openLocation":async t=>{if(!await rX(e))return S(t,"user permission denied");var r=t.params;if("number"!=typeof r.latitude||"number"!=typeof r.longitude)throw Error("latitude and longitude must be numbers");let n=new URL("https://www.google.com/maps/search/");return n.searchParams.set("api","1"),n.searchParams.set("query",`${r.latitude},${r.longitude}`),window.open(n.toString(),"_blank","noopener,noreferrer"),w(t,{})},"doubao.startLocationUpdate":async t=>{await rX(e);let r=await r$.startLocationUpdates();return"success"===r.status?w(t,{}):rJ(t,r)},"doubao.stopLocationUpdate":e=>(r$.stopLocationUpdates(),w(e,{}))}}({...e,chooseLocation:t.chooseLocation}),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.presenter??rG();return{"applet.showToast":e=>(t.showToast(e.params),w(e,{})),"doubao.hideToast":e=>(t.hideToast(),w(e,{})),"doubao.showLoading":e=>(t.showLoading(),w(e,{})),"doubao.hideLoading":e=>(t.hideLoading(),w(e,{})),"doubao.showModal":async e=>w(e,await t.showModal(e.params)),"doubao.showActionSheet":async e=>w(e,await t.showActionSheet(e.params)),"doubao.showBottomSheet":async e=>w(e,await t.showBottomSheet(e.params)),"doubao.enableAlertBeforeUnload":e=>{var t;let r;return t=e.params,rK(),r="string"==typeof t.message?t.message:"",a=e=>(e.preventDefault(),e.returnValue=r,r),window.addEventListener("beforeunload",a),w(e,{})},"doubao.disableAlertBeforeUnload":e=>(rK(),w(e,{})),"doubao.hideKeyboard":e=>(document.activeElement.blur(),w(e,{}))}}({presenter:t}),...{"doubao.connectSocket":(e,t)=>w(e,function(e,t){if("string"!=typeof e.url||!e.url)throw Error("url must be a non-empty string");let r=aP++,n=new WebSocket(e.url,e.protocols);return n.binaryType="arraybuffer",aj.set(r,n),n.addEventListener("open",()=>{aD(t,aT,{socketTaskId:r,status:"connected",header:{},protocolType:n.protocol})}),n.addEventListener("message",e=>{!function(e,t,r){if("string"==typeof r)return aD(e,aA,{socketTaskId:t,data:r,dataType:"string"});if(r instanceof ArrayBuffer){let n;aD(e,aA,{socketTaskId:t,data:(n="",new Uint8Array(r).forEach(e=>{n+=String.fromCharCode(e)}),btoa(n)),dataType:"base64"})}}(t,r,e.data)}),n.addEventListener("close",e=>{aj.delete(r),aD(t,aT,{socketTaskId:r,status:"closed",code:e.code,reason:e.reason,protocolType:n.protocol})}),n.addEventListener("error",()=>{aj.delete(r),aD(t,aT,{socketTaskId:r,status:"failed",errMsg:"WebSocket error",protocolType:n.protocol})}),{socketTaskId:r}}(e.params,t)),"doubao.sendSocketData":e=>{var t;return function(e){let t=e.socketTaskId,r="number"==typeof t?aj.get(t):void 0;if(!r)throw Error(`socket not found: ${t}`);let n=e.data;if("string"!=typeof n&&!(n instanceof ArrayBuffer))throw Error("data must be a string or ArrayBuffer");r.send(n)}({socketTaskId:(t=e.params).socketTaskId,data:"base64"===t.dataType&&"string"==typeof t.data?function(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r.buffer}(t.data):t.data}),w(e,{})},"doubao.closeSocket":e=>{var t=e.params;let r=t.socketTaskId,n="number"==typeof r?aj.get(r):void 0;if(!n)throw Error(`socket not found: ${r}`);return n.close(t.code,t.reason),w(e,{})}},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.requestOrder":t=>ad(t,async()=>{let r=await n7.SandboxRequestOrder({app_key:aa(e),data:ai(t.params,"data"),db_authorization:ai(t.params,"dbAuthorization")});return r.err_code||!r.order_id?al(t,r,nM):w(t,{orderId:r.order_id,logId:r.log_id||""})}),"doubao.getOrderPayment":t=>ad(t,async()=>{let r=ai(t.params,"orderId"),n=await n7.SandboxGetOrderPayment({app_key:aa(e),aweme_bind_status:!0,order_id:r,platform_signed_pt_code:as(t.params,"platformSignedPtCode").trim()||void 0});return n.err_code||!n.pay_data?al(t,n,ng):(await au(n.pay_data,e),w(t,{orderId:r,logId:n.log_id||""}))}),"doubao.getOrderPaymentWithSign":t=>ad(t,async()=>{let r=ai(t.params,"orderId"),n=await n7.SandboxGetOrderPaymentWithSign({app_key:aa(e),aweme_bind_status:!0,order_id:r,sign_data:ai(t.params,"signData"),sign_db_authorization:ai(t.params,"signDbAuthorization")});return n.err_code||!n.pay_data?al(t,n,nf):(await au(n.pay_data,e),w(t,{orderId:r,logId:n.log_id||""}))}),"doubao.getPlatformSignInfo":e=>w(e,{signInfo:""}),"doubao.createSignOrder":t=>ad(t,async()=>{let r=await n7.SandboxCreateSignOrder({app_key:aa(e),data:ai(t.params,"data"),db_authorization:ai(t.params,"dbAuthorization")});return r.err_code||!r.auth_order_id?al(t,r,nO):w(t,{authOrderId:r.auth_order_id,logId:r.log_id||""})}),"doubao.sign":t=>ad(t,async()=>{let r=await n7.SandboxGetSignPageData({app_key:aa(e),auth_order_id:ai(t.params,"orderId"),aweme_bind_status:!0});return r.err_code||!r.data?al(t,r,nz,!0):w(t,{})},!0),"doubao.login":async t=>w(t,{code:await ac(e)}),"doubao.loginWithDoubaoWidget":e=>w(e,{result:!0}),"doubao.postLoginResult":async t=>{var r,n,a,s;let i,o=t.params;if(!1===o.result)return null==(a=e.onPrivacyLoginCardClose)||a.call(e,"login"),await (null==(s=e.onGrantingCompleted)?void 0:s.call(e,"login",{noLogin:!0})),w(t,{});let l=as(o,"code");if(!l)throw new nG(ns);try{i=await n7.SandboxApiExchangeCode({app_key:aa(e),code:l,version_tag:n5})}catch(e){throw n1(e,"login")}return n2(i,"login"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"login"),await (null==(n=e.onGrantingCompleted)?void 0:n.call(e,"login")),w(t,{})},"doubao.getPrivacySetting":async t=>{var r;let n;try{n=await n7.SandboxApiCheckPrivacyOrLoginStatus({app_key:aa(e),check_type:1,version_tag:n5})}catch(e){throw n1(e,"privacy")}return n2(n,"privacy"),w(t,{needAuthorization:(null==(r=n.data)?void 0:r.PrivacyAgreed)===!1})},"applet.agreePrivacyAuthorization":async t=>{var r,n;let a;try{a=await n7.SandboxApiAcceptPrivacy({app_key:aa(e)})}catch(e){throw n1(e,"privacy")}return n2(a,"privacy"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"privacy"),await (null==(n=e.onGrantingCompleted)?void 0:n.call(e,"privacy")),w(t,{result:!0})},"applet.getPhoneNumber":async t=>w(t,{code:await ac(e,"profile","user_info,mobile"),message:"success"}),"applet.openLoginPage":t=>{let r=as(t.params,"url");if(r){var n;null==(n=e.onCustomLoginNavigate)||n.call(e,r)}return w(t,{})},"applet.closePrivacyLoginCard":t=>{var r;return null==(r=e.onPrivacyLoginCardClose)||r.call(e,as(t.params,"type")),w(t,{})},"applet.reportAppLog":e=>w(e,{}),"applet.open":e=>{let t=as(e.params,"schema");return t&&window.open(t,"_blank","noopener,noreferrer"),w(e,{})},"doubao.__debuggerUpdateSandboxBusinessInfo":async e=>{let t=e.params,r=as(t,"csrPem"),n=as(t,"locationInfo");return w(e,await ap({...r?{csrPem:r}:{},...n?{locationInfo:n}:{},phoneNum:as(t,"phoneNum")}))},...e.onCustomLoginNavigate?{"doubao.navigateTo":t=>{let r=as(t.params,"url");if(r){var n;null==(n=e.onCustomLoginNavigate)||n.call(e,r)}return w(t,{})}}:{}}}(e),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.authorize":async t=>{let r=r7(t.params,"scope");return r?await r9(e,r,!1)?w(t,{}):S(t,"user permission denied"):S(t,"scope is required")},"doubao.operateRecorder":async t=>"start"!==r7(t.params,"operationType")||await r9(e,"scope.record",!1)?w(t,{}):S(t,"user permission denied")}}(e),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.sendFollowUpMessage":async t=>{if(!e.sendFollowUpMessage)throw Error("sendFollowUpMessage is not configured in web-sdk-debugger");return await e.sendFollowUpMessage(function(e){let t=e.content;if(!Array.isArray(t)||0===t.length)throw Error("content must be a non-empty array");let r=!1;for(let e of t){if(!eK(e))throw Error("content items must be objects");if("text"===e.type){if("string"!=typeof e.text||!e.text.trim())throw Error("text content must be a non-empty string");r=!0;continue}if("api/call"===e.type){if(!r)throw Error("api/call content must follow text content");if(!eK(e.data)||"string"!=typeof e.data.name||!e.data.name.trim()||!eK(e.data.arguments))throw Error("api/call content must include a name and arguments object");continue}if("responseHint"===e.type){if(!eK(e.data)||void 0!==e.data.userAction&&"string"!=typeof e.data.userAction||void 0!==e.data.responseGuidance&&"string"!=typeof e.data.responseGuidance)throw Error("responseHint content must include valid string guidance fields");continue}throw Error('content type must be "text", "api/call", or "responseHint"')}if(!r)throw Error("content must include a non-empty text message");return{content:t,prompt:t.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}}(t.params)),w(t,{})},"doubao.multiMediaBroadcast":async t=>w(t,await rC(function(e){if("play"!==e.action&&"pause"!==e.action)throw Error('action must be "play" or "pause"');return{action:e.action,mediaId:"string"==typeof e.mediaId&&e.mediaId.trim()?e.mediaId.trim():void 0}}(t.params),e.multiMediaBroadcastContainer))}}(e)}}({...r,requestHandler:r.requestHandler??(null==(t=r.baseAPIRegistry)?void 0:t.get("doubao.request"))}),{override:!0}),n.registerEventSources({...{"doubao.onNetworkStatusChange":e=>{var t;let r;return t=t=>e({isConnected:t.isConnected,networkType:t.networkType}),addEventListener("online",r=()=>t(r4())),addEventListener("offline",r),()=>{removeEventListener("online",r),removeEventListener("offline",r)}}},...{"doubao.onLocationChange":e=>r$.subscribeLocation(t=>{var r;"success"===t.status&&e({latitude:(r=t.location).latitude,longitude:r.longitude,speed:r.speed,accuracy:r.accuracy,altitude:r.altitude,verticalAccuracy:r.altitudeAccuracy,horizontalAccuracy:r.accuracy})}),"doubao.onLocationChangeError":e=>r$.subscribeLocation(t=>{"success"!==t.status&&e("user_unauthorized"===t.status?{errMsg:"user permission denied"}:{errCode:t.code,errMsg:t.message})})},...{[aT]:()=>void 0,[aA]:()=>void 0}},{override:!0}),n}function aU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{apiRegistry:e.apiRegistry??aO(e),runtimeHost:e.runtimeHost??{mountRuntimeEmptyState:rI},scanCodePresenter:e.scanCodePresenter,uiPresenter:e.uiPresenter}}var aq=r(39649),a$=r(73471);function aB(e,t,r){null==e||e({category:"mcp",source:"local_mcp",...(null==r?void 0:r.trace)?{trace_id:r.trace.trace_id,trace:r.trace}:{},...t})}function aF(e){return{name:e.name,description:e.description||"",input_schema_json:tp(e.inputSchema??{type:"object",additionalProperties:!0})}}async function aW(e,t){let r=new aq.K({name:"web-sdk-debugger",version:"0.0.1"}),n=new a$.j(new URL(e),{fetch:t.fetcher,requestInit:t.headers?{headers:t.headers}:void 0});try{await r.connect(n)}catch(e){throw await n.close().catch(()=>void 0),await r.close().catch(()=>void 0),e}return{client:r,transport:n}}async function aH(e){await e.transport.close().catch(()=>void 0),await e.client.close().catch(()=>void 0)}let az="wsd:runtime-console",aV=new WeakMap;function aG(e,t){if(!e.dispatchEvent(new CustomEvent(az,{cancelable:!0,detail:t})))return;let r=aV.get(e)??[];r.push(t),aV.set(e,r)}let aK=["log","info","warn","error","debug"];function aJ(){return{entries:[],nextEntryId:0}}function aX(e){if(e instanceof Error)return e.stack||e.message;if("string"==typeof e)return e;if(void 0===e)return"undefined";if("function"==typeof e)return e.toString();try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function aQ(e){return"number"==typeof e&&Number.isFinite(e)?Math.max(e-1,0):0}function aZ(e){let t=[e.url,e.src,e.getAttribute("url"),e.getAttribute("src")].find(e=>"string"==typeof e&&e.trim());return"string"==typeof t?t.trim():void 0}function aY(e,t){var r;let n=e.trim(),a=n.match(/^(.*):(\d+):(\d+)$/)??n.match(/^(.*):(\d+)$/);if(!a)return null;let[,s,i,o]=a;return s?{url:t&&("<anonymous>"===s||s.endsWith(", <anonymous>")||/^eval at\b.*<anonymous>$/.test(s))?t:s,lineNumber:aQ(Number(i)),columnNumber:void 0===o?0:"number"==typeof(r=Number(o))&&Number.isFinite(r)?Math.max(r-1,0):0}:null}function a0(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"!=typeof e)return;let r=e.split("\n").map(e=>(function(e,t){let r=e.trim(),n=r.startsWith("at ")?r.slice(3).trim():r,a=n.match(/^(.*?)\s+\((.*)\)$/);if(a){let[,e,r]=a,n=aY(r,t);return n?{functionName:e,scriptId:"",...n}:null}let s=aY(n,t);return s?{functionName:"",scriptId:"",...s}:null})(e,t.fallbackSourceUrl)).filter(e=>!!e),n=t.dropFirstFrame&&r.length>1?r.slice(1):r,a=n.filter(e=>!(e.url.includes("console-recorder")||e.url.includes("web-sdk-debugger")||/capture.*Stack|hookConsole|console\.(?:log|info|warn|error|debug)/.test(e.functionName))),s=a.length>0?a:n;return s.length>0?{callFrames:s}:void 0}function a1(e){let t=null==e?void 0:e.callFrames[0];return t?{url:t.url,lineNumber:t.lineNumber,columnNumber:t.columnNumber}:void 0}function a2(e){return e?{callFrames:[{functionName:"",scriptId:"",...e}]}:void 0}function a3(e){return e?`[${e}] `:""}class a4{target;store;listeners=new Set;constructor(e,t=aJ()){this.target=e,this.store=t,this.target.addEventListener("error",this.handleRuntimeError),this.target.addEventListener(az,this.handleRuntimeConsole),this.drainPendingRuntimeConsoleEvents()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getEntries(){return this.store.entries}clear(){this.store.entries.length=0,this.notify()}evaluate(e){let t=this.getFirstIframeWindow()?"iframe":"host",r=this.getFirstIframeWindow()??window;this.addEntry("eval","eval",`> ${e}`);try{let n=r.eval(e),a=aX(n);return this.addEntry("eval","iframe"===t?"iframe":"eval",a),{ok:!0,value:a}}catch(t){let e=aX(t);return this.addEntry("error","eval",e),{ok:!1,value:e}}}destroy(){this.target.removeEventListener("error",this.handleRuntimeError),this.target.removeEventListener(az,this.handleRuntimeConsole),this.listeners.clear()}addEntry(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};this.store.entries.push({id:`console-${++this.store.nextEntryId}`,level:e,source:t,timestamp:Date.now(),message:r,...n}),this.store.entries.length>1e3&&this.store.entries.splice(0,this.store.entries.length-1e3),this.notify()}getFirstIframeWindow(){let e=this.target.shadowRoot;if(!e)return null;for(let t of Array.from(e.querySelectorAll("iframe")))try{if(t.contentWindow)return t.contentWindow}catch{break}return null}handleRuntimeError=e=>{let t,r,n,a,s,i=(r=null==(t=e.detail)?void 0:t.error,n=e.currentTarget instanceof HTMLElement?aZ(e.currentTarget):void 0,s=a1(a=a0(null==r?void 0:r.stack,{fallbackSourceUrl:n}))??function(e){var t,r,n,a,s,i;if((null==e?void 0:e.fileName)||(null==e?void 0:e.release)||(null==e||null==(t=e.sourceMap)?void 0:t.offset))return{url:e.fileName??e.release??"runtime",lineNumber:aQ(null==(n=e.sourceMap)||null==(r=n.offset)?void 0:r.line),columnNumber:"number"==typeof(i=null==(s=e.sourceMap)||null==(a=s.offset)?void 0:a.col)&&Number.isFinite(i)?Math.max(i,0):0}}(t),"string"==typeof(null==r?void 0:r.message)&&r.message?{message:r.message,metadata:{location:s,stackTrace:a??a2(s)}}:{message:aX(r??t??e),metadata:{location:s,stackTrace:a??a2(s)}});this.addEntry("error","runtime",i.message,i.metadata)};handleRuntimeConsole=e=>{let t=e.detail;("string"==typeof(null==t?void 0:t.message)||Array.isArray(null==t?void 0:t.args))&&(e.preventDefault(),this.addRuntimeConsoleEntry(t))};drainPendingRuntimeConsoleEvents(){var e;let t;for(let r of(e=this.target,t=aV.get(e)??[],aV.delete(e),t))this.addRuntimeConsoleEntry(r)}addRuntimeConsoleEntry(e){var t;let r=e.stackTrace??a0(e.stack,{dropFirstFrame:!0,fallbackSourceUrl:aZ(this.target)}),n=e.location??a1(r),a="string"==typeof e.message?e.message:(e.args??[]).map(aX).join(" "),s="string"==typeof e.pagePath&&e.pagePath?e.pagePath:void 0,i="string"==typeof e.label&&e.label?e.label:s;this.addEntry((t=e.level,aK.includes(t)?t:"log"),"runtime",`${a3(i)}${a}`,{args:function(e,t){if(!e||!t)return e;let r=a3(t);if(0===e.length)return[r.trim()];let[n,...a]=e;return"string"==typeof n?[`${r}${n}`,...a]:[r.trim(),n,...a]}(e.args,i),location:n,pagePath:s,stackTrace:r??a2(n)})}notify(){for(let e of this.listeners)e()}}let a5=new Set(["IFRAME","LINK","SCRIPT","STYLE","TEMPLATE"]),a6=new Set(["data-wsd-node-id"]),a8=new Set(["part","lynx-default-overflow-visible"]),a7=new Set(["style","data-wsd-node-id"]);function a9(e){return e.nodeType===Node.ELEMENT_NODE&&!a5.has(e.tagName)}function se(e){var t;return e.nodeType===Node.TEXT_NODE&&!!(null==(t=e.textContent)?void 0:t.trim())}function st(e){return e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"#shadow-root":e.nodeType===Node.TEXT_NODE?"#text":e.tagName.toLowerCase()}function sr(e){if(!Number.isFinite(e))return"0";let t=Math.round(100*e)/100;return Number.isInteger(t)?String(t):t.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function sn(e){return Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")}function sa(e){let t=e.trim(),r=Number.parseFloat(t);return Number.isFinite(r)&&0===r?"0":t}function ss(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function si(e){var t,r,n;let a=null==(t=e.getAttribute("aria-label"))?void 0:t.trim();if(a)return a;let s=null==(r=e.getAttribute("title"))?void 0:r.trim();if(s)return s;if(e instanceof HTMLImageElement)return e.alt.trim();if(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement){let t=Array.from(e.labels??[]).map(e=>{var t;return null==(t=e.textContent)?void 0:t.replace(/\s+/g," ").trim()}).filter(Boolean).join(" ");if(t)return t}return e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement?(null==(n=e.textContent)?void 0:n.replace(/\s+/g," ").trim())??"":""}function so(e){var t;let r=null==(t=e.getAttribute("role"))?void 0:t.trim();if(r)return r;switch(e.tagName){case"A":return e.hasAttribute("href")?"link":"generic";case"BUTTON":return"button";case"IMG":return"img";case"INPUT":case"TEXTAREA":return"textbox";case"SELECT":return"combobox";default:return"generic"}}function sl(e){return!e.hasAttribute("disabled")&&"true"!==e.getAttribute("aria-disabled")&&(!!(e.isContentEditable||e instanceof HTMLAnchorElement&&e.hasAttribute("href"))||e.tabIndex>=0)}function sd(e){return Array.from(e.attributes).filter(e=>!a6.has(e.name)).map(e=>({name:e.name,value:e.value}))}function su(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function sc(e){return a6.has(e)||a8.has(e)}function sp(e){return"DIV"===e.tagName&&"page"===e.getAttribute("part")}function sm(e,t){return a6.has(t)||sp(e)&&sc(t)}function sh(e,t){for(let r of t)sm(e,r.name)||e.setAttribute(r.name,r.value)}function sg(e){return sd(e).filter(t=>!sm(e,t.name))}function sf(e,t,r){let n=new Map(t.map(e=>[e.name,e.value])),a=new Map(r.map(e=>[e.name,e.value])),s=r.filter(e=>n.get(e.name)!==e.value),i=t.filter(e=>!a.has(e.name)).map(e=>e.name);return s.length||i.length?[{type:"attributes",nodeId:e,before:t,modified:s,removed:i}]:[]}function sv(e){return Array.from(e.childNodes).filter(e=>a9(e)||se(e))}function sy(e,t,r){let n=("elementFromPoint"in e&&"function"==typeof e.elementFromPoint?e.elementFromPoint.bind(e):document.elementFromPoint.bind(document))(t,r);for(;(null==n?void 0:n.shadowRoot)&&"function"==typeof n.shadowRoot.elementFromPoint;){let e=n.shadowRoot.elementFromPoint(t,r);if(!e||e===n)break;n=e}return n}function s_(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement??null;for(;t;){if(a5.has(t.tagName))return!0;t=t.parentElement}return!1}class sb{target;nodeIds=new WeakMap;nodes=new Map;onChange;nextNodeId=0;mutationObserver=null;notifyTimer=null;constructor(e,t){this.target=e,this.onChange=t,this.observe()}getDocument(){let e=this.getRoot();return e?(this.nodes.clear(),this.serializeNode(e,!0)):null}getNode(e){return this.nodes.get(e)??null}getElement(e){let t=this.getNode(e);return t instanceof HTMLElement?t:null}setAttributesAsText(e,t,r){let n=function(e){let t=e.trim();if(!t)return[];let r=document.createElement("template");r.innerHTML=`<div ${t}></div>`;let n=r.content.firstElementChild;return n?sd(n):[]}(t),a=null==r?void 0:r.trim();return this.editElementAttributes(e,e=>{a&&!sm(e,a)&&e.removeAttribute(a),sh(e,n)})}setAttributeValue(e,t,r){let n=t.trim();return n?this.editElementAttributes(e,e=>{if(sm(e,n))return!1;e.setAttribute(n,r)}):[]}removeAttribute(e,t){let r=t.trim();return r?this.editElementAttributes(e,e=>{if(sm(e,r))return!1;e.removeAttribute(r)}):[]}setNodeValue(e,t){return this.runWithoutObservation(()=>{let r=this.getNode(e),n=(null==r?void 0:r.textContent)??"";return(null==r?void 0:r.nodeType)!==Node.TEXT_NODE||n===t?[]:(r.textContent=t,[{type:"characterData",nodeId:e,value:t,previousValue:n}])})}setNodeName(e,t){return this.runWithoutObservation(()=>{let r=this.getElement(e),n=t.trim();if(!r||!n)return{nodeId:null,mutations:[]};if(sp(r))return{nodeId:e,mutations:[]};let a=r.parentNode,s=this.getPreviousInspectableSiblingId(r),i=function(e,t){let r=document.createElement(t);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);for(;e.firstChild;)r.append(e.firstChild);return e.replaceWith(r),r}(r,n);return{nodeId:this.getNodeId(i),mutations:a?[this.getChildListMutation(a,[e],[{previousNodeId:s,node:this.serializeNode(i)}])]:[]}})}setOuterHTML(e,t){return this.runWithoutObservation(()=>{let r=this.getNode(e);if(!r)return[];if(r instanceof DocumentFragment){let e=sv(r).map(e=>this.getNodeId(e)),n=su(t);return r.replaceChildren(...Array.from(n.childNodes)),[this.getChildListMutation(r,e,this.getInsertedNodeMutations(r,null,sv(r)))]}if(r instanceof Element&&sp(r)){let n=sg(r),a=sv(r).map(e=>this.getNodeId(e));!function(e,t){let r=su(t),n=r.firstElementChild;if(!n)return e.replaceChildren(...Array.from(r.childNodes));for(let t of Array.from(e.attributes))sc(t.name)||e.removeAttribute(t.name);sh(e,sd(n)),e.replaceChildren(...Array.from(n.childNodes))}(r,t);let s=this.getInsertedNodeMutations(r,null,sv(r));return[...sf(e,n,sg(r)),this.getChildListMutation(r,a,s)]}let n=r.parentNode;if(!n)return[];let a=this.getPreviousInspectableSiblingId(r),s=su(t),i=sv(s);return n.replaceChild(s,r),[this.getChildListMutation(n,[e],this.getInsertedNodeMutations(n,a,i))]})}getNodeIdAtPoint(e,t){let r,n,a=this.getRoot(),s=this.target.shadowRoot,i=(r=null,(n=a=>{let s;for(let i of(a9(a)&&(s=a.getBoundingClientRect()).width>0&&s.height>0&&e>=s.left&&e<=s.right&&t>=s.top&&t<=s.bottom&&(r=a),Array.from(a.childNodes)))a9(i)&&n(i)})(a),r),o=s?sy(s,e,t):sy(document,e,t),l=(i&&a.contains(i)?i:null)??(o&&a.contains(o)?o:null);if(!l)return null;let d=l;for(;d&&!a9(d);)d=d.parentNode??function(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.host:null}(d);return d&&a.contains(d)?this.getNodeId(d):null}findLynxViews(){return function(e){let t=[],r=[e];for(;r.length;){let e=r.shift();for(let n of(e instanceof HTMLElement&&"LYNX-VIEW"===e.tagName&&t.push(e),e instanceof Element&&e.shadowRoot&&r.push(e.shadowRoot),e.children??[]))r.push(n)}return t}(this.target)}findNodeIdByLynxUniqueId(e){let t=function(e,t){let r=[e];for(;r.length;){let e=r.shift();if(e instanceof HTMLElement&&function(e){for(let t of Object.getOwnPropertySymbols(e))if("uniqueId"===t.description){let r=e[t];return"number"==typeof r?r:null}return null}(e)===t)return e;for(let t of(e instanceof Element&&e.shadowRoot&&r.push(e.shadowRoot),e.children??[]))r.push(t)}return null}(this.getRoot(),e);return t?this.getNodeId(t):null}getHighlight(e,t){var r,n;let a,s,i,o,l,d,u,c,p,m,h,g,f,v,y,_=this.getElement(e);if(!_||!_.isConnected)return null;let b=_.getBoundingClientRect(),w=t.getBoundingClientRect(),S=t.offsetWidth?w.width/t.offsetWidth:1,x=t.offsetHeight?w.height/t.offsetHeight:1,I=b.width/S,E=b.height/x,C=getComputedStyle(_),k=C.backgroundColor.trim(),N=(r=C.paddingTop,n=C.paddingRight,(a=[r,n,C.paddingBottom,C.paddingLeft].map(sa)).every(e=>"0"===e)?null:a.every(e=>e===a[0])?a[0]:a[0]===a[2]&&a[1]===a[3]?`${a[0]} ${a[1]}`:a[1]===a[3]?`${a[0]} ${a[1]} ${a[2]}`:a.join(" "));return{left:(b.left-w.left)/S,top:(b.top-w.top)/x,width:I,height:E,nodeName:st(_),selector:(s=_.id.trim(),{tagName:st(_),...s?{id:s}:{},classNames:Array.from(_.classList).filter(Boolean)}),boxModel:(i=ss(C.borderTopWidth),o=ss(C.borderRightWidth),l=ss(C.borderBottomWidth),d=ss(C.borderLeftWidth),u=ss(C.paddingTop),c=ss(C.paddingRight),p=ss(C.paddingBottom),m=d+ss(C.paddingLeft),{content:{left:m,top:h=i+u,width:Math.max(0,I-m-o-c),height:Math.max(0,E-h-l-p)}}),dimensions:`${sr(I)} \xd7 ${sr(E)}`,styles:[...k?[{name:"Background",value:(f=(g=k.trim()).match(/^rgb\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/i),v=g.match(/^rgba\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d?(?:\.\d+)?)\s*\)$/i),(y=f??(v&&1===Number(v[4])?v:null))?`#${sn(Math.round(Number(y[1])))}${sn(Math.round(Number(y[2])))}${sn(Math.round(Number(y[3])))}`:g),swatch:k}]:[],...N?[{name:"Padding",value:N}]:[]],accessibility:{name:si(_),role:so(_),keyboardFocusable:sl(_)}}}destroy(){var e;null==(e=this.mutationObserver)||e.disconnect(),this.mutationObserver=null,null!==this.notifyTimer&&(window.clearTimeout(this.notifyTimer),this.notifyTimer=null),this.nodes.clear()}getRoot(){let e=this.target.shadowRoot;return e?e.querySelector('[part="page"]')??e:this.target}getNodeId(e){let t=this.nodeIds.get(e);if(t)return this.nodes.set(t,e),t;let r=`node-${++this.nextNodeId}`;return this.nodeIds.set(e,r),this.nodes.set(r,e),r}editElementAttributes(e,t){return this.runWithoutObservation(()=>{let r=this.getElement(e);if(!r)return[];let n=sg(r);return!1===t(r)?[]:sf(e,n,sg(r))})}getPreviousInspectableSiblingId(e){let t=e.parentNode;if(!t)return null;let r=sv(t),n=r.findIndex(t=>t===e),a=n>0?r[n-1]:null;return a?this.getNodeId(a):null}getChildListMutation(e,t,r){return{type:"childList",parentNodeId:this.getNodeId(e),removedNodeIds:t,insertedNodes:r,childNodeCount:sv(e).length}}getInsertedNodeMutations(e,t,r){let n=[],a=t;for(let t of r){if((t.parentNode??(t instanceof ShadowRoot?t.host:null))!==e)continue;let r=this.serializeNode(t);n.push({previousNodeId:a,node:r}),a=r.id}return n}runWithoutObservation(e){var t,r;let n=null!==this.mutationObserver;n&&(null==(t=this.mutationObserver)||t.disconnect());try{return e()}finally{n&&(null==(r=this.mutationObserver)||r.takeRecords(),this.observe())}}serializeNode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getNodeId(e);if(e.nodeType===Node.TEXT_NODE){let t;return{id:r,type:"text",name:st(e),attributes:[],children:[],textContent:(t=(e.textContent??"").replace(/\s+/g," ").trim()).length>120?`${t.slice(0,120)}...`:t}}let n=e instanceof HTMLElement?e:null;return{id:r,type:t&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"document":"element",name:st(e),attributes:e instanceof Element?sd(e):[],children:sv(e).map(e=>this.serializeNode(e)),...n?{accessibility:{name:si(n),role:so(n),keyboardFocusable:sl(n)}}:{}}}observe(){let e=this.target.shadowRoot??this.target;this.mutationObserver=new MutationObserver(e=>{e.some(e=>(function(e){if(s_(e.target))return!1;if("attributes"===e.type)return e.target instanceof Element&&a9(e.target)&&!a7.has(e.attributeName??"");if("characterData"===e.type){var t,r;return!!((null==(t=e.oldValue)?void 0:t.trim())||(null==(r=e.target.textContent)?void 0:r.trim()))}return"childList"!==e.type||[...Array.from(e.addedNodes),...Array.from(e.removedNodes)].some(e=>(function e(t){return!s_(t)&&(!!(a9(t)||se(t))||Array.from(t.childNodes).some(t=>e(t)))})(e))})(e))&&this.scheduleNotify()}),this.mutationObserver.observe(e,{attributes:!0,childList:!0,characterData:!0,characterDataOldValue:!0,subtree:!0})}scheduleNotify(){null===this.notifyTimer&&(this.notifyTimer=window.setTimeout(()=>{this.notifyTimer=null,this.onChange()},0))}}let sw="data-wsd-node-id";function sS(e){let t=[];for(let r=0;r<e.length;r++){let n="function"==typeof e.item?e.item(r):e[r];if(!n)continue;let a=e.getPropertyValue(n);t.push({name:n,value:a,priority:e.getPropertyPriority(n),active:!0})}return t}function sx(e){return"u">typeof CSSStyleRule&&e instanceof CSSStyleRule}function sI(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",a=r.trim();a?e.setProperty(t,a,n):e.removeProperty(t)}function sE(e){return`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`}function sC(e){return e.map(e=>({...e}))}function sk(e){return`inline:${e}`}function sN(e){return`rule:${e}`}class sM{target;elementInspector;ruleIds=new WeakMap;rules=new Map;overriddenElements=new Set;overrides=new Map;styleTextSnapshots=new Map;overrideStyleElement=null;inspectorRuleStyleElement=null;inspectorRuleStyleSheet=null;nextRuleId=0;constructor(e,t){this.target=e,this.elementInspector=t}getMatchedStyles(e){let t=this.elementInspector.getElement(e);if(!t)return null;let r=getComputedStyle(t);return{nodeId:e,inlineStyle:this.getInlineStyle(e,t,r),matchedRules:this.getMatchedRules(t,r),computedStyles:function(e){let t=[];for(let r=0;r<e.length;r++){let n=e.item(r);t.push({name:n,value:e.getPropertyValue(n)})}return t}(r)}}setInlineDeclaration(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",a=!(arguments.length>4)||void 0===arguments[4]||arguments[4],s=this.elementInspector.getElement(e);if(!s)return;let i=sk(e);this.rememberStyleTextDeclaration(i,sS(s.style),t,r,n,a),sI(s.style,t,a?r:"")}setInlineDeclarations(e,t){let r=this.elementInspector.getElement(e);if(r){for(let e of(r.style.cssText="",t))e.active&&sI(r.style,e.name,e.value,e.priority);this.styleTextSnapshots.set(sk(e),sC(t))}}setRuleDeclaration(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",s=!(arguments.length>5)||void 0===arguments[5]||arguments[5],i=this.rules.get(t),o=sN(t);if(this.rememberStyleTextDeclaration(o,i?sS(i.style):[],r,n,a,s),!s){if(i)try{sI(i.style,r,"")}catch{this.setOverrideDeclaration(e,r,"")}else this.setOverrideDeclaration(e,r,"");return}if(!i)return void this.setOverrideDeclaration(e,r,n,a);try{sI(i.style,r,n,a)}catch{this.setOverrideDeclaration(e,r,n,a)}}setRuleDeclarations(e,t,r){let n=this.rules.get(t),a=r.filter(e=>e.active);if(this.styleTextSnapshots.set(sN(t),sC(r)),!n)return void this.setOverrideDeclarations(e,a);try{for(let e of(n.style.cssText="",a))sI(n.style,e.name,e.value,e.priority)}catch{this.setOverrideDeclarations(e,a)}}addRule(e,t,r){let n=this.elementInspector.getElement(e),a=t.trim();if(!n||!a)return null;let s=this.getInspectorRuleStyleSheet();if(!s)return null;let i=`${a} { ${r.map(sE).join(" ")} }`;try{let e=s.cssRules.length;s.insertRule(i,e);let t=s.cssRules[e];if(t&&sx(t))return this.toMatchedStyleRule(t,getComputedStyle(n))}catch{}return null}setRuleSelector(e,t,r){let n=this.elementInspector.getElement(e),a=this.rules.get(t),s=r.trim();if(!n||!a||!s)return null;try{return a.selectorText=s,this.toMatchedStyleRule(a,getComputedStyle(n))}catch{return null}}setOverrideDeclaration(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",a=this.elementInspector.getElement(e);if(!a)return;a.setAttribute(sw,e),this.overriddenElements.add(a);let s=this.overrides.get(e)??new Map,i=r.trim();i?s.set(t,{value:i,priority:n}):s.delete(t),s.size>0?this.overrides.set(e,s):this.overrides.delete(e),this.renderOverrideStyleSheet()}setOverrideDeclarations(e,t){let r=this.elementInspector.getElement(e);if(!r)return;r.setAttribute(sw,e),this.overriddenElements.add(r);let n=new Map;for(let e of t)e.value.trim()&&n.set(e.name,{value:e.value.trim(),priority:e.priority});n.size>0?this.overrides.set(e,n):this.overrides.delete(e),this.renderOverrideStyleSheet()}destroy(){var e;for(let t of(null==(e=this.overrideStyleElement)||e.remove(),this.overrideStyleElement=null,this.removeInspectorRuleStyleSheet(),this.overrides.clear(),this.styleTextSnapshots.clear(),this.overriddenElements))t.removeAttribute(sw);this.overriddenElements.clear(),this.rules.clear()}getInlineStyle(e,t,r){return{id:"inline",selectorText:"element.style",editable:!0,declarations:this.getStyleTextSnapshot(sk(e))??sS(t.style)}}getMatchedRules(e,t){let r,n=this.target.shadowRoot??this.target,a=[];for(let s of(this.rules.clear(),r=[],"styleSheets"in n&&r.push(...Array.from(n.styleSheets)),"adoptedStyleSheets"in n&&r.push(...n.adoptedStyleSheets),r))this.collectRulesFromList(s,e,t,a);return a}collectRulesFromList(e,t,r,n,a){let s;try{s=e.cssRules}catch{return}for(let e of Array.from(s)){if(sx(e)){if(!function(e,t){try{return e.matches(t)}catch{return!1}}(t,e.selectorText))continue;n.push(this.toMatchedStyleRule(e,r,a));continue}if("cssRules"in e){let s=function(e){if("conditionText"in e&&"string"==typeof e.conditionText)return e.conditionText}(e);this.collectRulesFromList(e,t,r,n,a&&s?`${a} and ${s}`:s??a)}}}getRuleId(e){let t=this.ruleIds.get(e);if(t)return t;let r=`rule-${++this.nextRuleId}`;return this.ruleIds.set(e,r),r}toMatchedStyleRule(e,t,r){let n=this.getRuleId(e);return this.rules.set(n,e),{id:n,selectorText:e.selectorText,conditionText:r,editable:!0,source:this.isOverrideRule(e)?"override":"rule",declarations:this.getStyleTextSnapshot(sN(n))??sS(e.style)}}getStyleTextSnapshot(e){let t=this.styleTextSnapshots.get(e);return t?sC(t):void 0}rememberStyleTextDeclaration(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",s=!(arguments.length>5)||void 0===arguments[5]||arguments[5],i=this.getStyleTextSnapshot(e)??sC(t),o=n.trim(),l=i.findIndex(e=>e.name===r);if(o||!s){let e={name:r,value:o||(l>=0?i[l].value:""),priority:a,active:s};l>=0?i[l]=e:i.push(e)}else l>=0&&i.splice(l,1);i.length>0?this.styleTextSnapshots.set(e,i):this.styleTextSnapshots.delete(e)}getOverrideStyleElement(){if(this.overrideStyleElement)return this.overrideStyleElement;let e=document.createElement("style");return e.dataset.wsdInspectorOverride="true",(this.target.shadowRoot??this.target).append(e),this.overrideStyleElement=e,e}getInspectorRuleStyleSheet(){if(this.inspectorRuleStyleSheet)return this.inspectorRuleStyleSheet;let e=this.target.shadowRoot??this.target;if("adoptedStyleSheets"in e&&"u">typeof CSSStyleSheet)try{let t=new CSSStyleSheet;return e.adoptedStyleSheets=[...e.adoptedStyleSheets,t],this.inspectorRuleStyleSheet=t,t}catch{}if(!this.inspectorRuleStyleElement){let t=document.createElement("style");t.dataset.wsdInspectorRules="true",e.append(t),this.inspectorRuleStyleElement=t}return this.inspectorRuleStyleSheet=this.inspectorRuleStyleElement.sheet,this.inspectorRuleStyleSheet}removeInspectorRuleStyleSheet(){var e;let t=this.target.shadowRoot??this.target;this.inspectorRuleStyleSheet&&"adoptedStyleSheets"in t&&(t.adoptedStyleSheets=t.adoptedStyleSheets.filter(e=>e!==this.inspectorRuleStyleSheet)),null==(e=this.inspectorRuleStyleElement)||e.remove(),this.inspectorRuleStyleElement=null,this.inspectorRuleStyleSheet=null}isOverrideRule(e){var t,r;return e.parentStyleSheet===(null==(t=this.overrideStyleElement)?void 0:t.sheet)||e.parentStyleSheet===(null==(r=this.inspectorRuleStyleElement)?void 0:r.sheet)||e.parentStyleSheet===this.inspectorRuleStyleSheet}renderOverrideStyleSheet(){if(0===this.overrides.size){var e;null==(e=this.overrideStyleElement)||e.remove(),this.overrideStyleElement=null;return}let t=Array.from(this.overrides.entries()).map(e=>{let[t,r]=e,n=Array.from(r.entries()).map(e=>{let[t,r]=e;return` ${t}: ${r.value}${r.priority?` !${r.priority}`:""};`}).join("\n");return`[${sw}="${t}"] {
|
|
21
|
-
${n}
|
|
22
|
-
}`});this.getOverrideStyleElement().textContent=t.join("\n\n")}}class sR{listeners=new Set;elementInspector;styleInspector;consoleRecorder;selectedNodeId=null;consoleUnsubscribe=null;constructor(e,t={}){this.elementInspector=new sb(e,()=>this.notify({type:"document"})),this.styleInspector=new sM(e,this.elementInspector),this.consoleRecorder=new a4(e,t.consoleStore),this.consoleUnsubscribe=this.consoleRecorder.subscribe(()=>this.notify({type:"console"}))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getDocument(){return this.elementInspector.getDocument()}getElement(e){return this.elementInspector.getElement(e)}getSelectedNodeId(){return this.selectedNodeId}selectNode(e){this.selectedNodeId!==e&&(this.selectedNodeId=e,this.notify({type:"selection"}))}getNodeIdAtPoint(e,t){return this.elementInspector.getNodeIdAtPoint(e,t)}findLynxViews(){return this.elementInspector.findLynxViews()}findNodeIdByLynxUniqueId(e){return this.elementInspector.findNodeIdByLynxUniqueId(e)}getNodeHighlight(e,t){return this.elementInspector.getHighlight(e,t)}getMatchedStyles(e){return this.styleInspector.getMatchedStyles(e)}setAttributesAsText(e,t,r){return this.elementInspector.setAttributesAsText(e,t,r)}setAttributeValue(e,t,r){return this.elementInspector.setAttributeValue(e,t,r)}removeAttribute(e,t){return this.elementInspector.removeAttribute(e,t)}setNodeValue(e,t){return this.elementInspector.setNodeValue(e,t)}setNodeName(e,t){let r=this.elementInspector.setNodeName(e,t);return this.selectedNodeId===e&&(this.selectedNodeId=r.nodeId),r}setOuterHTML(e,t){return this.elementInspector.setOuterHTML(e,t)}setInlineDeclaration(e,t,r,n,a){this.styleInspector.setInlineDeclaration(e,t,r,n,a),this.notify({type:"style",styleSheetId:`inline:${e}`})}setInlineDeclarations(e,t){this.styleInspector.setInlineDeclarations(e,t),this.notify({type:"style",styleSheetId:`inline:${e}`})}setRuleDeclaration(e,t,r,n,a,s){this.styleInspector.setRuleDeclaration(e,t,r,n,a,s),this.notify({type:"style",styleSheetId:`rule:${t}`})}setRuleDeclarations(e,t,r){this.styleInspector.setRuleDeclarations(e,t,r),this.notify({type:"style",styleSheetId:`rule:${t}`})}addRule(e,t,r){let n=this.styleInspector.addRule(e,t,r);return this.notify({type:"style",styleSheetId:n?`rule:${n.id}`:"inspector:main"}),n}setRuleSelector(e,t,r){let n=this.styleInspector.setRuleSelector(e,t,r);return this.notify({type:"style",styleSheetId:n?`rule:${n.id}`:`rule:${t}`}),n}getConsoleEntries(){return this.consoleRecorder.getEntries()}clearConsole(){this.consoleRecorder.clear()}evaluate(e){return this.consoleRecorder.evaluate(e)}destroy(){var e;null==(e=this.consoleUnsubscribe)||e.call(this),this.consoleUnsubscribe=null,this.elementInspector.destroy(),this.styleInspector.destroy(),this.consoleRecorder.destroy(),this.listeners.clear()}notify(e){for(let t of this.listeners)t(e)}}async function sT(e){let t,r="string"==typeof(t=[e.url,e.src,e.getAttribute("url"),e.getAttribute("src")].find(e=>"string"==typeof e&&e.trim()))?t.trim():void 0;if(!r||!/\.web\.bundle(?:[?#]|$)/.test(r))return;let n=new URL(r,window.location.href);n.pathname+=".map";let a=await fetch(n.href).catch(()=>void 0);if(!(null==a?void 0:a.ok))return;let s=await a.text();return{content:"",sourceMapURL:`data:application/json;charset=utf-8,${encodeURIComponent(s)}`,url:r}}function sA(e){return"object"==typeof e&&null!==e||"function"==typeof e}function sP(e){return Array.isArray(e)?"array":void 0}function sj(e){return Array.isArray(e)?`Array(${e.length})`:sD(e)}function sD(e){if(Array.isArray(e))return"Array";try{var t,r;return(null==(r=Object.getPrototypeOf(e))||null==(t=r.constructor)?void 0:t.name)||"Object"}catch{return"Object"}}function sL(e,t){return{name:e,type:sO(t),subtype:sA(t)?sP(t):void 0,value:sA(t)?sj(t):String(t)}}function sO(e){return null===e?"object":typeof e}function sU(e,t){if(void 0===e)return{type:"undefined",description:"undefined"};if(null===e)return{type:"object",subtype:"null",value:null,description:"null"};let r=function(e){if("number"==typeof e){if(Object.is(e,-0))return"-0";let t=String(e);return"NaN"===t||"Infinity"===t||"-Infinity"===t?t:void 0}return"bigint"==typeof e?`${e}n`:void 0}(e);if(r)return{type:sO(e),unserializableValue:r,description:r};if("symbol"==typeof e)return{type:"symbol",description:String(e)};if(sA(e)){let r;return{type:"function"==typeof e?"function":"object",subtype:"function"==typeof e?void 0:sP(e),className:"function"==typeof e?"Function":sD(e),description:"function"==typeof e?e.toString():sj(e),objectId:null==t?void 0:t.register(e),preview:"function"==typeof e||Array.isArray(e)?void 0:(r=function(e){try{return Object.keys(e)}catch{return[]}}(e),{type:"object",subtype:sP(e),description:sj(e),overflow:r.length>5,properties:r.slice(0,5).map(t=>{try{let r=Object.getOwnPropertyDescriptor(e,t);return sL(t,r&&"value"in r?r.value:void 0)}catch{return sL(t,void 0)}})})}}return{type:sO(e),value:e,description:String(e)}}function sq(e,t){return(e.args??[e.message]).map(e=>sU(e,t))}function s$(e,t){return{startLine:0,startColumn:e,endLine:0,endColumn:t}}function sB(e,t){let r=0,n="",a=t.map(e=>{let t=`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`,a=e.active?t:`/* ${t} */`,s=s$(r,r+a.length);return n+=`${a} `,r=n.length,{name:e.name,value:e.value,important:"important"===e.priority,disabled:!e.active,parsedOk:!0,implicit:!1,text:a,range:s}});return{styleSheetId:e,cssText:n.trim(),range:s$(0,Math.max(0,n.trim().length)),shorthandEntries:[],cssProperties:a}}function sF(e){let t=e.indexOf(":");return t<0?{kind:e,id:""}:{kind:e.slice(0,t),id:e.slice(t+1)}}function sW(e){let t,r=e.includes("{")?e.slice(e.indexOf("{")+1,e.lastIndexOf("}")):e,n=[],a=/\/\*([\s\S]*?)\*\//g,s=0;for(;t=a.exec(r);)n.push(...sH(r.slice(s,t.index),!0)),n.push(...sH(t[1],!1)),s=t.index+t[0].length;return n.push(...sH(r.slice(s),!0)),n}function sH(e,t){let r=[];for(let n of e.split(";")){let e=n.indexOf(":");if(e<=0)continue;let a=n.slice(0,e).trim(),s=n.slice(e+1).trim(),i="";/!\s*important$/i.test(s)&&(s=s.replace(/!\s*important$/i,"").trim(),i="important"),a&&r.push({name:a,value:s,priority:i,active:t})}return r}let sz=new Map([["x-view","view"],["x-text","text"]]);function sV(e){if("element"!==e.type||"div"!==e.name)return!1;let t=e.attributes.find(e=>"part"===e.name);return(null==t?void 0:t.value)==="page"}function sG(e){return sV(e)?e.attributes.filter(e=>"part"!==e.name&&"lynx-default-overflow-visible"!==e.name):e.attributes}function sK(e){return sG(e).flatMap(e=>[e.name,e.value])}function sJ(e){return sV(e)?"page":sz.get(e.name)??e.name}function sX(e,t){var r;return(null==(r=e.attributes.find(e=>e.name===t))?void 0:r.value)||void 0}function sQ(e,t){return e.type===t.type&&e.name===t.name&&(t.id?sX(e,"id")===t.id:!t.className||sX(e,"class")===t.className)}function sZ(e,t){let r=Number(e);return Number.isFinite(r)?r<0?1/0:r:t}function sY(e){return e===1/0?e:Math.max(0,e-1)}function s0(e){if("text"===e.type)return e.textContent??"";if("document"===e.type)return s1(e);let t=sG(e).map(e=>` ${e.name}="${e.value}"`).join(""),r=e.children.map(e=>s0(e)).join(""),n=sJ(e);return`<${n}${t}>${r}</${n}>`}function s1(e){return e.children.map(e=>s0(e)).join("")}function s2(e,t){let r=(e,n)=>{let a=[...n,e];if(e.id===t)return a;for(let t of e.children){let e=r(t,a);if(e)return e}return null};return r(e,[])}let s3="__wsd_document__";function s4(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}let s5="wsd-main-frame";function s6(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function s8(e){var t;let r;if(e instanceof ArrayBuffer)return{base64Encoded:!0,body:te(e),byteLength:e.byteLength};if("string"==typeof e)r=e;else if(void 0===e)r="";else try{r=JSON.stringify(e)??String(e)}catch{r=String(e)}return{base64Encoded:!1,body:r,byteLength:(t=r,new TextEncoder().encode(t).byteLength)}}function s7(e){throw Object.assign(Error(e),{code:-32602})}function s9(e,t,r){return e??s7(null===e?r:t)}class ie{emit;enabledSessions=new Map;payloads=new Map;requests=new Map;unsubscribe;maxTotalBufferSize=262144e3;storedPayloadSize=0;constructor(e){this.emit=e}enable(e,t){var r;return this.unsubscribe??=(r=this.handleRequestLifecycle,r0.add(r),()=>r0.delete(r)),this.enabledSessions.set(this.getSessionKey(t),{maxPostDataSize:s6(null==e?void 0:e.maxPostDataSize,65536),maxTotalBufferSize:s6(null==e?void 0:e.maxTotalBufferSize,262144e3)}),this.refreshBufferLimit(),{}}disable(e){let t=this.getSessionKey(e);for(let[e,r]of(this.enabledSessions.delete(t),this.requests))r.sessions.delete(t),0===r.sessions.size&&this.deleteRequest(e,r);if(0===this.enabledSessions.size){var r;null==(r=this.unsubscribe)||r.call(this),this.unsubscribe=void 0,this.clearRequests()}else this.refreshBufferLimit();return{}}getRequestPostData(e,t){let r=s9(this.getRequest(e,t).requestBody,"No post data was sent with this request","Request post data is no longer available");return{postData:r.body,base64Encoded:r.base64Encoded}}getResponseBody(e,t){let r=s9(this.getRequest(e,t).responseBody,"No response body is available for this request","Response body is no longer available");return{body:r.body,base64Encoded:r.base64Encoded}}destroy(){var e;null==(e=this.unsubscribe)||e.call(this),this.unsubscribe=void 0,this.enabledSessions.clear(),this.clearRequests()}handleRequestLifecycle=e=>{if("request"===e.phase)return void this.handleRequestStarted(e);let t=this.requests.get(e.requestId);if(t){if("response"===e.phase)return void this.handleResponseReceived(e,t);this.emitForRequest(t,{method:"Network.loadingFailed",params:{canceled:!1,errorText:e.errorText,requestId:e.requestId,timestamp:e.timestamp,type:"XHR"}})}};handleRequestStarted(e){var t;let r;if(0===this.enabledSessions.size)return;let n=void 0===e.request.body?void 0:s8(e.request.body),a={request:e.request,sessions:new Set(this.enabledSessions.keys())};this.requests.set(e.requestId,a),n&&this.storePayload(a,"requestBody",n);let s=(r=(t=e.request.url).indexOf("#"))<0?{url:t}:{url:t.slice(0,r),urlFragment:t.slice(r)};for(let t of a.sessions){let r=this.enabledSessions.get(t);if(!r)continue;let a=n&&!n.base64Encoded&&n.byteLength<=r.maxPostDataSize;this.emit({method:"Network.requestWillBeSent",params:{documentURL:s.url,frameId:s5,initiator:{type:"script"},loaderId:s5,redirectHasExtraInfo:!1,request:{...s,hasPostData:!!n,headers:e.request.headers,initialPriority:"High",isSameSite:!0,method:e.request.method,mixedContentType:"none",...a?{postData:n.body}:{},referrerPolicy:"no-referrer"},requestId:e.requestId,timestamp:e.timestamp,type:"XHR",wallTime:e.wallTime}},this.getSessionId(t))}}handleResponseReceived(e,t){var r;let n=e.response??{},a=!(r=n.header)||"object"!=typeof r||Array.isArray(r)?{}:Object.fromEntries(Object.entries(r).map(e=>{let[t,r]=e;return[t,String(r)]})),s=s8(n.data),{charset:i,mimeType:o}=function(e){var t,r;let n,a=(null==(n=Object.entries(e).find(e=>{let[t]=e;return"content-type"===t.toLowerCase()}))?void 0:n[1])??"",[s=""]=a.split(";");return{charset:(null==(r=/(?:^|;)\s*charset\s*=\s*["']?([^;"']+)/i.exec(a))||null==(t=r[1])?void 0:t.trim())??"",mimeType:s.trim()}}(a),l="number"==typeof n.statusCode&&Number.isFinite(n.statusCode)?n.statusCode:0;this.storePayload(t,"responseBody",s),this.emitForRequest(t,{method:"Network.responseReceived",params:{frameId:s5,hasExtraInfo:!1,loaderId:s5,requestId:e.requestId,response:{charset:i,connectionId:0,connectionReused:!1,encodedDataLength:s.byteLength,fromDiskCache:!1,fromPrefetchCache:!1,fromServiceWorker:!1,headers:a,mimeType:o,protocol:"",requestHeaders:t.request.headers,responseTime:1e3*e.wallTime,securityState:"unknown",status:l,statusText:"",url:t.request.url},timestamp:e.timestamp,type:"XHR"}}),this.emitForRequest(t,{method:"Network.loadingFinished",params:{encodedDataLength:s.byteLength,requestId:e.requestId,timestamp:e.timestamp}})}emitForRequest(e,t){for(let r of e.sessions)this.enabledSessions.has(r)&&this.emit(t,this.getSessionId(r))}getRequest(e,t){let r="string"!=typeof(null==e?void 0:e.requestId)||0===e.requestId.length?s7("requestId must be a non-empty string"):e.requestId,n=this.requests.get(r);return(null==n?void 0:n.sessions.has(this.getSessionKey(t)))?n:s7(`Unknown requestId: ${r}`)}storePayload(e,t,r){let n=e[t];n&&(this.payloads.delete(n),this.storedPayloadSize-=n.byteLength),e[t]=r,this.payloads.set(r,[e,t]),this.storedPayloadSize+=r.byteLength,this.evictPayloads()}evictPayloads(){for(;this.storedPayloadSize>this.maxTotalBufferSize;){let e=this.payloads.entries().next().value;if(!e)return;let[t,[r,n]]=e;this.payloads.delete(t),this.storedPayloadSize-=t.byteLength,r[n]=null}}refreshBufferLimit(){this.maxTotalBufferSize=Math.min(...[...this.enabledSessions.values()].map(e=>e.maxTotalBufferSize)),this.evictPayloads()}deleteRequest(e,t){for(let e of[t.requestBody,t.responseBody])e&&(this.payloads.delete(e),this.storedPayloadSize-=e.byteLength);this.requests.delete(e)}clearRequests(){this.requests.clear(),this.payloads.clear(),this.storedPayloadSize=0}getSessionKey(e){return e??""}getSessionId(e){return e||void 0}}class it{cdpNodes=new Map;nodeIds=new Map;inspectorNodeIds=new Map;nextNodeId=0;get size(){return this.nodeIds.size}reset(){this.cdpNodes.clear(),this.nodeIds.clear(),this.inspectorNodeIds.clear(),this.nextNodeId=0}getCdpNodeId(e){let t=this.nodeIds.get(e);if(t)return t;let r=++this.nextNodeId;return this.nodeIds.set(e,r),this.inspectorNodeIds.set(r,e),r}getExistingCdpNodeId(e){return this.nodeIds.get(e)}getInspectorNodeId(e){return this.inspectorNodeIds.get(e)}resolveInspectorNodeId(e){let t=this.inspectorNodeIds.get(Number(e));if(!t)throw Object.assign(Error(`Unknown nodeId: ${String(e)}`),{code:-32602});return t}toDocumentCdpNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=this.getCdpNodeId(s3),n=sY(t),a=t>0?[this.toCdpNode(e,n,r)]:void 0,s={nodeId:r,backendNodeId:r,nodeType:9,nodeName:"#document",localName:"",nodeValue:"",childNodeCount:1,frameId:"wsd-main-frame",documentURL:"wsd://runtime",baseURL:"wsd://runtime",publicId:"",systemId:"",xmlVersion:"",children:a};return this.cdpNodes.set(r,s),s}toCdpNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=arguments.length>2?arguments[2]:void 0,n=this.getCdpNodeId(e.id),a=sY(t),s=t>0?e.children.map(e=>this.toCdpNode(e,a,n)):void 0,i="text"===e.type,o="document"===e.type,l=sJ(e),d={nodeId:n,backendNodeId:n,parentId:r,nodeType:"text"===e.type?3:"document"===e.type?11:1,nodeName:i||o?e.name:l.toUpperCase(),localName:i||o?"":l,nodeValue:e.textContent??"",childNodeCount:e.children.length,frameId:o?"wsd-main-frame":void 0,documentURL:o?"wsd://runtime":void 0,baseURL:o?"wsd://runtime":void 0,publicId:o?"":void 0,systemId:o?"":void 0,xmlVersion:o?"":void 0,name:i?e.name:void 0,value:i?e.textContent??"":void 0,attributes:"element"===e.type?sK(e):void 0,children:s};return this.cdpNodes.set(n,d),d}}function ir(e){return e.map(e=>({...e}))}function ia(e){return"attributes"===e.type||"characterData"===e.type}class is{adapter;consoleAdapter=null;appAdapter=null;appTarget=null;target;listeners=new Set;options;nodeStore=new it;network;consoleStore=aJ();appConsoleStore=aJ();knownConsoleEntryIdsBySession=new Map;preservingConsoleOnTargetChange;knownStyleSheetIds=new Set;unsubscribeAdapter=null;unsubscribeConsoleAdapter=null;unsubscribeAppAdapter=null;stopInspectModeListener=null;selectedNodeSignaturePath=null;preferredNodeSignaturePath=null;pendingDocumentRevealSignaturePath=null;shouldRevealDocumentAfterUpdate=!1;activeSessionId;isApplyingStyleEdit=!1;runtimeEnabledSessions=new Set;debuggerEnabledSessions=new Set;nextScriptId=0;scriptIdsByUrl=new Map;sourceScriptsById=new Map;parsedScriptIdsBySession=new Map;sourceLoadId=0;undoEntries=[];pendingUndoEntry=null;nextRemoteObjectId=0;remoteObjects=new Map;remoteObjectStore={get:e=>this.remoteObjects.get(e),register:e=>this.registerRemoteObject(e)};constructor(e,t){this.target=e,this.options=t,this.preservingConsoleOnTargetChange=!!t.preserveConsoleOnTargetChange,this.adapter=this.createTargetAdapter(e),this.network=new ie((e,t)=>this.emit(e,t)),this.subscribeAdapter(),this.createConsoleAdapter(),this.loadSources(e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getInspectorSnapshot(){return{root:this.adapter.getDocument(),selectedUid:this.adapter.getSelectedNodeId()}}getComputedStyles(e,t){var r;let n=null==(r=this.adapter.getMatchedStyles(e))?void 0:r.computedStyles;if(!n)return null;if(!(null==t?void 0:t.length))return n;let a=new Set(t);return n.filter(e=>a.has(e.name))}getElementRect(e){let t=this.options.getRuntimeFrame(),r=t?this.adapter.getNodeHighlight(e,t):null;return r?{x:r.left,y:r.top,width:r.width,height:r.height}:null}getElement(e){return this.adapter.getElement(e)}dispatch(e){e.sessionId&&(this.activeSessionId=e.sessionId);try{let t={id:e.id,result:this.handleRequest(e)};return e.sessionId&&(t.sessionId=e.sessionId),t}catch(n){let t,r={id:e.id,error:{code:"number"==typeof(t=null==n?void 0:n.code)?t:-32603,message:n instanceof Error?n.message:String(n)}};return e.sessionId&&(r.sessionId=e.sessionId),r}}destroy(){var e,t,r,n,a;this.sourceLoadId++,this.stopInspectMode(),null==(e=this.unsubscribeAdapter)||e.call(this),this.unsubscribeAdapter=null,null==(t=this.unsubscribeConsoleAdapter)||t.call(this),this.unsubscribeConsoleAdapter=null,null==(r=this.consoleAdapter)||r.destroy(),this.consoleAdapter=null,null==(n=this.unsubscribeAppAdapter)||n.call(this),this.unsubscribeAppAdapter=null,null==(a=this.appAdapter)||a.destroy(),this.appAdapter=null,this.appTarget=null,this.adapter.destroy(),this.network.destroy(),this.sourceScriptsById.clear(),this.remoteObjects.clear(),this.listeners.clear(),this.options.onHighlightChange(null)}subscribeAdapter(){this.unsubscribeAdapter=this.adapter.subscribe(this.handleAdapterChange)}createConsoleAdapter(){let e=this.options.consoleTarget;e&&e!==this.target&&(this.consoleAdapter=new sR(e,{consoleStore:this.consoleStore}),this.unsubscribeConsoleAdapter=this.consoleAdapter.subscribe(e=>{"console"===e.type&&this.handleConsoleChange()}))}getConsoleAdapter(){return this.consoleAdapter??this.adapter}createTargetAdapter(e){return new sR(e,{consoleStore:this.options.preserveConsoleOnTargetChange?this.consoleStore:void 0})}createAppTargetAdapter(e){return new sR(e,{consoleStore:this.appConsoleStore})}subscribeAppAdapter(){var e;this.unsubscribeAppAdapter=(null==(e=this.appAdapter)?void 0:e.subscribe(e=>{"console"===e.type&&(this.emitNewConsoleEntries("app"),this.emit({method:"WSD.appConsoleUpdated"}))}))??null}handleAdapterChange=e=>{if("document"===e.type){if(!this.pendingDocumentRevealSignaturePath){let e=this.preferredNodeSignaturePath??this.selectedNodeSignaturePath;this.pendingDocumentRevealSignaturePath=e?[...e]:null}this.nodeStore.reset(),this.shouldRevealDocumentAfterUpdate=!0,this.emit({method:"DOM.documentUpdated"});return}if("console"===e.type){this.consoleAdapter||this.handleConsoleChange();return}"selection"===e.type?this.emitSelectedStyleInvalidated():this.isApplyingStyleEdit||(this.emitSelectedStyleInvalidated(),this.emit({method:"CSS.styleSheetChanged",params:{styleSheetId:e.styleSheetId??"inspector:main"}}))};setConsoleTarget(e){var t,r;this.options.consoleTarget!==e&&(null==(t=this.unsubscribeConsoleAdapter)||t.call(this),this.unsubscribeConsoleAdapter=null,null==(r=this.consoleAdapter)||r.destroy(),this.consoleAdapter=null,this.options.consoleTarget=e,this.createConsoleAdapter(),this.emitNewConsoleEntries(),this.emit({method:"WSD.consoleUpdated"}))}setTarget(e){var t;if(this.target===e)return;let r=!!this.options.preserveConsoleOnTargetChange,n=r!==this.preservingConsoleOnTargetChange;if(this.preservingConsoleOnTargetChange=r,null==(t=this.unsubscribeAdapter)||t.call(this),this.unsubscribeAdapter=null,this.adapter.destroy(),this.target=e,this.adapter=this.createTargetAdapter(e),this.nodeStore.reset(),this.knownStyleSheetIds.clear(),this.sourceScriptsById.clear(),this.parsedScriptIdsBySession.clear(),!this.consoleAdapter&&!this.options.preserveConsoleOnTargetChange){for(let e of this.knownConsoleEntryIdsBySession.values())e.delete("current");0===this.appConsoleStore.entries.length&&this.remoteObjects.clear()}this.selectedNodeSignaturePath=null,this.preferredNodeSignaturePath=null,this.pendingDocumentRevealSignaturePath=null,this.shouldRevealDocumentAfterUpdate=!1,this.undoEntries.length=0,this.pendingUndoEntry=null,this.subscribeAdapter(),this.loadSources(e),n&&this.clearConsoleForTargetScopeChange(),this.emit({method:"DOM.documentUpdated"}),this.emitNewConsoleEntries(),this.emit({method:"WSD.consoleUpdated"})}handleConsoleChange(){this.emitNewConsoleEntries(),this.emit({method:"WSD.consoleUpdated"})}getAppAdapter(){var e,t,r,n,a,s;let i=(null==(e=(t=this.options).getAppTarget)?void 0:e.call(t))??null;return i?(this.appAdapter&&this.appTarget===i||(null==(r=this.unsubscribeAppAdapter)||r.call(this),this.unsubscribeAppAdapter=null,null==(n=this.appAdapter)||n.destroy(),this.appTarget=i,this.appAdapter=this.createAppTargetAdapter(i),this.subscribeAppAdapter(),this.emit({method:"WSD.appConsoleUpdated"})),this.appAdapter):(null==(a=this.unsubscribeAppAdapter)||a.call(this),this.unsubscribeAppAdapter=null,null==(s=this.appAdapter)||s.destroy(),this.appAdapter=null,this.appTarget=null,null)}handleRequest(e){switch(e.method){case"DOM.enable":case"CSS.enable":case"Overlay.enable":case"Page.enable":case"Log.enable":case"CSS.trackComputedStyleUpdatesForNode":case"Page.removeScriptToEvaluateOnNewDocument":case"Log.startViolationsReport":case"Runtime.addBinding":case"Runtime.removeBinding":case"Runtime.runIfWaitingForDebugger":case"Runtime.setCustomObjectFormatterEnabled":return{};case"Runtime.enable":return this.runtimeEnabledSessions.add(this.getSessionKey(e.sessionId)),this.emitRuntimeExecutionContext(e.sessionId),this.emitNewConsoleEntriesForSession(e.sessionId),this.getAppAdapter(),this.emitNewConsoleEntriesForSession(e.sessionId,"app"),{};case"Runtime.disable":return this.runtimeEnabledSessions.delete(this.getSessionKey(e.sessionId)),this.knownConsoleEntryIdsBySession.delete(this.getSessionKey(e.sessionId)),{};case"Debugger.enable":return this.debuggerEnabledSessions.add(this.getSessionKey(e.sessionId)),this.getAppAdapter(),this.emitNewConsoleEntries("app"),this.emitSourceScripts(e.sessionId),{debuggerId:"wsd-debugger"};case"Debugger.disable":return this.debuggerEnabledSessions.delete(this.getSessionKey(e.sessionId)),this.parsedScriptIdsBySession.delete(this.getSessionKey(e.sessionId)),{};case"Debugger.getScriptSource":return this.getScriptSource(e.params);case"DOM.getFlattenedDocument":return this.getFlattenedDocument();case"DOM.getDocument":return this.getDocument(e.params,e.sessionId);case"DOM.requestChildNodes":return this.requestChildNodes(e.params,e.sessionId);case"DOM.describeNode":return this.describeNode(e.params);case"DOM.getAttributes":return this.getAttributes(e.params);case"DOM.getOuterHTML":return this.getOuterHTML(e.params);case"DOM.setAttributesAsText":return this.setAttributesAsText(e.params,e.sessionId);case"DOM.setAttributeValue":return this.setAttributeValue(e.params,e.sessionId);case"DOM.removeAttribute":return this.removeAttribute(e.params,e.sessionId);case"DOM.setNodeValue":return this.setNodeValue(e.params,e.sessionId);case"DOM.setNodeName":return this.setNodeName(e.params,e.sessionId);case"DOM.setOuterHTML":return this.setOuterHTML(e.params,e.sessionId);case"DOM.getBoxModel":return this.getBoxModel(e.params);case"DOM.pushNodesByBackendIdsToFrontend":return this.pushNodesByBackendIdsToFrontend(e.params,e.sessionId);case"DOM.markUndoableState":return this.markUndoableState();case"DOM.undo":return this.undo(e.sessionId);case"DOM.querySelector":return{nodeId:0};case"DOM.querySelectorAll":case"DOM.getSearchResults":return{nodeIds:[]};case"DOM.performSearch":return{searchId:"wsd-empty-search",resultCount:0};case"DOM.resolveNode":return this.resolveNode(e.params);case"CSS.getMatchedStylesForNode":return this.getMatchedStylesForNode(e.params);case"CSS.getInlineStylesForNode":return this.getInlineStylesForNode(e.params);case"CSS.getComputedStyleForNode":return this.getComputedStyleForNode(e.params);case"CSS.getPlatformFontsForNode":return{fonts:[]};case"CSS.getMediaQueries":return{medias:[]};case"CSS.getEnvironmentVariables":return{environmentVariables:{}};case"CSS.getBackgroundColors":return{backgroundColors:[],computedFontSize:"",computedFontWeight:"",computedBodyFontSize:""};case"CSS.getStyleSheetText":return this.getStyleSheetText(e.params);case"CSS.resolveValues":return this.resolveCssValues(e.params);case"CSS.setStyleTexts":return this.setStyleTexts(e.params);case"CSS.setEffectivePropertyValueForNode":return this.setEffectivePropertyValueForNode(e.params);case"CSS.createStyleSheet":return{styleSheetId:"inspector:main"};case"CSS.addRule":return this.addRule(e.params);case"CSS.setRuleSelector":return this.setRuleSelector(e.params);case"Page.getResourceTree":case"Page.getFrameTree":return this.getFrameTree();case"Page.getNavigationHistory":return{currentIndex:0,entries:[{id:1,url:"wsd://runtime",title:"Web SDK Runtime",transitionType:"typed"}]};case"Page.getLayoutMetrics":return this.getLayoutMetrics();case"Page.createIsolatedWorld":return{executionContextId:1};case"Page.addScriptToEvaluateOnNewDocument":return{identifier:"wsd-script"};case"Page.getCookies":return{cookies:[]};case"Page.getAppManifest":return{url:"",errors:[],data:""};case"Network.enable":return this.network.enable(e.params,e.sessionId);case"Network.disable":return this.network.disable(e.sessionId);case"Network.getRequestPostData":return this.network.getRequestPostData(e.params,e.sessionId);case"Network.getResponseBody":return this.network.getResponseBody(e.params,e.sessionId);case"Network.emulateNetworkConditionsByRule":return{ruleIds:[]};case"Performance.getMetrics":return{metrics:[]};case"Memory.getDOMCounters":return{documents:1,nodes:this.nodeStore.size,jsEventListeners:0};case"SystemInfo.getInfo":return{gpu:{devices:[],auxAttributes:{},featureStatus:{},driverBugWorkarounds:[]},modelName:"Web SDK Debugger",modelVersion:"",commandLine:""};case"Browser.getVersion":return{protocolVersion:"1.3",product:"Web SDK Debugger",revision:"",userAgent:"u"<typeof navigator?"":navigator.userAgent,jsVersion:""};case"Schema.getDomains":return{domains:[]};case"Runtime.evaluate":return this.evaluate(e.params);case"Runtime.getProperties":return this.getRuntimeProperties(e.params);case"Runtime.callFunctionOn":case"Runtime.awaitPromise":return{result:{type:"undefined",description:"undefined"}};case"Runtime.releaseObject":var t;return"string"==typeof(null==(t=e.params)?void 0:t.objectId)&&this.remoteObjects.delete(e.params.objectId),{};case"Runtime.releaseObjectGroup":return this.remoteObjects.clear(),{};case"Runtime.discardConsoleEntries":case"Console.clearMessages":case"Log.clear":return this.clearConsole(),{};case"Overlay.highlightNode":return this.highlightNode(e.params);case"Overlay.hideHighlight":return this.options.onHighlightChange(null),{};case"Overlay.setInspectMode":return this.setInspectMode(e.params,e.sessionId);case"WSD.getConsoleEntries":return{entries:this.getConsoleAdapter().getConsoleEntries().map(e=>this.toConsoleEntry(e))};case"WSD.getAppConsoleEntries":return this.getAppAdapter(),this.emitNewConsoleEntries("app"),{entries:this.appConsoleStore.entries.map(e=>this.toConsoleEntry(e))};case"WSD.clearAppConsole":return this.clearAppConsole(),{};case"WSD.setStyleDeclaration":return this.setStyleDeclaration(e.params);default:if(function(e){let[t,r]=e.split(".");return new Set(["Audits","Browser","DOMDebugger","Debugger","Emulation","HeapProfiler","IndexedDB","Inspector","LayerTree","Memory","Network","Performance","Profiler","Security","ServiceWorker","Storage","Target"]).has(t)||"enable"===r||"disable"===r||(null==r?void 0:r.startsWith("set"))||(null==r?void 0:r.startsWith("clear"))||(null==r?void 0:r.startsWith("stop"))}(e.method))return{};throw Object.assign(Error(`Unsupported CDP method: ${e.method}`),{code:-32601})}}getDocument(e,t){let r=this.adapter.getDocument(),n=sZ(null==e?void 0:e.depth,1);if(r&&this.shouldRevealDocumentAfterUpdate){let e=this.pendingDocumentRevealSignaturePath?[...this.pendingDocumentRevealSignaturePath]:null;this.shouldRevealDocumentAfterUpdate=!1,window.setTimeout(()=>this.revealDocumentAfterUpdate(r,t,e),0)}return{root:r?this.nodeStore.toDocumentCdpNode(r,n):null}}getFlattenedDocument(){let e=this.getDocument({depth:-1}).root;return{nodes:e?function e(t){return[t,...(t.children??[]).flatMap(t=>e(t))]}(e):[]}}requestChildNodes(e,t){let r=Number(null==e?void 0:e.nodeId),n=this.nodeStore.resolveInspectorNodeId(r),a=sZ(null==e?void 0:e.depth,1),s=this.adapter.getDocument(),i=n===s3?null:this.findInspectorNode(n),o=n===s3?s?[this.nodeStore.toCdpNode(s,sY(a),r)]:[]:(null==i?void 0:i.children.map(e=>this.nodeStore.toCdpNode(e,sY(a),r)))??[];return this.emit({method:"DOM.setChildNodes",params:{parentId:r,nodes:o}},t),{}}pushNodesByBackendIdsToFrontend(e,t){let r=this.adapter.getDocument();return{nodeIds:(Array.isArray(null==e?void 0:e.backendNodeIds)?e.backendNodeIds:[]).map(e=>{let n=Number(e),a=this.nodeStore.getInspectorNodeId(n);return r&&a&&this.materializeInspectorNodePath(r,a,t)?n:0})}}materializeInspectorNodePath(e,t,r){let n=s2(e,t);if(!n)return!1;let a=this.nodeStore.getCdpNodeId(s3);for(let t of(this.emit({method:"DOM.setChildNodes",params:{parentId:a,nodes:[this.nodeStore.toCdpNode(e,0,a)]}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:a,childNodeCount:1}},r),n.slice(0,-1))){let e=this.nodeStore.getCdpNodeId(t.id),n=t.children.map(t=>this.nodeStore.toCdpNode(t,0,e));this.emit({method:"DOM.setChildNodes",params:{parentId:e,nodes:n}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:e,childNodeCount:n.length}},r)}return!0}revealDocumentAfterUpdate(e,t,r){if(!(null==r?void 0:r.length))return;let n=this.findInspectorNodeBySignaturePath(e,r??null),a=n??this.findDocumentRevealNode(e);if(!a||!this.materializeInspectorNodePath(e,a.id,t))return;let s=this.nodeStore.getCdpNodeId(a.id),i=!!n||!(null==r?void 0:r.length);this.selectInspectorNode(a.id,{rememberPreferred:i}),i&&(this.pendingDocumentRevealSignaturePath=null),this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:s}},t),this.emit({method:"Overlay.inspectNodeRequested",params:{backendNodeId:s}},t)}findDocumentRevealNode(e){let t=this.adapter.getSelectedNodeId();if(t){let r=s2(e,t);if(r)return r[r.length-1]}let r=this.findInspectorNodeBySignaturePath(e,this.selectedNodeSignaturePath);if(r)return r;let n=e;for(let e=0;e<3;e+=1){let e=n.children.find(e=>"element"===e.type);if(!e)break;n=e}return n}selectInspectorNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{rememberPreferred:!0};this.adapter.selectNode(e);let r=this.rememberSelectedNodePath(e);t.rememberPreferred&&r&&(this.preferredNodeSignaturePath=[...r])}rememberSelectedNodePath(e){let t=this.adapter.getDocument(),r=t?s2(t,e):null;if(r){let e=r.map(e=>({type:e.type,name:e.name,className:sX(e,"class"),id:sX(e,"id")}));return this.selectedNodeSignaturePath=e,e}return null}findInspectorNodeBySignaturePath(e,t){if(!(null==t?void 0:t.length)||!sQ(e,t[0]))return null;let r=e;for(let e of t.slice(1)){let t=r.children.find(t=>sQ(t,e));if(!t)return null;r=t}return r}resolveNode(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId));return{object:{objectId:`node:${t}`,type:"object",subtype:"node",className:"HTMLElement",description:t}}}describeNode(e){let t=Number((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.nodeStore.resolveInspectorNodeId(t),n=this.findInspectorNode(r),a=this.adapter.getDocument();return{node:r===s3&&a?this.nodeStore.toDocumentCdpNode(a):n?this.nodeStore.toCdpNode(n):null}}getAttributes(e){let t=this.findInspectorNode(this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId));return{attributes:t?sK(t):[]}}getOuterHTML(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.findInspectorNode(t),n=this.adapter.getDocument();return{outerHTML:t===s3&&n?s0(n):r?s0(r):""}}setAttributesAsText(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.text)??""),a="string"==typeof(null==e?void 0:e.name)?e.name:void 0,s=this.applyDomEdit(()=>this.adapter.setAttributesAsText(r,n,a));return this.emitDomMutations(s,t),{}}setAttributeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.name)??""),a=String((null==e?void 0:e.value)??""),s=this.applyDomEdit(()=>this.adapter.setAttributeValue(r,n,a));return this.emitDomMutations(s,t),{}}removeAttribute(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.name)??""),a=this.applyDomEdit(()=>this.adapter.removeAttribute(r,n));return this.emitDomMutations(a,t),{}}setNodeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.value)??""),a=this.applyDomEdit(()=>this.adapter.setNodeValue(r,n));return this.emitDomMutations(a,t),{}}setNodeName(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.name)??""),a=this.applyDomEdit(()=>this.adapter.setNodeName(r,n),!0);return this.emitDomMutations(a.mutations,t),{nodeId:a.nodeId?this.nodeStore.getCdpNodeId(a.nodeId):0}}setOuterHTML(e,t){let r=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),n=String((null==e?void 0:e.outerHTML)??""),a=this.applyDomEdit(()=>this.adapter.setOuterHTML(r,n),!0);return this.emitDomMutations(a,t),{}}applyDomEdit(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t?this.adapter.getDocument():null,n=r?this.createDomRootSnapshot(r):null,a=e(),s=Array.isArray(a)?a:a.mutations,i=s.filter(ia),o=null;return s.length>0&&i.length===s.length?o={type:"mutations",mutations:i}:s.length>0&&n&&(o=n),o&&this.rememberDomUndoEntry(o),a}createDomRootSnapshot(e){return{type:"rootSnapshot",rootHtml:"document"===e.type?s1(e):s0(e)}}emitDomMutations(e,t){for(let r of e){if("attributes"===r.type){for(let e of r.removed)this.emit({method:"DOM.attributeRemoved",params:{nodeId:this.nodeStore.getCdpNodeId(r.nodeId),name:e}},t);for(let e of r.modified)this.emit({method:"DOM.attributeModified",params:{nodeId:this.nodeStore.getCdpNodeId(r.nodeId),name:e.name,value:e.value}},t);continue}if("characterData"===r.type){this.emit({method:"DOM.characterDataModified",params:{nodeId:this.nodeStore.getCdpNodeId(r.nodeId),characterData:r.value}},t);continue}let e=this.nodeStore.getCdpNodeId(r.parentNodeId);for(let n of r.removedNodeIds)this.emit({method:"DOM.childNodeRemoved",params:{parentNodeId:e,nodeId:this.nodeStore.getCdpNodeId(n)}},t);for(let n of r.insertedNodes)this.emit({method:"DOM.childNodeInserted",params:{parentNodeId:e,previousNodeId:n.previousNodeId?this.nodeStore.getCdpNodeId(n.previousNodeId):0,node:this.nodeStore.toCdpNode(n.node,1/0,e)}},t);this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:e,childNodeCount:r.childNodeCount}},t)}}getMatchedStylesForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId);this.selectInspectorNode(t,{rememberPreferred:!this.pendingDocumentRevealSignaturePath&&!this.preferredNodeSignaturePath});let r=this.adapter.getMatchedStyles(t);return r?{inlineStyle:sB(`inline:${t}`,r.inlineStyle.declarations),attributesStyle:null,matchedCSSRules:r.matchedRules.map(e=>({matchingSelectors:[0],rule:this.toCdpRulePayload(e)})),pseudoElements:[],inherited:[],cssKeyframesRules:[]}:{inlineStyle:null,attributesStyle:null,matchedCSSRules:[],pseudoElements:[],inherited:[],cssKeyframesRules:[]}}getInlineStylesForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=this.adapter.getMatchedStyles(t);return{inlineStyle:r?sB(`inline:${t}`,r.inlineStyle.declarations):null,attributesStyle:null}}getComputedStyleForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=this.adapter.getMatchedStyles(t);return{computedStyle:((null==r?void 0:r.computedStyles)??[]).map(e=>({name:e.name,value:e.value}))}}resolveCssValues(e){return{results:Array.isArray(null==e?void 0:e.values)?e.values.map(String):[]}}setStyleTexts(e){let t=Array.isArray(null==e?void 0:e.edits)?e.edits:[],r=[];this.isApplyingStyleEdit=!0;try{for(let e of t){let t=String(e.styleSheetId??""),n=sW(String(e.text??"")),{id:a,kind:s}=sF(t),i=this.adapter.getSelectedNodeId(),o="inline"===s?a:i,l=this.getDeclarationsForStyleSheet(t);"inline"===s?this.adapter.setInlineDeclarations(a,n):"rule"===s&&i&&this.adapter.setRuleDeclarations(i,a,n),r.push(this.getStylePayloadForStyleSheet(t,n)),this.rememberStyleUndoEntry(t,o,l,this.getDeclarationsForStyleSheet(t))}}finally{this.isApplyingStyleEdit=!1}return{styles:r}}getStyleSheetText(e){let t=String((null==e?void 0:e.styleSheetId)??"");return{text:this.getStylePayloadForStyleSheet(t,[]).cssText}}setEffectivePropertyValueForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=String((null==e?void 0:e.propertyName)??(null==e?void 0:e.name)??""),n=String((null==e?void 0:e.value)??"");return r&&this.adapter.setInlineDeclaration(t,r,n),{}}addRule(e){let t=String((null==e?void 0:e.ruleText)??""),r=this.getRuleSelectorText(t),n=sW(t).map(e=>({...e,active:!0})),a=this.adapter.getSelectedNodeId(),s=a?this.adapter.addRule(a,r,n):null;return{rule:s?this.toCdpRulePayload(s):{origin:"inspector",selectorList:this.toSelectorList(r),style:sB("inspector:main",n)}}}setRuleSelector(e){let t=String((null==e?void 0:e.selector)??(null==e?void 0:e.text)??"").trim(),{id:r,kind:n}=sF(String((null==e?void 0:e.styleSheetId)??"")),a=this.adapter.getSelectedNodeId(),s="rule"===n&&a?this.adapter.setRuleSelector(a,r,t):null;return{selectorList:this.toSelectorList((null==s?void 0:s.selectorText)??t)}}evaluate(e){let t=String((null==e?void 0:e.expression)??""),r=this.adapter.evaluate(t);return{result:function(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return{type:t?"string":"object",subtype:t?void 0:"error",value:e,description:e}}(r.value,r.ok),exceptionDetails:r.ok?void 0:{text:r.value}}}getRuntimeProperties(e){let t="string"==typeof(null==e?void 0:e.objectId)?this.remoteObjectStore.get(e.objectId):void 0;return{result:function(e,t){if(!sA(e))return[];try{return Object.getOwnPropertyNames(e).map(r=>{let n=Object.getOwnPropertyDescriptor(e,r),a={name:r,configurable:(null==n?void 0:n.configurable)??!0,enumerable:(null==n?void 0:n.enumerable)??!0,isOwn:!0};return n&&"value"in n&&(a.value=sU(n.value,t),a.writable=n.writable),a})}catch{return[]}}(t,this.remoteObjectStore),internalProperties:function(e,t){if(!sA(e))return[];let r=Object.getPrototypeOf(e);return r?[{name:"[[Prototype]]",value:sU(r,t)}]:[]}(t,this.remoteObjectStore)}}clearConsole(){this.getConsoleAdapter().clearConsole(),this.clearAppConsole(),this.remoteObjects.clear()}clearConsoleForTargetScopeChange(){for(let e of(this.consoleStore.entries.length=0,this.knownConsoleEntryIdsBySession.clear(),this.parsedScriptIdsBySession.clear(),this.remoteObjects.clear(),this.runtimeEnabledSessions)){let t=this.getSessionId(e);this.emit({method:"Runtime.executionContextsCleared"},t),this.emitRuntimeExecutionContext(t),this.emitNewConsoleEntriesForSession(t,"app")}}clearAppConsole(){this.getAppAdapter(),0!==this.appConsoleStore.entries.length&&(this.appConsoleStore.entries.length=0,this.emit({method:"WSD.appConsoleUpdated"}))}highlightNode(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.options.getRuntimeFrame();return r?this.options.onHighlightChange(this.adapter.getNodeHighlight(t,r)):this.options.onHighlightChange(null),{}}sendPreactDevtoolsMessage(e){let t=JSON.stringify(e);for(let e of this.adapter.findLynxViews()){var r;null==(r=e.sendDevtoolEvent)||r.call(e,"PreactDevtools",t)}}highlightLynxNode(e){if(null==e)return void this.options.onHighlightChange(null);let t=this.options.getRuntimeFrame(),r=t?this.adapter.findNodeIdByLynxUniqueId(e):null;this.options.onHighlightChange(r&&t?this.adapter.getNodeHighlight(r,t):null)}setInspectMode(e,t){return"none"===String((null==e?void 0:e.mode)??"none")?this.stopInspectMode():this.startInspectMode(t),{}}startInspectMode(e){this.stopInspectMode();let t=this.options.getRuntimeFrame();t&&(this.stopInspectModeListener=function(e){let{frame:t,highlightNodeAtPoint:r,onHighlightChange:n,onNodeHighlightRequested:a,onNodeInspected:s}=e;t.classList.add("is-inspecting");let i=e=>{let t=r(e.clientX,e.clientY);t&&a(t)},o=()=>{n(null)},l=e=>{if(0!==e.button)return;let n=r(e.clientX,e.clientY);n&&(s4(e),function(e){let t=["mousedown","mouseup","pointerup","pointercancel","click","dblclick","auxclick","contextmenu"],r=[e,e.ownerDocument],n=e.ownerDocument.defaultView;n&&r.push(n);let a=null,s=()=>{for(let e of(null!==a&&(window.clearTimeout(a),a=null),r))for(let r of t)e.removeEventListener(r,i,!0)},i=e=>{s4(e),("click"===e.type||"dblclick"===e.type||"auxclick"===e.type)&&s()};for(let e of r)for(let r of t)e.addEventListener(r,i,!0);a=window.setTimeout(s,800)}(t),s(n))};return t.addEventListener("pointermove",i,!0),t.addEventListener("pointerleave",o,!0),t.addEventListener("pointerdown",l,!0),t.addEventListener("mousemove",i,!0),t.addEventListener("mouseleave",o,!0),t.addEventListener("mousedown",l,!0),()=>{t.classList.remove("is-inspecting"),t.removeEventListener("pointermove",i,!0),t.removeEventListener("pointerleave",o,!0),t.removeEventListener("pointerdown",l,!0),t.removeEventListener("mousemove",i,!0),t.removeEventListener("mouseleave",o,!0),t.removeEventListener("mousedown",l,!0),n(null)}}({frame:t,highlightNodeAtPoint:(e,t)=>this.highlightNodeAtPoint(e,t),onHighlightChange:this.options.onHighlightChange,onNodeHighlightRequested:t=>{this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:t.cdpNodeId}},e)},onNodeInspected:t=>{let r=this.adapter.getDocument();r&&this.materializeInspectorNodePath(r,t.inspectorNodeId,e),this.selectInspectorNode(t.inspectorNodeId,{rememberPreferred:!0}),this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:t.cdpNodeId}},e),this.emit({method:"Overlay.inspectNodeRequested",params:{backendNodeId:t.cdpNodeId}},e),this.stopInspectMode()}}))}stopInspectMode(){var e;null==(e=this.stopInspectModeListener)||e.call(this),this.stopInspectModeListener=null}highlightNodeAtPoint(e,t){var r,n;let a=null==(r=(n=this.options).resolveTargetAtPoint)?void 0:r.call(n,e,t);a&&this.setTarget(a);let s=this.adapter.getNodeIdAtPoint(e,t),i=this.options.getRuntimeFrame();return s&&i?(this.options.onHighlightChange(this.adapter.getNodeHighlight(s,i)),{cdpNodeId:this.nodeStore.getCdpNodeId(s),inspectorNodeId:s}):(this.options.onHighlightChange(null),null)}setStyleDeclaration(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=String((null==e?void 0:e.name)??"").trim(),n=String((null==e?void 0:e.value)??""),a="string"==typeof(null==e?void 0:e.ruleId)?e.ruleId:null;if(!r)throw Error("CSS property name is required");return a?this.adapter.setRuleDeclaration(t,a,r,n):this.adapter.setInlineDeclaration(t,r,n),{}}undo(e){let t=this.pendingUndoEntry??this.undoEntries.pop()??null;return(this.pendingUndoEntry=null,t)?"dom"===t.type?(this.undoDomEdit(t.entry,e)||(this.pendingUndoEntry=t),{}):this.undoStyleEdit(t.entry):{}}undoDomEdit(e,t){if("mutations"===e.type)return this.undoIncrementalDomMutations(e.mutations,t),!0;let r=this.adapter.getDocument();if(!r)return!1;let n=this.adapter.setOuterHTML(r.id,e.rootHtml);return 0!==n.length&&(this.emitDomMutations(n,t),!0)}undoIncrementalDomMutations(e,t){let r=[];for(let t of[...e].reverse())"attributes"===t.type?r.push(...this.restoreAttributeMutation(t)):r.push(...this.adapter.setNodeValue(t.nodeId,t.previousValue));this.emitDomMutations(r,t)}restoreAttributeMutation(e){let t=new Set(e.before.map(e=>e.name)),r=new Set(e.modified.map(e=>e.name)),n=new Set(e.removed),a=[];for(let r of e.modified)t.has(r.name)||a.push(...this.adapter.removeAttribute(e.nodeId,r.name));for(let t of e.before)(r.has(t.name)||n.has(t.name))&&a.push(...this.adapter.setAttributeValue(e.nodeId,t.name,t.value));return a}undoStyleEdit(e){return this.applyStyleDeclarations(e),{styleSheetId:e.styleSheetId}}markUndoableState(){return this.commitPendingUndoEntry(),{}}rememberDomUndoEntry(e){this.setPendingUndoEntry({type:"dom",entry:e})}rememberStyleUndoEntry(e,t,r,n){var a;t&&JSON.stringify(r)!==JSON.stringify(n)&&((null==(a=this.pendingUndoEntry)?void 0:a.type)!=="style"||this.pendingUndoEntry.entry.styleSheetId!==e||this.pendingUndoEntry.entry.nodeId!==t)&&this.setPendingUndoEntry({type:"style",entry:{styleSheetId:e,nodeId:t,previousDeclarations:ir(r)}})}setPendingUndoEntry(e){var t;((null==(t=this.pendingUndoEntry)?void 0:t.type)!=="style"||"style"!==e.type||this.pendingUndoEntry.entry.styleSheetId!==e.entry.styleSheetId||this.pendingUndoEntry.entry.nodeId!==e.entry.nodeId)&&(this.commitPendingUndoEntry(),this.pendingUndoEntry=e)}commitPendingUndoEntry(){this.pendingUndoEntry&&(this.pushUndoEntry(this.pendingUndoEntry),this.pendingUndoEntry=null)}pushUndoEntry(e){this.undoEntries.push(e),this.undoEntries.length>50&&this.undoEntries.shift()}applyStyleDeclarations(e){let{id:t,kind:r}=sF(e.styleSheetId);this.isApplyingStyleEdit=!0;try{"inline"===r?this.adapter.setInlineDeclarations(t,ir(e.previousDeclarations)):"rule"===r&&this.adapter.setRuleDeclarations(e.nodeId,t,ir(e.previousDeclarations))}finally{this.isApplyingStyleEdit=!1}this.emitSelectedStyleInvalidated(),this.emit({method:"CSS.styleSheetChanged",params:{styleSheetId:e.styleSheetId}})}getBoxModel(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.options.getRuntimeFrame(),n=r?this.adapter.getNodeHighlight(t,r):null,a=(null==n?void 0:n.left)??0,s=(null==n?void 0:n.top)??0,i=(null==n?void 0:n.width)??0,o=(null==n?void 0:n.height)??0,l=[a,s,a+i,s,a+i,s+o,a,s+o];return{model:{content:l,padding:l,border:l,margin:l,width:i,height:o}}}getFrameTree(){return{frameTree:{frame:{id:"wsd-main-frame",loaderId:"wsd-loader",url:"wsd://runtime",securityOrigin:"wsd://runtime",mimeType:"text/html"},resources:[]}}}getLayoutMetrics(){let e=this.options.getRuntimeFrame(),t=(null==e?void 0:e.offsetWidth)??0,r=(null==e?void 0:e.offsetHeight)??0;return{layoutViewport:{pageX:0,pageY:0,clientWidth:t,clientHeight:r},visualViewport:{offsetX:0,offsetY:0,pageX:0,pageY:0,clientWidth:t,clientHeight:r,scale:1,zoom:1},contentSize:{x:0,y:0,width:t,height:r}}}findInspectorNode(e){let t=this.adapter.getDocument();if(!t)return null;let r=[t];for(;r.length;){let t=r.shift();if(t){if(t.id===e)return t;r.push(...t.children)}}return null}getStylePayloadForStyleSheet(e,t){var r,n;let{id:a,kind:s}=sF(e),i=t.map(e=>({name:e.name,value:e.value,priority:e.priority,active:e.active}));if("inline"===s)return sB(e,(null==(r=this.adapter.getMatchedStyles(a))?void 0:r.inlineStyle.declarations)??i);if("rule"===s){let t=this.adapter.getSelectedNodeId(),r=t?null==(n=this.adapter.getMatchedStyles(t))?void 0:n.matchedRules.find(e=>e.id===a):null;return sB(e,(null==r?void 0:r.declarations)??i)}return sB(e,i)}getDeclarationsForStyleSheet(e){var t,r;let{id:n,kind:a}=sF(e);if("inline"===a)return ir((null==(t=this.adapter.getMatchedStyles(n))?void 0:t.inlineStyle.declarations)??[]);if("rule"===a){let e=this.adapter.getSelectedNodeId(),t=e?null==(r=this.adapter.getMatchedStyles(e))?void 0:r.matchedRules.find(e=>e.id===n):null;return ir((null==t?void 0:t.declarations)??[])}return[]}getRuleSelectorText(e){let t=e.indexOf("{");return t<0?e.trim():e.slice(0,t).trim()}toSelectorList(e){return{selectors:[{text:e,range:s$(0,e.length)}],text:e}}toCdpRulePayload(e){let t=`rule:${e.id}`,r=sB(t,e.declarations);return this.ensureStyleSheetAdded(t,r.cssText,"override"===e.source?"inspector":"regular"),{styleSheetId:t,origin:"override"===e.source?"inspector":"regular",selectorList:this.toSelectorList(e.selectorText),style:r}}ensureStyleSheetAdded(e,t,r){this.knownStyleSheetIds.has(e)||(this.knownStyleSheetIds.add(e),this.emit({method:"CSS.styleSheetAdded",params:{header:{styleSheetId:e,frameId:"wsd-main-frame",sourceURL:`wsd://styles/${e}`,origin:r,title:e,disabled:!1,isInline:!1,isMutable:!0,isConstructed:!0,startLine:0,startColumn:0,length:t.length,endLine:0,endColumn:t.length}}}))}toConsoleEntry(e){let t=this.toCdpStackTrace(e.stackTrace),r={...e,stackTrace:t,args:sq(e,this.remoteObjectStore)};return e.location&&(r.url=e.location.url,r.lineNumber=e.location.lineNumber,r.columnNumber=e.location.columnNumber),r}getSessionKey(e){return e??""}getSessionId(e){return e||void 0}getKnownConsoleEntryIds(e,t){let r=this.knownConsoleEntryIdsBySession.get(e)??new Map;this.knownConsoleEntryIdsBySession.set(e,r);let n=r.get(t)??new Set;return r.set(t,n),n}getParsedScriptIds(e){let t=this.parsedScriptIdsBySession.get(e)??new Set;return this.parsedScriptIdsBySession.set(e,t),t}getScriptId(e){let t=this.scriptIdsByUrl.get(e)??`wsd-script-${++this.nextScriptId}`;return this.scriptIdsByUrl.set(e,t),t}getScriptSource(e){let t=String((null==e?void 0:e.scriptId)??""),r=this.sourceScriptsById.get(t);return{scriptSource:(null==r?void 0:r.content)??""}}async loadSources(e){let t=++this.sourceLoadId,r=await sT(e);t===this.sourceLoadId&&(r&&this.sourceScriptsById.set(this.getScriptId(r.url),r),this.emitSourceScriptsForEnabledSessions())}emitSourceScriptsForEnabledSessions(){for(let e of this.debuggerEnabledSessions)this.emitSourceScripts(this.getSessionId(e))}emitSourceScripts(e){for(let t of this.sourceScriptsById.values())this.emitScriptParsed(t.url,e,t)}toCdpStackTrace(e){return e?{callFrames:e.callFrames.map(e=>({...e,scriptId:e.scriptId||(e.url?this.getScriptId(e.url):e.scriptId)}))}:void 0}registerRemoteObject(e){let t=`runtime:${++this.nextRemoteObjectId}`;return this.remoteObjects.set(t,e),t}emitScriptParsed(e,t,r){var n;let a=this.getSessionKey(t),s=this.getScriptId(e),i=this.getParsedScriptIds(a);if(!this.debuggerEnabledSessions.has(a)||i.has(s))return;i.add(s);let o=(null==r?void 0:r.content.split("\n"))??[""];this.emit({method:"Debugger.scriptParsed",params:{scriptId:s,url:e,startLine:0,startColumn:0,endLine:r?o.length-1:1,endColumn:r?(null==(n=o.at(-1))?void 0:n.length)??0:0,executionContextId:1,hash:"",executionContextAuxData:{isDefault:!0,frameId:"wsd-main-frame"},isLiveEdit:!1,hasSourceURL:!1,isModule:!1,length:(null==r?void 0:r.content.length)??0,sourceMapURL:null==r?void 0:r.sourceMapURL,scriptLanguage:"JavaScript"}},t)}emit(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];let a=r.length>0?r[0]:this.activeSessionId,s=a?{...e,sessionId:a}:e;for(let e of this.listeners)e(s)}emitRuntimeExecutionContext(e){this.emit({method:"Runtime.executionContextCreated",params:{context:{id:1,origin:"wsd://runtime",name:"Doubao",auxData:{isDefault:!0,frameId:"wsd-main-frame"}}}},e)}emitNewConsoleEntries(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"current";for(let t of this.runtimeEnabledSessions)this.emitNewConsoleEntriesForSession(this.getSessionId(t),e)}emitNewConsoleEntriesForSession(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"current",r=this.getSessionKey(e);if(!this.runtimeEnabledSessions.has(r))return;let n="app"===t?this.appConsoleStore.entries:this.getConsoleAdapter().getConsoleEntries(),a=this.getKnownConsoleEntryIds(r,t);for(let t of n){var s;if(a.has(t.id)||(a.add(t.id),"host"===t.source))continue;let r=this.toCdpStackTrace(t.stackTrace),n={type:"warn"===(s=t.level)?"warning":"eval"===s?"log":s,args:sq(t,this.remoteObjectStore),executionContextId:1,timestamp:t.timestamp};r&&(n.stackTrace=r),this.emit({method:"Runtime.consoleAPICalled",params:n},e)}}emitSelectedStyleInvalidated(){let e=this.adapter.getSelectedNodeId(),t=e?this.nodeStore.getExistingCdpNodeId(e):void 0;t&&this.emit({method:"DOM.inlineStyleInvalidated",params:{nodeIds:[t]}})}}let ii="AppletJSModule",io=["log","info","warn","error","debug"];function il(e,t,r){if("log"!==e)return null;let n=td(t)&&("string"==typeof t.message||Array.isArray(t.args))?{level:io.includes(t.level)?t.level:void 0,message:"string"==typeof t.message?t.message:void 0,args:Array.isArray(t.args)?t.args:void 0,stack:"string"==typeof t.stack?t.stack:void 0}:null;return n?r===ii?n:null:r!==ii?null:{level:"log",message:function(e){if("string"==typeof e)return e;if(void 0===e)return"undefined";try{return JSON.stringify(e)??String(e)}catch{return String(e)}}(t)}}class id{listeners=new Set;runtimeConsoleEvents=[];current=null;subscribe(e){return this.listeners.add(e),()=>void this.listeners.delete(e)}reset(){this.runtimeConsoleEvents.length=0,this.set(null)}destroy(){this.reset(),this.listeners.clear()}set(e){this.current=e,this.flush(),this.notify()}notify(){for(let e of this.listeners)e(this.current)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];!this.current||t?this.runtimeConsoleEvents.push(e):aG(this.current,e)}flush(){if(this.current)for(let e of this.runtimeConsoleEvents.splice(0))aG(this.current,e)}}let iu=new Set(["doubao.navigateTo","doubao.redirectTo","doubao.reLaunch","doubao.navigateBack","doubao.exitApp","doubao.close"]);function ic(e){return"string"==typeof e&&e.trim()?e.trim().replace(/^\/+/,""):void 0}function ip(e){return ic(null==e?void 0:e.path)??ic(null==e?void 0:e.id)}class im{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onExitApp;onError;apiEnvironment;previewTarget=new id;appPreviewTarget=new id;pagePathsByTarget=new WeakMap;targetObserver=null;runtime=null;runtimeManifestUrl=null;lastRenderOptions=null;isRuntimeTargetChanging=!1;deferredPagePath;constructor(e){if(!e.container)throw Error("Page preview controller requires a container element");this.container=e.container,this.fileSystemNamespace=e.fileSystemNamespace,this.nativeModulesCallHandler=e.nativeModulesCallHandler,this.webSdkDebugger=e.webSdkDebugger,this.onExitApp=e.onExitApp,this.onError=e.onError,this.apiEnvironment=e.apiEnvironment??aU(),"u">typeof MutationObserver&&(this.targetObserver=new MutationObserver(this.handleRuntimeContainerMutation),this.targetObserver.observe(this.container,{childList:!0}))}render(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=this.webSdkDebugger.getState(),n=!t.entry&&!t.pageId&&(null==(e=r.pageSelection)?void 0:e.routeUrl)?e3({url:r.pageSelection.routeUrl},r.manifest):void 0,a=(null==n?void 0:n.entry)??function(e,t){if(t.entry)return t.entry;if(t.pageId)return e.manifest.getPageEntry(t.pageId);if(!e.pageSelection)throw Error("No page selected");return e.pageSelection.item}(r,t),s=t.device??rf["0"],i=(null==n?void 0:n.initData)??t.initData??{},o=n?rb(s,{...t.globalProps,...n.globalProps}):t.globalProps??rb(s),l=this.getRuntime(r),d=ip(a);this.lastRenderOptions=t,this.isRuntimeTargetChanging=!0,this.deferredPagePath=d;try{let e=l.replacePage({entry:a,initData:i,globalProps:o,pageCapsule:t.pageCapsule??{statusBarHeight:s.statusBarHeight}});return this.bindPageTarget(e.element,d??ip(e.entry)),this.previewTarget.set(e.element),e.element}catch(e){throw this.syncCurrentRuntimeTarget(),e}finally{this.isRuntimeTargetChanging=!1,this.deferredPagePath=void 0,this.previewTarget.flush()}}getCurrentTarget(){return this.previewTarget.current}getCurrentAppTarget(){return this.appPreviewTarget.current}getPageStackSize(){var e;return(null==(e=this.runtime)?void 0:e.pages.length)??0}subscribeTarget(e){return this.previewTarget.subscribe(e)}subscribeAppTarget(e){return this.appPreviewTarget.subscribe(e)}closeCurrentPage(){var e;2>this.getPageStackSize()||(null==(e=this.runtime)||e.popPage(),this.syncCurrentRuntimeTarget())}reopenCurrentPage(){try{this.render(this.lastRenderOptions??{})}catch(t){var e;null==(e=this.onError)||e.call(this,t,new Event("error"))}}reload(){var e;null==(e=this.runtime)||e.reload(),this.previewTarget.notify()}clear(){var e;null==(e=this.runtime)||e.clear(),this.deferredPagePath=void 0,this.previewTarget.reset(),this.appPreviewTarget.reset()}destroy(){var e,t;null==(e=this.targetObserver)||e.disconnect(),null==(t=this.runtime)||t.destroy(),this.runtime=null,this.runtimeManifestUrl=null,this.previewTarget.destroy(),this.appPreviewTarget.destroy()}getRuntime(e){let t=e.manifestUrl;if(!this.runtime){let r={container:this.container,manifest:e.manifest,manifestUrl:t,apiRegistry:this.apiEnvironment.apiRegistry,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.handleNativeModulesCall,onError:this.onError,runtimeHost:{...this.apiEnvironment.runtimeHost,mountRuntimeEmptyState:e=>rI(e,()=>this.reopenCurrentPage())}};return this.runtime=new e6(r),this.runtimeManifestUrl=t,this.runtime}return this.runtimeManifestUrl!==t&&(this.previewTarget.set(null),this.appPreviewTarget.set(null),this.runtime.setManifest(e.manifest,t),this.runtimeManifestUrl=t),this.runtime}handleNativeModulesCall=(e,t,r,n)=>{var a;let s=function(e,t,r){if("AppletBridgeModule"===r&&"postMessage"===e&&"object"==typeof t&&null!==t&&"call"===t.type&&"string"==typeof t.name&&iu.has(t.name))return t.name}(e,t,r);s&&(this.deferredPagePath=this.getNavigationPagePath(t),this.scheduleRuntimeTargetSync("doubao.exitApp"===s?this.onExitApp:void 0));let i=il(e,t,r);if(i){if((null==n?void 0:n.containerType)==="APP")this.syncAppRuntimeTarget(n.element),this.appPreviewTarget.dispatch({...i,label:"app"});else{let e=this.getRuntimeConsolePagePath(n);this.previewTarget.dispatch(e?{...i,pagePath:e}:i,this.isRuntimeTargetChanging)}return}return null==(a=this.nativeModulesCallHandler)?void 0:a.call(this,e,t,r,n)};handleRuntimeContainerMutation=()=>{this.syncCurrentRuntimeTarget(),this.syncAppRuntimeTarget()};scheduleRuntimeTargetSync(e){var t;this.isRuntimeTargetChanging=!0,t=()=>{this.syncCurrentRuntimeTarget(),this.isRuntimeTargetChanging=!1,this.deferredPagePath=void 0,this.previewTarget.flush(),null==e||e()},"function"==typeof queueMicrotask?queueMicrotask(t):Promise.resolve().then(t)}syncCurrentRuntimeTarget(){var e;let t=(null==(e=this.runtime)?void 0:e.currentPage)??null,r=(null==t?void 0:t.element)??null;(r&&this.bindPageTarget(r,this.getCurrentPagePath()),this.previewTarget.current===r)?this.previewTarget.flush():this.previewTarget.set(r)}syncAppRuntimeTarget(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.getAppRuntimeElement();this.appPreviewTarget.current===e?this.appPreviewTarget.flush():this.appPreviewTarget.set(e)}getAppRuntimeElement(){return this.container.querySelector('lynx-view[data-container-type="APP"]')}bindPageTarget(e,t){e&&t&&this.pagePathsByTarget.set(e,t)}getNavigationPagePath(e){var t;if("object"!=typeof e||null===e)return;let r=null==(t=e.params)?void 0:t.url;if("string"==typeof r)try{return ip(e3({url:r},this.webSdkDebugger.getState().manifest).entry)}catch{return ic(r.split("?")[0])}}getCurrentPagePath(){var e;let t=null==(e=this.runtime)?void 0:e.currentPage;return ip(null==t?void 0:t.entry)??ic(null==t?void 0:t.route)??ic(null==t?void 0:t.pageId)}getRuntimeConsolePagePath(e){var t,r;if((null==e?void 0:e.containerType)!=="PAGE")return;let n=this.pagePathsByTarget.get(e.element)??this.deferredPagePath??this.getCurrentPagePath();return this.bindPageTarget(null==(r=this.runtime)||null==(t=r.currentPage)?void 0:t.element,n),n}}class ih{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onError;apiEnvironment;previewTarget=new id;widget=null;constructor(e){if(!e.container)throw Error("Widget preview controller requires a container element");this.container=e.container,this.fileSystemNamespace=e.fileSystemNamespace,this.nativeModulesCallHandler=e.nativeModulesCallHandler,this.webSdkDebugger=e.webSdkDebugger,this.onError=e.onError,this.apiEnvironment=e.apiEnvironment??aU()}async render(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.webSdkDebugger.getState(),r=function(e,t){if(t.widgetId)return t.widgetId;if(!e.widgetSelection)throw Error("No widget selected");return e.widgetSelection.item.widgetId}(t,e),n=e.viewport??ry,a=tl(e.initData??{}),s=e.globalProps??rw(n);this.clear(),this.widget=new eZ({appId:t.manifest.appId,apiRegistry:this.apiEnvironment.apiRegistry,container:this.container,fileSystemNamespace:this.fileSystemNamespace,globalProps:s,initData:a,nativeModulesCallHandler:this.handleNativeModulesCall,onError:this.onError,runtimeHost:this.apiEnvironment.runtimeHost,widgetId:r});let i=await this.widget.render();return this.previewTarget.set(i),i}getCurrentTarget(){return this.previewTarget.current}subscribeTarget(e){return this.previewTarget.subscribe(e)}reload(){var e,t;null==(e=this.widget)||e.reload(),this.previewTarget.set((null==(t=this.widget)?void 0:t.element)??null)}clear(){this.disposeWidget(),this.previewTarget.reset()}destroy(){this.disposeWidget(),this.previewTarget.destroy()}disposeWidget(){var e;null==(e=this.widget)||e.destroy(),this.widget=null,this.container.replaceChildren()}handleNativeModulesCall=(e,t,r)=>{var n;let a=il(e,t,r);return a?void this.previewTarget.dispatch(a):null==(n=this.nativeModulesCallHandler)?void 0:n.call(this,e,t,r)}}let ig=(0,e9.createContext)(null);function iv(e){let t=function(e){let t=(0,e9.useContext)(ig),r=e??t;if(!r)throw Error("WebSdkDebuggerProvider is missing");return r}(e),r=(0,e9.useCallback)(e=>t.subscribe(e),[t]),n=(0,e9.useCallback)(()=>t.getState(),[t]);return(0,e9.useSyncExternalStore)(r,n,n)}function iy(e){let t=(0,e9.useRef)(e);t.current=e;let r=(0,e9.useRef)();return r.current??=function(){for(var e=arguments.length,r=Array(e),n=0;n<e;n++)r[n]=arguments[n];return t.current(...r)},r.current}function i_(e){let{fallbackName:t,selector:r}=e;return r?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("span",{className:"wsd-runtime-highlight-selector-tag",children:r.tagName}),r.id?(0,s.jsxs)("span",{className:"wsd-runtime-highlight-selector-id",children:["#",r.id]}):null,r.classNames.map(e=>(0,s.jsxs)("span",{className:"wsd-runtime-highlight-selector-class",children:[".",e]},e))]}):(0,s.jsx)("span",{className:"wsd-runtime-highlight-selector-tag",children:t??"element"})}function ib(e){let{focusable:t}=e;return t?(0,s.jsx)("span",{children:"true"}):(0,s.jsx)("span",{"aria-label":"not focusable",className:"wsd-runtime-highlight-not-focusable"})}function iw(e){var t,r,n,a,i;let{highlightRect:o,overlay:l,runtimeFrameRef:d,runtimeFrameScaleBoxRef:u,runtimeScaleMode:c,runtimeShellRef:p,runtimeStyle:m,runtimeTargetRef:h}=e,g=(0,e9.useRef)(null),[f,v]=(0,e9.useState)(null),y=function(e,t){let r=e[t];if("number"==typeof r)return r;if("string"!=typeof r)return null;let n=Number.parseFloat(r);return Number.isFinite(n)?n:null}(m,"--wsd-runtime-height"),_=o&&f&&null!==y&&o.top+o.height+f.gap+f.height>y&&o.top>f.gap+f.height,b=o?{"--wsd-highlight-content-height":`${(null==(t=o.boxModel)?void 0:t.content.height)??o.height}px`,"--wsd-highlight-content-left":`${(null==(r=o.boxModel)?void 0:r.content.left)??0}px`,"--wsd-highlight-content-top":`${(null==(n=o.boxModel)?void 0:n.content.top)??0}px`,"--wsd-highlight-content-width":`${(null==(a=o.boxModel)?void 0:a.content.width)??o.width}px`,"--wsd-highlight-height":`${o.height}px`,"--wsd-highlight-left":`${o.left}px`,"--wsd-highlight-top":`${o.top}px`,"--wsd-highlight-width":`${o.width}px`}:void 0,w=iy(e=>{let t=Number.parseFloat(getComputedStyle(e).getPropertyValue("--wsd-highlight-popover-gap")),r={gap:Number.isFinite(t)?t:0,height:e.offsetHeight};v(e=>(null==e?void 0:e.gap)===r.gap&&e.height===r.height?e:r)}),S=iy(e=>{var t;if(null==(t=g.current)||t.disconnect(),g.current=null,!e||(w(e),"u"<typeof ResizeObserver))return;let r=new ResizeObserver(()=>w(e));r.observe(e),g.current=r});return(0,s.jsx)("section",{className:"wsd-device-preview","data-scale-mode":c,ref:p,children:(0,s.jsx)("div",{className:"wsd-device-preview-scale-box",ref:u,style:m,children:(0,s.jsxs)("div",{className:"wsd-device-preview-frame",ref:d,children:[h?(0,s.jsx)("div",{className:"wsd-runtime-target",ref:h}):null,o?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-runtime-highlight",style:b,children:(0,s.jsx)("div",{className:"wsd-runtime-highlight-content-frame"})}),(0,s.jsxs)("div",{"aria-hidden":"true",className:(0,eJ.$)("wsd-runtime-highlight-popover",_&&"is-above"),ref:S,style:b,children:[(0,s.jsxs)("div",{className:"wsd-runtime-highlight-header",children:[(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-runtime-highlight-node-icon"}),(0,s.jsx)("strong",{className:"wsd-runtime-highlight-selector",children:(0,s.jsx)(i_,{fallbackName:o.nodeName,selector:o.selector})}),(0,s.jsx)("span",{className:"wsd-runtime-highlight-dimensions",children:o.dimensions??`${o.width} \xd7 ${o.height}`})]}),(null==(i=o.styles)?void 0:i.length)?(0,s.jsx)("dl",{className:"wsd-runtime-highlight-details",children:o.styles.map(e=>(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:e.name}),(0,s.jsxs)("dd",{children:[e.swatch?(0,s.jsx)("span",{className:"wsd-runtime-highlight-swatch",style:{backgroundColor:e.swatch}}):null,(0,s.jsx)("span",{children:e.value})]})]},e.name))}):null,o.accessibility?(0,s.jsxs)("section",{className:"wsd-runtime-highlight-accessibility",children:[(0,s.jsx)("div",{className:"wsd-runtime-highlight-section-title",children:(0,s.jsx)("span",{children:"ACCESSIBILITY"})}),(0,s.jsxs)("dl",{className:"wsd-runtime-highlight-details",children:[(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:"Name"}),(0,s.jsx)("dd",{children:o.accessibility.name})]}),(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:"Role"}),(0,s.jsx)("dd",{children:o.accessibility.role})]}),(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:"Keyboard-focusable"}),(0,s.jsx)("dd",{children:(0,s.jsx)(ib,{focusable:o.accessibility.keyboardFocusable})})]})]})]}):null]})]}):null,l]})})})}function iS(e){let t,r,n,{cashier:a,onCancel:i,onConfirm:o}=e,[l,d]=(0,e9.useState)(!1),[u,c]=(0,e9.useState)(""),[p,m]=(0,e9.useState)(a.paymentTypes[0].id),h=a.paymentTypes.find(e=>{let{id:t}=e;return t===p})||a.paymentTypes[0],g=a.paymentTypes.length>1,f=async()=>{if(!l){d(!0),c("");try{await o(p)}catch(e){d(!1),c(n0(e))}}};return(0,s.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-sandbox-cashier-layer",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop wsd-sandbox-cashier-backdrop"}),(0,s.jsxs)("dialog",{"aria-label":"支付收银台","aria-modal":"true",className:"wsd-sandbox-cashier",open:!0,children:[(0,s.jsx)("button",{"aria-label":"关闭收银台",className:"wsd-sandbox-cashier-close",disabled:l,onClick:i,type:"button",children:"×"}),(0,s.jsx)("section",{className:"wsd-sandbox-cashier-amount",children:(0,s.jsx)("strong",{children:(r=(t=a.totalAmount.replace(/^0+(?=\d)/,"").padStart(3,"0")).slice(0,-2)||"0",n=t.slice(-2),`\xa5${r.replace(/\B(?=(\d{3})+(?!\d))/g,",")}.${n}`)})}),(0,s.jsxs)("section",{className:"wsd-sandbox-cashier-payment",children:[(0,s.jsx)("h2",{children:"支付方式"}),g?(0,s.jsx)("div",{className:"wsd-sandbox-cashier-payment-options",children:a.paymentTypes.map(e=>{let t=e.id===p;return(0,s.jsxs)("button",{"aria-pressed":t,className:"wsd-sandbox-cashier-payment-option",disabled:l,onClick:()=>{m(e.id)},type:"button",children:[(0,s.jsx)("span",{children:e.name}),t?(0,s.jsx)("span",{"aria-hidden":"true",children:"✓"}):null]},e.id)})}):(0,s.jsx)("div",{className:"wsd-sandbox-cashier-payment-trigger is-static",children:h.name}),u?(0,s.jsxs)("p",{className:"wsd-sandbox-cashier-error",role:"alert",children:["支付失败,请重试:",u]}):null]}),(0,s.jsx)("footer",{className:"wsd-sandbox-cashier-actions",children:(0,s.jsx)("button",{"aria-busy":l,className:"wsd-sandbox-cashier-button",disabled:l,onClick:()=>void f(),type:"button",children:l?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("svg",{"aria-hidden":"true",className:"wsd-sandbox-cashier-spinner",viewBox:"0 0 16 16",children:[(0,s.jsx)("circle",{className:"wsd-sandbox-cashier-spinner-track",cx:"8",cy:"8",fill:"none",r:"6",strokeWidth:"2"}),(0,s.jsx)("path",{className:"wsd-sandbox-cashier-spinner-indicator",d:"M 8 2 A 6 6 0 0 1 14 8",fill:"none",strokeLinecap:"round",strokeWidth:"2"})]}),"支付中"]}):"模拟支付"})})]})]})}function ix(){let[e,t]=(0,e9.useState)(),r=(0,e9.useRef)(null),n=(0,e9.useRef)(null),a=(0,e9.useRef)(!1),s=iy((e,a)=>r.current?Promise.reject(Error("Sandbox cashier is already open")):new Promise(s=>{r.current=s,n.current=a,t(e)})),i=iy(e=>{let a=r.current;a&&(r.current=null,n.current=null,t(void 0),a(e))}),o=iy(()=>{a.current||i(!1)}),l=iy(async e=>{let t=n.current;if(!t)throw Error("Sandbox cashier is unavailable");if(!a.current){a.current=!0;try{await t(e),i(!0)}finally{a.current=!1}}});return(0,e9.useEffect)(()=>()=>{let e=r.current;r.current=null,n.current=null,a.current=!1,null==e||e(!1)},[]),{cashier:e,cancelCashier:o,confirmCashier:l,showCashier:s}}let iI=new WeakMap;async function iE(e,t,r){iI.set(e,t);try{await e.sendSimulatorQuery(r)}finally{iI.get(e)===t&&iI.delete(e)}}function iC(e,t){let r=iI.get(e);if(r&&(!t||r===t))return iI.delete(e),e.cancelSimulatorQuery(),r}var ik=e=>(0,s.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:15,height:15,fill:"none",viewBox:"0 0 15 15",...e,children:[(0,s.jsx)("path",{fill:"#999",fillRule:"evenodd",d:"M7.333 4.545a2.788 2.788 0 1 0 0 5.576 2.788 2.788 0 0 0 0-5.576m0 1.334a1.455 1.455 0 1 0 0 2.909 1.455 1.455 0 0 0 0-2.91",clipRule:"evenodd"}),(0,s.jsx)("path",{fill:"#999",fillRule:"evenodd",d:"M5.067 1.862c.489-2.483 4.045-2.483 4.533 0 2.1-1.41 4.615 1.104 3.205 3.205 2.482.489 2.482 4.044 0 4.533 1.41 2.1-1.104 4.615-3.205 3.205-.488 2.483-4.044 2.482-4.533 0-2.1 1.41-4.615-1.104-3.205-3.205-2.483-.488-2.483-4.045 0-4.533-1.41-2.1 1.105-4.615 3.205-3.205m1.307.266c.202-1.06 1.718-1.06 1.92 0a1.322 1.322 0 0 0 2.042.846c.891-.607 1.964.466 1.357 1.357a1.322 1.322 0 0 0 .846 2.043c1.06.201 1.06 1.718 0 1.92a1.322 1.322 0 0 0-.846 2.042c.607.891-.466 1.963-1.357 1.357a1.322 1.322 0 0 0-2.042.846c-.202 1.06-1.719 1.06-1.92 0a1.322 1.322 0 0 0-2.043-.846c-.891.607-1.963-.466-1.357-1.357a1.322 1.322 0 0 0-.846-2.043c-1.06-.201-1.06-1.718 0-1.92l.44-.083A1.028 1.028 0 0 0 3.225 4.7l-.251-.37c-.607-.891.466-1.964 1.357-1.357a1.322 1.322 0 0 0 2.043-.846",clipRule:"evenodd"})]});function iN(){return(0,s.jsxs)("div",{className:"wsd-doubao-status-bar","aria-hidden":"true",children:[(0,s.jsx)("span",{className:"wsd-doubao-status-time",children:"9:41"}),(0,s.jsx)("span",{className:"wsd-doubao-status-indicators"})]})}function iM(e){let{className:t,fallback:r,src:n}=e,[a,i]=(0,e9.useState)(!1);return(0,e9.useEffect)(()=>{i(!1)},[n]),(0,s.jsx)("span",{className:`${t}-box`,"aria-hidden":"true",children:n&&!a?(0,s.jsx)("img",{alt:"",className:t,onError:()=>i(!0),src:n}):(0,s.jsx)("span",{className:`${t}-fallback`,children:(null==r?void 0:r.trim().slice(0,1))||"服"})})}function iR(e){let t=Number(e);if(!Number.isFinite(t))return;let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}function iT(e){let{notices:t,onAction:r,onBack:n,status:a}=e;return(0,s.jsxs)("section",{"aria-label":"服务通知",className:"wsd-service-notice-panel",children:[(0,s.jsxs)("header",{className:"wsd-service-notice-chrome",children:[(0,s.jsx)(iN,{}),(0,s.jsxs)("div",{className:"wsd-service-notice-title-bar",children:[(0,s.jsx)("button",{"aria-label":"返回对话",className:"wsd-service-notice-nav-button is-back",onClick:n,type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})}),(0,s.jsx)("h1",{children:"服务通知"}),(0,s.jsx)("button",{"aria-label":"服务通知设置",className:"wsd-service-notice-nav-button is-settings",type:"button",children:(0,s.jsx)(ik,{"aria-hidden":"true"})})]})]}),(0,s.jsx)("div",{className:"wsd-service-notice-list",children:"loading"===a&&0===t.length?(0,s.jsx)("p",{className:"wsd-service-notice-empty",children:"正在加载服务通知..."}):t.length>0?t.map(e=>{let t=e.title||"服务通知",n=iR(e.created_at_ms),a=e.redirect_url;return(null==a?void 0:a.startsWith("sslocal://"))&&(a=""),(0,s.jsxs)("div",{className:"wsd-service-notice-item",children:[(0,s.jsx)("time",{dateTime:null==n?void 0:n.toISOString(),children:function(e){let t=iR(e);if(!t)return"";let r=new Date,n=new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime(),a=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),s=new Intl.DateTimeFormat("zh-CN",{hour:"2-digit",hour12:!1,minute:"2-digit"}).format(t);return a===n?s:a===n-864e5?`昨天 ${s}`:`${t.getMonth()+1}月${t.getDate()}日 ${s}`}(e.created_at_ms)}),(0,s.jsxs)("article",{"aria-label":a?`${t},查看详情`:void 0,className:`wsd-service-notice-card${a?" is-clickable":""}`,onClick:()=>{a&&(null==r||r(a))},onKeyDown:e=>{a&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),null==r||r(a))},role:a?"link":void 0,tabIndex:a?0:void 0,children:[(0,s.jsxs)("div",{className:"wsd-service-notice-app",children:[(0,s.jsx)(iM,{className:"wsd-service-notice-icon",fallback:e.app_name,src:e.app_icon_url}),(0,s.jsx)("span",{children:e.app_name||"智能服务"})]}),(0,s.jsxs)("div",{className:"wsd-service-notice-body",children:[(0,s.jsx)("h2",{children:t}),e.fields.length>0?(0,s.jsx)("dl",{children:e.fields.map((e,t)=>(0,s.jsxs)("div",{children:[(0,s.jsx)("dt",{children:e.name}),(0,s.jsx)("dd",{children:e.value})]},`${e.name}-${t}`))}):e.brief?(0,s.jsx)("p",{children:e.brief}):null]})]})]},e.notice_id)}):(0,s.jsx)("p",{className:"wsd-service-notice-empty",children:"暂无服务通知"})})]})}let iA=new Set([1,2,3]);function iP(e){return e.filter(e=>1!==e.display_status&&iA.has(e.status))}function ij(e){let{onAction:t,onClose:r,onRemove:n,removingTaskIds:a,tasks:i}=e,o=iP(i);async function l(e){var r,a;let s=null==(r=e.remove_action)?void 0:r.confirm;(null==s||!s.need_confirm||window.confirm([s.title||"移除任务",s.content||"确定要移除这个任务吗?"].join("\n")))&&((null==(a=e.remove_action)?void 0:a.target)&&await (null==t?void 0:t(e.remove_action.target)),await n(e.task_id))}return((0,e9.useEffect)(()=>{let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[r]),(0,e9.useEffect)(()=>{0===o.length&&r()},[o.length,r]),0===o.length)?null:(0,s.jsxs)("div",{className:"wsd-sandbox-task-overlay-layer",children:[(0,s.jsx)("button",{"aria-label":"关闭进行中的任务",className:"wsd-sandbox-task-overlay-backdrop",onClick:r,type:"button"}),(0,s.jsx)("dialog",{"aria-label":"进行中的任务","aria-modal":"true",className:"wsd-sandbox-task-overlay",open:!0,children:(0,s.jsx)("div",{className:"wsd-sandbox-task-list",children:o.map(e=>{var r,n,i,o,d,u;let c=(null==(r=e.display_data)?void 0:r.title)||"未命名任务",p=(null==(n=e.display_data)?void 0:n.sub_title)||(null==(i=e.progress)?void 0:i.text),m=null==(o=e.primary_action)?void 0:o.target,h=a.has(e.task_id);return(0,s.jsxs)("article",{"aria-label":m?`${c},${(null==(d=e.primary_action)?void 0:d.text)||"查看详情"}`:void 0,className:(0,eJ.A)("wsd-sandbox-task-card",m&&"is-clickable"),onClick:()=>{m&&(null==t||t(m))},onKeyDown:e=>{m&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),null==t||t(m))},role:m?"button":void 0,tabIndex:m?0:void 0,children:[(0,s.jsx)(iM,{className:"wsd-sandbox-task-icon",fallback:c,src:null==(u=e.display_data)?void 0:u.icon_url}),(0,s.jsxs)("span",{className:"wsd-sandbox-task-copy",children:[(0,s.jsx)("strong",{children:c}),p?(0,s.jsx)("span",{children:p}):null]}),(0,s.jsx)("button",{"aria-label":`移除任务:${c}`,className:"wsd-sandbox-task-remove",disabled:h,onClick:t=>{t.stopPropagation(),l(e)},type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})})]},e.task_id)})})})]})}let iD={hasUnreadNotices:!1,hasUnreadTasks:!1,markServiceNoticesRead:()=>void 0,markTasksRead:()=>void 0,notices:[],removeTask:async()=>void 0,removingTaskIds:new Set,status:"unavailable",tasks:[]},iL=(0,e9.createContext)(iD);function iO(e,t){try{let r=BigInt(e),n=BigInt(t);return r===n?0:r>n?1:-1}catch{return String(e).localeCompare(String(t),void 0,{numeric:!0})}}function iU(e){if(eK(e)&&("remove"===e.action||"upsert"===e.action)&&("notice"===e.resource||"task"===e.resource)&&"string"==typeof e.resourceId&&("number"==typeof e.revision||"string"==typeof e.revision)&&"number"==typeof e.sequence)return{action:e.action,eventId:"string"==typeof e.eventId?e.eventId:"",occurredAtMs:"number"==typeof e.occurredAtMs?e.occurredAtMs:void 0,resource:e.resource,resourceId:e.resourceId,revision:e.revision,sequence:e.sequence}}function iq(e){let{children:t,enabled:r,eventsEndpoint:n,onMessage:a}=e,[i,o]=(0,e9.useState)([]),[l,d]=(0,e9.useState)([]),[u,c]=(0,e9.useState)(!1),[p,m]=(0,e9.useState)(!1),[h,g]=(0,e9.useState)(r&&n?"loading":"unavailable"),[f,v]=(0,e9.useState)(new Set),y=(0,e9.useRef)(new Map),_=(0,e9.useRef)(new Map),b=(0,e9.useRef)(new Map),w=(0,e9.useRef)(new Map),S=(0,e9.useRef)({notice:void 0,task:void 0}),x=(0,e9.useRef)({}),I=(0,e9.useRef)(0),E=(0,e9.useRef)(a);E.current=a;let C=iy(()=>{o([...y.current.values()].sort((e,t)=>Number(e.created_at_ms)-Number(t.created_at_ms)))}),k=iy(()=>{d([..._.current.values()].sort((e,t)=>Number(t.updated_at_ms)-Number(e.updated_at_ms)))}),N=iy(e=>{let t=!1;for(let r of e.notices??[]){let e=b.current.get(r.notice_id);(void 0===e||iO(r.revision,e)>0)&&(b.current.set(r.notice_id,r.revision),y.current.set(r.notice_id,r),t=!0)}for(let t of e.removed_notices??[]){let e=b.current.get(t.resource_id);(void 0===e||iO(t.revision,e)>=0)&&(b.current.set(t.resource_id,t.revision),y.current.delete(t.resource_id))}t&&c(!0),C()}),M=iy(e=>{let t=w.current.get(e.resource_id);(void 0===t||iO(e.revision,t)>=0)&&(w.current.set(e.resource_id,e.revision),_.current.delete(e.resource_id),k())}),R=iy(e=>{let t=!1;for(let r of e.tasks??[]){let e=w.current.get(r.task_id);void 0!==e&&0>=iO(r.revision,e)||(w.current.set(r.task_id,r.revision),t=!0,1===r.display_status?_.current.delete(r.task_id):_.current.set(r.task_id,r))}for(let r of e.removed_tasks??[]){let e=w.current.get(r.resource_id);(void 0===e||iO(r.revision,e)>=0)&&(w.current.set(r.resource_id,r.revision),_.current.delete(r.resource_id),t=!0)}t&&m(!0),k()}),T=iy(async(e,t)=>{let r=!1;do{let n=S.current[e],a="notice"===e?await ae({cursor:n,limit:100}):await at({cursor:n,limit:100});if(I.current!==t)return;if("notice"===e?N(a):R(a),a.has_more&&!a.next_cursor)throw Error(`Sandbox ${e} pull returned has_more without next_cursor`);a.next_cursor&&(S.current[e]=a.next_cursor),r=a.has_more}while(r)}),A=iy((e,t)=>{let r=x.current[e];if(r)return r;let n=T(e,t).finally(()=>{x.current[e]===n&&delete x.current[e]});return x.current[e]=n,n}),P=iy(async(e,t)=>{if(I.current===t){if("remove"===e.action){let t={resource_id:e.resourceId,revision:e.revision,updated_at_ms:e.occurredAtMs??Date.now()};if("notice"===e.resource){let t=b.current.get(e.resourceId);(void 0===t||iO(e.revision,t)>=0)&&(b.current.set(e.resourceId,e.revision),y.current.delete(e.resourceId),C())}else M(t);return}if("notice"===e.resource){let r=await ae({notice_ids:[e.resourceId]});I.current===t&&N(r)}else{let r=await at({task_ids:[e.resourceId]});I.current===t&&R(r)}}}),j=iy(()=>{y.current.clear(),_.current.clear(),b.current.clear(),w.current.clear(),S.current={notice:void 0,task:void 0},x.current={},c(!1),m(!1),o([]),d([])});(0,e9.useEffect)(()=>{let e,t,a;if(!r||!n){I.current+=1,j(),g("unavailable");return}let s=!1,i=++I.current,o=!1,l=0,d=0,u=-1,c=!1;j(),g("loading");let p=e=>{var t;if(s)return;let r=e instanceof Error?e.message:String(e);g("error"),null==(t=E.current)||t.call(E,`Sandbox 资源同步失败:${r}`,!0)},m=e=>!!function(e){if(!(e instanceof nK))return!1;let t=e.remoteCode??e.options.httpStatus;return -1===t||401===t||403===t||404===t}(e)&&(c||(c=!0,p(e)),!0),h=()=>c?Promise.resolve():Promise.all([A("notice",i),A("task",i)]);h().then(()=>{s||c||I.current!==i||(o=!0,g("reconnecting"===a?"reconnecting":"connected"))}).catch(e=>{m(e)||p(e)});let f=async()=>{t=new AbortController;try{let e=await fetch(n,{cache:"no-store",headers:{Accept:"application/json"},signal:t.signal});if(!e.ok)throw Error(`资源事件接口请求失败(HTTP ${e.status})`);let r=function(e){if(eK(e)&&["connected","connecting","reconnecting"].includes(String(e.connectionStatus))&&"number"==typeof e.generation&&"number"==typeof e.updatedAtMs)return{connectionStatus:e.connectionStatus,events:Array.isArray(e.events)?e.events.map(iU).filter(e=>!!e):[],generation:e.generation,updatedAtMs:e.updatedAtMs}}(await e.json());if(!r)throw Error("资源事件接口返回格式错误");if(s)return;let p=r.connectionStatus!==a;if(a=r.connectionStatus,r.updatedAtMs!==u){if(u=r.updatedAtMs,0===d?d=r.generation:r.generation!==d&&(d=r.generation,l=0,c=!1,i=++I.current,o=!1,j(),g("loading"),await h(),o=!0),c)return;let e=r.events.filter(e=>e.sequence>l).sort((e,t)=>e.sequence-t.sequence);for(let t of(l>0&&e[0]&&e[0].sequence>l+1&&await h(),e))await P(t,i),l=Math.max(l,t.sequence)}if(c)return;"reconnecting"===r.connectionStatus&&p?(g("reconnecting"),await h()):o&&"connected"===r.connectionStatus&&g("connected")}catch(e){s||(null==t?void 0:t.signal.aborted)||m(e)||g("reconnecting")}finally{s||(e=window.setTimeout(f,800))}};return f(),()=>{s=!0,I.current+=1,null==t||t.abort(),void 0!==e&&window.clearTimeout(e)}},[r,n,A,P,j]);let D=iy(async e=>{v(t=>new Set(t).add(e));try{let t=await ar(e);M(t)}finally{v(t=>{let r=new Set(t);return r.delete(e),r})}}),L=iy(()=>{c(!1)}),O=iy(()=>{m(!1)}),U=(0,e9.useMemo)(()=>({hasUnreadNotices:u,hasUnreadTasks:p,markServiceNoticesRead:L,markTasksRead:O,notices:i,removeTask:D,removingTaskIds:f,status:h,tasks:l}),[u,p,L,O,i,D,f,h,l]);return(0,s.jsx)(iL.Provider,{value:U,children:t})}var i$=r(64031),iB=r(88460);let iF={a(e){let{children:t,href:r}=e;return r&&function(e){if(!e)return!1;if(e.startsWith("#"))return!0;try{let t=new URL(e,"http://localhost");return["http:","https:","mailto:"].includes(t.protocol)}catch{return!1}}(r)?(0,s.jsx)("a",{href:r,rel:"noreferrer",target:"_blank",children:t}):(0,s.jsx)(s.Fragment,{children:t})}};function iW(e){let{text:t}=e;return(0,s.jsx)("div",{className:"wsd-widget-chat-text markdown-body wsd-widget-chat-markdown",children:(0,s.jsx)(i$.oz,{components:iF,remarkPlugins:[iB.A],children:t})})}function iH(e,t,r){return{request_id:t,trace_id:r,card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type,entity_id:e.entity_id,source_tool_call_id:eK(e.source)?e.source.tool_call_id:void 0,render_data:e.render_data}}function iz(e){let{apiEnvironment:t,appId:r,card:n,inspectableTargetKey:a,reloadKey:i,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,onUpdateWidget:u,requestId:c,runtimeConsoleTarget:p,traceId:m,viewport:h,widgets:g}=e,f=(0,e9.useRef)(null),v=(0,e9.useRef)(null),y=(0,e9.useRef)(null),_=n.widget_id,b=h??ry,x=!!_&&((null==g?void 0:g.some(e=>e.widgetId===_))??!1),[I,E]=(0,e9.useState)(0),[C,k]=(0,e9.useState)(0),[N,M]=(0,e9.useState)({status:"idle"}),R=I>0?I:b.width,T=(0,e9.useMemo)(()=>({...b,width:R}),[b,R]),A={height:`${Math.round(+(C||Math.round(1.35*R)))}px`,width:`${Math.round(+R)}px`},P={"--wsd-widget-chat-card-runtime-scale":1,width:`${R}px`},j=(0,e9.useMemo)(()=>{if(!u)return null==t?void 0:t.apiRegistry;let e=(null==t?void 0:t.apiRegistry.fork())??aO();return e.register("doubao.updateWidget",{handler:e=>{let t=function(e){if(eK(e)&&"string"==typeof e.widgetInstanceId&&"string"==typeof e.widgetData&&(void 0===e.widgetId||"string"==typeof e.widgetId))return{widgetInstanceId:e.widgetInstanceId,widgetData:e.widgetData,..."string"==typeof e.widgetId?{widgetId:e.widgetId}:{}}}(e.params);if(!t)return S(e,"Invalid doubao.updateWidget parameters");let r=u(t);return"updated"===r.status?w(e,{}):S(e,r.message)}},{override:!0}),e},[null==t?void 0:t.apiRegistry,u]),D=(0,e9.useMemo)(()=>(e,t,r,n)=>{let a=il(e,t,r);return a?void aG(p??n.element,a):null==o?void 0:o(e,t,r,n)},[o,p]);return(0,e9.useEffect)(()=>{let e=v.current;if(!e)return;let t=()=>{let t=f.current,r=null==t?void 0:t.closest(".wsd-widget-chat-card");E(Math.max(0,r instanceof HTMLElement?r.clientWidth:0,(null==t?void 0:t.clientWidth)??0,e.clientWidth,Math.floor(e.getBoundingClientRect().width)))};if(t(),"u"<typeof ResizeObserver)return window.addEventListener("resize",t),()=>{window.removeEventListener("resize",t)};let r=new ResizeObserver(t),n=f.current,a=null==n?void 0:n.closest(".wsd-widget-chat-card");return r.observe(e),n&&r.observe(n),a instanceof HTMLElement&&r.observe(a),()=>{r.disconnect()}},[]),(0,e9.useEffect)(()=>{let e,s,i=y.current;if(!i)return;if(i.replaceChildren(),k(0),a&&(null==l||l(a,null)),!_){let e="缺少 widget_id,已展示 fallback";M({status:"skipped",message:e}),null==d||d({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:e,...iH(n,c,m)});return}if(!r){let e="缺少 appId,已展示 fallback";M({status:"skipped",message:e}),null==d||d({category:"card",event:"simulator_card_render_skipped",reason:"missing_app_id",summary:e,...iH(n,c,m)});return}if(!x){let e=`Manifest 中找不到 widget_id: ${_}`;M({status:"skipped",message:e}),null==d||d({category:"card",event:"simulator_card_render_skipped",reason:"widget_not_found",summary:e,...iH(n,c,m)});return}let o=!1,u=null,p=rw(T,n.card_id?{__VIEW_CONTEXT__:{widgetInstanceId:n.card_id}}:{}),h=()=>{o||k(Math.ceil(i.scrollHeight||i.getBoundingClientRect().height))},g=()=>{"u"<typeof window?h():(void 0!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(h))},f=Date.now();M({status:"rendering"});try{u=new eZ({appId:r,apiRegistry:j,container:i,globalProps:p,initData:tl(n.render_data),nativeModulesCallHandler:D,onError:e=>{null==d||d({category:"card",event:"simulator_card_runtime_error",elapsed_ms:Date.now()-f,summary:e.message,...iH(n,c,m)})},runtimeHost:null==t?void 0:t.runtimeHost,widgetId:_})}catch(t){let e=tm(t);M({status:"error",message:e}),null==d||d({category:"card",event:"simulator_card_render_failed",elapsed_ms:Date.now()-f,summary:e,...iH(n,c,m)});return}return u.render().then(e=>{o||(M({status:"rendered"}),a&&(null==l||l(a,e)),g(),"u">typeof ResizeObserver&&(s=new ResizeObserver(g)).observe(i),null==d||d({category:"card",event:"simulator_card_rendered",elapsed_ms:Date.now()-f,...iH(n,c,m)}))}).catch(e=>{if(o)return;let t=tm(e);M({status:"error",message:t}),a&&(null==l||l(a,null)),null==d||d({category:"card",event:"simulator_card_render_failed",elapsed_ms:Date.now()-f,summary:t,...iH(n,c,m)})}),()=>{o=!0,void 0!==e&&window.cancelAnimationFrame(e),null==s||s.disconnect(),null==u||u.destroy(),i.replaceChildren(),a&&(null==l||l(a,null))}},[t,j,r,n,D,a,l,d,i,T,x,_]),(0,s.jsxs)("div",{className:"wsd-widget-chat-card-runtime",ref:f,children:[(0,s.jsx)("div",{className:"wsd-widget-chat-card-runtime-viewport",ref:v,children:(0,s.jsx)("div",{className:"wsd-widget-chat-card-runtime-scale-shell",style:A,children:(0,s.jsx)("div",{className:"wsd-widget-chat-card-runtime-target",ref:y,style:P})})}),"rendering"===N.status?(0,s.jsx)("span",{className:"wsd-widget-chat-card-runtime-status",children:"卡片渲染中..."}):null,"skipped"===N.status||"error"===N.status?(0,s.jsx)("span",{className:"wsd-widget-chat-card-runtime-status",children:N.message}):null]})}let iV="mcp-privacy-login-card",iG="__doubao_apps__expired-widget";function iK(e){return e.title||e.fallback_text||e.card_type||e.card_id||"卡片"}function iJ(e,t){return(null==e?void 0:e.some(e=>e.widgetId===t))?e:[...e??[],{widgetId:t}]}function iX(e,t){return`${e.messageId}:${t.blockId}:${t.card.card_id||t.blockId}`}function iQ(e){var t,r;let{apiEnvironment:n,appId:a,block:i,cardReloadKey:o,message:l,nativeModulesCallHandler:d,onInspectableCardTargetChange:u,grantingItemIndex:c,onGrantingCardOpen:p,onGrantingPermissionDecision:m,onGrantingCardSkip:h,onTraceEvent:g,onUpdateWidget:f,runtimeConsoleTarget:v,widgetViewport:y,widgets:_}=e,b=(0,e9.useMemo)(()=>"card"===i.type&&i.card.widget_id===iG?iJ(_,iG):_,[i,_]);if((0,e9.useEffect)(()=>{var e;"card"!==i.type||i.card.widget_id||null==g||g({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:"缺少 widget_id,已展示 fallback",...(e=i.card,{request_id:l.requestId,trace_id:l.traceId,card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type})})},[i,l.requestId,l.traceId,g]),"text"===i.type)return(0,s.jsx)(iW,{text:i.text});if("card"===(t=i).type&&"permission_apply"===t.card.card_type){let e=iX(l,i),t=(null==(r=i0(i.card,c))?void 0:r.itemIndex)??0;return(0,s.jsx)(i3,{card:i.card,grantingItemIndex:t,onLogin:()=>null==p?void 0:p(i.card,e,t),onPermissionDecision:r=>null==m?void 0:m(i.card,e,t,r),onSkip:r=>null==h?void 0:h(r,i.card,e,t),onTraceEvent:g})}return i.card.widget_id?(0,s.jsx)("article",{className:"wsd-widget-chat-card has-runtime",children:(0,s.jsx)(iz,{apiEnvironment:n,appId:a,card:i.card,inspectableTargetKey:iX(l,i),reloadKey:o,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:g,onUpdateWidget:f,requestId:l.requestId,runtimeConsoleTarget:v,traceId:l.traceId,viewport:y,widgets:b})}):(0,s.jsxs)("article",{className:"wsd-widget-chat-card",children:[(0,s.jsx)("span",{className:"wsd-widget-chat-card-kicker",children:i.card.card_type||"卡片"}),(0,s.jsx)("strong",{children:iK(i.card)}),i.card.fallback_text&&i.card.fallback_text!==iK(i.card)?(0,s.jsx)("span",{className:"wsd-widget-chat-card-summary",children:i.card.fallback_text}):null]})}function iZ(e){var t;let r=null==(t=e.render_data)?void 0:t.grantingData;return eK(r)&&Array.isArray(r.grantingList)?r:void 0}function iY(e){return"pending"===e.permissionStatus||"revoked"===e.permissionStatus}function i0(e,t){let r=iZ(e),n=(null==r?void 0:r.grantingList.findIndex(iY))??-1,a="number"==typeof t&&(null==r?void 0:r.grantingList[t])?t:-1===n?0:n;if(a<0)return;let s=null==r?void 0:r.grantingList[a];return s&&r?{grantingData:r,item:s,itemIndex:a}:void 0}function i1(e){return"string"==typeof e?e:""}function i2(e){let{appIcon:t}=e,[r,n]=(0,e9.useState)(!1);return((0,e9.useEffect)(()=>{n(!1)},[t]),!t||r)?null:(0,s.jsx)("img",{alt:"",className:"wsd-widget-granting-prompt-logo",onError:()=>n(!0),src:t})}function i3(e){var t,r,n;let{card:a,grantingItemIndex:i,onLogin:o,onPermissionDecision:l,onSkip:d,onTraceEvent:u}=e,c=(0,e9.useMemo)(()=>i0(a,i),[a,i]),p=null==c?void 0:c.grantingData,m=null==c?void 0:c.item,h=(null==p?void 0:p.doubaoAppletName)||"智能服务",g=(null==m?void 0:m.grantingName)==="permission",f=i1(null==m||null==(t=m.relatedData)?void 0:t.scopeName),v=(0,e9.useMemo)(()=>rH(f),[f]),[y,_]=(0,e9.useState)(),[b,w]=(0,e9.useState)(),S=r$.isLocationScope(f),x=void 0!==b,I=S&&"granted"===b,E=g&&(null==p?void 0:p.cardStatus)==="expired",C=g&&!y&&(!x||S)&&!E&&((null==m?void 0:m.permissionStatus)==="pending"||(null==m?void 0:m.permissionStatus)==="revoked"),k=g?v.title:`在豆包内使用 ${h}`,N=g?"granted"===y?`已允许${h}获取`:"refused"===y?`已拒绝${h}获取`:E?"已过期,暂无法操作":i1(null==m||null==(r=m.relatedData)?void 0:r.scopeDescription)||v.description:i1(null==m||null==(n=m.relatedData)?void 0:n.bizLoginDescription)||((null==m?void 0:m.grantingName)==="privacy"?"需同意后才可以继续使用":"需登录后才可以继续使用");async function M(e){if(!x){w(e?"granted":"refused"),null==u||u({category:"card",event:"simulator_granting_prompt_permission_click",granted:e,scope:f});try{let t=await (null==l?void 0:l(e));!1!==t&&_(e?"granted":"refused")}finally{w(void 0)}}}return(0,e9.useEffect)(()=>{_(void 0),w(void 0)},[a.card_id,null==p?void 0:p.cardStatus,i,null==m?void 0:m.permissionStatus,f]),(0,s.jsxs)("article",{className:(0,eJ.$)("wsd-widget-granting-prompt-card",g&&"is-permission"),children:[(0,s.jsxs)("header",{className:"wsd-widget-granting-prompt-brand",children:[(0,s.jsx)(i2,{appIcon:null==p?void 0:p.doubaoAppletIcon}),(0,s.jsx)("span",{children:h})]}),(0,s.jsx)("strong",{className:"wsd-widget-granting-prompt-title",children:k}),(0,s.jsx)("p",{className:"wsd-widget-granting-prompt-description",children:N}),g?C?(0,s.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-secondary",disabled:x,onClick:()=>void M(!1),type:"button",children:"拒绝"}),(0,s.jsxs)("button",{"aria-busy":I,className:"wsd-widget-granting-prompt-primary",disabled:x,onClick:()=>void M(!0),type:"button",children:[I?(0,s.jsxs)("svg",{"aria-hidden":"true",className:"wsd-widget-granting-prompt-spinner",viewBox:"0 0 16 16",children:[(0,s.jsx)("circle",{className:"wsd-widget-granting-prompt-spinner-track",cx:"8",cy:"8",fill:"none",r:"6",strokeWidth:"2"}),(0,s.jsx)("path",{className:"wsd-widget-granting-prompt-spinner-indicator",d:"M 8 2 A 6 6 0 0 1 14 8",fill:"none",strokeLinecap:"round",strokeWidth:"2"})]}):null,"允许"]})]}):null:(0,s.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-secondary",onClick:function(){null==u||u({category:"card",event:"simulator_granting_prompt_skip_click",granting_name:null==m?void 0:m.grantingName}),null==d||d((null==m?void 0:m.grantingName)==="privacy"?"privacy":"login")},type:"button",children:"暂不登录"}),(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-primary",onClick:function(){null==u||u({category:"card",event:"simulator_granting_prompt_login_click",granting_name:null==m?void 0:m.grantingName}),null==o||o()},type:"button",children:"登录"})]})]})}function i4(e){let{apiEnvironment:t,appId:r,card:n,grantingItemIndex:a,inspectableTargetKey:i,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,runtimeConsoleTarget:u,widgets:c}=e,p=(0,e9.useMemo)(()=>iJ(c,iV),[c]),m=(0,e9.useMemo)(()=>(function(e,t){let r,n,a,s,i,o,l,d;return{...e,card_id:`${e.card_id||"permission_apply"}:${iV}`,card_type:"permission_apply",render_data:{...eK(e.render_data)?e.render_data:{},viewData:(n=null==(r=i0(e,t))?void 0:r.grantingData,s=(null==(a=null==r?void 0:r.item)?void 0:a.relatedData)??{},i=(null==n?void 0:n.doubaoAppletName)||"智能服务",o=(null==a?void 0:a.grantingName)==="privacy",l=i1(s.mobileMask),d=o?i1(s.bizPrivacyContent)||`${i} 需要你同意隐私政策后继续。`:i1(s.bizLoginDescription)||"登录后继续使用相关服务",{type:(null==a?void 0:a.grantingName)==="privacy"?"agreePrivacyAuthorization":"getPhoneNumber",currentPage:"chat",brand:{name:i,logo:(null==n?void 0:n.doubaoAppletIcon)||""},content:{title:o?"隐私协议提示":"申请获取并验证你的手机号",description:d},buttons:o?{primary:{text:"同意并继续",loadingText:"处理中..."},secondary:{text:"暂不同意"}}:{primary:{text:l,loadingText:"登录中...",subtext:"豆包绑定号码"},secondary:{text:"暂不登录"},other:{text:"其他登录方式"}},agreement:{text:[{text:`已阅读并同意${i}的`},{text:"服务协议",url:i1(s.termsOfServiceURL)||void 0},{text:"和"},{text:"隐私政策",url:i1(s.privacyURL)||void 0}]},warningToast:"请先阅读并同意协议"})},widget_id:iV}})(n,a),[n,a]),h=(0,e9.useMemo)(()=>({key:"simulator-login-sheet",label:"登录半屏",width:393,density:3}),[]);return(0,s.jsx)("dialog",{className:"wsd-widget-granting-card has-runtime",open:!0,children:(0,s.jsx)(iz,{apiEnvironment:t,appId:r,card:m,inspectableTargetKey:i,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,runtimeConsoleTarget:u,viewport:h,widgets:p})})}function i5(e){let{apiEnvironment:t,appId:r,cardReloadKey:n,grantingItemIndexes:a,message:i,nativeModulesCallHandler:o,onInspectableCardTargetChange:l,onGrantingCardOpen:d,onGrantingPermissionDecision:u,onGrantingCardSkip:c,onTraceEvent:p,onTraceSelect:m,onUpdateWidget:h,runtimeConsoleTarget:g,selectedTraceId:f,widgetViewport:v,widgets:y}=e,_="assistant"===i.role,b=(i.blocks.length>0?i.blocks:i.text.trim()?[{blockId:`${i.messageId}-text`,type:"text",text:i.text}]:[]).reduce((e,t)=>{let r=e[e.length-1];return"text"===t.type&&(null==r?void 0:r.type)==="text"?e[e.length-1]={...r,text:`${r.text}${t.text}`}:e.push(t),e},[]),w=b.some(e=>"card"===e.type),S=b.some(e=>"text"===e.type&&e.text.trim()),x=i.traceId,I=!!(x&&m),E=!!(x&&x===f);return(0,s.jsxs)("article",{"aria-pressed":I?E:void 0,className:(0,eJ.$)("wsd-widget-chat-message",_?"is-assistant":"is-user",S&&"has-text",w&&"has-card",I&&"is-trace-selectable",E&&"is-trace-selected"),onClick:e=>{!x||!m||i6(e.target)||m(x)},onKeyDown:e=>{!x||!m||i6(e.target)||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),m(x))},role:I?"button":void 0,tabIndex:I?0:void 0,children:[_?(0,s.jsx)("span",{className:"wsd-widget-chat-avatar",children:"AI"}):null,(0,s.jsxs)("div",{className:"wsd-widget-chat-bubble",children:[b.map(e=>(0,s.jsx)(iQ,{apiEnvironment:t,appId:r,block:e,cardReloadKey:n,grantingItemIndex:"card"===e.type?null==a?void 0:a[iX(i,e)]:void 0,message:i,nativeModulesCallHandler:o,onGrantingCardOpen:d,onGrantingPermissionDecision:u,onGrantingCardSkip:c,onInspectableCardTargetChange:l,onTraceEvent:p,onUpdateWidget:h,runtimeConsoleTarget:g,widgetViewport:v,widgets:y},e.blockId)),"streaming"===i.status&&b.every(e=>"text"!==e.type||!e.text)?(0,s.jsx)("span",{className:"wsd-widget-chat-placeholder",children:"正在思考..."}):null]})]})}function i6(e){return e instanceof Element&&!!e.closest("button,a,input,textarea,select,.wsd-widget-chat-card")}let i8="mcp-login-page";function i7(e){return e.split(":")[0]||""}function i9(e){var t,r,n;let{apiEnvironment:a,appId:i,cardReloadKey:o,controlCommand:l,nativeModulesCallHandler:d,onGrantingSheetTargetChange:u,onControlResult:c,onInspectableCardTargetChange:p,onNavigateToPage:m,onQuerySubmit:h,onSandboxLocationConfigOpen:g,onTraceEvent:f,onTraceMessageSelect:v,runtimeConsoleTarget:y,sandboxLoginHint:_,simulator:b,selectedTraceId:w,widgetViewport:S,widgets:x,webSdkDebugger:I,onMessage:E}=e,[C,k]=(0,e9.useState)(""),[N,M]=(0,e9.useState)(!1),[R,T]=(0,e9.useState)(!1),A=(0,e9.useContext)(iL),P=(0,e9.useMemo)(()=>iP(A.tasks).length>0,[A.tasks]),j=(0,e9.useRef)(null),D=(0,e9.useRef)(b.messages.length),L=(0,e9.useRef)(!0),[O,U]=(0,e9.useState)(),[q,$]=(0,e9.useState)({}),B=(0,e9.useRef)(new Set),F=(0,e9.useRef)(),W="streaming"===b.streamStatus,H=!!C.trim()&&!W,z=((r=null==O?void 0:O.card)?null==(n=iZ(r))?void 0:n.doubaoAppletKey:void 0)||void 0,V=i||z,G=iy(e=>{(U(void 0),m)?m({url:e}):I.navigateToPage(e)}),K=iy(e=>I.updateSimulatorWidget(e)),J=iy((e,t)=>{let r=tV(I,{grantingMessageId:(null==t?void 0:t.grantingMessageId)??(O?i7(O.key):void 0),noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==E||E("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==E||E("当前仍在生成中,暂不重发授权后的消息",!0);return}U(void 0),null==f||f({category:"card",event:"simulator_granting_resend_query",granting_type:e,no_login:(null==t?void 0:t.noLogin)===!0,removed_message_ids:r.target.messageIds,query_preview:r.target.query.slice(0,80)}),null==h||h(),r.completion.catch(e=>{null==E||E(e.message,!0)})}),X=iy((e,t,r,n)=>{var a;let s=i0(e,r);if(!s){null==E||E("索权卡缺少有效的授权项",!0);return}let i=`${t}:${r}`;if(B.current.has(i))return;B.current.add(i);let o=function(e,t){let r=iZ(e);if(!r)return;let n=r.grantingList.findIndex((e,r)=>r>t&&iY(e));return -1===n?void 0:n}(e,r),l=function(e){switch(e){case"permission":case"privacy":return e;default:return"login"}}(s.item.grantingName);if(!n&&!1!==s.item.required)return void J(l,{grantingMessageId:i7(t),noLogin:!0});if(void 0!==o){$(e=>({...e,[t]:o})),U(e=>(null==e?void 0:e.key)===t?void 0:e),null==f||f({category:"card",event:"simulator_granting_item_advanced",granted:n,granting_name:s.item.grantingName,next_granting_name:null==(a=i0(e,o))?void 0:a.item.grantingName});return}J(l,{grantingMessageId:i7(t)})}),Q=iy((e,t,r)=>{var n,a;let s;(null==(s=null==(n=i0(e,r))?void 0:n.item)?void 0:s.grantingName)==="privacy"||i1(null==s||null==(a=s.relatedData)?void 0:a.mobileMask).trim()?U({card:e,itemIndex:r,key:t}):(null==f||f({category:"card",event:"simulator_granting_custom_login_navigate",reason:"missing_mobile_mask",url:i8}),G(i8))}),Z=iy(async(e,t,r,n)=>{var s,i,o,l;let d,u=function(e,t){var r;let n=i0(e,t),a=null==n?void 0:n.grantingData,s=null==n?void 0:n.item,i=i1(null==a?void 0:a.doubaoAppletKey).trim(),o=i1(null==s||null==(r=s.relatedData)?void 0:r.scopeName).trim();if((null==s?void 0:s.grantingName)==="permission"&&i&&o)return{appId:i,appName:(null==a?void 0:a.doubaoAppletName)||"智能服务",required:!1!==s.required,scope:o}}(e,r);if(!u)return null==E||E("索权卡缺少有效的智能服务 appId 或 scopeName",!0),!1;if(r$.isLocationScope(u.scope)&&(r$.updateUserAuthorization(n),n)){let e=await r$.requestLocation();if("success"!==e.status)return"browser_unauthorized"===e.status&&(null==a||null==(s=a.uiPresenter)||s.showToast({duration:3e3,icon:"warn",message:"请先在 DevTools Sandbox 面板配置位置",type:"warning"}),null==g||g()),null==f||f({category:"card",event:"simulator_granting_location_unavailable",location_status:e.status,scope:u.scope}),!1;d=r$.createBusinessLocationInfo(e.location)}try{await an({appletId:u.appId,granted:n,scopeName:u.scope})}catch(t){let e=t instanceof Error?t.message:String(t);return null==f||f({category:"card",event:"simulator_granting_permission_report_failed",applet_id:u.appId,granted:n,scope:u.scope}),null==E||E(`权限授权状态上报失败:${e}`,!0),!1}if(d){try{await ah(JSON.stringify(d))}catch(t){let e=t instanceof Error?t.message:String(t);return null==f||f({category:"card",event:"simulator_granting_location_report_failed",scope:u.scope}),null==E||E(`位置信息上报失败:${e}`,!0),!1}null==f||f({category:"card",event:"simulator_granting_location_reported",scope:u.scope})}return i=u.appId,o=u.scope,l=n?"granted":"denied",rB.set(rW(i,o),l),null==f||f({category:"card",event:"simulator_granting_permission_reported",applet_id:u.appId,granted:n,scope:u.scope}),X(e,t,r,n),!0}),Y=iy((e,t,r,n)=>{X(t,r,n,!1)}),ee=(0,e9.useMemo)(()=>{var e,t;if(!O)return;let r=(e=O.key,t=O.itemIndex,`${e}:${t}`);return aU({appId:V,baseAPIRegistry:null==a?void 0:a.apiRegistry,onGrantingCompleted:(e,t)=>X(O.card,O.key,O.itemIndex,!(null==t?void 0:t.noLogin)),onCustomLoginNavigate:G,onPrivacyLoginCardClose:()=>{Promise.resolve().then(()=>{B.current.has(r)||X(O.card,O.key,O.itemIndex,!1)})},runtimeHost:null==a?void 0:a.runtimeHost,scanCodePresenter:null==a?void 0:a.scanCodePresenter,uiPresenter:null==a?void 0:a.uiPresenter})},[O,a,V,X,G]),et=iy((e,t)=>{null==p||p(e,t),null==u||u(t)}),er=iy(e=>{T(!1);try{I.navigateToPage(e),null==m||m({url:e})}catch{let t=function(e,t){try{let r=new URL(e,t);return"http:"===r.protocol||"https:"===r.protocol?r.toString():void 0}catch{return}}(e,window.location.href);t&&window.open(t,"_blank","noopener,noreferrer")}}),en=iy(()=>{T(!1)}),ea=iy(async e=>{try{await A.removeTask(e)}catch(e){null==E||E(e.message,!0)}});(0,e9.useEffect)(()=>{let e=j.current,t=D.current,r=b.messages.at(-1),n=b.messages.length>t&&(null==r?void 0:r.role)==="user";D.current=b.messages.length,e&&(L.current||n)&&(e.scrollTop=e.scrollHeight,L.current=!0)},[null==(t=b.error)?void 0:t.message,b.messages,b.streamStatus]);let es=iy(async(e,t)=>{null==h||h(),await (t?iE(I,t,e):I.sendSimulatorQuery(e))});return((0,e9.useEffect)(()=>{if((null==l?void 0:l.type)!=="submit_chat_query"||F.current===l.commandId)return;F.current=l.commandId;let e=I.getState();if("ready"!==e.status.type){null==c||c(l.commandId,{ok:!1,error:{code:"CHAT_NOT_READY",message:"Web SDK debugger is not ready to submit a chat query"}});return}if("streaming"===e.simulator.streamStatus){null==c||c(l.commandId,{ok:!1,error:{code:"CHAT_BUSY",message:"A chat query is already streaming"}});return}let t=e.simulator.messages.length;es(l.query,l.commandId).then(()=>{var e,r;let n=I.getState().simulator,a=null==(e=n.messages.slice(t).reverse().find(e=>"assistant"===e.role&&!!e.requestId))?void 0:e.requestId;if("completed"!==n.streamStatus||!a)throw Error((null==(r=n.error)?void 0:r.message)??"Chat query did not complete with a request ID");null==c||c(l.commandId,{ok:!0,result:{completed:!0,query:l.query,requestId:a}})}).catch(e=>{null==c||c(l.commandId,{ok:!1,error:{code:"CHAT_SUBMIT_FAILED",message:e.message}})})},[l,c,es,I]),(0,e9.useEffect)(()=>{N&&A.hasUnreadNotices&&A.markServiceNoticesRead()},[A.hasUnreadNotices,A.markServiceNoticesRead,N]),N)?(0,s.jsx)(iT,{notices:A.notices,onAction:er,onBack:()=>M(!1),status:A.status}):(0,s.jsxs)("div",{className:"wsd-widget-chat-panel",children:[(0,s.jsxs)("header",{className:"wsd-doubao-simulator-chrome","aria-label":"豆包模拟器标题栏",children:[(0,s.jsx)(iN,{}),(0,s.jsxs)("div",{className:"wsd-doubao-title-bar",children:[(0,s.jsxs)("div",{className:"wsd-doubao-title-actions is-left",children:[(0,s.jsx)("button",{"aria-label":A.hasUnreadNotices?"打开菜单,有更新":"打开菜单",className:(0,eJ.$)("wsd-doubao-icon-button",A.hasUnreadNotices&&"has-badge"),onClick:()=>M(!0),type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-menu-icon","aria-hidden":"true"})}),(0,s.jsx)("button",{"aria-label":"打开应用入口",className:"wsd-doubao-icon-button",type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-mask-icon is-circle4","aria-hidden":"true"})})]}),(0,s.jsxs)("div",{className:"wsd-doubao-title-stack",children:[(0,s.jsxs)("span",{className:"wsd-doubao-title",children:["豆包",(0,s.jsx)("span",{"aria-hidden":"true",children:"›"})]}),(0,s.jsx)("span",{className:"wsd-doubao-subtitle",children:"doubao.com"})]}),(0,s.jsxs)("div",{className:"wsd-doubao-title-actions",children:[(0,s.jsx)("button",{"aria-label":"语音通话",className:"wsd-doubao-icon-button",type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-mask-icon is-phone","aria-hidden":"true"})}),(0,s.jsx)("button",{"aria-label":"静音",className:"wsd-doubao-icon-button",type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-mask-icon is-mute","aria-hidden":"true"})})]})]})]}),_?(0,s.jsxs)("div",{className:(0,eJ.$)("wsd-doubao-login-banner",!_.available&&"is-unavailable"),children:[(0,s.jsxs)("button",{className:"wsd-doubao-login-banner-open",onClick:_.onOpen,type:"button",children:[(0,s.jsx)("span",{children:_.available?"配置登录信息,模拟登录后场景":"无法模拟平台服务"}),_.available?(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-login-banner-arrow",children:"→"}):null]}),(0,s.jsx)("button",{"aria-label":"关闭登录信息配置提示",className:"wsd-doubao-login-banner-close",onClick:_.onClose,type:"button",children:"×"})]}):null,(0,s.jsxs)("div",{"aria-label":"对话预览",className:"wsd-widget-chat-messages",onScroll:function(e){let t=e.currentTarget;L.current=t.scrollHeight-t.scrollTop-t.clientHeight<=24},ref:j,children:[b.messages.length>0?b.messages.map(e=>(0,s.jsx)(i5,{apiEnvironment:a,appId:i,cardReloadKey:o,grantingItemIndexes:q,message:e,nativeModulesCallHandler:d,onGrantingCardOpen:Q,onGrantingPermissionDecision:Z,onGrantingCardSkip:Y,onInspectableCardTargetChange:p,onTraceEvent:f,onTraceSelect:v,onUpdateWidget:K,runtimeConsoleTarget:y,selectedTraceId:w,widgetViewport:S,widgets:x},e.messageId)):null,b.error?(0,s.jsx)("div",{className:"wsd-widget-chat-error",children:b.error.message}):null]}),(0,s.jsx)("div",{className:"wsd-widget-chat-input-dock",children:(0,s.jsxs)("form",{className:"wsd-widget-chat-composer",onSubmit:function(e){e.preventDefault();let t=C.trim();t&&!W&&(k(""),es(t).catch(e=>{null==E||E(e.message,!0)}))},children:[(0,s.jsx)("input",{"aria-label":"输入消息",className:"wsd-widget-chat-input",disabled:W,onChange:e=>k(e.currentTarget.value),placeholder:"发消息...",type:"text",value:C}),(0,s.jsx)("button",{"aria-label":W?"取消生成":"发送消息",className:"wsd-widget-chat-send",disabled:!W&&!H,onClick:function(){W&&I.cancelSimulatorQuery()},type:W?"button":"submit",children:W?(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-cancel-icon"}):(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-send-icon"})})]})}),P&&!R?(0,s.jsx)("button",{"aria-label":"展开进行中的任务",className:"wsd-sandbox-task-collapsed-entry",onClick:()=>{A.markTasksRead(),T(!0)},type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})}):null,O?(0,s.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-widget-granting-sheet-layer",children:[(0,s.jsx)("div",{className:"wsd-simulator-overlay-backdrop wsd-widget-granting-sheet-backdrop"}),(0,s.jsx)("div",{className:"wsd-widget-granting-sheet",children:(0,s.jsx)(i4,{apiEnvironment:ee,appId:V,card:O.card,grantingItemIndex:O.itemIndex,inspectableTargetKey:O.key,nativeModulesCallHandler:d,onInspectableTargetChange:et,onTraceEvent:f,runtimeConsoleTarget:y,widgets:x})})]}):null,R?(0,s.jsx)(ij,{onAction:er,onClose:en,onRemove:ea,removingTaskIds:A.removingTaskIds,tasks:A.tasks}):null]})}function oe(e){let{appIcon:t}=e,[r,n]=(0,e9.useState)(!1);return((0,e9.useEffect)(()=>{n(!1)},[t]),!t||r)?null:(0,s.jsx)("img",{alt:"",className:"wsd-simulator-permission-app-icon",onError:()=>n(!0),src:t})}function ot(e){let{onAllow:t,onReject:r,permission:n}=e;return(0,s.jsxs)("div",{className:"wsd-simulator-permission-layer",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-permission-backdrop"}),(0,s.jsxs)("dialog",{"aria-label":`${n.appName}权限申请`,"aria-modal":"true",className:"wsd-simulator-permission-dialog",open:!0,children:[(0,s.jsxs)("header",{className:"wsd-simulator-permission-brand",children:[(0,s.jsx)(oe,{appIcon:n.appIcon}),(0,s.jsx)("strong",{children:n.appName})]}),(0,s.jsxs)("section",{className:"wsd-simulator-permission-content",children:[(0,s.jsx)("h2",{children:n.title}),(0,s.jsx)("p",{children:n.description})]}),(0,s.jsxs)("footer",{className:"wsd-simulator-permission-actions",children:[(0,s.jsx)("button",{className:"is-primary",onClick:t,type:"button",children:"允许"}),(0,s.jsx)("button",{className:"is-secondary",onClick:r,type:"button",children:"拒绝"})]})]})]})}function or(){let[e,t]=(0,e9.useState)(),r=(0,e9.useRef)(null),n=iy(e=>r.current?Promise.reject(Error("Simulator permission prompt is already open")):new Promise(n=>{r.current=n,t(e)})),a=iy(e=>{let n=r.current;n&&(r.current=null,t(void 0),n(e))}),s=iy(()=>a(!0)),i=iy(()=>a(!1));return(0,e9.useEffect)(()=>()=>{let e=r.current;r.current=null,null==e||e(!1)},[]),{allowPermission:s,permission:e,rejectPermission:i,showPermission:n}}var on=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:13,height:13,fill:"none",viewBox:"0 0 13 13",...e,children:(0,s.jsx)("path",{fill:"#999",d:"M6.346 0a6.33 6.33 0 0 1 4.763 2.153V.75a.667.667 0 0 1 1.334 0v2.813a1 1 0 0 1-1 1H8.63a.667.667 0 0 1 0-1.334h1.639a4.997 4.997 0 0 0-3.923-1.896 5.012 5.012 0 1 0 4.517 7.188.667.667 0 0 1 1.2.58A6.346 6.346 0 1 1 6.347 0"})}),oa=r(35668),os=r(27860),oi=r(26661),oo=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:15,fill:"none",viewBox:"0 0 12 15",...e,children:(0,s.jsx)("path",{fill:"#999",d:"M6.667 0c1.866 0 2.8 0 3.513.363l.116.062c.574.322 1.041.807 1.34 1.395l.065.136C12 2.653 12 3.583 12 5.333v4l-.006 1.237c-.017 1.083-.085 1.742-.357 2.276a3.34 3.34 0 0 1-1.457 1.457l-.136.064c-.511.22-1.148.278-2.141.294l-1.236.006H5.333l-1.236-.006c-.993-.016-1.63-.074-2.14-.294l-.137-.064a3.34 3.34 0 0 1-1.395-1.34l-.062-.117c-.272-.534-.34-1.193-.357-2.276L0 9.333v-4c0-1.866 0-2.8.363-3.513.32-.627.83-1.137 1.457-1.457C2.533 0 3.467 0 5.333 0zM5.333 1.333c-.955 0-1.591.001-2.08.041-.474.039-.69.108-.828.177a2 2 0 0 0-.874.874c-.07.137-.138.354-.177.828-.04.489-.04 1.125-.04 2.08v4c0 .956 0 1.592.04 2.081.039.473.108.69.177.828a2 2 0 0 0 .874.873c.137.07.354.139.828.177.489.04 1.125.041 2.08.041h1.334c.955 0 1.591 0 2.08-.04.474-.04.69-.108.828-.178a2 2 0 0 0 .874-.873c.07-.138.138-.355.177-.828.04-.489.04-1.125.04-2.08v-4c0-.956 0-1.592-.04-2.081-.039-.474-.107-.69-.177-.828a2 2 0 0 0-.874-.874c-.137-.07-.354-.138-.828-.177-.489-.04-1.125-.04-2.08-.04zM8 2.667A.667.667 0 1 1 8 4H4a.667.667 0 0 1 0-1.333z"})});let ol=[{key:"conversation",label:"对话"},{key:"card",label:"卡片"},{key:"page",label:"全页"}],od=[{label:"iOS",devices:rf.filter(e=>e.key.startsWith("iphone"))},{label:"Android",devices:rf.filter(e=>e.key.startsWith("pixel")||e.key.startsWith("galaxy"))},{label:"平板",devices:rf.filter(e=>e.key.startsWith("ipad"))}];function ou(e){let{activeView:t,children:r,onActiveViewChange:n,onDeviceChange:a,selectedDeviceKey:i}=e,[o,l]=(0,e9.useState)(!1),[d,u]=(0,e9.useState)(),c=r_(i??rg),[p,m]=(0,e9.useState)(()=>String(c.width)),[h,g]=(0,e9.useState)(()=>String(c.height)),f=(0,e9.useRef)(null),v=(null==i?void 0:i.startsWith("custom-"))===!0&&c.key===i,y=(e,t)=>{let r=`custom-${e}x${t}`;r_(r).key===r&&(null==a||a(r))};return(0,e9.useEffect)(()=>{let e=e=>{var t;(null==(t=f.current)?void 0:t.contains(e.target))||l(!1)},t=e=>{"Escape"===e.key&&l(!1)};return window.addEventListener("pointerdown",e),window.addEventListener("keydown",t),()=>{window.removeEventListener("pointerdown",e),window.removeEventListener("keydown",t)}},[]),(0,s.jsxs)("header",{className:"wsd-preview-device-toolbar",ref:f,children:[(0,s.jsxs)("div",{className:"wsd-device-toolbar-leading",children:[(0,s.jsx)("button",{"aria-label":"手机预览","aria-expanded":o,"aria-haspopup":"dialog","aria-pressed":"phone"===d,className:(0,eJ.$)("wsd-device-toolbar-icon","phone"===d&&"is-active"),onClick:()=>{u("phone"),o||(m(String(c.width)),g(String(c.height))),l(e=>!e)},type:"button",children:(0,s.jsx)(oo,{"aria-hidden":"true"})}),o?(0,s.jsxs)("dialog",{"aria-label":"选择模拟器类型",className:"wsd-preview-toolbar-menu",open:!0,children:[(0,s.jsx)("div",{className:"wsd-custom-device-size-label",children:"自定义"}),(0,s.jsxs)("div",{className:(0,eJ.$)("wsd-custom-device-size",v&&"is-selected"),children:[(0,s.jsx)("input",{"aria-label":"自定义宽度",className:"wsd-custom-device-size-input",max:9999,min:1,onChange:e=>{let t=e.currentTarget.value;m(t),y(t,h)},step:1,type:"number",value:p}),(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-custom-device-size-separator",children:"×"}),(0,s.jsx)("input",{"aria-label":"自定义高度",className:"wsd-custom-device-size-input",max:9999,min:1,onChange:e=>{let t=e.currentTarget.value;g(t),y(p,t)},step:1,type:"number",value:h}),(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-custom-device-size-check",children:"✓"})]}),(0,s.jsx)(oa.o,{"aria-label":"选择预设机型",className:"wsd-preview-toolbar-device-menu",selectedKeys:!v&&i?[i]:[],selectionMode:"single",onAction:e=>{null==a||a(String(e)),l(!1)},children:od.map(e=>(0,s.jsx)(os.g,{showDivider:e!==od.at(-1),title:e.label,children:e.devices.map(e=>(0,s.jsx)(oi.Y,{title:e.label,children:e.label},e.key))},e.label))})]}):null,(0,s.jsx)("button",{"aria-label":"设置","aria-pressed":"settings"===d,className:(0,eJ.$)("wsd-device-toolbar-icon","settings"===d&&"is-active"),onClick:()=>{u("settings"),l(!1)},type:"button",children:(0,s.jsx)(ik,{"aria-hidden":"true"})})]}),(0,s.jsx)("div",{className:"wsd-debug-mode-slot",children:(0,s.jsx)("nav",{"aria-label":"调试视图",className:"wsd-debug-mode-tabs",role:"tablist",children:ol.map(e=>(0,s.jsx)("span",{"aria-selected":t===e.key,className:(0,eJ.$)("wsd-debug-mode-tab",t===e.key&&"is-active"),onClick:()=>null==n?void 0:n(e.key),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),null==n||n(e.key))},role:"tab",tabIndex:0,children:e.label},e.key))})}),(0,s.jsx)("div",{className:"wsd-page-toolbar-actions",children:r})]})}function oc(e){let{children:t,runtime:r}=e,n=(0,e9.useMemo)(()=>({consoleTarget:"conversation"===r.activeView?r.conversationConsoleTarget:void 0,controlCommand:r.controlCommand,controlTarget:"card"===r.activeView?r.devtoolsTarget:null,debugState:r.debugState,frontendUrl:r.chromeDevToolsFrontendUrl,getRuntimeFrame:r.getRuntimeFrame,onConsoleSnapshotChange:r.setRuntimeConsoleSnapshot,onControlResult:r.onControlResult,onDebugAction:r.handleDebugAction,onHighlightChange:r.setHighlightRect,onRuntimeSnapshotChange:r.setRuntimeDomSnapshot,resolveTargetAtPoint:"conversation"===r.activeView?r.resolveConversationInspectTarget:void 0,showPanelId:r.devToolsPanelId,showPanelRequestId:r.latestDevToolsPanelRequestId,target:r.devtoolsTarget}),[r.activeView,r.chromeDevToolsFrontendUrl,r.controlCommand,r.conversationConsoleTarget,r.debugState,r.devToolsPanelId,r.devtoolsTarget,r.getRuntimeFrame,r.handleDebugAction,r.latestDevToolsPanelRequestId,r.onControlResult,r.resolveConversationInspectTarget,r.setHighlightRect,r.setRuntimeConsoleSnapshot,r.setRuntimeDomSnapshot]);return(0,e9.useEffect)(()=>{var e;null==(e=r.onChromeDevToolsPanelChange)||e.call(r,n)},[n,r.onChromeDevToolsPanelChange]),(0,s.jsxs)("div",{className:(0,eJ.$)("wsd-widget-preview-column","card"===r.activeView&&"is-card-debug"),children:[(0,s.jsx)(ou,{activeView:r.activeView,onActiveViewChange:r.onActiveViewChange,onDeviceChange:r.setSelectedDeviceKey,selectedDeviceKey:r.selectedDeviceKey,children:(0,s.jsx)("button",{"aria-label":"刷新资源并重载卡片",className:"wsd-icon-button",disabled:!r.canReloadResources,onClick:r.reloadResources,title:"streaming"===r.simulatorState.streamStatus?"对话生成中暂不能刷新资源":"刷新资源并重载卡片",type:"button",children:(0,s.jsx)(on,{"aria-hidden":"true"})})}),t]})}function op(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}let om=["agreeMain","agreeSub","reject"],oh={success:"M12 21.91a9.95 9.95 0 1 0 0-19.92 9.95 9.95 0 0 0 0 19.92Zm-1.09-5.2a.88.88 0 0 1-.86-.46L7.6 13.24a1.05 1.05 0 0 1-.24-.64c0-.22.08-.41.23-.56a.75.75 0 0 1 .55-.25c.14 0 .27.03.38.09.12.06.24.17.36.33l1.98 2.56 4.17-6.7c.18-.3.42-.45.7-.45.21 0 .4.07.57.2.17.14.25.32.25.55 0 .11-.02.22-.08.33-.05.11-.1.21-.16.31l-4.59 7.24a1.1 1.1 0 0 1-.82.46Z",error:"M4.43 21.18c-.55 0-1.03-.12-1.42-.35a2.4 2.4 0 0 1-.92-.96 2.75 2.75 0 0 1-.32-1.34c0-.47.12-.93.38-1.37L9.72 3.96c.25-.44.58-.77.99-1 .41-.22.84-.34 1.29-.34s.88.12 1.28.34c.41.23.74.56 1 1l7.57 13.2c.12.22.22.44.28.68.07.23.1.46.1.69 0 .5-.1.94-.32 1.34-.21.4-.52.72-.92.96-.4.23-.87.35-1.42.35H4.43Zm7.58-6.54c.5 0 .77-.26.77-.8l.15-5.31a.81.81 0 0 0-.27-.63.9.9 0 0 0-.66-.27c-.27 0-.5.09-.67.26a.8.8 0 0 0-.25.63l.13 5.32c.01.54.28.8.8.8Zm0 3.28c.29 0 .55-.1.76-.3.22-.21.33-.45.33-.75 0-.29-.11-.54-.33-.74a1.08 1.08 0 0 0-.76-.31c-.3 0-.56.1-.77.31-.22.2-.32.45-.32.74 0 .3.1.54.32.75.22.2.47.3.77.3Z",warn:"M12 21.91a9.95 9.95 0 1 0 0-19.92 9.95 9.95 0 0 0 0 19.92Zm0-8.14c-.52 0-.79-.27-.8-.8l-.13-5.33a.8.8 0 0 1 .25-.63c.18-.17.4-.26.67-.26.27 0 .49.09.67.27.18.17.27.38.26.63l-.15 5.32c0 .53-.26.8-.77.8Zm0 3.27c-.3 0-.56-.1-.77-.3a1 1 0 0 1-.32-.75c0-.29.1-.54.32-.74.21-.21.47-.31.77-.31.29 0 .55.1.76.31.22.2.33.45.33.74 0 .3-.11.54-.33.75-.21.2-.47.3-.76.3Z"},og={error:"error",success:"success",warning:"warn"};function of(e){return Array.isArray(e.itemList)?e.itemList:[]}function ov(e){let t=new DOMParser().parseFromString(e,"text/html");return t.doctype||0!==t.documentElement.attributes.length||0!==t.head.attributes.length||0!==t.head.childNodes.length||0!==t.body.attributes.length?null:function e(t){let r=[];for(let n of Array.from(t)){let t=function(t){if(t.nodeType===Node.TEXT_NODE)return{type:"text",value:t.textContent??""};if(t.nodeType!==Node.ELEMENT_NODE)return null;let r=e(t.childNodes);if(!r)return null;if("a"===t.localName){if(1!==t.attributes.length||!t.hasAttribute("href"))return null;try{let e=new URL(t.getAttribute("href")??"");if("http:"!==e.protocol&&"https:"!==e.protocol)return null;return{children:r,href:e.href,type:"link"}}catch{return null}}return 0!==t.attributes.length||"p"!==t.localName&&"b"!==t.localName?null:{children:r,type:"p"===t.localName?"paragraph":"bold"}}(n);if(!t)return null;r.push(t)}return r}(t.body.childNodes)}function oy(e){let{content:t}=e,r=(0,e9.useMemo)(()=>ov(t)??[],[t]);return(0,s.jsx)("div",{className:"wsd-simulator-bottom-sheet-content",children:function e(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"content";return t.map((t,n)=>{if("text"===t.type)return t.value;let a=`${r}-${n}`,i=e(t.children,a);return"paragraph"===t.type?(0,s.jsx)("p",{children:i},a):"bold"===t.type?(0,s.jsx)("b",{children:i},a):(0,s.jsx)("a",{href:t.href,rel:"noreferrer",target:"_blank",children:i},a)})}(r)})}function o_(e){let{id:t,params:r,onSubmit:n}=e,[a,i]=(0,e9.useState)(String(r.latitude??0)),[o,l]=(0,e9.useState)(String(r.longitude??0)),[d,u]=(0,e9.useState)(""),[c,p]=(0,e9.useState)(""),[m,h]=(0,e9.useState)("");return(0,s.jsxs)("form",{"aria-label":"选择位置",className:"wsd-simulator-overlay-dialog wsd-simulator-location-form",onClick:e=>e.stopPropagation(),onSubmit:function(e){e.preventDefault();let r=Number(a),s=Number(o);Number.isFinite(r)&&Number.isFinite(s)?n(t,{address:c.trim()||void 0,latitude:r,longitude:s,name:d.trim()||void 0}):h("纬度和经度必须是有效数字")},children:[(0,s.jsx)("h2",{children:"选择位置"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("span",{children:"纬度"}),(0,s.jsx)("input",{onChange:e=>i(e.currentTarget.value),value:a})]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("span",{children:"经度"}),(0,s.jsx)("input",{onChange:e=>l(e.currentTarget.value),value:o})]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("span",{children:"名称(可选)"}),(0,s.jsx)("input",{onChange:e=>u(e.currentTarget.value),value:d})]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("span",{children:"地址(可选)"}),(0,s.jsx)("input",{onChange:e=>p(e.currentTarget.value),value:c})]}),m?(0,s.jsx)("p",{className:"wsd-simulator-location-error",role:"alert",children:m}):null,(0,s.jsx)("footer",{className:"wsd-simulator-overlay-actions",children:(0,s.jsx)("button",{className:"wsd-simulator-overlay-button is-primary",type:"submit",children:"确定"})})]})}function ob(e){let{scanner:t}=e,r=(0,e9.useRef)(null),n=(0,e9.useRef)(null);return(0,e9.useEffect)(()=>{let e=n.current;e&&t.options.onVideoReady(e)},[t.options]),(0,s.jsxs)("div",{"aria-label":"扫码",className:"wsd-simulator-scan-code",children:[(0,s.jsx)("video",{autoPlay:!0,muted:!0,playsInline:!0,ref:n}),(0,s.jsx)("div",{className:"wsd-simulator-scan-code-message",children:t.message}),(0,s.jsxs)("div",{className:"wsd-simulator-scan-code-actions",children:[(0,s.jsx)("button",{onClick:t.options.onCancel,type:"button",children:"关闭"}),(0,s.jsx)("button",{onClick:t.options.onCapture,type:"button",children:"识别"}),t.options.allowImageUpload?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("button",{onClick:()=>{var e;return null==(e=r.current)?void 0:e.click()},type:"button",children:"相册"}),(0,s.jsx)("input",{accept:"image/*",hidden:!0,onChange:e=>{var r;let n=null==(r=e.currentTarget.files)?void 0:r[0];e.currentTarget.value="",n&&t.options.onFile(n)},ref:r,type:"file"})]}):null]})]})}function ow(e){let{children:t,className:r,exiting:n=!1,onDismiss:a}=e;return(0,s.jsxs)("div",{className:`wsd-simulator-overlay-interaction${r?` ${r}`:""}${n?" is-exiting":""}`,children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop",onClick:a}),t]})}function oS(e){var t;let{interaction:r,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:i,onLocationSubmit:o,onModalResult:l}=e,d=()=>i(r);if("location"===r.kind)return(0,s.jsx)(ow,{onDismiss:d,children:(0,s.jsx)(o_,{id:r.id,onSubmit:o,params:r.params},r.id)});if("modal"===r.kind){let{params:e}=r,t=!1!==e.showCancel;return(0,s.jsx)(ow,{className:"is-modal",exiting:r.exiting,onDismiss:d,children:(0,s.jsxs)("dialog",{"aria-label":e.title||"提示","aria-modal":"true",className:`wsd-simulator-modal${e.title?" has-title":""}`,onClick:e=>e.stopPropagation(),open:!0,children:[e.title?(0,s.jsx)("h2",{className:"wsd-simulator-modal-title",children:e.title}):null,(0,s.jsx)("p",{className:"wsd-simulator-modal-message",children:e.content||""}),(0,s.jsxs)("footer",{className:`wsd-simulator-modal-actions${t?"":" is-single"}`,children:[t?(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-cancel",onClick:()=>l(r.id,"cancel"),type:"button",children:e.cancelText||"cancel"}):null,(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-confirm",onClick:()=>l(r.id,"confirm"),type:"button",children:e.confirmText||"confirm"})]})]})})}if("actionSheet"===r.kind){let e=of(r.params);return(0,s.jsx)(ow,{onDismiss:d,children:(0,s.jsxs)("dialog",{"aria-label":r.params.title||"操作菜单","aria-modal":"true",className:"wsd-simulator-overlay-sheet wsd-simulator-action-sheet",onClick:e=>e.stopPropagation(),open:!0,children:[r.params.title?(0,s.jsx)("h2",{children:r.params.title}):null,(0,s.jsx)("div",{className:"wsd-simulator-overlay-list",children:e.map((e,t)=>(0,s.jsx)("button",{className:"wsd-simulator-overlay-list-item",onClick:()=>n(r.id,t),style:r.params.itemColor?{color:r.params.itemColor}:void 0,type:"button",children:e},`${e}-${t}`))})]})})}let u=Array.isArray((t=r.params).buttons)?t.buttons:[];return(0,s.jsx)(ow,{onDismiss:d,children:(0,s.jsxs)("dialog",{"aria-label":r.params.title||"底部弹窗","aria-modal":"true",className:"wsd-simulator-overlay-sheet wsd-simulator-bottom-sheet",onClick:e=>e.stopPropagation(),open:!0,children:[r.params.title?(0,s.jsx)("h2",{children:r.params.title}):null,r.params.content?(0,s.jsx)(oy,{content:r.params.content}):null,(0,s.jsx)("div",{className:"wsd-simulator-overlay-actions",children:u.map(e=>(0,s.jsx)("button",{className:`wsd-simulator-overlay-button ${"reject"===e.role?"is-secondary":"is-primary"}`,onClick:()=>a(r.id,e.role),type:"button",children:e.text},e.role))})]})})}function ox(e){let{interaction:t,loading:r,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:i,onLocationSubmit:o,onModalResult:l,scanner:d,toast:u}=e;return(0,s.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-simulator-overlay-host",children:[r?(0,s.jsxs)("div",{"aria-live":"polite",className:"wsd-simulator-loading",children:[(0,s.jsx)("span",{className:"wsd-simulator-loading-spinner"}),(0,s.jsx)("span",{children:"Loading..."})]}):null,u?(0,s.jsxs)("output",{"aria-live":"polite",className:`wsd-simulator-toast is-${u.type}${u.exiting?" is-exiting":""}`,children:[function(e){if(e.customIcon)return(0,s.jsx)("img",{alt:"",className:"wsd-simulator-toast-icon",src:e.customIcon});let t=e.icon||og[e.type];return t?(0,s.jsx)("svg",{"aria-hidden":"true",className:`wsd-simulator-toast-icon is-${t}`,focusable:"false",viewBox:"0 0 24 24",children:(0,s.jsx)("path",{d:oh[t]})}):null}(u),(0,s.jsx)("span",{className:"wsd-simulator-toast-message",children:u.message})]},u.id):null,d?(0,s.jsx)(ob,{scanner:d}):null,t?(0,s.jsx)(oS,{interaction:t,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:i,onLocationSubmit:o,onModalResult:l}):null]})}function oI(){let[e,t]=(0,e9.useState)(null),[r,n]=(0,e9.useState)(!1),[a,i]=(0,e9.useState)(null),o=(0,e9.useRef)(null),l=(0,e9.useRef)(),d=(0,e9.useRef)(0),u=(0,e9.useRef)(0),c=(0,e9.useRef)(0),p=(0,e9.useRef)(null),[m,h]=(0,e9.useState)(null),g=(0,e9.useRef)(null),f=(0,e9.useRef)(),v=(0,e9.useRef)(),y=iy((e,r,n)=>{let a=o.current;a&&a.id===e&&(l.current&&(clearTimeout(l.current),l.current=void 0),n?a.reject(n):a.resolve(r),o.current=null,t(null))}),_=iy(()=>{let e=o.current;e&&("modal"===e.kind?y(e.id,{action:"cancel"}):"bottomSheet"===e.kind?y(e.id,{action:"cancel",source:"unknown"}):"actionSheet"===e.kind?y(e.id,void 0,Error("action sheet selection was cancelled")):y(e.id,void 0,Error("chooseLocation was cancelled")))}),b=iy((e,r,n,a)=>{l.current&&(clearTimeout(l.current),l.current=void 0),_();let s={exiting:!1,id:++d.current,kind:e,params:r,reject:a,resolve:n};o.current=s,t({exiting:s.exiting,id:s.id,kind:s.kind,params:s.params})}),w=iy(()=>{v.current&&(clearTimeout(v.current),v.current=void 0),f.current&&(clearTimeout(f.current),f.current=void 0)}),S=iy(e=>{var t;(null==(t=g.current)?void 0:t.id)===e&&(g.current=null,f.current=void 0,i(null))}),x=iy(()=>{let e=g.current;if(!e||e.exiting)return;v.current&&(clearTimeout(v.current),v.current=void 0);let t={...e,exiting:!0};g.current=t,i(t),f.current=setTimeout(()=>S(e.id),180)}),I=iy(e=>{w();let t="number"==typeof e.duration&&e.duration>=0?e.duration:2e3,r={customIcon:e.customIcon,exiting:!1,id:++c.current,icon:e.icon,message:"string"==typeof e.message?e.message:"",type:e.type||"default"};g.current=r,i(r),t>0&&(v.current=setTimeout(x,Math.max(0,t-180)))}),E=iy(e=>{var t;(null==(t=p.current)?void 0:t.id)===e&&(p.current=null,h(null))}),C=iy((e,t)=>{let r=p.current;if((null==r?void 0:r.id)!==e)return;let n={...r,message:t};p.current=n,h(n)}),k=iy(e=>{var t;null==(t=p.current)||t.options.onCancel();let r=++u.current,n={id:r,message:"正在打开摄像头...",options:e};return p.current=n,h(n),{close:()=>E(r),setMessage:e=>C(r,e)}}),N=iy(e=>new Promise((t,r)=>{b("modal",e,t,r)})),M=iy(e=>new Promise((t,r)=>{b("location",e,t,r)})),R=iy(e=>new Promise((t,r)=>{0===of(e).length?r(Error("itemList must contain at least one item")):b("actionSheet",e,t,r)})),T=iy(e=>new Promise((t,r)=>{let n=function(e){if("string"!=typeof e.title||""===e.title.trim())return"title must not be empty";if("string"!=typeof e.content||""===e.content.trim())return"content must not be empty";if(!ov(e.content))return"content contains unsupported HTML";let t=e.buttons;if(!Array.isArray(t)||t.length<1||t.length>3)return"buttons must contain between one and three buttons";let r=new Set;for(let e of t){if("object"!=typeof e||null===e)return"button must be an object";let t="role"in e?e.role:void 0,n=om.find(e=>e===t);if(!n)return"button role is invalid";if(r.has(n))return"button roles must be unique";r.add(n);let a="text"in e?e.text:void 0;if("string"!=typeof a||""===a.trim())return"button text must not be empty"}return null}(e);n?r(Error(n)):b("bottomSheet",e,t,r)})),A=iy((e,r)=>{let n=o.current;n&&n.id===e&&"modal"===n.kind&&(n.resolve(r),o.current=null,t(t=>(null==t?void 0:t.id)===e?{...t,exiting:!0}:t),l.current=setTimeout(()=>{l.current=void 0,t(t=>(null==t?void 0:t.id)===e?null:t)},200))}),P=iy((e,t)=>{let r=o.current;r&&r.id===e&&A(e,{action:t})}),j=iy((e,t)=>{let r=o.current;r&&r.id===e&&"actionSheet"===r.kind&&y(e,{tapIndex:t})}),D=iy((e,t)=>{let r=o.current;r&&r.id===e&&"bottomSheet"===r.kind&&y(e,{action:"buttonClick",role:t})}),L=iy((e,t)=>{let r=o.current;r&&r.id===e&&"location"===r.kind&&y(e,t)}),O=iy(e=>{let t=o.current;if(t&&t.id===e.id)if("modal"===e.kind){if(!1===e.params.tapMaskToDismiss)return;A(e.id,{action:"mask"})}else if("bottomSheet"===e.kind){var r;if((null==(r=e.params.behavior)?void 0:r.dismissOnMaskTap)===!1)return;y(e.id,{action:"cancel",source:"mask"})}else"actionSheet"===e.kind?y(e.id,void 0,Error("action sheet selection was cancelled")):y(e.id,void 0,Error("chooseLocation was cancelled"))});(0,e9.useEffect)(()=>()=>{var e;w(),g.current=null,l.current&&(clearTimeout(l.current),l.current=void 0);let t=o.current;t&&(t.reject(Error("simulator overlay was unmounted")),o.current=null),null==(e=p.current)||e.options.onCancel(),p.current=null},[]);let U=(0,e9.useMemo)(()=>({chooseLocation:M,hideLoading:()=>n(!1),hideToast:x,showActionSheet:R,showBottomSheet:T,showLoading:()=>n(!0),showModal:N,showToast:I}),[M,x,R,T,N,I]);return{overlay:(0,s.jsx)(ox,{interaction:e,loading:r,onActionSheetSelect:j,onBottomSheetSelect:D,onDismiss:O,onLocationSubmit:L,onModalResult:P,scanner:m,toast:a}),presenter:U,scanCodePresenter:k}}function oE(e){return"string"==typeof e&&e.trim()?e.trim():""}function oC(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function ok(e){return"boolean"!=typeof(null==e?void 0:e.sandboxPhoneNumberUploaded)?void 0:!1===e.sandboxCsrRequired?e.sandboxPhoneNumberUploaded:"boolean"==typeof e.sandboxCsrUploaded?e.sandboxCsrUploaded&&e.sandboxPhoneNumberUploaded:void 0}function oN(e,t){return eK(e)?e[t]:void 0}function oM(e,t){let r=oN(e,t);return eK(r)?r:void 0}function oR(e,t){let r=oN(e,t);return Array.isArray(r)?r:[]}function oT(e){let t=oN(e,"raw");return eK(t)?t:eK(e)?e:{}}function oA(e){return oM(oT(e),"applet")}function oP(e){return null==e?void 0:e.replace(/^\/+|\/+$/g,"")}function oj(e){return eK(e.payload)?e.payload:void 0}function oD(e,t){for(let r=e.length-1;r>=0;r-=1){let n=oj(e[r]);if((null==n?void 0:n.event)===t)return n}}function oL(e,t,r){return!e||function(e,t){if(!e)return!1;try{return new URL(e,"http://localhost").pathname===t}catch{return!1}}(e,r)&&!t?"":e}function oO(e,t,r){let n=function(){for(var r=arguments.length,n=Array(r),a=0;a<r;a++)n[a]=arguments[a];return n.map(r=>oD(e,`simulator_${t}_${r}`)).find(Boolean)},a=n("missing"),s=n("fetch_started","load_started"),i=n("fetch_failed","load_failed"),o=n("fetch_succeeded","loaded"),l=n("empty");return o?{bytes:oC(o.bytes)??oC(o.skill_length),detail:oE(o.url)||r,label:"已加载",tone:"success"}:l?{detail:r||"未配置",label:"空内容",tone:"muted"}:a||!r?{detail:r,label:"未配置",tone:"muted"}:i?{detail:oE(i.error)||oE(i.url)||r,label:"加载失败",tone:"error"}:s?{detail:oE(s.url)||r,label:"加载中",tone:"pending"}:{detail:r,label:"检查中",tone:"pending"}}function oU(e){return"string"==typeof e?e.trim():eK(e)?oE(e.name)||oE(e.id):""}function oq(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.map((e,t)=>0===t?e.replace(/\/+$/g,""):e.replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/")}function o$(e,t,r,n){if(!e)return"";if(n.startsWith(`${t}/`)){let e=n.replace(/\.web\.bundle$/g,"").replace(/\.bundle$/g,"").replace(/\.template\.js$/g,"").replace(/\.js$/g,"");return oq("src",/\.(tsx|ts|jsx|js)$/.test(e)?e:`${e}.tsx`)}return!r||r.startsWith("__")?"":oq("src",t,r,"index.tsx")}function oB(e){var t,r;let n,a,s,i,o,l,d,u,c,p,m,{context:h,events:g,manifest:f,pages:v=[],widgets:y}=e,_=(null==h?void 0:h.launchDir)||"",b=(null==h?void 0:h.mcpEndpoint)||(null==h?void 0:h.mcpProxyEndpoint)||"",w=(null==h?void 0:h.mcpOriginalEndpoint)||oE(null==(a=oM(oT(f),"mcp_server"))?void 0:a.end_point)||oE(null==a?void 0:a.endpoint)||oE(null==a?void 0:a.url)||oE(null==a?void 0:a.mcp_endpoint),S=(null==h?void 0:h.mcpProxyEndpoint)||(null==h?void 0:h.mcpEndpoint)||"",x=(null==h?void 0:h.simulatorManifestOriginalUrl)||"",I=(null==h?void 0:h.simulatorManifestProxyUrl)||(null==h?void 0:h.simulatorManifestUrl)||"",E=(null==h?void 0:h.simulatorManifestRelativePath)||"",C=(null==h?void 0:h.simulatorBusinessTemplatesOriginalUrl)||"",k=(null==h?void 0:h.simulatorBusinessTemplatesRelativePath)||"",N=(null==h?void 0:h.simulatorManifestUrl)||(null==h?void 0:h.simulatorManifestProxyUrl)||"",M=(null==h?void 0:h.simulatorSkillOriginalUrl)||"",R=(null==h?void 0:h.simulatorSkillProxyUrl)||(null==h?void 0:h.simulatorSkillUrl)||"",T=(null==h?void 0:h.simulatorSkillRelativePath)||"",A=(null==h?void 0:h.simulatorSkillUrl)||(null==h?void 0:h.simulatorSkillProxyUrl)||"",P=oL(N,x,"/__simulator_manifest/manifest.yaml"),j=oL(A,M,"/__simulator_skill/skill.md"),D=oL(b,(null==h?void 0:h.mcpOriginalEndpoint)||"","/__mcp_proxy"),L=function(e){let t=new Set;for(let r of e){let e=oj(r);if(e){for(let r of oR(e,"tools")){let e=oU(r);e&&t.add(e)}for(let r of oR(e,"mcp_servers"))for(let e of oR(r,"tools")){let r=oU(e);r&&t.add(r)}}}return[...t]}(g),O=function(e){let t=new Map,r=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",a=eK(r)?oE(r.widget_id)||oE(r.widgetId)||oE(r.widget):oE(r),s=eK(r)&&(oE(r.entity_type)||oE(r.entityType)||oE(r.entity))||n;e&&a&&t.set(`${e}:${a}:${s}`,{entityType:s,toolName:e,widgetId:a})},n=oT(e),a=oN(n,"tool_card_binding");if(eK(a))for(let[e,t]of Object.entries(a))r(e,t);let s=oN(n,"entities");for(let[e,t]of eK(s)?Object.entries(s):[]){if(!eK(t))continue;let n=oE(t.entity_type)||oE(t.entityType)||e,a=oN(t,"tool_card_binding");if(eK(a))for(let[e,t]of Object.entries(a))r(e,t,n)}return[...t.values()]}(f),U={manifest:oO(g,"manifest",P),mcp:(s=oD(g,"local_mcp_missing"),i=oD(g,"local_mcp_tools_load_started"),o=oD(g,"local_mcp_tools_load_failed"),(l=oD(g,"local_mcp_tools_loaded"))?{detail:oE(l.mcp_endpoint)||D,label:"已连接",tone:"success"}:s||!D?{detail:D,label:"未配置",tone:"muted"}:o?{detail:oE(o.error)||oE(o.mcp_endpoint)||D,label:"连接失败",tone:"error"}:i?{detail:oE(i.mcp_endpoint)||D,label:"连接中",tone:"pending"}:{detail:D,label:"检查中",tone:"pending"}),skill:oO(g,"skill",j)},q=!!P||"success"===U.manifest.tone,$=!!j||"success"===U.skill.tone,B=!!D||"success"===U.mcp.tone,F={businessTemplates:C?{detail:k||C,label:"已加载",tone:"success"}:{detail:"",label:"未配置",tone:"muted"},manifest:{...U.manifest,detail:E||U.manifest.detail},mcp:U.mcp,skill:{...U.skill,detail:T||U.skill.detail}};return{appId:(d=oT(f),u=oA(f),oE(oN(f,"appId"))||oE(d.appId)||oE(d.app_key)||oE(null==u?void 0:u.appletId)),appName:(c=oT(f),p=oA(f),oE(oN(f,"name"))||oE(c.name)||oE(c.app_name)||oE(null==p?void 0:p.name)),context:{launchDir:function(e,t){if(!t||!e.startsWith(t))return e;let r=e.slice(t.length);return""===r||/^[\\/]/.test(r)?`~${r.replaceAll("\\","/")}`:e}(_,(null==h?void 0:h.homeDir)||"")},mcpTools:L,pages:(t=f,m=(null==(n=function(e,t){let r=oP(t);if(r)return e.find(e=>e.id===t||oP(e.path)===r)}(r=v,oE(oN(oA(t),"appletEntry")))??r.find(e=>{let t=oP(e.path);return"index"===e.id||"pages/index"===t||"pages/index/index"===t})??r[0])?void 0:n.id)||"",v.map(e=>{var t;return{entry:o$(_,"pages",e.id,oE(e.entry)),isHome:!!m&&e.id===m,name:oE(oN(e,"name"))||oE(oN(e,"title")),pageId:e.id,path:oE(e.path)||oE(null==(t=e.web)?void 0:t.entry)||oE(e.entry)}})),resources:F,sources:{manifest:{original:q?x:"",proxy:q?I||N:""},mcp:{original:B?w:"",proxy:B?S:""},skill:{original:$?M:"",proxy:$?R||A:""}},widgets:function(e,t,r){let n=new Map;for(let e of t){let t=n.get(e.widgetId)??[];t.push(e.toolName),n.set(e.widgetId,t)}return e.filter(to).map(e=>({boundTools:n.get(e.widgetId)??[],entry:o$(r,"widgets",e.widgetId,oE(e.entry)),name:oE(e.name),widgetId:e.widgetId}))}(y,O,_)}}function oF(e,t,r){return!!(e&&t&&t!==r&&e.sourceTarget===t)}function oW(e,t){return{pages:e.pages.map(e=>{let{isHome:t,name:r,pageId:n,path:a}=e;return{isHome:t,name:r,pageId:n,path:a}}),widgets:e.widgets.map(e=>{let{name:t,widgetId:r}=e;return{name:t,widgetId:r}}),...t?{currentTarget:t}:{}}}let oH={message:"未上传",tone:"muted"},oz={message:"已上传",tone:"success"},oV=oH,oG=new Set;function oK(e){return oG.add(e),()=>oG.delete(e)}function oJ(){return oV}function oX(e){for(let t of(oV=e,oG))t()}function oQ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:oH.message;oX({message:e,tone:"muted",updatedAtMs:Date.now()})}function oZ(e){let t=(0,e9.useSyncExternalStore)(oK,oJ,oJ);return(0,e9.useEffect)(()=>{void 0!==e&&oX(e?oz:oH)},[e]),t}let oY={message:"可用",tone:"success"},o0={message:"不可用",tone:"error"},o1=oY,o2=new Set;function o3(e){return o2.add(e),()=>o2.delete(e)}function o4(){return o1}function o5(e){for(let t of(o1=e,o2))t()}function o6(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],t=(0,e9.useSyncExternalStore)(o3,o4,o4);return(0,e9.useEffect)(()=>{o5(e?oY:o0)},[e]),t}function o8(e){var t,r,n;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("locate-sandbox-location"===e.kind)return r$.requestBrowserLocation().then(e=>{var t,r;"success"===e.status?null==(t=a.onMessage)||t.call(a,"浏览器定位已配置"):null==(r=a.onMessage)||r.call(a,`浏览器定位失败:${e.message}`,!0)}),!0;if("update-sandbox-location"===e.kind){try{r$.setManualLocation({latitude:e.latitude,longitude:e.longitude}),null==(t=a.onMessage)||t.call(a,"模拟位置已配置")}catch(t){let e=t instanceof Error?t.message:String(t);r$.setConfigurationError(e),null==(r=a.onMessage)||r.call(a,`坐标配置失败:${e}`,!0)}return!0}return"clear-sandbox-bridge-logs"===e.kind?(a.onClearLogs?a.onClearLogs().then(()=>{var e;return null==(e=a.onMessage)?void 0:e.call(a,"服务端交互日志已清空")}).catch(e=>{var t;return null==(t=a.onMessage)?void 0:t.call(a,e.message,!0)}):null==(n=a.onMessage)||n.call(a,"服务端日志接口不可用",!0),!0):"recreate-sandbox-session"===e.kind?(o5({message:"正在重建",tone:"pending",updatedAtMs:Date.now()}),ag({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(t=>{var r,n,s,i,o;let l=(null==(r=t.data)?void 0:r.business_info_uploaded)===!0;l?oX({message:"已上传",tone:"success",updatedAtMs:Date.now()}):oQ(),o5({message:"已重建",tone:"success",updatedAtMs:Date.now()}),l?null==(i=a.onUpdated)||i.call(a):null==(o=a.onRecreated)||o.call(a),null==(s=a.onMessage)||s.call(a,`调试会话已重建${l?`,${e.csrPem.trim()?"手机号和证书":"手机号"}已自动上传`:""}:${(null==(n=t.data)?void 0:n.sandbox_session_id)??""}`)}).catch(e=>{var t,r;let n=`重建调试会话失败:${e.message}`;oQ(),o5({errorMessage:n,message:"重建失败",tone:"error",updatedAtMs:Date.now()}),null==(t=a.onRecreated)||t.call(a),null==(r=a.onMessage)||r.call(a,n,!0)}),!0):"update-sandbox-business-info"===e.kind&&(oX({message:"正在上传...",tone:"pending",updatedAtMs:Date.now()}),am({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(()=>{var e,t;oX({message:"上传成功",tone:"success",updatedAtMs:Date.now()}),null==(e=a.onUpdated)||e.call(a),null==(t=a.onMessage)||t.call(a,"上传成功")}).catch(e=>{var t;let r=e&&"object"==typeof e&&"logId"in e&&"string"==typeof e.logId?e.logId:"";oX({errorMessage:(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:"")||void 0,message:"上传失败",tone:"error",updatedAtMs:Date.now()}),console.error("Sandbox business info upload failed",e,{logId:r}),null==(t=a.onMessage)||t.call(a,"上传失败",!0)}),!0)}let o7=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"]),o9={query:0,"tool-call":10,"tool-result":20,"agent-processing":25,card:30,"agent-response":40,error:50};function le(e,t){return{category:"api",detail:{query:t},key:"query",phase:"request",payload:{event:"query",query:t},source:e,sources:[e],title:"Query"}}function lt(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=li(ls(e.source));return lr(li(ls(t.source)))>lr(r)}return!1}(r,t),a=n?t:r,s=n?r:t;e.steps.set(t.key,{...r,category:"error"===t.phase?t.category:a.category,detail:lc(a.detail,s.detail),phase:"error"===t.phase?t.phase:a.phase,payload:lc(a.payload,s.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 lr(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 ln(e){let t=lf([...e.steps.values()]);return t.map((r,n)=>{var a,s,i,o,l,d,u;let c,p,m,h,g,f,v,y,_,b,w;return a=r,s=e,i=t,o=n,y=lh(a.sources.flatMap(tb)),_=lh(a.sources.map(e=>lp(ls(e).request_id))),w=void 0===(b=(l=a,d=i,u=o,c=lm(l.payload.elapsed_ms)??lm(l.detail.elapsed_ms),m=(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,h=Number.isFinite(l.source.timestamp)&&Number.isFinite(m)?Math.max(0,m-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?lm(f.payload.elapsed_ms)??lm(f.detail.elapsed_ms):void 0)?v:l.key.startsWith("tool-result:")&&f?void 0:void 0!==c?void 0===h?c:Math.max(c,h):h))?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:{...1===_.length?{request_id:_[0]}:{},..._.length>1?{request_ids:_}:{},...a.payload,trace_id:s.id,...s.status?{run_status:s.status}:{},...void 0===b?{elapsed_ms:void 0}:{elapsed_ms:b},...y.length>0?{log_ids:y}:{}}}})}function la(e,t){let r=lg(ls(t)),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 ls(e){return eK(e.payload)?e.payload:{}}function li(e){return lp(e.event)}function lo(e,t){return ll(e)||[lg(e)||t.id,lp(e.tool_name)||"unknown-tool"].filter(Boolean).join(":")}function ll(e){return lp(e.tool_call_id)}function ld(e){let t=lp(e.tool_name)||ll(e);return t?`: ${t}`:""}function lu(e){let t={};for(let[r,n]of Object.entries(e))null!=n&&""!==n&&(t[r]=n);return t}function lc(e,t){return{...t,...e,...Object.fromEntries(Object.entries(t).filter(t=>{let[r,n]=t;return void 0===e[r]&&void 0!==n}))}}function lp(e){return"string"==typeof e&&e.trim()?e.trim():""}function lm(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function lh(e){return[...new Set(e.filter(e=>!!e))]}function lg(e){let t=eK(e.trace)?e.trace:{};return lp(e.trace_id)||lp(t.trace_id)}function lf(e){return[...e].sort((e,t)=>e.source.timestamp-t.source.timestamp||(e.source.order??0)-(t.source.order??0)||o9[e.key.split(":")[0]]-o9[t.key.split(":")[0]]||e.key.localeCompare(t.key))}function lv(e,t){return e.startedAt-t.startedAt||e.order-t.order||e.id.localeCompare(t.id)}function ly(e,t){return e.timestamp-t.timestamp||(e.order??0)-(t.order??0)||e.id.localeCompare(t.id)}function l_(e){let t=new WeakSet;try{return JSON.stringify(e,(e,r)=>{if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if("function"==typeof r)return`[Function ${r.name||"anonymous"}]`;if(td(r)){if(t.has(r))return"[Circular]";t.add(r)}return r},2)}catch{var r=e;if("string"==typeof r){let e=r.trim();if(!e)return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}if(void 0===r)return"";try{return JSON.stringify(r,null,2)}catch{return String(r)}}}function lb(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:lw(e,t),debug_snapshot:lw(e,{...t,debug:!0,includeRuntimeRoot:!1})}}function lw(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,eK(t)&&!r&&eK(t.runtime_snapshot)?{...t,runtime_snapshot:lx(t.runtime_snapshot,!1)}:t):function(e,t){var r;if(!eK(e))return e;let n=eK(e.simulator)?e.simulator:{},a=Array.isArray(n.messages)?n.messages.filter(e=>lI(e,t.traceId)):void 0,s=Array.isArray(n.tool_calls)?n.tool_calls.filter(e=>lI(e,t.traceId)):void 0,i=lx(e.runtime_snapshot,!1!==t.includeRuntimeRoot);return{...lR(e,["exported_at","client_id","command_id","context","render_targets"]),...eK(i)?{runtime_snapshot:i}:{},...eK(e.simulator)?{simulator:{...lR(n,["stream_status","active_request_id","active_reply_message_id"]),...n.error?{error:lM(n.error)}:{},...n.selected_card?{selected_card:lN(n.selected_card)}:{},...n.answer_finish?{answer_finish:eK(r=n.answer_finish)?lR(r,["messageId","status","finishReason","usage","createdAtMs"]):r}:{},...a?{messages:a.map(lE)}:{},...s?{tool_calls:s.map(lk)}:{},...Array.isArray(n.trace_events)?{trace_events:lS(n.trace_events,{debug:t.debug,messages:a,traceId:t.traceId})}:{}}}:{},...Array.isArray(e.widget_runtime_trace_events)?{widget_runtime_trace_events:lS(e.widget_runtime_trace_events,{debug:t.debug,traceId:t.traceId})}:{},...Array.isArray(e.page_runtime_trace_events)?{page_runtime_trace_events:lS(e.page_runtime_trace_events,{debug:t.debug,traceId:t.traceId})}:{},...eK(e.runtime_console)?{runtime_console:e.runtime_console}:{}}}(e,n),s=tb(e);return s.length>0&&eK(a)?{...a,log_ids:s}:a}function lS(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=>lg(ls(e))===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(ly))!function(e,t){var r,n;let a=ls(t),s=li(a);if("tool_result_report_started"===s){let r=la(e,t);if(!r)return;lt(r,function(e){let t=ls(e),r=lu({tool_call_id:ll(t),tool_name:t.tool_name});return{category:"agent",detail:r,key:`agent-processing:${lo(t,e)}`,phase:"request",payload:{event:"agent_processing",...r},source:e,sources:[e],title:`Agent Processing${ld(t)}`}}(t));return}if(!((r=s).startsWith("tool_result_report_")||"tool_result_ack"===r)){if("simulator_chat_fetch_started"===s){let r=function(e){let t=eK(e.request)?e.request:{},r=eK(t.message)?t.message:{};return lp(e.query)||lp(t.query)||lp(r.content)}(a);if(!r)return;let n=la(e,t);if(!n)return;lt(n,le(t,r));return}if("tool_call"===s||"local_mcp_call_started"===s){let r=la(e,t);if(!r)return;lt(r,function(e){let t=ls(e),r=lu({tool_call_id:ll(t),tool_name:t.tool_name,arguments:t.arguments,arguments_json:t.arguments_json});return{category:"agent",detail:r,key:`tool-call:${lo(t,e)}`,phase:"request",payload:{event:"tool_call",...r},source:e,sources:[e],title:`Tool Call${ld(t)}`}}(t));return}if("local_mcp_call_succeeded"===s||"local_mcp_call_failed"===s){let r=la(e,t);if(!r)return;lt(r,function(e){let t=ls(e),r="local_mcp_call_failed"===li(t),n=lu({tool_call_id:ll(t),tool_name:t.tool_name,status:t.status,result:t.result,structured_result:t.structured_result,structured_result_json:t.structured_result_json,raw_result_text:t.raw_result_text,raw_mcp_result:t.raw_mcp_result,raw_mcp_result_json:t.raw_mcp_result_json,elapsed_ms:t.elapsed_ms,error:t.error});return{category:"mcp",detail:n,key:`tool-result:${lo(t,e)}`,phase:r?"error":"response",payload:{event:r?"tool_result_failed":"tool_result",...n},source:e,sources:[e],title:`${r?"Tool Result Failed":"Tool Result"}${ld(t)}`}}(t));return}if("card_delta"===(n=s)||"simulator_card_rendered"===n||"simulator_card_render_failed"===n||"simulator_card_runtime_error"===n||"simulator_card_render_skipped"===n){let r=la(e,t);if(!r)return;lt(r,function(e){var t,r;let n=ls(e),a=li(n),s="error"in n||a.endsWith("_failed")||a.endsWith("_error"),i=lu({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:i,key:`card:${t=n,r=e,lp(t.card_id)||lp(t.source_tool_call_id)||[lg(t)||r.id,lp(t.widget_id)||r.id].filter(Boolean).join(":")}`,phase:s?"error":"response",payload:{event:s?"card_render_failed":"card_delta"===a?"card_received":"card_rendered",...i},source:e,sources:[e],title:s?"Card Render Failed":"card_delta"===a?"Card Received":"Card Rendered"}}(t));return}if(function(e,t){let r=lp(e.phase),n=e.status;return o7.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,s)){let r=la(e,t);if(!r)return;lt(r,function(e){var t,r;let n=ls(e),a=eK(n.detail)?n.detail:{},s=n.event_count??a.event_count,i=lu({elapsed_ms:n.elapsed_ms??a.elapsed_ms,endpoint:n.endpoint??a.endpoint,error:n.error??a.error,event_count:s,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"===li(n)&&0===s?"对话流未收到任何事件,未触发 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:i,key:`error:${e.id}`,phase:"error",payload:{event:li(n)||"trace_error",...i},source:e,sources:[e],title:(null==(r=e.display)?void 0:r.title)||lp(n.title)||"Trace Error"}}(t))}}}(r,t);for(let e of t)!function(e,t){var r,n,a,s;let i=(r=t,{id:`trace-message-${r.messageId}`,timestamp:r.createdAtMs,payload:lu({message_id:r.messageId,request_id:r.requestId,trace_id:r.traceId})}),o=la(e,i);o&&("assistant"===t.role&&t.status&&(n=o,a=t.status,s=t.createdAtMs,void 0!==n.statusUpdatedAt&&s<n.statusUpdatedAt||(n.status=a,n.statusUpdatedAt=s)),"user"===t.role&&t.text.trim()&&!o.steps.has("query")&<(o,le(i,t.text)),"assistant"===t.role&&t.text.trim()&<(o,function(e,t){let r=lf([...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:"number"==typeof(null==r?void 0:r.source.order)?r.source.order+.1:null==r?void 0:r.source.order,timestamp:n,payload:lu({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"}}(o,t)))}(r,e);return r}(e,t.messages);return(t.traceId?a.runs.filter(e=>e.id===t.traceId):a.runs).sort(lv).flatMap(ln)}(e,t)}function lx(e,t){if(!eK(e)||t)return e;let{root:r,...n}=e;return n}function lI(e,t){if(!t)return!0;if(!eK(e))return!1;let r=eK(e.trace)?e.trace:{};return e.traceId===t||r.trace_id===t}function lE(e){return eK(e)?{...lR(e,["messageId","localMessageId","requestId","traceId","role","contentType","status","createdAtMs"]),..."string"==typeof e.text?{text:lT(e.text)}:{},...Array.isArray(e.blocks)?{blocks:e.blocks.map(lC)}:{},...Array.isArray(e.toolCalls)?{toolCalls:e.toolCalls}:{},...Array.isArray(e.toolResults)?{toolResults:e.toolResults}:{}}:e}function lC(e){return eK(e)?"card"===e.type?{...lR(e,["blockId","type"]),card:lN(e.card)}:{...lR(e,["blockId","type"]),..."string"==typeof e.text?{text:lT(e.text)}:{}}:e}function lk(e){return eK(e)?{...lR(e,["requestId","runId","replyMessageId","toolCallId","toolName","serverId","appKey","status","createdAtMs","updatedAtMs","requiresUserApproval","timeoutMs","deadlineMs","progress","message","resultSummary","structuredResultSummary","isMiniApp"]),...void 0===e.arguments?{}:{arguments:e.arguments},...void 0===e.arguments&&e.argumentsJson?{argumentsJson:e.argumentsJson}:{},...e.error?{error:lM(e.error)}:{}}:e}function lN(e){return eK(e)?lR(e,["reply_message_id","block_id","card_id","widget_id","card_type","app_id","entity_id","title","fallback_text"]):e}function lM(e){return eK(e)?lR(e,["code","message","user_message","retryable","stage","details","name","stack"]):e}function lR(e,t){let r={};for(let n of t)void 0!==e[n]&&(r[n]=e[n]);return r}function lT(e){return e.length>1e3?`${e.slice(0,1e3)}...`:e}function lA(e){let[t,r]=(0,e9.useState)(),n=(0,e9.useRef)(),a=(0,e9.useRef)(),s=iy((e,t)=>{if(a.current===e.commandId)return!1;a.current=e.commandId;let s={previousTarget:t,command:e};return n.current=s,r(s),!0}),i=iy((t,a)=>{var s;(null==(s=n.current)?void 0:s.command.commandId)===t&&(n.current=void 0,r(void 0),null==e||e(t,a))});return{accept:s,pending:t,pendingRef:n,report:i}}let lP="u"<typeof window?e9.useEffect:e9.useLayoutEffect;function lj(e,t){let[r,n]=(0,e9.useState)(rg),[a,s]=(0,e9.useState)("fit"),i=(0,e9.useRef)(),o=(0,e9.useMemo)(()=>r_(r),[r]),l=rv.find(e=>e.key===a)??rv.find(e=>"fit"===e.key)??rv[0],d="fit"===l.key,{fitScale:u,setRuntimeShellRef:c}=function(e){let{deviceHeight:t,deviceWidth:r,enabled:n}=e,[a,s]=(0,e9.useState)(.88),i=(0,e9.useRef)(null),o=(0,e9.useRef)(null),l=(0,e9.useCallback)(()=>{let e=i.current;if(!e)return;let n=getComputedStyle(e),a=Number.parseFloat(n.paddingLeft)+Number.parseFloat(n.paddingRight),o=Number.parseFloat(n.paddingTop)+Number.parseFloat(n.paddingBottom),l=Math.floor(1e3*Math.max(.1,Math.min(1,(e.clientWidth-a-12)/r,(e.clientHeight-o-12)/t)))/1e3;s(e=>Math.abs(e-l)>.001?l:e)},[t,r]),d=(0,e9.useCallback)(e=>{var t;if(null==(t=o.current)||t.disconnect(),o.current=null,i.current=e,!e||!n)return;let r=new ResizeObserver(l);r.observe(e),o.current=r,l()},[n,l]);return lP(()=>{n&&l()},[n,l]),lP(()=>()=>{var e;null==(e=o.current)||e.disconnect()},[]),{fitScale:a,setRuntimeShellRef:d}}({deviceHeight:o.height,deviceWidth:o.width,enabled:d}),p=d?u:l.scale,m=d?"fit":"fixed",h={"--wsd-runtime-width":`${o.width}px`,"--wsd-runtime-height":`${o.height}px`,"--wsd-runtime-layout-width":`${o.width*p}px`,"--wsd-runtime-layout-height":`${o.height*p}px`,"--wsd-runtime-radius":`${o.radius}px`,"--wsd-runtime-home-indicator-display":o.homeIndicator?"block":"none","--wsd-runtime-safe-area-bottom":`${o.safeArea.bottom}px`,"--wsd-runtime-scale":p};return(0,e9.useEffect)(()=>{if((null==e?void 0:e.type)!=="set_viewport"||i.current===e.commandId)return;let a=`custom-${e.width}x${e.height}`;r!==a?n(a):(i.current=e.commandId,null==t||t(e.commandId,{ok:!0,result:{width:e.width,height:e.height}}))},[e,t,r]),{runtimeScaleMode:m,runtimeStyle:h,selectedDevice:o,selectedDeviceKey:r,selectedScaleKey:a,setRuntimeShellRef:c,setSelectedDeviceKey:n,setSelectedScaleKey:s}}let lD={logs:[],updatedAtMs:0};function lL(e){if(eK(e)&&"string"==typeof e.id&&eK(e.request)&&"string"==typeof e.status&&["error","pending","success"].includes(e.status)&&"number"==typeof e.timestamp&&"number"==typeof e.updatedAtMs)return{errorMessage:"string"==typeof e.errorMessage?e.errorMessage:void 0,id:e.id,logIds:Array.isArray(e.logIds)?e.logIds.filter(e=>"string"==typeof e):[],request:e.request,requestId:"string"==typeof e.requestId?e.requestId:"",response:eK(e.response)?e.response:void 0,sandboxSessionId:"string"==typeof e.sandboxSessionId?e.sandboxSessionId:"",status:e.status,timestamp:e.timestamp,updatedAtMs:e.updatedAtMs}}function lO(e){return eK(e)?{logs:Array.isArray(e.logs)?e.logs.map(lL).filter(e=>!!e):[],updatedAtMs:"number"==typeof e.updatedAtMs?e.updatedAtMs:0}:lD}function lU(e){let[t,r]=(0,e9.useState)(lD),n=(0,e9.useRef)(0),a=iy(async()=>{if(!e)throw Error("服务端日志接口不可用");let t=++n.current,a=await fetch(e,{headers:{Accept:"application/json"},method:"DELETE"});if(!a.ok)throw Error(`清空服务端日志失败(HTTP ${a.status})`);let s=lO(await a.json());t===n.current&&r(s)});return(0,e9.useEffect)(()=>{let t,a;if(!e)return void r(lD);let s=!1,i=async()=>{a=new AbortController;let o=n.current;try{let t=await fetch(e,{cache:"no-store",headers:{Accept:"application/json"},signal:a.signal});if(t.ok&&!s&&o===n.current){let e=lO(await t.json());r(t=>t.updatedAtMs===e.updatedAtMs?t:e)}}catch{}s||(t=window.setTimeout(i,1e3))};return i(),()=>{s=!0,null==a||a.abort(),void 0!==t&&window.clearTimeout(t)}},[e]),{clearLogs:a,logs:t.logs}}function lq(){return(0,e9.useSyncExternalStore)(r$.subscribe,r$.getSnapshot,r$.getSnapshot)}function l$(e,t,r){var n;let a=(0,e9.useRef)(),s=!!(e&&r&&((null==(n=a.current)?void 0:n.endpoint)!==e||a.current.snapshot!==r)),i=(0,e9.useMemo)(()=>e?l_(lb(t,{includeRuntimeRoot:s})):void 0,[e,s,t]);(0,e9.useEffect)(()=>{if(!e||!i)return;let t=window.setTimeout(()=>{e&&"u">typeof fetch&&fetch(e,{body:i,headers:{"Content-Type":"application/json"},method:"POST"}).catch(()=>{}),s&&r&&(a.current={endpoint:e,snapshot:r})},500);return()=>window.clearTimeout(t)},[e,s,r,i])}let lB={appEntries:[],entries:[],updatedAtMs:0};function lF(e,t){var r;return!t||e.traceId===t||(null==(r=e.trace)?void 0:r.trace_id)===t}function lW(e,t){var r;let{chromeDevToolsFrontendUrl:n,controlCommand:a,controlClientId:s,debugContext:i,onChromeDevToolsPanelChange:o,onActiveViewChange:l,onControlResult:d,onMessage:u,onNavigateToPage:c,apiEnvironment:p,showDebugTrace:m,traceSnapshotEndpoint:h,webSdkDebugger:g}=e,f=iv(g),v=(0,e9.useMemo)(()=>f.widgets.filter(to),[f.widgets]),y=(0,e9.useRef)(null),_=(0,e9.useRef)(null),S=(0,e9.useRef)(null),x=(0,e9.useRef)(null),I=(0,e9.useRef)(null);!I.current&&"u">typeof document&&(I.current=document.createElement("div"));let[E,C]=(0,e9.useState)(0),k=iy(()=>_.current),[N,M]=(0,e9.useState)(null),[R,T]=(0,e9.useState)(!1),[A,P]=(0,e9.useState)(0),[j,D]=(0,e9.useState)(!1),[L,O]=(0,e9.useState)([]),[U,q]=(0,e9.useState)(lB),[$,B]=(0,e9.useState)(null),[F,W]=(0,e9.useState)(null),[H,z]=(0,e9.useState)(),[V,G]=(0,e9.useState)(0),[K,J]=(0,e9.useState)(0),[X,Q]=(0,e9.useState)(0),Z=ix(),Y=oI(),ee=or(),et=(null==i?void 0:i.sandboxSessionAvailable)!==!1,er=ok(i),[en,ea]=(0,e9.useState)(!0!==er),es=oZ(er),ei=lq(),eo=o6(et),{clearLogs:el,logs:ed}=lU(null==i?void 0:i.sandboxBridgeLogsEndpoint),eu=(0,e9.useRef)(null),ec=(0,e9.useMemo)(()=>x.current,[E]),{accept:ep,pending:em,pendingRef:eh,report:eg}=lA(d),ef=(0,e9.useRef)(),ev=(0,e9.useRef)(new Map),ey=(0,e9.useRef)(new Map),e_=(0,e9.useRef)(0),{runtimeScaleMode:eb,runtimeStyle:ew,selectedDevice:eS,selectedDeviceKey:ex,setRuntimeShellRef:eI,setSelectedDeviceKey:eE}=lj(a,d),eC=(0,e9.useRef)(ex),ek=(null==(r=f.widgetSelection)?void 0:r.item.widgetId)??"",eN=(0,e9.useRef)(ek),eM=f.simulator,eR=(0,e9.useRef)(eM.toolCalls),eT=!!f.widgetSelection&&"streaming"!==eM.streamStatus&&!j,eA=(0,e9.useMemo)(()=>({...ry,density:eS.density,label:eS.label,width:Math.max(1,eS.width-38)}),[eS.density,eS.label,eS.width]);(0,e9.useEffect)(()=>{eR.current=eM.toolCalls},[eM.toolCalls]);let eP=iy(e=>{let t=function(e,t){var r;if(!eK(e))return e;let n="string"==typeof e.source_tool_call_id?e.source_tool_call_id:void 0,a=n?t.find(e=>e.toolCallId===n):void 0;if(!a)return e;let s=eK(e.trace)?e.trace:{},i="string"==typeof e.trace_id||"string"==typeof s.trace_id;return{...e,...e.request_id?{}:{request_id:a.requestId},...i||!(null==(r=a.trace)?void 0:r.trace_id)?{}:{trace_id:a.trace.trace_id}}}(e,eR.current),r=++e_.current,n={display:tW(t),id:`trace-${r}`,order:r,payload:t,timestamp:Date.now()};O(e=>[...e,n].slice(-200))}),ej=iy(()=>{O([])}),eD=(0,e9.useMemo)(()=>[...eM.traceEvents.map((e,t)=>({event:e,sortOrder:e.order??t})),...L.map((e,t)=>({event:e,sortOrder:e.order??eM.traceEvents.length+t}))].sort((e,t)=>e.event.timestamp-t.event.timestamp||e.sortOrder-t.sortOrder||e.event.id.localeCompare(t.event.id)).map(e=>{let{event:t}=e;return t}),[L,eM.traceEvents]),eL=(0,e9.useMemo)(()=>({...i,manifestUrl:f.manifestUrl,simulatorEndpoint:eM.endpoint}),[i,eM.endpoint,f.manifestUrl]),eO=(0,e9.useMemo)(()=>oB({context:eL,events:eD,manifest:f.manifest,pages:f.pages,widgets:f.widgets}),[eD,eL,f.manifest,f.pages,f.widgets]),eU=eO.appId||f.manifest.appId,eq=eO.appName||f.manifest.name,e$=(0,e9.useMemo)(()=>({type:"widget",appId:eU,appName:eq,widgetId:ek,viewport:{key:eS.key,label:eS.label,width:Math.max(1,eS.width-38),height:eS.height,density:eS.density}}),[eU,eq,eS,ek]),eB=(0,e9.useMemo)(()=>oW(eO,"card"===t&&f.widgetSelection?e$:void 0),[t,e$,eO.pages,eO.widgets,f.widgetSelection]),eF=!!(em&&oF($,ec,em.previousTarget)&&"card"===t&&ek===em.command.widgetId),eW=(0,e9.useMemo)(()=>"card"===t&&(null==$?void 0:$.sourceTarget)===ec?{target:e$,root:$.root,nodeCount:$.nodeCount,selectedUid:$.selectedUid,truncated:$.truncated,updatedAtMs:$.updatedAtMs}:void 0,[t,e$,$,ec]),eH=(0,e9.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:s,...eF?{command_id:null==em?void 0:em.command.commandId}:{},context:{launch_dir:eL.launchDir,manifest_url:f.manifestUrl,app_id:eU,app_name:f.manifest.name,mcp_endpoint:eL.mcpEndpoint,mcp_original_endpoint:eO.sources.mcp.original,mcp_proxy_endpoint:eO.sources.mcp.proxy,simulator_manifest_original_url:eO.sources.manifest.original,simulator_manifest_proxy_url:eO.sources.manifest.proxy,simulator_manifest_url:eL.simulatorManifestUrl,simulator_skill_original_url:eO.sources.skill.original,simulator_skill_proxy_url:eO.sources.skill.proxy,simulator_skill_url:eL.simulatorSkillUrl,widget_id:ek,simulator_endpoint:eM.endpoint,web_url:eL.webUrl},render_targets:eB,runtime_snapshot:eW,simulator:{stream_status:eM.streamStatus,active_request_id:eM.activeRequestId,active_reply_message_id:eM.activeReplyMessageId,error:eM.error,answer_finish:eM.answerFinish,messages:eM.messages,tool_calls:eM.toolCalls,trace_events:eM.traceEvents},runtime_console:{app:{entries:U.appEntries,updated_at_ms:U.updatedAtMs},widget:{entries:U.entries,updated_at_ms:U.updatedAtMs}},widget_runtime_trace_events:L}),[L,eO.sources.manifest.original,eO.sources.manifest.proxy,eO.sources.mcp.original,eO.sources.mcp.proxy,eO.sources.skill.original,eO.sources.skill.proxy,eL.launchDir,eL.mcpEndpoint,eL.simulatorManifestUrl,eL.simulatorSkillUrl,eL.webUrl,U,ek,eM,eU,s,eF,null==em?void 0:em.command.commandId,eB,f.manifest.name,f.manifestUrl,eW]),ez=iy(e=>{g.approveSimulatorToolCall(e).catch(e=>{null==u||u(e.message,!0)})}),eV=iy(e=>{g.rejectSimulatorToolCall(e).catch(e=>{null==u||u(e.message,!0)})}),eG=iy(e=>{"clear-trace-filter"===e.kind?z(void 0):o8(e,{onClearLogs:el,onMessage:u,onRecreated:()=>ea(!0),onUpdated:()=>ea(!1)})||("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&("approve-tool-call"===e.kind?ez:eV)(e.toolCallId)}),eJ=iy(e=>{z(t=>t===e?void 0:e)}),eX=iy(()=>{G(e=>Math.max(e,K)+1)});(0,e9.useEffect)(()=>{"success"===es.tone&&ea(!1)},[es.tone]),(0,e9.useEffect)(()=>{void 0!==er&&ea(!er)},[er]);let eQ=iy(()=>{J(e=>Math.max(e,V)+1)}),eZ=iy(()=>{J(e=>Math.max(e,V)+1),Q(e=>e+1)}),eY=iy(e=>{e.stopPropagation(),ea(!1)}),e0=Math.max(V,K);(0,e9.useEffect)(()=>{H&&!eM.messages.some(e=>lF(e,H))&&z(void 0)},[H,eM.messages]);let e1=(0,e9.useMemo)(()=>m?eD:eD.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[eD,m]),e2="conversation"===t?F:ec,e3=iy(e=>{W(e)}),e4=iy((e,t)=>{t?ey.current.set(e,t):ey.current.delete(e)}),e5=iy((e,t)=>Array.from(ey.current.values()).reverse().find(r=>{let n;return r.isConnected&&(n=r.getBoundingClientRect()).width>0&&n.height>0&&e>=n.left&&e<=n.right&&t>=n.top&&t<=n.bottom})??null),e6=(0,e9.useMemo)(()=>lS(e1,{debug:m,messages:eM.messages,traceId:H}),[H,m,eM.messages,e1]),e8=(0,e9.useMemo)(()=>H?eM.toolCalls.filter(e=>lF(e,H)):eM.toolCalls,[H,eM.toolCalls]),e7=(0,e9.useMemo)(()=>lw(eH,{debug:m,traceId:H}),[H,m,eH]),te=(0,e9.useMemo)(()=>l_(e7),[e7]),tt=(0,e9.useMemo)(()=>({debugData:eO,events:e6,logSnapshot:e7,logSnapshotText:te,sandbox:{available:et,csrRequired:(null==i?void 0:i.sandboxCsrRequired)!==!1,input:{csrPem:(null==i?void 0:i.sandboxCsrPem)??"",phoneNum:(null==i?void 0:i.sandboxPhoneNum)??""},logs:ed,businessInfoStatus:es,location:ei,locationFocusRequestId:X,sessionStatus:eo},showDebugTrace:m,traceFilterId:H??"",traceSurface:"conversation",toolCalls:e8,updatedAtMs:Date.now()}),[eO,e8,e6,e7,te,ed,et,es,ei,X,eo,null==i?void 0:i.sandboxCsrRequired,H,m]);l$(h,eH,$),(0,e9.useEffect)(()=>{if((null==a?void 0:a.type)==="render_widget"&&ep(a,ec))try{g.selectWidget(a.widgetId)}catch(e){eg(a.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[ep,a,eg,g,ec]),(0,e9.useEffect)(()=>{em&&eF&&eg(em.command.commandId,{ok:!0,target:e$,snapshot:lb(eH)})},[e$,eF,em,eg,eH]);let tr=(0,e9.useMemo)(()=>{let e=(e,t,r)=>{var n;if("AppletBridgeModule"===r&&("postMessage"===e||"postMessageSync"===e)&&eK(n=t)&&"call"===n.type&&"string"==typeof n.name&&"number"==typeof n.callbackId){if("mind.getAgentTraceSwitch"===t.name)return op(t,{value:!0});if("mind.reportAgentTraceEvent"===t.name)return eP(t.params??{}),op(t)}};return(t,r,n,a)=>"AppletBridgeModule"===n&&"postMessage"===t&&b(r)&&"doubao.navigateTo"===r.name&&eK(r.params)&&"string"==typeof r.params.url?(null==c||c({url:r.params.url}),null==u||u(`卡片 navigateTo: ${r.params.url}`),w(r,{})):e(t,r,n,a)},[eP,u,c]),tn=(0,e9.useCallback)(e=>aU({appId:eU,appIcon:f.manifest.iconSrc,appName:eq,baseAPIRegistry:null==p?void 0:p.apiRegistry,onCustomLoginNavigate:e=>null==c?void 0:c({url:e}),sendFollowUpMessage:e=>{let{content:t,prompt:r}=e;return g.sendSimulatorQuery(r,{followUpContent:t})},multiMediaBroadcastContainer:e??void 0,runtimeHost:null==p?void 0:p.runtimeHost,scanCodePresenter:Y.scanCodePresenter,showSandboxCashier:Z.showCashier,uiPresenter:Y.presenter,showSimulatorPermission:ee.showPermission,vibrationContainer:S.current??void 0}),[p,eU,eq,c,Z.showCashier,Y.scanCodePresenter,Y.presenter,ee.showPermission,f.manifest.iconSrc,g]),ta=(0,e9.useMemo)(()=>tn(),[tn]),ts=iy(e=>{x.current!==e&&(x.current=e,C(e=>e+1)),M(null)});(0,e9.useEffect)(()=>{let e=y.current;if(!e)return;let t=tn(e),r=new ih({container:e,fileSystemNamespace:null==i?void 0:i.fileSystemNamespace,nativeModulesCallHandler:tr,webSdkDebugger:g,onError:e=>{null==u||u(`Widget runtime error ${ek}: ${e.message}`,!0)},apiEnvironment:t});eu.current=r;let n=r.subscribeTarget(ts);return ts(r.getCurrentTarget()),()=>{n(),r.destroy(),eu.current=null,ts(null)}},[t,tn,null==i?void 0:i.fileSystemNamespace,tr,u,ek,ts,g]);let ti=iy(async function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=eu.current,n=t.widgetId??(null==(e=f.widgetSelection)?void 0:e.item.widgetId);if(!r||!n)return!1;let a=t.initData??ev.current.get(n);void 0!==t.initData&&ev.current.set(n,t.initData),console.log(`Rendering widget ${n} with initData:`,a),ej();try{return await r.render({widgetId:n,...a?{initData:a}:{},viewport:{...ry,density:eS.density,label:eS.label,width:Math.max(1,eS.width-38)}}),eC.current=ex,T(!0),null==u||u(`Rendered widget ${n}`),!0}catch(t){T(!1),null==u||u(t.message,!0);let e=eh.current;return(null==e?void 0:e.command.widgetId)===n&&eg(e.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:t.message}}),!1}});(0,e9.useEffect)(()=>{let e=eh.current;e&&"card"===t&&eu.current&&ef.current!==e.command.commandId&&(ef.current=e.command.commandId,ti({widgetId:e.command.widgetId,initData:e.command.structuredContent}))},[t,em,ti]),(0,e9.useEffect)(()=>{var e,t;let r=eN.current;if((eN.current=ek,r!==ek)&&(null==(e=eh.current)?void 0:e.command.widgetId)!==ek){if(f.widgetSelection)return void ti();ej(),T(!1),null==(t=eu.current)||t.clear()}},[ej,ti,ek,f.widgetSelection]),(0,e9.useEffect)(()=>{!eh.current&&R&&eC.current!==ex&&ti()},[R,ti,ex]);let tl=iy(async()=>{if(!eT)return!1;D(!0);try{if(await g.reloadResources(),P(e=>e+1),R&&!await ti())return!1;return null==u||u("已刷新卡片资源"),!0}catch(e){return null==u||u(e.message,!0),!1}finally{D(!1)}});return{activeView:t,appendAgentTraceEvent:eP,canReloadResources:eT,cardReloadKey:A,chromeDevToolsFrontendUrl:n,controlCommand:a,conversationAPIEnvironment:ta,conversationConsoleTarget:I.current,conversationWidgetViewport:eA,currentDebugAppId:eU,currentDebugAppName:eq,debugState:tt,devtoolsTarget:e2,devToolsPanelId:K===e0&&e0>0?"wsd-sandbox":V>0?"wsd-trace":void 0,getRuntimeFrame:k,handleDebugAction:eG,handleGrantingSheetTargetChange:e3,handleInspectableCardTargetChange:e4,handleQuerySubmit:eX,handleSandboxLoginHintClick:eQ,handleSandboxLoginHintClose:eY,handleSandboxLocationConfigOpen:eZ,handleTraceMessageSelect:eJ,hasRenderedPreview:R,highlightRect:N,latestDevToolsPanelRequestId:e0,nativeModulesCallHandler:tr,onActiveViewChange:l,onChromeDevToolsPanelChange:o,onControlResult:d,onMessage:u,onNavigateToPage:c,reloadResources:tl,renderSelectedWidget:ti,resolveConversationInspectTarget:e5,runtimeFrameRef:_,runtimeFrameScaleBoxRef:S,runtimeScaleMode:eb,runtimeStyle:ew,runtimeTargetRef:y,sandboxCashier:Z,simulatorUI:Y,simulatorPermissionPrompt:ee,selectedDeviceKey:ex,selectedTraceId:H,selectedWidgetId:ek,setHighlightRect:M,setRuntimeConsoleSnapshot:q,setRuntimeDomSnapshot:B,setSelectedDeviceKey:eE,setRuntimeShellRef:eI,sandboxLoginAvailable:et,showSandboxLoginHint:en,simulatorState:eM,state:f,visibleWidgets:v,webSdkDebugger:g}}function lH(e){let t=lW(e,"conversation");return(0,s.jsx)(oc,{runtime:t,children:(0,s.jsx)(iw,{highlightRect:t.highlightRect,overlay:(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("section",{"aria-label":"对话",className:"wsd-widget-phone-scroll is-conversation",children:(0,s.jsx)(i9,{apiEnvironment:t.conversationAPIEnvironment,appId:t.currentDebugAppId,cardReloadKey:t.cardReloadKey,controlCommand:t.controlCommand,nativeModulesCallHandler:t.nativeModulesCallHandler,onControlResult:t.onControlResult,onMessage:t.onMessage,onGrantingSheetTargetChange:t.handleGrantingSheetTargetChange,onInspectableCardTargetChange:t.handleInspectableCardTargetChange,onNavigateToPage:t.onNavigateToPage,onQuerySubmit:t.handleQuerySubmit,onSandboxLocationConfigOpen:t.handleSandboxLocationConfigOpen,onTraceEvent:t.appendAgentTraceEvent,onTraceMessageSelect:t.handleTraceMessageSelect,runtimeConsoleTarget:t.conversationConsoleTarget,sandboxLoginHint:t.showSandboxLoginHint?{available:t.sandboxLoginAvailable,onClose:t.handleSandboxLoginHintClose,onOpen:t.handleSandboxLoginHintClick}:void 0,selectedTraceId:t.selectedTraceId,simulator:t.simulatorState,webSdkDebugger:t.webSdkDebugger,widgetViewport:t.conversationWidgetViewport,widgets:t.state.widgets})}),t.simulatorUI.overlay,t.sandboxCashier.cashier?(0,s.jsx)(iS,{cashier:t.sandboxCashier.cashier,onCancel:t.sandboxCashier.cancelCashier,onConfirm:t.sandboxCashier.confirmCashier}):null,t.simulatorPermissionPrompt.permission?(0,s.jsx)(ot,{onAllow:t.simulatorPermissionPrompt.allowPermission,onReject:t.simulatorPermissionPrompt.rejectPermission,permission:t.simulatorPermissionPrompt.permission}):null]}),runtimeFrameRef:t.runtimeFrameRef,runtimeFrameScaleBoxRef:t.runtimeFrameScaleBoxRef,runtimeScaleMode:t.runtimeScaleMode,runtimeShellRef:t.setRuntimeShellRef,runtimeStyle:t.runtimeStyle})})}var lz=r(18017),lV=r(29912),lG=r(80405);async function lK(e,t,r){let n=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!n.ok)throw Error(`加载 ${t}失败:HTTP ${n.status} ${n.statusText}`);return n.json()}async function lJ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/__web_sdk_debug_scenes",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:fetch;var r=await lK(e,"Scene ",t);if(!eK(r)||!Array.isArray(r.scenes)||!Array.isArray(r.errors))throw Error("Scene 发现接口返回了无效数据");let n=r.scenes.flatMap(e=>eK(e)&&"string"==typeof e.name&&eK(e.content)?[{content:e.content,name:e.name}]:[]);return{errors:r.errors.flatMap(e=>eK(e)&&"string"==typeof e.name&&"string"==typeof e.message?[{name:e.name,message:e.message}]:[]),scenes:n}}function lX(e){let t=e.content,r=eH(t),n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{...e.input||{},...eH(e,t)}}(t);if("page"===t.type){if(t.url){var a;let n=(a=t.url,a.replace(eW,(e,t)=>Object.prototype.hasOwnProperty.call(r,t)?encodeURIComponent(r[t]):e)),s=function(e){let t=new Set;for(let r of e.matchAll(eW))t.add(r[1]);return Array.from(t)}(n);if(s.length>0)throw Error(`Scene ${e.name} 缺少 URL 变量:${s.map(e=>`{{${e}}}`).join("、")}`);return{type:"page",url:n}}if(t.id)return{type:"page",url:function(e,t){let r=new URLSearchParams;for(let[e,n]of Object.entries(t)){let t="string"==typeof n?n:JSON.stringify(n);void 0!==t&&r.set(e,t)}let n=r.toString();return n?`${e}?${n}`:e}(t.id,n)};throw Error("Page Scene 必须配置 id 或 url")}if("widget"===t.type)return{initData:n,sceneName:e.name,type:"widget",widgetId:t.id};throw Error("Web Debugger 暂不支持 Tool Scene")}let lQ={appEntries:[],entries:[],updatedAtMs:0};function lZ(e){var t,r;return e.path??(null==(r=(t=e).web)?void 0:r.entry)??t.entry}function lY(e){let{showTooltip:t=!1,value:r}=e,n=r.indexOf("?"),a=n<0?r:r.slice(0,n),i=n<0?"":r.slice(n),o=(0,s.jsxs)("span",{className:"wsd-page-route-label",children:[(0,s.jsx)("span",{className:"wsd-page-route-path",children:a}),i?(0,s.jsx)("span",{className:"wsd-page-route-query",children:i}):null]});return t?(0,s.jsx)(lz.I,{closeDelay:0,content:r,delay:300,placement:"right",children:o}):o}function l0(){return(0,s.jsx)("svg",{"aria-hidden":"true",className:"wsd-page-route-arrow is-back",viewBox:"0 0 16 16",children:(0,s.jsx)("path",{d:"M3 8h10M9 4l4 4-4 4",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}function l1(e){var t,r,n,a;let{activeView:i,chromeDevToolsFrontendUrl:o,controlCommand:l,controlClientId:d,debugContext:u,onChromeDevToolsPanelChange:c,onActiveViewChange:p,onControlResult:m,onMessage:h,apiEnvironment:g,showDebugTrace:f,traceSnapshotEndpoint:v,webSdkDebugger:y}=e,_=iv(y),b=(0,e9.useMemo)(()=>_.pages.filter(to),[_.pages]),[w,S]=(0,e9.useState)({errors:[],scenes:[]}),[x,I]=(0,e9.useState)(""),[E,C]=(0,e9.useState)(null),[k,N]=(0,e9.useState)(null),[M,R]=(0,e9.useState)(null),[T,A]=(0,e9.useState)(null),[P,j]=(0,e9.useState)(null),[D,L]=(0,e9.useState)(0),[O,U]=(0,e9.useState)(null),[q,$]=(0,e9.useState)(lQ),B=ix(),F=oI(),W=(null==u?void 0:u.sandboxSessionAvailable)!==!1,H=oZ(ok(u)),z=lq(),V=o6(W),{clearLogs:G,logs:K}=lU(null==u?void 0:u.sandboxBridgeLogsEndpoint),[J,X]=(0,e9.useState)(null),Q=or(),Z=(0,e9.useRef)(null),{accept:Y,pending:ee,pendingRef:et,report:er}=lA(m),{runtimeScaleMode:en,runtimeStyle:ea,selectedDevice:es,selectedDeviceKey:ei,setRuntimeShellRef:eo,setSelectedDeviceKey:el}=lj(l,m),ed=(null==(t=_.pageSelection)?void 0:t.item.id)??"",eu=_.pageSelection?lZ(_.pageSelection.item):"",ec=(0,e9.useMemo)(()=>w.scenes.flatMap(e=>{let t=lX(e);if("page"!==t.type)return[];try{let{entry:r}=e3({url:t.url},_.manifest),n=t.url.indexOf("?"),a=n<0?"":t.url.slice(n),s=e.content.id?`${lZ(r)}${a}`:t.url;return[{key:`scene:${e.name}`,label:s,type:"scene",url:s}]}catch{return[]}}),[w.scenes,_.manifest]),ep=(0,e9.useMemo)(()=>[...b.map(e=>({key:e.id,label:lZ(e),pageId:e.id,type:"page"})),...ec],[ec,b]),em=(null==(r=ec.find(e=>{var t;return e.key===x&&e.url===(null==(t=_.pageSelection)?void 0:t.routeUrl)}))?void 0:r.key)??"",eh=(0,e9.useMemo)(()=>({...u,manifestUrl:_.manifestUrl,simulatorEndpoint:_.simulator.endpoint}),[u,_.manifestUrl,_.simulator.endpoint]),eg=(0,e9.useMemo)(()=>oB({context:eh,events:_.simulator.traceEvents,manifest:_.manifest,pages:_.pages,widgets:_.widgets}),[eh,_.manifest,_.pages,_.simulator.traceEvents,_.widgets]),ef=eg.appId||_.manifest.appId,ev=eg.appName||_.manifest.name,ey=(0,e9.useMemo)(()=>{var e;return{type:"page",appId:ef,appName:ev,pageId:ed,pagePath:eu,url:(null==(e=_.pageSelection)?void 0:e.routeUrl)??eu,viewport:{key:es.key,label:es.label,width:es.width,height:es.height,density:es.density}}},[ef,ev,es,ed,eu,null==(n=_.pageSelection)?void 0:n.routeUrl]),e_=(0,e9.useMemo)(()=>oW(eg,_.pageSelection?ey:void 0),[ey,eg.pages,eg.widgets,_.pageSelection]),eb=!!(ee&&oF(J,T,ee.previousTarget)&&(null==(a=_.pageSelection)?void 0:a.routeUrl)===ee.command.url),ew=(0,e9.useMemo)(()=>(null==J?void 0:J.sourceTarget)===T?{target:ey,root:J.root,nodeCount:J.nodeCount,selectedUid:J.selectedUid,truncated:J.truncated,updatedAtMs:J.updatedAtMs}:void 0,[ey,T,J]),eS=(0,e9.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:d,...eb?{command_id:null==ee?void 0:ee.command.commandId}:{},context:{launch_dir:eh.launchDir,manifest_url:_.manifestUrl,app_id:ef,app_name:eg.appName||_.manifest.name,mcp_endpoint:eh.mcpEndpoint,mcp_original_endpoint:eg.sources.mcp.original,mcp_proxy_endpoint:eg.sources.mcp.proxy,page_id:ed,page_path:eu,simulator_endpoint:_.simulator.endpoint,simulator_manifest_original_url:eg.sources.manifest.original,simulator_manifest_proxy_url:eg.sources.manifest.proxy,simulator_manifest_url:eh.simulatorManifestUrl,simulator_skill_original_url:eg.sources.skill.original,simulator_skill_proxy_url:eg.sources.skill.proxy,simulator_skill_url:eh.simulatorSkillUrl,web_url:eh.webUrl},render_targets:e_,runtime_snapshot:ew,page_runtime_trace_events:[],runtime_console:{app:{entries:q.appEntries,updated_at_ms:q.updatedAtMs},page:{entries:q.entries,updated_at_ms:q.updatedAtMs}},simulator:{stream_status:_.simulator.streamStatus,trace_events:_.simulator.traceEvents,tool_calls:_.simulator.toolCalls}}),[eg.appId,eg.appName,eg.sources.manifest.original,eg.sources.manifest.proxy,eg.sources.mcp.original,eg.sources.mcp.proxy,eg.sources.skill.original,eg.sources.skill.proxy,eh.launchDir,eh.mcpEndpoint,eh.simulatorManifestUrl,eh.simulatorSkillUrl,eh.webUrl,q,ed,eu,ef,d,eb,null==ee?void 0:ee.command.commandId,e_,_.manifest.name,_.manifestUrl,_.simulator.endpoint,_.simulator.streamStatus,_.simulator.toolCalls,_.simulator.traceEvents,ew]),ex=(0,e9.useMemo)(()=>f?_.simulator.traceEvents:_.simulator.traceEvents.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[f,_.simulator.traceEvents]),eI=(0,e9.useMemo)(()=>lS(ex,{debug:f,messages:_.simulator.messages}),[f,_.simulator.messages,ex]),eE=(0,e9.useMemo)(()=>lw(eS,{debug:f}),[f,eS]),eC=(0,e9.useMemo)(()=>l_(eE),[eE]);(0,e9.useEffect)(()=>{let e=!0;return lJ(null==u?void 0:u.debugScenesEndpoint).then(t=>{if(e)for(let e of(S(t),t.errors))null==h||h(`${e.name}: ${e.message}`,!0)}).catch(t=>{e&&(S({errors:[],scenes:[]}),null==h||h(t.message,!0))}),()=>{e=!1}},[null==u?void 0:u.debugScenesEndpoint,h]);let ek=iy(e=>{var t,r;let n=(null==(t=Z.current)?void 0:t.getCurrentTarget())??(null==(r=Z.current)?void 0:r.getCurrentAppTarget()),a=`[Debug Scene] ${e}`;n?aG(n,{level:"error",message:a,pagePath:eu||void 0}):console.error(a)}),eN=iy(e=>{let t=ep.find(t=>t.key===e);t&&("scene"===t.type?(I(t.key),y.navigateToPage(t.url)):(I(""),y.selectPage(t.pageId)))}),eM=iy(e=>{o8(e,{onClearLogs:G,onMessage:h})}),eR=(0,e9.useMemo)(()=>({debugData:eg,events:eI,logSnapshot:eE,logSnapshotText:eC,sandbox:{available:W,csrRequired:(null==u?void 0:u.sandboxCsrRequired)!==!1,input:{csrPem:(null==u?void 0:u.sandboxCsrPem)??"",phoneNum:(null==u?void 0:u.sandboxPhoneNum)??""},logs:K,businessInfoStatus:H,location:z,sessionStatus:V},showDebugTrace:f,traceSurface:"page",toolCalls:_.simulator.toolCalls,updatedAtMs:Date.now()}),[eg,eI,eE,eC,K,H,z,W,V,null==u?void 0:u.sandboxCsrRequired,f,_.simulator.toolCalls]);l$(v,eS,J),(0,e9.useEffect)(()=>{if((null==l?void 0:l.type)==="render_page"&&Y(l,T))try{I(""),y.navigateToPage(l.url)}catch(e){er(l.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[Y,l,T,er,y]),(0,e9.useEffect)(()=>{ee&&eb&&er(ee.command.commandId,{ok:!0,target:ey,snapshot:lb(eS)})},[ey,eb,ee,er,eS]);let eT=iy((e,t)=>{let r=tV(y,{noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==h||h("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==h||h("当前仍在生成中,暂不重发授权后的消息",!0);return}y.appendSimulatorTraceEvent({category:"card",event:"simulator_granting_resend_query",granting_type:e,no_login:(null==t?void 0:t.noLogin)===!0,removed_message_ids:r.target.messageIds,query_preview:r.target.query.slice(0,80),source:"custom_login_page"}),r.completion.catch(e=>{null==h||h(e.message,!0)})}),eA=iy((e,t)=>{eT(e,t),"login"===e&&(null==p||p("conversation"))}),eP=(0,e9.useMemo)(()=>aU({appId:ef,appIcon:_.manifest.iconSrc,appName:ev,baseAPIRegistry:null==g?void 0:g.apiRegistry,onGrantingCompleted:eA,sendFollowUpMessage:e=>{let{content:t,prompt:r}=e;return y.sendSimulatorQuery(r,{followUpContent:t})},multiMediaBroadcastContainer:E??void 0,runtimeHost:null==g?void 0:g.runtimeHost,scanCodePresenter:F.scanCodePresenter,showSandboxCashier:B.showCashier,uiPresenter:F.presenter,showSimulatorPermission:Q.showPermission,vibrationContainer:M??void 0}),[g,eA,ef,ev,M,E,B.showCashier,F.scanCodePresenter,F.presenter,Q.showPermission,_.manifest.iconSrc,y]);(0,e9.useEffect)(()=>{if(!E)return;let e=new im({container:E,fileSystemNamespace:null==u?void 0:u.fileSystemNamespace,webSdkDebugger:y,onExitApp:()=>null==p?void 0:p("conversation"),onError:e=>{null==h||h(`Page runtime error: ${e.message}`,!0)},apiEnvironment:eP});Z.current=e;let t=e.subscribeTarget(t=>{A(t),L(e.getPageStackSize()),U(null)}),r=e.subscribeAppTarget(e=>{j(e)});return A(e.getCurrentTarget()),j(e.getCurrentAppTarget()),L(e.getPageStackSize()),()=>{t(),r(),e.destroy(),Z.current=null,A(null),j(null),L(0),U(null)}},[null==u?void 0:u.fileSystemNamespace,p,h,eP,E,y]),(0,e9.useEffect)(()=>{let e=Z.current;if(!e||!_.pageSelection){null==e||e.clear();return}try{e.render({device:es})}catch(r){let e=r.message;em?ek(e):null==h||h(e,!0);let t=et.current;t&&er(t.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:r.message}})}},[h,ek,er,E,es,ed,em,_.pageSelection]);let ej=(0,e9.useMemo)(()=>({appTarget:P,controlCommand:l,controlTarget:_.pageSelection?T:null,debugState:eR,frontendUrl:o,onConsoleSnapshotChange:$,onControlResult:m,onDebugAction:eM,onHighlightChange:U,onRuntimeSnapshotChange:X,preserveConsoleOnTargetChange:!0,runtimeFrame:k,target:_.pageSelection?T:null}),[P,o,l,eR,eM,m,T,k,_.pageSelection]);return(0,e9.useEffect)(()=>{null==c||c(ej)},[ej,c]),(0,s.jsxs)("div",{className:"wsd-page-preview-column",children:[(0,s.jsx)(ou,{activeView:i??"page",onActiveViewChange:p,onDeviceChange:el,selectedDeviceKey:ei,children:(0,s.jsx)("button",{"aria-label":"Reload",className:"wsd-icon-button",disabled:!_.pageSelection,onClick:()=>{var e;return null==(e=Z.current)?void 0:e.reload()},title:"Reload",type:"button",children:(0,s.jsx)(on,{"aria-hidden":"true"})})}),(0,s.jsxs)("div",{className:"wsd-page-route-control",children:[(0,s.jsx)("div",{className:"wsd-page-route-navigation",children:(0,s.jsx)("button",{"aria-label":"返回",className:"wsd-page-route-button",disabled:D<2,onClick:()=>{var e;return null==(e=Z.current)?void 0:e.closeCurrentPage()},title:"返回",type:"button",children:(0,s.jsx)(l0,{})})}),(0,s.jsx)("div",{className:"wsd-page-route-select-wrapper",children:(0,s.jsx)(lV.d,{"aria-label":"页面路径",className:"wsd-page-route-select",classNames:{listbox:"wsd-page-path-listbox",popoverContent:"wsd-page-path-popover",selectorIcon:"wsd-page-path-icon",trigger:"wsd-page-path-select",value:"wsd-page-path-value"},isDisabled:0===b.length&&0===ec.length,listboxProps:{itemClasses:{base:"wsd-page-path-option",selectedIcon:"wsd-page-path-selected-icon",title:"wsd-page-path-option-title"}},onChange:e=>eN(e.target.value),placeholder:eu||"No page",popoverProps:{offset:0},renderValue:e=>{var t;return(0,s.jsx)(lY,{value:String((null==(t=e[0])?void 0:t.textValue)??eu)})},selectedKeys:em?[em]:ed?[ed]:[],size:"sm",children:ep.map(e=>(0,s.jsx)(lG.y,{textValue:e.label,children:(0,s.jsx)(lY,{showTooltip:!0,value:e.label})},e.key))})})]}),_.pageSelection?(0,s.jsx)(iw,{highlightRect:O,overlay:(0,s.jsxs)(s.Fragment,{children:[F.overlay,B.cashier?(0,s.jsx)(iS,{cashier:B.cashier,onCancel:B.cancelCashier,onConfirm:B.confirmCashier}):null,Q.permission?(0,s.jsx)(ot,{onAllow:Q.allowPermission,onReject:Q.rejectPermission,permission:Q.permission}):null]}),runtimeFrameRef:N,runtimeFrameScaleBoxRef:R,runtimeScaleMode:en,runtimeShellRef:eo,runtimeStyle:ea,runtimeTargetRef:C}):(0,s.jsx)("div",{className:"wsd-page-empty",children:"No page"})]})}var l2=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:12,fill:"none",viewBox:"0 0 12 12",...e,children:(0,s.jsx)("path",{fill:"#BABABA",d:"M1.162 4.61a.5.5 0 1 1 .707-.706l4.06 4.06a.1.1 0 0 0 .142 0l4.06-4.06a.5.5 0 0 1 .707.707l-4.06 4.06a1.1 1.1 0 0 1-1.556 0z"})}),l3=r(48986),l4=r(80704),l5=r(51290),l6=r(36091);let l8=l5.Lz.theme({"&":{height:"100%",backgroundColor:"#fbfcff",color:"#172033",fontSize:"12px"},"&.cm-focused":{outline:"none"},".cm-scroller":{fontFamily:"'SFMono-Regular', Consolas, monospace",lineHeight:"1.55"},".cm-content":{padding:"8px 0"},".cm-line":{padding:"0 10px 0 8px"},".cm-gutters":{borderRight:"1px solid #dfe5ee",backgroundColor:"#f4f7fb",color:"#8a98ab"},".cm-activeLine":{backgroundColor:"rgba(36, 84, 198, 0.05)"},".cm-activeLineGutter":{backgroundColor:"rgba(36, 84, 198, 0.08)"},".cm-tooltip":{border:"1px solid #c7d0dd",borderRadius:"7px",boxShadow:"0 12px 28px rgba(28, 39, 56, 0.16)"}}),l7=[(0,l3.Pq)(),(0,l4.pJ)(),(0,l4.bu)((0,l3.cp)()),l5.Lz.lineWrapping,l8];function l9(e){let{ariaLabel:t,minHeight:r=96,onChange:n,value:a}=e,i={"--json-editor-min-height":`${r}px`};return(0,s.jsx)("div",{"aria-label":t,className:"json-editor-shell",style:i,children:(0,s.jsx)(l6.Ay,{basicSetup:{autocompletion:!0,bracketMatching:!0,closeBrackets:!0,foldGutter:!0,highlightActiveLine:!0,highlightActiveLineGutter:!0,lineNumbers:!0,searchKeymap:!0},extensions:l7,minHeight:`${r}px`,onChange:n,value:a})})}async function de(e,t,r){try{if(!navigator.clipboard)throw Error("Clipboard API is unavailable");await navigator.clipboard.writeText(t),null==r||r(`${e} copied`)}catch(t){null==r||r(`${e}: ${t.message}`,!0)}}function dt(e){let{actionDisabled:t,actionLabel:r,JsonEditorComponent:n,label:a,minHeight:i=96,onAction:o,onChange:l,onMessage:d,value:u}=e;return(0,s.jsxs)("form",{className:"wsd-debug-inputs",onSubmit:function(e){e.preventDefault(),null==o||o()},children:[(0,s.jsxs)("div",{className:"wsd-debug-editor-block",children:[(0,s.jsxs)("div",{className:"wsd-editor-toolbar",children:[(0,s.jsx)("span",{className:"wsd-section-label",children:a}),(0,s.jsxs)("div",{className:"wsd-editor-actions",children:[(0,s.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:function(){try{l(JSON.stringify(rS("JSON",u),null,2)),null==d||d(`${a} formatted`)}catch(e){null==d||d(e.message,!0)}},type:"button",children:"格式化"}),(0,s.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:()=>{de(a,u,d)},type:"button",children:"复制"})]})]}),n?(0,s.jsx)(n,{ariaLabel:a,minHeight:i,onChange:l,value:u}):(0,s.jsx)("textarea",{"aria-label":a,className:"wsd-json-textarea",onChange:e=>l(e.currentTarget.value),spellCheck:!1,style:{minHeight:i},value:u})]}),r?(0,s.jsx)("div",{className:"wsd-debug-action-bar",children:(0,s.jsx)("button",{className:"wsd-button wsd-button-primary",disabled:t,type:"submit",children:r})}):null]})}function dr(e){return eK(e)?Object.fromEntries(Object.entries(e).flatMap(e=>{let[t,r]=e;return eK(r)?[[t,r]]:[]})):{}}async function dn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/__web_sdk_widget_view_data_templates",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:fetch,r=await t(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!r.ok)throw Error(`加载 Widget viewData 模板失败:HTTP ${r.status} ${r.statusText}`);let n=await r.json();if(!eK(n)||!eK(n.templatesByEntry)&&!eK(n.templatesByWidget))throw Error("Widget viewData 模板接口返回了无效数据");return{templatesByEntry:dr(n.templatesByEntry),templatesByWidget:dr(n.templatesByWidget)}}let da="输入数据(structuredContent)",ds={};function di(e){var t,r,n;let a=lW(e,"card"),[i,o]=(0,e9.useState)("{}"),[l,d]=(0,e9.useState)([]),[u,c]=(0,e9.useState)({templatesByEntry:{},templatesByWidget:{}}),p=(0,e9.useRef)(!1),m=(0,e9.useRef)(a.selectedWidgetId),h=((null==(t=a.state.widgetSelection)?void 0:t.item.entry)??"").replaceAll("\\","/").replace(/^src\//,"").replace(/\.(?:bundle|tsx?|jsx?)$/,""),g=u.templatesByWidget[a.selectedWidgetId]??u.templatesByEntry[h]??ds,f=(0,e9.useMemo)(()=>l.flatMap(e=>{let t=lX(e);return"widget"===t.type&&t.widgetId===a.selectedWidgetId?[t]:[]}),[l,a.selectedWidgetId]);(0,e9.useEffect)(()=>{var t;(null==(t=e.controlCommand)?void 0:t.type)==="render_widget"&&e.controlCommand.widgetId===a.selectedWidgetId&&(p.current=!0,o(JSON.stringify(e.controlCommand.structuredContent,null,2)))},[e.controlCommand,a.selectedWidgetId]),(0,e9.useEffect)(()=>{var t;let r=m.current!==a.selectedWidgetId;m.current=a.selectedWidgetId,((null==(t=e.controlCommand)?void 0:t.type)!=="render_widget"||e.controlCommand.widgetId!==a.selectedWidgetId)&&(r&&(p.current=!1),p.current||o(JSON.stringify(g,null,2)))},[g,e.controlCommand,a.selectedWidgetId]),(0,e9.useEffect)(()=>{var t;let r=!0;return lJ(null==(t=e.debugContext)?void 0:t.debugScenesEndpoint).then(e=>{r&&d(e.scenes)}).catch(e=>{if(r){var t;d([]),null==(t=a.onMessage)||t.call(a,e.message,!0)}}),()=>{r=!1}},[null==(r=e.debugContext)?void 0:r.debugScenesEndpoint,a.onMessage]);let v=iy(async function(){var t,r;let n=arguments.length>0&&void 0!==arguments[0]&&arguments[0];try{let r=await dn(null==(t=e.debugContext)?void 0:t.widgetViewDataTemplatesEndpoint);n&&(p.current=!1),c(r)}catch(e){c({templatesByEntry:{},templatesByWidget:{}}),null==(r=a.onMessage)||r.call(a,e.message,!0)}});(0,e9.useEffect)(()=>{v()},[null==(n=e.debugContext)?void 0:n.widgetViewDataTemplatesEndpoint,v]);let y=iy(e=>{p.current=!0,o(e)}),_=iy(async()=>{let e=await a.reloadResources();return e&&await v(!0),e});function b(){try{let e=rS(da,i);a.renderSelectedWidget({initData:{viewData:e}})}catch(t){var e;null==(e=a.onMessage)||e.call(a,t.message,!0)}}return(0,s.jsx)(oc,{runtime:{...a,reloadResources:_},children:a.state.widgetSelection?(0,s.jsx)(iw,{highlightRect:a.highlightRect,overlay:(0,s.jsxs)("section",{"aria-label":"卡片调试",className:(0,eJ.$)("wsd-widget-card-debug",{"has-rendered-preview":a.hasRenderedPreview}),children:[(0,s.jsx)(iN,{}),(0,s.jsxs)("section",{className:"wsd-widget-card-form",children:[(0,s.jsxs)("label",{className:"wsd-widget-card-template-control",children:[(0,s.jsx)("span",{children:"卡片模板:"}),(0,s.jsx)("span",{className:"wsd-widget-card-template-value",children:a.selectedWidgetId}),(0,s.jsx)(l2,{"aria-hidden":"true"}),(0,s.jsx)("select",{"aria-label":"卡片模板",disabled:0===a.visibleWidgets.length,onChange:e=>a.webSdkDebugger.selectWidget(e.currentTarget.value),value:a.selectedWidgetId,children:a.visibleWidgets.map(e=>(0,s.jsx)("option",{value:e.widgetId,children:e.widgetId},e.widgetId))})]}),f.length>0?(0,s.jsx)("div",{"aria-label":"Debug Scene 预设",className:"wsd-widget-scene-presets",children:f.map(e=>(0,s.jsx)("button",{className:"wsd-widget-scene-preset",onClick:()=>{p.current=!0,o(JSON.stringify(e.initData,null,2))},type:"button",children:e.sceneName},e.sceneName))}):null,(0,s.jsx)(dt,{JsonEditorComponent:l9,label:da,minHeight:200,onAction:b,onChange:y,onMessage:a.onMessage,value:i}),(0,s.jsx)("button",{className:"wsd-button wsd-button-primary wsd-widget-card-render-button",onClick:b,type:"button",children:"渲染卡片"})]}),(0,s.jsxs)("section",{className:"wsd-widget-card-preview-section",children:[(0,s.jsx)("span",{children:"以下是卡片渲染预览"}),(0,s.jsxs)("div",{className:"wsd-widget-card-preview-canvas",children:[(0,s.jsx)("div",{className:(0,eJ.$)({"wsd-widget-card-preview-target":a.hasRenderedPreview}),ref:a.runtimeTargetRef}),a.hasRenderedPreview?null:(0,s.jsx)("span",{className:"wsd-widget-card-preview-empty",children:"未传入内容"}),a.simulatorUI.overlay,a.sandboxCashier.cashier?(0,s.jsx)(iS,{cashier:a.sandboxCashier.cashier,onCancel:a.sandboxCashier.cancelCashier,onConfirm:a.sandboxCashier.confirmCashier}):null,a.simulatorPermissionPrompt.permission?(0,s.jsx)(ot,{onAllow:a.simulatorPermissionPrompt.allowPermission,onReject:a.simulatorPermissionPrompt.rejectPermission,permission:a.simulatorPermissionPrompt.permission}):null]})]})]}),runtimeFrameRef:a.runtimeFrameRef,runtimeFrameScaleBoxRef:a.runtimeFrameScaleBoxRef,runtimeScaleMode:a.runtimeScaleMode,runtimeShellRef:a.setRuntimeShellRef,runtimeStyle:a.runtimeStyle}):(0,s.jsx)("div",{className:"wsd-page-empty",children:"No widget"})})}var dl=r(85624);function dd(e,t){let r=Math.max(0,e.scrollWidth-e.clientWidth),n=Math.max(0,e.scrollHeight-e.clientHeight);return(r>0||n>0)&&(void 0===t.x||0===t.x||r>0)&&(void 0===t.y||0===t.y||n>0)}async function du(e,t,r){let n=e.uid?t.getElement(e.uid):null,a=e.uid?n?{element:n,uid:e.uid}:null:function(e,t,r){let n=t.getInspectorSnapshot().root,a=n?[n]:[],s=null;for(let n=0;n<a.length;n+=1){let i=a[n];a.push(...i.children);let o=t.getElement(i.id);if(!o||!dd(o,e))continue;let l=function(e,t){if(!e.isConnected)return 0;let r=getComputedStyle(e);if("none"===r.display||"hidden"===r.visibility||"collapse"===r.visibility)return 0;let n=e.getBoundingClientRect(),a=t.getBoundingClientRect();return Math.max(0,Math.min(n.right,a.right)-Math.max(n.left,a.left))*Math.max(0,Math.min(n.bottom,a.bottom)-Math.max(n.top,a.top))}(o,r);l>0&&(!s||l>s.area)&&(s={area:l,element:o,uid:i.id})}return s}(e,t,r);if(!a||!dd(a.element,e))return null;let s=Math.max(0,a.element.scrollWidth-a.element.clientWidth),i=Math.max(0,a.element.scrollHeight-a.element.clientHeight);void 0!==e.x&&(a.element.scrollLeft=Math.min(e.x,s)),void 0!==e.y&&(a.element.scrollTop=Math.min(e.y,i)),await new Promise(e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()))});let o=Math.max(0,a.element.scrollWidth-a.element.clientWidth),l=Math.max(0,a.element.scrollHeight-a.element.clientHeight);return{uid:a.uid,x:Math.max(0,Math.min(a.element.scrollLeft,o)),y:Math.max(0,Math.min(a.element.scrollTop,l)),maxX:o,maxY:l,viewportWidth:a.element.clientWidth,viewportHeight:a.element.clientHeight}}let dc="wsd-cdp-adapter",dp={jpeg:"image/jpeg",png:"image/png",webp:"image/webp"};function dm(e,t){return{ok:!1,error:{code:e,message:t}}}async function dh(e,t,r){if(!t||!r)return dm("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");if("scroll_to"===e.type){if(e.uid&&!t.getElement(e.uid))return dm("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let n=await du(e,t,r);return n?{ok:!0,result:n}:dm("SCROLL_FAILED",e.uid?`Element uid ${e.uid} is not scrollable`:"No visible scrollable container was found")}if("get_computed_style"===e.type){let r=t.getComputedStyles(e.uid,e.properties);return r?{ok:!0,result:{uid:e.uid,computedStyle:r}}:dm("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`)}if("get_element_rect"===e.type){let r=t.getElementRect(e.uid);return r?{ok:!0,result:{uid:e.uid,...r}}:dm("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`)}let n=e.uid?t.getElement(e.uid):r;if(!n)return dm("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let a=dp[e.format],s=n.getBoundingClientRect(),i=n.offsetWidth||s.width,o=n.offsetHeight||s.height;try{let t=await (0,dl.TC)(n,{height:o,scale:3,type:a,width:i,...void 0!==e.quality&&"png"!==e.format?{quality:e.quality/100}:{},onCloneEachNode:e=>{if(!(e instanceof HTMLElement)||"raw-text"!==e.localName)return;let t=e.getAttribute("text");null!==t&&(e.textContent=t)}}),r=`data:${a};base64,`,s=t.startsWith(r)?t.slice(r.length):"";if(!s||s.length>8388608)return dm("SCREENSHOT_FAILED",s?"Screenshot exceeds the 8 MiB debugger limit":"Screenshot returned invalid image data");return{ok:!0,result:{data:s,format:e.format,mimeType:a,width:Math.floor(3*i),height:Math.floor(3*o),...e.uid?{uid:e.uid}:{}}}}catch(e){return dm("SCREENSHOT_FAILED",e instanceof Error?e.message:String(e))}}function dg(e){let{controlCommand:t,controlTarget:r,debugState:n,frontendUrl:a,onDebugAction:i,onConsoleSnapshotChange:o,onControlResult:l,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p,getRuntimeFrame:m,runtimeFrame:h,showPanelId:g,showPanelRequestId:f,appTarget:v,consoleTarget:y,target:_}=e,b=(0,e9.useRef)(null),w=(0,e9.useRef)(n),S=(0,e9.useRef)(h??null),x=(0,e9.useRef)(v??null),I=(0,e9.useRef)(_),E=(0,e9.useRef)({consoleTarget:y,getRuntimeFrame:m,onConsoleSnapshotChange:o,onDebugAction:i,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p}),C=(0,e9.useRef)(),k=(0,e9.useRef)(null),N=(0,e9.useRef)(null),M=(0,e9.useRef)(null),R=(0,e9.useRef)(null),T=(0,e9.useMemo)(()=>(function(e){let t,r=null==e?void 0:e.trim();if(!r||"u"<typeof window)return null;try{t=new URL(r,window.location.href)}catch{return null}if("http:"!==t.protocol&&"https:"!==t.protocol)return null;t.origin===window.location.origin&&window.localStorage.setItem("navigator-just-my-code","true"),t.searchParams.set("wsdCdpTransport","postmessage");let n=t.searchParams.get("panel");return n&&"wsd-mcp"!==n&&"wsd-view"!==n||t.searchParams.set("panel","wsd-overview"),{origin:t.origin,url:t.toString()}})(a),[a]),A=(null==T?void 0:T.url)??null;E.current={consoleTarget:y,getRuntimeFrame:m,onConsoleSnapshotChange:o,onDebugAction:i,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p};let P=(0,e9.useCallback)(e=>{var t,r;T&&(null==(r=b.current)||null==(t=r.contentWindow)||t.postMessage({source:dc,type:"wsd-show-panel",panelId:e},T.origin))},[T]),j=iy(()=>{var e,t;let r=w.current;r&&T&&(null==(t=b.current)||null==(e=t.contentWindow)||e.postMessage({source:dc,type:"wsd-debug-state",state:r},T.origin))});return((0,e9.useEffect)(()=>{S.current=h??null},[h]),(0,e9.useEffect)(()=>{var e;x.current=v??null,null==(e=N.current)||e.call(N)},[v]),(0,e9.useEffect)(()=>{w.current=n,j();let e=[100,500,1e3].map(e=>window.setTimeout(j,e));return()=>e.forEach(e=>window.clearTimeout(e))},[n,j,A]),(0,e9.useEffect)(()=>{if(!g||!f)return;P(g);let e=[100,500].map(e=>window.setTimeout(()=>P(g),e));return()=>e.forEach(e=>window.clearTimeout(e))},[P,g,f]),(0,e9.useEffect)(()=>{E.current.onHighlightChange(null);let e=null==T?void 0:T.origin;R.current??=document.createElement("div");let t=new is(I.current??R.current,{consoleTarget:E.current.consoleTarget,getAppTarget:()=>x.current,getRuntimeFrame:()=>E.current.getRuntimeFrame?E.current.getRuntimeFrame():S.current,onHighlightChange:e=>E.current.onHighlightChange(e),get preserveConsoleOnTargetChange(){return E.current.preserveConsoleOnTargetChange},resolveTargetAtPoint:(e,t)=>{var r,n;return(null==(r=(n=E.current).resolveTargetAtPoint)?void 0:r.call(n,e,t))??null}});k.current=t;let r=0,n=e=>{var n;let a=null==(n=t.dispatch({id:--r,method:e}).result)?void 0:n.entries;return Array.isArray(a)?a:[]},a=()=>{var e,t;null==(e=(t=E.current).onConsoleSnapshotChange)||e.call(t,{appEntries:n("WSD.getAppConsoleEntries"),entries:n("WSD.getConsoleEntries"),updatedAtMs:Date.now()})},s=()=>{var e,r,n,a,s,i;let o,l,d,u,c=I.current;if(!c){null==(n=(a=E.current).onRuntimeSnapshotChange)||n.call(a,null);return}let p=t.getInspectorSnapshot();null==(e=(r=E.current).onRuntimeSnapshotChange)||e.call(r,(s=p.root,i=p.selectedUid,o=0,l=!1,d=()=>{l=!0},u=e=>{if(o>=5e3)return l=!0,null;o+=1;let t=e.children.map(u).filter(e=>null!==e);return{uid:e.id,type:e.type,name:"text"===e.type?"#text":sJ(e),attributes:"element"===e.type?sG(e).map(e=>{var t;return{name:e.name,value:(t=e.value,t.length<=500?t:(d(),`${t.slice(0,499)}…`))}}):[],children:t,...e.accessibility?{accessibility:e.accessibility}:{},...e.textContent?{text:e.textContent}:{}}},{root:s?u(s):null,...i?{selectedUid:i}:{},nodeCount:o,truncated:l,...c?{sourceTarget:c}:{},updatedAtMs:Date.now()}))},i=t=>{var r,n;e&&(null==(n=b.current)||null==(r=n.contentWindow)||r.postMessage({source:dc,...t},e))},o=t=>{var r,n;e&&(null==(n=b.current)||null==(r=n.contentWindow)||r.postMessage({source:dc,type:"cdp-raw-message",message:JSON.stringify(t)},e))};N.current=a,M.current=s;let l=t.subscribe(e=>{i(e),o(e),("WSD.consoleUpdated"===e.method||"WSD.appConsoleUpdated"===e.method)&&a(),("DOM.documentUpdated"===e.method||"DOM.inlineStyleInvalidated"===e.method||"Overlay.inspectNodeRequested"===e.method)&&s()}),d={method:"DOM.documentUpdated"};i(d),o(d),a(),s();let u=r=>{var n,a,s,l,d,u,c,p,m,h,g,f,v;if(!e||r.source!==(null==(n=b.current)?void 0:n.contentWindow)||r.origin!==e)return;let y=r.data;if((null==y?void 0:y.source)==="wsd-chrome-devtools-frontend"){if("ready"===y.type||"wsd-debug-ready"===y.type)return void j();if("wsd-debug-action"===y.type){let e=y.action;if((null==e?void 0:e.kind)==="clear-sandbox-bridge-logs"||(null==e?void 0:e.kind)==="clear-trace-filter"){null==(a=(s=E.current).onDebugAction)||a.call(s,e);return}if((null==e?void 0:e.kind)==="locate-sandbox-location"){null==(l=(d=E.current).onDebugAction)||l.call(d,e);return}if((null==e?void 0:e.kind)==="update-sandbox-location"&&"number"==typeof e.latitude&&Number.isFinite(e.latitude)&&"number"==typeof e.longitude&&Number.isFinite(e.longitude)){null==(u=(c=E.current).onDebugAction)||u.call(c,e);return}if((null==e?void 0:e.kind)==="update-sandbox-business-info"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(p=(m=E.current).onDebugAction)||p.call(m,e);return}if((null==e?void 0:e.kind)==="recreate-sandbox-session"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(h=(g=E.current).onDebugAction)||h.call(g,e);return}e&&("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&"string"==typeof e.toolCallId&&(null==(f=(v=E.current).onDebugAction)||f.call(v,e));return}if("wsd-preact-devtools-message"===y.type)return void t.sendPreactDevtoolsMessage(y.payload);if("wsd-preact-highlight"===y.type){let e=y.uniqueId;t.highlightLynxNode("number"==typeof e?e:null);return}if("cdp-raw-message"===y.type&&"string"==typeof y.message){let e;try{e=JSON.parse(y.message)}catch{return}o(t.dispatch(e));return}"cdp-request"===y.type&&y.id&&i(t.dispatch({id:y.id,method:y.method??"",params:y.params,sessionId:y.sessionId}))}},c=e=>{let t=e.detail;if((null==t?void 0:t.type)==="PreactDevtools"&&"string"==typeof t.data)try{i({type:"wsd-preact-devtools-message",payload:JSON.parse(t.data)})}catch{}};return e&&(window.addEventListener("message",u),document.addEventListener("devtoolMessage",c)),()=>{window.removeEventListener("message",u),document.removeEventListener("devtoolMessage",c),l(),N.current===a&&(N.current=null),M.current===s&&(M.current=null),k.current===t&&(k.current=null),t.destroy(),E.current.onHighlightChange(null)}},[j,T]),(0,e9.useEffect)(()=>{var e,t,r,n;I.current=_,R.current??=document.createElement("div"),null==(e=k.current)||e.setConsoleTarget(y),null==(t=k.current)||t.setTarget(_??R.current),null==(r=N.current)||r.call(N),null==(n=M.current)||n.call(M)},[y,_]),(0,e9.useEffect)(()=>{t&&"render_page"!==t.type&&"render_widget"!==t.type&&"set_viewport"!==t.type&&"submit_chat_query"!==t.type&&C.current!==t.commandId&&(C.current=t.commandId,(async()=>{let e;try{e=await dh(t,k.current,void 0===r?I.current:r)}catch(r){e=dm("take_screenshot"===t.type?"SCREENSHOT_FAILED":"scroll_to"===t.type?"SCROLL_FAILED":"INSPECTION_FAILED",r instanceof Error?r.message:String(r))}null==l||l(t.commandId,e)})())},[t,r,l]),A)?(0,s.jsx)("aside",{className:"wsd-chrome-devtools",children:(0,s.jsx)("iframe",{allow:"clipboard-write",className:"wsd-chrome-devtools-frame",onLoad:()=>{j(),g&&P(g)},ref:b,sandbox:"allow-scripts allow-same-origin allow-forms",src:A,title:"Chrome DevTools"})}):(0,s.jsx)("aside",{className:"wsd-chrome-devtools",children:(0,s.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is not configured"})})}function df(e,t,r){return Math.min(Math.max(e,t),r)}function dv(e,t,r,n){if(!t)return df(e,r,n);let a=t.getBoundingClientRect().width;if(!a)return df(e,r,n);let s=Math.min(n,Math.max(r,a-8-340));return df(e,r,s)}function dy(e){var t,r;let{activeView:n="conversation",className:a,onActiveViewChange:i,...o}=e,[l,d]=(0,e9.useState)({onHighlightChange:()=>void 0,target:null}),u=iy(e=>{d(e)}),{isResizing:c,panelStyle:p,separatorProps:m}=function(){let{defaultWidth:e=520,minWidth:t=420,maxWidth:r=640}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},[n,a]=(0,e9.useState)(e),[s,i]=(0,e9.useState)(!1),o=(0,e9.useRef)(null),l=(0,e9.useMemo)(()=>({"--wsd-preview-column-width":`${n}px`}),[n]),d=iy((e,n)=>{if(!n)return;let s=n.getBoundingClientRect();s.width&&a(dv(e-s.left,n,t,r))});(0,e9.useEffect)(()=>()=>{var e;null==(e=o.current)||e.call(o)},[]);let u=iy(e=>{var t,r;if(0!==e.button)return;let n=e.currentTarget,a=n.parentElement;if(!a)return;e.preventDefault(),null==(t=o.current)||t.call(o),null==(r=n.setPointerCapture)||r.call(n,e.pointerId),d(e.clientX,a),i(!0);let s=document.body.style.cursor,l=document.body.style.userSelect;document.body.style.cursor="col-resize",document.body.style.userSelect="none";let u=e=>{d(e.clientX,a)},c=()=>{o.current===c&&(o.current=null,window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),document.body.style.cursor=s,document.body.style.userSelect=l,i(!1))};o.current=c,window.addEventListener("pointermove",u),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c)}),c=iy(e=>{let n=e.currentTarget.parentElement;if("ArrowLeft"===e.key){e.preventDefault(),a(e=>dv(e-24,n,t,r));return}if("ArrowRight"===e.key){e.preventDefault(),a(e=>dv(e+24,n,t,r));return}if("Home"===e.key){e.preventDefault(),a(dv(t,n,t,r));return}"End"===e.key&&(e.preventDefault(),a(dv(r,n,t,r)))});return{isResizing:s,panelStyle:l,separatorProps:{"aria-label":"Resize preview and DevTools","aria-orientation":"vertical","aria-valuemax":r,"aria-valuemin":t,"aria-valuenow":Math.round(n),onKeyDown:c,onPointerDown:u,role:"separator",tabIndex:0}}}({defaultWidth:340,maxWidth:560,minWidth:300}),h={...o,onChromeDevToolsPanelChange:u},g="page"===n?(0,s.jsx)(l1,{...h,activeView:n,onActiveViewChange:i}):"card"===n?(0,s.jsx)(di,{...h,onActiveViewChange:i}):(0,s.jsx)(lH,{...h,onActiveViewChange:i});return(0,s.jsxs)("section",{className:(0,eJ.$)("page"===n?"wsd-page-panel":"wsd-widget-panel",c&&"is-resizing",a),style:p,children:[(0,s.jsx)(iq,{enabled:!!((null==(t=o.debugContext)?void 0:t.sandboxResourceEventsEndpoint)&&!1!==o.debugContext.sandboxSessionAvailable),eventsEndpoint:null==(r=o.debugContext)?void 0:r.sandboxResourceEventsEndpoint,onMessage:o.onMessage,children:g}),(0,s.jsx)("div",{className:"wsd-runtime-splitter",...m}),(0,s.jsx)(dg,{...l})]})}var d_=r(33680);function db(e,t){null==e||e({category:"string"==typeof t.event&&(t.event.startsWith("simulator_manifest_")||t.event.startsWith("simulator_skill_")||t.event.startsWith("simulator_resources_"))?"resource":"mcp",source:"local_mcp",...t})}function dw(e){return eV(e,{allowRootRelative:!0,baseUrl:window.location.href})}function dS(e){let t=function(e){let t={};for(let r of["content-type","content-length","x-tt-logid"]){let n=e.headers.get(r);n&&(t[r]=n)}return t}(e);return{status:e.status,status_text:e.statusText,...Object.keys(t).length>0?{response_headers:t}:{}}}function dx(e,t,r){db(e,{event:`simulator_${t}_fetch_started`,phase:"request",url:r})}function dI(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};db(e,{event:`simulator_${t}_fetch_succeeded`,phase:"response",url:r,...dS(n),...a})}function dE(e,t,r,n,a){db(e,{event:`simulator_${t}_fetch_failed`,phase:"error",url:r,...a?dS(a):{},error:n instanceof Error?n.message:String(n)})}function dC(e,t,r){return Error(`Simulator ${e} failed: ${r.status} ${r.statusText} (${t})`)}let dk="web-sdk-debugger-demo",dN="mock_local_mcp",dM="mock_lookup",dR=["template-transport-card","template-price-action-card","template-ticket-order-card","weather-card","flight-card","api-demo-card","summary-card","configured-widget-id"],dT=[{server_id:dN,name:"Mock Local MCP",description:"Web SDK Debugger 本地模拟 MCP server",tools:[{name:dM,description:"返回用于本地调试的智能服务结构化结果",input_schema_json:JSON.stringify({type:"object",properties:{keyword:{type:"string"}},required:["keyword"]})}]}];function dA(e,t){return`id: evt_mock_${t.toString().padStart(4,"0")}
|
|
23
|
-
event: ${e.event}
|
|
24
|
-
data: ${JSON.stringify(e)}
|
|
25
|
-
|
|
26
|
-
`}function dP(e,t){return t.find(t=>null==e?void 0:e.widgets.some(e=>e.widgetId===t))}function dj(e,t,r,n){var a;return{event:t,request_id:n.requestId,reply_message_id:n.replyMessageId,trace:{trace_id:(null==(a=e.trace)?void 0:a.trace_id)||`trace_mock_${e.idempotency_key??n.requestId}`,component:"mock_simulator",stage:t,sampled:!0},...r}}let dD=async e=>{var t;let r=`找到和 ${(null==(t=e.arguments)?void 0:t.keyword)||"调试数据"} 相关的模拟结果`,n={content:[{type:"text",text:r}],structuredContent:{entities:[{entity_type:"debug_item",entity_id:"debug-item-1",name:"调试示例数据"}]},isError:!1},a=JSON.stringify(n);return{status:"succeeded",result:n.structuredContent,raw_result_text:r,raw_mcp_result_json:a,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{mock:!0}}},dL=tw(ti),dO=aU({requestHandler:async e=>{var t,r;let n=await fetch("/__web_sdk_request_proxy__",{body:JSON.stringify((r=e.params).data instanceof ArrayBuffer?{...r,data:te(r.data),dataEncoding:"base64"}:r),headers:{"content-type":"application/json"},method:"POST"}),a=(null==(t=n.headers.get("content-type"))?void 0:t.toLowerCase())??"",s=await n.text();if(!a.includes("application/json"))throw Error(`Request proxy returned a non-JSON response. Make sure the debugger is started with the local request proxy. Response starts with: ${s.slice(0,120)}`);let i=s?JSON.parse(s):{};if(!n.ok)throw Error((null==i?void 0:i.message)||`Request proxy failed with status ${n.status}`);return(null==i?void 0:i.dataEncoding)==="base64"&&"string"==typeof i.data?w(e,{statusCode:i.statusCode,header:i.header,data:function(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r.buffer}(i.data)}):w(e,i)}});function dU(e,t){if(e.has(t))return!1;if(e.add(t),e.size>100){let t=e.values().next().value;t&&e.delete(t)}return!0}function dq(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return new URL(window.location.href).searchParams.get(e)||r||t}async function d$(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fetch;try{var t;let r=await e("/__web_sdk_debug_context",{cache:"no-store",headers:{Accept:"application/json"}});if(!r.ok)return{};return!(t=await r.json())||"object"!=typeof t||Array.isArray(t)?{}:t}catch{return{}}}async function dB(e,t){let r=t.skill,n=t.mcpServers,a=[];if("function"==typeof r&&a.push(Promise.resolve(r()).catch(()=>void 0)),"function"==typeof n){let t=e.getState();a.push(Promise.resolve(n({appKey:t.manifest.appId,appName:t.manifest.name,manifest:t.manifest.raw})).catch(()=>void 0))}await Promise.all(a)}function dF(){return(0,s.jsx)("main",{className:"chrome-devtools-unavailable-page",children:(0,s.jsx)("section",{className:"wsd-chrome-devtools",children:(0,s.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is unavailable"})})})}function dW(){let e=(0,e9.useMemo)(()=>new URL(window.location.href).searchParams.get("manifest")||ts,[]),t=(0,e9.useMemo)(()=>dq("mcp","/__mcp_proxy",void 0),[]),r=(0,e9.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("mcpOriginal")||e.searchParams.get("mcpEndpoint")||""},[]),n=(0,e9.useMemo)(()=>dq("simulatorManifest","/__simulator_manifest/manifest.yaml",void 0),[]),a=(0,e9.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorManifestOriginal")||"",[]),i=(0,e9.useMemo)(()=>dq("simulatorSkill","/__simulator_skill/skill.md",void 0),[]),o=(0,e9.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorSkillOriginal")||"",[]),l=(0,e9.useMemo)(()=>tw(new URL(window.location.href).searchParams.get("simulator")||dL),[]),d=(0,e9.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("launchDir")||e.searchParams.get("projectPath")||e.searchParams.get("cwd")||""},[]),u=(0,e9.useMemo)(()=>`${window.location.origin}${window.location.pathname}`,[]),c=(0,e9.useMemo)(()=>{let e;return null!==(e=new URL(window.location.href).searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase()},[]),p=(0,e9.useMemo)(()=>"1"===new URL(window.location.href).searchParams.get("simulatorMock")||"true"===String((void 0)??"").toLowerCase(),[]),[m,h]=(0,e9.useState)({}),g=(0,e9.useMemo)(()=>crypto.randomUUID(),[]),[f,v]=(0,e9.useState)(),y=(0,e9.useRef)(new Set),_=(0,e9.useRef)(null),b=(0,e9.useMemo)(()=>(function(e){var t,r,n,a,s;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o={mcpEndpoint:dw((t={mcpEndpoint:e,simulatorManifestUrl:i.simulatorManifestUrl,simulatorSkillUrl:i.simulatorSkillUrl}).mcpEndpoint),simulatorManifestUrl:dw(t.simulatorManifestUrl),simulatorSkillUrl:dw(t.simulatorSkillUrl)};return{...o.simulatorManifestUrl?{simulatorManifest:(r=o.simulatorManifestUrl,n=i.onTraceEvent,async()=>{let e;dx(n,"manifest",r);try{if(!(e=await fetch(r,{cache:"no-store",headers:{Accept:"application/yaml, text/yaml, text/x-yaml, application/json, text/plain"}})).ok)throw dC("manifest",r,e);let t=await e.text(),a=function(e){let t=(0,d_.qg)(e);if(!eK(t))throw Error("Simulator manifest must be a YAML object");return t}(t);return dI(n,"manifest",r,e,{bytes:t.length}),{...a,raw_manifest_yaml:t}}catch(t){throw dE(n,"manifest",r,t,e),console.warn("[web-sdk-debugger] Failed to load simulator manifest supplement",t),t}})}:{},...o.simulatorSkillUrl?{skill:(a=o.simulatorSkillUrl,s=i.onTraceEvent,async()=>{let e;dx(s,"skill",a);try{var t;if(!(e=await fetch(a,{cache:"no-store",headers:{Accept:"text/markdown, text/plain"}})).ok)throw dC("skill",a,e);let r=(await e.text()).trim();if(((null==(t=e.headers.get("content-type"))?void 0:t.toLowerCase())??"").includes("text/html")||/^<!doctype html\b|^<html[\s>]/i.test(r.trimStart()))throw Error(`Simulator skill returned HTML instead of markdown (${a})`);return dI(s,"skill",a,e,{bytes:r.length}),r}catch(t){throw dE(s,"skill",a,t,e),console.warn("[web-sdk-debugger] Failed to load simulator skill",t),t}})}:{},...o.mcpEndpoint?function(e){let t=eV(e.endpoint);if(!t)return{};let r=function(e,t){if(null==t?void 0:t.trim())return t.trim();let r=new URL(e);return`${r.hostname}_${r.port||r.protocol.replace(":","")}${r.pathname}`.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"local_mcp"}(t,e.serverId);return{mcpServers:async n=>{let a;try{aB(e.onTraceEvent,{event:"local_mcp_tools_load_started",app_key:n.appKey,mcp_endpoint:t,server_id:r},n),a=await aW(t,e);let s=await a.client.listTools(),i=a.client.getServerVersion(),o={server_id:r,name:(null==i?void 0:i.name)||r,description:a.client.getInstructions()||"",tools:s.tools.map(aF).filter(e=>e.name)};return aB(e.onTraceEvent,{event:"local_mcp_tools_loaded",app_key:n.appKey,mcp_endpoint:t,server_id:o.server_id,server_version:i,tools:o.tools.map(e=>e.name)},n),[o]}catch(a){return aB(e.onTraceEvent,{event:"local_mcp_tools_load_failed",app_key:n.appKey,mcp_endpoint:t,server_id:r,error:tm(a),request_will_continue:!0,tool_count:0,tools:[]},n),console.warn("[web-sdk-debugger] Failed to load MCP tools",a),[]}finally{a&&await aH(a)}},toolExecutor:async r=>{var n,a,s,i;let o,l=r.arguments??tu(r.argumentsJson)??{},d=r.argumentsJson||tp(l),u=Date.now();try{let c,p,m,h,g,f;if(aB(e.onTraceEvent,{event:"local_mcp_call_started",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments:l,arguments_json:d,mcp_endpoint:t}),o=await aW(t,{...e,headers:function(e,t){if(!e&&!t)return;let r=new Headers(e);for(let[e,n]of Object.entries(t??{}))r.set(e,n);return r}(e.headers,r.headers)}),null==(n=r.signal)?void 0:n.aborted)throw a="MCP tool call aborted","u">typeof DOMException?new DOMException(a,"AbortError"):Object.assign(Error(a),{name:"AbortError"});let v=(s=await o.client.callTool({name:r.toolName,arguments:l,_meta:{request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments_json:d}},void 0,r.signal?{signal:r.signal}:void 0),m=(c=(p=eK(s)?s:{}).structuredContent,eK(c)?c:{value:c??{}}),h=tp(p),g=(i=p,"string"==typeof i.content?i.content:Array.isArray(i.content)&&i.content.filter(eK).map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n")||void 0),{status:(f=!0===p.isError)?"failed":"succeeded",result:m,...f?{error:{code:"LOCAL_MCP_BUSINESS_ERROR",message:"string"==typeof m.message?m.message:g||h,retryable:!1,stage:"tool_execute",details:m}}:{},raw_result_text:h,raw_mcp_result_json:h,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:"local_mcp",protocol:"streamable_http"}}),y=tu(v.raw_mcp_result_json);return aB(e.onTraceEvent,{event:"local_mcp_call_succeeded",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,status:v.status,result:v.result,structured_result_json:tp(v.result),raw_result_text:v.raw_result_text,raw_mcp_result_json:v.raw_mcp_result_json,...void 0===y?{}:{raw_mcp_result:y},elapsed_ms:Date.now()-u,mcp_endpoint:t}),v}catch(a){if(t4(a))throw a;let n=tm(a);return aB(e.onTraceEvent,{event:"local_mcp_call_failed",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,error:n,elapsed_ms:Date.now()-u,mcp_endpoint:t}),{status:"failed",result:{error:n},error:{code:"LOCAL_MCP_CALL_FAILED",message:n,retryable:!0,stage:"tool_execute"},raw_result_text:n}}finally{o&&await aH(o)}}}}({endpoint:o.mcpEndpoint,onTraceEvent:i.onTraceEvent}):{}}})(t,{onTraceEvent:e=>{var t;return null==(t=_.current)?void 0:t.appendSimulatorTraceEvent(e)},simulatorManifestUrl:n,simulatorSkillUrl:i}),[t,n,i]),w=(0,e9.useMemo)(()=>{let t=p?{appKey:dk,appName:"调试示例智能服务",mcpServers:dT,simulatorFetch:function(e){let{getDebuggerState:t}=e;return async(e,r)=>{var n,a,s,i,o,l,d,u;let c,p,m,h,g,f,v,y,_=String(e);if(_.endsWith("/simulator/tool/report")){let e="string"==typeof(null==r?void 0:r.body)?JSON.parse(r.body):{};return new Response(JSON.stringify({code:0,message:"OK",request_id:e.request_id,tool_call_id:e.tool_call_id,trace:e.trace}),{headers:{"Content-Type":"application/json"},status:200,statusText:"OK"})}return _.endsWith("/simulator/chat")?(y=(n="string"!=typeof(null==r?void 0:r.body)?{}:JSON.parse(r.body),i=t(),p=((c=new URL(window.location.href).searchParams.get("simulatorMockWidget"))?dP(i,[c]):void 0)||dP(i,dR)||(null==i||null==(o=i.widgetSelection)?void 0:o.item.widgetId)||(null==(l=i)||null==(d=l.widgets.find(e=>{var t;return null==(t=e.web)?void 0:t.entry}))?void 0:d.widgetId)||(null==l||null==(u=l.widgets[0])?void 0:u.widgetId)||"weather-card",m=Date.now().toString(36),h={requestId:`req_mock_server_${m}`,replyMessageId:`msg_mock_reply_${m}`},g=(null==(a=n.message)?void 0:a.content)||"模拟请求",f=`call_mock_${m}`,v={applet_id:n.app_id||dk,widget_id:p,entity_id:"mock-entity-1",viewData:{source:"web-sdk-debugger-mock",keyword:g,widgetId:p},extra:{"doubao/outputTemplate":"mock.output.template"}},[dj(n,"ack",{ack:{request_id:h.requestId,message_id:h.replyMessageId,local_message_id:null==(s=n.message)?void 0:s.local_message_id}},h),dj(n,"tool_call",{tool_call:{tool_call_id:f,tool_name:dM,server_id:dN,app_key:n.app_id||dk,arguments_json:JSON.stringify({keyword:g}),status:"PENDING",timeout_ms:2e3}},h),dj(n,"tool_status",{tool_status:{tool_call_id:f,status:"RUNNING",progress:.6,message:"Mock tool running"}},h),dj(n,"text_delta",{text_delta:{block_id:"block_mock_text",op:"append",delta:`Mock 已收到:${g}`}},h),dj(n,"card_delta",{card_delta:{block_id:"block_mock_card",op:"append",card_id:`card_mock_${m}`,source_tool_call_id:f,source_entity_ids:["mock-entity-1"],is_final:!0,card:{card_id:`card_mock_${m}`,card_type:"mock_widget_card",title:"Mock 智能服务卡片",fallback_text:`使用 ${p} 渲染`,props_json:JSON.stringify(v)}}},h),dj(n,"debug",{debug_event:{category:"mock",title:"Mock Simulator",summary:"本地 mock SSE 已生成 text/card/tool 事件",data:{widget_id:p},redaction_level:"none"}},h),dj(n,"answer_finish",{answer_finish:{status:"completed",finish_reason:"stop",usage:{output_tokens:12}}},h),dj(n,"reply_finish",{reply_finish:{status:"completed",finish_reason:"stop",event_count:7}},h)]).map(dA).join(""),new Response(new ReadableStream({start(e){e.enqueue(new TextEncoder().encode(y)),e.close()}}),{headers:{"Content-Type":"text/event-stream"},status:200,statusText:"OK"})):new Response(JSON.stringify({ok:!1,error:"Unknown mock simulator endpoint"}),{status:404,statusText:"Not Found"})}}({getDebuggerState:()=>{var e;return(null==(e=_.current)?void 0:e.getState())??null}}),toolExecutor:dD}:{},r=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new rh(e)}({manifestUrl:e,simulatorEndpoint:l,...b,...t});return _.current=r,r},[e,l,b,p]),[S,x]=(0,e9.useState)(()=>{let e,t,r;return t=(e=new URL(window.location.href)).searchParams.get("view"),r=e.searchParams.get("debugMode")||e.searchParams.get("mode"),"conversation"===t||"card"===t||"page"===t?t:"conversation"===r||"card"===r||"page"===r?r:"conversation"}),I=iy((e,t)=>{dU(y.current,e)&&ta({clientId:g,commandId:e,...t},tt).catch(e=>console.error(e)).finally(()=>{v(t=>(null==t?void 0:t.commandId)===e?void 0:t)})}),E=iy(e=>{if("cancel_chat_query"===e.type){iC(w,e.commandId),I(e.commandId,{ok:!1,error:{code:"CHAT_TIMEOUT",message:"Chat query was cancelled after the debugger control timeout"}});return}v(e),("render_page"===e.type||"render_widget"===e.type||"submit_chat_query"===e.type)&&x("render_page"===e.type?"page":"render_widget"===e.type?"card":"conversation")}),C=iy(e=>{try{var t;null==(t=_.current)||t.navigateToPage(e.url)}catch{}x("page")});(0,e9.useEffect)(()=>(function(e){let{clientId:t,endpoint:r="/__wsd_control_events",onCommand:n,onDisconnect:a}=e;if("u"<typeof EventSource)return()=>void 0;let s=new URL(r,window.location.href);s.searchParams.set("clientId",t);let i=new EventSource(s.toString());return i.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}let r=function(e){if(!eK(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&&eK(e.structuredContent))return{commandId:e.commandId,type:e.type,widgetId:e.widgetId,structuredContent:e.structuredContent};if("set_viewport"===e.type&&tr(e.width)&&tr(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("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,...e.properties?{properties:e.properties}:{}}:null;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,..."string"==typeof e.uid?{uid:e.uid}:{},..."number"==typeof r?{quality:r}:{}}}return"scroll_to"===e.type?(void 0===e.uid||"string"==typeof e.uid&&e.uid.trim())&&(void 0===e.x||tn(e.x))&&(void 0===e.y||tn(e.y))?{commandId:e.commandId,type:e.type,..."string"==typeof e.uid?{uid:e.uid}:{},..."number"==typeof e.x?{x:e.x}:{},..."number"==typeof e.y?{y:e.y}:{}}:null:null}(t);r&&n(r)},i.onerror=()=>null==a?void 0:a(),()=>i.close()})({clientId:g,onCommand:E,onDisconnect:()=>{let e=iC(w);e&&(dU(y.current,e),v(t=>(null==t?void 0:t.commandId)===e?void 0:t))}}),[g,E,w]),(0,e9.useEffect)(()=>{let t=!1;return w.loadManifest(e).then(()=>{if(!t){let t;return t=new URL(window.location.href),e===ts?t.searchParams.delete("manifest"):t.searchParams.set("manifest",e),window.history.replaceState(null,"",t),dB(w,b)}}).catch(()=>{}),()=>{t=!0,w.destroy(),_.current===w&&(_.current=null)}},[e,b,w]),(0,e9.useEffect)(()=>{let e=!1;return d$().then(t=>{e||h(t)}),()=>{e=!0}},[]);let k=(0,e9.useMemo)(()=>({launchDir:d,mcpEndpoint:t,mcpOriginalEndpoint:r,mcpProxyEndpoint:t,simulatorManifestOriginalUrl:a,simulatorManifestProxyUrl:n,simulatorManifestUrl:n,simulatorSkillOriginalUrl:o,simulatorSkillProxyUrl:i,simulatorSkillUrl:i,webUrl:u,...m}),[d,t,r,a,n,o,i,u,m]);return(0,s.jsx)(e7.M,{children:(0,s.jsx)("section",{className:"workspace",children:(0,s.jsx)("section",{className:"debug-workspace",children:(0,s.jsx)("section",{className:"debug-mode-panel",children:(0,s.jsx)(dy,{activeView:S,apiEnvironment:dO,chromeDevToolsFrontendUrl:"/chrome-devtools/inspector.html",controlCommand:f,controlClientId:g,debugContext:k,onActiveViewChange:x,onControlResult:I,onNavigateToPage:C,showDebugTrace:c,traceSnapshotEndpoint:"/__agent_trace",webSdkDebugger:w})})})})})}eN=e=>({url:`/__web_view_proxy__?url=${encodeURIComponent(e)}`});let dH=document.querySelector("#app");if(!dH)throw Error("Cannot find #app");(0,e8.H)(dH).render((0,s.jsx)(function(){return window.location.pathname.startsWith("/chrome-devtools/")?(0,s.jsx)(dF,{}):(0,s.jsx)(dW,{})},{}))}},m={};function h(e){var t=m[e];if(void 0!==t)return t.exports;var r=m[e]={id:e,exports:{}};return p[e].call(r.exports,r,r.exports,h),r.exports}h.m=p,h.c=m,t=(e="function"==typeof Symbol)?Symbol("rspack queues"):"__rspack_queues",r=h.aE=e?Symbol("rspack exports"):"__webpack_exports__",n=e?Symbol("rspack error"):"__rspack_error",a=e?Symbol("rspack done"):"__rspack_done",s=h.zS=e?Symbol("rspack defer"):"__rspack_defer",h.zT=e=>{if(e.some(e=>{var t=m[e];return!t||!1===t[a]}))return{then:(t,r)=>Promise.all(e.map(h)).then(t,r)}},i=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},h.a=(e,o,l)=>{l&&((d=[]).d=-1);var d,u,c,p,m=new Set,g=e.exports,f=new Promise((e,t)=>{p=t,c=e});f[r]=g,f[t]=e=>{d&&e(d),m.forEach(e),f.catch(()=>{})},e.exports=f,o(e=>{u=e.map(e=>{if(null!==e&&"object"==typeof e){if(!e[t]&&e[s]){var a=h.zT(e[s]);if(!a)return e;var o=e;e={then(e,t){a.then(()=>e(o),t)}}}if(e[t])return e;if(e.then){var l=[];l.d=0,e.then(e=>{d[r]=e,i(l)},e=>{d[n]=e,i(l)});var d={};return d[s]=!1,d[t]=e=>e(l),d}}var u={};return u[t]=()=>{},u[r]=e,u});var a,o=()=>u.map(e=>{if(e[s])return e;if(e[n])throw e[n];return e[r]}),l=new Promise(e=>{(a=()=>e(o)).r=0;var r=e=>e!==d&&!m.has(e)&&(m.add(e),e&&!e.d&&(a.r++,e.push(a)));u.map(e=>e[s]||e[t](r))});return a.r?l:o()},e=>(e?p(f[n]=e):c(g),i(d),f[a]=!0)),d&&d.d<0&&(d.d=0)},h.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return h.d(t,{a:t}),t},h.d=(e,t,r)=>{var n=(t,r)=>{for(var n in t)h.o(t,n)&&!h.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[r]:t[n]})};n(t,"get"),n(r,"value")},h.f={},h.e=(e,t)=>Promise.all(Object.keys(h.f).reduce((r,n)=>(h.f[n](e,r,t),r),[])),h.u=e=>"static/js/async/"+(({166:"xmarkdown-deps",350:"web-core-template-loader-thread",724:"web-elements",778:"legacy-wasm-js",894:"web-core-main-chunk",97:"web-core-worker-chunk"})[e]||e)+"."+({166:"576bbf433d",350:"f9f3ef68b1",503:"cf61731bba",724:"a0014ddd5b",778:"cc9aea9d55",894:"bc96e803db",97:"002a4f7b9d"})[e]+".js",h.miniCssF=e=>""+e+".css",h.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),h.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o={},h.l=function(e,t,r,n,a){if(o[e])return void o[e].push(t);if(void 0!==r)for(var s,i,l=document.getElementsByTagName("script"),d=0;d<l.length;d++){var u=l[d];if(u.getAttribute("src")==e||u.getAttribute("data-rspack")=="@byted-doubao-apps/web-sdk-debugger-app:"+r){s=u;break}}s||(i=!0,(s=document.createElement("script")).timeout=120,h.nc&&s.setAttribute("nonce",h.nc),s.setAttribute("data-rspack","@byted-doubao-apps/web-sdk-debugger-app:"+r),a&&s.setAttribute("fetchpriority",a),s.src=e),o[e]=[t];var c=function(t,r){s.onerror=s.onload=null,clearTimeout(p);var n=o[e];if(delete o[e],s.parentNode&&s.parentNode.removeChild(s),n&&n.forEach(function(e){return e(r)}),t)return t(r)},p=setTimeout(c.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=c.bind(null,s.onerror),s.onload=c.bind(null,s.onload),i&&document.head.appendChild(s)},h.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l=[],h.O=(e,t,r,n)=>{if(t){n=n||0;for(var a=l.length;a>0&&l[a-1][2]>n;a--)l[a]=l[a-1];l[a]=[t,r,n];return}for(var s=1/0,a=0;a<l.length;a++){for(var[t,r,n]=l[a],i=!0,o=0;o<t.length;o++)(!1&n||s>=n)&&Object.keys(h.O).every(e=>h.O[e](t[o]))?t.splice(o--,1):(i=!1,n<s&&(s=n));if(i){l.splice(a--,1);var d=r();void 0!==d&&(e=d)}}return e},h.p="/",h.j="410",h.b=document.baseURI||self.location.href,d={410:0},h.f.j=function(e,t,r){var n=h.o(d,e)?d[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var a=new Promise((t,r)=>n=d[e]=[t,r]);t.push(n[2]=a);var s=h.p+h.u(e),i=Error();h.l(s,function(t){if(h.o(d,e)&&(0!==(n=d[e])&&(d[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),a=t&&t.target&&t.target.src;i.message="Loading chunk "+e+" failed.\n("+r+": "+a+")",i.name="ChunkLoadError",i.type=r,i.request=a,n[1](i)}},"chunk-"+e,e,r)}},h.O.j=e=>0===d[e],u=(e,t)=>{var r,n,[a,s,i]=t,o=0;if(a.some(e=>0!==d[e])){for(r in s)h.o(s,r)&&(h.m[r]=s[r]);if(i)var l=i(h)}for(e&&e(t);o<a.length;o++)n=a[o],h.o(d,n)&&d[n]&&d[n][0](),d[n]=0;return h.O(l)},(c=globalThis.rspackChunk_byted_doubao_apps_web_sdk_debugger_app||=[]).forEach(u.bind(null,0)),c.push=u.bind(null,c.push.bind(c));var g=h.O(void 0,["493","783","922","741"],()=>h(75047));g=h.O(g)})();
|