@doubao-dev/cli 0.0.14 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/bin/run.js +1 -1
  2. package/dist/1664.js +60 -0
  3. package/dist/180.js +1 -0
  4. package/dist/{bin/win32-x64/security_tasm_codec.exe → 1966.js} +0 -0
  5. package/dist/1966.js.LICENSE.txt +119 -0
  6. package/dist/2585.js +2 -0
  7. package/dist/318.js +1 -0
  8. package/dist/3551.js +1 -0
  9. package/dist/3997.js +2 -0
  10. package/dist/4880.js +1 -0
  11. package/dist/5418.js +3 -0
  12. package/dist/5732.js +1 -0
  13. package/dist/7410.js +2 -0
  14. package/dist/7410.js.LICENSE.txt +1 -0
  15. package/dist/7526.js +1 -0
  16. package/dist/@byted-doubao-apps/create.js +4 -5
  17. package/dist/@byted-doubao-apps/login.js +2 -3
  18. package/dist/@byted-doubao-apps/login~1.js +2 -0
  19. package/dist/@byted-doubao-apps/template-empty/package.json +3 -3
  20. package/dist/@byted-doubao-apps/template-starter/package.json +3 -3
  21. package/dist/@byted-hdt/cli.js +11 -12
  22. package/dist/@inquirer/select.js +1 -0
  23. package/dist/app.js +1 -2
  24. package/dist/assets/web-sdk-debugger/index.html +1 -1
  25. package/dist/assets/web-sdk-debugger/static/css/{index.4b84c01189.css → index.123e72a5bc.css} +1 -1
  26. package/dist/assets/web-sdk-debugger/static/js/index.019ceb233a.js +26 -0
  27. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-api.template.js +0 -0
  28. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-framework.template.js +0 -0
  29. package/dist/auth.js +1 -2
  30. package/dist/browser.js +1 -2
  31. package/dist/components-loader.js +2 -3
  32. package/dist/dbx-demo.js +2 -3
  33. package/dist/demo-server.js +3 -4
  34. package/dist/dev-service-client.js +16 -10
  35. package/dist/dev-service-client.js.LICENSE.txt +89 -0
  36. package/dist/dev-shell.js +5 -2
  37. package/dist/dev-shell.js.LICENSE.txt +59 -0
  38. package/dist/dev.js +18 -19
  39. package/dist/devtools.js +2 -0
  40. package/dist/devtools.js.LICENSE.txt +1 -0
  41. package/dist/environment.js +1 -0
  42. package/dist/eval.js +1 -2
  43. package/dist/get.js +1 -2
  44. package/dist/init.js +6 -7
  45. package/dist/login.js +1 -2
  46. package/dist/main.js +1 -0
  47. package/dist/manifest-mcp-config.js +1 -2
  48. package/dist/project-layout.js +1 -2
  49. package/dist/prompt.js +5 -6
  50. package/dist/push-page.js +1 -2
  51. package/dist/push-widget.js +1 -2
  52. package/dist/rslib-runtime.js +1 -2
  53. package/dist/sandbox.js +1 -2
  54. package/dist/sdk.js +76 -169
  55. package/dist/sdk.js.LICENSE.txt +1 -13
  56. package/dist/sdk~1.js +218 -0
  57. package/dist/sdk~1.js.LICENSE.txt +15 -0
  58. package/dist/skills.js +2 -3
  59. package/dist/static/404/404.html +455 -0
  60. package/dist/static/assets/package.json +137 -0
  61. package/dist/static/home_choose/chooseRegion.html +345 -0
  62. package/dist/static/openChrome.applescript +88 -0
  63. package/dist/status.js +2 -3
  64. package/dist/status~1.js +1 -2
  65. package/dist/stop.js +1 -2
  66. package/dist/update.js +1 -2
  67. package/dist/upgrade.js +1 -2
  68. package/dist/upload.js +7 -8
  69. package/dist/validate.js +1 -2
  70. package/dist/yaml.js +25 -0
  71. package/package.json +34 -35
  72. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/01-/345/237/272/347/241/200.md +114 -7
  73. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/02-/347/263/273/347/273/237.md +126 -0
  74. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/06-/344/272/244/344/272/222.md +71 -0
  75. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/08-/347/275/221/347/273/234.md +222 -0
  76. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/10-/344/270/232/345/212/241/350/203/275/345/212/233.md +122 -0
  77. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/groups.md +5 -5
  78. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/quick-reference.md +7 -2
  79. package/dist/183.js +0 -2
  80. package/dist/564.js +0 -13
  81. package/dist/714.js +0 -1
  82. package/dist/assets/web-sdk-debugger/static/js/index.62b5cae841.js +0 -26
  83. package/dist/bin/darwin-arm64/security_tasm_codec +0 -0
  84. package/dist/bin/darwin-arm64/security_tasm_codec.sha256 +0 -1
  85. package/dist/bin/darwin-x64/security_tasm_codec +0 -0
  86. package/dist/bin/darwin-x64/security_tasm_codec.sha256 +0 -1
  87. package/dist/bin/linux-x64/security_tasm_codec +0 -0
  88. package/dist/bin/linux-x64/security_tasm_codec.sha256 +0 -1
  89. package/dist/bin/win32-x64/security_tasm_codec.exe.sha256 +0 -1
  90. package/dist/index.js +0 -1
  91. package/dist/package.json +0 -56
