@doubao-dev/cli 0.0.14 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/bin/run.js +1 -1
  2. package/dist/1664.js +60 -0
  3. package/dist/180.js +1 -0
  4. package/dist/{bin/win32-x64/security_tasm_codec.exe → 1966.js} +0 -0
  5. package/dist/1966.js.LICENSE.txt +119 -0
  6. package/dist/2585.js +2 -0
  7. package/dist/318.js +1 -0
  8. package/dist/3551.js +1 -0
  9. package/dist/3997.js +2 -0
  10. package/dist/4880.js +1 -0
  11. package/dist/5418.js +3 -0
  12. package/dist/5732.js +1 -0
  13. package/dist/7410.js +2 -0
  14. package/dist/7410.js.LICENSE.txt +1 -0
  15. package/dist/7526.js +1 -0
  16. package/dist/@byted-doubao-apps/create.js +4 -5
  17. package/dist/@byted-doubao-apps/login.js +2 -3
  18. package/dist/@byted-doubao-apps/login~1.js +2 -0
  19. package/dist/@byted-doubao-apps/template-empty/package.json +3 -3
  20. package/dist/@byted-doubao-apps/template-starter/package.json +3 -3
  21. package/dist/@byted-hdt/cli.js +11 -12
  22. package/dist/@inquirer/select.js +1 -0
  23. package/dist/app.js +1 -2
  24. package/dist/assets/web-sdk-debugger/index.html +1 -1
  25. package/dist/assets/web-sdk-debugger/static/css/{index.4b84c01189.css → index.123e72a5bc.css} +1 -1
  26. package/dist/assets/web-sdk-debugger/static/js/index.019ceb233a.js +26 -0
  27. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-api.template.js +0 -0
  28. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-framework.template.js +0 -0
  29. package/dist/auth.js +1 -2
  30. package/dist/browser.js +1 -2
  31. package/dist/components-loader.js +2 -3
  32. package/dist/dbx-demo.js +2 -3
  33. package/dist/demo-server.js +3 -4
  34. package/dist/dev-service-client.js +16 -10
  35. package/dist/dev-service-client.js.LICENSE.txt +89 -0
  36. package/dist/dev-shell.js +5 -2
  37. package/dist/dev-shell.js.LICENSE.txt +59 -0
  38. package/dist/dev.js +18 -19
  39. package/dist/devtools.js +2 -0
  40. package/dist/devtools.js.LICENSE.txt +1 -0
  41. package/dist/environment.js +1 -0
  42. package/dist/eval.js +1 -2
  43. package/dist/get.js +1 -2
  44. package/dist/init.js +6 -7
  45. package/dist/login.js +1 -2
  46. package/dist/main.js +1 -0
  47. package/dist/manifest-mcp-config.js +1 -2
  48. package/dist/project-layout.js +1 -2
  49. package/dist/prompt.js +5 -6
  50. package/dist/push-page.js +1 -2
  51. package/dist/push-widget.js +1 -2
  52. package/dist/rslib-runtime.js +1 -2
  53. package/dist/sandbox.js +1 -2
  54. package/dist/sdk.js +76 -169
  55. package/dist/sdk.js.LICENSE.txt +1 -13
  56. package/dist/sdk~1.js +218 -0
  57. package/dist/sdk~1.js.LICENSE.txt +15 -0
  58. package/dist/skills.js +2 -3
  59. package/dist/static/404/404.html +455 -0
  60. package/dist/static/assets/package.json +137 -0
  61. package/dist/static/home_choose/chooseRegion.html +345 -0
  62. package/dist/static/openChrome.applescript +88 -0
  63. package/dist/status.js +2 -3
  64. package/dist/status~1.js +1 -2
  65. package/dist/stop.js +1 -2
  66. package/dist/update.js +1 -2
  67. package/dist/upgrade.js +1 -2
  68. package/dist/upload.js +7 -8
  69. package/dist/validate.js +1 -2
  70. package/dist/yaml.js +25 -0
  71. package/package.json +34 -35
  72. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/01-/345/237/272/347/241/200.md +114 -7
  73. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/02-/347/263/273/347/273/237.md +126 -0
  74. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/06-/344/272/244/344/272/222.md +71 -0
  75. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/08-/347/275/221/347/273/234.md +222 -0
  76. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/10-/344/270/232/345/212/241/350/203/275/345/212/233.md +122 -0
  77. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/groups.md +5 -5
  78. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/quick-reference.md +7 -2
  79. package/dist/183.js +0 -2
  80. package/dist/564.js +0 -13
  81. package/dist/714.js +0 -1
  82. package/dist/assets/web-sdk-debugger/static/js/index.62b5cae841.js +0 -26
  83. package/dist/bin/darwin-arm64/security_tasm_codec +0 -0
  84. package/dist/bin/darwin-arm64/security_tasm_codec.sha256 +0 -1
  85. package/dist/bin/darwin-x64/security_tasm_codec +0 -0
  86. package/dist/bin/darwin-x64/security_tasm_codec.sha256 +0 -1
  87. package/dist/bin/linux-x64/security_tasm_codec +0 -0
  88. package/dist/bin/linux-x64/security_tasm_codec.sha256 +0 -1
  89. package/dist/bin/win32-x64/security_tasm_codec.exe.sha256 +0 -1
  90. package/dist/index.js +0 -1
  91. package/dist/package.json +0 -56
