@doubao-dev/cli 0.0.34 → 0.0.36

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 (142) hide show
  1. package/dist/1232.js +1 -0
  2. package/dist/1264.js +1 -0
  3. package/dist/1611.js +2 -0
  4. package/dist/2232.js +60 -0
  5. package/dist/2507.js +1 -0
  6. package/dist/275.js +5 -8
  7. package/dist/2932.js +1 -1
  8. package/dist/4525.js +1 -1
  9. package/dist/4880.js +1 -1
  10. package/dist/4931.js +1 -1
  11. package/dist/{3688.js → 5887.js} +3 -3
  12. package/dist/6438.js +140 -0
  13. package/dist/6976.js +280 -0
  14. package/dist/{8981.js.LICENSE.txt → 6976.js.LICENSE.txt} +108 -0
  15. package/dist/7410.js +1 -2
  16. package/dist/@byted-doubao-apps/create.js +1 -1
  17. package/dist/@byted-doubao-apps/kit.js +1 -1
  18. package/dist/@byted-doubao-apps/login.js +2 -2
  19. package/dist/@byted-doubao-apps/login~1.js +2 -2
  20. package/dist/@byted-doubao-apps/template-empty/package.json +3 -3
  21. package/dist/@byted-doubao-apps/template-starter/package.json +3 -3
  22. package/dist/@byted-hdt/cli.js +1 -1
  23. package/dist/@inquirer/select.js +1 -1
  24. package/dist/{assets/web-sdk-debugger/static/wasm/eaf690f2cd.module.wasm → @lynx-js/static/wasm/77fb77f77f.module.wasm} +0 -0
  25. package/dist/@lynx-js/{web-core-canary.js → web-core.js} +2 -2
  26. package/dist/app.js +1 -1
  27. package/dist/assets/web-sdk-debugger/__doubao_web_sdk_native_modules/applet-bridge-module-core.js +1 -1
  28. package/dist/assets/web-sdk-debugger/index.html +1 -1
  29. package/dist/assets/web-sdk-debugger/preact-devtools/index.js +4 -1
  30. package/dist/assets/web-sdk-debugger/static/css/index.ef5d8bc5ad.css +1 -0
  31. package/dist/assets/web-sdk-debugger/static/js/{682.de47e82f6b.js → 426.53c43a8594.js} +2 -2
  32. package/dist/assets/web-sdk-debugger/static/js/479.26e0b1d922.js +1829 -0
  33. package/dist/assets/web-sdk-debugger/static/js/async/503.259fed5610.js +1 -0
  34. package/dist/assets/web-sdk-debugger/static/js/async/{legacy-wasm-js.bacc8b5564.js → legacy-wasm-js.9b9367f818.js} +2 -2
  35. package/dist/assets/web-sdk-debugger/static/js/async/lynx-core-chunk.7f5e94dfae.js +5 -0
  36. package/dist/assets/web-sdk-debugger/static/js/async/web-core-main-chunk.f78260697f.js +1 -0
  37. package/dist/assets/web-sdk-debugger/static/js/async/web-core-markup-encoder.33c43c480e.js +4 -0
  38. package/dist/assets/web-sdk-debugger/static/js/async/web-core-template-loader-thread.ba290b32d7.js +4 -0
  39. package/dist/assets/web-sdk-debugger/static/js/async/web-core-worker-chunk.9a5989b104.js +1 -0
  40. package/dist/assets/web-sdk-debugger/static/js/async/web-elements.3fbd53918e.js +365 -0
  41. package/dist/assets/web-sdk-debugger/static/js/async/xmarkdown-deps.efd0ffb051.js +5 -0
  42. package/dist/assets/web-sdk-debugger/static/js/async/{xmarkdown-deps.3ea5672b2c.js.LICENSE.txt → xmarkdown-deps.efd0ffb051.js.LICENSE.txt} +1 -1
  43. package/dist/assets/web-sdk-debugger/static/js/index.b6e5c76345.js +44 -0
  44. package/dist/assets/web-sdk-debugger/static/js/lib-polyfill.c91181f230.js +1 -0
  45. package/dist/assets/web-sdk-debugger/static/wasm/{69a8ba8eb9.module.wasm → 4c402c7981.module.wasm} +0 -0
  46. package/dist/assets/web-sdk-debugger/static/wasm/{03b02f9e5a.module.wasm → 72aaf7d0aa.module.wasm} +0 -0
  47. package/dist/{@lynx-js/static/wasm/eaf690f2cd.module.wasm → assets/web-sdk-debugger/static/wasm/77fb77f77f.module.wasm} +0 -0
  48. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-api.template.js +0 -0
  49. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-framework.template.js +0 -0
  50. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-react-dev.template.js +0 -0
  51. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-react.template.js +0 -0
  52. package/dist/browser.js +1 -1
  53. package/dist/build.js +1 -1
  54. package/dist/build~1.js +10 -10
  55. package/dist/check.js +1 -1
  56. package/dist/client.js +1 -0
  57. package/dist/client~1.js +1 -0
  58. package/dist/components-loader.js +1 -1
  59. package/dist/demo-server.js +2 -2
  60. package/dist/demo.js +2 -2
  61. package/dist/dev-config.js +2 -2
  62. package/dist/dev-shell.js +1 -1
  63. package/dist/dev.js +19 -16
  64. package/dist/explore.js +10 -0
  65. package/dist/gen-explore.js +1 -1
  66. package/dist/gen-trajectory.js +1 -1
  67. package/dist/info.js +2 -2
  68. package/dist/init.js +4 -4
  69. package/dist/ink.js +1 -1
  70. package/dist/inquirer.js +1 -1
  71. package/dist/json-file.js +2 -2
  72. package/dist/legacy-status.js +1 -1
  73. package/dist/legacy-upload.js +1 -1
  74. package/dist/lepus.js +1 -1
  75. package/dist/login.js +2 -1
  76. package/dist/main.js +1 -1
  77. package/dist/{manifest-mcp-config.js → manifest-headers.js} +1 -1
  78. package/dist/ora.js +1 -1
  79. package/dist/portal.js +1 -1
  80. package/dist/project-layout.js +1 -1
  81. package/dist/project.js +1 -1
  82. package/dist/prompt.js +8 -8
  83. package/dist/prompts.js +1 -1
  84. package/dist/qrcode.js +1 -0
  85. package/dist/report.js +1 -1
  86. package/dist/run-registry.js +1 -1
  87. package/dist/run.js +321 -321
  88. package/dist/sandbox.js +1 -1
  89. package/dist/scan.js +1 -1
  90. package/dist/sdk.js +192 -59
  91. package/dist/sdk~1.js +66 -58
  92. package/dist/server.js +10 -10
  93. package/dist/skill.js +1 -1
  94. package/dist/skills.js +1 -1
  95. package/dist/skills~1.js +1 -1
  96. package/dist/status.js +1 -1
  97. package/dist/status~1.js +2 -2
  98. package/dist/stop.js +1 -1
  99. package/dist/sync.js +1 -1
  100. package/dist/trajectory.js +3 -0
  101. package/dist/update.js +1 -1
  102. package/dist/upgrade.js +1 -1
  103. package/dist/workspace.js +1 -1
  104. package/dist/yaml.js +1 -1
  105. package/package.json +7 -7
  106. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/02-/347/263/273/347/273/237.md +2 -2
  107. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/06-/350/267/257/347/224/261.md +4 -0
  108. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/07-/347/225/214/351/235/242.md +8 -0
  109. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/26-/345/237/272/347/241/200/344/277/241/346/201/257.md +2 -1
  110. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/33-/345/261/217/345/271/225.md +124 -8
  111. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/groups.md +1 -1
  112. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/quick-reference.md +2 -1
  113. package/skills/doubao-agentic-service-development/references/frontend/examples/page-widget-basics.md +1 -0
  114. package/skills/doubao-agentic-service-development/references/frontend/guides/client-tools-and-events.md +209 -0
  115. package/skills/doubao-agentic-service-development/references/frontend/guides/component-development.md +7 -1
  116. package/skills/doubao-agentic-service-development/references/frontend/guides/debugger-mcp.md +1 -1
  117. package/skills/doubao-agentic-service-development/references/frontend/widget-templates/overview.md +13 -9
  118. package/skills/doubao-agentic-service-development/references/frontend/widget-templates/props.md +26 -1
  119. package/skills/doubao-agentic-service-development/references/frontend-dev.md +2 -0
  120. package/dist/2168.js +0 -60
  121. package/dist/318.js +0 -1
  122. package/dist/3974.js +0 -151
  123. package/dist/6427.js +0 -126
  124. package/dist/7417.js +0 -204
  125. package/dist/7417.js.LICENSE.txt +0 -107
  126. package/dist/7945.js +0 -1
  127. package/dist/8981.js +0 -78
  128. package/dist/assets/web-sdk-debugger/static/css/index.7c65607402.css +0 -1
  129. package/dist/assets/web-sdk-debugger/static/js/670.8a8f0f7d57.js +0 -1829
  130. package/dist/assets/web-sdk-debugger/static/js/async/503.cf61731bba.js +0 -1
  131. package/dist/assets/web-sdk-debugger/static/js/async/lynx-core-chunk.afc1ded023.js +0 -5
  132. package/dist/assets/web-sdk-debugger/static/js/async/web-core-main-chunk.7fe9af852c.js +0 -1
  133. package/dist/assets/web-sdk-debugger/static/js/async/web-core-markup-encoder.f81d6d2cae.js +0 -4
  134. package/dist/assets/web-sdk-debugger/static/js/async/web-core-template-loader-thread.4a49f8a286.js +0 -4
  135. package/dist/assets/web-sdk-debugger/static/js/async/web-core-worker-chunk.c315fd6753.js +0 -1
  136. package/dist/assets/web-sdk-debugger/static/js/async/web-elements.43d1e29387.js +0 -365
  137. package/dist/assets/web-sdk-debugger/static/js/async/xmarkdown-deps.3ea5672b2c.js +0 -5
  138. package/dist/assets/web-sdk-debugger/static/js/index.9f626ba3a2.js +0 -44
  139. package/dist/assets/web-sdk-debugger/static/js/lib-polyfill.9daa7c863e.js +0 -1
  140. package/dist/simulator-client.js +0 -1
  141. /package/dist/{7410.js.LICENSE.txt → 1611.js.LICENSE.txt} +0 -0
  142. /package/dist/assets/web-sdk-debugger/static/js/{670.8a8f0f7d57.js.LICENSE.txt → 479.26e0b1d922.js.LICENSE.txt} +0 -0
package/dist/sdk~1.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*! LICENSE: sdk~1.js.LICENSE.txt */
2
- let e,t,r,n,i,o,a;import"node:module";import{LAYERS as s,pluginReactLynx as l}from"@lynx-js/react-rsbuild-plugin";import{createRspeedy as d,mergeRspeedyConfig as p,rspack as c}from"@lynx-js/rspeedy";import{pluginLess as u}from"@rsbuild/plugin-less";import{pluginSass as h}from"@rsbuild/plugin-sass";import m from"tinypool";import{__webpack_require__ as f}from"./rslib-runtime.js";import{external_node_stream_promises_namespaceObject as g,core_namespaceObject as y,external_node_tty_namespaceObject as b,external_node_https_namespaceObject as _,external_node_timers_promises_namespaceObject as v,external_jiti_namespaceObject as w,external_node_process_namespaceObject as S,external_better_opn_namespaceObject as E,promises_namespaceObject as x}from"./7945.js";import{external_node_module_namespaceObject as A}from"./3551.js";import{schemas_number as T,schemas_enum as C,McpServer as I,unknown as O,dist_esm as P,schemas_string as k,schemas_object as D,createMcpHandler as $,pluginReactAlias as R,schemas_boolean as N,toNodeHandler as L,lodash_es_get as M,lodash_es_merge as j,schemas_array as U,record as B,getWebSdkDebuggerDistPath as F,eraseLines as W,lodash_es_mergeWith as H,pluginExternalBundle as V}from"./7417.js";import{parseDebugScene as G,APP_DEVELOPER_DOMAIN as q,getDebugSceneVariableEntries as J,TokenExpiredError as K,AUTH_META as z,normalizeWidgetSourceEntry as Y,resolveDebugScene as X,execaCommand as Z,APP_DEVELOPER_ORIGIN as Q,prepareCloudBuildSource as ee,normalizeHttpEndpoint as et,withAuth as er,RenderType as en,TitleType as ei,NotLoggedInError as eo,BoxType as ea,parseSandboxSimulatorToolCallEvent as es,isRecord as el}from"./8981.js";import{walk_simple as ed}from"./7526.js";import"./4525.js";import"./yaml.js";import"./ora.js";import{source as ep,TeaUploader as ec}from"./3688.js";import eu from"./inquirer.js";import{wrapper as eh}from"./wrapper.js";import{create as em}from"./@byted-doubao-apps/create.js";f.add({"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-bootstrap.js"(e,t,r){e.exports=r.p+"static/assets/web-view-proxy-bootstrap.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"(e,t,r){e.exports=r.p+"static/assets/web-view-proxy-page-client.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"(e,t,r){e.exports=r.p+"static/assets/web-view-proxy-service-worker.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.3.0-rc.3_@lynx-js+types@4.1.0_@pnpm+logger@1001.0.1_@swc+helpe_1a6b167d04325d26c47447895a884d09/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"(e,t,r){e.exports=r.p+"static/assets/encode-worker.js"}});let ef=f("node:async_hooks"),eg=Math.max(...["cli","auth","config","security","build","deploy","dev-server","simulator"].map(e=>`[${e}]`.length)),ey=/authorization|cookie|token|secret|password|credential|private_?key|\bdek\b/i,eb=new ef.AsyncLocalStorage;function e_(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function ev(e,t=new WeakSet){if(null==e)return String(e);if("string"==typeof e)return/^[\w./:@-]+$/.test(e)&&e.length>0?e:JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(e instanceof Error)return ev(e.message,t);if("object"!=typeof e)return String(e);if(t.has(e))return'"[Circular]"';t.add(e);let r=Array.isArray(e)?`[${e.map(e=>ev(e,t)).join(",")}]`:`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,r])=>{let n=ey.test(e_(e))?'"[REDACTED]"':ev(r,t);return`${JSON.stringify(e)}:${n}`}).join(",")}}`;return t.delete(e),r}function ew(e){return ep.cyan(`[${e}]`.padEnd(eg))}function eS(e={}){let t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),r=t["x-tt-env"],n=t["x-use-ppe"],i=Array.isArray(r)?r.join(","):r;return n&&i?String(i):void 0}function eE(e){let t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e_(e),t]).sort(([e],[t])=>e.localeCompare(t));return 0===t.length?"":t.map(([e,t])=>{let r=ey.test(e)?"[REDACTED]":ev(t);return ep.dim(`${e}=${r}`)}).join(" ")}let ex=new class e{constructor(e={}){this.sink=e.sink??y.logger,this.tag=e.tag,this.context=e.context??{},this.isDebugEnabled=e.isDebug??(()=>"applet0930"===process.env.DEBUG)}child(t,r={}){return new e({sink:this.sink,tag:t,context:{...this.context,...r},isDebug:this.isDebugEnabled})}withContext(t){return new e({sink:this.sink,tag:this.tag,context:{...this.context,...t},isDebug:this.isDebugEnabled})}info(e,t){this.emit("info",e,t)&&this.sink.info(this.formatMessage(e,t))}success(e,t){this.emit("info",e,t)&&this.sink.success(this.formatMessage(e,t))}start(e,t){this.emit("info",e,t)&&this.sink.start(this.formatMessage(e,t))}ready(e,t){this.emit("info",e,t)&&this.sink.ready(this.formatMessage(e,t))}warn(e,t){this.emit("warn",e,t)&&this.sink.warn(this.formatMessage(e,t))}debug(e,t){this.isDebugEnabled()&&this.emit("debug",e,t)&&this.sink.debug(this.formatMessage(e,t))}error(e,t={}){let r,{error:n,...i}=t,o=this.tag?`${ew(this.tag)} `:"",a=e instanceof Error?e.message:String(e),s=`${o}${a}`;if(void 0!==n)s+=`: ${n instanceof Error?n.message:ev(n)}`,this.isDebugEnabled()&&n instanceof Error&&n.stack&&(r=n.stack);else e instanceof Error&&this.isDebugEnabled()&&e.stack&&(r=e.stack);let l=eE({...this.context,...i});l&&(s+=` ${l}`),r&&(s+=`
3
- ${r}`),this.emit("error",a,{...i,...void 0!==n?{error:n}:{}})&&this.sink.error(s)}greet(e){this.emit("info",e)&&this.sink.greet(e)}request(e){var t;let r,n,i,o,a,s,l,d=e.timestamp??new Date,p=ep.gray(`[${(r=d.getFullYear(),n=String(d.getMonth()+1).padStart(2,"0"),i=String(d.getDate()).padStart(2,"0"),o=String(d.getHours()).padStart(2,"0"),a=String(d.getMinutes()).padStart(2,"0"),s=String(d.getSeconds()).padStart(2,"0"),l=String(d.getMilliseconds()).padStart(3,"0"),`${r}-${n}-${i} ${o}:${a}:${s}.${l}`)}]`),c=ep.bold(e.method),u=void 0===e.durationMs?"":` ${ep.dim(`${e.durationMs.toFixed(1)}ms`)}`,h=eS(e.headers),m=Array.isArray(e.logId)?e.logId.join(","):e.logId,f=[h?eE({ppe:h}):"",m?eE({logid:m}):"",eE({...this.context,...e.context})].filter(Boolean).join(" "),g=`${this.tag?`${ew(this.tag)} `:""}${p} ${c} ${e.url} ${((t=e.statusCode)>=500?ep.red:t>=400?ep.yellow:ep.green)(String(t))}${u}${f?` ${f}`:""}`,y=e.statusCode>=500?"error":e.statusCode>=400?"warn":"info";this.emit(y,`${e.method} ${e.url} ${e.statusCode}`,{...e.context,durationMs:e.durationMs,logId:m,ppe:h},d.getTime())&&("error"===y?this.sink.error(g):"warn"===y?this.sink.warn(g):this.sink.info(g))}formatMessage(e,t={}){let r=eE({...this.context,...t}),n=this.tag?`${ew(this.tag)} `:"",i=e instanceof Error?e.message:String(e);return`${n}${i}${r?` ${r}`:""}`}emit(e,t,r={},n=Date.now()){let i=eb.getStore(),o=i?.onLog;if(o)try{o({timestamp:n,level:e,scope:this.tag,message:t instanceof Error?t.message:String(t),context:function(e){let t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e_(e),t]).sort(([e],[t])=>e.localeCompare(t));if(0!==t.length)return Object.fromEntries(t.map(([e,t])=>[e,ey.test(e)?"[REDACTED]":function e(t,r=new WeakSet){if(t instanceof Error)return t.message;if(null===t||"object"!=typeof t)return"bigint"==typeof t?String(t):t;if(r.has(t))return"[Circular]";r.add(t);let n=Array.isArray(t)?t.map(t=>e(t,r)):Object.fromEntries(Object.entries(t).map(([t,n])=>[t,ey.test(e_(t))?"[REDACTED]":e(n,r)]));return r.delete(t),n}(t)]))}({...this.context,...r})})}catch{}return i?.printLogs!==!1}},eA=ex.child("build");var eT,eC,eI,eO,eP,ek,eD,e$,eR,eN,eL,eM,ej,eU,eB,eF,eW,eH,eV,eG,eq,eJ,eK,ez=((eM={}).Adb="adb",eM.Hdt="hdt",eM.DevTools="devtools",eM);let eY=["adb","hdt","devtools"],eX=f("path"),eZ="./node_modules/.doubao",eQ="./node_modules/.injected.js",e0="./node_modules/.injected.css",e1=`.doubao-apps-style-anchor{display:none}
2
+ let e,t,r,n,i,s,o;import"node:module";import{LAYERS as a,pluginReactLynx as l}from"@lynx-js/react-rsbuild-plugin";import{createRspeedy as c,mergeRspeedyConfig as p,rspack as d}from"@lynx-js/rspeedy";import{pluginLess as u}from"@rsbuild/plugin-less";import{pluginSass as m}from"@rsbuild/plugin-sass";import h from"tinypool";import{__webpack_require__ as f}from"./rslib-runtime.js";import{external_node_stream_promises_namespaceObject as g,core_namespaceObject as y,external_node_tty_namespaceObject as b,external_node_https_namespaceObject as _,external_node_timers_promises_namespaceObject as v,external_jiti_namespaceObject as E,external_node_process_namespaceObject as w,external_better_opn_namespaceObject as S,promises_namespaceObject as x}from"./1264.js";import{external_node_module_namespaceObject as A}from"./3551.js";import{parseDebugScene as T,schemas_enum as I,schemas_number as O,unknown as P,TokenExpiredError as C,AUTH_META as R,normalizeWidgetSourceEntry as $,resolveDebugScene as k,schemas_object as N,createMcpHandler as L,prepareCloudBuildSource as D,withAuth as j,ExternalsLoadingPlugin as M,schemas_boolean as U,lodash_es_get as B,TitleType as F,RenderType as H,schemas_record as W,getWebSdkDebuggerDistPath as G,eraseLines as V,NotLoggedInError as q,parseSandboxSimulatorToolCallEvent as J,lodash_es_mergeWith as z,isRecord as K,getDebugSceneVariableEntries as Y,McpServer as X,dist_esm as Z,schemas_string as Q,APP_DEVELOPER_ORIGIN as ee,execaCommand as et,normalizeHttpEndpoint as er,toNodeHandler as en,schemas_array as ei,lodash_es_merge as es,BoxType as eo,APP_DEVELOPER_DOMAIN as ea}from"./6976.js";import{walk_simple as el}from"./7526.js";import"./4525.js";import"./yaml.js";import{source as ec,TeaUploader as ep}from"./5887.js";import ed from"./inquirer.js";import{wrapper as eu}from"./wrapper.js";import{create as em}from"./@byted-doubao-apps/create.js";f.add({"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_tslib@2.8.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-bootstrap.js"(e,t,r){e.exports=r.p+"static/assets/web-view-proxy-bootstrap.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_tslib@2.8.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"(e,t,r){e.exports=r.p+"static/assets/web-view-proxy-page-client.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_tslib@2.8.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"(e,t,r){e.exports=r.p+"static/assets/web-view-proxy-service-worker.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.5.0-rc.3_@lynx-js+types@4.1.0_@pnpm+logger@1001.0.1_@swc+helpe_0e0a52a284c18388b1ab9c5a0abf4e84/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"(e,t,r){e.exports=r.p+"static/assets/encode-worker.js"}});let eh=f("node:async_hooks"),ef=Math.max(...["cli","auth","config","security","build","deploy","dev-server","simulator"].map(e=>`[${e}]`.length)),eg=/authorization|cookie|token|secret|password|credential|private_?key|\bdek\b/i,ey=new eh.AsyncLocalStorage;function eb(){return(process.env.DEBUG??"").toLocaleLowerCase().split(",").includes("applet0930")}function e_(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function ev(e,t=new WeakSet){if(null==e)return String(e);if("string"==typeof e)return/^[\w./:@-]+$/.test(e)&&e.length>0?e:JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(e instanceof Error)return ev(e.message,t);if("object"!=typeof e)return String(e);if(t.has(e))return'"[Circular]"';t.add(e);let r=Array.isArray(e)?`[${e.map(e=>ev(e,t)).join(",")}]`:`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,r])=>{let n=eg.test(e_(e))?'"[REDACTED]"':ev(r,t);return`${JSON.stringify(e)}:${n}`}).join(",")}}`;return t.delete(e),r}function eE(e){return ec.cyan(`[${e}]`.padEnd(ef))}function ew(e={}){let t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),r=t["x-tt-env"],n=t["x-use-ppe"],i=Array.isArray(r)?r.join(","):r;return n&&i?String(i):void 0}function eS(e){let t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e_(e),t]).sort(([e],[t])=>e.localeCompare(t));return 0===t.length?"":t.map(([e,t])=>{let r=eg.test(e)?"[REDACTED]":ev(t);return ec.dim(`${e}=${r}`)}).join(" ")}let ex=new class e{constructor(e={}){this.sink=e.sink??y.logger,this.tag=e.tag,this.context=e.context??{},this.isDebugEnabled=e.isDebug??eb}child(t,r={}){return new e({sink:this.sink,tag:t,context:{...this.context,...r},isDebug:this.isDebugEnabled})}withContext(t){return new e({sink:this.sink,tag:this.tag,context:{...this.context,...t},isDebug:this.isDebugEnabled})}info(e,t){this.emit("info",e,t)&&this.sink.info(this.formatMessage(e,t))}success(e,t){this.emit("info",e,t)&&this.sink.success(this.formatMessage(e,t))}start(e,t){this.emit("info",e,t)&&this.sink.start(this.formatMessage(e,t))}ready(e,t){this.emit("info",e,t)&&this.sink.ready(this.formatMessage(e,t))}warn(e,t){this.emit("warn",e,t)&&this.sink.warn(this.formatMessage(e,t))}debug(e,t){if(this.isDebugEnabled()&&this.emit("debug",e,t)){let r=this.formatMessage(e,t);this.sink===y.logger?y.logger.log(r):this.sink.debug(r)}}error(e,t={}){let r,{error:n,...i}=t,s=this.tag?`${eE(this.tag)} `:"",o=e instanceof Error?e.message:String(e),a=`${s}${o}`;if(void 0!==n)a+=`: ${n instanceof Error?n.message:ev(n)}`,this.isDebugEnabled()&&n instanceof Error&&n.stack&&(r=n.stack);else e instanceof Error&&this.isDebugEnabled()&&e.stack&&(r=e.stack);let l=eS({...this.context,...i});l&&(a+=` ${l}`),r&&(a+=`
3
+ ${r}`),this.emit("error",o,{...i,...void 0!==n?{error:n}:{}})&&this.sink.error(a)}greet(e){this.emit("info",e)&&this.sink.greet(e)}request(e){var t;let r,n,i,s,o,a,l,c=e.timestamp??new Date,p=ec.gray(`[${(r=c.getFullYear(),n=String(c.getMonth()+1).padStart(2,"0"),i=String(c.getDate()).padStart(2,"0"),s=String(c.getHours()).padStart(2,"0"),o=String(c.getMinutes()).padStart(2,"0"),a=String(c.getSeconds()).padStart(2,"0"),l=String(c.getMilliseconds()).padStart(3,"0"),`${r}-${n}-${i} ${s}:${o}:${a}.${l}`)}]`),d=ec.bold(e.method),u=void 0===e.durationMs?"":` ${ec.dim(`${e.durationMs.toFixed(1)}ms`)}`,m=ew(e.headers),h=Array.isArray(e.logId)?e.logId.join(","):e.logId,f=[m?eS({ppe:m}):"",h?eS({logid:h}):"",eS({...this.context,...e.context})].filter(Boolean).join(" "),g=`${this.tag?`${eE(this.tag)} `:""}${p} ${d} ${e.url} ${((t=e.statusCode)>=500?ec.red:t>=400?ec.yellow:ec.green)(String(t))}${u}${f?` ${f}`:""}`,y=e.statusCode>=500?"error":e.statusCode>=400?"warn":"info";this.emit(y,`${e.method} ${e.url} ${e.statusCode}`,{...e.context,durationMs:e.durationMs,logId:h,ppe:m},c.getTime())&&("error"===y?this.sink.error(g):"warn"===y?this.sink.warn(g):this.sink.info(g))}formatMessage(e,t={}){let r=eS({...this.context,...t}),n=this.tag?`${eE(this.tag)} `:"",i=e instanceof Error?e.message:String(e);return`${n}${i}${r?` ${r}`:""}`}emit(e,t,r={},n=Date.now()){let i=ey.getStore(),s=i?.onLog;if(s)try{s({timestamp:n,level:e,scope:this.tag,message:t instanceof Error?t.message:String(t),context:function(e){let t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e_(e),t]).sort(([e],[t])=>e.localeCompare(t));if(0!==t.length)return Object.fromEntries(t.map(([e,t])=>[e,eg.test(e)?"[REDACTED]":function e(t,r=new WeakSet){if(t instanceof Error)return t.message;if(null===t||"object"!=typeof t)return"bigint"==typeof t?String(t):t;if(r.has(t))return"[Circular]";r.add(t);let n=Array.isArray(t)?t.map(t=>e(t,r)):Object.fromEntries(Object.entries(t).map(([t,n])=>[t,eg.test(e_(t))?"[REDACTED]":e(n,r)]));return r.delete(t),n}(t)]))}({...this.context,...r})})}catch{}return i?.printLogs!==!1}},eA=ex.child("build");var eT,eI,eO,eP,eC,eR,e$,ek,eN,eL,eD,ej,eM,eU,eB,eF,eH,eW,eG,eV=((eL={}).Adb="adb",eL.Hdt="hdt",eL.DevTools="devtools",eL);let eq=["adb","hdt","devtools"],eJ=f("path"),ez="./node_modules/.doubao",eK="./node_modules/.injected.js",eY="./node_modules/.injected.css",eX=`.doubao-apps-style-anchor{display:none}
4
4
  :root {
5
5
  --doubao-picker-view-height: 108px;
6
6
  --doubao-picker-view-indicator-radius: 12px;
@@ -124,7 +124,7 @@ ${r}`),this.emit("error",a,{...i,...void 0!==n?{error:n}:{}})&&this.sink.error(s
124
124
  line-height: var(--doubao-picker-view-item-line-height);
125
125
  font-weight: var(--doubao-picker-view-item-font-weight);
126
126
  color: var(--doubao-picker-view-item-selected-color);
127
- }`,e3="widgets";eX.sep;let e2=`base${eX.sep}manifest.json`,e4=`base${eX.sep}manifest.sign`,e5="mcp-privacy-login-card",e9="__doubao_apps__expired-widget",e8="bundle.keystore",e7={"@byted-lynx/react":"React","@lynx-js/react":"React","@lynx-js/react/internal":"ReactInternal","@lynx-js/react/jsx-dev-runtime":"ReactJSXDevRuntime","@lynx-js/react/jsx-runtime":"ReactJSXRuntime","@lynx-js/react/lepus/jsx-dev-runtime":"ReactJSXLepusDevRuntime","@lynx-js/react/lepus/jsx-runtime":"ReactJSXLepusRuntime","@lynx-js/react/experimental/lazy/import":"ReactLazyImport","@lynx-js/react/legacy-react-runtime":"ReactLegacyRuntime","@lynx-js/react/runtime-components":"ReactComponents","@lynx-js/react/worklet-runtime/bindings":"ReactWorkletRuntime","@lynx-js/react/debug":"ReactDebug",preact:"Preact",react:"React"},e6="client-tool",te=e=>e===e5||e===e9,tt="app.config",tr=[".js",".ts",".mjs"],tn="com.larus.nova";class ti{}let to=f("node:fs"),ta=f("node:path"),ts="@byted-doubao-apps/framework",tl="@doubao-dev/framework",td=[ts,tl];function tp(e){return`${e}/components`}function tc(e){let t=ta.resolve(e,"package.json");if(to.existsSync(t))try{let e=JSON.parse(to.readFileSync(t,"utf8")),r={...e.dependencies,...e.devDependencies,...e.peerDependencies};if(r[tl])return tl;if(r[ts])return ts}catch{}}function tu(e){return tc(e)??ts}let th=e=>void 0!==process.env[e],tm=()=>(process.env.DEBUG??"").toLocaleLowerCase().split(",").includes("applet0930"),tf=()=>th("DISABLE_EXTERNAL")||"1"===process.env.ENABLE_SELF_CONTAINED||th("LEGACY_FRAMEWORK"),tg=()=>th("DISABLE_APP_TEMPLATE_JS")||th("LEGACY_FRAMEWORK");function ty({mcpEndpoint:e}={}){let t=e?.trim();return t||(process.env.DOUBAO_SIMULATOR_MCP_ENDPOINT?.trim()??"")}function tb(e,t=3e3){return Z(e,{timeout:t}).catch(()=>({stdout:"",stderr:""}))}async function t_(e,t){return tb(`adb -s ${e} ${t}`)}async function tv(e){let t=(await tb(`adb -s ${e} shell dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity' | tail -n 1`)).stdout.match(/\su\d+\s+([^\s\/]+)\//);return t?.[1]}async function tw(e,t){let r=(await t_(e,`shell pidof ${t}`)).stdout.trim();return r?r.split(/\s+/)[0]:void 0}async function tS(e){let t=await tv(e);return(t===tn||"com.flow.aisdk.example"===t)&&(await tb(`adb -s ${e} shell am force-stop ${t}`),await tb(`adb -s ${e} shell monkey -p ${t} -c android.intent.category.LAUNCHER 1`),!0)}async function tE(){return(await tb("adb devices")).stdout.split("\n").slice(1).map(e=>e.split(" ")[0].trim()).filter(Boolean)}async function tx(){let e=await tE();if(e.length>1){let{device:t}=await eu.prompt([{type:"search",name:"device",message:"检测到多个设备,请选择用于调试的设备(可按设备 ID 搜索):",source:t=>e.filter(e=>e.toLowerCase().includes(t?.toLowerCase()??""))}]);return t}return e[0]}class tA extends ti{deviceId;latestLoadParams;lastAppProcessId;isWatchingAppProcess=!1;isAutoReloading=!1;constructor(e,t={}){if(super(),this.deviceId=e,t.skipForegroundAppWatch)return;let r=setInterval(()=>{this.watchAppProcess()},500);process.once("exit",()=>clearInterval(r))}async watchAppProcess(){if(!this.isWatchingAppProcess){this.isWatchingAppProcess=!0;try{let e=await tw(this.deviceId,tn);void 0!==this.lastAppProcessId&&void 0!==e&&this.lastAppProcessId!==e&&await this.reloadOnAppRestart(e),void 0!==e&&(this.lastAppProcessId=e)}finally{this.isWatchingAppProcess=!1}}}async reloadOnAppRestart(e){if(void 0!==this.latestLoadParams&&!this.isAutoReloading){this.isAutoReloading=!0;try{if(await new Promise(e=>setTimeout(e,5e3)),await tw(this.deviceId,tn)!==e)return;await this.load(this.latestLoadParams)}finally{this.isAutoReloading=!1}}}async load(e){this.latestLoadParams=e;let{appletUrl:t,appId:r,isSigned:n}=e,i=`shell am broadcast -a com.bytedance.applet.SET_APPLET_DEBUG_HOST --es appletName ${r} --es appletHost ${t} --es appletType 1 --es isSigned ${n}`;tm()&&console.log(ep.dim(`adb -s ${this.deviceId} ${i}`)),await t_(this.deviceId,i)}async openPage(e){let{appId:t,pageId:r,pageData:n,pageSettings:i,mode:o}=e,a=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageName ${r} --es appletPageData '${n}' --es appletPageSettings '${i}' --es mode '${o}'`;tm()&&console.log(ep.dim(`adb -s ${this.deviceId} ${a}`)),await t_(this.deviceId,a)}async openPageUrl(e){let{appId:t,url:r}=e,n=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageUrl '${r}'`;tm()&&console.log(ep.dim(`adb -s ${this.deviceId} ${n}`)),await t_(this.deviceId,n)}async pushWidget(e){let{appId:t,widgetId:r,widgetData:n,botId:i}=e,o=`shell am broadcast -a com.bytedance.applet.START_APPLET_WIDGET --es appletName ${t} --es widgetName ${r} --es widgetData '${n}' --es botId ${i||process.env.DEBUG_BOT_ID}`;tm()&&console.log(ep.dim(`adb -s ${this.deviceId} ${o}`)),await t_(this.deviceId,o)}async callTool(e){let{appId:t,toolId:r,toolData:n}=e,i=`shell am broadcast -a com.bytedance.applet.CALL_TOOL --es appletName ${t} --es toolName '${r}' --es toolData '${n}'`;tm()&&console.log(ep.dim(`adb -s ${this.deviceId} ${i}`)),await t_(this.deviceId,i)}}class tT extends ti{async load(e){}async openPage(e){}async openPageUrl(e){}async pushWidget(e){}async callTool(e){}}ex.child("cli");let tC=ex.child("config"),tI=ex.child("security"),tO=ex.child("build"),tP=tO.withContext({mode:"cloud"}),tk=ex.child("deploy"),tD=ex.child("dev-server");class t${options;currentUrl=null;debugDriver=null;appId=null;constructor(e){this.options=e}async start(e,t,r){if(null!==this.currentUrl){this.currentUrl=e,this.debugDriver?.getAllAppClients().forEach(e=>this.onConnect(e,r));return}this.currentUrl=e,this.appId=t;let{getDebugDriver:n,toolkitExecutor:i}=await import("./@byted-hdt/cli.js").then(f.bind(f,"../../../node_modules/.pnpm/@byted-hdt+cli@0.0.71_debug@4.4.3/node_modules/@byted-hdt/cli/dist/es/index.js"));await i({runType:"rspeedy",openWebview:this.options.devtool});let o=n();this.debugDriver=o,o.getAllAppClients().forEach(e=>this.onConnect(e,r)),o.on("app-client-connected",this.onConnect)}stop(){this.currentUrl=null,this.debugDriver?.off("app-client-connected",this.onConnect)}sendMessage(e){this.debugDriver?.getAllAppClients().forEach(t=>{try{t.sendCustomizedMessage(e.method,e.params,-1,"CDP")}catch(e){tD.error("向 HDT 客户端发送消息失败",{error:e})}})}onConnect=(e,t)=>{null!==this.currentUrl&&null!==this.debugDriver&&null!==this.appId&&this.sendMessage({method:"Applet_AppReload",params:{appletName:this.appId,appletHost:this.currentUrl,appletType:1,isSigned:t}})}}class tR extends ti{server;constructor(){super(),this.server=new t$({devtool:!0,open:!0})}async load(e){let{appletUrl:t,appId:r,isSigned:n}=e;this.server.start(t,r,n)}async openPage(e){let{appId:t,pageId:r,pageData:n,pageSettings:i,mode:o}=e;this.server.sendMessage({method:"Applet_OpenPage",params:{appletName:t,appletPageName:r,appletPageData:n,appletPageSettings:i,mode:o}})}async openPageUrl(e){let{appId:t,url:r}=e;this.server.sendMessage({method:"Applet_OpenPageUrl",params:{appletName:t,url:r}})}async pushWidget(e){let{appId:t,widgetId:r,widgetData:n,botId:i}=e;this.server.sendMessage({method:"Applet_OpenWidget",params:{appletName:t,widgetName:r,widgetData:n,botId:i||process.env.DEBUG_BOT_ID}})}async callTool(e){let{appId:t,toolId:r,toolData:n}=e;this.server.sendMessage({method:"Applet_CallTool",params:{appletName:t,toolName:r,toolData:n}})}}async function tN(t={}){if(!e){let r=t.debugDriver??ez.Adb;if(!eY.includes(r))throw Error(`无效的调试驱动 "${r}",可选值:${eY.join(", ")}。`);switch(r){case ez.Hdt:e=new tR;break;case ez.DevTools:e=new tT;break;case ez.Adb:{let r=t.deviceId??await tx();r&&(e=new tA(r,{skipForegroundAppWatch:t.skipAdbForegroundAppWatch}));break}default:throw Error(`无效的调试驱动 "${r}",可选值:${eY.join(", ")}。`)}}return e}let tL=f("node:fs/promises");async function tM(e){let t=(0,ta.join)(e,"debug-scene");try{return(await (0,tL.readdir)(t,{withFileTypes:!0})).filter(e=>e.isFile()&&e.name.endsWith(".json")).map(e=>({name:e.name.slice(0,-5),path:(0,ta.join)(t,e.name)}))}catch{return[]}}async function tj(e){try{return G(JSON.parse(await (0,tL.readFile)(e,"utf8")))}catch(t){return tm()&&console.warn(`[DoubaoApps] 加载调试场景 "${e}" 失败:${t instanceof Error?t.message:String(t)}`),null}}async function tU(e,t){let{matchedScene:r,appId:n,driver:i,variables:o}=e,a=t??await tj(r.path);if(!a)return;let s=X(a,o);if("page"===s.type){var l,d;l=r.name,0!==(d=s.unresolvedVariables).length&&console.warn(`[DoubaoApps] 调试场景 "${l}" 存在未解析的变量占位符:${d.map(e=>`{{${e}}}`).join(", ")}`),await i.openPageUrl({appId:n,url:s.url})}else if("widget"===s.type){let e=JSON.stringify(s.resolvedInput),t={appId:n,widgetId:s.id,widgetData:e,botId:s.botId};await i.pushWidget(t)}else{let e=JSON.stringify(s.resolvedInput),t={appId:n,toolId:s.id,toolData:e};await i.callTool(t)}}let tB="https://lf3-static.bytednsdoc.com/obj/eden-cn/777eh7nuptpfnuhd/default.svg";function tF(e){if("string"==typeof e){let t=e.length>0?e:tB;return{"1x":t,"2x":t,"3x":t}}return{"1x":e?.["1x"]||tB,"2x":e?.["2x"]||tB,"3x":e?.["3x"]||tB}}function tW(e){let t=Object.keys(e);return t.sort(),t.reduce((t,r)=>(t[r]=e[r],t),{})}class tH{get metadata(){return this._metadata}toString(){return JSON.stringify(this._metadata,null,2)}}class tV extends tH{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,r){let n=this._metadata;return{id:n.id,name:n.name,path:n.path,description:n.description,keywords:n.keywords,digest:t,prop:n.prop,entry:e,renderType:r,title:n.title,chat:n.chat}}}class tG extends tH{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,r,n=[]){let i=this._metadata;return{widgetId:i.id,name:i.name,description:i.description,keywords:i.keywords,digest:t,prop:i.prop,entry:e,renderType:r,border:i.border,appSettings:n,boxType:"full_box"===i.boxType?ea.FULL_BOX:ea.INBOX,titleType:i.titleType?tG.TITLE_TYPE_MAP[i.titleType]:void 0}}}tG.TITLE_TYPE_MAP={none:2,normal:0,float:1};class tq extends tH{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(){let e=this._metadata;return{id:e.id,name:e.name,description:e.description,timeout:e.timeout}}}class tJ extends tH{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest({toolsMetadata:e,hashCode:t,appRuntimeEntry:r,appRuntimeType:n}){return{name:this._metadata.name,description:this._metadata.description,appletId:this._metadata.appId,appletEntry:"index",pages:[],darkMode:this._metadata.darkMode,chat:this._metadata.chat,keywords:this._metadata.keywords,icons:tF(this._metadata.icons),digest:t,prop:"",tools:Object.values(e).map(e=>e.toManifest()),appRuntimeEntry:r,appRuntimeType:n}}}class tK{constructor(){this.metadata={app:{},widgets:{},pages:{},tools:{}}}get app(){return this.metadata.app.metadata??{}}get appId(){return this.app.appId}addAppMeta(e){this.metadata.app.metadata?this.metadata.app.assign(e):this.metadata.app=new tJ(e)}addToolMeta(e,t){this.metadata.tools[e]?this.metadata.tools[e].assign(t):this.metadata.tools[e]=new tq(t)}addPageMeta(e,t){this.metadata.pages[e]?this.metadata.pages[e].assign(t):this.metadata.pages[e]=new tV(t)}addWidgetMeta(e,t){this.metadata.widgets[e]?this.metadata.widgets[e].assign(t):this.metadata.widgets[e]=new tG(t)}getData(){let{tools:e,pages:t,widgets:r,app:n}=this.metadata;return{app:n.metadata??{},tools:tW(Object.fromEntries(Object.keys(e).map(t=>[t,e[t].metadata]))),pages:tW(Object.fromEntries(Object.keys(t).map(e=>[e,t[e].metadata]))),widgets:tW(Object.fromEntries(Object.keys(r).map(e=>[e,r[e].metadata])))}}getInstance(){let{tools:e,pages:t,widgets:r,app:n}=this.metadata;return{app:n,tools:tW(e),pages:tW(t),widgets:tW(r)}}clearData(){this.metadata={app:{},pages:{},tools:{},widgets:{}}}}(eT=ej||(ej={})).DEV="dev",eT.BUILD="build",eT.PERF="perf",eT.DEPLOY="deploy",eT.ANALYZE="analyze";let tz={DEV:ej.DEV,BUILD:ej.BUILD,PERF:ej.PERF,DEPLOY:ej.DEPLOY,ANALYZE:ej.ANALYZE},tY={MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE:1e3,MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY:2e3,MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE:3e3},tX={BEFORE_BUILD_STAGE_CREATE_CONFIG:1e3,BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG:2e3,BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG:3e3},tZ={COLLECT_METADATA_STAGE_START:1e3,COLLECT_METADATA_STAGE_PROCESS_METADATA:2e3,COLLECT_METADATA_STAGE_OPTIMIZE:3e3,COLLECT_METADATA_STAGE_FINISH:4e3},tQ={...tY,...tX,...tZ},t0={...tY,...tX,...tZ};(eC=eU||(eU={}))[eC.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS=1e3]="BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS",eC[eC.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS=2e3]="BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS",eC[eC.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=3e3]="BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS",eC[eC.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS=3999]="BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS",eC[eC.AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS=4e3]="AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS",eC[eC.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS=5e3]="AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS",eC[eC.AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=6e3]="AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS";let t1=f("../../../node_modules/.pnpm/tapable@2.2.1/node_modules/tapable/lib/index.js");function t3(){return{modifyEnvironment:new t1.FU(["arg0"]),modifyEntryOption:new t1.BD(["arg0"]),beforeBuild:new t1.FU(["arg0"]),collectMetaData:new t1.FU(["arg0"]),build:new t1.FU(["arg0"]),afterBuild:new t1.FU(["arg0"])}}function t2({hooks:e,stages:t}){return{hooks:e,...t}}class t4{constructor(e,t=[]){this.plugins=[],this.api={...{worker:t2({hooks:t3(),stages:t0}),view:t2({hooks:t3(),stages:tQ}),assets:t2({hooks:{beforeEmit:new t1.FU(["arg0"]),afterEmit:new t1.FU(["arg0"])},stages:eU}),deploy:t2({hooks:{beforeDeploy:new t1.FU(["arg0"]),deploy:new t1.FU(["arg0"]),afterDeploy:new t1.FU(["arg0"])},stages:{}})},context:e},this.addPlugins(t)}getScopeHooks(e){return this.api[e].hooks}addPlugins(e){this.plugins.push(...e)}async bootstrap(){for await(let e of this.plugins)await e.setup(this.api)}async callScopeHooks(e,t,...r){let n=M(this.getScopeHooks(e),t);return await n.promise(...r)}async callWorkerHooks(e,...t){return this.callScopeHooks("worker",e,...t)}async callViewHooks(e,...t){return this.callScopeHooks("view",e,...t)}async callAssetsHooks(e,...t){return this.callScopeHooks("assets",e,...t)}async callDeployHooks(e,...t){return this.callScopeHooks("deploy",e,...t)}}let t5=f("fs"),t9=f("../../../node_modules/.pnpm/archiver@7.0.1/node_modules/archiver/index.js");function t8(e,t,r,n){return new Promise((i,o)=>{let a=t5.createWriteStream(e),s=t9("zip",{zlib:{level:9}});s.pipe(a),s.directory(t,r??!1),a.on("close",()=>{n?.deleteResource&&t5.rmSync(t,{recursive:!0}),eA.success("Compiled artifacts packaged",{file:eX.basename(e)}),i("")}),s.on("error",e=>{eA.error("An error occurred during packaging",{error:e}),o(e)}),s.finalize()})}async function t7({channelName:e,manifest:t,rootPath:r}){let n=ta.resolve(r),i=ta.resolve(r,"doubao_app_output"),o=ta.resolve(i,t.packageName),a={outputFolder:i,transformFolder:o,manifest:t};to.existsSync(i)&&to.rmSync(i,{recursive:!0}),to.mkdirSync(i),to.mkdirSync(o),function(e,t){let{transformFolder:r,manifest:n}=t,{applet:i,widgets:o}=n,a=ta.resolve(e,"base"),s=ta.resolve(r,"base");to.mkdirSync(s),to.cpSync(a,s,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0});let l=ta.resolve(e,i.appletId),d=ta.resolve(r,i.appletId);to.mkdirSync(d),i.pages.length>0&&to.cpSync(l,d,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0}),o.forEach(t=>{let n=ta.resolve(e,t.widgetId),i=ta.resolve(r,t.widgetId);to.mkdirSync(i),to.cpSync(n,i,{filter:e=>null===e.match(/(.)*\.map$/),recursive:!0})});let p=ta.resolve(e,`web_${n.versionCode}`);if(to.existsSync(p)){let e=ta.resolve(r,`web_${n.versionCode}`);to.cpSync(p,e,{recursive:!0})}}(n,a);let s=await t6(e,a);return eA.debug("Package resource created",{packageResource:s}),{packageResource:s}}async function t6(e,t){if(!/([a-z0-9_-]+)/.test(e))throw Error("Channel name is invalid, only support /[a-z0-9_-]+/. archive gecko package failed. ");let{manifest:r,outputFolder:n,transformFolder:i}=t,{applet:o,widgets:a,packageName:s,versionCode:l}=r,d=ta.resolve(n,"deploy-package"),p=ta.resolve(d,e),c=ta.resolve(p,s);to.mkdirSync(d),to.mkdirSync(p),to.mkdirSync(c),to.cpSync(i,c,{recursive:!0});let u={},h=to.readdirSync(c).filter(e=>to.statSync(ta.resolve(c,e)).isDirectory()),m=ta.resolve(d,`${e}.zip`);try{if(await Promise.all(h.map(e=>{if(e===`web_${l}`)return Promise.resolve();if("base"===e)return t8(ta.resolve(c,`${e}_${l}.zip`),ta.resolve(c,e),e,{deleteResource:!0});if(e===o.appletId){let t=`${e}_${o.digest}.zip`;return u[o.appletId]=t,t8(ta.resolve(c,t),ta.resolve(c,e),e,{deleteResource:!0})}let t=a.find(t=>t.widgetId===e);if(t){let r=`${e}_${t.digest}.zip`;return u[t.widgetId]=r,t8(ta.resolve(c,r),ta.resolve(c,e),e,{deleteResource:!0})}return eA.error("Invalid package directory",{directory:e}),Promise.resolve()})),await t8(m,p,e),process.env.BUILD_VERSION){let e=ta.resolve(n,"scm-deploy-package"),t=ta.resolve(e,s);to.mkdirSync(e),to.mkdirSync(t),to.cpSync(c,t,{recursive:!0})}return eA.success("Deploy package archived",{destination:m}),{resource:m,fileNames:u}}catch(e){throw Error(`ERROR: Archive the deploy-package failed. ${e}`)}}(eI=eB||(eB={})).NORMAL="normal",eI.SELF_BUILT_CREATE="selfBuiltCreate",eI.SELF_BUILT_PUBLISH="selfBuiltPublish",eI.SELF_BUILT_CHECK_STATUS="selfBuiltCheckStatus",eI.SELF_BUILT_STOP="selfBuiltStop",eI.SELF_BUILT_ROLLBACK="selfBuiltRollback";let re={NORMAL:eB.NORMAL,SELF_BUILT_CREATE:eB.SELF_BUILT_CREATE,SELF_BUILT_PUBLISH:eB.SELF_BUILT_PUBLISH,SELF_BUILT_CHECK_STATUS:eB.SELF_BUILT_CHECK_STATUS,SELF_BUILT_STOP:eB.SELF_BUILT_STOP,SELF_BUILT_ROLLBACK:eB.SELF_BUILT_ROLLBACK};function rt(e,t){let r=(t||e).replace(/^\/+/,"").split("/").filter(Boolean);return r.length>1&&"index"===r[r.length-1]?r[r.length-2]||"index":r[r.length-1]||"index"}function rr(e,t){let[r]=(t??e).split(/[?#]/,1),n=r.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"");return n?`/${n}`:"/"}function rn(e,t,r){let n=rr(t).slice(1);return`${e}/${n}/${r}`}function ri(e,...t){return H(e,...t,(e,t,r)=>Array.isArray(e)?e.concat(t):Buffer.isBuffer(t)?t:void 0)}let ro=(e,t)=>ta.relative(e,t).replaceAll(ta.sep,"/");class ra{constructor(e,t=""){this.imports=[],this.contents=[],this._filename=e,t&&this.appendContent(t)}appendImports(...e){this.imports.push(...e)}appendContent(...e){this.contents.push(...e)}unshiftContent(...e){this.contents.unshift(...e)}get filename(){return this._filename}toString(){return[this.imports.map(e=>{if(e.importSpecifiers&&e.importSpecifiers.length>0){let t="",r=e.importSpecifiers.find(e=>"default"===e.propertyName),n=e.importSpecifiers.filter(e=>"default"!==e.propertyName);return r&&(t+=`${r.name}`),n.length&&(r&&(t+=", "),t+=`{ ${n.map(e=>e.name===e.propertyName?e.name:`${e.propertyName} as ${e.name}`).join(", ")} }`),`import ${t} from "${e.moduleSpecifier}";`}return`import "${e.moduleSpecifier}";`}).join("\n"),...this.contents].join("\n").trim()}write(e){if(this._filename){let t=eX.dirname(this._filename);(0,t5.existsSync)(t)||(0,t5.mkdirSync)(t,{recursive:!0}),(0,t5.writeFileSync)(this._filename,this.toString(),e)}return this._filename}}function rs(e,t,r=!1,n=!1){return Object.keys(e).reduce((i,o)=>{let{filename:a,isVirtualFile:s,isSpecial:l}=e[o];if(s||l)return i;let d=`${eZ}${ta.sep}${o}${ta.extname(a)}`,p=ro(ta.join(t,d,".."),a),c=tu(t),u=r?"defineWidget":"definePage";return i[o]=new ra(d),i[o].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:c,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"getViewData",name:"getViewData"},{propertyName:u,name:u}]},{moduleSpecifier:p,importSpecifiers:[{propertyName:"default",name:"TaroView"}]}),i[o].appendContent(`
127
+ }`,eZ="widgets";eJ.sep;let eQ=`base${eJ.sep}manifest.json`,e0=`base${eJ.sep}manifest.sign`,e1="mcp-privacy-login-card",e2="__doubao_apps__expired-widget",e3="bundle.keystore",e4={"@byted-lynx/react":"React","@lynx-js/react":"React","@lynx-js/react/internal":"ReactInternal","@lynx-js/react/jsx-dev-runtime":"ReactJSXDevRuntime","@lynx-js/react/jsx-runtime":"ReactJSXRuntime","@lynx-js/react/lepus/jsx-dev-runtime":"ReactJSXLepusDevRuntime","@lynx-js/react/lepus/jsx-runtime":"ReactJSXLepusRuntime","@lynx-js/react/experimental/lazy/import":"ReactLazyImport","@lynx-js/react/legacy-react-runtime":"ReactLegacyRuntime","@lynx-js/react/runtime-components":"ReactComponents","@lynx-js/react/worklet-runtime/bindings":"ReactWorkletRuntime","@lynx-js/react/debug":"ReactDebug",preact:"Preact",react:"React"},e5="client-tool",e8=e=>e===e1||e===e2,e9="app.config",e7=[".js",".ts",".mjs"],e6="com.larus.nova";class te{}function tt(e,t=3e3){return et(e,{timeout:t}).catch(()=>({stdout:"",stderr:""}))}async function tr(e,t){return tt(`adb -s ${e} ${t}`)}async function tn(e){let t=(await tt(`adb -s ${e} shell dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity' | tail -n 1`)).stdout.match(/\su\d+\s+([^\s\/]+)\//);return t?.[1]}async function ti(e,t){let r=(await tr(e,`shell pidof ${t}`)).stdout.trim();return r?r.split(/\s+/)[0]:void 0}async function ts(e){let t=await tn(e);return(t===e6||"com.flow.aisdk.example"===t)&&(await tt(`adb -s ${e} shell am force-stop ${t}`),await tt(`adb -s ${e} shell monkey -p ${t} -c android.intent.category.LAUNCHER 1`),!0)}async function to(){return(await tt("adb devices")).stdout.split("\n").slice(1).map(e=>e.split(" ")[0].trim()).filter(Boolean)}async function ta(){let e=await to();if(e.length>1){let{device:t}=await ed.prompt([{type:"search",name:"device",message:"检测到多个设备,请选择用于调试的设备(可按设备 ID 搜索):",source:t=>e.filter(e=>e.toLowerCase().includes(t?.toLowerCase()??""))}]);return t}return e[0]}class tl extends te{deviceId;latestLoadParams;lastAppProcessId;isWatchingAppProcess=!1;isAutoReloading=!1;constructor(e,t={}){if(super(),this.deviceId=e,t.skipForegroundAppWatch)return;let r=setInterval(()=>{this.watchAppProcess()},500);process.once("exit",()=>clearInterval(r))}async watchAppProcess(){if(!this.isWatchingAppProcess){this.isWatchingAppProcess=!0;try{let e=await ti(this.deviceId,e6);void 0!==this.lastAppProcessId&&void 0!==e&&this.lastAppProcessId!==e&&await this.reloadOnAppRestart(e),void 0!==e&&(this.lastAppProcessId=e)}finally{this.isWatchingAppProcess=!1}}}async reloadOnAppRestart(e){if(void 0!==this.latestLoadParams&&!this.isAutoReloading){this.isAutoReloading=!0;try{if(await new Promise(e=>setTimeout(e,5e3)),await ti(this.deviceId,e6)!==e)return;await this.load(this.latestLoadParams)}finally{this.isAutoReloading=!1}}}async load(e){this.latestLoadParams=e;let{appletUrl:t,appId:r,isSigned:n}=e,i=`shell am broadcast -a com.bytedance.applet.SET_APPLET_DEBUG_HOST --es appletName ${r} --es appletHost ${t} --es appletType 1 --es isSigned ${n}`;eb()&&console.log(ec.dim(`adb -s ${this.deviceId} ${i}`)),await tr(this.deviceId,i)}async openPage(e){let{appId:t,pageId:r,pageData:n,pageSettings:i,mode:s}=e,o=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageName ${r} --es appletPageData '${n}' --es appletPageSettings '${i}' --es mode '${s}'`;eb()&&console.log(ec.dim(`adb -s ${this.deviceId} ${o}`)),await tr(this.deviceId,o)}async openPageUrl(e){let{appId:t,url:r}=e,n=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageUrl '${r}'`;eb()&&console.log(ec.dim(`adb -s ${this.deviceId} ${n}`)),await tr(this.deviceId,n)}async pushWidget(e){let{appId:t,widgetId:r,widgetData:n,botId:i}=e,s=`shell am broadcast -a com.bytedance.applet.START_APPLET_WIDGET --es appletName ${t} --es widgetName ${r} --es widgetData '${n}' --es botId ${i||process.env.DEBUG_BOT_ID}`;eb()&&console.log(ec.dim(`adb -s ${this.deviceId} ${s}`)),await tr(this.deviceId,s)}async callTool(e){let{appId:t,toolId:r,toolData:n}=e,i=`shell am broadcast -a com.bytedance.applet.CALL_TOOL --es appletName ${t} --es toolName '${r}' --es toolData '${n}'`;eb()&&console.log(ec.dim(`adb -s ${this.deviceId} ${i}`)),await tr(this.deviceId,i)}}class tc extends te{async load(e){}async openPage(e){}async openPageUrl(e){}async pushWidget(e){}async callTool(e){}}ex.child("cli");let tp=ex.child("config"),td=ex.child("security"),tu=ex.child("build"),tm=ex.child("deploy"),th=ex.child("dev-server");class tf{options;currentUrl=null;debugDriver=null;appId=null;constructor(e){this.options=e}async start(e,t,r){if(null!==this.currentUrl){this.currentUrl=e,this.debugDriver?.getAllAppClients().forEach(e=>this.onConnect(e,r));return}this.currentUrl=e,this.appId=t;let{getDebugDriver:n,toolkitExecutor:i}=await import("./@byted-hdt/cli.js").then(f.bind(f,"../../../node_modules/.pnpm/@byted-hdt+cli@0.0.71_debug@4.4.3/node_modules/@byted-hdt/cli/dist/es/index.js"));await i({runType:"rspeedy",openWebview:this.options.devtool});let s=n();this.debugDriver=s,s.getAllAppClients().forEach(e=>this.onConnect(e,r)),s.on("app-client-connected",this.onConnect)}stop(){this.currentUrl=null,this.debugDriver?.off("app-client-connected",this.onConnect)}sendMessage(e){this.debugDriver?.getAllAppClients().forEach(t=>{try{t.sendCustomizedMessage(e.method,e.params,-1,"CDP")}catch(e){th.error("向 HDT 客户端发送消息失败",{error:e})}})}onConnect=(e,t)=>{null!==this.currentUrl&&null!==this.debugDriver&&null!==this.appId&&this.sendMessage({method:"Applet_AppReload",params:{appletName:this.appId,appletHost:this.currentUrl,appletType:1,isSigned:t}})}}class tg extends te{server;constructor(){super(),this.server=new tf({devtool:!0,open:!0})}async load(e){let{appletUrl:t,appId:r,isSigned:n}=e;this.server.start(t,r,n)}async openPage(e){let{appId:t,pageId:r,pageData:n,pageSettings:i,mode:s}=e;this.server.sendMessage({method:"Applet_OpenPage",params:{appletName:t,appletPageName:r,appletPageData:n,appletPageSettings:i,mode:s}})}async openPageUrl(e){let{appId:t,url:r}=e;this.server.sendMessage({method:"Applet_OpenPageUrl",params:{appletName:t,url:r}})}async pushWidget(e){let{appId:t,widgetId:r,widgetData:n,botId:i}=e;this.server.sendMessage({method:"Applet_OpenWidget",params:{appletName:t,widgetName:r,widgetData:n,botId:i||process.env.DEBUG_BOT_ID}})}async callTool(e){let{appId:t,toolId:r,toolData:n}=e;this.server.sendMessage({method:"Applet_CallTool",params:{appletName:t,toolName:r,toolData:n}})}}async function ty(t={}){if(!e){let r=t.debugDriver??eV.Adb;if(!eq.includes(r))throw Error(`无效的调试驱动 "${r}",可选值:${eq.join(", ")}。`);switch(r){case eV.Hdt:e=new tg;break;case eV.DevTools:e=new tc;break;case eV.Adb:{let r=t.deviceId??await ta();r&&(e=new tl(r,{skipForegroundAppWatch:t.skipAdbForegroundAppWatch}));break}default:throw Error(`无效的调试驱动 "${r}",可选值:${eq.join(", ")}。`)}}return e}let tb=f("node:fs/promises"),t_=f("node:path");async function tv(e){let t=(0,t_.join)(e,"debug-scene");try{return(await (0,tb.readdir)(t,{withFileTypes:!0})).filter(e=>e.isFile()&&e.name.endsWith(".json")).map(e=>({name:e.name.slice(0,-5),path:(0,t_.join)(t,e.name)}))}catch{return[]}}async function tE(e){try{return T(JSON.parse(await (0,tb.readFile)(e,"utf8")))}catch(t){return eb()&&console.warn(`[DoubaoApps] 加载调试场景 "${e}" 失败:${t instanceof Error?t.message:String(t)}`),null}}async function tw(e,t){let{matchedScene:r,appId:n,driver:i,variables:s}=e,o=t??await tE(r.path);if(!o)return;let a=k(o,s);if("page"===a.type){var l,c;l=r.name,0!==(c=a.unresolvedVariables).length&&console.warn(`[DoubaoApps] 调试场景 "${l}" 存在未解析的变量占位符:${c.map(e=>`{{${e}}}`).join(", ")}`),await i.openPageUrl({appId:n,url:a.url})}else if("widget"===a.type){let e=JSON.stringify(a.resolvedInput),t={appId:n,widgetId:a.id,widgetData:e,botId:a.botId};await i.pushWidget(t)}else{let e=JSON.stringify(a.resolvedInput),t={appId:n,toolId:a.id,toolData:e};await i.callTool(t)}}let tS="https://lf3-static.bytednsdoc.com/obj/eden-cn/777eh7nuptpfnuhd/default.svg";function tx(e){if("string"==typeof e){let t=e.length>0?e:tS;return{"1x":t,"2x":t,"3x":t}}return{"1x":e?.["1x"]||tS,"2x":e?.["2x"]||tS,"3x":e?.["3x"]||tS}}function tA(e){let t=Object.keys(e);return t.sort(),t.reduce((t,r)=>(t[r]=e[r],t),{})}class tT{get metadata(){return this._metadata}toString(){return JSON.stringify(this._metadata,null,2)}}class tI extends tT{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,r){let n=this._metadata;return{id:n.id,name:n.name,path:n.path,description:n.description,keywords:n.keywords,digest:t,prop:n.prop,entry:e,renderType:r,title:n.title,chat:n.chat}}}class tO extends tT{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,r,n=[]){let i=this._metadata;return{widgetId:i.id,name:i.name,description:i.description,keywords:i.keywords,digest:t,prop:i.prop,entry:e,renderType:r,border:i.border,appSettings:n,boxType:tO.BOX_TYPE_MAP[i.boxType??"inbox"]??eo.INBOX,titleType:i.titleType?tO.TITLE_TYPE_MAP[i.titleType]:void 0}}}tO.BOX_TYPE_MAP={inbox:eo.INBOX,full_box:eo.FULL_BOX,custom_box:eo.CUSTOM_BOX},tO.TITLE_TYPE_MAP={none:2,normal:0,float:1};class tP extends tT{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(){let e=this._metadata;return{id:e.id,name:e.name,description:e.description,timeout:e.timeout}}}class tC extends tT{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest({toolsMetadata:e,hashCode:t,appRuntimeEntry:r,appRuntimeType:n}){return{name:this._metadata.name,description:this._metadata.description,appletId:this._metadata.appId,appletEntry:"index",pages:[],darkMode:this._metadata.darkMode,chat:this._metadata.chat,keywords:this._metadata.keywords,icons:tx(this._metadata.icons),digest:t,prop:"",tools:Object.values(e).map(e=>e.toManifest()),appRuntimeEntry:r,appRuntimeType:n}}}class tR{constructor(){this.metadata={app:{},widgets:{},pages:{},tools:{}}}get app(){return this.metadata.app.metadata??{}}get appId(){return this.app.appId}addAppMeta(e){this.metadata.app.metadata?this.metadata.app.assign(e):this.metadata.app=new tC(e)}addToolMeta(e,t){this.metadata.tools[e]?this.metadata.tools[e].assign(t):this.metadata.tools[e]=new tP(t)}addPageMeta(e,t){this.metadata.pages[e]?this.metadata.pages[e].assign(t):this.metadata.pages[e]=new tI(t)}addWidgetMeta(e,t){this.metadata.widgets[e]?this.metadata.widgets[e].assign(t):this.metadata.widgets[e]=new tO(t)}getData(){let{tools:e,pages:t,widgets:r,app:n}=this.metadata;return{app:n.metadata??{},tools:tA(Object.fromEntries(Object.keys(e).map(t=>[t,e[t].metadata]))),pages:tA(Object.fromEntries(Object.keys(t).map(e=>[e,t[e].metadata]))),widgets:tA(Object.fromEntries(Object.keys(r).map(e=>[e,r[e].metadata])))}}getInstance(){let{tools:e,pages:t,widgets:r,app:n}=this.metadata;return{app:n,tools:tA(e),pages:tA(t),widgets:tA(r)}}clearData(){this.metadata={app:{},pages:{},tools:{},widgets:{}}}}(eT=eD||(eD={})).DEV="dev",eT.BUILD="build",eT.PERF="perf",eT.DEPLOY="deploy",eT.ANALYZE="analyze";let t$={DEV:eD.DEV,BUILD:eD.BUILD,PERF:eD.PERF,DEPLOY:eD.DEPLOY,ANALYZE:eD.ANALYZE},tk={MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE:1e3,MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY:2e3,MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE:3e3},tN={BEFORE_BUILD_STAGE_CREATE_CONFIG:1e3,BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG:2e3,BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG:3e3},tL={COLLECT_METADATA_STAGE_START:1e3,COLLECT_METADATA_STAGE_PROCESS_METADATA:2e3,COLLECT_METADATA_STAGE_OPTIMIZE:3e3,COLLECT_METADATA_STAGE_FINISH:4e3},tD={...tk,...tN,...tL},tj={...tk,...tN,...tL};(eI=ej||(ej={}))[eI.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS=1e3]="BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS",eI[eI.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS=2e3]="BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS",eI[eI.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=3e3]="BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS",eI[eI.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS=3999]="BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS",eI[eI.AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS=4e3]="AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS",eI[eI.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS=5e3]="AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS",eI[eI.AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=6e3]="AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS";let tM=f("../../../node_modules/.pnpm/tapable@2.2.1/node_modules/tapable/lib/index.js");function tU(){return{modifyEnvironment:new tM.FU(["arg0"]),modifyEntryOption:new tM.BD(["arg0"]),beforeBuild:new tM.FU(["arg0"]),collectMetaData:new tM.FU(["arg0"]),build:new tM.FU(["arg0"]),afterBuild:new tM.FU(["arg0"])}}function tB({hooks:e,stages:t}){return{hooks:e,...t}}class tF{constructor(e,t=[]){this.plugins=[],this.api={...{worker:tB({hooks:tU(),stages:tj}),view:tB({hooks:tU(),stages:tD}),assets:tB({hooks:{beforeEmit:new tM.FU(["arg0"]),afterEmit:new tM.FU(["arg0"])},stages:ej}),deploy:tB({hooks:{beforeDeploy:new tM.FU(["arg0"]),deploy:new tM.FU(["arg0"]),afterDeploy:new tM.FU(["arg0"])},stages:{}})},context:e},this.addPlugins(t)}getScopeHooks(e){return this.api[e].hooks}addPlugins(e){this.plugins.push(...e)}async bootstrap(){for await(let e of this.plugins)await e.setup(this.api)}async callScopeHooks(e,t,...r){let n=B(this.getScopeHooks(e),t);return await n.promise(...r)}async callWorkerHooks(e,...t){return this.callScopeHooks("worker",e,...t)}async callViewHooks(e,...t){return this.callScopeHooks("view",e,...t)}async callAssetsHooks(e,...t){return this.callScopeHooks("assets",e,...t)}async callDeployHooks(e,...t){return this.callScopeHooks("deploy",e,...t)}}let tH=f("fs"),tW=f("../../../node_modules/.pnpm/archiver@7.0.1/node_modules/archiver/index.js");function tG(e,t,r,n){return new Promise((i,s)=>{let o=tH.createWriteStream(e),a=tW("zip",{zlib:{level:9}});a.pipe(o),a.directory(t,r??!1),o.on("close",()=>{n?.deleteResource&&tH.rmSync(t,{recursive:!0}),eA.success("Compiled artifacts packaged",{file:eJ.basename(e)}),i("")}),a.on("error",e=>{eA.error("An error occurred during packaging",{error:e}),s(e)}),a.finalize()})}let tV=f("node:fs");async function tq({channelName:e,manifest:t,rootPath:r}){let n=t_.resolve(r),i=t_.resolve(r,"doubao_app_output"),s=t_.resolve(i,t.packageName),o={outputFolder:i,transformFolder:s,manifest:t};tV.existsSync(i)&&tV.rmSync(i,{recursive:!0}),tV.mkdirSync(i),tV.mkdirSync(s),function(e,t){let{transformFolder:r,manifest:n}=t,{applet:i,widgets:s}=n,o=t_.resolve(e,"base"),a=t_.resolve(r,"base");tV.mkdirSync(a),tV.cpSync(o,a,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0});let l=t_.resolve(e,i.appletId),c=t_.resolve(r,i.appletId);tV.mkdirSync(c),i.pages.length>0&&tV.cpSync(l,c,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0}),s.forEach(t=>{let n=t_.resolve(e,t.widgetId),i=t_.resolve(r,t.widgetId);tV.mkdirSync(i),tV.cpSync(n,i,{filter:e=>null===e.match(/(.)*\.map$/),recursive:!0})});let p=t_.resolve(e,`web_${n.versionCode}`);if(tV.existsSync(p)){let e=t_.resolve(r,`web_${n.versionCode}`);tV.cpSync(p,e,{recursive:!0})}}(n,o);let a=await tJ(e,o);return eA.debug("Package resource created",{packageResource:a}),{packageResource:a}}async function tJ(e,t){if(!/([a-z0-9_-]+)/.test(e))throw Error("Channel name is invalid, only support /[a-z0-9_-]+/. archive gecko package failed. ");let{manifest:r,outputFolder:n,transformFolder:i}=t,{applet:s,widgets:o,packageName:a,versionCode:l}=r,c=t_.resolve(n,"deploy-package"),p=t_.resolve(c,e),d=t_.resolve(p,a);tV.mkdirSync(c),tV.mkdirSync(p),tV.mkdirSync(d),tV.cpSync(i,d,{recursive:!0});let u={},m=tV.readdirSync(d).filter(e=>tV.statSync(t_.resolve(d,e)).isDirectory()),h=t_.resolve(c,`${e}.zip`);try{if(await Promise.all(m.map(e=>{if(e===`web_${l}`)return Promise.resolve();if("base"===e)return tG(t_.resolve(d,`${e}_${l}.zip`),t_.resolve(d,e),e,{deleteResource:!0});if(e===s.appletId){let t=`${e}_${s.digest}.zip`;return u[s.appletId]=t,tG(t_.resolve(d,t),t_.resolve(d,e),e,{deleteResource:!0})}let t=o.find(t=>t.widgetId===e);if(t){let r=`${e}_${t.digest}.zip`;return u[t.widgetId]=r,tG(t_.resolve(d,r),t_.resolve(d,e),e,{deleteResource:!0})}return eA.error("Invalid package directory",{directory:e}),Promise.resolve()})),await tG(h,p,e),process.env.BUILD_VERSION){let e=t_.resolve(n,"scm-deploy-package"),t=t_.resolve(e,a);tV.mkdirSync(e),tV.mkdirSync(t),tV.cpSync(d,t,{recursive:!0})}return eA.success("Deploy package archived",{destination:h}),{resource:h,fileNames:u}}catch(e){throw Error(`ERROR: Archive the deploy-package failed. ${e}`)}}(eO=eM||(eM={})).NORMAL="normal",eO.SELF_BUILT_CREATE="selfBuiltCreate",eO.SELF_BUILT_PUBLISH="selfBuiltPublish",eO.SELF_BUILT_CHECK_STATUS="selfBuiltCheckStatus",eO.SELF_BUILT_STOP="selfBuiltStop",eO.SELF_BUILT_ROLLBACK="selfBuiltRollback";let tz={NORMAL:eM.NORMAL,SELF_BUILT_CREATE:eM.SELF_BUILT_CREATE,SELF_BUILT_PUBLISH:eM.SELF_BUILT_PUBLISH,SELF_BUILT_CHECK_STATUS:eM.SELF_BUILT_CHECK_STATUS,SELF_BUILT_STOP:eM.SELF_BUILT_STOP,SELF_BUILT_ROLLBACK:eM.SELF_BUILT_ROLLBACK};function tK(e,t){let r=(t||e).replace(/^\/+/,"").split("/").filter(Boolean);return r.length>1&&"index"===r[r.length-1]?r[r.length-2]||"index":r[r.length-1]||"index"}function tY(e,t){let[r]=(t??e).split(/[?#]/,1),n=r.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"");return n?`/${n}`:"/"}function tX(e,t,r){let n=tY(t).slice(1);return`${e}/${n}/${r}`}function tZ(e,...t){return z(e,...t,(e,t,r)=>Array.isArray(e)?e.concat(t):Buffer.isBuffer(t)?t:void 0)}let tQ=(e,t)=>t_.relative(e,t).replaceAll(t_.sep,"/"),t0="@byted-doubao-apps/framework",t1="@doubao-dev/framework",t2=[t0,t1];function t3(e){return`${e}/components`}function t4(e){let t=t_.resolve(e,"package.json");if(tV.existsSync(t))try{let e=JSON.parse(tV.readFileSync(t,"utf8")),r={...e.dependencies,...e.devDependencies,...e.peerDependencies};if(r[t1])return t1;if(r[t0])return t0}catch{}}function t5(e){return t4(e)??t0}class t8{constructor(e,t=""){this.imports=[],this.contents=[],this._filename=e,t&&this.appendContent(t)}appendImports(...e){this.imports.push(...e)}appendContent(...e){this.contents.push(...e)}unshiftContent(...e){this.contents.unshift(...e)}get filename(){return this._filename}toString(){return[this.imports.map(e=>{if(e.importSpecifiers&&e.importSpecifiers.length>0){let t="",r=e.importSpecifiers.find(e=>"default"===e.propertyName),n=e.importSpecifiers.filter(e=>"default"!==e.propertyName);return r&&(t+=`${r.name}`),n.length&&(r&&(t+=", "),t+=`{ ${n.map(e=>e.name===e.propertyName?e.name:`${e.propertyName} as ${e.name}`).join(", ")} }`),`import ${t} from "${e.moduleSpecifier}";`}return`import "${e.moduleSpecifier}";`}).join("\n"),...this.contents].join("\n").trim()}write(e){if(this._filename){let t=eJ.dirname(this._filename);(0,tH.existsSync)(t)||(0,tH.mkdirSync)(t,{recursive:!0}),(0,tH.writeFileSync)(this._filename,this.toString(),e)}return this._filename}}function t9(e,t,r=!1,n=!1){return Object.keys(e).reduce((i,s)=>{let{filename:o,isVirtualFile:a,isSpecial:l}=e[s];if(a||l)return i;let c=`${ez}${t_.sep}${s}${t_.extname(o)}`,p=tQ(t_.join(t,c,".."),o),d=t5(t),u=r?"defineWidget":"definePage";return i[s]=new t8(c),i[s].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:d,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"getViewData",name:"getViewData"},{propertyName:u,name:u}]},{moduleSpecifier:p,importSpecifiers:[{propertyName:"default",name:"TaroView"}]}),i[s].appendContent(`
128
128
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
129
129
 
130
130
  const View = ${u}({
@@ -139,54 +139,60 @@ root.render(<FC />);`,n?`
139
139
  if (import.meta.webpackHot) {
140
140
  import.meta.webpackHot.accept()
141
141
  }
142
- `:""),i},{})}let rl=f("module"),rd="doubao:plugin:taro";class rp extends ra{toString(){return this.contents.join("\n").trim()}}async function rc({config:e,pluginSystem:t}){let r=e.context.environment;await t.callWorkerHooks("modifyEnvironment",{environment:r}),e.context.setEnvironment(r);let{entry:n}=await t.callWorkerHooks("modifyEntryOption",{entry:{app:new rp(`.${ta.sep}app.js`,"")}});return{entry:n}}async function ru({compiler:e,compilation:t,assets:r,metadata:n,resolveAppInfo:i,shouldInjectAsset:o}){let a=Object.keys(r).reduce((e,r)=>{if(!o(r))return e;let n=t.getAsset(r);return n&&e.push(n),e},[]);if(0===a.length)return;let s=n.app,l=await i?.(),d=`globalThis.__AI_MANIFEST__ = ${JSON.stringify({package:l?.appKey||s.appId,appId:l?.appKey||s.appId,name:l?.appName||s.name,icons:l?.iconUrl?tF(l.iconUrl):s.icons})};
143
- `;a.forEach(r=>{if(r.source.source().toString().startsWith(d))return;let n=new e.webpack.sources.ReplaceSource(r.source,r.name);n.insert(0,d),t.updateAsset(r.name,n,r.info)})}function rh(e){let t=ta.posix.basename(e);return"background.js"===t||"main-thread.js"===t||/^background\.[^/]+\.js$/.test(t)||/^main-thread\.[^/]+\.js$/.test(t)}function rm(e){let t=e.replaceAll("\\","/");return t.split("/").some(e=>e.startsWith("__doubao_web__"))&&rh(t)}class rf{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(rf.name,t=>{t.hooks.processAssets.tapPromise({name:rf.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{await ru({compiler:e,compilation:t,assets:r,...this.options})})})}}let rg="index.web.bundle",ry="base/app.web.bundle",rb="base/client-tool/index.web.bundle";function r_(e){return`__doubao_web__${e.replaceAll("\\","/").replaceAll("/","__")}`}function rv(e,t,r){return t[r]?.id??rt(r,e[r]?.folderName)}function rw(e){return!!e?.internal}function rS(e={},t={},r="configured"){return"all"===r?e:function(e={},t={}){return Object.fromEntries(Object.entries(e).filter(([e,r])=>rw(r)||!!t[e]?.web))}(e,t)}class rE{apply(e){e.hooks.thisCompilation.tap(rE.name,t=>{t.hooks.processAssets.tapPromise({name:rE.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{let r=rx(t,"app"),n=r?t.getAsset(r):void 0;if(!r||!n)throw Error("Worker entry asset was not emitted.");await rA(t,e,r,ry);let i=rx(t,e6);i&&await rA(t,e,i,rb)})})}}function rx(e,t){let r=e.entrypoints.get(t)?.getEntrypointChunk();return[...r?.files??[]].find(t=>t.endsWith(".js")&&!e.getAsset(t)?.info?.hotModuleReplacement)}async function rA(e,t,r,n){let i=e.getAsset(r);if(!i)throw Error(`Worker entry asset was not emitted: ${r}`);e.emitAsset(n,new t.webpack.sources.RawSource(await rT(i.source.source().toString())));let o=e.getAsset(`${r}.map`);o&&e.emitAsset(`${n}.map`,o.source,o.info),e.deleteAsset(r)}async function rT(e){let{encode:t}=await import("./@lynx-js/web-core-canary.js");return Buffer.from(t({styleInfo:{},manifest:{"/app-service.js":e},cardType:"react",appType:"card",pageConfig:{enableFiberArch:!0,useLepusNG:!0,enableReuseContext:!0,bundleModuleMode:"ReturnByFunction",targetSdkVersion:"3.2"},lepusCode:{root:"void 0;"},customSections:{},elementTemplates:{}}))}class rC{options;recordNativeAppAssetPaths;constructor(e,t){this.options=e,this.recordNativeAppAssetPaths=t}apply(e){new e.webpack.experiments.VirtualModulesPlugin({[eQ]:"",[e0]:e1,...Object.fromEntries(Object.entries(this.options.entry).map(([,e])=>[e.filename,e.toString()]))}).apply(e),e.hooks.make.tapPromise(rC.name,async()=>{await this.options.pluginSystem.callWorkerHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(rC.name,t=>{t.hooks.optimizeTree.tapPromise(rC.name,async()=>{await this.options.pluginSystem.callWorkerHooks("build",{metadata:this.options.context.metadata,fileDependencies:t.fileDependencies})}),t.hooks.processAssets.tapPromise({name:rC.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{var n,i,o;let a,s=rx(t,"app");if(!s||!t.getAsset(s))throw Error("Worker entry asset was not emitted.");this.recordNativeAppAssetPaths&&(n=t,i=this.options.context,o=s,i.setAppAssetPath(o),a=`${o}.map`,n.getAsset(a)&&i.setAppMapAssetPath(a)),await ru({compiler:e,compilation:t,assets:r,metadata:this.options.context.metadata,resolveAppInfo:()=>this.options.context.resolveAppInfo(),shouldInjectAsset:e=>e===s})})}),e.hooks.done.tapPromise(rC.name,async e=>{await this.options.pluginSystem.callWorkerHooks("afterBuild",{stats:e})})}}let rI=f("node:os"),rO=f("process"),rP=f("../../../node_modules/.pnpm/@lynx-js+type-config@4.1.3/node_modules/@lynx-js/type-config/index.js");var rk={},rD={};function r$(e){var t=rD[e];if(void 0!==t)return t.exports;var r=rD[e]={exports:{}};return rk[e](r,r.exports,r$),r.exports}r$.m=rk,r$.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r$.d(t,{a:t}),t},r$.d=(e,t,r)=>{var n=(t,r)=>{for(var n in t)r$.o(t,n)&&!r$.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[r]:t[n]})};n(t,"get"),n(r,"value")},r$.add=function(e){Object.assign(r$.m,e)},r$.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r$.add({"../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js"(e){e.exports=function(e){return null!=e&&"object"==typeof e&&!1===Array.isArray(e)}},"../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js"(e,t,r){var n=r("../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js");e.exports=function(e,t){if(!n(e)&&"function"!=typeof e)return{};var r={};if("string"==typeof t)return t in e&&(r[t]=e[t]),r;for(var i=t.length,o=-1;++o<i;){var a=t[o];a in e&&(r[a]=e[a])}return r}},"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(e){let t=rO||{},r=t.argv||[],n=t.env||{},i=!(n.NO_COLOR||r.includes("--no-color"))&&(!!n.FORCE_COLOR||r.includes("--color")||"win32"===t.platform||(t.stdout||{}).isTTY&&"dumb"!==n.TERM||!!n.CI),o=(e,t,r=e)=>n=>{let i=""+n,o=i.indexOf(t,e.length);return~o?e+a(i,t,r,o)+t:e+i+t},a=(e,t,r,n)=>{let i="",o=0;do i+=e.substring(o,n)+r,o=n+t.length,n=e.indexOf(t,o);while(~n);return i+e.substring(o)},s=(e=i)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t("\x1b[0m","\x1b[0m"),bold:t("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:t("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:t("\x1b[3m","\x1b[23m"),underline:t("\x1b[4m","\x1b[24m"),inverse:t("\x1b[7m","\x1b[27m"),hidden:t("\x1b[8m","\x1b[28m"),strikethrough:t("\x1b[9m","\x1b[29m"),black:t("\x1b[30m","\x1b[39m"),red:t("\x1b[31m","\x1b[39m"),green:t("\x1b[32m","\x1b[39m"),yellow:t("\x1b[33m","\x1b[39m"),blue:t("\x1b[34m","\x1b[39m"),magenta:t("\x1b[35m","\x1b[39m"),cyan:t("\x1b[36m","\x1b[39m"),white:t("\x1b[37m","\x1b[39m"),gray:t("\x1b[90m","\x1b[39m"),bgBlack:t("\x1b[40m","\x1b[49m"),bgRed:t("\x1b[41m","\x1b[49m"),bgGreen:t("\x1b[42m","\x1b[49m"),bgYellow:t("\x1b[43m","\x1b[49m"),bgBlue:t("\x1b[44m","\x1b[49m"),bgMagenta:t("\x1b[45m","\x1b[49m"),bgCyan:t("\x1b[46m","\x1b[49m"),bgWhite:t("\x1b[47m","\x1b[49m"),blackBright:t("\x1b[90m","\x1b[39m"),redBright:t("\x1b[91m","\x1b[39m"),greenBright:t("\x1b[92m","\x1b[39m"),yellowBright:t("\x1b[93m","\x1b[39m"),blueBright:t("\x1b[94m","\x1b[39m"),magentaBright:t("\x1b[95m","\x1b[39m"),cyanBright:t("\x1b[96m","\x1b[39m"),whiteBright:t("\x1b[97m","\x1b[39m"),bgBlackBright:t("\x1b[100m","\x1b[49m"),bgRedBright:t("\x1b[101m","\x1b[49m"),bgGreenBright:t("\x1b[102m","\x1b[49m"),bgYellowBright:t("\x1b[103m","\x1b[49m"),bgBlueBright:t("\x1b[104m","\x1b[49m"),bgMagentaBright:t("\x1b[105m","\x1b[49m"),bgCyanBright:t("\x1b[106m","\x1b[49m"),bgWhiteBright:t("\x1b[107m","\x1b[49m")}};e.exports=s(),e.exports.createColors=s}});let rR=globalThis.window?.document!==void 0;globalThis.process?.versions?.node,globalThis.process?.versions?.bun,globalThis.Deno?.version?.deno,globalThis.process?.versions?.electron,globalThis.navigator?.userAgent?.includes("jsdom");let rN=globalThis.navigator?.userAgentData?.platform;function rL(e,t=globalThis.Deno?globalThis.Deno.args:S.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}"macOS"===rN||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform,"Windows"===rN||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform,"Linux"===rN||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform,"iOS"===rN||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),"Android"===rN||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform,rR||S.env.TERM_PROGRAM,rR||S.platform,rR||S.cwd;let{env:rM}=S;function rj(e,r={}){var n;return 0!==(n=function(e,{streamIsTTY:r,sniffFlags:n=!0}={}){let i=function(){if(!("FORCE_COLOR"in rM))return;if("true"===rM.FORCE_COLOR)return 1;if("false"===rM.FORCE_COLOR)return 0;if(0===rM.FORCE_COLOR.length)return 1;let e=Math.min(Number.parseInt(rM.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}();void 0!==i&&(t=i);let o=n?t:i;if(0===o)return 0;if(n){if(rL("color=16m")||rL("color=full")||rL("color=truecolor"))return 3;if(rL("color=256"))return 2}if("TF_BUILD"in rM&&"AGENT_NAME"in rM)return 1;if(e&&!r&&void 0===o)return 0;let a=o||0;if("dumb"===rM.TERM)return a;if("win32"===S.platform){let e=rI.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in rM)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in rM)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in rM)||"codeship"===rM.CI_NAME?1:a;if("TEAMCITY_VERSION"in rM)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(rM.TEAMCITY_VERSION);if("truecolor"===rM.COLORTERM||"xterm-kitty"===rM.TERM||"xterm-ghostty"===rM.TERM||"wezterm"===rM.TERM)return 3;if("TERM_PROGRAM"in rM){let e=Number.parseInt((rM.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(rM.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(rM.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(rM.TERM)||"COLORTERM"in rM?1:a}(e,{streamIsTTY:e&&e.isTTY,...r}))&&{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function rU(e,t=rO.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}function rB(e=""){if(/^\d{3,4}$/.test(e)){let t=/(\d{1,2})(\d{2})/.exec(e)??[];return{major:0,minor:Number.parseInt(t[1],10),patch:Number.parseInt(t[2],10)}}let t=(e??"").split(".").map(e=>Number.parseInt(e,10));return{major:t[0],minor:t[1],patch:t[2]}}function rF(e){let{CI:t,CURSOR_TRACE_ID:r,FORCE_HYPERLINK:n,NETLIFY:i,TEAMCITY_VERSION:o,TERM_PROGRAM:a,TERM_PROGRAM_VERSION:s,VTE_VERSION:l,TERM:d}=S.env;if(n)return!(n.length>0&&0===Number.parseInt(n,10));if(rU("no-hyperlink")||rU("no-hyperlinks")||rU("hyperlink=false")||rU("hyperlink=never"))return!1;if(rU("hyperlink=true")||rU("hyperlink=always")||i)return!0;if(!rj(e)||e&&!e.isTTY)return!1;if("WT_SESSION"in S.env)return!0;if("win32"===S.platform||t||o)return!1;if(a){let e=rB(s);switch(a){case"iTerm.app":if(3===e.major)return e.minor>=1;return e.major>3;case"WezTerm":if(/^0-unstable-\d{4}-\d{2}-\d{2}$/.test(s))return s.slice(11)>="2020-06-20";return e.major>=0x1343cac;case"vscode":if(r)return!0;return e.major>1||1===e.major&&e.minor>=72;case"ghostty":case"zed":case"Orca":return!0}}if(l){if("0.50.0"===l)return!1;let e=rB(l);return e.major>0||e.minor>=50}switch(d){case"alacritty":case"xterm-kitty":return!0}return!1}rL("no-color")||rL("no-colors")||rL("color=false")||rL("color=never")?t=0:(rL("color")||rL("colors")||rL("color=true")||rL("color=always"))&&(t=1),rj({isTTY:b.isatty(1)}),rj({isTTY:b.isatty(2)});let rW={stdout:rF(S.stdout),stderr:rF(S.stderr)};function rH(e,t,{target:r="stdout",...n}={}){return rW[r]?["\x1b]","8",";",";",t,"\x07",e,"\x1b]","8",";",";","\x07"].join(""):!1===n.fallback?e:"function"==typeof n.fallback?n.fallback(e,t):`${e} ${t}`}rH.isSupported=rW.stdout,rH.stderr=(e,t,r={})=>rH(e,t,{target:"stderr",...r}),rH.stderr.isSupported=rW.stderr;let rV=r$("../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js");var rG=r$.n(rV);class rq{options;constructor(e){this.options=e}name="LynxConfigWebpackPlugin";apply(e){e.hooks.thisCompilation.tap(this.name,e=>{this.options.LynxTemplatePlugin.getLynxTemplatePluginHooks(e).beforeEncode.tap(this.name,e=>{let{config:t}=this.options;return e.encodeData.compilerOptions={...e.encodeData.compilerOptions,...rG()(t,this.options.compilerOptionsKeys)},e.encodeData.sourceContent.config={...e.encodeData.sourceContent.config,...rG()(t,this.options.configKeys)},e})})}}let rJ=e=>rK.has(e),rK=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"]);(eO=eF||(eF={}))[eO.Start=0]="Start",eO[eO.Property=1]="Property",eO[eO.StringKey=2]="StringKey",eO[eO.NumberKey=3]="NumberKey";let rz=r$("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");var rY=r$.n(rz);let rX=Object.assign(a=e=>{if(!1===("object"==typeof e&&null!==e&&!1===Array.isArray(e)&&((e,t=!0)=>(void 0===e.alignMouseEventWithW3C||"boolean"==typeof e.alignMouseEventWithW3C)&&(void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll)&&(void 0===e.enableA11y||"boolean"==typeof e.enableA11y)&&(void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement)&&(void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance)&&(void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables)&&(void 0===e.enableCSSRule||"boolean"==typeof e.enableCSSRule)&&(void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp)&&(void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor)&&(void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough)&&(void 0===e.enableFetchAPIStandardStreaming||"boolean"==typeof e.enableFetchAPIStandardStreaming)&&(void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew)&&(void 0===e.enableFlexBasisZeroPercent||"boolean"==typeof e.enableFlexBasisZeroPercent)&&(void 0===e.enableGridPlacementShorthands||"boolean"==typeof e.enableGridPlacementShorthands)&&(void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException)&&(void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture)&&(void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch)&&(void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList)&&(void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture)&&(void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver)&&(void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin)&&(void 0===e.enableParseIntFlex||"boolean"==typeof e.enableParseIntFlex)&&(void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle)&&(void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap)&&(void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow)&&(void 0===e.enableTransformedTouchPosition||"boolean"==typeof e.enableTransformedTouchPosition)&&(void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp)&&(void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding)&&(void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight)&&(void 0===e.longPressDuration||"number"==typeof e.longPressDuration)&&(void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope)&&(void 0===e.tapSlop||"string"==typeof e.tapSlop)&&(void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior)&&(0===Object.keys(e).length||Object.keys(e).every(t=>!!["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableListNewArchitecture","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(e=>t===e)||void 0===e[t])))(e,!0))){var t;t=i=[],o=(e,r)=>(e&&(e=>{if(0===t.length)return!0;let r=t[t.length-1].path;return e.length>r.length||r.substring(0,e.length)!==e})(r.path)&&(void 0===r.value&&(r.description??=`The value at this path is \`undefined\`.
144
-
145
- Please fill the \`${r.expected}\` typed value next time.`),t.push(r)),!1),((e,t,r=!0)=>("object"==typeof e&&null!==e&&!1===Array.isArray(e)||o(!0,{path:t+"",expected:"Config",value:e}))&&((e,t,r=!0)=>[void 0===e.alignMouseEventWithW3C||"boolean"==typeof e.alignMouseEventWithW3C||o(r,{path:t+".alignMouseEventWithW3C",expected:"(boolean | undefined)",value:e.alignMouseEventWithW3C}),void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll||o(r,{path:t+".disableLongpressAfterScroll",expected:"(boolean | undefined)",value:e.disableLongpressAfterScroll}),void 0===e.enableA11y||"boolean"==typeof e.enableA11y||o(r,{path:t+".enableA11y",expected:"(boolean | undefined)",value:e.enableA11y}),void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement||o(r,{path:t+".enableAccessibilityElement",expected:"(boolean | undefined)",value:e.enableAccessibilityElement}),void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance||o(r,{path:t+".enableCSSInheritance",expected:"(boolean | undefined)",value:e.enableCSSInheritance}),void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables||o(r,{path:t+".enableCSSInlineVariables",expected:"(boolean | undefined)",value:e.enableCSSInlineVariables}),void 0===e.enableCSSRule||"boolean"==typeof e.enableCSSRule||o(r,{path:t+".enableCSSRule",expected:"(boolean | undefined)",value:e.enableCSSRule}),void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp||o(r,{path:t+".enableEndGestureAtLastFingerUp",expected:"(boolean | undefined)",value:e.enableEndGestureAtLastFingerUp}),void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor||o(r,{path:t+".enableEventHandleRefactor",expected:"(boolean | undefined)",value:e.enableEventHandleRefactor}),void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough||o(r,{path:t+".enableEventThrough",expected:"(boolean | undefined)",value:e.enableEventThrough}),void 0===e.enableFetchAPIStandardStreaming||"boolean"==typeof e.enableFetchAPIStandardStreaming||o(r,{path:t+".enableFetchAPIStandardStreaming",expected:"(boolean | undefined)",value:e.enableFetchAPIStandardStreaming}),void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew||o(r,{path:t+".enableFixedNew",expected:"(boolean | undefined)",value:e.enableFixedNew}),void 0===e.enableFlexBasisZeroPercent||"boolean"==typeof e.enableFlexBasisZeroPercent||o(r,{path:t+".enableFlexBasisZeroPercent",expected:"(boolean | undefined)",value:e.enableFlexBasisZeroPercent}),void 0===e.enableGridPlacementShorthands||"boolean"==typeof e.enableGridPlacementShorthands||o(r,{path:t+".enableGridPlacementShorthands",expected:"(boolean | undefined)",value:e.enableGridPlacementShorthands}),void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException||o(r,{path:t+".enableJsBindingApiThrowException",expected:"(boolean | undefined)",value:e.enableJsBindingApiThrowException}),void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture||o(r,{path:t+".enableListNewArchitecture",expected:"(boolean | undefined)",value:e.enableListNewArchitecture}),void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch||o(r,{path:t+".enableMultiTouch",expected:"(boolean | undefined)",value:e.enableMultiTouch}),void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList||o(r,{path:t+".enableNativeList",expected:"(boolean | undefined)",value:e.enableNativeList}),void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture||o(r,{path:t+".enableNewGesture",expected:"(boolean | undefined)",value:e.enableNewGesture}),void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver||o(r,{path:t+".enableNewIntersectionObserver",expected:"(boolean | undefined)",value:e.enableNewIntersectionObserver}),void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin||o(r,{path:t+".enableNewTransformOrigin",expected:"(boolean | undefined)",value:e.enableNewTransformOrigin}),void 0===e.enableParseIntFlex||"boolean"==typeof e.enableParseIntFlex||o(r,{path:t+".enableParseIntFlex",expected:"(boolean | undefined)",value:e.enableParseIntFlex}),void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle||o(r,{path:t+".enableReloadLifecycle",expected:"(boolean | undefined)",value:e.enableReloadLifecycle}),void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap||o(r,{path:t+".enableSimultaneousTap",expected:"(boolean | undefined)",value:e.enableSimultaneousTap}),void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow||o(r,{path:t+".enableTextOverflow",expected:"(boolean | undefined)",value:e.enableTextOverflow}),void 0===e.enableTransformedTouchPosition||"boolean"==typeof e.enableTransformedTouchPosition||o(r,{path:t+".enableTransformedTouchPosition",expected:"(boolean | undefined)",value:e.enableTransformedTouchPosition}),void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp||o(r,{path:t+".fontScaleEffectiveOnlyOnSp",expected:"(boolean | undefined)",value:e.fontScaleEffectiveOnlyOnSp}),void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding||o(r,{path:t+".includeFontPadding",expected:"(boolean | undefined)",value:e.includeFontPadding}),void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight||o(r,{path:t+".keyboardCallbackPassRelativeHeight",expected:"(boolean | undefined)",value:e.keyboardCallbackPassRelativeHeight}),void 0===e.longPressDuration||"number"==typeof e.longPressDuration||o(r,{path:t+".longPressDuration",expected:"(number | undefined)",value:e.longPressDuration}),void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope||o(r,{path:t+".removeDescendantSelectorScope",expected:"(boolean | undefined)",value:e.removeDescendantSelectorScope}),void 0===e.tapSlop||"string"==typeof e.tapSlop||o(r,{path:t+".tapSlop",expected:"(string | undefined)",value:e.tapSlop}),void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior||o(r,{path:t+".unifyVWVHBehavior",expected:"(boolean | undefined)",value:e.unifyVWVHBehavior}),0===Object.keys(e).length||!1===r||Object.keys(e).map(n=>{let i;if(["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableListNewArchitecture","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(e=>n===e))return!0;let a=e[n];if(void 0===a)return!0;return o(r,{path:t+(!1===rJ(i=n)&&/^[a-zA-Z_$][a-zA-Z_$0-9]*$/g.test(i)?`.${n}`:`[${JSON.stringify(n)}]`),expected:"undefined",value:a,description:`The property \`${n}\` is not defined in the object type.
146
-
147
- Please remove the property next time.`})}).every(e=>e)].every(e=>e))(e,t+"",!0)||o(!0,{path:t+"",expected:"Config",value:e}))(e,"$input",!0);let r=0===i.length;return r?{success:r,data:e}:{success:r,errors:i,data:e}}return{success:!0,data:e}},{"~standard":{version:1,vendor:"typia",validate:e=>{let t=a(e);return t.success?{value:t.data}:{issues:t.errors.map(e=>({message:`expected ${e.expected}, got ${e.value}`,path:(e=>{if(!e.startsWith("$input"))throw Error(`Invalid path: ${JSON.stringify(e)}`);let t=[],r="",n=eF.Start,i=5;for(;i<e.length-1;){let o=e[++i];if(n===eF.Property?"."===o||"["===o?(t.push({key:r}),n=eF.Start):i===e.length-1?(r+=o,t.push({key:r}),i++,n=eF.Start):r+=o:n===eF.StringKey?'"'===o?(t.push({key:JSON.parse(r+o)}),i+=2,n=eF.Start):"\\"===o?(r+=e[i],r+=e[++i]):r+=o:n===eF.NumberKey&&("]"===o?(t.push({key:Number.parseInt(r)}),i++,n=eF.Start):r+=o),n===eF.Start&&i<e.length-1){let t=e[i];if(r="","["===t)'"'===e[i+1]?(n=eF.StringKey,i++,r='"'):n=eF.NumberKey;else if("."===t)n=eF.Property;else throw Error("Unreachable: pointer points invalid character")}}if(n!==eF.Start)throw Error(`Failed to parse path: ${JSON.stringify(e)}`);return t})(e.path)}))}}}});function rZ(e){let t=rX(e);if(t.success)return t.data;throw Error(["[pluginLynxConfig] Invalid configuration.",""].concat(t.errors.flatMap(({expected:e,path:t,value:r})=>{var n;return"undefined"===e?[` Unsupported configuration: \`${rY().red(t)}\``,""]:[`Invalid config on \`${rY().red(t)}\`.`,` - Expect to be ${rY().green(e)}`,` - Got: ${rY().red((n=r,Object.prototype.toString.call(n).replace(/^\[object\s+([a-z]+)\]$/i,"$1").toLowerCase()))}`,""]})).join("\n"))}let rQ={"lynx:react":"@lynx-js/react-rsbuild-plugin"};function r0(e){return e?.type==="Identifier"}function r1(e){return e?.type==="StringLiteral"}function r3(e){return e?.type==="NumericLiteral"}function r2(e){return e?.type==="BooleanLiteral"}function r4(e){return e?.type==="ObjectExpression"}function r5(e){return e?.type==="ArrayExpression"}function r9(e){return e?.type==="KeyValueProperty"}let r8=e=>{if(r4(e)){let t={};for(let r of e.properties){if(r?.type==="SpreadElement"||!r9(r))return null;let{key:e,value:n}=r;if(!r0(e)&&!r1(e))return null;let i=e.value;r4(n)||r5(n)?t[i]=r8(n):r1(n)||r3(n)||r2(n)?t[i]=n.value:r0(n)&&(t[i]=n)}return t}if(r5(e)){let t=[];for(let r of e.elements){if(!r||r.spread)return null;let e=r.expression;r4(e)||r5(e)?t.push(r8(e)):r1(e)||r3(e)||r2(e)?t.push(e.value):r0(e)&&t.push(e)}return t}},r7=f("../../../node_modules/.pnpm/@swc+core@1.15.11_@swc+helpers@0.5.23/node_modules/@swc/core/index.js");function r6(e,t,r){let{widgets:n,pages:i,collector:o,define:a,onDeprecatedAIMeta:s}=r,l=i[t],d=n[t],p=e;return(l||d)&&(a&&Object.keys(a).length>0&&(p=Object.keys(a).reduce((e,t)=>{let r=a[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`Define value ${t} is not a string`)},e)),ed((0,r7.parseSync)(p,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(r0(e.callee)&&["defineWidget","definePage"].includes(e.callee.value)){let r=e.arguments[0]?.expression;if(r4(r)){for(let e of r.properties)if(r9(e)&&r0(e.key)&&"aiMeta"===e.key.value){let r=r8(e.value);if(!r)continue;l?(s?.({kind:"page",entryName:l,filename:t}),o.addPageMeta(l,r)):d&&(s?.({kind:"widget",entryName:d,filename:t}),o.addWidgetMeta(d,r))}}}r0(e.callee)&&e.callee.value in z&&(d&&o.addWidgetMeta(d,z[e.callee.value]),l&&o.addPageMeta(l,z[e.callee.value]))}})),e}let ne=/[/\\]/;function nt(e,t){t.forEach(([t,{id:r}])=>{if(r&&ne.test(r))throw Error(`Invalid ${e} id "${r}" for "${t}": a ${e} id cannot contain a path separator. Set an "id" without one in src/app.config.ts, or drop it to derive the id from the entry.`)})}async function nr({pages:e,widgets:t,entries:r,collector:n,normalizedAppConfig:i,define:o}){let a=new tK,s=new Set,l={collector:a,widgets:Object.fromEntries(Object.entries(t).map(([e,t])=>[t.filename,e])),pages:Object.fromEntries(Object.entries(e).map(([e,t])=>[t.filename,e])),define:o,onDeprecatedAIMeta({kind:e,entryName:t,filename:r}){let n=`${e}:${t}:${r}`;s.has(n)||(s.add(n),tC.warn(`define${"page"===e?"Page":"Widget"}({ aiMeta }) is deprecated for ${t}. Configure this ${e} metadata in src/app.config.ts instead. Source: ${r}`))}},d=i.pages.entries,p=i.widgets.entries;await Promise.all(Object.values({...t,...e}).filter(({filename:e})=>/\.(ts|tsx|jsx|js)$/i.test(e)).map(({filename:e,isVirtualFile:t})=>{if(t){let t=l.widgets[e]??l.pages[e],n=r[t];return n?r6(n.toString(),e,l):void tC.warn("Cannot find virtual file",{file:t})}return r6(t5.readFileSync(e,"utf-8"),e,l)})).catch(e=>{tC.error("Failed to collect view metadata",{error:e})});let c=a.getData(),u=z.defineLoginPage,h=rr("",u.path),m=Object.entries(e).map(([e,t])=>{let r=c.pages[e],{web:n,...i}=d[e]??{},o=r?.path,a=t.isLoginPage||void 0!==o&&rr(e,o)===h;return[e,{id:rt(e,t.folderName),...r,...i,...a?u:{},path:rr(e,a?u.path:t.isSpecial?o:void 0)}]}),f=[...new Set([...m.filter(([,e])=>e.path===h).map(([e])=>e),...m.filter(([,e])=>e.id===u.id).map(([e])=>e)])];if(f.length>1)throw Error(`Only one login page is allowed: ${f.join(", ")}`);nt("page",m),m.forEach(([e,t])=>{n.addPageMeta(e,t)});let g=Object.entries(t).map(([e,t])=>{let{web:r,...n}=p[e]??{};return[e,{id:rt(e,t.folderName),...c.widgets[e],...n}]});nt("widget",g),function(e){let t=new Map;e.forEach(([e,{id:r}])=>{if(!r)return;let n=t.get(r)??[];n.push(e),t.set(r,n)});let r=[...t].filter(([,e])=>e.length>1);if(0===r.length)return;let n=r.map(([e,t])=>`Duplicate widget id "${e}" is used by:
142
+ `:""),i},{})}let t7=f("module"),t6="doubao:plugin:taro";class re extends t8{toString(){return this.contents.join("\n").trim()}}async function rt({config:e,pluginSystem:t}){let r=e.context.environment;await t.callWorkerHooks("modifyEnvironment",{environment:r}),e.context.setEnvironment(r);let{entry:n}=await t.callWorkerHooks("modifyEntryOption",{entry:{app:new re(`.${t_.sep}app.js`,"")}});return{entry:n}}let rr=e=>void 0!==process.env[e],rn=()=>rr("DISABLE_EXTERNAL")||"1"===process.env.ENABLE_SELF_CONTAINED||rr("LEGACY_FRAMEWORK"),ri=()=>rr("DISABLE_APP_TEMPLATE_JS")||rr("LEGACY_FRAMEWORK");function rs({mcpEndpoint:e}={}){let t=e?.trim();return t||(process.env.DOUBAO_SIMULATOR_MCP_ENDPOINT?.trim()??"")}async function ro({compiler:e,compilation:t,assets:r,metadata:n,resolveAppInfo:i,resolveVersionTag:s,isNative:o,shouldInjectAsset:a}){var l;let c,p=Object.keys(r).reduce((e,r)=>{if(!a(r))return e;let n=t.getAsset(r);return n&&e.push(n),e},[]);if(0===p.length)return;let d=n.app,u=await i?.(),m=(l=s?.(),c=`globalThis.__AI_MANIFEST__ = ${JSON.stringify({package:u?.appKey||d.appId,appId:u?.appKey||d.appId,name:u?.appName||d.name,icons:u?.iconUrl?tx(u.iconUrl):d.icons})};
143
+ `,l?`${c}globalThis.__VERSION_TAG__ = ${JSON.stringify(l)};
144
+ `:c),h=new Map;if(o){let{pages:e,widgets:r}=n.getData();for(let[n,i]of t.entrypoints){let t="app"===n?{type:"app",key:n}:n===e5?{type:"client_tool",key:n}:e[n]?{type:"page",key:n,id:e[n].path}:r[n]?{type:"widget",key:n,id:r[n].id}:void 0;if(!t)continue;let s=`try {
145
+ const key = Symbol.for('doubao-apps.runtime-error-state');
146
+ const state = globalThis[key] || (globalThis[key] = {});
147
+ state.entry = Object.freeze(${JSON.stringify(t)});
148
+ } catch {}
149
+ `;for(let e of i.getEntrypointChunk().files)h.set(e,s)}}p.forEach(r=>{let n=m+(h.get(r.name)??"");if(r.source.source().toString().startsWith(n))return;let i=new e.webpack.sources.ReplaceSource(r.source,r.name);i.insert(0,n),t.updateAsset(r.name,i,r.info)})}function ra(e){let t=t_.posix.basename(e);return"background.js"===t||"main-thread.js"===t||/^background\.[^/]+\.js$/.test(t)||/^main-thread\.[^/]+\.js$/.test(t)}function rl(e){let t=e.replaceAll("\\","/");return t.split("/").some(e=>e.startsWith("__doubao_web__"))&&ra(t)}class rc{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(rc.name,t=>{t.hooks.processAssets.tapPromise({name:rc.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{await ro({compiler:e,compilation:t,assets:r,...this.options})})})}}let rp="index.web.bundle",rd="base/app.web.bundle",ru="base/client-tool/index.web.bundle";function rm(e){return`__doubao_web__${e.replaceAll("\\","/").replaceAll("/","__")}`}function rh(e,t,r){return t[r]?.id??tK(r,e[r]?.folderName)}function rf(e){return!!e?.internal}function rg(e={},t={},r="configured"){return"all"===r?e:function(e={},t={}){return Object.fromEntries(Object.entries(e).filter(([e,r])=>rf(r)||!!t[e]?.web))}(e,t)}class ry{apply(e){e.hooks.thisCompilation.tap(ry.name,t=>{t.hooks.processAssets.tapPromise({name:ry.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{let r=rb(t,"app"),n=r?t.getAsset(r):void 0;if(!r||!n)throw Error("未生成 Worker 入口产物");await r_(t,e,r,rd);let i=rb(t,e5);i&&await r_(t,e,i,ru)})})}}function rb(e,t){let r=e.entrypoints.get(t)?.getEntrypointChunk();return[...r?.files??[]].find(t=>t.endsWith(".js")&&!e.getAsset(t)?.info?.hotModuleReplacement)}async function r_(e,t,r,n){let i=e.getAsset(r);if(!i)throw Error(`未生成 Worker 入口产物:${r}`);e.emitAsset(n,new t.webpack.sources.RawSource(await rv(i.source.source().toString())));let s=e.getAsset(`${r}.map`);s&&e.emitAsset(`${n}.map`,s.source,s.info),e.deleteAsset(r)}async function rv(e){let{encode:t}=await import("./@lynx-js/web-core.js");return Buffer.from(t({styleInfo:{},manifest:{"/app-service.js":e},cardType:"react",appType:"card",pageConfig:{enableCSSSelector:!0,enableFiberArch:!0,useLepusNG:!0,enableReuseContext:!0,bundleModuleMode:"ReturnByFunction",targetSdkVersion:"3.2"},lepusCode:{root:"void 0;"},customSections:{},elementTemplates:{}}))}class rE{options;isNative;constructor(e,t){this.options=e,this.isNative=t}apply(e){new e.webpack.experiments.VirtualModulesPlugin({[eK]:"",[eY]:eX,...Object.fromEntries(Object.entries(this.options.entry).map(([,e])=>[e.filename,e.toString()]))}).apply(e),e.hooks.make.tapPromise(rE.name,async()=>{await this.options.pluginSystem.callWorkerHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(rE.name,t=>{t.hooks.optimizeTree.tapPromise(rE.name,async()=>{await this.options.pluginSystem.callWorkerHooks("build",{metadata:this.options.context.metadata,fileDependencies:t.fileDependencies})}),t.hooks.processAssets.tapPromise({name:rE.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{var n,i,s;let o,a=rb(t,"app");if(!a||!t.getAsset(a))throw Error("未生成 Worker 入口产物");this.isNative&&(n=t,i=this.options.context,s=a,i.setAppAssetPath(s),o=`${s}.map`,n.getAsset(o)&&i.setAppMapAssetPath(o));let l=rb(t,e5);await ro({compiler:e,compilation:t,assets:r,metadata:this.options.context.metadata,resolveAppInfo:()=>this.options.context.resolveAppInfo(),resolveVersionTag:()=>this.options.context.versionTag,isNative:this.isNative,shouldInjectAsset:e=>e===a||e===l})})}),e.hooks.done.tapPromise(rE.name,async e=>{await this.options.pluginSystem.callWorkerHooks("afterBuild",{stats:e})})}}let rw=f("node:os"),rS=f("process"),rx=f("../../../node_modules/.pnpm/@lynx-js+type-config@4.2.0/node_modules/@lynx-js/type-config/index.js");var rA={},rT={};function rI(e){var t=rT[e];if(void 0!==t)return t.exports;var r=rT[e]={exports:{}};return rA[e](r,r.exports,rI),r.exports}rI.m=rA,rI.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return rI.d(t,{a:t}),t},rI.d=(e,t,r)=>{var n=(t,r)=>{for(var n in t)rI.o(t,n)&&!rI.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[r]:t[n]})};n(t,"get"),n(r,"value")},rI.add=function(e){Object.assign(rI.m,e)},rI.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),rI.add({"../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js"(e){e.exports=function(e){return null!=e&&"object"==typeof e&&!1===Array.isArray(e)}},"../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js"(e,t,r){var n=r("../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js");e.exports=function(e,t){if(!n(e)&&"function"!=typeof e)return{};var r={};if("string"==typeof t)return t in e&&(r[t]=e[t]),r;for(var i=t.length,s=-1;++s<i;){var o=t[s];o in e&&(r[o]=e[o])}return r}},"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(e){let t=rS||{},r=t.argv||[],n=t.env||{},i=!(n.NO_COLOR||r.includes("--no-color"))&&(!!n.FORCE_COLOR||r.includes("--color")||"win32"===t.platform||(t.stdout||{}).isTTY&&"dumb"!==n.TERM||!!n.CI),s=(e,t,r=e)=>n=>{let i=""+n,s=i.indexOf(t,e.length);return~s?e+o(i,t,r,s)+t:e+i+t},o=(e,t,r,n)=>{let i="",s=0;do i+=e.substring(s,n)+r,s=n+t.length,n=e.indexOf(t,s);while(~n);return i+e.substring(s)},a=(e=i)=>{let t=e?s:()=>String;return{isColorSupported:e,reset:t("\x1b[0m","\x1b[0m"),bold:t("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:t("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:t("\x1b[3m","\x1b[23m"),underline:t("\x1b[4m","\x1b[24m"),inverse:t("\x1b[7m","\x1b[27m"),hidden:t("\x1b[8m","\x1b[28m"),strikethrough:t("\x1b[9m","\x1b[29m"),black:t("\x1b[30m","\x1b[39m"),red:t("\x1b[31m","\x1b[39m"),green:t("\x1b[32m","\x1b[39m"),yellow:t("\x1b[33m","\x1b[39m"),blue:t("\x1b[34m","\x1b[39m"),magenta:t("\x1b[35m","\x1b[39m"),cyan:t("\x1b[36m","\x1b[39m"),white:t("\x1b[37m","\x1b[39m"),gray:t("\x1b[90m","\x1b[39m"),bgBlack:t("\x1b[40m","\x1b[49m"),bgRed:t("\x1b[41m","\x1b[49m"),bgGreen:t("\x1b[42m","\x1b[49m"),bgYellow:t("\x1b[43m","\x1b[49m"),bgBlue:t("\x1b[44m","\x1b[49m"),bgMagenta:t("\x1b[45m","\x1b[49m"),bgCyan:t("\x1b[46m","\x1b[49m"),bgWhite:t("\x1b[47m","\x1b[49m"),blackBright:t("\x1b[90m","\x1b[39m"),redBright:t("\x1b[91m","\x1b[39m"),greenBright:t("\x1b[92m","\x1b[39m"),yellowBright:t("\x1b[93m","\x1b[39m"),blueBright:t("\x1b[94m","\x1b[39m"),magentaBright:t("\x1b[95m","\x1b[39m"),cyanBright:t("\x1b[96m","\x1b[39m"),whiteBright:t("\x1b[97m","\x1b[39m"),bgBlackBright:t("\x1b[100m","\x1b[49m"),bgRedBright:t("\x1b[101m","\x1b[49m"),bgGreenBright:t("\x1b[102m","\x1b[49m"),bgYellowBright:t("\x1b[103m","\x1b[49m"),bgBlueBright:t("\x1b[104m","\x1b[49m"),bgMagentaBright:t("\x1b[105m","\x1b[49m"),bgCyanBright:t("\x1b[106m","\x1b[49m"),bgWhiteBright:t("\x1b[107m","\x1b[49m")}};e.exports=a(),e.exports.createColors=a}});let rO=globalThis.window?.document!==void 0;globalThis.process?.versions?.node,globalThis.process?.versions?.bun,globalThis.Deno?.version?.deno,globalThis.process?.versions?.electron,globalThis.navigator?.userAgent?.includes("jsdom");let rP=globalThis.navigator?.userAgentData?.platform;function rC(e,t=globalThis.Deno?globalThis.Deno.args:w.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}"macOS"===rP||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform,"Windows"===rP||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform,"Linux"===rP||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform,"iOS"===rP||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),"Android"===rP||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform,rO||w.env.TERM_PROGRAM,rO||w.platform,rO||w.cwd;let{env:rR}=w;function r$(e,r={}){var n;return 0!==(n=function(e,{streamIsTTY:r,sniffFlags:n=!0}={}){let i=function(){if(!("FORCE_COLOR"in rR))return;if("true"===rR.FORCE_COLOR)return 1;if("false"===rR.FORCE_COLOR)return 0;if(0===rR.FORCE_COLOR.length)return 1;let e=Math.min(Number.parseInt(rR.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}();void 0!==i&&(t=i);let s=n?t:i;if(0===s)return 0;if(n){if(rC("color=16m")||rC("color=full")||rC("color=truecolor"))return 3;if(rC("color=256"))return 2}if("TF_BUILD"in rR&&"AGENT_NAME"in rR)return 1;if(e&&!r&&void 0===s)return 0;let o=s||0;if("dumb"===rR.TERM)return o;if("win32"===w.platform){let e=rw.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in rR)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in rR)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in rR)||"codeship"===rR.CI_NAME?1:o;if("TEAMCITY_VERSION"in rR)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(rR.TEAMCITY_VERSION);if("truecolor"===rR.COLORTERM||"xterm-kitty"===rR.TERM||"xterm-ghostty"===rR.TERM||"wezterm"===rR.TERM)return 3;if("TERM_PROGRAM"in rR){let e=Number.parseInt((rR.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(rR.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(rR.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(rR.TERM)||"COLORTERM"in rR?1:o}(e,{streamIsTTY:e&&e.isTTY,...r}))&&{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function rk(e,t=rS.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}function rN(e=""){if(/^\d{3,4}$/.test(e)){let t=/(\d{1,2})(\d{2})/.exec(e)??[];return{major:0,minor:Number.parseInt(t[1],10),patch:Number.parseInt(t[2],10)}}let t=(e??"").split(".").map(e=>Number.parseInt(e,10));return{major:t[0],minor:t[1],patch:t[2]}}function rL(e){let{CI:t,CURSOR_TRACE_ID:r,FORCE_HYPERLINK:n,NETLIFY:i,TEAMCITY_VERSION:s,TERM_PROGRAM:o,TERM_PROGRAM_VERSION:a,VTE_VERSION:l,TERM:c}=w.env;if(n)return!(n.length>0&&0===Number.parseInt(n,10));if(rk("no-hyperlink")||rk("no-hyperlinks")||rk("hyperlink=false")||rk("hyperlink=never"))return!1;if(rk("hyperlink=true")||rk("hyperlink=always")||i)return!0;if(!r$(e)||e&&!e.isTTY)return!1;if("WT_SESSION"in w.env)return!0;if("win32"===w.platform||t||s)return!1;if(o){let e=rN(a);switch(o){case"iTerm.app":if(3===e.major)return e.minor>=1;return e.major>3;case"WezTerm":if(/^0-unstable-\d{4}-\d{2}-\d{2}$/.test(a))return a.slice(11)>="2020-06-20";return e.major>=0x1343cac;case"vscode":if(r)return!0;return e.major>1||1===e.major&&e.minor>=72;case"ghostty":case"zed":case"Orca":return!0}}if(l){if("0.50.0"===l)return!1;let e=rN(l);return e.major>0||e.minor>=50}switch(c){case"alacritty":case"xterm-kitty":return!0}return!1}rC("no-color")||rC("no-colors")||rC("color=false")||rC("color=never")?t=0:(rC("color")||rC("colors")||rC("color=true")||rC("color=always"))&&(t=1),r$({isTTY:b.isatty(1)}),r$({isTTY:b.isatty(2)});let rD={stdout:rL(w.stdout),stderr:rL(w.stderr)};function rj(e,t,{target:r="stdout",...n}={}){return rD[r]?["\x1b]","8",";",";",t,"\x07",e,"\x1b]","8",";",";","\x07"].join(""):!1===n.fallback?e:"function"==typeof n.fallback?n.fallback(e,t):`${e} ${t}`}rj.isSupported=rD.stdout,rj.stderr=(e,t,r={})=>rj(e,t,{target:"stderr",...r}),rj.stderr.isSupported=rD.stderr;let rM=rI("../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js");var rU=rI.n(rM);class rB{options;constructor(e){this.options=e}name="LynxConfigWebpackPlugin";apply(e){e.hooks.thisCompilation.tap(this.name,e=>{this.options.LynxTemplatePlugin.getLynxTemplatePluginHooks(e).beforeEncode.tap(this.name,e=>{let{config:t}=this.options;return e.encodeData.compilerOptions={...e.encodeData.compilerOptions,...rU()(t,this.options.compilerOptionsKeys)},e.encodeData.sourceContent.config={...e.encodeData.sourceContent.config,...rU()(t,this.options.configKeys)},e})})}}let rF=e=>rH.has(e),rH=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"]);(eP=eU||(eU={}))[eP.Start=0]="Start",eP[eP.Property=1]="Property",eP[eP.StringKey=2]="StringKey",eP[eP.NumberKey=3]="NumberKey";let rW=rI("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");var rG=rI.n(rW);let rV=Object.assign(o=e=>{if(!1===("object"==typeof e&&null!==e&&!1===Array.isArray(e)&&((e,t=!0)=>(void 0===e.alignMouseEventWithW3C||"boolean"==typeof e.alignMouseEventWithW3C)&&(void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll)&&(void 0===e.enableA11y||"boolean"==typeof e.enableA11y)&&(void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement)&&(void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance)&&(void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables)&&(void 0===e.enableCSSRule||"boolean"==typeof e.enableCSSRule)&&(void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp)&&(void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor)&&(void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough)&&(void 0===e.enableEventThroughInheritFromPage||"boolean"==typeof e.enableEventThroughInheritFromPage)&&(void 0===e.enableFetchAPIStandardStreaming||"boolean"==typeof e.enableFetchAPIStandardStreaming)&&(void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew)&&(void 0===e.enableFlexBasisZeroPercent||"boolean"==typeof e.enableFlexBasisZeroPercent)&&(void 0===e.enableGridPlacementShorthands||"boolean"==typeof e.enableGridPlacementShorthands)&&(void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException)&&(void 0===e.enableLayoutOnlyEventThrough||"boolean"==typeof e.enableLayoutOnlyEventThrough)&&(void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture)&&(void 0===e.enableMouseDragScroll||"boolean"==typeof e.enableMouseDragScroll)&&(void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch)&&(void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList)&&(void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture)&&(void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver)&&(void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin)&&(void 0===e.enableParseIntFlex||"boolean"==typeof e.enableParseIntFlex)&&(void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle)&&(void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap)&&(void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow)&&(void 0===e.enableTransformedTouchPosition||"boolean"==typeof e.enableTransformedTouchPosition)&&(void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp)&&(void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding)&&(void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight)&&(void 0===e.longPressDuration||"number"==typeof e.longPressDuration)&&(void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope)&&(void 0===e.tapSlop||"string"==typeof e.tapSlop)&&(void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior)&&(0===Object.keys(e).length||Object.keys(e).every(t=>!!["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableEventThroughInheritFromPage","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableLayoutOnlyEventThrough","enableListNewArchitecture","enableMouseDragScroll","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(e=>t===e)||void 0===e[t])))(e,!0))){var t;t=i=[],s=(e,r)=>(e&&(e=>{if(0===t.length)return!0;let r=t[t.length-1].path;return e.length>r.length||r.substring(0,e.length)!==e})(r.path)&&(void 0===r.value&&(r.description??=`The value at this path is \`undefined\`.
150
+
151
+ Please fill the \`${r.expected}\` typed value next time.`),t.push(r)),!1),((e,t,r=!0)=>("object"==typeof e&&null!==e&&!1===Array.isArray(e)||s(!0,{path:t+"",expected:"Config",value:e}))&&((e,t,r=!0)=>[void 0===e.alignMouseEventWithW3C||"boolean"==typeof e.alignMouseEventWithW3C||s(r,{path:t+".alignMouseEventWithW3C",expected:"(boolean | undefined)",value:e.alignMouseEventWithW3C}),void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll||s(r,{path:t+".disableLongpressAfterScroll",expected:"(boolean | undefined)",value:e.disableLongpressAfterScroll}),void 0===e.enableA11y||"boolean"==typeof e.enableA11y||s(r,{path:t+".enableA11y",expected:"(boolean | undefined)",value:e.enableA11y}),void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement||s(r,{path:t+".enableAccessibilityElement",expected:"(boolean | undefined)",value:e.enableAccessibilityElement}),void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance||s(r,{path:t+".enableCSSInheritance",expected:"(boolean | undefined)",value:e.enableCSSInheritance}),void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables||s(r,{path:t+".enableCSSInlineVariables",expected:"(boolean | undefined)",value:e.enableCSSInlineVariables}),void 0===e.enableCSSRule||"boolean"==typeof e.enableCSSRule||s(r,{path:t+".enableCSSRule",expected:"(boolean | undefined)",value:e.enableCSSRule}),void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp||s(r,{path:t+".enableEndGestureAtLastFingerUp",expected:"(boolean | undefined)",value:e.enableEndGestureAtLastFingerUp}),void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor||s(r,{path:t+".enableEventHandleRefactor",expected:"(boolean | undefined)",value:e.enableEventHandleRefactor}),void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough||s(r,{path:t+".enableEventThrough",expected:"(boolean | undefined)",value:e.enableEventThrough}),void 0===e.enableEventThroughInheritFromPage||"boolean"==typeof e.enableEventThroughInheritFromPage||s(r,{path:t+".enableEventThroughInheritFromPage",expected:"(boolean | undefined)",value:e.enableEventThroughInheritFromPage}),void 0===e.enableFetchAPIStandardStreaming||"boolean"==typeof e.enableFetchAPIStandardStreaming||s(r,{path:t+".enableFetchAPIStandardStreaming",expected:"(boolean | undefined)",value:e.enableFetchAPIStandardStreaming}),void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew||s(r,{path:t+".enableFixedNew",expected:"(boolean | undefined)",value:e.enableFixedNew}),void 0===e.enableFlexBasisZeroPercent||"boolean"==typeof e.enableFlexBasisZeroPercent||s(r,{path:t+".enableFlexBasisZeroPercent",expected:"(boolean | undefined)",value:e.enableFlexBasisZeroPercent}),void 0===e.enableGridPlacementShorthands||"boolean"==typeof e.enableGridPlacementShorthands||s(r,{path:t+".enableGridPlacementShorthands",expected:"(boolean | undefined)",value:e.enableGridPlacementShorthands}),void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException||s(r,{path:t+".enableJsBindingApiThrowException",expected:"(boolean | undefined)",value:e.enableJsBindingApiThrowException}),void 0===e.enableLayoutOnlyEventThrough||"boolean"==typeof e.enableLayoutOnlyEventThrough||s(r,{path:t+".enableLayoutOnlyEventThrough",expected:"(boolean | undefined)",value:e.enableLayoutOnlyEventThrough}),void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture||s(r,{path:t+".enableListNewArchitecture",expected:"(boolean | undefined)",value:e.enableListNewArchitecture}),void 0===e.enableMouseDragScroll||"boolean"==typeof e.enableMouseDragScroll||s(r,{path:t+".enableMouseDragScroll",expected:"(boolean | undefined)",value:e.enableMouseDragScroll}),void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch||s(r,{path:t+".enableMultiTouch",expected:"(boolean | undefined)",value:e.enableMultiTouch}),void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList||s(r,{path:t+".enableNativeList",expected:"(boolean | undefined)",value:e.enableNativeList}),void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture||s(r,{path:t+".enableNewGesture",expected:"(boolean | undefined)",value:e.enableNewGesture}),void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver||s(r,{path:t+".enableNewIntersectionObserver",expected:"(boolean | undefined)",value:e.enableNewIntersectionObserver}),void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin||s(r,{path:t+".enableNewTransformOrigin",expected:"(boolean | undefined)",value:e.enableNewTransformOrigin}),void 0===e.enableParseIntFlex||"boolean"==typeof e.enableParseIntFlex||s(r,{path:t+".enableParseIntFlex",expected:"(boolean | undefined)",value:e.enableParseIntFlex}),void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle||s(r,{path:t+".enableReloadLifecycle",expected:"(boolean | undefined)",value:e.enableReloadLifecycle}),void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap||s(r,{path:t+".enableSimultaneousTap",expected:"(boolean | undefined)",value:e.enableSimultaneousTap}),void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow||s(r,{path:t+".enableTextOverflow",expected:"(boolean | undefined)",value:e.enableTextOverflow}),void 0===e.enableTransformedTouchPosition||"boolean"==typeof e.enableTransformedTouchPosition||s(r,{path:t+".enableTransformedTouchPosition",expected:"(boolean | undefined)",value:e.enableTransformedTouchPosition}),void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp||s(r,{path:t+".fontScaleEffectiveOnlyOnSp",expected:"(boolean | undefined)",value:e.fontScaleEffectiveOnlyOnSp}),void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding||s(r,{path:t+".includeFontPadding",expected:"(boolean | undefined)",value:e.includeFontPadding}),void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight||s(r,{path:t+".keyboardCallbackPassRelativeHeight",expected:"(boolean | undefined)",value:e.keyboardCallbackPassRelativeHeight}),void 0===e.longPressDuration||"number"==typeof e.longPressDuration||s(r,{path:t+".longPressDuration",expected:"(number | undefined)",value:e.longPressDuration}),void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope||s(r,{path:t+".removeDescendantSelectorScope",expected:"(boolean | undefined)",value:e.removeDescendantSelectorScope}),void 0===e.tapSlop||"string"==typeof e.tapSlop||s(r,{path:t+".tapSlop",expected:"(string | undefined)",value:e.tapSlop}),void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior||s(r,{path:t+".unifyVWVHBehavior",expected:"(boolean | undefined)",value:e.unifyVWVHBehavior}),0===Object.keys(e).length||!1===r||Object.keys(e).map(n=>{let i;if(["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableEventThroughInheritFromPage","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableLayoutOnlyEventThrough","enableListNewArchitecture","enableMouseDragScroll","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(e=>n===e))return!0;let o=e[n];if(void 0===o)return!0;return s(r,{path:t+(!1===rF(i=n)&&/^[a-zA-Z_$][a-zA-Z_$0-9]*$/g.test(i)?`.${n}`:`[${JSON.stringify(n)}]`),expected:"undefined",value:o,description:`The property \`${n}\` is not defined in the object type.
152
+
153
+ Please remove the property next time.`})}).every(e=>e)].every(e=>e))(e,t+"",!0)||s(!0,{path:t+"",expected:"Config",value:e}))(e,"$input",!0);let r=0===i.length;return r?{success:r,data:e}:{success:r,errors:i,data:e}}return{success:!0,data:e}},{"~standard":{version:1,vendor:"typia",validate:e=>{let t=o(e);return t.success?{value:t.data}:{issues:t.errors.map(e=>({message:`expected ${e.expected}, got ${e.value}`,path:(e=>{if(!e.startsWith("$input"))throw Error(`Invalid path: ${JSON.stringify(e)}`);let t=[],r="",n=eU.Start,i=5;for(;i<e.length-1;){let s=e[++i];if(n===eU.Property?"."===s||"["===s?(t.push({key:r}),n=eU.Start):i===e.length-1?(r+=s,t.push({key:r}),i++,n=eU.Start):r+=s:n===eU.StringKey?'"'===s?(t.push({key:JSON.parse(r+s)}),i+=2,n=eU.Start):"\\"===s?(r+=e[i],r+=e[++i]):r+=s:n===eU.NumberKey&&("]"===s?(t.push({key:Number.parseInt(r)}),i++,n=eU.Start):r+=s),n===eU.Start&&i<e.length-1){let t=e[i];if(r="","["===t)'"'===e[i+1]?(n=eU.StringKey,i++,r='"'):n=eU.NumberKey;else if("."===t)n=eU.Property;else throw Error("Unreachable: pointer points invalid character")}}if(n!==eU.Start)throw Error(`Failed to parse path: ${JSON.stringify(e)}`);return t})(e.path)}))}}}});function rq(e){let t=rV(e);if(t.success)return t.data;throw Error(["[pluginLynxConfig] Invalid configuration.",""].concat(t.errors.flatMap(({expected:e,path:t,value:r})=>{var n;return"undefined"===e?[` Unsupported configuration: \`${rG().red(t)}\``,""]:[`Invalid config on \`${rG().red(t)}\`.`,` - Expect to be ${rG().green(e)}`,` - Got: ${rG().red((n=r,Object.prototype.toString.call(n).replace(/^\[object\s+([a-z]+)\]$/i,"$1").toLowerCase()))}`,""]})).join("\n"))}let rJ={"lynx:react":"@lynx-js/react-rsbuild-plugin"},rz=(0,A.createRequire)(import.meta.url),rK={react:{libraryName:["ReactLynx","React"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react":{libraryName:["ReactLynx","React"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/internal":{libraryName:["ReactLynx","ReactInternal"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/jsx-dev-runtime":{libraryName:["ReactLynx","ReactJSXDevRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/jsx-runtime":{libraryName:["ReactLynx","ReactJSXRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/lepus/jsx-dev-runtime":{libraryName:["ReactLynx","ReactJSXLepusDevRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/lepus/jsx-runtime":{libraryName:["ReactLynx","ReactJSXLepusRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/experimental/lazy/import":{libraryName:["ReactLynx","ReactLazyImport"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/legacy-react-runtime":{libraryName:["ReactLynx","ReactLegacyRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/runtime-components":{libraryName:["ReactLynx","ReactComponents"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/worklet-runtime/bindings":{libraryName:["ReactLynx","ReactWorkletRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/debug":{libraryName:["ReactLynx","ReactDebug"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/refresh":{libraryName:["ReactLynx","ReactRefresh"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},preact:{libraryName:["ReactLynx","Preact"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1}};function rY(e){return e?new Map(e instanceof Map?e:Object.entries(e)):new Map}let rX=r0();function rZ(e){if(e)return!0===e?{}:e}function rQ(e){return e.replace(/^\/+/,"")}function r0(){return{reactlynx:{resolveExternals:(e,t)=>{var r,n;let i;return r=rZ(e),n=r1(t),i=r?.url?{url:r.url}:{bundlePath:r3(r,n)},Object.fromEntries(Object.entries(rK).map(([e,t])=>[e,{...t,...r?.async===void 0?{}:{async:r.async},...i}]))},resolveManagedAssets(e,t){let r=rZ(e);if(!r||r.url)return new Map;let n=r1(t);return new Map([[r3(r,n),function(e,t,r){let n="production"===process.env.NODE_ENV?"prod":"dev",i=`${t}/${n}${r?"-web":""}`;try{return rz.resolve(i,{paths:[e]})}catch{throw Error(`external-bundle-rsbuild-plugin requires \`${i}\` when \`externalsPresets.reactlynx\` is enabled. Install a compatible \`${t}\` into your devDependencies.`)}}(t.rootPath,r.reactUmdPackageName??"@lynx-js/react-umd",n)]])}}}}function r1(e){let t=e.environmentName;return void 0!==t&&"lynx"!==t&&!t.startsWith("lynx-")}class r2{assets;constructor(e){this.assets=e}apply(e){e.hooks.thisCompilation.tap(r2.name,t=>{t.hooks.processAssets.tap({name:r2.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},()=>{let{RawSource:r}=e.webpack.sources;for(let[e,n]of this.assets)if(!t.getAsset(e)){if(!(0,tV.existsSync)(n))throw Error(`external-bundle-rsbuild-plugin could not find local bundle \`${n}\` for emitted asset \`${e}\`.`);t.emitAsset(e,new r((0,tV.readFileSync)(n),!1))}})})}}function r3(e,t){return e?.bundlePath?rQ(e.bundlePath):t?"react.web.bundle":"react.lynx.bundle"}function r4(e,t){return"string"!=typeof t?t:{bundlePath:t,libraryName:e,background:{sectionPath:e},mainThread:{sectionPath:`${e}__main-thread`},async:!0}}function r5(e){return{name:"lynx:external-bundle",setup(t){let r,n=function(e){let t={...r0()};for(let[r,n]of Object.entries(e??{})){let e=rX[r];t[r]=e?function(e,t){return{extends:[...e.extends?Array.isArray(e.extends)?e.extends:[e.extends]:[],...t.extends?Array.isArray(t.extends)?t.extends:[t.extends]:[]],resolveExternals:(r,n)=>({...e.resolveExternals?.(r,n)??{},...t.resolveExternals?.(r,n)??{}}),resolveManagedAssets(r,n){let i=rY(e.resolveManagedAssets?.(r,n));for(let[e,s]of rY(t.resolveManagedAssets?.(r,n)))i.set(e,s);return i}}}(e,n):n}return t}(e.externalsPresetDefinitions),i=new Map;t.modifyRsbuildConfig((t,{mergeRsbuildConfig:n})=>(r=t.server?.base,void 0===e.externals&&void 0===e.externalsPresets)?t:n(t,{server:{setup:({server:e,action:t})=>{"dev"===t&&e.middlewares.use((e,t,r)=>{let n=e.url?i.get(e.url):void 0;if(n&&(0,tV.existsSync)(n)){t.setHeader("Content-Type","application/octet-stream"),t.setHeader("Access-Control-Allow-Origin","*");let e=(0,tV.createReadStream)(n);e.on("error",()=>{t.headersSent||(t.statusCode=404),t.end()}),e.pipe(t);return}r()})}}})),t.modifyRspackConfig((s,{environment:o})=>{let a=t.useExposed(Symbol.for("LAYERS"));if(!a)throw Error("external-bundle-rsbuild-plugin requires exposed `LAYERS`. Please install a DSL plugin, for example `pluginReactLynx` for ReactLynx.");let l=function(e,t,r){let n={},i=new Map;for(let[s,o]of Object.entries(e??{})){if(!o)continue;let e=function e(t,r,n,i,s){let o=n[t];if(!o)throw Error(`Unknown externals preset "${t}". Define it in \`externalsPresetDefinitions\` before enabling it in \`externalsPresets\`.`);if(i.includes(t))throw Error(`Circular externals preset dependency detected: ${[...i,t].join(" -> ")}`);let a={},l=new Map,c=[...i,t];for(let t of o.extends?Array.isArray(o.extends)?o.extends:[o.extends]:[]){let r=e(t,!0,n,c,s);for(let[e,t]of(Object.assign(a,r.externals),r.managedAssets))l.set(e,t)}for(let[e,t]of(Object.assign(a,o.resolveExternals?.(r,s)??{}),rY(o.resolveManagedAssets?.(r,s))))l.set(e,t);return{externals:a,managedAssets:l}}(s,o,t,[],r);for(let[t,r]of(Object.assign(n,e.externals),e.managedAssets))i.set(t,r)}return{externals:n,managedAssets:i}}(e.externalsPresets,n,{rootPath:t.context.rootPath,environmentName:o.name}),c=function(e){if(!e)return{};for(let[t,r]of Object.entries(e)){let e=r4(t,r);if(!e.url&&!e.bundlePath)throw Error(`external-bundle-rsbuild-plugin requires \`url\` or \`bundlePath\` for external "${t}".`)}return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,r4(e,t)]))}(e.externals),p={...l.externals,...c},d=function(e,t,r){let n=new Map(t),i=t_.resolve(r.context.rootPath,e.externalBundleRoot??"dist-external-bundle");for(let[t,r]of Object.entries(e.externals??{})){let e=r4(t,r);!e.url&&e.bundlePath&&n.set(rQ(e.bundlePath),t_.resolve(i,rQ(e.bundlePath)))}return n}(e,l.managedAssets,t);for(let[e,t]of d)i.set(function(e,t){let r=e??"/",n=rQ(t);if("/"===r)return`/${n}`;if(/^[a-z][a-z\d+\-.]*:/i.test(r))try{return new URL(n,r).toString()}catch{}return`${r.replace(/\/$/,"")}/${n}`}(r,e),t);return s.plugins=s.plugins||[],d.size>0&&s.plugins.push(new r2(d)),s.plugins.push(new M({backgroundLayer:a.BACKGROUND,mainThreadLayer:a.MAIN_THREAD,externals:p,globalObject:e.globalObject,timeout:e.timeout,retries:e.retries})),s})}}}var r8={},r9={};function r7(e){var t=r9[e];if(void 0!==t)return t.exports;var r=r9[e]={exports:{}};return r8[e](r,r.exports,r7),r.exports}r7.m=r8,r7.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r7.d(t,{a:t}),t},r7.d=(e,t,r)=>{var n=(t,r)=>{for(var n in t)r7.o(t,n)&&!r7.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[r]:t[n]})};n(t,"get"),n(r,"value")},r7.add=function(e){Object.assign(r7.m,e)},r7.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r7.add({"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js"(e,t,r){let n=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"),{MAX_LENGTH:i,MAX_SAFE_INTEGER:s}=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"),{safeRe:o,t:a}=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"),l=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"),{compareIdentifiers:c}=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js");e.exports=class e{constructor(t,r){if(r=l(r),t instanceof e)if(!!r.loose===t.loose&&!!r.includePrerelease===t.includePrerelease)return t;else t=t.version;else if("string"!=typeof t)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>i)throw TypeError(`version is longer than ${i} characters`);n("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let c=t.trim().match(r.loose?o[a.LOOSE]:o[a.FULL]);if(!c)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+c[1],this.minor=+c[2],this.patch=+c[3],this.major>s||this.major<0)throw TypeError("Invalid major version");if(this.minor>s||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>s||this.patch<0)throw TypeError("Invalid patch version");c[4]?this.prerelease=c[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<s)return t}return e}):this.prerelease=[],this.build=c[5]?c[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(n("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if("string"==typeof t&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return(t instanceof e||(t=new e(t,this.options)),this.major<t.major)?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:+(this.patch>t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return -1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n("prerelease compare",r,e,i),void 0===e&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===e)return -1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n("build compare",r,e,i),void 0===e&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===e)return -1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&!1===r)throw Error("invalid increment argument: identifier is empty");if(t){let e=`-${t}`.match(this.options.loose?o[a.PRERELEASELOOSE]:o[a.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(0===this.prerelease.length)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(0!==this.minor||0!==this.patch||0===this.prerelease.length)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(0!==this.patch||0===this.prerelease.length)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{let e=+!!Number(r);if(0===this.prerelease.length)this.prerelease=[e];else{let n=this.prerelease.length;for(;--n>=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);if(-1===n){if(t===this.prerelease.join(".")&&!1===r)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let n=[t,e];!1===r&&(n=[t]),((e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let t=0;t<r.length;t++)if(0!==c(e[t],r[t]))return!1;return!0})(this.prerelease,t)?isNaN(this.prerelease[t.split(".").length])&&(this.prerelease=n):this.prerelease=n}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js"(e,t,r){let n=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js");e.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js"(e,t,r){let n=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js");e.exports=(e,t,r)=>n(e,t,r)>=0},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"(e){e.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||0x1fffffffffffff,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"(e){e.exports="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js"(e){let t=/^[0-9]+$/,r=(e,r)=>{if("number"==typeof e&&"number"==typeof r)return e===r?0:e<r?-1:1;let n=t.test(e),i=t.test(r);return n&&i&&(e*=1,r*=1),e===r?0:n&&!i?-1:i&&!n?1:e<r?-1:1};e.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"(e){let t=Object.freeze({loose:!0}),r=Object.freeze({});e.exports=e=>e?"object"!=typeof e?t:e:r},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"(e,t,r){let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:i,MAX_LENGTH:s}=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"),o=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"),a=(t=e.exports={}).re=[],l=t.safeRe=[],c=t.src=[],p=t.safeSrc=[],d=t.t={},u=0,m="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",s],[m,i]],f=(e,t,r)=>{let n=(e=>{for(let[t,r]of h)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),i=u++;o(e,i,t),d[e]=i,c[i]=t,p[i]=n,a[i]=new RegExp(t,r?"g":void 0),l[i]=new RegExp(n,r?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*"),f("NUMERICIDENTIFIERLOOSE","\\d+"),f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${m}*`),f("MAINVERSION",`(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})`),f("MAINVERSIONLOOSE",`(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASEIDENTIFIER",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIER]})`),f("PRERELEASEIDENTIFIERLOOSE",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASE",`(?:-(${c[d.PRERELEASEIDENTIFIER]}(?:\\.${c[d.PRERELEASEIDENTIFIER]})*))`),f("PRERELEASELOOSE",`(?:-?(${c[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[d.PRERELEASEIDENTIFIERLOOSE]})*))`),f("BUILDIDENTIFIER",`${m}+`),f("BUILD",`(?:\\+(${c[d.BUILDIDENTIFIER]}(?:\\.${c[d.BUILDIDENTIFIER]})*))`),f("FULLPLAIN",`v?${c[d.MAINVERSION]}${c[d.PRERELEASE]}?${c[d.BUILD]}?`),f("FULL",`^${c[d.FULLPLAIN]}$`),f("LOOSEPLAIN",`[v=\\s]*${c[d.MAINVERSIONLOOSE]}${c[d.PRERELEASELOOSE]}?${c[d.BUILD]}?`),f("LOOSE",`^${c[d.LOOSEPLAIN]}$`),f("GTLT","((?:<|>)?=?)"),f("XRANGEIDENTIFIERLOOSE",`${c[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),f("XRANGEIDENTIFIER",`${c[d.NUMERICIDENTIFIER]}|x|X|\\*`),f("XRANGEPLAIN",`[v=\\s]*(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:${c[d.PRERELEASE]})?${c[d.BUILD]}?)?)?`),f("XRANGEPLAINLOOSE",`[v=\\s]*(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:${c[d.PRERELEASELOOSE]})?${c[d.BUILD]}?)?)?`),f("XRANGE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAIN]}$`),f("XRANGELOOSE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAINLOOSE]}$`),f("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),f("COERCE",`${c[d.COERCEPLAIN]}(?:$|[^\\d])`),f("COERCEFULL",c[d.COERCEPLAIN]+`(?:${c[d.PRERELEASE]})?`+`(?:${c[d.BUILD]})?`+"(?:$|[^\\d])"),f("COERCERTL",c[d.COERCE],!0),f("COERCERTLFULL",c[d.COERCEFULL],!0),f("LONETILDE","(?:~>?)"),f("TILDETRIM",`(\\s*)${c[d.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",f("TILDE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAIN]}$`),f("TILDELOOSE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAINLOOSE]}$`),f("LONECARET","(?:\\^)"),f("CARETTRIM",`(\\s*)${c[d.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",f("CARET",`^${c[d.LONECARET]}${c[d.XRANGEPLAIN]}$`),f("CARETLOOSE",`^${c[d.LONECARET]}${c[d.XRANGEPLAINLOOSE]}$`),f("COMPARATORLOOSE",`^${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]})$|^$`),f("COMPARATOR",`^${c[d.GTLT]}\\s*(${c[d.FULLPLAIN]})$|^$`),f("COMPARATORTRIM",`(\\s*)${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]}|${c[d.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",f("HYPHENRANGE",`^\\s*(${c[d.XRANGEPLAIN]})\\s+-\\s+(${c[d.XRANGEPLAIN]})\\s*$`),f("HYPHENRANGELOOSE",`^\\s*(${c[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[d.XRANGEPLAINLOOSE]})\\s*$`),f("STAR","(<|>)?=?\\s*\\*"),f("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),f("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}});let r6=r7("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js");var ne=r7.n(r6);let nt=Symbol.for("@lynx-js/plugin-react-alias");function nr(e,t,r){let n,i,{ResolverFactory:s}=e.experiments.resolver;return async e=>{if(n||(n={}),void 0===n[e]){if(!i){let e=new s({conditionNames:r,enablePnp:!!process.versions.pnp});i=(t,r)=>e.sync(t,r)}let o=i(t,e);if(o.error)throw Error(o.error);if(!o.path)throw Error(`Failed to resolve ${e}`);n[e]=o.path}return n[e]}}function nn(e){return e?.type==="Identifier"}function ni(e){return e?.type==="StringLiteral"}function ns(e){return e?.type==="NumericLiteral"}function no(e){return e?.type==="BooleanLiteral"}function na(e){return e?.type==="ObjectExpression"}function nl(e){return e?.type==="ArrayExpression"}function nc(e){return e?.type==="KeyValueProperty"}let np=e=>{if(na(e)){let t={};for(let r of e.properties){if(r?.type==="SpreadElement"||!nc(r))return null;let{key:e,value:n}=r;if(!nn(e)&&!ni(e))return null;let i=e.value;na(n)||nl(n)?t[i]=np(n):ni(n)||ns(n)||no(n)?t[i]=n.value:nn(n)&&(t[i]=n)}return t}if(nl(e)){let t=[];for(let r of e.elements){if(!r||r.spread)return null;let e=r.expression;na(e)||nl(e)?t.push(np(e)):ni(e)||ns(e)||no(e)?t.push(e.value):nn(e)&&t.push(e)}return t}},nd=f("../../../node_modules/.pnpm/@swc+core@1.15.11_@swc+helpers@0.5.23/node_modules/@swc/core/index.js");function nu(e,t,r){let{widgets:n,pages:i,collector:s,define:o,onDeprecatedAIMeta:a}=r,l=i[t],c=n[t],p=e;return(l||c)&&(o&&Object.keys(o).length>0&&(p=Object.keys(o).reduce((e,t)=>{let r=o[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`define 配置项 ${t} 的值必须是字符串`)},e)),el((0,nd.parseSync)(p,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(nn(e.callee)&&["defineWidget","definePage"].includes(e.callee.value)){let r=e.arguments[0]?.expression;if(na(r)){for(let e of r.properties)if(nc(e)&&nn(e.key)&&"aiMeta"===e.key.value){let r=np(e.value);if(!r)continue;l?(a?.({kind:"page",entryName:l,filename:t}),s.addPageMeta(l,r)):c&&(a?.({kind:"widget",entryName:c,filename:t}),s.addWidgetMeta(c,r))}}}nn(e.callee)&&e.callee.value in R&&(c&&s.addWidgetMeta(c,R[e.callee.value]),l&&s.addPageMeta(l,R[e.callee.value]))}})),e}let nm=/[/\\]/;function nh(e,t){t.forEach(([t,{id:r}])=>{if(r&&nm.test(r))throw Error(`入口 "${t}" 的 ${e} id "${r}" 无效:id 不能包含路径分隔符。请在 src/app.config.ts 中设置不含路径分隔符的 "id",或删除该配置以根据入口自动生成 id。`)})}async function nf({pages:e,widgets:t,entries:r,collector:n,normalizedAppConfig:i,define:s}){let o=new tR,a=new Set,l={collector:o,widgets:Object.fromEntries(Object.entries(t).map(([e,t])=>[t.filename,e])),pages:Object.fromEntries(Object.entries(e).map(([e,t])=>[t.filename,e])),define:s,onDeprecatedAIMeta({kind:e,entryName:t,filename:r}){let n=`${e}:${t}:${r}`;a.has(n)||(a.add(n),tp.warn(`define${"page"===e?"Page":"Widget"}({ aiMeta }) 已弃用,入口:${t}。请改为在 src/app.config.ts 中配置该 ${e} 的元数据。源文件:${r}`))}},c=i.pages.entries,p=i.widgets.entries;await Promise.all(Object.values({...t,...e}).filter(({filename:e})=>/\.(ts|tsx|jsx|js)$/i.test(e)).map(({filename:e,isVirtualFile:t})=>{if(t){let t=l.widgets[e]??l.pages[e],n=r[t];return n?nu(n.toString(),e,l):void tp.warn("未找到虚拟文件",{file:t})}return nu(tV.readFileSync(e,"utf-8"),e,l)})).catch(e=>{tp.error("收集视图元数据失败",{error:e})});let d=o.getData(),u=R.defineLoginPage,m=tY("",u.path),h=Object.entries(e).map(([e,t])=>{let r=d.pages[e],{web:n,...i}=c[e]??{},s=r?.path,o=t.isLoginPage||void 0!==s&&tY(e,s)===m;return[e,{id:tK(e,t.folderName),...r,...i,...o?u:{},path:tY(e,o?u.path:t.isSpecial?s:void 0)}]}),f=[...new Set([...h.filter(([,e])=>e.path===m).map(([e])=>e),...h.filter(([,e])=>e.id===u.id).map(([e])=>e)])];if(f.length>1)throw Error(`只允许配置一个登录页面:${f.join(", ")}`);nh("page",h),h.forEach(([e,t])=>{n.addPageMeta(e,t)});let g=Object.entries(t).map(([e,t])=>{let{web:r,...n}=p[e]??{};return[e,{id:tK(e,t.folderName),...d.widgets[e],...n}]});nh("widget",g),function(e){let t=new Map;e.forEach(([e,{id:r}])=>{if(!r)return;let n=t.get(r)??[];n.push(e),t.set(r,n)});let r=[...t].filter(([,e])=>e.length>1);if(0===r.length)return;let n=r.map(([e,t])=>`重复的 widget id "${e}" 被以下入口使用:
148
154
  ${t.map(e=>`- ${e}`).join("\n")}`).join("\n\n");throw Error(`${n}
149
155
 
150
- Widget IDs must be globally unique. Configure distinct "id" values in src/app.config.ts.`)}(g),g.forEach(([e,t])=>{n.addWidgetMeta(e,t)})}let nn=f("os"),ni=`base/${e8}`;async function no({encryption:e}){let t=t5.mkdtempSync(eX.join(nn.tmpdir(),"doubao-keystore-")),r=eX.join(t,e8);try{let{generateKeystore:t}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),n=await t(r,{encryption:e});if(0!==n.status)throw Error(n.error_msg);return t5.readFileSync(r)}finally{t5.rmSync(t,{recursive:!0,force:!0})}}let na=f("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40_debug@4.4.3/node_modules/@byted-lynx/tasm/index.js");class ns{options;isGenerateKeystore=!1;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(ns.name,t=>{t.hooks.processAssets.tapPromise({name:ns.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH},async()=>{let r=Date.now();try{let{RawSource:r}=e.webpack.sources,n=this.options.getAppAssetPath(),i=rx(t,e6);for(let e of[n,i].filter(e=>!!e)){let i=t.getAsset(e);if(!i)throw Error(`Worker entry asset was not emitted: ${e}`);let{buffer:o,encodeOptions:a,keystoreContent:s}=await this.encode([i]);if(t.updateAsset(e,new r(o,!1)),s){let e=new r(s,!1);t.getAsset(ni)?t.updateAsset(ni,e):t.emitAsset(ni,e)}tm()&&e===n&&t.emitAsset(`${eX.dirname(e)}/tasm.json`,new r(JSON.stringify(a,null,2)))}}finally{this.options.onProcessDuration?.(Date.now()-r)}})})}async encode(e){let t={},{resolveSigningEncryptionOptions:r}=this.options;for(let r of e)r.name.endsWith(".js")&&(t[r.name.replace(/\.template\.js$/,"")]={content:r.source.source().toString()});let n={compilerOptions:{enableFiberArch:!0,targetSdkVersion:this.options.engineVersion??"3.5"},sourceContent:{appType:"DynamicComponent"},customSections:t},i=await r?.();if(i?.signing.enabled||i?.encryption.enabled){let{encode:e}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),t=this.options.metadata.appId,r=ri(i,{signing:{extra_config:{app_id:t,bundle_id:t}},encryption:{salt:t}}),{buffer:o,lepus_debug:a,status:s,error_msg:l}=await e(JSON.stringify(n),r);if(0!==s)throw Error(l);return!this.isGenerateKeystore&&r.encryption.enabled?(this.isGenerateKeystore=!0,{buffer:o,encodeOptions:n,debugInfo:a,keystoreContent:await no({encryption:{...r.encryption}})}):{buffer:o,encodeOptions:n,debugInfo:a}}let o=(0,na.getEncodeMode)(),{buffer:a}=await o(n);return{buffer:a,encodeOptions:n}}}function nl(e,t,n,i,o){let a=!1;return{name:nl.name,apply(s){let l=new s.webpack.experiments.VirtualModulesPlugin;l.apply(s),s.hooks.thisCompilation.tap(nl.name,()=>{Object.keys(n).forEach(e=>{l.writeModule(n[e].filename,n[e].toString())})}),s.hooks.thisCompilation.tap(nl.name,n=>{let l,d=()=>{void 0!==l&&o?.(Math.max(0,Date.now()-l))},p=e.getLynxTemplatePluginHooks(n);p.beforeEncode.tapPromise(nl.name,async e=>(l??=Date.now(),e.encodeData.sourceContent.config=j({},e.encodeData.sourceContent.config,{mapContainerType:1,trailNewImage:!0}),e)),p.encode.tapPromise({name:nl.name,stage:255},async e=>{let{encodeOptions:o}=e,l=await i?.();if(l?.signing.enabled||l?.encryption.enabled){let{encode:r}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),i=t.getData(),p=function(e,t){let r=(t??"").replaceAll("\\","/"),n=r.match(/(?:^|\/)(pages|widgets)\/(.+)$/);if(n){let[,t,r]=n,i=`${t}/${r}`;return"widgets"===t?e.widgets[i]?.id:e.pages[i]?.path}let i=ta.posix.basename(r);return e.widgets[`widgets/${i}`]?.id??e.pages[`pages/${i}`]?.path}(i,e.intermediate),c=i.app.appId,u=ri(l,{signing:{extra_config:{app_id:c,bundle_id:p}},encryption:{salt:c}}),{buffer:h,lepus_debug:m,status:g,error_msg:y}=await r(JSON.stringify(o),u);if(0!==g)throw Error(y);if(!a&&u.encryption.enabled){a=!0;let e=await no({encryption:{...u.encryption}}),t=new s.webpack.sources.RawSource(e,!1);n.getAsset(ni)?n.updateAsset(ni,t):n.emitAsset(ni,t)}return d(),{buffer:h,debugInfo:m}}let{buffer:p,lepus_debug:c}=await (r??=new m({filename:new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.3.0-rc.3_@lynx-js+types@4.1.0_@pnpm+logger@1001.0.1_@swc+helpe_1a6b167d04325d26c47447895a884d09/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"),f.b).href,maxThreads:(0,rI.availableParallelism)()})).run({encodeOptions:o});return d(),{buffer:Buffer.from(p),debugInfo:c}})}),s.hooks.failed.tap(nl.name,e=>{tO.error("Failed to bundle template",{error:e})})}}}class nd{static _instance;listeners=[];stdinListener;nextIndex=0;static get instance(){return nd._instance??=new nd}start(){this.stdinListener||0===this.listeners.length||(this.stdinListener=e=>{let t=e.toString("utf-8");this.listeners.some(e=>e.run(t))},process.stdin.on("data",this.stdinListener),process.stdin.resume())}stop(){this.stdinListener&&(process.stdin.off("data",this.stdinListener),this.stdinListener=void 0)}addListener(e,t,r=0){let n=e=>()=>{let t=this.listeners.findIndex(t=>t.run===e);t>-1&&(this.listeners.splice(t,1),0===this.listeners.length&&(this.stop(),0===process.stdin.listenerCount("data")&&process.stdin.pause()))};if(t){let e=this.listeners.find(e=>e.tag===t);if(e)return n(e.run)}return this.listeners.push({run:e,tag:t,priority:r,index:this.nextIndex++}),this.listeners.sort((e,t)=>e.priority-t.priority||e.index-t.index),this.start(),n(e)}}function np(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e}function nc(e){nd.instance.stop(),e().catch(np).finally(()=>nd.instance.start())}let nu=ex.child("simulator"),nh=f("node:http"),nm={"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless"},nf=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),ng=new Set([...nf,"cookie","host","origin","referer"]),ny=/authorization|cookie|token|secret|password|credential|private[-_]?key|(?:^|[-_])api[-_]?key(?:$|[-_])|(?:^|[-_])dek(?:$|[-_])/i,nb="X-DBX-Sandbox-Session-ID",n_="x-tt-logid";function nv(e){try{return new URL(e.url??"/","http://localhost")}catch{return}}function nw(e){if(!e)throw Error("url 必须为非空字符串");let t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error(`不支持的请求协议:${t.protocol}`);return t}function nS(e,t,r={}){let n={};for(let[t,r]of Object.entries(e))void 0===r||ng.has(t.toLowerCase())||(n[t]=r);return{...n,...r,host:t.host}}function nE(e,t=[]){let r={};for(let[t,n]of Object.entries(e))void 0===n||nf.has(t.toLowerCase())||(r[t]=n);if(t.length>0){let e=new Set(String(r["access-control-expose-headers"]??"").split(",").map(e=>e.trim().toLowerCase()).filter(Boolean));for(let r of t)e.add(r.toLowerCase());r["access-control-expose-headers"]=[...e].join(", ")}return r}function nx(e,t=[]){let r=nE(Object.fromEntries(e),t);return delete r["content-encoding"],delete r["content-length"],r}function nA(e,t={}){Object.entries({...nm,...t}).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})}function nT(e,t,r,n){nA(e,n),e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(r)}function nC(e,t,r,n){let i=JSON.stringify(r);nA(e,n),e.writeHead(t,{"Content-Length":Buffer.byteLength(i),"Content-Type":"application/json; charset=utf-8"}),e.end(i)}function nI(e,t,r){return new Promise((n,i)=>{let o=[],a=0,s=!1;e.on("data",n=>{if(s)return;let l=Uint8Array.from(Buffer.isBuffer(n)?n:Buffer.from(n));if((a+=l.byteLength)>r){s=!0,e.pause(),t.shouldKeepAlive=!1,t.setHeader("Connection","close");let r=()=>{e.destroyed||e.destroy()};t.once("finish",r),t.once("close",r),i(Error("Request body is too large"));return}o.push(l)}),e.once("end",()=>{if(s)return;s=!0;let e=new Uint8Array(a),t=0;for(let r of o)e.set(r,t),t+=r.byteLength;n(e)}),e.once("aborted",()=>{s||(s=!0,i(Error("Request aborted")))}),e.once("error",e=>{s||(s=!0,i(e))})})}function nO(e,t,r){return nI(e,t,r).then(e=>Buffer.from(e).toString("utf8"))}function nP(e){return e.arrayBuffer().then(e=>Buffer.from(e))}function nk(e){return Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r=ny.test(e)?"[REDACTED]":Array.isArray(t)?t.join(", "):t;return` ${e}: ${r}`}).join("\n")}function nD(e){return("string"==typeof e||void 0===e?e:e.toString("utf8"))||"(no content)"}function n$({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a}){"applet0930"===process.env.DEBUG&&nu.info(`${e} ${a.pathname}${a.search} ${(o>=500?ep.red:o>=400?ep.yellow:ep.green)(String(o))}
156
+ widget id 必须全局唯一,请在 src/app.config.ts 中配置不同的 "id"。`)}(g),g.forEach(([e,t])=>{n.addWidgetMeta(e,t)})}let ng=f("os"),ny=`base/${e3}`;async function nb({encryption:e}){let t=tH.mkdtempSync(eJ.join(ng.tmpdir(),"doubao-keystore-")),r=eJ.join(t,e3);try{let{generateKeystore:t}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),n=await t(r,{encryption:e});if(0!==n.status)throw Error(n.error_msg);return tH.readFileSync(r)}finally{tH.rmSync(t,{recursive:!0,force:!0})}}let n_=f("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40_debug@4.4.3/node_modules/@byted-lynx/tasm/index.js");class nv{options;isGenerateKeystore=!1;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(nv.name,t=>{t.hooks.processAssets.tapPromise({name:nv.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH},async()=>{let r=Date.now();try{let{RawSource:r}=e.webpack.sources,n=this.options.getAppAssetPath(),i=rb(t,e5);for(let e of[n,i].filter(e=>!!e)){let i=t.getAsset(e);if(!i)throw Error(`未生成 Worker 入口产物:${e}`);let{buffer:s,encodeOptions:o,keystoreContent:a}=await this.encode([i]);if(t.updateAsset(e,new r(s,!1)),a){let e=new r(a,!1);t.getAsset(ny)?t.updateAsset(ny,e):t.emitAsset(ny,e)}eb()&&e===n&&t.emitAsset(`${t_.dirname(e)}/tasm.json`,new r(JSON.stringify(o,null,2)))}}finally{this.options.onProcessDuration?.(Date.now()-r)}})})}async encode(e){let t={},{resolveSigningEncryptionOptions:r}=this.options;for(let r of e)r.name.endsWith(".js")&&(t[r.name.replace(/\.template\.js$/,"")]={content:r.source.source().toString()});let n={compilerOptions:{enableFiberArch:!0,targetSdkVersion:this.options.engineVersion??"3.5"},sourceContent:{appType:"DynamicComponent"},customSections:t},i=await r?.();if(i?.signing.enabled||i?.encryption.enabled){let{encode:e}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),t=this.options.metadata.appId,r=tZ(i,{signing:{extra_config:{app_id:t,bundle_id:t}},encryption:{salt:t}}),{buffer:s,lepus_debug:o,status:a,error_msg:l}=await e(JSON.stringify(n),r);if(0!==a)throw Error(l);return!this.isGenerateKeystore&&r.encryption.enabled?(this.isGenerateKeystore=!0,{buffer:s,encodeOptions:n,debugInfo:o,keystoreContent:await nb({encryption:{...r.encryption}})}):{buffer:s,encodeOptions:n,debugInfo:o}}let s=(0,n_.getEncodeMode)(),{buffer:o}=await s(n);return{buffer:o,encodeOptions:n}}}function nE(e,t,n,i,s){let o=!1;return{name:nE.name,apply(a){let l=new a.webpack.experiments.VirtualModulesPlugin;l.apply(a),a.hooks.thisCompilation.tap(nE.name,()=>{Object.keys(n).forEach(e=>{l.writeModule(n[e].filename,n[e].toString())})}),a.hooks.thisCompilation.tap(nE.name,n=>{let l,c=()=>{void 0!==l&&s?.(Math.max(0,Date.now()-l))},p=e.getLynxTemplatePluginHooks(n);p.beforeEncode.tapPromise(nE.name,async e=>(l??=Date.now(),e.encodeData.sourceContent.config=es({},e.encodeData.sourceContent.config,{mapContainerType:1,trailNewImage:!0,disableQuickTracingGC:!0}),e)),p.encode.tapPromise({name:nE.name,stage:255},async e=>{let{encodeOptions:s}=e,l=await i?.();if(l?.signing.enabled||l?.encryption.enabled){let{encode:r}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),i=t.getData(),p=function(e,t){let r=(t??"").replaceAll("\\","/"),n=r.match(/(?:^|\/)(pages|widgets)\/(.+)$/);if(n){let[,t,r]=n,i=`${t}/${r}`;return"widgets"===t?e.widgets[i]?.id:e.pages[i]?.path}let i=t_.posix.basename(r);return e.widgets[`widgets/${i}`]?.id??e.pages[`pages/${i}`]?.path}(i,e.intermediate),d=i.app.appId,u=tZ(l,{signing:{extra_config:{app_id:d,bundle_id:p}},encryption:{salt:d}}),{buffer:m,lepus_debug:h,status:g,error_msg:y}=await r(JSON.stringify(s),u);if(0!==g)throw Error(y);if(!o&&u.encryption.enabled){o=!0;let e=await nb({encryption:{...u.encryption}}),t=new a.webpack.sources.RawSource(e,!1);n.getAsset(ny)?n.updateAsset(ny,t):n.emitAsset(ny,t)}return c(),{buffer:m,debugInfo:h}}let{buffer:p,lepus_debug:d}=await (r??=new h({filename:new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.5.0-rc.3_@lynx-js+types@4.1.0_@pnpm+logger@1001.0.1_@swc+helpe_0e0a52a284c18388b1ab9c5a0abf4e84/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"),f.b).href,maxThreads:(0,rw.availableParallelism)()})).run({encodeOptions:s});return c(),{buffer:Buffer.from(p),debugInfo:d}})}),a.hooks.failed.tap(nE.name,e=>{tu.error("模板打包失败",{error:e})})}}}class nw{static _instance;listeners=[];stdinListener;nextIndex=0;static get instance(){return nw._instance??=new nw}start(){this.stdinListener||0===this.listeners.length||(this.stdinListener=e=>{let t=e.toString("utf-8");this.listeners.some(e=>e.run(t))},process.stdin.on("data",this.stdinListener),process.stdin.resume())}stop(){this.stdinListener&&(process.stdin.off("data",this.stdinListener),this.stdinListener=void 0)}addListener(e,t,r=0){let n=e=>()=>{let t=this.listeners.findIndex(t=>t.run===e);t>-1&&(this.listeners.splice(t,1),0===this.listeners.length&&(this.stop(),0===process.stdin.listenerCount("data")&&process.stdin.pause()))};if(t){let e=this.listeners.find(e=>e.tag===t);if(e)return n(e.run)}return this.listeners.push({run:e,tag:t,priority:r,index:this.nextIndex++}),this.listeners.sort((e,t)=>e.priority-t.priority||e.index-t.index),this.start(),n(e)}}function nS(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e}function nx(e){nw.instance.stop(),e().catch(nS).finally(()=>nw.instance.start())}let nA=ex.child("simulator"),nT=f("node:http"),nI={"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless"},nO=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),nP=new Set([...nO,"cookie","host","origin","referer"]),nC=/authorization|cookie|token|secret|password|credential|private[-_]?key|(?:^|[-_])api[-_]?key(?:$|[-_])|(?:^|[-_])dek(?:$|[-_])/i,nR="X-DBX-Sandbox-Session-ID",n$="x-tt-logid";function nk(e){try{return new URL(e.url??"/","http://localhost")}catch{return}}function nN(e){if(!e)throw Error("url 必须为非空字符串");let t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error(`不支持的请求协议:${t.protocol}`);return t}function nL(e,t,r={}){let n={};for(let[t,r]of Object.entries(e))void 0===r||nP.has(t.toLowerCase())||(n[t]=r);return{...n,...r,host:t.host}}function nD(e,t=[]){let r={};for(let[t,n]of Object.entries(e))void 0===n||nO.has(t.toLowerCase())||(r[t]=n);if(t.length>0){let e=new Set(String(r["access-control-expose-headers"]??"").split(",").map(e=>e.trim().toLowerCase()).filter(Boolean));for(let r of t)e.add(r.toLowerCase());r["access-control-expose-headers"]=[...e].join(", ")}return r}function nj(e,t=[]){let r=nD(Object.fromEntries(e),t);return delete r["content-encoding"],delete r["content-length"],r}function nM(e,t={}){Object.entries({...nI,...t}).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})}function nU(e,t,r,n){nM(e,n),e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(r)}function nB(e,t,r,n){let i=JSON.stringify(r);nM(e,n),e.writeHead(t,{"Content-Length":Buffer.byteLength(i),"Content-Type":"application/json; charset=utf-8"}),e.end(i)}function nF(e,t,r){return new Promise((n,i)=>{let s=[],o=0,a=!1;e.on("data",n=>{if(a)return;let l=Uint8Array.from(Buffer.isBuffer(n)?n:Buffer.from(n));if((o+=l.byteLength)>r){a=!0,e.pause(),t.shouldKeepAlive=!1,t.setHeader("Connection","close");let r=()=>{e.destroyed||e.destroy()};t.once("finish",r),t.once("close",r),i(Error("Request body is too large"));return}s.push(l)}),e.once("end",()=>{if(a)return;a=!0;let e=new Uint8Array(o),t=0;for(let r of s)e.set(r,t),t+=r.byteLength;n(e)}),e.once("aborted",()=>{a||(a=!0,i(Error("Request aborted")))}),e.once("error",e=>{a||(a=!0,i(e))})})}function nH(e,t,r){return nF(e,t,r).then(e=>Buffer.from(e).toString("utf8"))}function nW(e){return e.arrayBuffer().then(e=>Buffer.from(e))}function nG(e){return Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r=nC.test(e)?"[REDACTED]":Array.isArray(t)?t.join(", "):t;return` ${e}: ${r}`}).join("\n")}function nV(e){return("string"==typeof e||void 0===e?e:e.toString("utf8"))||"(no content)"}function nq({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:s,targetUrl:o}){eb()&&nA.info(`${e} ${o.pathname}${o.search} ${(s>=500?ec.red:s>=400?ec.yellow:ec.green)(String(s))}
151
157
  Request headers:
152
- ${nk(r)}
153
- Request body: ${nD(t)}
158
+ ${nG(r)}
159
+ Request body: ${nV(t)}
154
160
 
155
161
  Response headers:
156
- ${nk(Object.fromEntries(i))}
157
- Response body: ${nD(n)}`)}function nR(e,t){let r=new AbortController,n=()=>r.abort();return e.once("aborted",n),t.once("close",()=>{e.off("aborted",n),t.writableEnded||n()}),(e.aborted||t.destroyed)&&n(),r.signal}function nN(e,t,r){let n,i=("https:"===r.targetUrl.protocol?_:nh).request(r.targetUrl,{headers:r.requestHeaders,method:e.method},e=>{(n=e,t.destroyed||t.writableEnded)?e.destroy():(nA(t,r.commonHeaders),t.writeHead(e.statusCode??500,r.createResponseHeaders?.(e.headers)??nE(e.headers)),e.pipe(t))}),o=()=>{i.destroy(),n?.destroy()};i.once("error",e=>{if(!t.destroyed&&!t.writableEnded){if(t.headersSent)return void t.destroy(e);nT(t,502,`${r.errorMessage}: ${e.message}`,r.commonHeaders)}}),e.once("aborted",()=>{o()}),t.once("close",()=>{t.writableEnded||o()}),e.pipe(i)}async function nL(e,t,r){let n=t.find(({match:t})=>"string"==typeof t?e.url.pathname===t:t(e.url));await (n?.handle??r)(e)}function nM(e,t){return(r,n)=>{let i=nv(r);i?nL({request:r,response:n,url:i},e,t).catch(e=>(function(e,t){if(nu.error("处理 Web SDK 调试器请求失败",{error:t}),!e.destroyed&&!e.writableEnded){if(e.headersSent)return void e.destroy(t instanceof Error?t:void 0);nT(e,500,"Internal server error")}})(n,e)):nT(n,400,"Bad request")}}let nj=f("../../../node_modules/.pnpm/undici@6.22.0/node_modules/undici/index.js"),nU={"sso-internal":"doubao-developer.bytedance.net","sms-internal":"doubao-developer-open.bytedance.net","sms-external":"hello.doubao-dev.com"},nB={"http:":"80","https:":"443"},nF=new Map;function nW(){return process.env.X_TT_ENV?{"x-use-ppe":"1","x-tt-env":process.env.X_TT_ENV}:{}}function nH(e){let t=e.startsWith("/")?e:`/${e}`;return"/app_developer"===t||t.startsWith("/app_developer/")}async function nV(e,t={}){let r=function(e){var t,r;let n="string"==typeof e?new URL(e):e;if(function(e){let t=nJ(["NO_PROXY","no_proxy"]);if(!t)return!1;let r=nK(e.hostname),n=e.port||nB[e.protocol]||"";for(let e of t.split(",")){let t=function(e){let t=e.trim().toLowerCase();if(!t)return{host:""};if((t=t.replace(/^[a-z][a-z\d+.-]*:\/\//,"").split("/")[0]).startsWith("[")){let e=t.indexOf("]");if(-1!==e)return{host:nK(t.slice(0,e+1)),port:":"===t[e+1]?t.slice(e+2):void 0}}let r=t.indexOf(":")===t.lastIndexOf(":")?t.match(/:(\d+)$/):void 0;return{host:nK(r?t.slice(0,-r[0].length):t),port:r?.[1]}}(e);if(t.host&&(!t.port||t.port===n)){if("*"===t.host)return!0;if(t.host.startsWith("*.")){let e=t.host.slice(1);if(r.endsWith(e))return!0;continue}if(t.host.startsWith(".")){if(r.endsWith(t.host))return!0;continue}if(r===t.host)return!0}}return!1}(n))return;let i="https:"===(t=n.protocol)?nJ(["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):"http:"===t?nJ(["HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):void 0;if(!i)return;let o=(r=i,/^[a-z][a-z\d+.-]*:\/\//i.test(r)?r:`http://${r}`),a=nF.get(o);return a||(a=new nj.kT(o),nF.set(o,a)),a}(e),n=r?{...t,dispatcher:r}:t;return await fetch(e,n)}async function nG({internal:e,domainId:t,path:r,query:n,method:i="GET",body:o,headers:a,signal:s,auth:l=!0}){let d={method:i,body:o,headers:{...nW(),...a}};s&&(d.signal=s);let p=function({internal:e,domainId:t,path:r,query:n}){let i=r.startsWith("/")?r:`/${r}`,o=new URLSearchParams;for(let[e,t]of Object.entries(n||{}))null!=t&&o.append(e,t.toString());let a=o.toString(),s=a?`${i.includes("?")?"&":"?"}${a}`:"",l=nH(i)?q:t?nU[t]:e?nU["sso-internal"]:nU["sms-external"];return`https://${l}${i}${s}`}({internal:e,domainId:t,path:r,query:n}),c=new Headers(d.headers),u=c.has("Cookie");if(!l||!nH(r)||c.has("Authorization")||c.has("X-Developer-Open-Build-Token"))return await nV(p,d);let h=new URL(p).origin,m=er(nV,{baseUrl:h,allowedOrigins:[h]});try{return await m(p,d)}catch(e){if(!(e instanceof eo||e instanceof K))throw e;if(u)return await nV(p,d);throw Error(e instanceof K?"Doubao Apps Platform 登录已过期,请运行 `dbx auth login` 后重试。":"Doubao Apps Platform 请求需要登录,请运行 `dbx auth login` 后重试。")}}async function nq(e){let t=await nG(e),r=t.headers.get("x-tt-logid")||"";if(!t.ok){let e=await t.text();throw Error(JSON.stringify({code:t.status,message:"HTTP 请求失败",data:e,log_id:r}))}let n=await t.json();if(0!==n.code)throw Error(JSON.stringify({...n,log_id:r}));return{...n,log_id:r}}function nJ(e){for(let t of e){let e=process.env[t]?.trim();if(e)return e}}function nK(e){return e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"")}let nz="/__mcp_proxy",nY=f("../../../node_modules/.pnpm/ws@8.21.2/node_modules/ws/lib/websocket-server.js");function nX(e,t,r){e.readyState!==eh.OPEN||e.bufferedAmount>0xa00000?e.terminate():e.send(JSON.stringify({type:t,data:r}))}let nZ=new Set(["DEBUGGER_NOT_CONNECTED","DEBUGGER_DISCONNECTED","TARGET_NOT_FOUND","ELEMENT_NOT_FOUND","RENDER_FAILED","RENDER_TIMEOUT","VIEWPORT_FAILED","INSPECTION_FAILED","SCROLL_FAILED","SCREENSHOT_FAILED","SNAPSHOT_FAILED","CHAT_NOT_READY","CHAT_BUSY","CHAT_SUBMIT_FAILED","CHAT_TIMEOUT","TOOL_CALL_FAILED","COMMAND_TIMEOUT"]);class nQ extends Error{code;constructor(e,t){super(t),this.name="DebuggerControlError",this.code=e}}function n0(e){return"render_page"===e||"render_widget"===e}function n1(e){return"number"==typeof e&&Number.isFinite(e)}function n3(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function n2(e){if("submit_chat_query"===e.type)return 12e4;if("execute_sandbox_tool_call"===e.type){let t=e.toolCall?.tool_call?.deadline_ms;if("number"==typeof t&&Number.isFinite(t))return Math.max(1,t-Date.now()+1e3)}return 15e3}class n4{clients=new Map;lastSnapshotAtByClientId=new Map;snapshotStore;snapshotsByClientId=new Map;nextCommandId=0;constructor(e){this.snapshotStore=e}registerClient(e,t){let r=this.getSnapshotStore(e),n=this.clients.get(e);n&&this.disconnectClient(n,"Debugger control connection was replaced");let i={clientId:e,lastSnapshotAtMs:this.lastSnapshotAtByClientId.get(e)??0,parallelJobs:new Map,queue:[],socket:t};this.clients.set(e,i),this.snapshotsByClientId.set(e,r),t.once("close",()=>{this.disconnectClient(i,"Debugger control connection was closed",!1)})}getSnapshotStore(e){return this.snapshotsByClientId.get(e)??{}}noteSnapshot(e){if(!e)return;let t=this.getSnapshotStore(e);Object.assign(t,this.snapshotStore),this.snapshotsByClientId.set(e,t);let r=Date.now();this.lastSnapshotAtByClientId.set(e,r);let n=this.clients.get(e);n&&(n.lastSnapshotAtMs=r)}execute(e,t,r){let n=void 0!==r?this.clients.get(r):"execute_sandbox_tool_call"===e?this.getToolCallClient():this.getActiveClient();if(!n||n.socket.readyState!==eh.OPEN)return Promise.reject(new nQ("DEBUGGER_NOT_CONNECTED","execute_sandbox_tool_call"===e?"No Web SDK debugger is connected":"No Web SDK debugger with a stored snapshot is connected"));let i=`control-${Date.now()}-${++this.nextCommandId}`;return new Promise((r,o)=>{let a={command:{...t,commandId:i,type:e},reject:o,resolve:r};"execute_sandbox_tool_call"===e?this.startParallelJob(n,a):(n.queue.push(a),this.flushClient(n))})}handleResult(e){var t,r;let n,i=e.clientId?.trim(),o=e.commandId?.trim(),a=i?this.clients.get(i):void 0,s=o?a?.parallelJobs.get(o):void 0,l=s??a?.activeJob;if(!a||!l||l.command.commandId!==o)return!1;if(!0===e.ok&&n0(l.command.type)&&(t=e.snapshot,t.snapshot.command_id===o&&t.snapshot.runtime_snapshot)?(this.snapshotStore.snapshot=e.snapshot,this.snapshotStore.updatedAtMs=Date.now(),this.noteSnapshot(i),n={target:e.target}):!0===e.ok&&!n0(l.command.type)&&(n=function(e,t){if("set_viewport"===e)return n3(t.width)&&n3(t.height)?t:void 0;if("submit_chat_query"===e)return!0===t.completed&&t.query?.trim()&&t.requestId?.trim()?t:void 0;if("take_snapshot"===e){let e=t.runtimeSnapshot;return e?.target?{runtimeSnapshot:e}:void 0}if("execute_sandbox_tool_call"===e)return!0===t.reported&&t.request_id?.trim()&&t.tool_call_id?.trim()?t:void 0;if("take_screenshot"===e||t.uid?.trim()){if("get_computed_style"===e){if(!Array.isArray(t.computedStyle)||!t.computedStyle.every(e=>!!e.name?.trim()&&"string"==typeof e.value))return;return t}if("get_element_rect"===e)return[t.x,t.y,t.width,t.height].every(n1)?t:void 0;if("scroll_to"===e)return[t.x,t.y,t.maxX,t.maxY,t.viewportWidth,t.viewportHeight].every(e=>n1(e)&&e>=0)&&t.x<=t.maxX&&t.y<=t.maxY?t:void 0;if("take_screenshot"===e){let e="png"===t.format?"image/png":"jpeg"===t.format?"image/jpeg":"webp"===t.format?"image/webp":void 0;return"string"==typeof t.data&&t.data.length>0&&t.mimeType===e&&n1(t.width)&&n1(t.height)&&(void 0===t.uid||t.uid?.trim())?t:void 0}}}(l.command.type,e.result),"take_snapshot"===l.command.type&&n&&"runtimeSnapshot"in n&&this.storeRuntimeSnapshot(a.clientId,n.runtimeSnapshot)),n)l.resolve(n);else{let t=e.error??{},n=t.code?.trim(),i=n&&nZ.has(n)?n:void 0;l.reject(new nQ(i??(n0(r=l.command.type)?"RENDER_FAILED":"set_viewport"===r?"VIEWPORT_FAILED":"scroll_to"===r?"SCROLL_FAILED":"submit_chat_query"===r?"CHAT_SUBMIT_FAILED":"take_snapshot"===r?"SNAPSHOT_FAILED":"execute_sandbox_tool_call"===r?"TOOL_CALL_FAILED":"take_screenshot"===r?"SCREENSHOT_FAILED":"INSPECTION_FAILED"),t.message?.trim()||"Debugger control command failed"))}return l.timeout&&clearTimeout(l.timeout),s?a.parallelJobs.delete(o):a.activeJob=void 0,this.flushClient(a),!0}getActiveClient(){return[...this.clients.values()].filter(e=>e.socket.readyState===eh.OPEN&&e.lastSnapshotAtMs>0).sort((e,t)=>t.lastSnapshotAtMs-e.lastSnapshotAtMs)[0]}storeRuntimeSnapshot(e,t){let r=this.getSnapshotStore(e).snapshot,n=r?.snapshot;if(!r||!n||n.client_id!==e)return;let i=r.debug_snapshot,{root:o,...a}=t,s=Date.now();this.snapshotStore.snapshot={...r,stored_at:new Date(s).toISOString(),stored_at_ms:s,snapshot:{...n,runtime_snapshot:t},...i?{debug_snapshot:{...i,runtime_snapshot:a}}:{}},this.snapshotStore.updatedAtMs=s,this.noteSnapshot(e)}getConnectedClient(){return[...this.clients.values()].reverse().find(e=>e.socket.readyState===eh.OPEN)}getToolCallClient(){return[...this.clients.values()].reverse().find(e=>e.socket.readyState===eh.OPEN&&e.activeJob?.command.type==="submit_chat_query")??this.getActiveClient()??this.getConnectedClient()}startParallelJob(e,t){let r=t.command.commandId;e.parallelJobs.set(r,t),t.timeout=setTimeout(()=>{e.parallelJobs.delete(r)&&t.reject(new nQ("TOOL_CALL_FAILED","Debugger control command timed out"))},n2(t.command));try{nX(e.socket,"control",t.command)}catch{this.disconnectClient(e,"Debugger control connection was closed")}}flushClient(e){if(e.activeJob||e.socket.readyState!==eh.OPEN)return;let t=e.queue.shift();if(t){e.activeJob=t,t.timeout=setTimeout(()=>{if(e.activeJob===t){if("submit_chat_query"===t.command.type){t.timeout=void 0,t.reject(new nQ("CHAT_TIMEOUT","Debugger control command timed out"));try{nX(e.socket,"control",{commandId:t.command.commandId,type:"cancel_chat_query"})}catch{this.disconnectClient(e,"Debugger control connection was closed");return}t.timeout=setTimeout(()=>{e.activeJob===t&&this.disconnectClient(e,"Debugger chat cancellation was not acknowledged")},5e3);return}e.activeJob=void 0,t.reject(new nQ(n0(t.command.type)?"RENDER_TIMEOUT":"COMMAND_TIMEOUT","Debugger control command timed out")),this.flushClient(e)}},n2(t.command));try{nX(e.socket,"control",t.command)}catch{this.disconnectClient(e,"Debugger control connection was closed")}}}disconnectClient(e,t,r=!0){if(this.clients.get(e.clientId)!==e)return;this.clients.delete(e.clientId),this.snapshotsByClientId.delete(e.clientId);let n=new nQ("DEBUGGER_DISCONNECTED",t);for(let t of(e.activeJob?.timeout&&clearTimeout(e.activeJob.timeout),e.activeJob?.reject(n),e.activeJob=void 0,e.parallelJobs.values()))t.timeout&&clearTimeout(t.timeout),t.reject(n);for(let t of(e.parallelJobs.clear(),e.queue.splice(0)))t.reject(n);r&&e.socket.readyState===eh.OPEN&&e.socket.close()}}let n5=["page","widget","app"],n9=["log","info","warn","error","debug","eval"],n8=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function n7(e,t){let r=t.pageIdx??0,n=t.pageSize??50,i=r*n,o=e.slice(i,i+n);return{pageIdx:r,pageSize:n,total:e.length,hasMore:i+o.length<e.length,items:o}}function n6(e){if(!e.snapshot)return{stored:!1,updatedAtMs:e.updatedAtMs};let{debug_snapshot:t,...r}=e.snapshot;return{stored:!0,storedAt:r.stored_at,updatedAtMs:r.stored_at_ms??e.updatedAtMs,snapshot:r.snapshot}}function ie(e){return e.value??e.unserializableValue??e.description??e.type??""}function it(e,t){var r,n;let i;return(r=e,"all"===(n=t)?n5:"page"===n||"widget"===n||"app"===n?[n]:(i=r.context,i?.page_id||i?.page_path?["page","app"]:i?.widget_id?["widget"]:n5)).flatMap(t=>{let r,n=(r=e.runtime_console?.[t],{entries:r?.entries??[],updatedAtMs:r?.updated_at_ms??r?.updatedAtMs});return n.entries.map((e,r)=>{var i;let o,a,s,l;return i=n.updatedAtMs,o=e.url??e.location?.url,a=e.lineNumber??e.location?.lineNumber,s=e.columnNumber??e.location?.columnNumber,l=e.id??String(r),{msgid:`${t}:${l}`,target:t,level:e.level??"log",source:e.source??"",timestamp:e.timestamp??0,text:e.message??(e.args??[]).map(ie).filter(Boolean).join(" "),...o?{url:o}:{},...void 0===a?{}:{lineNumber:a},...void 0===s?{}:{columnNumber:s},...void 0===i?{}:{updatedAtMs:i},entry:e}})})}function ir(e,t){return{id:e.toolCallId??e.id??`tool-call:${t}`,requestId:e.requestId??e.request_id??"",toolCallId:e.toolCallId??e.id??"",toolName:e.toolName??e.name??"",serverId:e.serverId??e.server_id??"",appKey:e.appKey??e.app_key??"",status:e.status??"",createdAtMs:e.createdAtMs??e.created_at_ms??0,updatedAtMs:e.updatedAtMs??e.updated_at_ms??0,requiresUserApproval:!0===e.requiresUserApproval,isMiniApp:!0===e.isMiniApp,message:e.message??"",resultSummary:e.resultSummary??e.structuredResultSummary}}function ii(e,t){if("page"===t){let{pageId:t,path:r}=e;if(!t||!r)return;return{pageId:t,path:r,name:e.name??t,isHome:!0===e.isHome}}let{widgetId:r}=e;if(r)return{widgetId:r,name:e.name??r}}let io={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},ia={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},is={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function il(e,t={}){return{structuredContent:e,content:t.image?[{type:"image",...t.image}]:[{type:"text",text:t.text??JSON.stringify(e,null,2)}],...t.isError?{isError:!0}:{}}}async function id(e,t={}){try{return await e()}catch(e){return function(e,t={}){let r=e instanceof nQ?e:new nQ("INSPECTION_FAILED",String(e));return il({...t,error:{code:r.code,message:r.message}},{isError:!0})}(e,t)}}function ip(e,t,r,n){let i=D(r.inputSchema);e.registerTool(t,{...r,inputSchema:i},n)}let ic="/__wsd_mcp";async function iu({request:e,response:t,url:r},n,i){if("OPTIONS"===e.method){nA(t),t.writeHead(204),t.end();return}if("POST"!==e.method)return void nT(t,405,"Method not allowed");let o=r.searchParams.get("clientId")??void 0,a=void 0===o?n:i.getSnapshotStore(o),s=$(()=>{let e,t;return e=new I({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),t=async e=>{var t;let r=n6(a);if(!r.stored)return il(r);let n=n7((t=r.snapshot,[{source:"simulator",events:t.simulator?.trace_events??[]},{source:"widget_runtime",events:t.widget_runtime_trace_events??[]},{source:"page_runtime",events:t.page_runtime_trace_events??[]}].flatMap(({source:e,events:t})=>t.map((t,r)=>{let n;return n=t.payload??{},{source:e,id:t.id??`${e}:${r}`,timestamp:t.timestamp??0,category:n.category??t.display?.category??"",event:n.event??t.event??"",requestId:n.request_id??n.requestId??n.trace_id??n.trace?.trace_id??"",payload:t.payload??t}}))).filter(t=>{let r,n,i;return r=e.category??[],n=e.event?.trim(),i=e.requestId?.trim(),(0===r.length||r.includes(t.category))&&(!n||t.event===n)&&(!i||t.requestId===i)}),e);return il({stored:!0,storedAt:r.storedAt,updatedAtMs:r.updatedAtMs,total:n.total,pageIdx:n.pageIdx,pageSize:n.pageSize,hasMore:n.hasMore,events:n.items})},ip(e,"list_chat_messages",{annotations:io,description:"List conversation messages in chronological order from the latest debugger snapshot, including message content and generation status.",inputSchema:{}},async()=>{let e=n6(a);if(!e.stored)return il(e);let t=a.snapshot?.debug_snapshot?.simulator??e.snapshot.simulator;return il({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,streamStatus:t?.stream_status,messages:t?.messages??[]})}),ip(e,"list_console_messages",{annotations:io,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:U(C(n9)).optional(),pageIdx:T().int().min(0).optional(),pageSize:T().int().min(1).max(200).optional(),query:k().optional(),target:C(["current","page","widget","app","all"]).optional()}},async e=>{let t=n6(a);if(!t.stored)return il(t);let r=n7(it(t.snapshot,e.target).filter(t=>{let r,n;return r=e.levels??[],n=e.query?.trim().toLowerCase(),(!(r.length>0)||!!r.includes(t.level))&&(!n||[t.text,t.url,t.source,t.target].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(n)))}),e);return il({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,messages:r.items.map(({entry:e,...t})=>t)})}),ip(e,"get_console_message",{annotations:io,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:k()}},async e=>{let t=n6(a);if(!t.stored)return il(t);let r=it(t.snapshot,"all").find(t=>t.msgid===e.msgid);return il({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,found:!!r,...r?{message:r}:{msgid:e.msgid}})}),ip(e,"get_log_snapshot",{annotations:io,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let e=n6(a);return e.stored?il({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,snapshot:e.snapshot}):il(e)}),ip(e,"list_render_targets",{annotations:io,description:"List Page and Widget targets that can be rendered by the Web SDK debugger.",inputSchema:{type:C(["all","page","widget"]).optional()}},async e=>{var t,r;let n,i=n6(a);return i.stored?il({stored:!0,storedAt:i.storedAt,updatedAtMs:i.updatedAtMs,...(t=i.snapshot,r=e.type??"all",n=t.render_targets??{},{pages:"widget"===r?[]:(n.pages??[]).map(e=>ii(e,"page")).filter(Boolean),widgets:"page"===r?[]:(n.widgets??[]).map(e=>ii(e,"widget")).filter(Boolean),...n.currentTarget?{currentTarget:n.currentTarget}:{}})}):il(i)}),ip(e,"take_snapshot",{annotations:io,description:"Capture and return a fresh text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:C(["current","page","widget"]).optional(),verbose:N().optional()}},e=>id(async()=>{let t=function(e,t){var r,n;let i,o,a,s=e.runtime_snapshot;if(!s?.target)return{available:!1,reason:"NO_RUNTIME_SNAPSHOT"};let l=s.target,d=l.type,p=t.target??"current";if(("page"===p||"widget"===p)&&d!==p)return{available:!1,reason:"TARGET_MISMATCH",requestedTarget:p,currentTarget:l};if(!s.root)return{available:!1,reason:"NO_RENDERED_TARGET",currentTarget:l};let c=s.selectedUid,u=(r=s.root,n=!0===t.verbose,i=[],o=0,(a=(e,t)=>{var r,s;let{name:l,uid:d}=e;if(!d||!l)return;o+=1;let p=" ".repeat(t);if("text"===e.type)return void i.push(`${p}uid=${d} text ${JSON.stringify(e.text??"")}`);let u=[`uid=${d}`,l],{keyboardFocusable:h=!1,name:m,role:f}=e.accessibility??{};for(let t of(f&&(n||"generic"!==f)&&u.push(`role=${JSON.stringify(f)}`),m&&u.push(`name=${JSON.stringify(m)}`),(n||h)&&u.push(`focusable=${String(h)}`),(e.attributes??[]).map(e=>({name:e.name,value:e.value})).filter(e=>e.name&&(n||n8.has(e.name)||e.name.startsWith("aria-")))))u.push((r=t.name,(s=t.value)?`${r}=${JSON.stringify(s)}`:r));for(let r of(d===c&&u.push("[selected]"),i.push(`${p}${u.join(" ")}`),e.children??[]))a(r,t+1)})(r,0),{actualNodeCount:o,text:i.join("\n")});return{available:!0,target:l,nodeCount:s.nodeCount??u.actualNodeCount,...c?{selectedUid:c}:{},truncated:!0===s.truncated,snapshot:u.text,snapshotUpdatedAtMs:s.updatedAtMs}}({runtime_snapshot:(await i.execute("take_snapshot",{target:e.target??"current"},o)).runtimeSnapshot},e),r=n6(a),n={stored:r.stored,...r.stored?{storedAt:r.storedAt,updatedAtMs:r.updatedAtMs}:{},...t};return il(n,{text:t.available?t.snapshot:JSON.stringify(n,null,2)})},{available:!1,stored:!1})),ip(e,"get_computed_style",{annotations:io,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:U(k().min(1)).max(100).optional(),uid:k().min(1)}},({properties:e,uid:t})=>id(async()=>il(await i.execute("get_computed_style",{uid:t,...e?{properties:e}:{}},o)))),ip(e,"get_element_rect",{annotations:io,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:k().min(1)}},({uid:e})=>id(async()=>il(await i.execute("get_element_rect",{uid:e},o)))),ip(e,"take_screenshot",{annotations:io,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:C(["png","jpeg","webp"]).optional(),quality:T().min(0).max(100).optional(),uid:k().min(1).optional()}},({format:e="png",quality:t,uid:r})=>id(async()=>{let n=await i.execute("take_screenshot",{format:e,...void 0!==t?{quality:t}:{},...r?{uid:r}:{}},o),{data:a,...s}=n;return il({captured:!0,...s},{image:{data:a,mimeType:n.mimeType}})},{captured:!1})),ip(e,"scroll_to",{annotations:is,description:"Scroll a Page or Widget container to absolute coordinates, or return its current scroll position.",inputSchema:{uid:k().min(1).optional(),x:T().min(0).optional(),y:T().min(0).optional()}},({uid:e,x:t,y:r})=>id(async()=>il({scrolled:!0,...await i.execute("scroll_to",{uid:e,x:t,y:r},o)}),{scrolled:!1})),ip(e,"set_viewport",{annotations:is,description:"Set the current Page or Widget emulated viewport size.",inputSchema:{height:T().int().min(1).max(9999),width:T().int().min(1).max(9999)}},({height:e,width:t})=>id(async()=>il({updated:!0,viewport:await i.execute("set_viewport",{height:e,width:t},o)}),{updated:!1})),ip(e,"render_page",{annotations:ia,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:k().min(1)}},({url:e})=>id(async()=>il({rendered:!0,target:(await i.execute("render_page",{url:e},o)).target}),{rendered:!1})),ip(e,"render_widget",{annotations:ia,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:B(k(),O()).optional(),widgetId:k().min(1)}},({structuredContent:e,widgetId:t})=>id(async()=>il({rendered:!0,target:(await i.execute("render_widget",{structuredContent:e??{},widgetId:t},o)).target}),{rendered:!1})),ip(e,"submit_chat_query",{annotations:ia,description:"Submit a chat query through the connected Web SDK debugger and wait for the simulator response to complete.",inputSchema:{query:k().trim().min(1)}},({query:e})=>id(async()=>il({submitted:!0,...await i.execute("submit_chat_query",{query:e},o)}),{submitted:!1})),ip(e,"list_agent_trace_events",{annotations:io,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:U(k()).optional(),event:k().optional(),pageIdx:T().int().min(0).optional(),pageSize:T().int().min(1).max(200).optional(),requestId:k().optional()}},t),ip(e,"list_agent_tool_calls",{annotations:io,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:T().int().min(0).optional(),pageSize:T().int().min(1).max(200).optional(),query:k().optional(),requestId:k().optional(),status:U(k()).optional(),toolName:k().optional()}},async e=>{var t;let r=n6(a);if(!r.stored)return il(r);let n=n7((t=r.snapshot,(t.simulator?.tool_calls??[]).map(ir)).filter(t=>{let r,n,i,o;return r=e.requestId?.trim(),n=e.toolName?.trim(),i=e.status??[],o=e.query?.trim().toLowerCase(),(!r||t.requestId===r)&&(!n||t.toolName===n)&&(!(i.length>0)||!!i.includes(t.status))&&(!o||[t.toolName,t.serverId,t.appKey,t.status,t.message,"string"==typeof t.resultSummary?t.resultSummary:void 0].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(o)))}),e);return il({stored:!0,storedAt:r.storedAt,updatedAtMs:r.updatedAtMs,total:n.total,pageIdx:n.pageIdx,pageSize:n.pageSize,hasMore:n.hasMore,toolCalls:n.items})}),e}),l=L(s);try{await l(e,t)}catch(e){t.headersSent?t.destroy(e instanceof Error?e:void 0):nT(t,500,e instanceof Error?e.message:String(e))}finally{await s.close().catch(()=>void 0)}}let ih="/__web_sdk_debug_scenes",im="/__web_sdk_widget_view_data_templates",ig={"Cache-Control":"no-cache"};async function iy(e,t){try{let r=await t?.()??{templatesByEntry:{},templatesByWidget:{}};nC(e,200,r,ig)}catch(t){nu.error("加载 Widget viewData 模板失败",{error:t}),nC(e,500,{templatesByEntry:{},templatesByWidget:{}},ig)}}let ib=f("node:crypto"),i_="/__dbx_real_device_debug",iv=`${i_}/state`,iw=`${i_}/start`,iS=`${i_}/cancel`,iE=`${i_}/qr`;class ix{accessToken;provider;getDebugContext(){if(this.provider&&this.accessToken)return{stateEndpoint:iv,startEndpoint:iw,cancelEndpoint:iS,qrEndpoint:iE,accessToken:this.accessToken,pollIntervalMs:500}}setProvider(e){this.provider=e,this.accessToken=e?ib.randomBytes(32).toString("hex"):void 0}dispose(){this.setProvider(void 0)}getRequestRoutes(){return[{match:e=>e.pathname.startsWith(i_),handle:({request:e,response:t,url:r})=>this.serveRequest(e,t,r)}]}async serveRequest(e,t,r){if(!this.validateRequest(e,t))return;let n=this.provider;if(!n)return this.writeError(t,503,"REAL_DEVICE_DEBUG_UNAVAILABLE","Physical device debugging is unavailable");let i=await this.readJsonBody(e,t);if(i)try{if(r.pathname===iv||r.pathname===iw){if(Object.keys(i).length>0)return this.writeError(t,400,"INVALID_REQUEST","Unexpected request fields");let e=r.pathname===iv?await n.getState():await n.start();nC(t,200,e);return}if(r.pathname===iS){let e=i.operationId;if("string"!=typeof e||!e||1!==Object.keys(i).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid operationId");nC(t,200,await n.cancel(e));return}if(r.pathname===iE){let{operationId:e,kind:r}=i;if("string"!=typeof e||!e||"modern"!==r&&"legacy"!==r||2!==Object.keys(i).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid QR request");let o=await n.getQrImage(e,r);if(!o)return this.writeError(t,404,"QR_NOT_FOUND","QR image is unavailable");nA(t),t.writeHead(200,{"Content-Length":o.body.byteLength,"Content-Type":o.contentType}),t.end(o.body);return}return this.writeError(t,404,"NOT_FOUND","Not found")}catch{return this.writeError(t,500,"REAL_DEVICE_DEBUG_FAILED","Physical device debugging failed")}}validateRequest(e,t){var r,n;let i,o,a;if(!function(e){if(!e)return!1;try{let t=new URL(`http://${e}`).hostname.toLowerCase();return"127.0.0.1"===t||"[::1]"===t||"localhost"===t}catch{return!1}}(e.headers.host))return this.writeError(t,403,"FORBIDDEN_HOST","Forbidden host"),!1;let s=e.headers["x-dbx-real-device-token"];if("string"!=typeof s||!this.accessToken||(r=s,n=this.accessToken,o=(i=new TextEncoder).encode(r),a=i.encode(n),!(o.length===a.length&&ib.timingSafeEqual(o,a))))return this.writeError(t,401,"UNAUTHORIZED","Unauthorized"),!1;if("POST"!==e.method)return this.writeError(t,405,"METHOD_NOT_ALLOWED","Method must be POST"),!1;if(!(e.headers["content-type"]?.toLowerCase()??"").startsWith("application/json"))return this.writeError(t,415,"UNSUPPORTED_MEDIA_TYPE","Content-Type must be application/json"),!1;let l=e.headers.origin;return!l||l===`http://${e.headers.host}`||(this.writeError(t,403,"FORBIDDEN_ORIGIN","Forbidden origin"),!1)}async readJsonBody(e,t){let r,n;try{r=await nO(e,t,4096)}catch{return this.writeError(t,413,"PAYLOAD_TOO_LARGE","Request body is too large")}if(!r.trim())return{};try{n=JSON.parse(r)}catch{return this.writeError(t,400,"INVALID_REQUEST","Invalid JSON body")}return!n||"object"!=typeof n||Array.isArray(n)?this.writeError(t,400,"INVALID_REQUEST","Invalid JSON body"):n}writeError(e,t,r,n){e.writableEnded||e.destroyed||nC(e,t,{error:{code:r,message:n}})}}let iA={"Cache-Control":"no-cache"};async function iT({request:e,response:t,url:r},n,i){let o;if("OPTIONS"===e.method){nA(t,iA),t.writeHead(204),t.end();return}if("GET"===e.method){let e;return void nC(t,200,function(e,t){if(!e?.debug_snapshot)return e;let{debug_snapshot:r,...n}=e;return t?{...n,snapshot:r}:n}(n.snapshot,null!=(e=r.searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase())??{stored:!1},iA)}if("POST"!==e.method)return void nC(t,405,{error:"Method not allowed"},iA);try{o=JSON.parse(await nO(e,t,0xa00000))}catch(e){nC(t,400,{error:e.message},iA);return}iC(n,i,o),nC(t,200,{ok:!0,updated_at_ms:n.updatedAtMs},iA)}function iC(e,t,r){var n;let i,o="string"==typeof(i=(n=r).snapshot.client_id??n.debug_snapshot?.client_id)&&i.trim()?i.trim():void 0;r=function(e,t){let r=e?.snapshot,n=t.snapshot,i=r?.runtime_snapshot,o=n.runtime_snapshot;if(!r||!i||r.client_id!==n.client_id)return t;if(!o){var a;let e;if(a=i.target,e=function(e){let t=e.render_targets?.currentTarget;if(t)return t;let r=e.context;if(r){if(Object.hasOwn(r,"widget_id"))return{type:"widget"};if(Object.hasOwn(r,"page_id")||Object.hasOwn(r,"page_path"))return{type:"page"}}}(n),a&&e&&(1===Object.keys(e).length?e.type!==a.type:JSON.stringify(e)!==JSON.stringify(a)))return t;let{root:r,...o}=i;return{...t,snapshot:{...n,runtime_snapshot:i},...t.debug_snapshot?{debug_snapshot:{...t.debug_snapshot,runtime_snapshot:o}}:{}}}return Object.hasOwn(o,"root")||!Object.hasOwn(i,"root")||i.updatedAtMs!==o.updatedAtMs||JSON.stringify(i.target)!==JSON.stringify(o.target)?t:{...t,snapshot:{...n,runtime_snapshot:{...o,root:i.root}}}}(o?t.getSnapshotStore(o).snapshot:e.snapshot,r),e.snapshot=r,e.updatedAtMs=Date.now(),t.noteSnapshot(o)}let iI="/app_developer/api/sandbox/",iO=`${iI}session/business_info/update`,iP=new Set([`${iI}resources/notices/pull`,`${iI}resources/tasks/pull`]),ik={"Access-Control-Expose-Headers":n_},iD=new Set;function i$(e,t,r,n,i,o){if("applet0930"!==process.env.DEBUG)return!1;let a=`${i[nb]??""} ${e} ${t.pathname}`,s=iP.has(t.pathname);if(s&&r>=500){if(iD.has(a))return!1;iD.add(a)}else s&&r<500&&iD.delete(a);let l=Number(process.hrtime.bigint()-n)/1e6;return nu.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:l,headers:i,logId:o}),!0}function iR({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a}){n$({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a})}function iN(e,t,r){return r&&!(iP.has(e.pathname)&&t>=500)}function iL(e,t){if(e.pathname!==iO||!t)return t;try{let e=JSON.parse(t);return JSON.stringify({...e,..."csr_pem"in e?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]"})}catch{return JSON.stringify({omitted:"invalid business info request"})}}async function iM({method:e,request:t,requestBody:r,requestHeaders:n,response:i,targetUrl:o,usePlatformFetch:a}){let s=process.hrtime.bigint(),l=nR(t,i);try{let t,d=a?await nG({internal:!0,path:`${o.pathname}${o.search}`,method:e,body:r,headers:n,signal:l}):await fetch(o,{body:"GET"===e||"HEAD"===e?void 0:r,headers:n,method:e,signal:l}),p=i$(e,o,d.status,s,n,d.headers.get(n_)??void 0);if(i.destroyed||i.writableEnded)return void d.body?.cancel().catch(()=>void 0);let c=await nP(d);return iN(o,d.status,p)&&iR({method:e,requestBody:iL(o,r),requestHeaders:n,responseBody:c,responseHeaders:d.headers,statusCode:d.status,targetUrl:o}),i.destroyed||i.writableEnded||(t=nx(d.headers,[n_]),nA(i,ik),i.writeHead(d.status,t),i.end(c)),{body:c,ok:d.ok}}catch(d){if(i.destroyed||i.writableEnded||l.aborted)return;let t=`Failed to proxy sandbox request: ${d instanceof Error?d.message:String(d)}`,a=i$(e,o,502,s,n);iN(o,502,a)&&iR({method:e,requestBody:iL(o,r),requestHeaders:n,responseBody:t,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:o}),nT(i,502,t,ik)}}async function ij(e,t,r={}){let n;if("POST"!==e.method)return void nT(t,405,"Method not allowed",ik);try{n=JSON.parse(await nO(e,t,0xa00000))}catch(e){nT(t,400,`Invalid sandbox proxy payload: ${e.message}`,ik);return}let i=function(e,t){if(!e.url)return;let r=new URL(e.url,t);if(!r.pathname.startsWith(iI))return;let n=new URL(`${r.pathname}${r.search}`,t);var i=e.params;if(i)for(let[e,t]of Object.entries(i))null!=t&&n.searchParams.set(e,String(t));return n}(n,r.targetOrigin??Q);if(!i)return void nT(t,404,"Sandbox endpoint not found",ik);if(!r.sandboxSessionId)return void nC(t,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},ik);let o=function(e,t,r,n){if(t.pathname.startsWith(`${iI}session/`)&&t.pathname!==`${iI}session/create`)return JSON.stringify({..."object"==typeof e.data&&null!==e.data?e.data:{},sandbox_session_id:n});if(void 0===e.data)return;if("object"!=typeof e.data||null===e.data||!r)return JSON.stringify(e.data);let i={...e.data};return t.pathname.startsWith(`${iI}jsb/`)&&"app_key"in i&&(i.app_key=r),t.pathname===`${iI}passport/open/auth`&&"client_key"in i&&(i.client_key=r),JSON.stringify(i)}(n,i,r.sandboxAppId,r.sandboxSessionId),a=n.method||"POST",s=function(e,t,r,n,i){let o=Object.fromEntries(Object.entries(nS({...e.headers,...r,...void 0===n?{}:{"content-length":String(Buffer.byteLength(n))},"content-type":"application/json"},t,{...nW(),...i?{[nb]:i}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]));for(let e of Object.keys(o))"accept-encoding"===e.toLowerCase()&&delete o[e];return o["accept-encoding"]="identity",o}(e,i,n.headers,o,r.sandboxSessionId),l=await iM({method:a,request:e,requestBody:o,requestHeaders:s,response:t,targetUrl:i,usePlatformFetch:!r.targetOrigin});if(i.pathname===iO&&l?.ok)try{let e=JSON.parse(l.body.toString("utf8"));(void 0===e.code||0===e.code)&&r.onBusinessInfoUpdated?.(function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t="string"==typeof e.csr_pem?e.csr_pem.trim():"",r="string"==typeof e.phone_num?e.phone_num.trim():"";return r?{...t?{csrPem:t}:{},phoneNum:r}:void 0}(n.data))}catch{}}let iU=f("node:util"),iB="/app_developer/api/sandbox/bridge/events",iF="/app_developer/api/sandbox/bridge/response",iW=new Set(["connection","content-length","host"]),iH=new Set(["heartbeat"]),iV=[500,1e3,2e3,5e3],iG=0;function iq(e){return e.length<=8?e:`${e.slice(0,4)}...${e.slice(-4)}`}function iJ(e,t=new Headers,r=""){return{response:e,responseHeaders:Object.fromEntries(t),statusText:r}}async function iK(e){let t,r,n=e.request_id||"";if(!n)return iJ({error_message:"bridge request_id is required",http_status:0,request_id:n,success:!1});if(!e.path?.startsWith("/"))return iJ({error_message:`invalid bridge request path: ${e.path??""}`,http_status:0,request_id:n,success:!1});let i=function(e){if(e.origin)try{var t;return new URL(e.path??"/",(t=e.origin).endsWith("/")?t:`${t}/`)}catch{return}}(e);if(!i)return iJ({error_message:`invalid bridge request origin: ${e.origin??""}`,http_status:0,request_id:n,success:!1});let o=(e.method||"GET").toUpperCase(),a=function(e){let t={};for(let[r,n]of Object.entries(e??{}))!r||iW.has(r.toLowerCase())||(t[r]=n);return t}(e.headers),s="GET"===o||"HEAD"===o?void 0:e.body??"",l=new AbortController,d=setTimeout(()=>l.abort(),(t="number"==typeof e.timeout_ms?e.timeout_ms:3e3,r="number"==typeof e.deadline_ms?e.deadline_ms-Date.now():t,Math.max(1,Math.min(t,r))));try{var p;let e=await fetch(i,{body:s,headers:a,method:o,redirect:"manual",signal:l.signal}),t=await e.text();return p={method:o,requestBody:s,requestHeaders:a,responseBody:t,responseHeaders:e.headers,statusCode:e.status,targetUrl:i},n$(p),iJ({body:t,http_status:e.status,request_id:n,success:!0},e.headers,e.statusText)}catch(e){return n$({method:o,requestBody:s,requestHeaders:a,responseBody:e instanceof Error?e.message:String(e),responseHeaders:new Headers,statusCode:0,targetUrl:i}),iJ({error_message:e instanceof Error?e.message:String(e),http_status:0,request_id:n,success:!1})}finally{clearTimeout(d)}}function iz(e,t=new Set){if(Array.isArray(e)){for(let r of e)iz(r,t);return[...t]}if(!e||"object"!=typeof e)return[...t];for(let[r,n]of Object.entries(e)){if(r.toLowerCase().replace(/[_-]/g,"").includes("logid")){if("string"==typeof n&&n)t.add(n);else if(Array.isArray(n))for(let e of n)"string"==typeof e&&e&&t.add(e);continue}iz(n,t)}return[...t]}function iY(e,t){e.onLog?.(t)}function iX(e){try{return JSON.parse(e)}catch{return}}function iZ({detail:e,requestHeaders:t,status:r,targetUrl:n}){if("applet0930"===process.env.DEBUG){if("number"==typeof r)return void nu.request({method:"CONNECT",url:n.pathname,statusCode:r,headers:t,context:{detail:e}});nu.info("Bridge connection pending",{url:n.pathname,detail:e,ppe:eS(t)})}}function iQ(e,t={}){"applet0930"===process.env.DEBUG&&nu.info(e,t)}async function i0(e,t){let r=JSON.stringify({sandbox_session_id:e.sandboxSessionId,...t}),n={"content-type":"application/json",[nb]:e.sandboxSessionId,...nW()};if(e.targetOrigin){let t=new URL(iF,e.targetOrigin),i=await fetch(t,{body:r,headers:n,method:"POST"}),o=await i.text();if(n$({method:"POST",requestBody:r,requestHeaders:n,responseBody:o,responseHeaders:i.headers,statusCode:i.status,targetUrl:t}),!i.ok)throw Error(`upload bridge response failed: ${i.status} ${o}`);return{responseBody:o,responseHeaders:Object.fromEntries(i.headers),responsePayload:iX(o)}}let i=new URL(iF,Q),o=await nG({body:r,headers:n,internal:!0,method:"POST",path:iF}),a=await o.text();if(n$({method:"POST",requestBody:r,requestHeaders:n,responseBody:a,responseHeaders:o.headers,statusCode:o.status,targetUrl:i}),!o.ok)throw Error(`upload bridge response failed: ${o.status} ${a}`);return{responseBody:a,responseHeaders:Object.fromEntries(o.headers),responsePayload:iX(a)}}async function i1(e,t){let r;try{r=JSON.parse(t)}catch(e){nu.warn("Sandbox Bridge request parse failed",{reason:e.message});return}let n=Date.now(),i=`bridge-${n}-${++iG}`,o=r.request_id||"",a={id:i,request:r,requestId:o,sandboxSessionId:e.sandboxSessionId,timestamp:n};iY(e,{...a,logIds:iz(r),status:"pending",updatedAtMs:n});let s=await iK(r),l={...s.response,headers:s.responseHeaders,status_text:s.statusText};try{let t=await i0(e,s.response);iY(e,{...a,logIds:iz([r,l,t]),response:l,status:s.response.success?"success":"error",updatedAtMs:Date.now()})}catch(t){throw iY(e,{...a,errorMessage:t instanceof Error?t.message:String(t),logIds:iz([r,l]),response:l,status:"error",updatedAtMs:Date.now()}),t}}async function i3(e,t,r){let n={sandbox_session_id:e.sandboxSessionId},i=new URL(`${iB}?sandbox_session_id=${encodeURIComponent(e.sandboxSessionId)}`,Q),o=(p=e.sandboxSessionId,{accept:"text/event-stream",host:i.host,[nb]:p,...nW()});iZ({detail:`host=${o.host} session=${iq(e.sandboxSessionId)}`,requestHeaders:o,status:"pending",targetUrl:i}),iQ("bridge/events request",{headers:{accept:o.accept,host:o.host,[nb]:iq(e.sandboxSessionId),"x-tt-env":o["x-tt-env"],"x-use-ppe":o["x-use-ppe"]},path:iB,query:n});let a=await nG({headers:o,internal:!0,method:"GET",path:iB,query:n,signal:t});if(iZ({detail:`content-type=${a.headers.get("content-type")??""}`,requestHeaders:o,status:a.status,targetUrl:i}),!a.ok||!a.body){let e=await a.text().catch(()=>"");n$({method:"GET",requestBody:void 0,requestHeaders:o,responseBody:e,responseHeaders:a.headers,statusCode:a.status,targetUrl:i}),nu.warn("Sandbox Bridge events request failed",{status:a.status,body:e.slice(0,500)});let t=Error(`Sandbox Bridge SSE failed: ${a.status} ${e}`);throw t.status=a.status,t}n$({method:"GET",requestBody:void 0,requestHeaders:o,responseBody:"",responseHeaders:a.headers,statusCode:a.status,targetUrl:i}),r?.();let s=a.body.getReader(),l=new iU.TextDecoder,d="";for(;!t.aborted;){let{done:t,value:r}=await s.read();if(t){iQ("bridge/events stream ended",{session:iq(e.sandboxSessionId)});break}let n=(d+=l.decode(r,{stream:!0})).search(/\r?\n\r?\n/);for(;n>=0;){let t=d.slice(0,n),r=d.slice(n).match(/^\r?\n\r?\n/);d=d.slice(n+(r?.[0].length??2));let s=function(e){let t="message",r=[];for(let n of e.split(/\r?\n/)){if(n.startsWith("event:")){t=n.slice(6).trim();continue}n.startsWith("data:")&&r.push(n.slice(5).trimStart())}return{data:r.join("\n"),name:t}}(t);if(!function(e,t){if("applet0930"!==process.env.DEBUG||iH.has(e.name))return;let r=function(e){try{let t=JSON.parse(e);return"string"==typeof t.request_id?t.request_id:void 0}catch{return}}(e.data);nu.info("Bridge event received",{event:e.name,requestId:r,ppe:eS(t)}),nu.info(`Event detail
158
- ${e.data}`)}(s,o),"bridge_request"===s.name){var p,c=a.headers,u=a.status;n$({method:`EVENT ${s.name}`,requestBody:s.data,requestHeaders:o,responseBody:"",responseHeaders:c,statusCode:u,targetUrl:i}),i1(e,s.data).catch(e=>{nu.warn("Sandbox Bridge request failed",{reason:e.message})})}else if("TOOL_CALL"===s.name){let t=es(iX(s.data));t?Promise.resolve(e.onSimulatorToolCall?.(t)).catch(e=>{nu.warn("Sandbox tool call forwarding failed",{reason:e instanceof Error?e.message:String(e),requestId:t.request_id,toolCallId:t.tool_call.tool_call_id})}):nu.warn("Sandbox tool call event parse failed")}else if("sandbox_resource_changed"===s.name){let t=function(e){let t=iX(e);if(!t||"object"!=typeof t||Array.isArray(t))return;let r=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,n=r?.resource,i=r?.action,o=r?.resource_id,a=r?.revision;if(("notice"===n||"task"===n)&&("upsert"===i||"remove"===i)&&"string"==typeof o&&o&&("number"==typeof a||"string"==typeof a))return{action:i,eventId:"string"==typeof t.event_id?t.event_id:"",occurredAtMs:"number"==typeof t.occurred_at_ms?t.occurred_at_ms:void 0,resource:n,resourceId:o,revision:a}}(s.data);t?e.onResourceChanged?.(t):nu.warn("Sandbox resource event parse failed")}else if("card_delta"===s.name){let t=function(e){let t=iX(e);if(!t||"object"!=typeof t||Array.isArray(t))return;let r=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,n=r?.card_delta;if(!("card_delta"!==t.type||!n||"object"!=typeof n||Array.isArray(n)))return n}(s.data);t?e.onSimulatorEvent?.({payload:t,type:"card_delta"}):nu.warn("Sandbox simulator event parse failed",{event:s.name})}else if("get_simulator_card_snapshots"===s.name){let t=iX(s.data);t&&"object"==typeof t&&!Array.isArray(t)?e.onSimulatorEvent?.({payload:t,type:s.name}):nu.warn("Sandbox simulator event parse failed",{event:s.name})}n=d.search(/\r?\n\r?\n/)}}}async function i2(e,t){let r=0,n=!1;for(;!t.aborted;){try{await i3(e,t,()=>{n=!1,e.onConnectionStatusChange?.("connected")}),r=0}catch(r){if(t.aborted)return;let e=r.status;if(n||(nu.warn("无法接收来自平台服务的请求",{reason:r.message}),n=!0),401===e||403===e||404===e)return}e.onConnectionStatusChange?.("reconnecting"),await (0,v.setTimeout)(iV[Math.min(r,iV.length-1)],void 0,{signal:t}).catch(()=>void 0),r+=1}}let i4=f("node:net"),i5="/__web_sdk_sandbox_bridge_logs",i9="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",i8="/app_developer/api/sandbox/session/business_info/update";function i7(e){if(!e)return!1;try{return to.statSync(e).isFile()}catch{return!1}}async function i6({body:e,headers:t,method:r,sandboxPath:n,targetOrigin:i,targetUrl:o}){let a=new AbortController,s=setTimeout(()=>a.abort(),3e4);try{return i?await fetch(o,{body:e,headers:t,method:r,signal:a.signal}):await nG({internal:!0,path:n,body:e,headers:t,method:r,signal:a.signal})}catch(e){if(a.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${o}`);throw e}finally{clearTimeout(s)}}function oe(e,t){return(e?.[t]??process.env[t])?.trim()??""}function ot(e,t,r,n,i,o){if("applet0930"!==process.env.DEBUG)return;let a=Number(process.hrtime.bigint()-n)/1e6;nu.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:a,headers:i,logId:o})}function or({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a}){n$({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a})}async function on(e,t,r,n,i,o){let a,s,l="/app_developer/api/sandbox/session/create",d="POST",p=function(){let e=new Set;for(let t of(process.env[i9]??"").split(",")){let r=t.trim();if(r)try{let t=new URL(r),n=t.hostname.replace(/^\[|\]$/g,"").toLowerCase(),i="localhost"===n||"::1"===n||4===(0,i4.isIP)(n)&&n.startsWith("127.");if("http:"!==t.protocol&&"https:"!==t.protocol||!i)throw Error("only loopback HTTP(S) origins are allowed");e.add(t.origin)}catch(e){throw Error(`${i9} contains an invalid origin: ${r} (${e instanceof Error?e.message:String(e)})`)}}return[...e]}(),c=JSON.stringify({sandbox_project_id:e,manifest:r?.()??(i7(t)?to.readFileSync(t,"utf8"):""),business_templates:i7(n)?to.readFileSync(n,"utf8"):"",...o?{app_id:o}:{},...p.length>0?{bridge_origins:p}:{}}),u={"content-type":"application/json",...nW()},h=new URL(l,i??Q),m=process.hrtime.bigint();try{a=await i6({body:c,headers:u,method:d,sandboxPath:l,targetOrigin:i,targetUrl:h})}catch(t){let e=`创建 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw ot(d,h,502,m,u),or({method:d,requestBody:c,requestHeaders:u,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:h}),t}let f=a.headers.get(n_)||"",g=await a.text();ot(d,h,a.status,m,u,f),or({method:d,requestBody:c,requestHeaders:u,responseBody:g,responseHeaders:a.headers,statusCode:a.status,targetUrl:h});try{s=JSON.parse(g||"{}")}catch{throw Error(`创建 Sandbox session 失败:HTTP ${a.status} ${a.statusText||g||"响应不是有效 JSON"}${f?`,log_id=${f}`:""}`)}if(!a.ok||0!==s.code)throw Error(`创建 Sandbox session 失败:${s.message||a.statusText||a.status}${s.log_id||f?`,log_id=${s.log_id||f}`:""}`);let y=s.data?.sandbox_session_id,b=s.data?.sandbox_appid;if(!y||!b)throw Error(`创建 Sandbox session 失败:响应缺少 ${y?"sandbox_appid":"sandbox_session_id"}${s.log_id||f?`,log_id=${s.log_id||f}`:""}`);return{appId:b,sessionId:y}}async function oi(e,t,r,n,i,o){try{return await on(e,t,r,n,i,o)}catch(e){return nu.warn(`Sandbox 平台服务模拟已跳过:${e instanceof Error?e.message:String(e)}`),{appId:"",sessionId:""}}}function oo(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function oa(e){return{csrUploaded:!!e,phoneNumberUploaded:!0}}async function os(e,t){let r,n,i="/app_developer/api/sandbox/session/business_info/get",o="POST",a=JSON.stringify({sandbox_session_id:e}),s={"content-type":"application/json",...nW()},l=new URL(i,t??Q),d=process.hrtime.bigint();try{r=await i6({body:a,headers:s,method:o,sandboxPath:i,targetOrigin:t,targetUrl:l})}catch(e){throw ot(o,l,502,d,s),e}let p=r.headers.get(n_)||"",c=await r.text();ot(o,l,r.status,d,s,p);try{n=JSON.parse(c||"{}")}catch{throw or({method:o,requestBody:a,requestHeaders:s,responseBody:JSON.stringify({omitted:"invalid business info response"}),responseHeaders:r.headers,statusCode:r.status,targetUrl:l}),Error(`获取 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${p?`,log_id=${p}`:""}`)}let u={csrUploaded:!!n.data?.csr_pem?.trim(),phoneNumberUploaded:!!n.data?.phone_num?.trim()};if(or({method:o,requestBody:a,requestHeaders:s,responseBody:JSON.stringify({code:n.code,data:u,log_id:n.log_id}),responseHeaders:r.headers,statusCode:r.status,targetUrl:l}),!r.ok||void 0!==n.code&&0!==n.code)throw Error(`获取 Sandbox session 信息失败:${n.message||r.statusText||r.status}${n.log_id||p?`,log_id=${n.log_id||p}`:""}`);return u}async function ol(e,t){if(!e)return oo();try{return await os(e,t)}catch(e){return nu.warn(`Sandbox session 信息查询已跳过:${e instanceof Error?e.message:String(e)}`),oo()}}async function od(e,t,r){let n,i,o="POST",a=JSON.stringify({...e.csrPem?{csr_pem:e.csrPem}:{},phone_num:e.phoneNum,sandbox_session_id:t}),s={"content-type":"application/json",...nW(),[nb]:t},l=new URL(i8,r??Q),d=process.hrtime.bigint();try{n=await i6({body:a,headers:s,method:o,sandboxPath:i8,targetOrigin:r,targetUrl:l})}catch(e){throw ot(o,l,502,d,s),e}let p=n.headers.get(n_)||"",c=await n.text();ot(o,l,n.status,d,s,p),or({method:o,requestBody:JSON.stringify({...e.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:t}),requestHeaders:s,responseBody:c,responseHeaders:n.headers,statusCode:n.status,targetUrl:l});try{i=JSON.parse(c||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${n.status} 响应不是有效 JSON${p?`,log_id=${p}`:""}`)}if(!n.ok||void 0!==i.code&&0!==i.code)throw Error(`更新 Sandbox session 信息失败:${i.message||n.statusText||n.status}${i.log_id||p?`,log_id=${i.log_id||p}`:""}`)}async function op(e,t,r,n){if(e&&t.phoneNum&&(!r||t.csrPem))try{return await od({...t.csrPem?{csrPem:t.csrPem}:{},phoneNum:t.phoneNum},e,n),nu.info("Sandbox business info 已自动上传",{sessionId:e}),oa(t.csrPem)}catch(e){nu.warn(`Sandbox business info 自动上传已跳过:${e instanceof Error?e.message:String(e)}`);return}}async function oc(e,t){let r,n="/app_developer/api/sandbox/session/revoke",i="POST",o=JSON.stringify({sandbox_session_id:e}),a={"content-type":"application/json",...nW()},s=new URL(n,t??Q),l=process.hrtime.bigint();try{r=await i6({body:o,headers:a,method:i,sandboxPath:n,targetOrigin:t,targetUrl:s})}catch(t){let e=`撤回 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw ot(i,s,502,l,a),or({method:i,requestBody:o,requestHeaders:a,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:s}),t}let d=r.headers.get(n_)||"",p=await r.text();ot(i,s,r.status,l,a,d),or({method:i,requestBody:o,requestHeaders:a,responseBody:p,responseHeaders:r.headers,statusCode:r.status,targetUrl:s});let c=JSON.parse(p||"{}");if(!r.ok||0!==c.code)throw Error(`撤回 Sandbox session 失败:${c.message||r.statusText||r.status}${c.log_id||d?`,log_id=${c.log_id||d}`:""}`)}async function ou(e){if(e.recreatePromise)return e.recreatePromise;e.recreatePromise=(async()=>{var t;let r=e.sandboxSessionId;r&&await oc(r,e.sandboxTargetOrigin),e.bridge?.close(),e.bridge=void 0;let n=await on(e.sandboxProjectId,e.simulatorManifestPath,e.simulatorManifestReader,e.simulatorBusinessTemplatesPath,e.sandboxTargetOrigin,e.sandboxSessionAppId),i=n.sessionId,o=!e.sandboxSessionAppId,a=await op(i,e.businessInfoInput,o,e.sandboxTargetOrigin)??await ol(i,e.sandboxTargetOrigin);return e.sandboxAppId=n.appId,e.sandboxSessionId=i,e.businessInfo=a,(t=e).resourceConnectionStatus="connecting",t.resourceEventSequence=0,t.resourceEvents.length=0,t.simulatorEventSequence=0,t.simulatorEvents.length=0,t.resourceGeneration+=1,of(t),e.bridge=og(e,i),nu.info("Sandbox session 已重建",{sessionId:i}),{...n,businessInfoUploaded:a.phoneNumberUploaded&&(!o||a.csrUploaded)}})();try{return await e.recreatePromise}finally{e.recreatePromise=void 0}}function oh(e){return{bridgeLogs:e.bridgeLogs,bridgeLogsUpdatedAtMs:e.bridgeLogsUpdatedAtMs,connectionStatus:e.resourceConnectionStatus,events:e.resourceEvents,generation:e.resourceGeneration,instanceId:e.resourceInstanceId,simulatorEvents:e.simulatorEvents,updatedAtMs:e.resourceEventsUpdatedAtMs}}function om(e){clearTimeout(e.logBroadcastTimer),e.logBroadcastTimer=void 0;let t=oh(e);for(let r of e.eventListeners)r(t)}function of(e){e.resourceEventsUpdatedAtMs=Math.max(Date.now(),e.resourceEventsUpdatedAtMs+1),om(e)}function og(e,t){var r={onConnectionStatusChange:t=>{e.resourceConnectionStatus!==t&&(e.resourceConnectionStatus=t,of(e))},onLog:t=>{let r=e.bridgeLogs.findIndex(e=>e.id===t.id);r>=0?e.bridgeLogs[r]=t:(e.bridgeLogs.push(t),e.bridgeLogs.length>200&&e.bridgeLogs.splice(0,e.bridgeLogs.length-200)),e.bridgeLogsUpdatedAtMs=Math.max(Date.now(),e.bridgeLogsUpdatedAtMs+1),e.logBroadcastTimer??=setTimeout(()=>om(e),50)},onResourceChanged:t=>{e.resourceEvents.push({...t,sequence:++e.resourceEventSequence}),e.resourceEvents.length>200&&e.resourceEvents.splice(0,e.resourceEvents.length-200),of(e)},onSimulatorEvent:t=>{e.simulatorEvents.push({...t,sequence:++e.simulatorEventSequence}),e.simulatorEvents.length>200&&e.simulatorEvents.splice(0,e.simulatorEvents.length-200),of(e)},onSimulatorToolCall:e.onSimulatorToolCall,sandboxSessionId:t,targetOrigin:e.sandboxTargetOrigin};if(!r.sandboxSessionId)return void nu.warn("Sandbox Bridge skipped: missing sandbox session id");let n=new AbortController;return iQ("start sandbox bridge",{session:iq(r.sandboxSessionId)}),r.onConnectionStatusChange?.("connecting"),i2(r,n.signal),{close:()=>n.abort()}}function oy(e){e.bridgeLogs.length=0,e.bridgeLogsUpdatedAtMs=Math.max(Date.now(),e.bridgeLogsUpdatedAtMs+1),om(e)}async function ob(e,t,r){if("POST"!==e.method)return void nT(t,405,"Method not allowed");if(!r)return void nT(t,503,"Sandbox session is not initialized");try{let n=await nO(e,t,1048576);if(n){let e=JSON.parse(n);if(void 0!==e.csrPem&&"string"!=typeof e.csrPem||"string"!=typeof e.phoneNum)return void nT(t,400,"Invalid Sandbox business info");r.businessInfoInput={..."string"==typeof e.csrPem&&e.csrPem.trim()?{csrPem:e.csrPem.trim()}:{},phoneNum:e.phoneNum.trim()}}let i=await ou(r);nC(t,200,{code:0,data:{sandbox_appid:i.appId,business_info_uploaded:i.businessInfoUploaded,sandbox_session_id:i.sessionId},message:"ok"})}catch(e){nT(t,500,e.message)}}function o_(e){let t=e.appId?.trim(),r=t&&!t.startsWith("doubao-sandbox-app-")?t:void 0,n=function(e){let t=ta.resolve(e??process.cwd()),r=t;try{r=to.realpathSync.native(t)}catch{}return(0,ib.createHash)("sha256").update(r).digest("hex")}(e.appDirectory),i=function(e,t){let r=oe(e,"DOUBAO_SANDBOX_PHONE_NUM"),n=oe(e,"DOUBAO_SANDBOX_CSR_FILE"),i=function(e,t){if(!e)return;let r=ta.isAbsolute(e)?e:ta.resolve(t??process.cwd(),e);return i7(r)?r:void 0}(n,t),o="";if(n&&!i)nu.warn(`Sandbox CSR 文件不存在:${n}`);else if(i)try{o=to.readFileSync(i,"utf8").trim()}catch(e){nu.warn(`Sandbox CSR 文件读取失败:${e instanceof Error?e.message:String(e)}`)}return{...r?{phoneNum:r}:{},...o?{csrPem:o}:{}}}(e.env,e.appDirectory),o=`${i.phoneNum??""}\0${i.csrPem??""}`;return{businessInfoInput:i,businessInfoInputKey:o,businessTemplatesPath:e.businessTemplatesPath,key:JSON.stringify([o,n,r,e.targetOrigin,e.businessTemplatesPath,e.manifestPath]),manifestReader:e.manifestReader,manifestPath:e.manifestPath,onSimulatorToolCall:e.onSimulatorToolCall,projectId:n,sessionAppId:r,targetOrigin:e.targetOrigin}}class ov{configKey;manifestReader;state;constructor(e,t,r){this.state=e,this.configKey=t,this.manifestReader=r}static async start(e){let t=o_(e),r=await oi(t.projectId,t.manifestPath,t.manifestReader,t.businessTemplatesPath,t.targetOrigin,t.sessionAppId),n=!t.sessionAppId,i={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await op(r.sessionId,t.businessInfoInput,n,t.targetOrigin)??await ol(r.sessionId,t.targetOrigin),businessInfoInput:t.businessInfoInput,eventListeners:new Set,onSimulatorToolCall:t.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,resourceInstanceId:(0,ib.randomUUID)(),simulatorEventSequence:0,simulatorEvents:[],sandboxAppId:r.appId,sandboxProjectId:t.projectId,sandboxSessionAppId:t.sessionAppId,sandboxSessionId:r.sessionId,sandboxTargetOrigin:t.targetOrigin,simulatorBusinessTemplatesPath:t.businessTemplatesPath,simulatorManifestReader:t.manifestReader,simulatorManifestPath:t.manifestPath},o=new ov(i,t.key,t.manifestReader);return i.bridge=r.sessionId?og(i,r.sessionId):void 0,o}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close(),clearTimeout(this.state.logBroadcastTimer),this.state.eventListeners.clear()}subscribeEvents(e){return this.state.eventListeners.add(e),e(oh(this.state)),()=>{this.state.eventListeners.delete(e)}}clearBridgeLogs(){oy(this.state)}matches(e){let t=o_(e);return this.configKey===t.key&&this.manifestReader===t.manifestReader}getDebugContext(){var e;let t;return{fileSystemNamespace:(t=(e=this.state).sandboxSessionAppId?`real-app\0${e.sandboxSessionAppId}`:`virtual-app\0${e.sandboxAppId}\0${e.sandboxProjectId}`,`sandbox-v1:${(0,ib.createHash)("sha256").update(t).digest("hex")}`),sandboxSessionAvailable:!!this.state.sandboxSessionId,sandboxCsrRequired:!this.state.sandboxSessionAppId,sandboxCsrUploaded:this.state.businessInfo.csrUploaded,sandboxPhoneNumberUploaded:this.state.businessInfo.phoneNumberUploaded,sandboxBridgeLogsEndpoint:i5,sandboxEventsAvailable:!0,...this.state.businessInfoInput.csrPem?{sandboxCsrPem:this.state.businessInfoInput.csrPem}:{},...this.state.businessInfoInput.phoneNum?{sandboxPhoneNum:this.state.businessInfoInput.phoneNum}:{}}}getRequestRoutes(){return[{match:i5,handle:({request:e,response:t})=>{var r;return r=this.state,void("GET"!==e.method&&"DELETE"!==e.method?nT(t,405,"Method not allowed"):("DELETE"===e.method&&r&&oy(r),nC(t,200,{logs:r?.bridgeLogs??[],updatedAtMs:r?.bridgeLogsUpdatedAtMs??0},{"Cache-Control":"no-cache"})))}},{match:"/__web_sdk_sandbox_resource_events",handle:({request:e,response:t})=>{var r;return r=this.state,void("GET"!==e.method?nT(t,405,"Method not allowed"):nC(t,200,{connectionStatus:r?.resourceConnectionStatus??"connecting",events:r?.resourceEvents??[],generation:r?.resourceGeneration??0,simulatorEvents:r?.simulatorEvents??[],updatedAtMs:r?.resourceEventsUpdatedAtMs??0},{"Cache-Control":"no-cache"}))}},{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>ij(e,t,{onBusinessInfoUpdated:e=>{this.state.businessInfo=oa(e?.csrPem),e&&(this.state.businessInfoInput=e)},sandboxAppId:this.state.sandboxAppId,sandboxSessionId:this.state.sandboxSessionId,targetOrigin:this.state.sandboxTargetOrigin})},{match:"/__web_sdk_sandbox_session_recreate__",handle:({request:e,response:t})=>ob(e,t,this.state)}]}}function ow(e,t){return e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath)}let oS="/__tools/tools.json",oE="/__events/events.json",ox="manifest.yaml",oA="skill";function oT(e){if(!e)return!1;try{return to.statSync(e).isFile()}catch{return!1}}function oC(e,t){if(!e)return;let r=ta.isAbsolute(e)?e:ta.resolve(t??process.cwd(),e);return oT(r)?r:void 0}function oI(e,t){if(e&&t)return ta.relative(t,e).split(ta.sep).join("/")||"."}function oO(e){let t=ta.resolve(e);for(;;){if(oT(ta.join(t,ox)))return t;let e=ta.dirname(t);if(e===t)return;t=e}}function oP(e){try{return to.lstatSync(e),!0}catch{return!1}}function ok(e,t,r,n){let i;if(!t.reader&&oT(t.sourcePath)){var o;let r,i=to.statSync(t.sourcePath);nA(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":i.size,"Content-Type":n}),o=t.sourcePath,(r=to.createReadStream(o)).once("error",()=>e.destroy()),r.pipe(e);return}try{i=t.reader?.()}catch{i=void 0}void 0===i?nT(e,404,`${r} not found`):(nA(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(i),"Content-Type":n}),e.end(i))}function oD(e,t){return function(e){let t,r;if(!e)return{layout:"missing",entries:[]};let n=ta.resolve(e);try{t=to.lstatSync(n)}catch(e){if("ENOENT"===e.code)return{directory:n,layout:"missing",entries:[]};return{directory:n,layout:"invalid",entries:[],error:`skill path cannot be inspected: ${n}: ${e.message}`}}if(t.isSymbolicLink()||!t.isDirectory())return{directory:n,layout:"invalid",entries:[],error:`skill path must be a non-symlink directory: ${n}`};try{var i;let e;i=n,e=[],function t(r){for(let n of to.readdirSync(r,{withFileTypes:!0})){if(n.isSymbolicLink())continue;let o=ta.join(r,n.name);n.isDirectory()?t(o):n.isFile()&&"SKILL.md"===n.name&&e.push(function(e,t){let r=ta.relative(e,t).split(ta.sep).join("/");return{content:to.readFileSync(t,"utf8"),relativePath:r}}(i,o))}}(i),r=e}catch(e){return{directory:n,layout:"invalid",entries:[],error:`skill directory is not readable: ${n}: ${e.message}`}}return r.sort(ow),r.length>0?{directory:n,layout:"resolved",entries:r}:{directory:n,layout:"missing",entries:[]}}(function(e,t){if(t){if(!t)return;if(ta.isAbsolute(t))return t;let r=e?oO(e):void 0,n=[e,r,process.cwd()].map(e=>ta.resolve(e??process.cwd(),t));return[...new Set(n)].find(oP)??n[0]}if(!e)return;let r=oO(e);return[...new Set([r?ta.join(r,oA):void 0,ta.join(e,oA),ta.join(process.cwd(),oA)].filter(Boolean))].find(oP)}(e,t))}class o${appDirectory;businessTemplatesPath;manifestPath;manifestReader;eventsConfigReader;eventsConfigSource;toolsConfigReader;toolsConfigSource;manifestSource;skillsDirectory;sourceKey;constructor(e){var t,r,n;this.appDirectory=e.appDirectory,this.manifestPath=e.manifestPath?oC(e.manifestPath,e.appDirectory):e.manifestSourcePath??(e.manifestReader?void 0:function(e){if(!e)return;let t=oO(e);return[...new Set([t?ta.join(t,ox):void 0,ta.join(process.cwd(),ox)].filter(Boolean))].find(oT)}(e.appDirectory)),this.businessTemplatesPath=(t=this.manifestPath,r=e.businessTemplatesPath,n=e.appDirectory,r?oC(r,n):t?oC(ta.join(ta.dirname(t),"business-templates.yaml"),n):void 0),this.manifestReader=e.manifestReader,this.eventsConfigReader=e.eventsConfigReader,this.toolsConfigReader=e.toolsConfigReader,this.eventsConfigSource={reader:e.eventsConfigReader,sourcePath:e.eventsConfigSourcePath},this.skillsDirectory=e.skillsDirectory;let i=oD(e.appDirectory,this.skillsDirectory);if(e.skillsDirectory&&"resolved"!==i.layout)throw Error(i.error??`Simulator skills directory contains no runtime Skill: ${e.skillsDirectory}`);this.toolsConfigSource={reader:e.toolsConfigReader,sourcePath:e.toolsConfigSourcePath},this.manifestSource={reader:e.manifestReader,sourcePath:e.manifestSourcePath??this.manifestPath},this.sourceKey=JSON.stringify([this.appDirectory,this.businessTemplatesPath,this.manifestPath,this.eventsConfigSource.sourcePath,this.toolsConfigSource.sourcePath,this.manifestSource.sourcePath,this.skillsDirectory])}matches(e){let t=new o$(e);return this.sourceKey===t.sourceKey&&this.eventsConfigReader===t.eventsConfigReader&&this.toolsConfigReader===t.toolsConfigReader&&this.manifestReader===t.manifestReader}getDebugContext(){let e=oD(this.appDirectory,this.skillsDirectory),t="resolved"===e.layout?e.directory:void 0,r=oI(this.businessTemplatesPath,this.appDirectory),n=oI(this.eventsConfigSource.sourcePath,this.appDirectory),i=oI(this.toolsConfigSource.sourcePath,this.appDirectory),o=oI(this.manifestSource.sourcePath,this.appDirectory),a=oI(t,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:oE,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...n?{eventsConfigRelativePath:n}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:oS,...i?{toolsConfigRelativePath:i}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,...o?{simulatorManifestRelativePath:o}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...r?{simulatorBusinessTemplatesRelativePath:r}:{}}:{},...t?{simulatorSkillsDirectoryOriginalUrl:t,...a?{simulatorSkillsDirectoryRelativePath:a}:{}}:{}}}getRequestRoutes(){return[{match:oE,handle:({response:e})=>ok(e,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:oS,handle:({response:e})=>ok(e,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:e})=>ok(e,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:e})=>{let t;"missing"===(t=oD(this.appDirectory,this.skillsDirectory)).layout?nT(e,404,"Simulator skills directory not found"):"invalid"===t.layout?nT(e,422,t.error??"Invalid simulator Skill layout"):nC(e,200,{skills:t.entries},{"Cache-Control":"no-cache"})}}]}}let oR=f("node:stream"),oN="/app_developer/api",oL=`${oN}/simulator/images/upload`,oM=new Set([`${oN}/simulator/chat`,oL,`${oN}/simulator/tool/report`]),oj={"Access-Control-Expose-Headers":n_};async function oU(e,t,r,n){if(!oM.has(r.pathname))return void nT(t,404,"未找到模拟器接口",oj);let i=n.targetOrigin??Q,o=new URL(`${r.pathname}${r.search}`,i),a=nR(e,t);try{var s;let i=e.method??"GET",l=process.hrtime.bigint(),d=function(e,t,r){return Object.fromEntries(Object.entries(nS(e.headers,t,{...nW(),...r?{[nb]:r}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]))}(e,o,n.getSandboxSessionId?.()),p=await oB(e,t,r,i),c=n.targetOrigin?await fetch(o,{body:p,headers:d,method:i,signal:a}):await nG({internal:!0,path:`${r.pathname}${r.search}`,method:i,body:p,headers:d,signal:a});if(function(e,t,r,n,i,o){if("applet0930"!==process.env.DEBUG)return;let a=Number(process.hrtime.bigint()-n)/1e6;nu.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:a,headers:i,logId:o})}(i,r,c.status,l,d,c.headers.get(n_)??void 0),t.destroyed||t.writableEnded)return void c.body?.cancel().catch(()=>void 0);await oF({method:i,requestBody:(s=p)instanceof Uint8Array?`(binary, ${s.byteLength} bytes)`:s,requestHeaders:d,requestUrl:r,response:t,upstreamResponse:c})}catch(e){if(t.destroyed||t.writableEnded||a.aborted)return;nT(t,502,`代理模拟器请求失败:${e instanceof Error?e.message:String(e)}`,oj)}}async function oB(e,t,r,n){if("GET"!==n&&"HEAD"!==n)return r.pathname===oL?await nI(e,t,0xb00000):await nO(e,t,0xb00000)}async function oF({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:o}){var a,s;if(nA(i,oj),i.writeHead(o.status,nx(o.headers,[n_])),a=n,s=o,a.pathname===`${oN}/simulator/chat`||s.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await oW({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:o});if("applet0930"!==process.env.DEBUG)return o.body?void await (0,g.pipeline)(oR.Readable.fromWeb(o.body),i):void i.end();let l=await nP(o);n$({method:e,requestBody:t,requestHeaders:r,responseBody:l,responseHeaders:o.headers,statusCode:o.status,targetUrl:n}),i.end(l)}async function oW({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:o}){if(!o.body){n$({method:e,requestBody:t,requestHeaders:r,responseBody:"",responseHeaders:o.headers,statusCode:o.status,targetUrl:n}),i.end();return}let a=oR.Readable.fromWeb(o.body);if("applet0930"!==process.env.DEBUG)return void await (0,g.pipeline)(a,i);n$({method:e,requestBody:t,requestHeaders:r,responseBody:"(event stream)",responseHeaders:o.headers,statusCode:o.status,targetUrl:n});let s=new oR.Transform({transform(e,t,r){let i;try{i=String(e).split("\n\n").filter(Boolean)}catch(t){return nu.error(`failed to decode event stream chunk: ${t?.toString()}`),r(null,e)}for(let e of i)nu.info(`Event from ${n.pathname}${n.search}
159
- ${e}`);r(null,e)}});await (0,g.pipeline)(a,s,i)}async function oH(e,t){if("POST"!==e.method)return void nC(t,405,{message:"Method Not Allowed"});let r=nR(e,t);try{var n,i;let o,a,s,l=JSON.parse(await nO(e,t,0xa00000)),d=nw(l.url),p=(l.method??"GET").toUpperCase(),c=(n=l.header,a=new Headers(n??{"content-type":"application/json"}),["connection","content-length","host","origin","referer"].forEach(e=>a.delete(e)),a),u=await fetch(d,{signal:r,body:"GET"!==p&&"HEAD"!==p?function(e,t){let r=e.data;if(null==r)return;if("base64"===e.dataEncoding&&"string"==typeof r){var n;let e;return e=new ArrayBuffer((n=Buffer.from(r,"base64")).byteLength),new Uint8Array(e).set(n),e}if("string"==typeof r)return r;let i=t.get("content-type")?.toLowerCase()??"";if(i.includes("application/x-www-form-urlencoded")&&"object"==typeof r){let e=new URLSearchParams;return Object.entries(r).forEach(([t,r])=>{e.set(t,String(r))}),e.toString()}return i.includes("application/json")||"object"==typeof r?JSON.stringify(r):String(r)}(l,c):void 0,headers:c,method:p}),h="arraybuffer"===l.dataType||"arraybuffer"===l.responseType;if(h)o=Buffer.from(await u.arrayBuffer()).toString("base64");else{let e=await u.text();o="string"===l.dataType||0===e.length?e:JSON.parse(e)}nC(t,200,{data:o,dataEncoding:h?"base64":void 0,header:(i=u.headers,s={},i.forEach((e,t)=>{s[t]=e}),s),statusCode:u.status})}catch(e){if(r.aborted||t.destroyed)return;nC(t,500,{message:e instanceof Error?e.message:String(e)})}}let oV=f("../../../node_modules/.pnpm/send@1.2.0/node_modules/send/index.js"),oG="/__web_artifacts",oq="/wsd";function oJ(e,t,r,n,i={}){nA(t,i.headers),oV(e,n,{root:r}).once("error",n=>{if(404===n.statusCode&&i.fallbackPath)return void oJ(e,t,r,i.fallbackPath,{headers:i.headers});if(t.headersSent)return void t.destroy(n);let o=n.statusCode??500;nT(t,o,nh.STATUS_CODES[o]??"Internal Server Error")}).pipe(t)}let oK="/__webview",oz=`${oK}/client.js`,oY=`${oK}/page`,oX=`${oK}/runtime`,oZ=`${oK}/sw.js`,oQ="x-doubao-web-view-target",o0="Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",o1=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-bootstrap.js"),f.b),o3=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"),f.b),o2=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"),f.b);function o4(e,t,r,n=!1){if("GET"!==e.method&&"HEAD"!==e.method)return void nT(t,405,"Method Not Allowed");let i=to.readFileSync(r,"utf8");nA(t,{"Cross-Origin-Resource-Policy":"cross-origin"}),t.writeHead(200,{"cache-control":"no-store","content-length":Buffer.byteLength(i),"content-type":"text/javascript; charset=utf-8",...n?{"service-worker-allowed":"/"}:{}}),t.end("HEAD"===e.method?void 0:i)}function o5(e,t){let r=e.searchParams.get("parentOrigin")??t[0];if(!t.includes(r))throw Error("Invalid WebView parent origin");return r}async function o9(e,t,r,n){if("GET"!==e.method&&"HEAD"!==e.method)return void nT(t,405,"Method Not Allowed");let i=nR(e,t);try{let o=o5(r,n),a=nw(r.searchParams.get("url")??void 0),s=await fetch(a,{signal:i,headers:{"user-agent":o0,..."string"==typeof e.headers.accept?{accept:e.headers.accept}:{},..."string"==typeof e.headers["accept-language"]?{"accept-language":e.headers["accept-language"]}:{}},method:e.method}),l=s.url?new URL(s.url):a;l.hash=a.hash;let d=s.headers.get("content-type")??"",p=nx(s.headers);if(p["cache-control"]="no-cache",p["cross-origin-resource-policy"]="cross-origin",p["x-doubao-web-view-parent-origin"]=o,"HEAD"===e.method||!d.includes("text/html")){let r="HEAD"===e.method?void 0:Buffer.from(await s.arrayBuffer());nA(t),t.writeHead(s.status,{...p,[oQ]:l.toString(),...r?{"content-length":r.byteLength}:{}}),t.end(r);return}let c=function(e,t,r){let n=new URLSearchParams({mobileUserAgent:o0,originalPath:`${t.pathname}${t.search}${t.hash}`,parentOrigin:r}).toString().replaceAll("&","&amp;"),i=`<script src="${oz}?${n}"></script>`,o=/<head[^>]*>/i.exec(e);if(o){let t=o.index+o[0].length;return`${e.slice(0,t)}${i}${e.slice(t)}`}return`${i}${e}`}(await s.text(),l,o);nA(t),t.writeHead(s.status,{...p,[oQ]:l.toString(),"content-length":Buffer.byteLength(c)}),t.end(c)}catch(e){if(i.aborted||t.destroyed)return;nT(t,502,`代理 web-view 页面失败: ${e instanceof Error?e.message:String(e)}`)}}async function o8(e){let t=new URL(e).toString();try{await E(t)}catch(e){nu.error("打开 Web 模拟器失败",{error:e}),nu.info("请手动打开 Web 模拟器(本地)",{url:t})}}async function o7(e,t){await new Promise((r,n)=>{let i=t=>{e.off("listening",o),n(t)},o=()=>{e.off("error",i),r()};e.once("error",i),e.once("listening",o),e.listen(t,"127.0.0.1")})}async function o6(e){var t;let r=await P(9e3),n=nh.createServer(nM((t=[`http://127.0.0.1:${r}`,`http://localhost:${r}`],[{match:`${oK}/bootstrap`,handle:({request:e,response:r,url:n})=>{if("GET"!==e.method&&"HEAD"!==e.method)return void nT(r,405,"Method Not Allowed");try{nw(n.searchParams.get("url")??void 0),o5(n,t)}catch{nT(r,400,"Invalid WebView URL");return}nA(r,{"Cross-Origin-Resource-Policy":"cross-origin"}),r.writeHead(200,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),r.end("HEAD"===e.method?void 0:'<!doctype html><meta charset="utf-8"><script src="/__webview/bootstrap.js"><\/script>')}},{match:`${oK}/bootstrap.js`,handle:({request:e,response:t})=>o4(e,t,o1)},{match:oZ,handle:({request:e,response:t})=>o4(e,t,o2,!0)},{match:oz,handle:({request:e,response:t})=>o4(e,t,o3)},{match:oX,handle:({request:e,response:t,url:r})=>(function(e,t,r){let n;try{n=nw(r.searchParams.get("url")??void 0)}catch(e){nT(t,400,`无效的 web-view 请求地址: ${e instanceof Error?e.message:String(e)}`);return}let i=nS(e.headers,n,{"user-agent":o0});for(let e of Object.keys(i))e.startsWith("sec-fetch-")&&delete i[e];nN(e,t,{createResponseHeaders:e=>{let t=nE(e),r=Array.isArray(e.location)?e.location[0]:e.location;if(r&&URL.canParse(r,n)){let e=new URL(r,n);t.location=`${oX}?url=${encodeURIComponent(e.toString())}`}return t["cache-control"]="no-cache",t},errorMessage:"代理 web-view 运行时请求失败",requestHeaders:i,targetUrl:n})})(e,t,r)},{match:oY,handle:({request:e,response:r,url:n})=>o9(e,r,n,t)}]),({response:e})=>{nT(e,404,"WebView resource not found")}));await o7(n,0);let i=n.address(),o=`http://127.0.0.1:${i.port}`,a=nh.createServer(function({webViewOrigin:e,artifactOrigin:t,debugScenes:r,debuggerProtocol:n,distPath:i,getWidgetViewDataTemplates:o,mcpEndpoint:a,mcpHeaders:s,physicalDeviceDebugGateway:l,sandboxRuntime:d,simulatorAssets:p,simulatorTargetOrigin:c}){var u;let h={routes:[{match:e=>e.pathname.startsWith(oG),handle:({request:e,response:r,url:n})=>{let i,o;return i=n.pathname.replace(oG,"")||"/",o=new URL(`${i}${n.search}`,t),void nN(e,r,{createResponseHeaders:e=>({...nE(e),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:nS(e.headers,o),targetUrl:o})}},{match:e=>e.pathname===oq||e.pathname.startsWith(`${oq}/`),handle:({request:e,response:t,url:r})=>{let n;!(n=r.pathname.slice(`${oq}/`.length))||n!==ta.basename(n)?nT(t,404,"Not found"):oJ(e,t,ta.join(i,"wsd"),n,{headers:{"Cache-Control":"no-cache"}})}},{match:"/__web_sdk_request_proxy__",handle:({request:e,response:t})=>oH(e,t)},{match:"/__webview/page",handle:({request:t,response:r,url:n})=>{"GET"!==t.method&&"HEAD"!==t.method?nT(r,405,"Method Not Allowed"):(nA(r),r.writeHead(302,{"cache-control":"no-store",location:`${e}/__webview/bootstrap${n.search}`}),r.end())}},{match:"/__webview/sw.js",handle:({response:e})=>{nA(e),e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript","service-worker-allowed":"/"}),e.end(`self.addEventListener('install', e => e.waitUntil(self.skipWaiting()));
162
+ ${nG(Object.fromEntries(i))}
163
+ Response body: ${nV(n)}`)}function nJ(e,t){let r=new AbortController,n=()=>r.abort();return e.once("aborted",n),t.once("close",()=>{e.off("aborted",n),t.writableEnded||n()}),(e.aborted||t.destroyed)&&n(),r.signal}function nz(e,t,r){let n,i=("https:"===r.targetUrl.protocol?_:nT).request(r.targetUrl,{headers:r.requestHeaders,method:e.method},e=>{(n=e,t.destroyed||t.writableEnded)?e.destroy():(nM(t,r.commonHeaders),t.writeHead(e.statusCode??500,r.createResponseHeaders?.(e.headers)??nD(e.headers)),e.pipe(t))}),s=()=>{i.destroy(),n?.destroy()};i.once("error",e=>{if(!t.destroyed&&!t.writableEnded){if(t.headersSent)return void t.destroy(e);nU(t,502,`${r.errorMessage}: ${e.message}`,r.commonHeaders)}}),e.once("aborted",()=>{s()}),t.once("close",()=>{t.writableEnded||s()}),e.pipe(i)}async function nK(e,t,r){let n=t.find(({match:t})=>"string"==typeof t?e.url.pathname===t:t(e.url));await (n?.handle??r)(e)}function nY(e,t){return(r,n)=>{let i=nk(r);i?nK({request:r,response:n,url:i},e,t).catch(e=>(function(e,t){if(nA.error("处理 Web SDK 调试器请求失败",{error:t}),!e.destroyed&&!e.writableEnded){if(e.headersSent)return void e.destroy(t instanceof Error?t:void 0);nU(e,500,"Internal server error")}})(n,e)):nU(n,400,"Bad request")}}let nX=f("../../../node_modules/.pnpm/undici@6.22.0/node_modules/undici/index.js"),nZ={"sso-internal":"doubao-developer.bytedance.net","sms-internal":"doubao-developer-open.bytedance.net","sms-external":"hello.doubao-dev.com"},nQ={"http:":"80","https:":"443"},n0=new Map;function n1(){return process.env.X_TT_ENV?{"x-use-ppe":"1","x-tt-env":process.env.X_TT_ENV}:{}}function n2(e){let t=e.startsWith("/")?e:`/${e}`;return"/app_developer"===t||t.startsWith("/app_developer/")}async function n3(e,t={}){let r=function(e){var t,r;let n="string"==typeof e?new URL(e):e;if(function(e){let t=n8(["NO_PROXY","no_proxy"]);if(!t)return!1;let r=n9(e.hostname),n=e.port||nQ[e.protocol]||"";for(let e of t.split(",")){let t=function(e){let t=e.trim().toLowerCase();if(!t)return{host:""};if((t=t.replace(/^[a-z][a-z\d+.-]*:\/\//,"").split("/")[0]).startsWith("[")){let e=t.indexOf("]");if(-1!==e)return{host:n9(t.slice(0,e+1)),port:":"===t[e+1]?t.slice(e+2):void 0}}let r=t.indexOf(":")===t.lastIndexOf(":")?t.match(/:(\d+)$/):void 0;return{host:n9(r?t.slice(0,-r[0].length):t),port:r?.[1]}}(e);if(t.host&&(!t.port||t.port===n)){if("*"===t.host)return!0;if(t.host.startsWith("*.")){let e=t.host.slice(1);if(r.endsWith(e))return!0;continue}if(t.host.startsWith(".")){if(r.endsWith(t.host))return!0;continue}if(r===t.host)return!0}}return!1}(n))return;let i="https:"===(t=n.protocol)?n8(["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):"http:"===t?n8(["HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):void 0;if(!i)return;let s=(r=i,/^[a-z][a-z\d+.-]*:\/\//i.test(r)?r:`http://${r}`),o=n0.get(s);return o||(o=new nX.kT(s),n0.set(s,o)),o}(e),n=r?{...t,dispatcher:r}:t;return await fetch(e,n)}async function n4({internal:e,domainId:t,path:r,query:n,method:i="GET",body:s,headers:o,signal:a,auth:l=!0}){let c={method:i,body:s,headers:{...n1(),...o}};a&&(c.signal=a);let p=function({internal:e,domainId:t,path:r,query:n}){let i=r.startsWith("/")?r:`/${r}`,s=new URLSearchParams;for(let[e,t]of Object.entries(n||{}))null!=t&&s.append(e,t.toString());let o=s.toString(),a=o?`${i.includes("?")?"&":"?"}${o}`:"",l=n2(i)?ea:t?nZ[t]:e?nZ["sso-internal"]:nZ["sms-external"];return`https://${l}${i}${a}`}({internal:e,domainId:t,path:r,query:n}),d=new Headers(c.headers),u=d.has("Cookie");if(!l||!n2(r)||d.has("Authorization")||d.has("X-Developer-Open-Build-Token"))return await n3(p,c);let m=new URL(p).origin,h=j(n3,{baseUrl:m,allowedOrigins:[m]});try{return await h(p,c)}catch(e){if(!(e instanceof q||e instanceof C))throw e;if(u)return await n3(p,c);throw Error(e instanceof C?"Doubao Apps Platform 登录已过期,请运行 `dbx auth login` 后重试。":"Doubao Apps Platform 请求需要登录,请运行 `dbx auth login` 后重试。")}}async function n5(e){let t=await n4(e),r=t.headers.get("x-tt-logid")||"";if(!t.ok){let e=await t.text();throw Error(JSON.stringify({code:t.status,message:"HTTP 请求失败",data:e,log_id:r}))}let n=await t.json();if(0!==n.code)throw Error(JSON.stringify({...n,log_id:r}));return{...n,log_id:r}}function n8(e){for(let t of e){let e=process.env[t]?.trim();if(e)return e}}function n9(e){return e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"")}let n7="/__mcp_proxy",n6=f("../../../node_modules/.pnpm/ws@8.21.2/node_modules/ws/lib/websocket-server.js");function ie(e,t,r){e.readyState!==eu.OPEN||e.bufferedAmount>0xa00000?e.terminate():e.send(JSON.stringify({type:t,data:r}))}let it=new Set(["DEBUGGER_NOT_CONNECTED","DEBUGGER_DISCONNECTED","TARGET_NOT_FOUND","ELEMENT_NOT_FOUND","RENDER_FAILED","RENDER_TIMEOUT","VIEWPORT_FAILED","INSPECTION_FAILED","SCROLL_FAILED","SCREENSHOT_FAILED","SNAPSHOT_FAILED","CHAT_NOT_READY","CHAT_BUSY","CHAT_SUBMIT_FAILED","CHAT_TIMEOUT","TOOL_CALL_FAILED","COMMAND_TIMEOUT"]);class ir extends Error{code;constructor(e,t){super(t),this.name="DebuggerControlError",this.code=e}}function ii(e){return"render_page"===e||"render_widget"===e}function is(e){return"number"==typeof e&&Number.isFinite(e)}function io(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function ia(e){if("submit_chat_query"===e.type)return 12e4;if("execute_sandbox_tool_call"===e.type){let t=e.toolCall?.tool_call?.deadline_ms;if("number"==typeof t&&Number.isFinite(t))return Math.max(1,t-Date.now()+1e3)}return 15e3}class il{clients=new Map;lastSnapshotAtByClientId=new Map;snapshotStore;snapshotsByClientId=new Map;nextCommandId=0;constructor(e){this.snapshotStore=e}registerClient(e,t){let r=this.getSnapshotStore(e),n=this.clients.get(e);n&&this.disconnectClient(n,"Debugger control connection was replaced");let i={clientId:e,lastSnapshotAtMs:this.lastSnapshotAtByClientId.get(e)??0,parallelJobs:new Map,queue:[],socket:t};this.clients.set(e,i),this.snapshotsByClientId.set(e,r),t.once("close",()=>{this.disconnectClient(i,"Debugger control connection was closed",!1)})}getSnapshotStore(e){return this.snapshotsByClientId.get(e)??{}}noteSnapshot(e){if(!e)return;let t=this.getSnapshotStore(e);Object.assign(t,this.snapshotStore),this.snapshotsByClientId.set(e,t);let r=Date.now();this.lastSnapshotAtByClientId.set(e,r);let n=this.clients.get(e);n&&(n.lastSnapshotAtMs=r)}execute(e,t,r){let n=void 0!==r?this.clients.get(r):"execute_sandbox_tool_call"===e?this.getToolCallClient():this.getActiveClient();if(!n||n.socket.readyState!==eu.OPEN)return Promise.reject(new ir("DEBUGGER_NOT_CONNECTED","execute_sandbox_tool_call"===e?"No Web SDK debugger is connected":"No Web SDK debugger with a stored snapshot is connected"));let i=`control-${Date.now()}-${++this.nextCommandId}`;return new Promise((r,s)=>{let o={command:{...t,commandId:i,type:e},reject:s,resolve:r};"execute_sandbox_tool_call"===e?this.startParallelJob(n,o):(n.queue.push(o),this.flushClient(n))})}handleResult(e){var t,r;let n,i=e.clientId?.trim(),s=e.commandId?.trim(),o=i?this.clients.get(i):void 0,a=s?o?.parallelJobs.get(s):void 0,l=a??o?.activeJob;if(!o||!l||l.command.commandId!==s)return!1;if(!0===e.ok&&ii(l.command.type)&&(t=e.snapshot,t.snapshot.command_id===s&&t.snapshot.runtime_snapshot)?(this.snapshotStore.snapshot=e.snapshot,this.snapshotStore.updatedAtMs=Date.now(),this.noteSnapshot(i),n={target:e.target}):!0===e.ok&&!ii(l.command.type)&&(n=function(e,t){if("set_viewport"===e)return io(t.width)&&io(t.height)?t:void 0;if("submit_chat_query"===e)return!0===t.completed&&t.query?.trim()&&t.requestId?.trim()?t:void 0;if("take_snapshot"===e){let e=t.runtimeSnapshot;return e?.target?{runtimeSnapshot:e}:void 0}if("execute_sandbox_tool_call"===e)return!0===t.reported&&t.request_id?.trim()&&t.tool_call_id?.trim()?t:void 0;if("take_screenshot"===e||t.uid?.trim()){if("get_computed_style"===e){if(!Array.isArray(t.computedStyle)||!t.computedStyle.every(e=>!!e.name?.trim()&&"string"==typeof e.value))return;return t}if("get_element_rect"===e)return[t.x,t.y,t.width,t.height].every(is)?t:void 0;if("scroll_to"===e)return[t.x,t.y,t.maxX,t.maxY,t.viewportWidth,t.viewportHeight].every(e=>is(e)&&e>=0)&&t.x<=t.maxX&&t.y<=t.maxY?t:void 0;if("take_screenshot"===e){let e="png"===t.format?"image/png":"jpeg"===t.format?"image/jpeg":"webp"===t.format?"image/webp":void 0;return"string"==typeof t.data&&t.data.length>0&&t.mimeType===e&&is(t.width)&&is(t.height)&&(void 0===t.uid||t.uid?.trim())?t:void 0}}}(l.command.type,e.result),"take_snapshot"===l.command.type&&n&&"runtimeSnapshot"in n&&this.storeRuntimeSnapshot(o.clientId,n.runtimeSnapshot)),n)l.resolve(n);else{let t=e.error??{},n=t.code?.trim(),i=n&&it.has(n)?n:void 0;l.reject(new ir(i??(ii(r=l.command.type)?"RENDER_FAILED":"set_viewport"===r?"VIEWPORT_FAILED":"scroll_to"===r?"SCROLL_FAILED":"submit_chat_query"===r?"CHAT_SUBMIT_FAILED":"take_snapshot"===r?"SNAPSHOT_FAILED":"execute_sandbox_tool_call"===r?"TOOL_CALL_FAILED":"take_screenshot"===r?"SCREENSHOT_FAILED":"INSPECTION_FAILED"),t.message?.trim()||"Debugger control command failed"))}return l.timeout&&clearTimeout(l.timeout),a?o.parallelJobs.delete(s):o.activeJob=void 0,this.flushClient(o),!0}getActiveClient(){return[...this.clients.values()].filter(e=>e.socket.readyState===eu.OPEN&&e.lastSnapshotAtMs>0).sort((e,t)=>t.lastSnapshotAtMs-e.lastSnapshotAtMs)[0]}storeRuntimeSnapshot(e,t){let r=this.getSnapshotStore(e).snapshot,n=r?.snapshot;if(!r||!n||n.client_id!==e)return;let i=r.debug_snapshot,{root:s,...o}=t,a=Date.now();this.snapshotStore.snapshot={...r,stored_at:new Date(a).toISOString(),stored_at_ms:a,snapshot:{...n,runtime_snapshot:t},...i?{debug_snapshot:{...i,runtime_snapshot:o}}:{}},this.snapshotStore.updatedAtMs=a,this.noteSnapshot(e)}getConnectedClient(){return[...this.clients.values()].reverse().find(e=>e.socket.readyState===eu.OPEN)}getToolCallClient(){return[...this.clients.values()].reverse().find(e=>e.socket.readyState===eu.OPEN&&e.activeJob?.command.type==="submit_chat_query")??this.getActiveClient()??this.getConnectedClient()}startParallelJob(e,t){let r=t.command.commandId;e.parallelJobs.set(r,t),t.timeout=setTimeout(()=>{e.parallelJobs.delete(r)&&t.reject(new ir("TOOL_CALL_FAILED","Debugger control command timed out"))},ia(t.command));try{ie(e.socket,"control",t.command)}catch{this.disconnectClient(e,"Debugger control connection was closed")}}flushClient(e){if(e.activeJob||e.socket.readyState!==eu.OPEN)return;let t=e.queue.shift();if(t){e.activeJob=t,t.timeout=setTimeout(()=>{if(e.activeJob===t){if("submit_chat_query"===t.command.type){t.timeout=void 0,t.reject(new ir("CHAT_TIMEOUT","Debugger control command timed out"));try{ie(e.socket,"control",{commandId:t.command.commandId,type:"cancel_chat_query"})}catch{this.disconnectClient(e,"Debugger control connection was closed");return}t.timeout=setTimeout(()=>{e.activeJob===t&&this.disconnectClient(e,"Debugger chat cancellation was not acknowledged")},5e3);return}e.activeJob=void 0,t.reject(new ir(ii(t.command.type)?"RENDER_TIMEOUT":"COMMAND_TIMEOUT","Debugger control command timed out")),this.flushClient(e)}},ia(t.command));try{ie(e.socket,"control",t.command)}catch{this.disconnectClient(e,"Debugger control connection was closed")}}}disconnectClient(e,t,r=!0){if(this.clients.get(e.clientId)!==e)return;this.clients.delete(e.clientId),this.snapshotsByClientId.delete(e.clientId);let n=new ir("DEBUGGER_DISCONNECTED",t);for(let t of(e.activeJob?.timeout&&clearTimeout(e.activeJob.timeout),e.activeJob?.reject(n),e.activeJob=void 0,e.parallelJobs.values()))t.timeout&&clearTimeout(t.timeout),t.reject(n);for(let t of(e.parallelJobs.clear(),e.queue.splice(0)))t.reject(n);r&&e.socket.readyState===eu.OPEN&&e.socket.close()}}let ic=["page","widget","app"],ip=["log","info","warn","error","debug","eval"],id=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function iu(e,t){let r=t.pageIdx??0,n=t.pageSize??50,i=r*n,s=e.slice(i,i+n);return{pageIdx:r,pageSize:n,total:e.length,hasMore:i+s.length<e.length,items:s}}function im(e){if(!e.snapshot)return{stored:!1,updatedAtMs:e.updatedAtMs};let{debug_snapshot:t,...r}=e.snapshot;return{stored:!0,storedAt:r.stored_at,updatedAtMs:r.stored_at_ms??e.updatedAtMs,snapshot:r.snapshot}}function ih(e){return e.value??e.unserializableValue??e.description??e.type??""}function ig(e,t){var r,n;let i;return(r=e,"all"===(n=t)?ic:"page"===n||"widget"===n||"app"===n?[n]:(i=r.context,i?.page_id||i?.page_path?["page","app"]:i?.widget_id?["widget"]:ic)).flatMap(t=>{let r,n=(r=e.runtime_console?.[t],{entries:r?.entries??[],updatedAtMs:r?.updated_at_ms??r?.updatedAtMs});return n.entries.map((e,r)=>{var i;let s,o,a,l;return i=n.updatedAtMs,s=e.url??e.location?.url,o=e.lineNumber??e.location?.lineNumber,a=e.columnNumber??e.location?.columnNumber,l=e.id??String(r),{msgid:`${t}:${l}`,target:t,level:e.level??"log",source:e.source??"",timestamp:e.timestamp??0,text:e.message??(e.args??[]).map(ih).filter(Boolean).join(" "),...s?{url:s}:{},...void 0===o?{}:{lineNumber:o},...void 0===a?{}:{columnNumber:a},...void 0===i?{}:{updatedAtMs:i},entry:e}})})}function iy(e,t){return{id:e.toolCallId??e.id??`tool-call:${t}`,requestId:e.requestId??e.request_id??"",toolCallId:e.toolCallId??e.id??"",toolName:e.toolName??e.name??"",serverId:e.serverId??e.server_id??"",appKey:e.appKey??e.app_key??"",status:e.status??"",createdAtMs:e.createdAtMs??e.created_at_ms??0,updatedAtMs:e.updatedAtMs??e.updated_at_ms??0,requiresUserApproval:!0===e.requiresUserApproval,isMiniApp:!0===e.isMiniApp,message:e.message??"",resultSummary:e.resultSummary??e.structuredResultSummary}}function ib(e,t){if("page"===t){let{pageId:t,path:r}=e;if(!t||!r)return;return{pageId:t,path:r,name:e.name??t,isHome:!0===e.isHome}}let{widgetId:r}=e;if(r)return{widgetId:r,name:e.name??r}}let i_={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},iv={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},iE={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function iw(e,t={}){return{structuredContent:e,content:t.image?[{type:"image",...t.image}]:[{type:"text",text:t.text??JSON.stringify(e,null,2)}],...t.isError?{isError:!0}:{}}}async function iS(e,t={}){try{return await e()}catch(e){return function(e,t={}){let r=e instanceof ir?e:new ir("INSPECTION_FAILED",String(e));return iw({...t,error:{code:r.code,message:r.message}},{isError:!0})}(e,t)}}function ix(e,t,r,n){let i=N(r.inputSchema);e.registerTool(t,{...r,inputSchema:i},n)}let iA="/__wsd_mcp";async function iT({request:e,response:t,url:r},n,i){if("OPTIONS"===e.method){nM(t),t.writeHead(204),t.end();return}if("POST"!==e.method)return void nU(t,405,"Method not allowed");let s=r.searchParams.get("clientId")??void 0,o=void 0===s?n:i.getSnapshotStore(s),a=L(()=>{let e,t;return e=new X({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),t=async e=>{var t;let r=im(o);if(!r.stored)return iw(r);let n=iu((t=r.snapshot,[{source:"simulator",events:t.simulator?.trace_events??[]},{source:"widget_runtime",events:t.widget_runtime_trace_events??[]},{source:"page_runtime",events:t.page_runtime_trace_events??[]}].flatMap(({source:e,events:t})=>t.map((t,r)=>{let n;return n=t.payload??{},{source:e,id:t.id??`${e}:${r}`,timestamp:t.timestamp??0,category:n.category??t.display?.category??"",event:n.event??t.event??"",requestId:n.request_id??n.requestId??n.trace_id??n.trace?.trace_id??"",payload:t.payload??t}}))).filter(t=>{let r,n,i;return r=e.category??[],n=e.event?.trim(),i=e.requestId?.trim(),(0===r.length||r.includes(t.category))&&(!n||t.event===n)&&(!i||t.requestId===i)}),e);return iw({stored:!0,storedAt:r.storedAt,updatedAtMs:r.updatedAtMs,total:n.total,pageIdx:n.pageIdx,pageSize:n.pageSize,hasMore:n.hasMore,events:n.items})},ix(e,"list_chat_messages",{annotations:i_,description:"List conversation messages in chronological order from the latest debugger snapshot, including message content and generation status.",inputSchema:{}},async()=>{let e=im(o);if(!e.stored)return iw(e);let t=o.snapshot?.debug_snapshot?.simulator??e.snapshot.simulator;return iw({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,streamStatus:t?.stream_status,messages:t?.messages??[]})}),ix(e,"list_console_messages",{annotations:i_,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:ei(I(ip)).optional(),pageIdx:O().int().min(0).optional(),pageSize:O().int().min(1).max(200).optional(),query:Q().optional(),target:I(["current","page","widget","app","all"]).optional()}},async e=>{let t=im(o);if(!t.stored)return iw(t);let r=iu(ig(t.snapshot,e.target).filter(t=>{let r,n;return r=e.levels??[],n=e.query?.trim().toLowerCase(),(!(r.length>0)||!!r.includes(t.level))&&(!n||[t.text,t.url,t.source,t.target].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(n)))}),e);return iw({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,messages:r.items.map(({entry:e,...t})=>t)})}),ix(e,"get_console_message",{annotations:i_,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:Q()}},async e=>{let t=im(o);if(!t.stored)return iw(t);let r=ig(t.snapshot,"all").find(t=>t.msgid===e.msgid);return iw({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,found:!!r,...r?{message:r}:{msgid:e.msgid}})}),ix(e,"get_log_snapshot",{annotations:i_,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let e=im(o);return e.stored?iw({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,snapshot:e.snapshot}):iw(e)}),ix(e,"list_render_targets",{annotations:i_,description:"List Page and Widget targets that can be rendered by the Web SDK debugger.",inputSchema:{type:I(["all","page","widget"]).optional()}},async e=>{var t,r;let n,i=im(o);return i.stored?iw({stored:!0,storedAt:i.storedAt,updatedAtMs:i.updatedAtMs,...(t=i.snapshot,r=e.type??"all",n=t.render_targets??{},{pages:"widget"===r?[]:(n.pages??[]).map(e=>ib(e,"page")).filter(Boolean),widgets:"page"===r?[]:(n.widgets??[]).map(e=>ib(e,"widget")).filter(Boolean),...n.currentTarget?{currentTarget:n.currentTarget}:{}})}):iw(i)}),ix(e,"take_snapshot",{annotations:i_,description:"Capture and return a fresh text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:I(["current","page","widget"]).optional(),verbose:U().optional()}},e=>iS(async()=>{let t=function(e,t){var r,n;let i,s,o,a=e.runtime_snapshot;if(!a?.target)return{available:!1,reason:"NO_RUNTIME_SNAPSHOT"};let l=a.target,c=l.type,p=t.target??"current";if(("page"===p||"widget"===p)&&c!==p)return{available:!1,reason:"TARGET_MISMATCH",requestedTarget:p,currentTarget:l};if(!a.root)return{available:!1,reason:"NO_RENDERED_TARGET",currentTarget:l};let d=a.selectedUid,u=(r=a.root,n=!0===t.verbose,i=[],s=0,(o=(e,t)=>{var r,a;let{name:l,uid:c}=e;if(!c||!l)return;s+=1;let p=" ".repeat(t);if("text"===e.type)return void i.push(`${p}uid=${c} text ${JSON.stringify(e.text??"")}`);let u=[`uid=${c}`,l],{keyboardFocusable:m=!1,name:h,role:f}=e.accessibility??{};for(let t of(f&&(n||"generic"!==f)&&u.push(`role=${JSON.stringify(f)}`),h&&u.push(`name=${JSON.stringify(h)}`),(n||m)&&u.push(`focusable=${String(m)}`),(e.attributes??[]).map(e=>({name:e.name,value:e.value})).filter(e=>e.name&&(n||id.has(e.name)||e.name.startsWith("aria-")))))u.push((r=t.name,(a=t.value)?`${r}=${JSON.stringify(a)}`:r));for(let r of(c===d&&u.push("[selected]"),i.push(`${p}${u.join(" ")}`),e.children??[]))o(r,t+1)})(r,0),{actualNodeCount:s,text:i.join("\n")});return{available:!0,target:l,nodeCount:a.nodeCount??u.actualNodeCount,...d?{selectedUid:d}:{},truncated:!0===a.truncated,snapshot:u.text,snapshotUpdatedAtMs:a.updatedAtMs}}({runtime_snapshot:(await i.execute("take_snapshot",{target:e.target??"current"},s)).runtimeSnapshot},e),r=im(o),n={stored:r.stored,...r.stored?{storedAt:r.storedAt,updatedAtMs:r.updatedAtMs}:{},...t};return iw(n,{text:t.available?t.snapshot:JSON.stringify(n,null,2)})},{available:!1,stored:!1})),ix(e,"get_computed_style",{annotations:i_,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:ei(Q().min(1)).max(100).optional(),uid:Q().min(1)}},({properties:e,uid:t})=>iS(async()=>iw(await i.execute("get_computed_style",{uid:t,...e?{properties:e}:{}},s)))),ix(e,"get_element_rect",{annotations:i_,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:Q().min(1)}},({uid:e})=>iS(async()=>iw(await i.execute("get_element_rect",{uid:e},s)))),ix(e,"take_screenshot",{annotations:i_,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:I(["png","jpeg","webp"]).optional(),quality:O().min(0).max(100).optional(),uid:Q().min(1).optional()}},({format:e="png",quality:t,uid:r})=>iS(async()=>{let n=await i.execute("take_screenshot",{format:e,...void 0!==t?{quality:t}:{},...r?{uid:r}:{}},s),{data:o,...a}=n;return iw({captured:!0,...a},{image:{data:o,mimeType:n.mimeType}})},{captured:!1})),ix(e,"scroll_to",{annotations:iE,description:"Scroll a Page or Widget container to absolute coordinates, or return its current scroll position.",inputSchema:{uid:Q().min(1).optional(),x:O().min(0).optional(),y:O().min(0).optional()}},({uid:e,x:t,y:r})=>iS(async()=>iw({scrolled:!0,...await i.execute("scroll_to",{uid:e,x:t,y:r},s)}),{scrolled:!1})),ix(e,"set_viewport",{annotations:iE,description:"Set the current Page or Widget emulated viewport size.",inputSchema:{height:O().int().min(1).max(9999),width:O().int().min(1).max(9999)}},({height:e,width:t})=>iS(async()=>iw({updated:!0,viewport:await i.execute("set_viewport",{height:e,width:t},s)}),{updated:!1})),ix(e,"render_page",{annotations:iv,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:Q().min(1)}},({url:e})=>iS(async()=>iw({rendered:!0,target:(await i.execute("render_page",{url:e},s)).target}),{rendered:!1})),ix(e,"render_widget",{annotations:iv,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:W(Q(),P()).optional(),widgetId:Q().min(1)}},({structuredContent:e,widgetId:t})=>iS(async()=>iw({rendered:!0,target:(await i.execute("render_widget",{structuredContent:e??{},widgetId:t},s)).target}),{rendered:!1})),ix(e,"submit_chat_query",{annotations:iv,description:"Submit a chat query through the connected Web SDK debugger and wait for the simulator response to complete.",inputSchema:{query:Q().trim().min(1)}},({query:e})=>iS(async()=>iw({submitted:!0,...await i.execute("submit_chat_query",{query:e},s)}),{submitted:!1})),ix(e,"list_agent_trace_events",{annotations:i_,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:ei(Q()).optional(),event:Q().optional(),pageIdx:O().int().min(0).optional(),pageSize:O().int().min(1).max(200).optional(),requestId:Q().optional()}},t),ix(e,"list_agent_tool_calls",{annotations:i_,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:O().int().min(0).optional(),pageSize:O().int().min(1).max(200).optional(),query:Q().optional(),requestId:Q().optional(),status:ei(Q()).optional(),toolName:Q().optional()}},async e=>{var t;let r=im(o);if(!r.stored)return iw(r);let n=iu((t=r.snapshot,(t.simulator?.tool_calls??[]).map(iy)).filter(t=>{let r,n,i,s;return r=e.requestId?.trim(),n=e.toolName?.trim(),i=e.status??[],s=e.query?.trim().toLowerCase(),(!r||t.requestId===r)&&(!n||t.toolName===n)&&(!(i.length>0)||!!i.includes(t.status))&&(!s||[t.toolName,t.serverId,t.appKey,t.status,t.message,"string"==typeof t.resultSummary?t.resultSummary:void 0].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(s)))}),e);return iw({stored:!0,storedAt:r.storedAt,updatedAtMs:r.updatedAtMs,total:n.total,pageIdx:n.pageIdx,pageSize:n.pageSize,hasMore:n.hasMore,toolCalls:n.items})}),e}),l=en(a);try{await l(e,t)}catch(e){t.headersSent?t.destroy(e instanceof Error?e:void 0):nU(t,500,e instanceof Error?e.message:String(e))}finally{await a.close().catch(()=>void 0)}}let iI="/__web_sdk_debug_scenes",iO="/__web_sdk_widget_view_data_templates",iP={"Cache-Control":"no-cache"};async function iC(e,t){try{let r=await t?.()??{templatesByEntry:{},templatesByWidget:{}};nB(e,200,r,iP)}catch(t){nA.error("加载 Widget viewData 模板失败",{error:t}),nB(e,500,{templatesByEntry:{},templatesByWidget:{}},iP)}}let iR=f("node:crypto"),i$="/__dbx_real_device_debug",ik=`${i$}/state`,iN=`${i$}/start`,iL=`${i$}/cancel`,iD=`${i$}/qr`;class ij{accessToken;provider;getDebugContext(){if(this.provider&&this.accessToken)return{stateEndpoint:ik,startEndpoint:iN,cancelEndpoint:iL,qrEndpoint:iD,accessToken:this.accessToken,pollIntervalMs:500}}setProvider(e){this.provider=e,this.accessToken=e?iR.randomBytes(32).toString("hex"):void 0}dispose(){this.setProvider(void 0)}getRequestRoutes(){return[{match:e=>e.pathname.startsWith(i$),handle:({request:e,response:t,url:r})=>this.serveRequest(e,t,r)}]}async serveRequest(e,t,r){if(!this.validateRequest(e,t))return;let n=this.provider;if(!n)return this.writeError(t,503,"REAL_DEVICE_DEBUG_UNAVAILABLE","Physical device debugging is unavailable");let i=await this.readJsonBody(e,t);if(i)try{if(r.pathname===ik||r.pathname===iN){if(Object.keys(i).length>0)return this.writeError(t,400,"INVALID_REQUEST","Unexpected request fields");let e=r.pathname===ik?await n.getState():await n.start();nB(t,200,e);return}if(r.pathname===iL){let e=i.operationId;if("string"!=typeof e||!e||1!==Object.keys(i).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid operationId");nB(t,200,await n.cancel(e));return}if(r.pathname===iD){let{operationId:e,kind:r}=i;if("string"!=typeof e||!e||"modern"!==r&&"legacy"!==r||2!==Object.keys(i).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid QR request");let s=await n.getQrImage(e,r);if(!s)return this.writeError(t,404,"QR_NOT_FOUND","QR image is unavailable");nM(t),t.writeHead(200,{"Content-Length":s.body.byteLength,"Content-Type":s.contentType}),t.end(s.body);return}return this.writeError(t,404,"NOT_FOUND","Not found")}catch{return this.writeError(t,500,"REAL_DEVICE_DEBUG_FAILED","Physical device debugging failed")}}validateRequest(e,t){var r,n;let i,s,o;if(!function(e){if(!e)return!1;try{let t=new URL(`http://${e}`).hostname.toLowerCase();return"127.0.0.1"===t||"[::1]"===t||"localhost"===t}catch{return!1}}(e.headers.host))return this.writeError(t,403,"FORBIDDEN_HOST","Forbidden host"),!1;let a=e.headers["x-dbx-real-device-token"];if("string"!=typeof a||!this.accessToken||(r=a,n=this.accessToken,s=(i=new TextEncoder).encode(r),o=i.encode(n),!(s.length===o.length&&iR.timingSafeEqual(s,o))))return this.writeError(t,401,"UNAUTHORIZED","Unauthorized"),!1;if("POST"!==e.method)return this.writeError(t,405,"METHOD_NOT_ALLOWED","Method must be POST"),!1;if(!(e.headers["content-type"]?.toLowerCase()??"").startsWith("application/json"))return this.writeError(t,415,"UNSUPPORTED_MEDIA_TYPE","Content-Type must be application/json"),!1;let l=e.headers.origin;return!l||l===`http://${e.headers.host}`||(this.writeError(t,403,"FORBIDDEN_ORIGIN","Forbidden origin"),!1)}async readJsonBody(e,t){let r,n;try{r=await nH(e,t,4096)}catch{return this.writeError(t,413,"PAYLOAD_TOO_LARGE","Request body is too large")}if(!r.trim())return{};try{n=JSON.parse(r)}catch{return this.writeError(t,400,"INVALID_REQUEST","Invalid JSON body")}return!n||"object"!=typeof n||Array.isArray(n)?this.writeError(t,400,"INVALID_REQUEST","Invalid JSON body"):n}writeError(e,t,r,n){e.writableEnded||e.destroyed||nB(e,t,{error:{code:r,message:n}})}}let iM={"Cache-Control":"no-cache"},iU="/app_developer/api/sandbox/",iB=`${iU}session/business_info/update`,iF=new Set([`${iU}resources/notices/pull`,`${iU}resources/tasks/pull`]),iH={"Access-Control-Expose-Headers":n$},iW=new Set;function iG(e,t,r,n,i,s){if(!eb())return!1;let o=`${i[nR]??""} ${e} ${t.pathname}`,a=iF.has(t.pathname);if(a&&r>=500){if(iW.has(o))return!1;iW.add(o)}else a&&r<500&&iW.delete(o);let l=Number(process.hrtime.bigint()-n)/1e6;return nA.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:l,headers:i,logId:s}),!0}function iV({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:s,targetUrl:o}){nq({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:s,targetUrl:o})}function iq(e,t,r){return r&&!(iF.has(e.pathname)&&t>=500)}function iJ(e,t){if(e.pathname!==iB||!t)return t;try{let e=JSON.parse(t);return JSON.stringify({...e,..."csr_pem"in e?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]"})}catch{return JSON.stringify({omitted:"Sandbox 业务信息请求无效"})}}async function iz({method:e,request:t,requestBody:r,requestHeaders:n,response:i,targetUrl:s,usePlatformFetch:o}){let a=process.hrtime.bigint(),l=nJ(t,i);try{let t,c=o?await n4({internal:!0,path:`${s.pathname}${s.search}`,method:e,body:r,headers:n,signal:l}):await fetch(s,{body:"GET"===e||"HEAD"===e?void 0:r,headers:n,method:e,signal:l}),p=iG(e,s,c.status,a,n,c.headers.get(n$)??void 0);if(i.destroyed||i.writableEnded)return void c.body?.cancel().catch(()=>void 0);let d=await nW(c);return iq(s,c.status,p)&&iV({method:e,requestBody:iJ(s,r),requestHeaders:n,responseBody:d,responseHeaders:c.headers,statusCode:c.status,targetUrl:s}),i.destroyed||i.writableEnded||(t=nj(c.headers,[n$]),nM(i,iH),i.writeHead(c.status,t),i.end(d)),{body:d,ok:c.ok}}catch(c){if(i.destroyed||i.writableEnded||l.aborted)return;let t=`代理 Sandbox 请求失败:${c instanceof Error?c.message:String(c)}`,o=iG(e,s,502,a,n);iq(s,502,o)&&iV({method:e,requestBody:iJ(s,r),requestHeaders:n,responseBody:t,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:s}),nU(i,502,t,iH)}}async function iK(e,t,r={}){let n;if("POST"!==e.method)return void nU(t,405,"不支持的请求方法",iH);try{n=JSON.parse(await nH(e,t,0xa00000))}catch(e){nU(t,400,`Sandbox 代理请求内容无效:${e.message}`,iH);return}let i=function(e,t){if(!e.url)return;let r=new URL(e.url,t);if(!r.pathname.startsWith(iU))return;let n=new URL(`${r.pathname}${r.search}`,t);var i=e.params;if(i)for(let[e,t]of Object.entries(i))null!=t&&n.searchParams.set(e,String(t));return n}(n,r.targetOrigin??ee);if(!i)return void nU(t,404,"未找到 Sandbox endpoint",iH);if(!r.sandboxSessionId)return void nB(t,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},iH);let s=function(e,t,r,n){if(t.pathname.startsWith(`${iU}session/`)&&t.pathname!==`${iU}session/create`)return JSON.stringify({..."object"==typeof e.data&&null!==e.data?e.data:{},sandbox_session_id:n});if(void 0===e.data)return;if("object"!=typeof e.data||null===e.data||!r)return JSON.stringify(e.data);let i={...e.data};return t.pathname.startsWith(`${iU}jsb/`)&&"app_key"in i&&(i.app_key=r),t.pathname===`${iU}passport/open/auth`&&"client_key"in i&&(i.client_key=r),JSON.stringify(i)}(n,i,r.sandboxAppId,r.sandboxSessionId),o=n.method||"POST",a=function(e,t,r,n,i){let s=Object.fromEntries(Object.entries(nL({...e.headers,...r,...void 0===n?{}:{"content-length":String(Buffer.byteLength(n))},"content-type":"application/json"},t,{...n1(),...i?{[nR]:i}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]));for(let e of Object.keys(s))"accept-encoding"===e.toLowerCase()&&delete s[e];return s["accept-encoding"]="identity",s}(e,i,n.headers,s,r.sandboxSessionId),l=await iz({method:o,request:e,requestBody:s,requestHeaders:a,response:t,targetUrl:i,usePlatformFetch:!r.targetOrigin});if(i.pathname===iB&&l?.ok)try{let e=JSON.parse(l.body.toString("utf8"));(void 0===e.code||0===e.code)&&r.onBusinessInfoUpdated?.(function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t="string"==typeof e.csr_pem?e.csr_pem.trim():"",r="string"==typeof e.phone_num?e.phone_num.trim():"";return r?{...t?{csrPem:t}:{},phoneNum:r}:void 0}(n.data))}catch{}}let iY=f("node:util"),iX="/app_developer/api/sandbox/bridge/events",iZ="/app_developer/api/sandbox/bridge/response",iQ=new Set(["connection","content-length","host"]),i0=new Set(["heartbeat"]),i1=[500,1e3,2e3,5e3],i2=0;function i3(e){return e.length<=8?e:`${e.slice(0,4)}...${e.slice(-4)}`}function i4(e,t=new Headers,r=""){return{response:e,responseHeaders:Object.fromEntries(t),statusText:r}}async function i5(e){let t,r,n=e.request_id||"";if(!n)return i4({error_message:"Bridge 请求缺少 request_id",http_status:0,request_id:n,success:!1});if(!e.path?.startsWith("/"))return i4({error_message:`Bridge 请求路径无效:${e.path??""}`,http_status:0,request_id:n,success:!1});let i=function(e){if(e.origin)try{var t;return new URL(e.path??"/",(t=e.origin).endsWith("/")?t:`${t}/`)}catch{return}}(e);if(!i)return i4({error_message:`Bridge 请求 origin 无效:${e.origin??""}`,http_status:0,request_id:n,success:!1});let s=(e.method||"GET").toUpperCase(),o=function(e){let t={};for(let[r,n]of Object.entries(e??{}))!r||iQ.has(r.toLowerCase())||(t[r]=n);return t}(e.headers),a="GET"===s||"HEAD"===s?void 0:e.body??"",l=new AbortController,c=setTimeout(()=>l.abort(),(t="number"==typeof e.timeout_ms?e.timeout_ms:3e3,r="number"==typeof e.deadline_ms?e.deadline_ms-Date.now():t,Math.max(1,Math.min(t,r))));try{var p;let e=await fetch(i,{body:a,headers:o,method:s,redirect:"manual",signal:l.signal}),t=await e.text();return p={method:s,requestBody:a,requestHeaders:o,responseBody:t,responseHeaders:e.headers,statusCode:e.status,targetUrl:i},nq(p),i4({body:t,http_status:e.status,request_id:n,success:!0},e.headers,e.statusText)}catch(e){return nq({method:s,requestBody:a,requestHeaders:o,responseBody:e instanceof Error?e.message:String(e),responseHeaders:new Headers,statusCode:0,targetUrl:i}),i4({error_message:e instanceof Error?e.message:String(e),http_status:0,request_id:n,success:!1})}finally{clearTimeout(c)}}function i8(e,t=new Set){if(Array.isArray(e)){for(let r of e)i8(r,t);return[...t]}if(!e||"object"!=typeof e)return[...t];for(let[r,n]of Object.entries(e)){if(r.toLowerCase().replace(/[_-]/g,"").includes("logid")){if("string"==typeof n&&n)t.add(n);else if(Array.isArray(n))for(let e of n)"string"==typeof e&&e&&t.add(e);continue}i8(n,t)}return[...t]}function i9(e,t){e.onLog?.(t)}function i7(e){try{return JSON.parse(e)}catch{return}}function i6({detail:e,requestHeaders:t,status:r,targetUrl:n}){if(eb()){if("number"==typeof r)return void nA.request({method:"CONNECT",url:n.pathname,statusCode:r,headers:t,context:{detail:e}});nA.info("Bridge 连接等待中",{url:n.pathname,detail:e,ppe:ew(t)})}}function se(e,t={}){eb()&&nA.info(e,t)}async function st(e,t){let r=JSON.stringify({sandbox_session_id:e.sandboxSessionId,...t}),n={"content-type":"application/json",[nR]:e.sandboxSessionId,...n1()};if(e.targetOrigin){let t=new URL(iZ,e.targetOrigin),i=await fetch(t,{body:r,headers:n,method:"POST"}),s=await i.text();if(nq({method:"POST",requestBody:r,requestHeaders:n,responseBody:s,responseHeaders:i.headers,statusCode:i.status,targetUrl:t}),!i.ok)throw Error(`上传 Bridge 响应失败:${i.status} ${s}`);return{responseBody:s,responseHeaders:Object.fromEntries(i.headers),responsePayload:i7(s)}}let i=new URL(iZ,ee),s=await n4({body:r,headers:n,internal:!0,method:"POST",path:iZ}),o=await s.text();if(nq({method:"POST",requestBody:r,requestHeaders:n,responseBody:o,responseHeaders:s.headers,statusCode:s.status,targetUrl:i}),!s.ok)throw Error(`上传 Bridge 响应失败:${s.status} ${o}`);return{responseBody:o,responseHeaders:Object.fromEntries(s.headers),responsePayload:i7(o)}}async function sr(e,t){let r;try{r=JSON.parse(t)}catch(e){nA.warn("Sandbox Bridge 请求解析失败",{reason:e.message});return}let n=Date.now(),i=`bridge-${n}-${++i2}`,s=r.request_id||"",o={id:i,request:r,requestId:s,sandboxSessionId:e.sandboxSessionId,timestamp:n};i9(e,{...o,logIds:i8(r),status:"pending",updatedAtMs:n});let a=await i5(r),l={...a.response,headers:a.responseHeaders,status_text:a.statusText};try{let t=await st(e,a.response);i9(e,{...o,logIds:i8([r,l,t]),response:l,status:a.response.success?"success":"error",updatedAtMs:Date.now()})}catch(t){throw i9(e,{...o,errorMessage:t instanceof Error?t.message:String(t),logIds:i8([r,l]),response:l,status:"error",updatedAtMs:Date.now()}),t}}async function sn(e,t,r){let n={sandbox_session_id:e.sandboxSessionId},i=new URL(`${iX}?sandbox_session_id=${encodeURIComponent(e.sandboxSessionId)}`,ee),s=(p=e.sandboxSessionId,{accept:"text/event-stream",host:i.host,[nR]:p,...n1()});i6({detail:`host=${s.host} session=${i3(e.sandboxSessionId)}`,requestHeaders:s,status:"pending",targetUrl:i}),se("bridge/events request",{headers:{accept:s.accept,host:s.host,[nR]:i3(e.sandboxSessionId),"x-tt-env":s["x-tt-env"],"x-use-ppe":s["x-use-ppe"]},path:iX,query:n});let o=await n4({headers:s,internal:!0,method:"GET",path:iX,query:n,signal:t});if(i6({detail:`content-type=${o.headers.get("content-type")??""}`,requestHeaders:s,status:o.status,targetUrl:i}),!o.ok||!o.body){let e=await o.text().catch(()=>"");nq({method:"GET",requestBody:void 0,requestHeaders:s,responseBody:e,responseHeaders:o.headers,statusCode:o.status,targetUrl:i}),nA.warn("Sandbox Bridge 事件请求失败",{status:o.status,body:e.slice(0,500)});let t=Error(`Sandbox Bridge SSE 请求失败:${o.status} ${e}`);throw t.status=o.status,t}nq({method:"GET",requestBody:void 0,requestHeaders:s,responseBody:"",responseHeaders:o.headers,statusCode:o.status,targetUrl:i}),r?.();let a=o.body.getReader(),l=new iY.TextDecoder,c="";for(;!t.aborted;){let{done:t,value:r}=await a.read();if(t){se("Bridge events 流已结束",{session:i3(e.sandboxSessionId)});break}let n=(c+=l.decode(r,{stream:!0})).search(/\r?\n\r?\n/);for(;n>=0;){let t=c.slice(0,n),r=c.slice(n).match(/^\r?\n\r?\n/);c=c.slice(n+(r?.[0].length??2));let a=function(e){let t="message",r=[];for(let n of e.split(/\r?\n/)){if(n.startsWith("event:")){t=n.slice(6).trim();continue}n.startsWith("data:")&&r.push(n.slice(5).trimStart())}return{data:r.join("\n"),name:t}}(t);if(!function(e,t){if(!eb()||i0.has(e.name))return;let r=function(e){try{let t=JSON.parse(e);return"string"==typeof t.request_id?t.request_id:void 0}catch{return}}(e.data);nA.info("已收到 Bridge 事件",{event:e.name,requestId:r,ppe:ew(t)}),nA.info(`事件详情
164
+ ${e.data}`)}(a,s),"bridge_request"===a.name){var p,d=o.headers,u=o.status;nq({method:`EVENT ${a.name}`,requestBody:a.data,requestHeaders:s,responseBody:"",responseHeaders:d,statusCode:u,targetUrl:i}),sr(e,a.data).catch(e=>{nA.warn("Sandbox Bridge 请求处理失败",{reason:e.message})})}else if("TOOL_CALL"===a.name){let t=J(i7(a.data));t?Promise.resolve(e.onSimulatorToolCall?.(t)).catch(e=>{nA.warn("Sandbox Tool 调用转发失败",{reason:e instanceof Error?e.message:String(e),requestId:t.request_id,toolCallId:t.tool_call.tool_call_id})}):nA.warn("Sandbox Tool 调用事件解析失败")}else if("sandbox_resource_changed"===a.name){let t=function(e){let t=i7(e);if(!t||"object"!=typeof t||Array.isArray(t))return;let r=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,n=r?.resource,i=r?.action,s=r?.resource_id,o=r?.revision;if(("notice"===n||"task"===n)&&("upsert"===i||"remove"===i)&&"string"==typeof s&&s&&("number"==typeof o||"string"==typeof o))return{action:i,eventId:"string"==typeof t.event_id?t.event_id:"",occurredAtMs:"number"==typeof t.occurred_at_ms?t.occurred_at_ms:void 0,resource:n,resourceId:s,revision:o}}(a.data);t?e.onResourceChanged?.(t):nA.warn("Sandbox 资源事件解析失败")}else if("card_delta"===a.name){let t=function(e){let t=i7(e);if(!t||"object"!=typeof t||Array.isArray(t))return;let r=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,n=r?.card_delta;if(!("card_delta"!==t.type||!n||"object"!=typeof n||Array.isArray(n)))return n}(a.data);t?e.onSimulatorEvent?.({payload:t,type:"card_delta"}):nA.warn("Sandbox 模拟器事件解析失败",{event:a.name})}else if("get_simulator_card_snapshots"===a.name){let t=i7(a.data);t&&"object"==typeof t&&!Array.isArray(t)?e.onSimulatorEvent?.({payload:t,type:a.name}):nA.warn("Sandbox 模拟器事件解析失败",{event:a.name})}n=c.search(/\r?\n\r?\n/)}}}async function si(e,t){let r=0,n=!1;for(;!t.aborted;){try{await sn(e,t,()=>{n=!1,e.onConnectionStatusChange?.("connected")}),r=0}catch(r){if(t.aborted)return;let e=r.status;if(n||(nA.warn("无法接收来自平台服务的请求",{reason:r.message}),n=!0),401===e||403===e||404===e)return}e.onConnectionStatusChange?.("reconnecting"),await (0,v.setTimeout)(i1[Math.min(r,i1.length-1)],void 0,{signal:t}).catch(()=>void 0),r+=1}}let ss=f("node:net"),so="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",sa="/app_developer/api/sandbox/session/business_info/update";function sl(e){if(!e)return!1;try{return tV.statSync(e).isFile()}catch{return!1}}async function sc({body:e,headers:t,method:r,sandboxPath:n,targetOrigin:i,targetUrl:s}){let o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{return i?await fetch(s,{body:e,headers:t,method:r,signal:o.signal}):await n4({internal:!0,path:n,body:e,headers:t,method:r,signal:o.signal})}catch(e){if(o.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${s}`);throw e}finally{clearTimeout(a)}}function sp(e,t){return(e?.[t]??process.env[t])?.trim()??""}function sd(e,t,r,n,i,s){if(!eb())return;let o=Number(process.hrtime.bigint()-n)/1e6;nA.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:o,headers:i,logId:s})}function su({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:s,targetUrl:o}){nq({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:s,targetUrl:o})}async function sm(e,t,r,n,i,s){let o,a,l="/app_developer/api/sandbox/session/create",c="POST",p=function(){let e=new Set;for(let t of(process.env[so]??"").split(",")){let r=t.trim();if(r)try{let t=new URL(r),n=t.hostname.replace(/^\[|\]$/g,"").toLowerCase(),i="localhost"===n||"::1"===n||4===(0,ss.isIP)(n)&&n.startsWith("127.");if("http:"!==t.protocol&&"https:"!==t.protocol||!i)throw Error("仅允许本机回环 HTTP(S) origin");e.add(t.origin)}catch(e){throw Error(`${so} 包含无效 origin:${r}(${e instanceof Error?e.message:String(e)})`)}}return[...e]}(),d=JSON.stringify({sandbox_project_id:e,manifest:r?.()??(sl(t)?tV.readFileSync(t,"utf8"):""),business_templates:sl(n)?tV.readFileSync(n,"utf8"):"",...s?{app_id:s}:{},...p.length>0?{bridge_origins:p}:{}}),u={"content-type":"application/json",...n1()},m=new URL(l,i??ee),h=process.hrtime.bigint();try{o=await sc({body:d,headers:u,method:c,sandboxPath:l,targetOrigin:i,targetUrl:m})}catch(t){let e=`创建 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw sd(c,m,502,h,u),su({method:c,requestBody:d,requestHeaders:u,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:m}),t}let f=o.headers.get(n$)||"",g=await o.text();sd(c,m,o.status,h,u,f),su({method:c,requestBody:d,requestHeaders:u,responseBody:g,responseHeaders:o.headers,statusCode:o.status,targetUrl:m});try{a=JSON.parse(g||"{}")}catch{throw Error(`创建 Sandbox session 失败:HTTP ${o.status} ${o.statusText||g||"响应不是有效 JSON"}${f?`,log_id=${f}`:""}`)}if(!o.ok||0!==a.code)throw Error(`创建 Sandbox session 失败:${a.message||o.statusText||o.status}${a.log_id||f?`,log_id=${a.log_id||f}`:""}`);let y=a.data?.sandbox_session_id,b=a.data?.sandbox_appid;if(!y||!b)throw Error(`创建 Sandbox session 失败:响应缺少 ${y?"sandbox_appid":"sandbox_session_id"}${a.log_id||f?`,log_id=${a.log_id||f}`:""}`);return{appId:b,sessionId:y}}async function sh(e,t,r,n,i,s){try{return await sm(e,t,r,n,i,s)}catch(e){return nA.warn(`Sandbox 平台服务模拟已跳过:${e instanceof Error?e.message:String(e)}`),{appId:"",sessionId:""}}}function sf(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function sg(e){return{csrUploaded:!!e,phoneNumberUploaded:!0}}async function sy(e,t){let r,n,i="/app_developer/api/sandbox/session/business_info/get",s="POST",o=JSON.stringify({sandbox_session_id:e}),a={"content-type":"application/json",...n1()},l=new URL(i,t??ee),c=process.hrtime.bigint();try{r=await sc({body:o,headers:a,method:s,sandboxPath:i,targetOrigin:t,targetUrl:l})}catch(e){throw sd(s,l,502,c,a),e}let p=r.headers.get(n$)||"",d=await r.text();sd(s,l,r.status,c,a,p);try{n=JSON.parse(d||"{}")}catch{throw su({method:s,requestBody:o,requestHeaders:a,responseBody:JSON.stringify({omitted:"Sandbox 业务信息响应无效"}),responseHeaders:r.headers,statusCode:r.status,targetUrl:l}),Error(`获取 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${p?`,log_id=${p}`:""}`)}let u={csrUploaded:!!n.data?.csr_pem?.trim(),phoneNumberUploaded:!!n.data?.phone_num?.trim()};if(su({method:s,requestBody:o,requestHeaders:a,responseBody:JSON.stringify({code:n.code,data:u,log_id:n.log_id}),responseHeaders:r.headers,statusCode:r.status,targetUrl:l}),!r.ok||void 0!==n.code&&0!==n.code)throw Error(`获取 Sandbox session 信息失败:${n.message||r.statusText||r.status}${n.log_id||p?`,log_id=${n.log_id||p}`:""}`);return u}async function sb(e,t){if(!e)return sf();try{return await sy(e,t)}catch(e){return nA.warn(`Sandbox session 信息查询已跳过:${e instanceof Error?e.message:String(e)}`),sf()}}async function s_(e,t,r){let n,i,s="POST",o=JSON.stringify({...e.csrPem?{csr_pem:e.csrPem}:{},phone_num:e.phoneNum,sandbox_session_id:t}),a={"content-type":"application/json",...n1(),[nR]:t},l=new URL(sa,r??ee),c=process.hrtime.bigint();try{n=await sc({body:o,headers:a,method:s,sandboxPath:sa,targetOrigin:r,targetUrl:l})}catch(e){throw sd(s,l,502,c,a),e}let p=n.headers.get(n$)||"",d=await n.text();sd(s,l,n.status,c,a,p),su({method:s,requestBody:JSON.stringify({...e.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:t}),requestHeaders:a,responseBody:d,responseHeaders:n.headers,statusCode:n.status,targetUrl:l});try{i=JSON.parse(d||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${n.status} 响应不是有效 JSON${p?`,log_id=${p}`:""}`)}if(!n.ok||void 0!==i.code&&0!==i.code)throw Error(`更新 Sandbox session 信息失败:${i.message||n.statusText||n.status}${i.log_id||p?`,log_id=${i.log_id||p}`:""}`)}async function sv(e,t,r,n){if(e&&t.phoneNum&&(!r||t.csrPem))try{return await s_({...t.csrPem?{csrPem:t.csrPem}:{},phoneNum:t.phoneNum},e,n),nA.info("Sandbox 业务信息已自动上传",{sessionId:e}),sg(t.csrPem)}catch(e){nA.warn(`Sandbox 业务信息自动上传已跳过:${e instanceof Error?e.message:String(e)}`);return}}async function sE(e,t){let r,n="/app_developer/api/sandbox/session/revoke",i="POST",s=JSON.stringify({sandbox_session_id:e}),o={"content-type":"application/json",...n1()},a=new URL(n,t??ee),l=process.hrtime.bigint();try{r=await sc({body:s,headers:o,method:i,sandboxPath:n,targetOrigin:t,targetUrl:a})}catch(t){let e=`撤回 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw sd(i,a,502,l,o),su({method:i,requestBody:s,requestHeaders:o,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:a}),t}let c=r.headers.get(n$)||"",p=await r.text();sd(i,a,r.status,l,o,c),su({method:i,requestBody:s,requestHeaders:o,responseBody:p,responseHeaders:r.headers,statusCode:r.status,targetUrl:a});let d=JSON.parse(p||"{}");if(!r.ok||0!==d.code)throw Error(`撤回 Sandbox session 失败:${d.message||r.statusText||r.status}${d.log_id||c?`,log_id=${d.log_id||c}`:""}`)}async function sw(e){if(e.recreatePromise)return e.recreatePromise;e.recreatePromise=(async()=>{var t;let r=e.sandboxSessionId;r&&await sE(r,e.sandboxTargetOrigin),e.bridge?.close(),e.bridge=void 0;let n=await sm(e.sandboxProjectId,e.simulatorManifestPath,e.simulatorManifestReader,e.simulatorBusinessTemplatesPath,e.sandboxTargetOrigin,e.sandboxSessionAppId),i=n.sessionId,s=!e.sandboxSessionAppId,o=await sv(i,e.businessInfoInput,s,e.sandboxTargetOrigin)??await sb(i,e.sandboxTargetOrigin);return e.sandboxAppId=n.appId,e.sandboxSessionId=i,e.businessInfo=o,(t=e).resourceConnectionStatus="connecting",t.resourceEventSequence=0,t.resourceEvents.length=0,t.simulatorEventSequence=0,t.simulatorEvents.length=0,t.resourceGeneration+=1,sA(t),e.bridge=sT(e,i),nA.info("Sandbox session 已重建",{sessionId:i}),{...n,businessInfoUploaded:o.phoneNumberUploaded&&(!s||o.csrUploaded)}})();try{return await e.recreatePromise}finally{e.recreatePromise=void 0}}function sS(e){return{bridgeLogs:e.bridgeLogs,bridgeLogsUpdatedAtMs:e.bridgeLogsUpdatedAtMs,connectionStatus:e.resourceConnectionStatus,events:e.resourceEvents,generation:e.resourceGeneration,instanceId:e.resourceInstanceId,simulatorEvents:e.simulatorEvents,updatedAtMs:e.resourceEventsUpdatedAtMs}}function sx(e){clearTimeout(e.logBroadcastTimer),e.logBroadcastTimer=void 0;let t=sS(e);for(let r of e.eventListeners)r(t)}function sA(e){e.resourceEventsUpdatedAtMs=Math.max(Date.now(),e.resourceEventsUpdatedAtMs+1),sx(e)}function sT(e,t){var r={onConnectionStatusChange:t=>{e.resourceConnectionStatus!==t&&(e.resourceConnectionStatus=t,sA(e))},onLog:t=>{let r=e.bridgeLogs.findIndex(e=>e.id===t.id);r>=0?e.bridgeLogs[r]=t:(e.bridgeLogs.push(t),e.bridgeLogs.length>200&&e.bridgeLogs.splice(0,e.bridgeLogs.length-200)),e.bridgeLogsUpdatedAtMs=Math.max(Date.now(),e.bridgeLogsUpdatedAtMs+1),e.logBroadcastTimer??=setTimeout(()=>sx(e),50)},onResourceChanged:t=>{e.resourceEvents.push({...t,sequence:++e.resourceEventSequence}),e.resourceEvents.length>200&&e.resourceEvents.splice(0,e.resourceEvents.length-200),sA(e)},onSimulatorEvent:t=>{e.simulatorEvents.push({...t,sequence:++e.simulatorEventSequence}),e.simulatorEvents.length>200&&e.simulatorEvents.splice(0,e.simulatorEvents.length-200),sA(e)},onSimulatorToolCall:e.onSimulatorToolCall,sandboxSessionId:t,targetOrigin:e.sandboxTargetOrigin};if(!r.sandboxSessionId)return void nA.warn("已跳过 Sandbox Bridge:缺少 Sandbox session id");let n=new AbortController;return se("正在启动 Sandbox Bridge",{session:i3(r.sandboxSessionId)}),r.onConnectionStatusChange?.("connecting"),si(r,n.signal),{close:()=>n.abort()}}async function sI(e,t,r){if("POST"!==e.method)return void nU(t,405,"不支持的请求方法");if(!r)return void nU(t,503,"Sandbox session 尚未初始化");try{let n=await nH(e,t,1048576);if(n){let e=JSON.parse(n);if(void 0!==e.csrPem&&"string"!=typeof e.csrPem||"string"!=typeof e.phoneNum)return void nU(t,400,"Sandbox 业务信息无效");r.businessInfoInput={..."string"==typeof e.csrPem&&e.csrPem.trim()?{csrPem:e.csrPem.trim()}:{},phoneNum:e.phoneNum.trim()}}let i=await sw(r);nB(t,200,{code:0,data:{sandbox_appid:i.appId,business_info_uploaded:i.businessInfoUploaded,sandbox_session_id:i.sessionId},message:"ok"})}catch(e){nU(t,500,e.message)}}function sO(e){let t=e.appId?.trim(),r=t&&!t.startsWith("doubao-sandbox-app-")?t:void 0,n=function(e){let t=t_.resolve(e??process.cwd()),r=t;try{r=tV.realpathSync.native(t)}catch{}return(0,iR.createHash)("sha256").update(r).digest("hex")}(e.appDirectory),i=function(e,t){let r=sp(e,"DOUBAO_SANDBOX_PHONE_NUM"),n=sp(e,"DOUBAO_SANDBOX_CSR_FILE"),i=function(e,t){if(!e)return;let r=t_.isAbsolute(e)?e:t_.resolve(t??process.cwd(),e);return sl(r)?r:void 0}(n,t),s="";if(n&&!i)nA.warn(`Sandbox CSR 文件不存在:${n}`);else if(i)try{s=tV.readFileSync(i,"utf8").trim()}catch(e){nA.warn(`Sandbox CSR 文件读取失败:${e instanceof Error?e.message:String(e)}`)}return{...r?{phoneNum:r}:{},...s?{csrPem:s}:{}}}(e.env,e.appDirectory),s=`${i.phoneNum??""}\0${i.csrPem??""}`;return{businessInfoInput:i,businessInfoInputKey:s,businessTemplatesPath:e.businessTemplatesPath,key:JSON.stringify([s,n,r,e.targetOrigin,e.businessTemplatesPath,e.manifestPath]),manifestReader:e.manifestReader,manifestPath:e.manifestPath,onSimulatorToolCall:e.onSimulatorToolCall,projectId:n,sessionAppId:r,targetOrigin:e.targetOrigin}}class sP{configKey;manifestReader;state;constructor(e,t,r){this.state=e,this.configKey=t,this.manifestReader=r}static async start(e){let t=sO(e),r=await sh(t.projectId,t.manifestPath,t.manifestReader,t.businessTemplatesPath,t.targetOrigin,t.sessionAppId),n=!t.sessionAppId,i={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await sv(r.sessionId,t.businessInfoInput,n,t.targetOrigin)??await sb(r.sessionId,t.targetOrigin),businessInfoInput:t.businessInfoInput,eventListeners:new Set,onSimulatorToolCall:t.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,resourceInstanceId:(0,iR.randomUUID)(),simulatorEventSequence:0,simulatorEvents:[],sandboxAppId:r.appId,sandboxProjectId:t.projectId,sandboxSessionAppId:t.sessionAppId,sandboxSessionId:r.sessionId,sandboxTargetOrigin:t.targetOrigin,simulatorBusinessTemplatesPath:t.businessTemplatesPath,simulatorManifestReader:t.manifestReader,simulatorManifestPath:t.manifestPath},s=new sP(i,t.key,t.manifestReader);return i.bridge=r.sessionId?sT(i,r.sessionId):void 0,s}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close(),clearTimeout(this.state.logBroadcastTimer),this.state.eventListeners.clear()}subscribeEvents(e){return this.state.eventListeners.add(e),e(sS(this.state)),()=>{this.state.eventListeners.delete(e)}}clearBridgeLogs(){this.state.bridgeLogs.length=0,this.state.bridgeLogsUpdatedAtMs=Math.max(Date.now(),this.state.bridgeLogsUpdatedAtMs+1),sx(this.state)}matches(e){let t=sO(e);return this.configKey===t.key&&this.manifestReader===t.manifestReader}getDebugContext(){var e;let t;return{fileSystemNamespace:(t=(e=this.state).sandboxSessionAppId?`real-app\0${e.sandboxSessionAppId}`:`virtual-app\0${e.sandboxAppId}\0${e.sandboxProjectId}`,`sandbox-v1:${(0,iR.createHash)("sha256").update(t).digest("hex")}`),sandboxSessionAvailable:!!this.state.sandboxSessionId,sandboxCsrRequired:!this.state.sandboxSessionAppId,sandboxCsrUploaded:this.state.businessInfo.csrUploaded,sandboxPhoneNumberUploaded:this.state.businessInfo.phoneNumberUploaded,sandboxEventsAvailable:!0,...this.state.businessInfoInput.csrPem?{sandboxCsrPem:this.state.businessInfoInput.csrPem}:{},...this.state.businessInfoInput.phoneNum?{sandboxPhoneNum:this.state.businessInfoInput.phoneNum}:{}}}getRequestRoutes(){return[{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>iK(e,t,{onBusinessInfoUpdated:e=>{this.state.businessInfo=sg(e?.csrPem),e&&(this.state.businessInfoInput=e)},sandboxAppId:this.state.sandboxAppId,sandboxSessionId:this.state.sandboxSessionId,targetOrigin:this.state.sandboxTargetOrigin})},{match:"/__web_sdk_sandbox_session_recreate__",handle:({request:e,response:t})=>sI(e,t,this.state)}]}}function sC(e,t){return e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath)}let sR="/__tools/tools.json",s$="/__events/events.json",sk="manifest.yaml",sN="skill";function sL(e){if(!e)return!1;try{return tV.statSync(e).isFile()}catch{return!1}}function sD(e,t){if(!e)return;let r=t_.isAbsolute(e)?e:t_.resolve(t??process.cwd(),e);return sL(r)?r:void 0}function sj(e,t){if(e&&t)return t_.relative(t,e).split(t_.sep).join("/")||"."}function sM(e){let t=t_.resolve(e);for(;;){if(sL(t_.join(t,sk)))return t;let e=t_.dirname(t);if(e===t)return;t=e}}function sU(e){try{return tV.lstatSync(e),!0}catch{return!1}}function sB(e,t,r,n){let i;if(!t.reader&&sL(t.sourcePath)){var s;let r,i=tV.statSync(t.sourcePath);nM(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":i.size,"Content-Type":n}),s=t.sourcePath,(r=tV.createReadStream(s)).once("error",()=>e.destroy()),r.pipe(e);return}try{i=t.reader?.()}catch{i=void 0}void 0===i?nU(e,404,`未找到 ${r}`):(nM(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(i),"Content-Type":n}),e.end(i))}function sF(e,t){return function(e){let t,r;if(!e)return{layout:"missing",entries:[]};let n=t_.resolve(e);try{t=tV.lstatSync(n)}catch(e){if("ENOENT"===e.code)return{directory:n,layout:"missing",entries:[]};return{directory:n,layout:"invalid",entries:[],error:`skill path cannot be inspected: ${n}: ${e.message}`}}if(t.isSymbolicLink()||!t.isDirectory())return{directory:n,layout:"invalid",entries:[],error:`skill path must be a non-symlink directory: ${n}`};try{var i;let e;i=n,e=[],function t(r){for(let n of tV.readdirSync(r,{withFileTypes:!0})){if(n.isSymbolicLink())continue;let s=t_.join(r,n.name);n.isDirectory()?t(s):n.isFile()&&"SKILL.md"===n.name&&e.push(function(e,t){let r=t_.relative(e,t).split(t_.sep).join("/");return{content:tV.readFileSync(t,"utf8"),relativePath:r}}(i,s))}}(i),r=e}catch(e){return{directory:n,layout:"invalid",entries:[],error:`skill directory is not readable: ${n}: ${e.message}`}}return r.sort(sC),r.length>0?{directory:n,layout:"resolved",entries:r}:{directory:n,layout:"missing",entries:[]}}(function(e,t){if(t){if(!t)return;if(t_.isAbsolute(t))return t;let r=e?sM(e):void 0,n=[e,r,process.cwd()].map(e=>t_.resolve(e??process.cwd(),t));return[...new Set(n)].find(sU)??n[0]}if(!e)return;let r=sM(e);return[...new Set([r?t_.join(r,sN):void 0,t_.join(e,sN),t_.join(process.cwd(),sN)].filter(Boolean))].find(sU)}(e,t))}class sH{appDirectory;businessTemplatesPath;manifestPath;manifestReader;eventsConfigReader;eventsConfigSource;toolsConfigReader;toolsConfigSource;manifestSource;skillsDirectory;sourceKey;constructor(e){var t,r,n;this.appDirectory=e.appDirectory,this.manifestPath=e.manifestPath?sD(e.manifestPath,e.appDirectory):e.manifestSourcePath??(e.manifestReader?void 0:function(e){if(!e)return;let t=sM(e);return[...new Set([t?t_.join(t,sk):void 0,t_.join(process.cwd(),sk)].filter(Boolean))].find(sL)}(e.appDirectory)),this.businessTemplatesPath=(t=this.manifestPath,r=e.businessTemplatesPath,n=e.appDirectory,r?sD(r,n):t?sD(t_.join(t_.dirname(t),"business-templates.yaml"),n):void 0),this.manifestReader=e.manifestReader,this.eventsConfigReader=e.eventsConfigReader,this.toolsConfigReader=e.toolsConfigReader,this.eventsConfigSource={reader:e.eventsConfigReader,sourcePath:e.eventsConfigSourcePath},this.skillsDirectory=e.skillsDirectory;let i=sF(e.appDirectory,this.skillsDirectory);if(e.skillsDirectory&&"resolved"!==i.layout)throw Error(i.error??`Simulator skills directory contains no runtime Skill: ${e.skillsDirectory}`);this.toolsConfigSource={reader:e.toolsConfigReader,sourcePath:e.toolsConfigSourcePath},this.manifestSource={reader:e.manifestReader,sourcePath:e.manifestSourcePath??this.manifestPath},this.sourceKey=JSON.stringify([this.appDirectory,this.businessTemplatesPath,this.manifestPath,this.eventsConfigSource.sourcePath,this.toolsConfigSource.sourcePath,this.manifestSource.sourcePath,this.skillsDirectory])}matches(e){let t=new sH(e);return this.sourceKey===t.sourceKey&&this.eventsConfigReader===t.eventsConfigReader&&this.toolsConfigReader===t.toolsConfigReader&&this.manifestReader===t.manifestReader}getDebugContext(){let e=sF(this.appDirectory,this.skillsDirectory),t="resolved"===e.layout?e.directory:void 0,r=sj(this.businessTemplatesPath,this.appDirectory),n=sj(this.eventsConfigSource.sourcePath,this.appDirectory),i=sj(this.toolsConfigSource.sourcePath,this.appDirectory),s=sj(this.manifestSource.sourcePath,this.appDirectory),o=sj(t,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:s$,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...n?{eventsConfigRelativePath:n}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:sR,...i?{toolsConfigRelativePath:i}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,...s?{simulatorManifestRelativePath:s}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...r?{simulatorBusinessTemplatesRelativePath:r}:{}}:{},...t?{simulatorSkillsDirectoryOriginalUrl:t,...o?{simulatorSkillsDirectoryRelativePath:o}:{}}:{}}}getRequestRoutes(){return[{match:s$,handle:({response:e})=>sB(e,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:sR,handle:({response:e})=>sB(e,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:e})=>sB(e,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:e})=>{let t;"missing"===(t=sF(this.appDirectory,this.skillsDirectory)).layout?nU(e,404,"未找到模拟器 Skill 目录"):"invalid"===t.layout?nU(e,422,t.error??"模拟器 Skill 目录结构无效"):nB(e,200,{skills:t.entries},{"Cache-Control":"no-cache"})}}]}}let sW=f("node:stream"),sG="/app_developer/api",sV=`${sG}/simulator/images/upload`,sq=new Set([`${sG}/simulator/chat`,sV,`${sG}/simulator/tool/report`]),sJ={"Access-Control-Expose-Headers":n$};async function sz(e,t,r,n){if(!sq.has(r.pathname))return void nU(t,404,"未找到模拟器接口",sJ);let i=n.targetOrigin??ee,s=new URL(`${r.pathname}${r.search}`,i),o=nJ(e,t);try{var a;let i=e.method??"GET",l=process.hrtime.bigint(),c=function(e,t,r){return Object.fromEntries(Object.entries(nL(e.headers,t,{...n1(),...r?{[nR]:r}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]))}(e,s,n.getSandboxSessionId?.()),p=await sK(e,t,r,i),d=n.targetOrigin?await fetch(s,{body:p,headers:c,method:i,signal:o}):await n4({internal:!0,path:`${r.pathname}${r.search}`,method:i,body:p,headers:c,signal:o});if(function(e,t,r,n,i,s){if(!eb())return;let o=Number(process.hrtime.bigint()-n)/1e6;nA.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:o,headers:i,logId:s})}(i,r,d.status,l,c,d.headers.get(n$)??void 0),t.destroyed||t.writableEnded)return void d.body?.cancel().catch(()=>void 0);await sY({method:i,requestBody:(a=p)instanceof Uint8Array?`(binary, ${a.byteLength} bytes)`:a,requestHeaders:c,requestUrl:r,response:t,upstreamResponse:d})}catch(e){if(t.destroyed||t.writableEnded||o.aborted)return;nU(t,502,`代理模拟器请求失败:${e instanceof Error?e.message:String(e)}`,sJ)}}async function sK(e,t,r,n){if("GET"!==n&&"HEAD"!==n)return r.pathname===sV?await nF(e,t,0xb00000):await nH(e,t,0xb00000)}async function sY({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:s}){var o,a;if(nM(i,sJ),i.writeHead(s.status,nj(s.headers,[n$])),o=n,a=s,o.pathname===`${sG}/simulator/chat`||a.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await sX({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:s});if(!eb())return s.body?void await (0,g.pipeline)(sW.Readable.fromWeb(s.body),i):void i.end();let l=await nW(s);nq({method:e,requestBody:t,requestHeaders:r,responseBody:l,responseHeaders:s.headers,statusCode:s.status,targetUrl:n}),i.end(l)}async function sX({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:s}){if(!s.body){nq({method:e,requestBody:t,requestHeaders:r,responseBody:"",responseHeaders:s.headers,statusCode:s.status,targetUrl:n}),i.end();return}let o=sW.Readable.fromWeb(s.body);if(!eb())return void await (0,g.pipeline)(o,i);nq({method:e,requestBody:t,requestHeaders:r,responseBody:"(event stream)",responseHeaders:s.headers,statusCode:s.status,targetUrl:n});let a=new sW.Transform({transform(e,t,r){let i;try{i=String(e).split("\n\n").filter(Boolean)}catch(t){return nA.error(`事件流分片解码失败:${t?.toString()}`),r(null,e)}for(let e of i)nA.info(`来自 ${n.pathname}${n.search} 的事件
165
+ ${e}`);r(null,e)}});await (0,g.pipeline)(o,a,i)}async function sZ(e,t){if("POST"!==e.method)return void nB(t,405,{message:"不支持的请求方法"});let r=nJ(e,t);try{var n,i;let s,o,a=JSON.parse(await nH(e,t,0xa00000)),l=function(e){if("GET"!==e&&"POST"!==e)throw Error(`Unsupported request method: ${String(e)}`);return e}(a.method),c=nN(a.url),p=await fetch(c,{signal:r,body:"POST"===l?function(e){if(void 0!==e.data&&null!==e.data){if("base64"===e.dataEncoding&&"string"==typeof e.data){var t;let r;return r=new ArrayBuffer((t=Buffer.from(e.data,"base64")).byteLength),new Uint8Array(r).set(t),r}if(void 0===e.dataEncoding&&"string"==typeof e.data)return e.data;throw Error("Invalid prepared request body")}}(a):void 0,headers:(n=a.header,s=new Headers(n),["connection","content-length","host","origin","referer"].forEach(e=>s.delete(e)),s),method:l}),d=Buffer.from(await p.arrayBuffer()).toString("base64");nB(t,200,{data:d,dataEncoding:"base64",header:(i=p.headers,o={},i.forEach((e,t)=>{o[t]=e}),o),statusCode:p.status})}catch(e){if(r.aborted||t.destroyed)return;nB(t,500,{message:e instanceof Error?e.message:String(e)})}}let sQ=f("../../../node_modules/.pnpm/send@1.2.0/node_modules/send/index.js"),s0="/__web_artifacts",s1="/wsd";function s2(e,t,r,n,i={}){nM(t,i.headers),sQ(e,n,{root:r}).once("error",n=>{if(404===n.statusCode&&i.fallbackPath)return void s2(e,t,r,i.fallbackPath,{headers:i.headers});if(t.headersSent)return void t.destroy(n);let s=n.statusCode??500;nU(t,s,nT.STATUS_CODES[s]??"Internal Server Error")}).pipe(t)}let s3="/__webview",s4=`${s3}/client.js`,s5=`${s3}/page`,s8=`${s3}/runtime`,s9=`${s3}/sw.js`,s7="x-doubao-web-view-target",s6="Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",oe=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_tslib@2.8.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-bootstrap.js"),f.b),ot=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_tslib@2.8.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"),f.b),or=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_core-js@3.47.0_esbuild@0.28.1_hono@4.13.1_tslib@2.8.1_typescript@6.0.3/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"),f.b);function on(e,t,r,n=!1){if("GET"!==e.method&&"HEAD"!==e.method)return void nU(t,405,"不支持的请求方法");let i=tV.readFileSync(r,"utf8");nM(t,{"Cross-Origin-Resource-Policy":"cross-origin"}),t.writeHead(200,{"cache-control":"no-store","content-length":Buffer.byteLength(i),"content-type":"text/javascript; charset=utf-8",...n?{"service-worker-allowed":"/"}:{}}),t.end("HEAD"===e.method?void 0:i)}function oi(e,t){let r=e.searchParams.get("parentOrigin")??t[0];if(!t.includes(r))throw Error("WebView 父级 origin 无效");return r}async function os(e,t,r,n){if("GET"!==e.method&&"HEAD"!==e.method)return void nU(t,405,"不支持的请求方法");let i=nJ(e,t);try{let s=oi(r,n),o=nN(r.searchParams.get("url")??void 0),a=await fetch(o,{signal:i,headers:{"user-agent":s6,..."string"==typeof e.headers.accept?{accept:e.headers.accept}:{},..."string"==typeof e.headers["accept-language"]?{"accept-language":e.headers["accept-language"]}:{}},method:e.method}),l=a.url?new URL(a.url):o;l.hash=o.hash;let c=a.headers.get("content-type")??"",p=nj(a.headers);if(p["cache-control"]="no-cache",p["cross-origin-resource-policy"]="cross-origin",p["x-doubao-web-view-parent-origin"]=s,"HEAD"===e.method||!c.includes("text/html")){let r="HEAD"===e.method?void 0:Buffer.from(await a.arrayBuffer());nM(t),t.writeHead(a.status,{...p,[s7]:l.toString(),...r?{"content-length":r.byteLength}:{}}),t.end(r);return}let d=function(e,t,r){let n=new URLSearchParams({mobileUserAgent:s6,originalPath:`${t.pathname}${t.search}${t.hash}`,parentOrigin:r}).toString().replaceAll("&","&amp;"),i=`<script src="${s4}?${n}"></script>`,s=/<head[^>]*>/i.exec(e);if(s){let t=s.index+s[0].length;return`${e.slice(0,t)}${i}${e.slice(t)}`}return`${i}${e}`}(await a.text(),l,s);nM(t),t.writeHead(a.status,{...p,[s7]:l.toString(),"content-length":Buffer.byteLength(d)}),t.end(d)}catch(e){if(i.aborted||t.destroyed)return;nU(t,502,`代理 web-view 页面失败: ${e instanceof Error?e.message:String(e)}`)}}async function oo(e){let t=new URL(e).toString();try{await S(t)}catch(e){nA.error("打开 Web 模拟器失败",{error:e}),nA.info("请手动打开 Web 模拟器(本地)",{url:t})}}async function oa(e,t){await new Promise((r,n)=>{let i=t=>{e.off("listening",s),n(t)},s=()=>{e.off("error",i),r()};e.once("error",i),e.once("listening",s),e.listen(t,"127.0.0.1")})}async function ol(e){var t;let r=await Z(9e3),n=nT.createServer(nY((t=[`http://127.0.0.1:${r}`,`http://localhost:${r}`],[{match:`${s3}/bootstrap`,handle:({request:e,response:r,url:n})=>{if("GET"!==e.method&&"HEAD"!==e.method)return void nU(r,405,"不支持的请求方法");try{nN(n.searchParams.get("url")??void 0),oi(n,t)}catch{nU(r,400,"WebView URL 无效");return}nM(r,{"Cross-Origin-Resource-Policy":"cross-origin"}),r.writeHead(200,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),r.end("HEAD"===e.method?void 0:'<!doctype html><meta charset="utf-8"><script src="/__webview/bootstrap.js"><\/script>')}},{match:`${s3}/bootstrap.js`,handle:({request:e,response:t})=>on(e,t,oe)},{match:s9,handle:({request:e,response:t})=>on(e,t,or,!0)},{match:s4,handle:({request:e,response:t})=>on(e,t,ot)},{match:s8,handle:({request:e,response:t,url:r})=>(function(e,t,r){let n;try{n=nN(r.searchParams.get("url")??void 0)}catch(e){nU(t,400,`无效的 web-view 请求地址: ${e instanceof Error?e.message:String(e)}`);return}let i=nL(e.headers,n,{"user-agent":s6});for(let e of Object.keys(i))e.startsWith("sec-fetch-")&&delete i[e];nz(e,t,{createResponseHeaders:e=>{let t=nD(e),r=Array.isArray(e.location)?e.location[0]:e.location;if(r&&URL.canParse(r,n)){let e=new URL(r,n);t.location=`${s8}?url=${encodeURIComponent(e.toString())}`}return t["cache-control"]="no-cache",t},errorMessage:"代理 web-view 运行时请求失败",requestHeaders:i,targetUrl:n})})(e,t,r)},{match:s5,handle:({request:e,response:r,url:n})=>os(e,r,n,t)}]),({response:e})=>{nU(e,404,"未找到 WebView 资源")}));await oa(n,0);let i=n.address(),s=`http://127.0.0.1:${i.port}`,o=nT.createServer(function({webViewOrigin:e,artifactOrigin:t,debugScenes:r,debuggerProtocol:n,distPath:i,getWidgetViewDataTemplates:s,mcpEndpoint:o,mcpHeaders:a,physicalDeviceDebugGateway:l,sandboxRuntime:c,simulatorAssets:p,simulatorTargetOrigin:d}){var u;let m={routes:[{match:e=>e.pathname.startsWith(s0),handle:({request:e,response:r,url:n})=>{let i,s;return i=n.pathname.replace(s0,"")||"/",s=new URL(`${i}${n.search}`,t),void nz(e,r,{createResponseHeaders:e=>({...nD(e),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:nL(e.headers,s),targetUrl:s})}},{match:e=>e.pathname===s1||e.pathname.startsWith(`${s1}/`),handle:({request:e,response:t,url:r})=>{let n;!(n=r.pathname.slice(`${s1}/`.length))||n!==t_.basename(n)?nU(t,404,"未找到资源"):s2(e,t,t_.join(i,"wsd"),n,{headers:{"Cache-Control":"no-cache"}})}},{match:"/__web_sdk_request_proxy__",handle:({request:e,response:t})=>sZ(e,t)},{match:"/__webview/page",handle:({request:t,response:r,url:n})=>{"GET"!==t.method&&"HEAD"!==t.method?nU(r,405,"不支持的请求方法"):(nM(r),r.writeHead(302,{"cache-control":"no-store",location:`${e}/__webview/bootstrap${n.search}`}),r.end())}},{match:"/__webview/sw.js",handle:({response:e})=>{nM(e),e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript","service-worker-allowed":"/"}),e.end(`self.addEventListener('install', e => e.waitUntil(self.skipWaiting()));
160
166
  self.addEventListener('activate', e => e.waitUntil((async () => {
161
167
  await self.clients.claim();
162
168
  await self.registration.unregister();
163
- })()));`)}},{match:e=>e.pathname.startsWith("/__doubao_web_sdk_native_modules"),handle:({request:e,response:t,url:r})=>oJ(e,t,i,r.pathname)},{match:e=>e.pathname.startsWith("/__"),handle:({response:e})=>nT(e,404,"Debugger resource not found")}],fallback:({request:e,response:t,url:r})=>oJ(e,t,i,r.pathname,{fallbackPath:"/index.html"})};return nM([...(u={artifactOrigin:t,webViewOrigin:e,debugScenes:r,getWidgetViewDataTemplates:o,mcpEndpoint:a,physicalDeviceDebugGateway:l,sandboxRuntime:d,simulatorAssets:p},[{match:"/__web_sdk_debug_context",handle:({request:e,response:t})=>{let r,n;return n="string"==typeof(r=e.headers.host)&&r?`http://${r}`:void 0,void nC(t,200,{homeDir:rI.homedir(),webViewOrigin:u.webViewOrigin,launchDir:u.simulatorAssets.appDirectory,debugScenesEndpoint:ih,widgetViewDataTemplatesEndpoint:im,debuggerMcpEndpoint:n?new URL(ic,n).toString():ic,manifestOriginalUrl:new URL("/base/manifest.json",u.artifactOrigin).toString(),...u.mcpEndpoint?{mcpOriginalEndpoint:u.mcpEndpoint,mcpProxyEndpoint:nz}:{},realDeviceDebug:u.physicalDeviceDebugGateway?.getDebugContext(),...u.simulatorAssets.getDebugContext(),...u.sandboxRuntime.getDebugContext()},ig)}},{match:ih,handle:({response:e})=>nC(e,200,u.debugScenes??{errors:[],scenes:[]},ig)},{match:im,handle:({response:e})=>iy(e,u.getWidgetViewDataTemplates)}]),...l.getRequestRoutes(),...n,...function(e={}){return[{match:e=>e.pathname===oN||e.pathname.startsWith(`${oN}/`),handle:({request:t,response:r,url:n})=>oU(t,r,n,e)}]}({getSandboxSessionId:()=>d.sessionId,targetOrigin:c}),...d.getRequestRoutes(),...function(e={}){return[{match:nz,handle:({request:t,response:r,url:n})=>(function(e,t,r={},n=nv(e)){let i=et(r.targetEndpoint);if(!n)return void nT(t,400,"Bad request");if(!i)return void nT(t,404,"MCP endpoint not configured");let o=new URL(i);for(let[e,t]of new URLSearchParams(n.search))o.searchParams.append(e,t);nN(e,t,{createResponseHeaders:nE,errorMessage:"代理 MCP 请求失败",requestHeaders:nS(e.headers,o,{...nW(),...r.headers}),targetUrl:o})})(t,r,e,n)}]}({headers:s,targetEndpoint:a}),...p.getRequestRoutes(),...h.routes],h.fallback)}({...e,webViewOrigin:o})),s=e.debuggerProtocol.attachConnection(a,e.sandboxRuntime);try{await o7(a,r)}catch(e){throw s(),await ae(n),e}return{origin:`http://127.0.0.1:${r}`,server:a,webViewServer:n,closeConnections:s}}async function ae(e){e.listening&&await new Promise((t,r)=>{e.close(e=>{e?r(e):t()}),e.closeIdleConnections(),e.closeAllConnections()})}async function at(){if(!n)return;let{physicalDeviceDebugGateway:e,sandboxRuntime:t,server:r,webViewServer:i,closeConnections:o}=n;n=void 0,o(),e.dispose(),t.close(),await Promise.all([ae(r),ae(i)])}async function ar(e){let t,{targetOrigin:r,...i}=e.simulator??{},o={appDirectory:e.appDirectory,eventsConfigReader:e.eventsConfigReader,eventsConfigSourcePath:e.eventsConfigSourcePath,toolsConfigReader:e.toolsConfigReader,toolsConfigSourcePath:e.toolsConfigSourcePath,manifestReader:e.simulatorManifestReader,manifestSourcePath:e.simulatorManifestSourcePath,...i},a=new o$(o);try{var s,l;let i,d,p=et(e.mcpEndpoint),c={appDirectory:e.appDirectory,appId:e.appId,businessTemplatesPath:a.businessTemplatesPath,env:e.env,manifestReader:e.simulatorManifestReader,manifestPath:a.manifestPath,targetOrigin:e.sandboxTargetOrigin};if(s=n,s?.server.listening){if(n?.artifactOrigin===e.artifactOrigin&&n.mcpEndpoint===p&&n.simulatorAssets.matches(o)&&n.getWidgetViewDataTemplates===e.getWidgetViewDataTemplates&&n.sandboxRuntime.matches(c)&&n.simulatorTargetOrigin===r)return n;await at()}let u={distPath:l=e.debuggerDistPath,indexPath:ta.join(l,"index.html")};if(!to.existsSync(u.indexPath))return void nu.error("Web 模拟器资源缺失,请联系框架开发者。");let h=(i={},d=new n4(i),Object.assign([{match:"/__agent_trace",handle:e=>iT(e,i,d)},{match:ic,handle:e=>iu(e,i,d)}],{attachConnection:(e,t)=>{var r;let n,o,a,s;return r=e=>iC(i,d,e),n=new nY({noServer:!0,maxPayload:0xa00000}),o=new Set,a=(i,a,s)=>{let l,p=e.address().port,c=i.headers.host;try{l=new URL(i.url??"/","http://127.0.0.1")}catch{a.destroy();return}let u=l.searchParams.get("clientId")?.trim();c!==`127.0.0.1:${p}`&&c!==`localhost:${p}`||void 0!==i.headers.origin&&i.headers.origin!==`http://${c}`?a.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"):"/__wsd_connection"!==l.pathname||!u||u.length>128?a.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"):n.handleUpgrade(i,a,s,e=>{d.registerClient(u,e),o.add(e),e.on("pong",()=>o.add(e)),e.on("error",()=>e.close());let n=t.subscribeEvents(t=>nX(e,"sandbox",t));e.once("close",()=>{o.delete(e),n()}),e.on("message",(n,i)=>{try{let e=i?void 0:JSON.parse(n.toString());if(!el(e))throw Error("Invalid debugger message");if("snapshot"===e.type&&el(e.data)&&el(e.data.snapshot))r({...e.data,...el(e.data.debug_snapshot)?{debug_snapshot:{...e.data.debug_snapshot,client_id:u}}:{},snapshot:{...e.data.snapshot,client_id:u}});else if("control_result"===e.type&&el(e.data))d.handleResult({...e.data,clientId:u});else if("clear_sandbox_logs"===e.type)t.clearBridgeLogs();else throw Error("Unknown debugger message")}catch{e.close(1008,"Invalid debugger message")}})})},e.on("upgrade",a),(s=setInterval(()=>{for(let e of n.clients)o.delete(e)?e.ping():e.terminate()},3e4)).unref(),()=>{for(let t of(clearInterval(s),e.off("upgrade",a),n.clients))t.terminate();n.close()}},executeSandboxToolCall:e=>d.execute("execute_sandbox_tool_call",{toolCall:e})})),m=await ov.start({...c,onSimulatorToolCall:async e=>{await h.executeSandboxToolCall(e)}});t=m;let f=new ix,{origin:g,server:y,webViewServer:b,closeConnections:_}=await o6({artifactOrigin:e.artifactOrigin,debugScenes:e.debugScenes,debuggerProtocol:h,distPath:u.distPath,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:p,mcpHeaders:e.mcpHeaders,physicalDeviceDebugGateway:f,sandboxRuntime:m,simulatorAssets:a,simulatorTargetOrigin:r}),v=()=>{y.close(),b.close()};y.once("close",()=>{process.off("exit",v)}),process.once("exit",v);let w=new URL(g).toString();return n={artifactOrigin:e.artifactOrigin,close:()=>at(),debuggerMcpEndpoint:new URL(ic,g).toString(),getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:p,open:()=>o8(w),origin:g,physicalDeviceDebugGateway:f,sandboxRuntime:m,get sandboxSessionId(){return m.sessionId},server:y,webViewServer:b,closeConnections:_,setRealDeviceDebugProvider(e){f.setProvider(e)},simulatorAssets:a,simulatorTargetOrigin:r,url:w}}catch(e){t?.close(),nu.error("启动 Web SDK 调试器失败",{error:e});return}}async function an(e,t){let r={errors:[],scenes:[]};if(!e)return r;for(let n of(await tM(e)).sort((e,t)=>e.name.localeCompare(t.name))){let e=await tj(n.path);e&&function(e,t){let r=X(e);return"tool"!==r.type&&("widget"===r.type?t.widgetIds.has(r.id):0===r.unresolvedVariables.length)}(e,t)&&r.scenes.push({content:e,name:n.name})}return r}async function ai(e,t){let r=e.metadata.getData(),n=e.widgets,i=await an(e.appDirectory,{widgetIds:new Set(Object.keys(n).map(e=>rv(n,r.widgets,e)))});return ar({...t,debuggerDistPath:t.debuggerDistPath??F(),debugScenes:i,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates})}function ao(e){return!!(e&&!/<%=?\s*appId\s*%>/.test(e))}function aa(e){if(!(e instanceof Error))return!1;try{let t=JSON.parse(e.message);return t?.code===0x2fb1799}catch{return!1}}async function as(e){ao(e.appId)&&(await e.getCachedLoginCookie().catch(()=>void 0)||tD.warn(e.appId.startsWith("db_")?"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `dbx auth login` 后重新启动开发服务。":"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `npx doubao login` 后重新启动开发服务。"))}let al=e=>ep.bgHex("#9873b9")(ep.italic(ep.black(` ${e} `))),ad=e=>ep.bgBlueBright(ep.italic(ep.black(` ${e} `))),ap=e=>ep.bold(ep.blueBright(e)),ac=[{command:"d",description:"选择调试场景 / pages / widgets"},{command:"web",description:"打开 Web 模拟器"}],au={page:"页面",scene:"调试场景",widget:"组件"};function ah(e){console.log(` ${ap(e.command.padEnd(21))} ${ep.gray(`- ${e.description}`)}`)}async function am(e){let t=J(e);if(0!==t.length)return await eu.prompt(t.map(([e,t])=>({type:"input",name:e,message:`请输入调试场景变量 "${e}" 的值:`,default:t??void 0})))}async function af({matchedScene:e,appId:t,driver:r}){let n=await tj(e.path);if(!n)return;let i=await am(n);await tU({matchedScene:e,appId:t,driver:r,variables:i},n)}async function ag(e,t,r,n,i,o,{interactive:a=!0}={}){if(await i.load({appletUrl:t,appId:e,isSigned:o}),!a)return;let s=await tM(process.cwd()),l=Object.values(r),d=Object.values(n),p=d.filter(({id:e})=>!te(e));return l.length>0&&(console.log(`
164
-
165
- ${ad("可用 pages 列表")}
166
- `),l.forEach(e=>{console.log(` - ${ap(e.path)}`)})),p.length>0&&(console.log(`
167
- ${ad("可用 widgets 列表")}
168
- `),p.forEach(e=>{let t=ap(e.id);console.log(` - ${t}`)})),s.length>0&&(console.log(`
169
- ${ad("可用调试场景")}
170
- `),s.forEach(e=>console.log(` - ${ap(e.name)}`))),console.log(`
171
- ${ad("可以继续执行以下命令:")}
172
- `),ac.forEach(ah),console.log("\n"),nd.instance.addListener(t=>{let r=t.trim();if("d"===r){let t=[...s.map(e=>({type:"scene",id:e.name})),...p.map(e=>({type:"widget",id:e.id})),...l.map(e=>({type:"page",id:e.path}))];if(0===t.length)return console.log(`
173
- ${ad("暂无可用的页面、组件或调试场景")}`),!0;nc(async()=>{let{selectedEntry:r}=await eu.prompt([{type:"search",name:"selectedEntry",message:"请选择调试目标:",source:e=>t.filter(t=>`${au[t.type]} ${t.type} ${t.id}`.toLowerCase().includes(e?.toLowerCase()??"")).map(e=>({name:`${ep.gray(au[e.type])}: ${e.id}`,short:`${au[e.type]} \xb7 ${e.id}`,value:e}))}]);if("scene"===r.type){let t=s.find(e=>e.name===r.id);t&&await af({matchedScene:t,appId:e,driver:i})}else"widget"===r.type?i.pushWidget({appId:e,widgetId:r.id}):i.openPageUrl({appId:e,url:r.id})})}else{let t=s.find(e=>e.name===r);t?nc(async()=>{await af({matchedScene:t,appId:e,driver:i})}):d.some(e=>e.id===r)?i.pushWidget({appId:e,widgetId:r}):i.openPageUrl({appId:e,url:r})}return!0},"openPage")}async function ay({appId:e,appletUrl:t,pages:r,widgets:n,driver:i,isSigned:o,isDisposed:a}){let s=await tx();if(a())return;if(!s)return void tD.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");let l=await tS(s).catch(e=>(a()||tD.error("重新启动应用失败",{error:e}),!1));if(a())return;if(!l)return void setTimeout(()=>{a()||tD.info("请确认应用已经启动。\n")},1e3);if(await new Promise(e=>{setTimeout(e,5e3)}),a())return;if(!i)return void tD.error("调试驱动尚未就绪。");let d=await ag(e,t,r,n,i,o);a()&&d?.()}async function ab({context:e,port:t,driver:r,isSigned:n,onCleanupReady:i}){let o,a,{host:s,artifactOrigin:l}=await e.resolveDevServer(t);e.devServerAbort.signal.throwIfAborted();let d=e.metadata.getData(),p=d.app.appId,c=async()=>{let t,r=await (t=e.webDebuggerLaunchOptions,ai(e,{appId:e.appId,appDirectory:e.appDirectory,artifactOrigin:l,env:{...e.env,...t?.env??{}},mcpEndpoint:t?.mcpEndpoint??ty(),mcpHeaders:t?.mcpHeaders,simulator:t?.simulator,eventsConfigReader:e.eventsResources?.readJson,eventsConfigSourcePath:e.eventsResources?.sourcePath,toolsConfigReader:e.toolsResources?.readToolsJson,toolsConfigSourcePath:e.toolsResources?.toolsSourcePath,simulatorManifestReader:t?.simulator?.manifestPath?void 0:e.toolsResources?.readManifestYaml,simulatorManifestSourcePath:t?.simulator?.manifestPath?void 0:e.toolsResources?.manifestSourcePath}));await r?.open()};if(e.devServerInteractive){let t;t=function(e={}){let t={name:"Doubao Apps SDK",...e},r=t.name?`${t.name} 开发服务`:"",n=t.origin?`正在监听 ${ep.gray(t.origin)}。`:"已启动。";return`
174
- ${ap(r)}${n}
175
- `}(),tm()||console.clear(),console.log(t),console.log(((e,t)=>{if(e&&t){let r=[{title:"\uD83C\uDF10 服务地址",content:t},{title:"\uD83D\uDCE6 应用 ID",content:e}].map(({title:e,titleHighlighter:t,content:r})=>{let n=t?t(e):ep.bold(ep.gray(e));return` - ${ep.bgWhiteBright(ep.italic(ep.black(` ${n} `)))}: ${ep.gray(r.startsWith("http")?ep.underline(r):r)}`}).join("\n");return`
176
- ${al("豆包应用服务信息")}:
169
+ })()));`)}},{match:e=>e.pathname.startsWith("/__doubao_web_sdk_native_modules"),handle:({request:e,response:t,url:r})=>s2(e,t,i,r.pathname)},{match:e=>e.pathname.startsWith("/__"),handle:({response:e})=>nU(e,404,"未找到调试器资源")}],fallback:({request:e,response:t,url:r})=>s2(e,t,i,r.pathname,{fallbackPath:"/index.html"})};return nY([...(u={artifactOrigin:t,webViewOrigin:e,debugScenes:r,getWidgetViewDataTemplates:s,mcpEndpoint:o,physicalDeviceDebugGateway:l,sandboxRuntime:c,simulatorAssets:p},[{match:"/__web_sdk_debug_context",handle:({request:e,response:t})=>{let r,n;return n="string"==typeof(r=e.headers.host)&&r?`http://${r}`:void 0,void nB(t,200,{homeDir:rw.homedir(),webViewOrigin:u.webViewOrigin,launchDir:u.simulatorAssets.appDirectory,debugScenesEndpoint:iI,widgetViewDataTemplatesEndpoint:iO,debuggerMcpEndpoint:n?new URL(iA,n).toString():iA,manifestOriginalUrl:new URL("/base/manifest.json",u.artifactOrigin).toString(),...u.mcpEndpoint?{mcpOriginalEndpoint:u.mcpEndpoint,mcpProxyEndpoint:n7}:{},realDeviceDebug:u.physicalDeviceDebugGateway?.getDebugContext(),...u.simulatorAssets.getDebugContext(),...u.sandboxRuntime.getDebugContext()},iP)}},{match:iI,handle:({response:e})=>nB(e,200,u.debugScenes??{errors:[],scenes:[]},iP)},{match:iO,handle:({response:e})=>iC(e,u.getWidgetViewDataTemplates)}]),...l.getRequestRoutes(),...n,...function(e={}){return[{match:e=>e.pathname===sG||e.pathname.startsWith(`${sG}/`),handle:({request:t,response:r,url:n})=>sz(t,r,n,e)}]}({getSandboxSessionId:()=>c.sessionId,targetOrigin:d}),...c.getRequestRoutes(),...function(e={}){return[{match:n7,handle:({request:t,response:r,url:n})=>(function(e,t,r={},n=nk(e)){let i=er(r.targetEndpoint);if(!n)return void nU(t,400,"Bad request");if(!i)return void nU(t,404,"MCP endpoint not configured");let s=new URL(i);for(let[e,t]of new URLSearchParams(n.search))s.searchParams.append(e,t);nz(e,t,{createResponseHeaders:nD,errorMessage:"代理 MCP 请求失败",requestHeaders:nL(e.headers,s,{...n1(),...r.headers}),targetUrl:s})})(t,r,e,n)}]}({headers:a,targetEndpoint:o}),...p.getRequestRoutes(),...m.routes],m.fallback)}({...e,webViewOrigin:s})),a=e.debuggerProtocol.attachConnection(o,e.sandboxRuntime);try{await oa(o,r)}catch(e){throw a(),await oc(n),e}return{origin:`http://127.0.0.1:${r}`,server:o,webViewServer:n,closeConnections:a}}async function oc(e){e.listening&&await new Promise((t,r)=>{e.close(e=>{e?r(e):t()}),e.closeIdleConnections(),e.closeAllConnections()})}async function op(){if(!n)return;let{physicalDeviceDebugGateway:e,sandboxRuntime:t,server:r,webViewServer:i,closeConnections:s}=n;n=void 0,s(),e.dispose(),t.close(),await Promise.all([oc(r),oc(i)])}async function od(e){let t,{targetOrigin:r,...i}=e.simulator??{},s={appDirectory:e.appDirectory,eventsConfigReader:e.eventsConfigReader,eventsConfigSourcePath:e.eventsConfigSourcePath,toolsConfigReader:e.toolsConfigReader,toolsConfigSourcePath:e.toolsConfigSourcePath,manifestReader:e.simulatorManifestReader,manifestSourcePath:e.simulatorManifestSourcePath,...i},o=new sH(s);try{var a,l;let i,c,p=er(e.mcpEndpoint),d={appDirectory:e.appDirectory,appId:e.appId,businessTemplatesPath:o.businessTemplatesPath,env:e.env,manifestReader:e.simulatorManifestReader,manifestPath:o.manifestPath,targetOrigin:e.sandboxTargetOrigin};if(a=n,a?.server.listening){if(n?.artifactOrigin===e.artifactOrigin&&n.mcpEndpoint===p&&n.simulatorAssets.matches(s)&&n.getWidgetViewDataTemplates===e.getWidgetViewDataTemplates&&n.sandboxRuntime.matches(d)&&n.simulatorTargetOrigin===r)return n;await op()}let u={distPath:l=e.debuggerDistPath,indexPath:t_.join(l,"index.html")};if(!tV.existsSync(u.indexPath))return void nA.error("Web 模拟器资源缺失,请联系框架开发者。");let m=(i={},c=new il(i),Object.assign([{match:"/__agent_trace",handle:e=>(function({request:e,response:t,url:r},n){let i;if("OPTIONS"===e.method){nM(t,iM),t.writeHead(204),t.end();return}"GET"!==e.method?nB(t,405,{error:"Method not allowed"},iM):nB(t,200,function(e,t){if(!e?.debug_snapshot)return e;let{debug_snapshot:r,...n}=e;return t?{...n,snapshot:r}:n}(n.snapshot,(i=r.searchParams.get("DEBUG"),null!=i&&"0"!==i&&"false"!==i.toLowerCase()))??{stored:!1},iM)})(e,i)},{match:iA,handle:e=>iT(e,i,c)}],{attachConnection:(e,t)=>{var r;let n,s,o,a;return r=e=>{var t,r;let n,s;return s=(r=t=e).snapshot.client_id??r.debug_snapshot?.client_id,n="string"==typeof s&&s.trim()?s.trim():void 0,void(t=function(e,t){let r=e?.snapshot,n=t.snapshot,i=r?.runtime_snapshot,s=n.runtime_snapshot;if(!r||!i||r.client_id!==n.client_id)return t;if(!s){var o;let e;if(o=i.target,e=function(e){let t=e.render_targets?.currentTarget;if(t)return t;let r=e.context;if(r){if(Object.hasOwn(r,"widget_id"))return{type:"widget"};if(Object.hasOwn(r,"page_id")||Object.hasOwn(r,"page_path"))return{type:"page"}}}(n),o&&e&&(1===Object.keys(e).length?e.type!==o.type:JSON.stringify(e)!==JSON.stringify(o)))return t;let{root:r,...s}=i;return{...t,snapshot:{...n,runtime_snapshot:i},...t.debug_snapshot?{debug_snapshot:{...t.debug_snapshot,runtime_snapshot:s}}:{}}}return Object.hasOwn(s,"root")||!Object.hasOwn(i,"root")||i.updatedAtMs!==s.updatedAtMs||JSON.stringify(i.target)!==JSON.stringify(s.target)?t:{...t,snapshot:{...n,runtime_snapshot:{...s,root:i.root}}}}(n?c.getSnapshotStore(n).snapshot:i.snapshot,t),i.snapshot=t,i.updatedAtMs=Date.now(),c.noteSnapshot(n))},n=new n6({noServer:!0,maxPayload:0xa00000}),s=new Set,o=(i,o,a)=>{let l,p=e.address().port,d=i.headers.host;try{l=new URL(i.url??"/","http://127.0.0.1")}catch{o.destroy();return}let u=l.searchParams.get("clientId")?.trim();d!==`127.0.0.1:${p}`&&d!==`localhost:${p}`||void 0!==i.headers.origin&&i.headers.origin!==`http://${d}`?o.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"):"/__wsd_connection"!==l.pathname||!u||u.length>128?o.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"):n.handleUpgrade(i,o,a,e=>{c.registerClient(u,e),s.add(e),e.on("pong",()=>s.add(e)),e.on("error",()=>e.close());let n=t.subscribeEvents(t=>ie(e,"sandbox",t));e.once("close",()=>{s.delete(e),n()}),e.on("message",(n,i)=>{try{let e=i?void 0:JSON.parse(n.toString());if(!K(e))throw Error("Invalid debugger message");if("snapshot"===e.type&&K(e.data)&&K(e.data.snapshot))r({...e.data,...K(e.data.debug_snapshot)?{debug_snapshot:{...e.data.debug_snapshot,client_id:u}}:{},snapshot:{...e.data.snapshot,client_id:u}});else if("control_result"===e.type&&K(e.data))c.handleResult({...e.data,clientId:u});else if("clear_sandbox_logs"===e.type)t.clearBridgeLogs();else throw Error("Unknown debugger message")}catch{e.close(1008,"Invalid debugger message")}})})},e.on("upgrade",o),(a=setInterval(()=>{for(let e of n.clients)s.delete(e)?e.ping():e.terminate()},3e4)).unref(),()=>{for(let t of(clearInterval(a),e.off("upgrade",o),n.clients))t.terminate();n.close()}},executeSandboxToolCall:e=>c.execute("execute_sandbox_tool_call",{toolCall:e})})),h=await sP.start({...d,onSimulatorToolCall:async e=>{await m.executeSandboxToolCall(e)}});t=h;let f=new ij,{origin:g,server:y,webViewServer:b,closeConnections:_}=await ol({artifactOrigin:e.artifactOrigin,debugScenes:e.debugScenes,debuggerProtocol:m,distPath:u.distPath,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:p,mcpHeaders:e.mcpHeaders,physicalDeviceDebugGateway:f,sandboxRuntime:h,simulatorAssets:o,simulatorTargetOrigin:r}),v=()=>{y.close(),b.close()};y.once("close",()=>{process.off("exit",v)}),process.once("exit",v);let E=new URL(g).toString();return n={artifactOrigin:e.artifactOrigin,close:()=>op(),debuggerMcpEndpoint:new URL(iA,g).toString(),getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:p,open:()=>oo(E),origin:g,physicalDeviceDebugGateway:f,sandboxRuntime:h,get sandboxSessionId(){return h.sessionId},server:y,webViewServer:b,closeConnections:_,setRealDeviceDebugProvider(e){f.setProvider(e)},simulatorAssets:o,simulatorTargetOrigin:r,url:E}}catch(e){t?.close(),nA.error("启动 Web SDK 调试器失败",{error:e});return}}async function ou(e,t){let r={errors:[],scenes:[]};if(!e)return r;for(let n of(await tv(e)).sort((e,t)=>e.name.localeCompare(t.name))){let e=await tE(n.path);e&&function(e,t){let r=k(e);return"tool"!==r.type&&("widget"===r.type?t.widgetIds.has(r.id):0===r.unresolvedVariables.length)}(e,t)&&r.scenes.push({content:e,name:n.name})}return r}async function om(e,t){let r=e.metadata.getData(),n=e.widgets,i=await ou(e.appDirectory,{widgetIds:new Set(Object.keys(n).map(e=>rh(n,r.widgets,e)))});return od({...t,debuggerDistPath:t.debuggerDistPath??G(),debugScenes:i,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates})}function oh(e){return!!(e&&!/<%=?\s*appId\s*%>/.test(e))}function of(e){if(!(e instanceof Error))return!1;try{let t=JSON.parse(e.message);return t?.code===0x2fb1799}catch{return!1}}async function og(e){oh(e.appId)&&(await e.getCachedLoginCookie().catch(()=>void 0)||th.warn(e.appId.startsWith("db_")?"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `dbx auth login` 后重新启动开发服务。":"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `npx doubao login` 后重新启动开发服务。"))}let oy=e=>ec.bgHex("#9873b9")(ec.italic(ec.black(` ${e} `))),ob=e=>ec.bgBlueBright(ec.italic(ec.black(` ${e} `))),o_=e=>ec.bold(ec.blueBright(e)),ov=[{command:"d",description:"选择调试场景 / pages / widgets"},{command:"web",description:"打开 Web 模拟器"}],oE={page:"页面",scene:"调试场景",widget:"组件"};function ow(e){console.log(` ${o_(e.command.padEnd(21))} ${ec.gray(`- ${e.description}`)}`)}async function oS(e){let t=Y(e);if(0!==t.length)return await ed.prompt(t.map(([e,t])=>({type:"input",name:e,message:`请输入调试场景变量 "${e}" 的值:`,default:t??void 0})))}async function ox({matchedScene:e,appId:t,driver:r}){let n=await tE(e.path);if(!n)return;let i=await oS(n);await tw({matchedScene:e,appId:t,driver:r,variables:i},n)}async function oA(e,t,r,n,i,s,{interactive:o=!0}={}){if(await i.load({appletUrl:t,appId:e,isSigned:s}),!o)return;let a=await tv(process.cwd()),l=Object.values(r),c=Object.values(n),p=c.filter(({id:e})=>!e8(e));return l.length>0&&(console.log(`
170
+
171
+ ${ob("可用 pages 列表")}
172
+ `),l.forEach(e=>{console.log(` - ${o_(e.path)}`)})),p.length>0&&(console.log(`
173
+ ${ob("可用 widgets 列表")}
174
+ `),p.forEach(e=>{let t=o_(e.id);console.log(` - ${t}`)})),a.length>0&&(console.log(`
175
+ ${ob("可用调试场景")}
176
+ `),a.forEach(e=>console.log(` - ${o_(e.name)}`))),console.log(`
177
+ ${ob("可以继续执行以下命令:")}
178
+ `),ov.forEach(ow),console.log("\n"),nw.instance.addListener(t=>{let r=t.trim();if("d"===r){let t=[...a.map(e=>({type:"scene",id:e.name})),...p.map(e=>({type:"widget",id:e.id})),...l.map(e=>({type:"page",id:e.path}))];if(0===t.length)return console.log(`
179
+ ${ob("暂无可用的页面、组件或调试场景")}`),!0;nx(async()=>{let{selectedEntry:r}=await ed.prompt([{type:"search",name:"selectedEntry",message:"请选择调试目标:",source:e=>t.filter(t=>`${oE[t.type]} ${t.type} ${t.id}`.toLowerCase().includes(e?.toLowerCase()??"")).map(e=>({name:`${ec.gray(oE[e.type])}: ${e.id}`,short:`${oE[e.type]} \xb7 ${e.id}`,value:e}))}]);if("scene"===r.type){let t=a.find(e=>e.name===r.id);t&&await ox({matchedScene:t,appId:e,driver:i})}else"widget"===r.type?i.pushWidget({appId:e,widgetId:r.id}):i.openPageUrl({appId:e,url:r.id})})}else{let t=a.find(e=>e.name===r);t?nx(async()=>{await ox({matchedScene:t,appId:e,driver:i})}):c.some(e=>e.id===r)?i.pushWidget({appId:e,widgetId:r}):i.openPageUrl({appId:e,url:r})}return!0},"openPage")}async function oT({appId:e,appletUrl:t,pages:r,widgets:n,driver:i,isSigned:s,isDisposed:o}){let a=await ta();if(o())return;if(!a)return void th.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");let l=await ts(a).catch(e=>(o()||th.error("重新启动应用失败",{error:e}),!1));if(o())return;if(!l)return void setTimeout(()=>{o()||th.info("请确认应用已经启动。\n")},1e3);if(await new Promise(e=>{setTimeout(e,5e3)}),o())return;if(!i)return void th.error("调试驱动尚未就绪。");let c=await oA(e,t,r,n,i,s);o()&&c?.()}async function oI({context:e,port:t,driver:r,isSigned:n,onCleanupReady:i}){let s,o,{host:a,artifactOrigin:l}=await e.resolveDevServer(t);e.devServerAbort.signal.throwIfAborted();let c=e.metadata.getData(),p=c.app.appId,d=async()=>{let t,r=await (t=e.webDebuggerLaunchOptions,om(e,{appId:e.appId,appDirectory:e.appDirectory,artifactOrigin:l,env:{...e.env,...t?.env??{}},mcpEndpoint:t?.mcpEndpoint??rs(),mcpHeaders:t?.mcpHeaders,simulator:t?.simulator,eventsConfigReader:e.eventsResources?.readJson,eventsConfigSourcePath:e.eventsResources?.sourcePath,toolsConfigReader:e.toolsResources?.readToolsJson,toolsConfigSourcePath:e.toolsResources?.toolsSourcePath,simulatorManifestReader:t?.simulator?.manifestPath?void 0:e.toolsResources?.readManifestYaml,simulatorManifestSourcePath:t?.simulator?.manifestPath?void 0:e.toolsResources?.manifestSourcePath}));await r?.open()};if(e.devServerInteractive){let t;t=function(e={}){let t={name:"Doubao Apps SDK",...e},r=t.name?`${t.name} 开发服务`:"",n=t.origin?`正在监听 ${ec.gray(t.origin)}。`:"已启动。";return`
180
+ ${o_(r)}${n}
181
+ `}(),eb()||console.clear(),console.log(t),console.log(((e,t)=>{if(e&&t){let r=[{title:"\uD83C\uDF10 服务地址",content:t},{title:"\uD83D\uDCE6 应用 ID",content:e}].map(({title:e,titleHighlighter:t,content:r})=>{let n=t?t(e):ec.bold(ec.gray(e));return` - ${ec.bgWhiteBright(ec.italic(ec.black(` ${n} `)))}: ${ec.gray(r.startsWith("http")?ec.underline(r):r)}`}).join("\n");return`
182
+ ${oy("豆包应用服务信息")}:
177
183
 
178
184
  ${r}
179
185
 
180
186
  `}return`
181
- ${al("豆包应用服务信息")}:
187
+ ${oy("豆包应用服务信息")}:
182
188
 
183
- 调试服务未运行。`})(p,s)),await as(e)}let u=(o=!1,a=[],{add(e){e&&(o?e():a.push(e))},cleanup:()=>{o=!0,a.splice(0).forEach(e=>e())},isDisposed:()=>o});if(e.devServerInteractive){let t={context:e,appId:p,appletUrl:s,pages:d.pages,widgets:d.widgets,driver:r,isSigned:n,openWebDebugger:c,isDisposed:u.isDisposed};u.add(nd.instance.addListener(e=>{let r=e.trim().toLowerCase();return("r"===r||"web"===r)&&(process.stdout.write(W(2)),"r"===r?ay(t).catch(np):t.openWebDebugger(),!0)},"devCommands",-1))}i(u.cleanup);try{if(!r){e.devServerInteractive&&tD.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");return}u.add(await ag(p,s,d.pages,d.widgets,r,n,{interactive:e.devServerInteractive}))}catch(e){throw u.cleanup(),e}}let a_=(e,t,r)=>{if(!tm())return void r();let n=process.hrtime.bigint(),i=e.method,o=e.url;t.on("finish",()=>{let e=Number(process.hrtime.bigint()-n)/1e6,r=o?new URL(o,"http://localhost").pathname:"",a=t.statusCode;tD.request({method:i||"UNKNOWN",url:r,statusCode:a,durationMs:e})}),r()},av=new Set(["EACCES","EPERM"]),aw=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"]),aS=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_REQUEST_TIMEOUT"]),aE=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN","EPIPE"]),ax=new Set(["EEXIST","EISDIR","EMFILE","ENOENT","ENOSPC","ENOTDIR","EROFS"]),aA={SyntaxError:"syntax_error",TypeError:"type_error",ModuleNotFoundError:"dependency_error",ModuleBuildError:"compilation_error",ValidationError:"config_error",TimeoutError:"timeout_error",FetchError:"network_error",LoaderError:"loader_error",PluginError:"plugin_error"};function aT(e,t){if(!e||"object"!=typeof e||!(t in e))return;let r=e[t];return"string"==typeof r?r:void 0}function aC(e){if(!e||"object"!=typeof e)return[];if(Array.isArray(e.errors)&&e.errors.length>0)return e.errors;if(Array.isArray(e.stats))return e.stats.flatMap(aC);let t=e.stats&&"object"==typeof e.stats?e.stats:e;try{let e=t.toJson?.({all:!1,errors:!0}).errors;return Array.isArray(e)?e:[]}catch{return[]}}function aI(e){return{scene:void 0,commandStartTime:e,compileStartTime:void 0,builderInitStartTime:void 0,compilePhaseEndTimes:{moduleProcess:void 0,assetProcess:void 0},prepareDurations:{configLoadMs:0,projectScanMs:0,contextBootstrapMs:0,pluginBootstrapMs:0,builderInitMs:0},appInfoDurationMs:0,appInfoMeasured:!1,appTemplateProcessDurationMs:0,viewTemplateProcessDurationMs:0,reported:!1}}function aO(e,t){Object.assign(e,aI(t))}function aP(e,{scene:t,commandStartTime:r,compileStartTime:n}){let i=e.commandStartTime===r,o=e.prepareDurations,a=e.builderInitStartTime,s=e.appInfoDurationMs,l=e.appInfoMeasured;i&&void 0!==a&&(o.builderInitMs=Math.max(0,n-a)),aO(e,r),e.scene=t,e.compileStartTime=n,i&&(e.prepareDurations=o,e.appInfoDurationMs=s,e.appInfoMeasured=l)}function ak(e,t,r){e.compilePhaseEndTimes[t]=Math.max(e.compilePhaseEndTimes[t]??0,r)}function aD(e){return Math.max(0,Math.round(Number.isFinite(e)?e:0))}let a$=new class{uploader;constructor(e){this.uploader=e}async report(e){try{var t,r;let n,i,o,a,s,l,d,p=e.context?.compileLifecycle;if(p){if(p.reported)return;p.reported=!0}let c="dev_initial"===e.scene||"hot_update"===e.scene?"dev":e.scene,u={appDirectory:e.appDirectory,targetAppId:function(e){try{let t=e?.appId;return ao(t)?t:void 0}catch{return}}(e.context),scene:e.scene,command:c},h="failed"===e.status?{...u,status:e.status,errorStage:e.errorStage,error:aC(e.error)[0]??e.error}:{...u,status:e.status,pageCount:Object.keys(e.context.pages).length,widgetCount:Object.keys(e.context.widgets).length,securityMode:(n=e.context.signingEncryptionOptions,i=!!n?.signing.enabled,o=!!n?.encryption.enabled,i&&o?"signing_and_encryption":i?"signing":o?"encryption":"none"),durations:(t=e.context.compileLifecycle,r=e.compileEndTime,a=t.commandStartTime??r,s=t.compileStartTime??r,l=Math.min(r,Math.max(s,t.compilePhaseEndTimes.moduleProcess??r)),d=Math.min(r,Math.max(l,t.compilePhaseEndTimes.assetProcess??r)),{totalMs:r-a,prepareMs:s-a,compileMs:r-s,...t.prepareDurations,appInfoMs:t.appInfoDurationMs,appTemplateProcessMs:t.appTemplateProcessDurationMs,viewTemplateProcessMs:t.viewTemplateProcessDurationMs,moduleProcessMs:l-s,assetProcessMs:d-l,outputWriteMs:r-d})};await this.upload(h)}catch{}}async flush(e=3e3){try{await this.uploader?.flush?.(e)}catch{}}async upload(e){let{appDirectory:t,...r}=e;await (this.uploader??=new ec).upload(function(e,t){let r={kit_compile_id:function(){let e="unknown";try{e=(0,rI.userInfo)().username||e}catch{}return`${Date.now()}_${e}_${(0,ib.randomUUID)()}`}(),kit_compile_scene:e.scene,kit_command:e.command,kit_status:e.status,kit_version:t.kitVersion,kit_node_version:process.version,kit_os_name:process.platform,kit_run_env:t.runEnv.toLowerCase()};if(e.targetAppId&&(r.kit_appId=e.targetAppId),"success"===e.status)r.kit_page_count=e.pageCount,r.kit_widget_count=e.widgetCount,r.kit_security_mode=e.securityMode,r.kit_duration_ms_total=aD(e.durations.totalMs),r.kit_prepare_ms=aD(e.durations.prepareMs),r.kit_compile_ms=aD(e.durations.compileMs),r.kit_config_load_ms=aD(e.durations.configLoadMs),r.kit_project_scan_ms=aD(e.durations.projectScanMs),r.kit_context_bootstrap_ms=aD(e.durations.contextBootstrapMs),r.kit_app_info_ms=aD(e.durations.appInfoMs),r.kit_app_template_process_ms=aD(e.durations.appTemplateProcessMs),r.kit_view_template_process_ms=aD(e.durations.viewTemplateProcessMs),r.kit_plugin_bootstrap_ms=aD(e.durations.pluginBootstrapMs),r.kit_builder_init_ms=aD(e.durations.builderInitMs),r.kit_module_process_ms=aD(e.durations.moduleProcessMs),r.kit_asset_process_ms=aD(e.durations.assetProcessMs),r.kit_output_write_ms=aD(e.durations.outputWriteMs);else{r.kit_error_type=function(e){let t=aT(e,"code")?.toUpperCase();if(t){if(av.has(t))return"permission_error";if(aw.has(t))return"dependency_error";if(aS.has(t))return"timeout_error";if(aE.has(t))return"network_error";if(ax.has(t))return"filesystem_error"}let r="string"==typeof e?e:aT(e,"message")??"";if(/cannot find module|can't resolve|cannot resolve|module not found|package .+ not found/i.test(r))return"dependency_error";if(/permission denied|operation not permitted/i.test(r))return"permission_error";if(/timed out|timeout/i.test(r))return"timeout_error";if(/connection (?:refused|reset)|getaddrinfo|network error|socket hang up|unable to connect/i.test(r))return"network_error";if(/no such file|file does not exist|not a directory|directory does not exist/i.test(r))return"filesystem_error";if(/syntax\s*error|syntaxerror|unexpected token|failed to parse|pars(?:e|ing) error/i.test(r))return"syntax_error";if(/\bTS\d{4}:|\btype\s*error\b|\btypeerror\b/i.test(r))return"type_error";if(/appId is required|entry config|invalid config|configuration (?:is )?(?:invalid|missing)/i.test(r))return"config_error";if(/loader/i.test(r))return"loader_error";if(/plugin/i.test(r))return"plugin_error";let n=aT(e,"name");return n&&aA[n]||"unknown_error"}(e.error),e.errorStage&&(r.kit_error_stage=e.errorStage);let i=function(e){if("string"==typeof e)return e;if(!e||"object"!=typeof e||!("message"in e))return;let t=e.message;return"string"==typeof t?t:void 0}(e.error);if(i){var n;let e=(n=t.appDirectory,(0,iU.stripVTControlCharacters)(i).replaceAll(ta.resolve(n),"<project>").replaceAll((0,rI.homedir)(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));e&&(r.kit_error_message=e)}}return{name:"kit_compile",params:r}}(r,{appDirectory:t,kitVersion:"0.3.0-rc.3",runEnv:process.env.BUILD_VERSION?"SCM":process.env.CI_REPO_NAME?"CI":"LOCAL"}))}};function aR(e,t,r){r?.hasErrors()?a$.report({appDirectory:e.appDirectory,context:e,scene:t,status:"failed",errorStage:"compile",error:aC(r)[0]}):a$.report({appDirectory:e.appDirectory,context:e,scene:t,status:"success",compileEndTime:Date.now()})}let aN=f("crypto");class aL{constructor(e,t,r){this._content=t,this._hashCode=r,this.source=e}get content(){return this._content}get hashCode(){var e;return this._hashCode||(e=this.content,aN.createHash("sha256").update("string"==typeof e?e:new DataView(e.buffer,e.byteOffset,e.byteLength)).digest("hex").substring(0,8))}}class aM extends aL{constructor(e,t){super(e,t),this._manifest={applet:{pages:[],tools:[]},widgets:[]};try{this._manifest=j(this._manifest,JSON.parse(t))}catch(e){}this.destination=e}get manifest(){return this._manifest}get content(){return JSON.stringify({manifestVersion:this._manifest.manifestVersion,packageName:this._manifest.packageName,appId:this._manifest.appId,scmVersion:this._manifest.scmVersion,versionName:this._manifest.versionName,versionTag:this._manifest.versionTag,versionCode:this._manifest.versionCode,runtimeVersion:this._manifest.runtimeVersion,sourceType:this._manifest.sourceType,permissions:this._manifest.permissions,settings:this._manifest.settings,applet:this._manifest.applet,widgets:this._manifest.widgets},null,2)}setManifestVersion(e){this._manifest.manifestVersion=e}setRuntimeVersion(e){this._manifest.runtimeVersion=e}setPackageName(e){this._manifest.packageName=e}setVersionName(e){this._manifest.versionName=e}assignBasicManifest(e){Object.assign(this._manifest,e)}mergeBasicManifest(e){j(this._manifest,e)}setSCMVersion(e){this._manifest.scmVersion=e}setVersionCode(e){this._manifest.versionCode=e}setAppletManifest(e){this._manifest.applet=e}mergeAppletManifest(e){j(this._manifest.applet,e)}setRenderType(e=en.REACT_LYNX){this._manifest.renderType=e}appendWidget(e){this._manifest.widgets||(this._manifest.widgets=[]),this._manifest.widgets.push(e)}appendPage(e){this._manifest.applet.pages||(this._manifest.applet.pages=[]),this._manifest.applet.pages.push(e)}toString(){return JSON.stringify(this._manifest,null,2)}}class aj{constructor(){this.assets={}}addAsset(e,t){this.assets[e]=t}deleteAsset(e){delete this.assets[e]}getAsset(e){return this.assets[e]}getAssets(){return this.assets}getManifestAsset(e){return this.getAsset(e)||(this.assets[e]=new aM(e,JSON.stringify({}))),this.getAsset(e)}}class aU{options;constructor(e){this.options=e}apply(e){let t,{pluginSystem:r}=this.options;e.hooks.thisCompilation.tap({name:aU.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},n=>{n.hooks.processAssets.tapPromise({name:aU.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{t=new aj,n.getAssets().forEach(e=>{let r=new aL(e.name,e.source.source(),e.info.contenthash?.[0]);t.addAsset(e.name,r)});let{entrypoints:i}=n,o={};i.forEach((e,r)=>{o[r]=e.getFiles().map(e=>{let r=t.getAsset(e);if(!r)throw Error(`Asset ${e} not found`);return new aL(r.source,r.content,r.hashCode)})});let a=this.options.context.appId;a&&to.mkdirSync(ta.join(this.options.context.rootPath,a),{recursive:!0}),await r.callAssetsHooks("beforeEmit",{assets:t,chunks:o}),Object.keys(t.getAssets()).forEach(r=>{let i=t.getAsset(r);if(!i)return;let{source:o,destination:a}=i;if(!o||!a)return;n.getAsset(o)?n.renameAsset(o,a):n.emitAsset(a,new e.rspack.sources.RawSource(i.content));let s=n.getAsset(`${o}.map`);s&&n.renameAsset(s.name,`${a}.map`)}),await r.callAssetsHooks("afterEmit",{assets:{...t.getAssets()}})})})}}let aB=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class aF{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(aF.name,e=>{e.hooks.finishModules.tap(aF.name,()=>{let t=new Map,r=n=>{if(!n)return!1;let i=t.get(n);if(void 0!==i)return i;if(function(e){var t;let r=e.resourceResolveData?.descriptionFileData?.name;if("string"==typeof r&&aB.has(r))return!0;let n=(t=e.resource,t?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...aB].some(e=>n?.includes(`/node_modules/${e}/`))}(n))return t.set(n,!0),!0;for(let i of(t.set(n,!1),e.moduleGraph.getOutgoingConnections(n)))if(r(i.module))return t.set(n,!0),!0;return!1};e.entries.forEach((t,n)=>{t.dependencies.some(t=>r(e.moduleGraph.getModule(t)))&&this.options.markTemplateWidgetEntry(this.options.normalizeEntryName?.(n)??n)})})})}}class aW{options;constructor(e){this.options=e}apply(e){e.hooks.make.tapPromise(aW.name,async()=>{await this.options.pluginSystem.callViewHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(aW.name,e=>{e.hooks.optimizeTree.tapPromise(aW.name,async t=>{await this.options.pluginSystem.callViewHooks("build",{metadata:this.options.context.metadata,fileDependencies:e.fileDependencies})})}),e.hooks.done.tapPromise(aW.name,async e=>{await this.options.pluginSystem.callViewHooks("afterBuild",{stats:e})})}}function aH(e){return e.replaceAll("\\","/")}function aV(e,t,r,n=`${t}.map`){return t!==r&&!!e.getAsset(t)&&(e.renameAsset(t,r),e.getAsset(n)&&e.renameAsset(n,`${r}.map`),!0)}class aG{context;constructor(e){this.context=e}apply(e){e.hooks.thisCompilation.tap(aG.name,t=>{t.hooks.processAssets.tapPromise({name:aG.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{var e,r;let n=this.context.metadata.getData(),i=this.context.command===ej.DEV?"all":"configured",o=rS(this.context.pages,this.context.normalizedAppConfig.pages.entries,i),a=rS(this.context.widgets,this.context.normalizedAppConfig.widgets.entries,i),s=n.app.appId||this.context.appId;if(!s&&Object.keys(o).length>0)throw Error("appId is required to resolve Web page entry paths");s&&(e=n.pages,Object.keys(o).forEach(r=>{let n=aH(r),i=r_(n);aV(t,`${i}/template.js`,rn(s,e[r]?.path??rr(n),rg),`${i}/background.js.map`)})),r=n.widgets,Object.keys(a).forEach(e=>{var n;let i=r_(aH(e));aV(t,`${i}/template.js`,(n=rv(a,r,e),`${n}/${rg}`),`${i}/background.js.map`)})})})}}class aq{entry;constructor(e){this.entry=e}apply(e){let t=new e.webpack.experiments.VirtualModulesPlugin;t.apply(e),e.hooks.thisCompilation.tap(aq.name,()=>{t.writeModule(eQ,""),t.writeModule(e0,e1),Object.values(this.entry).forEach(e=>{t.writeModule(e.filename,e.toString())})})}}function aJ(e,t){return e.isIdentifier(t)?t.text:e.isPropertyAccessExpression(t)?t.name.text:void 0}let aK={templatesByEntry:{},templatesByWidget:{}},az="/doubao-apps-framework.template.js",aY="/doubao-apps-api.template.js",aX=(e,t)=>{let r=(e,r,n)=>({libraryName:n,url:t?`/wsd${e}`:e,background:{sectionPath:r},mainThread:{sectionPath:`${r}__main-thread`},async:!!t});return{"@byted-doubao-apps/bridge-base":r(aY,"api"),"@byted-doubao-apps/open-api":r(aY,"api"),...Object.fromEntries(Object.entries(e7).map(([t,n])=>[t,r(e?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",n])])),[`${ts}/api`]:r(aY,"api"),[`${tl}/api`]:r(aY,"api"),[ts]:r(az,"framework"),[tl]:r(az,"framework"),"@byted-doubao-apps/components":r(az,"components"),[tp(ts)]:r(az,"components"),[tp(tl)]:r(az,"components")}},aZ=f("node:url"),aQ=(0,A.createRequire)(import.meta.url);function a0(e,t){for(let r of e)try{return aQ.resolve(r,{paths:t})}catch{}throw Error(`Cannot resolve package from candidates: ${e.join(", ")}`)}class a1{pluginSystem;constructor(e){this.pluginSystem=e}async createEntry(){let{entry:e}=await this.pluginSystem.callViewHooks("modifyEntryOption",{entry:{}});return e}async createConfig({config:e}){var t,r,n,i,o;let{appDirectory:a,command:d,metadata:m,rootPath:f}=e.context,g=e.context.environment,y="1"===process.env.ENABLE_SELF_CONTAINED;await this.pluginSystem.callViewHooks("modifyEnvironment",{environment:g}),e.context.setEnvironment(g);let b=d===ej.DEV,_=await this.createEntry(),v=tu(a),w=[a,ta.dirname((0,aZ.fileURLToPath)(import.meta.url))],S=aQ.resolve("@lynx-js/react/transform"),E=b?"all":"configured",x=rS(e.context.pages,e.context.normalizedAppConfig.pages.entries,E),T=new Set([...Object.keys(rS(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,E)),...Object.keys(x)]),C=T.size>0;C&&await nr({widgets:e.context.widgets,pages:e.context.pages,entries:_,collector:m,normalizedAppConfig:e.context.normalizedAppConfig,define:e.context.userConfig?.source?.define});let I={include:e.options.source?.include,exclude:e.options.source?.exclude,decorators:e.options.source?.decorators,define:{...e.options.source?.define,__DOUBAO__:JSON.stringify(!0),__MAIN_PROCESS__:JSON.stringify(!1),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__VERSION_TAG__:JSON.stringify(e.context.versionTag)??"undefined",__LEPUS__:JSON.stringify(!1),"process.env":"({})"}},O=e=>[eQ,e0,e.filename],P={...I,entry:Object.fromEntries(Object.entries(_).map(([e,t])=>[e,O(t)]))},k=Object.fromEntries(Object.entries(_).filter(([e])=>T.has(e))),D=new Map(Object.keys(k).map(e=>[r_(e),e])),$={...P,entry:Object.fromEntries(Object.entries(k).map(([e,t])=>[r_(e),O(t)])),define:{...P.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},N=[...tf()?[]:[V({externals:aX(b),globalObject:"lynx"})]],L=[function({metadata:e,resolveAppInfo:t}){return{name:"ai-manifest-plugin",setup(r){r.modifyBundlerChain((r,n)=>{let i=n?.environment?.name==="web"?rm:rh;r.plugin(rf.name).use(rf,[{metadata:e,resolveAppInfo:t,shouldInjectAsset:i}])})}}}({metadata:m,resolveAppInfo:()=>e.context.resolveAppInfo()})],M={source:P,plugins:N},j=[function e({metadata:t,entry:r,resolveSigningEncryptionOptions:n,onProcessDuration:i}){return{name:e.name,setup(e){e.modifyBundlerChain((o,a)=>{if(a?.environment?.name==="web")return;let s=e.useExposed(Symbol.for("LynxTemplatePlugin"));o.plugin(nl.name).use(nl,[s.LynxTemplatePlugin,t,r,n,i])})}}}({metadata:m,entry:_,resolveSigningEncryptionOptions:()=>e.context.resolveSigningEncryptionOptions(),onProcessDuration:t=>{e.context.compileLifecycle.viewTemplateProcessDurationMs=Math.max(e.context.compileLifecycle.viewTemplateProcessDurationMs,t)}}),function({context:e,normalizeEntryName:t}){return{name:"template-widget-entry-plugin",setup(r){r.modifyBundlerChain((r,n)=>{let i=n?.environment?.name;r.plugin("template-widget-entry-plugin").use(aF,[{markTemplateWidgetEntry:t=>{e.addTemplateWidgetEntry(t)},normalizeEntryName:e=>t?.(e,i)}])})}}}({context:e.context,normalizeEntryName:(e,t)=>"web"===t?D.get(e):e}),(t=this.pluginSystem,r=e.context,{name:"output-plugin",setup(e){let n={pluginSystem:t,context:r};e.modifyBundlerChain((e,t)=>{t?.environment?.name!=="web"&&e.plugin("output-plugin").use(aU,[n])})}}),...d===ej.DEV&&C?[function({context:e}){let t;return e.getWidgetViewDataTemplates=async()=>{if(t)return t;try{t=function(e,t,r){let n=function(e){let t,r=(0,A.createRequire)(ta.join(e,"package.json"));try{t=r.resolve("typescript")}catch(e){return}return r(t)}(e);if(!n)return{templatesByEntry:{},templatesByWidget:{}};let i=[...new Set(Object.values(t).map(({filename:e})=>e))],o=n.createProgram({options:function(e,t){let r={allowJs:!0,checkJs:!1,jsx:e.JsxEmit.Preserve,noEmit:!0,skipLibCheck:!0,target:e.ScriptTarget.ESNext},n=e.findConfigFile(t,to.existsSync);if(!n)return r;let i=e.readConfigFile(n,e.sys.readFile);return i.error?r:{...e.parseJsonConfigFileContent(i.config,e.sys,ta.dirname(n)).options,...r}}(n,e),rootNames:i}),a=o.getTypeChecker(),s=Object.fromEntries(Object.entries(t).map(([e,{filename:t}])=>{let r,i=o.getSourceFile(t);return[Y(e),i?(r={},!function e(t){if(n.isCallExpression(t)&&("getViewData"===aJ(n,t.expression)||"useViewData"===aJ(n,t.expression))&&t.typeArguments?.[0]){let e=a.getTypeFromTypeNode(t.typeArguments[0]);for(let i of a.getPropertiesOfType(e)){let o=i.valueDeclaration??i.declarations?.[0]??t;r[i.getName()]=function e(t,r,n,i,o){let a=(r.isUnion()?r.types:[r]).filter(e=>!(e.flags&(t.TypeFlags.Undefined|t.TypeFlags.Never)));if(a.some(e=>e.flags&t.TypeFlags.Null))return null;if(a.some(e=>e.flags&t.TypeFlags.StringLike))return"";if(a.some(e=>e.flags&(t.TypeFlags.NumberLike|t.TypeFlags.BigIntLike)))return 0;if(a.some(e=>e.flags&t.TypeFlags.BooleanLike))return!1;if(a.some(e=>n.isArrayType(e)||n.isTupleType(e)))return[];let s=a.find(e=>e.flags&t.TypeFlags.Object);if(!s||o.has(s))return{};o.add(s);let l=Object.fromEntries(n.getPropertiesOfType(s).map(r=>{let a=r.valueDeclaration??r.declarations?.[0]??i;return[r.getName(),e(t,n.getTypeOfSymbolAtLocation(r,a),n,a,o)]}));return o.delete(s),l}(n,a.getTypeOfSymbolAtLocation(i,o),a,o,new Set([e]))}}n.forEachChild(t,e)}(i),r):{}]})),l=Object.fromEntries(Object.keys(t).map(e=>{let n=Y(e);return[rv(t,r,e),s[n]??{}]}));return{templatesByEntry:s,templatesByWidget:l}}(e.appDirectory,e.widgets,e.metadata.getData().widgets)}catch{t=aK}return t},{name:"WidgetViewDataPlugin",setup(e){e.onAfterDevCompile(({stats:e})=>{e.hasErrors()||(t=void 0)})}}}({context:e.context})]:[],(({context:e})=>({name:"DevServerLogPlugin",setup(t){let r,n=!1,i=!1;t.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{setup({server:e}){e.middlewares.use(a_)}}})),t.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.failed.tap("DevServerLogPlugin",t=>e.finishInitialDevCompile(t))}),t.onAfterDevCompile(async({stats:o})=>{if(o.hasErrors())return void e.finishInitialDevCompile(Error(o.toString({all:!1,errors:!0,colors:!1})));if(n)return;let{devServer:a}=t.context;if(!a)return;n=!0;let s=await tN({debugDriver:e.userConfig.debugDriver,skipAdbForegroundAppWatch:e.userConfig.skipAdbForegroundAppWatch}).catch(np);i||(e.finishInitialDevCompile(),ab({context:e,port:a.port,driver:s,isSigned:e.isSignedEncryption,onCleanupReady(e){i?e():r=e}}).catch(e=>{i||tD.error("Failed to initialize dev server actions",{error:e})}))}),t.onCloseDevServer(()=>{i=!0,e.devServerAbort.abort(),r?.(),r=void 0})}}))({context:e.context}),function({context:e}){let t="KitMonitorPlugin";return{name:t,setup(r){if(r.onAfterCreateCompiler(({compiler:r})=>{for(let n of"compilers"in r?r.compilers:[r])n.hooks.finishMake.tap(t,()=>{ak(e.compileLifecycle,"moduleProcess",Date.now())}),n.hooks.emit.tap(t,()=>{ak(e.compileLifecycle,"assetProcess",Date.now())}),n.hooks.failed.tap(t,t=>{a$.report({appDirectory:e.appDirectory,context:e,scene:e.compileLifecycle.scene??(e.command===ej.DEV?"dev_initial":e.command),status:"failed",errorStage:"compile",error:t})})}),e.command!==ej.DEV){let t=e.command;r.onBeforeBuild(()=>{let r=Date.now();aP(e.compileLifecycle,{scene:t,commandStartTime:e.compileLifecycle.commandStartTime??r,compileStartTime:r})}),r.onAfterBuild(({stats:r})=>{aR(e,t,r)})}else r.onBeforeDevCompile(({isFirstCompile:t})=>{let r=Date.now();aP(e.compileLifecycle,{scene:t?"dev_initial":"hot_update",commandStartTime:t?e.compileLifecycle.commandStartTime??r:r,compileStartTime:r})}),r.onAfterDevCompile(({stats:t})=>{aR(e,e.compileLifecycle.scene??"dev_initial",t)})}}}({context:e.context}),..."true"===process.env.BYTED_RSDOCTOR?[{name:"doubao-apps:byted-rsdoctor",setup(e){e.onBeforeCreateCompiler(({bundlerConfigs:e})=>{let{BytedRsdoctorPlugin:t}=aQ(a0(["@byted/rsdoctor"],w));for(let r of e){let e=ta.join(r.output?.path??"",`.rsdoctor-${r.name}`);r.plugins??=[],r.plugins.push(new t({disableClientServer:!0,supports:{banner:!0},output:{reportDir:e}}))}})}}]:[],(n=this.pluginSystem,i=e.context,{name:"view-hooks-plugin",setup(e){e.modifyBundlerChain((e,t)=>{t?.environment?.name==="web"||e.plugin("view-hooks-plugin").use(aW,[{pluginSystem:n,context:i}])})}}),(({getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:o})=>({name:"lynx:encode-worker",async setup(a){tg()||a.modifyBundlerChain((a,s)=>{s?.environment?.name!=="web"&&a.plugin(ns.name).use(ns,[{getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:o}]).end()})}}))({getAppAssetPath:()=>e.context.appAssetPath,getAppMapAssetPath:()=>e.context.appMapAssetPath,metadata:e.context.metadata,resolveSigningEncryptionOptions:()=>e.context.resolveSigningEncryptionOptions(),onProcessDuration:t=>{e.context.compileLifecycle.appTemplateProcessDurationMs+=t}}),...e.rsbuildPlugins||[]],U=[{name:"web-virtual-entry-plugin",setup(e){e.modifyBundlerChain((e,{environment:t})=>{"web"===t.name&&e.plugin(aq.name).use(aq,[k])})}},(o=e.context,{name:"web-output-plugin",setup(e){e.modifyBundlerChain({order:"post",handler(e,{environment:t}){if("web"===t.name){let t=".rspeedy/";for(let r of Object.keys(e.plugins.entries()??{}))r.startsWith("lynx:template-")&&e.plugin(r).tap(e=>{let r=e[0];return r?.intermediate?.startsWith(t)&&(r.intermediate=r.intermediate.slice(t.length)),e});e.plugins.has("lynx:sourcemap")&&e.plugin("lynx:sourcemap").tap(e=>{var t;let r,n=e[0];return n.ignoreList=[/^(?!file:\/\/\/)/,/\/(?:externals-loading-runtime|webpack\/runtime)(?:\/|$)/,/\/node_modules\//,/\.(?:css|less|sass|scss)(?:[?#]|$)/],t=o.appDirectory,r=ta.resolve(t),n.moduleFilenameTemplate=({absoluteResourcePath:e,query:t=""})=>{let n=ta.relative(r,e),i=".."!==n&&!n.startsWith(`..${ta.sep}`)&&!ta.isAbsolute(n),o=i?aH(n):aH(e).replace(/^\/+/,"");return`${i?"file":"webpack"}:///${o}${t}`},e}),e.plugin(aG.name).use(aG,[o])}}})}})],B=p({mode:d===ej.DEV?"development":"production",environments:C?{lynx:M,web:{source:$,output:{distPath:{css:"",js:"base/web-common"},cleanDistPath:!1,filename:{assets:"[name]/web.bundle"},sourceMap:{js:!!b&&"cheap-module-source-map",css:!1}},plugins:[V({externals:aX(d===ej.DEV,!0),globalObject:"lynx"})]}}:{lynx:M},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(e,t,r=ta.join(ta.dirname((0,aZ.fileURLToPath)(import.meta.url)),"components-loader.js"),n=a0){try{return n(t===tl?["@doubao-dev/kit/components-loader","@byted-doubao-apps/kit/components-loader"]:["@byted-doubao-apps/kit/components-loader","@doubao-dev/kit/components-loader"],e)}catch(e){if((0,to.existsSync)(r))return r;throw e}}(w,v),options:{frameworkPackage:v}}]},plugins:[new c.BannerPlugin({banner:'"use registerWorkletInternal";',raw:!0,entryOnly:!0,stage:c.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE+1,test:/\.js$/})]}},source:{...I,entry:{}},server:{cors:!0,host:e.context.devServerHost},dev:{writeToDisk:tm(),hmr:d===ej.DEV},output:{distPath:{js:"base/common",root:f||"dist"},cleanDistPath:!1,filename:{bundle:"[name]/template.js"},dataUriLimit:5120},resolve:{alias:{...e.options.resolve?.alias||{}}},performance:{printFileSize:tm(),...tf()&&!y?{chunkSplit:{strategy:"split-by-experience"}}:{}},...y?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(e){R({LAYERS:s,lazy:!1,rootPath:ta.dirname((0,aZ.fileURLToPath)(import.meta.url))}).setup(e)}},{name:"set-server.printUrls-false",setup(e){e.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{printUrls:!1}}))}},l({compat:{componentsPkg:[],newRuntimePkg:v,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...td]}}),{name:"pin-react-transform-path",pre:["lynx:react"],setup(e){e.modifyBundlerChain((e,{CHAIN_ID:t})=>{let r=e.module.rule(t.RULE.JS).oneOf(t.ONE_OF.JS_MAIN);for(let e of[s.BACKGROUND,s.MAIN_THREAD]){let t=r.oneOfs.get(e)?.uses.get(e);if(!t)throw Error(`React transform loader not found for layer: ${e}`);t.tap(e=>({...e,transformPath:S}))}})}},function(e){let{compilerOptionsKeys:t=rP.compilerOptionsKeys,configKeys:r=rP.configKeys,validate:n=rZ,dslPluginName2PkgName:i=rQ,upgradeRspeedyLink:o="https://www.npmjs.com/package/upgrade-rspeedy"}=(void 0)??{};return n(e),{name:"lynx:config",async setup(n){n.expose(Symbol.for("lynx.config"),{config:e}),n.modifyBundlerChain(a=>{let s=n.useExposed(Symbol.for("LynxTemplatePlugin"));if(!s){let e="Rspeedy and plugins";throw Object.entries(i).forEach(([t,r])=>{n.isPluginExists(t)&&(e=r)}),Error(`\
184
- [pluginLynxConfig] No \`LynxTemplatePlugin\` exposed to ${rH("the plugin API","https://rsbuild.rs/plugins/dev/core#apiexpose")}.
189
+ 调试服务未运行。`})(p,a)),await og(e)}let u=(s=!1,o=[],{add(e){e&&(s?e():o.push(e))},cleanup:()=>{s=!0,o.splice(0).forEach(e=>e())},isDisposed:()=>s});if(e.devServerInteractive){let t={context:e,appId:p,appletUrl:a,pages:c.pages,widgets:c.widgets,driver:r,isSigned:n,openWebDebugger:d,isDisposed:u.isDisposed};u.add(nw.instance.addListener(e=>{let r=e.trim().toLowerCase();return("r"===r||"web"===r)&&(process.stdout.write(V(2)),"r"===r?oT(t).catch(nS):t.openWebDebugger(),!0)},"devCommands",-1))}i(u.cleanup);try{if(!r){e.devServerInteractive&&th.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");return}u.add(await oA(p,a,c.pages,c.widgets,r,n,{interactive:e.devServerInteractive}))}catch(e){throw u.cleanup(),e}}let oO=(e,t,r)=>{if(!eb())return void r();let n=process.hrtime.bigint(),i=e.method,s=e.url;t.on("finish",()=>{let e=Number(process.hrtime.bigint()-n)/1e6,r=s?new URL(s,"http://localhost").pathname:"",o=t.statusCode;th.request({method:i||"UNKNOWN",url:r,statusCode:o,durationMs:e})}),r()},oP=new Set(["EACCES","EPERM"]),oC=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"]),oR=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_REQUEST_TIMEOUT"]),o$=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN","EPIPE"]),ok=new Set(["EEXIST","EISDIR","EMFILE","ENOENT","ENOSPC","ENOTDIR","EROFS"]),oN={SyntaxError:"syntax_error",TypeError:"type_error",ModuleNotFoundError:"dependency_error",ModuleBuildError:"compilation_error",ValidationError:"config_error",TimeoutError:"timeout_error",FetchError:"network_error",LoaderError:"loader_error",PluginError:"plugin_error"};function oL(e,t){if(!e||"object"!=typeof e||!(t in e))return;let r=e[t];return"string"==typeof r?r:void 0}function oD(e){if(!e||"object"!=typeof e)return[];if(Array.isArray(e.errors)&&e.errors.length>0)return e.errors;if(Array.isArray(e.stats))return e.stats.flatMap(oD);let t=e.stats&&"object"==typeof e.stats?e.stats:e;try{let e=t.toJson?.({all:!1,errors:!0}).errors;return Array.isArray(e)?e:[]}catch{return[]}}function oj(e){return{scene:void 0,commandStartTime:e,compileStartTime:void 0,builderInitStartTime:void 0,compilePhaseEndTimes:{moduleProcess:void 0,assetProcess:void 0},prepareDurations:{configLoadMs:0,projectScanMs:0,contextBootstrapMs:0,pluginBootstrapMs:0,builderInitMs:0},appInfoDurationMs:0,appInfoMeasured:!1,appTemplateProcessDurationMs:0,viewTemplateProcessDurationMs:0,reported:!1}}function oM(e,t){Object.assign(e,oj(t))}function oU(e,{scene:t,commandStartTime:r,compileStartTime:n}){let i=e.commandStartTime===r,s=e.prepareDurations,o=e.builderInitStartTime,a=e.appInfoDurationMs,l=e.appInfoMeasured;i&&void 0!==o&&(s.builderInitMs=Math.max(0,n-o)),oM(e,r),e.scene=t,e.compileStartTime=n,i&&(e.prepareDurations=s,e.appInfoDurationMs=a,e.appInfoMeasured=l)}function oB(e,t,r){e.compilePhaseEndTimes[t]=Math.max(e.compilePhaseEndTimes[t]??0,r)}function oF(e){return Math.max(0,Math.round(Number.isFinite(e)?e:0))}let oH=new class{uploader;constructor(e){this.uploader=e}async reportEvent(e){try{await (this.uploader??=new ep).upload({name:e.name,params:{...e.params,kit_version:"0.5.0-rc.3",kit_node_version:process.version,kit_os_name:process.platform,kit_run_env:(process.env.BUILD_VERSION?"SCM":process.env.CI_REPO_NAME?"CI":"LOCAL").toLowerCase()}})}catch{}}async report(e){try{var t,r;let n,i,s,o,a,l,c,p=e.context?.compileLifecycle;if(p){if(p.reported)return;p.reported=!0}let d="dev_initial"===e.scene||"hot_update"===e.scene?"dev":e.scene,u={appDirectory:e.appDirectory,targetAppId:function(e){try{let t=e?.appId;return oh(t)?t:void 0}catch{return}}(e.context),scene:e.scene,command:d},m="failed"===e.status?{...u,status:e.status,errorStage:e.errorStage,error:oD(e.error)[0]??e.error}:{...u,status:e.status,pageCount:Object.keys(e.context.pages).length,widgetCount:Object.keys(e.context.widgets).length,securityMode:(n=e.context.signingEncryptionOptions,i=!!n?.signing.enabled,s=!!n?.encryption.enabled,i&&s?"signing_and_encryption":i?"signing":s?"encryption":"none"),durations:(t=e.context.compileLifecycle,r=e.compileEndTime,o=t.commandStartTime??r,a=t.compileStartTime??r,l=Math.min(r,Math.max(a,t.compilePhaseEndTimes.moduleProcess??r)),c=Math.min(r,Math.max(l,t.compilePhaseEndTimes.assetProcess??r)),{totalMs:r-o,prepareMs:a-o,compileMs:r-a,...t.prepareDurations,appInfoMs:t.appInfoDurationMs,appTemplateProcessMs:t.appTemplateProcessDurationMs,viewTemplateProcessMs:t.viewTemplateProcessDurationMs,moduleProcessMs:l-a,assetProcessMs:c-l,outputWriteMs:r-c})};await this.upload(m)}catch{}}async flush(e=3e3){try{await this.uploader?.flush?.(e)}catch{}}async upload(e){let{appDirectory:t,...r}=e;await this.reportEvent(function(e,t){let r={kit_compile_id:function(){let e="unknown";try{e=(0,rw.userInfo)().username||e}catch{}return`${Date.now()}_${e}_${(0,iR.randomUUID)()}`}(),kit_compile_scene:e.scene,kit_command:e.command,kit_status:e.status};if(e.targetAppId&&(r.kit_appId=e.targetAppId),"success"===e.status)r.kit_page_count=e.pageCount,r.kit_widget_count=e.widgetCount,r.kit_security_mode=e.securityMode,r.kit_duration_ms_total=oF(e.durations.totalMs),r.kit_prepare_ms=oF(e.durations.prepareMs),r.kit_compile_ms=oF(e.durations.compileMs),r.kit_config_load_ms=oF(e.durations.configLoadMs),r.kit_project_scan_ms=oF(e.durations.projectScanMs),r.kit_context_bootstrap_ms=oF(e.durations.contextBootstrapMs),r.kit_app_info_ms=oF(e.durations.appInfoMs),r.kit_app_template_process_ms=oF(e.durations.appTemplateProcessMs),r.kit_view_template_process_ms=oF(e.durations.viewTemplateProcessMs),r.kit_plugin_bootstrap_ms=oF(e.durations.pluginBootstrapMs),r.kit_builder_init_ms=oF(e.durations.builderInitMs),r.kit_module_process_ms=oF(e.durations.moduleProcessMs),r.kit_asset_process_ms=oF(e.durations.assetProcessMs),r.kit_output_write_ms=oF(e.durations.outputWriteMs);else{r.kit_error_type=function(e){let t=oL(e,"code")?.toUpperCase();if(t){if(oP.has(t))return"permission_error";if(oC.has(t))return"dependency_error";if(oR.has(t))return"timeout_error";if(o$.has(t))return"network_error";if(ok.has(t))return"filesystem_error"}let r="string"==typeof e?e:oL(e,"message")??"";if(/cannot find module|can't resolve|cannot resolve|module not found|package .+ not found|无法解析以下候选包/i.test(r))return"dependency_error";if(/permission denied|operation not permitted/i.test(r))return"permission_error";if(/timed out|timeout/i.test(r))return"timeout_error";if(/connection (?:refused|reset)|getaddrinfo|network error|socket hang up|unable to connect/i.test(r))return"network_error";if(/no such file|file does not exist|not a directory|directory does not exist|配置的入口文件不存在/i.test(r))return"filesystem_error";if(/syntax\s*error|syntaxerror|unexpected token|failed to parse|pars(?:e|ing) error|解析 (?:tools\.json|manifest\.yaml) 失败/i.test(r))return"syntax_error";if(/\bTS\d{4}:|\btype\s*error\b|\btypeerror\b/i.test(r))return"type_error";if(/appId is required|entry config|invalid config|configuration (?:is )?(?:invalid|missing)|入口配置|(?:需要|提供) appId/i.test(r))return"config_error";if(/loader|加载器/i.test(r))return"loader_error";if(/plugin/i.test(r))return"plugin_error";let n=oL(e,"name");return n&&oN[n]||"unknown_error"}(e.error),e.errorStage&&(r.kit_error_stage=e.errorStage);let i=function(e){if("string"==typeof e)return e;if(!e||"object"!=typeof e||!("message"in e))return;let t=e.message;return"string"==typeof t?t:void 0}(e.error);if(i){var n;let e=(n=t.appDirectory,(0,iY.stripVTControlCharacters)(i).replaceAll(t_.resolve(n),"<project>").replaceAll((0,rw.homedir)(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));e&&(r.kit_error_message=e)}}return{name:"kit_compile",params:r}}(r,{appDirectory:t}))}};function oW(e,t,r){r?.hasErrors()?oH.report({appDirectory:e.appDirectory,context:e,scene:t,status:"failed",errorStage:"compile",error:oD(r)[0]}):oH.report({appDirectory:e.appDirectory,context:e,scene:t,status:"success",compileEndTime:Date.now()})}let oG=f("crypto");class oV{constructor(e,t,r){this._content=t,this._hashCode=r,this.source=e}get content(){return this._content}get hashCode(){var e;return this._hashCode||(e=this.content,oG.createHash("sha256").update("string"==typeof e?e:new DataView(e.buffer,e.byteOffset,e.byteLength)).digest("hex").substring(0,8))}}class oq extends oV{constructor(e,t){super(e,t),this._manifest={applet:{pages:[],tools:[]},widgets:[]};try{this._manifest=es(this._manifest,JSON.parse(t))}catch(e){}this.destination=e}get manifest(){return this._manifest}get content(){return JSON.stringify({manifestVersion:this._manifest.manifestVersion,packageName:this._manifest.packageName,appId:this._manifest.appId,scmVersion:this._manifest.scmVersion,versionName:this._manifest.versionName,versionTag:this._manifest.versionTag,versionCode:this._manifest.versionCode,runtimeVersion:this._manifest.runtimeVersion,sourceType:this._manifest.sourceType,permissions:this._manifest.permissions,settings:this._manifest.settings,applet:this._manifest.applet,widgets:this._manifest.widgets},null,2)}setManifestVersion(e){this._manifest.manifestVersion=e}setRuntimeVersion(e){this._manifest.runtimeVersion=e}setPackageName(e){this._manifest.packageName=e}setVersionName(e){this._manifest.versionName=e}assignBasicManifest(e){Object.assign(this._manifest,e)}mergeBasicManifest(e){es(this._manifest,e)}setSCMVersion(e){this._manifest.scmVersion=e}setVersionCode(e){this._manifest.versionCode=e}setAppletManifest(e){this._manifest.applet=e}mergeAppletManifest(e){es(this._manifest.applet,e)}setRenderType(e=H.REACT_LYNX){this._manifest.renderType=e}appendWidget(e){this._manifest.widgets||(this._manifest.widgets=[]),this._manifest.widgets.push(e)}appendPage(e){this._manifest.applet.pages||(this._manifest.applet.pages=[]),this._manifest.applet.pages.push(e)}toString(){return JSON.stringify(this._manifest,null,2)}}class oJ{constructor(){this.assets={}}addAsset(e,t){this.assets[e]=t}deleteAsset(e){delete this.assets[e]}getAsset(e){return this.assets[e]}getAssets(){return this.assets}getManifestAsset(e){return this.getAsset(e)||(this.assets[e]=new oq(e,JSON.stringify({}))),this.getAsset(e)}}class oz{options;constructor(e){this.options=e}apply(e){let t,{pluginSystem:r}=this.options;e.hooks.thisCompilation.tap({name:oz.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},n=>{n.hooks.processAssets.tapPromise({name:oz.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{t=new oJ,n.getAssets().forEach(e=>{let r=new oV(e.name,e.source.source(),e.info.contenthash?.[0]);t.addAsset(e.name,r)});let{entrypoints:i}=n,s={};i.forEach((e,r)=>{s[r]=e.getFiles().map(e=>{let r=t.getAsset(e);if(!r)throw Error(`未找到构建产物 ${e}`);return new oV(r.source,r.content,r.hashCode)})});let o=this.options.context.appId;o&&tV.mkdirSync(t_.join(this.options.context.rootPath,o),{recursive:!0}),await r.callAssetsHooks("beforeEmit",{assets:t,chunks:s}),Object.keys(t.getAssets()).forEach(r=>{let i=t.getAsset(r);if(!i)return;let{source:s,destination:o}=i;if(!s||!o)return;n.getAsset(s)?n.renameAsset(s,o):n.emitAsset(o,new e.rspack.sources.RawSource(i.content));let a=n.getAsset(`${s}.map`);a&&n.renameAsset(a.name,`${o}.map`)}),await r.callAssetsHooks("afterEmit",{assets:{...t.getAssets()}})})})}}let oK=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class oY{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(oY.name,e=>{e.hooks.finishModules.tap(oY.name,()=>{let t=new Map,r=n=>{if(!n)return!1;let i=t.get(n);if(void 0!==i)return i;if(function(e){var t;let r=e.resourceResolveData?.descriptionFileData?.name;if("string"==typeof r&&oK.has(r))return!0;let n=(t=e.resource,t?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...oK].some(e=>n?.includes(`/node_modules/${e}/`))}(n))return t.set(n,!0),!0;for(let i of(t.set(n,!1),e.moduleGraph.getOutgoingConnections(n)))if(r(i.module))return t.set(n,!0),!0;return!1};e.entries.forEach((t,n)=>{t.dependencies.some(t=>r(e.moduleGraph.getModule(t)))&&this.options.markTemplateWidgetEntry(this.options.normalizeEntryName?.(n)??n)})})})}}class oX{options;constructor(e){this.options=e}apply(e){e.hooks.make.tapPromise(oX.name,async()=>{await this.options.pluginSystem.callViewHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(oX.name,e=>{e.hooks.optimizeTree.tapPromise(oX.name,async t=>{await this.options.pluginSystem.callViewHooks("build",{metadata:this.options.context.metadata,fileDependencies:e.fileDependencies})})}),e.hooks.done.tapPromise(oX.name,async e=>{await this.options.pluginSystem.callViewHooks("afterBuild",{stats:e})})}}function oZ(e){return e.replaceAll("\\","/")}function oQ(e,t,r,n=`${t}.map`){return t!==r&&!!e.getAsset(t)&&(e.renameAsset(t,r),e.getAsset(n)&&e.renameAsset(n,`${r}.map`),!0)}class o0{context;constructor(e){this.context=e}apply(e){e.hooks.thisCompilation.tap(o0.name,t=>{t.hooks.processAssets.tapPromise({name:o0.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{var e,r;let n=this.context.metadata.getData(),i=this.context.command===eD.DEV?"all":"configured",s=rg(this.context.pages,this.context.normalizedAppConfig.pages.entries,i),o=rg(this.context.widgets,this.context.normalizedAppConfig.widgets.entries,i),a=n.app.appId||this.context.appId;if(!a&&Object.keys(s).length>0)throw Error("解析 Web 页面入口路径需要 appId");a&&(e=n.pages,Object.keys(s).forEach(r=>{let n=oZ(r),i=rm(n);oQ(t,`${i}/template.js`,tX(a,e[r]?.path??tY(n),rp),`${i}/background.js.map`)})),r=n.widgets,Object.keys(o).forEach(e=>{var n;let i=rm(oZ(e));oQ(t,`${i}/template.js`,(n=rh(o,r,e),`${n}/${rp}`),`${i}/background.js.map`)})})})}}class o1{entry;constructor(e){this.entry=e}apply(e){let t=new e.webpack.experiments.VirtualModulesPlugin;t.apply(e),e.hooks.thisCompilation.tap(o1.name,()=>{t.writeModule(eK,""),t.writeModule(eY,eX),Object.values(this.entry).forEach(e=>{t.writeModule(e.filename,e.toString())})})}}function o2(e,t){return e.isIdentifier(t)?t.text:e.isPropertyAccessExpression(t)?t.name.text:void 0}let o3={templatesByEntry:{},templatesByWidget:{}},o4="/doubao-apps-framework.template.js",o5="/doubao-apps-api.template.js",o8=(e,t)=>{let r=(e,r,n)=>({libraryName:n,url:t?`/wsd${e}`:e,background:{sectionPath:r},mainThread:{sectionPath:`${r}__main-thread`},async:!!t});return{"@byted-doubao-apps/bridge-base":r(o5,"api"),"@byted-doubao-apps/open-api":r(o5,"api"),...Object.fromEntries(Object.entries(e4).map(([t,n])=>[t,r(e?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",n])])),[`${t0}/api`]:r(o5,"api"),[`${t1}/api`]:r(o5,"api"),[t0]:r(o4,"framework"),[t1]:r(o4,"framework"),"@byted-doubao-apps/components":r(o4,"components"),[t3(t0)]:r(o4,"components"),[t3(t1)]:r(o4,"components")}},o9=f("node:url"),o7=(0,A.createRequire)(import.meta.url);function o6(e,t){for(let r of e)try{return o7.resolve(r,{paths:t})}catch{}throw Error(`无法解析以下候选包:${e.join(", ")}`)}class ae{pluginSystem;constructor(e){this.pluginSystem=e}async createEntry(){let{entry:e}=await this.pluginSystem.callViewHooks("modifyEntryOption",{entry:{}});return e}async createConfig({config:e}){var t,r,n,i,s;let{appDirectory:o,command:c,metadata:h,rootPath:f}=e.context,g=e.context.environment,y="1"===process.env.ENABLE_SELF_CONTAINED;await this.pluginSystem.callViewHooks("modifyEnvironment",{environment:g}),e.context.setEnvironment(g);let b=c===eD.DEV,_=await this.createEntry(),v=t5(o),E=[o,t_.dirname((0,o9.fileURLToPath)(import.meta.url))],w=o7.resolve("@lynx-js/react/transform"),S=b?"all":"configured",x=rg(e.context.pages,e.context.normalizedAppConfig.pages.entries,S),T=new Set([...Object.keys(rg(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,S)),...Object.keys(x)]),I=T.size>0;I&&await nf({widgets:e.context.widgets,pages:e.context.pages,entries:_,collector:h,normalizedAppConfig:e.context.normalizedAppConfig,define:e.context.userConfig?.source?.define});let O={include:e.options.source?.include,exclude:e.options.source?.exclude,decorators:e.options.source?.decorators,define:{...e.options.source?.define,__DOUBAO__:JSON.stringify(!0),__MAIN_PROCESS__:JSON.stringify(!1),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__VERSION_TAG__:JSON.stringify(e.context.versionTag)??"undefined",__LEPUS__:JSON.stringify(!1),"process.env":"({})"}},P=e=>[eK,eY,e.filename],C={...O,entry:Object.fromEntries(Object.entries(_).map(([e,t])=>[e,P(t)]))},R=Object.fromEntries(Object.entries(_).filter(([e])=>T.has(e))),k=new Map(Object.keys(R).map(e=>[rm(e),e])),N={...C,entry:Object.fromEntries(Object.entries(R).map(([e,t])=>[rm(e),P(t)])),define:{...C.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},L=[...rn()?[]:[r5({externals:o8(b),globalObject:"lynx"})]],D=[function({metadata:e,resolveAppInfo:t,resolveVersionTag:r}){return{name:"ai-manifest-plugin",setup(n){n.modifyBundlerChain((n,i)=>{let s=i?.environment?.name==="web"?rl:ra;n.plugin(rc.name).use(rc,[{metadata:e,resolveAppInfo:t,resolveVersionTag:r,isNative:i?.environment?.name!=="web",shouldInjectAsset:s}])})}}}({metadata:h,resolveAppInfo:()=>e.context.resolveAppInfo(),resolveVersionTag:()=>e.context.versionTag})],j={source:{...C,define:{...C.define,...rn()?{__DOUBAO_APPS_SDK_VERSION__:JSON.stringify(o7(o7.resolve(`${v}/package.json`,{paths:[o]})).version)}:{}}},plugins:L},M=[function e({metadata:t,entry:r,resolveSigningEncryptionOptions:n,onProcessDuration:i}){return{name:e.name,setup(e){e.modifyBundlerChain((s,o)=>{if(o?.environment?.name==="web")return;let a=e.useExposed(Symbol.for("LynxTemplatePlugin"));s.plugin(nE.name).use(nE,[a.LynxTemplatePlugin,t,r,n,i])})}}}({metadata:h,entry:_,resolveSigningEncryptionOptions:()=>e.context.resolveSigningEncryptionOptions(),onProcessDuration:t=>{e.context.compileLifecycle.viewTemplateProcessDurationMs=Math.max(e.context.compileLifecycle.viewTemplateProcessDurationMs,t)}}),function({context:e,normalizeEntryName:t}){return{name:"template-widget-entry-plugin",setup(r){r.modifyBundlerChain((r,n)=>{let i=n?.environment?.name;r.plugin("template-widget-entry-plugin").use(oY,[{markTemplateWidgetEntry:t=>{e.addTemplateWidgetEntry(t)},normalizeEntryName:e=>t?.(e,i)}])})}}}({context:e.context,normalizeEntryName:(e,t)=>"web"===t?k.get(e):e}),(t=this.pluginSystem,r=e.context,{name:"output-plugin",setup(e){let n={pluginSystem:t,context:r};e.modifyBundlerChain((e,t)=>{t?.environment?.name!=="web"&&e.plugin("output-plugin").use(oz,[n])})}}),...c===eD.DEV&&I?[function({context:e}){let t;return e.getWidgetViewDataTemplates=async()=>{if(t)return t;try{t=function(e,t,r){let n=function(e){let t,r=(0,A.createRequire)(t_.join(e,"package.json"));try{t=r.resolve("typescript")}catch(e){return}return r(t)}(e);if(!n)return{templatesByEntry:{},templatesByWidget:{}};let i=[...new Set(Object.values(t).map(({filename:e})=>e))],s=n.createProgram({options:function(e,t){let r={allowJs:!0,checkJs:!1,jsx:e.JsxEmit.Preserve,noEmit:!0,skipLibCheck:!0,target:e.ScriptTarget.ESNext},n=e.findConfigFile(t,tV.existsSync);if(!n)return r;let i=e.readConfigFile(n,e.sys.readFile);return i.error?r:{...e.parseJsonConfigFileContent(i.config,e.sys,t_.dirname(n)).options,...r}}(n,e),rootNames:i}),o=s.getTypeChecker(),a=Object.fromEntries(Object.entries(t).map(([e,{filename:t}])=>{let r,i=s.getSourceFile(t);return[$(e),i?(r={},!function e(t){if(n.isCallExpression(t)&&("getViewData"===o2(n,t.expression)||"useViewData"===o2(n,t.expression))&&t.typeArguments?.[0]){let e=o.getTypeFromTypeNode(t.typeArguments[0]);for(let i of o.getPropertiesOfType(e)){let s=i.valueDeclaration??i.declarations?.[0]??t;r[i.getName()]=function e(t,r,n,i,s){let o=(r.isUnion()?r.types:[r]).filter(e=>!(e.flags&(t.TypeFlags.Undefined|t.TypeFlags.Never)));if(o.some(e=>e.flags&t.TypeFlags.Null))return null;if(o.some(e=>e.flags&t.TypeFlags.StringLike))return"";if(o.some(e=>e.flags&(t.TypeFlags.NumberLike|t.TypeFlags.BigIntLike)))return 0;if(o.some(e=>e.flags&t.TypeFlags.BooleanLike))return!1;if(o.some(e=>n.isArrayType(e)||n.isTupleType(e)))return[];let a=o.find(e=>e.flags&t.TypeFlags.Object);if(!a||s.has(a))return{};s.add(a);let l=Object.fromEntries(n.getPropertiesOfType(a).map(r=>{let o=r.valueDeclaration??r.declarations?.[0]??i;return[r.getName(),e(t,n.getTypeOfSymbolAtLocation(r,o),n,o,s)]}));return s.delete(a),l}(n,o.getTypeOfSymbolAtLocation(i,s),o,s,new Set([e]))}}n.forEachChild(t,e)}(i),r):{}]})),l=Object.fromEntries(Object.keys(t).map(e=>{let n=$(e);return[rh(t,r,e),a[n]??{}]}));return{templatesByEntry:a,templatesByWidget:l}}(e.appDirectory,e.widgets,e.metadata.getData().widgets)}catch{t=o3}return t},{name:"WidgetViewDataPlugin",setup(e){e.onAfterDevCompile(({stats:e})=>{e.hasErrors()||(t=void 0)})}}}({context:e.context})]:[],(({context:e})=>({name:"DevServerLogPlugin",setup(t){let r,n=!1,i=!1;t.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{setup({server:e}){e.middlewares.use(oO)}}})),t.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.failed.tap("DevServerLogPlugin",t=>e.finishInitialDevCompile(t))}),t.onAfterDevCompile(async({stats:s})=>{if(s.hasErrors())return void e.finishInitialDevCompile(Error(s.toString({all:!1,errors:!0,colors:!1})));if(n)return;let{devServer:o}=t.context;if(!o)return;n=!0;let a=await ty({debugDriver:e.userConfig.debugDriver,skipAdbForegroundAppWatch:e.userConfig.skipAdbForegroundAppWatch}).catch(nS);i||(e.finishInitialDevCompile(),oI({context:e,port:o.port,driver:a,isSigned:e.isSignedEncryption,onCleanupReady(e){i?e():r=e}}).catch(e=>{i||th.error("初始化开发服务操作失败",{error:e})}))}),t.onCloseDevServer(()=>{i=!0,e.devServerAbort.abort(),r?.(),r=void 0})}}))({context:e.context}),function({context:e}){let t="KitMonitorPlugin";return{name:t,setup(r){if(r.onAfterCreateCompiler(({compiler:r})=>{for(let n of"compilers"in r?r.compilers:[r])n.hooks.finishMake.tap(t,()=>{oB(e.compileLifecycle,"moduleProcess",Date.now())}),n.hooks.emit.tap(t,()=>{oB(e.compileLifecycle,"assetProcess",Date.now())}),n.hooks.failed.tap(t,t=>{oH.report({appDirectory:e.appDirectory,context:e,scene:e.compileLifecycle.scene??(e.command===eD.DEV?"dev_initial":e.command),status:"failed",errorStage:"compile",error:t})})}),e.command!==eD.DEV){let t=e.command;r.onBeforeBuild(()=>{let r=Date.now();oU(e.compileLifecycle,{scene:t,commandStartTime:e.compileLifecycle.commandStartTime??r,compileStartTime:r})}),r.onAfterBuild(({stats:r})=>{oW(e,t,r)})}else r.onBeforeDevCompile(({isFirstCompile:t})=>{let r=Date.now();oU(e.compileLifecycle,{scene:t?"dev_initial":"hot_update",commandStartTime:t?e.compileLifecycle.commandStartTime??r:r,compileStartTime:r})}),r.onAfterDevCompile(({stats:t})=>{oW(e,e.compileLifecycle.scene??"dev_initial",t)})}}}({context:e.context}),..."true"===process.env.BYTED_RSDOCTOR?[{name:"doubao-apps:byted-rsdoctor",setup(e){e.onBeforeCreateCompiler(({bundlerConfigs:e})=>{let{BytedRsdoctorPlugin:t}=o7(o6(["@byted/rsdoctor"],E));for(let r of e){let e=t_.join(r.output?.path??"",`.rsdoctor-${r.name}`);r.plugins??=[],r.plugins.push(new t({disableClientServer:!0,supports:{banner:!0},output:{reportDir:e}}))}})}}]:[],(n=this.pluginSystem,i=e.context,{name:"view-hooks-plugin",setup(e){e.modifyBundlerChain((e,t)=>{t?.environment?.name==="web"||e.plugin("view-hooks-plugin").use(oX,[{pluginSystem:n,context:i}])})}}),(({getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:s})=>({name:"lynx:encode-worker",async setup(o){ri()||o.modifyBundlerChain((o,a)=>{a?.environment?.name!=="web"&&o.plugin(nv.name).use(nv,[{getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:s}]).end()})}}))({getAppAssetPath:()=>e.context.appAssetPath,getAppMapAssetPath:()=>e.context.appMapAssetPath,metadata:e.context.metadata,resolveSigningEncryptionOptions:()=>e.context.resolveSigningEncryptionOptions(),onProcessDuration:t=>{e.context.compileLifecycle.appTemplateProcessDurationMs+=t}}),...e.rsbuildPlugins||[]],U=[{name:"web-virtual-entry-plugin",setup(e){e.modifyBundlerChain((e,{environment:t})=>{"web"===t.name&&e.plugin(o1.name).use(o1,[R])})}},(s=e.context,{name:"web-output-plugin",setup(e){e.modifyBundlerChain({order:"post",handler(e,{environment:t}){if("web"===t.name){let t=".rspeedy/";for(let r of Object.keys(e.plugins.entries()??{}))r.startsWith("lynx:template-")&&e.plugin(r).tap(e=>{let r=e[0];return r?.intermediate?.startsWith(t)&&(r.intermediate=r.intermediate.slice(t.length)),e});e.plugins.has("lynx:sourcemap")&&e.plugin("lynx:sourcemap").tap(e=>{var t;let r,n=e[0];return n.ignoreList=[/^(?!file:\/\/\/)/,/\/(?:externals-loading-runtime|webpack\/runtime)(?:\/|$)/,/\/node_modules\//,/\.(?:css|less|sass|scss)(?:[?#]|$)/],t=s.appDirectory,r=t_.resolve(t),n.moduleFilenameTemplate=({absoluteResourcePath:e,query:t=""})=>{let n=t_.relative(r,e),i=".."!==n&&!n.startsWith(`..${t_.sep}`)&&!t_.isAbsolute(n),s=i?oZ(n):oZ(e).replace(/^\/+/,"");return`${i?"file":"webpack"}:///${s}${t}`},e}),e.plugin(o0.name).use(o0,[s])}}})}})],B=p({mode:c===eD.DEV?"development":"production",environments:I?{lynx:j,web:{source:N,output:{distPath:{css:"",js:"base/web-common"},cleanDistPath:!1,filename:{assets:"[name]/web.bundle"},sourceMap:{js:!!b&&"cheap-module-source-map",css:!1}},plugins:[r5({externals:o8(c===eD.DEV,!0),globalObject:"lynx"})]}}:{lynx:j},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(e,t,r=t_.join(t_.dirname((0,o9.fileURLToPath)(import.meta.url)),"components-loader.js"),n=o6){try{return n(t===t1?["@doubao-dev/kit/components-loader","@byted-doubao-apps/kit/components-loader"]:["@byted-doubao-apps/kit/components-loader","@doubao-dev/kit/components-loader"],e)}catch(e){if((0,tV.existsSync)(r))return r;throw e}}(E,v),options:{frameworkPackage:v}}]},plugins:[new d.BannerPlugin({banner:'"use registerWorkletInternal";',raw:!0,entryOnly:!0,stage:d.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE+1,test:/\.js$/})]}},source:{...O,entry:{}},server:{cors:!0,host:e.context.devServerHost},dev:{writeToDisk:eb(),hmr:c===eD.DEV},output:{distPath:{js:"base/common",root:f||"dist"},cleanDistPath:!1,filename:{bundle:"[name]/template.js"},dataUriLimit:5120},resolve:{alias:{...e.options.resolve?.alias||{}}},performance:{printFileSize:eb(),...rn()&&!y?{chunkSplit:{strategy:"split-by-experience"}}:{}},...y?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(e){(function(e){let{LAYERS:t,lazy:r,rootPath:n,elementTemplate:i}=e??{};return{name:"lynx:react-alias",setup(e){let s=(0,A.createRequire)(import.meta.url),o=s.resolve("@lynx-js/react/package.json",{paths:[n??e.context.rootPath]}),{version:a}=s(o),l=t_.dirname(o);e.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{source:{include:[l]}})),e.modifyBundlerChain(async(s,{isProd:o,rspack:c})=>{if(Object.hasOwn(s,nt))return;let p=nr(c,n??e.context.rootPath,r?["lazy","import"]:["import"]),d=nr(c,l,["import"]);e.expose(Symbol.for("@lynx-js/react/internal:resolve"),{resolve:p}),Object.defineProperty(s,nt,{value:!0});let[u,m,h,f,g,y,b,_,v,E,w,S,x,A]=await Promise.all([p("@lynx-js/react/jsx-runtime"),p("@lynx-js/react/lepus/jsx-runtime"),p("@lynx-js/react/jsx-dev-runtime"),p("@lynx-js/react/lepus/jsx-dev-runtime"),i?p("@lynx-js/react/element-template/jsx-runtime"):Promise.resolve(null),i?p("@lynx-js/react/element-template/jsx-dev-runtime"):Promise.resolve(null),d("preact/hooks"),p("@lynx-js/react/hooks"),p("@lynx-js/react/lepus/hooks"),p("@lynx-js/react"),p("@lynx-js/react/lepus"),ne()(a,"0.111.9999")?p("@lynx-js/react/compat"):Promise.resolve(null),i?p("@lynx-js/react/element-template"):Promise.resolve(null),i?p("@lynx-js/react/element-template/internal"):Promise.resolve(null)]),T={background:u,mainThread:g??m},I={background:h,mainThread:y??f};s.module.rule("react:jsx-runtime:main-thread").issuerLayer(t.MAIN_THREAD).resolve.alias.set("react/jsx-runtime",T.mainThread).set("react/jsx-dev-runtime",I.mainThread).set("@lynx-js/react/jsx-runtime",T.mainThread).set("@lynx-js/react/jsx-dev-runtime",I.mainThread).set("@lynx-js/react/lepus$",w).set("@lynx-js/react/lepus/jsx-runtime",T.mainThread).set("@lynx-js/react/lepus/jsx-dev-runtime",I.mainThread).set("preact/hooks",v).set("@lynx-js/react/hooks",v).set("@lynx-js/react/lepus/hooks",v).set("@lynx-js/react-signals$","@lynx-js/react-signals/lepus").end().end().end().rule("react:jsx-runtime:background").issuerLayer(t.BACKGROUND).resolve.alias.set("react/jsx-runtime",T.background).set("react/jsx-dev-runtime",I.background).set("@lynx-js/react/jsx-runtime",T.background).set("@lynx-js/react/jsx-dev-runtime",I.background).set("@lynx-js/react/lepus$",x??E).set("preact/hooks",b).set("@lynx-js/react/hooks",_).end().end().end().end();let O=new Map;for(let[e,t]of(i&&O.set("experimental/lazy/import",t_.join(l,"runtime/lazy/element-template-import.js")),await Promise.all(["experimental/lazy/import","internal","legacy-react-runtime","runtime-components","worklet-runtime/bindings"].map(async e=>{let t=`@lynx-js/react/${e}`,r=O.get(e)??await p(t);return[`${t}$`,r]}))))s.resolve.alias.set(e,t);o&&(s.resolve.alias.set("@lynx-js/react/debug$",!1),process.env.REACT_DEVTOOL||s.resolve.alias.set("@lynx-js/preact-devtools$",!1)),s.resolve.alias.has("react$")||s.resolve.alias.set("react$",E),s.resolve.alias.set("@lynx-js/react$",x??E).set("@lynx-js/react/internal$",A??s.resolve.alias.get("@lynx-js/react/internal$")).set("@lynx-js/react/jsx-runtime",T.background).set("@lynx-js/react/jsx-dev-runtime",I.background),i&&s.resolve.alias.set("@lynx-js/react/element-template$",x).set("@lynx-js/react/element-template/internal$",A).set("@lynx-js/react/element-template/jsx-runtime",g).set("@lynx-js/react/element-template/jsx-dev-runtime",y),S&&s.resolve.alias.set("@lynx-js/react/compat$",S),await Promise.all(["preact","preact/compat","preact/debug","preact/devtools","preact/test-utils","preact/jsx-runtime","preact/jsx-dev-runtime","preact/compat","preact/compat/client","preact/compat/server","preact/compat/jsx-runtime","preact/compat/jsx-dev-runtime","preact/compat/scheduler"].map(e=>d(e).then(t=>{s.resolve.alias.set(`${e}$`,t)})))})}}})({LAYERS:a,lazy:!1,rootPath:t_.dirname((0,o9.fileURLToPath)(import.meta.url))}).setup(e)}},{name:"set-server.printUrls-false",setup(e){e.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{printUrls:!1}}))}},l({compat:{componentsPkg:[],newRuntimePkg:v,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...t2]}}),{name:"pin-react-transform-path",pre:["lynx:react"],setup(e){e.modifyBundlerChain((e,{CHAIN_ID:t})=>{let r=e.module.rule(t.RULE.JS).oneOf(t.ONE_OF.JS_MAIN);for(let e of[a.BACKGROUND,a.MAIN_THREAD]){let t=r.oneOfs.get(e)?.uses.get(e);if(!t)throw Error(`未找到该层的 React 转换加载器:${e}`);t.tap(e=>({...e,transformPath:w}))}})}},function(e){let{compilerOptionsKeys:t=rx.compilerOptionsKeys,configKeys:r=rx.configKeys,validate:n=rq,dslPluginName2PkgName:i=rJ,upgradeRspeedyLink:s="https://www.npmjs.com/package/upgrade-rspeedy"}=(void 0)??{};return n(e),{name:"lynx:config",async setup(n){n.expose(Symbol.for("lynx.config"),{config:e}),n.modifyBundlerChain(o=>{let a=n.useExposed(Symbol.for("LynxTemplatePlugin"));if(!a){let e="Rspeedy and plugins";throw Object.entries(i).forEach(([t,r])=>{n.isPluginExists(t)&&(e=r)}),Error(`\
190
+ [pluginLynxConfig] No \`LynxTemplatePlugin\` exposed to ${rj("the plugin API","https://rsbuild.rs/plugins/dev/core#apiexpose")}.
185
191
 
186
192
  Please upgrade ${e} to latest version.
187
193
 
188
- See ${rH(rY().yellow("Upgrade Rspeedy"),o)} for more details.
189
- `)}let{LynxTemplatePlugin:l}=s;a.plugin("lynx:config").use(rq,[{LynxTemplatePlugin:l,config:e,compilerOptionsKeys:t,configKeys:r}])})}}}({enableMultiTouch:!0,enableNewGesture:!0,enableCSSInlineVariables:!0,enableSimultaneousTap:!0,enableReloadLifecycle:!0}),h(),u(),...C?[]:N,...L,...j,...C?U:[]]});return await this.pluginSystem.callViewHooks("beforeBuild",{buildConfig:B}),B}}async function a3(e,t){let r=new a1(t),n=await r.createConfig({config:e}),i=await d({rspeedyConfig:n,cwd:e.context.appDirectory});return i.removePlugins(["lynx:react-alias"]),i}async function a2(e,t){var r;let{entry:n}=await rc({config:e,pluginSystem:t});return await a3({...e,rsbuildPlugins:[...e.rsbuildPlugins||[],(r={context:e.context,entry:n,pluginSystem:t},{name:"worker-in-view-plugin",setup(e){e.modifyRspackConfig((e,{environment:t})=>{var n,i,o;let a;("lynx"===t.name||"web"===t.name)&&(n=e,i=r,o=t.name,n.entry??={},a=n.entry,Object.entries(i.entry).forEach(([e,t])=>{a[e]={filename:"web"===o?`${e}.js`:`base/${e}${tg()?".js":".template.js"}`,import:"web"===o&&"development"===n.mode&&"app"===e?["@lynx-js/webpack-dev-transport/client","@rspack/core/hot/dev-server",t.filename]:t.filename,layer:s.BACKGROUND}}),e.plugins.push(new rC(r,"lynx"===t.name)),"web"===t.name&&e.plugins.push(new rE))})}})]},t)}function a4(e){if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}let a5=e=>{try{return to.statSync(e,{throwIfNoEntry:!1})?.isFile()}catch(e){return!1}};async function a9({internal:e,appKey:t}){try{return await nq({internal:e,path:`/developer/resource_api/apps/${encodeURIComponent(t)}/dek/public_key`})}catch(e){throw tI.error("Failed to get KEK",{error:e,appKey:t,operation:"get-kek"}),e}}async function a8(e,t,r,n){if(!(n||th("DISABLE_SIGNING_ENCRYPTION")||th("LEGACY_FRAMEWORK"))){if(e)return e;if("production"===process.env.NODE_ENV&&t===ej.DEPLOY){if(!r)throw Error("appId is required to get KEK");let{data:e}=await a9({internal:!1,appKey:r}),t=Number(Object.keys(e.keys)[0]);return{signing:{enabled:!1},encryption:{enabled:!0,wrap_key:e.keys[t],key_id:t,salt:""}}}}}let a7=eX.join("node_modules",".doubao-dev","config.json");function a6(e,t,r){if(r){let t=eX.isAbsolute(r)?r:eX.resolve(e,r);if(t5.existsSync(t))return t;tC.warn("Cannot find config file",{path:t})}for(let r of tr.map(r=>eX.resolve(e,`${t}${r}`)))if(a5(r))return r;return!1}async function se(e){let t=(0,w.createJiti)((0,aZ.fileURLToPath)(import.meta.url),{requireCache:!1,interopDefault:!0});return await t.import(e,{default:!0})}async function st({cwd:e=process.cwd(),customConfigFile:t}){let r=a6(e,"doubao.config",t);if(!r)return{};try{return await se(r)}catch(e){throw tC.error("Failed to load config file",{path:r}),e}}async function sr({cwd:e=process.cwd()}={}){let t=a6(eX.resolve(e,"src"),tt);if(t)try{return await se(t)}catch(e){throw tC.error("Failed to load app config file",{path:t}),e}}async function sn(e){let t=globalThis,r=Object.prototype.hasOwnProperty.call(t,"defineAppConfig"),n=t.defineAppConfig;t.defineAppConfig=e=>e;try{return await se(e)}finally{r?t.defineAppConfig=n:delete t.defineAppConfig}}async function si({cwd:e=process.cwd()}={}){let t=a6(eX.resolve(e,"src"),tt);if(t)try{let e=await sn(t);return{...void 0!==e.darkMode?{darkMode:e.darkMode}:{},...void 0!==e.chat?{chat:e.chat}:{},...Array.isArray(e.pages)?{pages:e.pages}:{},...Array.isArray(e.widgets)?{widgets:e.widgets}:{}}}catch(e){throw tC.error("Failed to load Taro app config file",{path:t}),e}}let so=async(e,t=ta.basename(e))=>{if(!to.existsSync(e))return{};let r={};for(let n of(await tL.readdir(e))){let i=ta.resolve(e,n);if(!to.statSync(i).isDirectory())continue;let o=ta.resolve(i,"index.tsx");to.existsSync(o)&&(r[`${t}/${n}/index`]={folderName:`${n}/index`,renderType:en.REACT_LYNX,filename:o})}return r},sa=async(e,t=ta.basename(e))=>{if(!to.existsSync(e))return{viewEntries:{},apiEntries:{}};let r=await so(e,t),n={},i=ta.resolve(e,"login.ts");to.existsSync(i)&&(n[`${t}/login`]={filename:i,folderName:e});let o=ta.resolve(e,"privacy.ts");return to.existsSync(o)&&(n[`${t}/privacy`]={filename:o,folderName:e}),{viewEntries:r,apiEntries:n}},ss=async(e,t)=>to.existsSync(e)?(await tL.readdir(e)).reduce((r,n)=>{let i=ta.resolve(e,n);return to.statSync(i).isDirectory()&&to.existsSync(ta.resolve(i,t))&&(r[n]=ta.resolve(i,t)),r},{}):{};function sl(e){return ta.resolve(e,"app.ts")}function sd(e,t,r,n){let i=`${r}/`;if(!t.startsWith(i))throw Error(`${r} config key must start with "${i}": ${t}`);let o=t.slice(i.length),a=ta.resolve(e,r,`${o}${n}`);if(!to.existsSync(a))throw Error(`Configured entry file does not exist for ${t}: ${a}`);return{relativeEntry:o,filename:a}}function sp(e,t){let r=t.entries[e]?.name;if(void 0===r)return rt(e);if("string"!=typeof r||!r.trim())throw Error(`Configured Tool name must be a non-empty string: ${e}`);return r.trim()}let sc=async(e,t={entryNames:[],entries:{}})=>{let r=ta.resolve(e,"tools"),n={...await ss(r,"index.ts")};t.entryNames.forEach(r=>{let{filename:i}=sd(e,r,"tools",".ts"),o=sp(r,t),a=n[o];if(a&&a!==i)throw Error(`Tool name "${o}" is already used by another entry: ${a}`);n[o]=i});let i=sl(e);return{tools:n,app:to.existsSync(i)?i:void 0}},su=async(e,t)=>{let r=ta.resolve(e,"pages"),n=ta.resolve(e,"widgets"),i=ta.resolve(e,"auth"),o=ta.resolve(e,"mcp-ui"),[a,s,l,d]=await Promise.all([so(r),so(n),sa(o),sa(i)]),p=Object.keys(d.viewEntries).length>0||Object.keys(d.apiEntries).length>0?d:l,c=t.pages,u=t.widgets,h=(t,r,n)=>{let i={...t};return r.forEach(t=>{if(i[t])return;let{relativeEntry:r,filename:o}=sd(e,t,n,".tsx");i[t]={folderName:r,renderType:en.REACT_LYNX,filename:o,isVirtualFile:!1}}),i},m=h(a,c.entryNames,"pages");return{widgets:h(s,u.entryNames,"widgets"),pages:m,auth:p}};function sh(e,t,r=!1,n=!1){let i=tu(t);return Object.keys(e).reduce((o,a)=>{let{filename:s}=e[a],l=n&&e[a].isLoginPage?"defineLoginPage":n?"definePage":"defineWidget",d=`${eZ}${ta.sep}${a}${ta.extname(s)}`,p=ro(ta.join(t,d,".."),s);return o[a]=new ra(d),o[a].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:p,importSpecifiers:[{propertyName:"default",name:"ViewEntry"}]},{moduleSpecifier:i,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:l,name:l},{propertyName:"getViewContext",name:"getViewContext"}]}),o[a].appendContent(`
194
+ See ${rj(rG().yellow("Upgrade Rspeedy"),s)} for more details.
195
+ `)}let{LynxTemplatePlugin:l}=a;o.plugin("lynx:config").use(rB,[{LynxTemplatePlugin:l,config:e,compilerOptionsKeys:t,configKeys:r}])})}}}({enableMultiTouch:!0,enableNewGesture:!0,enableCSSInlineVariables:!0,enableReloadLifecycle:!0}),m(),u(),...I?[]:L,...D,...M,...I?U:[]]});return await this.pluginSystem.callViewHooks("beforeBuild",{buildConfig:B}),B}}async function at(e,t){let r=new ae(t),n=await r.createConfig({config:e}),i=await c({rspeedyConfig:n,cwd:e.context.appDirectory});return i.removePlugins(["lynx:react-alias"]),i}async function ar(e,t){var r;let{entry:n}=await rt({config:e,pluginSystem:t});return await at({...e,rsbuildPlugins:[...e.rsbuildPlugins||[],(r={context:e.context,entry:n,pluginSystem:t},{name:"worker-in-view-plugin",setup(e){e.modifyRspackConfig((e,{environment:t})=>{var n,i,s;let o;("lynx"===t.name||"web"===t.name)&&(n=e,i=r,s=t.name,n.entry??={},o=n.entry,Object.entries(i.entry).forEach(([e,t])=>{o[e]={filename:"web"===s?`${e}.js`:`base/${e}${ri()?".js":".template.js"}`,import:"web"===s&&"development"===n.mode&&"app"===e?["@lynx-js/webpack-dev-transport/client","@rspack/core/hot/dev-server",t.filename]:t.filename,layer:a.BACKGROUND}}),e.plugins.push(new rE(r,"lynx"===t.name)),"web"===t.name&&e.plugins.push(new ry))})}})]},t)}function an(e){if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}let ai=e=>{try{return tV.statSync(e,{throwIfNoEntry:!1})?.isFile()}catch(e){return!1}};async function as({internal:e,appKey:t}){try{return await n5({internal:e,path:`/developer/resource_api/apps/${encodeURIComponent(t)}/dek/public_key`})}catch(e){throw td.error("获取 KEK 失败",{error:e,appKey:t,operation:"get-kek"}),e}}async function ao(e,t,r,n){if(!(n||rr("DISABLE_SIGNING_ENCRYPTION")||rr("LEGACY_FRAMEWORK"))){if(e)return e;if("production"===process.env.NODE_ENV&&t===eD.DEPLOY){if(!r)throw Error("获取 KEK 需要 appId");let{data:e}=await as({internal:!1,appKey:r}),t=Number(Object.keys(e.keys)[0]);return{signing:{enabled:!1},encryption:{enabled:!0,wrap_key:e.keys[t],key_id:t,salt:""}}}}}let aa=t_.join("node_modules",".doubao-dev","config.json");function al(e,t,r){if(r){let t=t_.isAbsolute(r)?r:t_.resolve(e,r);if(tV.existsSync(t))return t;tp.warn("未找到配置文件",{path:t})}for(let r of e7.map(r=>t_.resolve(e,`${t}${r}`)))if(ai(r))return r;return!1}async function ac(e){let t=(0,E.createJiti)((0,o9.fileURLToPath)(import.meta.url),{requireCache:!1,interopDefault:!0});return await t.import(e,{default:!0})}async function ap({cwd:e=process.cwd(),customConfigFile:t}){let r=al(e,"doubao.config",t);if(!r)return{};try{return await ac(r)}catch(e){throw tp.error("加载配置文件失败",{path:r}),e}}async function ad({cwd:e=process.cwd()}={}){let t=al(t_.resolve(e,"src"),e9);if(t)try{return await ac(t)}catch(e){throw tp.error("加载应用配置文件失败",{path:t}),e}}async function au(e){let t=globalThis,r=Object.prototype.hasOwnProperty.call(t,"defineAppConfig"),n=t.defineAppConfig;t.defineAppConfig=e=>e;try{return await ac(e)}finally{r?t.defineAppConfig=n:delete t.defineAppConfig}}async function am({cwd:e=process.cwd()}={}){let t=al(t_.resolve(e,"src"),e9);if(t)try{let e=await au(t);return{...void 0!==e.darkMode?{darkMode:e.darkMode}:{},...void 0!==e.chat?{chat:e.chat}:{},...Array.isArray(e.pages)?{pages:e.pages}:{},...Array.isArray(e.widgets)?{widgets:e.widgets}:{}}}catch(e){throw tp.error("加载 Taro 应用配置文件失败",{path:t}),e}}let ah=async(e,t=t_.basename(e))=>{if(!tV.existsSync(e))return{};let r={};for(let n of(await tb.readdir(e))){let i=t_.resolve(e,n);if(!tV.statSync(i).isDirectory())continue;let s=t_.resolve(i,"index.tsx");tV.existsSync(s)&&(r[`${t}/${n}/index`]={folderName:`${n}/index`,renderType:H.REACT_LYNX,filename:s})}return r},af=async(e,t=t_.basename(e))=>{if(!tV.existsSync(e))return{viewEntries:{},apiEntries:{}};let r=await ah(e,t),n={},i=t_.resolve(e,"login.ts");tV.existsSync(i)&&(n[`${t}/login`]={filename:i,folderName:e});let s=t_.resolve(e,"privacy.ts");return tV.existsSync(s)&&(n[`${t}/privacy`]={filename:s,folderName:e}),{viewEntries:r,apiEntries:n}},ag=async(e,t)=>tV.existsSync(e)?(await tb.readdir(e)).reduce((r,n)=>{let i=t_.resolve(e,n);return tV.statSync(i).isDirectory()&&tV.existsSync(t_.resolve(i,t))&&(r[n]=t_.resolve(i,t)),r},{}):{};function ay(e,t){return tQ(e,t).replace(/\.(?:t|j)sx?$/i,"")}function ab(e){return t_.resolve(e,"app.ts")}function a_(e,t,r,n){let i=`${r}/`;if(!t.startsWith(i))throw Error(`${r} 配置键必须以 "${i}" 开头:${t}`);let s=t.slice(i.length),o=t_.resolve(e,r,`${s}${n}`);if(!tV.existsSync(o))throw Error(`配置的入口文件不存在:${o}(入口:${t})`);return{relativeEntry:s,filename:o}}function av(e,t){let r=t.entries[e]?.name;if(void 0===r)return tK(e);if("string"!=typeof r||!r.trim())throw Error(`配置的 Tool 名称必须是非空字符串:${e}`);return r.trim()}let aE=async(e,t={entryNames:[],entries:{}})=>{let r=t_.resolve(e,"tools"),n={...await ag(r,"index.ts")};t.entryNames.forEach(r=>{let{filename:i}=a_(e,r,"tools",".ts"),s=av(r,t),o=n[s];if(o&&o!==i)throw Error(`Tool 名称 "${s}" 已被其他入口使用:${o}`);n[s]=i});let i=ab(e);return{tools:n,app:tV.existsSync(i)?i:void 0}},aw=async(e,t)=>{let r=t_.resolve(e,"pages"),n=t_.resolve(e,"widgets"),i=t_.resolve(e,"auth"),s=t_.resolve(e,"mcp-ui"),[o,a,l,c]=await Promise.all([ah(r),ah(n),af(s),af(i)]),p=Object.keys(c.viewEntries).length>0||Object.keys(c.apiEntries).length>0?c:l,d=t.pages,u=t.widgets,m=(t,r,n)=>{let i={...t};return r.forEach(t=>{if(i[t])return;let{relativeEntry:r,filename:s}=a_(e,t,n,".tsx");i[t]={folderName:r,renderType:H.REACT_LYNX,filename:s,isVirtualFile:!1}}),i},h=m(o,d.entryNames,"pages");return{widgets:m(a,u.entryNames,"widgets"),pages:h,auth:p}};function aS(e,t,r=!1,n=!1){let i=t5(t);return Object.keys(e).reduce((s,o)=>{let{filename:a}=e[o],l=n&&e[o].isLoginPage?"defineLoginPage":n?"definePage":"defineWidget",c=`${ez}${t_.sep}${o}${t_.extname(a)}`,p=tQ(t_.join(t,c,".."),a);return s[o]=new t8(c),s[o].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:i,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:l,name:l},{propertyName:"getViewContext",name:"getViewContext"}]},{moduleSpecifier:p,importSpecifiers:[{propertyName:"default",name:"ViewEntry"}]}),s[o].appendContent(`
190
196
  lynx.__DOUBAO_VIEW_TYPE__ = ${JSON.stringify(n?"page":"widget")};
191
197
 
192
198
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
@@ -202,11 +208,11 @@ const View =
202
208
  const FC = bootstrapReactLynx(View, viewId, ${JSON.stringify(n)});
203
209
 
204
210
  root.render(<FC />);
205
- `),r&&o[a].appendContent(`
211
+ `),r&&s[o].appendContent(`
206
212
  if (import.meta.webpackHot) {
207
213
  import.meta.webpackHot.accept()
208
214
  }
209
- `),o},{})}let sm={name:"AuthPlugin",async setup(e){th("DISABLE_GENERATE_LOGIN_CARD")||th("LEGACY_FRAMEWORK")||(e.view.hooks.modifyEnvironment.tapPromise(sm.name,async({environment:e})=>{e.useAuth=!0}),e.view.hooks.modifyEntryOption.tapPromise({name:sm.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,o,a,s,l,{isDev:d,auth:p,appDirectory:c}=e.context,u={},h=Object.keys(p.viewEntries).reduce((e,t)=>(e[t]={...p.viewEntries[t],internal:!0,isSpecial:!0,isLoginPage:"auth/login-page/index"===t||"auth/mcp-login-page/index"===t||"mcp-ui/mcp-login-page/index"===t},e),{});return e.context.appendPages(h),t=Object.assign(t,(r=tu(c),n=`${eZ}${ta.sep}${e3}${ta.sep}${e5}.tsx`,u[i=`${e3}/${e5}`]={filename:n,renderType:en.REACT_LYNX,folderName:e5,isVirtualFile:!0,isSpecial:!0,internal:!0},o=new ra(n),a=ta.join(c,ta.dirname(n)),s=Object.values(p.apiEntries).find(e=>"login"===ta.parse(e.filename).name),l=Object.values(p.apiEntries).find(e=>"privacy"===ta.parse(e.filename).name),s&&o.appendImports({moduleSpecifier:ro(a,s.filename),importSpecifiers:[{propertyName:"default",name:"loginApi"}]}),l&&o.appendImports({moduleSpecifier:ro(a,l.filename),importSpecifiers:[{propertyName:"default",name:"privacyApi"}]}),o.appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:r,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"definePrivacyLoginWidget",name:"definePrivacyLoginWidget"}]},{moduleSpecifier:`${r}/components`,importSpecifiers:[{propertyName:"MCPAuthCard",name:"MCPAuthCard"}]}),o.appendContent(`
215
+ `),s},{})}let ax={name:"AuthPlugin",async setup(e){rr("DISABLE_GENERATE_LOGIN_CARD")||rr("LEGACY_FRAMEWORK")||(e.view.hooks.modifyEnvironment.tapPromise(ax.name,async({environment:e})=>{e.useAuth=!0}),e.view.hooks.modifyEntryOption.tapPromise({name:ax.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,s,o,a,l,{isDev:c,auth:p,appDirectory:d}=e.context,u={},m=Object.keys(p.viewEntries).reduce((e,t)=>(e[t]={...p.viewEntries[t],internal:!0,isSpecial:!0,isLoginPage:"auth/login-page/index"===t||"auth/mcp-login-page/index"===t||"mcp-ui/mcp-login-page/index"===t},e),{});return e.context.appendPages(m),t=Object.assign(t,(r=t5(d),n=`${ez}${t_.sep}${eZ}${t_.sep}${e1}.tsx`,u[i=`${eZ}/${e1}`]={filename:n,renderType:H.REACT_LYNX,folderName:e1,isVirtualFile:!0,isSpecial:!0,internal:!0},s=new t8(n),o=t_.join(d,t_.dirname(n)),a=Object.values(p.apiEntries).find(e=>"login"===t_.parse(e.filename).name),l=Object.values(p.apiEntries).find(e=>"privacy"===t_.parse(e.filename).name),s.appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:r,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"definePrivacyLoginWidget",name:"definePrivacyLoginWidget"}]},{moduleSpecifier:`${r}/components`,importSpecifiers:[{propertyName:"MCPAuthCard",name:"MCPAuthCard"}]}),a&&s.appendImports({moduleSpecifier:tQ(o,a.filename),importSpecifiers:[{propertyName:"default",name:"loginApi"}]}),l&&s.appendImports({moduleSpecifier:tQ(o,l.filename),importSpecifiers:[{propertyName:"default",name:"privacyApi"}]}),s.appendContent(`
210
216
  lynx.__DOUBAO_VIEW_TYPE__ = 'widget';
211
217
 
212
218
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
@@ -217,8 +223,8 @@ const View = definePrivacyLoginWidget({
217
223
  <MCPAuthCard
218
224
  ${l?"onAgreePrivacy={privacyApi.onAgreePrivacy}":""}
219
225
  ${l?"onRefusePrivacy={privacyApi.onRefusePrivacy}":""}
220
- ${s?"onLogin={loginApi.onLogin}":""}
221
- ${s?"onRefuseLogin={loginApi.onRefuseLogin}":""}
226
+ ${a?"onLogin={loginApi.onLogin}":""}
227
+ ${a?"onRefuseLogin={loginApi.onRefuseLogin}":""}
222
228
  />
223
229
  );
224
230
  }
@@ -226,11 +232,11 @@ const View = definePrivacyLoginWidget({
226
232
 
227
233
  const FC = bootstrapReactLynx(View, viewId);
228
234
  root.render(<FC />);
229
- `,d?`
235
+ `,c?`
230
236
  if (import.meta.webpackHot) {
231
237
  import.meta.webpackHot.accept()
232
238
  }
233
- `:""),{[i]:o}),sh(h,c,d,!0)),e.context.appendWidgets(u),{entry:t}}))}};(eP=eW||(eW={}))[eP.DISABLED=0]="DISABLED",eP[eP.ENABLED=1]="ENABLED";let sf="AppletDoubaoAppInfoPlugin",sg={name:sf,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sf,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-1},async({assets:t})=>{if(e.context.command!==ej.DEV&&e.context.command!==ej.BUILD&&e.context.command!==ej.DEPLOY||!e.context.appId)return;let r=await e.context.resolveAppInfo();if(r){var n=t.getManifestAsset(e.context.manifestAssetPath),i=e.context.permissions;n.assignBasicManifest({permissions:void 0===i?Object.fromEntries(r.permissionList.filter(e=>e.status===eW.ENABLED).map(e=>[e.scope_name,{desc:e.description||e.scope_name||"",apis:(e.api_list||[]).map(e=>e.api_name).filter(Boolean)}]).filter(([e,t])=>e&&t.apis.length>0)):Object.fromEntries(i.filter(e=>"string"==typeof e?.scope_name&&!!e.scope_name.trim()).map(e=>{let t=e.scope_name.trim();return[t,{desc:"string"==typeof e.description&&e.description?e.description:t,apis:[]}]}))}),r?.appName&&n.mergeAppletManifest({name:r.appName}),r?.iconUrl&&n.mergeAppletManifest({icons:tF(r.iconUrl)})}})}},sy={name:"ExpiredWidgetPlugin",async setup(e){e.view.hooks.modifyEntryOption.tapPromise({name:sy.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,o,{isDev:a,appDirectory:s}=e.context,l={};return t=Object.assign(t,(r=tu(s),n=`${eZ}${ta.sep}${e3}${ta.sep}${e9}.tsx`,l[i=`${e3}/${e9}`]={filename:n,renderType:en.REACT_LYNX,folderName:e9,isVirtualFile:!0,isSpecial:!0,internal:!0},(o=new ra(n)).appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:r,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"defineWidget",name:"defineWidget"}]},{moduleSpecifier:`${r}/components`,importSpecifiers:[{propertyName:"UpdatedState",name:"UpdatedState"}]}),o.appendContent(`
239
+ `:""),{[i]:s}),aS(m,d,c,!0)),e.context.appendWidgets(u),{entry:t}}))}};(eC=eB||(eB={}))[eC.DISABLED=0]="DISABLED",eC[eC.ENABLED=1]="ENABLED";let aA="AppletDoubaoAppInfoPlugin",aT={name:aA,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:aA,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-1},async({assets:t})=>{if(e.context.command!==eD.DEV&&e.context.command!==eD.BUILD&&e.context.command!==eD.DEPLOY||!e.context.appId)return;let r=await e.context.resolveAppInfo();if(r){var n=t.getManifestAsset(e.context.manifestAssetPath),i=e.context.permissions;n.assignBasicManifest({permissions:void 0===i?Object.fromEntries(r.permissionList.filter(e=>e.status===eB.ENABLED).map(e=>[e.scope_name,{desc:e.description||e.scope_name||"",apis:(e.api_list||[]).map(e=>e.api_name).filter(Boolean)}]).filter(([e,t])=>e&&t.apis.length>0)):Object.fromEntries(i.filter(e=>"string"==typeof e?.scope_name&&!!e.scope_name.trim()).map(e=>{let t=e.scope_name.trim();return[t,{desc:"string"==typeof e.description&&e.description?e.description:t,apis:[]}]}))}),r?.appName&&n.mergeAppletManifest({name:r.appName}),r?.iconUrl&&n.mergeAppletManifest({icons:tx(r.iconUrl)})}})}},aI={name:"ExpiredWidgetPlugin",async setup(e){e.view.hooks.modifyEntryOption.tapPromise({name:aI.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,s,{isDev:o,appDirectory:a}=e.context,l={};return t=Object.assign(t,(r=t5(a),n=`${ez}${t_.sep}${eZ}${t_.sep}${e2}.tsx`,l[i=`${eZ}/${e2}`]={filename:n,renderType:H.REACT_LYNX,folderName:e2,isVirtualFile:!0,isSpecial:!0,internal:!0},(s=new t8(n)).appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:r,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"defineWidget",name:"defineWidget"}]},{moduleSpecifier:`${r}/components`,importSpecifiers:[{propertyName:"UpdatedState",name:"UpdatedState"}]}),s.appendContent(`
234
240
  lynx.__DOUBAO_VIEW_TYPE__ = 'widget';
235
241
 
236
242
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
@@ -245,12 +251,12 @@ const View = defineWidget({
245
251
 
246
252
  const FC = bootstrapReactLynx(View, viewId);
247
253
  root.render(<FC />);
248
- `,a?`
254
+ `,o?`
249
255
  if (import.meta.webpackHot) {
250
256
  import.meta.webpackHot.accept()
251
257
  }
252
- `:""),{[i]:o})),e.context.appendWidgets(l),{entry:t}})}},sb="LynxPlugin",s_={name:sb,async setup(e){e.view.hooks.modifyEnvironment.tapPromise(sb,async({environment:e})=>{e.useLynx=!0});let t={};e.view.hooks.modifyEntryOption.tapPromise({name:sb,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:r})=>{let{appDirectory:n,isDev:i,widgets:o,pages:a}=e.context;return t=r=Object.assign(r,sh(o,n,i),sh(a,n,i,!0)),{entry:r}}),e.view.hooks.collectMetaData.tapPromise({name:sb,stage:e.view.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:r})=>{let{normalizedAppConfig:n,userConfig:i,widgets:o,pages:a}=e.context;await nr({widgets:o,pages:a,entries:t,collector:r,normalizedAppConfig:n,define:i.source?.define})}),e.assets.hooks.beforeEmit.tapPromise({name:sb,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS},async({assets:t})=>{let{widgets:r,pages:n,app:i}=e.context.metadata.getInstance(),o=e.context.templateWidgetEntries;Object.keys(r).forEach(n=>{let i=r[n],a=`${n}/template.js`,s=t.getAsset(a);if(i&&s){let r=`${i.metadata.id}/template.js`;s.destination=r;let a=t.getManifestAsset(e.context.manifestAssetPath),l=i.toManifest(r,s.hashCode,en.LYNX);o.has(n)&&(l.titleType=ei.NONE),a.appendWidget(l)}}),Object.keys(n).forEach(r=>{let o=n[r],a=`${r}/template.js`,s=t.getAsset(a);if(o&&s){let r=rn(i.metadata.appId,o.metadata.path,"template.js");s.destination=r,t.getManifestAsset(e.context.manifestAssetPath).appendPage(o.toManifest(r,s.hashCode,en.LYNX))}})}),e.assets.hooks.afterEmit.tapPromise(sb,async({assets:e})=>{}),e.view.hooks.afterBuild.tapPromise(sb,async({stats:e})=>{})}};async function sv(e,t,r){let{app:n,tools:i,collector:o,define:a}=r,s=i[t],l=e;(s||n===t)&&(a&&Object.keys(a).length>0&&(l=Object.keys(a).reduce((e,t)=>{let r=a[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`Define value ${t} is not a string`)},e)),ed((0,r7.parseSync)(l,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(r0(e.callee)&&["defineTool","defineApp"].includes(e.callee.value)){let t=e.arguments[0]?.expression;if(r4(t)){for(let e of t.properties)if(r9(e)&&r0(e.key)&&"aiMeta"===e.key.value){let t=r8(e.value);s?o.addToolMeta(s,t):o.addAppMeta({...t,appId:t.appId??t.package})}}}}}))}async function sw({tools:e,app:t,collector:r,define:n,appConfig:i}){let o={collector:r,tools:Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),app:t,define:n};Object.entries(e).forEach(([e])=>{r.addToolMeta(e,{id:e})}),t5.existsSync(t)?await Promise.all(Object.values({...e,app:t}).filter(e=>/\.(ts|tsx|jsx|js)$/i.test(e)&&t5.existsSync(e)).map(e=>sv(t5.readFileSync(e,"utf-8"),e,o))):tC.warn("App file does not exist",{path:t});let a=r.app,s=i?.appId??a.appId;if(!s)throw Error("appId is required in app config or AI metadata");r.addAppMeta({...a,name:i?.name??a.name,description:i?.description??a.description,icons:i?.icons??a.icons,keywords:i?.keywords??a.keywords,version:i?.version??a.version,darkMode:i?.darkMode??a.darkMode,chat:i?.chat??a.chat,appId:s})}let sS={name:"AppletMainPlugin",setup:async e=>{e.context.app&&(e.worker.hooks.modifyEntryOption.tapPromise("AppletMainPlugin",async({entry:t})=>{var r,n,i;let o,{app:a,tools:s}=e.context,l=Object.fromEntries((r=e.context.normalizedAppConfig.tools).entryNames.map(e=>{let t=sp(e,r),n=s[t];if(!n)throw Error(`Configured Tool entry was not analyzed: ${e}`);return[t,n]}));return Object.assign(t,{app:(n=`${e.context.appDirectory}${ta.sep}${eZ}${ta.sep}app.js`,o=(({dirname:e,app:t,tools:r})=>{let n=[],i=[],o=tu(eX.resolve(t,"..",".."));Object.entries(r).forEach(([t,r],o)=>{let a=JSON.stringify(t);n.push(`import Tool${o} from "${ro(e,r)}";`),i.push(`toAppRuntimeTool(Tool${o}, ${a})`)});let a=i.length>0?`function toAppRuntimeTool(tool, id) {
253
- return typeof tool === 'object' &&
258
+ `:""),{[i]:s})),e.context.appendWidgets(l),{entry:t}})}},aO="LynxPlugin",aP={name:aO,async setup(e){e.view.hooks.modifyEnvironment.tapPromise(aO,async({environment:e})=>{e.useLynx=!0});let t={};e.view.hooks.modifyEntryOption.tapPromise({name:aO,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:r})=>{let{appDirectory:n,isDev:i,widgets:s,pages:o}=e.context;return t=r=Object.assign(r,aS(s,n,i),aS(o,n,i,!0)),{entry:r}}),e.view.hooks.collectMetaData.tapPromise({name:aO,stage:e.view.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:r})=>{let{normalizedAppConfig:n,userConfig:i,widgets:s,pages:o}=e.context;await nf({widgets:s,pages:o,entries:t,collector:r,normalizedAppConfig:n,define:i.source?.define})}),e.assets.hooks.beforeEmit.tapPromise({name:aO,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS},async({assets:t})=>{let{widgets:r,pages:n,app:i}=e.context.metadata.getInstance(),s=e.context.templateWidgetEntries;Object.keys(r).forEach(n=>{let i=r[n],o=`${n}/template.js`,a=t.getAsset(o);if(i&&a){let r=`${i.metadata.id}/template.js`;a.destination=r;let o=t.getManifestAsset(e.context.manifestAssetPath),l=i.toManifest(r,a.hashCode,H.LYNX);s.has(n)&&(l.titleType=F.NONE),o.appendWidget(l)}}),Object.keys(n).forEach(r=>{let s=n[r],o=`${r}/template.js`,a=t.getAsset(o);if(s&&a){let r=tX(i.metadata.appId,s.metadata.path,"template.js");a.destination=r,t.getManifestAsset(e.context.manifestAssetPath).appendPage(s.toManifest(r,a.hashCode,H.LYNX))}})}),e.assets.hooks.afterEmit.tapPromise(aO,async({assets:e})=>{}),e.view.hooks.afterBuild.tapPromise(aO,async({stats:e})=>{})}},aC=`function toAppRuntimeTool(tool, id, key) {
259
+ const normalizedTool = typeof tool === 'object' &&
254
260
  tool !== null &&
255
261
  '__FUNCTIONAL__' in tool &&
256
262
  tool.__FUNCTIONAL__ === true
@@ -267,26 +273,28 @@ if (import.meta.webpackHot) {
267
273
  return tool(typeof input === 'string' ? JSON.parse(input) : input);
268
274
  }
269
275
  });
270
- }`:"",s=i.length>0?"Applet, defineTool":"Applet";return`
271
- import { ${s} } from "${o}";
272
- import App from "${ro(e,t)}";
273
-
274
- ${n.join("\n")}
275
276
 
276
- ${a}
277
+ return Object.defineProperty(normalizedTool, '__runtimeEntry', {
278
+ value: Object.freeze({ type: 'functional_tool', key, id: normalizedTool.aiMeta.id })
279
+ });
280
+ }`;async function aR(e,t,r){let{app:n,tools:i,collector:s,define:o}=r,a=i[t],l=e;(a||n===t)&&(o&&Object.keys(o).length>0&&(l=Object.keys(o).reduce((e,t)=>{let r=o[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`define 配置项 ${t} 的值必须是字符串`)},e)),el((0,nd.parseSync)(l,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(nn(e.callee)&&["defineTool","defineApp"].includes(e.callee.value)){let t=e.arguments[0]?.expression;if(na(t)){for(let e of t.properties)if(nc(e)&&nn(e.key)&&"aiMeta"===e.key.value){let t=np(e.value);a?s.addToolMeta(a,t):s.addAppMeta({...t,appId:t.appId??t.package})}}}}}))}async function a$({tools:e,app:t,collector:r,define:n,appConfig:i}){let s={collector:r,tools:Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),app:t,define:n};Object.entries(e).forEach(([e])=>{r.addToolMeta(e,{id:e})}),tV.existsSync(t)?await Promise.all(Object.values({...e,app:t}).filter(e=>/\.(ts|tsx|jsx|js)$/i.test(e)&&tV.existsSync(e)).map(e=>aR(tV.readFileSync(e,"utf-8"),e,s))):tp.warn("应用入口文件不存在",{path:t});let o=r.app,a=i?.appId??o.appId;if(!a)throw Error("请在应用配置或 AI 元数据中提供 appId");r.addAppMeta({...o,name:i?.name??o.name,description:i?.description??o.description,icons:i?.icons??o.icons,keywords:i?.keywords??o.keywords,version:i?.version??o.version,darkMode:i?.darkMode??o.darkMode,chat:i?.chat??o.chat,appId:a})}let ak={name:"AppletMainPlugin",setup:async e=>{e.context.app&&(e.worker.hooks.modifyEntryOption.tapPromise("AppletMainPlugin",async({entry:t})=>{var r;let{app:n,srcDirectory:i,tools:s}=e.context,o=Object.fromEntries((r=e.context.normalizedAppConfig.tools).entryNames.map(e=>{let t=av(e,r),n=s[t];if(!n)throw Error(`未解析到配置的 Tool 入口:${e}`);return[t,n]}));return Object.assign(t,{app:((e,t,r,n=t_.dirname(t))=>{let i=t_.dirname(e),s=t5(t_.resolve(t,"..","..")),o=[],a=[];Object.entries(r).forEach(([e,t],r)=>{let s=ay(n,t);o.push(`import Tool${r} from "${tQ(i,t)}";`),a.push(`toAppRuntimeTool(Tool${r}, ${JSON.stringify(e)}, ${JSON.stringify(s)})`)});let l=a.length>0;return new t8(e,`
281
+ import { ${l?"Applet, defineTool":"Applet"} } from "${s}";
282
+ import App from "${tQ(i,t)}";
283
+ ${o.join("\n")}
277
284
 
278
- new Applet(App, [${i.join(", ")}]).bootstrap();
279
- `})({dirname:eX.dirname(n),app:a,tools:s}),new ra(n,o))}),Object.keys(l).length>0&&(t[e6]=(i=`${e.context.appDirectory}${ta.sep}${eZ}${ta.sep}${e6}.js`,new ra(i,function({appDirectory:e,clientTools:t,dirname:r}){let n=tu(e),i=[],o=[];return Object.entries(t).forEach(([e,t],n)=>{i.push(`import ClientTool${n} from "${ro(r,t)}";`),o.push(`{ name: ${JSON.stringify(e)}, handler: ClientTool${n} }`)}),`
280
- import { bootstrapClientToolRuntime } from "${n}";
285
+ ${l?aC:""}
281
286
 
282
- ${i.join("\n")}
287
+ new Applet(App, [${a.join(", ")}]).bootstrap();
288
+ `)})(`${e.context.appDirectory}${t_.sep}${ez}${t_.sep}app.js`,n,s,i)}),Object.keys(o).length>0&&(t[e5]=function(e,t,r,n=t_.resolve(r,"src")){let i=t_.dirname(e),s=t5(r),o=[],a=[];return Object.entries(t).forEach(([e,t],r)=>{let s={type:"client_tool",key:ay(n,t),id:e};o.push(`import ClientTool${r} from "${tQ(i,t)}";`),a.push(`{ name: ${JSON.stringify(e)}, handler: ClientTool${r}, entry: Object.freeze(${JSON.stringify(s)}) }`)}),new t8(e,`
289
+ import { bootstrapClientToolRuntime } from "${s}";
290
+ ${o.join("\n")}
283
291
 
284
- bootstrapClientToolRuntime([${o.join(", ")}]);
285
- `}({appDirectory:e.context.appDirectory,clientTools:l,dirname:ta.dirname(i)})))),{entry:t}}),e.worker.hooks.modifyEnvironment.tapPromise("AppletMainPlugin",async({environment:e})=>{}),e.worker.hooks.collectMetaData.tapPromise({name:"AppletMainPlugin",stage:e.worker.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:t})=>{let{app:r,appConfig:n,tools:i,userConfig:o}=e.context;await sw({appConfig:n,tools:i,app:r,collector:t,define:o.source?.define}),e.context.setVersionTag(e.context.metadata.app.version)}),e.assets.hooks.beforeEmit.tapPromise({name:"AppletMainPlugin",stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:t,chunks:r})=>{var n,i;let{app:o,pages:a,tools:s}=e.context.metadata.getInstance(),l=t.getAsset(e.context.appAssetPath),d=r[e6]?.find(({source:e})=>e.endsWith(".js")),p=t.getManifestAsset(e.context.manifestAssetPath),{manifest:c}=p,u=[];c.applet.pages.forEach(e=>{u.push(e.digest)});let h=o.metadata.appId,m=e.context.versionTag;p.assignBasicManifest({manifestVersion:"3.0",packageName:h,appId:h,versionName:m,versionTag:m,scmVersion:process.env.BUILD_VERSION,versionCode:Date.now().toString(),runtimeVersion:"1.0",sourceType:e.context.internal?1:2,settings:e.context.manifestSettings});let f=e.context.appAssetPath,g=e.context.normalizedAppConfig.pages.entryNames[0]??Object.keys(e.context.pages)[0],y=g?a[g]?.metadata.path:void 0,b=o.toManifest({toolsMetadata:s,hashCode:l?.hashCode??(n=l?.hashCode??c?.applet?.digest,i=u.join(""),aN.createHash("sha256").update(n+i).digest("hex").substring(0,8)),appRuntimeEntry:f,appRuntimeType:e.context.environment.useLynx?"lynx":"js"});d&&(b.toolRuntimeEntry=d.source),p.mergeAppletManifest(b),y&&p.mergeAppletManifest({appletEntry:y})}),e.assets.hooks.afterEmit.tapPromise({name:"AppletMainPlugin",stage:e.assets.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:e})=>{}),e.worker.hooks.afterBuild.tapPromise("AppletMainPlugin",async({stats:e})=>{}))}},sE={name:"AppletMainEntryCheckPlugin",setup:async e=>{let{srcDirectory:t}=e.context,r=sl(t);if(!to.existsSync(r))throw Error("ENOENT: no such file or directory")}},sx={name:"AppletManifestPlugin",setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:"AppletManifestPlugin",stage:e.assets.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS},async({assets:t})=>{let{signing:r}=await e.context.resolveSigningEncryptionOptions()||{};if(r?.enabled){let{signData:n}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),i=t.getManifestAsset(e.context.manifestAssetPath),{manifest:o}=i,{buffer:a,status:s,error_msg:l}=await n(Buffer.from(i.content),ri(r,{extra_config:{app_id:o.appId,bundle_id:""},output_mode:"sign_block"}));if(0!==s)throw Error(l);let d=new aL(e4,a);d.destination=e4,t.addAsset(e4,d)}})}},sA="AppletWebManifestPlugin",sT={name:sA,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sA,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-2},async({assets:t})=>{var r,n;let i=e.context.metadata.getData(),o=i.app.appId||e.context.appId,a=e.context.command===ej.DEV?"all":"configured",s=rS(e.context.pages,e.context.normalizedAppConfig.pages.entries,a),l=rS(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,a);if(!o&&Object.keys(s).length>0)throw Error("appId is required to resolve Web page entry paths");let d=o?(r=i.pages,Object.keys(s).map(e=>{let t=r[e]??{},n=t.path??rr(e),i={entry:rn(o,n,rg)},a=rw(s[e]);return{path:n,entryName:e,web:i,debugHidden:a,manifest:{...t,path:n,digest:"",entry:"",renderType:en.LYNX,web:i,...a?{debugHidden:!0}:{}}}})):[],p=(n=i.widgets,Object.keys(l).map(e=>{let{id:t,...r}=n[e]??{},i=t??rv(l,n,e),o={entry:`${i}/${rg}`},a=rw(l[e]);return{id:i,entryName:e,web:o,debugHidden:a,manifest:{...r,widgetId:i,digest:"",entry:"",renderType:en.LYNX,web:o,...a?{debugHidden:!0}:{}}}}));if(0===d.length&&0===p.length&&0===e.context.normalizedAppConfig.tools.entryNames.length)return;let c=t.getManifestAsset(e.context.manifestAssetPath),u=new Map(d.map(e=>[e.path,e])),h=new Set(c.manifest.applet.pages?.map(e=>e.path));for(let e of(c.manifest.applet.pages?.forEach(e=>{let t=u.get(e.path);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),d))h.has(e.path)||c.appendPage(e.manifest);let m=new Map(p.map(e=>[e.id,e])),f=new Set(c.manifest.widgets?.map(e=>e.widgetId));for(let t of(c.manifest.widgets?.forEach(e=>{let t=m.get(e.widgetId);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),p))if(!f.has(t.id)){let r=t.manifest;e.context.templateWidgetEntries.has(t.entryName)&&(r.titleType=ei.NONE),c.appendWidget(r)}e.context.app&&(c.manifest.applet.web={appRuntimeEntry:ry,...e.context.normalizedAppConfig.tools.entryNames.length>0?{toolRuntimeEntry:rb}:{}})})}};function sC(e=((e=process.cwd())=>tc(e)===ts)()){return e?"sso":"sms"}async function sI(e={},t={}){if(e.cookie)return e.cookie;let{ensureLoginCookie:r}=await import("./@byted-doubao-apps/login~1.js");return await r({route:sC(t.internal),browser:e.loginBrowser,browserPath:e.loginBrowserPath,force:t.force})}async function sO(e,t){if(e.cookie)return e.cookie;let{getCachedLoginCookie:r}=await import("./@byted-doubao-apps/login~1.js");return await r({route:sC(t)})}function sP(e,t){let r;if(!e)return{entryNames:[],entries:{}};if(Array.isArray(e))r=e;else if("object"==typeof e)t&&tC.warn(`${t} config object map is deprecated. Use an array of strings or { entry, ...metadata } objects instead.`),r=Object.entries(e).map(([e,t])=>{let r;return{...t,entry:(r=e.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"")).endsWith("/index")?r:`${r}/index`}});else throw Error("Entry config must be an array or object map.");let n=[],i={},o=new Set,a=[],s=new Set;return r.forEach(e=>{let t,r;if("string"==typeof e)t=e,r={};else{let{entry:n,...i}=e;if(!n)throw Error('Entry config object must include "entry".');t=n,r=i}o.has(t)?s.has(t)||(a.push(t),s.add(t)):(n.push(t),o.add(t)),i[t]=r}),t&&a.length>0&&tC.warn(`${t} config contains duplicate entries: ${a.join(", ")}. Entries are deduplicated, and the last metadata config takes effect.`),{entryNames:n,entries:i}}class sk{constructor(){this.deploy={},this._isInitialized=!1,this._environment={useLynx:!1,useAuth:!1},this._srcDirectory="",this._virtualEntryDir="",this._appDirectory=process.cwd(),this._rootPath="",this._appAssetPath="",this._appMapAssetPath="",this._manifestPath="",this._widgets={},this._app="",this._tools={},this._cookie="",this._pages={},this._auth={viewEntries:{},apiEntries:{}},this._viewEntriesByType={}}async bootstrap({command:e,metadata:t,versionTag:r,srcDirectory:n="",virtualEntryDir:i="",appDirectory:o=process.cwd(),rootPath:a="",manifestPath:s="",pages:l={},widgets:d={},auth:p,mcpUI:c,app:u="",tools:h={},environment:m={useLynx:!1,useAuth:!1},viewEntriesByType:f={},loginCookieResolver:g,cachedLoginCookieResolver:y}){this._command=e,this._metadata=t,this._versionTag=r,this._srcDirectory=n,this._virtualEntryDir=i,this._appDirectory=o,this._rootPath=a,this._manifestPath=s,this._pages={...l},this._widgets={...d};let b=p??c??{viewEntries:{},apiEntries:{}};this._auth={viewEntries:{...b.viewEntries},apiEntries:{...b.apiEntries}},this._app=u,this._tools={...h},this._environment={useLynx:m.useLynx,useAuth:!!(m.useAuth||m.useMcpUI)},this._cookie="",this._loginCookieResolver=g,this._loginCookiePromise=void 0,this._cachedLoginCookieResolver=y,this._viewEntriesByType=Object.fromEntries(Object.entries(f).map(([e,t])=>[e,{pages:{...t.pages},widgets:{...t.widgets}}])),this._isInitialized=!0}assertInitialized(e){if(!this._isInitialized)throw Error(`BuildContext.${e} is unavailable before bootstrap`)}get isDev(){return this.assertInitialized("isDev"),this._command===ej.DEV}get command(){return this.assertInitialized("command"),this._command}get metadata(){return this.assertInitialized("metadata"),this._metadata}get manifestPath(){return this.assertInitialized("manifestPath"),this._manifestPath}get appDirectory(){return this._appDirectory}get virtualEntryDir(){return this.assertInitialized("virtualEntryDir"),this._virtualEntryDir}get srcDirectory(){return this.assertInitialized("srcDirectory"),this._srcDirectory}get rootPath(){return this.assertInitialized("rootPath"),this._rootPath}get manifest(){if(this._manifest)return{...this._manifest};try{return this._manifest=JSON.parse(to.readFileSync(this._manifestPath,"utf-8")),{...this._manifest}}catch(e){return{}}}get useLynx(){return this._environment.useLynx}get useAuth(){return this._environment.useAuth}get useMcpUI(){return this.useAuth}get manifestAssetPath(){return e2}get appAssetPath(){return this._appAssetPath}get appMapAssetPath(){return this._appMapAssetPath}get environment(){return{...this._environment}}get widgets(){return{...this._widgets}}get pages(){return{...this._pages}}get auth(){return{viewEntries:{...this._auth.viewEntries},apiEntries:{...this._auth.apiEntries}}}get mcpUI(){return this.auth}get viewEntriesByType(){return Object.fromEntries(Object.entries(this._viewEntriesByType).map(([e,t])=>[e,{pages:{...t.pages},widgets:{...t.widgets}}]))}get app(){return this._app}get tools(){return{...this._tools}}async getLoginCookie(){return(this.assertInitialized("getLoginCookie"),this._cookie)?this._cookie:this._loginCookieResolver?(this._loginCookiePromise||(this._loginCookiePromise=this._loginCookieResolver().then(e=>(this._cookie=e??"",e)).catch(e=>{throw this._loginCookiePromise=void 0,e})),await this._loginCookiePromise):void 0}async getCachedLoginCookie(){if(this.assertInitialized("getCachedLoginCookie"),this._cookie)return this._cookie;if(!this._cachedLoginCookieResolver)return;let e=await this._cachedLoginCookieResolver();return e&&(this._cookie=e),e}get appId(){return this._appId||this._metadata.appId}setAppId(e){this._appId=e}setApp(e){this._app=e}setTools(e){this._tools=e}setEnvironment(e){this._environment={...e}}mergeEnvironment(e){this._environment={...this._environment,...e}}setPages(e){this._pages=e}setWidgets(e){this._widgets=e}appendPages(e){Object.assign(this._pages,e)}appendWidgets(e){Object.assign(this._widgets,e)}getViewEntriesByType(e){let t=this._viewEntriesByType[e];return t?{pages:{...t.pages},widgets:{...t.widgets}}:{pages:{},widgets:{}}}setViewEntriesByType(e,t){this._viewEntriesByType[e]={pages:{...t.pages},widgets:{...t.widgets}}}setAppAssetPath(e){this._appAssetPath=e}setAppMapAssetPath(e){this._appMapAssetPath=e}setManifest(e){this._manifest=e}setVersionTag(e){return this.assertInitialized("versionTag"),!this._versionTag&&e&&(this._versionTag=e),this._versionTag}setAuthApi(e){this._auth={viewEntries:{...e.viewEntries},apiEntries:{...e.apiEntries}}}setMcpUIApi(e){this.setAuthApi(e)}get versionTag(){return this.assertInitialized("versionTag"),this._versionTag}}async function sD({internal:e,domainId:t,appLimit:r,appOffset:n,keyWord:i,appKey:o,cookie:a}){return await nq({internal:e,domainId:t,path:"/app_developer/api/apps",query:{app_limit:r,app_offset:n,key_word:i,app_key:o},method:"GET",headers:a?{Cookie:a}:void 0})}async function s$({source:e,internal:t,domainId:r,appLimit:n,appOffset:i,releaseStatus:o,keyWord:a,appKey:s,cookie:l}){return await nq({internal:t,domainId:r,path:"/developer/api/apps",query:{source:e,app_limit:n,app_offset:i,release_status:o,key_word:a,app_key:s},method:"GET",headers:l?{Cookie:l}:void 0})}async function sR({appKey:e,source:t,internal:r,domainId:n,releaseStatus:i,limit:o,offset:a,status:s,keyWord:l,versionTag:d,cookie:p}){return await nq({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/version`,query:{source:t,release_status:i,limit:o,offset:a,status:s,key_word:l,version_tag:d},method:"GET",headers:p?{Cookie:p}:void 0})}async function sN({appKey:e,versionTag:t,internal:r,domainId:n,pageSize:i,pageNum:o,cookie:a}){return await nq({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/permission/versions/${encodeURIComponent(t)}/permission_list`,query:{page_size:i,page_num:o},method:"GET",headers:a?{Cookie:a}:void 0})}function sL(e){return e.is_latest||e.is_current}function sM(e){return Date.parse(e.updated_at??e.created_at??e.online_at??"")}function sj(e){return Number(e.version_code??e.qr_data?.artifact_version_code)}function sU(e){return e.version_tag}function sB(e,t){tm()&&tC.info(e,t)}async function sF({appKey:e,internal:t=!1,cookie:r,source:n=eq.REQUEST_SOURCE_IDE}){sB("[app-info] 开始获取应用信息",{appKey:e,internal:t,session:r?"present":"absent"});let i=await sD({internal:t,appLimit:1,appOffset:0,appKey:e,cookie:r}).then(({data:t,log_id:r})=>{let n=t?.app_list||[],i=n.find(t=>t.app_key===e);return sB("[app-info] MGetApps 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),i}).catch(t=>{if(sB("[app-info] MGetApps 请求失败",{appKey:e,reason:a4(t)}),aa(t))throw t}),o=i?void 0:await s$({source:n,internal:t,appLimit:1,appOffset:0,appKey:e,cookie:r}).then(({data:t,log_id:r})=>{let n=t?.org_list?.flatMap(e=>e.app_list)||[],i=n.find(t=>t.app_key===e),o=i||n[0];return sB("[app-info] MGetAppsDeprecated 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),o?.app_meta}).catch(t=>{sB("[app-info] MGetAppsDeprecated 请求失败",{appKey:e,reason:a4(t)})});if(!i&&!o)throw sB("[app-info] 应用信息查询结束,未找到可用结果",{appKey:e}),Error(`未找到应用 ${e}`);let a=i?void 0:await sR({appKey:e,source:n,internal:t,cookie:r}).then(({data:t,log_id:r})=>{let n=Array.isArray(t?.version_list)?t.version_list:[];if(sB("[app-info] MGetAppVersions 请求完成",{appKey:e,versionCount:n.length,logId:r}),0===n.length)return;let i=n.find(sL);return i||n.reduce((e,t)=>{let r,n;return!e||(r=sM(t),n=sM(e),(Number.isNaN(r)&&Number.isNaN(n)?sj(t)-sj(e):(Number.isNaN(r)?-1/0:r)-(Number.isNaN(n)?-1/0:n))>0)?t:e},void 0)}).catch(t=>{sB("[app-info] MGetAppVersions 请求失败",{appKey:e,reason:a4(t)})}),s=i?.current_version_tag||(a?sU(a):""),l=i?.icon_url||(a?a.icon_url:void 0)||o?.icon_url,d=i?.name||o?.name,p=a&&sU(a)===s?a:i?{version_tag:i.current_version_tag,icon_url:i.icon_url,updated_at:i.updated_at,online_at:i.online_at,offline_at:i.offline_at}:{version_tag:s,icon_url:l};if(i||!s||!r)return{appKey:e,appName:d,versionTag:s,iconUrl:l,permissionList:[],permissionTotal:0,version:p};let c=await sN({appKey:e,versionTag:s,pageSize:1e3,pageNum:1,internal:t,cookie:r}).then(t=>(sB("[app-info] FetchAppPermissionList 请求完成",{appKey:e,versionTag:s,permissionTotal:t.data?.total||0,logId:t.log_id}),t)).catch(t=>{throw sB("[app-info] FetchAppPermissionList 请求失败",{appKey:e,versionTag:s,reason:a4(t)}),t});return{appKey:e,appName:d,versionTag:s,iconUrl:l,permissionList:c.data?.permission_list||[],permissionTotal:c.data?.total||0,version:p}}function sW(){return function({fetch:e,getCacheKey:t,ttl:r,timeout:n,cacheFailures:i=!1,now:o=Date.now}){let a=new Map;return function(...s){var l,d;let p,c="string"==typeof(l=t(...s))?l:JSON.stringify(l),u=o(),h=a.get(c);if(h&&h.expiresAt>u)return h.promise;let m=(d=e(...s),void 0===n?d:Promise.race([d,new Promise((e,t)=>{p=setTimeout(()=>{t(Error(`Request timed out after ${n}ms`))},n)})]).finally(()=>{p&&clearTimeout(p)})).catch(e=>{throw i||a.get(c)?.promise!==m||a.delete(c),e});return a.set(c,{expiresAt:u+r,promise:m}),m}}({fetch:sF,getCacheKey:({appKey:e,internal:t,cookie:r})=>[e,t,r],ttl:6e4,timeout:1e4,cacheFailures:!0})}function sH(){let e=Object.entries(rI.networkInterfaces()),t=[];for(let[r,n]of e){if(!n)continue;let e=/^(?:utun|tun|tap|ppp|ipsec|wg|docker|vboxnet|vmnet|awdl|llw|tailscale|zt)/i.test(r)||/^(?:br-|bridge\d|virbr\d|veth)/i.test(r)||/(?:vEthernet|Hyper-V|Docker|VirtualBox|VMware|WireGuard|Tailscale|ZeroTier|VPN)/i.test(r),i=/^(?:en\d+|eth\d+|eno\d+|enp\w+|wl\w+)$|^(?:Ethernet|Wi-?Fi|WLAN|以太网|无线网络连接)(?:\s|$)/i.test(r);for(let r of n){let{address:n,family:o,internal:a}=r;if(!a&&"IPv4"===o){let r=n.startsWith("169.254.")?3:e?2:+!i;t.push({address:n,priority:r})}}}return t.sort((e,t)=>e.priority-t.priority),[...new Set(t.map(({address:e})=>e))]}async function sV(e="0.0.0.0"){if(!e||e.includes(":"))throw Error("--host 必须是 IPv4 地址或主机名,不能包含协议或端口;暂不支持 IPv6。");let{address:t}=await (0,x.lookup)(e,{family:4});if("0.0.0.0"!==t)return t;let r=sH()[0];return r||(tD.warn("未找到外部 IPv4 地址,将使用 127.0.0.1,仅支持本机访问。"),"127.0.0.1")}async function sG(e,t,r){let n=await fetch(`${e}/base/manifest.json`,{signal:AbortSignal.any([r,AbortSignal.timeout(1500)]),redirect:"error"}),i=await n.json();if(!n.ok||t&&i?.appId!==t)throw Error(`开发服务器返回的 manifest 无效:${e}(HTTP ${n.status},appId:${t})`)}async function sq(e,t,r,n){let i,o=function(e,t=sH()[0]??"127.0.0.1"){return`http://${t}:${e}`}(e,t),a=AbortSignal.any([n,AbortSignal.timeout(5e3)]);try{for(;;)try{await sG(o,r,a);break}catch(e){i=e,await (0,v.setTimeout)(200,void 0,{signal:a})}}catch{throw n.throwIfAborted(),Error(`开发服务器的 manifest 在 5 秒内未就绪:${o}/base/manifest.json。请检查网络,或使用 --host <IP> 指定设备可访问的本机 IP`,{cause:i})}return{host:o,artifactOrigin:o}}(ek=eH||(eH={}))[ek.APP_TYPE_MINI_APP=0]="APP_TYPE_MINI_APP",ek[ek.APP_TYPE_NATIVE=1]="APP_TYPE_NATIVE",(eD=eV||(eV={}))[eD.DRAFT=0]="DRAFT",eD[eD.UNDER_REVIEW=1]="UNDER_REVIEW",eD[eD.APPROVED=2]="APPROVED",eD[eD.REJECTED=3]="REJECTED",eD[eD.WITHDRAWN=4]="WITHDRAWN",eD[eD.PUBLISHING=5]="PUBLISHING",eD[eD.PUBLISHED=6]="PUBLISHED",eD[eD.ARCHIVED=7]="ARCHIVED",eD[eD.DELETED=8]="DELETED",(e$=eG||(eG={}))[e$.DRAFT=0]="DRAFT",e$[e$.PUBLISHED=1]="PUBLISHED",e$[e$.ARCHIVED=2]="ARCHIVED",(eR=eq||(eq={}))[eR.REQUEST_SOURCE_PLATFORM=0]="REQUEST_SOURCE_PLATFORM",eR[eR.REQUEST_SOURCE_IDE=1]="REQUEST_SOURCE_IDE",eR[eR.REQUEST_SOURCE_DEVICE=2]="REQUEST_SOURCE_DEVICE",eR[eR.REQUEST_SOURCE_OP_PLATFORM=3]="REQUEST_SOURCE_OP_PLATFORM";class sJ extends sk{devServerInteractive=!0;devServerHost="0.0.0.0";devServerAbort=new AbortController;finishInitialDevCompile;initialDevCompile=new Promise(e=>{this.finishInitialDevCompile=e,this.devServerAbort.signal.addEventListener("abort",()=>e(void 0),{once:!0})});devServerResolution;resolveDevServer(e){return this.devServerResolution??=this.initialDevCompile.then(t=>{if(t)throw t;return this.devServerAbort.signal.throwIfAborted(),sq(e,this.devServerHost,this.appId,this.devServerAbort.signal)})}getWidgetViewDataTemplates;webDebuggerLaunchOptions;compileLifecycle=aI();eventsResources;toolsResources;manifestSettings;_userConfig={};_env={};_appConfig={};_normalizedAppConfig={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}};_signingEncryptionOptions;_rawSigningEncryptionOptions;_signingEncryptionOptionsPromise;_disableSigningEncryption=!1;_dek=Buffer.from("");_internal=!1;_fetchCachedAppInfo=sW();_skipAppInfoFetch=!1;_hasWarnedAppInfoFetchFailure=!1;_templateWidgetEntries=new Set;_permissions;get userConfig(){return this._userConfig}get env(){return{...this._env}}get appConfig(){return this._appConfig}get normalizedAppConfig(){var e;return{pages:{entryNames:[...(e=this._normalizedAppConfig).pages.entryNames],entries:Object.fromEntries(Object.entries(e.pages.entries).map(([e,t])=>[e,{...t}]))},tools:{entryNames:[...e.tools.entryNames],entries:Object.fromEntries(Object.entries(e.tools.entries).map(([e,t])=>[e,{...t}]))},widgets:{entryNames:[...e.widgets.entryNames],entries:Object.fromEntries(Object.entries(e.widgets.entries).map(([e,t])=>[e,{...t}]))}}}get templateWidgetEntries(){return new Set(this._templateWidgetEntries)}get permissions(){return this._permissions?.map(e=>({...e}))}get signingEncryptionOptions(){if(this._signingEncryptionOptions)return{...this._signingEncryptionOptions,encryption:{...this._signingEncryptionOptions?.encryption,dek:this.dek}}}get dek(){return this._dek}get isSignedEncryption(){return this.signingEncryptionOptions?.signing.enabled||this.signingEncryptionOptions?.encryption.enabled}get internal(){return this.assertInitialized("internal"),this._internal}setSigningEncryptionOptions(e){this._rawSigningEncryptionOptions=e,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0}disableSigningEncryption(){this._disableSigningEncryption=!0,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._dek=Buffer.from("")}addTemplateWidgetEntry(e){this._templateWidgetEntries.add(e)}async resolveSigningEncryptionOptions(){return this._signingEncryptionOptionsPromise||(this._signingEncryptionOptionsPromise=this.resolveSigningEncryptionOptionsOnce()),this._signingEncryptionOptionsPromise}async resolveAppInfo(){this.assertInitialized("resolveAppInfo");let e=this.compileLifecycle.appInfoMeasured?void 0:Date.now();this.compileLifecycle.appInfoMeasured=!0;try{return await this.resolveAppInfoInternal()}finally{void 0!==e&&(this.compileLifecycle.appInfoDurationMs=Math.max(0,Date.now()-e))}}async resolveAppInfoInternal(){var e;let t=this.appId;if(!ao(t))return;let r="string"==typeof(e=this._appConfig.icons)?e.length>0?e:void 0:e?.["3x"]||e?.["2x"]||e?.["1x"],n={appKey:t,versionTag:this.versionTag??"",permissionList:[],permissionTotal:0,version:{},...this._appConfig.name?{appName:this._appConfig.name}:{},...r?{iconUrl:r}:{}};if(this._skipAppInfoFetch)return n;let i=await this.getCachedLoginCookie().catch(()=>void 0);try{return Object.assign(n,await this._fetchCachedAppInfo({appKey:t,cookie:i,internal:this.internal})),n.appName||=this._appConfig.name,n.iconUrl||=r,n}catch(e){if(this.command!==ej.DEV&&this.command!==ej.BUILD)throw e;if(aa(e))return n;return this._hasWarnedAppInfoFetchFailure||(this._hasWarnedAppInfoFetchFailure=!0,tC.warn("从平台获取 Doubao 应用信息失败,将使用本地 `app.config.ts` 配置的数据",{reason:a4(e)})),n}}async bootstrap({srcDirectory:e,appDirectory:t,rootPath:r,userConfig:n,appConfig:i={},normalizedAppConfig:o={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}},command:a,metadata:s,signingEncryptionOptions:l,disableSigningEncryption:d,appId:p,versionTag:c,pages:u,widgets:h,auth:m,app:f,tools:g,internal:y,skipAppInfoFetch:b,permissions:_,devServerInteractive:v=!0,env:w={},loginCookieResolver:S,cachedLoginCookieResolver:E}){await super.bootstrap({srcDirectory:e,appDirectory:t,virtualEntryDir:ta.resolve(t,eZ),rootPath:r,manifestPath:ta.resolve(`${r}/${e2}`),command:a,metadata:s,versionTag:c,pages:u,widgets:h,auth:m,app:f,tools:g,loginCookieResolver:S,cachedLoginCookieResolver:E});let{icons:x,...A}=i??{};this._userConfig=n,this.devServerInteractive=v,this._env={...w},this._appConfig={...A,...void 0!==p?{appId:p}:{},...void 0!==x?{icons:tF(x)}:{}},this._normalizedAppConfig=o,this._internal=y??((e=process.cwd())=>tc(e)===ts)(t),this._skipAppInfoFetch=!!b,this._permissions=_?.map(e=>({...e})),this._hasWarnedAppInfoFetchFailure=!1,this._templateWidgetEntries=new Set,this._rawSigningEncryptionOptions=l,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._disableSigningEncryption=!!d,this._appId=p??i?.appId,this._dek=Buffer.from(""),this._fetchCachedAppInfo=sW()}async resolveSigningEncryptionOptionsOnce(){let e=this._appId??this.metadata.appId;if(this._signingEncryptionOptions=await a8(this._rawSigningEncryptionOptions,this.command,e,this._disableSigningEncryption),this._signingEncryptionOptions?.encryption.enabled){let{generateDEK:e}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)});this._dek=e(),tm()&&console.log("DEK base64:",Buffer.from(this.dek.buffer,this.dek.byteOffset,this.dek.byteLength).toString("base64"))}return this.signingEncryptionOptions}}async function sK({appId:e,versionTag:t,versionCode:r,packagePath:n,internal:i,domainId:o,cookie:a,token:s,needAuth:l=!0}){let d=new FormData,p=new Blob([new Uint8Array(to.readFileSync(n))],{type:"application/zip"});d.append("applet_file",p,"doubao_app.zip"),d.append("applet_version_code",r.toString());let c=`/developer/${l?"resource_api":"resource_internal_api"}/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/package/upload_applet`;return await nq({internal:i,domainId:s?"sms-external":o,path:c,method:"POST",body:d,headers:{...a?{Cookie:a}:{},...s?{"X-Developer-Open-Build-Token":s}:{}},auth:l&&!s})}async function sz({versionTag:e,appKey:t,manifest:r,rootPath:n,internal:i,needAuth:o=!0,cookie:a,token:s}){process.env.NODE_ENV="production";let{appId:l,packageName:d,versionCode:p}=r,c=function(e,t){let r=e||t.versionTag||t.versionName;if(!r)throw Error("Doubao Apps Platform deploy requires versionTag in params or app metadata.");return r}(e,r),{packageResource:u}=await t7({channelName:"doubao_app",manifest:r,rootPath:n});if(!u)throw Error("Failed to archive package");let h=await sK({appId:t||l||d,versionTag:c,versionCode:p,packagePath:u.resource,internal:i,needAuth:o,cookie:a,token:s});return console.log("Deploy success:",h),h}let sY=f("../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"),sX="x-db-llm-modifiable",sZ="x-db-is-entity-id",sQ="x-db-is-refresh-key",s0=["entity_type"];function s1(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function s3(e,t,r){if(!s1(e))throw Error(`Tool "${r}" requires an object ${t}`);return e}function s2(e,t,r,n,i=!1){let o=`Tool "${t}" ${r} property "${n}"`;if(!s1(e)||"string"!=typeof e.type||!e.type.trim())throw Error(`${o} requires a string type`);let a=e.type.trim(),s=e[sX];if(void 0!==s&&"boolean"!=typeof s)throw Error(`${o} ${sX} must be a boolean`);if(s&&"outputSchema"!==r)throw Error(`${o} ${sX} is only supported in outputSchema`);if(s&&"array"!==a)throw Error(`${o} ${sX} is only supported for array fields`);let l=e[sZ];if(void 0!==l&&"boolean"!=typeof l)throw Error(`${o} ${sZ} must be a boolean`);if(l&&!i)throw Error(`${o} ${sZ} is only supported on top-level card output fields`);let d=e[sQ];if(void 0!==d&&"boolean"!=typeof d)throw Error(`${o} ${sQ} must be a boolean`);if(d&&!i)throw Error(`${o} ${sQ} is only supported on top-level card output fields`);let p={type:function(e,t){if("integer"===e)return"int";if("number"===e)return"float";if(["string","boolean","object","array"].includes(e))return e;throw Error(`${t} has unsupported type "${e}"`)}(a,o),...s?{llm_modifiable:!0}:{},...l?{is_entity_id:!0}:{},..."string"==typeof e.description&&e.description.trim()?{description:e.description.trim()}:{}};if("object"===a){if(!s1(e.properties))throw Error(`${o} requires object properties`);if(p.properties=Object.fromEntries(Object.entries(e.properties).map(([e,i])=>[e,s2(i,t,r,`${n}.${e}`)])),void 0!==e.required){if(!Array.isArray(e.required)||e.required.some(e=>"string"!=typeof e))throw Error(`${o} required must be a string array`);p.required=e.required}}if("array"===a){if(!s1(e.items))throw Error(`${o} requires object array items`);p.items=s2(e.items,t,r,`${n}[]`)}return p}function s4(e,t,r){let n=e[t];if(void 0===n)return{};if(!s1(n))throw Error(`manifest.yaml ${t} must be an object: ${r}`);return{...n}}function s5(e,t){if(!to.existsSync(e)||!to.statSync(e).isFile())throw Error(`${t} does not exist: ${e}`);return to.readFileSync(e,"utf8")}class s9{pluginSystem;rootPath="dist";context;appDirectory;_userConfig;_appConfig;_appConfigLoaded=!1;_env={};constructor(e=process.cwd()){this.appDirectory=e}async prepare(e,t={},r){let n=this.context;try{let n=Date.now(),i=await this.getUserConfig(t),o={...await this.getAppConfig(),...t.appName?{name:t.appName}:{},...t.appIcon?{icons:tF(t.appIcon)}:{}},a={pages:sP(o?.pages,"pages"),tools:sP(o?.tools,"tools"),widgets:sP(o?.widgets,"widgets")},s=function(e){let t=ta.join(e,"events.json");if(to.existsSync(t)&&to.statSync(t).isFile())return{readJson:()=>to.readFileSync(t,"utf8"),sourcePath:t}}(this.appDirectory),l=function({appDirectory:e,normalizedAppConfig:t}){let r=ta.join(e,"tools.json");if(!to.existsSync(r))return;let n=ta.join(e,"manifest.yaml"),i=()=>s5(r,"tools.json"),o=()=>(function({tools:e,manifestPath:t,manifestText:r}){let n=function(e,t){let r;try{r=(0,sY.qg)(e)}catch(e){throw Error(`Failed to parse manifest.yaml: ${t}`,{cause:e})}if(!s1(r))throw Error(`manifest.yaml must contain an object: ${t}`);return r}(r,t),i=s4(n,"tools",t),o=s4(n,"entities",t);for(let t of e){if(t.name in i)throw Error(`Tool "${t.name}" conflicts with a tool in manifest.yaml`);if(i[t.name]={login_type:"no_login",description:t.description,..."client"===t.toolType?{is_client_tool:!0}:{},input_schema:function(e,t){if("object"!==e.type||!s1(e.properties))throw Error(`Tool "${t}" inputSchema requires type object and object properties`);let r=Object.fromEntries(Object.entries(e.properties).map(([e,r])=>[e,s2(r,t,"inputSchema",e)])),n=e.required;if(void 0!==n&&(!Array.isArray(n)||n.some(e=>"string"!=typeof e)))throw Error(`Tool "${t}" inputSchema required must be a string array`);return{type:"object",properties:r,...n&&n.length>0?{required:n}:{}}}(t.inputSchema,t.name),output:t.widgetId?{kind:"entities",entity_types:[t.name]}:{kind:"execution_result"},...t.permissions.length>0?{permissions:t.permissions}:{}},t.widgetId){if(t.name in o)throw Error(`Tool "${t.name}" conflicts with an entity in manifest.yaml`);o[t.name]={schema:{entity_type:{type:"string",llm_visible:!1},...function(e,t){let r=t.name;if("array"!==e.type||!s1(e.items))throw Error(`Card Tool "${r}" outputSchema must be an array`);if("object"!==e.items.type||!s1(e.items.properties))throw Error(`Card Tool "${r}" outputSchema items must be objects`);let n=e.items.properties,i=s0.find(e=>e in n);if(i)throw Error(`Tool "${r}" outputSchema must not declare reserved field "${i}"`);let o=Object.entries(n).filter(([e,t])=>{if(!s1(t)||void 0===t[sZ])return!1;if("boolean"!=typeof t[sZ])throw Error(`Tool "${r}" outputSchema property "${e}" ${sZ} must be a boolean`);return t[sZ]});if(1!==o.length)throw Error(`Card Tool "${r}" outputSchema requires exactly one ${sZ} field; found ${o.length}`);let a=Object.entries(n).filter(([e,t])=>{if(!s1(t)||void 0===t[sQ])return!1;if("boolean"!=typeof t[sQ])throw Error(`Tool "${r}" outputSchema property "${e}" ${sQ} must be a boolean`);return t[sQ]});if("same_conversation"===t.expirePolicy){let e=o[0]?.[0];if(1!==a.length||a[0]?.[0]!==e)throw Error(`Card Tool "${r}" with expirePolicy "same_conversation" requires ${sQ} on its ${sZ} field`)}return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,s2(t,r,"outputSchema",e,!0)]))}(t.outputSchema,t)},tool_card_binding:{[t.name]:t.widgetId},..."same_conversation"===t.expirePolicy?{history_card_refresh:{enabled:!0,scope:"same_conversation",refresh_to:"fixed_style"}}:{}}}}return(0,sY.As)({...n,tools:i,entities:o})})({tools:(()=>{let e=function(e,t){let r;try{r=JSON.parse(e)}catch(e){throw Error(`Failed to parse tools.json: ${t}`,{cause:e})}if(!s1(r)||!Array.isArray(r.tools)||0===r.tools.length)throw Error(`tools.json requires a non-empty tools array: ${t}`);let n=new Set;return{tools:r.tools.map((e,r)=>{let i=function(e,t,r){if(!s1(e))throw Error(`Tool at index ${t} must be an object: ${r}`);let n="string"==typeof e.name?e.name.trim():"",i="string"==typeof e.description?e.description.trim():"";if(!n||!i)throw Error(`Tool at index ${t} requires name and description: ${r}`);if(void 0!==e.tool_type&&"client"!==e.tool_type&&"server"!==e.tool_type)throw Error(`Tool "${n}" tool_type must be "client" or "server"`);let o=function(e,t){if(void 0===e)return{};if(!s1(e))throw Error(`Tool "${t}" _meta must be an object`);if(void 0===e.ui)return{};if(!s1(e.ui))throw Error(`Tool "${t}" _meta.ui must be an object`);if("widgetPath"in e.ui)throw Error(`Tool "${t}" must use _meta.ui.widgetId instead of widgetPath`);let r=e.ui.widgetId;if(void 0!==r&&("string"!=typeof r||!r.trim()))throw Error(`Tool "${t}" _meta.ui.widgetId must be a non-empty string`);let n=e.ui.expirePolicy;if(void 0!==n&&"same_conversation"!==n)throw Error(`Tool "${t}" _meta.ui.expirePolicy must be "same_conversation" when provided`);if("same_conversation"===n&&"string"!=typeof r)throw Error(`Tool "${t}" _meta.ui.expirePolicy requires _meta.ui.widgetId`);return{..."string"==typeof r?{widgetId:r.trim()}:{},..."same_conversation"===n?{expirePolicy:n}:{}}}(e._meta,n);return{name:n,description:i,...o,inputSchema:s3(e.inputSchema,"inputSchema",n),outputSchema:s3(e.outputSchema,"outputSchema",n),permissions:function(e,t){if(void 0===e)return[];if(!Array.isArray(e)||e.some(e=>"string"!=typeof e||!e.trim()))throw Error(`Tool "${t}" permissions must be an array of non-empty strings`);return e.map(e=>e.trim())}(e.permissions,n),toolType:"client"===e.tool_type?"client":"server"}}(e,r,t);if(n.has(i.name))throw Error(`Duplicate Tool name: ${i.name}`);return n.add(i.name),i})}}(i(),r);var n=e.tools;let o=new Set(t.widgets.entryNames.map(e=>t.widgets.entries[e]?.id??rt(e)));for(let e of n)if(e.widgetId&&!o.has(e.widgetId))throw Error(`Tool "${e.name}" references widgetId "${e.widgetId}" not declared in app.config.ts`);return e})().tools,manifestPath:n,manifestText:s5(n,"manifest.yaml")});return o(),{manifestSourcePath:n,readManifestYaml:o,readToolsJson:i,toolsSourcePath:r}}({appDirectory:this.appDirectory,normalizedAppConfig:a}),d=function(e){if(e)return!0===e?{mcpEndpoint:ty()}:{...e,mcpEndpoint:ty({mcpEndpoint:e.mcpEndpoint})}}(t.openWebDebugger),p=Date.now()-n;this.rootPath=ta.resolve(this.appDirectory,"dist"),to.existsSync(ta.resolve(this.rootPath))&&to.rmSync(ta.resolve(this.rootPath),{recursive:!0,force:!0}),this.context=new sJ,aO(this.context.compileLifecycle,n),this.context.compileLifecycle.prepareDurations.configLoadMs=p;let c=ta.resolve(this.appDirectory,"src"),u=Date.now(),{pages:h,widgets:m,auth:f,app:g,tools:y}=await this.analyzeConvention(c,a);this.context.compileLifecycle.prepareDurations.projectScanMs=Date.now()-u;let b=new tK,_=((e=process.cwd())=>tc(e)===ts)(this.appDirectory),v=Date.now();await this.context.bootstrap({srcDirectory:c,appDirectory:this.appDirectory,rootPath:this.rootPath,userConfig:i,env:this._env,appConfig:o,normalizedAppConfig:a,command:e,metadata:b,signingEncryptionOptions:t.signingEncryptionOptions,skipAppInfoFetch:!!t.token,permissions:t.permissions,appId:t.appId,versionTag:t.versionTag,pages:h,widgets:m,auth:f,app:g,tools:y,internal:_,devServerInteractive:t.interactive,loginCookieResolver:()=>sI(t,{internal:_}),cachedLoginCookieResolver:()=>sO(t,_)}),this.context.compileLifecycle.prepareDurations.contextBootstrapMs=Date.now()-v,(e===ej.DEV||void 0!==t.host)&&(this.context.devServerHost=await sV(t.host)),this.context.webDebuggerLaunchOptions=d,this.context.eventsResources=s,this.context.toolsResources=l,this.pluginSystem=new t4(this.context,[sS,s_,sE,sm,sT,sg,sx,sy,...i.experiments?.taro?[function({name:e,appId:t,icons:r,widgets:n}){return{name:rd,setup:i=>{let o=(0,rl.createRequire)(import.meta.url);i.view.hooks.modifyEntryOption.tapPromise({name:rd,stage:i.view.MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY},async({entry:e})=>{let{appDirectory:t,isDev:r,pages:n,widgets:o}=i.context,a=rs(n,t,!1,r);return{entry:e=Object.assign(e,a,rs(o,t,!0,r))}}),i.view.hooks.beforeBuild.tapPromise({name:rd,stage:i.view.BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG},async({buildConfig:e})=>{let{appDirectory:t}=i.context;ri(e,{resolve:{alias:{"@tarojs/components":o.resolve("@doubao-dev/taro-runtime/components",{paths:[t]}),"@tarojs/taro":(0,eX.dirname)(o.resolve("@doubao-dev/taro-runtime/package.json",{paths:[t]}))}}})}),i.worker.hooks.modifyEntryOption.tapPromise({name:rd,stage:i.worker.MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE},async({entry:r})=>{let{appDirectory:n,isDev:o}=i.context,{app:a}=i.context;return a&&(r.app=function(e,t,r,n,i=!1){var o;let a=`${eZ}${ta.sep}app.js`,s=(o=ro(ta.dirname(a),e)).startsWith(".")?o:`./${o}`,l=tu(t);return new ra(a,`
292
+ bootstrapClientToolRuntime([${a.join(", ")}]);
293
+ `)}(`${e.context.appDirectory}${t_.sep}${ez}${t_.sep}${e5}.js`,o,e.context.appDirectory,i)),{entry:t}}),e.worker.hooks.modifyEnvironment.tapPromise("AppletMainPlugin",async({environment:e})=>{}),e.worker.hooks.collectMetaData.tapPromise({name:"AppletMainPlugin",stage:e.worker.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:t})=>{let{app:r,appConfig:n,tools:i,userConfig:s}=e.context;await a$({appConfig:n,tools:i,app:r,collector:t,define:s.source?.define}),e.context.setVersionTag(e.context.metadata.app.version)}),e.assets.hooks.beforeEmit.tapPromise({name:"AppletMainPlugin",stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:t,chunks:r})=>{var n,i;let{app:s,pages:o,tools:a}=e.context.metadata.getInstance(),l=t.getAsset(e.context.appAssetPath),c=r[e5]?.find(({source:e})=>e.endsWith(".js")),p=t.getManifestAsset(e.context.manifestAssetPath),{manifest:d}=p,u=[];d.applet.pages.forEach(e=>{u.push(e.digest)});let m=s.metadata.appId,h=e.context.versionTag;p.assignBasicManifest({manifestVersion:"3.0",packageName:m,appId:m,versionName:h,versionTag:h,scmVersion:process.env.BUILD_VERSION,versionCode:Date.now().toString(),runtimeVersion:"1.0",sourceType:e.context.internal?1:2,settings:e.context.manifestSettings});let f=e.context.appAssetPath,g=e.context.normalizedAppConfig.pages.entryNames[0]??Object.keys(e.context.pages)[0],y=g?o[g]?.metadata.path:void 0,b=s.toManifest({toolsMetadata:a,hashCode:l?.hashCode??(n=l?.hashCode??d?.applet?.digest,i=u.join(""),oG.createHash("sha256").update(n+i).digest("hex").substring(0,8)),appRuntimeEntry:f,appRuntimeType:e.context.environment.useLynx?"lynx":"js"});c&&(b.toolRuntimeEntry=c.source),p.mergeAppletManifest(b),y&&p.mergeAppletManifest({appletEntry:y})}),e.assets.hooks.afterEmit.tapPromise({name:"AppletMainPlugin",stage:e.assets.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:e})=>{}),e.worker.hooks.afterBuild.tapPromise("AppletMainPlugin",async({stats:e})=>{}))}},aN={name:"AppletMainEntryCheckPlugin",setup:async e=>{let{srcDirectory:t}=e.context,r=ab(t);if(!tV.existsSync(r))throw Error("ENOENT: no such file or directory")}},aL={name:"AppletManifestPlugin",setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:"AppletManifestPlugin",stage:e.assets.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS},async({assets:t})=>{let{signing:r}=await e.context.resolveSigningEncryptionOptions()||{};if(r?.enabled){let{signData:n}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),i=t.getManifestAsset(e.context.manifestAssetPath),{manifest:s}=i,{buffer:o,status:a,error_msg:l}=await n(Buffer.from(i.content),tZ(r,{extra_config:{app_id:s.appId,bundle_id:""},output_mode:"sign_block"}));if(0!==a)throw Error(l);let c=new oV(e0,o);c.destination=e0,t.addAsset(e0,c)}})}},aD="AppletWebManifestPlugin",aj={name:aD,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:aD,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-2},async({assets:t})=>{var r,n;let i=e.context.metadata.getData(),s=i.app.appId||e.context.appId,o=e.context.command===eD.DEV?"all":"configured",a=rg(e.context.pages,e.context.normalizedAppConfig.pages.entries,o),l=rg(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,o);if(!s&&Object.keys(a).length>0)throw Error("解析 Web 页面入口路径需要 appId");let c=s?(r=i.pages,Object.keys(a).map(e=>{let t=r[e]??{},n=t.path??tY(e),i={entry:tX(s,n,rp)},o=rf(a[e]);return{path:n,entryName:e,web:i,debugHidden:o,manifest:{...t,path:n,digest:"",entry:"",renderType:H.LYNX,web:i,...o?{debugHidden:!0}:{}}}})):[],p=(n=i.widgets,Object.keys(l).map(e=>{let{id:t,...r}=n[e]??{},i=t??rh(l,n,e),s={entry:`${i}/${rp}`},o=rf(l[e]);return{id:i,entryName:e,web:s,debugHidden:o,manifest:{...r,widgetId:i,digest:"",entry:"",renderType:H.LYNX,web:s,...o?{debugHidden:!0}:{}}}}));if(0===c.length&&0===p.length&&0===e.context.normalizedAppConfig.tools.entryNames.length)return;let d=t.getManifestAsset(e.context.manifestAssetPath),u=new Map(c.map(e=>[e.path,e])),m=new Set(d.manifest.applet.pages?.map(e=>e.path));for(let e of(d.manifest.applet.pages?.forEach(e=>{let t=u.get(e.path);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),c))m.has(e.path)||d.appendPage(e.manifest);let h=new Map(p.map(e=>[e.id,e])),f=new Set(d.manifest.widgets?.map(e=>e.widgetId));for(let t of(d.manifest.widgets?.forEach(e=>{let t=h.get(e.widgetId);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),p))if(!f.has(t.id)){let r=t.manifest;e.context.templateWidgetEntries.has(t.entryName)&&(r.titleType=F.NONE),d.appendWidget(r)}e.context.app&&(d.manifest.applet.web={appRuntimeEntry:rd,...e.context.normalizedAppConfig.tools.entryNames.length>0?{toolRuntimeEntry:ru}:{}})})}};function aM(e=((e=process.cwd())=>t4(e)===t0)()){return e?"sso":"sms"}async function aU(e={},t={}){if(e.cookie)return e.cookie;let{ensureLoginCookie:r}=await import("./@byted-doubao-apps/login~1.js");return await r({route:aM(t.internal),browser:e.loginBrowser,browserPath:e.loginBrowserPath,force:t.force})}async function aB(e,t){if(e.cookie)return e.cookie;let{getCachedLoginCookie:r}=await import("./@byted-doubao-apps/login~1.js");return await r({route:aM(t)})}function aF(e,t){let r;if(!e)return{entryNames:[],entries:{}};if(Array.isArray(e))r=e;else if("object"==typeof e)t&&tp.warn(`${t} 的对象映射配置已弃用,请改用由字符串或 { entry, ...metadata } 对象组成的数组。`),r=Object.entries(e).map(([e,t])=>{let r;return{...t,entry:(r=e.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"")).endsWith("/index")?r:`${r}/index`}});else throw Error("入口配置必须是数组或对象映射。");let n=[],i={},s=new Set,o=[],a=new Set;return r.forEach(e=>{let t,r;if("string"==typeof e)t=e,r={};else{let{entry:n,...i}=e;if(!n)throw Error('入口配置对象必须包含 "entry"。');t=n,r=i}s.has(t)?a.has(t)||(o.push(t),a.add(t)):(n.push(t),s.add(t)),i[t]=r}),t&&o.length>0&&tp.warn(`${t} 配置中存在重复入口:${o.join(", ")}。已合并重复入口,以最后一次的元数据配置为准。`),{entryNames:n,entries:i}}class aH{constructor(){this.deploy={},this._isInitialized=!1,this._environment={useLynx:!1,useAuth:!1},this._srcDirectory="",this._virtualEntryDir="",this._appDirectory=process.cwd(),this._rootPath="",this._appAssetPath="",this._appMapAssetPath="",this._manifestPath="",this._widgets={},this._app="",this._tools={},this._cookie="",this._pages={},this._auth={viewEntries:{},apiEntries:{}},this._viewEntriesByType={}}async bootstrap({command:e,metadata:t,versionTag:r,srcDirectory:n="",virtualEntryDir:i="",appDirectory:s=process.cwd(),rootPath:o="",manifestPath:a="",pages:l={},widgets:c={},auth:p,mcpUI:d,app:u="",tools:m={},environment:h={useLynx:!1,useAuth:!1},viewEntriesByType:f={},loginCookieResolver:g,cachedLoginCookieResolver:y}){this._command=e,this._metadata=t,this._versionTag=r,this._srcDirectory=n,this._virtualEntryDir=i,this._appDirectory=s,this._rootPath=o,this._manifestPath=a,this._pages={...l},this._widgets={...c};let b=p??d??{viewEntries:{},apiEntries:{}};this._auth={viewEntries:{...b.viewEntries},apiEntries:{...b.apiEntries}},this._app=u,this._tools={...m},this._environment={useLynx:h.useLynx,useAuth:!!(h.useAuth||h.useMcpUI)},this._cookie="",this._loginCookieResolver=g,this._loginCookiePromise=void 0,this._cachedLoginCookieResolver=y,this._viewEntriesByType=Object.fromEntries(Object.entries(f).map(([e,t])=>[e,{pages:{...t.pages},widgets:{...t.widgets}}])),this._isInitialized=!0}assertInitialized(e){if(!this._isInitialized)throw Error(`BuildContext.${e} is unavailable before bootstrap`)}get isDev(){return this.assertInitialized("isDev"),this._command===eD.DEV}get command(){return this.assertInitialized("command"),this._command}get metadata(){return this.assertInitialized("metadata"),this._metadata}get manifestPath(){return this.assertInitialized("manifestPath"),this._manifestPath}get appDirectory(){return this._appDirectory}get virtualEntryDir(){return this.assertInitialized("virtualEntryDir"),this._virtualEntryDir}get srcDirectory(){return this.assertInitialized("srcDirectory"),this._srcDirectory}get rootPath(){return this.assertInitialized("rootPath"),this._rootPath}get manifest(){if(this._manifest)return{...this._manifest};try{return this._manifest=JSON.parse(tV.readFileSync(this._manifestPath,"utf-8")),{...this._manifest}}catch(e){return{}}}get useLynx(){return this._environment.useLynx}get useAuth(){return this._environment.useAuth}get useMcpUI(){return this.useAuth}get manifestAssetPath(){return eQ}get appAssetPath(){return this._appAssetPath}get appMapAssetPath(){return this._appMapAssetPath}get environment(){return{...this._environment}}get widgets(){return{...this._widgets}}get pages(){return{...this._pages}}get auth(){return{viewEntries:{...this._auth.viewEntries},apiEntries:{...this._auth.apiEntries}}}get mcpUI(){return this.auth}get viewEntriesByType(){return Object.fromEntries(Object.entries(this._viewEntriesByType).map(([e,t])=>[e,{pages:{...t.pages},widgets:{...t.widgets}}]))}get app(){return this._app}get tools(){return{...this._tools}}async getLoginCookie(){return(this.assertInitialized("getLoginCookie"),this._cookie)?this._cookie:this._loginCookieResolver?(this._loginCookiePromise||(this._loginCookiePromise=this._loginCookieResolver().then(e=>(this._cookie=e??"",e)).catch(e=>{throw this._loginCookiePromise=void 0,e})),await this._loginCookiePromise):void 0}async getCachedLoginCookie(){if(this.assertInitialized("getCachedLoginCookie"),this._cookie)return this._cookie;if(!this._cachedLoginCookieResolver)return;let e=await this._cachedLoginCookieResolver();return e&&(this._cookie=e),e}get appId(){return this._appId||this._metadata.appId}setAppId(e){this._appId=e}setApp(e){this._app=e}setTools(e){this._tools=e}setEnvironment(e){this._environment={...e}}mergeEnvironment(e){this._environment={...this._environment,...e}}setPages(e){this._pages=e}setWidgets(e){this._widgets=e}appendPages(e){Object.assign(this._pages,e)}appendWidgets(e){Object.assign(this._widgets,e)}getViewEntriesByType(e){let t=this._viewEntriesByType[e];return t?{pages:{...t.pages},widgets:{...t.widgets}}:{pages:{},widgets:{}}}setViewEntriesByType(e,t){this._viewEntriesByType[e]={pages:{...t.pages},widgets:{...t.widgets}}}setAppAssetPath(e){this._appAssetPath=e}setAppMapAssetPath(e){this._appMapAssetPath=e}setManifest(e){this._manifest=e}setVersionTag(e){return this.assertInitialized("versionTag"),!this._versionTag&&e&&(this._versionTag=e),this._versionTag}setAuthApi(e){this._auth={viewEntries:{...e.viewEntries},apiEntries:{...e.apiEntries}}}setMcpUIApi(e){this.setAuthApi(e)}get versionTag(){return this.assertInitialized("versionTag"),this._versionTag}}async function aW({internal:e,domainId:t,appLimit:r,appOffset:n,keyWord:i,appKey:s,cookie:o}){return await n5({internal:e,domainId:t,path:"/app_developer/api/apps",query:{app_limit:r,app_offset:n,key_word:i,app_key:s},method:"GET",headers:o?{Cookie:o}:void 0})}async function aG({source:e,internal:t,domainId:r,appLimit:n,appOffset:i,releaseStatus:s,keyWord:o,appKey:a,cookie:l}){return await n5({internal:t,domainId:r,path:"/developer/api/apps",query:{source:e,app_limit:n,app_offset:i,release_status:s,key_word:o,app_key:a},method:"GET",headers:l?{Cookie:l}:void 0})}async function aV({appKey:e,source:t,internal:r,domainId:n,releaseStatus:i,limit:s,offset:o,status:a,keyWord:l,versionTag:c,cookie:p}){return await n5({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/version`,query:{source:t,release_status:i,limit:s,offset:o,status:a,key_word:l,version_tag:c},method:"GET",headers:p?{Cookie:p}:void 0})}async function aq({appKey:e,versionTag:t,internal:r,domainId:n,pageSize:i,pageNum:s,cookie:o}){return await n5({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/permission/versions/${encodeURIComponent(t)}/permission_list`,query:{page_size:i,page_num:s},method:"GET",headers:o?{Cookie:o}:void 0})}function aJ(e){return e.is_latest||e.is_current}function az(e){return Date.parse(e.updated_at??e.created_at??e.online_at??"")}function aK(e){return Number(e.version_code??e.qr_data?.artifact_version_code)}function aY(e){return e.version_tag}function aX(e,t){eb()&&tp.info(e,t)}async function aZ({appKey:e,internal:t=!1,cookie:r,source:n=eG.REQUEST_SOURCE_IDE}){aX("[app-info] 开始获取应用信息",{appKey:e,internal:t,session:r?"present":"absent"});let i=await aW({internal:t,appLimit:1,appOffset:0,appKey:e,cookie:r}).then(({data:t,log_id:r})=>{let n=t?.app_list||[],i=n.find(t=>t.app_key===e);return aX("[app-info] MGetApps 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),i}).catch(t=>{if(aX("[app-info] MGetApps 请求失败",{appKey:e,reason:an(t)}),of(t))throw t}),s=i?void 0:await aG({source:n,internal:t,appLimit:1,appOffset:0,appKey:e,cookie:r}).then(({data:t,log_id:r})=>{let n=t?.org_list?.flatMap(e=>e.app_list)||[],i=n.find(t=>t.app_key===e),s=i||n[0];return aX("[app-info] MGetAppsDeprecated 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),s?.app_meta}).catch(t=>{aX("[app-info] MGetAppsDeprecated 请求失败",{appKey:e,reason:an(t)})});if(!i&&!s)throw aX("[app-info] 应用信息查询结束,未找到可用结果",{appKey:e}),Error(`未找到应用 ${e}`);let o=i?void 0:await aV({appKey:e,source:n,internal:t,cookie:r}).then(({data:t,log_id:r})=>{let n=Array.isArray(t?.version_list)?t.version_list:[];if(aX("[app-info] MGetAppVersions 请求完成",{appKey:e,versionCount:n.length,logId:r}),0===n.length)return;let i=n.find(aJ);return i||n.reduce((e,t)=>{let r,n;return!e||(r=az(t),n=az(e),(Number.isNaN(r)&&Number.isNaN(n)?aK(t)-aK(e):(Number.isNaN(r)?-1/0:r)-(Number.isNaN(n)?-1/0:n))>0)?t:e},void 0)}).catch(t=>{aX("[app-info] MGetAppVersions 请求失败",{appKey:e,reason:an(t)})}),a=i?.current_version_tag||(o?aY(o):""),l=i?.icon_url||(o?o.icon_url:void 0)||s?.icon_url,c=i?.name||s?.name,p=o&&aY(o)===a?o:i?{version_tag:i.current_version_tag,icon_url:i.icon_url,updated_at:i.updated_at,online_at:i.online_at,offline_at:i.offline_at}:{version_tag:a,icon_url:l};if(i||!a||!r)return{appKey:e,appName:c,versionTag:a,iconUrl:l,permissionList:[],permissionTotal:0,version:p};let d=await aq({appKey:e,versionTag:a,pageSize:1e3,pageNum:1,internal:t,cookie:r}).then(t=>(aX("[app-info] FetchAppPermissionList 请求完成",{appKey:e,versionTag:a,permissionTotal:t.data?.total||0,logId:t.log_id}),t)).catch(t=>{throw aX("[app-info] FetchAppPermissionList 请求失败",{appKey:e,versionTag:a,reason:an(t)}),t});return{appKey:e,appName:c,versionTag:a,iconUrl:l,permissionList:d.data?.permission_list||[],permissionTotal:d.data?.total||0,version:p}}function aQ(){return function({fetch:e,getCacheKey:t,ttl:r,timeout:n,cacheFailures:i=!1,now:s=Date.now}){let o=new Map;return function(...a){var l,c;let p,d="string"==typeof(l=t(...a))?l:JSON.stringify(l),u=s(),m=o.get(d);if(m&&m.expiresAt>u)return m.promise;let h=(c=e(...a),void 0===n?c:Promise.race([c,new Promise((e,t)=>{p=setTimeout(()=>{t(Error(`Request timed out after ${n}ms`))},n)})]).finally(()=>{p&&clearTimeout(p)})).catch(e=>{throw i||o.get(d)?.promise!==h||o.delete(d),e});return o.set(d,{expiresAt:u+r,promise:h}),h}}({fetch:aZ,getCacheKey:({appKey:e,internal:t,cookie:r})=>[e,t,r],ttl:6e4,timeout:1e4,cacheFailures:!0})}function a0(){let e=Object.entries(rw.networkInterfaces()),t=[];for(let[r,n]of e){if(!n)continue;let e=/^(?:utun|tun|tap|ppp|ipsec|wg|docker|vboxnet|vmnet|awdl|llw|tailscale|zt)/i.test(r)||/^(?:br-|bridge\d|virbr\d|veth)/i.test(r)||/(?:vEthernet|Hyper-V|Docker|VirtualBox|VMware|WireGuard|Tailscale|ZeroTier|VPN)/i.test(r),i=/^(?:en\d+|eth\d+|eno\d+|enp\w+|wl\w+)$|^(?:Ethernet|Wi-?Fi|WLAN|以太网|无线网络连接)(?:\s|$)/i.test(r);for(let r of n){let{address:n,family:s,internal:o}=r;if(!o&&"IPv4"===s){let r=n.startsWith("169.254.")?3:e?2:+!i;t.push({address:n,priority:r})}}}return t.sort((e,t)=>e.priority-t.priority),[...new Set(t.map(({address:e})=>e))]}async function a1(e="0.0.0.0"){if(!e||e.includes(":"))throw Error("--host 必须是 IPv4 地址或主机名,不能包含协议或端口;暂不支持 IPv6。");let{address:t}=await (0,x.lookup)(e,{family:4});if("0.0.0.0"!==t)return t;let r=a0()[0];return r||(th.warn("未找到外部 IPv4 地址,将使用 127.0.0.1,仅支持本机访问。"),"127.0.0.1")}async function a2(e,t,r){let n=await fetch(`${e}/base/manifest.json`,{signal:AbortSignal.any([r,AbortSignal.timeout(1500)]),redirect:"error"}),i=await n.json();if(!n.ok||t&&i?.appId!==t)throw Error(`开发服务器返回的 manifest 无效:${e}(HTTP ${n.status},appId:${t})`)}async function a3(e,t,r,n){let i,s=function(e,t=a0()[0]??"127.0.0.1"){return`http://${t}:${e}`}(e,t),o=AbortSignal.any([n,AbortSignal.timeout(5e3)]);try{for(;;)try{await a2(s,r,o);break}catch(e){i=e,await (0,v.setTimeout)(200,void 0,{signal:o})}}catch{throw n.throwIfAborted(),Error(`开发服务器的 manifest 在 5 秒内未就绪:${s}/base/manifest.json。请检查网络,或使用 --host <IP> 指定设备可访问的本机 IP`,{cause:i})}return{host:s,artifactOrigin:s}}(eR=eF||(eF={}))[eR.APP_TYPE_MINI_APP=0]="APP_TYPE_MINI_APP",eR[eR.APP_TYPE_NATIVE=1]="APP_TYPE_NATIVE",(e$=eH||(eH={}))[e$.DRAFT=0]="DRAFT",e$[e$.UNDER_REVIEW=1]="UNDER_REVIEW",e$[e$.APPROVED=2]="APPROVED",e$[e$.REJECTED=3]="REJECTED",e$[e$.WITHDRAWN=4]="WITHDRAWN",e$[e$.PUBLISHING=5]="PUBLISHING",e$[e$.PUBLISHED=6]="PUBLISHED",e$[e$.ARCHIVED=7]="ARCHIVED",e$[e$.DELETED=8]="DELETED",(ek=eW||(eW={}))[ek.DRAFT=0]="DRAFT",ek[ek.PUBLISHED=1]="PUBLISHED",ek[ek.ARCHIVED=2]="ARCHIVED",(eN=eG||(eG={}))[eN.REQUEST_SOURCE_PLATFORM=0]="REQUEST_SOURCE_PLATFORM",eN[eN.REQUEST_SOURCE_IDE=1]="REQUEST_SOURCE_IDE",eN[eN.REQUEST_SOURCE_DEVICE=2]="REQUEST_SOURCE_DEVICE",eN[eN.REQUEST_SOURCE_OP_PLATFORM=3]="REQUEST_SOURCE_OP_PLATFORM";class a4 extends aH{devServerInteractive=!0;devServerHost="0.0.0.0";devServerAbort=new AbortController;finishInitialDevCompile;initialDevCompile=new Promise(e=>{this.finishInitialDevCompile=e,this.devServerAbort.signal.addEventListener("abort",()=>e(void 0),{once:!0})});devServerResolution;resolveDevServer(e){return this.devServerResolution??=this.initialDevCompile.then(t=>{if(t)throw t;return this.devServerAbort.signal.throwIfAborted(),a3(e,this.devServerHost,this.appId,this.devServerAbort.signal)})}getWidgetViewDataTemplates;webDebuggerLaunchOptions;compileLifecycle=oj();eventsResources;toolsResources;manifestSettings;_userConfig={};_env={};_appConfig={};_normalizedAppConfig={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}};_signingEncryptionOptions;_rawSigningEncryptionOptions;_signingEncryptionOptionsPromise;_disableSigningEncryption=!1;_dek=Buffer.from("");_internal=!1;_fetchCachedAppInfo=aQ();_skipAppInfoFetch=!1;_hasWarnedAppInfoFetchFailure=!1;_templateWidgetEntries=new Set;_permissions;get userConfig(){return this._userConfig}get env(){return{...this._env}}get appConfig(){return this._appConfig}get normalizedAppConfig(){var e;return{pages:{entryNames:[...(e=this._normalizedAppConfig).pages.entryNames],entries:Object.fromEntries(Object.entries(e.pages.entries).map(([e,t])=>[e,{...t}]))},tools:{entryNames:[...e.tools.entryNames],entries:Object.fromEntries(Object.entries(e.tools.entries).map(([e,t])=>[e,{...t}]))},widgets:{entryNames:[...e.widgets.entryNames],entries:Object.fromEntries(Object.entries(e.widgets.entries).map(([e,t])=>[e,{...t}]))}}}get templateWidgetEntries(){return new Set(this._templateWidgetEntries)}get permissions(){return this._permissions?.map(e=>({...e}))}get signingEncryptionOptions(){if(this._signingEncryptionOptions)return{...this._signingEncryptionOptions,encryption:{...this._signingEncryptionOptions?.encryption,dek:this.dek}}}get dek(){return this._dek}get isSignedEncryption(){return this.signingEncryptionOptions?.signing.enabled||this.signingEncryptionOptions?.encryption.enabled}get internal(){return this.assertInitialized("internal"),this._internal}setSigningEncryptionOptions(e){this._rawSigningEncryptionOptions=e,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0}disableSigningEncryption(){this._disableSigningEncryption=!0,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._dek=Buffer.from("")}addTemplateWidgetEntry(e){this._templateWidgetEntries.add(e)}async resolveSigningEncryptionOptions(){return this._signingEncryptionOptionsPromise||(this._signingEncryptionOptionsPromise=this.resolveSigningEncryptionOptionsOnce()),this._signingEncryptionOptionsPromise}async resolveAppInfo(){this.assertInitialized("resolveAppInfo");let e=this.compileLifecycle.appInfoMeasured?void 0:Date.now();this.compileLifecycle.appInfoMeasured=!0;try{return await this.resolveAppInfoInternal()}finally{void 0!==e&&(this.compileLifecycle.appInfoDurationMs=Math.max(0,Date.now()-e))}}async resolveAppInfoInternal(){var e;let t=this.appId;if(!oh(t))return;let r="string"==typeof(e=this._appConfig.icons)?e.length>0?e:void 0:e?.["3x"]||e?.["2x"]||e?.["1x"],n={appKey:t,versionTag:this.versionTag??"",permissionList:[],permissionTotal:0,version:{},...this._appConfig.name?{appName:this._appConfig.name}:{},...r?{iconUrl:r}:{}};if(this._skipAppInfoFetch)return n;let i=await this.getCachedLoginCookie().catch(()=>void 0);try{return Object.assign(n,await this._fetchCachedAppInfo({appKey:t,cookie:i,internal:this.internal})),n.appName||=this._appConfig.name,n.iconUrl||=r,n}catch(e){if(this.command!==eD.DEV&&this.command!==eD.BUILD)throw e;if(of(e))return n;return this._hasWarnedAppInfoFetchFailure||(this._hasWarnedAppInfoFetchFailure=!0,tp.warn("从平台获取 Doubao 应用信息失败,将使用本地 `app.config.ts` 配置的数据",{reason:an(e)})),n}}async bootstrap({srcDirectory:e,appDirectory:t,rootPath:r,userConfig:n,appConfig:i={},normalizedAppConfig:s={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}},command:o,metadata:a,signingEncryptionOptions:l,disableSigningEncryption:c,appId:p,versionTag:d,pages:u,widgets:m,auth:h,app:f,tools:g,internal:y,skipAppInfoFetch:b,permissions:_,devServerInteractive:v=!0,env:E={},loginCookieResolver:w,cachedLoginCookieResolver:S}){await super.bootstrap({srcDirectory:e,appDirectory:t,virtualEntryDir:t_.resolve(t,ez),rootPath:r,manifestPath:t_.resolve(`${r}/${eQ}`),command:o,metadata:a,versionTag:d,pages:u,widgets:m,auth:h,app:f,tools:g,loginCookieResolver:w,cachedLoginCookieResolver:S});let{icons:x,...A}=i??{};this._userConfig=n,this.devServerInteractive=v,this._env={...E},this._appConfig={...A,...void 0!==p?{appId:p}:{},...void 0!==x?{icons:tx(x)}:{}},this._normalizedAppConfig=s,this._internal=y??((e=process.cwd())=>t4(e)===t0)(t),this._skipAppInfoFetch=!!b,this._permissions=_?.map(e=>({...e})),this._hasWarnedAppInfoFetchFailure=!1,this._templateWidgetEntries=new Set,this._rawSigningEncryptionOptions=l,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._disableSigningEncryption=!!c,this._appId=p??i?.appId,this._dek=Buffer.from(""),this._fetchCachedAppInfo=aQ()}async resolveSigningEncryptionOptionsOnce(){let e=this._appId??this.metadata.appId;if(this._signingEncryptionOptions=await ao(this._rawSigningEncryptionOptions,this.command,e,this._disableSigningEncryption),this._signingEncryptionOptions?.encryption.enabled){let{generateDEK:e}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)});this._dek=e(),eb()&&console.log("DEK base64:",Buffer.from(this.dek.buffer,this.dek.byteOffset,this.dek.byteLength).toString("base64"))}return this.signingEncryptionOptions}}async function a5({appId:e,versionTag:t,versionCode:r,packagePath:n,internal:i,domainId:s,cookie:o,token:a,needAuth:l=!0}){let c=new FormData,p=new Blob([new Uint8Array(tV.readFileSync(n))],{type:"application/zip"});c.append("applet_file",p,"doubao_app.zip"),c.append("applet_version_code",r.toString());let d=`/developer/${l?"resource_api":"resource_internal_api"}/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/package/upload_applet`;return await n5({internal:i,domainId:a?"sms-external":s,path:d,method:"POST",body:c,headers:{...o?{Cookie:o}:{},...a?{"X-Developer-Open-Build-Token":a}:{}},auth:l&&!a})}async function a8({versionTag:e,appKey:t,manifest:r,rootPath:n,internal:i,needAuth:s=!0,cookie:o,token:a}){process.env.NODE_ENV="production";let{appId:l,packageName:c,versionCode:p}=r,d=function(e,t){let r=e||t.versionTag||t.versionName;if(!r)throw Error("Doubao Apps Platform deploy requires versionTag in params or app metadata.");return r}(e,r),{packageResource:u}=await tq({channelName:"doubao_app",manifest:r,rootPath:n});if(!u)throw Error("Failed to archive package");let m=await a5({appId:t||l||c,versionTag:d,versionCode:p,packagePath:u.resource,internal:i,needAuth:s,cookie:o,token:a});return console.log("Deploy success:",m),m}let a9=f("../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"),a7="x-db-llm-modifiable",a6="x-db-is-entity-id",le="x-db-is-refresh-key",lt=["entity_type"];function lr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ln(e,t,r){if(!lr(e))throw Error(`Tool "${r}" 的 ${t} 必须是对象`);return e}function li(e,t,r,n,i=!1){let s=`Tool "${t}" 的 ${r} 属性 "${n}"`;if(!lr(e)||"string"!=typeof e.type||!e.type.trim())throw Error(`${s} 必须提供字符串类型的 type`);let o=e.type.trim(),a=e[a7];if(void 0!==a&&"boolean"!=typeof a)throw Error(`${s} 的 ${a7} 必须是布尔值`);if(a&&"outputSchema"!==r)throw Error(`${s} 的 ${a7} 仅支持在 outputSchema 中使用`);if(a&&"array"!==o)throw Error(`${s} 的 ${a7} 仅支持用于数组字段`);let l=e[a6];if(void 0!==l&&"boolean"!=typeof l)throw Error(`${s} 的 ${a6} 必须是布尔值`);if(l&&!i)throw Error(`${s} 的 ${a6} 仅支持用于卡片输出的顶层字段`);let c=e[le];if(void 0!==c&&"boolean"!=typeof c)throw Error(`${s} 的 ${le} 必须是布尔值`);if(c&&!i)throw Error(`${s} 的 ${le} 仅支持用于卡片输出的顶层字段`);let p={type:function(e,t){if("integer"===e)return"int";if("number"===e)return"float";if(["string","boolean","object","array"].includes(e))return e;throw Error(`${t} 使用了不支持的类型 "${e}"`)}(o,s),...a?{llm_modifiable:!0}:{},...l?{is_entity_id:!0}:{},..."string"==typeof e.description&&e.description.trim()?{description:e.description.trim()}:{}};if("object"===o){if(!lr(e.properties))throw Error(`${s} 必须提供对象类型的 properties`);if(p.properties=Object.fromEntries(Object.entries(e.properties).map(([e,i])=>[e,li(i,t,r,`${n}.${e}`)])),void 0!==e.required){if(!Array.isArray(e.required)||e.required.some(e=>"string"!=typeof e))throw Error(`${s} 的 required 必须是字符串数组`);p.required=e.required}}if("array"===o){if(!lr(e.items))throw Error(`${s} 必须提供对象类型的数组项定义 items`);p.items=li(e.items,t,r,`${n}[]`)}return p}function ls(e,t,r){let n=e[t];if(void 0===n)return{};if(!lr(n))throw Error(`manifest.yaml 的 ${t} 必须是对象:${r}`);return{...n}}function lo(e,t){if(!tV.existsSync(e)||!tV.statSync(e).isFile())throw Error(`${t} 文件不存在:${e}`);return tV.readFileSync(e,"utf8")}class la{pluginSystem;rootPath="dist";context;appDirectory;_userConfig;_appConfig;_appConfigLoaded=!1;_env={};constructor(e=process.cwd()){this.appDirectory=e}async prepare(e,t={},r){let n=this.context;try{let n=Date.now(),i=await this.getUserConfig(t),s={...await this.getAppConfig(),...t.appName?{name:t.appName}:{},...t.appIcon?{icons:tx(t.appIcon)}:{}},o={pages:aF(s?.pages,"pages"),tools:aF(s?.tools,"tools"),widgets:aF(s?.widgets,"widgets")},a=function(e){let t=t_.join(e,"events.json");if(tV.existsSync(t)&&tV.statSync(t).isFile())return{readJson:()=>tV.readFileSync(t,"utf8"),sourcePath:t}}(this.appDirectory),l=function({appDirectory:e,normalizedAppConfig:t}){let r=t_.join(e,"tools.json");if(!tV.existsSync(r))return;let n=t_.join(e,"manifest.yaml"),i=()=>lo(r,"tools.json"),s=()=>(function({tools:e,manifestPath:t,manifestText:r}){let n=function(e,t){let r;try{r=(0,a9.qg)(e)}catch(e){throw Error(`解析 manifest.yaml 失败:${t}`,{cause:e})}if(!lr(r))throw Error(`manifest.yaml 必须包含一个对象:${t}`);return r}(r,t),i=ls(n,"tools",t),s=ls(n,"entities",t);for(let t of e){if(t.name in i)throw Error(`Tool "${t.name}" 与 manifest.yaml 中的 Tool 重名`);if(i[t.name]={login_type:"no_login",description:t.description,..."client"===t.toolType?{is_client_tool:!0}:{},input_schema:function(e,t){if("object"!==e.type||!lr(e.properties))throw Error(`Tool "${t}" 的 inputSchema.type 必须为 object,且 properties 必须是对象`);let r=Object.fromEntries(Object.entries(e.properties).map(([e,r])=>[e,li(r,t,"inputSchema",e)])),n=e.required;if(void 0!==n&&(!Array.isArray(n)||n.some(e=>"string"!=typeof e)))throw Error(`Tool "${t}" 的 inputSchema.required 必须是字符串数组`);return{type:"object",properties:r,...n&&n.length>0?{required:n}:{}}}(t.inputSchema,t.name),output:t.widgetId?{kind:"entities",entity_types:[t.name]}:{kind:"execution_result"},...t.permissions.length>0?{permissions:t.permissions}:{}},t.widgetId){if(t.name in s)throw Error(`Tool "${t.name}" 与 manifest.yaml 中的实体重名`);s[t.name]={schema:{entity_type:{type:"string",llm_visible:!1},...function(e,t){let r=t.name;if("array"!==e.type||!lr(e.items))throw Error(`Card Tool "${r}" 的 outputSchema.type 必须为 array,且 items 必须是对象`);if("object"!==e.items.type||!lr(e.items.properties))throw Error(`Card Tool "${r}" 的 outputSchema.items 必须是对象类型的定义`);let n=e.items.properties,i=lt.find(e=>e in n);if(i)throw Error(`Tool "${r}" 的 outputSchema 不能声明保留字段 "${i}"`);let s=Object.entries(n).filter(([e,t])=>{if(!lr(t)||void 0===t[a6])return!1;if("boolean"!=typeof t[a6])throw Error(`Tool "${r}" 的 outputSchema 属性 "${e}" 的 ${a6} 必须是布尔值`);return t[a6]});if(1!==s.length)throw Error(`Card Tool "${r}" 的 outputSchema 必须有且仅有一个 ${a6} 字段,当前有 ${s.length} 个`);let o=Object.entries(n).filter(([e,t])=>{if(!lr(t)||void 0===t[le])return!1;if("boolean"!=typeof t[le])throw Error(`Tool "${r}" 的 outputSchema 属性 "${e}" 的 ${le} 必须是布尔值`);return t[le]});if("same_conversation"===t.expirePolicy){let e=s[0]?.[0];if(1!==o.length||o[0]?.[0]!==e)throw Error(`Card Tool "${r}" 使用 expirePolicy "same_conversation" 时,必须在 ${a6} 字段上设置 ${le}`)}return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,li(t,r,"outputSchema",e,!0)]))}(t.outputSchema,t)},tool_card_binding:{[t.name]:t.widgetId},..."same_conversation"===t.expirePolicy?{history_card_refresh:{enabled:!0,scope:"same_conversation",refresh_to:"fixed_style"}}:{}}}}return(0,a9.As)({...n,tools:i,entities:s})})({tools:(()=>{let e=function(e,t){let r;try{r=JSON.parse(e)}catch(e){throw Error(`解析 tools.json 失败:${t}`,{cause:e})}if(!lr(r)||!Array.isArray(r.tools)||0===r.tools.length)throw Error(`tools.json 必须包含非空的 tools 数组:${t}`);let n=new Set;return{tools:r.tools.map((e,r)=>{let i=function(e,t,r){if(!lr(e))throw Error(`索引为 ${t} 的 Tool 配置必须是对象:${r}`);let n="string"==typeof e.name?e.name.trim():"",i="string"==typeof e.description?e.description.trim():"";if(!n||!i)throw Error(`索引为 ${t} 的 Tool 配置必须提供 name 和 description:${r}`);if(void 0!==e.tool_type&&"client"!==e.tool_type&&"server"!==e.tool_type)throw Error(`Tool "${n}" 的 tool_type 必须为 "client" 或 "server"`);let s=function(e,t){if(void 0===e)return{};if(!lr(e))throw Error(`Tool "${t}" 的 _meta 必须是对象`);if(void 0===e.ui)return{};if(!lr(e.ui))throw Error(`Tool "${t}" 的 _meta.ui 必须是对象`);if("widgetPath"in e.ui)throw Error(`Tool "${t}" 必须使用 _meta.ui.widgetId,不能使用 widgetPath`);let r=e.ui.widgetId;if(void 0!==r&&("string"!=typeof r||!r.trim()))throw Error(`Tool "${t}" 的 _meta.ui.widgetId 必须是非空字符串`);let n=e.ui.expirePolicy;if(void 0!==n&&"same_conversation"!==n)throw Error(`Tool "${t}" 的 _meta.ui.expirePolicy 如有设置,必须为 "same_conversation"`);if("same_conversation"===n&&"string"!=typeof r)throw Error(`Tool "${t}" 设置 _meta.ui.expirePolicy 时必须提供 _meta.ui.widgetId`);return{..."string"==typeof r?{widgetId:r.trim()}:{},..."same_conversation"===n?{expirePolicy:n}:{}}}(e._meta,n);return{name:n,description:i,...s,inputSchema:ln(e.inputSchema,"inputSchema",n),outputSchema:ln(e.outputSchema,"outputSchema",n),permissions:function(e,t){if(void 0===e)return[];if(!Array.isArray(e)||e.some(e=>"string"!=typeof e||!e.trim()))throw Error(`Tool "${t}" 的 permissions 必须是由非空字符串组成的数组`);return e.map(e=>e.trim())}(e.permissions,n),toolType:"client"===e.tool_type?"client":"server"}}(e,r,t);if(n.has(i.name))throw Error(`Tool 名称重复:${i.name}`);return n.add(i.name),i})}}(i(),r);var n=e.tools;let s=new Set(t.widgets.entryNames.map(e=>t.widgets.entries[e]?.id??tK(e)));for(let e of n)if(e.widgetId&&!s.has(e.widgetId))throw Error(`Tool "${e.name}" 引用的 widgetId "${e.widgetId}" 未在 app.config.ts 中声明`);return e})().tools,manifestPath:n,manifestText:lo(n,"manifest.yaml")});return s(),{manifestSourcePath:n,readManifestYaml:s,readToolsJson:i,toolsSourcePath:r}}({appDirectory:this.appDirectory,normalizedAppConfig:o}),c=function(e){if(e)return!0===e?{mcpEndpoint:rs()}:{...e,mcpEndpoint:rs({mcpEndpoint:e.mcpEndpoint})}}(t.openWebDebugger),p=Date.now()-n;this.rootPath=t_.resolve(this.appDirectory,"dist"),tV.existsSync(t_.resolve(this.rootPath))&&tV.rmSync(t_.resolve(this.rootPath),{recursive:!0,force:!0}),this.context=new a4,oM(this.context.compileLifecycle,n),this.context.compileLifecycle.prepareDurations.configLoadMs=p;let d=t_.resolve(this.appDirectory,"src"),u=Date.now(),{pages:m,widgets:h,auth:f,app:g,tools:y}=await this.analyzeConvention(d,o);this.context.compileLifecycle.prepareDurations.projectScanMs=Date.now()-u;let b=new tR,_=((e=process.cwd())=>t4(e)===t0)(this.appDirectory),v=Date.now();await this.context.bootstrap({srcDirectory:d,appDirectory:this.appDirectory,rootPath:this.rootPath,userConfig:i,env:this._env,appConfig:s,normalizedAppConfig:o,command:e,metadata:b,signingEncryptionOptions:t.signingEncryptionOptions,skipAppInfoFetch:!!t.token,permissions:t.permissions,appId:t.appId,versionTag:t.versionTag,pages:m,widgets:h,auth:f,app:g,tools:y,internal:_,devServerInteractive:t.interactive,loginCookieResolver:()=>aU(t,{internal:_}),cachedLoginCookieResolver:()=>aB(t,_)}),this.context.compileLifecycle.prepareDurations.contextBootstrapMs=Date.now()-v,(e===eD.DEV||void 0!==t.host)&&(this.context.devServerHost=await a1(t.host)),this.context.webDebuggerLaunchOptions=c,this.context.eventsResources=a,this.context.toolsResources=l,this.pluginSystem=new tF(this.context,[ak,aP,aN,ax,aj,aT,aL,aI,...i.experiments?.taro?[function({name:e,appId:t,icons:r,widgets:n}){return{name:t6,setup:i=>{let s=(0,t7.createRequire)(import.meta.url);i.view.hooks.modifyEntryOption.tapPromise({name:t6,stage:i.view.MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY},async({entry:e})=>{let{appDirectory:t,isDev:r,pages:n,widgets:s}=i.context,o=t9(n,t,!1,r);return{entry:e=Object.assign(e,o,t9(s,t,!0,r))}}),i.view.hooks.beforeBuild.tapPromise({name:t6,stage:i.view.BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG},async({buildConfig:e})=>{let{appDirectory:t}=i.context;tZ(e,{resolve:{alias:{"@tarojs/components":s.resolve("@doubao-dev/taro-runtime/components",{paths:[t]}),"@tarojs/taro":(0,eJ.dirname)(s.resolve("@doubao-dev/taro-runtime/package.json",{paths:[t]}))}}})}),i.worker.hooks.modifyEntryOption.tapPromise({name:t6,stage:i.worker.MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE},async({entry:r})=>{let{appDirectory:n,isDev:s}=i.context,{app:o}=i.context;return o&&(r.app=function(e,t,r,n,i=!1){var s;let o=`${ez}${t_.sep}app.js`,a=(s=tQ(t_.dirname(o),e)).startsWith(".")?s:`./${s}`,l=t5(t);return new t8(o,`
286
294
  import { Applet } from "${l}";
287
295
  import { defineApp } from '${l}';
288
296
  import { APP_ID, getLifecycle, setCurrentId } from '@doubao-dev/taro-runtime/internal';
289
- import App from '${s}';
297
+ import App from '${a}';
290
298
 
291
299
  const lifecycle = getLifecycle(APP_ID);
292
300
 
@@ -327,4 +335,4 @@ if (import.meta.webpackHot) {
327
335
  import.meta.webpackHot.accept()
328
336
  }
329
337
  `:""}
330
- `)}(a,n,e,t,o)),{entry:r}}),i.worker.hooks.collectMetaData.tapPromise(rd,async({collector:n})=>{n.addAppMeta({name:e,appId:t,icons:r})}),i.view.hooks.collectMetaData.tapPromise({name:rd,stage:i.view.COLLECT_METADATA_STAGE_OPTIMIZE},async({collector:e})=>{let{pages:t,widgets:r}=i.context;Object.entries(t).forEach(([t,r])=>{let{folderName:n}=r;e.addPageMeta(t,{id:rt(t,n),path:rr(t)})}),Object.entries(r).forEach(([t,r])=>{let i,{folderName:o}=r;e.addWidgetMeta(t,(i=rt(t,o),{...n?.[o]??n?.[t]??n?.[i]??{},id:i}))})})}}}(i.experiments.taro)]:[],...i.plugins||[]]);let w=Date.now();await this.pluginSystem.bootstrap(),this.context.compileLifecycle.prepareDurations.pluginBootstrapMs=Date.now()-w,this.context.setVersionTag(o.version),this.context.compileLifecycle.builderInitStartTime=Date.now();let S=await a2({options:i,commandType:e,context:this.context,rsbuildPlugins:r},this.pluginSystem);return{userConfig:i,builder:S}}catch(t){throw a$.report({appDirectory:this.appDirectory,context:this.context===n?void 0:this.context,scene:e===ej.DEV?"dev_initial":e,status:"failed",errorStage:"prepare",error:t}),t}}async dev(e){let t,r,{builder:n}=await this.prepare(ej.DEV,e,e.rsbuildPlugins);this.context.manifestSettings=function({cwd:e=process.cwd()}={}){let t=eX.resolve(e,a7);if(t5.existsSync(t))try{let e=JSON.parse(t5.readFileSync(t,"utf-8"));if(!el(e))throw TypeError("Development config must be a JSON object");return e}catch(e){tC.warn("Failed to load development config file; ignoring it",{path:t,reason:a4(e)});return}}({cwd:this.appDirectory});let i=await n.startDevServer(),o=this.context.webDebuggerLaunchOptions;try{let e=await this.context.resolveDevServer(i.port);t=e.host,r=o?await ai(this.context,{appId:this.context.appId,appDirectory:this.appDirectory,artifactOrigin:e.artifactOrigin,env:{...this.context.env,...o.env??{}},mcpEndpoint:o.mcpEndpoint,mcpHeaders:o.mcpHeaders,simulator:o.simulator,eventsConfigReader:this.context.eventsResources?.readJson,eventsConfigSourcePath:this.context.eventsResources?.sourcePath,toolsConfigReader:this.context.toolsResources?.readToolsJson,toolsConfigSourcePath:this.context.toolsResources?.toolsSourcePath,simulatorManifestReader:o.simulator?.manifestPath?void 0:this.context.toolsResources?.readManifestYaml,simulatorManifestSourcePath:o.simulator?.manifestPath?void 0:this.context.toolsResources?.manifestSourcePath}):void 0}catch(e){throw await i.server.close(),e}let a=async()=>{tD.info("Shutting down...");try{await r?.close(),await i.server.close()}finally{await a$.flush()}tD.info("dev server closed")};return{host:t,devServerReady:!0,...r?{webDebugger:r}:{},closeServer:a}}async build(e){let{builder:t}=await this.prepare(ej.BUILD,e,e.rsbuildPlugins);try{await t.build(),this.copyWebAssetsToRoot()}finally{if(e.skipCleanupRootPath||tm()){if(e.archive&&e.channel){let{channel:t}=e;await t7({channelName:t,manifest:this.context.manifest,rootPath:this.rootPath})}}else to.rmSync(this.rootPath,{recursive:!0,force:!0})}}async analyze(e){let{builder:t}=await this.prepare(ej.ANALYZE,e);await t.build()}async perf(e){let{builder:t}=await this.prepare(ej.PERF,e);await t.build()}async deploy(e){let{builder:t}=await this.prepare(ej.DEPLOY,e),r=e.deployType||re.NORMAL;if(this.context.deploy={...this.context.deploy,...e.appId?{appId:e.appId}:{},...e.versionCode?{versionCode:e.versionCode}:{}},await this.pluginSystem.callDeployHooks("beforeDeploy",{config:this.context.deploy}),!this.context.deploy.doubaoAppsPlatform&&!this.context.deploy.selfBuilt){if(r!==re.NORMAL)return void tk.error("Please use deploy plugin in doubao.config.ts");let n=e.token?void 0:await this.context.getLoginCookie();if(!e.token&&!n)throw Error("Doubao Apps Platform 部署需要登录,请运行 `doubao login` 后重试。");return await t.build(),this.copyWebAssetsToRoot(),await sz({...this.context.versionTag?{versionTag:this.context.versionTag}:{},...e.appId?{appKey:e.appId}:{},manifest:this.context.manifest,rootPath:this.rootPath,internal:this.context.internal,needAuth:!0,...n?{cookie:n}:{},...e.token?{token:e.token}:{}})}(e.build||r===re.NORMAL)&&(await t.build(),this.copyWebAssetsToRoot());try{await this.pluginSystem.callDeployHooks("deploy",{deployType:r})}finally{await this.pluginSystem.callDeployHooks("afterDeploy",{})}}async run(e,t){switch(e){case tz.DEV:return await this.dev(t);case tz.BUILD:return await this.build(t);case tz.ANALYZE:return await this.analyze(t);case tz.PERF:return await this.perf(t);case tz.DEPLOY:return await this.deploy(t)}}async getUserConfig(e){if(!this._userConfig){let t=(0,y.loadEnv)({cwd:this.appDirectory,mode:e.envMode}),r=await st({cwd:this.appDirectory,customConfigFile:e.config});this._env=t.parsed,r.source||={},r.source.define={...t.publicVars,...r.source.define},e.debugDriver&&(r.debugDriver=e.debugDriver),void 0!==e.skipAdbForegroundAppWatch&&(r.skipAdbForegroundAppWatch=e.skipAdbForegroundAppWatch),this._userConfig=r}return this._userConfig}copyWebAssetsToRoot(){if(!this.context)return;let e=[this.context.manifest?.applet.web?.appRuntimeEntry,...this.context.manifest?.applet.pages?.map(e=>e.web?.entry)??[],...this.context.manifest?.widgets?.map(e=>e.web?.entry)??[]].filter(e=>!!e);if(0===e.length)return;let t=ta.resolve(this.appDirectory,"dist");for(let r of e){let e=ta.resolve(t,r);if(e!==t&&!e.startsWith(`${t}${ta.sep}`))throw Error(`Web artifact path escapes the Web output root: ${r}`);if(!to.existsSync(e))throw Error(`Web artifact is missing after build: ${e}`);let n=ta.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`,r);to.mkdirSync(ta.dirname(n),{recursive:!0}),to.copyFileSync(e,n)}let r=ta.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`),n=ta.resolve(r,"base","manifest.json");to.mkdirSync(ta.dirname(n),{recursive:!0}),to.writeFileSync(n,JSON.stringify(this.context.manifest),"utf-8")}async getAppConfig(){if(!this._appConfigLoaded){let e=await this.getUserConfig({});if(e.experiments?.taro)return this._appConfig=await si({cwd:this.appDirectory}),this._appConfigLoaded=!0,this._appConfig;this._appConfig=await sr({cwd:this.appDirectory}),this._appConfigLoaded=!0}return this._appConfig}async analyzeConvention(e,t){let{pages:r,widgets:n,auth:i}=await su(e,t),{app:o,tools:a}=await sc(e,t.tools);return{pages:r,widgets:n,auth:i,app:o,tools:a}}}async function s8({appKey:e,versionTag:t,cloudBuildSource:r,runner:n,config:i,variables:o,properties:a,internal:s,domainId:l,cookie:d}){return await nq({internal:s,domainId:l,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/cloud_build/create_job`,method:"POST",body:JSON.stringify({cloud_build_source:r,runner:n,config:i,variables:o,properties:a}),headers:{"Content-Type":"application/json",...d?{Cookie:d}:{}}})}async function s7({appKey:e,jobId:t,reason:r,internal:n,domainId:i,cookie:o}){return await nq({internal:n,domainId:i,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}/cancel`,method:"POST",body:JSON.stringify({reason:r}),headers:{"Content-Type":"application/json",...o?{Cookie:o}:{}}})}async function s6({appKey:e,jobId:t,internal:r,domainId:n,cookie:i}){return await nq({internal:r,domainId:n,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}`,method:"GET",headers:i?{Cookie:i}:void 0})}async function le({appKey:e,jobId:t,start:r,end:n,internal:i,domainId:o,cookie:a}){return await nq({internal:i,domainId:o,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}/logs`,query:{start:r,end:n},method:"GET",headers:a?{Cookie:a}:void 0})}async function lt({appKey:e,filename:t,sha256:r,category:n,internal:i,domainId:o,cookie:a,signal:s}){return await nq({internal:i,domainId:o,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/file_upload/start`,method:"POST",body:JSON.stringify({filename:t,sha256:r,category:n}),headers:{"Content-Type":"application/json",...a?{Cookie:a}:{}},signal:s})}async function lr({appKey:e,uploadToken:t,size:r,internal:n,domainId:i,cookie:o,signal:a}){return await nq({internal:n,domainId:i,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/file_upload/finish`,method:"POST",body:JSON.stringify({upload_token:t,size:r}),headers:{"Content-Type":"application/json",...o?{Cookie:o}:{}},signal:a})}async function ln({appId:e,category:t,filePath:r,filename:n=ta.basename(r),...i}){let o=new Uint8Array(to.readFileSync(r)),a=(0,ib.createHash)("sha256").update(o).digest("hex"),s=(await lt({appKey:e,filename:n,sha256:a,category:t,...i})).data;if(!s?.upload_url||!s.upload_token)throw Error("File upload session is incomplete");await li({uploadUrl:s.upload_url,body:new Blob([o]),headers:s.upload_headers||{},signal:i.signal});let l=await lr({appKey:e,uploadToken:s.upload_token,size:o.byteLength,...i});if(!l.data?.stored_file_id)throw Error("File upload finish response did not return stored_file_id");return l.data}async function li({uploadUrl:e,body:t,headers:r,signal:n}){let i=await nV(e,{method:"PUT",body:t,headers:r,signal:n}),o=i.headers.get("x-tt-logid")||"";if(!i.ok){let e=await i.text();throw Error([`File upload failed with HTTP ${i.status}`,e?`message: ${e}`:"",o?`log_id: ${o}`:""].filter(Boolean).join(", "))}}(eN=eJ||(eJ={}))[eN.WAITING=0]="WAITING",eN[eN.QUEUED=1]="QUEUED",eN[eN.RUNNING=2]="RUNNING",eN[eN.PENDING=3]="PENDING",eN[eN.SUCCESS=4]="SUCCESS",eN[eN.FAIL=5]="FAIL",eN[eN.CANCELED=6]="CANCELED",eN[eN.TIMEOUT=7]="TIMEOUT",eN[eN.UNKNOWN=8]="UNKNOWN",(eL=eK||(eK={}))[eL.UNKNOWN=0]="UNKNOWN",eL[eL.SOURCE=1]="SOURCE",eL[eL.ARTIFACT=2]="ARTIFACT";let lo=f("../../../node_modules/.pnpm/ora@5.4.1/node_modules/ora/index.js"),la=new Set([eJ.SUCCESS,eJ.FAIL,eJ.CANCELED,eJ.TIMEOUT]);class ls{options;cwd;appDir;internal;env;secretEnv;appInfo;constructor(e,t){this.options=e,this.cwd=t,this.appDir=ta.resolve(e.appDir||t),(0,y.loadEnv)({cwd:this.appDir,mode:e.envMode}),this.internal=((e=process.cwd())=>tc(e)===ts)(this.appDir)}async start({versionTag:e,logs:t,runner:r,config:n,variables:i,properties:o}={}){this.resolveEnv(),this.resolveSecretEnv();let a=await this.upload();if(!a)throw Error("Cloud upload did not return stored_file_id");let s=await this.build({sourceRef:a,versionTag:e,runner:r,config:n,variables:i,properties:o});return t&&await this.waitForBuildJob({jobId:s}),s}async package({outputDir:e}={}){let t={appDir:this.appDir,internal:this.internal,outputDir:e?ta.resolve(this.cwd,e):void 0},r=await this.runWithSpinner("Preparing cloud build source...",e=>ee({...t,onProgress:e}));if(this.logSourceDiagnostics(r),tP.success("Cloud build source archive created",{archivePath:r.archivePath}),r.blockers.length>0)throw Error(r.blockers.join("\n"));return r.archivePath}async upload({packOnly:e,outputDir:t}={}){if(e)return void await this.package({outputDir:t});let r={appDir:this.appDir,internal:this.internal},n=await this.resolveAppId("upload"),i=await this.resolveCookie(),o=await this.runWithSpinner("Preparing cloud build source...",e=>ee({...r,onProgress:e}));if(this.logSourceDiagnostics(o),o.blockers.length>0)throw Error(o.blockers.join("\n"));let a=(await this.runWithSpinner("Uploading cloud build source...",()=>ln({appId:n,category:eK.SOURCE,filePath:o.archivePath,internal:this.internal,cookie:i}))).stored_file_id;if(!a)throw Error("Cloud build source upload did not return stored_file_id");return tP.success("Cloud build source uploaded",{storedFileId:a}),a}async build({sourceRef:e,versionTag:t,runner:r,config:n,variables:i,properties:o}={}){let a;if(!e)throw Error("Cloud build requires --source-ref.");let{appId:s,appConfig:l}=await this.resolveAppInfo();if(!s)throw Error("Cloud build requires appId in doubao.config.ts or src/app.config.ts.");try{a=JSON.parse(to.readFileSync(ta.resolve(this.appDir,"package.json"),"utf-8")).version}catch{a=void 0}let d=t||l.version||a;if(!d)throw Error("Cloud build requires --version-tag or version in src/app.config.ts/package.json.");let p=await this.resolveCookie(),c=(await this.runWithSpinner("Creating cloud build job...",()=>s8({appKey:s,versionTag:d,cloudBuildSource:{type:"stored_file",ref:e},runner:r,config:n,variables:this.resolveBuildVariables(i),properties:o,internal:this.internal,cookie:p}))).data;if(!c?.job_id)throw Error("Cloud build create_job response did not return job_id");let u=eJ[c.status]||String(c.status);return tP.success("Cloud build job created",{jobId:c.job_id}),tP.info("Cloud build status",{status:u}),c.job_id}async cancel({jobId:e,reason:t}){if(!e)throw Error("Cloud cancel requires job id.");let r=await this.resolveAppId("cancel"),n=await this.resolveCookie(),i=await this.runWithSpinner("Canceling cloud build job...",()=>s7({appKey:r,jobId:e,reason:t||"Canceled by doubao CLI",internal:this.internal,cookie:n})),o=i.data?.job_id;if(!o)throw Error("Cloud build cancel response did not return job_id");return tP.success("Cloud build job canceled",{jobId:o}),o}async getStatus({jobId:e}){if(!e)throw Error("Cloud status requires job id.");let t=await this.resolveAppId("build"),r=await this.resolveCookie(),n=(await s6({appKey:t,jobId:e,internal:this.internal,cookie:r})).data;if(!n)throw Error("Cloud build status response did not return data");let i=eJ[n.status]||String(n.status);return tP.info("Cloud build job",{jobId:n.job_id}),tP.info("Cloud build status",{status:i}),n}async log({jobId:e,start:t,end:r}){if(!e)throw Error("Cloud log requires job id.");let n=Number(t??1),i=Number(r??n+200-1);if(!Number.isInteger(n)||!Number.isInteger(i)||n<1||i<n)throw Error("Cloud log requires a valid line range.");let o=await this.resolveAppId("log"),a=await this.resolveCookie(),s=(await le({appKey:o,jobId:e,start:n,end:i,internal:this.internal,cookie:a})).data;if(!s)throw Error("Cloud build log response did not return data");return this.printLogLines(s.lines),tP.info("Cloud build logs fetched",{start:s.start??n,end:s.end??i,totalLineCount:s.total_line_count}),s}async waitForBuildJob({jobId:e}){let t=await this.resolveAppId("build"),r=await this.resolveCookie(),n=lo("Waiting for cloud build to finish...").start(),i=!1;try{for(;;){let o=await s6({appKey:t,jobId:e,internal:this.internal,cookie:r}),a=o.data?.status,s=void 0===a?"UNKNOWN":eJ[a]||String(a);if(n.text=`Cloud build status: ${s}`,void 0!==a&&la.has(a)){if(a===eJ.SUCCESS){n.succeed(`Cloud build status: ${s}`),i=!0;return}throw n.fail(`Cloud build status: ${s}`),i=!0,await this.printFailureLogs({appId:t,jobId:e,cookie:r}),Error(`Cloud build ended with status: ${s}`)}await new Promise(e=>setTimeout(e,5e3))}}catch(e){throw i||n.fail(),e}}async printFailureLogs({appId:e,jobId:t,cookie:r}){let n=1,i=0,o=!1;try{for(tP.info("Fetching cloud build failure logs");i<1e3&&n<=1e3;){let a=Math.min(n+200-1,1e3),s=(await le({appKey:e,jobId:t,start:n,end:a,internal:this.internal,cookie:r})).data;if(!s||0===s.lines.length)break;this.printLogLines(s.lines),i+=s.lines.length;let l=s.lines.at(-1)?.line_number,d=void 0!==l&&l>=n?l+1:void 0!==s.end&&s.end>=n?s.end+1:n,p=d>n;if(!(o=s.has_more_after&&p))break;n=d}o&&tP.warn("Cloud build failure logs truncated",{limit:1e3,jobId:t})}catch(e){tP.warn("Failed to fetch cloud build failure logs",{reason:a4(e)})}}async resolveCookie(){return await sI(this.options,{internal:this.internal})}resolveBuildVariables(e){let t=new Map;for(let[e,r]of Object.entries(this.resolveEnv()))t.set(e,{name:e,value:r,env_var_name:e});for(let[e,r]of Object.entries(this.resolveSecretEnv()))t.set(e,{name:e,value:r,env_var_name:e,is_secret:!0});for(let r of e||[])t.set(r.env_var_name||r.name,r);return t.size>0?Array.from(t.values()):void 0}resolveEnv(){return this.options.env?(this.env??=ll(this.resolveAppPath(this.options.env),"Env"),this.env):{}}resolveSecretEnv(){return this.options.secretEnv?(this.secretEnv??=ll(this.resolveAppPath(this.options.secretEnv),"Secret env"),this.secretEnv):{}}resolveAppPath(e){return ta.isAbsolute(e)?e:ta.resolve(this.appDir,e)}async resolveAppId(e){let{appId:t}=await this.resolveAppInfo();if(!t)throw Error(`Cloud ${e} requires appId in doubao.config.ts or src/app.config.ts.`);return t}async resolveAppInfo(){if(this.appInfo)return this.appInfo;let e=await st({cwd:this.appDir,customConfigFile:this.options.config}),t=await sr({cwd:this.appDir})??{};return this.appInfo={appId:e.experiments?.taro?.appId?e.experiments?.taro?.appId:t.appId,appConfig:t},this.appInfo}logSourceDiagnostics(e){for(let t of e.warnings)tP.warn(t);for(let t of e.blockers)tP.error(t)}printLogLines(e){for(let t of e)console.log(t.content)}async runWithSpinner(e,t){let r=lo(e).start();try{let e=await t(e=>{r.text=e});return r.succeed(),e}catch(e){throw r.fail(),e}}}function ll(e,t){if(!to.existsSync(e))throw Error(`${t} file does not exist: ${e}`);return function(e){let t={};for(let r of e.split(/\r?\n/)){let e=r.trim();if(!e||e.startsWith("#"))continue;let n=e.startsWith("export ")?e.slice(7).trimStart():e,i=n.indexOf("=");if(i<=0)continue;let o=n.slice(0,i).trim();/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)&&(t[o]=function(e){let t=e[0];if(('"'===t||"'"===t)&&e.endsWith(t))return e.slice(1,-1);let r=e.indexOf(" #");return -1===r?e:e.slice(0,r).trimEnd()}(n.slice(i+1).trim()))}return t}(to.readFileSync(e,"utf8"))}async function ld(e){let t=await tN(e);if(!t)throw Error("未检测到可用的 Android 设备。");return t}function lp({compileHooks:e,output:t}){let r=new Map,n={percentage:0},i=()=>{if(0===r.size)return;let e=[...r.values()].reduce((e,t)=>t.percentage<e.percentage?t:e);(e.percentage!==n.percentage||e.stage!==n.stage)&&(n=e,t?.onProgress?.(e))},o=e=>{for(let t of(r.clear(),e))r.set(t,{percentage:0});n={percentage:0}};return[{name:"DoubaoAppsDevPlugin",setup(n){t?.printLogs===!1&&(n.logger.level="silent"),t?.progressBar!==void 0&&n.modifyRsbuildConfig(e=>((e.dev??={}).progressBar=t.progressBar,e)),t?.onProgress&&(n.modifyRspackConfig((e,{appendPlugins:t,environment:n,environments:a})=>{0===r.size&&o(Object.keys(a)),t(new y.rspack.ProgressPlugin((e,t)=>{r.set(n.name,{percentage:Math.max(0,Math.min(1,e)),...t?{stage:t}:{}}),i()}))}),n.onBeforeDevCompile(({environments:e})=>{o(Object.keys(e))})),n.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.failed.tap("DoubaoAppsDevPlugin",t=>e?.onDevCompileFailed?.(t))}),n.onAfterDevCompile(({stats:t})=>{if(r.size>0){for(let e of r.keys())r.set(e,{percentage:1,stage:"done"});i()}e?.onAfterDevCompile?.(aC(t))})}}]}class lc{appDirectory;launcher;constructor(e,t=s9){this.appDirectory=e,this.launcher=new t(e)}createCloudBuildLauncher(e={}){return new ls(e,this.appDirectory||process.cwd())}async create(e){await em(e)}async dev(e={}){let{compileHooks:t,output:r,simulator:n,...i}=e,o=n;if("object"==typeof n){let{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i,...a}=n;o={...a,simulator:{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i}}}let a=()=>this.launcher.dev({...i,...void 0!==o?{openWebDebugger:o}:{},rsbuildPlugins:lp({compileHooks:t,output:r}),signingEncryptionOptions:e.signingEncryptionOptions});return r?await eb.run(r,a):await a()}async build(e={}){process.env.NODE_ENV="production";let{compileHooks:t,...r}=e;await this.launcher.build({...r,rsbuildPlugins:lp({compileHooks:t}),signingEncryptionOptions:e.signingEncryptionOptions,versionTag:e.versionTag})}async discoverWidgets(){return Object.values(this.launcher.context.metadata.getData().widgets).filter(({id:e})=>!te(e))}async discoverPages(){return Object.values(this.launcher.context.metadata.getData().pages)}async discoverTools(){return Object.values(this.launcher.context.metadata.getData().tools)}async pushWidget(e){let{widgetId:t,deviceId:r,botId:n,widgetData:i,debugDriver:o,skipAdbForegroundAppWatch:a}=e,s=await ld({debugDriver:o,deviceId:r,skipAdbForegroundAppWatch:a}),l=this.launcher.context.metadata.appId;s.pushWidget({appId:l,widgetId:t,widgetData:i,botId:n})}async openPage(e){let{pageId:t,pageData:r,pageSettings:n,mode:i,debugDriver:o,deviceId:a,skipAdbForegroundAppWatch:s}=e,l=await ld({debugDriver:o,deviceId:a,skipAdbForegroundAppWatch:s}),d=this.launcher.context.metadata.appId;l.openPage({appId:d,pageId:t,pageData:r,pageSettings:n,mode:i})}async callTool(e){let{toolId:t,toolData:r,debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:o}=e,a=await ld({debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:o}),s=this.launcher.context.metadata.appId;a.callTool({appId:s,toolId:t,toolData:r})}async executeDebugScene(e){let{matchedScene:t,variables:r,deviceId:n,debugDriver:i,skipAdbForegroundAppWatch:o}=e,a=this.launcher.context.metadata.appId,s=await ld({debugDriver:i,deviceId:n,skipAdbForegroundAppWatch:o});await tU({matchedScene:t,appId:a,driver:s,variables:r})}async getDebugScenes(){let e=await tM(this.appDirectory||process.cwd());return await Promise.all(e.map(async e=>({...e,content:await tj(e.path)})))}async cloud(e={}){let{versionTag:t,logs:r,runner:n,createJobConfig:i,variables:o,properties:a,...s}=e;return await this.createCloudBuildLauncher(s).start({versionTag:t,logs:r,runner:n,config:i,variables:o,properties:a})}async cloudUpload(e={}){let{packOnly:t,outputDir:r,...n}=e;return await this.createCloudBuildLauncher(n).upload({packOnly:t,outputDir:r})}async cloudPackage(e={}){let{outputDir:t,...r}=e;return await this.createCloudBuildLauncher(r).package({outputDir:t})}async cloudBuild(e){let{sourceRef:t,versionTag:r,runner:n,createJobConfig:i,variables:o,properties:a,...s}=e;return await this.createCloudBuildLauncher(s).build({sourceRef:t,versionTag:r,runner:n,config:i,variables:o,properties:a})}async cloudCancel(e){let{jobId:t,reason:r,...n}=e;return await this.createCloudBuildLauncher(n).cancel({jobId:t,reason:r})}async cloudGetStatus(e){let{jobId:t,...r}=e;return await this.createCloudBuildLauncher(r).getStatus({jobId:t})}async cloudLog(e){let{jobId:t,start:r,end:n,...i}=e;return await this.createCloudBuildLauncher(i).log({jobId:t,start:r,end:n})}async deploy(e){let{versionTag:t,cookie:r,token:n,appKey:i,signingEncryptionOptions:o}=e;if(!r&&!n)throw Error("Doubao Apps SDK 部署需要 Cookie 或 Developer Open Build Token。");process.env.NODE_ENV="production",await this.launcher.build({skipCleanupRootPath:!0,cookie:r,signingEncryptionOptions:o,token:n,versionTag:t});let{manifest:a}=this.launcher.context;try{return await sz({versionTag:this.launcher.context.versionTag,...i?{appKey:i}:{},manifest:a,rootPath:this.launcher.rootPath,internal:e.internal??this.launcher.context.internal,cookie:r,token:n})}finally{tm()||to.rmSync(this.launcher.rootPath,{recursive:!0,force:!0})}}}export{lc as DoubaoAppsSDK,a4 as error_getErrorMessage};
338
+ `)}(o,n,e,t,s)),{entry:r}}),i.worker.hooks.collectMetaData.tapPromise(t6,async({collector:n})=>{n.addAppMeta({name:e,appId:t,icons:r})}),i.view.hooks.collectMetaData.tapPromise({name:t6,stage:i.view.COLLECT_METADATA_STAGE_OPTIMIZE},async({collector:e})=>{let{pages:t,widgets:r}=i.context;Object.entries(t).forEach(([t,r])=>{let{folderName:n}=r;e.addPageMeta(t,{id:tK(t,n),path:tY(t)})}),Object.entries(r).forEach(([t,r])=>{let i,{folderName:s}=r;e.addWidgetMeta(t,(i=tK(t,s),{...n?.[s]??n?.[t]??n?.[i]??{},id:i}))})})}}}(i.experiments.taro)]:[],...i.plugins||[]]);let E=Date.now();await this.pluginSystem.bootstrap(),this.context.compileLifecycle.prepareDurations.pluginBootstrapMs=Date.now()-E,this.context.setVersionTag(s.version),this.context.compileLifecycle.builderInitStartTime=Date.now();let w=await ar({options:i,commandType:e,context:this.context,rsbuildPlugins:r},this.pluginSystem);return{userConfig:i,builder:w}}catch(t){throw oH.report({appDirectory:this.appDirectory,context:this.context===n?void 0:this.context,scene:e===eD.DEV?"dev_initial":e,status:"failed",errorStage:"prepare",error:t}),t}}async dev(e){let t,r,{builder:n}=await this.prepare(eD.DEV,e,e.rsbuildPlugins);this.context.manifestSettings=function({cwd:e=process.cwd()}={}){let t=t_.resolve(e,aa);if(tV.existsSync(t))try{let e=JSON.parse(tV.readFileSync(t,"utf-8"));if(!K(e))throw TypeError("开发配置必须是 JSON 对象");return e}catch(e){tp.warn("加载开发配置文件失败,已忽略该文件",{path:t,reason:an(e)});return}}({cwd:this.appDirectory});let i=await n.startDevServer(),s=this.context.webDebuggerLaunchOptions;try{let e=await this.context.resolveDevServer(i.port);t=e.host,r=s?await om(this.context,{appId:this.context.appId,appDirectory:this.appDirectory,artifactOrigin:e.artifactOrigin,env:{...this.context.env,...s.env??{}},mcpEndpoint:s.mcpEndpoint,mcpHeaders:s.mcpHeaders,simulator:s.simulator,eventsConfigReader:this.context.eventsResources?.readJson,eventsConfigSourcePath:this.context.eventsResources?.sourcePath,toolsConfigReader:this.context.toolsResources?.readToolsJson,toolsConfigSourcePath:this.context.toolsResources?.toolsSourcePath,simulatorManifestReader:s.simulator?.manifestPath?void 0:this.context.toolsResources?.readManifestYaml,simulatorManifestSourcePath:s.simulator?.manifestPath?void 0:this.context.toolsResources?.manifestSourcePath}):void 0}catch(e){throw await i.server.close(),e}let o=async()=>{th.info("正在关闭开发服务…");try{await r?.close(),await i.server.close()}finally{await oH.flush()}th.info("开发服务已关闭")};return{host:t,devServerReady:!0,...r?{webDebugger:r}:{},closeServer:o}}async build(e){let{builder:t}=await this.prepare(eD.BUILD,e,e.rsbuildPlugins);try{await t.build(),this.copyWebAssetsToRoot()}finally{if(e.skipCleanupRootPath||eb()){if(e.archive&&e.channel){let{channel:t}=e;await tq({channelName:t,manifest:this.context.manifest,rootPath:this.rootPath})}}else tV.rmSync(this.rootPath,{recursive:!0,force:!0})}}async analyze(e){let{builder:t}=await this.prepare(eD.ANALYZE,e);await t.build()}async perf(e){let{builder:t}=await this.prepare(eD.PERF,e);await t.build()}async deploy(e){let{builder:t}=await this.prepare(eD.DEPLOY,e),r=e.deployType||tz.NORMAL;if(this.context.deploy={...this.context.deploy,...e.appId?{appId:e.appId}:{},...e.versionCode?{versionCode:e.versionCode}:{}},await this.pluginSystem.callDeployHooks("beforeDeploy",{config:this.context.deploy}),!this.context.deploy.doubaoAppsPlatform&&!this.context.deploy.selfBuilt){if(r!==tz.NORMAL)return void tm.error("请在 doubao.config.ts 中配置部署插件");let n=e.token?void 0:await this.context.getLoginCookie();if(!e.token&&!n)throw Error("Doubao Apps Platform 部署需要登录,请运行 `doubao login` 后重试。");return await t.build(),this.copyWebAssetsToRoot(),await a8({...this.context.versionTag?{versionTag:this.context.versionTag}:{},...e.appId?{appKey:e.appId}:{},manifest:this.context.manifest,rootPath:this.rootPath,internal:this.context.internal,needAuth:!0,...n?{cookie:n}:{},...e.token?{token:e.token}:{}})}(e.build||r===tz.NORMAL)&&(await t.build(),this.copyWebAssetsToRoot());try{await this.pluginSystem.callDeployHooks("deploy",{deployType:r})}finally{await this.pluginSystem.callDeployHooks("afterDeploy",{})}}async run(e,t){switch(e){case t$.DEV:return await this.dev(t);case t$.BUILD:return await this.build(t);case t$.ANALYZE:return await this.analyze(t);case t$.PERF:return await this.perf(t);case t$.DEPLOY:return await this.deploy(t)}}async getUserConfig(e){if(!this._userConfig){let t=(0,y.loadEnv)({cwd:this.appDirectory,mode:e.envMode}),r=await ap({cwd:this.appDirectory,customConfigFile:e.config});this._env=t.parsed,r.source||={},r.source.define={...t.publicVars,...r.source.define},e.debugDriver&&(r.debugDriver=e.debugDriver),void 0!==e.skipAdbForegroundAppWatch&&(r.skipAdbForegroundAppWatch=e.skipAdbForegroundAppWatch),this._userConfig=r}return this._userConfig}copyWebAssetsToRoot(){if(!this.context)return;let e=[this.context.manifest?.applet.web?.appRuntimeEntry,...this.context.manifest?.applet.pages?.map(e=>e.web?.entry)??[],...this.context.manifest?.widgets?.map(e=>e.web?.entry)??[]].filter(e=>!!e);if(0===e.length)return;let t=t_.resolve(this.appDirectory,"dist");for(let r of e){let e=t_.resolve(t,r);if(e!==t&&!e.startsWith(`${t}${t_.sep}`))throw Error(`Web 构建产物路径超出输出根目录:${r}`);if(!tV.existsSync(e))throw Error(`构建完成后未找到 Web 构建产物:${e}`);let n=t_.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`,r);tV.mkdirSync(t_.dirname(n),{recursive:!0}),tV.copyFileSync(e,n)}let r=t_.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`),n=t_.resolve(r,"base","manifest.json");tV.mkdirSync(t_.dirname(n),{recursive:!0}),tV.writeFileSync(n,JSON.stringify(this.context.manifest),"utf-8")}async getAppConfig(){if(!this._appConfigLoaded){let e=await this.getUserConfig({});if(e.experiments?.taro)return this._appConfig=await am({cwd:this.appDirectory}),this._appConfigLoaded=!0,this._appConfig;this._appConfig=await ad({cwd:this.appDirectory}),this._appConfigLoaded=!0}return this._appConfig}async analyzeConvention(e,t){let{pages:r,widgets:n,auth:i}=await aw(e,t),{app:s,tools:o}=await aE(e,t.tools);return{pages:r,widgets:n,auth:i,app:s,tools:o}}}async function ll(e){let t=await ty(e);if(!t)throw Error("未检测到可用的 Android 设备。");return t}function lc({compileHooks:e,output:t}){let r=new Map,n={percentage:0},i=()=>{if(0===r.size)return;let e=[...r.values()].reduce((e,t)=>t.percentage<e.percentage?t:e);(e.percentage!==n.percentage||e.stage!==n.stage)&&(n=e,t?.onProgress?.(e))},s=e=>{for(let t of(r.clear(),e))r.set(t,{percentage:0});n={percentage:0}};return[{name:"DoubaoAppsDevPlugin",setup(n){t?.printLogs===!1&&(n.logger.level="silent"),t?.progressBar!==void 0&&n.modifyRsbuildConfig(e=>((e.dev??={}).progressBar=t.progressBar,e)),t?.onProgress&&(n.modifyRspackConfig((e,{appendPlugins:t,environment:n,environments:o})=>{0===r.size&&s(Object.keys(o)),t(new y.rspack.ProgressPlugin((e,t)=>{r.set(n.name,{percentage:Math.max(0,Math.min(1,e)),...t?{stage:t}:{}}),i()}))}),n.onBeforeDevCompile(({environments:e})=>{s(Object.keys(e))})),n.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.failed.tap("DoubaoAppsDevPlugin",t=>e?.onDevCompileFailed?.(t))}),n.onAfterDevCompile(({stats:t})=>{if(r.size>0){for(let e of r.keys())r.set(e,{percentage:1,stage:"done"});i()}e?.onAfterDevCompile?.(oD(t))})}}]}class lp{appDirectory;launcher;constructor(e,t=la){this.appDirectory=e,this.launcher=new t(e)}async create(e){await em(e)}async dev(e={}){let{compileHooks:t,output:r,simulator:n,...i}=e,s=n;if("object"==typeof n){let{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i,...o}=n;s={...o,simulator:{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i}}}let o=()=>this.launcher.dev({...i,...void 0!==s?{openWebDebugger:s}:{},rsbuildPlugins:lc({compileHooks:t,output:r}),signingEncryptionOptions:e.signingEncryptionOptions});return r?await ey.run(r,o):await o()}async build(e={}){process.env.NODE_ENV="production";let{compileHooks:t,...r}=e;await this.launcher.build({...r,rsbuildPlugins:lc({compileHooks:t}),signingEncryptionOptions:e.signingEncryptionOptions,versionTag:e.versionTag})}async discoverWidgets(){return Object.values(this.launcher.context.metadata.getData().widgets).filter(({id:e})=>!e8(e))}async discoverPages(){return Object.values(this.launcher.context.metadata.getData().pages)}async discoverTools(){return Object.values(this.launcher.context.metadata.getData().tools)}async pushWidget(e){let{widgetId:t,deviceId:r,botId:n,widgetData:i,debugDriver:s,skipAdbForegroundAppWatch:o}=e,a=await ll({debugDriver:s,deviceId:r,skipAdbForegroundAppWatch:o}),l=this.launcher.context.metadata.appId;a.pushWidget({appId:l,widgetId:t,widgetData:i,botId:n})}async openPage(e){let{pageId:t,pageData:r,pageSettings:n,mode:i,debugDriver:s,deviceId:o,skipAdbForegroundAppWatch:a}=e,l=await ll({debugDriver:s,deviceId:o,skipAdbForegroundAppWatch:a}),c=this.launcher.context.metadata.appId;l.openPage({appId:c,pageId:t,pageData:r,pageSettings:n,mode:i})}async callTool(e){let{toolId:t,toolData:r,debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:s}=e,o=await ll({debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:s}),a=this.launcher.context.metadata.appId;o.callTool({appId:a,toolId:t,toolData:r})}async executeDebugScene(e){let{matchedScene:t,variables:r,deviceId:n,debugDriver:i,skipAdbForegroundAppWatch:s}=e,o=this.launcher.context.metadata.appId,a=await ll({debugDriver:i,deviceId:n,skipAdbForegroundAppWatch:s});await tw({matchedScene:t,appId:o,driver:a,variables:r})}async getDebugScenes(){let e=await tv(this.appDirectory||process.cwd());return await Promise.all(e.map(async e=>({...e,content:await tE(e.path)})))}async cloudPackage(e={}){let t=this.appDirectory||process.cwd(),r=t_.resolve(t,e.appDir||".");(0,y.loadEnv)({cwd:r,mode:e.envMode});let n=await D({appDir:r,outputDir:e.outputDir?t_.resolve(t,e.outputDir):void 0});for(let e of n.warnings)tu.warn(e);if(n.blockers.length>0)throw Error(n.blockers.join("\n"));return n.archivePath}async deploy(e){let{versionTag:t,cookie:r,token:n,appKey:i,signingEncryptionOptions:s}=e;if(!r&&!n)throw Error("Doubao Apps SDK 部署需要 Cookie 或 Developer Open Build Token。");process.env.NODE_ENV="production",await this.launcher.build({skipCleanupRootPath:!0,cookie:r,signingEncryptionOptions:s,token:n,versionTag:t});let{manifest:o}=this.launcher.context;try{return await a8({versionTag:this.launcher.context.versionTag,...i?{appKey:i}:{},manifest:o,rootPath:this.launcher.rootPath,internal:e.internal??this.launcher.context.internal,cookie:r,token:n})}finally{eb()||tV.rmSync(this.launcher.rootPath,{recursive:!0,force:!0})}}}export{lp as DoubaoAppsSDK,an as error_getErrorMessage,eb as isDebugMode};