package/dist/sdk~1.js ADDED
@@ -0,0 +1,218 @@
1
+ /*! LICENSE: sdk~1.js.LICENSE.txt */
2
+ let e,t,n,a,o,i,r;import"node:module";import{createRspeedy as s,mergeRspeedyConfig as l,rspack as p}from"@lynx-js/rspeedy";import{LAYERS as d,pluginReactLynx as c}from"@lynx-js/react-rsbuild-plugin";import{pluginLess as u}from"@rsbuild/plugin-less";import{pluginSass as m}from"@rsbuild/plugin-sass";import{__webpack_require__ as h}from"./rslib-runtime.js";import{external_node_stream_promises_namespaceObject as f,external_node_https_namespaceObject as g,external_node_process_namespaceObject as b,promises_namespaceObject as y,external_rsbuild_core_namespaceObject as v,external_jiti_namespaceObject as S,chalk_source as w}from"./1664.js";import{external_node_module_namespaceObject as _}from"./3551.js";import{parseDebugScene as E,schemas_enum as x,schemas_number as C,StreamableHTTPServerTransport as A,unknown as O,TokenExpiredError as I,AUTH_META as T,prepareCloudBuildSource as P,schemas_boolean as k,withAuth as L,RenderType as N,lodash_es_get as R,TitleType as D,schemas_record as M,resolveDebugSceneVariables as $,getWebSdkDebuggerDistPath as B,eraseLines as j,NotLoggedInError as U,lodash_es_mergeWith as W,pluginExternalBundle as F,RuntimeWrapperWebpackPlugin as H,getDebugSceneVariableEntries as V,McpServer as G,getUnresolvedDebugSceneVariables as q,dist_esm as z,schemas_string as J,stringifyDebugSceneSettings as K,replaceDebugSceneUrlVariables as Y,inquirer_dist as X,execaCommand as Q,APP_DEVELOPER_ORIGIN as Z,normalizeHttpEndpoint as ee,pluginReactAlias as et,schemas_array as en,lodash_es_merge as ea,BoxType as eo,resolveDebugSceneInput as ei,APP_DEVELOPER_DOMAIN as er}from"./1966.js";import{walk_simple as es}from"./7526.js";import"./180.js";import"./5418.js";import{create as el}from"./@byted-doubao-apps/create.js";let ep=h("node:async_hooks"),ed=Math.max(...["cli","auth","config","security","build","deploy","dev-server","simulator"].map(e=>`[${e}]`.length)),ec=/authorization|cookie|token|secret|password|credential|private_?key|\bdek\b/i,eu=new ep.AsyncLocalStorage,em=[];function eh(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function ef(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 ef(e.message,t);if("object"!=typeof e)return String(e);if(t.has(e))return'"[Circular]"';t.add(e);let n=Array.isArray(e)?`[${e.map(e=>ef(e,t)).join(",")}]`:`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>{let a=ec.test(eh(e))?'"[REDACTED]"':ef(n,t);return`${JSON.stringify(e)}:${a}`}).join(",")}}`;return t.delete(e),n}function eg(e){return w.cyan(`[${e}]`.padEnd(ed))}function eb(e={}){let t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),n=t["x-tt-env"],a=t["x-use-ppe"],o=Array.isArray(n)?n.join(","):n;return a&&o?String(o):void 0}function ey(e){let t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[eh(e),t]).sort(([e],[t])=>e.localeCompare(t));return 0===t.length?"":t.map(([e,t])=>{let n=ec.test(e)?"[REDACTED]":ef(t);return w.dim(`${e}=${n}`)}).join(" ")}let ev=new class e{constructor(e={}){this.sink=e.sink??v.logger,this.tag=e.tag,this.context=e.context??{},this.isDebugEnabled=e.isDebug??(()=>"applet0930"===process.env.DEBUG)}child(t,n={}){return new e({sink:this.sink,tag:t,context:{...this.context,...n},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 n,{error:a,...o}=t,i=this.tag?`${eg(this.tag)} `:"",r=e instanceof Error?e.message:String(e),s=`${i}${r}`;if(void 0!==a)s+=`: ${a instanceof Error?a.message:ef(a)}`,this.isDebugEnabled()&&a instanceof Error&&a.stack&&(n=a.stack);else e instanceof Error&&this.isDebugEnabled()&&e.stack&&(n=e.stack);let l=ey({...this.context,...o});l&&(s+=` ${l}`),n&&(s+=`
3
+ ${n}`),this.emit("error",r,{...o,...void 0!==a?{error:a}:{}})&&this.sink.error(s)}greet(e){this.emit("info",e)&&this.sink.greet(e)}request(e){var t;let n,a,o,i,r,s,l,p=e.timestamp??new Date,d=w.gray(`[${(n=p.getFullYear(),a=String(p.getMonth()+1).padStart(2,"0"),o=String(p.getDate()).padStart(2,"0"),i=String(p.getHours()).padStart(2,"0"),r=String(p.getMinutes()).padStart(2,"0"),s=String(p.getSeconds()).padStart(2,"0"),l=String(p.getMilliseconds()).padStart(3,"0"),`${n}-${a}-${o} ${i}:${r}:${s}.${l}`)}]`),c=w.bold(e.method),u=void 0===e.durationMs?"":` ${w.dim(`${e.durationMs.toFixed(1)}ms`)}`,m=eb(e.headers),h=Array.isArray(e.logId)?e.logId.join(","):e.logId,f=[m?ey({ppe:m}):"",h?ey({logid:h}):"",ey({...this.context,...e.context})].filter(Boolean).join(" "),g=`${this.tag?`${eg(this.tag)} `:""}${d} ${c} ${e.url} ${((t=e.statusCode)>=500?w.red:t>=400?w.yellow:w.green)(String(t))}${u}${f?` ${f}`:""}`,b=e.statusCode>=500?"error":e.statusCode>=400?"warn":"info";this.emit(b,`${e.method} ${e.url} ${e.statusCode}`,{...e.context,durationMs:e.durationMs,logId:h,ppe:m},p.getTime())&&("error"===b?this.sink.error(g):"warn"===b?this.sink.warn(g):this.sink.info(g))}formatMessage(e,t={}){let n=ey({...this.context,...t}),a=this.tag?`${eg(this.tag)} `:"",o=e instanceof Error?e.message:String(e);return`${a}${o}${n?` ${n}`:""}`}emit(e,t,n={},a=Date.now()){let o=eu.getStore()??em[em.length-1],i=o?.onLog;if(i)try{i({timestamp:a,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])=>[eh(e),t]).sort(([e],[t])=>e.localeCompare(t));if(0!==t.length)return Object.fromEntries(t.map(([e,t])=>[e,ec.test(e)?"[REDACTED]":function e(t,n=new WeakSet){if(t instanceof Error)return t.message;if(null===t||"object"!=typeof t)return"bigint"==typeof t?String(t):t;if(n.has(t))return"[Circular]";n.add(t);let a=Array.isArray(t)?t.map(t=>e(t,n)):Object.fromEntries(Object.entries(t).map(([t,a])=>[t,ec.test(eh(t))?"[REDACTED]":e(a,n)]));return n.delete(t),a}(t)]))}({...this.context,...n})})}catch{}return o?.printLogs!==!1}},eS=ev.child("build"),ew=h("node:fs/promises"),e_=h("node:path");async function eE(e){let t=(0,e_.join)(e,"debug-scene");try{return(await (0,ew.readdir)(t,{withFileTypes:!0})).filter(e=>e.isFile()&&e.name.endsWith(".json")).map(e=>({name:e.name.replace(".json",""),path:(0,e_.join)(t,e.name)}))}catch{return[]}}async function ex(e){try{let t=await (0,ew.readFile)(e,"utf-8");return E(JSON.parse(t))}catch{return null}}async function eC(e){let{matchedScene:t,appId:n,driver:a,variables:o}=e,i=await ex(t.path);if(!i)return;let r=$(i,o);if("page"===i.type){if(i.url){var s,l;let e=Y(i.url,r);s=t.name,0!==(l=q(e)).length&&console.warn(`[DoubaoApps] 调试场景 "${s}" 存在未解析的变量占位符:${l.map(e=>`{{${e}}}`).join(", ")}`),a.openPageUrl({appId:n,url:e});return}let e=JSON.stringify(ei(i,o)),p=K(i.settings),d=i.mode||"full",c={appId:n,pageId:i.id||"",pageData:e,pageSettings:p,mode:d};a.openPage(c)}else if("widget"===i.type){let e=JSON.stringify(ei(i,o)),t={appId:n,widgetId:i.id,widgetData:e,botId:i.botId};a.pushWidget(t)}else if("tool"===i.type){let e=JSON.stringify({...i.input||{},...r}),t={appId:n,toolId:i.id,toolData:e};a.callTool(t)}}var eA,eO,eI,eT,eP,ek,eL,eN,eR,eD,eM,e$,eB,ej,eU,eW,eF,eH,eV,eG,eq,ez,eJ,eK=((e$={}).Adb="adb",e$.Hdt="hdt",e$.DevTools="devtools",e$);let eY=["adb","hdt","devtools"],eX=h("path"),eQ="./node_modules/.doubao",eZ="./node_modules/.injected.js",e0="widgets";eX.sep;let e1=`base${eX.sep}manifest.json`,e3=`base${eX.sep}manifest.sign`,e2="mcp-privacy-login-card",e4="__doubao_apps__expired-widget",e9="bundle.keystore",e5={"@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"},e8=["Chrome 75","iOS 11"],e6=["iOS >= 9","Android >= 4.4","last 2 versions","> 0.2%","not dead"],e7="main-virtual",te=e=>e===e2||e===e4,tt="app.config",tn=[".js",".ts",".mjs"],ta="com.larus.nova",to=h("node:fs"),ti="@byted-doubao-apps/framework",tr="@doubao-dev/framework",ts=[ti,tr];function tl(e){return`${e}/components`}function tp(e){let t=e_.resolve(e,"package.json");if(to.existsSync(t))try{let e=JSON.parse(to.readFileSync(t,"utf8")),n={...e.dependencies,...e.devDependencies,...e.peerDependencies};if(n[tr])return tr;if(n[ti])return ti}catch{}}function td(e){return tp(e)??ti}let tc=e=>void 0!==process.env[e],tu="DOUBAO_SIMULATOR_MCP_ENDPOINT",tm=()=>tc("DISABLE_EXTERNAL")||tc("LEGACY_FRAMEWORK"),th=()=>tc("DISABLE_APP_TEMPLATE_JS")||tc("LEGACY_FRAMEWORK"),tf=()=>tc("DISABLE_NEW_CONTAINER")||tc("LEGACY_FRAMEWORK");function tg({env:e,mcpEndpoint:t}={}){let n=t?.trim();if(n)return n;let a=e?.[tu]?.trim();return a||(process.env[tu]?.trim()??"")}class tb{}let ty=(0,_.createRequire)(import.meta.url);function tv(e,t=3e3){return Q(e,{timeout:t}).catch(()=>({stdout:"",stderr:""}))}async function tS(e,t){return tv(`adb -s ${e} ${t}`)}async function tw(e){let t=(await tv(`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 t_(e,t){let n=(await tS(e,`shell pidof ${t}`)).stdout.trim();return n?n.split(/\s+/)[0]:void 0}async function tE(e){let t=await tw(e);return(t===ta||"com.flow.aisdk.example"===t)&&(await tv(`adb -s ${e} shell am force-stop ${t}`),await tv(`adb -s ${e} shell monkey -p ${t} -c android.intent.category.LAUNCHER 1`),!0)}async function tx(){return(await tv("adb devices")).stdout.split("\n").slice(1).map(e=>e.split(" ")[0].trim()).filter(Boolean)}async function tC(){let e=await tx();if(e.length>1){let{device:t}=await X.prompt([{type:"search-list",name:"device",message:"检测到多个设备,请选择用于调试的设备(可按设备 ID 搜索):",choices:e,default:e[0]}]);return t}return e[0]}X.registerPrompt("search-list",ty("inquirer-search-list"));class tA extends tb{deviceId;latestLoadParams;lastAppProcessId;isWatchingAppProcess=!1;isAutoReloading=!1;constructor(e,t={}){if(super(),this.deviceId=e,t.skipForegroundAppWatch)return;let n=setInterval(()=>{this.watchAppProcess()},500);process.once("exit",()=>clearInterval(n))}async watchAppProcess(){if(!this.isWatchingAppProcess){this.isWatchingAppProcess=!0;try{let e=await t_(this.deviceId,ta);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 t_(this.deviceId,ta)!==e)return;await this.load(this.latestLoadParams)}finally{this.isAutoReloading=!1}}}async load(e){this.latestLoadParams=e;let{appletUrl:t,appId:n,isSigned:a}=e,o=`shell am broadcast -a com.bytedance.applet.SET_APPLET_DEBUG_HOST --es appletName ${n} --es appletHost ${t} --es appletType 1 --es isSigned ${a}`;"applet0930"===process.env.DEBUG&&console.log(w.dim(`adb -s ${this.deviceId} ${o}`)),await tS(this.deviceId,o)}async openPage(e){let{appId:t,pageId:n,pageData:a,pageSettings:o,mode:i}=e,r=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageName ${n} --es appletPageData '${a}' --es appletPageSettings '${o}' --es mode '${i}'`;"applet0930"===process.env.DEBUG&&console.log(w.dim(`adb -s ${this.deviceId} ${r}`)),await tS(this.deviceId,r)}async openPageUrl(e){let{appId:t,url:n}=e,a=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageUrl '${n}'`;"applet0930"===process.env.DEBUG&&console.log(w.dim(`adb -s ${this.deviceId} ${a}`)),await tS(this.deviceId,a)}async pushWidget(e){let{appId:t,widgetId:n,widgetData:a,botId:o}=e,i=`shell am broadcast -a com.bytedance.applet.START_APPLET_WIDGET --es appletName ${t} --es widgetName ${n} --es widgetData '${a}' --es botId ${o||process.env.DEBUG_BOT_ID}`;"applet0930"===process.env.DEBUG&&console.log(w.dim(`adb -s ${this.deviceId} ${i}`)),await tS(this.deviceId,i)}async callTool(e){let{appId:t,toolId:n,toolData:a}=e,o=`shell am broadcast -a com.bytedance.applet.CALL_TOOL --es appletName ${t} --es toolName '${n}' --es toolData '${a}'`;"applet0930"===process.env.DEBUG&&console.log(w.dim(`adb -s ${this.deviceId} ${o}`)),await tS(this.deviceId,o)}}class tO extends tb{async load(e){}async openPage(e){}async openPageUrl(e){}async pushWidget(e){}async callTool(e){}}ev.child("cli");let tI=ev.child("config"),tT=ev.child("security"),tP=ev.child("build"),tk=tP.withContext({mode:"cloud"}),tL=ev.child("deploy"),tN=ev.child("dev-server");class tR{options;currentUrl=null;debugDriver=null;appId=null;constructor(e){this.options=e}async start(e,t,n){if(null!==this.currentUrl){this.currentUrl=e,this.debugDriver?.getAllAppClients().forEach(e=>this.onConnect(e,n));return}this.currentUrl=e,this.appId=t;let{getDebugDriver:a,toolkitExecutor:o}=await import("./@byted-hdt/cli.js").then(h.bind(h,"../../../node_modules/.pnpm/@byted-hdt+cli@0.0.71_debug@4.4.3/node_modules/@byted-hdt/cli/dist/es/index.js"));await o({runType:"rspeedy",openWebview:this.options.devtool});let i=a();this.debugDriver=i,i.getAllAppClients().forEach(e=>this.onConnect(e,n)),i.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){tN.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 tD extends tb{server;constructor(){super(),this.server=new tR({devtool:!0,open:!0})}async load(e){let{appletUrl:t,appId:n,isSigned:a}=e;this.server.start(t,n,a)}async openPage(e){let{appId:t,pageId:n,pageData:a,pageSettings:o,mode:i}=e;this.server.sendMessage({method:"Applet_OpenPage",params:{appletName:t,appletPageName:n,appletPageData:a,appletPageSettings:o,mode:i}})}async openPageUrl(e){let{appId:t,url:n}=e;this.server.sendMessage({method:"Applet_OpenPageUrl",params:{appletName:t,url:n}})}async pushWidget(e){let{appId:t,widgetId:n,widgetData:a,botId:o}=e;this.server.sendMessage({method:"Applet_OpenWidget",params:{appletName:t,widgetName:n,widgetData:a,botId:o||process.env.DEBUG_BOT_ID}})}async callTool(e){let{appId:t,toolId:n,toolData:a}=e;this.server.sendMessage({method:"Applet_CallTool",params:{appletName:t,toolName:n,toolData:a}})}}async function tM(t={}){if(!e){let n=t.debugDriver??eK.Adb;if(!eY.includes(n))throw Error(`无效的调试驱动 "${n}",可选值:${eY.join(", ")}。`);switch(n){case eK.Hdt:e=new tD;break;case eK.DevTools:e=new tO;break;case eK.Adb:e=new tA(t.deviceId??await tC()??"",{skipForegroundAppWatch:t.skipAdbForegroundAppWatch});break;default:throw Error(`无效的调试驱动 "${n}",可选值:${eY.join(", ")}。`)}}return e}let t$="https://lf3-static.bytednsdoc.com/obj/eden-cn/777eh7nuptpfnuhd/default.svg";function tB(e){if("string"==typeof e){let t=e.length>0?e:t$;return{"1x":t,"2x":t,"3x":t}}return{"1x":e?.["1x"]||t$,"2x":e?.["2x"]||t$,"3x":e?.["3x"]||t$}}(eA=eB||(eB={})).DEV="dev",eA.BUILD="build",eA.PERF="perf",eA.DEPLOY="deploy",eA.ANALYZE="analyze";let tj={DEV:eB.DEV,BUILD:eB.BUILD,PERF:eB.PERF,DEPLOY:eB.DEPLOY,ANALYZE:eB.ANALYZE};function tU(e){let t=Object.keys(e);return t.sort(),t.reduce((t,n)=>(t[n]=e[n],t),{})}class tW{get metadata(){return this._metadata}toString(){return JSON.stringify(this._metadata,null,2)}}class tF extends tW{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,n){let a=this._metadata;return{id:a.id,name:a.name,path:a.path,description:a.description,keywords:a.keywords,digest:t,prop:a.prop,entry:e,renderType:n,title:a.title}}}class tH extends tW{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,n,a=[]){let o=this._metadata;return{widgetId:o.id,name:o.name,description:o.description,keywords:o.keywords,digest:t,prop:o.prop,entry:e,renderType:n,border:o.border,appSettings:a,boxType:"full_box"===o.boxType?eo.FULL_BOX:eo.INBOX,titleType:o.titleType?tH.TITLE_TYPE_MAP[o.titleType]:void 0}}}tH.TITLE_TYPE_MAP={none:2,normal:0,float:1};class tV extends tW{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 tG extends tW{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest({toolsMetadata:e,hashCode:t,appRuntimeEntry:n,appRuntimeType:a}){return{name:this._metadata.name,description:this._metadata.description,appletId:this._metadata.appId,appletEntry:"index",pages:[],keywords:this._metadata.keywords,icons:tB(this._metadata.icons),digest:t,prop:"",tools:Object.values(e).map(e=>e.toManifest()),appRuntimeEntry:n,appRuntimeType:a}}}class tq{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 tG(e)}addToolMeta(e,t){this.metadata.tools[e]?this.metadata.tools[e].assign(t):this.metadata.tools[e]=new tV(t)}addPageMeta(e,t){this.metadata.pages[e]?this.metadata.pages[e].assign(t):this.metadata.pages[e]=new tF(t)}addWidgetMeta(e,t){this.metadata.widgets[e]?this.metadata.widgets[e].assign(t):this.metadata.widgets[e]=new tH(t)}getData(){let{tools:e,pages:t,widgets:n,app:a}=this.metadata;return{app:a.metadata??{},tools:tU(Object.fromEntries(Object.keys(e).map(t=>[t,e[t].metadata]))),pages:tU(Object.fromEntries(Object.keys(t).map(e=>[e,t[e].metadata]))),widgets:tU(Object.fromEntries(Object.keys(n).map(e=>[e,n[e].metadata])))}}getInstance(){let{tools:e,pages:t,widgets:n,app:a}=this.metadata;return{app:a,tools:tU(e),pages:tU(t),widgets:tU(n)}}clearData(){this.metadata={app:{},pages:{},tools:{},widgets:{}}}}let tz={MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE:1e3,MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY:2e3,MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE:3e3},tJ={BEFORE_BUILD_STAGE_CREATE_CONFIG:1e3,BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG:2e3,BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG:3e3},tK={COLLECT_METADATA_STAGE_START:1e3,COLLECT_METADATA_STAGE_PROCESS_METADATA:2e3,COLLECT_METADATA_STAGE_OPTIMIZE:3e3,COLLECT_METADATA_STAGE_FINISH:4e3},tY={...tz,...tJ,...tK},tX={...tz,...tJ,...tK};(eO=ej||(ej={}))[eO.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS=1e3]="BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS",eO[eO.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS=2e3]="BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS",eO[eO.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=3e3]="BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS",eO[eO.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS=3999]="BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS",eO[eO.AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS=4e3]="AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS",eO[eO.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS=5e3]="AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS",eO[eO.AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=6e3]="AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS";let tQ=h("../../../node_modules/.pnpm/tapable@2.2.1/node_modules/tapable/lib/index.js");function tZ(){return{modifyEnvironment:new tQ.FU(["arg0"]),modifyEntryOption:new tQ.BD(["arg0"]),beforeBuild:new tQ.FU(["arg0"]),collectMetaData:new tQ.FU(["arg0"]),build:new tQ.FU(["arg0"]),afterBuild:new tQ.FU(["arg0"])}}function t0({hooks:e,stages:t}){return{hooks:e,...t}}class t1{constructor(e,t=[]){this.plugins=[],this.api={...{worker:t0({hooks:tZ(),stages:tX}),view:t0({hooks:tZ(),stages:tY}),assets:t0({hooks:{beforeEmit:new tQ.FU(["arg0"]),afterEmit:new tQ.FU(["arg0"])},stages:ej}),deploy:t0({hooks:{beforeDeploy:new tQ.FU(["arg0"]),deploy:new tQ.FU(["arg0"]),afterDeploy:new tQ.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,...n){let a=R(this.getScopeHooks(e),t);return await a.promise(...n)}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 t3=h("fs"),t2=h("../../../node_modules/.pnpm/archiver@7.0.1/node_modules/archiver/index.js");function t4(e,t,n,a){return new Promise((o,i)=>{let r=t3.createWriteStream(e),s=t2("zip",{zlib:{level:9}});s.pipe(r),s.directory(t,n??!1),r.on("close",()=>{a?.deleteResource&&t3.rmSync(t,{recursive:!0}),eS.success("Compiled artifacts packaged",{file:eX.basename(e)}),o("")}),s.on("error",e=>{eS.error("An error occurred during packaging",{error:e}),i(e)}),s.finalize()})}async function t9({channelName:e,manifest:t,rootPath:n}){let a=eX.resolve(n),o=eX.resolve(n,"doubao_app_output"),i=eX.resolve(o,t.packageName),r={outputFolder:o,transformFolder:i,manifest:t};t3.existsSync(o)&&t3.rmSync(o,{recursive:!0}),t3.mkdirSync(o),t3.mkdirSync(i),function(e,t){let{transformFolder:n,manifest:a}=t,{applet:o,widgets:i}=a,r=eX.resolve(e,"base"),s=eX.resolve(n,"base");t3.mkdirSync(s),t3.cpSync(r,s,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0});let l=eX.resolve(e,o.appletId),p=eX.resolve(n,o.appletId);t3.mkdirSync(p),o.pages.length>0&&t3.cpSync(l,p,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0}),i.forEach(t=>{let a=eX.resolve(e,t.widgetId),o=eX.resolve(n,t.widgetId);t3.mkdirSync(o),t3.cpSync(a,o,{filter:e=>null===e.match(/(.)*\.map$/),recursive:!0})})}(a,r);let s=await t5(e,r);return eS.debug("Package resource created",{packageResource:s}),{packageResource:s}}async function t5(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:n,outputFolder:a,transformFolder:o}=t,{applet:i,widgets:r,packageName:s,versionCode:l}=n,p=eX.resolve(a,"deploy-package"),d=eX.resolve(p,e),c=eX.resolve(d,s);t3.mkdirSync(p),t3.mkdirSync(d),t3.mkdirSync(c),t3.cpSync(o,c,{recursive:!0});let u={},m=t3.readdirSync(c).filter(e=>t3.statSync(eX.resolve(c,e)).isDirectory()),h=eX.resolve(p,`${e}.zip`);try{if(await Promise.all(m.map(e=>{if("base"===e)return t4(eX.resolve(c,`${e}_${l}.zip`),eX.resolve(c,e),e,{deleteResource:!0});if(e===i.appletId){let t=`${e}_${i.digest}.zip`;return u[i.appletId]=t,t4(eX.resolve(c,t),eX.resolve(c,e),e,{deleteResource:!0})}let t=r.find(t=>t.widgetId===e);if(t){let n=`${e}_${t.digest}.zip`;return u[t.widgetId]=n,t4(eX.resolve(c,n),eX.resolve(c,e),e,{deleteResource:!0})}return eS.error("Invalid package directory",{directory:e}),Promise.resolve()})),await t4(h,d,e),process.env.BUILD_VERSION){let e=eX.resolve(a,"scm-deploy-package"),t=eX.resolve(e,s);t3.mkdirSync(e),t3.mkdirSync(t),t3.cpSync(c,t,{recursive:!0})}return eS.success("Deploy package archived",{destination:h}),{resource:h,fileNames:u}}catch(e){throw Error(`ERROR: Archive the deploy-package failed. ${e}`)}}(eI=eU||(eU={})).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 t8={NORMAL:eU.NORMAL,SELF_BUILT_CREATE:eU.SELF_BUILT_CREATE,SELF_BUILT_PUBLISH:eU.SELF_BUILT_PUBLISH,SELF_BUILT_CHECK_STATUS:eU.SELF_BUILT_CHECK_STATUS,SELF_BUILT_STOP:eU.SELF_BUILT_STOP,SELF_BUILT_ROLLBACK:eU.SELF_BUILT_ROLLBACK};function t6(e,t){let n=(t||e).replace(/^\/+/,"").split("/").filter(Boolean);return n.length>1&&"index"===n[n.length-1]?n[n.length-2]||"index":n[n.length-1]||"index"}function t7(e,t){let n=(t??e).replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"");return n?`/${n}`:"/"}function ne(e,...t){return W(e,...t,(e,t,n)=>Array.isArray(e)?e.concat(t):Buffer.isBuffer(t)?t:void 0)}let nt=(e,t)=>e_.relative(e,t).replaceAll(e_.sep,"/");class nn{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="",n=e.importSpecifiers.find(e=>"default"===e.propertyName),a=e.importSpecifiers.filter(e=>"default"!==e.propertyName);return n&&(t+=`${n.name}`),a.length&&(n&&(t+=", "),t+=`{ ${a.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,t3.existsSync)(t)||(0,t3.mkdirSync)(t,{recursive:!0}),(0,t3.writeFileSync)(this._filename,this.toString(),e)}return this._filename}}function na(e,t,n=!1,a=!1){return Object.keys(e).reduce((o,i)=>{let{filename:r,isVirtualFile:s,isSpecial:l}=e[i];if(s||l)return o;let p=`${eQ}${e_.sep}${i}${e_.extname(r)}`,d=nt(e_.join(t,p,".."),r),c=td(t),u=n?"defineWidget":"definePage";return o[i]=new nn(p),o[i].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:d,importSpecifiers:[{propertyName:"default",name:"TaroView"}]}),o[i].appendContent(`
4
+ const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
5
+
6
+ const View = ${u}({
7
+ render() {
8
+ return <TaroView data={getViewData()} />;
9
+ }
10
+ });
11
+
12
+ const FC = bootstrapReactLynx(View, viewId, ${JSON.stringify(!n)});
13
+
14
+ root.render(<FC />);`,a?`
15
+ if (import.meta.webpackHot) {
16
+ import.meta.webpackHot.accept()
17
+ }
18
+ `:""),o},{})}let no=h("module"),ni="doubao:plugin:taro";function nr(e,t){return`globalThis.__AI_MANIFEST__ = ${JSON.stringify({package:t?.appKey||e.appId,appId:t?.appKey||e.appId,name:t?.appName||e.name,icons:t?.iconUrl?tB(t.iconUrl):e.icons})};
19
+ `}async function ns({compiler:e,compilation:t,assets:n,metadata:a,resolveAppInfo:o,shouldInjectAsset:i}){let r=Object.keys(n).reduce((e,n)=>{if(!i(n))return e;let a=t.getAsset(n);return a&&e.push(a),e},[]);if(0===r.length)return;let s=nr(a.app,await o?.());r.forEach(n=>{if(n.source.source().toString().startsWith(s))return;let a=new e.webpack.sources.ReplaceSource(n.source,n.name);a.insert(0,s),t.updateAsset(n.name,a,n.info)})}function nl(e){let t=eX.posix.basename(e);return"background.js"===t||"main-thread.js"===t||/^background\.[^/]+\.js$/.test(t)||/^main-thread\.[^/]+\.js$/.test(t)}function np(e){let t=e.replaceAll("\\","/");return t.startsWith("__doubao_web__")&&"template.js"===eX.posix.basename(t)}class nd{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(nd.name,t=>{t.hooks.processAssets.tapPromise({name:nd.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async n=>{await ns({compiler:e,compilation:t,assets:n,...this.options})})})}}let nc=/\.(css|less|s[ac]ss)(?:[?#].*)?$/i,nu=e_.join("node_modules",".doubao","worker-style-empty.js"),nm=new WeakMap,nh="index.web.bundle",nf="__doubao_web_app_runtime__";function ng(e,t,n){if("pages"===e&&!n)throw Error("appId is required to resolve Web page entry path");return`${"pages"===e?`${n}/`:""}${t}/${nh}`}function nb(e){return`${e?`${e}/`:""}__doubao_web_app_runtime_entry__/${nh}`}function ny(e){return`__doubao_web__${e.replaceAll("\\","/").replaceAll("/","__")}`}function nv(e,t,n){return t[n]?.id??t6(n,e[n]?.folderName)}function nS(e={},t={},n="configured"){return"all"===n?e:function(e={},t={}){return Object.fromEntries(Object.entries(e).filter(([e])=>t[e]?.web===!0))}(e,t)}function nw(e){return"mixed-all"===e||"web-only-all"===e?"all":"configured"}function n_(e){return"web-only-all"===e||"web-only-configured"===e}class nE{options;workerCompiler=null;workerWatching=null;latestWorkerStats=null;pendingWorkerWatchBuild=null;resolvePendingWorkerWatchBuild=null;rejectPendingWorkerWatchBuild=null;workerStyleResources=new Set;constructor(e){this.options=e}apply(e){let t=new e.webpack.experiments.VirtualModulesPlugin;t.apply(e),e.hooks.make.tapPromise({name:nE.name,stage:-1e3},async n=>{var a,o,i;let r,s=this.getOrCreateWorkerCompiler(),l=(await this.runWorkerCompilation(e,s)).compilation;t.writeModule(eZ,(r=Array.from(new Set(this.workerStyleResources)).map(e=>`import ${JSON.stringify(e)};`)).length>0?`${r.join("\n")}
20
+ `:""),await nx(s,l,this.options.context),a=n,l.getAssets().forEach(e=>{a.getAsset(e.name)?a.updateAsset(e.name,e.source,e.info):a.emitAsset(e.name,e.source,e.info)}),function(e,t){for(let n of t.fileDependencies)e.fileDependencies.add(n);for(let n of t.contextDependencies)e.contextDependencies.add(n);for(let n of t.missingDependencies)e.missingDependencies.add(n);for(let n of t.buildDependencies??[])e.buildDependencies?.add?.(n)}(n,l),o=n,i=l,o.warnings.push(...i.warnings),o.errors.push(...i.errors)}),e.hooks.shutdown.tapPromise(nE.name,async()=>{await this.disposeWorkerCompiler()})}getOrCreateWorkerCompiler(){if(!this.workerCompiler){var e,t;this.workerCompiler=(0,v.rspack)(this.options.workerConfig),e=this.workerCompiler,t=this.workerStyleResources,nm.set(e,t),this.workerCompiler.hooks.beforeRun.tap(nE.name,()=>{this.workerStyleResources.clear()}),this.workerCompiler.hooks.watchRun.tap(nE.name,()=>{this.workerStyleResources.clear()})}return this.workerCompiler}async runWorkerCompilation(e,t){return this.options.context.isDev?this.runWorkerCompilerInWatchMode(t,e):this.runWorkerCompilerOnce(t)}async runWorkerCompilerOnce(e){return new Promise((t,n)=>{e.run((e,a)=>{e?n(e):a?t(a):n(Error("Worker compiler did not return stats."))})})}async runWorkerCompilerInWatchMode(e,t){if(!this.workerWatching){let t=this.createPendingWorkerWatchBuild();return this.workerWatching=e.watch({},(e,t)=>{e?this.finishPendingWorkerWatchBuild(void 0,e):t?(this.latestWorkerStats=t,this.finishPendingWorkerWatchBuild(t)):this.finishPendingWorkerWatchBuild(void 0,Error("Worker compiler did not return stats."))}),t}if(this.workerWatching.running)return this.pendingWorkerWatchBuild??this.createPendingWorkerWatchBuild();if(t.modifiedFiles?.size===0&&t.removedFiles?.size===0){if(!this.latestWorkerStats)throw Error("Worker compiler did not return stats.");return this.latestWorkerStats}let n=this.createPendingWorkerWatchBuild();return"function"==typeof this.workerWatching.invalidateWithChangesAndRemovals?this.workerWatching.invalidateWithChangesAndRemovals(t.modifiedFiles,t.removedFiles):this.workerWatching.invalidate(),n}createPendingWorkerWatchBuild(){return this.pendingWorkerWatchBuild||(this.pendingWorkerWatchBuild=new Promise((e,t)=>{this.resolvePendingWorkerWatchBuild=e,this.rejectPendingWorkerWatchBuild=t})),this.pendingWorkerWatchBuild}finishPendingWorkerWatchBuild(e,t){let n=this.resolvePendingWorkerWatchBuild,a=this.rejectPendingWorkerWatchBuild;(this.pendingWorkerWatchBuild=null,this.resolvePendingWorkerWatchBuild=null,this.rejectPendingWorkerWatchBuild=null,t)?a?.(t):e?n?.(e):a?.(Error("Worker compiler did not return stats."))}async disposeWorkerCompiler(){if(!this.workerCompiler)return;let e=this.workerCompiler,t=null;try{await new Promise((t,n)=>{e.close(e=>{e?n(e):t()})})}catch(e){throw t=e,e}finally{this.finishPendingWorkerWatchBuild(void 0,t??Error("Worker compiler was disposed before build completion.")),nm.delete(e),this.workerWatching=null,this.latestWorkerStats=null,this.workerCompiler=null}}}async function nx(e,t,n){let a=n.metadata.app,o=t.getAsset(n.mainThreadAssetPath),i=o.source.source().toString(),r=nr(a,await n.resolveAppInfo());if(i.startsWith(r))return;let s=new e.webpack.sources.ReplaceSource(o.source,o.name);s.insert(0,r),t.updateAsset(o.name,s,o.info)}let nC=h("../../../node_modules/.pnpm/@lynx-js+type-config@3.6.0/node_modules/@lynx-js/type-config/index.js"),nA=(0,_.createRequire)(import.meta.url);var nO={},nI={};function nT(e){var t=nI[e];if(void 0!==t)return t.exports;var n=nI[e]={exports:{}};return nO[e](n,n.exports,nT),n.exports}nT.m=nO,nT.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return nT.d(t,{a:t}),t},nT.d=(e,t,n)=>{var a=(t,n)=>{for(var a in t)nT.o(t,a)&&!nT.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,[n]:t[a]})};a(t,"get"),a(n,"value")},nT.add=function(e){Object.assign(nT.m,e)},nT.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),nT.add({"../../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"(e){e.exports=(e,t=process.argv)=>{let n=e.startsWith("-")?"":1===e.length?"-":"--",a=t.indexOf(n+e),o=t.indexOf("--");return -1!==a&&(-1===o||a<o)}},"../../../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,n){var a=n("../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js");e.exports=function(e,t){if(!a(e)&&"function"!=typeof e)return{};var n={};if("string"==typeof t)return t in e&&(n[t]=e[t]),n;for(var o=t.length,i=-1;++i<o;){var r=t[i];r in e&&(n[r]=e[r])}return n}},"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(e){let t=process||{},n=t.argv||[],a=t.env||{},o=!(a.NO_COLOR||n.includes("--no-color"))&&(!!a.FORCE_COLOR||n.includes("--color")||"win32"===t.platform||(t.stdout||{}).isTTY&&"dumb"!==a.TERM||!!a.CI),i=(e,t,n=e)=>a=>{let o=""+a,i=o.indexOf(t,e.length);return~i?e+r(o,t,n,i)+t:e+o+t},r=(e,t,n,a)=>{let o="",i=0;do o+=e.substring(i,a)+n,i=a+t.length,a=e.indexOf(t,i);while(~a);return o+e.substring(i)},s=(e=o)=>{let t=e?i:()=>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},"../../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js"(e,t,n){let a,o=n("os"),i=n("tty"),r=n("../../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"),{env:s}=process;function l(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function p(e,t){if(0===a)return 0;if(r("color=16m")||r("color=full")||r("color=truecolor"))return 3;if(r("color=256"))return 2;if(e&&!t&&void 0===a)return 0;let n=a||0;if("dumb"===s.TERM)return n;if("win32"===process.platform){let e=o.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in s)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(e=>e in s)||"codeship"===s.CI_NAME?1:n;if("TEAMCITY_VERSION"in s)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(s.TEAMCITY_VERSION);if("truecolor"===s.COLORTERM)return 3;if("TERM_PROGRAM"in s){let e=parseInt((s.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(s.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(s.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(s.TERM)||"COLORTERM"in s?1:n}r("no-color")||r("no-colors")||r("color=false")||r("color=never")?a=0:(r("color")||r("colors")||r("color=true")||r("color=always"))&&(a=1),"FORCE_COLOR"in s&&(a="true"===s.FORCE_COLOR?1:"false"===s.FORCE_COLOR?0:0===s.FORCE_COLOR.length?1:Math.min(parseInt(s.FORCE_COLOR,10),3)),e.exports={supportsColor:function(e){return l(p(e,e&&e.isTTY))},stdout:l(p(!0,i.isatty(1))),stderr:l(p(!0,i.isatty(2)))}},"../../../node_modules/.pnpm/supports-hyperlinks@3.2.0/node_modules/supports-hyperlinks/index.js"(e,t,n){let a=n("../../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js"),o=n("../../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js");function i(e){if(/^\d{3,4}$/.test(e)){let t=/(\d{1,2})(\d{2})/.exec(e)||[];return{major:0,minor:parseInt(t[1],10),patch:parseInt(t[2],10)}}let t=(e||"").split(".").map(e=>parseInt(e,10));return{major:t[0],minor:t[1],patch:t[2]}}function r(e){let{CI:t,FORCE_HYPERLINK:n,NETLIFY:r,TEAMCITY_VERSION:s,TERM_PROGRAM:l,TERM_PROGRAM_VERSION:p,VTE_VERSION:d,TERM:c}=process.env;if(n)return!(n.length>0&&0===parseInt(n,10));if(o("no-hyperlink")||o("no-hyperlinks")||o("hyperlink=false")||o("hyperlink=never"))return!1;if(o("hyperlink=true")||o("hyperlink=always")||r)return!0;if(!a.supportsColor(e)||e&&!e.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if("win32"===process.platform||t||s)return!1;if(l){let e=i(p||"");switch(l){case"iTerm.app":if(3===e.major)return e.minor>=1;return e.major>3;case"WezTerm":return e.major>=0x1343cac;case"vscode":return e.major>1||1===e.major&&e.minor>=72;case"ghostty":return!0}}if(d){if("0.50.0"===d)return!1;let e=i(d);return e.major>0||e.minor>=50}return"alacritty"===c}e.exports={supportsHyperlink:r,stdout:r(process.stdout),stderr:r(process.stderr)}},os(e){e.exports=nA("os")},tty(e){e.exports=nA("tty")}});let nP=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 nk=globalThis.navigator?.userAgentData?.platform;"macOS"===nk||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform,"Windows"===nk||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform,"Linux"===nk||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform,"iOS"===nk||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),"Android"===nk||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform,nP||b.env.TERM_PROGRAM,nP||b.platform,nP||b.cwd;let nL=nT("../../../node_modules/.pnpm/supports-hyperlinks@3.2.0/node_modules/supports-hyperlinks/index.js");function nN(e,t,{target:n="stdout",...a}={}){return nL[n]?["\x1b]","8",";",";",t,"\x07",e,"\x1b]","8",";",";","\x07"].join(""):!1===a.fallback?e:"function"==typeof a.fallback?a.fallback(e,t):`${e} (\u200B${t}\u200B)`}nN.isSupported=nL.stdout,nN.stderr=(e,t,n={})=>nN(e,t,{target:"stderr",...n}),nN.stderr.isSupported=nL.stderr;let nR=nT("../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js");var nD=nT.n(nR);class nM{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,...nD()(t,this.options.compilerOptionsKeys)},e.encodeData.sourceContent.config={...e.encodeData.sourceContent.config,...nD()(t,this.options.configKeys)},e})})}}let n$=e=>nB.has(e),nB=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"]);(eT=eW||(eW={}))[eT.Start=0]="Start",eT[eT.Property=1]="Property",eT[eT.StringKey=2]="StringKey",eT[eT.NumberKey=3]="NumberKey";let nj=nT("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");var nU=nT.n(nj);let nW=(o=(e,t=!0)=>Object.keys(e).every(t=>(e[t],!0)),i=(e,t,n=!0)=>[!1===n||Object.keys(e).map(t=>(e[t],!0)).every(e=>e)].every(e=>e),Object.assign(r=e=>{if(!1===("object"==typeof e&&null!==e&&!1===Array.isArray(e)&&((e,t=!0)=>(void 0===e.absoluteInContentBound||"boolean"==typeof e.absoluteInContentBound)&&(void 0===e.asyncRedirect||"boolean"==typeof e.asyncRedirect)&&(void 0===e.autoExpose||"boolean"==typeof e.autoExpose)&&(void 0===e.CSSAlignWithLegacyW3C||"boolean"==typeof e.CSSAlignWithLegacyW3C)&&(void 0===e.customCSSInheritanceList||Array.isArray(e.customCSSInheritanceList)&&e.customCSSInheritanceList.every((e,t)=>"string"==typeof e))&&(void 0===e.dataStrictMode||"boolean"==typeof e.dataStrictMode)&&(void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll)&&(void 0===e.disableQuickTracingGC||"boolean"==typeof e.disableQuickTracingGC)&&(void 0===e.enableA11y||"boolean"==typeof e.enableA11y)&&(void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement)&&(void 0===e.enableAsyncInitVideoEngine||"boolean"==typeof e.enableAsyncInitVideoEngine)&&(void 0===e.enableAsyncRequestImage||"boolean"==typeof e.enableAsyncRequestImage)&&(void 0===e.enableAsyncResolveSubtree||"boolean"==typeof e.enableAsyncResolveSubtree)&&(void 0===e.enableCheckExposureOptimize||"boolean"==typeof e.enableCheckExposureOptimize)&&(void 0===e.enableCheckLocalImage||"boolean"==typeof e.enableCheckLocalImage)&&(void 0===e.enableCircularDataCheck||"boolean"==typeof e.enableCircularDataCheck)&&(void 0===e.enableComponentAsyncDecode||"boolean"==typeof e.enableComponentAsyncDecode)&&(void 0===e.enableComponentNullProp||"boolean"==typeof e.enableComponentNullProp)&&(void 0===e.enableCreateViewAsync||"boolean"==typeof e.enableCreateViewAsync)&&(void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance)&&(void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables)&&(void 0===e.enableCSSLazyImport||"boolean"==typeof e.enableCSSLazyImport)&&(void 0===e.enableDisexposureWhenLynxHidden||"boolean"==typeof e.enableDisexposureWhenLynxHidden)&&(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.enableExposureUIMargin||"boolean"==typeof e.enableExposureUIMargin)&&(void 0===e.enableExposureWhenLayout||"boolean"==typeof e.enableExposureWhenLayout)&&(void 0===e.enableExposureWhenReload||"boolean"==typeof e.enableExposureWhenReload)&&(void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew)&&(void 0===e.enableHarmonyNewOverlay||"boolean"==typeof e.enableHarmonyNewOverlay)&&(void 0===e.enableHarmonyVisibleAreaChangeForExposure||"boolean"==typeof e.enableHarmonyVisibleAreaChangeForExposure)&&(void 0===e.enableICU||"boolean"==typeof e.enableICU)&&(void 0===e.enableImageDownsampling||"boolean"==typeof e.enableImageDownsampling)&&(void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException)&&(void 0===e.enableJSDataProcessor||"boolean"==typeof e.enableJSDataProcessor)&&(void 0===e.enableListMoveOperation||"boolean"==typeof e.enableListMoveOperation)&&(void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture)&&(void 0===e.enableListPlug||"boolean"==typeof e.enableListPlug)&&(void 0===e.enableLynxScrollFluency||"number"==typeof e.enableLynxScrollFluency||"boolean"==typeof e.enableLynxScrollFluency)&&(void 0===e.enableMicrotaskPromisePolyfill||"boolean"==typeof e.enableMicrotaskPromisePolyfill)&&(void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch)&&(void 0===e.enableMultiTouchParamsCompatible||"boolean"==typeof e.enableMultiTouchParamsCompatible)&&(void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList)&&(void 0===e.enableNewAnimator||"boolean"==typeof e.enableNewAnimator)&&(void 0===e.enableNewClipMode||"boolean"==typeof e.enableNewClipMode)&&(void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture)&&(void 0===e.enableNewImage||"boolean"==typeof e.enableNewImage)&&(void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver)&&(void 0===e.enableNewListContainer||"boolean"==typeof e.enableNewListContainer)&&(void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin)&&(void 0===e.enablePlatformGesture||"boolean"==typeof e.enablePlatformGesture)&&(void 0===e.enablePropertyBasedSimpleStyle||"boolean"==typeof e.enablePropertyBasedSimpleStyle)&&(void 0===e.enableQueryComponentSync||"boolean"==typeof e.enableQueryComponentSync)&&(void 0===e.enableReactOnlyPropsId||"boolean"==typeof e.enableReactOnlyPropsId)&&(void 0===e.enableReduceInitDataCopy||"boolean"==typeof e.enableReduceInitDataCopy)&&(void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle)&&(void 0===e.enableRemoveComponentExtraData||"boolean"==typeof e.enableRemoveComponentExtraData)&&(void 0===e.enableReuseLoadScriptExports||"boolean"==typeof e.enableReuseLoadScriptExports)&&(void 0===e.enableSignalAPI||"boolean"==typeof e.enableSignalAPI)&&(void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap)&&(void 0===e.enableTextBoringLayout||"boolean"==typeof e.enableTextBoringLayout)&&(void 0===e.enableTextGradientOpt||"boolean"==typeof e.enableTextGradientOpt)&&(void 0===e.enableTextLanguageAlignment||"boolean"==typeof e.enableTextLanguageAlignment)&&(void 0===e.enableTextLayerRender||"boolean"==typeof e.enableTextLayerRender)&&(void 0===e.enableTextLayoutCache||"boolean"==typeof e.enableTextLayoutCache)&&(void 0===e.enableTextNonContiguousLayout||"boolean"==typeof e.enableTextNonContiguousLayout)&&(void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow)&&(void 0===e.enableTextRefactor||"boolean"==typeof e.enableTextRefactor)&&(void 0===e.enableTouchRefactor||"boolean"==typeof e.enableTouchRefactor)&&(void 0===e.enableUIOperationOptimize||"boolean"==typeof e.enableUIOperationOptimize)&&(void 0===e.enableUnifiedPipeline||"boolean"==typeof e.enableUnifiedPipeline)&&(void 0===e.enableUseContextPool||"boolean"==typeof e.enableUseContextPool)&&(void 0===e.enableUseMapBuffer||"boolean"==typeof e.enableUseMapBuffer)&&(void 0===e.enableViewReceiveTouch||"boolean"==typeof e.enableViewReceiveTouch)&&(void 0===e.enableVsyncAlignedFlush||"boolean"==typeof e.enableVsyncAlignedFlush)&&(void 0===e.enableXTextLayoutReused||"boolean"==typeof e.enableXTextLayoutReused)&&(void 0===e.extendedLayoutOnlyOpt||"boolean"==typeof e.extendedLayoutOnlyOpt)&&(void 0===e.extraInfo||"object"==typeof e.extraInfo&&null!==e.extraInfo&&!1===Array.isArray(e.extraInfo)&&o(e.extraInfo,t))&&(void 0===e.flatten||"boolean"==typeof e.flatten)&&(void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp)&&(void 0===e.implicit||"boolean"==typeof e.implicit)&&(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.observerFrameRate||"number"==typeof e.observerFrameRate)&&(void 0===e.pipelineSchedulerConfig||"number"==typeof e.pipelineSchedulerConfig)&&(void 0===e.preferredFps||"string"==typeof e.preferredFps)&&(void 0===e.quirksMode||"string"==typeof e.quirksMode||"boolean"==typeof e.quirksMode)&&(void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope)&&(void 0===e.strictPropType||"boolean"==typeof e.strictPropType)&&(void 0===e.tapSlop||"string"==typeof e.tapSlop)&&(void 0===e.trailNewImage||"boolean"==typeof e.trailNewImage)&&(void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior)&&(void 0===e.useImagePostProcessor||"boolean"==typeof e.useImagePostProcessor)&&(void 0===e.useNewSwiper||"boolean"==typeof e.useNewSwiper)&&(void 0===e.autoResumeAnimation||"boolean"==typeof e.autoResumeAnimation)&&(void 0===e.cli||"string"==typeof e.cli)&&(void 0===e.compileRender||"boolean"==typeof e.compileRender)&&(void 0===e.customData||"string"==typeof e.customData)&&(void 0===e.enableA11yIDMutationObserver||"boolean"==typeof e.enableA11yIDMutationObserver)&&(void 0===e.enableAsyncDisplay||"boolean"==typeof e.enableAsyncDisplay)&&(void 0===e.enableBackgroundShapeLayer||"boolean"==typeof e.enableBackgroundShapeLayer)&&(void 0===e.enableCascadePseudo||"boolean"==typeof e.enableCascadePseudo)&&(void 0===e.enableCheckDataWhenUpdatePage||"boolean"==typeof e.enableCheckDataWhenUpdatePage)&&(void 0===e.enableComponentLayoutOnly||"boolean"==typeof e.enableComponentLayoutOnly)&&(void 0===e.enableGlobalComponentMap||"boolean"==typeof e.enableGlobalComponentMap)&&(void 0===e.enableNativeScheduleCreateViewAsync||"boolean"==typeof e.enableNativeScheduleCreateViewAsync)&&(void 0===e.enableNewAccessibility||"boolean"==typeof e.enableNewAccessibility)&&(void 0===e.enableNewLayoutOnly||"boolean"==typeof e.enableNewLayoutOnly)&&(void 0===e.enableOptPushStyleToBundle||"boolean"==typeof e.enableOptPushStyleToBundle)&&(void 0===e.enableOverlapForAccessibilityElement||"boolean"==typeof e.enableOverlapForAccessibilityElement)&&(void 0===e.fixCSSImportRuleOrder||"boolean"==typeof e.fixCSSImportRuleOrder)&&(void 0===e.forceCalcNewStyle||"boolean"==typeof e.forceCalcNewStyle)&&(void 0===e.reactVersion||"string"==typeof e.reactVersion)&&(void 0===e.redBoxImageSizeWarningThreshold||"number"==typeof e.redBoxImageSizeWarningThreshold)&&(void 0===e.removeComponentElement||"boolean"==typeof e.removeComponentElement)&&(void 0===e.syncImageAttach||"boolean"==typeof e.syncImageAttach)&&(void 0===e.useNewImage||"boolean"==typeof e.useNewImage)&&(void 0===e.version||"string"==typeof e.version)&&(void 0===e.debugInfoOutside||"boolean"==typeof e.debugInfoOutside)&&(void 0===e.defaultDisplayLinear||"boolean"==typeof e.defaultDisplayLinear)&&(void 0===e.defaultOverflowVisible||"boolean"==typeof e.defaultOverflowVisible)&&(void 0===e.disableMultipleCascadeCSS||"boolean"==typeof e.disableMultipleCascadeCSS)&&(void 0===e.enableComponentConfig||"boolean"==typeof e.enableComponentConfig)&&(void 0===e.enableCSSAsyncDecode||"boolean"==typeof e.enableCSSAsyncDecode)&&(void 0===e.enableCSSClassMerge||"boolean"==typeof e.enableCSSClassMerge)&&(void 0===e.enableCSSEngine||"boolean"==typeof e.enableCSSEngine)&&(void 0===e.enableCSSExternalClass||"boolean"==typeof e.enableCSSExternalClass)&&(void 0===e.enableCSSInvalidation||"boolean"==typeof e.enableCSSInvalidation)&&(void 0===e.enableCSSLazyDecode||"boolean"==typeof e.enableCSSLazyDecode)&&(void 0===e.enableCSSSelector||"boolean"==typeof e.enableCSSSelector)&&(void 0===e.enableCSSStrictMode||"boolean"==typeof e.enableCSSStrictMode)&&(void 0===e.enableCSSVariable||"boolean"==typeof e.enableCSSVariable)&&(void 0===e.enableEventRefactor||"boolean"==typeof e.enableEventRefactor)&&(void 0===e.enableFiberArch||"boolean"==typeof e.enableFiberArch)&&(void 0===e.enableFlexibleTemplate||"boolean"==typeof e.enableFlexibleTemplate)&&(void 0===e.enableKeepPageData||"boolean"==typeof e.enableKeepPageData)&&(void 0===e.enableRemoveCSSScope||"boolean"==typeof e.enableRemoveCSSScope)&&(void 0===e.enableSimpleStyling||"boolean"==typeof e.enableSimpleStyling)&&(void 0===e.experimental_encodeQuickjsBytecode||"boolean"==typeof e.experimental_encodeQuickjsBytecode)&&(void 0===e.implicitAnimation||"boolean"==typeof e.implicitAnimation)&&(void 0===e.removeCSSParserLog||"boolean"==typeof e.removeCSSParserLog)&&(void 0===e.targetSdkVersion||"string"==typeof e.targetSdkVersion)&&(void 0===e.templateDebugUrl||"string"==typeof e.templateDebugUrl)&&(0===Object.keys(e).length||Object.keys(e).every(t=>!!["absoluteInContentBound","asyncRedirect","autoExpose","CSSAlignWithLegacyW3C","customCSSInheritanceList","dataStrictMode","disableLongpressAfterScroll","disableQuickTracingGC","enableA11y","enableAccessibilityElement","enableAsyncInitVideoEngine","enableAsyncRequestImage","enableAsyncResolveSubtree","enableCheckExposureOptimize","enableCheckLocalImage","enableCircularDataCheck","enableComponentAsyncDecode","enableComponentNullProp","enableCreateViewAsync","enableCSSInheritance","enableCSSInlineVariables","enableCSSLazyImport","enableDisexposureWhenLynxHidden","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableExposureUIMargin","enableExposureWhenLayout","enableExposureWhenReload","enableFixedNew","enableHarmonyNewOverlay","enableHarmonyVisibleAreaChangeForExposure","enableICU","enableImageDownsampling","enableJsBindingApiThrowException","enableJSDataProcessor","enableListMoveOperation","enableListNewArchitecture","enableListPlug","enableLynxScrollFluency","enableMicrotaskPromisePolyfill","enableMultiTouch","enableMultiTouchParamsCompatible","enableNativeList","enableNewAnimator","enableNewClipMode","enableNewGesture","enableNewImage","enableNewIntersectionObserver","enableNewListContainer","enableNewTransformOrigin","enablePlatformGesture","enablePropertyBasedSimpleStyle","enableQueryComponentSync","enableReactOnlyPropsId","enableReduceInitDataCopy","enableReloadLifecycle","enableRemoveComponentExtraData","enableReuseLoadScriptExports","enableSignalAPI","enableSimultaneousTap","enableTextBoringLayout","enableTextGradientOpt","enableTextLanguageAlignment","enableTextLayerRender","enableTextLayoutCache","enableTextNonContiguousLayout","enableTextOverflow","enableTextRefactor","enableTouchRefactor","enableUIOperationOptimize","enableUnifiedPipeline","enableUseContextPool","enableUseMapBuffer","enableViewReceiveTouch","enableVsyncAlignedFlush","enableXTextLayoutReused","extendedLayoutOnlyOpt","extraInfo","flatten","fontScaleEffectiveOnlyOnSp","implicit","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","observerFrameRate","pipelineSchedulerConfig","preferredFps","quirksMode","removeDescendantSelectorScope","strictPropType","tapSlop","trailNewImage","unifyVWVHBehavior","useImagePostProcessor","useNewSwiper","autoResumeAnimation","cli","compileRender","customData","enableA11yIDMutationObserver","enableAsyncDisplay","enableBackgroundShapeLayer","enableCascadePseudo","enableCheckDataWhenUpdatePage","enableComponentLayoutOnly","enableGlobalComponentMap","enableNativeScheduleCreateViewAsync","enableNewAccessibility","enableNewLayoutOnly","enableOptPushStyleToBundle","enableOverlapForAccessibilityElement","fixCSSImportRuleOrder","forceCalcNewStyle","reactVersion","redBoxImageSizeWarningThreshold","removeComponentElement","syncImageAttach","useNewImage","version","debugInfoOutside","defaultDisplayLinear","defaultOverflowVisible","disableMultipleCascadeCSS","enableComponentConfig","enableCSSAsyncDecode","enableCSSClassMerge","enableCSSEngine","enableCSSExternalClass","enableCSSInvalidation","enableCSSLazyDecode","enableCSSSelector","enableCSSStrictMode","enableCSSVariable","enableEventRefactor","enableFiberArch","enableFlexibleTemplate","enableKeepPageData","enableRemoveCSSScope","enableSimpleStyling","experimental_encodeQuickjsBytecode","implicitAnimation","removeCSSParserLog","targetSdkVersion","templateDebugUrl"].some(e=>t===e)||void 0===e[t])))(e,!0))){var t;t=n=[],a=(e,n)=>(e&&(e=>{if(0===t.length)return!0;let n=t[t.length-1].path;return e.length>n.length||n.substring(0,e.length)!==e})(n.path)&&(void 0===n.value&&(n.description??=`The value at this path is \`undefined\`.
21
+
22
+ Please fill the \`${n.expected}\` typed value next time.`),t.push(n)),!1),((e,t,n=!0)=>("object"==typeof e&&null!==e&&!1===Array.isArray(e)||a(!0,{path:t+"",expected:"Config",value:e}))&&((e,t,n=!0)=>[void 0===e.absoluteInContentBound||"boolean"==typeof e.absoluteInContentBound||a(n,{path:t+".absoluteInContentBound",expected:"(boolean | undefined)",value:e.absoluteInContentBound}),void 0===e.asyncRedirect||"boolean"==typeof e.asyncRedirect||a(n,{path:t+".asyncRedirect",expected:"(boolean | undefined)",value:e.asyncRedirect}),void 0===e.autoExpose||"boolean"==typeof e.autoExpose||a(n,{path:t+".autoExpose",expected:"(boolean | undefined)",value:e.autoExpose}),void 0===e.CSSAlignWithLegacyW3C||"boolean"==typeof e.CSSAlignWithLegacyW3C||a(n,{path:t+".CSSAlignWithLegacyW3C",expected:"(boolean | undefined)",value:e.CSSAlignWithLegacyW3C}),void 0===e.customCSSInheritanceList||(Array.isArray(e.customCSSInheritanceList)||a(n,{path:t+".customCSSInheritanceList",expected:"(Array<string> | undefined)",value:e.customCSSInheritanceList}))&&e.customCSSInheritanceList.map((e,o)=>"string"==typeof e||a(n,{path:t+".customCSSInheritanceList["+o+"]",expected:"string",value:e})).every(e=>e)||a(n,{path:t+".customCSSInheritanceList",expected:"(Array<string> | undefined)",value:e.customCSSInheritanceList}),void 0===e.dataStrictMode||"boolean"==typeof e.dataStrictMode||a(n,{path:t+".dataStrictMode",expected:"(boolean | undefined)",value:e.dataStrictMode}),void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll||a(n,{path:t+".disableLongpressAfterScroll",expected:"(boolean | undefined)",value:e.disableLongpressAfterScroll}),void 0===e.disableQuickTracingGC||"boolean"==typeof e.disableQuickTracingGC||a(n,{path:t+".disableQuickTracingGC",expected:"(boolean | undefined)",value:e.disableQuickTracingGC}),void 0===e.enableA11y||"boolean"==typeof e.enableA11y||a(n,{path:t+".enableA11y",expected:"(boolean | undefined)",value:e.enableA11y}),void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement||a(n,{path:t+".enableAccessibilityElement",expected:"(boolean | undefined)",value:e.enableAccessibilityElement}),void 0===e.enableAsyncInitVideoEngine||"boolean"==typeof e.enableAsyncInitVideoEngine||a(n,{path:t+".enableAsyncInitVideoEngine",expected:"(boolean | undefined)",value:e.enableAsyncInitVideoEngine}),void 0===e.enableAsyncRequestImage||"boolean"==typeof e.enableAsyncRequestImage||a(n,{path:t+".enableAsyncRequestImage",expected:"(boolean | undefined)",value:e.enableAsyncRequestImage}),void 0===e.enableAsyncResolveSubtree||"boolean"==typeof e.enableAsyncResolveSubtree||a(n,{path:t+".enableAsyncResolveSubtree",expected:"(boolean | undefined)",value:e.enableAsyncResolveSubtree}),void 0===e.enableCheckExposureOptimize||"boolean"==typeof e.enableCheckExposureOptimize||a(n,{path:t+".enableCheckExposureOptimize",expected:"(boolean | undefined)",value:e.enableCheckExposureOptimize}),void 0===e.enableCheckLocalImage||"boolean"==typeof e.enableCheckLocalImage||a(n,{path:t+".enableCheckLocalImage",expected:"(boolean | undefined)",value:e.enableCheckLocalImage}),void 0===e.enableCircularDataCheck||"boolean"==typeof e.enableCircularDataCheck||a(n,{path:t+".enableCircularDataCheck",expected:"(boolean | undefined)",value:e.enableCircularDataCheck}),void 0===e.enableComponentAsyncDecode||"boolean"==typeof e.enableComponentAsyncDecode||a(n,{path:t+".enableComponentAsyncDecode",expected:"(boolean | undefined)",value:e.enableComponentAsyncDecode}),void 0===e.enableComponentNullProp||"boolean"==typeof e.enableComponentNullProp||a(n,{path:t+".enableComponentNullProp",expected:"(boolean | undefined)",value:e.enableComponentNullProp}),void 0===e.enableCreateViewAsync||"boolean"==typeof e.enableCreateViewAsync||a(n,{path:t+".enableCreateViewAsync",expected:"(boolean | undefined)",value:e.enableCreateViewAsync}),void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance||a(n,{path:t+".enableCSSInheritance",expected:"(boolean | undefined)",value:e.enableCSSInheritance}),void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables||a(n,{path:t+".enableCSSInlineVariables",expected:"(boolean | undefined)",value:e.enableCSSInlineVariables}),void 0===e.enableCSSLazyImport||"boolean"==typeof e.enableCSSLazyImport||a(n,{path:t+".enableCSSLazyImport",expected:"(boolean | undefined)",value:e.enableCSSLazyImport}),void 0===e.enableDisexposureWhenLynxHidden||"boolean"==typeof e.enableDisexposureWhenLynxHidden||a(n,{path:t+".enableDisexposureWhenLynxHidden",expected:"(boolean | undefined)",value:e.enableDisexposureWhenLynxHidden}),void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp||a(n,{path:t+".enableEndGestureAtLastFingerUp",expected:"(boolean | undefined)",value:e.enableEndGestureAtLastFingerUp}),void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor||a(n,{path:t+".enableEventHandleRefactor",expected:"(boolean | undefined)",value:e.enableEventHandleRefactor}),void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough||a(n,{path:t+".enableEventThrough",expected:"(boolean | undefined)",value:e.enableEventThrough}),void 0===e.enableExposureUIMargin||"boolean"==typeof e.enableExposureUIMargin||a(n,{path:t+".enableExposureUIMargin",expected:"(boolean | undefined)",value:e.enableExposureUIMargin}),void 0===e.enableExposureWhenLayout||"boolean"==typeof e.enableExposureWhenLayout||a(n,{path:t+".enableExposureWhenLayout",expected:"(boolean | undefined)",value:e.enableExposureWhenLayout}),void 0===e.enableExposureWhenReload||"boolean"==typeof e.enableExposureWhenReload||a(n,{path:t+".enableExposureWhenReload",expected:"(boolean | undefined)",value:e.enableExposureWhenReload}),void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew||a(n,{path:t+".enableFixedNew",expected:"(boolean | undefined)",value:e.enableFixedNew}),void 0===e.enableHarmonyNewOverlay||"boolean"==typeof e.enableHarmonyNewOverlay||a(n,{path:t+".enableHarmonyNewOverlay",expected:"(boolean | undefined)",value:e.enableHarmonyNewOverlay}),void 0===e.enableHarmonyVisibleAreaChangeForExposure||"boolean"==typeof e.enableHarmonyVisibleAreaChangeForExposure||a(n,{path:t+".enableHarmonyVisibleAreaChangeForExposure",expected:"(boolean | undefined)",value:e.enableHarmonyVisibleAreaChangeForExposure}),void 0===e.enableICU||"boolean"==typeof e.enableICU||a(n,{path:t+".enableICU",expected:"(boolean | undefined)",value:e.enableICU}),void 0===e.enableImageDownsampling||"boolean"==typeof e.enableImageDownsampling||a(n,{path:t+".enableImageDownsampling",expected:"(boolean | undefined)",value:e.enableImageDownsampling}),void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException||a(n,{path:t+".enableJsBindingApiThrowException",expected:"(boolean | undefined)",value:e.enableJsBindingApiThrowException}),void 0===e.enableJSDataProcessor||"boolean"==typeof e.enableJSDataProcessor||a(n,{path:t+".enableJSDataProcessor",expected:"(boolean | undefined)",value:e.enableJSDataProcessor}),void 0===e.enableListMoveOperation||"boolean"==typeof e.enableListMoveOperation||a(n,{path:t+".enableListMoveOperation",expected:"(boolean | undefined)",value:e.enableListMoveOperation}),void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture||a(n,{path:t+".enableListNewArchitecture",expected:"(boolean | undefined)",value:e.enableListNewArchitecture}),void 0===e.enableListPlug||"boolean"==typeof e.enableListPlug||a(n,{path:t+".enableListPlug",expected:"(boolean | undefined)",value:e.enableListPlug}),void 0===e.enableLynxScrollFluency||"number"==typeof e.enableLynxScrollFluency||"boolean"==typeof e.enableLynxScrollFluency||a(n,{path:t+".enableLynxScrollFluency",expected:"(boolean | number | undefined)",value:e.enableLynxScrollFluency}),void 0===e.enableMicrotaskPromisePolyfill||"boolean"==typeof e.enableMicrotaskPromisePolyfill||a(n,{path:t+".enableMicrotaskPromisePolyfill",expected:"(boolean | undefined)",value:e.enableMicrotaskPromisePolyfill}),void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch||a(n,{path:t+".enableMultiTouch",expected:"(boolean | undefined)",value:e.enableMultiTouch}),void 0===e.enableMultiTouchParamsCompatible||"boolean"==typeof e.enableMultiTouchParamsCompatible||a(n,{path:t+".enableMultiTouchParamsCompatible",expected:"(boolean | undefined)",value:e.enableMultiTouchParamsCompatible}),void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList||a(n,{path:t+".enableNativeList",expected:"(boolean | undefined)",value:e.enableNativeList}),void 0===e.enableNewAnimator||"boolean"==typeof e.enableNewAnimator||a(n,{path:t+".enableNewAnimator",expected:"(boolean | undefined)",value:e.enableNewAnimator}),void 0===e.enableNewClipMode||"boolean"==typeof e.enableNewClipMode||a(n,{path:t+".enableNewClipMode",expected:"(boolean | undefined)",value:e.enableNewClipMode}),void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture||a(n,{path:t+".enableNewGesture",expected:"(boolean | undefined)",value:e.enableNewGesture}),void 0===e.enableNewImage||"boolean"==typeof e.enableNewImage||a(n,{path:t+".enableNewImage",expected:"(boolean | undefined)",value:e.enableNewImage}),void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver||a(n,{path:t+".enableNewIntersectionObserver",expected:"(boolean | undefined)",value:e.enableNewIntersectionObserver}),void 0===e.enableNewListContainer||"boolean"==typeof e.enableNewListContainer||a(n,{path:t+".enableNewListContainer",expected:"(boolean | undefined)",value:e.enableNewListContainer}),void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin||a(n,{path:t+".enableNewTransformOrigin",expected:"(boolean | undefined)",value:e.enableNewTransformOrigin}),void 0===e.enablePlatformGesture||"boolean"==typeof e.enablePlatformGesture||a(n,{path:t+".enablePlatformGesture",expected:"(boolean | undefined)",value:e.enablePlatformGesture}),void 0===e.enablePropertyBasedSimpleStyle||"boolean"==typeof e.enablePropertyBasedSimpleStyle||a(n,{path:t+".enablePropertyBasedSimpleStyle",expected:"(boolean | undefined)",value:e.enablePropertyBasedSimpleStyle}),void 0===e.enableQueryComponentSync||"boolean"==typeof e.enableQueryComponentSync||a(n,{path:t+".enableQueryComponentSync",expected:"(boolean | undefined)",value:e.enableQueryComponentSync}),void 0===e.enableReactOnlyPropsId||"boolean"==typeof e.enableReactOnlyPropsId||a(n,{path:t+".enableReactOnlyPropsId",expected:"(boolean | undefined)",value:e.enableReactOnlyPropsId}),void 0===e.enableReduceInitDataCopy||"boolean"==typeof e.enableReduceInitDataCopy||a(n,{path:t+".enableReduceInitDataCopy",expected:"(boolean | undefined)",value:e.enableReduceInitDataCopy}),void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle||a(n,{path:t+".enableReloadLifecycle",expected:"(boolean | undefined)",value:e.enableReloadLifecycle}),void 0===e.enableRemoveComponentExtraData||"boolean"==typeof e.enableRemoveComponentExtraData||a(n,{path:t+".enableRemoveComponentExtraData",expected:"(boolean | undefined)",value:e.enableRemoveComponentExtraData}),void 0===e.enableReuseLoadScriptExports||"boolean"==typeof e.enableReuseLoadScriptExports||a(n,{path:t+".enableReuseLoadScriptExports",expected:"(boolean | undefined)",value:e.enableReuseLoadScriptExports}),void 0===e.enableSignalAPI||"boolean"==typeof e.enableSignalAPI||a(n,{path:t+".enableSignalAPI",expected:"(boolean | undefined)",value:e.enableSignalAPI}),void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap||a(n,{path:t+".enableSimultaneousTap",expected:"(boolean | undefined)",value:e.enableSimultaneousTap}),void 0===e.enableTextBoringLayout||"boolean"==typeof e.enableTextBoringLayout||a(n,{path:t+".enableTextBoringLayout",expected:"(boolean | undefined)",value:e.enableTextBoringLayout}),void 0===e.enableTextGradientOpt||"boolean"==typeof e.enableTextGradientOpt||a(n,{path:t+".enableTextGradientOpt",expected:"(boolean | undefined)",value:e.enableTextGradientOpt}),void 0===e.enableTextLanguageAlignment||"boolean"==typeof e.enableTextLanguageAlignment||a(n,{path:t+".enableTextLanguageAlignment",expected:"(boolean | undefined)",value:e.enableTextLanguageAlignment}),void 0===e.enableTextLayerRender||"boolean"==typeof e.enableTextLayerRender||a(n,{path:t+".enableTextLayerRender",expected:"(boolean | undefined)",value:e.enableTextLayerRender}),void 0===e.enableTextLayoutCache||"boolean"==typeof e.enableTextLayoutCache||a(n,{path:t+".enableTextLayoutCache",expected:"(boolean | undefined)",value:e.enableTextLayoutCache}),void 0===e.enableTextNonContiguousLayout||"boolean"==typeof e.enableTextNonContiguousLayout||a(n,{path:t+".enableTextNonContiguousLayout",expected:"(boolean | undefined)",value:e.enableTextNonContiguousLayout}),void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow||a(n,{path:t+".enableTextOverflow",expected:"(boolean | undefined)",value:e.enableTextOverflow}),void 0===e.enableTextRefactor||"boolean"==typeof e.enableTextRefactor||a(n,{path:t+".enableTextRefactor",expected:"(boolean | undefined)",value:e.enableTextRefactor}),void 0===e.enableTouchRefactor||"boolean"==typeof e.enableTouchRefactor||a(n,{path:t+".enableTouchRefactor",expected:"(boolean | undefined)",value:e.enableTouchRefactor}),void 0===e.enableUIOperationOptimize||"boolean"==typeof e.enableUIOperationOptimize||a(n,{path:t+".enableUIOperationOptimize",expected:"(boolean | undefined)",value:e.enableUIOperationOptimize}),void 0===e.enableUnifiedPipeline||"boolean"==typeof e.enableUnifiedPipeline||a(n,{path:t+".enableUnifiedPipeline",expected:"(boolean | undefined)",value:e.enableUnifiedPipeline}),void 0===e.enableUseContextPool||"boolean"==typeof e.enableUseContextPool||a(n,{path:t+".enableUseContextPool",expected:"(boolean | undefined)",value:e.enableUseContextPool}),void 0===e.enableUseMapBuffer||"boolean"==typeof e.enableUseMapBuffer||a(n,{path:t+".enableUseMapBuffer",expected:"(boolean | undefined)",value:e.enableUseMapBuffer}),void 0===e.enableViewReceiveTouch||"boolean"==typeof e.enableViewReceiveTouch||a(n,{path:t+".enableViewReceiveTouch",expected:"(boolean | undefined)",value:e.enableViewReceiveTouch}),void 0===e.enableVsyncAlignedFlush||"boolean"==typeof e.enableVsyncAlignedFlush||a(n,{path:t+".enableVsyncAlignedFlush",expected:"(boolean | undefined)",value:e.enableVsyncAlignedFlush}),void 0===e.enableXTextLayoutReused||"boolean"==typeof e.enableXTextLayoutReused||a(n,{path:t+".enableXTextLayoutReused",expected:"(boolean | undefined)",value:e.enableXTextLayoutReused}),void 0===e.extendedLayoutOnlyOpt||"boolean"==typeof e.extendedLayoutOnlyOpt||a(n,{path:t+".extendedLayoutOnlyOpt",expected:"(boolean | undefined)",value:e.extendedLayoutOnlyOpt}),void 0===e.extraInfo||("object"==typeof e.extraInfo&&null!==e.extraInfo&&!1===Array.isArray(e.extraInfo)||a(n,{path:t+".extraInfo",expected:"(Record<string, unknown> | undefined)",value:e.extraInfo}))&&i(e.extraInfo,t+".extraInfo",n)||a(n,{path:t+".extraInfo",expected:"(Record<string, unknown> | undefined)",value:e.extraInfo}),void 0===e.flatten||"boolean"==typeof e.flatten||a(n,{path:t+".flatten",expected:"(boolean | undefined)",value:e.flatten}),void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp||a(n,{path:t+".fontScaleEffectiveOnlyOnSp",expected:"(boolean | undefined)",value:e.fontScaleEffectiveOnlyOnSp}),void 0===e.implicit||"boolean"==typeof e.implicit||a(n,{path:t+".implicit",expected:"(boolean | undefined)",value:e.implicit}),void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding||a(n,{path:t+".includeFontPadding",expected:"(boolean | undefined)",value:e.includeFontPadding}),void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight||a(n,{path:t+".keyboardCallbackPassRelativeHeight",expected:"(boolean | undefined)",value:e.keyboardCallbackPassRelativeHeight}),void 0===e.longPressDuration||"number"==typeof e.longPressDuration||a(n,{path:t+".longPressDuration",expected:"(number | undefined)",value:e.longPressDuration}),void 0===e.observerFrameRate||"number"==typeof e.observerFrameRate||a(n,{path:t+".observerFrameRate",expected:"(number | undefined)",value:e.observerFrameRate}),void 0===e.pipelineSchedulerConfig||"number"==typeof e.pipelineSchedulerConfig||a(n,{path:t+".pipelineSchedulerConfig",expected:"(number | undefined)",value:e.pipelineSchedulerConfig}),void 0===e.preferredFps||"string"==typeof e.preferredFps||a(n,{path:t+".preferredFps",expected:"(string | undefined)",value:e.preferredFps}),void 0===e.quirksMode||"string"==typeof e.quirksMode||"boolean"==typeof e.quirksMode||a(n,{path:t+".quirksMode",expected:"(boolean | string | undefined)",value:e.quirksMode}),void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope||a(n,{path:t+".removeDescendantSelectorScope",expected:"(boolean | undefined)",value:e.removeDescendantSelectorScope}),void 0===e.strictPropType||"boolean"==typeof e.strictPropType||a(n,{path:t+".strictPropType",expected:"(boolean | undefined)",value:e.strictPropType}),void 0===e.tapSlop||"string"==typeof e.tapSlop||a(n,{path:t+".tapSlop",expected:"(string | undefined)",value:e.tapSlop}),void 0===e.trailNewImage||"boolean"==typeof e.trailNewImage||a(n,{path:t+".trailNewImage",expected:"(boolean | undefined)",value:e.trailNewImage}),void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior||a(n,{path:t+".unifyVWVHBehavior",expected:"(boolean | undefined)",value:e.unifyVWVHBehavior}),void 0===e.useImagePostProcessor||"boolean"==typeof e.useImagePostProcessor||a(n,{path:t+".useImagePostProcessor",expected:"(boolean | undefined)",value:e.useImagePostProcessor}),void 0===e.useNewSwiper||"boolean"==typeof e.useNewSwiper||a(n,{path:t+".useNewSwiper",expected:"(boolean | undefined)",value:e.useNewSwiper}),void 0===e.autoResumeAnimation||"boolean"==typeof e.autoResumeAnimation||a(n,{path:t+".autoResumeAnimation",expected:"(boolean | undefined)",value:e.autoResumeAnimation}),void 0===e.cli||"string"==typeof e.cli||a(n,{path:t+".cli",expected:"(string | undefined)",value:e.cli}),void 0===e.compileRender||"boolean"==typeof e.compileRender||a(n,{path:t+".compileRender",expected:"(boolean | undefined)",value:e.compileRender}),void 0===e.customData||"string"==typeof e.customData||a(n,{path:t+".customData",expected:"(string | undefined)",value:e.customData}),void 0===e.enableA11yIDMutationObserver||"boolean"==typeof e.enableA11yIDMutationObserver||a(n,{path:t+".enableA11yIDMutationObserver",expected:"(boolean | undefined)",value:e.enableA11yIDMutationObserver}),void 0===e.enableAsyncDisplay||"boolean"==typeof e.enableAsyncDisplay||a(n,{path:t+".enableAsyncDisplay",expected:"(boolean | undefined)",value:e.enableAsyncDisplay}),void 0===e.enableBackgroundShapeLayer||"boolean"==typeof e.enableBackgroundShapeLayer||a(n,{path:t+".enableBackgroundShapeLayer",expected:"(boolean | undefined)",value:e.enableBackgroundShapeLayer}),void 0===e.enableCascadePseudo||"boolean"==typeof e.enableCascadePseudo||a(n,{path:t+".enableCascadePseudo",expected:"(boolean | undefined)",value:e.enableCascadePseudo}),void 0===e.enableCheckDataWhenUpdatePage||"boolean"==typeof e.enableCheckDataWhenUpdatePage||a(n,{path:t+".enableCheckDataWhenUpdatePage",expected:"(boolean | undefined)",value:e.enableCheckDataWhenUpdatePage}),void 0===e.enableComponentLayoutOnly||"boolean"==typeof e.enableComponentLayoutOnly||a(n,{path:t+".enableComponentLayoutOnly",expected:"(boolean | undefined)",value:e.enableComponentLayoutOnly}),void 0===e.enableGlobalComponentMap||"boolean"==typeof e.enableGlobalComponentMap||a(n,{path:t+".enableGlobalComponentMap",expected:"(boolean | undefined)",value:e.enableGlobalComponentMap}),void 0===e.enableNativeScheduleCreateViewAsync||"boolean"==typeof e.enableNativeScheduleCreateViewAsync||a(n,{path:t+".enableNativeScheduleCreateViewAsync",expected:"(boolean | undefined)",value:e.enableNativeScheduleCreateViewAsync}),void 0===e.enableNewAccessibility||"boolean"==typeof e.enableNewAccessibility||a(n,{path:t+".enableNewAccessibility",expected:"(boolean | undefined)",value:e.enableNewAccessibility}),void 0===e.enableNewLayoutOnly||"boolean"==typeof e.enableNewLayoutOnly||a(n,{path:t+".enableNewLayoutOnly",expected:"(boolean | undefined)",value:e.enableNewLayoutOnly}),void 0===e.enableOptPushStyleToBundle||"boolean"==typeof e.enableOptPushStyleToBundle||a(n,{path:t+".enableOptPushStyleToBundle",expected:"(boolean | undefined)",value:e.enableOptPushStyleToBundle}),void 0===e.enableOverlapForAccessibilityElement||"boolean"==typeof e.enableOverlapForAccessibilityElement||a(n,{path:t+".enableOverlapForAccessibilityElement",expected:"(boolean | undefined)",value:e.enableOverlapForAccessibilityElement}),void 0===e.fixCSSImportRuleOrder||"boolean"==typeof e.fixCSSImportRuleOrder||a(n,{path:t+".fixCSSImportRuleOrder",expected:"(boolean | undefined)",value:e.fixCSSImportRuleOrder}),void 0===e.forceCalcNewStyle||"boolean"==typeof e.forceCalcNewStyle||a(n,{path:t+".forceCalcNewStyle",expected:"(boolean | undefined)",value:e.forceCalcNewStyle}),void 0===e.reactVersion||"string"==typeof e.reactVersion||a(n,{path:t+".reactVersion",expected:"(string | undefined)",value:e.reactVersion}),void 0===e.redBoxImageSizeWarningThreshold||"number"==typeof e.redBoxImageSizeWarningThreshold||a(n,{path:t+".redBoxImageSizeWarningThreshold",expected:"(number | undefined)",value:e.redBoxImageSizeWarningThreshold}),void 0===e.removeComponentElement||"boolean"==typeof e.removeComponentElement||a(n,{path:t+".removeComponentElement",expected:"(boolean | undefined)",value:e.removeComponentElement}),void 0===e.syncImageAttach||"boolean"==typeof e.syncImageAttach||a(n,{path:t+".syncImageAttach",expected:"(boolean | undefined)",value:e.syncImageAttach}),void 0===e.useNewImage||"boolean"==typeof e.useNewImage||a(n,{path:t+".useNewImage",expected:"(boolean | undefined)",value:e.useNewImage}),void 0===e.version||"string"==typeof e.version||a(n,{path:t+".version",expected:"(string | undefined)",value:e.version}),void 0===e.debugInfoOutside||"boolean"==typeof e.debugInfoOutside||a(n,{path:t+".debugInfoOutside",expected:"(boolean | undefined)",value:e.debugInfoOutside}),void 0===e.defaultDisplayLinear||"boolean"==typeof e.defaultDisplayLinear||a(n,{path:t+".defaultDisplayLinear",expected:"(boolean | undefined)",value:e.defaultDisplayLinear}),void 0===e.defaultOverflowVisible||"boolean"==typeof e.defaultOverflowVisible||a(n,{path:t+".defaultOverflowVisible",expected:"(boolean | undefined)",value:e.defaultOverflowVisible}),void 0===e.disableMultipleCascadeCSS||"boolean"==typeof e.disableMultipleCascadeCSS||a(n,{path:t+".disableMultipleCascadeCSS",expected:"(boolean | undefined)",value:e.disableMultipleCascadeCSS}),void 0===e.enableComponentConfig||"boolean"==typeof e.enableComponentConfig||a(n,{path:t+".enableComponentConfig",expected:"(boolean | undefined)",value:e.enableComponentConfig}),void 0===e.enableCSSAsyncDecode||"boolean"==typeof e.enableCSSAsyncDecode||a(n,{path:t+".enableCSSAsyncDecode",expected:"(boolean | undefined)",value:e.enableCSSAsyncDecode}),void 0===e.enableCSSClassMerge||"boolean"==typeof e.enableCSSClassMerge||a(n,{path:t+".enableCSSClassMerge",expected:"(boolean | undefined)",value:e.enableCSSClassMerge}),void 0===e.enableCSSEngine||"boolean"==typeof e.enableCSSEngine||a(n,{path:t+".enableCSSEngine",expected:"(boolean | undefined)",value:e.enableCSSEngine}),void 0===e.enableCSSExternalClass||"boolean"==typeof e.enableCSSExternalClass||a(n,{path:t+".enableCSSExternalClass",expected:"(boolean | undefined)",value:e.enableCSSExternalClass}),void 0===e.enableCSSInvalidation||"boolean"==typeof e.enableCSSInvalidation||a(n,{path:t+".enableCSSInvalidation",expected:"(boolean | undefined)",value:e.enableCSSInvalidation}),void 0===e.enableCSSLazyDecode||"boolean"==typeof e.enableCSSLazyDecode||a(n,{path:t+".enableCSSLazyDecode",expected:"(boolean | undefined)",value:e.enableCSSLazyDecode}),void 0===e.enableCSSSelector||"boolean"==typeof e.enableCSSSelector||a(n,{path:t+".enableCSSSelector",expected:"(boolean | undefined)",value:e.enableCSSSelector}),void 0===e.enableCSSStrictMode||"boolean"==typeof e.enableCSSStrictMode||a(n,{path:t+".enableCSSStrictMode",expected:"(boolean | undefined)",value:e.enableCSSStrictMode}),void 0===e.enableCSSVariable||"boolean"==typeof e.enableCSSVariable||a(n,{path:t+".enableCSSVariable",expected:"(boolean | undefined)",value:e.enableCSSVariable}),void 0===e.enableEventRefactor||"boolean"==typeof e.enableEventRefactor||a(n,{path:t+".enableEventRefactor",expected:"(boolean | undefined)",value:e.enableEventRefactor}),void 0===e.enableFiberArch||"boolean"==typeof e.enableFiberArch||a(n,{path:t+".enableFiberArch",expected:"(boolean | undefined)",value:e.enableFiberArch}),void 0===e.enableFlexibleTemplate||"boolean"==typeof e.enableFlexibleTemplate||a(n,{path:t+".enableFlexibleTemplate",expected:"(boolean | undefined)",value:e.enableFlexibleTemplate}),void 0===e.enableKeepPageData||"boolean"==typeof e.enableKeepPageData||a(n,{path:t+".enableKeepPageData",expected:"(boolean | undefined)",value:e.enableKeepPageData}),void 0===e.enableRemoveCSSScope||"boolean"==typeof e.enableRemoveCSSScope||a(n,{path:t+".enableRemoveCSSScope",expected:"(boolean | undefined)",value:e.enableRemoveCSSScope}),void 0===e.enableSimpleStyling||"boolean"==typeof e.enableSimpleStyling||a(n,{path:t+".enableSimpleStyling",expected:"(boolean | undefined)",value:e.enableSimpleStyling}),void 0===e.experimental_encodeQuickjsBytecode||"boolean"==typeof e.experimental_encodeQuickjsBytecode||a(n,{path:t+".experimental_encodeQuickjsBytecode",expected:"(boolean | undefined)",value:e.experimental_encodeQuickjsBytecode}),void 0===e.implicitAnimation||"boolean"==typeof e.implicitAnimation||a(n,{path:t+".implicitAnimation",expected:"(boolean | undefined)",value:e.implicitAnimation}),void 0===e.removeCSSParserLog||"boolean"==typeof e.removeCSSParserLog||a(n,{path:t+".removeCSSParserLog",expected:"(boolean | undefined)",value:e.removeCSSParserLog}),void 0===e.targetSdkVersion||"string"==typeof e.targetSdkVersion||a(n,{path:t+".targetSdkVersion",expected:"(string | undefined)",value:e.targetSdkVersion}),void 0===e.templateDebugUrl||"string"==typeof e.templateDebugUrl||a(n,{path:t+".templateDebugUrl",expected:"(string | undefined)",value:e.templateDebugUrl}),0===Object.keys(e).length||!1===n||Object.keys(e).map(o=>{let i;if(["absoluteInContentBound","asyncRedirect","autoExpose","CSSAlignWithLegacyW3C","customCSSInheritanceList","dataStrictMode","disableLongpressAfterScroll","disableQuickTracingGC","enableA11y","enableAccessibilityElement","enableAsyncInitVideoEngine","enableAsyncRequestImage","enableAsyncResolveSubtree","enableCheckExposureOptimize","enableCheckLocalImage","enableCircularDataCheck","enableComponentAsyncDecode","enableComponentNullProp","enableCreateViewAsync","enableCSSInheritance","enableCSSInlineVariables","enableCSSLazyImport","enableDisexposureWhenLynxHidden","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableExposureUIMargin","enableExposureWhenLayout","enableExposureWhenReload","enableFixedNew","enableHarmonyNewOverlay","enableHarmonyVisibleAreaChangeForExposure","enableICU","enableImageDownsampling","enableJsBindingApiThrowException","enableJSDataProcessor","enableListMoveOperation","enableListNewArchitecture","enableListPlug","enableLynxScrollFluency","enableMicrotaskPromisePolyfill","enableMultiTouch","enableMultiTouchParamsCompatible","enableNativeList","enableNewAnimator","enableNewClipMode","enableNewGesture","enableNewImage","enableNewIntersectionObserver","enableNewListContainer","enableNewTransformOrigin","enablePlatformGesture","enablePropertyBasedSimpleStyle","enableQueryComponentSync","enableReactOnlyPropsId","enableReduceInitDataCopy","enableReloadLifecycle","enableRemoveComponentExtraData","enableReuseLoadScriptExports","enableSignalAPI","enableSimultaneousTap","enableTextBoringLayout","enableTextGradientOpt","enableTextLanguageAlignment","enableTextLayerRender","enableTextLayoutCache","enableTextNonContiguousLayout","enableTextOverflow","enableTextRefactor","enableTouchRefactor","enableUIOperationOptimize","enableUnifiedPipeline","enableUseContextPool","enableUseMapBuffer","enableViewReceiveTouch","enableVsyncAlignedFlush","enableXTextLayoutReused","extendedLayoutOnlyOpt","extraInfo","flatten","fontScaleEffectiveOnlyOnSp","implicit","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","observerFrameRate","pipelineSchedulerConfig","preferredFps","quirksMode","removeDescendantSelectorScope","strictPropType","tapSlop","trailNewImage","unifyVWVHBehavior","useImagePostProcessor","useNewSwiper","autoResumeAnimation","cli","compileRender","customData","enableA11yIDMutationObserver","enableAsyncDisplay","enableBackgroundShapeLayer","enableCascadePseudo","enableCheckDataWhenUpdatePage","enableComponentLayoutOnly","enableGlobalComponentMap","enableNativeScheduleCreateViewAsync","enableNewAccessibility","enableNewLayoutOnly","enableOptPushStyleToBundle","enableOverlapForAccessibilityElement","fixCSSImportRuleOrder","forceCalcNewStyle","reactVersion","redBoxImageSizeWarningThreshold","removeComponentElement","syncImageAttach","useNewImage","version","debugInfoOutside","defaultDisplayLinear","defaultOverflowVisible","disableMultipleCascadeCSS","enableComponentConfig","enableCSSAsyncDecode","enableCSSClassMerge","enableCSSEngine","enableCSSExternalClass","enableCSSInvalidation","enableCSSLazyDecode","enableCSSSelector","enableCSSStrictMode","enableCSSVariable","enableEventRefactor","enableFiberArch","enableFlexibleTemplate","enableKeepPageData","enableRemoveCSSScope","enableSimpleStyling","experimental_encodeQuickjsBytecode","implicitAnimation","removeCSSParserLog","targetSdkVersion","templateDebugUrl"].some(e=>o===e))return!0;let r=e[o];if(void 0===r)return!0;return a(n,{path:t+(!1===n$(i=o)&&/^[a-zA-Z_$][a-zA-Z_$0-9]*$/g.test(i)?`.${o}`:`[${JSON.stringify(o)}]`),expected:"undefined",value:r,description:`The property \`${o}\` is not defined in the object type.
23
+
24
+ Please remove the property next time.`})}).every(e=>e)].every(e=>e))(e,t+"",!0)||a(!0,{path:t+"",expected:"Config",value:e}))(e,"$input",!0);let o=0===n.length;return o?{success:o,data:e}:{success:o,errors:n,data:e}}return{success:!0,data:e}},{"~standard":{version:1,vendor:"typia",validate:e=>{let t=r(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=[],n="",a=eW.Start,o=5;for(;o<e.length-1;){let i=e[++o];if(a===eW.Property?"."===i||"["===i?(t.push({key:n}),a=eW.Start):o===e.length-1?(n+=i,t.push({key:n}),o++,a=eW.Start):n+=i:a===eW.StringKey?'"'===i?(t.push({key:JSON.parse(n+i)}),o+=2,a=eW.Start):"\\"===i?(n+=e[o],n+=e[++o]):n+=i:a===eW.NumberKey&&("]"===i?(t.push({key:Number.parseInt(n)}),o++,a=eW.Start):n+=i),a===eW.Start&&o<e.length-1){let t=e[o];if(n="","["===t)'"'===e[o+1]?(a=eW.StringKey,o++,n='"'):a=eW.NumberKey;else if("."===t)a=eW.Property;else throw Error("Unreachable: pointer points invalid character")}}if(a!==eW.Start)throw Error(`Failed to parse path: ${JSON.stringify(e)}`);return t})(e.path)}))}}}}));function nF(e){let t=nW(e);if(t.success)return t.data;throw Error(["[pluginLynxConfig] Invalid configuration.",""].concat(t.errors.flatMap(({expected:e,path:t,value:n})=>{var a;return"undefined"===e?[` Unsupported configuration: \`${nU().red(t)}\``,""]:[`Invalid config on \`${nU().red(t)}\`.`,` - Expect to be ${nU().green(e)}`,` - Got: ${nU().red((a=n,Object.prototype.toString.call(a).replace(/^\[object\s+([a-z]+)\]$/i,"$1").toLowerCase()))}`,""]})).join("\n"))}let nH={"lynx:react":"@lynx-js/react-rsbuild-plugin"},nV=(e,t,n,a={})=>{let o=(({dirname:e,app:t,functionalTools:n,enableWebConsoleHook:a=!1})=>{let o=[],i=[],r=[],s=td(eX.resolve(t,"..","..")),l=a?`if (__DOUBAO_APPS_WEB__ && typeof __BACKGROUND__ === 'boolean' && __BACKGROUND__) {
25
+ hookConsole();
26
+ }
27
+
28
+ `:"";return Object.keys(n).forEach((t,a)=>{n[t]&&(i.push(`import Tool${a} from "${nt(e,n[t])}";`),r.push(`const Tool${a}Wrapper = {
29
+ ...Tool${a},
30
+ aiMeta: {
31
+ ...Tool${a}.aiMeta,
32
+ id: Tool${a}.aiMeta?.id || "${t}"
33
+ }
34
+ };`),o.push(`Tool${a}Wrapper`))}),`
35
+ import { Applet${a?", hookConsole":""} } from "${s}";
36
+ import App from "${nt(e,t)}";
37
+
38
+ ${i.join("\n")}
39
+
40
+ ${r.join("\n")}
41
+
42
+ ${l}new Applet(App, [${o.join(", ")}]).bootstrap();
43
+ `})({dirname:eX.dirname(e),app:t,functionalTools:n,enableWebConsoleHook:a.enableWebConsoleHook});return new nn(e,o)};function nG(e){return e?.type==="Identifier"}function nq(e){return e?.type==="StringLiteral"}function nz(e){return e?.type==="NumericLiteral"}function nJ(e){return e?.type==="BooleanLiteral"}function nK(e){return e?.type==="ObjectExpression"}function nY(e){return e?.type==="ArrayExpression"}function nX(e){return e?.type==="KeyValueProperty"}let nQ=e=>{if(nK(e)){let t={};for(let n of e.properties){if(n?.type==="SpreadElement"||!nX(n))return null;let{key:e,value:a}=n;if(!nG(e)&&!nq(e))return null;let o=e.value;nK(a)||nY(a)?t[o]=nQ(a):nq(a)||nz(a)||nJ(a)?t[o]=a.value:nG(a)&&(t[o]=a)}return t}if(nY(e)){let t=[];for(let n of e.elements){if(!n||n.spread)return null;let e=n.expression;nK(e)||nY(e)?t.push(nQ(e)):nq(e)||nz(e)||nJ(e)?t.push(e.value):nG(e)&&t.push(e)}return t}},nZ=h("../../../node_modules/.pnpm/@swc+core@1.15.11_@swc+helpers@0.5.23/node_modules/@swc/core/index.js");function n0(e,t,n){let{widgets:a,pages:o,collector:i,define:r,onDeprecatedAIMeta:s}=n,l=o[t],p=a[t],d=e;return(l||p)&&(r&&Object.keys(r).length>0&&(d=Object.keys(r).reduce((e,t)=>{let n=r[t];if("string"==typeof n)return e.replaceAll(t,n);throw Error(`Define value ${t} is not a string`)},e)),es((0,nZ.parseSync)(d,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(nG(e.callee)&&["defineWidget","definePage"].includes(e.callee.value)){let n=e.arguments[0]?.expression;if(nK(n)){for(let e of n.properties)if(nX(e)&&nG(e.key)&&"aiMeta"===e.key.value){let n=nQ(e.value);if(!n)continue;l?(s?.({kind:"page",entryName:l,filename:t}),i.addPageMeta(l,n)):p&&(s?.({kind:"widget",entryName:p,filename:t}),i.addWidgetMeta(p,n))}}}nG(e.callee)&&e.callee.value in T&&(p&&i.addWidgetMeta(p,T[e.callee.value]),l&&i.addPageMeta(l,T[e.callee.value]))}})),e}async function n1({pages:e,widgets:t,entries:n,collector:a,normalizedAppConfig:o,define:i}){let r=new tq,s=new Set,l={collector:r,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:i,onDeprecatedAIMeta({kind:e,entryName:t,filename:n}){let a=`${e}:${t}:${n}`;s.has(a)||(s.add(a),tI.warn(`define${"page"===e?"Page":"Widget"}({ aiMeta }) is deprecated for ${t}. Configure this ${e} metadata in src/app.config.ts instead. Source: ${n}`))}},p=o.pages.entries,d=o.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],a=n[t];return a?n0(a.toString(),e,l):void tI.warn("Cannot find virtual file",{file:t})}return n0(t3.readFileSync(e,"utf-8"),e,l)})).catch(e=>{tI.error("Failed to collect view metadata",{error:e})});let c=r.getData(),u=T.defineLoginPage,m=Object.entries(e).map(([e,t])=>{let n=c.pages[e],{web:a,...o}=p[e]??{},i=t.isLoginPage||n?.id===u.id;return[e,{id:t6(e,t.folderName),...n,...o,...i?u:{},path:i?u.path:t.isSpecial&&n?.path?n.path:t7(e)}]}),h=m.filter(([,e])=>e.id===u.id).map(([e])=>e);if(h.length>1)throw Error(`Only one login page is allowed: ${h.join(", ")}`);m.forEach(([e,t])=>{a.addPageMeta(e,t)}),Object.entries(t).forEach(([e,t])=>{let{web:n,...o}=d[e]??{};a.addWidgetMeta(e,{id:t6(e,t.folderName),...c.widgets[e],...o})})}let n3=h("os");function n2(e){let[t,n]=e.split(".").map(e=>Number(e));return Number.isNaN(t)||Number.isNaN(n)?1/0:10===t?0:172===t&&n>=16&&n<=31?1:192===t&&168===n?2:3}function n4(e){return/^(?:utun|tun|tap|ppp|ipsec|wg|docker|vboxnet|vmnet)\d*$/i.test(e)||/^br-/i.test(e)||/(?:vEthernet|Hyper-V|Docker|VirtualBox|VMware)/i.test(e)}function n9(e=function(){let e=Object.entries(n3.networkInterfaces()),t=[],n=[],a=[],o=[];for(let[i,r]of e)if(r)for(let e of r){let{address:r,family:s,internal:l}=e;if(!l)if("IPv4"===s)n4(i)||r.startsWith("169.254.")?a.push(r):t.push(r);else"IPv6"!==s||/^fe[89ab]/i.test(r)||(n4(i)?o.push(r):n.push(r))}return t.length>0?t:a.length>0?a:n.length>0?n:o}()){return e.slice().sort((e,t)=>n2(e)-n2(t))[0]}function n5(e){let t=n9()??"127.0.0.1",n=t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t;return`http://${n}:${e}`}let n8=`base/${e9}`;async function n6({encryption:e}){let t=t3.mkdtempSync(eX.join(n3.tmpdir(),"doubao-keystore-")),n=eX.join(t,e9);try{let{generateKeystore:t}=await import("node:module").then(function(e){return h.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),a=await t(n,{encryption:e});if(0!==a.status)throw Error(a.error_msg);return t3.readFileSync(n)}finally{t3.rmSync(t,{recursive:!0,force:!0})}}let n7=h("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40_debug@4.4.3/node_modules/@byted-lynx/tasm/index.js");class ae{options;isGenerateKeystore=!1;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(ae.name,t=>{t.hooks.processAssets.tapPromise({name:ae.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH},async()=>{let n=this.options.getMainThreadAssetPath(),a=t.getAsset(n),{buffer:o,encodeOptions:i,keystoreContent:r}=await this.encode([a]),{RawSource:s}=e.webpack.sources;if(t.updateAsset(n,new s(o,!1)),r){let e=new s(r,!1);t.getAsset(n8)?t.updateAsset(n8,e):t.emitAsset(n8,e)}"applet0930"===process.env.DEBUG&&t.emitAsset(`${eX.dirname(n)}/tasm.json`,new s(JSON.stringify(i,null,2)))})})}async encode(e){let t={},{resolveSigningEncryptionOptions:n}=this.options;for(let n of e)n.name.endsWith(".js")&&(t[n.name.replace(/\.template\.js$/,"")]={content:n.source.source().toString()});let a={compilerOptions:{enableFiberArch:!0,targetSdkVersion:this.options.engineVersion??"3.5"},sourceContent:{appType:"DynamicComponent"},customSections:t},o=await n?.();if(o?.signing.enabled||o?.encryption.enabled){let{encode:e}=await import("node:module").then(function(e){return h.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),t=this.options.metadata.appId,n=ne(o,{signing:{extra_config:{app_id:t,bundle_id:t}},encryption:{salt:t}}),{buffer:i,lepus_debug:r,status:s,error_msg:l}=await e(JSON.stringify(a),n);if(0!==s)throw Error(l);return!this.isGenerateKeystore&&n.encryption.enabled?(this.isGenerateKeystore=!0,{buffer:i,encodeOptions:a,debugInfo:r,keystoreContent:await n6({encryption:{...n.encryption}})}):{buffer:i,encodeOptions:a,debugInfo:r}}let i=(0,n7.getEncodeMode)(),{buffer:r}=await i(a);return{buffer:r,encodeOptions:a}}}function at(e,t,n,a){let o=!1;return{name:at.name,apply(i){let r=new i.webpack.experiments.VirtualModulesPlugin;r.apply(i),i.hooks.thisCompilation.tap(at.name,()=>{Object.keys(n).forEach(e=>{r.writeModule(n[e].filename,n[e].toString())})}),i.hooks.thisCompilation.tap(at.name,n=>{let r=e.getLynxTemplatePluginHooks(n);r.beforeEncode.tapPromise(at.name,async e=>(e.encodeData.sourceContent.config=ea({},e.encodeData.sourceContent.config,{mapContainerType:1}),e)),r.encode.tapPromise({name:at.name,stage:255},async e=>{let{encodeOptions:r}=e,s=await a?.();if(s?.signing.enabled||s?.encryption.enabled){let{encode:a}=await import("node:module").then(function(e){return h.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),l=t.getData(),p=function(e,t){let n=(t??"").replaceAll("\\","/"),a=n.match(/(?:^|\/)(pages|widgets)\/(.+)$/);if(a){let[,t,n]=a,o=`${t}/${n}`;return e.widgets[o]?.id??e.pages[o]?.id}let o=eX.posix.basename(n);return e.widgets[`widgets/${o}`]?.id??e.pages[`pages/${o}`]?.id}(l,e.intermediate),d=l.app.appId,c=ne(s,{signing:{extra_config:{app_id:d,bundle_id:p}},encryption:{salt:d}}),{buffer:u,lepus_debug:m,status:f,error_msg:g}=await a(JSON.stringify(r),c);if(0!==f)throw Error(g);if(!o&&c.encryption.enabled){o=!0;let e=await n6({encryption:{...c.encryption}}),t=new i.webpack.sources.RawSource(e,!1);n.getAsset(n8)?n.updateAsset(n8,t):n.emitAsset(n8,t)}return{buffer:u,debugInfo:m}}let l=(0,n7.getEncodeMode)(),{buffer:p,lepus_debug:d}=await l(r);return{buffer:p,debugInfo:d}})}),i.hooks.failed.tap(at.name,e=>{tP.error("Failed to bundle template",{error:e})})}}}class an{static _instance;listeners=[];stdinListener;nextIndex=0;static get instance(){return an._instance??=new an}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,n=0){let a=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 a(e.run)}return this.listeners.push({run:e,tag:t,priority:n,index:this.nextIndex++}),this.listeners.sort((e,t)=>e.priority-t.priority||e.index-t.index),this.start(),a(e)}}function aa(e){return!!(e&&!/<%=?\s*appId\s*%>/.test(e))}function ao(e){if(!(e instanceof Error))return!1;try{let t=JSON.parse(e.message);return t?.code===0x2fb1799}catch{return!1}}async function ai(e){aa(e.appId)&&(await e.getCachedLoginCookie().catch(()=>void 0)||tN.warn(e.appId.startsWith("db_")?"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `dbx auth login` 后重新启动开发服务。":"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `npx doubao login` 后重新启动开发服务。"))}let ar=e=>w.bgHex("#9873b9")(w.italic(w.black(` ${e} `))),as=e=>w.bgBlueBright(w.italic(w.black(` ${e} `))),al=e=>w.bold(w.blueBright(e)),ap=(0,_.createRequire)(import.meta.url);X.registerPrompt("search-list",ap("inquirer-search-list"));let ad=[{command:"d",description:"选择调试场景 / pages / widgets"},{command:"web",description:"打开 Web 模拟器"}],ac={page:"页面",scene:"调试场景",widget:"组件"};function au(e){console.log(` ${al(e.command.padEnd(21))} ${w.gray(`- ${e.description}`)}`)}async function am(e){let t=await ex(e.path);if(!t)return;let n=V(t);if(0!==n.length)return await X.prompt(n.map(([e,t])=>({type:"input",name:e,message:`请输入调试场景变量 "${e}" 的值:`,default:t??void 0})))}async function ah(e,t,n,a,o,i,{interactive:r=!0}={}){if(await o.load({appletUrl:t,appId:e,isSigned:i}),!r)return;let s=await eE(process.cwd()),l=Object.values(n),p=Object.values(a),d=p.filter(({id:e})=>!te(e));return l.length>0&&(console.log(`
44
+
45
+ ${as("可用 pages 列表")}
46
+ `),l.forEach(e=>{let t=al(e.id);console.log(` - ${t}`)})),d.length>0&&(console.log(`
47
+ ${as("可用 widgets 列表")}
48
+ `),d.forEach(e=>{let t=al(e.id);console.log(` - ${t}`)})),s.length>0&&(console.log(`
49
+ ${as("可用调试场景")}
50
+ `),s.forEach(e=>console.log(` - ${al(e.name)}`))),console.log(`
51
+ ${as("可以继续执行以下命令:")}
52
+ `),ad.forEach(au),console.log("\n"),an.instance.addListener(t=>{let n=t.trim();if("d"===n)(async()=>{let t=[...s.map(e=>({type:"scene",id:e.name})),...d.map(e=>({type:"widget",id:e.id})),...l.map(e=>({type:"page",id:e.id}))];if(0===t.length)return console.log(`
53
+ ${as("暂无可用的页面、组件或调试场景")}`);an.instance.stop();try{let{selectedEntry:n}=await X.prompt([{type:"search-list",name:"selectedEntry",message:"请选择要运行的页面、组件或调试场景(可按名称或类型搜索):",choices:t.map(e=>({name:`${w.gray(ac[e.type])}: ${e.id}`,value:`${e.type}:${e.id}`}))}]),[a,i]=n.split(":"),r=t.find(e=>e.type===a&&e.id===i);if(r)if("scene"===r.type){let t=s.find(e=>e.name===r.id);if(t){let n=await am(t);await eC({matchedScene:t,appId:e,driver:o,variables:n})}}else"widget"===r.type?o.pushWidget({appId:e,widgetId:r.id}):o.openPage({appId:e,pageId:r.id})}finally{an.instance.start()}})();else{let t=s.find(e=>e.name===n);t?(async()=>{an.instance.stop();try{let n=await am(t);await eC({matchedScene:t,appId:e,driver:o,variables:n})}finally{an.instance.start()}})():p.some(e=>e.id===n)?o.pushWidget({appId:e,widgetId:n}):o.openPage({appId:e,pageId:n})}return!0},"openPage")}let af=h("../../../node_modules/.pnpm/undici@6.22.0/node_modules/undici/index.js"),ag={"sso-internal":"doubao-developer.bytedance.net","sms-internal":"doubao-developer-open.bytedance.net","sms-external":"hello.doubao-dev.com"},ab={"http:":"80","https:":"443"},ay=new Map;function av(){return process.env.X_TT_ENV?{"x-use-ppe":"1","x-tt-env":process.env.X_TT_ENV}:{}}function aS(e){let t=e.startsWith("/")?e:`/${e}`;return"/app_developer"===t||t.startsWith("/app_developer/")}async function aw(e,t={}){let n=function(e){var t,n;let a="string"==typeof e?new URL(e):e;if(function(e){let t=ax(["NO_PROXY","no_proxy"]);if(!t)return!1;let n=aC(e.hostname),a=e.port||ab[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:aC(t.slice(0,e+1)),port:":"===t[e+1]?t.slice(e+2):void 0}}let n=t.indexOf(":")===t.lastIndexOf(":")?t.match(/:(\d+)$/):void 0;return{host:aC(n?t.slice(0,-n[0].length):t),port:n?.[1]}}(e);if(t.host&&(!t.port||t.port===a)){if("*"===t.host)return!0;if(t.host.startsWith("*.")){let e=t.host.slice(1);if(n.endsWith(e))return!0;continue}if(t.host.startsWith(".")){if(n.endsWith(t.host))return!0;continue}if(n===t.host)return!0}}return!1}(a))return;let o="https:"===(t=a.protocol)?ax(["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):"http:"===t?ax(["HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):void 0;if(!o)return;let i=(n=o,/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`http://${n}`),r=ay.get(i);return r||(r=new af.kT(i),ay.set(i,r)),r}(e),a=n?{...t,dispatcher:n}:t;return await fetch(e,a)}async function a_({internal:e,domainId:t,path:n,query:a,method:o="GET",body:i,headers:r,signal:s,auth:l=!0}){let p={method:o,body:i,headers:{...av(),...r}};s&&(p.signal=s);let d=function({internal:e,domainId:t,path:n,query:a}){let o=n.startsWith("/")?n:`/${n}`,i=new URLSearchParams;for(let[e,t]of Object.entries(a||{}))null!=t&&i.append(e,t.toString());let r=i.toString(),s=r?`${o.includes("?")?"&":"?"}${r}`:"",l=aS(o)?er:t?ag[t]:e?ag["sso-internal"]:ag["sms-external"];return`https://${l}${o}${s}`}({internal:e,domainId:t,path:n,query:a}),c=new Headers(p.headers),u=c.has("Cookie");if(!l||!aS(n)||c.has("Authorization")||c.has("X-Developer-Open-Build-Token"))return await aw(d,p);let m=new URL(d).origin,h=L(aw,{baseUrl:m,allowedOrigins:[m]});try{return await h(d,p)}catch(e){if(!(e instanceof U||e instanceof I))throw e;if(u)return await aw(d,p);throw Error(e instanceof I?"Doubao Apps Platform 登录已过期,请运行 `dbx auth login` 后重试。":"Doubao Apps Platform 请求需要登录,请运行 `dbx auth login` 后重试。")}}async function aE(e){let t=await a_(e),n=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:n}))}let a=await t.json();if(0!==a.code)throw Error(JSON.stringify({...a,log_id:n}));return{...a,log_id:n}}function ax(e){for(let t of e){let e=process.env[t]?.trim();if(e)return e}}function aC(e){return e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"")}let aA=["page","widget","app"],aO=["log","info","warn","error","debug","eval"],aI=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function aT(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function aP(e){return"string"==typeof e?e:void 0}function ak(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function aL(e){return Array.isArray(e)?e:[]}function aN(e,t){let n=Math.max(0,Math.floor(ak(t.pageIdx)??0)),a=Math.min(200,Math.max(1,Math.floor(ak(t.pageSize)??50))),o=n*a,i=e.slice(o,o+a);return{pageIdx:n,pageSize:a,total:e.length,hasMore:o+i.length<e.length,items:i}}function aR(e){let t=function(e){if(!aT(e.snapshot))return{stored:!1,updatedAtMs:e.updatedAtMs};let{debug_snapshot:t,...n}=e.snapshot;return{stored:!0,storedAt:aP(n.stored_at),updatedAtMs:ak(n.stored_at_ms)??e.updatedAtMs,snapshot:n.snapshot}}(e);return t.stored?{...t,snapshot:aT(t.snapshot)?t.snapshot:{}}:t}function aD(e){return aT(e)?aP(e.value)??aP(e.unserializableValue)??aP(e.description)??aP(e.type)??"":String(e)}function aM(e){let{entry:t,...n}=e;return n}function a$(e,t){return(function(e,t){let n;return"all"===t?aA:"page"===t||"widget"===t||"app"===t?[t]:aP((n=aT(e.context)?e.context:{}).page_id)||aP(n.page_path)?["page","app"]:aP(n.widget_id)?["widget"]:aA})(e,t).flatMap(t=>{let n,a=Array.isArray(n=(aT(e.runtime_console)?e.runtime_console:{})[t])?{entries:n,updatedAtMs:void 0}:aT(n)?{entries:aL(n.entries),updatedAtMs:ak(n.updated_at_ms)??ak(n.updatedAtMs)}:{entries:[],updatedAtMs:void 0};return a.entries.map((e,n)=>{var o;let i,r,s,l,p,d,c;return o=a.updatedAtMs,i=aT(e)?e:{message:String(e)},r=aT(i.location)?i.location:{},s=aP(i.url)??aP(r.url),l=ak(i.lineNumber)??ak(r.lineNumber),p=ak(i.columnNumber)??ak(r.columnNumber),d=aP(i.id)??String(n),{msgid:`${t}:${d}`,target:t,level:aP(i.level)??"log",source:aP(i.source)??"",timestamp:ak(i.timestamp)??0,text:void 0!==(c=aP(i.message))?c:aL(i.args).map(aD).filter(Boolean).join(" "),...s?{url:s}:{},...void 0===l?{}:{lineNumber:l},...void 0===p?{}:{columnNumber:p},...void 0===o?{}:{updatedAtMs:o},entry:i}})})}function aB(e){return aT(e)&&aT(e.payload)?e.payload:{}}function aj(e,t){let n=aT(e)?e:{value:e};return{id:aP(n.toolCallId)??aP(n.id)??`tool-call:${t}`,requestId:aP(n.requestId)??aP(n.request_id)??"",toolCallId:aP(n.toolCallId)??aP(n.id)??"",toolName:aP(n.toolName)??aP(n.name)??"",serverId:aP(n.serverId)??aP(n.server_id)??"",appKey:aP(n.appKey)??aP(n.app_key)??"",status:aP(n.status)??"",createdAtMs:ak(n.createdAtMs)??ak(n.created_at_ms)??0,updatedAtMs:ak(n.updatedAtMs)??ak(n.updated_at_ms)??0,requiresUserApproval:!0===n.requiresUserApproval,isMiniApp:!0===n.isMiniApp,message:aP(n.message)??"",resultSummary:n.resultSummary??n.structuredResultSummary,arguments:n.arguments??n.argumentsJson,error:n.error,entry:n}}function aU(e){return{id:e.id,requestId:e.requestId,toolCallId:e.toolCallId,toolName:e.toolName,serverId:e.serverId,appKey:e.appKey,status:e.status,createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs,requiresUserApproval:e.requiresUserApproval,isMiniApp:e.isMiniApp,message:e.message}}function aW(e,t){if(!aT(e))return;if("page"===t){let t=aP(e.pageId),n=aP(e.path);if(!t||!n)return;return{pageId:t,path:n,name:aP(e.name)??t,isHome:!0===e.isHome}}let n=aP(e.widgetId);if(n)return{widgetId:n,name:aP(e.name)??n}}let aF=ev.child("simulator"),aH=h("node:http"),aV={"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless"},aG=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),aq=new Set([...aG,"cookie","host","origin","referer"]),az=/authorization|cookie|token|secret|password|credential|private[-_]?key|(?:^|[-_])api[-_]?key(?:$|[-_])|(?:^|[-_])dek(?:$|[-_])/i,aJ="X-DBX-Sandbox-Session-ID",aK="x-tt-logid";function aY(e){try{return new URL(e.url??"/","http://localhost")}catch{return}}function aX(e,t,n={}){let a={};for(let[t,n]of Object.entries(e))void 0===n||aq.has(t.toLowerCase())||(a[t]=n);return{...a,...n,host:t.host}}function aQ(e,t=[]){let n={};for(let[t,a]of Object.entries(e))void 0===a||aG.has(t.toLowerCase())||(n[t]=a);if(t.length>0){let e=new Set(String(n["access-control-expose-headers"]??"").split(",").map(e=>e.trim().toLowerCase()).filter(Boolean));for(let n of t)e.add(n.toLowerCase());n["access-control-expose-headers"]=[...e].join(", ")}return n}function aZ(e,t={}){Object.entries({...aV,...t}).forEach(([t,n])=>{void 0!==n&&e.setHeader(t,n)})}function a0(e,t,n,a){aZ(e,a),e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(n)}function a1(e,t,n,a){let o=JSON.stringify(n);aZ(e,a),e.writeHead(t,{"Content-Length":Buffer.byteLength(o),"Content-Type":"application/json; charset=utf-8"}),e.end(o)}function a3(e,t){return new Promise((n,a)=>{let o="",i=0;e.setEncoding("utf8"),e.on("data",n=>{if((i+=Buffer.byteLength(n))>t){a(Error("Request body is too large")),e.destroy();return}o+=n}),e.once("end",()=>n(o)),e.once("aborted",()=>a(Error("Request aborted"))),e.once("error",a)})}function a2(e){return e.arrayBuffer().then(e=>Buffer.from(e))}function a4(e){return Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let n=az.test(e)?"[REDACTED]":Array.isArray(t)?t.join(", "):t;return` ${e}: ${n}`}).join("\n")}function a9(e){return("string"==typeof e||void 0===e?e:e.toString("utf8"))||"(no content)"}function a5({method:e,requestBody:t,requestHeaders:n,responseBody:a,responseHeaders:o,statusCode:i,targetUrl:r}){"applet0930"===process.env.DEBUG&&aF.info(`${e} ${r.pathname}${r.search} ${(i>=500?w.red:i>=400?w.yellow:w.green)(String(i))}
54
+ Request headers:
55
+ ${a4(n)}
56
+ Request body: ${a9(t)}
57
+
58
+ Response headers:
59
+ ${a4(Object.fromEntries(o))}
60
+ Response body: ${a9(a)}`)}function a8(e,t,n){let a,o=("https:"===n.targetUrl.protocol?g:aH).request(n.targetUrl,{headers:n.requestHeaders,method:e.method},e=>{(a=e,t.destroyed||t.writableEnded)?e.destroy():(aZ(t,n.commonHeaders),t.writeHead(e.statusCode??500,n.createResponseHeaders?.(e.headers)??aQ(e.headers)),e.pipe(t))}),i=()=>{o.destroy(),a?.destroy()};o.once("error",e=>{if(!t.destroyed&&!t.writableEnded){if(t.headersSent)return void t.destroy(e);a0(t,502,`${n.errorMessage}: ${e.message}`,n.commonHeaders)}}),e.once("aborted",()=>{i()}),e.socket.once("close",()=>{t.writableEnded||i()}),t.once("close",()=>{t.writableEnded||i()}),e.pipe(o)}let a6=new Set(["DEBUGGER_NOT_CONNECTED","DEBUGGER_DISCONNECTED","TARGET_NOT_FOUND","ELEMENT_NOT_FOUND","RENDER_FAILED","RENDER_TIMEOUT","INSPECTION_FAILED","SCREENSHOT_FAILED","COMMAND_TIMEOUT"]);class a7 extends Error{code;constructor(e,t){super(t),this.name="DebuggerControlError",this.code=e}}function oe(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function ot(e){return"render_page"===e||"render_widget"===e}function on(e){return"number"==typeof e&&Number.isFinite(e)}class oa{clients=new Map;lastSnapshotAtByClientId=new Map;snapshotStore;nextCommandId=0;constructor(e){this.snapshotStore=e}registerClient(e,t){let n=this.clients.get(e);n&&this.disconnectClient(n,"Debugger control connection was replaced");let a={clientId:e,lastSnapshotAtMs:this.lastSnapshotAtByClientId.get(e)??0,queue:[],response:t};this.clients.set(e,a),t.once("close",()=>{this.clients.get(e)===a&&this.disconnectClient(a,"Debugger control connection was closed",!1)})}noteSnapshot(e){if(!e)return;let t=Date.now();this.lastSnapshotAtByClientId.set(e,t);let n=e?this.clients.get(e):void 0;n&&(n.lastSnapshotAtMs=t)}execute(e,t){let n=this.getActiveClient();if(!n)return Promise.reject(new a7("DEBUGGER_NOT_CONNECTED","No Web SDK debugger with a stored snapshot is connected"));let a=`control-${Date.now()}-${++this.nextCommandId}`;return new Promise((o,i)=>{n.queue.push({command:{...t,commandId:a,type:e},reject:i,resolve:o}),this.flushClient(n)})}handleResult(e){var t,n;let a,o;if(!aT(e))return!1;let i=oe(e.clientId),r=oe(e.commandId),s=i?this.clients.get(i):void 0,l=s?.activeJob;if(!s||!l||l.command.commandId!==r)return!1;if(l.timeout&&clearTimeout(l.timeout),s.activeJob=void 0,!0===e.ok&&ot(l.command.type)&&aT(e.snapshot)&&aT(e.target)&&(t=e.snapshot,o=aT(t.snapshot)?t.snapshot:void 0,o?.command_id===r&&aT(o?.runtime_snapshot))?(this.snapshotStore.snapshot=e.snapshot,this.snapshotStore.updatedAtMs=Date.now(),this.noteSnapshot(i),a={target:e.target}):!0!==e.ok||ot(l.command.type)||(a=function(e,t){if(aT(t)&&("take_screenshot"===e||oe(t.uid))){if("get_computed_style"===e){if(!Array.isArray(t.computedStyle)||!t.computedStyle.every(e=>aT(e)&&!!oe(e.name)&&"string"==typeof e.value))return;return t}if("get_element_rect"===e)return[t.x,t.y,t.width,t.height].every(on)?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&&on(t.width)&&on(t.height)&&(void 0===t.uid||oe(t.uid))?t:void 0}}}(l.command.type,e.result)),a)l.resolve(a);else{let t=aT(e.error)?e.error:{},a=oe(t.code),o=a&&a6.has(a)?a:void 0;l.reject(new a7(o??(ot(n=l.command.type)?"RENDER_FAILED":"take_screenshot"===n?"SCREENSHOT_FAILED":"INSPECTION_FAILED"),oe(t.message)??"Debugger control command failed"))}return this.flushClient(s),!0}getActiveClient(){return[...this.clients.values()].filter(e=>!e.response.writableEnded&&e.lastSnapshotAtMs>0).sort((e,t)=>t.lastSnapshotAtMs-e.lastSnapshotAtMs)[0]}flushClient(e){if(e.activeJob||e.response.writableEnded)return;let t=e.queue.shift();if(t){e.activeJob=t,t.timeout=setTimeout(()=>{e.activeJob===t&&(e.activeJob=void 0,t.reject(new a7(ot(t.command.type)?"RENDER_TIMEOUT":"COMMAND_TIMEOUT","Debugger control command timed out")),this.flushClient(e))},15e3);try{e.response.write(`data: ${JSON.stringify(t.command)}
61
+
62
+ `)}catch{t.timeout&&clearTimeout(t.timeout),e.activeJob=void 0,t.reject(new a7("DEBUGGER_DISCONNECTED","Debugger control connection was closed")),this.disconnectClient(e,"Debugger control connection was closed")}}}disconnectClient(e,t,n=!0){if(this.clients.get(e.clientId)!==e)return;this.clients.delete(e.clientId);let a=new a7("DEBUGGER_DISCONNECTED",t);for(let t of(e.activeJob?.timeout&&clearTimeout(e.activeJob.timeout),e.activeJob?.reject(a),e.activeJob=void 0,e.queue.splice(0)))t.reject(a);n&&!e.response.writableEnded&&e.response.end()}}async function oo(e,t,n){let a;if("POST"!==e.method)return void a1(t,405,{error:"Method not allowed"});try{a=JSON.parse(await a3(e,0xa00000))}catch(e){a1(t,400,{error:e.message});return}n.handleResult(a)?a1(t,200,{ok:!0}):a1(t,404,{error:"Pending debugger command not found"})}let oi={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},or={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0};function os(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 ol(e,t={}){try{return await e()}catch(e){return function(e,t={}){let n=e instanceof a7?e:new a7("INSPECTION_FAILED",String(e));return os({...t,error:{code:n.code,message:n.message}},{isError:!0})}(e,t)}}function op(e,t,n,a){e.registerTool(t,n,a)}let od="/__wsd_mcp";async function oc(e,t,n,a){let o,i;if("OPTIONS"===e.method){aZ(t),t.writeHead(204),t.end();return}if("POST"!==e.method)return void a0(t,405,"Method not allowed");let r=(o=new G({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),i=async e=>{var t;let a=aR(n);if(!a.stored)return os(a);let o=aN([{source:"simulator",events:aL((aT((t=a.snapshot).simulator)?t.simulator:{}).trace_events)},{source:"widget_runtime",events:aL(t.widget_runtime_trace_events)},{source:"page_runtime",events:aL(t.page_runtime_trace_events)}].flatMap(({source:e,events:t})=>t.map((t,n)=>(function(e,t,n){let a,o,i,r,s=aT(e)?e:{payload:e};return{source:t,id:aP(s.id)??`${t}:${n}`,timestamp:ak(s.timestamp)??0,category:(a=aB(s),o=aT(s)&&aT(s.display)?s.display:{},aP(a.category)??aP(o.category)??""),event:aP(aB(s).event)??(aT(s)?aP(s.event):void 0)??"",requestId:(r=aT((i=aB(s)).trace)?i.trace:{},aP(i.request_id)??aP(i.requestId)??aP(i.trace_id)??aP(r.trace_id)??""),payload:s.payload??s}})(t,e,n))).filter(t=>{let n,a,o;return n=aL(e.category).filter(e=>"string"==typeof e),a=aP(e.event)?.trim(),o=aP(e.requestId)?.trim(),(0===n.length||n.includes(t.category))&&(!a||t.event===a)&&(!o||t.requestId===o)}),e);return os({stored:!0,storedAt:a.storedAt,updatedAtMs:a.updatedAtMs,total:o.total,pageIdx:o.pageIdx,pageSize:o.pageSize,hasMore:o.hasMore,events:o.items})},op(o,"list_console_messages",{annotations:oi,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:en(x(aO)).optional(),pageIdx:C().int().min(0).optional(),pageSize:C().int().min(1).max(200).optional(),query:J().optional(),target:x(["current","page","widget","app","all"]).optional()}},async e=>{let t=aR(n);if(!t.stored)return os(t);let a=aN(a$(t.snapshot,e.target).filter(t=>{let n,a;return n=aL(e.levels).filter(e=>"string"==typeof e),a=aP(e.query)?.trim().toLowerCase(),(!(n.length>0)||!!n.includes(t.level))&&(!a||[t.text,t.url,t.source,t.target].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(a)))}),e);return os({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:a.total,pageIdx:a.pageIdx,pageSize:a.pageSize,hasMore:a.hasMore,messages:a.items.map(aM)})}),op(o,"get_console_message",{annotations:oi,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:J()}},async e=>{let t=aR(n);if(!t.stored)return os(t);let a=a$(t.snapshot,"all").find(t=>t.msgid===e.msgid);return os({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,found:!!a,...a?{message:a}:{msgid:e.msgid}})}),op(o,"get_log_snapshot",{annotations:oi,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let e=aR(n);return e.stored?os({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,snapshot:e.snapshot}):os(e)}),op(o,"list_render_targets",{annotations:oi,description:"List Page and Widget targets that can be rendered by the Web SDK debugger.",inputSchema:{type:x(["all","page","widget"]).optional()}},async e=>{var t,a;let o,i=aR(n);return i.stored?os({stored:!0,storedAt:i.storedAt,updatedAtMs:i.updatedAtMs,...(t=i.snapshot,a=e.type??"all",o=aT(t.render_targets)?t.render_targets:{},{pages:"widget"===a?[]:aL(o.pages).map(e=>aW(e,"page")).filter(Boolean),widgets:"page"===a?[]:aL(o.widgets).map(e=>aW(e,"widget")).filter(Boolean),...aT(o.currentTarget)?{currentTarget:o.currentTarget}:{}})}):os(i)}),op(o,"take_snapshot",{annotations:oi,description:"Take a text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:x(["current","page","widget"]).optional(),verbose:k().optional()}},async e=>{let t=aR(n);if(!t.stored)return os(t);let a=function(e,t){var n,a;let o,i,r,s=aT(e.runtime_snapshot)?e.runtime_snapshot:void 0;if(!s||!aT(s.target))return{available:!1,reason:"NO_RUNTIME_SNAPSHOT"};let l=s.target,p=aP(l.type),d=t.target??"current";if(("page"===d||"widget"===d)&&p!==d)return{available:!1,reason:"TARGET_MISMATCH",requestedTarget:d,currentTarget:l};if(!aT(s.root))return{available:!1,reason:"NO_RENDERED_TARGET",currentTarget:l};let c=aP(s.selectedUid),u=(n=s.root,a=!0===t.verbose,o=[],i=0,(r=(e,t)=>{var n,s;let l=aP(e.uid),p=aP(e.name);if(!l||!p)return;i+=1;let d=" ".repeat(t);if("text"===e.type)return void o.push(`${d}uid=${l} text ${JSON.stringify(aP(e.text)??"")}`);let u=[`uid=${l}`,p],m=aT(e.accessibility)?e.accessibility:{},h=aP(m.role),f=aP(m.name),g=!0===m.keyboardFocusable;for(let t of(h&&(a||"generic"!==h)&&u.push(`role=${JSON.stringify(h)}`),f&&u.push(`name=${JSON.stringify(f)}`),(a||g)&&u.push(`focusable=${String(g)}`),aL(e.attributes).filter(aT).map(e=>({name:aP(e.name)??"",value:aP(e.value)??""})).filter(e=>e.name&&(a||aI.has(e.name)||e.name.startsWith("aria-")))))u.push((n=t.name,(s=t.value)?`${n}=${JSON.stringify(s)}`:n));for(let n of(l===c&&u.push("[selected]"),o.push(`${d}${u.join(" ")}`),aL(e.children)))aT(n)&&r(n,t+1)})(n,0),{actualNodeCount:i,text:o.join("\n")});return{available:!0,target:l,nodeCount:ak(s.nodeCount)??u.actualNodeCount,...c?{selectedUid:c}:{},truncated:!0===s.truncated,snapshot:u.text,snapshotUpdatedAtMs:ak(s.updatedAtMs)}}(t.snapshot,e),o={stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,...a};return os(o,{text:a.available?a.snapshot:JSON.stringify(o,null,2)})}),op(o,"get_computed_style",{annotations:oi,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:en(J().min(1)).max(100).optional(),uid:J().min(1)}},({properties:e,uid:t})=>ol(async()=>os(await a.execute("get_computed_style",{uid:t,...e?{properties:e}:{}})))),op(o,"get_element_rect",{annotations:oi,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:J().min(1)}},({uid:e})=>ol(async()=>os(await a.execute("get_element_rect",{uid:e})))),op(o,"take_screenshot",{annotations:oi,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:x(["png","jpeg","webp"]).optional(),quality:C().min(0).max(100).optional(),uid:J().min(1).optional()}},({format:e="png",quality:t,uid:n})=>ol(async()=>{let o=await a.execute("take_screenshot",{format:e,...void 0!==t?{quality:t}:{},...n?{uid:n}:{}}),{data:i,...r}=o;return os({captured:!0,...r},{image:{data:i,mimeType:o.mimeType}})},{captured:!1})),op(o,"render_page",{annotations:or,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:J().min(1)}},({url:e})=>ol(async()=>os({rendered:!0,target:(await a.execute("render_page",{url:e})).target}),{rendered:!1})),op(o,"render_widget",{annotations:or,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:M(J(),O()).optional(),widgetId:J().min(1)}},({structuredContent:e,widgetId:t})=>ol(async()=>os({rendered:!0,target:(await a.execute("render_widget",{structuredContent:e??{},widgetId:t})).target}),{rendered:!1})),op(o,"list_agent_trace_events",{annotations:oi,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:en(J()).optional(),event:J().optional(),pageIdx:C().int().min(0).optional(),pageSize:C().int().min(1).max(200).optional(),requestId:J().optional()}},i),op(o,"list_agent_tool_calls",{annotations:oi,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:C().int().min(0).optional(),pageSize:C().int().min(1).max(200).optional(),query:J().optional(),requestId:J().optional(),status:en(J()).optional(),toolName:J().optional()}},async e=>{var t;let a=aR(n);if(!a.stored)return os(a);let o=aN(aL((aT((t=a.snapshot).simulator)?t.simulator:{}).tool_calls).map(aj).filter(t=>{let n,a,o,i;return n=aP(e.requestId)?.trim(),a=aP(e.toolName)?.trim(),o=aL(e.status).filter(e=>"string"==typeof e),i=aP(e.query)?.trim().toLowerCase(),(!n||t.requestId===n)&&(!a||t.toolName===a)&&(!(o.length>0)||!!o.includes(t.status))&&(!i||[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(i)))}),e);return os({stored:!0,storedAt:a.storedAt,updatedAtMs:a.updatedAtMs,total:o.total,pageIdx:o.pageIdx,pageSize:o.pageSize,hasMore:o.hasMore,toolCalls:o.items.map(aU)})}),o),s=new A({enableJsonResponse:!0,sessionIdGenerator:void 0});try{await r.connect(s),await s.handleRequest(e,t)}catch(e){t.headersSent?t.destroy(e instanceof Error?e:void 0):a0(t,500,e instanceof Error?e.message:String(e))}finally{await s.close().catch(()=>void 0),await r.close().catch(()=>void 0)}}let ou="/app_developer/api/sandbox/",om=`${ou}session/business_info/update`,oh=new Set([`${ou}resources/notices/pull`,`${ou}resources/tasks/pull`]),of={"Access-Control-Expose-Headers":aK},og=new Set;function ob(e,t,n,a,o,i){if("applet0930"!==process.env.DEBUG)return!1;let r=`${o[aJ]??""} ${e} ${t.pathname}`,s=oh.has(t.pathname);if(s&&n>=500){if(og.has(r))return!1;og.add(r)}else s&&n<500&&og.delete(r);let l=Number(process.hrtime.bigint()-a)/1e6;return aF.request({method:e,url:`${t.pathname}${t.search}`,statusCode:n,durationMs:l,headers:o,logId:i}),!0}function oy({method:e,requestBody:t,requestHeaders:n,responseBody:a,responseHeaders:o,statusCode:i,targetUrl:r}){a5({method:e,requestBody:t,requestHeaders:n,responseBody:a,responseHeaders:o,statusCode:i,targetUrl:r})}function ov(e,t,n){return n&&!(oh.has(e.pathname)&&t>=500)}function oS(e,t){if(e.pathname!==om||!t)return t;try{let e=JSON.parse(t);return JSON.stringify({...e,csr_pem:"[redacted]",phone_num:"[redacted]"})}catch{return JSON.stringify({omitted:"invalid business info request"})}}async function ow({method:e,request:t,requestBody:n,requestHeaders:a,response:o,targetUrl:i,usePlatformFetch:r}){let s=new AbortController,l=process.hrtime.bigint(),p=()=>s.abort();t.once("aborted",p),t.socket.once("close",p),o.once("close",()=>{o.writableEnded||p()});try{let t,p=r?await a_({internal:!0,path:`${i.pathname}${i.search}`,method:e,body:n,headers:a,signal:s.signal}):await fetch(i,{body:"GET"===e||"HEAD"===e?void 0:n,headers:a,method:e,signal:s.signal}),d=ob(e,i,p.status,l,a,p.headers.get(aK)??void 0);if(o.destroyed||o.writableEnded)return void p.body?.cancel().catch(()=>void 0);let c=await a2(p);return ov(i,p.status,d)&&oy({method:e,requestBody:oS(i,n),requestHeaders:a,responseBody:c,responseHeaders:p.headers,statusCode:p.status,targetUrl:i}),o.destroyed||o.writableEnded||(t=aQ(Object.fromEntries(p.headers),[aK]),delete t["content-encoding"],delete t["content-length"],aZ(o,of),o.writeHead(p.status,t),o.end(c)),{body:c,ok:p.ok}}catch(p){if(o.destroyed||o.writableEnded||s.signal.aborted)return;let t=`Failed to proxy sandbox request: ${p instanceof Error?p.message:String(p)}`,r=ob(e,i,502,l,a);ov(i,502,r)&&oy({method:e,requestBody:oS(i,n),requestHeaders:a,responseBody:t,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:i}),a0(o,502,t,of)}}async function o_(e,t,n={}){let a;if("POST"!==e.method)return void a0(t,405,"Method not allowed",of);try{a=JSON.parse(await a3(e,0xa00000))}catch(e){a0(t,400,`Invalid sandbox proxy payload: ${e.message}`,of);return}let o=function(e,t){if(!e.url)return;let n=new URL(e.url,t);if(!n.pathname.startsWith(ou))return;let a=new URL(`${n.pathname}${n.search}`,t);var o=e.params;if(o)for(let[e,t]of Object.entries(o))null!=t&&a.searchParams.set(e,String(t));return a}(a,n.targetOrigin??Z);if(!o)return void a0(t,404,"Sandbox endpoint not found",of);if(!n.sandboxSessionId)return void a1(t,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},of);let i=function(e,t,n,a){if(t.pathname.startsWith(`${ou}session/`)&&t.pathname!==`${ou}session/create`)return JSON.stringify({..."object"==typeof e.data&&null!==e.data?e.data:{},sandbox_session_id:a});if(void 0===e.data)return;if("object"!=typeof e.data||null===e.data||!n)return JSON.stringify(e.data);let o={...e.data};return t.pathname.startsWith(`${ou}jsb/`)&&"app_key"in o&&(o.app_key=n),t.pathname===`${ou}passport/open/auth`&&"client_key"in o&&(o.client_key=n),JSON.stringify(o)}(a,o,n.sandboxAppId,n.sandboxSessionId),r=a.method||"POST",s=function(e,t,n,a,o){let i=Object.fromEntries(Object.entries(aX({...e.headers,...n,...void 0===a?{}:{"content-length":String(Buffer.byteLength(a))},"content-type":"application/json"},t,{...av(),...o?{[aJ]:o}:{}})).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(i))"accept-encoding"===e.toLowerCase()&&delete i[e];return i["accept-encoding"]="identity",i}(e,o,a.headers,i,n.sandboxSessionId),l=await ow({method:r,request:e,requestBody:i,requestHeaders:s,response:t,targetUrl:o,usePlatformFetch:!n.targetOrigin});if(o.pathname===om&&l?.ok)try{let e=JSON.parse(l.body.toString("utf8"));(void 0===e.code||0===e.code)&&n.onBusinessInfoUpdated?.(function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t="string"==typeof e.csr_pem?e.csr_pem.trim():"",n="string"==typeof e.phone_num?e.phone_num.trim():"";return t&&n?{csrPem:t,phoneNum:n}:void 0}(a.data))}catch{}}let oE=h("node:util"),ox="/app_developer/api/sandbox/bridge/events",oC="/app_developer/api/sandbox/bridge/response",oA=new Set(["connection","content-length","host"]),oO=new Set(["heartbeat"]),oI=[500,1e3,2e3,5e3],oT=0;function oP(e){return e.length<=8?e:`${e.slice(0,4)}...${e.slice(-4)}`}function ok(e,t=new Headers,n=""){return{response:e,responseHeaders:Object.fromEntries(t),statusText:n}}async function oL(e){let t,n,a=e.request_id||"";if(!a)return ok({error_message:"bridge request_id is required",http_status:0,request_id:a,success:!1});if(!e.path?.startsWith("/"))return ok({error_message:`invalid bridge request path: ${e.path??""}`,http_status:0,request_id:a,success:!1});let o=function(e){if(e.origin)try{var t;return new URL(e.path??"/",(t=e.origin).endsWith("/")?t:`${t}/`)}catch{return}}(e);if(!o)return ok({error_message:`invalid bridge request origin: ${e.origin??""}`,http_status:0,request_id:a,success:!1});let i=(e.method||"GET").toUpperCase(),r=function(e){let t={};for(let[n,a]of Object.entries(e??{}))!n||oA.has(n.toLowerCase())||(t[n]=a);return t}(e.headers),s="GET"===i||"HEAD"===i?void 0:e.body??"",l=new AbortController,p=setTimeout(()=>l.abort(),(t="number"==typeof e.timeout_ms?e.timeout_ms:3e3,n="number"==typeof e.deadline_ms?e.deadline_ms-Date.now():t,Math.max(1,Math.min(t,n))));try{var d;let e=await fetch(o,{body:s,headers:r,method:i,redirect:"manual",signal:l.signal}),t=await e.text();return d={method:i,requestBody:s,requestHeaders:r,responseBody:t,responseHeaders:e.headers,statusCode:e.status,targetUrl:o},a5(d),ok({body:t,http_status:e.status,request_id:a,success:!0},e.headers,e.statusText)}catch(e){return a5({method:i,requestBody:s,requestHeaders:r,responseBody:e instanceof Error?e.message:String(e),responseHeaders:new Headers,statusCode:0,targetUrl:o}),ok({error_message:e instanceof Error?e.message:String(e),http_status:0,request_id:a,success:!1})}finally{clearTimeout(p)}}function oN(e,t=new Set){if(Array.isArray(e)){for(let n of e)oN(n,t);return[...t]}if(!e||"object"!=typeof e)return[...t];for(let[n,a]of Object.entries(e)){if(n.toLowerCase().replace(/[_-]/g,"").includes("logid")){if("string"==typeof a&&a)t.add(a);else if(Array.isArray(a))for(let e of a)"string"==typeof e&&e&&t.add(e);continue}oN(a,t)}return[...t]}function oR(e,t){e.onLog?.(t)}function oD(e){try{return JSON.parse(e)}catch{return}}function oM({detail:e,requestHeaders:t,status:n,targetUrl:a}){if("applet0930"===process.env.DEBUG){if("number"==typeof n)return void aF.request({method:"CONNECT",url:a.pathname,statusCode:n,headers:t,context:{detail:e}});aF.info("Bridge connection pending",{url:a.pathname,detail:e,ppe:eb(t)})}}function o$(e,t={}){"applet0930"===process.env.DEBUG&&aF.info(e,t)}async function oB(e,t){let n=JSON.stringify({sandbox_session_id:e.sandboxSessionId,...t}),a={"content-type":"application/json",[aJ]:e.sandboxSessionId,...av()};if(e.targetOrigin){let t=new URL(oC,e.targetOrigin),o=await fetch(t,{body:n,headers:a,method:"POST"}),i=await o.text();if(a5({method:"POST",requestBody:n,requestHeaders:a,responseBody:i,responseHeaders:o.headers,statusCode:o.status,targetUrl:t}),!o.ok)throw Error(`upload bridge response failed: ${o.status} ${i}`);return{responseBody:i,responseHeaders:Object.fromEntries(o.headers),responsePayload:oD(i)}}let o=new URL(oC,Z),i=await a_({body:n,headers:a,internal:!0,method:"POST",path:oC}),r=await i.text();if(a5({method:"POST",requestBody:n,requestHeaders:a,responseBody:r,responseHeaders:i.headers,statusCode:i.status,targetUrl:o}),!i.ok)throw Error(`upload bridge response failed: ${i.status} ${r}`);return{responseBody:r,responseHeaders:Object.fromEntries(i.headers),responsePayload:oD(r)}}async function oj(e,t){let n;try{n=JSON.parse(t)}catch(e){aF.warn("Sandbox Bridge request parse failed",{reason:e.message});return}let a=Date.now(),o=`bridge-${a}-${++oT}`,i=n.request_id||"",r={id:o,request:n,requestId:i,sandboxSessionId:e.sandboxSessionId,timestamp:a};oR(e,{...r,logIds:oN(n),status:"pending",updatedAtMs:a});let s=await oL(n),l={...s.response,headers:s.responseHeaders,status_text:s.statusText};try{let t=await oB(e,s.response);oR(e,{...r,logIds:oN([n,l,t]),response:l,status:s.response.success?"success":"error",updatedAtMs:Date.now()})}catch(t){throw oR(e,{...r,errorMessage:t instanceof Error?t.message:String(t),logIds:oN([n,l]),response:l,status:"error",updatedAtMs:Date.now()}),t}}async function oU(e,t,n){let a={sandbox_session_id:e.sandboxSessionId},o=new URL(`${ox}?sandbox_session_id=${encodeURIComponent(e.sandboxSessionId)}`,Z),i=(d=e.sandboxSessionId,{accept:"text/event-stream",host:o.host,[aJ]:d,...av()});oM({detail:`host=${i.host} session=${oP(e.sandboxSessionId)}`,requestHeaders:i,status:"pending",targetUrl:o}),o$("bridge/events request",{headers:{accept:i.accept,host:i.host,[aJ]:oP(e.sandboxSessionId),"x-tt-env":i["x-tt-env"],"x-use-ppe":i["x-use-ppe"]},path:ox,query:a});let r=await a_({headers:i,internal:!0,method:"GET",path:ox,query:a,signal:t});if(oM({detail:`content-type=${r.headers.get("content-type")??""}`,requestHeaders:i,status:r.status,targetUrl:o}),!r.ok||!r.body){let e=await r.text().catch(()=>"");a5({method:"GET",requestBody:void 0,requestHeaders:i,responseBody:e,responseHeaders:r.headers,statusCode:r.status,targetUrl:o}),aF.warn("Sandbox Bridge events request failed",{status:r.status,body:e.slice(0,500)});let t=Error(`Sandbox Bridge SSE failed: ${r.status} ${e}`);throw t.status=r.status,t}a5({method:"GET",requestBody:void 0,requestHeaders:i,responseBody:"",responseHeaders:r.headers,statusCode:r.status,targetUrl:o}),n?.();let s=r.body.getReader(),l=new oE.TextDecoder,p="";for(;!t.aborted;){let{done:t,value:n}=await s.read();if(t){o$("bridge/events stream ended",{session:oP(e.sandboxSessionId)});break}let a=(p+=l.decode(n,{stream:!0})).search(/\r?\n\r?\n/);for(;a>=0;){let t=p.slice(0,a),n=p.slice(a).match(/^\r?\n\r?\n/);p=p.slice(a+(n?.[0].length??2));let s=function(e){let t="message",n=[];for(let a of e.split(/\r?\n/)){if(a.startsWith("event:")){t=a.slice(6).trim();continue}a.startsWith("data:")&&n.push(a.slice(5).trimStart())}return{data:n.join("\n"),name:t}}(t);if(!function(e,t){if("applet0930"!==process.env.DEBUG||oO.has(e.name))return;let n=function(e){try{let t=JSON.parse(e);return"string"==typeof t.request_id?t.request_id:void 0}catch{return}}(e.data);aF.info("Bridge event received",{event:e.name,requestId:n,ppe:eb(t)}),aF.info(`Event detail
63
+ ${e.data}`)}(s,i),"bridge_request"===s.name){var d,c=r.headers,u=r.status;a5({method:`EVENT ${s.name}`,requestBody:s.data,requestHeaders:i,responseBody:"",responseHeaders:c,statusCode:u,targetUrl:o}),oj(e,s.data).catch(e=>{aF.warn("Sandbox Bridge request failed",{reason:e.message})})}else if("sandbox_resource_changed"===s.name){let t=function(e){let t=oD(e);if(!t||"object"!=typeof t||Array.isArray(t))return;let n=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,a=n?.resource,o=n?.action,i=n?.resource_id,r=n?.revision;if(("notice"===a||"task"===a)&&("upsert"===o||"remove"===o)&&"string"==typeof i&&i&&("number"==typeof r||"string"==typeof r))return{action:o,eventId:"string"==typeof t.event_id?t.event_id:"",occurredAtMs:"number"==typeof t.occurred_at_ms?t.occurred_at_ms:void 0,resource:a,resourceId:i,revision:r}}(s.data);t?e.onResourceChanged?.(t):aF.warn("Sandbox resource event parse failed")}a=p.search(/\r?\n\r?\n/)}}}async function oW(e,t){let n=0,a=!1;for(;!t.aborted;){try{await oU(e,t,()=>{a=!1,e.onConnectionStatusChange?.("connected")}),n=0}catch(n){if(t.aborted)return;let e=n.status;if(a||(aF.warn("无法接收来自平台服务的请求",{reason:n.message}),a=!0),401===e||403===e||404===e)return}e.onConnectionStatusChange?.("reconnecting"),await (0,y.setTimeout)(oI[Math.min(n,oI.length-1)],void 0,{signal:t}).catch(()=>void 0),n+=1}}let oF=h("node:stream"),oH="/app_developer/api",oV=new Set([`${oH}/simulator/chat`,`${oH}/simulator/tool/report`]),oG={"Access-Control-Expose-Headers":aK};async function oq(e,t,n,a){let o=new AbortController,i=()=>o.abort();e.once("aborted",i),e.socket.once("close",i),t.once("close",()=>{t.writableEnded||i()});try{let i=e.method??"GET",r=process.hrtime.bigint(),s=oX(e,n,a),l="GET"===i||"HEAD"===i?void 0:await a3(e,0xa00000),p=await a_({internal:!0,path:`${n.pathname}${n.search}`,method:i,body:l,headers:s,signal:o.signal});if(oY(i,n,p.status,r,s,p.headers.get(aK)??void 0),t.destroyed||t.writableEnded)return void p.body?.cancel().catch(()=>void 0);await oJ({method:i,requestBody:l,requestHeaders:s,requestUrl:n,response:t,upstreamResponse:p})}catch(e){if(t.destroyed||t.writableEnded||o.signal.aborted)return;a0(t,502,`代理模拟器请求失败:${e instanceof Error?e.message:String(e)}`,oG)}}async function oz(e,t,n,a,o){let i=new AbortController,r=()=>i.abort();e.once("aborted",r),e.socket.once("close",r),t.once("close",()=>{t.writableEnded||r()});try{let r=e.method??"GET",s=process.hrtime.bigint(),l="GET"===r||"HEAD"===r?void 0:await a3(e,0xa00000),p=oX(e,n,o,a),d=await fetch(a,{body:l,headers:p,method:r,signal:i.signal});if(oY(r,n,d.status,s,p,d.headers.get(aK)??void 0),t.destroyed||t.writableEnded)return void d.body?.cancel().catch(()=>void 0);await oJ({method:r,requestBody:l,requestHeaders:p,requestUrl:n,response:t,upstreamResponse:d})}catch(e){if(t.destroyed||t.writableEnded||i.signal.aborted)return;a0(t,502,`代理模拟器请求失败:${e instanceof Error?e.message:String(e)}`,oG)}}async function oJ({method:e,requestBody:t,requestHeaders:n,requestUrl:a,response:o,upstreamResponse:i}){var r,s;if(aZ(o,oG),o.writeHead(i.status,aQ(Object.fromEntries(i.headers),[aK])),r=a,s=i,r.pathname===`${oH}/simulator/chat`||s.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await oK({method:e,requestBody:t,requestHeaders:n,requestUrl:a,response:o,upstreamResponse:i});if("applet0930"!==process.env.DEBUG)return i.body?void await (0,f.pipeline)(oF.Readable.fromWeb(i.body),o):void o.end();let l=await a2(i);a5({method:e,requestBody:t,requestHeaders:n,responseBody:l,responseHeaders:i.headers,statusCode:i.status,targetUrl:a}),o.end(l)}async function oK({method:e,requestBody:t,requestHeaders:n,requestUrl:a,response:o,upstreamResponse:i}){if(!i.body){a5({method:e,requestBody:t,requestHeaders:n,responseBody:"",responseHeaders:i.headers,statusCode:i.status,targetUrl:a}),o.end();return}let r=oF.Readable.fromWeb(i.body);if("applet0930"!==process.env.DEBUG)return void await (0,f.pipeline)(r,o);a5({method:e,requestBody:t,requestHeaders:n,responseBody:"(event stream)",responseHeaders:i.headers,statusCode:i.status,targetUrl:a});let s=new oF.Transform({transform(e,t,n){let o;try{o=String(e).split("\n\n").filter(Boolean)}catch(t){return aF.error(`failed to decode event stream chunk: ${t?.toString()}`),n(null,e)}for(let e of o)aF.info(`Event from ${a.pathname}${a.search}
64
+ ${e}`);n(null,e)}});await (0,f.pipeline)(r,s,o)}function oY(e,t,n,a,o,i){if("applet0930"!==process.env.DEBUG)return;let r=Number(process.hrtime.bigint()-a)/1e6;aF.request({method:e,url:`${t.pathname}${t.search}`,statusCode:n,durationMs:r,headers:o,logId:i})}function oX(e,t,n,a=new URL(`${t.pathname}${t.search}`,Z)){return Object.fromEntries(Object.entries(aX(e.headers,a,{...av(),...n?{[aJ]:n}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]))}let oQ=h("node:child_process"),oZ=h("node:net"),o0="/__web_artifacts",o1="/wsd",o3="/__web_view_proxy__",o2="/__web_sdk_sandbox_bridge_logs",o4="/__web_sdk_sandbox_resource_events",o9={"Cache-Control":"no-cache"},o5={"Cache-Control":"no-cache"},o8="manifest.yaml",o6="SKILL.md",o7=e_.join("skill",o6),ie=e_.join(".dbx","config.json"),it="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",ia="/app_developer/api/sandbox/session/business_info/update";async function io({body:e,headers:t,method:n,sandboxPath:a,targetOrigin:o,targetUrl:i}){let r=new AbortController,s=setTimeout(()=>r.abort(),3e4);try{return o?await fetch(i,{body:e,headers:t,method:n,signal:r.signal}):await a_({internal:!0,path:a,body:e,headers:t,method:n,signal:r.signal})}catch(e){if(r.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${i}`);throw e}finally{clearTimeout(s)}}function ii(e,t){return(e?.[t]??process.env[t])?.trim()??""}function ir(e,t,n,a,o,i){if("applet0930"!==process.env.DEBUG)return;let r=Number(process.hrtime.bigint()-a)/1e6;aF.request({method:e,url:`${t.pathname}${t.search}`,statusCode:n,durationMs:r,headers:o,logId:i})}function is({method:e,requestBody:t,requestHeaders:n,responseBody:a,responseHeaders:o,statusCode:i,targetUrl:r}){a5({method:e,requestBody:t,requestHeaders:n,responseBody:a,responseHeaders:o,statusCode:i,targetUrl:r})}async function il(e,t,n){let a,o,i="/app_developer/api/sandbox/session/create",r="POST",s=function(){let e=new Set;for(let t of(process.env[it]??"").split(",")){let n=t.trim();if(n)try{let t=new URL(n),a=t.hostname.replace(/^\[|\]$/g,"").toLowerCase(),o="localhost"===a||"::1"===a||4===(0,oZ.isIP)(a)&&a.startsWith("127.");if("http:"!==t.protocol&&"https:"!==t.protocol||!o)throw Error("only loopback HTTP(S) origins are allowed");e.add(t.origin)}catch(e){throw Error(`${it} contains an invalid origin: ${n} (${e instanceof Error?e.message:String(e)})`)}}return[...e]}(),l=JSON.stringify({sandbox_project_id:"default",manifest:ix(e)?to.readFileSync(e,"utf8"):"",business_templates:ix(t)?to.readFileSync(t,"utf8"):"",...s.length>0?{bridge_origins:s}:{}}),p={"content-type":"application/json",...av()},d=new URL(i,n??Z),c=process.hrtime.bigint();try{a=await io({body:l,headers:p,method:r,sandboxPath:i,targetOrigin:n,targetUrl:d})}catch(t){let e=`创建 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw ir(r,d,502,c,p),is({method:r,requestBody:l,requestHeaders:p,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:d}),t}let u=a.headers.get(aK)||"",m=await a.text();ir(r,d,a.status,c,p,u),is({method:r,requestBody:l,requestHeaders:p,responseBody:m,responseHeaders:a.headers,statusCode:a.status,targetUrl:d});try{o=JSON.parse(m||"{}")}catch{throw Error(`创建 Sandbox session 失败:HTTP ${a.status} ${a.statusText||m||"响应不是有效 JSON"}${u?`,log_id=${u}`:""}`)}if(!a.ok||0!==o.code)throw Error(`创建 Sandbox session 失败:${o.message||a.statusText||a.status}${o.log_id||u?`,log_id=${o.log_id||u}`:""}`);let h=o.data?.sandbox_session_id,f=o.data?.sandbox_appid;if(!h||!f)throw Error(`创建 Sandbox session 失败:响应缺少 ${h?"sandbox_appid":"sandbox_session_id"}${o.log_id||u?`,log_id=${o.log_id||u}`:""}`);return{appId:f,sessionId:h}}async function ip(e,t,n){try{return await il(e,t,n)}catch(e){return aF.warn(`Sandbox 平台服务模拟已跳过:${e instanceof Error?e.message:String(e)}`),{appId:"",sessionId:""}}}function id(){return{csrUploaded:!1,phoneNumberUploaded:!1}}async function ic(e,t){let n,a,o="/app_developer/api/sandbox/session/business_info/get",i="POST",r=JSON.stringify({sandbox_session_id:e}),s={"content-type":"application/json",...av()},l=new URL(o,t??Z),p=process.hrtime.bigint();try{n=await io({body:r,headers:s,method:i,sandboxPath:o,targetOrigin:t,targetUrl:l})}catch(e){throw ir(i,l,502,p,s),e}let d=n.headers.get(aK)||"",c=await n.text();ir(i,l,n.status,p,s,d);try{a=JSON.parse(c||"{}")}catch{throw is({method:i,requestBody:r,requestHeaders:s,responseBody:JSON.stringify({omitted:"invalid business info response"}),responseHeaders:n.headers,statusCode:n.status,targetUrl:l}),Error(`获取 Sandbox session 信息失败:HTTP ${n.status} 响应不是有效 JSON${d?`,log_id=${d}`:""}`)}let u={csrUploaded:!!a.data?.csr_pem?.trim(),phoneNumberUploaded:!!a.data?.phone_num?.trim()};if(is({method:i,requestBody:r,requestHeaders:s,responseBody:JSON.stringify({code:a.code,data:u,log_id:a.log_id}),responseHeaders:n.headers,statusCode:n.status,targetUrl:l}),!n.ok||void 0!==a.code&&0!==a.code)throw Error(`获取 Sandbox session 信息失败:${a.message||n.statusText||n.status}${a.log_id||d?`,log_id=${a.log_id||d}`:""}`);return u}async function iu(e,t){if(!e)return id();try{return await ic(e,t)}catch(e){return aF.warn(`Sandbox session 信息查询已跳过:${e instanceof Error?e.message:String(e)}`),id()}}async function im(e,t,n){let a,o,i="POST",r=JSON.stringify({csr_pem:e.csrPem,phone_num:e.phoneNum,sandbox_session_id:t}),s={"content-type":"application/json",...av(),[aJ]:t},l=new URL(ia,n??Z),p=process.hrtime.bigint();try{a=await io({body:r,headers:s,method:i,sandboxPath:ia,targetOrigin:n,targetUrl:l})}catch(e){throw ir(i,l,502,p,s),e}let d=a.headers.get(aK)||"",c=await a.text();ir(i,l,a.status,p,s,d),is({method:i,requestBody:JSON.stringify({csr_pem:"[redacted]",phone_num:"[redacted]",sandbox_session_id:t}),requestHeaders:s,responseBody:c,responseHeaders:a.headers,statusCode:a.status,targetUrl:l});try{o=JSON.parse(c||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${a.status} 响应不是有效 JSON${d?`,log_id=${d}`:""}`)}if(!a.ok||void 0!==o.code&&0!==o.code)throw Error(`更新 Sandbox session 信息失败:${o.message||a.statusText||a.status}${o.log_id||d?`,log_id=${o.log_id||d}`:""}`)}async function ih(e,t,n){if(!e||!t.csrPem||!t.phoneNum)return!1;try{return await im({csrPem:t.csrPem,phoneNum:t.phoneNum},e,n),aF.info("Sandbox business info 已自动上传",{sessionId:e}),!0}catch(e){return aF.warn(`Sandbox business info 自动上传已跳过:${e instanceof Error?e.message:String(e)}`),!1}}async function ig(e,t){let n,a="/app_developer/api/sandbox/session/revoke",o="POST",i=JSON.stringify({sandbox_session_id:e}),r={"content-type":"application/json",...av()},s=new URL(a,t??Z),l=process.hrtime.bigint();try{n=await io({body:i,headers:r,method:o,sandboxPath:a,targetOrigin:t,targetUrl:s})}catch(t){let e=`撤回 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw ir(o,s,502,l,r),is({method:o,requestBody:i,requestHeaders:r,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:s}),t}let p=n.headers.get(aK)||"",d=await n.text();ir(o,s,n.status,l,r,p),is({method:o,requestBody:i,requestHeaders:r,responseBody:d,responseHeaders:n.headers,statusCode:n.status,targetUrl:s});let c=JSON.parse(d||"{}");if(!n.ok||0!==c.code)throw Error(`撤回 Sandbox session 失败:${c.message||n.statusText||n.status}${c.log_id||p?`,log_id=${c.log_id||p}`:""}`)}async function ib(e){if(e.recreatePromise)return e.recreatePromise;e.recreatePromise=(async()=>{var n;let a=e.sandboxSessionId;a&&await ig(a,e.sandboxTargetOrigin),e.bridge?.close(),e.bridge=void 0;let o=await il(e.simulatorManifestPath,e.simulatorBusinessTemplatesPath,e.sandboxTargetOrigin),i=o.sessionId,r=await ih(i,e.businessInfoInput,e.sandboxTargetOrigin)?{csrUploaded:!0,phoneNumberUploaded:!0}:await iu(i,e.sandboxTargetOrigin);return e.sandboxAppId=o.appId,e.sandboxSessionId=i,e.businessInfo=r,(n=e).resourceConnectionStatus="connecting",n.resourceEventSequence=0,n.resourceEvents.length=0,n.resourceGeneration+=1,iy(n),e.bridge=iv(e,i),t&&(t.sandboxBridge=e.bridge,t.sandboxSessionId=i),aF.info("Sandbox session 已重建",{sessionId:i}),{...o,businessInfoUploaded:r.csrUploaded&&r.phoneNumberUploaded}})();try{return await e.recreatePromise}finally{e.recreatePromise=void 0}}function iy(e){e.resourceEventsUpdatedAtMs=Math.max(Date.now(),e.resourceEventsUpdatedAtMs+1)}function iv(e,t){var n={onConnectionStatusChange:t=>{e.resourceConnectionStatus!==t&&(e.resourceConnectionStatus=t,iy(e))},onLog:t=>{let n=e.bridgeLogs.findIndex(e=>e.id===t.id);n>=0?e.bridgeLogs[n]=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)},onResourceChanged:t=>{e.resourceEvents.push({...t,sequence:++e.resourceEventSequence}),e.resourceEvents.length>200&&e.resourceEvents.splice(0,e.resourceEvents.length-200),iy(e)},sandboxSessionId:t,targetOrigin:e.sandboxTargetOrigin};if(!n.sandboxSessionId)return void aF.warn("Sandbox Bridge skipped: missing sandbox session id");let a=new AbortController;return o$("start sandbox bridge",{session:oP(n.sandboxSessionId)}),n.onConnectionStatusChange?.("connecting"),oW(n,a.signal),{close:()=>a.abort()}}async function iS(e,t,n){if("POST"!==e.method)return void a0(t,405,"Method not allowed");if(!n)return void a0(t,503,"Sandbox session is not initialized");try{let a=await a3(e,1048576);if(a){let e=JSON.parse(a);if("string"!=typeof e.csrPem||"string"!=typeof e.phoneNum)return void a0(t,400,"Invalid Sandbox business info");n.businessInfoInput={csrPem:e.csrPem.trim(),phoneNum:e.phoneNum.trim()}}let o=await ib(n);a1(t,200,{code:0,data:{sandbox_appid:o.appId,business_info_uploaded:o.businessInfoUploaded,sandbox_session_id:o.sessionId},message:"ok"})}catch(e){a0(t,500,e.message)}}async function iw(e){let{command:t,args:n}="darwin"===process.platform?{command:"open",args:[e]}:"win32"===process.platform?{command:"cmd",args:["/c","start","",e]}:{command:"xdg-open",args:[e]};await new Promise((e,a)=>{let o=(0,oQ.spawn)(t,n,{detached:!0,stdio:"ignore"});o.once("error",a),o.once("spawn",()=>{o.unref(),e()})})}async function i_(e,t=iw){let n=new URL(e).toString();try{await t(n)}catch(e){aF.error("打开 Web 模拟器失败",{error:e}),aF.info("请手动打开 Web 模拟器(本地)",{url:n})}return n}function iE(e){return({".css":"text/css; charset=utf-8",".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".svg":"image/svg+xml",".wasm":"application/wasm",".yaml":"application/yaml; charset=utf-8",".yml":"application/yaml; charset=utf-8"})[e_.extname(e).toLowerCase()]??"application/octet-stream"}function ix(e){if(!e)return!1;try{return to.statSync(e).isFile()}catch{return!1}}function iC(e,t){if(!e)return;let n=e_.isAbsolute(e)?e:e_.resolve(t??process.cwd(),e);return ix(n)?n:void 0}function iA(e,t){if(e&&t)return e_.relative(t,e).split(e_.sep).join("/")||"."}function iO(e){let t=e_.resolve(e);for(;;){let e;if(e=t,ix(e_.join(e,ie)))return t;let n=e_.dirname(t);if(n===t)break;t=n}}function iI(e){return[...new Set(e.filter(Boolean))].find(ix)}function iT(e){if(!e)return!1;try{return to.statSync(e).isDirectory()}catch{return!1}}function iP(e){return ix(e)?e:iT(e)?iI([e_.join(e,o6)]):void 0}function ik(e,t){if(t){if(!t)return;let n=e?iO(e):void 0;return[...new Set((e_.isAbsolute(t)?[void 0]:[e,n,process.cwd()]).map(e=>e_.isAbsolute(t)?t:e_.resolve(e??process.cwd(),t)))].map(iP).find(Boolean)}if(!e)return;let n=iO(e);return iI([n?e_.join(n,o7):void 0,e_.join(e,o7),e_.join(process.cwd(),o7)])}function iL(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 iN(e,t){return`${o3}?url=${encodeURIComponent(new URL(t,e.origin).toString())}`}let iR="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",iD="__wsd_webview_target__";function iM(e,t="/"){let n,a,o=new URL(t,"http://localhost");try{n=decodeURIComponent(o.pathname)}catch{return}let i="/"===n||n.endsWith("/")?`${n}index.html`:n,r=e_.join(e,i);if(""===(a=e_.relative(e,r))||!a.startsWith("..")&&!e_.isAbsolute(a))return r}async function i$(e,t){if("POST"!==e.method)return void a1(t,405,{message:"Method Not Allowed"});try{var n,a;let o,i,r,s=JSON.parse(await a3(e,0xa00000)),l=iL(s.url),p=(s.method??"GET").toUpperCase(),d=(n=s.header,i=new Headers(n??{"content-type":"application/json"}),["connection","content-length","host","origin","referer"].forEach(e=>i.delete(e)),i),c=await fetch(l,{body:"GET"!==p&&"HEAD"!==p?function(e,t){var n;let a=e.data;if(null==a)return;if("base64"===e.dataEncoding&&"string"==typeof a){let e;return e=new ArrayBuffer((n=Buffer.from(a,"base64")).byteLength),new Uint8Array(e).set(n),e}if("string"==typeof a)return a;let o=t.get("content-type")?.toLowerCase()??"";if(o.includes("application/x-www-form-urlencoded")&&"object"==typeof a){let e=new URLSearchParams;return Object.entries(a).forEach(([t,n])=>{e.set(t,String(n))}),e.toString()}return o.includes("application/json")||"object"==typeof a?JSON.stringify(a):String(a)}(s,d):void 0,headers:d,method:p}),u="arraybuffer"===s.dataType||"arraybuffer"===s.responseType;if(u)o=Buffer.from(await c.arrayBuffer()).toString("base64");else{let e=await c.text();o="string"===s.dataType||0===e.length?e:JSON.parse(e)}a1(t,200,{data:o,dataEncoding:u?"base64":void 0,header:(a=c.headers,r={},a.forEach((e,t)=>{r[t]=e}),r),statusCode:c.status})}catch(e){a1(t,500,{message:e instanceof Error?e.message:String(e)})}}async function iB(e,t){if("GET"!==e.method&&"HEAD"!==e.method)return void a0(t,405,"Method Not Allowed");let n=aY(e);try{var a;let o=iL(n?.searchParams.get("url")??void 0),i=await fetch(o,{headers:{"user-agent":iR,..."string"==typeof e.headers.accept?{accept:e.headers.accept}:{},..."string"==typeof e.headers["accept-language"]?{"accept-language":e.headers["accept-language"]}:{}},method:e.method}),r=i.url?new URL(i.url):o,s=i.headers.get("content-type")??"",l=aQ(Object.fromEntries(i.headers));if(l["cache-control"]="no-cache",delete l["content-encoding"],delete l["content-length"],"HEAD"===e.method||!s.includes("text/html")&&!s.includes("text/css")){let n="HEAD"===e.method?void 0:Buffer.from(await i.arrayBuffer());aZ(t),t.writeHead(i.status,{...l,...n?{"content-length":n.byteLength}:{}}),t.end(n);return}let p=(a=await i.text(),s.includes("text/html")?(function(e,t){let n,a=(n=`${t.pathname}${t.search}${t.hash}`,`<script>(function () {
65
+ if (window === window.parent) { return; }
66
+ try { history.replaceState(null, '', ${JSON.stringify(n)}); } catch (_) {}
67
+ try {
68
+ Object.defineProperty(Navigator.prototype, 'userAgent', {
69
+ get: function () { return ${JSON.stringify(iR)}; },
70
+ configurable: true
71
+ });
72
+ Object.defineProperty(Navigator.prototype, 'platform', {
73
+ get: function () { return 'iPhone'; },
74
+ configurable: true
75
+ });
76
+ } catch (_) {}
77
+ if (window.AppletBridgeModule) { return; }
78
+ window.AppletBridgeModule = {
79
+ postMessage: function (message) {
80
+ var payload = typeof message === 'string' ? message : JSON.stringify(message);
81
+ try { window.parent.postMessage(payload, '*'); } catch (_) {}
82
+ return Promise.resolve({});
83
+ },
84
+ postMessageSync: function () { return undefined; }
85
+ };
86
+ })();</script>`),o=/<head[^>]*>/i.exec(e);if(o){let t=o.index+o[0].length;return`${e.slice(0,t)}${a}${e.slice(t)}`}return`${a}${e}`})(a,r).replace(/\b(src|href|action)=(["'])\/(?!\/)([^"']*)\2/g,(e,t,n,a)=>`${t}=${n}${iN(r,`/${a}`)}${n}`):s.includes("text/css")?a.replace(/url\((["']?)\/(?!\/)([^"')]+)\1\)/g,(e,t,n)=>{let a=iN(r,`/${n}`);return`url(${t}${a}${t})`}):a);aZ(t),t.writeHead(i.status,{...l,...s.includes("text/html")?{"set-cookie":`${iD}=${encodeURIComponent(r.origin)}; Path=/; SameSite=Lax; HttpOnly`}:{},"content-length":Buffer.byteLength(p)}),t.end(p)}catch(e){a0(t,502,`代理 web-view 页面失败: ${e instanceof Error?e.message:String(e)}`)}}async function ij(e,t,n,a){let o;if("OPTIONS"===e.method){aZ(t,o9),t.writeHead(204),t.end();return}if("GET"===e.method){let a,o;return void a1(t,200,function(e,t){if(!aT(e)||!("debug_snapshot"in e))return e;let{debug_snapshot:n,...a}=e;return t?{...a,snapshot:n}:a}(n.snapshot,(a=aY(e),null!=(o=a?.searchParams.get("DEBUG"))&&"0"!==o&&"false"!==o.toLowerCase()))??{stored:!1},o9)}if("POST"!==e.method)return void a1(t,405,{error:"Method not allowed"},o9);try{o=JSON.parse(await a3(e,0xa00000))}catch(e){a1(t,400,{error:e.message},o9);return}o=function(e,t){if(!aT(e)||!aT(t))return t;let n=aT(e.snapshot)?e.snapshot:void 0,a=aT(t.snapshot)?t.snapshot:void 0,o=aT(n?.runtime_snapshot)?n.runtime_snapshot:void 0,i=aT(a?.runtime_snapshot)?a.runtime_snapshot:void 0;return!(!n||!a||!o||!i||Object.hasOwn(i,"root"))&&Object.hasOwn(o,"root")&&n.client_id===a.client_id&&o.updatedAtMs===i.updatedAtMs&&JSON.stringify(o.target)===JSON.stringify(i.target)?{...t,snapshot:{...a,runtime_snapshot:{...i,root:o.root}}}:t}(n.snapshot,o),n.snapshot=o,n.updatedAtMs=Date.now(),a.noteSnapshot(function(e){if(!aT(e))return;let t=aT(e.snapshot)?e.snapshot:void 0,n=aT(e.debug_snapshot)?e.debug_snapshot:void 0,a=t?.client_id??n?.client_id;return"string"==typeof a&&a.trim()?a.trim():void 0}(o)),a1(t,200,{ok:!0,updated_at_ms:n.updatedAtMs},o9)}function iU(e){let t=e.headers.host;return"string"==typeof t&&t?`http://${t}`:void 0}async function iW(e,t){await new Promise((n,a)=>{let o=t=>{e.off("listening",i),a(t)},i=()=>{e.off("error",o),n()};e.once("error",o),e.once("listening",i),e.listen(t,"127.0.0.1")})}async function iF(e,t,n,a,o,i,r={},s,l,p){let d=await z(9e3),c=aH.createServer(function(e,t,n,a,o,i,r={},s,l,p){let d={},c=new oa(d);return(u,m)=>{var h;let f,g,b=aY(u),y=b?.pathname??"/";if("/__web_sdk_debug_context"===y){let e,a,l,p;return void(e=function(e){try{return ik(e.appDirectory,e.simulatorSkillPath)}catch{return}}((h={appDirectory:r.appDirectory,artifactOrigin:t,debuggerMcpEndpoint:iU(u)?new URL(od,iU(u)).toString():od,mcpEndpoint:n,sandboxBusinessInfo:s?.businessInfo??id(),sandboxBusinessInfoInput:s?.businessInfoInput??{},sandboxSessionAvailable:!!s?.sandboxSessionId,simulatorBusinessTemplatesPath:i,simulatorManifestPath:o,simulatorSkillSource:r}).simulatorSkillSource),a=iA(h.simulatorBusinessTemplatesPath,h.appDirectory),l=iA(h.simulatorManifestPath,h.appDirectory),p=iA(e,h.appDirectory),a1(m,200,{...h.appDirectory?{launchDir:h.appDirectory}:{},...h.debuggerMcpEndpoint?{debuggerMcpEndpoint:h.debuggerMcpEndpoint}:{},manifestOriginalUrl:new URL("/base/manifest.json",h.artifactOrigin).toString(),...h.mcpEndpoint?{mcpOriginalEndpoint:h.mcpEndpoint}:{},...h.simulatorManifestPath?{simulatorManifestOriginalUrl:h.simulatorManifestPath}:{},...h.simulatorBusinessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:h.simulatorBusinessTemplatesPath}:{},...a?{simulatorBusinessTemplatesRelativePath:a}:{},...l?{simulatorManifestRelativePath:l}:{},sandboxSessionAvailable:h.sandboxSessionAvailable,sandboxCsrUploaded:h.sandboxBusinessInfo.csrUploaded,sandboxPhoneNumberUploaded:h.sandboxBusinessInfo.phoneNumberUploaded,sandboxBridgeLogsEndpoint:o2,sandboxResourceEventsEndpoint:o4,...h.sandboxBusinessInfoInput.csrPem?{sandboxCsrPem:h.sandboxBusinessInfoInput.csrPem}:{},...h.sandboxBusinessInfoInput.phoneNum?{sandboxPhoneNum:h.sandboxBusinessInfoInput.phoneNum}:{},...e?{simulatorSkillOriginalUrl:e,...p?{simulatorSkillRelativePath:p}:{}}:{}},o5))}if("/__agent_trace"===y)return void ij(u,m,d,c);if(y===o2)return void("GET"!==u.method&&"DELETE"!==u.method?a0(m,405,"Method not allowed"):("DELETE"===u.method&&s&&(s.bridgeLogs.length=0,s.bridgeLogsUpdatedAtMs=Math.max(Date.now(),s.bridgeLogsUpdatedAtMs+1)),a1(m,200,{logs:s?.bridgeLogs??[],updatedAtMs:s?.bridgeLogsUpdatedAtMs??0},{"Cache-Control":"no-cache"})));if(y===o4)return void("GET"!==u.method?a0(m,405,"Method not allowed"):a1(m,200,{connectionStatus:s?.resourceConnectionStatus??"connecting",events:s?.resourceEvents??[],generation:s?.resourceGeneration??0,updatedAtMs:s?.resourceEventsUpdatedAtMs??0},{"Cache-Control":"no-cache"}));if(aY(u)?.pathname==="/__wsd_control_events")return void function(e,t,n){if("GET"!==e.method)return a1(t,405,{error:"Method not allowed"});let a=oe(aY(e)?.searchParams.get("clientId"));a?(aZ(t,{"Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}),t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8"}),t.write(": connected\n\n"),n.registerClient(a,t)):a1(t,400,{error:"clientId is required"})}(u,m,c);if(aY(u)?.pathname==="/__wsd_control_results")return void oo(u,m,c);if(aY(u)?.pathname===od)return void oc(u,m,d,c);if((f=aY(u))&&(f.pathname===oH||f.pathname.startsWith(`${oH}/`)))return void function(e,t,n={}){let a=aY(e);if(!a)return a0(t,400,"请求无效",oG);if(!oV.has(a.pathname))return a0(t,404,"未找到模拟器接口",oG);let o=n.targetOrigin??Z,i=new URL(`${a.pathname}${a.search}`,o);n.targetOrigin?oz(e,t,a,i,n.sandboxSessionId):oq(e,t,a,n.sandboxSessionId)}(u,m,{sandboxSessionId:s?.sandboxSessionId,targetOrigin:p});if(aY(u)?.pathname==="/__web_sdk_sandbox_proxy__")return void o_(u,m,{onBusinessInfoUpdated:e=>{s&&(s.businessInfo={csrUploaded:!0,phoneNumberUploaded:!0},e&&(s.businessInfoInput=e))},sandboxAppId:s?.sandboxAppId,sandboxSessionId:s?.sandboxSessionId,targetOrigin:l});if("/__web_sdk_sandbox_session_recreate__"===y)return void iS(u,m,s);if(g=aY(u),g?.pathname==="/__mcp_proxy")return void function(e,t,n={}){let a=aY(e),o=ee(n.targetEndpoint);if(!a)return a0(t,400,"Bad request");if(!o)return a0(t,404,"MCP endpoint not configured");let i=new URL(o);for(let[e,t]of new URLSearchParams(a.search))i.searchParams.append(e,t);a8(e,t,{createResponseHeaders:aQ,errorMessage:"代理 MCP 请求失败",requestHeaders:aX(e.headers,i,{...av(),...n.headers}),targetUrl:i})}(u,m,{headers:a,targetEndpoint:n});if("/__simulator_manifest/manifest.yaml"===y)return void function(e,t){if(!ix(t))return a0(e,404,"Simulator manifest not found");let n=to.statSync(t);aZ(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":n.size,"Content-Type":iE(t)}),to.createReadStream(t).pipe(e)}(m,o);if("/__simulator_skill/skill.md"===y){let e;return void(void 0===(e=function(e){try{return function(e,t){let n;var a,o=ik(e,t);if(ix(o))return[to.readFileSync(o,"utf8").trim(),...(a=e_.dirname(o),n=e_.join(a,"references"),!iT(n)?[]:(function e(t){let n;try{n=to.readdirSync(t,{withFileTypes:!0})}catch{return[]}let a=[];for(let o of n){let n=e_.join(t,o.name);if(o.isDirectory()){a.push(...e(n));continue}o.isFile()&&[".md",".markdown",".txt"].includes(e_.extname(n).toLowerCase())&&a.push(n)}return a})(n).sort((e,t)=>e_.relative(n,e).localeCompare(e_.relative(n,t))).flatMap(e=>{let t=to.readFileSync(e,"utf8").trim();if(!t)return[];let n=e_.relative(a,e).split(e_.sep).join("/");return[`<!-- local-skill-reference:${n} -->
87
+ ${t}`]}))].filter(Boolean).join("\n\n---\n\n")}(e.appDirectory,e.simulatorSkillPath)}catch{return}}(r))?a0(m,404,"Simulator skill not found"):(aZ(m),m.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(e),"Content-Type":"text/markdown; charset=utf-8"}),m.end(e)))}if(y.startsWith(o0))return void function(e,t,n){let a=aY(e);if(!a)return a0(t,400,"Bad request");let o=a.pathname.replace(o0,"")||"/",i=new URL(`${o}${a.search}`,n);a8(e,t,{createResponseHeaders:e=>({...aQ(e),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:aX(e.headers,i),targetUrl:i})}(u,m,t);if(y===o1||y.startsWith(`${o1}/`))return void function(e,t,n){let a=n.slice(`${o1}/`.length),o=e_.join(t,"wsd",a);if(!a||a!==e_.basename(a)||!ix(o))return a0(e,404,"Not found");let i=to.statSync(o);aZ(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":i.size,"Content-Type":iE(o)}),to.createReadStream(o).pipe(e)}(m,e,y);if("/__web_sdk_request_proxy__"===y)return void i$(u,m);if(y===o3)return void iB(u,m);if(y.startsWith("/__doubao_web_sdk_native_modules"))return void function(e,t,n){let a=iM(n,e.url);if(!a)return a0(t,403,"Forbidden");if(!ix(a))return a0(t,404,"Not found");let o=to.statSync(a);aZ(t),t.writeHead(200,{"Content-Length":o.size,"Content-Type":iE(a)}),to.createReadStream(a).pipe(t)}(u,m,e);if(y.startsWith("/__"))return void a0(m,404,"Debugger resource not found");let v=iM(e,u.url),S=function(e){let t=e.headers.referer;if("string"==typeof t)try{let e=new URL(t);if(e.pathname!==o3)return;let n=e.searchParams.get("url");return n?new URL(n).origin:void 0}catch{return}}(u)??function(e){let t=e.headers.cookie;if("string"!=typeof t)return;let n=t.split(";").map(e=>e.trim()).find(e=>e.startsWith(`${iD}=`));if(n)try{let e=new URL(decodeURIComponent(n.slice(iD.length+1)));return"http:"===e.protocol||"https:"===e.protocol?e.origin:void 0}catch{return}}(u);S&&!(v&&ix(v))?function(e,t,n){let a,o=aY(e);try{a=new URL(`${o?.pathname??"/"}${o?.search??""}`,n)}catch{a0(t,400,"Invalid web-view runtime request target");return}if("GET"===e.method&&String(e.headers.accept??"").includes("text/html")){aZ(t),t.writeHead(302,{location:`${o3}?url=${encodeURIComponent(a.toString())}`}),t.end();return}a8(e,t,{createResponseHeaders:e=>({...aQ(e),"cache-control":"no-cache"}),errorMessage:"代理 web-view 页面请求失败",requestHeaders:{...aX(e.headers,a),"user-agent":iR},targetUrl:a})}(u,m,S):function(e,t,n){let a=iM(n,e.url);if(!a)return a0(t,403,"Forbidden");to.existsSync(a)||(a=e_.join(n,"index.html"));let o=to.statSync(a);o.isFile()?(aZ(t),t.writeHead(200,{"Content-Length":o.size,"Content-Type":iE(a)}),to.createReadStream(a).pipe(t)):a0(t,404,"Not found")}(u,m,e)}}(e,t,n,a,o,i,r,s,l,p));return await iW(c,d),{origin:`http://127.0.0.1:${d}`,server:c}}async function iH(e){e.listening&&await new Promise((t,n)=>{e.close(e=>{e?n(e):t()}),e.closeIdleConnections()})}async function iV(){if(!t)return;let{sandboxBridge:e,server:n}=t;t=void 0,e?.close(),await iH(n)}async function iG(e){try{var n,a,o,i;let r=ee(e.mcpEndpoint),s=e.simulatorManifestPath?iC(e.simulatorManifestPath,e.appDirectory):function(e){if(!e)return;let t=iO(e);return iI([t?e_.join(t,o8):void 0,e_.join(e,o8),e_.join(process.cwd(),o8)])}(e.appDirectory),l=(n=e.simulatorBusinessTemplatesPath,a=e.appDirectory,n?iC(n,a):s?iC(e_.join(e_.dirname(s),"business-templates.yaml"),a):void 0),p={appDirectory:e.appDirectory,simulatorSkillPath:e.simulatorSkillPath},d=`${p.appDirectory??""}\0${p.simulatorSkillPath??""}`,c=function(e,t){let n=ii(e,"DOUBAO_SANDBOX_PHONE_NUM"),a=ii(e,"DOUBAO_SANDBOX_CSR_FILE"),o=iC(a,t),i="";if(a&&!o)aF.warn(`Sandbox CSR 文件不存在:${a}`);else if(o)try{i=to.readFileSync(o,"utf8").trim()}catch(e){aF.warn(`Sandbox CSR 文件读取失败:${e instanceof Error?e.message:String(e)}`)}return{...n?{phoneNum:n}:{},...i?{csrPem:i}:{}}}(e.env,e.appDirectory),u=`${c.phoneNum??""}\0${c.csrPem??""}`;if(o=t,o?.server.listening){if(t?.artifactOrigin===e.artifactOrigin&&t.mcpEndpoint===r&&t.simulatorBusinessTemplatesPath===l&&t.simulatorManifestPath===s&&t.simulatorSkillSourceKey===d&&t.sandboxBusinessInfoInputKey===u&&t.sandboxTargetOrigin===e.sandboxTargetOrigin&&t.simulatorTargetOrigin===e.simulatorTargetOrigin)return await i_(t.origin,e.openBrowser),t;await iV()}let m={distPath:i=e.debuggerDistPath,indexPath:e_.join(i,"index.html")};if(!to.existsSync(m.indexPath))return void aF.error("Web 模拟器资源缺失,请联系框架开发者。");let h=await ip(s,l,e.sandboxTargetOrigin),f=h.sessionId,g=await ih(f,c,e.sandboxTargetOrigin)?{csrUploaded:!0,phoneNumberUploaded:!0}:await iu(f,e.sandboxTargetOrigin),b={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:g,businessInfoInput:c,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,sandboxAppId:h.appId,sandboxSessionId:f,sandboxTargetOrigin:e.sandboxTargetOrigin,simulatorBusinessTemplatesPath:l,simulatorManifestPath:s},{origin:y,server:v}=await iF(m.distPath,e.artifactOrigin,r,e.mcpHeaders,s,l,p,b,e.sandboxTargetOrigin,e.simulatorTargetOrigin),S=()=>{v.close()};v.once("close",()=>{process.off("exit",S)}),process.once("exit",S);let w=await i_(y,e.openBrowser),_=f?iv(b,f):void 0;return b.bridge=_,t={artifactOrigin:e.artifactOrigin,close:()=>iV(),debuggerMcpEndpoint:new URL(od,y).toString(),mcpEndpoint:r,origin:y,sandboxBridge:_,sandboxBusinessInfoInputKey:u,server:v,simulatorBusinessTemplatesPath:l,simulatorManifestPath:s,simulatorSkillSource:p,simulatorSkillSourceKey:d,sandboxSessionId:f,sandboxTargetOrigin:e.sandboxTargetOrigin,simulatorTargetOrigin:e.simulatorTargetOrigin,url:w}}catch(e){aF.error("启动 Web SDK 调试器失败",{error:e});return}}function iq(e){return iG({...e,debuggerDistPath:e.debuggerDistPath??B()})}async function iz({appId:e,appletUrl:t,pages:n,widgets:a,driver:o,isSigned:i,isDisposed:r}){let s=await tC();if(r())return;if(!s)return void tN.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");let l=await tE(s).catch(e=>(r()||tN.error("重新启动应用失败",{error:e}),!1));if(r())return;if(!l)return void setTimeout(()=>{r()||tN.info("请确认应用已经启动。\n")},1e3);if(await new Promise(e=>{setTimeout(e,5e3)}),r())return;if(!o)return void tN.error("调试驱动尚未就绪。");let p=await ah(e,t,n,a,o,i);r()&&p?.()}async function iJ({context:e,port:t,driver:n,isSigned:a,onCleanupReady:o}){let i,r,s=e.metadata.getData(),l=s.app.appId,p=n5(t),d=n_(e.webMode),c=()=>{let t;return t=e.webDebuggerLaunchOptions,iq({appDirectory:e.appDirectory,artifactOrigin:p,env:{...e.env,...t?.env??{}},mcpEndpoint:t?.mcpEndpoint??tg({env:e.env}),mcpHeaders:t?.mcpHeaders,openBrowser:t?.openBrowser,simulatorBusinessTemplatesPath:t?.simulatorBusinessTemplatesPath,simulatorManifestPath:t?.simulatorManifestPath,simulatorSkillPath:t?.simulatorSkillPath,simulatorTargetOrigin:t?.simulatorTargetOrigin})};if(e.devServerInteractive){let t;t=function(e={}){let t={name:"Doubao Apps SDK",...e},n=t.name?`${t.name} 开发服务`:"",a=t.origin?`正在监听 ${w.gray(t.origin)}。`:"已启动。";return`
88
+ ${al(n)}${a}
89
+ `}(),"applet0930"===process.env.DEBUG||console.clear(),console.log(t),d||console.log(((e,t)=>{if(e&&t){let n=[{title:"\uD83C\uDF10 服务地址",content:t},{title:"\uD83D\uDCE6 应用 ID",content:e}].map(({title:e,titleHighlighter:t,content:n})=>{let a=t?t(e):w.bold(w.gray(e));return` - ${w.bgWhiteBright(w.italic(w.black(` ${a} `)))}: ${w.gray(n.startsWith("http")?w.underline(n):n)}`}).join("\n");return`
90
+ ${ar("豆包应用服务信息")}:
91
+
92
+ ${n}
93
+
94
+ `}return`
95
+ ${ar("豆包应用服务信息")}:
96
+
97
+ 调试服务未运行。`})(l,p)),await ai(e)}if(d)return void await c();let u=(i=!1,r=[],{add(e){e&&(i?e():r.push(e))},cleanup:()=>{i=!0,r.splice(0).forEach(e=>e())},isDisposed:()=>i});if(e.devServerInteractive){let t={context:e,appId:l,appletUrl:p,pages:s.pages,widgets:s.widgets,driver:n,isSigned:a,openWebDebugger:c,isDisposed:u.isDisposed};u.add(an.instance.addListener(e=>{let n=e.trim().toLowerCase();return("r"===n||"web"===n)&&(process.stdout.write(j(2)),"r"===n?iz(t):"off"===t.context.webMode?tN.error("Web 产物未启用。请在 app.config.ts 中添加 `web: true` 并重新启动开发服务。"):t.openWebDebugger(),!0)},"devCommands",-1))}o(u.cleanup);try{if(!n){e.devServerInteractive&&tN.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");return}u.add(await ah(l,p,s.pages,s.widgets,n,a,{interactive:e.devServerInteractive}))}catch(e){throw u.cleanup(),e}}let iK=(e,t,n)=>{if("applet0930"!==process.env.DEBUG)return void n();let a=process.hrtime.bigint(),o=e.method,i=e.url;t.on("finish",()=>{let e=Number(process.hrtime.bigint()-a)/1e6,n=i?new URL(i,"http://localhost").pathname:"",r=t.statusCode;tN.request({method:o||"UNKNOWN",url:n,statusCode:r,durationMs:e})}),n()},iY=h("crypto");class iX{constructor(e,t,n){this._content=t,this._hashCode=n,this.source=e}get content(){return this._content}get hashCode(){var e;return this._hashCode||(e=this.content,iY.createHash("sha256").update("string"==typeof e?e:new DataView(e.buffer,e.byteOffset,e.byteLength)).digest("hex").substring(0,8))}}class iQ extends iX{constructor(e,t){super(e,t),this._manifest={applet:{pages:[],tools:[]},widgets:[]};try{this._manifest=ea(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,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){ea(this._manifest,e)}setSCMVersion(e){this._manifest.scmVersion=e}setVersionCode(e){this._manifest.versionCode=e}setAppletManifest(e){this._manifest.applet=e}mergeAppletManifest(e){ea(this._manifest.applet,e)}setRenderType(e=N.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 iZ{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 iQ(e,JSON.stringify({}))),this.getAsset(e)}}class i0{options;constructor(e){this.options=e}apply(e){let t,{pluginSystem:n}=this.options;e.hooks.thisCompilation.tap({name:i0.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},a=>{a.hooks.processAssets.tapPromise({name:i0.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{t=new iZ,a.getAssets().forEach(e=>{let n=new iX(e.name,e.source.source(),e.info.contenthash?.[0]);t.addAsset(e.name,n)});let{entrypoints:o}=a,i={};o.forEach((e,n)=>{i[n]=e.getFiles().map(e=>{let n=t.getAsset(e);if(!n)throw Error(`Asset ${e} not found`);return new iX(n.source,n.content,n.hashCode)})});let r=this.options.context.appId;r&&t3.mkdirSync(eX.join(this.options.context.rootPath,r),{recursive:!0}),await n.callAssetsHooks("beforeEmit",{assets:t,chunks:i}),Object.keys(t.getAssets()).forEach(n=>{let o=t.getAsset(n);if(!o)return;let{source:i,destination:r}=o;if(!i||!r)return;a.getAsset(i)?a.renameAsset(i,r):a.emitAsset(r,new e.rspack.sources.RawSource(o.content));let s=a.getAsset(`${i}.map`);s&&a.renameAsset(s.name,`${r}.map`)}),await n.callAssetsHooks("afterEmit",{assets:{...t.getAssets()}})})})}}let i1=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class i3{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(i3.name,e=>{e.hooks.finishModules.tap(i3.name,()=>{let t=new Map,n=a=>{if(!a)return!1;let o=t.get(a);if(void 0!==o)return o;if(function(e){var t;let n=e.resourceResolveData?.descriptionFileData?.name;if("string"==typeof n&&i1.has(n))return!0;let a=(t=e.resource,t?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...i1].some(e=>a?.includes(`/node_modules/${e}/`))}(a))return t.set(a,!0),!0;for(let o of(t.set(a,!1),e.moduleGraph.getOutgoingConnections(a)))if(n(o.module))return t.set(a,!0),!0;return!1};e.entries.forEach((t,a)=>{t.dependencies.some(t=>n(e.moduleGraph.getModule(t)))&&this.options.markTemplateWidgetEntry(this.options.normalizeEntryName?.(a)??a)})})})}}class i2{options;constructor(e){this.options=e}apply(e){e.hooks.make.tapPromise(i2.name,async()=>{await this.options.pluginSystem.callViewHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(i2.name,e=>{e.hooks.optimizeTree.tapPromise(i2.name,async t=>{await this.options.pluginSystem.callViewHooks("build",{metadata:this.options.context.metadata,fileDependencies:e.fileDependencies})})}),e.hooks.done.tapPromise(i2.name,async e=>{await this.options.pluginSystem.callViewHooks("afterBuild",{stats:e})})}}function i4(e,t,n){if(t===n||!e.getAsset(t))return!1;e.renameAsset(t,n);let a=`${t}.map`;return e.getAsset(a)&&e.renameAsset(a,`${n}.map`),!0}function i9(e,t,n,a,o){Object.keys(t).forEach(i=>{let r=ny(i.replaceAll("\\","/"));i4(e,`${r}/template.js`,ng(a,nv(t,n,i),o))})}class i5{context;constructor(e){this.context=e}apply(e){e.hooks.thisCompilation.tap(i5.name,t=>{t.hooks.processAssets.tapPromise({name:i5.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{let e=this.context.metadata.getData(),n=nw(this.context.webMode),a=nS(this.context.pages,this.context.normalizedAppConfig.pages.entries,n),o=nS(this.context.widgets,this.context.normalizedAppConfig.widgets.entries,n),i=e.app.appId||this.context.appId;i9(t,a,e.pages,"pages",i),i9(t,o,e.widgets,"widgets"),i4(t,`${ny(nf)}/template.js`,nb(i))})})}}class i8{entry;constructor(e){this.entry=e}apply(e){let t=new e.webpack.experiments.VirtualModulesPlugin;t.apply(e),e.hooks.thisCompilation.tap(i8.name,()=>{t.writeModule(eZ,""),Object.values(this.entry).forEach(e=>{t.writeModule(e.filename,e.toString())})})}}let i6="/doubao-apps-framework.template.js",i7="/doubao-apps-api.template.js",re=(e,t)=>{let n=(e,n,a)=>({libraryName:a,url:t?`/wsd${e}`:e,background:{sectionPath:n},mainThread:{sectionPath:`${n}__main-thread`},async:!!t});return{"@byted-doubao-apps/bridge-base":n(i7,"api"),"@byted-doubao-apps/open-api":n(i7,"api"),...Object.fromEntries(Object.entries(e5).map(([t,a])=>[t,n(e?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",a])])),[`${ti}/api`]:n(i7,"api"),[`${tr}/api`]:n(i7,"api"),[ti]:n(i6,"framework"),[tr]:n(i6,"framework"),"@byted-doubao-apps/components":n(i6,"components"),[tl(ti)]:n(i6,"components"),[tl(tr)]:n(i6,"components")}},rt=h("node:url"),rn=(0,no.createRequire)(import.meta.url);class ra{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,n,a,o,i;let{appDirectory:r,command:s,metadata:h,rootPath:f}=e.context,g=e.context.environment;await this.pluginSystem.callViewHooks("modifyEnvironment",{environment:g}),e.context.setEnvironment(g);let b=await this.createEntry(),y=td(r),v=[r,eX.dirname((0,rt.fileURLToPath)(import.meta.url))],S=rn.resolve("@lynx-js/react/transform"),w=nw(e.context.webMode),_=nS(e.context.pages,e.context.normalizedAppConfig.pages.entries,w),E=new Set([...Object.keys(nS(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,w)),...Object.keys(_)]);if(e.web&&0===E.size)throw Error(s===eB.DEV?"No Web entries are available. Add page/widget entries under src/pages or src/widgets.":"No Web entries are configured. Add `web: true` to page/widget entries in src/app.config.ts.");e.web&&await n1({widgets:e.context.widgets,pages:e.context.pages,entries:b,collector:h,normalizedAppConfig:e.context.normalizedAppConfig,define:e.context.userConfig?.source?.define});let x={...{include:e.options.source?.include,exclude:e.options.source?.exclude,decorators:e.options.source?.decorators,define:{...e.options.source?.define,__MAIN_PROCESS__:JSON.stringify(!1),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__LEPUS__:JSON.stringify(!1),"process.env":"({})"}},entry:Object.fromEntries(Object.entries(b).map(([e,t])=>[e,[eZ,`${y}/components-style`,t.filename]]))},C=Object.fromEntries(Object.entries(b).filter(([e])=>E.has(e))),A=e.web&&e.context.app?nV(eX.join(r,eQ,`${nf}.js`),e.context.app,e.context.tools??{},{enableWebConsoleHook:!0}):void 0,O={...C,...A?{[nf]:A}:{}},I=new Map(Object.keys(C).map(e=>[ny(e),e])),T={...x,entry:Object.fromEntries(Object.entries(O).map(([e,t])=>[ny(e),[eZ,`${y}/components-style`,t.filename]])),define:{...x.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},P=[...tm()?[]:[F({externals:re(s===eB.DEV),globalObject:"lynx"})]],k=[function({metadata:e,resolveAppInfo:t}){return{name:"ai-manifest-plugin",setup(n){n.modifyBundlerChain((n,a)=>{let o=a?.environment?.name==="web"?np:nl;n.plugin(nd.name).use(nd,[{metadata:e,resolveAppInfo:t,shouldInjectAsset:o}])})}}}({metadata:h,resolveAppInfo:()=>e.context.resolveAppInfo()})],L=[function e(t,n,a){return{name:e.name,setup(e){e.modifyBundlerChain((o,i)=>{if(i?.environment?.name==="web")return;let r=e.useExposed(Symbol.for("LynxTemplatePlugin"));o.plugin(at.name).use(at,[r.LynxTemplatePlugin,t,n,a])})}}}(h,b,()=>e.context.resolveSigningEncryptionOptions()),function({context:e,normalizeEntryName:t}){return{name:"template-widget-entry-plugin",setup(n){n.modifyBundlerChain((n,a)=>{let o=a?.environment?.name;n.plugin("template-widget-entry-plugin").use(i3,[{markTemplateWidgetEntry:t=>{e.addTemplateWidgetEntry(t)},normalizeEntryName:e=>t?.(e,o)}])})}}}({context:e.context,normalizeEntryName:(e,t)=>"web"===t?I.get(e):e}),(t=this.pluginSystem,n=e.context,{name:"output-plugin",setup(e){let a={pluginSystem:t,context:n};e.modifyBundlerChain((e,t)=>{(t?.environment?.name!=="web"||n_(n.webMode))&&e.plugin("output-plugin").use(i0,[a])})}}),(({context:e})=>({name:"DevServerLogPlugin",setup(t){let n,a=!1,o=!1;t.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{setup({server:e}){e.middlewares.use(iK)}}})),t.onAfterDevCompile(async({stats:i})=>{if(i.hasErrors()||a)return;let{devServer:r}=t.context;if(!r)return;a=!0;let s=n_(e.webMode)?void 0:await tM({debugDriver:e.userConfig.debugDriver,skipAdbForegroundAppWatch:e.userConfig.skipAdbForegroundAppWatch});o||await iJ({context:e,port:r.port,driver:s,isSigned:e.isSignedEncryption,onCleanupReady(e){o?e():n=e}})}),t.onCloseDevServer(()=>{o=!0,n?.(),n=void 0})}}))({context:e.context}),(a=this.pluginSystem,o=e.context,{name:"view-hooks-plugin",setup(e){e.modifyBundlerChain((e,t)=>{t?.environment?.name==="web"||e.plugin("view-hooks-plugin").use(i2,[{pluginSystem:a,context:o}])})}}),(({getMainThreadAssetPath:e,getMainThreadMapAssetPath:t,engineVersion:n,metadata:a,resolveSigningEncryptionOptions:o})=>({name:"lynx:encode-worker",async setup(i){th()||i.modifyBundlerChain((i,r)=>{r?.environment?.name!=="web"&&i.plugin(ae.name).use(ae,[{getMainThreadAssetPath:e,getMainThreadMapAssetPath:t,engineVersion:n,metadata:a,resolveSigningEncryptionOptions:o}]).end()})}}))({getMainThreadAssetPath:()=>e.context.mainThreadAssetPath,getMainThreadMapAssetPath:()=>e.context.mainThreadMapAssetPath,metadata:e.context.metadata,resolveSigningEncryptionOptions:()=>e.context.resolveSigningEncryptionOptions()}),...e.rsbuildPlugins||[]],N=[{name:"web-virtual-entry-plugin",setup(e){e.modifyBundlerChain((e,{environment:t})=>{"web"===t.name&&e.plugin(i8.name).use(i8,[O])})}},(i=e.context,{name:"web-output-plugin",setup(e){e.modifyBundlerChain((e,{environment:t})=>{"web"===t.name&&e.plugin(i5.name).use(i5,[i])})}})],R=l({mode:s===eB.DEV?"development":"production",environments:e.web?{...n_(e.context.webMode)?{}:{lynx:{source:x,plugins:P}},web:{source:T,output:{distPath:{root:eX.resolve(r,"dist")},cleanDistPath:!1,filename:{assets:"[name]/web.bundle"}},plugins:[F({externals:re(s===eB.DEV,!0),globalObject:"lynx"})]}}:void 0,tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(e,t,n=eX.join(eX.dirname((0,rt.fileURLToPath)(import.meta.url)),"components-loader.js"),a=function(e,t){for(let n of e)try{return rn.resolve(n,{paths:t})}catch{}throw Error(`Cannot resolve package from candidates: ${e.join(", ")}`)}){try{return a(t===tr?["@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)(n))return n;throw e}}(v,y),options:{frameworkPackage:y}}]},plugins:[new p.BannerPlugin({banner:'"use registerWorkletInternal";',raw:!0,entryOnly:!0,test:/\.js$/})]}},source:e.web?{entry:Object.fromEntries(Object.entries(C).map(([e,t])=>[ny(e),[eZ,`${y}/components-style`,t.filename]]))}:x,server:{host:n9()},dev:{writeToDisk:"applet0930"===process.env.DEBUG,hmr:s===eB.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:"applet0930"===process.env.DEBUG,...tm()?{chunkSplit:{strategy:"split-by-experience"}}:{}},plugins:[{name:"replace-lynx-react-alias",setup(e){et({LAYERS:d,lazy:!1,rootPath:eX.dirname((0,rt.fileURLToPath)(import.meta.url))}).setup(e)}},{name:"set-server.printUrls-false",setup(e){e.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{printUrls:!1}}))}},c({compat:{componentsPkg:[],newRuntimePkg:y,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...ts]}}),{name:"pin-react-transform-path",pre:["lynx:react"],setup(e){e.modifyBundlerChain((e,{CHAIN_ID:t})=>{let n=e.module.rule(t.RULE.JS).oneOf(t.ONE_OF.JS_MAIN);for(let e of[d.BACKGROUND,d.MAIN_THREAD]){let t=n.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=nC.compilerOptionsKeys,configKeys:n=nC.configKeys,validate:a=nF,dslPluginName2PkgName:o=nH,upgradeRspeedyLink:i="https://www.npmjs.com/package/upgrade-rspeedy"}=(void 0)??{};return a(e),{name:"lynx:config",async setup(a){a.expose(Symbol.for("lynx.config"),{config:e}),a.modifyBundlerChain(r=>{let s=a.useExposed(Symbol.for("LynxTemplatePlugin"));if(!s){let e="Rspeedy and plugins";throw Object.entries(o).forEach(([t,n])=>{a.isPluginExists(t)&&(e=n)}),Error(`\
98
+ [pluginLynxConfig] No \`LynxTemplatePlugin\` exposed to ${nN("the plugin API","https://rsbuild.rs/plugins/dev/core#apiexpose")}.
99
+
100
+ Please upgrade ${e} to latest version.
101
+
102
+ See ${nN(nU().yellow("Upgrade Rspeedy"),i)} for more details.
103
+ `)}let{LynxTemplatePlugin:l}=s;r.plugin("lynx:config").use(nM,[{LynxTemplatePlugin:l,config:e,compilerOptionsKeys:t,configKeys:n}])})}}}({enableMultiTouch:!0,enableNewGesture:!0,enableCSSInlineVariables:!0,enableSimultaneousTap:!0,enableReloadLifecycle:!0}),m(),u(),...e.web?[]:P,...k,...L,...e.web?N:[]]});return await this.pluginSystem.callViewHooks("beforeBuild",{buildConfig:R}),R}}async function ro(e,t){let n=new ra(t),a=await n.createConfig({config:e}),o=await s({rspeedyConfig:a,cwd:e.context.appDirectory});return o.removePlugins(["lynx:react-alias"]),o}class ri extends nn{toString(){return this.contents.join("\n").trim()}}class rr{options;constructor(e){this.options=e}apply(e){e.hooks.make.tapPromise(rr.name,async()=>{await this.options.pluginSystem.callWorkerHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.compilation.tap(rr.name,e=>{e.hooks.optimizeTree.tapPromise(rr.name,async t=>{await this.options.pluginSystem.callWorkerHooks("build",{metadata:this.options.context.metadata,fileDependencies:e.fileDependencies})})}),e.hooks.shouldEmit.tap(rr.name,()=>!1),e.hooks.done.tapPromise(rr.name,async e=>{await this.options.pluginSystem.callWorkerHooks("afterBuild",{stats:e})}),e.hooks.thisCompilation.tap(rr.name,t=>{t.hooks.processAssets.tap({name:rr.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},()=>{let{context:e}=this.options;t.getAssets().forEach(t=>{let{name:n}=t;return n.endsWith(".js")?e.setMainThreadAssetPath(n):n.endsWith(".js.map")?e.setMainThreadMapAssetPath(n):void 0})})})}}class rs{pluginSystem;constructor(e){this.pluginSystem=e}async createEntry(){let{entry:e}=await this.pluginSystem.callWorkerHooks("modifyEntryOption",{entry:{[e7]:new ri(`.${e_.sep}${e7}.js`,"")}});return e}async createConfig({config:e}){var t,n,a;let o,i=e.context.environment;await this.pluginSystem.callWorkerHooks("modifyEnvironment",{environment:i}),e.context.setEnvironment(i);let r=await this.createEntry(),s=n_(e.context.webMode),l=(0,v.mergeRsbuildConfig)({root:e.context.appDirectory,source:{...e.options.source,entry:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{import:t.filename,layer:d.BACKGROUND}])),define:{...e.options.source?.define,__DEV__:JSON.stringify("production"!==process.env.NODE_ENV),__MAIN_PROCESS__:JSON.stringify(s||tf()),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__LEPUS__:JSON.stringify(!1),__BACKGROUND__:JSON.stringify(!0),"process.env":"({})"}},resolve:{alias:{...e.options.resolve?.alias||{},"@byted-doubao-apps/framework$":"@byted-doubao-apps/framework/worker"}},output:{minify:!1,cleanDistPath:!1,target:"web-worker",distPath:{root:e.context.rootPath,js:"base"},filename:{js:th()?"[name].js":"[name].template.js"},sourceMap:{js:"production"===process.env.NODE_ENV?"hidden-source-map":"cheap-module-source-map"},legalComments:"none",assetPrefix:"./",overrideBrowserslist:"production"===process.env.NODE_ENV?e6:e8,polyfill:"usage"},dev:{hmr:!1},tools:{htmlPlugin:!1,rspack:{watchOptions:{ignored:["**/.git"]},plugins:[new v.rspack.experiments.VirtualModulesPlugin(Object.fromEntries(Object.entries(r).map(([e,t])=>[t.filename,t.toString()]))),(t=e.context.appDirectory,o=e_.join(t,nu),{name:"worker-style-proxy-plugin",apply(e){new e.webpack.experiments.VirtualModulesPlugin({[o]:"export {};\n"}).apply(e),e.hooks.normalModuleFactory.tap("worker-style-proxy-plugin",t=>{t.hooks.beforeResolve.tap({name:"worker-style-proxy-plugin",stage:-1e3},t=>{var n;let a;return n=nm.get(e),void((a=function(e){let t=e.request;if(!t||!nc.test(t))return;let n=/^(.*?)([?#].*)?$/.exec(t),a=n?.[1]??t,o=n?.[2]??"";return e_.isAbsolute(a)?`${a}${o}`:a.startsWith(".")?`${e_.resolve(e.context??process.cwd(),a)}${o}`:t}(t))&&(n?.add(a),t.request=o))})})}}),new v.rspack.optimize.LimitChunkCountPlugin({maxChunks:1}),...s||tf()?[]:[new H]]},swc:{jsc:{target:"es2020"},env:void 0}},plugins:[(n=this.pluginSystem,a=e.context,{name:"worker-hooks-plugin",setup(e){e.modifyBundlerChain(e=>{e.plugin("worker-hooks-plugin").use(rr,[{pluginSystem:n,context:a}])})}}),{name:"expose-layers",setup(e){e.expose(Symbol.for("LAYERS"),d)}},...s||tm()?[]:[F({externals:re(e.commandType===eB.DEV),globalObject:"lynx"})]],performance:{bundleAnalyze:e.commandType===eB.ANALYZE?{}:void 0,printFileSize:"applet0930"===process.env.DEBUG}});return await this.pluginSystem.callWorkerHooks("beforeBuild",{buildConfig:l}),l}}async function rl(e,t){let n=new rs(t),a=await n.createConfig({config:e});return await (0,v.createRsbuild)({cwd:e.context.appDirectory,config:a})}async function rp(e,t){var n;let a=await rl(e,t),[o]=await a.initConfigs({action:e.commandType===eB.DEV?"dev":"build"});return await ro({...e,rsbuildPlugins:[...e.rsbuildPlugins||[],(n=e.context,{name:"worker-sub-compiler-plugin",setup(e){e.modifyBundlerChain((e,t)=>{(t?.environment?.name!=="web"||n_(n.webMode))&&e.plugin(nE.name).use(nE,[{workerConfig:o,context:n}])})}})]},t)}let rd=h("node:os"),rc=e=>{try{return to.statSync(e,{throwIfNoEntry:!1})?.isFile()}catch(e){return!1}};async function ru({internal:e,appKey:t}){try{return await aE({internal:e,path:`/developer/resource_api/apps/${encodeURIComponent(t)}/dek/public_key`})}catch(e){throw tT.error("Failed to get KEK",{error:e,appKey:t,operation:"get-kek"}),e}}async function rm(e,t,n,a){if(!(a||tc("DISABLE_SIGNING_ENCRYPTION")||tc("LEGACY_FRAMEWORK"))){if(e)return e;if("production"===process.env.NODE_ENV&&t===eB.DEPLOY){if(!n)throw Error("appId is required to get KEK");let{data:e}=await ru({internal:!1,appKey:n}),t=Number(Object.keys(e.keys)[0]);return{signing:{enabled:!1},encryption:{enabled:!0,wrap_key:e.keys[t],key_id:t,salt:""}}}}}function rh(e,t,n){if(n){let t=eX.isAbsolute(n)?n:eX.resolve(e,n);if(t3.existsSync(t))return t;tI.warn("Cannot find config file",{path:t})}for(let n of tn.map(n=>eX.resolve(e,`${t}${n}`)))if(rc(n))return n;return!1}async function rf(e){let t=(0,S.createJiti)((0,rt.fileURLToPath)(import.meta.url),{requireCache:!1,interopDefault:!0});return await t.import(e,{default:!0})}async function rg({cwd:e=process.cwd(),customConfigFile:t}){let n=rh(e,"doubao.config",t);if(!n)return{};try{return await rf(n)}catch(e){throw tI.error("Failed to load config file",{path:n}),e}}async function rb({cwd:e=process.cwd()}={}){let t=rh(eX.resolve(e,"src"),tt);if(t)try{return await rf(t)}catch(e){throw tI.error("Failed to load app config file",{path:t}),e}}async function ry(e){let t=globalThis,n=Object.prototype.hasOwnProperty.call(t,"defineAppConfig"),a=t.defineAppConfig;t.defineAppConfig=e=>e;try{return await rf(e)}finally{n?t.defineAppConfig=a:delete t.defineAppConfig}}async function rv({cwd:e=process.cwd()}={}){let t=rh(eX.resolve(e,"src"),tt);if(t)try{let e=await ry(t);return{...Array.isArray(e.pages)?{pages:e.pages}:{},...Array.isArray(e.widgets)?{widgets:e.widgets}:{}}}catch(e){throw tI.error("Failed to load Taro app config file",{path:t}),e}}let rS=h("fs/promises"),rw=async(e,t=eX.basename(e))=>{if(!t3.existsSync(e))return{};let n={};for(let a of(await rS.readdir(e))){let o=eX.resolve(e,a);if(!t3.statSync(o).isDirectory())continue;let i=eX.resolve(o,"index.tsx");t3.existsSync(i)&&(n[`${t}/${a}/index`]={folderName:`${a}/index`,renderType:N.REACT_LYNX,filename:i})}return n},r_=async(e,t=eX.basename(e))=>{if(!t3.existsSync(e))return{viewEntries:{},apiEntries:{}};let n=await rw(e,t),a={},o=eX.resolve(e,"login.ts");t3.existsSync(o)&&(a[`${t}/login`]={filename:o,folderName:e});let i=eX.resolve(e,"privacy.ts");return t3.existsSync(i)&&(a[`${t}/privacy`]={filename:i,folderName:e}),{viewEntries:n,apiEntries:a}},rE=async(e,t)=>t3.existsSync(e)?(await rS.readdir(e)).reduce((n,a)=>{let o=eX.resolve(e,a);return t3.statSync(o).isDirectory()&&t3.existsSync(eX.resolve(o,t))&&(n[a]=eX.resolve(o,t)),n},{}):{};function rx(e){return e_.resolve(e,"app.ts")}let rC=async e=>{let t=e_.resolve(e,"tools"),n=await rE(t,"index.ts"),a=rx(e);return{tools:n,app:to.existsSync(a)?a:void 0}},rA=async(e,t)=>{let n=e_.resolve(e,"pages"),a=e_.resolve(e,"widgets"),o=e_.resolve(e,"auth"),i=e_.resolve(e,"mcp-ui"),[r,s,l,p]=await Promise.all([rw(n),rw(a),r_(i),r_(o)]),d=Object.keys(p.viewEntries).length>0||Object.keys(p.apiEntries).length>0?p:l,c=t.pages,u=t.widgets,m=(t,n,a)=>{let o={...t};return n.forEach(t=>{if(o[t])return;let n=`${a}/`;if(!t.startsWith(n))throw Error(`${a} config key must start with "${n}": ${t}`);let i=t.slice(n.length),r=e_.resolve(e,a,`${i}.tsx`);if(!to.existsSync(r))throw Error(`Configured entry file does not exist for ${t}: ${r}`);o[t]={folderName:i,renderType:N.REACT_LYNX,filename:r,isVirtualFile:!1}}),o},h=m(r,c.entryNames,"pages");return{widgets:m(s,u.entryNames,"widgets"),pages:h,auth:d}};function rO(e,t,n=!1,a=!1){let o=td(t);return Object.keys(e).reduce((i,r)=>{let{filename:s}=e[r],l=a&&e[r].isLoginPage?"defineLoginPage":a?"definePage":"defineWidget",p=`${eQ}${e_.sep}${r}${e_.extname(s)}`,d=nt(e_.join(t,p,".."),s);return i[r]=new nn(p),i[r].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:d,importSpecifiers:[{propertyName:"default",name:"ViewEntry"}]},{moduleSpecifier:o,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:l,name:l},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"hookConsole",name:"hookConsole"}]}),i[r].appendContent(`
104
+ if (
105
+ typeof __DOUBAO_APPS_WEB__ === 'boolean' &&
106
+ __DOUBAO_APPS_WEB__ &&
107
+ typeof __BACKGROUND__ === 'boolean' &&
108
+ __BACKGROUND__
109
+ ) {
110
+ hookConsole();
111
+ }
112
+
113
+ const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
114
+
115
+ const View =
116
+ typeof ViewEntry === 'object' &&
117
+ ViewEntry !== null &&
118
+ '__UI__' in ViewEntry &&
119
+ ViewEntry.__UI__ === true
120
+ ? ViewEntry
121
+ : ${l}({ render: () => <ViewEntry /> });
122
+
123
+ const FC = bootstrapReactLynx(View, viewId, ${JSON.stringify(a)});
124
+
125
+ root.render(<FC />);
126
+ `),n&&i[r].appendContent(`
127
+ if (import.meta.webpackHot) {
128
+ import.meta.webpackHot.accept()
129
+ }
130
+ `),i},{})}let rI={name:"AuthPlugin",async setup(e){tc("DISABLE_GENERATE_LOGIN_CARD")||tc("LEGACY_FRAMEWORK")||(e.view.hooks.modifyEnvironment.tapPromise(rI.name,async({environment:e})=>{e.useAuth=!0}),e.view.hooks.modifyEntryOption.tapPromise({name:rI.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let n,a,o,i,r,s,l,{isDev:p,auth:d,appDirectory:c}=e.context,u={},m=Object.keys(d.viewEntries).reduce((e,t)=>(e[t]={...d.viewEntries[t],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,(n=td(c),a=`${eQ}${eX.sep}${e0}${eX.sep}${e2}.tsx`,u[o=`${e0}/${e2}`]={filename:a,renderType:N.REACT_LYNX,folderName:e2,isVirtualFile:!0,isSpecial:!0},i=new nn(a),r=eX.join(c,eX.dirname(a)),s=Object.values(d.apiEntries).find(e=>"login"===eX.parse(e.filename).name),l=Object.values(d.apiEntries).find(e=>"privacy"===eX.parse(e.filename).name),s&&i.appendImports({moduleSpecifier:nt(r,s.filename),importSpecifiers:[{propertyName:"default",name:"loginApi"}]}),l&&i.appendImports({moduleSpecifier:nt(r,l.filename),importSpecifiers:[{propertyName:"default",name:"privacyApi"}]}),i.appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:n,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"definePrivacyLoginWidget",name:"definePrivacyLoginWidget"},{propertyName:"hookConsole",name:"hookConsole"}]},{moduleSpecifier:`${n}/components`,importSpecifiers:[{propertyName:"MCPAuthCard",name:"MCPAuthCard"}]}),i.appendContent(`
131
+ if (
132
+ typeof __DOUBAO_APPS_WEB__ === 'boolean' &&
133
+ __DOUBAO_APPS_WEB__ &&
134
+ typeof __BACKGROUND__ === 'boolean' &&
135
+ __BACKGROUND__
136
+ ) {
137
+ hookConsole();
138
+ }
139
+
140
+ const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
141
+
142
+ const View = definePrivacyLoginWidget({
143
+ render() {
144
+ return (
145
+ <MCPAuthCard
146
+ ${l?"onAgreePrivacy={privacyApi.onAgreePrivacy}":""}
147
+ ${l?"onRefusePrivacy={privacyApi.onRefusePrivacy}":""}
148
+ ${s?"onLogin={loginApi.onLogin}":""}
149
+ ${s?"onRefuseLogin={loginApi.onRefuseLogin}":""}
150
+ />
151
+ );
152
+ }
153
+ });
154
+
155
+ const FC = bootstrapReactLynx(View, viewId);
156
+ root.render(<FC />);
157
+ `,p?`
158
+ if (import.meta.webpackHot) {
159
+ import.meta.webpackHot.accept()
160
+ }
161
+ `:""),{[o]:i}),rO(m,c,p,!0)),e.context.appendWidgets(u),{entry:t}}))}};(eP=eF||(eF={}))[eP.DISABLED=0]="DISABLED",eP[eP.ENABLED=1]="ENABLED";let rT="AppletDoubaoAppInfoPlugin",rP={name:rT,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:rT,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-1},async({assets:t})=>{if(e.context.command!==eB.DEV&&e.context.command!==eB.BUILD&&e.context.command!==eB.DEPLOY||!e.context.appId)return;let n=await e.context.resolveAppInfo();if(n){var a=t.getManifestAsset(e.context.manifestAssetPath);a.mergeBasicManifest({permissions:Object.fromEntries(n.permissionList.filter(e=>e.status===eF.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))}),n?.appName&&a.mergeAppletManifest({name:n.appName}),n?.iconUrl&&a.mergeAppletManifest({icons:tB(n.iconUrl)})}})}},rk={name:"ExpiredWidgetPlugin",async setup(e){e.view.hooks.modifyEntryOption.tapPromise({name:rk.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let n,a,o,i,{isDev:r,appDirectory:s}=e.context,l={};return t=Object.assign(t,(n=td(s),a=`${eQ}${eX.sep}${e0}${eX.sep}${e4}.tsx`,l[o=`${e0}/${e4}`]={filename:a,renderType:N.REACT_LYNX,folderName:e4,isVirtualFile:!0,isSpecial:!0},(i=new nn(a)).appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:n,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"defineWidget",name:"defineWidget"}]},{moduleSpecifier:`${n}/components`,importSpecifiers:[{propertyName:"UpdatedState",name:"UpdatedState"}]}),i.appendContent(`
162
+ const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
163
+
164
+ const View = defineWidget({
165
+ render() {
166
+ return (
167
+ <UpdatedState />
168
+ );
169
+ }
170
+ });
171
+
172
+ const FC = bootstrapReactLynx(View, viewId);
173
+ root.render(<FC />);
174
+ `,r?`
175
+ if (import.meta.webpackHot) {
176
+ import.meta.webpackHot.accept()
177
+ }
178
+ `:""),{[o]:i})),e.context.appendWidgets(l),{entry:t}})}},rL="LynxPlugin",rN={name:rL,async setup(e){e.view.hooks.modifyEnvironment.tapPromise(rL,async({environment:e})=>{e.useLynx=!0});let t={};e.view.hooks.modifyEntryOption.tapPromise({name:rL,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:n})=>{let{appDirectory:a,isDev:o,widgets:i,pages:r}=e.context;return t=n=Object.assign(n,rO(i,a,o),rO(r,a,o,!0)),{entry:n}}),e.view.hooks.collectMetaData.tapPromise({name:rL,stage:e.view.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:n})=>{let{normalizedAppConfig:a,userConfig:o,widgets:i,pages:r}=e.context;await n1({widgets:i,pages:r,entries:t,collector:n,normalizedAppConfig:a,define:o.source?.define})}),e.assets.hooks.beforeEmit.tapPromise({name:rL,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS},async({assets:t})=>{let{widgets:n,pages:a,app:o}=e.context.metadata.getInstance(),i=e.context.templateWidgetEntries;Object.keys(n).forEach(a=>{let o=n[a],r=`${a}/template.js`,s=t.getAsset(r);if(o&&s){let n=`${o.metadata.id}/template.js`;s.destination=n;let r=t.getManifestAsset(e.context.manifestAssetPath),l=o.toManifest(n,s.hashCode,N.LYNX);i.has(a)&&(l.titleType=D.NONE),r.appendWidget(l)}}),Object.keys(a).forEach(n=>{let i=a[n],r=`${n}/template.js`,s=t.getAsset(r);if(i&&s){let n=`${o.metadata.appId}/${i.metadata.id}/template.js`;s.destination=n,t.getManifestAsset(e.context.manifestAssetPath).appendPage(i.toManifest(n,s.hashCode,N.LYNX))}})}),e.assets.hooks.afterEmit.tapPromise(rL,async({assets:e})=>{}),e.view.hooks.afterBuild.tapPromise(rL,async({stats:e})=>{})}};async function rR(e,t,n){let{app:a,tools:o,collector:i,define:r}=n,s=o[t],l=e;(s||a===t)&&(r&&Object.keys(r).length>0&&(l=Object.keys(r).reduce((e,t)=>{let n=r[t];if("string"==typeof n)return e.replaceAll(t,n);throw Error(`Define value ${t} is not a string`)},e)),es((0,nZ.parseSync)(l,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(nG(e.callee)&&["defineTool","defineApp"].includes(e.callee.value)){let t=e.arguments[0]?.expression;if(nK(t)){for(let e of t.properties)if(nX(e)&&nG(e.key)&&"aiMeta"===e.key.value){let t=nQ(e.value);s?i.addToolMeta(s,t):i.addAppMeta({...t,appId:t.appId??t.package})}}}}}))}async function rD({tools:e,app:t,collector:n,define:a,appConfig:o}){let i={collector:n,tools:Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),app:t,define:a};Object.entries(e).forEach(([e])=>{n.addToolMeta(e,{id:e})}),t3.existsSync(t)?await Promise.all(Object.values({...e,app:t}).filter(e=>/\.(ts|tsx|jsx|js)$/i.test(e)&&t3.existsSync(e)).map(e=>rR(t3.readFileSync(e,"utf-8"),e,i))):tI.warn("App file does not exist",{path:t});let r=n.app,s=o?.appId??r.appId;if(!s)throw Error("appId is required in app config or AI metadata");n.addAppMeta({...r,name:o?.name??r.name,description:o?.description??r.description,icons:o?.icons??r.icons,keywords:o?.keywords??r.keywords,version:o?.version??r.version,appId:s})}let rM={name:"AppletMainPlugin",setup:async e=>{e.context.app&&(e.worker.hooks.modifyEntryOption.tapPromise("AppletMainPlugin",async({entry:t})=>{let{app:n,tools:a}=e.context;return delete t[e7],Object.assign(t,{app:nV(`${e.context.appDirectory}${e_.sep}${eQ}${e_.sep}app.js`,n,a)}),{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:n,appConfig:a,tools:o,userConfig:i}=e.context;await rD({appConfig:a,tools:o,app:n,collector:t,define:i.source?.define})}),e.assets.hooks.beforeEmit.tapPromise({name:"AppletMainPlugin",stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:t})=>{var n,a;let{app:o,pages:i,tools:r}=e.context.metadata.getInstance(),s=t.getAsset(e.context.mainThreadAssetPath),l=t.getManifestAsset(e.context.manifestAssetPath),{manifest:p}=l,d=[];p.applet.pages.forEach(e=>{d.push(e.digest)});let c=o.metadata.appId,u=e.context.versionTag??o.metadata.version;l.assignBasicManifest({manifestVersion:"3.0",packageName:c,appId:c,versionName:u,versionTag:u,scmVersion:process.env.BUILD_VERSION,versionCode:Date.now().toString(),runtimeVersion:"1.0",sourceType:e.context.internal?1:2}),tf()&&delete l.manifest.runtimeVersion;let m=e.context.mainThreadAssetPath,h=e.context.normalizedAppConfig.pages.entryNames[0],f=h?i[h]?.metadata.id:void 0,g=o.toManifest({toolsMetadata:r,hashCode:s?.hashCode??(n=s?.hashCode??p?.applet?.digest,a=d.join(""),iY.createHash("sha256").update(n+a).digest("hex").substring(0,8)),appRuntimeEntry:m,appRuntimeType:e.context.environment.useLynx?"lynx":"js"});l.mergeAppletManifest(g),f&&l.mergeAppletManifest({appletEntry:f})}),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})=>{}))}},r$={name:"AppletMainEntryCheckPlugin",setup:async e=>{let{srcDirectory:t}=e.context,n=rx(t);if(!t3.existsSync(n))throw Error("ENOENT: no such file or directory")}},rB={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:n}=await e.context.resolveSigningEncryptionOptions()||{};if(n?.enabled){let{signData:a}=await import("node:module").then(function(e){return h.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),o=t.getManifestAsset(e.context.manifestAssetPath),{manifest:i}=o,{buffer:r,status:s,error_msg:l}=await a(Buffer.from(o.content),ne(n,{extra_config:{app_id:i.appId,bundle_id:""},output_mode:"sign_block"}));if(0!==s)throw Error(l);let p=new iX(e3,r);p.destination=e3,t.addAsset(e3,p)}})}},rj="AppletWebManifestPlugin";function rU(e,t,n,a){return Object.keys(t).map(o=>{var i;let{id:r,...s}=n[o]??{},l=r??nv(t,n,o),p={entry:ng(e,l,a)},d=(i=t[o],!!(i?.isVirtualFile||i?.isSpecial));return{id:l,entryName:o,web:p,debugHidden:d,manifest:{...s,..."pages"===e?{id:l,path:s.path??`/${o}`}:{widgetId:l},digest:"",entry:"",renderType:N.LYNX,web:p,...d?{debugHidden:!0}:{}}}})}let rW={name:rj,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:rj,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-2},async({assets:t})=>{if("off"===e.context.webMode)return;let n=e.context.metadata.getData(),a=n.app.appId||e.context.appId,o=nw(e.context.webMode),i=nS(e.context.pages,e.context.normalizedAppConfig.pages.entries,o),r=nS(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,o),s=rU("pages",i,n.pages,a),l=rU("widgets",r,n.widgets);if(0===s.length&&0===l.length)return;let p=t.getManifestAsset(e.context.manifestAssetPath),d=new Map(s.map(e=>[e.id,e])),c=new Set(p.manifest.applet.pages?.map(e=>e.id));for(let e of(p.manifest.applet.pages?.forEach(e=>{let t=d.get(e.id);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),s))c.has(e.id)||p.appendPage(e.manifest);let u=new Map(l.map(e=>[e.id,e])),m=new Set(p.manifest.widgets?.map(e=>e.widgetId));for(let t of(p.manifest.widgets?.forEach(e=>{let t=u.get(e.widgetId);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),l))if(!m.has(t.id)){let n=t.manifest;e.context.templateWidgetEntries.has(t.entryName)&&(n.titleType=D.NONE),p.appendWidget(n)}e.context.app&&(p.manifest.applet.web={appRuntimeEntry:nb(a)})})}};function rF(e=((e=process.cwd())=>tp(e)===ti)()){return e?"sso":"sms"}async function rH(e={},t={}){if(e.cookie)return e.cookie;let{ensureLoginCookie:n}=await import("./@byted-doubao-apps/login~1.js");return await n({route:rF(t.internal),browser:e.loginBrowser,browserPath:e.loginBrowserPath,force:t.force})}async function rV(e,t){if(e.cookie)return e.cookie;let{getCachedLoginCookie:n}=await import("./@byted-doubao-apps/login~1.js");return await n({route:rF(t)})}function rG(e,t){let n;if(!e)return{entryNames:[],entries:{}};if(Array.isArray(e))n=e;else if("object"==typeof e)t&&tI.warn(`${t} config object map is deprecated. Use an array of strings or { entry, ...metadata } objects instead.`),n=Object.entries(e).map(([e,t])=>{let n;return{...t,entry:(n=e.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"")).endsWith("/index")?n:`${n}/index`}});else throw Error("Entry config must be an array or object map.");let a=[],o={},i=new Set,r=[],s=new Set;return n.forEach(e=>{let t,n;if("string"==typeof e)t=e,n={};else{let{entry:a,...o}=e;if(!a)throw Error('Entry config object must include "entry".');t=a,n=o}i.has(t)?s.has(t)||(r.push(t),s.add(t)):(a.push(t),i.add(t)),o[t]=n}),t&&r.length>0&&tI.warn(`${t} config contains duplicate entries: ${r.join(", ")}. Entries are deduplicated, and the last metadata config takes effect.`),{entryNames:a,entries:o}}class rq{constructor(){this.deploy={},this._isInitialized=!1,this._environment={useLynx:!1,useAuth:!1},this._srcDirectory="",this._virtualEntryDir="",this._appDirectory=process.cwd(),this._rootPath="",this._mainThreadAssetPath="",this._mainThreadMapAssetPath="",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:n,srcDirectory:a="",virtualEntryDir:o="",appDirectory:i=process.cwd(),rootPath:r="",manifestPath:s="",pages:l={},widgets:p={},auth:d,mcpUI:c,app:u="",tools:m={},environment:h={useLynx:!1,useAuth:!1},viewEntriesByType:f={},loginCookieResolver:g,cachedLoginCookieResolver:b}){this._command=e,this._metadata=t,this._versionTag=n,this._srcDirectory=a,this._virtualEntryDir=o,this._appDirectory=i,this._rootPath=r,this._manifestPath=s,this._pages={...l},this._widgets={...p};let y=d??c??{viewEntries:{},apiEntries:{}};this._auth={viewEntries:{...y.viewEntries},apiEntries:{...y.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=b,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===eB.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 e1}get mainThreadAssetPath(){return this._mainThreadAssetPath}get mainThreadMapAssetPath(){return this._mainThreadMapAssetPath}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}}}setMainThreadAssetPath(e){this._mainThreadAssetPath=e}setMainThreadMapAssetPath(e){this._mainThreadMapAssetPath=e}setManifest(e){this._manifest=e}setAuthApi(e){this._auth={viewEntries:{...e.viewEntries},apiEntries:{...e.apiEntries}}}setMcpUIApi(e){this.setAuthApi(e)}get versionTag(){return this.assertInitialized("versionTag"),this._versionTag}}function rz(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)}}async function rJ({internal:e,domainId:t,appLimit:n,appOffset:a,keyWord:o,appKey:i,cookie:r}){return await aE({internal:e,domainId:t,path:"/app_developer/api/apps",query:{app_limit:n,app_offset:a,key_word:o,app_key:i},method:"GET",headers:r?{Cookie:r}:void 0})}async function rK({source:e,internal:t,domainId:n,appLimit:a,appOffset:o,releaseStatus:i,keyWord:r,appKey:s,cookie:l}){return await aE({internal:t,domainId:n,path:"/developer/api/apps",query:{source:e,app_limit:a,app_offset:o,release_status:i,key_word:r,app_key:s},method:"GET",headers:l?{Cookie:l}:void 0})}async function rY({appKey:e,source:t,internal:n,domainId:a,releaseStatus:o,limit:i,offset:r,status:s,keyWord:l,versionTag:p,cookie:d}){return await aE({internal:n,domainId:a,path:`/developer/api/apps/${encodeURIComponent(e)}/version`,query:{source:t,release_status:o,limit:i,offset:r,status:s,key_word:l,version_tag:p},method:"GET",headers:d?{Cookie:d}:void 0})}async function rX({appKey:e,versionTag:t,internal:n,domainId:a,pageSize:o,pageNum:i,cookie:r}){return await aE({internal:n,domainId:a,path:`/developer/api/apps/${encodeURIComponent(e)}/permission/versions/${encodeURIComponent(t)}/permission_list`,query:{page_size:o,page_num:i},method:"GET",headers:r?{Cookie:r}:void 0})}function rQ(e){return e.is_latest||e.is_current}function rZ(e){return Date.parse(e.updated_at??e.created_at??e.online_at??"")}function r0(e){return Number(e.version_code??e.qr_data?.artifact_version_code)}function r1(e){return e.version_tag}function r3(e,t){"applet0930"===process.env.DEBUG&&tI.info(e,t)}async function r2({appKey:e,internal:t=!1,cookie:n,source:a=eq.REQUEST_SOURCE_IDE}){r3("[app-info] 开始获取应用信息",{appKey:e,internal:t,session:n?"present":"absent"});let o=await rJ({internal:t,appLimit:1,appOffset:0,appKey:e,cookie:n}).then(({data:t,log_id:n})=>{let a=t?.app_list||[],o=a.find(t=>t.app_key===e);return r3("[app-info] MGetApps 请求完成",{appKey:e,appCount:a.length,exactMatch:!!o,logId:n}),o||a[0]}).catch(t=>{if(r3("[app-info] MGetApps 请求失败",{appKey:e,reason:rz(t)}),ao(t))throw t}),i=o&&o.name&&o.icon_url?void 0:await rK({source:a,internal:t,appLimit:1,appOffset:0,appKey:e,cookie:n}).then(({data:t,log_id:n})=>{let a=t?.org_list?.flatMap(e=>e.app_list)||[],o=a.find(t=>t.app_key===e),i=o||a[0];return r3("[app-info] MGetAppsDeprecated 请求完成",{appKey:e,appCount:a.length,exactMatch:!!o,logId:n}),i?.app_meta}).catch(t=>{r3("[app-info] MGetAppsDeprecated 请求失败",{appKey:e,reason:rz(t)})});if(!o&&!i)throw r3("[app-info] 应用信息查询结束,未找到可用结果",{appKey:e}),Error(`未找到应用 ${e}`);let r=o?.current_version_tag&&(o.icon_url||i?.icon_url)?void 0:await rY({appKey:e,source:a,internal:t,cookie:n}).then(({data:t,log_id:n})=>{let a=Array.isArray(t?.version_list)?t.version_list:[];if(r3("[app-info] MGetAppVersions 请求完成",{appKey:e,versionCount:a.length,logId:n}),0===a.length)return;let o=a.find(rQ);return o||a.reduce((e,t)=>{let n,a;return!e||(n=rZ(t),a=rZ(e),(Number.isNaN(n)&&Number.isNaN(a)?r0(t)-r0(e):(Number.isNaN(n)?-1/0:n)-(Number.isNaN(a)?-1/0:a))>0)?t:e},void 0)}).catch(t=>{r3("[app-info] MGetAppVersions 请求失败",{appKey:e,reason:rz(t)})}),s=o?.current_version_tag||(r?r1(r):""),l=o?.icon_url||(r?r.icon_url:void 0)||i?.icon_url,p=o?.name||i?.name,d=r&&r1(r)===s?r:o?{version_tag:o.current_version_tag,icon_url:o.icon_url,updated_at:o.updated_at,online_at:o.online_at,offline_at:o.offline_at}:{version_tag:s,icon_url:l};if(!s||!n)return{appKey:e,appName:p,versionTag:s,iconUrl:l,permissionList:[],permissionTotal:0,version:d};let c=await rX({appKey:e,versionTag:s,pageSize:1e3,pageNum:1,internal:t,cookie:n}).then(t=>(r3("[app-info] FetchAppPermissionList 请求完成",{appKey:e,versionTag:s,permissionTotal:t.data?.total||0,logId:t.log_id}),t)).catch(t=>{throw r3("[app-info] FetchAppPermissionList 请求失败",{appKey:e,versionTag:s,reason:rz(t)}),t});return{appKey:e,appName:p,versionTag:s,iconUrl:l,permissionList:c.data?.permission_list||[],permissionTotal:c.data?.total||0,version:d}}function r4(){return function({fetch:e,getCacheKey:t,ttl:n,timeout:a,now:o=Date.now}){let i=new Map;return function(...r){var s,l;let p,d="string"==typeof(s=t(...r))?s:JSON.stringify(s),c=o(),u=i.get(d);if(u&&u.expiresAt>c)return u.promise;let m=(l=e(...r),void 0===a?l:Promise.race([l,new Promise((e,t)=>{p=setTimeout(()=>{t(Error(`Request timed out after ${a}ms`))},a)})]).finally(()=>{p&&clearTimeout(p)})).catch(e=>{throw i.get(d)?.promise===m&&i.delete(d),e});return i.set(d,{expiresAt:c+n,promise:m}),m}}({fetch:r2,getCacheKey:({appKey:e,internal:t,cookie:n})=>[e,t,n],ttl:6e4,timeout:1e4})}(ek=eH||(eH={}))[ek.APP_TYPE_MINI_APP=0]="APP_TYPE_MINI_APP",ek[ek.APP_TYPE_NATIVE=1]="APP_TYPE_NATIVE",(eL=eV||(eV={}))[eL.DRAFT=0]="DRAFT",eL[eL.UNDER_REVIEW=1]="UNDER_REVIEW",eL[eL.APPROVED=2]="APPROVED",eL[eL.REJECTED=3]="REJECTED",eL[eL.WITHDRAWN=4]="WITHDRAWN",eL[eL.PUBLISHING=5]="PUBLISHING",eL[eL.PUBLISHED=6]="PUBLISHED",eL[eL.ARCHIVED=7]="ARCHIVED",eL[eL.DELETED=8]="DELETED",(eN=eG||(eG={}))[eN.DRAFT=0]="DRAFT",eN[eN.PUBLISHED=1]="PUBLISHED",eN[eN.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 r9 extends rq{devServerInteractive=!0;webMode="off";webDebuggerLaunchOptions;_userConfig={};_env={};_appConfig={};_normalizedAppConfig={pages:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}};_signingEncryptionOptions;_rawSigningEncryptionOptions;_signingEncryptionOptionsPromise;_disableSigningEncryption=!1;_dek=Buffer.from("");_internal=!1;_fetchCachedAppInfo=r4();_skipAppInfoFetch=!1;_hasWarnedAppInfoFetchFailure=!1;_templateWidgetEntries=new Set;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}]))},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 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(){var e;this.assertInitialized("resolveAppInfo");let t=this.appId;if(!aa(t))return;let n="string"==typeof(e=this._appConfig.icons)?e.length>0?e:void 0:e?.["3x"]||e?.["2x"]||e?.["1x"],a={appKey:t,versionTag:this.versionTag??"",permissionList:[],permissionTotal:0,version:{},...this._appConfig.name?{appName:this._appConfig.name}:{},...n?{iconUrl:n}:{}};if(this._skipAppInfoFetch)return a;let o=await this.getCachedLoginCookie().catch(()=>void 0);try{return Object.assign(a,await this._fetchCachedAppInfo({appKey:t,cookie:o,internal:this.internal})),a.appName||=this._appConfig.name,a.iconUrl||=n,a}catch(e){if(this.command!==eB.DEV&&this.command!==eB.BUILD)throw e;if(ao(e))return a;return this._hasWarnedAppInfoFetchFailure||(this._hasWarnedAppInfoFetchFailure=!0,tI.warn("从平台获取 Doubao 应用信息失败,将使用本地 `app.config.ts` 配置的数据",{reason:rz(e)})),a}}async bootstrap({srcDirectory:e,appDirectory:t,rootPath:n,userConfig:a,appConfig:o={},normalizedAppConfig:i={pages:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}},command:r,metadata:s,signingEncryptionOptions:l,disableSigningEncryption:p,appId:d,versionTag:c,pages:u,widgets:m,auth:h,app:f,tools:g,internal:b,skipAppInfoFetch:y,devServerInteractive:v=!0,env:S={},loginCookieResolver:w,cachedLoginCookieResolver:_}){await super.bootstrap({srcDirectory:e,appDirectory:t,virtualEntryDir:e_.resolve(t,eQ),rootPath:n,manifestPath:e_.resolve(`${n}/${e1}`),command:r,metadata:s,versionTag:c,pages:u,widgets:m,auth:h,app:f,tools:g,loginCookieResolver:w,cachedLoginCookieResolver:_});let{icons:E,...x}=o??{};this._userConfig=a,this.devServerInteractive=v,this._env={...S},this._appConfig={...x,...void 0!==d?{appId:d}:{},...void 0!==E?{icons:tB(E)}:{}},this._normalizedAppConfig=i,this._internal=b??((e=process.cwd())=>tp(e)===ti)(t),this._skipAppInfoFetch=!!y,this._hasWarnedAppInfoFetchFailure=!1,this._templateWidgetEntries=new Set,this._rawSigningEncryptionOptions=l,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._disableSigningEncryption=!!p,this._appId=d??o?.appId,this._dek=Buffer.from(""),this._fetchCachedAppInfo=r4()}async resolveSigningEncryptionOptionsOnce(){let e=this._appId??this.metadata.appId;if(this._signingEncryptionOptions=await rm(this._rawSigningEncryptionOptions,this.command,e,this._disableSigningEncryption),this._signingEncryptionOptions?.encryption.enabled){let{generateDEK:e}=await import("node:module").then(function(e){return h.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)});this._dek=e(),"applet0930"===process.env.DEBUG&&console.log("DEK base64:",Buffer.from(this.dek.buffer,this.dek.byteOffset,this.dek.byteLength).toString("base64"))}return this.signingEncryptionOptions}}async function r5({appId:e,versionTag:t,versionCode:n,packagePath:a,internal:o,domainId:i,cookie:r,token:s,needAuth:l=!0}){let p=new FormData,d=new Blob([new Uint8Array(to.readFileSync(a))],{type:"application/zip"});p.append("applet_file",d,"doubao_app.zip"),p.append("applet_version_code",n.toString());let c=`/developer/${l?"resource_api":"resource_internal_api"}/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/package/upload_applet`;return await aE({internal:o,domainId:s?"sms-external":i,path:c,method:"POST",body:p,headers:{...r?{Cookie:r}:{},...s?{"X-Developer-Open-Build-Token":s}:{}},auth:l&&!s})}async function r8({versionTag:e,appKey:t,manifest:n,rootPath:a,internal:o,needAuth:i=!0,cookie:r,token:s}){process.env.NODE_ENV="production";let{appId:l,packageName:p,versionCode:d}=n,c=function(e,t){let n=e||t.versionTag||t.versionName;if(!n)throw Error("Doubao Apps Platform deploy requires versionTag in params or app metadata.");return n}(e,n),{packageResource:u}=await t9({channelName:"doubao_app",manifest:n,rootPath:a});if(!u)throw Error("Failed to archive package");let m=await r5({appId:t||l||p,versionTag:c,versionCode:d,packagePath:u.resource,internal:o,needAuth:i,cookie:r,token:s});return console.log("Deploy success:",m),m}class r6{pluginSystem;rootPath="dist";context;appDirectory;_userConfig;_appConfig;_appConfigLoaded=!1;_env={};constructor(e=process.cwd()){this.appDirectory=e}async prepare(e,t={},n){Date.now();let a=await this.getUserConfig(t),o={...await this.getAppConfig(),...t.appName?{name:t.appName}:{},...t.appIcon?{icons:tB(t.appIcon)}:{}},i={pages:rG(o?.pages,"pages"),widgets:rG(o?.widgets,"widgets")},r=Object.values(i.pages.entries).some(e=>!0===e.web)||Object.values(i.widgets.entries).some(e=>!0===e.web),s=e===eB.DEV?!0===t.web?"web-only-all":"mixed-all":e===eB.BUILD?!0===t.web?"web-only-configured":"off":!0===t.web?"web-only-configured":r?"mixed":"off",l=function(e,t){if(e)return!0===e?{mcpEndpoint:tg({env:t})}:{...e,mcpEndpoint:tg({env:t,mcpEndpoint:e.mcpEndpoint})}}(t.openWebDebugger,this._env);this.rootPath="applet0930"===process.env.DEBUG?eX.resolve(this.appDirectory,"dist"):function({appKey:e,appDirectory:t=process.cwd()}={}){let n=e_.basename(e_.resolve(t))||"temp";return`${rd.tmpdir()}/doubao_apps_sdk_template/${e||n}`}({appDirectory:this.appDirectory}),to.existsSync(eX.resolve(this.rootPath))&&to.rmSync(eX.resolve(this.rootPath),{recursive:!0,force:!0}),this.context=new r9;let p=eX.resolve(this.appDirectory,"src"),{pages:d,widgets:c,auth:u,app:m,tools:h}=await this.analyzeConvention(p,i),f=new tq,g=((e=process.cwd())=>tp(e)===ti)(this.appDirectory);await this.context.bootstrap({srcDirectory:p,appDirectory:this.appDirectory,rootPath:this.rootPath,userConfig:a,env:this._env,appConfig:o,normalizedAppConfig:i,command:e,metadata:f,signingEncryptionOptions:t.signingEncryptionOptions,skipAppInfoFetch:!!t.token,appId:t.appId,versionTag:t.versionTag,pages:d,widgets:c,auth:u,app:m,tools:h,internal:g,devServerInteractive:t.interactive,loginCookieResolver:()=>rH(t,{internal:g}),cachedLoginCookieResolver:()=>rV(t,g)}),this.context.webMode=s,this.context.webDebuggerLaunchOptions=l,this.pluginSystem=new t1(this.context,[rM,rN,r$,rI,rW,rP,rB,rk,...a.experiments?.taro?[function({name:e,appId:t,icons:n,widgets:a}){return{name:ni,setup:o=>{let i=(0,no.createRequire)(import.meta.url);o.view.hooks.modifyEntryOption.tapPromise({name:ni,stage:o.view.MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY},async({entry:e})=>{let{appDirectory:t,isDev:n,pages:a,widgets:i}=o.context;return{entry:e=Object.assign(e,na(a,t,!1,n),na(i,t,!0,n))}}),o.view.hooks.beforeBuild.tapPromise({name:ni,stage:o.view.BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG},async({buildConfig:e})=>{let{appDirectory:t}=o.context;ne(e,{resolve:{alias:{"@tarojs/components":i.resolve("@doubao-dev/taro-runtime/components",{paths:[t]}),"@tarojs/taro":(0,eX.dirname)(i.resolve("@doubao-dev/taro-runtime/package.json",{paths:[t]}))}}})}),o.worker.hooks.modifyEntryOption.tapPromise({name:ni,stage:-1},async()=>{let{appDirectory:n,isDev:a}=o.context,i={},{app:r}=o.context;return r&&(i.app=function(e,t,n,a,o=!1){var i;let r=`${eQ}${e_.sep}app.js`,s=(i=nt(e_.dirname(r),e)).startsWith(".")?i:`./${i}`,l=td(t);return new nn(r,`
179
+ import { Applet } from "${l}";
180
+ import { defineApp } from '${l}';
181
+ import { APP_ID, getLifecycle } from '@doubao-dev/taro-runtime/internal';
182
+ import App from '${s}';
183
+
184
+ const lifecycle = getLifecycle(APP_ID);
185
+
186
+ if (typeof App === 'function') {
187
+ App({ children: null });
188
+ }
189
+
190
+ const app = defineApp({
191
+ aiMeta: { name: '${n}', appId: '${a}', description: '${n}' },
192
+ onLaunch() {
193
+ lifecycle.onLaunch.forEach((handler) => handler());
194
+ },
195
+ onForeground() {
196
+ lifecycle.onForeground.forEach((handler) => handler());
197
+ },
198
+ onBackground() {
199
+ lifecycle.onBackground.forEach((handler) => handler());
200
+ },
201
+ onPageOpened(params) {
202
+ lifecycle.onPageOpened.forEach((handler) => handler(params));
203
+ },
204
+ onDestroy() {
205
+ lifecycle.onDestroy.forEach((handler) => handler());
206
+ },
207
+ onError(error) {
208
+ lifecycle.onError.forEach((handler) => handler(error));
209
+ }
210
+ });
211
+
212
+ new Applet(app, []).bootstrap();
213
+ ${o?`
214
+ if (import.meta.webpackHot) {
215
+ import.meta.webpackHot.accept()
216
+ }
217
+ `:""}
218
+ `)}(r,n,e,t,a)),{entry:i}}),o.worker.hooks.beforeBuild.tapPromise({name:ni,stage:o.worker.BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG},async({buildConfig:e})=>{let{appDirectory:t}=o.context;ne(e,{resolve:{alias:{"@tarojs/taro":i.resolve("@doubao-dev/taro-runtime/app",{paths:[t]})}}})}),o.worker.hooks.collectMetaData.tapPromise(ni,async({collector:a})=>{a.addAppMeta({name:e,appId:t,icons:n})}),o.view.hooks.collectMetaData.tapPromise({name:ni,stage:o.view.COLLECT_METADATA_STAGE_OPTIMIZE},async({collector:e})=>{let{pages:t,widgets:n}=o.context;Object.entries(t).forEach(([t,n])=>{let{folderName:a}=n;e.addPageMeta(t,{id:t6(t,a),path:t7(t)})}),Object.entries(n).forEach(([t,n])=>{let o,{folderName:i}=n;e.addWidgetMeta(t,(o=t6(t,i),{...a?.[i]??a?.[t]??a?.[o]??{},id:o}))})})}}}(a.experiments.taro)]:[],...a.plugins||[]]),await this.pluginSystem.bootstrap();let b=await rp({options:a,commandType:e,context:this.context,web:"off"!==s,rsbuildPlugins:n},this.pluginSystem);return{userConfig:a,builder:b}}async dev(e){let{builder:t}=await this.prepare(eB.DEV,e,e.rsbuildPlugins),n=await t.startDevServer(),a=n5(n.port),o=this.context.webDebuggerLaunchOptions,i=o?await iq({appDirectory:this.appDirectory,artifactOrigin:a,env:{...this.context.env,...o.env??{}},mcpEndpoint:o.mcpEndpoint,mcpHeaders:o.mcpHeaders,openBrowser:n_(this.context.webMode)?()=>void 0:o.openBrowser,simulatorBusinessTemplatesPath:o.simulatorBusinessTemplatesPath,simulatorManifestPath:o.simulatorManifestPath,simulatorSkillPath:o.simulatorSkillPath,simulatorTargetOrigin:o.simulatorTargetOrigin}):void 0,r=async()=>{tN.info("Shutting down..."),await i?.close(),await n.server.close(),tN.info("dev server closed")};return{host:a,...i?{webDebugger:i}:{},closeServer:r}}async build(e){let{builder:t}=await this.prepare(eB.BUILD,e,e.rsbuildPlugins);try{await t.build()}finally{if(e.skipCleanupRootPath||"applet0930"===process.env.DEBUG||"rspeedy"===process.env.DEBUG){if(e.archive&&e.channel){let{channel:t}=e;await t9({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(eB.ANALYZE,e);await t.build()}async perf(e){let{builder:t}=await this.prepare(eB.PERF,e);await t.build()}async deploy(e){let{builder:t}=await this.prepare(eB.DEPLOY,e),n=e.deployType||t8.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(n!==t8.NORMAL)return void tL.error("Please use deploy plugin in doubao.config.ts");let a=e.token?void 0:await this.context.getLoginCookie();if(!e.token&&!a)throw Error("Doubao Apps Platform 部署需要登录,请运行 `doubao login` 后重试。");return await t.build(),await r8({...e.versionTag?{versionTag:e.versionTag}:{},...e.appId?{appKey:e.appId}:{},manifest:this.context.manifest,rootPath:this.rootPath,internal:this.context.internal,needAuth:!0,...a?{cookie:a}:{},...e.token?{token:e.token}:{}})}(e.build||n===t8.NORMAL)&&await t.build();try{await this.pluginSystem.callDeployHooks("deploy",{deployType:n})}finally{await this.pluginSystem.callDeployHooks("afterDeploy",{})}}async run(e,t){switch(e){case tj.DEV:return await this.dev(t);case tj.BUILD:return await this.build(t);case tj.ANALYZE:return await this.analyze(t);case tj.PERF:return await this.perf(t);case tj.DEPLOY:return await this.deploy(t)}}async getUserConfig(e){if(!this._userConfig){let t=(0,v.loadEnv)({cwd:this.appDirectory,mode:e.envMode}),n=await rg({cwd:this.appDirectory,customConfigFile:e.config});this._env=t.parsed,n.source||={},n.source.define={...t.publicVars,...n.source.define},e.debugDriver&&(n.debugDriver=e.debugDriver),void 0!==e.skipAdbForegroundAppWatch&&(n.skipAdbForegroundAppWatch=e.skipAdbForegroundAppWatch),this._userConfig=n}return this._userConfig}async getAppConfig(){if(!this._appConfigLoaded){let e=await this.getUserConfig({});if(e.experiments?.taro)return this._appConfig=await rv({cwd:this.appDirectory}),this._appConfigLoaded=!0,this._appConfig;this._appConfig=await rb({cwd:this.appDirectory}),this._appConfigLoaded=!0}return this._appConfig}async analyzeConvention(e,t){let{pages:n,widgets:a,auth:o}=await rA(e,t),{app:i,tools:r}=await rC(e);return{pages:n,widgets:a,auth:o,app:i,tools:r}}}async function r7({appKey:e,versionTag:t,cloudBuildSource:n,runner:a,config:o,variables:i,properties:r,internal:s,domainId:l,cookie:p}){return await aE({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:n,runner:a,config:o,variables:i,properties:r}),headers:{"Content-Type":"application/json",...p?{Cookie:p}:{}}})}async function se({appKey:e,jobId:t,reason:n,internal:a,domainId:o,cookie:i}){return await aE({internal:a,domainId:o,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}/cancel`,method:"POST",body:JSON.stringify({reason:n}),headers:{"Content-Type":"application/json",...i?{Cookie:i}:{}}})}async function st({appKey:e,jobId:t,internal:n,domainId:a,cookie:o}){return await aE({internal:n,domainId:a,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}`,method:"GET",headers:o?{Cookie:o}:void 0})}async function sn({appKey:e,jobId:t,start:n,end:a,internal:o,domainId:i,cookie:r}){return await aE({internal:o,domainId:i,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}/logs`,query:{start:n,end:a},method:"GET",headers:r?{Cookie:r}:void 0})}async function sa({appKey:e,filename:t,sha256:n,category:a,internal:o,domainId:i,cookie:r,signal:s}){return await aE({internal:o,domainId:i,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/file_upload/start`,method:"POST",body:JSON.stringify({filename:t,sha256:n,category:a}),headers:{"Content-Type":"application/json",...r?{Cookie:r}:{}},signal:s})}async function so({appKey:e,uploadToken:t,size:n,internal:a,domainId:o,cookie:i,signal:r}){return await aE({internal:a,domainId:o,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/file_upload/finish`,method:"POST",body:JSON.stringify({upload_token:t,size:n}),headers:{"Content-Type":"application/json",...i?{Cookie:i}:{}},signal:r})}(eD=ez||(ez={}))[eD.WAITING=0]="WAITING",eD[eD.QUEUED=1]="QUEUED",eD[eD.RUNNING=2]="RUNNING",eD[eD.PENDING=3]="PENDING",eD[eD.SUCCESS=4]="SUCCESS",eD[eD.FAIL=5]="FAIL",eD[eD.CANCELED=6]="CANCELED",eD[eD.TIMEOUT=7]="TIMEOUT",eD[eD.UNKNOWN=8]="UNKNOWN";let si=h("node:crypto");async function sr({appId:e,category:t,filePath:n,filename:a=e_.basename(n),...o}){let i=new Uint8Array(to.readFileSync(n)),r=(0,si.createHash)("sha256").update(i).digest("hex"),s=(await sa({appKey:e,filename:a,sha256:r,category:t,...o})).data;if(!s?.upload_url||!s.upload_token)throw Error("File upload session is incomplete");await ss({uploadUrl:s.upload_url,body:new Blob([i]),headers:s.upload_headers||{},signal:o.signal});let l=await so({appKey:e,uploadToken:s.upload_token,size:i.byteLength,...o});if(!l.data?.stored_file_id)throw Error("File upload finish response did not return stored_file_id");return l.data}async function ss({uploadUrl:e,body:t,headers:n,signal:a}){let o=await aw(e,{method:"PUT",body:t,headers:n,signal:a}),i=o.headers.get("x-tt-logid")||"";if(!o.ok){let e=await o.text();throw Error([`File upload failed with HTTP ${o.status}`,e?`message: ${e}`:"",i?`log_id: ${i}`:""].filter(Boolean).join(", "))}}(eM=eJ||(eJ={}))[eM.UNKNOWN=0]="UNKNOWN",eM[eM.SOURCE=1]="SOURCE",eM[eM.ARTIFACT=2]="ARTIFACT";let sl=h("../../../node_modules/.pnpm/ora@5.4.1/node_modules/ora/index.js"),sp=new Set([ez.SUCCESS,ez.FAIL,ez.CANCELED,ez.TIMEOUT]);class sd{options;cwd;appDir;internal;env;secretEnv;appInfo;constructor(e,t){this.options=e,this.cwd=t,this.appDir=e_.resolve(e.appDir||t),(0,v.loadEnv)({cwd:this.appDir,mode:e.envMode}),this.internal=((e=process.cwd())=>tp(e)===ti)(this.appDir)}async start({versionTag:e,logs:t,runner:n,config:a,variables:o,properties:i}={}){this.resolveEnv(),this.resolveSecretEnv();let r=await this.upload();if(!r)throw Error("Cloud upload did not return stored_file_id");let s=await this.build({sourceRef:r,versionTag:e,runner:n,config:a,variables:o,properties:i});return t&&await this.waitForBuildJob({jobId:s}),s}async package({outputDir:e}={}){let t={appDir:this.appDir,internal:this.internal,outputDir:e?e_.resolve(this.cwd,e):void 0},n=await this.runWithSpinner("Preparing cloud build source...",e=>P({...t,onProgress:e}));if(this.logSourceDiagnostics(n),tk.success("Cloud build source archive created",{archivePath:n.archivePath}),n.blockers.length>0)throw Error(n.blockers.join("\n"));return n.archivePath}async upload({packOnly:e,outputDir:t}={}){if(e)return void await this.package({outputDir:t});let n={appDir:this.appDir,internal:this.internal},a=await this.resolveAppId("upload"),o=await this.resolveCookie(),i=await this.runWithSpinner("Preparing cloud build source...",e=>P({...n,onProgress:e}));if(this.logSourceDiagnostics(i),i.blockers.length>0)throw Error(i.blockers.join("\n"));let r=(await this.runWithSpinner("Uploading cloud build source...",()=>sr({appId:a,category:eJ.SOURCE,filePath:i.archivePath,internal:this.internal,cookie:o}))).stored_file_id;if(!r)throw Error("Cloud build source upload did not return stored_file_id");return tk.success("Cloud build source uploaded",{storedFileId:r}),r}async build({sourceRef:e,versionTag:t,runner:n,config:a,variables:o,properties:i}={}){let r;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{r=JSON.parse(to.readFileSync(e_.resolve(this.appDir,"package.json"),"utf-8")).version}catch{r=void 0}let p=t||l.version||r;if(!p)throw Error("Cloud build requires --version-tag or version in src/app.config.ts/package.json.");let d=await this.resolveCookie(),c=(await this.runWithSpinner("Creating cloud build job...",()=>r7({appKey:s,versionTag:p,cloudBuildSource:{type:"stored_file",ref:e},runner:n,config:a,variables:this.resolveBuildVariables(o),properties:i,internal:this.internal,cookie:d}))).data;if(!c?.job_id)throw Error("Cloud build create_job response did not return job_id");let u=ez[c.status]||String(c.status);return tk.success("Cloud build job created",{jobId:c.job_id}),tk.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 n=await this.resolveAppId("cancel"),a=await this.resolveCookie(),o=await this.runWithSpinner("Canceling cloud build job...",()=>se({appKey:n,jobId:e,reason:t||"Canceled by doubao CLI",internal:this.internal,cookie:a})),i=o.data?.job_id;if(!i)throw Error("Cloud build cancel response did not return job_id");return tk.success("Cloud build job canceled",{jobId:i}),i}async getStatus({jobId:e}){if(!e)throw Error("Cloud status requires job id.");let t=await this.resolveAppId("build"),n=await this.resolveCookie(),a=(await st({appKey:t,jobId:e,internal:this.internal,cookie:n})).data;if(!a)throw Error("Cloud build status response did not return data");let o=ez[a.status]||String(a.status);return tk.info("Cloud build job",{jobId:a.job_id}),tk.info("Cloud build status",{status:o}),a}async log({jobId:e,start:t,end:n}){if(!e)throw Error("Cloud log requires job id.");let a=Number(t??1),o=Number(n??a+200-1);if(!Number.isInteger(a)||!Number.isInteger(o)||a<1||o<a)throw Error("Cloud log requires a valid line range.");let i=await this.resolveAppId("log"),r=await this.resolveCookie(),s=(await sn({appKey:i,jobId:e,start:a,end:o,internal:this.internal,cookie:r})).data;if(!s)throw Error("Cloud build log response did not return data");return this.printLogLines(s.lines),tk.info("Cloud build logs fetched",{start:s.start??a,end:s.end??o,totalLineCount:s.total_line_count}),s}async waitForBuildJob({jobId:e}){let t=await this.resolveAppId("build"),n=await this.resolveCookie(),a=sl("Waiting for cloud build to finish...").start(),o=!1;try{for(;;){let i=await st({appKey:t,jobId:e,internal:this.internal,cookie:n}),r=i.data?.status,s=void 0===r?"UNKNOWN":ez[r]||String(r);if(a.text=`Cloud build status: ${s}`,void 0!==r&&sp.has(r)){if(r===ez.SUCCESS){a.succeed(`Cloud build status: ${s}`),o=!0;return}throw a.fail(`Cloud build status: ${s}`),o=!0,await this.printFailureLogs({appId:t,jobId:e,cookie:n}),Error(`Cloud build ended with status: ${s}`)}await new Promise(e=>setTimeout(e,5e3))}}catch(e){throw o||a.fail(),e}}async printFailureLogs({appId:e,jobId:t,cookie:n}){let a=1,o=0,i=!1;try{for(tk.info("Fetching cloud build failure logs");o<1e3&&a<=1e3;){let r=Math.min(a+200-1,1e3),s=(await sn({appKey:e,jobId:t,start:a,end:r,internal:this.internal,cookie:n})).data;if(!s||0===s.lines.length)break;this.printLogLines(s.lines),o+=s.lines.length;let l=s.lines.at(-1)?.line_number,p=void 0!==l&&l>=a?l+1:void 0!==s.end&&s.end>=a?s.end+1:a,d=p>a;if(!(i=s.has_more_after&&d))break;a=p}i&&tk.warn("Cloud build failure logs truncated",{limit:1e3,jobId:t})}catch(e){tk.warn("Failed to fetch cloud build failure logs",{reason:rz(e)})}}async resolveCookie(){return await rH(this.options,{internal:this.internal})}resolveBuildVariables(e){let t=new Map;for(let[e,n]of Object.entries(this.resolveEnv()))t.set(e,{name:e,value:n,env_var_name:e});for(let[e,n]of Object.entries(this.resolveSecretEnv()))t.set(e,{name:e,value:n,env_var_name:e,is_secret:!0});for(let n of e||[])t.set(n.env_var_name||n.name,n);return t.size>0?Array.from(t.values()):void 0}resolveEnv(){return this.options.env?(this.env??=sc(this.resolveAppPath(this.options.env),"Env"),this.env):{}}resolveSecretEnv(){return this.options.secretEnv?(this.secretEnv??=sc(this.resolveAppPath(this.options.secretEnv),"Secret env"),this.secretEnv):{}}resolveAppPath(e){return e_.isAbsolute(e)?e:e_.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 rg({cwd:this.appDir,customConfigFile:this.options.config}),t=await rb({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)tk.warn(t);for(let t of e.blockers)tk.error(t)}printLogLines(e){for(let t of e)console.log(t.content)}async runWithSpinner(e,t){let n=sl(e).start();try{let e=await t(e=>{n.text=e});return n.succeed(),e}catch(e){throw n.fail(),e}}}function sc(e,t){if(!to.existsSync(e))throw Error(`${t} file does not exist: ${e}`);return function(e){let t={};for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith("#"))continue;let a=e.startsWith("export ")?e.slice(7).trimStart():e,o=a.indexOf("=");if(o<=0)continue;let i=a.slice(0,o).trim();/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&(t[i]=function(e){let t=e[0];if(('"'===t||"'"===t)&&e.endsWith(t))return e.slice(1,-1);let n=e.indexOf(" #");return -1===n?e:e.slice(0,n).trimEnd()}(a.slice(o+1).trim()))}return t}(to.readFileSync(e,"utf8"))}function su({compileHooks:e,output:t}){let n=new Map,a={percentage:0},o=()=>{if(0===n.size)return;let o=[...n.values()].reduce((e,t)=>t.percentage<e.percentage?t:e);(o.percentage!==a.percentage||o.stage!==a.stage)&&(a=o,t?.onProgress?.(o),e?.onCompileProgress?.(o.percentage,o.stage??""))},i=e=>{for(let t of(n.clear(),e))n.set(t,{percentage:0});a={percentage:0}};return[{name:"DoubaoAppsDevPlugin",setup(a){(t?.progressBar!==void 0||t?.printLogs===!1)&&a.modifyRsbuildConfig((e,{mergeRsbuildConfig:n})=>n(e,{...t?.printLogs===!1?{logLevel:"silent"}:{},...t?.progressBar!==void 0?{dev:{progressBar:t.progressBar}}:{}})),(t?.onProgress||e?.onCompileProgress)&&(a.modifyRspackConfig((e,{appendPlugins:t,environment:a,environments:r})=>{0===n.size&&i(Object.keys(r)),t(new v.rspack.ProgressPlugin((e,t)=>{n.set(a.name,{percentage:Math.max(0,Math.min(1,e)),...t?{stage:t}:{}}),o()}))}),a.onBeforeDevCompile(({environments:e})=>{i(Object.keys(e))})),a.onDevCompileDone(()=>{if(n.size>0){for(let e of n.keys())n.set(e,{percentage:1,stage:"done"});o()}e?.onDevCompileDone?.()})}}]}class sm{appDirectory;launcher;constructor(e,t=r6){this.appDirectory=e,this.launcher=new t(e)}createCloudBuildLauncher(e={}){return new sd(e,this.appDirectory||process.cwd())}async create(e){await el(e)}async dev(e={}){var t,n;let{compileHooks:a,output:o,simulator:i,...r}=e,s=()=>this.launcher.dev({...r,...void 0!==i?{openWebDebugger:i}:{},rsbuildPlugins:su({compileHooks:a,output:o}),signingEncryptionOptions:e.signingEncryptionOptions});if(!o)return await s();let l=(t={printLogs:o.printLogs,onLog:o.onLog},em.push(t),()=>{let e=em.lastIndexOf(t);e>=0&&em.splice(e,1)}),p=v.logger.level;!1===o.printLogs&&(v.logger.level="silent");let d=!0,c=()=>{d&&(d=!1,v.logger.level=p,l())};try{let e=await (n={printLogs:o.printLogs,onLog:o.onLog},eu.run(n,s));if(e&&"function"==typeof e.closeServer){let t=e.closeServer.bind(e);e.closeServer=async()=>{try{await t()}finally{c()}}}else c();return e}catch(e){throw c(),e}}async build(e={}){process.env.NODE_ENV="production";let{compileHooks:t,...n}=e;await this.launcher.build({...n,rsbuildPlugins:su({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:n,botId:a,widgetData:o,debugDriver:i,skipAdbForegroundAppWatch:r}=e,s=await tM({debugDriver:i,deviceId:n,skipAdbForegroundAppWatch:r}),l=this.launcher.context.metadata.appId;s.pushWidget({appId:l,widgetId:t,widgetData:o,botId:a})}async openPage(e){let{pageId:t,pageData:n,pageSettings:a,mode:o,debugDriver:i,deviceId:r,skipAdbForegroundAppWatch:s}=e,l=await tM({debugDriver:i,deviceId:r,skipAdbForegroundAppWatch:s}),p=this.launcher.context.metadata.appId;l.openPage({appId:p,pageId:t,pageData:n,pageSettings:a,mode:o})}async callTool(e){let{toolId:t,toolData:n,debugDriver:a,deviceId:o,skipAdbForegroundAppWatch:i}=e,r=await tM({debugDriver:a,deviceId:o,skipAdbForegroundAppWatch:i}),s=this.launcher.context.metadata.appId;r.callTool({appId:s,toolId:t,toolData:n})}async executeDebugScene(e){let{matchedScene:t,variables:n,deviceId:a,debugDriver:o,skipAdbForegroundAppWatch:i}=e,r=this.launcher.context.metadata.appId,s=await tM({debugDriver:o,deviceId:a,skipAdbForegroundAppWatch:i});await eC({matchedScene:t,appId:r,driver:s,variables:n})}async getDebugScenes(){let e=await eE(this.appDirectory||process.cwd());return await Promise.all(e.map(async e=>({...e,content:await ex(e.path)})))}async cloud(e={}){let{versionTag:t,logs:n,runner:a,createJobConfig:o,variables:i,properties:r,...s}=e;return await this.createCloudBuildLauncher(s).start({versionTag:t,logs:n,runner:a,config:o,variables:i,properties:r})}async cloudUpload(e={}){let{packOnly:t,outputDir:n,...a}=e;return await this.createCloudBuildLauncher(a).upload({packOnly:t,outputDir:n})}async cloudPackage(e={}){let{outputDir:t,...n}=e;return await this.createCloudBuildLauncher(n).package({outputDir:t})}async cloudBuild(e){let{sourceRef:t,versionTag:n,runner:a,createJobConfig:o,variables:i,properties:r,...s}=e;return await this.createCloudBuildLauncher(s).build({sourceRef:t,versionTag:n,runner:a,config:o,variables:i,properties:r})}async cloudCancel(e){let{jobId:t,reason:n,...a}=e;return await this.createCloudBuildLauncher(a).cancel({jobId:t,reason:n})}async cloudGetStatus(e){let{jobId:t,...n}=e;return await this.createCloudBuildLauncher(n).getStatus({jobId:t})}async cloudLog(e){let{jobId:t,start:n,end:a,...o}=e;return await this.createCloudBuildLauncher(o).log({jobId:t,start:n,end:a})}async deploy(e){let{versionTag:t,cookie:n,token:a,appKey:o,signingEncryptionOptions:i}=e;if(!n&&!a)throw Error("Doubao Apps SDK 部署需要 Cookie 或 Developer Open Build Token。");process.env.NODE_ENV="production",await this.launcher.build({skipCleanupRootPath:!0,cookie:n,signingEncryptionOptions:i,token:a,versionTag:t});let{manifest:r}=this.launcher.context;try{return await r8({versionTag:t,...o?{appKey:o}:{},manifest:r,rootPath:this.launcher.rootPath,internal:e.internal??this.launcher.context.internal,cookie:n,token:a})}finally{"applet0930"===process.env.DEBUG||t3.rmSync(this.launcher.rootPath,{recursive:!0,force:!0})}}}export{sm as DoubaoAppsSDK,rz as error_getErrorMessage};