@@ -0,0 +1,26 @@
1
+ (()=>{"use strict";var e,t,r,a,n,s,i,o,l,d,u,c,p={39259(e,t,r){let a,n;r(15254);var s=r(63159);r(52205),r(40768),r(76235),r(74636);var i=r(23888);function o(e){return"object"==typeof e&&null!==e}function l(e){return o(e)&&"call"===e.type&&"string"==typeof e.name&&"number"==typeof e.callbackId}function d(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function u(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:0,msg:t,errNo:-1,errMsg:t}}}function c(e){return e instanceof Error?e.message:String(e)}function p(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!l(e))return;let a=t[e.name];if(!a)return u(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=a(e,r);if(t instanceof Promise)return t.catch(t=>u(e,c(t)));return t??u(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return u(e,c(t))}}function m(e,t){var r;let a=null==(r=globalThis.navigator)?void 0:r.clipboard;if(!a||"function"!=typeof a[t])throw Error(`${e} is not supported in this browser`);return a}function h(e,t){let r=t instanceof Error?t.message:String(t);return`${e} failed: ${r}`}async function g(e){let t=m("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw Error(h("setClipboardData",e))}}async function f(){let e=m("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw Error(h("getClipboardData",e))}throw Error("getClipboardData failed: clipboard did not return text")}function v(){return null==a?void 0:a.getPackageInfo()}r(42949),r(46455);let y="doubao-web-sdk:storage:";function _(e){return`${y}${e}`}function b(e){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 w(e){if(S(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function S(e){return new TextEncoder().encode(e).byteLength}function x(e){let t={};for(let r=0;r<e.length;r+=1){let a=e.key(r);(null==a?void 0:a.startsWith(y))&&(t[a.slice(y.length)]=e.getItem(a)??"")}return t}function I(e){return{key:b(e.key)}}function C(e){var t;let{screenWidth:r,statusBarHeight:a}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),n=Math.round(a)+4,s=Math.round(r)-12;return{bottom:n+36,height:36,left:s-84,right:s,top:n,width:84}}r(21301),r(14104),r(49678),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(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),r(18723);class E{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 a=this.registry.get(e),n="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,n),this.handlers[e]=n.handler,()=>{if(this.registry.get(e)===n){if(a){this.registry.set(e,a),this.handlers[e]=a.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[a,n]of Object.entries(e))r.push(this.register(a,n,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,a]of this.registry)a.syncResult&&this.canIUse(r,e)&&(t[r]="function"==typeof a.syncResult?a.syncResult({...e,apiRegistry:this}):a.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 a=this.eventSources.get(e),n="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,n),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,n),()=>{if(this.eventSources.get(e)===n){if(this.stopEventSource(e),a){this.eventSources.set(e,a),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,a);return}this.eventSources.delete(e)}}}registerEventSources(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[a,n]of Object.entries(e))r.push(this.registerEventSource(a,n,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 a=this.eventSources.get(e);return!!a&&("function"==typeof a.canIUse?a.canIUse({...t,apiRegistry:this}):a.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 a of this.eventControllers)r=a.emit(e,t)||r;return r}createEventController(e){return new k(this,e)}fork(){let e=new E(this.getRegistrations());return e.registerEventSources(this.getEventSources()),e}getRegistrations(){return Object.fromEntries(this.registry)}getEventSources(){return Object.fromEntries(this.eventSources)}attachEventController(e){return this.eventControllers.add(e),()=>{this.eventControllers.delete(e)}}retainEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(this.eventSourceRetainCounts.set(e,t+1),t>0)return;let r=this.eventSources.get(e);r&&this.startEventSource(e,r)}releaseEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(t<=1){this.eventSourceRetainCounts.delete(e),this.stopEventSource(e);return}this.eventSourceRetainCounts.set(e,t-1)}startEventSource(e,t){this.stopEventSource(e);let r=t.source(t=>{this.emitEvent(e,t)});"function"==typeof r&&this.eventSourceCleanups.set(e,r)}stopEventSource(e){var t;null==(t=this.eventSourceCleanups.get(e))||t(),this.eventSourceCleanups.delete(e)}}class k{apiRegistry;dispatch;cleanupRegistry;subscribedEventNames=new Set;constructor(e,t){this.apiRegistry=e,this.dispatch=t,this.cleanupRegistry=this.apiRegistry.attachEventController(this)}subscribe(e){this.subscribedEventNames.has(e)||(this.subscribedEventNames.add(e),this.apiRegistry.retainEventSource(e))}unsubscribe(e){this.subscribedEventNames.delete(e)&&this.apiRegistry.releaseEventSource(e)}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 N=new E;function R(){return(navigator.language||"zh-CN").replace("-","_")}function T(){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 M(){return"u"<typeof DoubaoAppsSDKVersion?void 0:DoubaoAppsSDKVersion}function A(){return navigator.userAgentData}function P(){var e;let t=null==(e=A())?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 a=navigator.userAgent??"";return/edg\//i.test(a)?"Microsoft Edge":/chrome|crios/i.test(a)?"Chrome":/firefox|fxios/i.test(a)?"Firefox":/safari/i.test(a)?"Safari":"Browser"}function j(){var e,t;let r=null==(e=A())?void 0:e.brands,a=null==r?void 0:r.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==a?void 0:a.version)return a.version;let n=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(n))?void 0:t[1])??void 0}function D(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",a=(null==(e=A())?void 0:e.platform)??"",n=`${a} ${r} ${t}`,s=navigator.maxTouchPoints??0;return/android/i.test(n)?{platform:"android",brand:"Android"}:/iphone/i.test(n)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(n)||/mac/i.test(r)&&s>1?{platform:"ios",brand:"iPad"}:/mac/i.test(n)?{platform:"mac",brand:"Mac"}:/win/i.test(n)?{platform:"windows",brand:"Windows"}:/linux/i.test(n)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function L(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:v();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function O(){var e,t,r,a,n;let s=Math.round((null==(a=window.visualViewport)?void 0:a.width)??window.innerWidth??0),i=Math.round((null==(n=window.visualViewport)?void 0:n.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 U(){return D().platform}function q(){var e,t,r,a,n;let s=navigator.userAgent??"",i=U();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==(n=/mac os x\s+([\d_]+)/i.exec(s))||null==(a=n[1])?void 0:a.replace(/_/g,"."):void 0}function $(){return{isConnected:!0,networkType:"unknown",hasSystemProxy:!1,weakNet:!1}}function B(){let e,t=D(),r=navigator.platform||U();return{abi:r,deviceAbi:r,benchmarkLevel:-1,brand:t.brand,model:function(){let e=navigator.userAgent??"",t=U();if("android"===t){var r,a;return(null==(a=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=a[1])?void 0:r.trim())||"Android"}return"ios"===t?D().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||D().brand:P()}(),system:function(){let e=U(),t=q();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=j(),a=P();return r?`${a} ${r}`:"Web"}(),platform:t.platform,cpuType:r,memorySize:"number"==typeof(e=navigator.deviceMemory)&&Number.isFinite(e)?String(Math.round(1024*e)):""}}function F(){let e=O(),t=B();return{...e,brand:t.brand,model:t.model,language:R(),version:j(),system:t.system,platform:t.platform,SDKVersion:M(),theme:T(),benchmarkLevel:-1,enableDebug:!0,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait",abi:t.abi}}function H(){let e=O();return{bluetoothEnabled:!1,locationEnabled:!0,wifiEnabled:$().isConnected,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait"}}function W(){let e=$();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function z(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:v();return{SDKVersion:M(),enableDebug:!0,host:{appId:L(e).appId},language:R(),version:j(),theme:T()}}function V(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:v();return{miniProgram:{appId:L(e).appId,envVersion:"develop",version:(null==e?void 0:e.versionName)??""}}}function G(e){return null==e?void 0:e.packageInfo}N.handlers;let K="doubao-web-sdk:file-system";function J(){let e=Date.now();return{entries:{"/":{type:"directory",createTime:e,lastModifiedTime:e}}}}let X={"doubao.getClipboardData":async e=>d(e,{data:await f()}),"doubao.setClipboardData":async e=>{let{data:t}=function(e){if(!o(e)||"string"!=typeof e.data)throw Error("data must be a string");return{data:e.data}}(e.params);return await g(t),d(e,{})},"applet.subscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var a;null==t||null==(a=t.events)||a.subscribe(r)}return d(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var a;null==t||null==(a=t.events)||a.unsubscribe(r)}return d(e,{})},"doubao.getCurrentPages":e=>d(e,{pages:(null==a?void 0:a.getCurrentPages())??[]}),"doubao.navigateTo":e=>{var t;return(t=e.params,null==a||a.navigateTo(t),a)?d(e,{}):u(e,"No active Runtime to navigate")},"doubao.redirectTo":e=>{var t;return(t=e.params,null==a||a.redirectTo(t),a)?d(e,{}):u(e,"No active Runtime to redirect")},"doubao.reLaunch":e=>{var t;return(t=e.params,null==a||a.reLaunch(t),a)?d(e,{}):u(e,"No active Runtime to relaunch")},"doubao.navigateBack":e=>{var t;return(t=e.params??{},null==a||a.navigateBack(t),a)?d(e,{}):u(e,"No active Runtime to navigate back")},"doubao.exitApp":e=>(null==a||a.exitApp(),a)?d(e,{}):u(e,"No active Runtime to exit app"),"doubao.close":e=>{var t;return(t=e.params??{},null==a||a.close(t),a)?d(e,{}):u(e,"No active Runtime to close page")},"doubao.setStorage":e=>{var t;let{key:r,data:a}={...I(t=e.params),data:t.data};return w(a),localStorage.setItem(_(r),a),d(e,{})},"doubao.getStorage":e=>{let{key:t}=I(e.params),r=localStorage.getItem(_(t));return null===r?u(e,`storage item not found: ${t}`):d(e,{data:r})},"doubao.removeStorage":e=>{let{key:t}=I(e.params);return localStorage.removeItem(_(t)),d(e,{})},"doubao.clearStorage":e=>{for(let e of Object.keys(x(localStorage)))localStorage.removeItem(_(e));return d(e,{})},"doubao.getStorageInfo":e=>{var t;return d(e,{keys:Object.keys(t=x(localStorage)),currentSize:Math.ceil(Object.values(t).reduce((e,t)=>e+S(t),0)/1024),limitSize:10240})},"doubao.__webSyncBridgePersist":e=>{var t,r;let a=o(t=e.params)&&o(t.storageSnapshot)?t.storageSnapshot:void 0,n=o(r=e.params)&&o(r.fileSystemSnapshot)?r.fileSystemSnapshot:void 0;return a&&function(e){let t=[];for(let e=0;e<localStorage.length;e+=1){let r=localStorage.key(e);(null==r?void 0:r.startsWith(y))&&t.push(r)}for(let e of t)localStorage.removeItem(e);for(let[t,r]of Object.entries(e)){let e=b(t);w(r),localStorage.setItem(_(e),r)}}(a),n&&localStorage.setItem(K,JSON.stringify(n)),d(e,{})},"doubao.authorize":{handler:e=>d(e,{}),syncResult:{}},"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return d(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:N;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:e=>d(e,V()),syncResult:e=>V(G(e))},"doubao.getPackageInfo":{handler:e=>d(e,L()),syncResult:e=>L(G(e))},"doubao.getAppBaseInfo":{handler:e=>d(e,z()),syncResult:e=>z(G(e))},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>d(e,C(null==t?void 0:t.globalProps)),syncResult:e=>C(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:e=>d(e,F()),syncResult:F},"doubao.getSystemSetting":{handler:e=>d(e,H()),syncResult:H},"doubao.getWindowInfo":{handler:e=>d(e,O()),syncResult:O},"doubao.getDeviceInfo":{handler:e=>d(e,B()),syncResult:B},"doubao.getNetworkType":{handler:e=>d(e,W()),syncResult:W}};N.registerMany(X,{override:!0}),N.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}),r(74678),r(55910),r(76691),r(72919);let Q="embed-webview",Z="__channel_ack__",Y=new WeakMap,ee=e=>({url:e});function et(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 ea=globalThis.HTMLElement??class{};"object"!=typeof customElements||customElements.get(Q)||customElements.define(Q,class e extends ea{static observedAttributes=["src"];#e=null;#t=null;#r=!1;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#a(),this.#n()}disconnectedCallback(){var e;this.#r=!1,this.#s(),null==(e=this.#e)||e.remove(),this.#e=null}attributeChangedCallback(e){"src"===e&&this.#r&&this.#n()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#n(!0)}postMessage(e){let t=o(e)?e.data:void 0;this.#i({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=o(e)&&"string"==typeof e.func?e.func:"";if(t)try{var r;null==(r=this.#o())||r.eval(t)}catch{}}onGoBack(){return{consumed:!1}}#a(){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}#n(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#a(),r=this.getAttribute("src");if(!r)return;let a=ee(r);(e||t.getAttribute("src")!==a.url)&&(this.#s(),t.toggleAttribute("credentialless",!0===a.credentialless),t.src=a.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===Z)return;let t=et(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!==Z&&this.#g(et(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(et(e)),Promise.resolve({})),postMessageSync:e=>{let t=et(e);return l(t)?u(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(o(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!l(e))return!1;if("doubao.postMessage"===e.name){let t=o(e.params)?e.params.data:void 0;return this.#f(er(t)),this.#i(d(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=Y.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#i(u(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#i(r??u(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 a=this.#o();null==a||null==(t=a.onWebViewMessage)||t.call(a,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 en="AppletBridgeModule",es="postMessage";function ei(e,t,r){t===es&&o(r)&&"callback"===r.type&&"callbackId"in r&&"function"==typeof e.sendGlobalEvent&&e.sendGlobalEvent("__APPLET_BRIDGE__",[r])}function eo(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;bridgeEvents=null;view=null;constructor(e){const t=e.container;if(!t)throw Error("Container requires a container element");this.container=t,this.className=e.className??"doubao-web-container-view",this.options=e}get element(){return this.view}render(e){var t,r,a,n,s,d,m,h;let g,f,v,y,_,b,w;this.clear();let S=document.createElement("lynx-view"),I=e.containerType??"PAGE",C="WIDGET"===I?"content":"fill";S.className=this.className,S.dataset.containerType=I,S.dataset.webSizing=C,S.style.display="APP"===I?"none":"block",S.style.width="100%",S.style.height="content"===C?"auto":"100%","content"===C&&S.setAttribute("height","auto"),S.url=function(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}(e),S.initData=e.initData??{};let E={...(g=B(),v=(f=O()).windowWidth>f.windowHeight,{os:g.platform,osVersion:q(),deviceBrand:g.brand,deviceModel:g.model,deviceType:g.model,channel:"debug",screenOrientation:+!!v,isLandscape:+!!v,abi:g.abi}),...e.globalProps??{}},k=(t=this.options.apiRegistry,{fileSystemSnapshot:function(){let e=localStorage.getItem(K);if(!e)return J();try{let t=JSON.parse(e);if(o(t)&&o(t.entries))return t}catch{}return J()}(),apiResults:(r=function(e){if(!o(e)||!o(e.packageInfo))return;let{appId:t,iconSrc:r,name:a,versionName:n}=e.packageInfo;return{appId:"string"==typeof t?t:void 0,iconSrc:"string"==typeof r?r:void 0,name:"string"==typeof a?a:void 0,versionName:"string"==typeof n?n:void 0}}(E),(t??N).getSyncResults({apiRegistry:t,globalProps:E,packageInfo:r})),storageSnapshot:x(localStorage),supportedAPIs:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N;return e.getSupportedNames({apiRegistry:e})}(t)});y=new URL("./__doubao_web_sdk_native_modules/",(null==(a=globalThis.document)?void 0:a.baseURI)??(null==(n=globalThis.location)?void 0:n.href)??"http://localhost/").href,S.nativeModulesMap={AppletBridgeModule:(s=new URL("applet-bridge-module.mjs",y).href,(b=new URLSearchParams((_=new URL(s)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify(k)),_.hash=b.toString(),_.href),AppletJSModule:new URL("applet-js-module.mjs",y).href},(0,i.B)(S),S.globalProps={...E,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:k};let R=this.options.apiRegistry??N;return this.bridgeEvents=R.createEventController((e,t)=>eo(S,e,t)),d=this.options,m=this.bridgeEvents,w=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.apiRegistry??N;return(r,a,n)=>{if(("AppletJSModule"!==n||"log"!==r)&&"AppletBridgeModule"===n&&"postMessage"===r)return p(a,t.handlers,{...e,apiRegistry:t})}}({apiRegistry:d.apiRegistry,emitEvent:(e,t)=>m.emit(e,t),events:m,globalProps:E}),S.onNativeModulesCall=(e,t,r)=>{var a,n,s,i;let p;if(r===en&&e===es&&o(a=t)&&"event"===a.type&&"__bridge_ready__"===a.name&&(null==(n=d.onReady)||n.call(d)),r===en&&e===es&&o(s=t)&&"callback"===s.type&&"callbackId"in s)return ei(S,e,t),t;try{p=(null==(i=d.nativeModulesCallHandler)?void 0:i.call(d,e,t,r,{containerType:I,element:S}))??w(e,t,r)}catch(a){let r=l(t)?u(t,c(a)):void 0;return ei(S,e,r),r}return p instanceof Promise?p.then(t=>(ei(S,e,t),t)).catch(r=>{let a=l(t)?u(t,c(r)):void 0;return ei(S,e,a),a}):(ei(S,e,p),p)},h=e=>p(e,R.handlers,{apiRegistry:R,globalProps:E}),Y.set(S,h),S.transformVW=!0,S.transformVH="content"!==C,S.transformREM=!0,S.addEventListener("error",e=>{var t,r;let a;null==(t=(r=this.options).onError)||t.call(r,(null==(a=e.detail)?void 0:a.error)instanceof Error?a.error:Error(String((null==a?void 0:a.error)??a??"Unknown Container runtime error")),e)}),this.view=S,this.container.replaceChildren(S),S}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&&eo(r,e,t)}reload(){var e,t;null==(t=this.view)||null==(e=t.reload)||e.call(t)}}let ed=`<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>`,eu=`<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>`,ec="doubao-apps-page",ep={body:`${ec}__body`,capsule:`${ec}__capsule`,capsuleAction:`${ec}__capsule-action`,capsuleCloseIcon:`${ec}__capsule-close-icon`,capsuleMoreIcon:`${ec}__capsule-more-icon`,root:ec};class em{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 a=document.createElement("div");a.className=ep.root,void 0!==(r=null==(t=e.pageCapsule)?void 0:t.statusBarHeight)&&a.style.setProperty("--doubao-page-capsule-top",`${r+4}px`);let n=document.createElement("div");return n.className=ep.body,a.append(n,this.createCapsule()),this.host.replaceChildren(a),this.root=a,this.container=new el({apiRegistry:this.options.apiRegistry,container:n,className:this.options.className,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,a){let n=this.createCapsuleSvg(r);return n.classList.add(ep.capsuleAction,e),n.setAttribute("role","button"),n.setAttribute("aria-label",t),n.setAttribute("tabindex","0"),n.setAttribute("focusable","true"),n.addEventListener("click",e=>{this.dispatchCapsuleEvent(a,e)}),n.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),this.dispatchCapsuleEvent(a,e))}),n}createCapsuleMoreIcon(){return this.createCapsuleAction(ep.capsuleMoreIcon,"More",ed,"doubao:page-capsule-more")}createCapsuleCloseIcon(){return this.createCapsuleAction(ep.capsuleCloseIcon,"Close app",eu,"doubao:page-capsule-close")}createCapsule(){let e=document.createElement("div");return e.className=ep.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}}var eh=r(70851);function eg(e){return o(e.web)&&"string"==typeof e.web.entry}function ef(e){return"widgetId"in e?e.widgetId:e.id}function ev(e){let t=new Map;for(let r of e)for(let e of function(e){let t=[ef(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}class ey{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(eg),this.pageEntryMap=ev(this.pageEntries),this.widgetEntries=e.widgets.filter(eg),this.widgetEntryMap=ev(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 e_(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.fetcher??fetch,a=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!a.ok)throw Error(`Failed to load Web manifest: ${a.status} ${a.statusText}`);let n=await a.json();if(!o(n))throw Error("Invalid Web manifest: expected a JSON object");return new ey(n)}function eb(e,t,r){var a;let n="item"in t?t.item:t,s="web"in n&&o(n.web)&&"string"==typeof n.web.entry?function(e){if(o(e.web)&&"string"==typeof e.web.entry)return e.web.entry;throw Error(`No Web entry configured for manifest entry: ${ef(e)}`)}(n):n.entry,i=new URL(e,r??(null==(a=globalThis.location)?void 0:a.href)??"http://localhost/");return i.pathname.endsWith("/web/manifest.json")?i.pathname=i.pathname.slice(0,-17):i.pathname.endsWith("/base/manifest.json")?i.pathname=i.pathname.slice(0,-18):i.pathname=i.pathname.replace(/\/[^/]*$/,"/"),i.search="",i.hash="",new URL(s,i).toString()}function ew(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function eS(e){return new URL(e,ew()).toString()}function ex(e,t){if(!t)return e;let r=new URL(e,ew());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class eI{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=eS(await this.getManifestUrl(e)),a=this.packages.get(r);if(a&&!t.forceReload)return a;let n=e_(r,{fetcher:this.options.fetcher}).then(e=>({manifest:e,manifestUrl:r}));return n.catch(()=>{this.packages.get(r)===n&&this.packages.delete(r)}),this.packages.set(r,n),n}deletePackage(e){this.packages.delete(eS(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}async resolvePage(e,t){let r=await this.loadPackage(e),a=r.manifest.getPageEntry(t);return{appId:r.manifest.appId,entry:a,iconSrc:r.manifest.iconSrc,name:r.manifest.name,resourceUrl:ex(eb(r.manifestUrl,a),this.resourceUrlVersion)}}async resolveWidget(e,t){let r=await this.loadPackage(e),a=r.manifest.getWidgetEntry(t);return{appId:r.manifest.appId,entry:a,iconSrc:r.manifest.iconSrc,appName:r.manifest.name,resourceUrl:ex(eb(r.manifestUrl,a),this.resourceUrlVersion)}}}let eC=new eI;function eE(e){var t;let{addProtocolToBareHost:r=!1,allowRootRelative:a=!1,defaultProtocol:n="http"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(/^https?:\/\//i.test(e))return e;if(e.startsWith("//"))return`${eN(n,e.slice(2))}:${e}`;if(a&&e.startsWith("/"))return e;return/^(?:\[[^\]]+\]|[a-z0-9.-]+):\d+(?:[/?#]|$)/i.test(e)||r&&(t=e,/^(?:\[[^\]]+\]|[a-z0-9.-]+)(?:[/?#]|$)/i.test(t))?`${eN(n,e)}://${e}`:e}function ek(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=String(e??"").trim();if(!r)return;let a=eE(r,t);try{let e=t.baseUrl?new URL(a,t.baseUrl):new URL(a);if("http:"!==e.protocol&&"https:"!==e.protocol)return;return e.toString()}catch{return}}function eN(e,t){return"function"==typeof e?e(t):e}r(37891);let eR="doubao-apps-widget",eT={body:`${eR}__body`,header:`${eR}__header`,icon:`${eR}__icon`,root:eR,title:`${eR}__title`};class eM{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 eC.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,eh.$)(eT.root,this.options.className);let r=document.createElement("div");if(r.className=eT.body,2!==e.titleType){let e=document.createElement("header");e.className=eT.header;let r=document.createElement("img");r.alt="",r.className=eT.icon,r.height=16,r.width=16;let a=document.createElement("div");a.className=eT.title,e.append(r,a),t.append(e),this.icon=r,this.title=a}return t.append(r),this.container.replaceChildren(t),this.root=t,this.body=r,this.updateHeader(e.appName,e.icon),this.runtimeContainer=new el({apiRegistry:this.options.apiRegistry,container:r,nativeModulesCallHandler:this.options.nativeModulesCallHandler,onError:this.options.onError}),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);let eA="onDestroy",eP="onShow";function ej(e){return e.path||e.id}function eD(e,t){e.style.display=t?"block":"none"}function eL(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 a={};return new URLSearchParams(r).forEach((e,t)=>{a[t]=e}),{pageId:t,viewData:a}}(e.url),a=JSON.stringify(r);return{pageId:t,initData:{viewData:r,viewContext:{}},globalProps:{__LOCATION__:e.url,__RENDER_DATA__:a,__VIEW_CONTEXT__:{}}}}(e);return{...r,entry:t.getPageEntry(r.pageId)}}function eO(e){if(o(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return o(t)?t:{}}catch{return{}}}class eU{container;className;apiRegistry;nativeModulesCallHandler;onError;appGlobalProps;appInitData;runtimeHost;cleanupBridgeController;cleanupEmptyState;emptyState;manifest;manifestUrl;pageCapsule;appRuntime=null;stack=[];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.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 a=e,()=>{a===e&&(a=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}pushPage(){var e,t,r;let a,n,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=this.resolvePageEntry(s),l=eb(this.manifestUrl,i),d=s.pageCapsule??this.pageCapsule,u=`page-${++this.nextPageIndex}`,c=(e=s,t=u,r=i,a=o(e.globalProps)?eO(e.globalProps.__VIEW_CONTEXT__):{},{...o(e.initData)?eO(e.initData.viewContext):{},...a,viewId:t,pageName:r.id,pageUrl:ej(r)}),p=((n=document.createElement("div")).className="doubao-runtime-page",n.style.display="block",n.style.width="100%",n.style.height="100%",n),m=null,h=new em({apiRegistry:this.apiRegistry,className:this.className,container:p,nativeModulesCallHandler:this.nativeModulesCallHandler,onError:this.onError,onReady:()=>{m&&this.stack.includes(m)&&(m.isReady=!0,this.flushPageLifecycleEvents(m))}});void 0!==s.pageCapsule&&(this.pageCapsule=s.pageCapsule),this.ensureAppRuntime(),this.container.append(p);try{let e,t,r=h.render({resourceUrl:l,initData:o(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}:{},o(s.globalProps)?{...s.globalProps,...t,__VIEW_CONTEXT__:c}:{...t,__VIEW_CONTEXT__:c}),pageCapsule:d}),a=this.getCurrentStackItem();return a&&(this.sendPageLifecycleEvent(a,"onHide"),eD(a.frame,!1)),m={id:u,pageId:i.id,route:ej(i),resourceUrl:l,entry:i,element:r,frame:p,isReady:!1,pendingLifecycleEvents:[],page:h},p.addEventListener("doubao:page-capsule-close",e=>{e.stopPropagation(),this.exitBridgeApp()}),this.stack.push(m),this.updateEmptyState(),this.sendPageLifecycleEvent(m,eP),this.sendAppLifecycleEvent("onPageOpened",{viewId:m.id}),this.toStackEntry(m)}catch(e){throw h.clear(),p.remove(),this.updateEmptyState(),e}}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,eA),e.page.clear(),e.frame.remove();let a=this.getCurrentStackItem();return t&&a&&(eD(a.frame,!0),this.sendPageLifecycleEvent(a,eP)),this.updateEmptyState(),r}ensureAppRuntime(){let e;if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let t=eb(this.manifestUrl,this.manifest.appRuntimeEntry),r=((e=document.createElement("div")).className="doubao-runtime-app",e.hidden=!0,e.style.display="none",e),a=new el({apiRegistry:this.apiRegistry,className:this.className,container:r,nativeModulesCallHandler:this.nativeModulesCallHandler,onError:this.onError,onReady:()=>{var e;(null==(e=this.appRuntime)?void 0:e.container)===a&&(this.appRuntime.isReady=!0,this.flushAppLifecycleEvents())}});this.container.append(r),this.appRuntime={container:a,frame:r,isReady:!1,pendingLifecycleEvents:[]};try{var n,s;a.render({resourceUrl:t,containerType:"APP",initData:this.appInitData??{},globalProps:(n=this.appGlobalProps??{},s=this.getPackageInfo(),n&&"object"==typeof n?{packageInfo:s,...n}:{packageInfo:s})}),this.sendAppLifecycleEvent("onForeground")}catch(e){throw this.appRuntime=null,a.clear(),r.remove(),e}}clearAppRuntime(){let e=this.appRuntime;(null==e?void 0:e.isReady)&&(this.sendAppLifecycleEvent("onBackground"),this.sendAppLifecycleEvent(eA)),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,a=(r={viewId:e.id,pageName:e.pageId,pageUrl:e.route},{viewId:e.id,eventName:JSON.stringify(r)});e.isReady?e.page.sendEvent(t,a):e.pendingLifecycleEvents.push({name:t,params:a})}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 eL(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}))}getPackageInfo(){return{appId:this.manifest.appId,name:this.manifest.name,iconSrc:this.manifest.iconSrc,versionName:this.manifest.versionName}}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,[a]=this.stack.splice(t,1);return this.removeStackItem(a,r)}toStackEntry(e){return{id:e.id,pageId:e.pageId,route:e.route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}var eq=r(75541),e$=r(80148),eB=r(11855);function eF(e){let t=new Uint8Array(e),r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}function eH(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function eW(e){return eH(e)?eH(e.viewData)?e:{...e,viewData:e}:{viewData:{}}}function ez(e){return"object"==typeof e&&null!==e}function eV(e){if("string"==typeof e&&e.trim())try{return JSON.parse(e)}catch{return}}function eG(e){if(eH(e))return e;let t=eV(e);return eH(t)?t:void 0}function eK(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return"{}"}}function eJ(e){return e instanceof Error?e.message:String(e)}function eX(e,t){let r=e[t];return"string"==typeof r?r:""}function eQ(e,t){let r=e[t];return"number"==typeof r&&Number.isFinite(r)?r:void 0}function eZ(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 eY(e){let[t,...r]=e.trim().split(":"),a=t.replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(e0).join(" ");return 0===r.length?a||e:`${a}: ${r.join(":").trim()}`}function e0(e){let t=function(e){switch(e.toLowerCase()){case"api":return"API";case"mcp":return"MCP";case"sse":return"SSE";case"ack":return"ACK";case"http":return"HTTP";case"json":return"JSON";case"id":return"ID";default:return""}}(e);if(t)return t;if(/^[A-Z0-9]+$/.test(e))return e;let r=e.toLowerCase();return`${r.slice(0,1).toUpperCase()}${r.slice(1)}`}r(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 e1="/__wsd_control_results";async function e2(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e1,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:fetch,a=await r(t,{body:JSON.stringify(e),headers:{"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw Error(`Failed to report debugger control result: ${a.status}`)}let e3="/__web_artifacts/base/manifest.json",e4="/app_developer";function e5(e){return!e.debugHidden}function e6(e,t){let r=t.trim();r&&!e.includes(r)&&e.push(r)}function e8(e){let t=[];return!function e(t,r,a){if(!(!ez(t)||a.has(t))){if(a.add(t),Array.isArray(t))return void t.forEach(t=>e(t,r,a));if(eH(t))for(let[n,s]of Object.entries(t))"response_headers"===n.toLowerCase()&&function(e,t){if(eH(e)){for(let[r,a]of Object.entries(e))if("x-tt-logid"===r.toLowerCase()&&"string"==typeof a)return void e6(t,a)}}(s,r),"log_ids"===n.toLowerCase()&&function(e,t){if("string"==typeof e)return e6(t,e);if(Array.isArray(e))for(let r of e)"string"==typeof r&&e6(t,r)}(s,r),e(s,r,a)}}(e,t,new WeakSet),t}function e7(e){let t=eE(String(e??e4).trim(),{addProtocolToBareHost:!0,allowRootRelative:!0,defaultProtocol:e9}).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 e9(e){return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\])(?::|\/|$)/i.test(e)?"http":"https"}function te(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 tt(e,t){return`${e7(e)}${"chat"===t?"/api/simulator/chat":"/api/simulator/tool/report"}`}r(12021),r(20789),r(62839),r(66876),r(78872),r(60972);var tr=r(75585);let ta=["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 tn(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=e.getReader(),n=new TextDecoder,s={...r,fallbackSeq:0},i=(0,tr.C)({onEvent:e=>{let r=function(e,t){var r,a,n;let s,i,o,l,d,u,c=void 0===(l=eV(r=e.data))&&r.trim()?r:l,p=eH(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 ta){let r=e[t];if(eH(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=eH(h)?h:{},f=eQ(p,"sequence")??(t.fallbackSeq+=1),v=e.id||eX(p,"id")||`evt_${f.toString().padStart(4,"0")}`,y=function(e,t,r){let a=eX(e,"request_id")||("ack"===r?eX(t,"request_id"):"");if("ack"===r&&!a)throw Error("Invalid simulator SSE ACK: missing request_id");return a||eX(e,"id")}(p,g,m),_=eX(p,"reply_message_id")||eX(g,"message_id")||t.replyMessageId;return{event_id:v,event_type:m,seq:f,request_id:y,query_message_id:eX(p,"query_message_id")||eX(g,"query_message_id"),reply_message_id:_,created_at_ms:eQ(p,"timestamp_ms")??Date.now(),received_at_ms:Date.now(),trace:(d=eH(p.trace)?p.trace:{},{trace_id:"string"==typeof(u=t.trace??{}).trace_id?u.trace_id:"string"==typeof d.trace_id?d.trace_id:te("trace"),span_id:"string"==typeof d.span_id?d.span_id:te("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:{...eH(u.baggage)?u.baggage:{},...eH(d.baggage)?d.baggage:{}}}),payload:(a=g,0===(o=Array.isArray(i=eH(s=null==(n=t.trace)?void 0:n.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!==a.log_ids?a:{...a,log_ids:o})}}(e,s);r.reply_message_id&&(s.replyMessageId=r.reply_message_id),t(r)}});for(;;){let{done:e,value:t}=await a.read();if(t&&i.feed(n.decode(t,{stream:!e})),e)break}let o=n.decode();o&&i.feed(o),i.feed("\n\n")}let ts="x-tt-logid";class ti extends Error{responseDebug;constructor(e,t){super(e),this.responseDebug=t,this.name="SimulatorHttpError"}}function to(e){return e.headers.get(ts)||void 0}function tl(e){let t={},r=to(e);return r&&(t[ts]=r),t}function td(e){return eH(e.trace)?e.trace:{}}async function tu(e,t){let r=to(t),a=tl(t),n=await t.text().catch(()=>""),s={status:t.status,status_text:t.statusText,...Object.keys(a).length>0?{response_headers:a}:{},...r?{log_ids:[r]}:{},...n?{response_text:n}:{}};return new ti(`${e}: ${t.status} ${t.statusText}`,s)}function tc(e){return e instanceof ti?e.responseDebug:void 0}function tp(e,t,r){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=arguments.length>4?arguments[4]:void 0,s=td(e),i=Date.now();return{event_id:te("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:te("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:n??(eH(s.baggage)?s.baggage:{})},payload:{event:t,category:"api",elapsed_ms:Date.now()-r,...a}}}async function tm(e){let t,{endpoint:r,fetcher:a,onEvent:n,request:s,signal:i}=e,o=Date.now(),l=tt(r,"chat");n(tp(s,"simulator_chat_fetch_started",o,{endpoint:"chat",phase:"request",request:s,request_json:eK(s),url:l}));let d=setTimeout(()=>{n(tp(s,"simulator_chat_fetch_waiting_for_headers",o,{endpoint:"chat",phase:"wait",url:l,wait_ms:5e3}))},5e3);try{t=await (a??fetch)(l,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(s),signal:i})}catch(e){throw clearTimeout(d),n(tp(s,"simulator_chat_fetch_failed",o,{endpoint:"chat",phase:"error",url:l,error:eJ(e)})),e}clearTimeout(d);let u=to(t),c=tl(t),p=td(s),m={...eH(p.baggage)?p.baggage:{}};if(u&&(m[ts]=u,m.log_ids=[u]),n(tp(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 tu("Simulator query failed",t);throw n(tp(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||n(tp(s,"simulator_chat_sse_waiting_for_first_event",o,{endpoint:"chat",wait_ms:5e3},m))},5e3);try{await tn(t.body,e=>{h+=1,g||(g=!0,clearTimeout(f)),n(e)},{trace:{...p,baggage:m}})}catch(e){throw clearTimeout(f),n(tp(s,"simulator_chat_sse_read_failed",o,{endpoint:"chat",phase:"error",event_count:h,error:eJ(e)},m)),e}clearTimeout(f)}async function th(e){let{endpoint:t,fetcher:r,result:a,signal:n}=e,s=await (r??fetch)(tt(t,"tool-report"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(a),signal:n});if(!s.ok)throw await tu("Simulator tool result failed",s);let i=await tg(s),o=to(s);return{...i,...o?{response_headers:{...eH(i.response_headers)?i.response_headers:{},[ts]:o},log_ids:[o]}:{}}}async function tg(e){let t=await e.text().catch(()=>"");if(!t.trim())return{};try{let e=JSON.parse(t);return eH(e)?e:{response_body:e}}catch{return{response_text:t}}}let tf={label:"Request",tone:"request"},tv={label:"Response",tone:"response"},ty={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:tf,title:"Chat"},simulator_chat_fetch_waiting_for_headers:{title:"Chat Waiting"},simulator_chat_response_meta:{badge:tv,title:"Chat"},simulator_chat_fetch_failed:{badge:tv,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:tf,debugOnly:!0,title:"MCP Load"},local_mcp_tools_loaded:{badge:tv,debugOnly:!0,title:"MCP Load"},local_mcp_tools_load_failed:{badge:tv,title:"MCP Load Failed"},local_mcp_missing:{title:"MCP Missing"},local_mcp_call_started:{badge:tf,title:e=>`MCP Tool${e}`},local_mcp_call_succeeded:{badge:tv,title:e=>`MCP Tool${e}`},local_mcp_call_failed:{badge:tv,title:e=>`MCP Tool Failed${e}`},tool_result_report_started:{badge:tf,title:e=>`Report Tool Result${e}`},tool_result_report_response_received:{badge:tv,title:e=>`Report Tool Result${e}`},tool_result_report_failed:{badge:tv,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:tv,title:e=>`Report Tool Result Failed${e}`},tool_executor_missing:{title:e=>`Tool Executor Missing${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:tf,debugOnly:!0,title:"Manifest Load"},simulator_manifest_loaded:{badge:tv,debugOnly:!0,title:"Manifest Load"},simulator_manifest_load_failed:{badge:tv,title:"Manifest Load Failed"},simulator_manifest_fetch_started:{badge:tf,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_succeeded:{badge:tv,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_failed:{badge:tv,title:"Manifest Fetch Failed"},simulator_manifest_missing:{title:"Manifest Missing"},simulator_skill_load_started:{badge:tf,debugOnly:!0,title:"Skill Load"},simulator_skill_loaded:{badge:tv,debugOnly:!0,title:"Skill Load"},simulator_skill_empty:{badge:tv,debugOnly:!0,title:"Skill Empty"},simulator_skill_load_failed:{badge:tv,title:"Skill Load Failed"},simulator_skill_fetch_started:{badge:tf,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_succeeded:{badge:tv,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_failed:{badge:tv,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 t_(e){try{return JSON.stringify(e??{})}catch{return""}}function tb(e){if(!eH(e))return;let t=tw(e);return{category:t.category,...t.debugOnly?{debugOnly:!0}:{},detail:t.detail,...t.transportBadge?{leftBadges:[t.transportBadge]}:{},phase:t.phase,title:t.title}}function tw(e){var t,r;let a="string"==typeof e.event?e.event:"",n=ty[a],s=e.detail??e.data??e,i="string"==typeof e.title&&e.title?eY(e.title):function(e,t){var r;let a=null==(r=ty[e])?void 0:r.title;if("function"==typeof a){let e,r,n;return a((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:"",(n=e||r)?`: ${n}`:""))}return a||(e?eY(e):"Agent Trace Event")}(a,e),o="string"==typeof e.category&&e.category?eZ(e.category):(t=a).startsWith("local_mcp_")?"mcp":t.startsWith("tool_result_report_")||"tool_result_ack"===t?"api":t.startsWith("tool_result_")||"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=a)?"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|cancel_requested)$/.test(r)?"status":"tool_result_ack"===r?"ack":"event";return{category:o,debugOnly:(null==n?void 0:n.debugOnly)===!0,detail:s,eventName:a,phase:l,title:i,transportBadge:null==n?void 0:n.badge}}function tS(e){return e.blocks.some(e=>"card"===e.type&&"permission_apply"===e.card.card_type)}function tx(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{messages:r,streamStatus:a}=e.getState().simulator,n=function(e,t){let r=t?e.findIndex(e=>e.messageId===t):e.findLastIndex(tS);if(-1===r)return;let a=e[r];if(tS(a))for(let t=r-1;t>=0;t--){let r=e[t];if("user"===r.role&&r.text.trim())return{messageIds:[r.messageId,a.messageId],query:r.text.trim()}}}(r,t.grantingMessageId);return n?"streaming"===a?{status:"streaming"}:(e.removeSimulatorMessages(n.messageIds),{completion:t.noLogin?e.sendSimulatorQuery(n.query,{noLogin:!0}):e.sendSimulatorQuery(n.query),status:"started",target:n}):{status:"not_found"}}function tI(e){if(!eH(e))return;let t=eX(e,"grantingName");if(t){var r;return{grantingName:t,permissionStatus:eX(e,"permissionStatus")||"pending",priorityLevel:"number"==typeof e.priorityLevel?e.priorityLevel:0,relatedData:eG(r=e.relatedData)??(eH(r)?r:{}),required:!1!==e.required}}}function tC(e){let t=eG(e);if(!t)return;let r=Array.isArray(t.grantingList)?t.grantingList.map(tI).filter(e=>!!e):[];if(0!==r.length)return{cardStatus:eX(t,"cardStatus")||"unexpired",doubaoAppletIcon:eX(t,"doubaoAppletIcon"),doubaoAppletKey:eX(t,"doubaoAppletKey"),doubaoAppletName:eX(t,"doubaoAppletName")||"智能服务",doubaoAppletVersion:eX(t,"doubaoAppletVersion"),grantingList:r,raw:t}}function tE(e){var t;switch(null==(t=e.grantingList[0])?void 0:t.grantingName){case"permission":return"权限申请";case"privacy":return"隐私协议提示";default:return"登录授权"}}function tk(e,t,r,a,n){let s=e.find(e=>e.messageId===t);return s?a&&!s.requestId||n&&!s.traceId?e.map(e=>e===s?{...e,...a&&!e.requestId?{requestId:a}:{},...n&&!e.traceId?{traceId:n}:{}}:e):e:[...e,{messageId:t,...a?{requestId:a}:{},...n?{traceId:n}:{},role:"assistant",contentType:"mixed",text:"",blocks:[],status:"streaming",createdAtMs:r}]}function tN(e,t,r){return e.map(e=>e.messageId===t?r(e):e)}function tR(e,t,r,a){let n={blockId:t,type:"card",card:r};if("replace"===a){let a=r.card_id,s=e.map(e=>e.blockId===t||"card"===e.type&&a&&e.card.card_id===a?n:e);return s.some(e=>e===n)?s:[...e,n]}return e.some(e=>e.blockId===t)?e.map(e=>e.blockId===t?n:e):[...e,n]}function tT(e,t,r){let a=!1,n=!1,s=e.map(e=>{let s=!1,i=e.blocks.map(e=>{if("card"!==e.type||e.card.card_id!==t)return e;a=!0;let i=r(e.card);return i?(n=!0,s=!0,{...e,card:i}):e});return s?{...e,blocks:i}:e});return{messages:n?s:e,found:a,updated:n}}function tM(e){return"debug"===e.event_type?e.payload.data??e.payload:e.payload}function tA(e){let t=eX(e.payload,"tool_name")||eX(e.payload,"tool_call_id"),r=eX(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 eY(eX(e.payload,"title")||"Agent Trace");case"heartbeat":return"Heartbeat";default:return eY(e.event_type)}}function tP(e){let t=eX(e.payload,"category");if(t)return eZ(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 tj(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 tD(e){return"u">typeof DOMException&&e instanceof DOMException?"AbortError"===e.name:e instanceof Error&&"AbortError"===e.name}function tL(e,t){if(eH(e)&&"code"in e&&"message"in e)return e;let r=eH(e)&&eH(e.responseDebug)?e.responseDebug:void 0,a=eG(null==r?void 0:r.response_text),n="string"==typeof(null==a?void 0:a.message)&&a.message.trim()?a.message.trim():"string"==typeof(null==r?void 0:r.response_text)&&r.response_text.trim()?r.response_text.trim():"";return{code:("string"==typeof(null==a?void 0:a.code)||"number"==typeof(null==a?void 0:a.code)?String(a.code):void 0)??"INTERNAL_ERROR",message:n||eJ(e),retryable:!1,stage:t,...r?{details:{response:r,...a?{response_body:a}:{}}}:{}}}function tO(e,t){var r;let a=(null==(r=e.traceEvents.at(-1))?void 0:r.order)??e.traceEvents.length;return{...e,traceEvents:[...e.traceEvents,{...t,order:a+1}].slice(-200)}}function tU(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 tq(e,t,r){return{...e,toolCalls:e.toolCalls.map(e=>e.toolCallId===t?{...e,...r}:e)}}function t$(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},a=e.findIndex(e=>e.tool_call_id===t.toolCallId);return a<0?[...e,r]:e.map((e,t)=>t===a?r:e)}r(66249);let tB="simulator_web_tester";function tF(e){return"string"==typeof e?e.trim():""}function tH(e){return["succeeded","failed","timeout","cancelled","rejected"].includes(e)}function tW(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"tool_execute",a=arguments.length>3?arguments[3]:void 0;return{code:e,message:t,user_message:t,retryable:!1,stage:r,...a?{details:a}:{}}}async function tz(e){let t,r,a,n,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===(a=void 0===t?r:void 0===r?t:Math.min(t,r))?void 0:Math.max(0,a)),p=tW("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=tW("TOOL_EXEC_TIMEOUT",`Tool execution timed out after ${c}ms`);g.push(new Promise((t,r)=>{n=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{n&&clearTimeout(n),null==s||s(),null==i||i()}}function tV(e){return e?String(e):e3}function tG(e,t,r){return r?{type:e,message:t,error:r}:{type:e,message:t}}let tK={simulator_manifest_load_failed:"Manifest",simulator_skill_load_failed:"Skill",local_mcp_tools_load_failed:"MCP",simulator_chat_fetch_failed:"对话接口"};function tJ(e,t){return e?{kind:"pages",item:e,...t?{routeUrl:t}:{}}:null}function tX(e,t){if(!t)return null;try{return tJ(eL({url:t},e).entry,t)}catch{return null}}function tQ(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):eK(r).slice(0,1e3))||e.status}function tZ(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 tY(e,t){let r=eH(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 t0(e,t){if(!eH(t))return e;let r=eH(e.applet)?e.applet:{},a=eH(t.applet)?t.applet:{},n=Array.isArray(r.tools)?r.tools:[],s=Array.isArray(a.tools)?a.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 a.name&&a.name||"";if(s.length>0)for(let e of[...n,...s])eH(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}:{},...eH(t.mcp_server)?{mcp_server:t.mcp_server}:{},...eH(t.tools)?{tools:t.tools}:{},...eH(t.entities)?{entities:t.entities}:{},...eH(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 t1{fetcher;simulatorFetcher;historyMaxTurns;simulatorAppKey;simulatorAppName;simulatorSkill;simulatorManifest;simulatorMaxStep;simulatorMcpServers;simulatorMcpServerProvider;simulatorToolExecutor;listeners=new Set;activeSimulatorRun=null;resourceUrlVersion;hasSimulatorManifestStateValue=!1;simulatorManifestStateValue;simulatorManifestStatePromise;simulatorRunSeq=0;destroyed=!1;state;constructor(e={}){const t=tV(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 ey({manifestVersion:"3.0",packageName:"",appId:"",versionCode:"",applet:{appletId:"",appRuntimeEntry:"",digest:"",pages:[]},widgets:[]}),pages:[],widgets:[],pageSelection:null,widgetSelection:null,simulator:function(e){return{endpoint:e7(e),messages:[],streamStatus:"idle",toolCalls:[],traceEvents:[]}}(e.simulatorEndpoint),status:tG("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 ey(t0(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=tV(e??this.state.manifestUrl);this.setState({...this.state,manifestUrl:r,status:tG("loading",`Loading manifest ${r}`)});try{var a,n,s,i,o,l,d;let e,t,u,c,p,m=await e_(r,{fetcher:this.fetcher}),h=await this.mergeSimulatorManifestForState(m),g=h.pages,f=h.widgets,v=tX(h,null==(a=this.state.pageSelection)?void 0:a.routeUrl)??(o=h,l=g,d=this.state.pageSelection,e=l.filter(e5),t=null==d?void 0:d.item.id,u=function(e,t){if(null==t?void 0:t.trim())try{return e.getPageEntry(t)}catch{return}}(o,o.raw.applet.appletEntry),tJ((t?e.find(e=>e.id===t):void 0)??(u&&e5(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])),y=(n=this.state.widgetSelection,c=f.filter(e5),(s=((p=null==n?void 0:n.item.widgetId)?c.find(e=>e.widgetId===p):void 0)??c[0])?{kind:"widgets",item:s}:null);return i={resolveManifestUrl:()=>r,resourceUrlVersion:this.resourceUrlVersion},eC.configure(i),this.setState({...this.state,manifestUrl:r,manifest:h,pages:g,widgets:f,pageSelection:v,widgetSelection:y,status:tG("ready",v||y?`Loaded manifest ${r}`:`Manifest has no entries ${r}`)}),this.state}catch(r){let e=r instanceof Error?r:Error(String(r));throw this.setState({...this.state,manifestUrl:t,status:tG("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:tG("error",t.message,t)}),t}this.setState({...this.state,pageSelection:{kind:"pages",item:t},status:tG("ready",`Selected page ${t.id}`)})}navigateToPage(e){this.assertActive();try{let t=tX(this.state.manifest,e);if(!t)throw Error(`Unknown pages route: ${e}`);this.setState({...this.state,pageSelection:t,status:tG("ready",`Navigated page ${t.item.id}`)})}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.setState({...this.state,status:tG("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:tG("error",t.message,t)}),t}this.setState({...this.state,widgetSelection:{kind:"widgets",item:t},status:tG("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=te("reload");this.resourceUrlVersion=t,this.clearSimulatorManifestStateValue(),eC.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 a=te("local_msg"),n=te("idem"),s=te("trace"),i=Date.now(),o=this.state.simulator,l=this.state.manifest.raw,d={messageId:a,localMessageId:a,traceId:s,role:"user",contentType:"text",text:r,blocks:[{blockId:te("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=tZ(w,this.state.manifest.appId),x=tY(w,this.state.manifest.name);if(!this.isSimulatorRunCurrent(u))return;let I=await this.resolveSimulatorSkillForQuery(s,t);if(!this.isSimulatorRunCurrent(u))return;let C={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},E=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider(C):this.simulatorMcpServers;if(!this.isSimulatorRunCurrent(u))return;this.appendSimulatorDebugEvent({event:"simulator_query_mcp_resolved",trace_id:s,elapsed_ms:Date.now()-i,mcp_server_count:E.length,mcp_servers:E.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:n,localMessageId:a,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:E,traceId:s}).messages,m=c.toolCalls,h=c.historyMaxTurns,e=p.slice(-Math.max(0,2*h)).map(e=>{var t,r,a;let n,s,i,o=(t=e,(n=m.filter(e=>e.replyMessageId===t.messageId&&tH(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?n:(t.toolCalls??[]).filter(e=>tH(e.status))),l=(r=e,(s=m.filter(e=>e.replyMessageId===r.messageId&&tH(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=(a=e).text?a.text:a.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,a;let n=eG(null==(t=e.debug)?void 0:t.props_json),s=tF(e.card_id),i=tF(null==n?void 0:n.applet_id)||tF(e.app_id),o=tF(null==n?void 0:n.entity_id)||tF(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==(a=e.state)?void 0:a.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:tB,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:eK(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:eK(e.input_schema_json)}))}))}],web_capabilities:{supports_debug_event:!0}});if(await tm({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(a){if(tD(a))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=tL(a,"query_stream"),t=this.getSimulatorQueryFailureDiagnosis(s,a),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"}}),a}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 a=te("req_tool"),n=te("reply_tool"),s=te("tool_call"),i=te("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:a,replyMessageId:n,toolCallId:s,toolName:r,serverId:d,appKey:this.simulatorAppKey||tZ(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.params,argumentsJson:e.params?t_(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:a,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 tz({executor:this.simulatorToolExecutor,input:this.createToolExecutorInput(u),record:u})}catch(r){let e=tL(r,"tool_execute");t={status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||tD(r)?"cancelled":"failed",error:e}}return this.updateToolCall(s,{status:t.status,updatedAtMs:Date.now(),error:t.error,resultSummary:tQ(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:a,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,a,n,s;this.assertActive();let i=Date.now(),o=(a=e.result??(e.error?{error:e.error.message}:{}),s=(n=e.raw_mcp_result_json)||e.raw_result_text||eK(e.error?{error:e.error.message,detail:e.error}:a),{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:n||s,structured_json:eK(a)},raw_result_text:s,raw_mcp_result_json:n||"",miniapp:e.miniapp,timing:e.timing,trace:{trace_id:e.trace.trace_id,component:tB,stage:"tool_report",sampled:e.trace.sampled??!0},ext:{reported_by:tB}});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:t_(o),endpoint:this.state.simulator.endpoint});try{r=await th({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,result:o,signal:t})}catch(r){let t=tc(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:eJ(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,a=void 0!==t&&0!==t&&"0"!==t;if(!r&&!a)return;let n="string"==typeof e.message&&e.message?e.message:a?`Simulator tool result rejected with code ${String(t)}`:"Simulator tool result was not accepted",s=e8(e)[0];return tW("TOOL_RESULT_REJECTED",s?`${n} (x-tt-logid: ${s})`:n,"tool_result_submit",{gateway_response:e,...a?{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(!eH(t))return{status:"invalid_widget_data",message:"widgetData must be a JSON object"};let r=tT(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 a={...t,status:"running",updatedAtMs:Date.now()};null==r||r.pendingApprovalToolCallIds.delete(e),this.updateToolCall(e,{status:a.status,updatedAtMs:a.updatedAtMs}),await this.executeSimulatorToolCall(a,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 a=this.getSimulatorToolCallRun(r);if(void 0!==r.runId&&!a)return void this.cancelStaleSimulatorToolCall(r);let n=this.createToolExecutorInput(r),s=tW("TOOL_EXEC_REJECTED",t),i=Date.now();null==a||a.pendingApprovalToolCallIds.delete(e);try{await this.submitExecutedToolResult(n,{status:"rejected",error:s},i,null==a?void 0:a.streamAbortController.signal),this.updateToolCall(e,{status:"rejected",updatedAtMs:Date.now(),error:s,resultSummary:t})}catch(n){if(a&&!this.isSimulatorRunCurrent(a))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=tL(n,"tool_result_submit");throw this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:r.trace.trace_id,tool_call_id:e,summary:eJ(n)}),this.updateToolCall(e,{status:"failed",updatedAtMs:Date.now(),error:t}),n}finally{a&&this.releaseSimulatorRun(a)}}getState(){return this.state}subscribe(e){return this.assertActive(),this.listeners.add(e),()=>{this.listeners.delete(e)}}getResourceUrl(e){return(this.assertActive(),e)?eb(this.state.manifestUrl,e)??null: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){if(!this.isSimulatorRunCurrent(t))return;let r=this.state.simulator.activeRequestId;if(r&&e.request_id!==r&&"ack"!==e.event_type&&"debug"!==e.event_type)return;let{state:a,toolCall:n,cardRefresh:s}=function(e,t,r){var a,n,s,i,o,l,d,u,c,p,m,h,g,f;let v,y,_,b,w,S,x,I,C,E,k,N,R={...e,activeReplyMessageId:t.reply_message_id??e.activeReplyMessageId},T=!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)?R:tO(R,(N=t.received_at_ms??Date.now(),{display:"debug"===(a=t).event_type?tb(a.payload)??{category:"debug",detail:tM(a),phase:"event",title:"Debug"}:{category:tP(a),detail:tM(a),phase:tj(a.event_type),title:tA(a)},id:t.event_id,timestamp:N,payload:(n=t,s=N,v=tP(n),y=tj(n.event_type),_={event:n.event_type,category:v,phase:y,received_at_ms:s,server_timestamp_ms:n.created_at_ms,title:tA(n),detail:tM(n),trace:n.trace},"debug"===n.event_type?{..._,event:eX(n.payload,"event")||"debug",title:eY(eX(n.payload,"title")||eX(n.payload,"event")||"Debug Event"),summary:eX(n.payload,"summary"),elapsed_ms:eQ(n.payload,"elapsed_ms"),redaction_level:eX(n.payload,"redaction_level")}:"heartbeat"===n.event_type?{..._,server_time_ms:eQ(n.payload,"server_time_ms"),message:eX(n.payload,"message")}:"answer_finish"===n.event_type?{..._,status:eX(n.payload,"status"),finish_reason:eX(n.payload,"finish_reason"),usage:n.payload.usage}:{..._,...n.payload})}));switch(t.event_type){case"ack":return{state:(i=T,b=eX((o=t).payload,"local_message_id"),w=eX(o.payload,"query_message_id"),S=eX(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=T,I=eX((d=t).payload,"message_id")||d.reply_message_id||te("reply"),{...l,activeReplyMessageId:I,messages:tk(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 a=eX(t.payload,"block_id")||`block_text_${t.seq}`,n=eX(t.payload,"delta"),s=eX(t.payload,"op")||"append";if("append"!==s&&"replace"!==s)return e;let i=tk(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:tN(i,r,e=>({...e,text:"replace"===s?n:`${e.text}${n}`,blocks:function(e,t,r,a){if(!e.find(e=>"text"===e.type&&e.blockId===t)){let n=e[e.length-1];return"append"===a&&(null==n?void 0:n.type)==="text"?e.map(e=>e===n?{...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"===a?r:`${e.text}${r}`}:e)}(e.blocks,a,n,s)}))}}(T,t)};case"card_delta":return function(e,t){var r;let a=function(e){let t=eH(e.card)?e.card:{},r=eH(t.state)?t.state:{},a=eX(e,"card_id"),n=eX(r,"widget_id");if("update_state"!==eX(e,"op")||"miniapp_history_refresh"!==eX(t,"card_type")||"fixed_style"!==eX(r,"refresh_to")||!a||!n)return;let s=eX(r,"url")||eX(r,"schema");return{cardId:a,state:r,widgetData:{...s?{url:s}:{},...eX(r,"title")?{title:eX(r,"title")}:{},...eX(r,"detailText")?{detailText:eX(r,"detailText")}:{}},widgetId:n}}(t.payload);if(a){let t=tT(e.messages,a.cardId,e=>{let t=eH(e.state)?e.state:{};if("fixed"!==eX(t,"lifecycle_state"))return{...e,render_data:{viewData:a.widgetData},widget_id:a.widgetId,state:{...t,...a.state,lifecycle_state:"fixed"}}});return{state:{...e,messages:t.messages},cardRefresh:{cardId:a.cardId,status:t.updated?"updated":t.found?"already_fixed":"not_found"}}}let n=t.reply_message_id??e.activeReplyMessageId;if(!n)return{state:e};let s=function(e){let t,r=e.card;if(!eH(r))return{};let a=eG(r.props_json)??{},n=function(e){let t,r;if("miniapp_packet_10066"!==e.card_type)return;let a=eG(e.props_json)||eG(e.render_data_json)||(eH(e.render_data)?eG(e.render_data.content_for_display):void 0)||{};return eX(a,"permission_data")||((r=(Array.isArray(null==(t=eH(a.structuredContent)?a.structuredContent:void 0)?void 0:t.entity_list)?t.entity_list:[]).find(e=>eH(e)&&(Array.isArray(e.grantingList)||eH(e._meta)&&!0===e._meta.is_permission)))&&eH(r)?JSON.stringify(r):void 0)}(r),s=tC(n),i=eH(a.extra)?a.extra:{},o=Object.keys(a).length>0?(t=eG(a.widget_data))?{viewData:t}:eH(a.viewData)?{viewData:a.viewData}:{viewData:a}:void 0,l={...eH(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 a.widget_id?{widget_id:a.widget_id}:{},..."string"==typeof a.applet_id?{app_id:a.applet_id}:{},..."string"==typeof a.entity_id?{entity_id:a.entity_id}:{},...Object.keys(l).length>0?{source:l}:{},...s?{card_type:"permission_apply",fallback_text:r.fallback_text||"需要授权后继续",render_data:{grantingData:s,permissionData:n},title:r.title||tE(s)}:o?{render_data:o}:{},debug:{...eH(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=eX(t.payload,"block_id")||s.card_id||(r=`card_${t.seq}`,s.card_id||s.title||r),o=eX(t.payload,"op")||"append";if("append"!==o&&"replace"!==o)return{state:e};let l=tk(e.messages,n,t.created_at_ms,t.request_id,t.trace.trace_id);return{state:{...e,messages:tN(l,n,e=>({...e,contentType:"mixed",blocks:tR(e.blocks,i,s,o)}))}}}(T,t);case"content_block":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let a=function(e,t){for(let[r,a]of(Array.isArray(e.content_block)?e.content_block:Array.isArray(e.contentBlock)?e.contentBlock:[]).entries()){let n=function(e){if(!eH(e))return;let t=eH(e.content)?e.content:e,r=eH(t.permission_apply_block)?t.permission_apply_block:eH(t.permissionApplyBlock)?t.permissionApplyBlock:void 0;return r?eX(r,"permission_data")||eX(r,"permissionData"):""}(a),s=tC(n);if(!s)continue;let i=eH(a)&&eX(a,"block_id")||eH(a)&&eX(a,"blockId")||`permission_apply_${t.seq}_${r}`;return{blockId:i,card:{card_id:i,card_type:"permission_apply",fallback_text:"需要授权后继续",render_data:{grantingData:s,permissionData:n},title:tE(s)},op:eX(e,"op")||"append"}}}(t.payload,t);if(!a||"append"!==a.op&&"replace"!==a.op)return e;let n=tk(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:tN(n,r,e=>({...e,contentType:"mixed",blocks:tR(e.blocks,a.blockId,a.card,a.op)}))}}(T,t)};case"tool_call":return function(e,t,r){let a,n=eX(t.payload,"tool_call_id"),s=eX(t.payload,"tool_name"),i=eX(t.payload,"server_id"),o=eX(t.payload,"arguments_json"),l=t.reply_message_id??e.activeReplyMessageId;if(!n||!s||!i||!l)return{state:e};let d=("boolean"==typeof(a=t.payload.requires_user_approval)?a: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:n,toolName:s,serverId:i,appKey:eX(t.payload,"app_key")||void 0,arguments:eH(t.payload.arguments)?t.payload.arguments:eG(o),argumentsJson:o||void 0,mcpHeaders:function(e){if(!eH(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:eQ(t.payload,"timeout_ms"),deadlineMs:eQ(t.payload,"deadline_ms")},p=tN(tk(e.messages,l,t.created_at_ms,t.request_id,t.trace.trace_id),l,e=>({...e,toolCalls:t$(e.toolCalls??[],c)})),m={...e,messages:p,toolCalls:[...e.toolCalls.filter(e=>e.toolCallId!==n),c]};return r.hasToolExecutor?{state:m,toolCall:c}:{state:tO(m,{id:te("trace"),timestamp:Date.now(),payload:{event:"tool_executor_missing",request_id:c.requestId,trace_id:c.trace.trace_id,tool_call_id:n,tool_name:s,summary:"No local simulator tool executor is configured"}})}}(T,t,r);case"tool_status":return{state:function(e,t){let r=eX(t.payload,"tool_call_id"),a=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""}}(eX(t.payload,"status"));if(!r||!a)return e;let n=eQ(t.payload,"progress"),s=eX(t.payload,"message"),i=t.payload.error?tL(t.payload.error,"tool_execute"):void 0,o=tq(e,r,{status:a,updatedAtMs:t.created_at_ms,...void 0===n?{}:{progress:n},...s?{message:s}:{},...i?{error:i}:{}}),l=o.toolCalls.find(e=>e.toolCallId===r);return l?{...o,messages:tN(o.messages,l.replyMessageId,e=>({...e,toolCalls:t$(e.toolCalls??[],l)}))}:o}(T,t)};case"trace_event":case"debug":default:return{state:T};case"heartbeat":return{state:(u=T,c=t,{...u,lastHeartbeatMs:eQ(c.payload,"server_time_ms")??c.created_at_ms})};case"answer_finish":return{state:(p=T,m=t,{...p,answerFinish:{messageId:m.reply_message_id,status:eX(m.payload,"status"),finishReason:eX(m.payload,"finish_reason"),usage:eH(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=eX(t.payload,"message_id")||t.reply_message_id;if(!r)return e;let a=eX(t.payload,"status")||"completed";return{...e,messages:tN(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"}}(a)}))}}(T,t)};case"reply_finish":return{state:(h=T,E="completed"===(C=eX(t.payload,"status")||"completed")||"finished"===C?"completed":"cancelled"===C?"cancelled":"error",{...h,activeRequestId:void 0,activeReplyMessageId:void 0,messages:tU(h.messages,E),streamStatus:E})};case"stream_error":return{state:(g=T,k=tL((f=t).payload.error??f.payload,eX(f.payload,"stage")||"stream"),{...g,activeRequestId:void 0,error:k,messages:tU(g.messages,"error"),streamStatus:"error"})}}}(this.state.simulator,e,{hasToolExecutor:!!this.simulatorToolExecutor,runId:t.id});this.updateSimulatorState(()=>a),(null==s?void 0:s.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:s.cardId}),n&&(n.requiresUserApproval?t.pendingApprovalToolCallIds.add(n.toolCallId):this.executeSimulatorToolCall(n,t))}async executeSimulatorToolCall(e,t){let r;if(!this.simulatorToolExecutor)return;let a=this.simulatorToolExecutor;if(t&&!this.isSimulatorRunCurrent(t))return;let n=Date.now(),s=this.createToolExecutorInput(e),i=t?new AbortController:void 0;t&&i&&t.toolAbortControllers.add(i);try{r=await tz({executor:a,input:s,record:e,signal:null==i?void 0:i.signal})}catch(t){let e=tL(t,"tool_execute");r={status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||tD(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,n,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:tQ(r),structuredResultSummary:r.result,isMiniApp:r.miniapp&&"boolean"==typeof r.miniapp.is_mini_app?r.miniapp.is_mini_app:void 0})}catch(a){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=tL(a,"tool_result_submit");this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,summary:eJ(a),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:te("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||tZ(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 a=Date.now(),n=void 0!==t.manifest,s=n?"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=n?{found:!1,value:void 0}:this.takeSimulatorManifestStateValue(),o=n?t.manifest:i.found?i.value:"function"==typeof this.simulatorManifest?await this.simulatorManifest():this.simulatorManifest,l=o?t0(r,o):r;return this.appendSimulatorDebugEvent({event:"simulator_manifest_loaded",trace_id:e,elapsed_ms:Date.now()-a,source:s,manifest:l}),l}catch(t){return this.appendSimulatorDebugEvent({event:"simulator_manifest_load_failed",trace_id:e,elapsed_ms:Date.now()-a,error:eJ(t),source:s}),r}}async resolveSimulatorSkillForQuery(e,t){let r=Date.now(),a=void 0===t.skill?"debugger_option":"query_option";this.appendSimulatorDebugEvent({event:"simulator_skill_load_started",trace_id:e,source:a});try{let n=t.skill??("function"==typeof this.simulatorSkill?await this.simulatorSkill():this.simulatorSkill)??"";return this.appendSimulatorDebugEvent({event:n.trim()?"simulator_skill_loaded":"simulator_skill_empty",trace_id:e,elapsed_ms:Date.now()-r,skill_length:n.length,source:a}),n}catch(t){return this.appendSimulatorDebugEvent({event:"simulator_skill_load_failed",trace_id:e,elapsed_ms:Date.now()-r,error:eJ(t),source:a}),""}}async resolveDirectToolCallServerId(e,t,r){var a;let n=null==t?void 0:t.trim();if(n)return n;let s=this.state.manifest.raw,i=this.simulatorAppKey||tZ(s,this.state.manifest.appId)||void 0,o=this.simulatorAppName||tY(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==(a=l[0])?void 0:a.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=tW("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,a){let n=Date.now();await this.submitToolResult({...e,...t,timing:{started_at_ms:r,ended_at_ms:n,duration_ms:n-r,attempt:1}},a)}updateToolCall(e,t){this.updateSimulatorState(r=>tq(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 a=eH(t.payload)?t.payload:{},n=tK["string"==typeof a.event?a.event:""];n&&function(e){let t=eH(e.trace)?e.trace:{},r=e.trace_id??t.trace_id;return"string"==typeof r?r:""}(a)===e&&"Failed to fetch"===("string"==typeof a.error?a.error:"")&&r.add(n)}if(r.size>=3)return{code:"DEBUG_SERVER_UNREACHABLE",confidence:"high",failed_services:[...r],summary:"调试 Dev Server 或本机网络不可达",suggestion:"检查调试 Dev Server 是否运行,以及浏览器能否访问当前调试端口。"};let a=tc(t),n="number"==typeof(null==a?void 0:a.status)?a.status:void 0;return 404===n?{code:"SIMULATOR_ENDPOINT_NOT_FOUND",confidence:"high",status:n,summary:"模拟器接口未配置或路由不存在",suggestion:"检查 simulator、manifest、skill 或 MCP 的接口地址与代理路由。"}:void 0!==n&&n>=500?{code:"SIMULATOR_ENDPOINT_SERVER_ERROR",confidence:"high",status:n,summary:`模拟器接口服务异常(HTTP ${n})`,suggestion:"接口已可达,但服务端或其上游依赖异常;请查看响应内容和服务端日志。"}:"Failed to fetch"===eJ(t)?{code:"SIMULATOR_ENDPOINT_UNREACHABLE",confidence:"unknown",summary:"无法连接模拟器接口",suggestion:"可能是接口服务未启动、端口不可达、浏览器网络异常或 CORS 被拦截。"}:void 0}appendSimulatorDebugEvent(e){let t=e8(e),r={display:tb(e),id:te("trace"),timestamp:Date.now(),payload:function(e,t){if(!eH(e))return e;let r=tw(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 t2="iphone-13",t3=[{key:t2,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}}],t4=[{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}],t5={key:"mobile-393",label:"393px",width:393,density:3};function t6(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t3["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 t8(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t5,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 t7(e,t){try{let e=t.trim()?JSON.parse(t):{};if(eH(e))return e;throw Error("expected a JSON object")}catch(t){throw Error(`${e}: ${t.message}`)}}function t9(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 re(e,t){let r=(0,eq.H)(e);return r.render((0,s.jsx)(t9,{onReopen:t})),()=>r.unmount()}function rt(e){return e??document.body}async function rr(e,t){var r;let a,n=rt(t),s=new CustomEvent("doubao:multi-media-broadcast",{bubbles:!0,composed:!0,detail:e});n.dispatchEvent(s),window.dispatchEvent(new CustomEvent("doubao:multi-media-broadcast",{detail:e}));let i=(r=e.mediaId,a=Array.from(rt(t).querySelectorAll("audio,video")),r?a.filter(e=>e.id===r||e.dataset.mediaId===r):a);return await Promise.all(i.map(t=>"play"===e.action?t.play():Promise.resolve(t.pause()))),{affected:i.length}}let ra=[],rn=new Map,rs=!1;function ri(e){for(let t of e)URL.revokeObjectURL(t),rn.delete(t)}function ro(){for(let e of ra.splice(0))ri(e)}function rl(e){var t;let r=rn.get(e);if(r)return r;let a=e.match(/^data:image\/([^;,]+)/i);if(null==a?void 0:a[1])return a[1].split("+")[0].toLowerCase();let n=e.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/);return(null==n||null==(t=n[1])?void 0:t.toLowerCase())??""}function rd(e){return new Promise((t,r)=>{let a=new Image;a.onload=()=>t(a),a.onerror=()=>r(Error(`failed to load image: ${e}`)),a.src=e})}async function ru(e){if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let t=await rd(e.src);return{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height,orientation:"up",path:e.src,type:rl(e.src)}}async function rc(e){if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let t=await rd(e.src),r=document.createElement("canvas"),a=e.compressedWidth??t.naturalWidth??t.width,n=e.compressedHeight??t.naturalHeight??t.height;r.width=a,r.height=n;let s=r.getContext("2d");if(!s)throw Error("canvas 2d context is not available");return s.drawImage(t,0,0,a,n),{tempFilePath:r.toDataURL("image/jpeg",Math.min(100,Math.max(0,e.quality??80))/100)}}let rp=new Map,rm={"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 rh(e,t){return`${e||"unknown-app"}:${t}`}function rg(e){return rm[e]??{description:"需要获得你的授权后才能继续使用此功能。",title:`申请获取你的${e.replace(/^scope\./,"")||"相关"}权限`}}async function rf(e){var t;let{appId:r,appIcon:a,appName:n,presenter:s,scope:i,skipDialogIfDenied:o=!1}=e,l=r||"unknown-app",d=rp.get(rh(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:a,appName:n||"智能服务",scope:i,...rg(i)});return t=u?"granted":"denied",rp.set(rh(l,i),t),u}function rv(){throw Error("Simulator UI presenter is unavailable")}function ry(){return{chooseLocation:async()=>rv(),hideLoading:rv,hideToast:rv,showActionSheet:async()=>rv(),showBottomSheet:async()=>rv(),showLoading:rv,showModal:async()=>rv(),showToast:rv}}function r_(){n&&window.removeEventListener("beforeunload",n),n=void 0}let rb=new Set;function rw(){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}}function rS(e,t){let{geolocation:r}=navigator;if(!r)throw Error("Geolocation is not available in the current browser");let a=r.watchPosition(e,t,rw());return rb.add(a),()=>{r.clearWatch(a),rb.delete(a)}}async function rx(e){return rf({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.userLocation",skipDialogIfDenied:!0})}function rI(e){let t={};return e.forEach((e,r)=>{t[r]=e}),t}function rC(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 a=(null==(r=t.get("content-type"))?void 0:r.toLowerCase())??"";if(a.includes("application/x-www-form-urlencoded")&&"object"==typeof e){let t=new URLSearchParams;return Object.entries(e).forEach(e=>{let[r,a]=e;t.set(r,String(a))}),t.toString()}return a.includes("application/json")||"object"==typeof e?JSON.stringify(e):String(e)}(e.data,r):void 0,headers:rI(r),method:t,url:"string"==typeof e.url?e.url:""}}async function rE(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rC(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}),a=e.dataType??"json",n="arraybuffer"===a?await r.arrayBuffer():await r.text().then(e=>"string"===a||0===e.length?e:JSON.parse(e));return{statusCode:r.status,header:rI(r.headers),data:n}}let rk=new Set,rN=new WeakSet,rR=0;function rT(){return navigator.connection}function rM(){var e;let t,r=rT(),a=null==r?void 0:r.effectiveType;return{isConnected:!1!==navigator.onLine,networkType:(t=null==(e=rT())?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"===a||"2g"===a}}function rA(){return{timestamp:performance.now()/1e3,wallTime:Date.now()/1e3}}function rP(e){for(let t of rk)try{t(e)}catch(e){console.error("Failed to record doubao.request in Chrome DevTools",e)}}function rj(){let e=rM();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function rD(e,t){let r=null==e?void 0:e[t];return"string"==typeof r?r.trim():""}async function rL(e,t,r){return rf({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:t,skipDialogIfDenied:r})}let rO="app_id_missing",rU="cashier_unavailable",rq="create_order_failed",r$="developer_order_exists",rB="login_credential_invalid",rF="login_credential_missing",rH="login_authorization_failed",rW="login_authorization_unsupported",rz="login_state_invalid",rV="login_session_unavailable",rG="payment_amount_invalid",rK="payment_authorization_invalid",rJ="payment_cancelled",rX="payment_data_invalid",rQ="payment_data_missing",rZ="payment_data_unavailable",rY="payment_data_unavailable_with_sign",r0="payment_data_unsupported",r1="payment_failed",r2="payment_method_unavailable",r3="payment_order_invalid",r4="payment_parameter_missing",r5="payment_params_invalid",r6="payment_params_unavailable",r8="payment_sign_params_invalid",r7="payment_sign_params_unavailable",r9="payment_incomplete",ae="privacy_state_unavailable",at="privacy_authorization_failed",ar="pre_order_failed",aa="phone_authorization_failed",an="request_format_invalid",as="request_params_invalid",ai="sandbox_resource_not_found",ao="sandbox_service_unavailable",al="sandbox_session_expired",ad="sandbox_session_forbidden",au="sign_order_failed",ac="sign_order_already_exists",ap="sign_order_not_found",am="sign_order_params_invalid",ah="sign_order_status_invalid",ag="sign_order_create_failed",af="sign_page_params_invalid",av="sign_page_unavailable",ay="sign_page_data_unavailable",a_="请求暂时无法完成,请稍后重试;如持续失败,请提供 log_id";class ab extends Error{code;details;constructor(e,t={}){super(aS(e,t)),this.code=e,this.details=t,this.name="SandboxError"}}class aw extends Error{remoteCode;options;constructor(e,t,r={}){super(t),this.remoteCode=e,this.options=r,this.name="SandboxRemoteError"}}function aS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(e){case rO:return"当前未配置应用 ID,请先完成应用配置。";case rU:return"无法打开模拟器收银台,请刷新模拟器后重试。";case rq:return"暂时无法创建订单,请检查签名参数后稍后重试;如持续失败,请提供 log_id";case r$:return"开发者订单号已存在,请查询原订单";case rB:return"登录失败:登录凭证已过期或已使用,请重新发起登录。";case rF:return"登录失败:成功登录回调未携带业务登录凭证,请检查登录实现。";case"login_failed":return"登录失败:无法完成模拟器登录,请检查模拟器会话后重试。";case"login_info_unavailable":return"登录信息暂时不可用,请稍后重试;如持续失败,请提供 log_id";case rH:return"暂时无法完成登录授权,请重新发起授权";case rW:return"当前 Sandbox 无法完成该授权请求,请检查授权方式和会话配置";case"login_permission_denied":return"登录失败:开发者账号没有该应用的调试权限,请检查应用归属和账号状态。";case rz:return"用户登录状态已失效,请重新登录";case rV:return"登录失败:模拟器会话不可用,请登录开发者账号后重新打开模拟器。";case"payment_already_paid":return"订单已完成支付,请勿重复提交。";case rG:return"支付金额无效,请使用最小货币单位的整数,并由业务服务端生成金额。";case rK:return"支付授权校验失败,请确认 data 和 dbAuthorization 使用同一个 dev.key 生成,并且模拟器配置了匹配的 dev.csr。";case rJ:return"已取消支付。";case rX:return"支付数据格式无效,请检查业务服务端生成的 pay_data。";case rQ:{let e=t.field?({id:"支付方式 ID",name:"支付方式名称",pay_order_no:"支付订单号",pay_status:"支付状态",trade_no:"交易号"})[t.field]||t.field:"必要字段";return`支付数据缺少${e},请检查业务服务端生成的 pay_data。`}case rZ:return"无法打开收银台:模拟器未返回支付数据,请检查订单状态和预下单响应。";case rY:return"无法打开支付签约收银台:模拟器未返回支付数据,请检查签约参数和订单状态。";case r0:return"当前支付数据不支持模拟器收银台,请检查模拟器支付配置。";case r1:return a_;case"payment_login_required":return"支付需要先登录,请完成模拟器登录并绑定支付账户后重试。";case r2:return"支付数据中没有可用的支付方式,请检查模拟器支付配置。";case"payment_order_expired":return"支付订单已过期,请重新创建订单后重试。";case r3:return"订单不存在或不属于当前应用";case r4:{let e=t.key||"该参数";return`缺少支付参数,请提供${({data:"业务服务端生成的 data",dbAuthorization:"业务服务端生成的 dbAuthorization",orderId:"requestOrder 返回的 orderId",signData:"业务服务端生成的 signData",signDbAuthorization:"业务服务端生成的 signDbAuthorization"})[e]||e}。`}case r5:return"请求参数不正确,请检查订单信息和金额";case r6:return"暂时无法获取支付参数,请检查订单号后重试;如持续失败,请提供 log_id";case r8:return"请求参数不正确,请检查订单号和签约信息";case r7:return"暂时无法获取支付参数,请稍后重试;如持续失败,请提供 log_id";case r9:return"模拟支付未完成,请检查支付方式和订单状态后重试;如持续失败,请提供 log_id";case ae:return"暂时无法读取或保存授权状态,请稍后重试";case aa:return"手机号授权失败:无法获取手机号授权凭证,请重试或使用其他登录方式。";case at:return"隐私授权失败:请刷新模拟器后重试。";case ar:return"预下单失败:模拟器未返回订单 ID,请检查业务服务端预下单响应。";case an:return"请求格式不正确,请检查后重试";case as:return"请求参数不正确,请检查必填字段和字段格式";case ai:return"未找到沙箱会话或相关资源,请重新创建后重试";case ao:return"沙箱服务暂时不可用,请稍后重试;如持续失败,请提供 log_id";case al:return"沙箱会话已过期,请重新启动调试会话";case ad:return"当前沙箱会话无权访问该应用,请检查应用和会话是否匹配";case au:return"创建签约订单失败:模拟器未返回签约订单 ID,请检查签约参数。";case ac:return"开发者签约单号已存在,请查询原签约单";case ap:return"签约单不存在或不属于当前应用";case am:return"签约单参数无效,请检查单号、应用和有效期";case ah:return"当前签约单状态不允许继续签约";case ag:return"暂时无法创建签约单,请检查签名参数后重试;如持续失败,请提供 log_id";case af:return"签约单参数无效,请检查单号、应用和有效期";case av:return"暂时无法获取签约页,请稍后重试;如持续失败,请提供 log_id";case ay:return"打开签约页面失败:模拟器未返回签约数据,请检查签约订单状态。";default:return a_}}function ax(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 aI(e,t){if(400===t)return an;switch(e){case 400:return as;case 401:return al;case 403:return ad;case 404:return ai;case 500:return ao;default:return}}function aC(e,t,r){switch(e){case 500:return"payment"===r?r9:ao;case 4201:return rK;case 0x1dcd6501:if(t===ar)return r5;if(t===rY)return r8;if(t===au)return am;if(t===ay)return af;return r5;case 0x1dcdb322:return r$;case 5e8:if(t===ar)return rq;if(t===rY)return r7;if(t===au)return ag;if(t===ay)return av;return r6;case 0x1dcdb325:return t===ay?ap:r3;case 0x1dcdb327:return ac;case 0x1dcdb328:return ah;default:return void 0===e||0===e?t:r1}}function aE(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("code"===r.errorField){let t=aI(e,r.httpStatus);if(t)return t}if("data.error_code"===r.errorField&&40001===e)return rW;if("err_code"===r.errorField){if(401===e)return as;if(402===e)return rz;if(501===e)return ae}switch(e){case -1:return rV;case 1001:return"phone"===t?aa:rB;case 4001:return rB;case 2001:return at;case 502:return rH;case 402:return rz;case 501:return ae;case 400:return as;default:return ao}}function ak(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a_;if(e instanceof ab)return aS(e.code,e.details);if(e instanceof aw){let t="code"===e.options.errorField?aI(e.remoteCode,e.options.httpStatus):void 0;return aS("payment"===e.options.operation?aC(e.remoteCode,r1,e.options.operation):t||aC(e.remoteCode,r1))}return t}function aN(e,t){return e instanceof ab?e:new ab(e instanceof aw?aE(e.remoteCode,t,e.options):ao)}function aR(e,t){let r=ax(e.err_code);if(void 0!==r&&0!==r)throw new ab(aE(r,t,{errorField:"err_code"}))}function aT(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:{code:ax(e.code),logId:"string"==typeof e.log_id?e.log_id:void 0}}function aM(e,t){let{code:r,logId:a}=aT(e);if(void 0!==r&&0!==r)throw new aw(r,`Sandbox 请求失败,错误码为 ${String(r)}。`,{errorField:"code",httpStatus:t,logId:a})}let aA="web-sdk-debugger",aP=[{id:"douyin",name:"抖音支付"}];async function aj(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:a,logId:n}=aT(r);if(!t.ok)throw new aw(a,`Sandbox 代理请求失败,HTTP 状态码为 ${t.status}。`,{errorField:"code",httpStatus:t.status,logId:n});return aM(r,t.status),r}let aD=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||{},a=this.genBaseURL("/app_developer/api/user/basic"),n={user_name:r.user_name,user_id:r.user_id};return this.request({url:a,method:"GET",params:n},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"),a={user_name:e.user_name};return this.request({url:r,method:"PUT",data:a},t)}GetInviteMemberList(e,t){let r=e||{},a=this.genBaseURL("/app_developer/api/member/member_list"),n={app_key:r.app_key,user_name:r.user_name,page_size:r.page_size,page_num:r.page_num};return this.request({url:a,method:"GET",params:n},t)}SendInviteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/invite/send_invite`),a={role_code:e.role_code,target_user_id:e.target_user_id};return this.request({url:r,method:"POST",data:a},t)}UpdateAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta/update`),a={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:a},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"),a={user_code:e.user_code,client_name:e.client_name};return this.request({url:r,method:"POST",data:a},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`),a={csr_pem:e.csr_pem};return this.request({url:r,method:"POST",data:a},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"),a={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:a},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"),a={client_name:e.client_name};return this.request({url:r,method:"POST",data:a},t)}GetAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),a={offset:e.offset,limit:e.limit,keyword:e.keyword};return this.request({url:r,method:"GET",params:a},t)}UpdateAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),a={action:e.action,subject:e.subject};return this.request({url:r,method:"POST",data:a},t)}ExchangeDeviceToken(e,t){let r=this.genBaseURL("/app_developer/oauth/token"),a={device_code:e.device_code};return this.request({url:r,method:"POST",data:a},t)}ListApps(e,t){let r=e||{},a=this.genBaseURL("/app_developer/api/apps"),n={app_limit:r.app_limit,app_offset:r.app_offset,key_word:r.key_word,app_key:r.app_key};return this.request({url:a,method:"GET",params:n},t)}GetAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta`),a={limit:e.limit,offset:e.offset,status:e.status};return this.request({url:r,method:"GET",params:a},t)}ToolList(e,t){let r=this.genBaseURL("/developer/api/tools/list"),a={mcp_server_url:e.mcp_server_url,mcp_config:e.mcp_config};return this.request({url:r,method:"GET",params:a},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`),a={source_type:e.source_type};return this.request({url:r,method:"POST",params:a},t)}SubmitMiniAppVersionDraft(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/submit`);return this.request({url:r,method:"POST"},t)}ListMiniAppVersions(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions`),a={page:e.page,page_size:e.page_size};return this.request({url:r,method:"GET",params:a},t)}VerifyYAML(e,t){let r=this.genBaseURL("/app_developer/api/yaml/verify"),a={yaml:e.yaml,mode:e.mode,yaml_type:e.yaml_type};return this.request({url:r,method:"POST",data:a},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"),a={app_key:e.app_key};return this.request({url:r,method:"POST",data:a},t)}GetMiniAppVersionDraftPackageDownloadURL(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/download_url`),a={source_type_list:e.source_type_list};return this.request({url:r,method:"GET",params:a},t)}GetSubMerchantList(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_list"),a={org_id:e.org_id};return this.request({url:r,method:"GET",params:a},t)}AppBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/app_bind_sub_merchant`),a={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"PUT",data:a},t)}CreateSubMerchant(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/create_sub_merchant"),a={org_id:e.org_id,sub_merchant_name:e.sub_merchant_name};return this.request({url:r,method:"POST",data:a},t)}UnBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/unbind_sub_merchant`),a={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"POST",data:a},t)}GetSubMerchantCaijingUrl(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_url"),a={sub_merchant_uid:e.sub_merchant_uid};return this.request({url:r,method:"POST",data:a},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`),a={source:e.source};return this.request({url:r,method:"GET",params:a},t)}UpdateAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/update_callback_conf`),a={source:e.source,callback_address:e.callback_address};return this.request({url:r,method:"PUT",data:a},t)}CreateOrganization(e,t){let r=this.genBaseURL("/app_developer/api/organization"),a={name:e.name};return this.request({url:r,method:"POST",data:a},t)}UpdateOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/update`),a={name:e.name};return this.request({url:r,method:"POST",data:a},t)}FinishMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/finish`),a={upload_token:e.upload_token,size:e.size,sha256:e.sha256};return this.request({url:r,method:"POST",data:a},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"),a={org_code:e.org_code};return this.request({url:r,method:"POST",data:a},t)}StartMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/start`),a={sha256:e.sha256};return this.request({url:r,method:"POST",data:a},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`),a={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:a},t)}DeleteAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/delete`),a={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:a},t)}VerifyAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_verify`),a={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:a},t)}CreateAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/create`),a={domain:e.domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:a},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"),a={app_key:e.app_key};return this.request({url:r,method:"POST",data:a},t)}SandboxUpdateMessageCardWidgetData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/update_message_card_widget_data"),a={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:a},t)}SandboxCreateSignOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/create_sign_order"),a={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:a},t)}SandboxGetOrderPaymentWithSign(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment_with_sign"),a={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:a},t)}SandboxRequestOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/request_order"),a={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:a},t)}SandboxGetSignPageData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_sign_page_data"),a={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:a},t)}SandboxGetMessageInfoByMixtureCardID(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/get_message_info_by_mixture_card_id"),a={mixture_card_id:e.mixture_card_id};return this.request({url:r,method:"POST",data:a},t)}SandboxGetOrderPayment(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment"),a={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:a},t)}SandboxApiGetUserAppsPermissionDetail(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/detail"),a={applets_list:e.applets_list};return this.request({url:r,method:"POST",data:a},t)}SandboxApiPostUserAppsPermission(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/post"),a={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:a},t)}SandboxApiGetUserAppsPermissionRecord(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/record"),a={applet_id:e.applet_id};return this.request({url:r,method:"POST",data:a},t)}SandboxApiExchangeCode(e,t){let r=e||{},a=this.genBaseURL("/app_developer/api/sandbox/jsb/oauth/token"),n={app_key:r.app_key,code:r.code,device_id:r.device_id,version_tag:r.version_tag};return this.request({url:a,method:"POST",data:n},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||{},a=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy_login/check"),n={app_key:r.app_key,version_tag:r.version_tag,check_type:r.check_type};return this.request({url:a,method:"POST",data:n},t)}SandboxApiAcceptPrivacy(e,t){let r=e||{},a=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy/accept"),n={app_key:r.app_key,request_id:r.request_id,device_id:r.device_id};return this.request({url:a,method:"POST",data:n},t)}SandboxApiDeleteDataObtainedByTicket(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/ticket_revoke"),a={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:a},t)}ListPublicNoticeTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates`),a={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:a},t)}SandboxIssueLoginCode(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/passport/open/auth"),a={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:a},t)}GetSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/get"),a={sandbox_session_id:e.sandbox_session_id};return this.request({url:r,method:"POST",data:a},t)}UpdateSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/update"),a={sandbox_session_id:e.sandbox_session_id,phone_num:e.phone_num,csr_pem:e.csr_pem};return this.request({url:r,method:"POST",data:a},t)}SandboxPay(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/payment/pay"),a={trade_no:e.trade_no,pay_type:e.pay_type};return this.request({url:r,method:"POST",data:a},t)}CheckDeveloperAccessWhitelist(e,t){let r=this.genBaseURL("/app_developer/api/user/whitelist/check"),a={invite_code:(e||{}).invite_code};return this.request({url:r,method:"POST",data:a},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"),a={code:e.code,nonce:e.nonce,state:e.state};return this.request({url:r,method:"GET",params:a},t)}ListBusinessTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates`),a={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:a},t)}GetBusinessTemplatesYaml(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/yaml`),a={status:e.status};return this.request({url:r,method:"GET",params:a},t)}SubmitBusinessTemplatesReview(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/submit_review`),a={template_ids:e.template_ids};return this.request({url:r,method:"POST",data:a},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||{},a=this.genBaseURL("/app_developer/api/sandbox/resources/notices/pull"),n={notice_ids:r.notice_ids,cursor:r.cursor,limit:r.limit};return this.request({url:a,method:"POST",data:n},t)}RemoveSandboxTaskFromUser(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/remove_from_user"),a={task_id:e.task_id};return this.request({url:r,method:"POST",data:a},t)}PullSandboxTasks(e,t){let r=e||{},a=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/pull"),n={task_ids:r.task_ids,cursor:r.cursor,limit:r.limit};return this.request({url:a,method:"POST",data:n},t)}}({baseURL:"",request:aj});function aL(e,t){if(!e.data)throw Error(e.message||`${t} returned empty data`);return e.data}async function aO(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return aL(await aD.PullSandboxNotices(e),"PullSandboxNotices")}async function aU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return aL(await aD.PullSandboxTasks(e),"PullSandboxTasks")}async function aq(e){return aL(await aD.RemoveSandboxTaskFromUser({task_id:e}),"RemoveSandboxTaskFromUser").removed_task}async function a$(e){let{appletId:t,granted:r,scopeName:a}=e;if(!t.trim())throw Error("appletId is required");if(!a.trim())throw Error("scopeName is required");let n=await aD.SandboxApiPostUserAppsPermission({applet_id:t,update_scope_info:{grant_status:r?1:2,scope_name:a}});if(0!==n.err_code)throw Error(n.err_msg||`Sandbox post Agentic Service permission failed with code ${String(n.err_code)}`)}function aB(e){var t;let r=(null==(t=e.getAppId)?void 0:t.call(e))||e.appId;if(!r)throw new ab(rO);return r}function aF(e,t){if(!e||"object"!=typeof e)return"";let r=e[t];return"string"==typeof r?r:""}function aH(e,t){let r=aF(e,t).trim();if(!r)throw new ab(r4,{key:t});return r}function aW(e,t){let r=e[t];if("string"!=typeof r||!r.trim())throw new ab(rQ,{field:t});return r.trim()}function az(e,t,r){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4?arguments[4]:void 0,s=ax(t.err_code),i=s??(n instanceof aw?n.remoteCode:void 0)??-1,o=t.log_id??(n instanceof aw?n.options.logId:void 0),l=n?ak(n,aS(r)):aS(aC(s,r)),d={...a?{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 aV(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return await t()}catch(t){return az(e,{},r1,r,t)}}async function aG(e,t){let r=function(e){let t;try{t=JSON.parse(e)}catch{throw new ab(rX)}if(!t||"object"!=typeof t||Array.isArray(t))throw new ab(rX);let r=t;if("sandbox_cashier"!==r.type)throw new ab(r0);let a="string"==typeof r.total_amount?r.total_amount.trim():"";if(!a||!/^\d+$/.test(a))throw new ab(rG);return{paymentTypes:function(e){if(!Array.isArray(e)||0===e.length)throw new ab(r2);let t=e.map(e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new ab(rX);return{id:aW(e,"id"),name:aW(e,"name")}});if(new Set(t.map(e=>{let{id:t}=e;return t})).size!==t.length)throw new ab(rX);return t}(r.pay_types??aP),payOrderNo:aW(r,"pay_order_no"),payStatus:aW(r,"pay_status"),totalAmount:a,tradeNo:aW(r,"trade_no"),type:"sandbox_cashier"}}(e);if(!t.showSandboxCashier)throw new ab(rU);if(!await t.showSandboxCashier(r,async e=>{if(!r.paymentTypes.some(t=>{let{id:r}=t;return r===e}))throw new ab(r2);try{await aD.SandboxPay({trade_no:r.tradeNo,pay_type:e})}catch(e){if(e instanceof aw&&"code"===e.options.errorField&&500===e.remoteCode)throw new aw(e.remoteCode,e.message,{...e.options,operation:"payment"});throw e}}))throw new ab(rJ)}async function aK(e,t){let r,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"user_info",n=t?"phone":"login";try{r=await aD.SandboxIssueLoginCode({aid:"482431",client_key:aB(e),scope:a,source:"jsb",...t?{exchange_type:t}:{}})}catch(e){throw aN(e,n)}var s,i,o=ax(null==(s=r.data)?void 0:s.error_code);let l=ax(o);if(void 0!==l&&0!==l)throw new ab(aE(l,n,{errorField:"data.error_code"}));let d=null==(i=r.data)?void 0:i.code;if(!d)throw new ab(ao);return d}async function aJ(e){try{let t=await aD.UpdateSandboxBusinessInfo({csr_pem:e.csrPem,phone_num:e.phoneNum,sandbox_session_id:""});return aM(t),t}catch(t){let e=Error(t.message);throw e.logId=t instanceof aw?t.options.logId:t&&"object"==typeof t&&"logId"in t&&"string"==typeof t.logId?t.logId:void 0,e}}async function aX(e){return aJ(e)}async function aQ(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 aZ=["aztec","codabar","code_39","code_93","code_128","data_matrix","ean_8","ean_13","itf","pdf417","qr_code","upc_a","upc_e"],aY={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 a0(e){let t=e.getSupportedFormats;return"function"==typeof t?new Set(await t()):null}function a1(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,aZ.includes(r)?"pdf417"===r?"PDF_417":r.toUpperCase():"QR_CODE")}}async function a2(e,t){if("function"==typeof createImageBitmap){let r=await createImageBitmap(t);try{return e.detect(r)}finally{r.close()}}let r=new Image,a=URL.createObjectURL(t);try{return await new Promise((e,t)=>{r.onload=()=>e(),r.onerror=()=>t(Error("Failed to load selected image")),r.src=a}),e.detect(r)}finally{URL.revokeObjectURL(a)}}function a3(e,t,r,a,n){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(n))};for(let t of(o=window.setTimeout(()=>{l(),i(Error(n))},a),r))e.addEventListener(t,d);e.addEventListener("error",u)})}async function a4(e,t){e.srcObject=t,await a3(e,()=>e.readyState>=HTMLMediaElement.HAVE_METADATA,["loadedmetadata"],3e3,"Camera stream started, but video metadata was not loaded"),await e.play(),await a3(e,()=>e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA,["loadeddata","canplay","playing"],3e3,"Camera stream started, but no video frame was rendered")}async function a5(e,t){var r;let a,n=globalThis.BarcodeDetector;if(!n)throw Error("BarcodeDetector is not supported in this browser");let s=await a0(n),i=[...new Set((null==(r=e.scanType)?void 0:r.length)?e.scanType.flatMap(e=>aY[e]):aZ)].filter(e=>!s||s.has(e));if(0===i.length)throw Error("Requested scanType is not supported in this browser");let o=new n({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==a||a.close())};try{return await new Promise((r,n)=>{let s=e=>{h(),e()},i=e=>{if(!l&&!d){if(!p||p.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){e&&(null==a||a.setMessage("摄像头画面还未准备好"));return}d=!0,o.detect(p).then(t=>{let n=t[0];n?s(()=>r(a1(n))):e&&(null==a||a.setMessage("未识别到二维码或条形码"))}).catch(t=>{e&&(null==a||a.setMessage(t instanceof Error?t.message:String(t)))}).finally(()=>{d=!1})}};a=t({allowImageUpload:!e.onlyFromCamera,onCancel:()=>s(()=>n(Error("scanCode canceled"))),onCapture:()=>i(!0),onFile:e=>{l||(null==a||a.setMessage("正在识别图片..."),a2(o,e).then(e=>{let t=e[0];t?s(()=>r(a1(t))):null==a||a.setMessage("未识别到二维码或条形码,请换一张图片重试")}).catch(e=>{null==a||a.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(()=>n(Error("Camera is not available in this browser"))):void(null==a||a.setMessage("无法使用摄像头,请从相册选择二维码或条形码图片"));navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:{ideal:"environment"}}}).then(e=>l?void e.getTracks().forEach(e=>e.stop()):(c=e,a4(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==a||a.setMessage(r),s(()=>n(t instanceof Error?t:Error(r)));return}null==a||a.setMessage(`无法使用摄像头,请从相册选择二维码或条形码图片:${r}`)})}}})})}catch(e){throw h(),e}}let a6="doubao-web-sdk-debugger-vibration-style",a8="doubao-web-sdk-debugger-screen-vibrating",a7={heavy:4,light:1,medium:2},a9=0,ne=null;function nt(e){e.classList.remove(a8),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-distance"),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-duration")}function nr(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 a;(function(){if(document.getElementById(a6))return;let e=document.createElement("style");e.id=a6,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
+ .${a8} {
18
+ animation: doubao-web-sdk-debugger-screen-vibrate var(--doubao-web-sdk-debugger-vibrate-duration) linear;
19
+ }
20
+ `,document.head.append(e)})(),window.clearTimeout(a9),a=r||(document.body??document.documentElement),ne&&ne!==a&&nt(ne),ne=a,nt(a),a.style.setProperty("--doubao-web-sdk-debugger-vibrate-distance",`${t}px`),a.style.setProperty("--doubao-web-sdk-debugger-vibrate-duration",`${e}ms`),a.offsetWidth,a.classList.add(a8),a9=window.setTimeout(()=>{nt(a),ne===a&&(ne=null)},e+50)}}let na="socketStatusChanged",nn="socketDataReceived",ns=1,ni=new Map;function no(e,t,r){var a,n;null!=e&&null!=(a=e.apiRegistry)&&a.emitEvent(t,r)||null==e||null==(n=e.emitEvent)||n.call(e,t,r)}function nl(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},a=(null==(e=r.baseAPIRegistry)?void 0:e.fork())??new E(X);return a.registerMany(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.uiPresenter??ry(),r=e.scanCodePresenter;return{"doubao.request":function(e){if(rN.has(e))return e;let t=(t,r)=>{let a=`wsd-request-${++rR}`,n=t.params??{},s=function(e){try{return rC(e)}catch{return}}(n);rP({phase:"request",request:s??{headers:{},method:"string"==typeof n.method?n.method.toUpperCase():"GET",url:"string"==typeof n.url?n.url:""},requestId:a,...rA()});let i=e=>rP({errorText:e,phase:"failure",requestId:a,...rA()}),o=e=>((null==e?void 0:e.params.code)===1?rP({phase:"response",requestId:a,response:e.params.data,...rA()}):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 a=e(t,r,s);return a instanceof Promise?a.then(e=>o(e),l):o(a)}catch(e){return l(e)}};return rN.add(t),t}(e.requestHandler??(async(e,t,r)=>d(e,await rE(e.params,r)))),"doubao.getNetworkType":{handler:e=>d(e,rj()),syncResult:rj},"doubao.scanCode":async e=>{if(!r)throw Error("Simulator scan-code presenter is unavailable");return d(e,await a5(e.params,r))},"doubao.vibrateLong":async t=>(await void nr(400,3,e.vibrationContainer),d(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;nr(15,a7[r],t)}(t.params,e.vibrationContainer),d(t,{})),...(!rs&&"u">typeof window&&(window.addEventListener("pagehide",ro),rs=!0),{"doubao.chooseImage":async e=>{var t;let r,a,n,s,i;return d(e,await (n=(a=(r="string"==typeof(t=e.params).imageId?document.getElementById(t.imageId):null)instanceof HTMLInputElement?r:document.createElement("input"))!==r,s=t.count??9,a.type="file",a.accept="image/*",a.multiple=s>1,a.capture=(i=Array.isArray(t.sourceType)?t.sourceType:[]).includes("album")?"":i.includes("user")?"user":i.some(e=>"camera"===e||"environment"===e)?"environment":"",a.style.display="none",a.value="",n&&document.body.append(a),new Promise((e,t)=>{let r=()=>{a.removeEventListener("change",i),a.removeEventListener("cancel",o),n&&a.remove()},i=()=>{let n,i=Array.from(a.files??[]).slice(0,s);if(r(),0===i.length)return void t(Error("chooseImage was cancelled"));let o=[];try{n=i.map(e=>{let t=URL.createObjectURL(e);o.push(t);let r=e.type.startsWith("image/")?e.type.slice(6).split("+")[0].toLowerCase():rl(e.name);return r&&rn.set(t,r),{path:t,size:e.size,type:e.type,originalFileObj:e}})}catch(e){ri(o),t(e);return}for(ra.push(o);ra.length>20;)ri(ra.shift()??[]);e({tempFilePaths:n.map(e=>e.path),tempFiles:n})},o=()=>{r(),t(Error("chooseImage was cancelled"))};a.addEventListener("change",i,{once:!0}),a.addEventListener("cancel",o,{once:!0}),a.click()})))},"doubao.getImageInfo":async e=>d(e,await ru(e.params)),"doubao.compressImage":async e=>d(e,await rc(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(),d(e,{})}}),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.chooseLocation??ry().chooseLocation;return{"doubao.getLocation":async t=>{var r;return await rx(e)?d(t,{latitude:(r=await function(e){let{geolocation:t}=navigator;if(!t)throw Error("Geolocation is not available in the current browser");return new Promise((r,a)=>{t.getCurrentPosition(r,a,rw(e))})}(t.params)).coords.latitude,longitude:r.coords.longitude,timestamp:new Date(r.timestamp).toISOString(),speed:r.coords.speed??0,accuracy:r.coords.accuracy??0}):u(t,"user permission denied")},"doubao.chooseLocation":async r=>await rx(e)?d(r,await t(r.params)):u(r,"user permission denied"),"doubao.openLocation":async t=>{if(!await rx(e))return u(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 a=new URL("https://www.google.com/maps/search/");return a.searchParams.set("api","1"),a.searchParams.set("query",`${r.latitude},${r.longitude}`),window.open(a.toString(),"_blank","noopener,noreferrer"),d(t,{})},"doubao.startLocationUpdate":async t=>{if(!await rx(e))return u(t,"user permission denied");if(!navigator.geolocation)throw Error("Geolocation is not available in the current browser");return d(t,{})},"doubao.stopLocationUpdate":e=>(!function(){let{geolocation:e}=navigator;if(!e)return rb.clear();for(let t of rb)e.clearWatch(t);rb.clear()}(),d(e,{}))}}({...e,chooseLocation:t.chooseLocation}),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.presenter??ry();return{"applet.showToast":e=>(t.showToast(e.params),d(e,{})),"doubao.hideToast":e=>(t.hideToast(),d(e,{})),"doubao.showLoading":e=>(t.showLoading(),d(e,{})),"doubao.hideLoading":e=>(t.hideLoading(),d(e,{})),"doubao.showModal":async e=>d(e,await t.showModal(e.params)),"doubao.showActionSheet":async e=>d(e,await t.showActionSheet(e.params)),"doubao.showBottomSheet":async e=>d(e,await t.showBottomSheet(e.params)),"doubao.enableAlertBeforeUnload":e=>{var t;let r;return t=e.params,r_(),r="string"==typeof t.message?t.message:"",n=e=>(e.preventDefault(),e.returnValue=r,r),window.addEventListener("beforeunload",n),d(e,{})},"doubao.disableAlertBeforeUnload":e=>(r_(),d(e,{})),"doubao.hideKeyboard":e=>(document.activeElement.blur(),d(e,{}))}}({presenter:t}),...{"doubao.connectSocket":(e,t)=>d(e,function(e,t){if("string"!=typeof e.url||!e.url)throw Error("url must be a non-empty string");let r=ns++,a=new WebSocket(e.url,e.protocols);return a.binaryType="arraybuffer",ni.set(r,a),a.addEventListener("open",()=>{no(t,na,{socketTaskId:r,status:"connected",header:{},protocolType:a.protocol})}),a.addEventListener("message",e=>{!function(e,t,r){if("string"==typeof r)return no(e,nn,{socketTaskId:t,data:r,dataType:"string"});if(r instanceof ArrayBuffer){let a;no(e,nn,{socketTaskId:t,data:(a="",new Uint8Array(r).forEach(e=>{a+=String.fromCharCode(e)}),btoa(a)),dataType:"base64"})}}(t,r,e.data)}),a.addEventListener("close",e=>{ni.delete(r),no(t,na,{socketTaskId:r,status:"closed",code:e.code,reason:e.reason,protocolType:a.protocol})}),a.addEventListener("error",()=>{ni.delete(r),no(t,na,{socketTaskId:r,status:"failed",errMsg:"WebSocket error",protocolType:a.protocol})}),{socketTaskId:r}}(e.params,t)),"doubao.sendSocketData":e=>{var t;return function(e){let t=e.socketTaskId,r="number"==typeof t?ni.get(t):void 0;if(!r)throw Error(`socket not found: ${t}`);let a=e.data;if("string"!=typeof a&&!(a instanceof ArrayBuffer))throw Error("data must be a string or ArrayBuffer");r.send(a)}({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}),d(e,{})},"doubao.closeSocket":e=>{var t=e.params;let r=t.socketTaskId,a="number"==typeof r?ni.get(r):void 0;if(!a)throw Error(`socket not found: ${r}`);return a.close(t.code,t.reason),d(e,{})}},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.requestOrder":t=>aV(t,async()=>{let r=await aD.SandboxRequestOrder({app_key:aB(e),data:aH(t.params,"data"),db_authorization:aH(t.params,"dbAuthorization")});return r.err_code||!r.order_id?az(t,r,ar):d(t,{orderId:r.order_id,logId:r.log_id||""})}),"doubao.getOrderPayment":t=>aV(t,async()=>{let r=aH(t.params,"orderId"),a=await aD.SandboxGetOrderPayment({app_key:aB(e),aweme_bind_status:!0,order_id:r,platform_signed_pt_code:aF(t.params,"platformSignedPtCode").trim()||void 0});return a.err_code||!a.pay_data?az(t,a,rZ):(await aG(a.pay_data,e),d(t,{orderId:r,logId:a.log_id||""}))}),"doubao.getOrderPaymentWithSign":t=>aV(t,async()=>{let r=aH(t.params,"orderId"),a=await aD.SandboxGetOrderPaymentWithSign({app_key:aB(e),aweme_bind_status:!0,order_id:r,sign_data:aH(t.params,"signData"),sign_db_authorization:aH(t.params,"signDbAuthorization")});return a.err_code||!a.pay_data?az(t,a,rY):(await aG(a.pay_data,e),d(t,{orderId:r,logId:a.log_id||""}))}),"doubao.getPlatformSignInfo":e=>d(e,{signInfo:""}),"doubao.createSignOrder":t=>aV(t,async()=>{let r=await aD.SandboxCreateSignOrder({app_key:aB(e),data:aH(t.params,"data"),db_authorization:aH(t.params,"dbAuthorization")});return r.err_code||!r.auth_order_id?az(t,r,au):d(t,{authOrderId:r.auth_order_id,logId:r.log_id||""})}),"doubao.sign":t=>aV(t,async()=>{let r=await aD.SandboxGetSignPageData({app_key:aB(e),auth_order_id:aH(t.params,"orderId"),aweme_bind_status:!0});return r.err_code||!r.data?az(t,r,ay,!0):d(t,{})},!0),"doubao.login":async t=>d(t,{code:await aK(e)}),"doubao.loginWithDoubaoWidget":e=>d(e,{result:!0}),"doubao.postLoginResult":async t=>{var r,a,n,s;let i,o=t.params;if(!1===o.result)return null==(n=e.onPrivacyLoginCardClose)||n.call(e,"login"),await (null==(s=e.onGrantingCompleted)?void 0:s.call(e,"login",{noLogin:!0})),d(t,{});let l=aF(o,"code");if(!l)throw new ab(rF);try{i=await aD.SandboxApiExchangeCode({app_key:aB(e),code:l,version_tag:aA})}catch(e){throw aN(e,"login")}return aR(i,"login"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"login"),await (null==(a=e.onGrantingCompleted)?void 0:a.call(e,"login")),d(t,{})},"doubao.getPrivacySetting":async t=>{var r;let a;try{a=await aD.SandboxApiCheckPrivacyOrLoginStatus({app_key:aB(e),check_type:1,version_tag:aA})}catch(e){throw aN(e,"privacy")}return aR(a,"privacy"),d(t,{needAuthorization:(null==(r=a.data)?void 0:r.PrivacyAgreed)===!1})},"applet.agreePrivacyAuthorization":async t=>{var r,a;let n;try{n=await aD.SandboxApiAcceptPrivacy({app_key:aB(e)})}catch(e){throw aN(e,"privacy")}return aR(n,"privacy"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"privacy"),await (null==(a=e.onGrantingCompleted)?void 0:a.call(e,"privacy")),d(t,{result:!0})},"applet.getPhoneNumber":async t=>d(t,{code:await aK(e,"profile","user_info,mobile"),message:"success"}),"applet.openLoginPage":t=>{let r=aF(t.params,"url");if(r){var a;null==(a=e.onCustomLoginNavigate)||a.call(e,r)}return d(t,{})},"applet.closePrivacyLoginCard":t=>{var r;return null==(r=e.onPrivacyLoginCardClose)||r.call(e,aF(t.params,"type")),d(t,{})},"applet.reportAppLog":e=>d(e,{}),"applet.open":e=>{let t=aF(e.params,"schema");return t&&window.open(t,"_blank","noopener,noreferrer"),d(e,{})},"doubao.__debuggerUpdateSandboxBusinessInfo":async e=>{let t=e.params;return d(e,await aJ({csrPem:aF(t,"csrPem"),phoneNum:aF(t,"phoneNum")}))},...e.onCustomLoginNavigate?{"doubao.navigateTo":t=>{let r=aF(t.params,"url");if(r){var a;null==(a=e.onCustomLoginNavigate)||a.call(e,r)}return d(t,{})}}:{}}}(e),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.authorize":async t=>{let r=rD(t.params,"scope");return r?await rL(e,r,!1)?d(t,{}):u(t,"user permission denied"):u(t,"scope is required")},"doubao.operateRecorder":async t=>"start"!==rD(t.params,"operationType")||await rL(e,"scope.record",!1)?d(t,{}):u(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(!eH(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(!eH(e.data)||"string"!=typeof e.data.name||!e.data.name.trim()||!eH(e.data.arguments))throw Error("api/call content must include a name and arguments object");continue}throw Error('content type must be "text" or "api/call"')}return{content:t,prompt:t.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}}(t.params)),d(t,{})},"doubao.toolCall":async t=>{if(!e.toolCall)throw Error("toolCall is not configured in web-sdk-debugger");return d(t,await e.toolCall(function(e){let t=e.toolName;if("string"!=typeof t||!t.trim())throw Error("toolName must be a non-empty string");return{toolName:t.trim(),params:e.params,serverId:"string"==typeof e.serverId&&e.serverId.trim()?e.serverId.trim():void 0,timeoutMs:"number"==typeof e.timeoutMs&&Number.isFinite(e.timeoutMs)?e.timeoutMs:void 0}}(t.params)))},"doubao.multiMediaBroadcast":async t=>d(t,await rr(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}),a.registerEventSources({...{"doubao.onNetworkStatusChange":e=>{var t;let r;return t=t=>e({isConnected:t.isConnected,networkType:t.networkType}),addEventListener("online",r=()=>t(rM())),addEventListener("offline",r),()=>{removeEventListener("online",r),removeEventListener("offline",r)}}},...{"doubao.onLocationChange":e=>rS(t=>e({latitude:t.coords.latitude,longitude:t.coords.longitude,speed:t.coords.speed??void 0,accuracy:t.coords.accuracy??void 0,altitude:t.coords.altitude??void 0,verticalAccuracy:t.coords.altitudeAccuracy??void 0,horizontalAccuracy:t.coords.accuracy??void 0}),()=>{}),"doubao.onLocationChangeError":e=>rS(()=>{},t=>e({errMsg:t.message,errCode:"code"in t?t.code:void 0}))},...{[na]:()=>void 0,[nn]:()=>void 0}},{override:!0}),a}function nd(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{apiRegistry:e.apiRegistry??nl(e),runtimeHost:e.runtimeHost??{mountRuntimeEmptyState:re},scanCodePresenter:e.scanCodePresenter,uiPresenter:e.uiPresenter}}var nu=r(39649),nc=r(73471);function np(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 nm(e){return{name:e.name,description:e.description||"",input_schema_json:eK(e.inputSchema??{type:"object",additionalProperties:!0})}}async function nh(e,t){let r=new nu.K({name:"web-sdk-debugger",version:"0.0.1"}),a=new nc.j(new URL(e),{fetch:t.fetcher,requestInit:t.headers?{headers:t.headers}:void 0});try{await r.connect(a)}catch(e){throw await a.close().catch(()=>void 0),await r.close().catch(()=>void 0),e}return{client:r,transport:a}}async function ng(e){await e.transport.close().catch(()=>void 0),await e.client.close().catch(()=>void 0)}let nf="wsd:runtime-console",nv=new WeakMap;function ny(e,t){if(!e.dispatchEvent(new CustomEvent(nf,{cancelable:!0,detail:t})))return;let r=nv.get(e)??[];r.push(t),nv.set(e,r)}let n_=["log","info","warn","error","debug"];function nb(){return{entries:[],nextEntryId:0}}function nw(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 nS(e){return"number"==typeof e&&Number.isFinite(e)?Math.max(e-1,0):0}function nx(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 nI(e,t){var r;let a=e.trim(),n=a.match(/^(.*):(\d+):(\d+)$/)??a.match(/^(.*):(\d+)$/);if(!n)return null;let[,s,i,o]=n;return s?{url:t&&("<anonymous>"===s||s.endsWith(", <anonymous>")||/^eval at\b.*<anonymous>$/.test(s))?t:s,lineNumber:nS(Number(i)),columnNumber:void 0===o?0:"number"==typeof(r=Number(o))&&Number.isFinite(r)?Math.max(r-1,0):0}:null}function nC(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(),a=r.startsWith("at ")?r.slice(3).trim():r,n=a.match(/^(.*?)\s+\((.*)\)$/);if(n){let[,e,r]=n,a=nI(r,t);return a?{functionName:e,scriptId:"",...a}:null}let s=nI(a,t);return s?{functionName:"",scriptId:"",...s}:null})(e,t.fallbackSourceUrl)).filter(e=>!!e),a=t.dropFirstFrame&&r.length>1?r.slice(1):r,n=a.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=n.length>0?n:a;return s.length>0?{callFrames:s}:void 0}function nE(e){let t=null==e?void 0:e.callFrames[0];return t?{url:t.url,lineNumber:t.lineNumber,columnNumber:t.columnNumber}:void 0}function nk(e){return e?{callFrames:[{functionName:"",scriptId:"",...e}]}:void 0}function nN(e){return e?`[${e}] `:""}class nR{target;store;listeners=new Set;constructor(e,t=nb()){this.target=e,this.store=t,this.target.addEventListener("error",this.handleRuntimeError),this.target.addEventListener(nf,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 a=r.eval(e),n=nw(a);return this.addEntry("eval","iframe"===t?"iframe":"eval",n),{ok:!0,value:n}}catch(t){let e=nw(t);return this.addEntry("error","eval",e),{ok:!1,value:e}}}destroy(){this.target.removeEventListener("error",this.handleRuntimeError),this.target.removeEventListener(nf,this.handleRuntimeConsole),this.listeners.clear()}addEntry(e,t,r){let a=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,...a}),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,a,n,s,i=(r=null==(t=e.detail)?void 0:t.error,a=e.currentTarget instanceof HTMLElement?nx(e.currentTarget):void 0,s=nE(n=nC(null==r?void 0:r.stack,{fallbackSourceUrl:a}))??function(e){var t,r,a,n,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:nS(null==(a=e.sourceMap)||null==(r=a.offset)?void 0:r.line),columnNumber:"number"==typeof(i=null==(s=e.sourceMap)||null==(n=s.offset)?void 0:n.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:n??nk(s)}}:{message:nw(r??t??e),metadata:{location:s,stackTrace:n??nk(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=nv.get(e)??[],nv.delete(e),t))this.addRuntimeConsoleEntry(r)}addRuntimeConsoleEntry(e){var t;let r=e.stackTrace??nC(e.stack,{dropFirstFrame:!0,fallbackSourceUrl:nx(this.target)}),a=e.location??nE(r),n="string"==typeof e.message?e.message:(e.args??[]).map(nw).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,n_.includes(t)?t:"log"),"runtime",`${nN(i)}${n}`,{args:function(e,t){if(!e||!t)return e;let r=nN(t);if(0===e.length)return[r.trim()];let[a,...n]=e;return"string"==typeof a?[`${r}${a}`,...n]:[r.trim(),a,...n]}(e.args,i),location:a,pagePath:s,stackTrace:r??nk(a)})}notify(){for(let e of this.listeners)e()}}let nT=new Set(["IFRAME","LINK","SCRIPT","STYLE","TEMPLATE"]),nM=new Set(["data-wsd-node-id"]),nA=new Set(["part","lynx-default-overflow-visible"]),nP=new Set(["style","data-wsd-node-id"]);function nj(e){return e.nodeType===Node.ELEMENT_NODE&&!nT.has(e.tagName)}function nD(e){var t;return e.nodeType===Node.TEXT_NODE&&!!(null==(t=e.textContent)?void 0:t.trim())}function nL(e){return e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"#shadow-root":e.nodeType===Node.TEXT_NODE?"#text":e.tagName.toLowerCase()}function nO(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 nU(e){return Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")}function nq(e){let t=e.trim(),r=Number.parseFloat(t);return Number.isFinite(r)&&0===r?"0":t}function n$(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function nB(e){var t,r,a;let n=null==(t=e.getAttribute("aria-label"))?void 0:t.trim();if(n)return n;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==(a=e.textContent)?void 0:a.replace(/\s+/g," ").trim())??"":""}function nF(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 nH(e){return!e.hasAttribute("disabled")&&"true"!==e.getAttribute("aria-disabled")&&(!!(e.isContentEditable||e instanceof HTMLAnchorElement&&e.hasAttribute("href"))||e.tabIndex>=0)}function nW(e){return Array.from(e.attributes).filter(e=>!nM.has(e.name)).map(e=>({name:e.name,value:e.value}))}function nz(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function nV(e){return nM.has(e)||nA.has(e)}function nG(e){return"DIV"===e.tagName&&"page"===e.getAttribute("part")}function nK(e,t){return nM.has(t)||nG(e)&&nV(t)}function nJ(e,t){for(let r of t)nK(e,r.name)||e.setAttribute(r.name,r.value)}function nX(e){return nW(e).filter(t=>!nK(e,t.name))}function nQ(e,t,r){let a=new Map(t.map(e=>[e.name,e.value])),n=new Map(r.map(e=>[e.name,e.value])),s=r.filter(e=>a.get(e.name)!==e.value),i=t.filter(e=>!n.has(e.name)).map(e=>e.name);return s.length||i.length?[{type:"attributes",nodeId:e,before:t,modified:s,removed:i}]:[]}function nZ(e){return Array.from(e.childNodes).filter(e=>nj(e)||nD(e))}function nY(e,t,r){let a=("elementFromPoint"in e&&"function"==typeof e.elementFromPoint?e.elementFromPoint.bind(e):document.elementFromPoint.bind(document))(t,r);for(;(null==a?void 0:a.shadowRoot)&&"function"==typeof a.shadowRoot.elementFromPoint;){let e=a.shadowRoot.elementFromPoint(t,r);if(!e||e===a)break;a=e}return a}function n0(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement??null;for(;t;){if(nT.has(t.tagName))return!0;t=t.parentElement}return!1}class n1{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 a=function(e){let t=e.trim();if(!t)return[];let r=document.createElement("template");r.innerHTML=`<div ${t}></div>`;let a=r.content.firstElementChild;return a?nW(a):[]}(t),n=null==r?void 0:r.trim();return this.editElementAttributes(e,e=>{n&&!nK(e,n)&&e.removeAttribute(n),nJ(e,a)})}setAttributeValue(e,t,r){let a=t.trim();return a?this.editElementAttributes(e,e=>{if(nK(e,a))return!1;e.setAttribute(a,r)}):[]}removeAttribute(e,t){let r=t.trim();return r?this.editElementAttributes(e,e=>{if(nK(e,r))return!1;e.removeAttribute(r)}):[]}setNodeValue(e,t){return this.runWithoutObservation(()=>{let r=this.getNode(e),a=(null==r?void 0:r.textContent)??"";return(null==r?void 0:r.nodeType)!==Node.TEXT_NODE||a===t?[]:(r.textContent=t,[{type:"characterData",nodeId:e,value:t,previousValue:a}])})}setNodeName(e,t){return this.runWithoutObservation(()=>{let r=this.getElement(e),a=t.trim();if(!r||!a)return{nodeId:null,mutations:[]};if(nG(r))return{nodeId:e,mutations:[]};let n=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,a);return{nodeId:this.getNodeId(i),mutations:n?[this.getChildListMutation(n,[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=nZ(r).map(e=>this.getNodeId(e)),a=nz(t);return r.replaceChildren(...Array.from(a.childNodes)),[this.getChildListMutation(r,e,this.getInsertedNodeMutations(r,null,nZ(r)))]}if(r instanceof Element&&nG(r)){let a=nX(r),n=nZ(r).map(e=>this.getNodeId(e));!function(e,t){let r=nz(t),a=r.firstElementChild;if(!a)return e.replaceChildren(...Array.from(r.childNodes));for(let t of Array.from(e.attributes))nV(t.name)||e.removeAttribute(t.name);nJ(e,nW(a)),e.replaceChildren(...Array.from(a.childNodes))}(r,t);let s=this.getInsertedNodeMutations(r,null,nZ(r));return[...nQ(e,a,nX(r)),this.getChildListMutation(r,n,s)]}let a=r.parentNode;if(!a)return[];let n=this.getPreviousInspectableSiblingId(r),s=nz(t),i=nZ(s);return a.replaceChild(s,r),[this.getChildListMutation(a,[e],this.getInsertedNodeMutations(a,n,i))]})}getNodeIdAtPoint(e,t){let r,a,n=this.getRoot(),s=this.target.shadowRoot,i=(r=null,(a=n=>{let s;for(let i of(nj(n)&&(s=n.getBoundingClientRect()).width>0&&s.height>0&&e>=s.left&&e<=s.right&&t>=s.top&&t<=s.bottom&&(r=n),Array.from(n.childNodes)))nj(i)&&a(i)})(n),r),o=s?nY(s,e,t):nY(document,e,t),l=(i&&n.contains(i)?i:null)??(o&&n.contains(o)?o:null);if(!l)return null;let d=l;for(;d&&!nj(d);)d=d.parentNode??function(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.host:null}(d);return d&&n.contains(d)?this.getNodeId(d):null}getHighlight(e,t){var r,a;let n,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,C=b.height/x,E=getComputedStyle(_),k=E.backgroundColor.trim(),N=(r=E.paddingTop,a=E.paddingRight,(n=[r,a,E.paddingBottom,E.paddingLeft].map(nq)).every(e=>"0"===e)?null:n.every(e=>e===n[0])?n[0]:n[0]===n[2]&&n[1]===n[3]?`${n[0]} ${n[1]}`:n[1]===n[3]?`${n[0]} ${n[1]} ${n[2]}`:n.join(" "));return{left:(b.left-w.left)/S,top:(b.top-w.top)/x,width:I,height:C,nodeName:nL(_),selector:(s=_.id.trim(),{tagName:nL(_),...s?{id:s}:{},classNames:Array.from(_.classList).filter(Boolean)}),boxModel:(i=n$(E.borderTopWidth),o=n$(E.borderRightWidth),l=n$(E.borderBottomWidth),d=n$(E.borderLeftWidth),u=n$(E.paddingTop),c=n$(E.paddingRight),p=n$(E.paddingBottom),m=d+n$(E.paddingLeft),{content:{left:m,top:h=i+u,width:Math.max(0,I-m-o-c),height:Math.max(0,C-h-l-p)}}),dimensions:`${nO(I)} \xd7 ${nO(C)}`,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))?`#${nU(Math.round(Number(y[1])))}${nU(Math.round(Number(y[2])))}${nU(Math.round(Number(y[3])))}`:g),swatch:k}]:[],...N?[{name:"Padding",value:N}]:[]],accessibility:{name:nB(_),role:nF(_),keyboardFocusable:nH(_)}}}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 a=nX(r);return!1===t(r)?[]:nQ(e,a,nX(r))})}getPreviousInspectableSiblingId(e){let t=e.parentNode;if(!t)return null;let r=nZ(t),a=r.findIndex(t=>t===e),n=a>0?r[a-1]:null;return n?this.getNodeId(n):null}getChildListMutation(e,t,r){return{type:"childList",parentNodeId:this.getNodeId(e),removedNodeIds:t,insertedNodes:r,childNodeCount:nZ(e).length}}getInsertedNodeMutations(e,t,r){let a=[],n=t;for(let t of r){if((t.parentNode??(t instanceof ShadowRoot?t.host:null))!==e)continue;let r=this.serializeNode(t);a.push({previousNodeId:n,node:r}),n=r.id}return a}runWithoutObservation(e){var t,r;let a=null!==this.mutationObserver;a&&(null==(t=this.mutationObserver)||t.disconnect());try{return e()}finally{a&&(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:nL(e),attributes:[],children:[],textContent:(t=(e.textContent??"").replace(/\s+/g," ").trim()).length>120?`${t.slice(0,120)}...`:t}}let a=e instanceof HTMLElement?e:null;return{id:r,type:t&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"document":"element",name:nL(e),attributes:e instanceof Element?nW(e):[],children:nZ(e).map(e=>this.serializeNode(e)),...a?{accessibility:{name:nB(a),role:nF(a),keyboardFocusable:nH(a)}}:{}}}observe(){let e=this.target.shadowRoot??this.target;this.mutationObserver=new MutationObserver(e=>{e.some(e=>(function(e){if(n0(e.target))return!1;if("attributes"===e.type)return e.target instanceof Element&&nj(e.target)&&!nP.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!n0(t)&&(!!(nj(t)||nD(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 n2="data-wsd-node-id";function n3(e){let t=[];for(let r=0;r<e.length;r++){let a="function"==typeof e.item?e.item(r):e[r];if(!a)continue;let n=e.getPropertyValue(a);t.push({name:a,value:n,priority:e.getPropertyPriority(a),active:!0})}return t}function n4(e){return"u">typeof CSSStyleRule&&e instanceof CSSStyleRule}function n5(e,t,r){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=r.trim();n?e.setProperty(t,n,a):e.removeProperty(t)}function n6(e){return`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`}function n8(e){return e.map(e=>({...e}))}function n7(e){return`inline:${e}`}function n9(e){return`rule:${e}`}class se{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 a=e.item(r);t.push({name:a,value:e.getPropertyValue(a)})}return t}(r)}}setInlineDeclaration(e,t,r){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=!(arguments.length>4)||void 0===arguments[4]||arguments[4],s=this.elementInspector.getElement(e);if(!s)return;let i=n7(e);this.rememberStyleTextDeclaration(i,n3(s.style),t,r,a,n),n5(s.style,t,n?r:"")}setInlineDeclarations(e,t){let r=this.elementInspector.getElement(e);if(r){for(let e of(r.style.cssText="",t))e.active&&n5(r.style,e.name,e.value,e.priority);this.styleTextSnapshots.set(n7(e),n8(t))}}setRuleDeclaration(e,t,r,a){let n=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=n9(t);if(this.rememberStyleTextDeclaration(o,i?n3(i.style):[],r,a,n,s),!s){if(i)try{n5(i.style,r,"")}catch{this.setOverrideDeclaration(e,r,"")}else this.setOverrideDeclaration(e,r,"");return}if(!i)return void this.setOverrideDeclaration(e,r,a,n);try{n5(i.style,r,a,n)}catch{this.setOverrideDeclaration(e,r,a,n)}}setRuleDeclarations(e,t,r){let a=this.rules.get(t),n=r.filter(e=>e.active);if(this.styleTextSnapshots.set(n9(t),n8(r)),!a)return void this.setOverrideDeclarations(e,n);try{for(let e of(a.style.cssText="",n))n5(a.style,e.name,e.value,e.priority)}catch{this.setOverrideDeclarations(e,n)}}addRule(e,t,r){let a=this.elementInspector.getElement(e),n=t.trim();if(!a||!n)return null;let s=this.getInspectorRuleStyleSheet();if(!s)return null;let i=`${n} { ${r.map(n6).join(" ")} }`;try{let e=s.cssRules.length;s.insertRule(i,e);let t=s.cssRules[e];if(t&&n4(t))return this.toMatchedStyleRule(t,getComputedStyle(a))}catch{}return null}setRuleSelector(e,t,r){let a=this.elementInspector.getElement(e),n=this.rules.get(t),s=r.trim();if(!a||!n||!s)return null;try{return n.selectorText=s,this.toMatchedStyleRule(n,getComputedStyle(a))}catch{return null}}setOverrideDeclaration(e,t,r){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=this.elementInspector.getElement(e);if(!n)return;n.setAttribute(n2,e),this.overriddenElements.add(n);let s=this.overrides.get(e)??new Map,i=r.trim();i?s.set(t,{value:i,priority:a}):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(n2,e),this.overriddenElements.add(r);let a=new Map;for(let e of t)e.value.trim()&&a.set(e.name,{value:e.value.trim(),priority:e.priority});a.size>0?this.overrides.set(e,a):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(n2);this.overriddenElements.clear(),this.rules.clear()}getInlineStyle(e,t,r){return{id:"inline",selectorText:"element.style",editable:!0,declarations:this.getStyleTextSnapshot(n7(e))??n3(t.style)}}getMatchedRules(e,t){let r,a=this.target.shadowRoot??this.target,n=[];for(let s of(this.rules.clear(),r=[],"styleSheets"in a&&r.push(...Array.from(a.styleSheets)),"adoptedStyleSheets"in a&&r.push(...a.adoptedStyleSheets),r))this.collectRulesFromList(s,e,t,n);return n}collectRulesFromList(e,t,r,a,n){let s;try{s=e.cssRules}catch{return}for(let e of Array.from(s)){if(n4(e)){if(!function(e,t){try{return e.matches(t)}catch{return!1}}(t,e.selectorText))continue;a.push(this.toMatchedStyleRule(e,r,n));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,a,n&&s?`${n} and ${s}`:s??n)}}}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 a=this.getRuleId(e);return this.rules.set(a,e),{id:a,selectorText:e.selectorText,conditionText:r,editable:!0,source:this.isOverrideRule(e)?"override":"rule",declarations:this.getStyleTextSnapshot(n9(a))??n3(e.style)}}getStyleTextSnapshot(e){let t=this.styleTextSnapshots.get(e);return t?n8(t):void 0}rememberStyleTextDeclaration(e,t,r,a){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",s=!(arguments.length>5)||void 0===arguments[5]||arguments[5],i=this.getStyleTextSnapshot(e)??n8(t),o=a.trim(),l=i.findIndex(e=>e.name===r);if(o||!s){let e={name:r,value:o||(l>=0?i[l].value:""),priority:n,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,a=Array.from(r.entries()).map(e=>{let[t,r]=e;return` ${t}: ${r.value}${r.priority?` !${r.priority}`:""};`}).join("\n");return`[${n2}="${t}"] {
21
+ ${a}
22
+ }`});this.getOverrideStyleElement().textContent=t.join("\n\n")}}class st{listeners=new Set;elementInspector;styleInspector;consoleRecorder;selectedNodeId=null;consoleUnsubscribe=null;constructor(e,t={}){this.elementInspector=new n1(e,()=>this.notify({type:"document"})),this.styleInspector=new se(e,this.elementInspector),this.consoleRecorder=new nR(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)}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,a,n){this.styleInspector.setInlineDeclaration(e,t,r,a,n),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,a,n,s){this.styleInspector.setRuleDeclaration(e,t,r,a,n,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 a=this.styleInspector.addRule(e,t,r);return this.notify({type:"style",styleSheetId:a?`rule:${a.id}`:"inspector:main"}),a}setRuleSelector(e,t,r){let a=this.styleInspector.setRuleSelector(e,t,r);return this.notify({type:"style",styleSheetId:a?`rule:${a.id}`:`rule:${t}`}),a}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)}}function sr(e){return"object"==typeof e&&null!==e||"function"==typeof e}function sa(e){return Array.isArray(e)?"array":void 0}function sn(e){return Array.isArray(e)?`Array(${e.length})`:ss(e)}function ss(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 si(e,t){return{name:e,type:so(t),subtype:sr(t)?sa(t):void 0,value:sr(t)?sn(t):String(t)}}function so(e){return null===e?"object":typeof e}function sl(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(sr(e)){let r;return{type:"function"==typeof e?"function":"object",subtype:"function"==typeof e?void 0:sa(e),className:"function"==typeof e?"Function":ss(e),description:"function"==typeof e?e.toString():sn(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:sa(e),description:sn(e),overflow:r.length>5,properties:r.slice(0,5).map(t=>{try{let r=Object.getOwnPropertyDescriptor(e,t);return si(t,r&&"value"in r?r.value:void 0)}catch{return si(t,void 0)}})})}}return{type:so(e),value:e,description:String(e)}}function sd(e,t){return(e.args??[e.message]).map(e=>sl(e,t))}function su(e,t){return{startLine:0,startColumn:e,endLine:0,endColumn:t}}function sc(e,t){let r=0,a="",n=t.map(e=>{let t=`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`,n=e.active?t:`/* ${t} */`,s=su(r,r+n.length);return a+=`${n} `,r=a.length,{name:e.name,value:e.value,important:"important"===e.priority,disabled:!e.active,parsedOk:!0,implicit:!1,text:n,range:s}});return{styleSheetId:e,cssText:a.trim(),range:su(0,Math.max(0,a.trim().length)),shorthandEntries:[],cssProperties:n}}function sp(e){let t=e.indexOf(":");return t<0?{kind:e,id:""}:{kind:e.slice(0,t),id:e.slice(t+1)}}function sm(e){let t,r=e.includes("{")?e.slice(e.indexOf("{")+1,e.lastIndexOf("}")):e,a=[],n=/\/\*([\s\S]*?)\*\//g,s=0;for(;t=n.exec(r);)a.push(...sh(r.slice(s,t.index),!0)),a.push(...sh(t[1],!1)),s=t.index+t[0].length;return a.push(...sh(r.slice(s),!0)),a}function sh(e,t){let r=[];for(let a of e.split(";")){let e=a.indexOf(":");if(e<=0)continue;let n=a.slice(0,e).trim(),s=a.slice(e+1).trim(),i="";/!\s*important$/i.test(s)&&(s=s.replace(/!\s*important$/i,"").trim(),i="important"),n&&r.push({name:n,value:s,priority:i,active:t})}return r}let sg=new Map([["x-view","view"],["x-text","text"]]);function sf(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 sv(e){return sf(e)?e.attributes.filter(e=>"part"!==e.name&&"lynx-default-overflow-visible"!==e.name):e.attributes}function sy(e){return sv(e).flatMap(e=>[e.name,e.value])}function s_(e){return sf(e)?"page":sg.get(e.name)??e.name}function sb(e,t){var r;return(null==(r=e.attributes.find(e=>e.name===t))?void 0:r.value)||void 0}function sw(e,t){return e.type===t.type&&e.name===t.name&&(t.id?sb(e,"id")===t.id:!t.className||sb(e,"class")===t.className)}function sS(e,t){let r=Number(e);return Number.isFinite(r)?r<0?1/0:r:t}function sx(e){return e===1/0?e:Math.max(0,e-1)}function sI(e){if("text"===e.type)return e.textContent??"";if("document"===e.type)return sC(e);let t=sv(e).map(e=>` ${e.name}="${e.value}"`).join(""),r=e.children.map(e=>sI(e)).join(""),a=s_(e);return`<${a}${t}>${r}</${a}>`}function sC(e){return e.children.map(e=>sI(e)).join("")}function sE(e,t){let r=(e,a)=>{let n=[...a,e];if(e.id===t)return n;for(let t of e.children){let e=r(t,n);if(e)return e}return null};return r(e,[])}let sk="__wsd_document__";function sN(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}let sR="wsd-main-frame";function sT(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function sM(e){var t;let r;if(e instanceof ArrayBuffer)return{base64Encoded:!0,body:eF(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 sA(e){throw Object.assign(Error(e),{code:-32602})}function sP(e,t,r){return e??sA(null===e?r:t)}class sj{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,rk.add(r),()=>rk.delete(r)),this.enabledSessions.set(this.getSessionKey(t),{maxPostDataSize:sT(null==e?void 0:e.maxPostDataSize,65536),maxTotalBufferSize:sT(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=sP(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=sP(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 a=void 0===e.request.body?void 0:sM(e.request.body),n={request:e.request,sessions:new Set(this.enabledSessions.keys())};this.requests.set(e.requestId,n),a&&this.storePayload(n,"requestBody",a);let s=(r=(t=e.request.url).indexOf("#"))<0?{url:t}:{url:t.slice(0,r),urlFragment:t.slice(r)};for(let t of n.sessions){let r=this.enabledSessions.get(t);if(!r)continue;let n=a&&!a.base64Encoded&&a.byteLength<=r.maxPostDataSize;this.emit({method:"Network.requestWillBeSent",params:{documentURL:s.url,frameId:sR,initiator:{type:"script"},loaderId:sR,redirectHasExtraInfo:!1,request:{...s,hasPostData:!!a,headers:e.request.headers,initialPriority:"High",isSameSite:!0,method:e.request.method,mixedContentType:"none",...n?{postData:a.body}:{},referrerPolicy:"no-referrer"},requestId:e.requestId,timestamp:e.timestamp,type:"XHR",wallTime:e.wallTime}},this.getSessionId(t))}}handleResponseReceived(e,t){var r;let a=e.response??{},n=!(r=a.header)||"object"!=typeof r||Array.isArray(r)?{}:Object.fromEntries(Object.entries(r).map(e=>{let[t,r]=e;return[t,String(r)]})),s=sM(a.data),{charset:i,mimeType:o}=function(e){var t,r;let a,n=(null==(a=Object.entries(e).find(e=>{let[t]=e;return"content-type"===t.toLowerCase()}))?void 0:a[1])??"",[s=""]=n.split(";");return{charset:(null==(r=/(?:^|;)\s*charset\s*=\s*["']?([^;"']+)/i.exec(n))||null==(t=r[1])?void 0:t.trim())??"",mimeType:s.trim()}}(n),l="number"==typeof a.statusCode&&Number.isFinite(a.statusCode)?a.statusCode:0;this.storePayload(t,"responseBody",s),this.emitForRequest(t,{method:"Network.responseReceived",params:{frameId:sR,hasExtraInfo:!1,loaderId:sR,requestId:e.requestId,response:{charset:i,connectionId:0,connectionReused:!1,encodedDataLength:s.byteLength,fromDiskCache:!1,fromPrefetchCache:!1,fromServiceWorker:!1,headers:n,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?sA("requestId must be a non-empty string"):e.requestId,a=this.requests.get(r);return(null==a?void 0:a.sessions.has(this.getSessionKey(t)))?a:sA(`Unknown requestId: ${r}`)}storePayload(e,t,r){let a=e[t];a&&(this.payloads.delete(a),this.storedPayloadSize-=a.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,a]]=e;this.payloads.delete(t),this.storedPayloadSize-=t.byteLength,r[a]=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 sD{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(sk),a=sx(t),n=t>0?[this.toCdpNode(e,a,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:n};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,a=this.getCdpNodeId(e.id),n=sx(t),s=t>0?e.children.map(e=>this.toCdpNode(e,n,a)):void 0,i="text"===e.type,o="document"===e.type,l=s_(e),d={nodeId:a,backendNodeId:a,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?sy(e):void 0,children:s};return this.cdpNodes.set(a,d),d}}function sL(e){return e.map(e=>({...e}))}function sO(e){return"attributes"===e.type||"characterData"===e.type}class sU{adapter;consoleAdapter=null;appAdapter=null;appTarget=null;target;listeners=new Set;options;nodeStore=new sD;network;consoleStore=nb();appConsoleStore=nb();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;parsedScriptIdsBySession=new Map;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 sj((e,t)=>this.emit(e,t)),this.subscribeAdapter(),this.createConsoleAdapter()}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 a=null==(r=this.adapter.getMatchedStyles(e))?void 0:r.computedStyles;if(!a)return null;if(!(null==t?void 0:t.length))return a;let n=new Set(t);return a.filter(e=>n.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(a){let t,r={id:e.id,error:{code:"number"==typeof(t=null==a?void 0:a.code)?t:-32603,message:a instanceof Error?a.message:String(a)}};return e.sessionId&&(r.sessionId=e.sessionId),r}}destroy(){var e,t,r,a,n;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==(a=this.unsubscribeAppAdapter)||a.call(this),this.unsubscribeAppAdapter=null,null==(n=this.appAdapter)||n.destroy(),this.appAdapter=null,this.appTarget=null,this.adapter.destroy(),this.network.destroy(),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 st(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 st(e,{consoleStore:this.options.preserveConsoleOnTargetChange?this.consoleStore:void 0})}createAppTargetAdapter(e){return new st(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,a=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.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(),a&&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,a,n,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==(a=this.appAdapter)||a.destroy(),this.appTarget=i,this.appAdapter=this.createAppTargetAdapter(i),this.subscribeAppAdapter(),this.emit({method:"WSD.appConsoleUpdated"})),this.appAdapter):(null==(n=this.unsubscribeAppAdapter)||n.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":for(let t of(this.debuggerEnabledSessions.add(this.getSessionKey(e.sessionId)),this.getAppAdapter(),this.emitNewConsoleEntries("app"),[this.getConsoleAdapter().getConsoleEntries(),this.appConsoleStore.entries]))for(let r of t)"host"!==r.source&&this.emitScriptParsedEvents(this.toCdpStackTrace(r.stackTrace),e.sessionId);return{debuggerId:"wsd-debugger"};case"Debugger.disable":return this.debuggerEnabledSessions.delete(this.getSessionKey(e.sessionId)),this.parsedScriptIdsBySession.delete(this.getSessionKey(e.sessionId)),{};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(),a=sS(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,a):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),a=this.nodeStore.resolveInspectorNodeId(r),n=sS(null==e?void 0:e.depth,1),s=this.adapter.getDocument(),i=a===sk?null:this.findInspectorNode(a),o=a===sk?s?[this.nodeStore.toCdpNode(s,sx(n),r)]:[]:(null==i?void 0:i.children.map(e=>this.nodeStore.toCdpNode(e,sx(n),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 a=Number(e),n=this.nodeStore.getInspectorNodeId(a);return r&&n&&this.materializeInspectorNodePath(r,n,t)?a:0})}}materializeInspectorNodePath(e,t,r){let a=sE(e,t);if(!a)return!1;let n=this.nodeStore.getCdpNodeId(sk);for(let t of(this.emit({method:"DOM.setChildNodes",params:{parentId:n,nodes:[this.nodeStore.toCdpNode(e,0,n)]}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:n,childNodeCount:1}},r),a.slice(0,-1))){let e=this.nodeStore.getCdpNodeId(t.id),a=t.children.map(t=>this.nodeStore.toCdpNode(t,0,e));this.emit({method:"DOM.setChildNodes",params:{parentId:e,nodes:a}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:e,childNodeCount:a.length}},r)}return!0}revealDocumentAfterUpdate(e,t,r){if(!(null==r?void 0:r.length))return;let a=this.findInspectorNodeBySignaturePath(e,r??null),n=a??this.findDocumentRevealNode(e);if(!n||!this.materializeInspectorNodePath(e,n.id,t))return;let s=this.nodeStore.getCdpNodeId(n.id),i=!!a||!(null==r?void 0:r.length);this.selectInspectorNode(n.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=sE(e,t);if(r)return r[r.length-1]}let r=this.findInspectorNodeBySignaturePath(e,this.selectedNodeSignaturePath);if(r)return r;let a=e;for(let e=0;e<3;e+=1){let e=a.children.find(e=>"element"===e.type);if(!e)break;a=e}return a}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?sE(t,e):null;if(r){let e=r.map(e=>({type:e.type,name:e.name,className:sb(e,"class"),id:sb(e,"id")}));return this.selectedNodeSignaturePath=e,e}return null}findInspectorNodeBySignaturePath(e,t){if(!(null==t?void 0:t.length)||!sw(e,t[0]))return null;let r=e;for(let e of t.slice(1)){let t=r.children.find(t=>sw(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),a=this.findInspectorNode(r),n=this.adapter.getDocument();return{node:r===sk&&n?this.nodeStore.toDocumentCdpNode(n):a?this.nodeStore.toCdpNode(a):null}}getAttributes(e){let t=this.findInspectorNode(this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId));return{attributes:t?sy(t):[]}}getOuterHTML(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.findInspectorNode(t),a=this.adapter.getDocument();return{outerHTML:t===sk&&a?sI(a):r?sI(r):""}}setAttributesAsText(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),a=String((null==e?void 0:e.text)??""),n="string"==typeof(null==e?void 0:e.name)?e.name:void 0,s=this.applyDomEdit(()=>this.adapter.setAttributesAsText(r,a,n));return this.emitDomMutations(s,t),{}}setAttributeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),a=String((null==e?void 0:e.name)??""),n=String((null==e?void 0:e.value)??""),s=this.applyDomEdit(()=>this.adapter.setAttributeValue(r,a,n));return this.emitDomMutations(s,t),{}}removeAttribute(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),a=String((null==e?void 0:e.name)??""),n=this.applyDomEdit(()=>this.adapter.removeAttribute(r,a));return this.emitDomMutations(n,t),{}}setNodeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),a=String((null==e?void 0:e.value)??""),n=this.applyDomEdit(()=>this.adapter.setNodeValue(r,a));return this.emitDomMutations(n,t),{}}setNodeName(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),a=String((null==e?void 0:e.name)??""),n=this.applyDomEdit(()=>this.adapter.setNodeName(r,a),!0);return this.emitDomMutations(n.mutations,t),{nodeId:n.nodeId?this.nodeStore.getCdpNodeId(n.nodeId):0}}setOuterHTML(e,t){let r=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),a=String((null==e?void 0:e.outerHTML)??""),n=this.applyDomEdit(()=>this.adapter.setOuterHTML(r,a),!0);return this.emitDomMutations(n,t),{}}applyDomEdit(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t?this.adapter.getDocument():null,a=r?this.createDomRootSnapshot(r):null,n=e(),s=Array.isArray(n)?n:n.mutations,i=s.filter(sO),o=null;return s.length>0&&i.length===s.length?o={type:"mutations",mutations:i}:s.length>0&&a&&(o=a),o&&this.rememberDomUndoEntry(o),n}createDomRootSnapshot(e){return{type:"rootSnapshot",rootHtml:"document"===e.type?sC(e):sI(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 a of r.removedNodeIds)this.emit({method:"DOM.childNodeRemoved",params:{parentNodeId:e,nodeId:this.nodeStore.getCdpNodeId(a)}},t);for(let a of r.insertedNodes)this.emit({method:"DOM.childNodeInserted",params:{parentNodeId:e,previousNodeId:a.previousNodeId?this.nodeStore.getCdpNodeId(a.previousNodeId):0,node:this.nodeStore.toCdpNode(a.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:sc(`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?sc(`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??""),a=sm(String(e.text??"")),{id:n,kind:s}=sp(t),i=this.adapter.getSelectedNodeId(),o="inline"===s?n:i,l=this.getDeclarationsForStyleSheet(t);"inline"===s?this.adapter.setInlineDeclarations(n,a):"rule"===s&&i&&this.adapter.setRuleDeclarations(i,n,a),r.push(this.getStylePayloadForStyleSheet(t,a)),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)??""),a=String((null==e?void 0:e.value)??"");return r&&this.adapter.setInlineDeclaration(t,r,a),{}}addRule(e){let t=String((null==e?void 0:e.ruleText)??""),r=this.getRuleSelectorText(t),a=sm(t).map(e=>({...e,active:!0})),n=this.adapter.getSelectedNodeId(),s=n?this.adapter.addRule(n,r,a):null;return{rule:s?this.toCdpRulePayload(s):{origin:"inspector",selectorList:this.toSelectorList(r),style:sc("inspector:main",a)}}}setRuleSelector(e){let t=String((null==e?void 0:e.selector)??(null==e?void 0:e.text)??"").trim(),{id:r,kind:a}=sp(String((null==e?void 0:e.styleSheetId)??"")),n=this.adapter.getSelectedNodeId(),s="rule"===a&&n?this.adapter.setRuleSelector(n,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(!sr(e))return[];try{return Object.getOwnPropertyNames(e).map(r=>{let a=Object.getOwnPropertyDescriptor(e,r),n={name:r,configurable:(null==a?void 0:a.configurable)??!0,enumerable:(null==a?void 0:a.enumerable)??!0,isOwn:!0};return a&&"value"in a&&(n.value=sl(a.value,t),n.writable=a.writable),n})}catch{return[]}}(t,this.remoteObjectStore),internalProperties:function(e,t){if(!sr(e))return[];let r=Object.getPrototypeOf(e);return r?[{name:"[[Prototype]]",value:sl(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),{}}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:a,onNodeHighlightRequested:n,onNodeInspected:s}=e;t.classList.add("is-inspecting");let i=e=>{let t=r(e.clientX,e.clientY);t&&n(t)},o=()=>{a(null)},l=e=>{if(0!==e.button)return;let a=r(e.clientX,e.clientY);a&&(sN(e),function(e){let t=["mousedown","mouseup","pointerup","pointercancel","click","dblclick","auxclick","contextmenu"],r=[e,e.ownerDocument],a=e.ownerDocument.defaultView;a&&r.push(a);let n=null,s=()=>{for(let e of(null!==n&&(window.clearTimeout(n),n=null),r))for(let r of t)e.removeEventListener(r,i,!0)},i=e=>{sN(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);n=window.setTimeout(s,800)}(t),s(a))};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),a(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,a;let n=null==(r=(a=this.options).resolveTargetAtPoint)?void 0:r.call(a,e,t);n&&this.setTarget(n);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(),a=String((null==e?void 0:e.value)??""),n="string"==typeof(null==e?void 0:e.ruleId)?e.ruleId:null;if(!r)throw Error("CSS property name is required");return n?this.adapter.setRuleDeclaration(t,n,r,a):this.adapter.setInlineDeclaration(t,r,a),{}}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 a=this.adapter.setOuterHTML(r.id,e.rootHtml);return 0!==a.length&&(this.emitDomMutations(a,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)),a=new Set(e.removed),n=[];for(let r of e.modified)t.has(r.name)||n.push(...this.adapter.removeAttribute(e.nodeId,r.name));for(let t of e.before)(r.has(t.name)||a.has(t.name))&&n.push(...this.adapter.setAttributeValue(e.nodeId,t.name,t.value));return n}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,a){var n;t&&JSON.stringify(r)!==JSON.stringify(a)&&((null==(n=this.pendingUndoEntry)?void 0:n.type)!=="style"||this.pendingUndoEntry.entry.styleSheetId!==e||this.pendingUndoEntry.entry.nodeId!==t)&&this.setPendingUndoEntry({type:"style",entry:{styleSheetId:e,nodeId:t,previousDeclarations:sL(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}=sp(e.styleSheetId);this.isApplyingStyleEdit=!0;try{"inline"===r?this.adapter.setInlineDeclarations(t,sL(e.previousDeclarations)):"rule"===r&&this.adapter.setRuleDeclarations(e.nodeId,t,sL(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(),a=r?this.adapter.getNodeHighlight(t,r):null,n=(null==a?void 0:a.left)??0,s=(null==a?void 0:a.top)??0,i=(null==a?void 0:a.width)??0,o=(null==a?void 0:a.height)??0,l=[n,s,n+i,s,n+i,s+o,n,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,a;let{id:n,kind:s}=sp(e),i=t.map(e=>({name:e.name,value:e.value,priority:e.priority,active:e.active}));if("inline"===s)return sc(e,(null==(r=this.adapter.getMatchedStyles(n))?void 0:r.inlineStyle.declarations)??i);if("rule"===s){let t=this.adapter.getSelectedNodeId(),r=t?null==(a=this.adapter.getMatchedStyles(t))?void 0:a.matchedRules.find(e=>e.id===n):null;return sc(e,(null==r?void 0:r.declarations)??i)}return sc(e,i)}getDeclarationsForStyleSheet(e){var t,r;let{id:a,kind:n}=sp(e);if("inline"===n)return sL((null==(t=this.adapter.getMatchedStyles(a))?void 0:t.inlineStyle.declarations)??[]);if("rule"===n){let e=this.adapter.getSelectedNodeId(),t=e?null==(r=this.adapter.getMatchedStyles(e))?void 0:r.matchedRules.find(e=>e.id===a):null;return sL((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:su(0,e.length)}],text:e}}toCdpRulePayload(e){let t=`rule:${e.id}`,r=sc(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:sd(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 a=r.get(t)??new Set;return r.set(t,a),a}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}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){let r=this.getSessionKey(t),a=this.getScriptId(e),n=this.getParsedScriptIds(r);!this.debuggerEnabledSessions.has(r)||n.has(a)||(n.add(a),this.emit({method:"Debugger.scriptParsed",params:{scriptId:a,url:e,startLine:0,startColumn:0,endLine:1,endColumn:0,executionContextId:1,hash:"",executionContextAuxData:{isDefault:!0,frameId:"wsd-main-frame"},isLiveEdit:!1,hasSourceURL:!1,isModule:!1,length:0,scriptLanguage:"JavaScript"}},t))}emitScriptParsedEvents(e,t){null==e||e.callFrames.forEach(e=>e.url&&this.emitScriptParsed(e.url,t))}emit(e){for(var t=arguments.length,r=Array(t>1?t-1:0),a=1;a<t;a++)r[a-1]=arguments[a];let n=r.length>0?r[0]:this.activeSessionId,s=n?{...e,sessionId:n}: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 a="app"===t?this.appConsoleStore.entries:this.getConsoleAdapter().getConsoleEntries(),n=this.getKnownConsoleEntryIds(r,t);for(let t of a){var s;if(n.has(t.id)||(n.add(t.id),"host"===t.source))continue;let r=this.toCdpStackTrace(t.stackTrace);this.emitScriptParsedEvents(r,e);let a={type:"warn"===(s=t.level)?"warning":"eval"===s?"log":s,args:sd(t,this.remoteObjectStore),executionContextId:1,timestamp:t.timestamp};r&&(a.stackTrace=r),this.emit({method:"Runtime.consoleAPICalled",params:a},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 sq="AppletJSModule",s$=["log","info","warn","error","debug"];function sB(e,t,r){if("log"!==e)return null;let a=ez(t)&&("string"==typeof t.message||Array.isArray(t.args))?{level:s$.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 a?r===sq?a:null:r!==sq?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 sF{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):ny(this.current,e)}flush(){if(this.current)for(let e of this.runtimeConsoleEvents.splice(0))ny(this.current,e)}}let sH=new Set(["doubao.navigateTo","doubao.redirectTo","doubao.reLaunch","doubao.navigateBack","doubao.exitApp","doubao.close"]);function sW(e){return"string"==typeof e&&e.trim()?e.trim().replace(/^\/+/,""):void 0}function sz(e){return sW(null==e?void 0:e.path)??sW(null==e?void 0:e.id)}class sV{container;nativeModulesCallHandler;webSdkDebugger;onExitApp;onError;apiEnvironment;previewTarget=new sF;appPreviewTarget=new sF;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.nativeModulesCallHandler=e.nativeModulesCallHandler,this.webSdkDebugger=e.webSdkDebugger,this.onExitApp=e.onExitApp,this.onError=e.onError,this.apiEnvironment=e.apiEnvironment??nd(),"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(),a=!t.entry&&!t.pageId&&(null==(e=r.pageSelection)?void 0:e.routeUrl)?eL({url:r.pageSelection.routeUrl},r.manifest):void 0,n=(null==a?void 0:a.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??t3["0"],i=(null==a?void 0:a.initData)??t.initData??{},o=a?t6(s,{...t.globalProps,...a.globalProps}):t.globalProps??t6(s),l=this.getRuntime(r),d=sz(n);this.lastRenderOptions=t,this.isRuntimeTargetChanging=!0,this.deferredPagePath=d;try{let e=l.replacePage({entry:n,initData:i,globalProps:o,pageCapsule:t.pageCapsule??{statusBarHeight:s.statusBarHeight}});return this.bindPageTarget(e.element,d??sz(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){if(!this.runtime){let t={container:this.container,manifest:e.manifest,manifestUrl:e.manifestUrl,apiRegistry:this.apiEnvironment.apiRegistry,nativeModulesCallHandler:this.handleNativeModulesCall,onError:this.onError,runtimeHost:{...this.apiEnvironment.runtimeHost,mountRuntimeEmptyState:e=>re(e,()=>this.reopenCurrentPage())}};return this.runtime=new eU(t),this.runtimeManifestUrl=e.manifestUrl,this.runtime}return this.runtimeManifestUrl!==e.manifestUrl&&(this.previewTarget.set(null),this.appPreviewTarget.set(null),this.runtime.setManifest(e.manifest,e.manifestUrl),this.runtimeManifestUrl=e.manifestUrl),this.runtime}handleNativeModulesCall=(e,t,r,a)=>{var n;let s=function(e,t,r){if("AppletBridgeModule"===r&&"postMessage"===e&&"object"==typeof t&&null!==t&&"call"===t.type&&"string"==typeof t.name&&sH.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=sB(e,t,r);if(i){if((null==a?void 0:a.containerType)==="APP")this.syncAppRuntimeTarget(a.element),this.appPreviewTarget.dispatch({...i,label:"app"});else{let e=this.getRuntimeConsolePagePath(a);this.previewTarget.dispatch(e?{...i,pagePath:e}:i,this.isRuntimeTargetChanging)}return}return null==(n=this.nativeModulesCallHandler)?void 0:n.call(this,e,t,r,a)};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 sz(eL({url:r},this.webSdkDebugger.getState().manifest).entry)}catch{return sW(r.split("?")[0])}}getCurrentPagePath(){var e;let t=null==(e=this.runtime)?void 0:e.currentPage;return sz(null==t?void 0:t.entry)??sW(null==t?void 0:t.route)??sW(null==t?void 0:t.pageId)}getRuntimeConsolePagePath(e){var t,r;if((null==e?void 0:e.containerType)!=="PAGE")return;let a=this.pagePathsByTarget.get(e.element)??this.deferredPagePath??this.getCurrentPagePath();return this.bindPageTarget(null==(r=this.runtime)||null==(t=r.currentPage)?void 0:t.element,a),a}}class sG{container;nativeModulesCallHandler;webSdkDebugger;onError;apiEnvironment;previewTarget=new sF;widget=null;constructor(e){if(!e.container)throw Error("Widget preview controller requires a container element");this.container=e.container,this.nativeModulesCallHandler=e.nativeModulesCallHandler,this.webSdkDebugger=e.webSdkDebugger,this.onError=e.onError,this.apiEnvironment=e.apiEnvironment??nd()}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),a=e.viewport??t5,n=eW(e.initData??{}),s=e.globalProps??t8(a);this.clear(),this.widget=new eM({appId:t.manifest.appId,apiRegistry:this.apiEnvironment.apiRegistry,container:this.container,globalProps:s,initData:n,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 a;let n=sB(e,t,r);return n?void this.previewTarget.dispatch(n):null==(a=this.nativeModulesCallHandler)?void 0:a.call(this,e,t,r)}}let sK=(0,eB.createContext)(null);function sJ(e){let t=function(e){let t=(0,eB.useContext)(sK),r=e??t;if(!r)throw Error("WebSdkDebuggerProvider is missing");return r}(e),r=(0,eB.useCallback)(e=>t.subscribe(e),[t]),a=(0,eB.useCallback)(()=>t.getState(),[t]);return(0,eB.useSyncExternalStore)(r,a,a)}function sX(e){let t=(0,eB.useRef)(e);t.current=e;let r=(0,eB.useRef)();return r.current??=function(){for(var e=arguments.length,r=Array(e),a=0;a<e;a++)r[a]=arguments[a];return t.current(...r)},r.current}function sQ(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 sZ(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 sY(e){var t,r,a,n,i;let{highlightRect:o,overlay:l,runtimeFrameRef:d,runtimeFrameScaleBoxRef:u,runtimeScaleMode:c,runtimeShellRef:p,runtimeStyle:m,runtimeTargetRef:h}=e,g=(0,eB.useRef)(null),[f,v]=(0,eB.useState)(null),y=function(e,t){let r=e[t];if("number"==typeof r)return r;if("string"!=typeof r)return null;let a=Number.parseFloat(r);return Number.isFinite(a)?a: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==(a=o.boxModel)?void 0:a.content.top)??0}px`,"--wsd-highlight-content-width":`${(null==(n=o.boxModel)?void 0:n.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=sX(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=sX(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,eh.$)("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)(sQ,{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)(sZ,{focusable:o.accessibility.keyboardFocusable})})]})]})]}):null]})]}):null,l]})})})}function s0(e){let t,r,a,{cashier:n,onCancel:i,onConfirm:o}=e,[l,d]=(0,eB.useState)(!1),[u,c]=(0,eB.useState)(""),[p,m]=(0,eB.useState)(n.paymentTypes[0].id),h=n.paymentTypes.find(e=>{let{id:t}=e;return t===p})||n.paymentTypes[0],g=n.paymentTypes.length>1,f=async()=>{if(!l){d(!0),c("");try{await o(p)}catch(e){d(!1),c(ak(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=n.totalAmount.replace(/^0+(?=\d)/,"").padStart(3,"0")).slice(0,-2)||"0",a=t.slice(-2),`\xa5${r.replace(/\B(?=(\d{3})+(?!\d))/g,",")}.${a}`)})}),(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:n.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 s1(){let[e,t]=(0,eB.useState)(),r=(0,eB.useRef)(null),a=(0,eB.useRef)(null),n=(0,eB.useRef)(!1),s=sX((e,n)=>r.current?Promise.reject(Error("Sandbox cashier is already open")):new Promise(s=>{r.current=s,a.current=n,t(e)})),i=sX(e=>{let n=r.current;n&&(r.current=null,a.current=null,t(void 0),n(e))}),o=sX(()=>{n.current||i(!1)}),l=sX(async e=>{let t=a.current;if(!t)throw Error("Sandbox cashier is unavailable");if(!n.current){n.current=!0;try{await t(e),i(!0)}finally{n.current=!1}}});return(0,eB.useEffect)(()=>()=>{let e=r.current;r.current=null,a.current=null,n.current=!1,null==e||e(!1)},[]),{cashier:e,cancelCashier:o,confirmCashier:l,showCashier:s}}var s2=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 s3(){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 s4(e){let{className:t,fallback:r,src:a}=e,[n,i]=(0,eB.useState)(!1);return(0,eB.useEffect)(()=>{i(!1)},[a]),(0,s.jsx)("span",{className:`${t}-box`,"aria-hidden":"true",children:a&&!n?(0,s.jsx)("img",{alt:"",className:t,onError:()=>i(!0),src:a}):(0,s.jsx)("span",{className:`${t}-fallback`,children:(null==r?void 0:r.trim().slice(0,1))||"服"})})}function s5(e){let t=Number(e);if(!Number.isFinite(t))return;let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}function s6(e){let{notices:t,onAction:r,onBack:a,status:n}=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)(s3,{}),(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:a,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)(s2,{"aria-hidden":"true"})})]})]}),(0,s.jsx)("div",{className:"wsd-service-notice-list",children:"loading"===n&&0===t.length?(0,s.jsx)("p",{className:"wsd-service-notice-empty",children:"正在加载服务通知..."}):t.length>0?t.map(e=>{let t=e.title||"服务通知",a=s5(e.created_at_ms),n=e.redirect_url;return(null==n?void 0:n.startsWith("sslocal://"))&&(n=""),(0,s.jsxs)("div",{className:"wsd-service-notice-item",children:[(0,s.jsx)("time",{dateTime:null==a?void 0:a.toISOString(),children:function(e){let t=s5(e);if(!t)return"";let r=new Date,a=new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime(),n=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 n===a?s:n===a-864e5?`昨天 ${s}`:`${t.getMonth()+1}月${t.getDate()}日 ${s}`}(e.created_at_ms)}),(0,s.jsxs)("article",{"aria-label":n?`${t},查看详情`:void 0,className:`wsd-service-notice-card${n?" is-clickable":""}`,onClick:()=>{n&&(null==r||r(n))},onKeyDown:e=>{n&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),null==r||r(n))},role:n?"link":void 0,tabIndex:n?0:void 0,children:[(0,s.jsxs)("div",{className:"wsd-service-notice-app",children:[(0,s.jsx)(s4,{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 s8=new Set([1,2,3]);function s7(e){return e.filter(e=>1!==e.display_status&&s8.has(e.status))}function s9(e){let{onAction:t,onClose:r,onRemove:a,removingTaskIds:n,tasks:i}=e,o=s7(i);async function l(e){var r,n;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==(n=e.remove_action)?void 0:n.target)&&await (null==t?void 0:t(e.remove_action.target)),await a(e.task_id))}return((0,eB.useEffect)(()=>{let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[r]),(0,eB.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,a,i,o,d,u;let c=(null==(r=e.display_data)?void 0:r.title)||"未命名任务",p=(null==(a=e.display_data)?void 0:a.sub_title)||(null==(i=e.progress)?void 0:i.text),m=null==(o=e.primary_action)?void 0:o.target,h=n.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,eh.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)(s4,{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 ie={hasUnreadNotices:!1,hasUnreadTasks:!1,markServiceNoticesRead:()=>void 0,markTasksRead:()=>void 0,notices:[],removeTask:async()=>void 0,removingTaskIds:new Set,status:"unavailable",tasks:[]},it=(0,eB.createContext)(ie);function ir(e,t){try{let r=BigInt(e),a=BigInt(t);return r===a?0:r>a?1:-1}catch{return String(e).localeCompare(String(t),void 0,{numeric:!0})}}function ia(e){if(eH(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 is(e){let{children:t,enabled:r,eventsEndpoint:a,onMessage:n}=e,[i,o]=(0,eB.useState)([]),[l,d]=(0,eB.useState)([]),[u,c]=(0,eB.useState)(!1),[p,m]=(0,eB.useState)(!1),[h,g]=(0,eB.useState)(r&&a?"loading":"unavailable"),[f,v]=(0,eB.useState)(new Set),y=(0,eB.useRef)(new Map),_=(0,eB.useRef)(new Map),b=(0,eB.useRef)(new Map),w=(0,eB.useRef)(new Map),S=(0,eB.useRef)({notice:void 0,task:void 0}),x=(0,eB.useRef)({}),I=(0,eB.useRef)(0),C=(0,eB.useRef)(n);C.current=n;let E=sX(()=>{o([...y.current.values()].sort((e,t)=>Number(e.created_at_ms)-Number(t.created_at_ms)))}),k=sX(()=>{d([..._.current.values()].sort((e,t)=>Number(t.updated_at_ms)-Number(e.updated_at_ms)))}),N=sX(e=>{let t=!1;for(let r of e.notices??[]){let e=b.current.get(r.notice_id);(void 0===e||ir(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||ir(t.revision,e)>=0)&&(b.current.set(t.resource_id,t.revision),y.current.delete(t.resource_id))}t&&c(!0),E()}),R=sX(e=>{let t=w.current.get(e.resource_id);(void 0===t||ir(e.revision,t)>=0)&&(w.current.set(e.resource_id,e.revision),_.current.delete(e.resource_id),k())}),T=sX(e=>{let t=!1;for(let r of e.tasks??[]){let e=w.current.get(r.task_id);void 0!==e&&0>=ir(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||ir(r.revision,e)>=0)&&(w.current.set(r.resource_id,r.revision),_.current.delete(r.resource_id),t=!0)}t&&m(!0),k()}),M=sX(async(e,t)=>{let r=!1;do{let a=S.current[e],n="notice"===e?await aO({cursor:a,limit:100}):await aU({cursor:a,limit:100});if(I.current!==t)return;if("notice"===e?N(n):T(n),n.has_more&&!n.next_cursor)throw Error(`Sandbox ${e} pull returned has_more without next_cursor`);n.next_cursor&&(S.current[e]=n.next_cursor),r=n.has_more}while(r)}),A=sX((e,t)=>{let r=x.current[e];if(r)return r;let a=M(e,t).finally(()=>{x.current[e]===a&&delete x.current[e]});return x.current[e]=a,a}),P=sX(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||ir(e.revision,t)>=0)&&(b.current.set(e.resourceId,e.revision),y.current.delete(e.resourceId),E())}else R(t);return}if("notice"===e.resource){let r=await aO({notice_ids:[e.resourceId]});I.current===t&&N(r)}else{let r=await aU({task_ids:[e.resourceId]});I.current===t&&T(r)}}}),j=sX(()=>{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,eB.useEffect)(()=>{let e,t,n;if(!r||!a){I.current+=1,j(),g("unavailable");return}let s=!1,i=++I.current,o=!1,l=0,d=0,u=-1;j(),g("loading");let c=()=>Promise.all([A("notice",i),A("task",i)]);c().then(()=>{s||I.current!==i||(o=!0,g("reconnecting"===n?"reconnecting":"connected"))}).catch(e=>{var t;if(s)return;let r=e instanceof Error?e.message:String(e);g("error"),null==(t=C.current)||t.call(C,`Sandbox 资源同步失败:${r}`,!0)});let p=async()=>{t=new AbortController;try{let e=await fetch(a,{cache:"no-store",headers:{Accept:"application/json"},signal:t.signal});if(!e.ok)throw Error(`资源事件接口请求失败(HTTP ${e.status})`);let r=function(e){if(eH(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(ia).filter(e=>!!e):[],generation:e.generation,updatedAtMs:e.updatedAtMs}}(await e.json());if(!r)throw Error("资源事件接口返回格式错误");if(s)return;if(r.updatedAtMs!==u){u=r.updatedAtMs,0===d?d=r.generation:r.generation!==d&&(d=r.generation,l=0,i=++I.current,o=!1,j(),g("loading"),await c(),o=!0);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 c(),e))await P(t,i),l=Math.max(l,t.sequence)}"reconnecting"===r.connectionStatus&&"reconnecting"!==n?(g("reconnecting"),await c()):o&&"connected"===r.connectionStatus&&g("connected"),n=r.connectionStatus}catch(e){s||(null==t?void 0:t.signal.aborted)||g("reconnecting")}finally{s||(e=window.setTimeout(p,800))}};return p(),()=>{s=!0,I.current+=1,null==t||t.abort(),void 0!==e&&window.clearTimeout(e)}},[r,a,A,P,j]);let D=sX(async e=>{v(t=>new Set(t).add(e));try{let t=await aq(e);R(t)}finally{v(t=>{let r=new Set(t);return r.delete(e),r})}}),L=sX(()=>{c(!1)}),O=sX(()=>{m(!1)}),U=(0,eB.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)(it.Provider,{value:U,children:t})}var ii=r(64031),io=r(88460);let il={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 id(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)(ii.oz,{components:il,remarkPlugins:[io.A],children:t})})}function iu(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:eH(e.source)?e.source.tool_call_id:void 0,render_data:e.render_data}}function ic(e){let{apiEnvironment:t,appId:r,card:a,inspectableTargetKey:n,reloadKey:i,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:c,onUpdateWidget:p,requestId:m,runtimeConsoleTarget:h,traceId:g,viewport:f,widgets:v}=e,y=(0,eB.useRef)(null),_=(0,eB.useRef)(null),b=(0,eB.useRef)(null),w=a.widget_id,S=f??t5,x=!!w&&((null==v?void 0:v.some(e=>e.widgetId===w))??!1),[I,C]=(0,eB.useState)(0),[E,k]=(0,eB.useState)(0),[N,R]=(0,eB.useState)({status:"idle"}),T=I>0?I:S.width,M=(0,eB.useMemo)(()=>({...S,width:T}),[S,T]),A={height:`${Math.round(+(E||Math.round(1.35*T)))}px`,width:`${Math.round(+T)}px`},P={"--wsd-widget-chat-card-runtime-scale":1,width:`${T}px`},j=(0,eB.useMemo)(()=>{if(!p)return null==t?void 0:t.apiRegistry;let e=(null==t?void 0:t.apiRegistry.fork())??nl();return e.register("doubao.updateWidget",{handler:e=>{let t=function(e){if(eH(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 u(e,"Invalid doubao.updateWidget parameters");let r=p(t);return"updated"===r.status?d(e,{}):u(e,r.message)}},{override:!0}),e},[null==t?void 0:t.apiRegistry,p]),D=(0,eB.useMemo)(()=>(e,t,r,a)=>{let n=sB(e,t,r);return n?void ny(h??a.element,n):null==o?void 0:o(e,t,r,a)},[o,h]);return(0,eB.useEffect)(()=>{let e=_.current;if(!e)return;let t=()=>{let t=y.current,r=null==t?void 0:t.closest(".wsd-widget-chat-card");C(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),a=y.current,n=null==a?void 0:a.closest(".wsd-widget-chat-card");return r.observe(e),a&&r.observe(a),n instanceof HTMLElement&&r.observe(n),()=>{r.disconnect()}},[]),(0,eB.useEffect)(()=>{let e,s,i=b.current;if(!i)return;if(i.replaceChildren(),k(0),n&&(null==l||l(n,null)),!w){let e="缺少 widget_id,已展示 fallback";R({status:"skipped",message:e}),null==c||c({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:e,...iu(a,m,g)});return}if(!r){let e="缺少 appId,已展示 fallback";R({status:"skipped",message:e}),null==c||c({category:"card",event:"simulator_card_render_skipped",reason:"missing_app_id",summary:e,...iu(a,m,g)});return}if(!x){let e=`Manifest 中找不到 widget_id: ${w}`;R({status:"skipped",message:e}),null==c||c({category:"card",event:"simulator_card_render_skipped",reason:"widget_not_found",summary:e,...iu(a,m,g)});return}let o=!1,d=null,u=t8(M,a.card_id?{__VIEW_CONTEXT__:{widgetInstanceId:a.card_id}}:{}),p=()=>{o||k(Math.ceil(i.scrollHeight||i.getBoundingClientRect().height))},h=()=>{"u"<typeof window?p():(void 0!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(p))},f=Date.now();R({status:"rendering"});try{d=new eM({appId:r,apiRegistry:j,container:i,globalProps:u,initData:eW(a.render_data),nativeModulesCallHandler:D,onError:e=>{null==c||c({category:"card",event:"simulator_card_runtime_error",elapsed_ms:Date.now()-f,summary:e.message,...iu(a,m,g)})},runtimeHost:null==t?void 0:t.runtimeHost,widgetId:w})}catch(t){let e=eJ(t);R({status:"error",message:e}),null==c||c({category:"card",event:"simulator_card_render_failed",elapsed_ms:Date.now()-f,summary:e,...iu(a,m,g)});return}return d.render().then(e=>{o||(R({status:"rendered"}),n&&(null==l||l(n,e)),h(),"u">typeof ResizeObserver&&(s=new ResizeObserver(h)).observe(i),null==c||c({category:"card",event:"simulator_card_rendered",elapsed_ms:Date.now()-f,...iu(a,m,g)}))}).catch(e=>{if(o)return;let t=eJ(e);R({status:"error",message:t}),n&&(null==l||l(n,null)),null==c||c({category:"card",event:"simulator_card_render_failed",elapsed_ms:Date.now()-f,summary:t,...iu(a,m,g)})}),()=>{o=!0,void 0!==e&&window.cancelAnimationFrame(e),null==s||s.disconnect(),null==d||d.destroy(),i.replaceChildren(),n&&(null==l||l(n,null))}},[t,j,r,a,D,n,l,c,i,M,x,w]),(0,s.jsxs)("div",{className:"wsd-widget-chat-card-runtime",ref:y,children:[(0,s.jsx)("div",{className:"wsd-widget-chat-card-runtime-viewport",ref:_,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:b,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 ip="mcp-privacy-login-card",im="__doubao_apps__expired-widget";function ih(e){return e.title||e.fallback_text||e.card_type||e.card_id||"卡片"}function ig(e,t){return(null==e?void 0:e.some(e=>e.widgetId===t))?e:[...e??[],{widgetId:t}]}function iv(e,t){return`${e.messageId}:${t.blockId}:${t.card.card_id||t.blockId}`}function iy(e){var t,r;let{apiEnvironment:a,appId:n,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,eB.useMemo)(()=>"card"===i.type&&i.card.widget_id===im?ig(_,im):_,[i,_]);if((0,eB.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)(id,{text:i.text});if("card"===(t=i).type&&"permission_apply"===t.card.card_type){let e=iv(l,i),t=(null==(r=iw(i.card,c))?void 0:r.itemIndex)??0;return(0,s.jsx)(iI,{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)(ic,{apiEnvironment:a,appId:n,card:i.card,inspectableTargetKey:iv(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:ih(i.card)}),i.card.fallback_text&&i.card.fallback_text!==ih(i.card)?(0,s.jsx)("span",{className:"wsd-widget-chat-card-summary",children:i.card.fallback_text}):null]})}function i_(e){var t;let r=null==(t=e.render_data)?void 0:t.grantingData;return eH(r)&&Array.isArray(r.grantingList)?r:void 0}function ib(e){return"pending"===e.permissionStatus||"revoked"===e.permissionStatus}function iw(e,t){let r=i_(e),a=(null==r?void 0:r.grantingList.findIndex(ib))??-1,n="number"==typeof t&&(null==r?void 0:r.grantingList[t])?t:-1===a?0:a;if(n<0)return;let s=null==r?void 0:r.grantingList[n];return s&&r?{grantingData:r,item:s,itemIndex:n}:void 0}function iS(e){return"string"==typeof e?e:""}function ix(e){let{appIcon:t}=e,[r,a]=(0,eB.useState)(!1);return((0,eB.useEffect)(()=>{a(!1)},[t]),!t||r)?null:(0,s.jsx)("img",{alt:"",className:"wsd-widget-granting-prompt-logo",onError:()=>a(!0),src:t})}function iI(e){var t,r,a;let{card:n,grantingItemIndex:i,onLogin:o,onPermissionDecision:l,onSkip:d,onTraceEvent:u}=e,c=(0,eB.useMemo)(()=>iw(n,i),[n,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=iS(null==m||null==(t=m.relatedData)?void 0:t.scopeName),v=(0,eB.useMemo)(()=>rg(f),[f]),[y,_]=(0,eB.useState)(),[b,w]=(0,eB.useState)(!1),S=g&&(null==p?void 0:p.cardStatus)==="expired",x=g&&!y&&!b&&!S&&((null==m?void 0:m.permissionStatus)==="pending"||(null==m?void 0:m.permissionStatus)==="revoked"),I=g?v.title:`在豆包内使用 ${h}`,C=g?"granted"===y?`已允许${h}获取`:"refused"===y?`已拒绝${h}获取`:S?"已过期,暂无法操作":iS(null==m||null==(r=m.relatedData)?void 0:r.scopeDescription)||v.description:iS(null==m||null==(a=m.relatedData)?void 0:a.bizLoginDescription)||((null==m?void 0:m.grantingName)==="privacy"?"需同意后才可以继续使用":"需登录后才可以继续使用");async function E(e){if(!b){w(!0),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(!1)}}}return(0,eB.useEffect)(()=>{_(void 0),w(!1)},[n.card_id,null==p?void 0:p.cardStatus,i,null==m?void 0:m.permissionStatus,f]),(0,s.jsxs)("article",{className:(0,eh.$)("wsd-widget-granting-prompt-card",g&&"is-permission"),children:[(0,s.jsxs)("header",{className:"wsd-widget-granting-prompt-brand",children:[(0,s.jsx)(ix,{appIcon:null==p?void 0:p.doubaoAppletIcon}),(0,s.jsx)("span",{children:h})]}),(0,s.jsx)("strong",{className:"wsd-widget-granting-prompt-title",children:I}),(0,s.jsx)("p",{className:"wsd-widget-granting-prompt-description",children:C}),g?x?(0,s.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-secondary",disabled:b,onClick:()=>void E(!1),type:"button",children:"拒绝"}),(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-primary",disabled:b,onClick:()=>void E(!0),type:"button",children:"允许"})]}):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 iC(e){let{apiEnvironment:t,appId:r,card:a,grantingItemIndex:n,inspectableTargetKey:i,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,runtimeConsoleTarget:u,widgets:c}=e,p=(0,eB.useMemo)(()=>ig(c,ip),[c]),m=(0,eB.useMemo)(()=>(function(e,t){let r,a,n,s,i,o,l,d;return{...e,card_id:`${e.card_id||"permission_apply"}:${ip}`,card_type:"permission_apply",render_data:{...eH(e.render_data)?e.render_data:{},viewData:(a=null==(r=iw(e,t))?void 0:r.grantingData,s=(null==(n=null==r?void 0:r.item)?void 0:n.relatedData)??{},i=(null==a?void 0:a.doubaoAppletName)||"智能服务",o=(null==n?void 0:n.grantingName)==="privacy",l=iS(s.mobileMask),d=o?iS(s.bizPrivacyContent)||`${i} 需要你同意隐私政策后继续。`:iS(s.bizLoginDescription)||"登录后继续使用相关服务",{type:(null==n?void 0:n.grantingName)==="privacy"?"agreePrivacyAuthorization":"getPhoneNumber",currentPage:"chat",brand:{name:i,logo:(null==a?void 0:a.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:iS(s.termsOfServiceURL)||void 0},{text:"和"},{text:"隐私政策",url:iS(s.privacyURL)||void 0}]},warningToast:"请先阅读并同意协议"})},widget_id:ip}})(a,n),[a,n]),h=(0,eB.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)(ic,{apiEnvironment:t,appId:r,card:m,inspectableTargetKey:i,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,runtimeConsoleTarget:u,viewport:h,widgets:p})})}function iE(e){let{apiEnvironment:t,appId:r,cardReloadKey:a,grantingItemIndexes:n,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),C=!!(x&&x===f);return(0,s.jsxs)("article",{"aria-pressed":I?C:void 0,className:(0,eh.$)("wsd-widget-chat-message",_?"is-assistant":"is-user",S&&"has-text",w&&"has-card",I&&"is-trace-selectable",C&&"is-trace-selected"),onClick:e=>{!x||!m||ik(e.target)||m(x)},onKeyDown:e=>{!x||!m||ik(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)(iy,{apiEnvironment:t,appId:r,block:e,cardReloadKey:a,grantingItemIndex:"card"===e.type?null==n?void 0:n[iv(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 ik(e){return e instanceof Element&&!!e.closest("button,a,input,textarea,select,.wsd-widget-chat-card")}let iN="mcp-login-page";function iR(e){return e.split(":")[0]||""}function iT(e){var t,r,a;let{apiEnvironment:n,appId:i,cardReloadKey:o,nativeModulesCallHandler:l,onGrantingSheetTargetChange:d,onInspectableCardTargetChange:u,onNavigateToPage:c,onQuerySubmit:p,onTraceEvent:m,onTraceMessageSelect:h,runtimeConsoleTarget:g,sandboxLoginHint:f,simulator:v,selectedTraceId:y,widgetViewport:_,widgets:b,webSdkDebugger:w,onMessage:S}=e,[x,I]=(0,eB.useState)(""),[C,E]=(0,eB.useState)(!1),[k,N]=(0,eB.useState)(!1),R=(0,eB.useContext)(it),T=(0,eB.useMemo)(()=>s7(R.tasks).length>0,[R.tasks]),M=(0,eB.useRef)(null),A=(0,eB.useRef)(v.messages.length),P=(0,eB.useRef)(!0),[j,D]=(0,eB.useState)(),[L,O]=(0,eB.useState)({}),U=(0,eB.useRef)(new Set),q="streaming"===v.streamStatus,$=!!x.trim()&&!q,B=((r=null==j?void 0:j.card)?null==(a=i_(r))?void 0:a.doubaoAppletKey:void 0)||void 0,F=i||B,H=sX(e=>{(D(void 0),c)?c({url:e}):w.navigateToPage(e)}),W=sX(e=>w.updateSimulatorWidget(e)),z=sX((e,t)=>{let r=tx(w,{grantingMessageId:(null==t?void 0:t.grantingMessageId)??(j?iR(j.key):void 0),noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==S||S("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==S||S("当前仍在生成中,暂不重发授权后的消息",!0);return}D(void 0),null==m||m({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==p||p(),r.completion.catch(e=>{null==S||S(e.message,!0)})}),V=sX((e,t,r,a)=>{var n;let s=iw(e,r);if(!s){null==S||S("索权卡缺少有效的授权项",!0);return}let i=`${t}:${r}`;if(U.current.has(i))return;U.current.add(i);let o=function(e,t){let r=i_(e);if(!r)return;let a=r.grantingList.findIndex((e,r)=>r>t&&ib(e));return -1===a?void 0:a}(e,r),l=function(e){switch(e){case"permission":case"privacy":return e;default:return"login"}}(s.item.grantingName);if(!a&&!1!==s.item.required)return void z(l,{grantingMessageId:iR(t),noLogin:!0});if(void 0!==o){O(e=>({...e,[t]:o})),D(e=>(null==e?void 0:e.key)===t?void 0:e),null==m||m({category:"card",event:"simulator_granting_item_advanced",granted:a,granting_name:s.item.grantingName,next_granting_name:null==(n=iw(e,o))?void 0:n.item.grantingName});return}z(l,{grantingMessageId:iR(t)})}),G=sX((e,t,r)=>{var a,n;let s;(null==(s=null==(a=iw(e,r))?void 0:a.item)?void 0:s.grantingName)==="privacy"||iS(null==s||null==(n=s.relatedData)?void 0:n.mobileMask).trim()?D({card:e,itemIndex:r,key:t}):(null==m||m({category:"card",event:"simulator_granting_custom_login_navigate",reason:"missing_mobile_mask",url:iN}),H(iN))}),K=sX(async(e,t,r,a)=>{var n,s,i;let o=function(e,t){var r;let a=iw(e,t),n=null==a?void 0:a.grantingData,s=null==a?void 0:a.item,i=iS(null==n?void 0:n.doubaoAppletKey).trim(),o=iS(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==n?void 0:n.doubaoAppletName)||"智能服务",required:!1!==s.required,scope:o}}(e,r);if(!o)return null==S||S("索权卡缺少有效的智能服务 appId 或 scopeName",!0),!1;try{await a$({appletId:o.appId,granted:a,scopeName:o.scope})}catch(t){let e=t instanceof Error?t.message:String(t);return null==m||m({category:"card",event:"simulator_granting_permission_report_failed",applet_id:o.appId,granted:a,scope:o.scope}),null==S||S(`权限授权状态上报失败:${e}`,!0),!1}return n=o.appId,s=o.scope,i=a?"granted":"denied",rp.set(rh(n,s),i),null==m||m({category:"card",event:"simulator_granting_permission_reported",applet_id:o.appId,granted:a,scope:o.scope}),V(e,t,r,a),!0}),J=sX((e,t,r,a)=>{V(t,r,a,!1)}),X=(0,eB.useMemo)(()=>{var e,t;if(!j)return;let r=(e=j.key,t=j.itemIndex,`${e}:${t}`);return nd({appId:F,baseAPIRegistry:null==n?void 0:n.apiRegistry,onGrantingCompleted:(e,t)=>V(j.card,j.key,j.itemIndex,!(null==t?void 0:t.noLogin)),onCustomLoginNavigate:H,onPrivacyLoginCardClose:()=>{Promise.resolve().then(()=>{U.current.has(r)||V(j.card,j.key,j.itemIndex,!1)})},runtimeHost:null==n?void 0:n.runtimeHost,scanCodePresenter:null==n?void 0:n.scanCodePresenter,uiPresenter:null==n?void 0:n.uiPresenter})},[j,n,F,V,H]),Q=sX((e,t)=>{null==u||u(e,t),null==d||d(t)}),Z=sX(e=>{N(!1);try{w.navigateToPage(e),null==c||c({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")}}),Y=sX(()=>{N(!1)}),ee=sX(async e=>{try{await R.removeTask(e)}catch(e){null==S||S(e.message,!0)}});return((0,eB.useEffect)(()=>{let e=M.current,t=A.current,r=v.messages.at(-1),a=v.messages.length>t&&(null==r?void 0:r.role)==="user";A.current=v.messages.length,e&&(P.current||a)&&(e.scrollTop=e.scrollHeight,P.current=!0)},[null==(t=v.error)?void 0:t.message,v.messages,v.streamStatus]),(0,eB.useEffect)(()=>{C&&R.hasUnreadNotices&&R.markServiceNoticesRead()},[R.hasUnreadNotices,R.markServiceNoticesRead,C]),C)?(0,s.jsx)(s6,{notices:R.notices,onAction:Z,onBack:()=>E(!1),status:R.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)(s3,{}),(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":R.hasUnreadNotices?"打开菜单,有更新":"打开菜单",className:(0,eh.$)("wsd-doubao-icon-button",R.hasUnreadNotices&&"has-badge"),onClick:()=>E(!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"})})]})]})]}),f?(0,s.jsxs)("div",{className:(0,eh.$)("wsd-doubao-login-banner",!f.available&&"is-unavailable"),children:[(0,s.jsxs)("button",{className:"wsd-doubao-login-banner-open",onClick:f.onOpen,type:"button",children:[(0,s.jsx)("span",{children:f.available?"配置登录信息,模拟登录后场景":"无法模拟平台服务"}),f.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:f.onClose,type:"button",children:"×"})]}):null,(0,s.jsxs)("div",{"aria-label":"对话预览",className:"wsd-widget-chat-messages",onScroll:function(e){let t=e.currentTarget;P.current=t.scrollHeight-t.scrollTop-t.clientHeight<=24},ref:M,children:[v.messages.length>0?v.messages.map(e=>(0,s.jsx)(iE,{apiEnvironment:n,appId:i,cardReloadKey:o,grantingItemIndexes:L,message:e,nativeModulesCallHandler:l,onGrantingCardOpen:G,onGrantingPermissionDecision:K,onGrantingCardSkip:J,onInspectableCardTargetChange:u,onTraceEvent:m,onTraceSelect:h,onUpdateWidget:W,runtimeConsoleTarget:g,selectedTraceId:y,widgetViewport:_,widgets:b},e.messageId)):null,v.error?(0,s.jsx)("div",{className:"wsd-widget-chat-error",children:v.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=x.trim();t&&!q&&(I(""),null==p||p(),w.sendSimulatorQuery(t).catch(e=>{null==S||S(e.message,!0)}))},children:[(0,s.jsx)("input",{"aria-label":"输入消息",className:"wsd-widget-chat-input",disabled:q,onChange:e=>I(e.currentTarget.value),placeholder:"发消息...",type:"text",value:x}),(0,s.jsx)("button",{"aria-label":q?"取消生成":"发送消息",className:"wsd-widget-chat-send",disabled:!q&&!$,onClick:function(){q&&w.cancelSimulatorQuery()},type:q?"button":"submit",children:q?(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-cancel-icon"}):(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-send-icon"})})]})}),T&&!k?(0,s.jsx)("button",{"aria-label":"展开进行中的任务",className:"wsd-sandbox-task-collapsed-entry",onClick:()=>{R.markTasksRead(),N(!0)},type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})}):null,j?(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)(iC,{apiEnvironment:X,appId:F,card:j.card,grantingItemIndex:j.itemIndex,inspectableTargetKey:j.key,nativeModulesCallHandler:l,onInspectableTargetChange:Q,onTraceEvent:m,runtimeConsoleTarget:g,widgets:b})})]}):null,k?(0,s.jsx)(s9,{onAction:Z,onClose:Y,onRemove:ee,removingTaskIds:R.removingTaskIds,tasks:R.tasks}):null]})}function iM(e){let{appIcon:t}=e,[r,a]=(0,eB.useState)(!1);return((0,eB.useEffect)(()=>{a(!1)},[t]),!t||r)?null:(0,s.jsx)("img",{alt:"",className:"wsd-simulator-permission-app-icon",onError:()=>a(!0),src:t})}function iA(e){let{onAllow:t,onReject:r,permission:a}=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":`${a.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)(iM,{appIcon:a.appIcon}),(0,s.jsx)("strong",{children:a.appName})]}),(0,s.jsxs)("section",{className:"wsd-simulator-permission-content",children:[(0,s.jsx)("h2",{children:a.title}),(0,s.jsx)("p",{children:a.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 iP(){let[e,t]=(0,eB.useState)(),r=(0,eB.useRef)(null),a=sX(e=>r.current?Promise.reject(Error("Simulator permission prompt is already open")):new Promise(a=>{r.current=a,t(e)})),n=sX(e=>{let a=r.current;a&&(r.current=null,t(void 0),a(e))}),s=sX(()=>n(!0)),i=sX(()=>n(!1));return(0,eB.useEffect)(()=>()=>{let e=r.current;r.current=null,null==e||e(!1)},[]),{allowPermission:s,permission:e,rejectPermission:i,showPermission:a}}var ij=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"})}),iD=r(35668),iL=r(27860),iO=r(26661),iU=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 iq=[{key:"conversation",label:"对话"},{key:"card",label:"卡片"},{key:"page",label:"全页"}],i$=[{label:"iOS",devices:t3.filter(e=>e.key.startsWith("iphone"))},{label:"Android",devices:t3.filter(e=>e.key.startsWith("pixel")||e.key.startsWith("galaxy"))},{label:"平板",devices:t3.filter(e=>e.key.startsWith("ipad"))}];function iB(e){let{activeView:t,children:r,onActiveViewChange:a,onDeviceChange:n,selectedDeviceKey:i}=e,[o,l]=(0,eB.useState)(!1),[d,u]=(0,eB.useState)(),c=(0,eB.useRef)(null);return(0,eB.useEffect)(()=>{let e=e=>{var t;(null==(t=c.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:c,children:[(0,s.jsxs)("div",{className:"wsd-device-toolbar-leading",children:[(0,s.jsx)("button",{"aria-label":"手机预览","aria-expanded":o,"aria-haspopup":"menu","aria-pressed":"phone"===d,className:(0,eh.$)("wsd-device-toolbar-icon","phone"===d&&"is-active"),onClick:()=>{u("phone"),l(e=>!e)},type:"button",children:(0,s.jsx)(iU,{"aria-hidden":"true"})}),o?(0,s.jsx)(iD.o,{"aria-label":"选择模拟器类型",className:"wsd-preview-toolbar-menu",selectedKeys:i?[i]:[],selectionMode:"single",onAction:e=>{null==n||n(String(e)),l(!1)},children:i$.map(e=>(0,s.jsx)(iL.g,{showDivider:e!==i$.at(-1),title:e.label,children:e.devices.map(e=>(0,s.jsx)(iO.Y,{title:e.label,children:e.label},e.key))},e.label))}):null,(0,s.jsx)("button",{"aria-label":"设置","aria-pressed":"settings"===d,className:(0,eh.$)("wsd-device-toolbar-icon","settings"===d&&"is-active"),onClick:()=>{u("settings"),l(!1)},type:"button",children:(0,s.jsx)(s2,{"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:iq.map(e=>(0,s.jsx)("span",{"aria-selected":t===e.key,className:(0,eh.$)("wsd-debug-mode-tab",t===e.key&&"is-active"),onClick:()=>null==a?void 0:a(e.key),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),null==a||a(e.key))},role:"tab",tabIndex:0,children:e.label},e.key))})}),(0,s.jsx)("div",{className:"wsd-page-toolbar-actions",children:r})]})}function iF(e){let{children:t,runtime:r}=e,a=(0,eB.useMemo)(()=>({consoleTarget:"conversation"===r.activeView?r.conversationConsoleTarget:void 0,controlCommand:r.controlCommand,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,eB.useEffect)(()=>{var e;null==(e=r.onChromeDevToolsPanelChange)||e.call(r,a)},[a,r.onChromeDevToolsPanelChange]),(0,s.jsxs)("div",{className:(0,eh.$)("wsd-widget-preview-column","card"===r.activeView&&"is-card-debug"),children:[(0,s.jsx)(iB,{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)(ij,{"aria-hidden":"true"})})}),t]})}function iH(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}let iW={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"},iz={error:"error",success:"success",warning:"warn"};function iV(e){return Array.isArray(e.itemList)?e.itemList:[]}function iG(e){return Array.isArray(e.buttons)?e.buttons:[]}function iK(e){let{id:t,params:r,onSubmit:a}=e,[n,i]=(0,eB.useState)(String(r.latitude??0)),[o,l]=(0,eB.useState)(String(r.longitude??0)),[d,u]=(0,eB.useState)(""),[c,p]=(0,eB.useState)(""),[m,h]=(0,eB.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(n),s=Number(o);Number.isFinite(r)&&Number.isFinite(s)?a(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:n})]}),(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 iJ(e){let{scanner:t}=e,r=(0,eB.useRef)(null),a=(0,eB.useRef)(null);return(0,eB.useEffect)(()=>{let e=a.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:a}),(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 a=null==(r=e.currentTarget.files)?void 0:r[0];e.currentTarget.value="",a&&t.options.onFile(a)},ref:r,type:"file"})]}):null]})]})}function iX(e){let{children:t,className:r,exiting:a=!1,onDismiss:n}=e;return(0,s.jsxs)("div",{className:`wsd-simulator-overlay-interaction${r?` ${r}`:""}${a?" is-exiting":""}`,children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop",onClick:n}),t]})}function iQ(e){let{interaction:t,onActionSheetSelect:r,onBottomSheetSelect:a,onDismiss:n,onLocationSubmit:i,onModalResult:o}=e,l=()=>n(t);if("location"===t.kind)return(0,s.jsx)(iX,{onDismiss:l,children:(0,s.jsx)(iK,{id:t.id,onSubmit:i,params:t.params},t.id)});if("modal"===t.kind){let{params:e}=t,r=!1!==e.showCancel;return(0,s.jsx)(iX,{className:"is-modal",exiting:t.exiting,onDismiss:l,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${r?"":" is-single"}`,children:[r?(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-cancel",onClick:()=>o(t.id,"cancel"),type:"button",children:e.cancelText||"cancel"}):null,(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-confirm",onClick:()=>o(t.id,"confirm"),type:"button",children:e.confirmText||"confirm"})]})]})})}if("actionSheet"===t.kind){let e=iV(t.params);return(0,s.jsx)(iX,{onDismiss:l,children:(0,s.jsxs)("dialog",{"aria-label":t.params.title||"操作菜单","aria-modal":"true",className:"wsd-simulator-overlay-sheet wsd-simulator-action-sheet",onClick:e=>e.stopPropagation(),open:!0,children:[t.params.title?(0,s.jsx)("h2",{children:t.params.title}):null,(0,s.jsx)("div",{className:"wsd-simulator-overlay-list",children:e.map((e,a)=>(0,s.jsx)("button",{className:"wsd-simulator-overlay-list-item",onClick:()=>r(t.id,a),style:t.params.itemColor?{color:t.params.itemColor}:void 0,type:"button",children:e},`${e}-${a}`))})]})})}let d=iG(t.params);return(0,s.jsx)(iX,{onDismiss:l,children:(0,s.jsxs)("dialog",{"aria-label":t.params.title||"底部弹窗","aria-modal":"true",className:"wsd-simulator-overlay-sheet wsd-simulator-bottom-sheet",onClick:e=>e.stopPropagation(),open:!0,children:[t.params.title?(0,s.jsx)("h2",{children:t.params.title}):null,t.params.content?(0,s.jsx)("p",{children:t.params.content}):null,(0,s.jsx)("div",{className:"wsd-simulator-overlay-actions",children:d.map(e=>(0,s.jsx)("button",{className:`wsd-simulator-overlay-button ${"reject"===e.role?"is-secondary":"is-primary"}`,onClick:()=>a(t.id,e.role),type:"button",children:e.text},e.role))})]})})}function iZ(e){let{interaction:t,loading:r,onActionSheetSelect:a,onBottomSheetSelect:n,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||iz[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:iW[t]})}):null}(u),(0,s.jsx)("span",{className:"wsd-simulator-toast-message",children:u.message})]},u.id):null,d?(0,s.jsx)(iJ,{scanner:d}):null,t?(0,s.jsx)(iQ,{interaction:t,onActionSheetSelect:a,onBottomSheetSelect:n,onDismiss:i,onLocationSubmit:o,onModalResult:l}):null]})}function iY(){let[e,t]=(0,eB.useState)(null),[r,a]=(0,eB.useState)(!1),[n,i]=(0,eB.useState)(null),o=(0,eB.useRef)(null),l=(0,eB.useRef)(),d=(0,eB.useRef)(0),u=(0,eB.useRef)(0),c=(0,eB.useRef)(0),p=(0,eB.useRef)(null),[m,h]=(0,eB.useState)(null),g=(0,eB.useRef)(null),f=(0,eB.useRef)(),v=(0,eB.useRef)(),y=sX((e,r,a)=>{let n=o.current;n&&n.id===e&&(l.current&&(clearTimeout(l.current),l.current=void 0),a?n.reject(a):n.resolve(r),o.current=null,t(null))}),_=sX(()=>{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=sX((e,r,a,n)=>{l.current&&(clearTimeout(l.current),l.current=void 0),_();let s={exiting:!1,id:++d.current,kind:e,params:r,reject:n,resolve:a};o.current=s,t({exiting:s.exiting,id:s.id,kind:s.kind,params:s.params})}),w=sX(()=>{v.current&&(clearTimeout(v.current),v.current=void 0),f.current&&(clearTimeout(f.current),f.current=void 0)}),S=sX(e=>{var t;(null==(t=g.current)?void 0:t.id)===e&&(g.current=null,f.current=void 0,i(null))}),x=sX(()=>{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=sX(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)))}),C=sX(e=>{var t;(null==(t=p.current)?void 0:t.id)===e&&(p.current=null,h(null))}),E=sX((e,t)=>{let r=p.current;if((null==r?void 0:r.id)!==e)return;let a={...r,message:t};p.current=a,h(a)}),k=sX(e=>{var t;null==(t=p.current)||t.options.onCancel();let r=++u.current,a={id:r,message:"正在打开摄像头...",options:e};return p.current=a,h(a),{close:()=>C(r),setMessage:e=>E(r,e)}}),N=sX(e=>new Promise((t,r)=>{b("modal",e,t,r)})),R=sX(e=>new Promise((t,r)=>{b("location",e,t,r)})),T=sX(e=>new Promise((t,r)=>{0===iV(e).length?r(Error("itemList must contain at least one item")):b("actionSheet",e,t,r)})),M=sX(e=>new Promise((t,r)=>{0===iG(e).length?r(Error("buttons must contain at least one button")):b("bottomSheet",e,t,r)})),A=sX((e,r)=>{let a=o.current;a&&a.id===e&&"modal"===a.kind&&(a.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=sX((e,t)=>{let r=o.current;r&&r.id===e&&A(e,{action:t})}),j=sX((e,t)=>{let r=o.current;r&&r.id===e&&"actionSheet"===r.kind&&y(e,{tapIndex:t})}),D=sX((e,t)=>{let r=o.current;r&&r.id===e&&"bottomSheet"===r.kind&&y(e,{action:"buttonClick",role:t})}),L=sX((e,t)=>{let r=o.current;r&&r.id===e&&"location"===r.kind&&y(e,t)}),O=sX(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,eB.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,eB.useMemo)(()=>({chooseLocation:R,hideLoading:()=>a(!1),hideToast:x,showActionSheet:T,showBottomSheet:M,showLoading:()=>a(!0),showModal:N,showToast:I}),[R,x,T,M,N,I]);return{overlay:(0,s.jsx)(iZ,{interaction:e,loading:r,onActionSheetSelect:j,onBottomSheetSelect:D,onDismiss:O,onLocationSubmit:L,onModalResult:P,scanner:m,toast:n}),presenter:U,scanCodePresenter:k}}function i0(e){return"string"==typeof e&&e.trim()?e.trim():""}function i1(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function i2(e){if("boolean"==typeof(null==e?void 0:e.sandboxCsrUploaded)&&"boolean"==typeof e.sandboxPhoneNumberUploaded)return e.sandboxCsrUploaded&&e.sandboxPhoneNumberUploaded}function i3(e,t){return eH(e)?e[t]:void 0}function i4(e,t){let r=i3(e,t);return eH(r)?r:void 0}function i5(e,t){let r=i3(e,t);return Array.isArray(r)?r:[]}function i6(e){let t=i3(e,"raw");return eH(t)?t:eH(e)?e:{}}function i8(e){return i4(i6(e),"applet")}function i7(e){return null==e?void 0:e.replace(/^\/+|\/+$/g,"")}function i9(e){return eH(e.payload)?e.payload:void 0}function oe(e,t){for(let r=e.length-1;r>=0;r-=1){let a=i9(e[r]);if((null==a?void 0:a.event)===t)return a}}function ot(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 or(e,t,r){let a=function(){for(var r=arguments.length,a=Array(r),n=0;n<r;n++)a[n]=arguments[n];return a.map(r=>oe(e,`simulator_${t}_${r}`)).find(Boolean)},n=a("missing"),s=a("fetch_started","load_started"),i=a("fetch_failed","load_failed"),o=a("fetch_succeeded","loaded"),l=a("empty");return o?{bytes:i1(o.bytes)??i1(o.skill_length),detail:i0(o.url)||r,label:"已加载",tone:"success"}:l?{detail:r||"未配置",label:"空内容",tone:"muted"}:n||!r?{detail:r,label:"未配置",tone:"muted"}:i?{detail:i0(i.error)||i0(i.url)||r,label:"加载失败",tone:"error"}:s?{detail:i0(s.url)||r,label:"加载中",tone:"pending"}:{detail:r,label:"检查中",tone:"pending"}}function oa(e){return"string"==typeof e?e.trim():eH(e)?i0(e.name)||i0(e.id):""}function on(){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 os(e,t,r,a){if(!e)return"";if(a.startsWith(`${t}/`)){let e=a.replace(/\.web\.bundle$/g,"").replace(/\.bundle$/g,"").replace(/\.template\.js$/g,"").replace(/\.js$/g,"");return on("src",/\.(tsx|ts|jsx|js)$/.test(e)?e:`${e}.tsx`)}return!r||r.startsWith("__")?"":on("src",t,r,"index.tsx")}function oi(e){var t,r;let a,n,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)||i0(null==(n=i4(i6(f),"mcp_server"))?void 0:n.end_point)||i0(null==n?void 0:n.endpoint)||i0(null==n?void 0:n.url)||i0(null==n?void 0:n.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)||"",C=(null==h?void 0:h.simulatorManifestRelativePath)||"",E=(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)||"",R=(null==h?void 0:h.simulatorSkillOriginalUrl)||"",T=(null==h?void 0:h.simulatorSkillProxyUrl)||(null==h?void 0:h.simulatorSkillUrl)||"",M=(null==h?void 0:h.simulatorSkillRelativePath)||"",A=(null==h?void 0:h.simulatorSkillUrl)||(null==h?void 0:h.simulatorSkillProxyUrl)||"",P=ot(N,x,"/__simulator_manifest/manifest.yaml"),j=ot(A,R,"/__simulator_skill/skill.md"),D=ot(b,(null==h?void 0:h.mcpOriginalEndpoint)||"","/__mcp_proxy"),L=function(e){let t=new Set;for(let r of e){let e=i9(r);if(e){for(let r of i5(e,"tools")){let e=oa(r);e&&t.add(e)}for(let r of i5(e,"mcp_servers"))for(let e of i5(r,"tools")){let r=oa(e);r&&t.add(r)}}}return[...t]}(g),O=function(e){let t=new Map,r=function(e,r){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",n=eH(r)?i0(r.widget_id)||i0(r.widgetId)||i0(r.widget):i0(r),s=eH(r)&&(i0(r.entity_type)||i0(r.entityType)||i0(r.entity))||a;e&&n&&t.set(`${e}:${n}:${s}`,{entityType:s,toolName:e,widgetId:n})},a=i6(e),n=i3(a,"tool_card_binding");if(eH(n))for(let[e,t]of Object.entries(n))r(e,t);let s=i3(a,"entities");for(let[e,t]of eH(s)?Object.entries(s):[]){if(!eH(t))continue;let a=i0(t.entity_type)||i0(t.entityType)||e,n=i3(t,"tool_card_binding");if(eH(n))for(let[e,t]of Object.entries(n))r(e,t,a)}return[...t.values()]}(f),U={manifest:or(g,"manifest",P),mcp:(s=oe(g,"local_mcp_missing"),i=oe(g,"local_mcp_tools_load_started"),o=oe(g,"local_mcp_tools_load_failed"),(l=oe(g,"local_mcp_tools_loaded"))?{detail:i0(l.mcp_endpoint)||D,label:"已连接",tone:"success"}:s||!D?{detail:D,label:"未配置",tone:"muted"}:o?{detail:i0(o.error)||i0(o.mcp_endpoint)||D,label:"连接失败",tone:"error"}:i?{detail:i0(i.mcp_endpoint)||D,label:"连接中",tone:"pending"}:{detail:D,label:"检查中",tone:"pending"}),skill:or(g,"skill",j)},q=!!P||"success"===U.manifest.tone,$=!!j||"success"===U.skill.tone,B=!!D||"success"===U.mcp.tone,F={businessTemplates:E?{detail:k||E,label:"已加载",tone:"success"}:{detail:"",label:"未配置",tone:"muted"},manifest:{...U.manifest,detail:C||U.manifest.detail},mcp:U.mcp,skill:{...U.skill,detail:M||U.skill.detail}};return{appId:(d=i6(f),u=i8(f),i0(i3(f,"appId"))||i0(d.appId)||i0(d.app_key)||i0(null==u?void 0:u.appletId)),appName:(c=i6(f),p=i8(f),i0(i3(f,"name"))||i0(c.name)||i0(c.app_name)||i0(null==p?void 0:p.name)),context:{launchDir:_},mcpTools:L,pages:(t=f,m=(null==(a=function(e,t){let r=i7(t);if(r)return e.find(e=>e.id===t||i7(e.path)===r)}(r=v,i0(i3(i8(t),"appletEntry")))??r.find(e=>{let t=i7(e.path);return"index"===e.id||"pages/index"===t||"pages/index/index"===t})??r[0])?void 0:a.id)||"",v.map(e=>{var t;return{entry:os(_,"pages",e.id,i0(e.entry)),isHome:!!m&&e.id===m,name:i0(i3(e,"name"))||i0(i3(e,"title")),pageId:e.id,path:i0(e.path)||i0(null==(t=e.web)?void 0:t.entry)||i0(e.entry)}})),resources:F,sources:{manifest:{original:q?x:"",proxy:q?I||N:""},mcp:{original:B?w:"",proxy:B?S:""},skill:{original:$?R:"",proxy:$?T||A:""}},widgets:function(e,t,r){let a=new Map;for(let e of t){let t=a.get(e.widgetId)??[];t.push(e.toolName),a.set(e.widgetId,t)}return e.filter(e5).map(e=>({boundTools:a.get(e.widgetId)??[],entry:os(r,"widgets",e.widgetId,i0(e.entry)),name:i0(e.name),widgetId:e.widgetId}))}(y,O,_)}}function oo(e,t,r){return!!(e&&t&&t!==r&&e.sourceTarget===t)}function ol(e,t){return{pages:e.pages.map(e=>{let{isHome:t,name:r,pageId:a,path:n}=e;return{isHome:t,name:r,pageId:a,path:n}}),widgets:e.widgets.map(e=>{let{name:t,widgetId:r}=e;return{name:t,widgetId:r}}),...t?{currentTarget:t}:{}}}let od={message:"未上传",tone:"muted"},ou={message:"已上传",tone:"success"},oc=od,op=new Set;function om(e){return op.add(e),()=>op.delete(e)}function oh(){return oc}function og(e){for(let t of(oc=e,op))t()}function of(e){let t=(0,eB.useSyncExternalStore)(om,oh,oh);return(0,eB.useEffect)(()=>{void 0!==e&&og(e?ou:od)},[e]),t}let ov={message:"可用",tone:"success"},oy={message:"不可用",tone:"error"},o_=ov,ob=new Set;function ow(e){return ob.add(e),()=>ob.delete(e)}function oS(){return o_}function ox(e){for(let t of(o_=e,ob))t()}function oI(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],t=(0,eB.useSyncExternalStore)(ow,oS,oS);return(0,eB.useEffect)(()=>{ox(e?ov:oy)},[e]),t}function oC(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("clear-sandbox-bridge-logs"===e.kind){if(!t.onClearLogs){var r;return null==(r=t.onMessage)||r.call(t,"服务端日志接口不可用",!0),!0}return t.onClearLogs().then(()=>{var e;return null==(e=t.onMessage)?void 0:e.call(t,"服务端交互日志已清空")}).catch(e=>{var r;return null==(r=t.onMessage)?void 0:r.call(t,e.message,!0)}),!0}return"recreate-sandbox-session"===e.kind?(ox({message:"正在重建",tone:"pending",updatedAtMs:Date.now()}),aQ({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(e=>{var r,a,n,s,i;let o=(null==(r=e.data)?void 0:r.business_info_uploaded)===!0;o?og({message:"已上传",tone:"success",updatedAtMs:Date.now()}):function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:od.message;og({message:e,tone:"muted",updatedAtMs:Date.now()})}(),ox({message:"已重建",tone:"success",updatedAtMs:Date.now()}),o?null==(s=t.onUpdated)||s.call(t):null==(i=t.onRecreated)||i.call(t),null==(n=t.onMessage)||n.call(t,`调试会话已重建${o?",手机号和证书已自动上传":""}:${(null==(a=e.data)?void 0:a.sandbox_session_id)??""}`)}).catch(e=>{var r;let a=`重建调试会话失败:${e.message}`;ox({errorMessage:a,message:"重建失败",tone:"error",updatedAtMs:Date.now()}),null==(r=t.onMessage)||r.call(t,a,!0)}),!0):"update-sandbox-business-info"===e.kind&&(og({message:"正在上传...",tone:"pending",updatedAtMs:Date.now()}),aX({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(()=>{var e,r;og({message:"上传成功",tone:"success",updatedAtMs:Date.now()}),null==(e=t.onUpdated)||e.call(t),null==(r=t.onMessage)||r.call(t,"上传成功")}).catch(e=>{var r;let a=e&&"object"==typeof e&&"logId"in e&&"string"==typeof e.logId?e.logId:"";og({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:a}),null==(r=t.onMessage)||r.call(t,"上传失败",!0)}),!0)}let oE=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"]),ok={query:0,"tool-call":10,"tool-result":20,card:30,"agent-response":40,error:50};function oN(e,t){return{category:"api",detail:{query:t},key:"query",phase:"request",payload:{event:"query",query:t},source:e,sources:[e],title:"Query"}}function oR(e,t){let r=e.steps.get(t.key);if(!r)return void e.steps.set(t.key,t);let a=function(e,t){if("error"===t.phase)return!0;if(e.key.startsWith("card:")){let r=oj(oP(e.source));return oT(oj(oP(t.source)))>oT(r)}return!1}(r,t),n=a?t:r,s=a?r:t;e.steps.set(t.key,{...r,category:"error"===t.phase?t.category:n.category,detail:oq(n.detail,s.detail),phase:"error"===t.phase?t.phase:n.phase,payload:oq(n.payload,s.payload),source:n.source,sources:[...new Map([...r.sources,...t.sources].map(e=>[e.id,e])).values()],title:"error"===t.phase||a?t.title:r.title})}function oT(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 oM(e){let t=oW([...e.steps.values()]);return t.map((r,a)=>{var n,s,i,o,l,d,u,c;let p,m,h,g,f,v,y,_,b,w;return n=r,s=e,i=t,o=a,y=oF(n.sources.flatMap(e8)),_=oF(n.sources.map(e=>o$(oP(e).request_id))),w=void 0===(b=(l=n,d=i,u=o,p=oB(l.payload.elapsed_ms)??oB(l.detail.elapsed_ms),m=(null==(c=d[u+1])?void 0:c.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?oB(f.payload.elapsed_ms)??oB(f.detail.elapsed_ms):void 0)?v:l.key.startsWith("tool-result:")&&f?h??0:void 0!==p?void 0===h?p:Math.max(p,h):h))?n.detail:{...n.detail,elapsed_ms:b},{id:n.source.id,order:n.source.order,timestamp:n.source.timestamp,display:{category:n.category,detail:w,phase:n.phase,title:n.title},payload:{...1===_.length?{request_id:_[0]}:{},..._.length>1?{request_ids:_}:{},...n.payload,trace_id:s.id,...s.status?{run_status:s.status}:{},...void 0===b?{}:{elapsed_ms:b},...y.length>0?{log_ids:y}:{}}}})}function oA(e,t){let r=oH(oP(t)),a=r?e.runs.find(e=>e.id===r):void 0;if(!a){if(!r)return;a={id:r,order:t.order??e.runs.length,startedAt:t.timestamp,steps:new Map},e.runs.push(a)}return a.startedAt=Math.min(a.startedAt,t.timestamp),a.order=Math.min(a.order,t.order??a.order),a}function oP(e){return eH(e.payload)?e.payload:{}}function oj(e){return o$(e.event)}function oD(e,t){return oL(e)||[oH(e)||t.id,o$(e.tool_name)||"unknown-tool"].filter(Boolean).join(":")}function oL(e){return o$(e.tool_call_id)}function oO(e){let t=o$(e.tool_name)||oL(e);return t?`: ${t}`:""}function oU(e){let t={};for(let[r,a]of Object.entries(e))null!=a&&""!==a&&(t[r]=a);return t}function oq(e,t){return{...t,...e,...Object.fromEntries(Object.entries(t).filter(t=>{let[r,a]=t;return void 0===e[r]&&void 0!==a}))}}function o$(e){return"string"==typeof e&&e.trim()?e.trim():""}function oB(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function oF(e){return[...new Set(e.filter(e=>!!e))]}function oH(e){let t=eH(e.trace)?e.trace:{};return o$(e.trace_id)||o$(t.trace_id)}function oW(e){return[...e].sort((e,t)=>ok[e.key.split(":")[0]]-ok[t.key.split(":")[0]]||e.source.timestamp-t.source.timestamp||(e.source.order??0)-(t.source.order??0)||e.key.localeCompare(t.key))}function oz(e,t){return e.startedAt-t.startedAt||e.order-t.order||e.id.localeCompare(t.id)}function oV(e,t){return e.timestamp-t.timestamp||(e.order??0)-(t.order??0)||e.id.localeCompare(t.id)}function oG(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(ez(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 oK(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:oJ(e,t),debug_snapshot:oJ(e,{...t,debug:!0,includeRuntimeRoot:!1})}}function oJ(e){var t,r;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=a.debug&&!a.traceId?(t=e,r=!1!==a.includeRuntimeRoot,eH(t)&&!r&&eH(t.runtime_snapshot)?{...t,runtime_snapshot:oQ(t.runtime_snapshot,!1)}:t):function(e,t){var r;if(!eH(e))return e;let a=eH(e.simulator)?e.simulator:{},n=Array.isArray(a.messages)?a.messages.filter(e=>oZ(e,t.traceId)):void 0,s=Array.isArray(a.tool_calls)?a.tool_calls.filter(e=>oZ(e,t.traceId)):void 0,i=oQ(e.runtime_snapshot,!1!==t.includeRuntimeRoot);return{...o4(e,["exported_at","client_id","command_id","context","render_targets"]),...eH(i)?{runtime_snapshot:i}:{},...eH(e.simulator)?{simulator:{...o4(a,["stream_status","active_request_id","active_reply_message_id"]),...a.error?{error:o3(a.error)}:{},...a.selected_card?{selected_card:o2(a.selected_card)}:{},...a.answer_finish?{answer_finish:eH(r=a.answer_finish)?o4(r,["messageId","status","finishReason","usage","createdAtMs"]):r}:{},...n?{messages:n.map(oY)}:{},...s?{tool_calls:s.map(o1)}:{},...Array.isArray(a.trace_events)?{trace_events:oX(a.trace_events,{debug:t.debug,messages:n,traceId:t.traceId})}:{}}}:{},...Array.isArray(e.widget_runtime_trace_events)?{widget_runtime_trace_events:oX(e.widget_runtime_trace_events,{debug:t.debug,traceId:t.traceId})}:{},...Array.isArray(e.page_runtime_trace_events)?{page_runtime_trace_events:oX(e.page_runtime_trace_events,{debug:t.debug,traceId:t.traceId})}:{},...eH(e.runtime_console)?{runtime_console:e.runtime_console}:{}}}(e,a),s=e8(e);return s.length>0&&eH(n)?{...n,log_ids:s}:n}function oX(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,a;return r=e,(a=t.traceId)?r.filter(e=>oH(oP(e))===a):r}let n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r={runs:[]};for(let t of[...e].sort(oV))!function(e,t){var r,a;let n=oP(t),s=oj(n);if(!((r=s).startsWith("tool_result_report_")||"tool_result_ack"===r)){if("simulator_chat_fetch_started"===s){let r=function(e){let t=eH(e.request)?e.request:{},r=eH(t.message)?t.message:{};return o$(e.query)||o$(t.query)||o$(r.content)}(n);if(!r)return;let a=oA(e,t);if(!a)return;oR(a,oN(t,r));return}if("tool_call"===s||"local_mcp_call_started"===s){let r=oA(e,t);if(!r)return;oR(r,function(e){let t=oP(e),r=oU({tool_call_id:oL(t),tool_name:t.tool_name,arguments:t.arguments,arguments_json:t.arguments_json});return{category:"agent",detail:r,key:`tool-call:${oD(t,e)}`,phase:"request",payload:{event:"tool_call",...r},source:e,sources:[e],title:`Tool Call${oO(t)}`}}(t));return}if("local_mcp_call_succeeded"===s||"local_mcp_call_failed"===s){let r=oA(e,t);if(!r)return;oR(r,function(e){let t=oP(e),r="local_mcp_call_failed"===oj(t),a=oU({tool_call_id:oL(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:a,key:`tool-result:${oD(t,e)}`,phase:r?"error":"response",payload:{event:r?"tool_result_failed":"tool_result",...a},source:e,sources:[e],title:`${r?"Tool Result Failed":"Tool Result"}${oO(t)}`}}(t));return}if("card_delta"===(a=s)||"simulator_card_rendered"===a||"simulator_card_render_failed"===a||"simulator_card_runtime_error"===a||"simulator_card_render_skipped"===a){let r=oA(e,t);if(!r)return;oR(r,function(e){var t,r;let a=oP(e),n=oj(a),s="error"in a||n.endsWith("_failed")||n.endsWith("_error"),i=oU({card_id:a.card_id,widget_id:a.widget_id,card_type:a.card_type,entity_id:a.entity_id,source_tool_call_id:a.source_tool_call_id,elapsed_ms:a.elapsed_ms,error:a.error,summary:a.summary});return{category:"card",detail:i,key:`card:${t=a,r=e,o$(t.card_id)||o$(t.source_tool_call_id)||[oH(t)||r.id,o$(t.widget_id)||r.id].filter(Boolean).join(":")}`,phase:s?"error":"response",payload:{event:s?"card_render_failed":"card_delta"===n?"card_received":"card_rendered",...i},source:e,sources:[e],title:s?"Card Render Failed":"card_delta"===n?"Card Received":"Card Rendered"}}(t));return}if(function(e,t){let r=o$(e.phase),a=e.status;return oE.has(t)||"error"===r||t.endsWith("_failed")||t.endsWith("_missing")||t.endsWith("_aborted")||t.endsWith("_error")||"failed"===a||"error"===a||"number"==typeof a&&a>=400}(n,s)){let r=oA(e,t);if(!r)return;oR(r,function(e){var t,r;let a=oP(e),n=eH(a.detail)?a.detail:{},s=a.event_count??n.event_count,i=oU({elapsed_ms:a.elapsed_ms??n.elapsed_ms,endpoint:a.endpoint??n.endpoint,error:a.error??n.error,event_count:s,message:a.message??n.message,reason:a.reason??n.reason,status:a.status??n.status,summary:a.summary??n.summary??("simulator_chat_sse_read_failed"===oj(a)&&0===s?"对话流未收到任何事件,未触发 MCP tool 与 tool/report;请结合 log_id 排查生成或下发 tool_call 前的服务端/链路异常。":void 0),response:a.response??n.response,response_text:a.response_text??n.response_text});return{category:(null==(t=e.display)?void 0:t.category)||"runtime",detail:i,key:`error:${e.id}`,phase:"error",payload:{event:oj(a)||"trace_error",...i},source:e,sources:[e],title:(null==(r=e.display)?void 0:r.title)||o$(a.title)||"Trace Error"}}(t))}}}(r,t);for(let e of t)!function(e,t){var r,a,n,s;let i=(r=t,{id:`trace-message-${r.messageId}`,timestamp:r.createdAtMs,payload:oU({message_id:r.messageId,request_id:r.requestId,trace_id:r.traceId})}),o=oA(e,i);o&&("assistant"===t.role&&t.status&&(a=o,n=t.status,s=t.createdAtMs,void 0!==a.statusUpdatedAt&&s<a.statusUpdatedAt||(a.status=n,a.statusUpdatedAt=s)),"user"===t.role&&t.text.trim()&&!o.steps.has("query")&&oR(o,oN(i,t.text)),"assistant"===t.role&&t.text.trim()&&oR(o,function(e,t){let r=oW([...e.steps.values()]).at(-1),a=Math.max(t.createdAtMs,((null==r?void 0:r.source.timestamp)??t.createdAtMs)+.1),n={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:a,payload:oU({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:n,sources:[n],title:"Agent Response"}}(o,t)))}(r,e);return r}(e,t.messages);return(t.traceId?n.runs.filter(e=>e.id===t.traceId):n.runs).sort(oz).flatMap(oM)}(e,t)}function oQ(e,t){if(!eH(e)||t)return e;let{root:r,...a}=e;return a}function oZ(e,t){if(!t)return!0;if(!eH(e))return!1;let r=eH(e.trace)?e.trace:{};return e.traceId===t||r.trace_id===t}function oY(e){return eH(e)?{...o4(e,["messageId","localMessageId","requestId","traceId","role","contentType","status","createdAtMs"]),..."string"==typeof e.text?{text:o5(e.text)}:{},...Array.isArray(e.blocks)?{blocks:e.blocks.map(o0)}:{},...Array.isArray(e.toolCalls)?{toolCalls:e.toolCalls}:{},...Array.isArray(e.toolResults)?{toolResults:e.toolResults}:{}}:e}function o0(e){return eH(e)?"card"===e.type?{...o4(e,["blockId","type"]),card:o2(e.card)}:{...o4(e,["blockId","type"]),..."string"==typeof e.text?{text:o5(e.text)}:{}}:e}function o1(e){return eH(e)?{...o4(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:o3(e.error)}:{}}:e}function o2(e){return eH(e)?o4(e,["reply_message_id","block_id","card_id","widget_id","card_type","app_id","entity_id","title","fallback_text"]):e}function o3(e){return eH(e)?o4(e,["code","message","user_message","retryable","stage","details","name","stack"]):e}function o4(e,t){let r={};for(let a of t)void 0!==e[a]&&(r[a]=e[a]);return r}function o5(e){return e.length>1e3?`${e.slice(0,1e3)}...`:e}function o6(e){let[t,r]=(0,eB.useState)(),a=(0,eB.useRef)(),n=(0,eB.useRef)(),s=sX((e,t)=>{if(n.current===e.commandId)return!1;n.current=e.commandId;let s={previousTarget:t,command:e};return a.current=s,r(s),!0}),i=sX((t,n)=>{var s;(null==(s=a.current)?void 0:s.command.commandId)===t&&(a.current=void 0,r(void 0),null==e||e(t,n))});return{accept:s,pending:t,pendingRef:a,report:i}}let o8="u"<typeof window?eB.useEffect:eB.useLayoutEffect;function o7(){let[e,t]=(0,eB.useState)(t2),[r,a]=(0,eB.useState)("fit"),n=t3.find(t=>t.key===e)??t3.find(e=>e.key===t2)??t3[0],s=t4.find(e=>e.key===r)??t4.find(e=>"fit"===e.key)??t4[0],i="fit"===s.key,{fitScale:o,setRuntimeShellRef:l}=function(e){let{deviceHeight:t,deviceWidth:r,enabled:a}=e,[n,s]=(0,eB.useState)(.88),i=(0,eB.useRef)(null),o=(0,eB.useRef)(null),l=(0,eB.useCallback)(()=>{let e=i.current;if(!e)return;let a=getComputedStyle(e),n=Number.parseFloat(a.paddingLeft)+Number.parseFloat(a.paddingRight),o=Number.parseFloat(a.paddingTop)+Number.parseFloat(a.paddingBottom),l=Math.floor(1e3*Math.max(.1,Math.min(1,(e.clientWidth-n-12)/r,(e.clientHeight-o-12)/t)))/1e3;s(e=>Math.abs(e-l)>.001?l:e)},[t,r]),d=(0,eB.useCallback)(e=>{var t;if(null==(t=o.current)||t.disconnect(),o.current=null,i.current=e,!e||!a)return;let r=new ResizeObserver(l);r.observe(e),o.current=r,l()},[a,l]);return o8(()=>{a&&l()},[a,l]),o8(()=>()=>{var e;null==(e=o.current)||e.disconnect()},[]),{fitScale:n,setRuntimeShellRef:d}}({deviceHeight:n.height,deviceWidth:n.width,enabled:i}),d=i?o:s.scale;return{runtimeScaleMode:i?"fit":"fixed",runtimeStyle:{"--wsd-runtime-width":`${n.width}px`,"--wsd-runtime-height":`${n.height}px`,"--wsd-runtime-layout-width":`${n.width*d}px`,"--wsd-runtime-layout-height":`${n.height*d}px`,"--wsd-runtime-radius":`${n.radius}px`,"--wsd-runtime-home-indicator-display":n.homeIndicator?"block":"none","--wsd-runtime-safe-area-bottom":`${n.safeArea.bottom}px`,"--wsd-runtime-scale":d},selectedDevice:n,selectedDeviceKey:e,selectedScaleKey:r,setRuntimeShellRef:l,setSelectedDeviceKey:t,setSelectedScaleKey:a}}let o9={logs:[],updatedAtMs:0};function le(e){if(eH(e)&&"string"==typeof e.id&&eH(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:eH(e.response)?e.response:void 0,sandboxSessionId:"string"==typeof e.sandboxSessionId?e.sandboxSessionId:"",status:e.status,timestamp:e.timestamp,updatedAtMs:e.updatedAtMs}}function lt(e){return eH(e)?{logs:Array.isArray(e.logs)?e.logs.map(le).filter(e=>!!e):[],updatedAtMs:"number"==typeof e.updatedAtMs?e.updatedAtMs:0}:o9}function lr(e){let[t,r]=(0,eB.useState)(o9),a=(0,eB.useRef)(0),n=sX(async()=>{if(!e)throw Error("服务端日志接口不可用");let t=++a.current,n=await fetch(e,{headers:{Accept:"application/json"},method:"DELETE"});if(!n.ok)throw Error(`清空服务端日志失败(HTTP ${n.status})`);let s=lt(await n.json());t===a.current&&r(s)});return(0,eB.useEffect)(()=>{let t,n;if(!e)return void r(o9);let s=!1,i=async()=>{n=new AbortController;let o=a.current;try{let t=await fetch(e,{cache:"no-store",headers:{Accept:"application/json"},signal:n.signal});if(t.ok&&!s&&o===a.current){let e=lt(await t.json());r(t=>t.updatedAtMs===e.updatedAtMs?t:e)}}catch{}s||(t=window.setTimeout(i,1e3))};return i(),()=>{s=!0,null==n||n.abort(),void 0!==t&&window.clearTimeout(t)}},[e]),{clearLogs:n,logs:t.logs}}function la(e,t,r){var a;let n=(0,eB.useRef)(),s=!!(e&&r&&((null==(a=n.current)?void 0:a.endpoint)!==e||n.current.snapshot!==r)),i=(0,eB.useMemo)(()=>e?oG(oK(t,{includeRuntimeRoot:s})):void 0,[e,s,t]);(0,eB.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&&(n.current={endpoint:e,snapshot:r})},500);return()=>window.clearTimeout(t)},[e,s,r,i])}let ln={appEntries:[],entries:[],updatedAtMs:0};function ls(e,t){var r;return!t||e.traceId===t||(null==(r=e.trace)?void 0:r.trace_id)===t}function li(e,t){var r;let{chromeDevToolsFrontendUrl:a,controlCommand:n,controlClientId:s,debugContext:i,onChromeDevToolsPanelChange:o,onActiveViewChange:u,onControlResult:c,onMessage:p,onNavigateToPage:m,apiEnvironment:h,showDebugTrace:g,traceSnapshotEndpoint:f,webSdkDebugger:v}=e,y=sJ(v),_=(0,eB.useMemo)(()=>y.widgets.filter(e5),[y.widgets]),b=(0,eB.useRef)(null),w=(0,eB.useRef)(null),S=(0,eB.useRef)(null),x=(0,eB.useRef)(null),I=(0,eB.useRef)(null);!I.current&&"u">typeof document&&(I.current=document.createElement("div"));let[C,E]=(0,eB.useState)(0),k=sX(()=>w.current),[N,R]=(0,eB.useState)(null),[T,M]=(0,eB.useState)(!1),[A,P]=(0,eB.useState)(0),[j,D]=(0,eB.useState)(!1),[L,O]=(0,eB.useState)([]),[U,q]=(0,eB.useState)(ln),[$,B]=(0,eB.useState)(null),[F,H]=(0,eB.useState)(null),[W,z]=(0,eB.useState)(),[V,G]=(0,eB.useState)(0),[K,J]=(0,eB.useState)(0),X=s1(),Q=iY(),Z=iP(),Y=(null==i?void 0:i.sandboxSessionAvailable)!==!1,ee=i2(i),[et,er]=(0,eB.useState)(!0!==ee),ea=of(ee),en=oI(Y),{clearLogs:es,logs:ei}=lr(null==i?void 0:i.sandboxBridgeLogsEndpoint),eo=(0,eB.useRef)(null),el=(0,eB.useMemo)(()=>x.current,[C]),{accept:ed,pending:eu,pendingRef:ec,report:ep}=o6(c),em=(0,eB.useRef)(),eh=(0,eB.useRef)(),eg=(0,eB.useRef)(new Map),ef=(0,eB.useRef)(0),{runtimeScaleMode:ev,runtimeStyle:ey,selectedDevice:e_,selectedDeviceKey:eb,setRuntimeShellRef:ew,setSelectedDeviceKey:eS}=o7(),ex=(0,eB.useRef)(eb),eI=(null==(r=y.widgetSelection)?void 0:r.item.widgetId)??"",eC=(0,eB.useRef)(eI),eE=y.simulator,ek=(0,eB.useRef)(eE.toolCalls),eN=!!y.widgetSelection&&"streaming"!==eE.streamStatus&&!j,eR=(0,eB.useMemo)(()=>({...t5,density:e_.density,label:e_.label,width:Math.max(1,e_.width-38)}),[e_.density,e_.label,e_.width]);(0,eB.useEffect)(()=>{ek.current=eE.toolCalls},[eE.toolCalls]);let eT=sX(e=>{let t=function(e,t){var r;if(!eH(e))return e;let a="string"==typeof e.source_tool_call_id?e.source_tool_call_id:void 0,n=a?t.find(e=>e.toolCallId===a):void 0;if(!n)return e;let s=eH(e.trace)?e.trace:{},i="string"==typeof e.trace_id||"string"==typeof s.trace_id;return{...e,...e.request_id?{}:{request_id:n.requestId},...i||!(null==(r=n.trace)?void 0:r.trace_id)?{}:{trace_id:n.trace.trace_id}}}(e,ek.current),r=++ef.current,a={display:tb(t),id:`trace-${r}`,order:r,payload:t,timestamp:Date.now()};O(e=>[...e,a].slice(-200))}),eM=sX(()=>{O([])}),eA=(0,eB.useMemo)(()=>[...eE.traceEvents.map((e,t)=>({event:e,sortOrder:e.order??t})),...L.map((e,t)=>({event:e,sortOrder:e.order??eE.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,eE.traceEvents]),eP=(0,eB.useMemo)(()=>({...i,manifestUrl:y.manifestUrl,simulatorEndpoint:eE.endpoint}),[i,eE.endpoint,y.manifestUrl]),ej=(0,eB.useMemo)(()=>oi({context:eP,events:eA,manifest:y.manifest,pages:y.pages,widgets:y.widgets}),[eA,eP,y.manifest,y.pages,y.widgets]),eD=ej.appId||y.manifest.appId,eL=ej.appName||y.manifest.name,eO=(0,eB.useMemo)(()=>({type:"widget",appId:eD,appName:eL,widgetId:eI,viewport:{key:e_.key,label:e_.label,width:Math.max(1,e_.width-38),height:e_.height,density:e_.density}}),[eD,eL,e_,eI]),eU=(0,eB.useMemo)(()=>ol(ej,"card"===t&&y.widgetSelection?eO:void 0),[t,eO,ej.pages,ej.widgets,y.widgetSelection]),eq=!!(eu&&oo($,el,eu.previousTarget)&&"card"===t&&eI===eu.command.widgetId),e$=(0,eB.useMemo)(()=>"card"===t&&(null==$?void 0:$.sourceTarget)===el?{target:eO,root:$.root,nodeCount:$.nodeCount,selectedUid:$.selectedUid,truncated:$.truncated,updatedAtMs:$.updatedAtMs}:void 0,[t,eO,$,el]),eF=(0,eB.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:s,...eq?{command_id:null==eu?void 0:eu.command.commandId}:{},context:{launch_dir:eP.launchDir,manifest_url:y.manifestUrl,app_id:eD,app_name:y.manifest.name,mcp_endpoint:eP.mcpEndpoint,mcp_original_endpoint:ej.sources.mcp.original,mcp_proxy_endpoint:ej.sources.mcp.proxy,simulator_manifest_original_url:ej.sources.manifest.original,simulator_manifest_proxy_url:ej.sources.manifest.proxy,simulator_manifest_url:eP.simulatorManifestUrl,simulator_skill_original_url:ej.sources.skill.original,simulator_skill_proxy_url:ej.sources.skill.proxy,simulator_skill_url:eP.simulatorSkillUrl,widget_id:eI,simulator_endpoint:eE.endpoint,web_url:eP.webUrl},render_targets:eU,runtime_snapshot:e$,simulator:{stream_status:eE.streamStatus,active_request_id:eE.activeRequestId,active_reply_message_id:eE.activeReplyMessageId,error:eE.error,answer_finish:eE.answerFinish,messages:eE.messages,tool_calls:eE.toolCalls,trace_events:eE.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,ej.sources.manifest.original,ej.sources.manifest.proxy,ej.sources.mcp.original,ej.sources.mcp.proxy,ej.sources.skill.original,ej.sources.skill.proxy,eP.launchDir,eP.mcpEndpoint,eP.simulatorManifestUrl,eP.simulatorSkillUrl,eP.webUrl,U,eI,eE,eD,s,eq,null==eu?void 0:eu.command.commandId,eU,y.manifest.name,y.manifestUrl,e$]),eW=sX(e=>{v.approveSimulatorToolCall(e).catch(e=>{null==p||p(e.message,!0)})}),ez=sX(e=>{v.rejectSimulatorToolCall(e).catch(e=>{null==p||p(e.message,!0)})}),eV=sX(e=>{"clear-trace-filter"===e.kind?z(void 0):oC(e,{onClearLogs:es,onMessage:p,onRecreated:()=>er(!0),onUpdated:()=>er(!1)})||("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&("approve-tool-call"===e.kind?eW:ez)(e.toolCallId)}),eG=sX(e=>{z(t=>t===e?void 0:e)}),eK=sX(()=>{G(e=>e+1)});(0,eB.useEffect)(()=>{"success"===ea.tone&&er(!1)},[ea.tone]),(0,eB.useEffect)(()=>{void 0!==ee&&er(!ee)},[ee]);let eJ=sX(()=>{J(e=>e+1)}),eX=sX(e=>{e.stopPropagation(),er(!1)}),eQ=Math.max(V,K);(0,eB.useEffect)(()=>{W&&!eE.messages.some(e=>ls(e,W))&&z(void 0)},[W,eE.messages]);let eZ=(0,eB.useMemo)(()=>g?eA:eA.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[eA,g]),eY="conversation"===t?F:el,e0=sX(e=>{H(e)}),e1=sX((e,t)=>{t?eg.current.set(e,t):eg.current.delete(e)}),e2=sX((e,t)=>Array.from(eg.current.values()).reverse().find(r=>{let a;return r.isConnected&&(a=r.getBoundingClientRect()).width>0&&a.height>0&&e>=a.left&&e<=a.right&&t>=a.top&&t<=a.bottom})??null),e3=(0,eB.useMemo)(()=>oX(eZ,{debug:g,messages:eE.messages,traceId:W}),[W,g,eE.messages,eZ]),e4=(0,eB.useMemo)(()=>W?eE.toolCalls.filter(e=>ls(e,W)):eE.toolCalls,[W,eE.toolCalls]),e6=(0,eB.useMemo)(()=>oJ(eF,{debug:g,traceId:W}),[W,g,eF]),e8=(0,eB.useMemo)(()=>oG(e6),[e6]),e7=(0,eB.useMemo)(()=>({debugData:ej,events:e3,logSnapshot:e6,logSnapshotText:e8,sandbox:{available:Y,input:{csrPem:(null==i?void 0:i.sandboxCsrPem)??"",phoneNum:(null==i?void 0:i.sandboxPhoneNum)??""},logs:ei,businessInfoStatus:ea,sessionStatus:en},showDebugTrace:g,traceFilterId:W??"",traceSurface:"conversation",toolCalls:e4,updatedAtMs:Date.now()}),[ej,e4,e3,e6,e8,ei,Y,ea,en,W,g]);la(f,eF,$),(0,eB.useEffect)(()=>{if((null==n?void 0:n.type)==="render_widget"&&ed(n,el))try{v.selectWidget(n.widgetId)}catch(e){ep(n.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[ed,n,ep,v,el]),(0,eB.useEffect)(()=>{eu&&eq&&ep(eu.command.commandId,{ok:!0,target:eO,snapshot:oK(eF)})},[eO,eq,eu,ep,eF]);let e9=(0,eB.useMemo)(()=>{let e=(e,t,r)=>{var a;if("AppletBridgeModule"===r&&("postMessage"===e||"postMessageSync"===e)&&eH(a=t)&&"call"===a.type&&"string"==typeof a.name&&"number"==typeof a.callbackId){if("mind.getAgentTraceSwitch"===t.name)return iH(t,{value:!0});if("mind.reportAgentTraceEvent"===t.name)return eT(t.params??{}),iH(t)}};return(t,r,a,n)=>"AppletBridgeModule"===a&&"postMessage"===t&&l(r)&&"doubao.navigateTo"===r.name&&eH(r.params)&&"string"==typeof r.params.url?(null==m||m({url:r.params.url}),null==p||p(`卡片 navigateTo: ${r.params.url}`),d(r,{})):e(t,r,a,n)},[eT,p,m]),te=(0,eB.useCallback)(e=>nd({appId:eD,appIcon:y.manifest.iconSrc,appName:eL,baseAPIRegistry:null==h?void 0:h.apiRegistry,onCustomLoginNavigate:e=>null==m?void 0:m({url:e}),sendFollowUpMessage:e=>{let{content:t,prompt:r}=e;return v.sendSimulatorQuery(r,{followUpContent:t})},toolCall:e=>v.callSimulatorTool(e),multiMediaBroadcastContainer:e??void 0,runtimeHost:null==h?void 0:h.runtimeHost,scanCodePresenter:Q.scanCodePresenter,showSandboxCashier:X.showCashier,uiPresenter:Q.presenter,showSimulatorPermission:Z.showPermission,vibrationContainer:S.current??void 0}),[h,eD,eL,m,X.showCashier,Q.scanCodePresenter,Q.presenter,Z.showPermission,y.manifest.iconSrc,v]),tt=(0,eB.useMemo)(()=>te(),[te]),tr=sX(e=>{x.current!==e&&(x.current=e,E(e=>e+1)),R(null)});(0,eB.useEffect)(()=>{let e=b.current;if(!e)return;let t=te(e),r=new sG({container:e,nativeModulesCallHandler:e9,webSdkDebugger:v,onError:e=>{null==p||p(`Widget runtime error ${eI}: ${e.message}`,!0)},apiEnvironment:t});eo.current=r;let a=r.subscribeTarget(tr);return tr(r.getCurrentTarget()),()=>{a(),r.destroy(),eo.current=null,tr(null)}},[t,te,e9,p,eI,tr,v]);let ta=sX(async function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=eo.current,a=t.widgetId??(null==(e=y.widgetSelection)?void 0:e.item.widgetId);if(!r||!a)return Promise.resolve();let n=t.initData??eh.current;return void 0!==t.initData&&(eh.current=t.initData),console.log(`Rendering widget ${a} with initData:`,n),eM(),r.render({widgetId:a,...n?{initData:n}:{},viewport:{...t5,density:e_.density,label:e_.label,width:Math.max(1,e_.width-38)}}).then(()=>{ex.current=eb,M(!0),null==p||p(`Rendered widget ${a}`)}).catch(e=>{M(!1),null==p||p(e.message,!0);let t=ec.current;(null==t?void 0:t.command.widgetId)===a&&ep(t.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:e.message}})})});(0,eB.useEffect)(()=>{let e=ec.current;e&&"card"===t&&eo.current&&em.current!==e.command.commandId&&(em.current=e.command.commandId,ta({widgetId:e.command.widgetId,initData:e.command.structuredContent}))},[t,eu,ta]),(0,eB.useEffect)(()=>{var e,t;let r=eC.current;if((eC.current=eI,r!==eI)&&(null==(e=ec.current)?void 0:e.command.widgetId)!==eI){if(y.widgetSelection)return void ta();eM(),M(!1),null==(t=eo.current)||t.clear()}},[eM,ta,eI,y.widgetSelection]),(0,eB.useEffect)(()=>{!ec.current&&T&&ex.current!==eb&&ta()},[T,ta,eb]);let tn=sX(()=>{eN&&(D(!0),v.reloadResources().then(()=>{P(e=>e+1),T&&ta(),null==p||p("已刷新卡片资源")}).catch(e=>{null==p||p(e.message,!0)}).finally(()=>{D(!1)}))});return{activeView:t,appendAgentTraceEvent:eT,canReloadResources:eN,cardReloadKey:A,chromeDevToolsFrontendUrl:a,controlCommand:n,conversationAPIEnvironment:tt,conversationConsoleTarget:I.current,conversationWidgetViewport:eR,currentDebugAppId:eD,currentDebugAppName:eL,debugState:e7,devtoolsTarget:eY,devToolsPanelId:K===eQ&&eQ>0?"wsd-sandbox":V>0?"wsd-trace":void 0,getRuntimeFrame:k,handleDebugAction:eV,handleGrantingSheetTargetChange:e0,handleInspectableCardTargetChange:e1,handleQuerySubmit:eK,handleSandboxLoginHintClick:eJ,handleSandboxLoginHintClose:eX,handleTraceMessageSelect:eG,hasRenderedPreview:T,highlightRect:N,latestDevToolsPanelRequestId:eQ,nativeModulesCallHandler:e9,onActiveViewChange:u,onChromeDevToolsPanelChange:o,onControlResult:c,onMessage:p,onNavigateToPage:m,reloadResources:tn,renderSelectedWidget:ta,resolveConversationInspectTarget:e2,runtimeFrameRef:w,runtimeFrameScaleBoxRef:S,runtimeScaleMode:ev,runtimeStyle:ey,runtimeTargetRef:b,sandboxCashier:X,simulatorUI:Q,simulatorPermissionPrompt:Z,selectedDeviceKey:eb,selectedTraceId:W,selectedWidgetId:eI,setHighlightRect:R,setRuntimeConsoleSnapshot:q,setRuntimeDomSnapshot:B,setSelectedDeviceKey:eS,setRuntimeShellRef:ew,sandboxLoginAvailable:Y,showSandboxLoginHint:et,simulatorState:eE,state:y,visibleWidgets:_,webSdkDebugger:v}}function lo(e){let t=li(e,"conversation");return(0,s.jsx)(iF,{runtime:t,children:(0,s.jsx)(sY,{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)(iT,{apiEnvironment:t.conversationAPIEnvironment,appId:t.currentDebugAppId,cardReloadKey:t.cardReloadKey,nativeModulesCallHandler:t.nativeModulesCallHandler,onMessage:t.onMessage,onGrantingSheetTargetChange:t.handleGrantingSheetTargetChange,onInspectableCardTargetChange:t.handleInspectableCardTargetChange,onNavigateToPage:t.onNavigateToPage,onQuerySubmit:t.handleQuerySubmit,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)(s0,{cashier:t.sandboxCashier.cashier,onCancel:t.sandboxCashier.cancelCashier,onConfirm:t.sandboxCashier.confirmCashier}):null,t.simulatorPermissionPrompt.permission?(0,s.jsx)(iA,{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 ll=r(48174),ld=r(80405);let lu={appEntries:[],entries:[],updatedAtMs:0};function lc(e){var t,r;return e.path??(null==(r=(t=e).web)?void 0:r.entry)??t.entry}function lp(){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 lm(e){var t,r,a;let{activeView:n,chromeDevToolsFrontendUrl:i,controlCommand:o,controlClientId:l,debugContext:d,onChromeDevToolsPanelChange:u,onActiveViewChange:c,onControlResult:p,onMessage:m,apiEnvironment:h,showDebugTrace:g,traceSnapshotEndpoint:f,webSdkDebugger:v}=e,y=sJ(v),_=(0,eB.useMemo)(()=>y.pages.filter(e5),[y.pages]),[b,w]=(0,eB.useState)(null),[S,x]=(0,eB.useState)(null),[I,C]=(0,eB.useState)(null),[E,k]=(0,eB.useState)(null),[N,R]=(0,eB.useState)(null),[T,M]=(0,eB.useState)(0),[A,P]=(0,eB.useState)(null),[j,D]=(0,eB.useState)(lu),L=s1(),O=iY(),U=(null==d?void 0:d.sandboxSessionAvailable)!==!1,q=of(i2(d)),$=oI(U),{clearLogs:B,logs:F}=lr(null==d?void 0:d.sandboxBridgeLogsEndpoint),[H,W]=(0,eB.useState)(null),z=iP(),V=(0,eB.useRef)(null),{accept:G,pending:K,pendingRef:J,report:X}=o6(p),{runtimeScaleMode:Q,runtimeStyle:Z,selectedDevice:Y,selectedDeviceKey:ee,setRuntimeShellRef:et,setSelectedDeviceKey:er}=o7(),ea=(null==(t=y.pageSelection)?void 0:t.item.id)??"",en=y.pageSelection?lc(y.pageSelection.item):"",es=(0,eB.useMemo)(()=>({...d,manifestUrl:y.manifestUrl,simulatorEndpoint:y.simulator.endpoint}),[d,y.manifestUrl,y.simulator.endpoint]),ei=(0,eB.useMemo)(()=>oi({context:es,events:y.simulator.traceEvents,manifest:y.manifest,pages:y.pages,widgets:y.widgets}),[es,y.manifest,y.pages,y.simulator.traceEvents,y.widgets]),eo=ei.appId||y.manifest.appId,el=ei.appName||y.manifest.name,ed=(0,eB.useMemo)(()=>{var e;return{type:"page",appId:eo,appName:el,pageId:ea,pagePath:en,url:(null==(e=y.pageSelection)?void 0:e.routeUrl)??en,viewport:{key:Y.key,label:Y.label,width:Y.width,height:Y.height,density:Y.density}}},[eo,el,Y,ea,en,null==(r=y.pageSelection)?void 0:r.routeUrl]),eu=(0,eB.useMemo)(()=>ol(ei,y.pageSelection?ed:void 0),[ed,ei.pages,ei.widgets,y.pageSelection]),ec=!!(K&&oo(H,E,K.previousTarget)&&(null==(a=y.pageSelection)?void 0:a.routeUrl)===K.command.url),ep=(0,eB.useMemo)(()=>(null==H?void 0:H.sourceTarget)===E?{target:ed,root:H.root,nodeCount:H.nodeCount,selectedUid:H.selectedUid,truncated:H.truncated,updatedAtMs:H.updatedAtMs}:void 0,[ed,E,H]),em=(0,eB.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:l,...ec?{command_id:null==K?void 0:K.command.commandId}:{},context:{launch_dir:es.launchDir,manifest_url:y.manifestUrl,app_id:eo,app_name:ei.appName||y.manifest.name,mcp_endpoint:es.mcpEndpoint,mcp_original_endpoint:ei.sources.mcp.original,mcp_proxy_endpoint:ei.sources.mcp.proxy,page_id:ea,page_path:en,simulator_endpoint:y.simulator.endpoint,simulator_manifest_original_url:ei.sources.manifest.original,simulator_manifest_proxy_url:ei.sources.manifest.proxy,simulator_manifest_url:es.simulatorManifestUrl,simulator_skill_original_url:ei.sources.skill.original,simulator_skill_proxy_url:ei.sources.skill.proxy,simulator_skill_url:es.simulatorSkillUrl,web_url:es.webUrl},render_targets:eu,runtime_snapshot:ep,page_runtime_trace_events:[],runtime_console:{app:{entries:j.appEntries,updated_at_ms:j.updatedAtMs},page:{entries:j.entries,updated_at_ms:j.updatedAtMs}},simulator:{stream_status:y.simulator.streamStatus,trace_events:y.simulator.traceEvents,tool_calls:y.simulator.toolCalls}}),[ei.appId,ei.appName,ei.sources.manifest.original,ei.sources.manifest.proxy,ei.sources.mcp.original,ei.sources.mcp.proxy,ei.sources.skill.original,ei.sources.skill.proxy,es.launchDir,es.mcpEndpoint,es.simulatorManifestUrl,es.simulatorSkillUrl,es.webUrl,j,ea,en,eo,l,ec,null==K?void 0:K.command.commandId,eu,y.manifest.name,y.manifestUrl,y.simulator.endpoint,y.simulator.streamStatus,y.simulator.toolCalls,y.simulator.traceEvents,ep]),eh=(0,eB.useMemo)(()=>g?y.simulator.traceEvents:y.simulator.traceEvents.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[g,y.simulator.traceEvents]),eg=(0,eB.useMemo)(()=>oX(eh,{debug:g,messages:y.simulator.messages}),[g,y.simulator.messages,eh]),ef=(0,eB.useMemo)(()=>oJ(em,{debug:g}),[g,em]),ev=(0,eB.useMemo)(()=>oG(ef),[ef]),ey=sX(e=>{oC(e,{onClearLogs:B,onMessage:m})}),e_=(0,eB.useMemo)(()=>({debugData:ei,events:eg,logSnapshot:ef,logSnapshotText:ev,sandbox:{available:U,input:{csrPem:(null==d?void 0:d.sandboxCsrPem)??"",phoneNum:(null==d?void 0:d.sandboxPhoneNum)??""},logs:F,businessInfoStatus:q,sessionStatus:$},showDebugTrace:g,traceSurface:"page",toolCalls:y.simulator.toolCalls,updatedAtMs:Date.now()}),[ei,eg,ef,ev,F,q,U,$,g,y.simulator.toolCalls]);la(f,em,H),(0,eB.useEffect)(()=>{if((null==o?void 0:o.type)==="render_page"&&G(o,E))try{v.navigateToPage(o.url)}catch(e){X(o.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[G,o,E,X,v]),(0,eB.useEffect)(()=>{K&&ec&&X(K.command.commandId,{ok:!0,target:ed,snapshot:oK(em)})},[ed,ec,K,X,em]);let eb=sX((e,t)=>{let r=tx(v,{noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==m||m("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==m||m("当前仍在生成中,暂不重发授权后的消息",!0);return}v.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==m||m(e.message,!0)})}),ew=sX((e,t)=>{eb(e,t),"login"===e&&(null==c||c("conversation"))}),eS=(0,eB.useMemo)(()=>nd({appId:eo,appIcon:y.manifest.iconSrc,appName:el,baseAPIRegistry:null==h?void 0:h.apiRegistry,onGrantingCompleted:ew,sendFollowUpMessage:e=>{let{content:t,prompt:r}=e;return v.sendSimulatorQuery(r,{followUpContent:t})},toolCall:e=>v.callSimulatorTool(e),multiMediaBroadcastContainer:b??void 0,runtimeHost:null==h?void 0:h.runtimeHost,scanCodePresenter:O.scanCodePresenter,showSandboxCashier:L.showCashier,uiPresenter:O.presenter,showSimulatorPermission:z.showPermission,vibrationContainer:I??void 0}),[h,ew,eo,el,I,b,L.showCashier,O.scanCodePresenter,O.presenter,z.showPermission,y.manifest.iconSrc,v]);(0,eB.useEffect)(()=>{if(!b)return;let e=new sV({container:b,webSdkDebugger:v,onExitApp:()=>null==c?void 0:c("conversation"),onError:e=>{null==m||m(`Page runtime error: ${e.message}`,!0)},apiEnvironment:eS});V.current=e;let t=e.subscribeTarget(t=>{k(t),M(e.getPageStackSize()),P(null)}),r=e.subscribeAppTarget(e=>{R(e)});return k(e.getCurrentTarget()),R(e.getCurrentAppTarget()),M(e.getPageStackSize()),()=>{t(),r(),e.destroy(),V.current=null,k(null),R(null),M(0),P(null)}},[c,m,eS,b,v]),(0,eB.useEffect)(()=>{let e=V.current;if(!e||!y.pageSelection){null==e||e.clear();return}try{e.render({device:Y})}catch(t){null==m||m(t.message,!0);let e=J.current;e&&X(e.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:t.message}})}},[m,X,b,Y,ea,y.pageSelection]);let ex=(0,eB.useMemo)(()=>({appTarget:N,controlCommand:o,debugState:e_,frontendUrl:i,onConsoleSnapshotChange:D,onControlResult:p,onDebugAction:ey,onHighlightChange:P,onRuntimeSnapshotChange:W,preserveConsoleOnTargetChange:!0,runtimeFrame:S,target:y.pageSelection?E:null}),[N,i,o,e_,ey,p,E,S,y.pageSelection]);return(0,eB.useEffect)(()=>{null==u||u(ex)},[ex,u]),(0,s.jsxs)("div",{className:"wsd-page-preview-column",children:[(0,s.jsx)(iB,{activeView:n??"page",onActiveViewChange:c,onDeviceChange:er,selectedDeviceKey:ee,children:(0,s.jsx)("button",{"aria-label":"Reload",className:"wsd-icon-button",disabled:!y.pageSelection,onClick:()=>{var e;return null==(e=V.current)?void 0:e.reload()},title:"Reload",type:"button",children:(0,s.jsx)(ij,{"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:T<2,onClick:()=>{var e;return null==(e=V.current)?void 0:e.closeCurrentPage()},title:"返回",type:"button",children:(0,s.jsx)(lp,{})})}),(0,s.jsx)(ll.d,{"aria-label":"页面路径",className:"wsd-page-route-select",classNames:{selectorIcon:"wsd-page-path-icon",trigger:"wsd-page-path-select",value:"wsd-page-path-value"},isDisabled:!y.pageSelection||0===_.length,onChange:e=>v.selectPage(e.target.value),placeholder:en||"No page",selectedKeys:ea?[ea]:[],size:"sm",children:_.map(e=>(0,s.jsx)(ld.y,{title:lc(e),children:lc(e)},e.id))})]}),y.pageSelection?(0,s.jsx)(sY,{highlightRect:A,overlay:(0,s.jsxs)(s.Fragment,{children:[O.overlay,L.cashier?(0,s.jsx)(s0,{cashier:L.cashier,onCancel:L.cancelCashier,onConfirm:L.confirmCashier}):null,z.permission?(0,s.jsx)(iA,{onAllow:z.allowPermission,onReject:z.rejectPermission,permission:z.permission}):null]}),runtimeFrameRef:x,runtimeFrameScaleBoxRef:C,runtimeScaleMode:Q,runtimeShellRef:et,runtimeStyle:Z,runtimeTargetRef:w}):(0,s.jsx)("div",{className:"wsd-page-empty",children:"No page"})]})}var lh=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"})}),lg=r(48986),lf=r(80704),lv=r(51290),ly=r(36091);let l_=lv.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)"}}),lb=[(0,lg.Pq)(),(0,lf.pJ)(),(0,lf.bu)((0,lg.cp)()),lv.Lz.lineWrapping,l_];function lw(e){let{ariaLabel:t,minHeight:r=96,onChange:a,value:n}=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)(ly.Ay,{basicSetup:{autocompletion:!0,bracketMatching:!0,closeBrackets:!0,foldGutter:!0,highlightActiveLine:!0,highlightActiveLineGutter:!0,lineNumbers:!0,searchKeymap:!0},extensions:lb,minHeight:`${r}px`,onChange:a,value:n})})}async function lS(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 lx(e){let{actionDisabled:t,actionLabel:r,JsonEditorComponent:a,label:n,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:n}),(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(t7("JSON",u),null,2)),null==d||d(`${n} formatted`)}catch(e){null==d||d(e.message,!0)}},type:"button",children:"格式化"}),(0,s.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:()=>{lS(n,u,d)},type:"button",children:"复制"})]})]}),a?(0,s.jsx)(a,{ariaLabel:n,minHeight:i,onChange:l,value:u}):(0,s.jsx)("textarea",{"aria-label":n,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]})}let lI="输入数据(structuredContent)";function lC(e){let t=li(e,"card"),[r,a]=(0,eB.useState)("{}");function n(){try{t.renderSelectedWidget({initData:t7(lI,r)})}catch(r){var e;null==(e=t.onMessage)||e.call(t,r.message,!0)}}return(0,eB.useEffect)(()=>{var t;(null==(t=e.controlCommand)?void 0:t.type)==="render_widget"&&a(JSON.stringify(e.controlCommand.structuredContent,null,2))},[e.controlCommand]),(0,s.jsx)(iF,{runtime:t,children:t.state.widgetSelection?(0,s.jsx)(sY,{highlightRect:t.highlightRect,overlay:(0,s.jsxs)("section",{"aria-label":"卡片调试",className:"wsd-widget-card-debug",children:[(0,s.jsx)(s3,{}),(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:t.selectedWidgetId}),(0,s.jsx)(lh,{"aria-hidden":"true"}),(0,s.jsx)("select",{"aria-label":"卡片模板",disabled:0===t.visibleWidgets.length,onChange:e=>t.webSdkDebugger.selectWidget(e.currentTarget.value),value:t.selectedWidgetId,children:t.visibleWidgets.map(e=>(0,s.jsx)("option",{value:e.widgetId,children:e.widgetId},e.widgetId))})]}),(0,s.jsx)(lx,{JsonEditorComponent:lw,label:lI,minHeight:200,onAction:n,onChange:a,onMessage:t.onMessage,value:r}),(0,s.jsx)("button",{className:"wsd-button wsd-button-primary wsd-widget-card-render-button",onClick:n,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,eh.$)({"wsd-widget-card-preview-target":t.hasRenderedPreview}),ref:t.runtimeTargetRef}),t.hasRenderedPreview?null:(0,s.jsx)("span",{className:"wsd-widget-card-preview-empty",children:"未传入内容"}),t.simulatorUI.overlay,t.sandboxCashier.cashier?(0,s.jsx)(s0,{cashier:t.sandboxCashier.cashier,onCancel:t.sandboxCashier.cancelCashier,onConfirm:t.sandboxCashier.confirmCashier}):null,t.simulatorPermissionPrompt.permission?(0,s.jsx)(iA,{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}):(0,s.jsx)("div",{className:"wsd-page-empty",children:"No widget"})})}var lE=r(85624);let lk="wsd-cdp-adapter",lN={jpeg:"image/jpeg",png:"image/png",webp:"image/webp"};function lR(e,t){return{ok:!1,error:{code:e,message:t}}}async function lT(e,t,r){if(!t||!r)return lR("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");if("get_computed_style"===e.type){let r=t.getComputedStyles(e.uid,e.properties);return r?{ok:!0,result:{uid:e.uid,computedStyle:r}}:lR("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}}:lR("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`)}let a=e.uid?t.getElement(e.uid):r;if(!a)return lR("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let n=lN[e.format],s=a.getBoundingClientRect(),i=a.offsetWidth||s.width,o=a.offsetHeight||s.height;try{let t=await (0,lE.TC)(a,{height:o,scale:3,type:n,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:${n};base64,`,s=t.startsWith(r)?t.slice(r.length):"";if(!s||s.length>8388608)return lR("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:n,width:Math.floor(3*i),height:Math.floor(3*o),...e.uid?{uid:e.uid}:{}}}}catch(e){return lR("SCREENSHOT_FAILED",e instanceof Error?e.message:String(e))}}function lM(e){let{controlCommand:t,debugState:r,frontendUrl:a,onDebugAction:n,onConsoleSnapshotChange:i,onControlResult:o,onHighlightChange:l,onRuntimeSnapshotChange:d,preserveConsoleOnTargetChange:u,resolveTargetAtPoint:c,getRuntimeFrame:p,runtimeFrame:m,showPanelId:h,showPanelRequestId:g,appTarget:f,consoleTarget:v,target:y}=e,_=(0,eB.useRef)(null),b=(0,eB.useRef)(r),w=(0,eB.useRef)(m??null),S=(0,eB.useRef)(f??null),x=(0,eB.useRef)(y),I=(0,eB.useRef)({consoleTarget:v,getRuntimeFrame:p,onConsoleSnapshotChange:i,onDebugAction:n,onHighlightChange:l,onRuntimeSnapshotChange:d,preserveConsoleOnTargetChange:u,resolveTargetAtPoint:c}),C=(0,eB.useRef)(),E=(0,eB.useRef)(null),k=(0,eB.useRef)(null),N=(0,eB.useRef)(null),R=(0,eB.useRef)(null),T=(0,eB.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.searchParams.set("wsdCdpTransport","postmessage");let a=t.searchParams.get("panel");return a&&"wsd-mcp"!==a&&"wsd-view"!==a||t.searchParams.set("panel","wsd-overview"),{origin:t.origin,url:t.toString()}})(a),[a]),M=(null==T?void 0:T.url)??null;I.current={consoleTarget:v,getRuntimeFrame:p,onConsoleSnapshotChange:i,onDebugAction:n,onHighlightChange:l,onRuntimeSnapshotChange:d,preserveConsoleOnTargetChange:u,resolveTargetAtPoint:c};let A=(0,eB.useCallback)(e=>{var t,r;T&&(null==(r=_.current)||null==(t=r.contentWindow)||t.postMessage({source:lk,type:"wsd-show-panel",panelId:e},T.origin))},[T]),P=sX(()=>{var e,t;let r=b.current;r&&T&&(null==(t=_.current)||null==(e=t.contentWindow)||e.postMessage({source:lk,type:"wsd-debug-state",state:r},T.origin))});return((0,eB.useEffect)(()=>{w.current=m??null},[m]),(0,eB.useEffect)(()=>{var e;S.current=f??null,null==(e=k.current)||e.call(k)},[f]),(0,eB.useEffect)(()=>{b.current=r,P();let e=[100,500,1e3].map(e=>window.setTimeout(P,e));return()=>e.forEach(e=>window.clearTimeout(e))},[r,P,M]),(0,eB.useEffect)(()=>{if(!h||!g)return;A(h);let e=[100,500].map(e=>window.setTimeout(()=>A(h),e));return()=>e.forEach(e=>window.clearTimeout(e))},[A,h,g]),(0,eB.useEffect)(()=>{I.current.onHighlightChange(null);let e=null==T?void 0:T.origin;R.current??=document.createElement("div");let t=new sU(x.current??R.current,{consoleTarget:I.current.consoleTarget,getAppTarget:()=>S.current,getRuntimeFrame:()=>I.current.getRuntimeFrame?I.current.getRuntimeFrame():w.current,onHighlightChange:e=>I.current.onHighlightChange(e),get preserveConsoleOnTargetChange(){return I.current.preserveConsoleOnTargetChange},resolveTargetAtPoint:(e,t)=>{var r,a;return(null==(r=(a=I.current).resolveTargetAtPoint)?void 0:r.call(a,e,t))??null}});E.current=t;let r=0,a=e=>{var a;let n=null==(a=t.dispatch({id:--r,method:e}).result)?void 0:a.entries;return Array.isArray(n)?n:[]},n=()=>{var e,t;null==(e=(t=I.current).onConsoleSnapshotChange)||e.call(t,{appEntries:a("WSD.getAppConsoleEntries"),entries:a("WSD.getConsoleEntries"),updatedAtMs:Date.now()})},s=()=>{var e,r,a,n,s,i;let o,l,d,u,c=x.current;if(!c){null==(a=(n=I.current).onRuntimeSnapshotChange)||a.call(n,null);return}let p=t.getInspectorSnapshot();null==(e=(r=I.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":s_(e),attributes:"element"===e.type?sv(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,a;e&&(null==(a=_.current)||null==(r=a.contentWindow)||r.postMessage({source:lk,...t},e))},o=t=>{var r,a;e&&(null==(a=_.current)||null==(r=a.contentWindow)||r.postMessage({source:lk,type:"cdp-raw-message",message:JSON.stringify(t)},e))};k.current=n,N.current=s;let l=t.subscribe(e=>{i(e),o(e),("WSD.consoleUpdated"===e.method||"WSD.appConsoleUpdated"===e.method)&&n(),("DOM.documentUpdated"===e.method||"DOM.inlineStyleInvalidated"===e.method||"Overlay.inspectNodeRequested"===e.method)&&s()}),d={method:"DOM.documentUpdated"};i(d),o(d),n(),s();let u=r=>{var a,n,s,l,d,u,c,p,m;if(!e||r.source!==(null==(a=_.current)?void 0:a.contentWindow)||r.origin!==e)return;let h=r.data;if((null==h?void 0:h.source)==="wsd-chrome-devtools-frontend"){if("ready"===h.type||"wsd-debug-ready"===h.type)return void P();if("wsd-debug-action"===h.type){let e=h.action;if((null==e?void 0:e.kind)==="clear-sandbox-bridge-logs"||(null==e?void 0:e.kind)==="clear-trace-filter"){null==(n=(s=I.current).onDebugAction)||n.call(s,e);return}if((null==e?void 0:e.kind)==="update-sandbox-business-info"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(l=(d=I.current).onDebugAction)||l.call(d,e);return}if((null==e?void 0:e.kind)==="recreate-sandbox-session"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(u=(c=I.current).onDebugAction)||u.call(c,e);return}e&&("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&"string"==typeof e.toolCallId&&(null==(p=(m=I.current).onDebugAction)||p.call(m,e));return}if("cdp-raw-message"===h.type&&"string"==typeof h.message){let e;try{e=JSON.parse(h.message)}catch{return}o(t.dispatch(e));return}"cdp-request"===h.type&&h.id&&i(t.dispatch({id:h.id,method:h.method??"",params:h.params,sessionId:h.sessionId}))}};return e&&window.addEventListener("message",u),()=>{window.removeEventListener("message",u),l(),k.current===n&&(k.current=null),N.current===s&&(N.current=null),E.current===t&&(E.current=null),t.destroy(),I.current.onHighlightChange(null)}},[P,T]),(0,eB.useEffect)(()=>{var e,t,r,a;x.current=y,R.current??=document.createElement("div"),null==(e=E.current)||e.setConsoleTarget(v),null==(t=E.current)||t.setTarget(y??R.current),null==(r=k.current)||r.call(k),null==(a=N.current)||a.call(N)},[v,y]),(0,eB.useEffect)(()=>{t&&"render_page"!==t.type&&"render_widget"!==t.type&&C.current!==t.commandId&&(C.current=t.commandId,(async()=>{let e;try{e=await lT(t,E.current,x.current)}catch(r){e=lR("take_screenshot"===t.type?"SCREENSHOT_FAILED":"INSPECTION_FAILED",r instanceof Error?r.message:String(r))}null==o||o(t.commandId,e)})())},[t,o]),M)?(0,s.jsx)("aside",{className:"wsd-chrome-devtools",children:(0,s.jsx)("iframe",{allow:"clipboard-write",className:"wsd-chrome-devtools-frame",onLoad:()=>{P(),h&&A(h)},ref:_,sandbox:"allow-scripts allow-same-origin allow-forms",src:M,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 lA(e,t,r){return Math.min(Math.max(e,t),r)}function lP(e,t,r,a){if(!t)return lA(e,r,a);let n=t.getBoundingClientRect().width;if(!n)return lA(e,r,a);let s=Math.min(a,Math.max(r,n-8-340));return lA(e,r,s)}function lj(e){var t,r;let{activeView:a="conversation",className:n,onActiveViewChange:i,...o}=e,[l,d]=(0,eB.useState)({onHighlightChange:()=>void 0,target:null}),u=sX(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]:{},[a,n]=(0,eB.useState)(e),[s,i]=(0,eB.useState)(!1),o=(0,eB.useRef)(null),l=(0,eB.useMemo)(()=>({"--wsd-preview-column-width":`${a}px`}),[a]),d=sX((e,a)=>{if(!a)return;let s=a.getBoundingClientRect();s.width&&n(lP(e-s.left,a,t,r))});(0,eB.useEffect)(()=>()=>{var e;null==(e=o.current)||e.call(o)},[]);let u=sX(e=>{var t,r;if(0!==e.button)return;let a=e.currentTarget,n=a.parentElement;if(!n)return;e.preventDefault(),null==(t=o.current)||t.call(o),null==(r=a.setPointerCapture)||r.call(a,e.pointerId),d(e.clientX,n),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,n)},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=sX(e=>{let a=e.currentTarget.parentElement;if("ArrowLeft"===e.key){e.preventDefault(),n(e=>lP(e-24,a,t,r));return}if("ArrowRight"===e.key){e.preventDefault(),n(e=>lP(e+24,a,t,r));return}if("Home"===e.key){e.preventDefault(),n(lP(t,a,t,r));return}"End"===e.key&&(e.preventDefault(),n(lP(r,a,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(a),onKeyDown:c,onPointerDown:u,role:"separator",tabIndex:0}}}({defaultWidth:340,maxWidth:560,minWidth:300}),h={...o,onChromeDevToolsPanelChange:u},g="page"===a?(0,s.jsx)(lm,{...h,activeView:a,onActiveViewChange:i}):"card"===a?(0,s.jsx)(lC,{...h,onActiveViewChange:i}):(0,s.jsx)(lo,{...h,onActiveViewChange:i});return(0,s.jsxs)("section",{className:(0,eh.$)("page"===a?"wsd-page-panel":"wsd-widget-panel",c&&"is-resizing",n),style:p,children:[(0,s.jsx)(is,{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)(lM,{...l})]})}var lD=r(33680);function lL(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 lO(e){return ek(e,{allowRootRelative:!0,baseUrl:window.location.href})}function lU(e){let t=function(e){let t={};for(let r of["content-type","content-length","x-tt-logid"]){let a=e.headers.get(r);a&&(t[r]=a)}return t}(e);return{status:e.status,status_text:e.statusText,...Object.keys(t).length>0?{response_headers:t}:{}}}function lq(e,t,r){lL(e,{event:`simulator_${t}_fetch_started`,phase:"request",url:r})}function l$(e,t,r,a){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};lL(e,{event:`simulator_${t}_fetch_succeeded`,phase:"response",url:r,...lU(a),...n})}function lB(e,t,r,a,n){lL(e,{event:`simulator_${t}_fetch_failed`,phase:"error",url:r,...n?lU(n):{},error:a instanceof Error?a.message:String(a)})}function lF(e,t,r){return Error(`Simulator ${e} failed: ${r.status} ${r.statusText} (${t})`)}let lH="web-sdk-debugger-demo",lW="mock_local_mcp",lz="mock_lookup",lV=["template-transport-card","template-price-action-card","template-ticket-order-card","weather-card","flight-card","api-demo-card","summary-card","configured-widget-id"],lG=[{server_id:lW,name:"Mock Local MCP",description:"Web SDK Debugger 本地模拟 MCP server",tools:[{name:lz,description:"返回用于本地调试的智能服务结构化结果",input_schema_json:JSON.stringify({type:"object",properties:{keyword:{type:"string"}},required:["keyword"]})}]}];function lK(e,t){return`id: evt_mock_${t.toString().padStart(4,"0")}
23
+ event: ${e.event}
24
+ data: ${JSON.stringify(e)}
25
+
26
+ `}function lJ(e,t){return t.find(t=>null==e?void 0:e.widgets.some(e=>e.widgetId===t))}function lX(e,t,r,a){var n;return{event:t,request_id:a.requestId,reply_message_id:a.replyMessageId,trace:{trace_id:(null==(n=e.trace)?void 0:n.trace_id)||`trace_mock_${e.idempotency_key??a.requestId}`,component:"mock_simulator",stage:t,sampled:!0},...r}}let lQ=async e=>{var t;let r=`找到和 ${(null==(t=e.arguments)?void 0:t.keyword)||"调试数据"} 相关的模拟结果`,a={content:[{type:"text",text:r}],structuredContent:{entities:[{entity_type:"debug_item",entity_id:"debug-item-1",name:"调试示例数据"}]},isError:!1},n=JSON.stringify(a);return{status:"succeeded",result:a.structuredContent,raw_result_text:r,raw_mcp_result_json:n,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{mock:!0}}},lZ=e7(e4),lY=nd({requestHandler:async e=>{var t,r;let a=await fetch("/__web_sdk_request_proxy__",{body:JSON.stringify((r=e.params).data instanceof ArrayBuffer?{...r,data:eF(r.data),dataEncoding:"base64"}:r),headers:{"content-type":"application/json"},method:"POST"}),n=(null==(t=a.headers.get("content-type"))?void 0:t.toLowerCase())??"",s=await a.text();if(!n.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(!a.ok)throw Error((null==i?void 0:i.message)||`Request proxy failed with status ${a.status}`);return(null==i?void 0:i.dataEncoding)==="base64"&&"string"==typeof i.data?d(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)}):d(e,i)}});function l0(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 l1(){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 l2(e,t){let r=t.skill,a=t.mcpServers,n=[];if("function"==typeof r&&n.push(Promise.resolve(r()).catch(()=>void 0)),"function"==typeof a){let t=e.getState();n.push(Promise.resolve(a({appKey:t.manifest.appId,appName:t.manifest.name,manifest:t.manifest.raw})).catch(()=>void 0))}await Promise.all(n)}function l3(){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 l4(){let e=(0,eB.useMemo)(()=>new URL(window.location.href).searchParams.get("manifest")||e3,[]),t=(0,eB.useMemo)(()=>l0("mcp","/__mcp_proxy",void 0),[]),r=(0,eB.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("mcpOriginal")||e.searchParams.get("mcpEndpoint")||""},[]),a=(0,eB.useMemo)(()=>l0("simulatorManifest","/__simulator_manifest/manifest.yaml",void 0),[]),n=(0,eB.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorManifestOriginal")||"",[]),i=(0,eB.useMemo)(()=>l0("simulatorSkill","/__simulator_skill/skill.md",void 0),[]),o=(0,eB.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorSkillOriginal")||"",[]),l=(0,eB.useMemo)(()=>e7(new URL(window.location.href).searchParams.get("simulator")||lZ),[]),d=(0,eB.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("launchDir")||e.searchParams.get("projectPath")||e.searchParams.get("cwd")||""},[]),u=(0,eB.useMemo)(()=>`${window.location.origin}${window.location.pathname}`,[]),c=(0,eB.useMemo)(()=>{let e;return null!==(e=new URL(window.location.href).searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase()},[]),p=(0,eB.useMemo)(()=>"1"===new URL(window.location.href).searchParams.get("simulatorMock")||"true"===String((void 0)??"").toLowerCase(),[]),[m,h]=(0,eB.useState)({}),g=(0,eB.useMemo)(()=>crypto.randomUUID(),[]),[f,v]=(0,eB.useState)(),y=(0,eB.useRef)(null),_=(0,eB.useMemo)(()=>(function(e){var t,r,a,n,s;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o={mcpEndpoint:lO((t={mcpEndpoint:e,simulatorManifestUrl:i.simulatorManifestUrl,simulatorSkillUrl:i.simulatorSkillUrl}).mcpEndpoint),simulatorManifestUrl:lO(t.simulatorManifestUrl),simulatorSkillUrl:lO(t.simulatorSkillUrl)};return{...o.simulatorManifestUrl?{simulatorManifest:(r=o.simulatorManifestUrl,a=i.onTraceEvent,async()=>{let e;lq(a,"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 lF("manifest",r,e);let t=await e.text(),n=function(e){let t=(0,lD.qg)(e);if(!eH(t))throw Error("Simulator manifest must be a YAML object");return t}(t);return l$(a,"manifest",r,e,{bytes:t.length}),{...n,raw_manifest_yaml:t}}catch(t){throw lB(a,"manifest",r,t,e),console.warn("[web-sdk-debugger] Failed to load simulator manifest supplement",t),t}})}:{},...o.simulatorSkillUrl?{skill:(n=o.simulatorSkillUrl,s=i.onTraceEvent,async()=>{let e;lq(s,"skill",n);try{var t;if(!(e=await fetch(n,{cache:"no-store",headers:{Accept:"text/markdown, text/plain"}})).ok)throw lF("skill",n,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 (${n})`);return l$(s,"skill",n,e,{bytes:r.length}),r}catch(t){throw lB(s,"skill",n,t,e),console.warn("[web-sdk-debugger] Failed to load simulator skill",t),t}})}:{},...o.mcpEndpoint?function(e){let t=ek(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 a=>{let n;try{np(e.onTraceEvent,{event:"local_mcp_tools_load_started",app_key:a.appKey,mcp_endpoint:t,server_id:r},a),n=await nh(t,e);let s=await n.client.listTools(),i=n.client.getServerVersion(),o={server_id:r,name:(null==i?void 0:i.name)||r,description:n.client.getInstructions()||"",tools:s.tools.map(nm).filter(e=>e.name)};return np(e.onTraceEvent,{event:"local_mcp_tools_loaded",app_key:a.appKey,mcp_endpoint:t,server_id:o.server_id,server_version:i,tools:o.tools.map(e=>e.name)},a),[o]}catch(n){return np(e.onTraceEvent,{event:"local_mcp_tools_load_failed",app_key:a.appKey,mcp_endpoint:t,server_id:r,error:eJ(n),request_will_continue:!0,tool_count:0,tools:[]},a),console.warn("[web-sdk-debugger] Failed to load MCP tools",n),[]}finally{n&&await ng(n)}},toolExecutor:async r=>{var a,n,s,i;let o,l=r.arguments??eV(r.argumentsJson)??{},d=r.argumentsJson||eK(l),u=Date.now();try{let c,p,m,h,g,f;if(np(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 nh(t,{...e,headers:function(e,t){if(!e&&!t)return;let r=new Headers(e);for(let[e,a]of Object.entries(t??{}))r.set(e,a);return r}(e.headers,r.headers)}),null==(a=r.signal)?void 0:a.aborted)throw n="MCP tool call aborted","u">typeof DOMException?new DOMException(n,"AbortError"):Object.assign(Error(n),{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=eH(s)?s:{}).structuredContent,eH(c)?c:{value:c??{}}),h=eK(p),g=(i=p,"string"==typeof i.content?i.content:Array.isArray(i.content)&&i.content.filter(eH).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=eV(v.raw_mcp_result_json);return np(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:eK(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(n){if(tD(n))throw n;let a=eJ(n);return np(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:a,elapsed_ms:Date.now()-u,mcp_endpoint:t}),{status:"failed",result:{error:a},error:{code:"LOCAL_MCP_CALL_FAILED",message:a,retryable:!0,stage:"tool_execute"},raw_result_text:a}}finally{o&&await ng(o)}}}}({endpoint:o.mcpEndpoint,onTraceEvent:i.onTraceEvent}):{}}})(t,{onTraceEvent:e=>{var t;return null==(t=y.current)?void 0:t.appendSimulatorTraceEvent(e)},simulatorManifestUrl:a,simulatorSkillUrl:i}),[t,a,i]),b=(0,eB.useMemo)(()=>{let t=p?{appKey:lH,appName:"调试示例智能服务",mcpServers:lG,simulatorFetch:function(e){let{getDebuggerState:t}=e;return async(e,r)=>{var a,n,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=(a="string"!=typeof(null==r?void 0:r.body)?{}:JSON.parse(r.body),i=t(),p=((c=new URL(window.location.href).searchParams.get("simulatorMockWidget"))?lJ(i,[c]):void 0)||lJ(i,lV)||(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==(n=a.message)?void 0:n.content)||"模拟请求",f=`call_mock_${m}`,v={applet_id:a.app_id||lH,widget_id:p,entity_id:"mock-entity-1",viewData:{source:"web-sdk-debugger-mock",keyword:g,widgetId:p},extra:{"doubao/outputTemplate":"mock.output.template"}},[lX(a,"ack",{ack:{request_id:h.requestId,message_id:h.replyMessageId,local_message_id:null==(s=a.message)?void 0:s.local_message_id}},h),lX(a,"tool_call",{tool_call:{tool_call_id:f,tool_name:lz,server_id:lW,app_key:a.app_id||lH,arguments_json:JSON.stringify({keyword:g}),status:"PENDING",timeout_ms:2e3}},h),lX(a,"tool_status",{tool_status:{tool_call_id:f,status:"RUNNING",progress:.6,message:"Mock tool running"}},h),lX(a,"text_delta",{text_delta:{block_id:"block_mock_text",op:"append",delta:`Mock 已收到:${g}`}},h),lX(a,"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),lX(a,"debug",{debug_event:{category:"mock",title:"Mock Simulator",summary:"本地 mock SSE 已生成 text/card/tool 事件",data:{widget_id:p},redaction_level:"none"}},h),lX(a,"answer_finish",{answer_finish:{status:"completed",finish_reason:"stop",usage:{output_tokens:12}}},h),lX(a,"reply_finish",{reply_finish:{status:"completed",finish_reason:"stop",event_count:7}},h)]).map(lK).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=y.current)?void 0:e.getState())??null}}),toolExecutor:lQ}:{},r=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new t1(e)}({manifestUrl:e,simulatorEndpoint:l,..._,...t});return y.current=r,r},[e,l,_,p]),[w,S]=(0,eB.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"}),x=sX(e=>{v(e),("render_page"===e.type||"render_widget"===e.type)&&S("render_page"===e.type?"page":"card")}),I=sX((e,t)=>{e2({clientId:g,commandId:e,...t},e1).catch(e=>console.error(e)).finally(()=>{v(t=>(null==t?void 0:t.commandId)===e?void 0:t)})}),C=sX(e=>{try{var t;null==(t=y.current)||t.navigateToPage(e.url)}catch{}S("page")});(0,eB.useEffect)(()=>(function(e){let{clientId:t,endpoint:r="/__wsd_control_events",onCommand:a}=e;if("u"<typeof EventSource)return()=>void 0;let n=new URL(r,window.location.href);n.searchParams.set("clientId",t);let s=new EventSource(n.toString());return s.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}let r=function(e){if(!eH(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&&eH(e.structuredContent))return{commandId:e.commandId,type:e.type,widgetId:e.widgetId,structuredContent:e.structuredContent};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 null}(t);r&&a(r)},()=>s.close()})({clientId:g,onCommand:x}),[g,x]),(0,eB.useEffect)(()=>{let t=!1;return b.loadManifest(e).then(()=>{if(!t){let t;return t=new URL(window.location.href),e===e3?t.searchParams.delete("manifest"):t.searchParams.set("manifest",e),window.history.replaceState(null,"",t),l2(b,_)}}).catch(()=>{}),()=>{t=!0,b.destroy(),y.current===b&&(y.current=null)}},[e,_,b]),(0,eB.useEffect)(()=>{let e=!1;return l1().then(t=>{e||h(t)}),()=>{e=!0}},[]);let E=(0,eB.useMemo)(()=>({launchDir:d,mcpEndpoint:t,mcpOriginalEndpoint:r,mcpProxyEndpoint:t,simulatorManifestOriginalUrl:n,simulatorManifestProxyUrl:a,simulatorManifestUrl:a,simulatorSkillOriginalUrl:o,simulatorSkillProxyUrl:i,simulatorSkillUrl:i,webUrl:u,...m}),[d,t,r,n,a,o,i,u,m]);return(0,s.jsx)(e$.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)(lj,{activeView:w,apiEnvironment:lY,chromeDevToolsFrontendUrl:"/chrome-devtools/inspector.html",controlCommand:f,controlClientId:g,debugContext:E,onActiveViewChange:S,onControlResult:I,onNavigateToPage:C,showDebugTrace:c,traceSnapshotEndpoint:"/__agent_trace",webSdkDebugger:b})})})})})}ee=e=>({url:`/__web_view_proxy__?url=${encodeURIComponent(e)}`});let l5=document.querySelector("#app");if(!l5)throw Error("Cannot find #app");(0,eq.H)(l5).render((0,s.jsx)(function(){return window.location.pathname.startsWith("/chrome-devtools/")?(0,s.jsx)(l3,{}):(0,s.jsx)(l4,{})},{}))}},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__",a=e?Symbol("rspack error"):"__rspack_error",n=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[n]}))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 n=h.zT(e[s]);if(!n)return e;var o=e;e={then(e,t){n.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[a]=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 n,o=()=>u.map(e=>{if(e[s])return e;if(e[a])throw e[a];return e[r]}),l=new Promise(e=>{(n=()=>e(o)).r=0;var r=e=>e!==d&&!m.has(e)&&(m.add(e),e&&!e.d&&(n.r++,e.push(n)));u.map(e=>e[s]||e[t](r))});return n.r?l:o()},e=>(e?p(f[a]=e):c(g),i(d),f[n]=!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 a=(t,r)=>{for(var a in t)h.o(t,a)&&!h.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,[r]:t[a]})};a(t,"get"),a(r,"value")},h.f={},h.e=(e,t)=>Promise.all(Object.keys(h.f).reduce((r,a)=>(h.f[a](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:"3d062fe593",350:"262e55a7be",503:"3c0bb1c897",724:"c806dbd80d",778:"7d93b838a6",894:"0d6f19dfb8",97:"f4b147aa28"})[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,a,n){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),n&&s.setAttribute("fetchpriority",n),s.src=e),o[e]=[t];var c=function(t,r){s.onerror=s.onload=null,clearTimeout(p);var a=o[e];if(delete o[e],s.parentNode&&s.parentNode.removeChild(s),a&&a.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,a)=>{if(t){a=a||0;for(var n=l.length;n>0&&l[n-1][2]>a;n--)l[n]=l[n-1];l[n]=[t,r,a];return}for(var s=1/0,n=0;n<l.length;n++){for(var[t,r,a]=l[n],i=!0,o=0;o<t.length;o++)(!1&a||s>=a)&&Object.keys(h.O).every(e=>h.O[e](t[o]))?t.splice(o--,1):(i=!1,a<s&&(s=a));if(i){l.splice(n--,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 a=h.o(d,e)?d[e]:void 0;if(0!==a)if(a)t.push(a[2]);else{var n=new Promise((t,r)=>a=d[e]=[t,r]);t.push(a[2]=n);var s=h.p+h.u(e),i=Error();h.l(s,function(t){if(h.o(d,e)&&(0!==(a=d[e])&&(d[e]=void 0),a)){var r=t&&("load"===t.type?"missing":t.type),n=t&&t.target&&t.target.src;i.message="Loading chunk "+e+" failed.\n("+r+": "+n+")",i.name="ChunkLoadError",i.type=r,i.request=n,a[1](i)}},"chunk-"+e,e,r)}},h.O.j=e=>0===d[e],u=(e,t)=>{var r,a,[n,s,i]=t,o=0;if(n.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<n.length;o++)a=n[o],h.o(d,a)&&d[a]&&d[a][0](),d[a]=0;return h.O(l)},(c=globalThis.rspackChunk_byted_doubao_apps_web_sdk_debugger_app=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","170","16"],()=>h(39259));g=h.O(g)})();