@doubao-dev/kit 0.8.0-rc.0 → 0.8.0-rc.2

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 (33) hide show
  1. package/dist/277~0.js +3 -3
  2. package/dist/assets/web-sdk-debugger/__doubao_web_sdk_native_modules/applet-bridge-module-core.js +1 -1
  3. package/dist/assets/web-sdk-debugger/assets/framework/doubao-apps-api.template.js +0 -0
  4. package/dist/assets/web-sdk-debugger/assets/framework/doubao-apps-framework.template.js +0 -0
  5. package/dist/assets/web-sdk-debugger/assets/framework/doubao-apps-react-dev.template.js +0 -0
  6. package/dist/assets/web-sdk-debugger/assets/framework/doubao-apps-react.template.js +0 -0
  7. package/dist/assets/web-sdk-debugger/index.html +1 -1
  8. package/dist/assets/web-sdk-debugger/static/js/270.9f817b369e.js +2 -0
  9. package/dist/assets/web-sdk-debugger/static/js/{148.80681ca28e.js → 275.41701d029c.js} +3 -3
  10. package/dist/assets/web-sdk-debugger/static/js/async/legacy-wasm-js.53cc49def0.js +2 -0
  11. package/dist/assets/web-sdk-debugger/static/js/async/web-core-main-chunk.d1b32950a5.js +1 -0
  12. package/dist/assets/web-sdk-debugger/static/js/async/{web-core-markup-encoder.0aadb2c971.js → web-core-markup-encoder.0157ce350a.js} +3 -3
  13. package/dist/assets/web-sdk-debugger/static/js/async/{web-core-template-loader-thread.559b06cf7a.js → web-core-template-loader-thread.73428c5c1e.js} +2 -2
  14. package/dist/assets/web-sdk-debugger/static/js/async/{web-core-worker-chunk.97f5cf9510.js → web-core-worker-chunk.cf495a4ab8.js} +1 -1
  15. package/dist/assets/web-sdk-debugger/static/js/async/{web-elements.98d43e1d95.js → web-elements.6807f163ca.js} +12 -12
  16. package/dist/assets/web-sdk-debugger/static/js/async/xmarkdown-deps.c4c1321ad5.js +5 -0
  17. package/dist/assets/web-sdk-debugger/static/js/async/xmarkdown-deps.c4c1321ad5.js.LICENSE.txt +5 -0
  18. package/dist/assets/web-sdk-debugger/static/js/{index.3ccc2f978a.js → index.84ba26caa4.js} +3 -3
  19. package/dist/assets/web-sdk-debugger/static/wasm/8585c2144c.module.wasm +0 -0
  20. package/dist/assets/web-sdk-debugger/static/wasm/{4c402c7981.module.wasm → 86e0a936fd.module.wasm} +0 -0
  21. package/dist/assets/web-sdk-debugger/static/wasm/9655be8557.module.wasm +0 -0
  22. package/dist/cli/index.js +1 -1
  23. package/dist/sdk.d.ts +1 -0
  24. package/dist/sdk.js +2 -2
  25. package/package.json +6 -6
  26. package/dist/assets/web-sdk-debugger/static/js/158.85b350c15f.js +0 -2
  27. package/dist/assets/web-sdk-debugger/static/js/async/legacy-wasm-js.555371d3dd.js +0 -2
  28. package/dist/assets/web-sdk-debugger/static/js/async/web-core-main-chunk.0802207289.js +0 -1
  29. package/dist/assets/web-sdk-debugger/static/js/async/xmarkdown-deps.6cec36ed6c.js +0 -5
  30. package/dist/assets/web-sdk-debugger/static/js/async/xmarkdown-deps.6cec36ed6c.js.LICENSE.txt +0 -3
  31. package/dist/assets/web-sdk-debugger/static/wasm/72aaf7d0aa.module.wasm +0 -0
  32. package/dist/assets/web-sdk-debugger/static/wasm/77fb77f77f.module.wasm +0 -0
  33. /package/dist/assets/web-sdk-debugger/static/js/{148.80681ca28e.js.LICENSE.txt → 275.41701d029c.js.LICENSE.txt} +0 -0
package/dist/cli/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import"node:module";import{logger as e}from"@rsbuild/core";import o from"chalk";import{Option as a,program as r}from"commander";import{package_namespaceObject as t,dev as n,cliLogger as i,deploy as p,build as c,analyze as s}from"../277~0.js";import{selectDevServerHost as d}from"../427~0.js";function l(){if(!process.env.NODE_ENV){let e=process.argv[2];process.env.NODE_ENV=["build","package","deploy","analyze","perf"].includes(e)?"production":"development"}i.greet(`Doubao Apps SDK v${t.rE}`)}async function m(e){let{devtools:o,host:a,...r}=e,t={...r,host:!0===a?await d():a};return o?{...t,debugDriver:"devtools"}:t}function u(e){return e.option("-c --config <config>","specify the configuration file, can be a relative or absolute path").option("--env-mode <mode>","specify the env mode to load the `.env.[mode]` file"),e}function v(t=process.cwd(),i={},d="0.8.0-rc.0"){r.name("doubao").usage("<command> [options]").version(d),u(r.command("dev")).description("starting the dev server...").option("--host [host]","listen hostname or IP; omit value to select an address interactively").option("--devtools","use DevTools debug driver").action(async o=>{try{await n(await m(o))}catch(o){e.error("Failed to dev"),e.error(o),process.exit(1)}}),u(r.command("build")).description("starting build the applet").option("-a --archive","Archive all package",!1).addOption(Object.assign(new a("--channel <string>","Need channel name"),{short:"-ch",flags:"-ch --channel <string>"})).action(async o=>{try{await c(o)}catch(o){e.error("Failed to build"),e.error(o),process.exit(1)}}),u(r.command("analyze")).description("analyze the applet package").action(async a=>{try{await s(a)}catch(a){e.error(o.red("Failed to analyze")),e.error(a),process.exit(1)}}),u(r.command("deploy")).option("--token <token>","developer open build token for Doubao Apps Platform deploy").option("--app-name, --appName <appName>","app name for Doubao Apps Platform deploy").option("--app-icon, --appIcon <appIcon>","app icon for Doubao Apps Platform deploy").option("--version-tag, --versionTag <versionTag>","version tag for Doubao Apps Platform deploy").description("build and upload the app package").action(async a=>{try{await p({...a,build:!0})}catch(a){e.error(o.red("Failed to deploy")),e.error(a),process.exit(1)}}),r.parse()}export{l as prepareCli,v as runCli};
1
+ import"node:module";import{logger as e}from"@rsbuild/core";import o from"chalk";import{Option as a,program as r}from"commander";import{package_namespaceObject as t,dev as n,cliLogger as i,deploy as p,build as c,analyze as s}from"../277~0.js";import{selectDevServerHost as d}from"../427~0.js";function l(){if(!process.env.NODE_ENV){let e=process.argv[2];process.env.NODE_ENV=["build","package","deploy","analyze","perf"].includes(e)?"production":"development"}i.greet(`Doubao Apps SDK v${t.rE}`)}async function m(e){let{devtools:o,host:a,...r}=e,t={...r,host:!0===a?await d():a};return o?{...t,debugDriver:"devtools"}:t}function u(e){return e.option("-c --config <config>","specify the configuration file, can be a relative or absolute path").option("--env-mode <mode>","specify the env mode to load the `.env.[mode]` file"),e}function v(t=process.cwd(),i={},d="0.8.0-rc.2"){r.name("doubao").usage("<command> [options]").version(d),u(r.command("dev")).description("starting the dev server...").option("--host [host]","listen hostname or IP; omit value to select an address interactively").option("--devtools","use DevTools debug driver").action(async o=>{try{await n(await m(o))}catch(o){e.error("Failed to dev"),e.error(o),process.exit(1)}}),u(r.command("build")).description("starting build the applet").option("-a --archive","Archive all package",!1).addOption(Object.assign(new a("--channel <string>","Need channel name"),{short:"-ch",flags:"-ch --channel <string>"})).action(async o=>{try{await c(o)}catch(o){e.error("Failed to build"),e.error(o),process.exit(1)}}),u(r.command("analyze")).description("analyze the applet package").action(async a=>{try{await s(a)}catch(a){e.error(o.red("Failed to analyze")),e.error(a),process.exit(1)}}),u(r.command("deploy")).option("--token <token>","developer open build token for Doubao Apps Platform deploy").option("--app-name, --appName <appName>","app name for Doubao Apps Platform deploy").option("--app-icon, --appIcon <appIcon>","app icon for Doubao Apps Platform deploy").option("--version-tag, --versionTag <versionTag>","version tag for Doubao Apps Platform deploy").description("build and upload the app package").action(async a=>{try{await p({...a,build:!0})}catch(a){e.error(o.red("Failed to deploy")),e.error(a),process.exit(1)}}),r.parse()}export{l as prepareCli,v as runCli};
2
2
  //# sourceMappingURL=index.js.map
package/dist/sdk.d.ts CHANGED
@@ -736,6 +736,7 @@ declare class SandboxRuntime {
736
736
  sandboxCsrPem?: string | undefined;
737
737
  fileSystemNamespace: string;
738
738
  sandboxSessionAvailable: boolean;
739
+ sandboxAppId: string;
739
740
  sandboxCsrRequired: boolean;
740
741
  sandboxCsrUploaded: boolean;
741
742
  sandboxPhoneNumberUploaded: boolean;
package/dist/sdk.js CHANGED
@@ -228,7 +228,7 @@ Please remove the property next time.`})}).every(x=>x)].every(x=>x))(x,e+"",!0)|
228
228
  ${e.map(x=>`- ${x}`).join("\n")}`).join("\n\n");throw Error(`${r}
229
229
 
230
230
  widget id 必须全局唯一,请在 src/app.config.ts 中配置不同的 "id"。`)}(b),b.forEach(([x,e])=>{r.addWidgetMeta(x,e)})}let ry=`base/${tx}`;async function rS({encryption:x}){let e=M.mkdtempSync(Q.join(xp.tmpdir(),"doubao-keystore-")),t=Q.join(e,tx);try{let{generateKeystore:e}=await import("node:module").then(function(x){return xV.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),22)}),r=await e(t,{encryption:x});if(0!==r.status)throw Error(r.error_msg);return M.readFileSync(t)}finally{M.rmSync(e,{recursive:!0,force:!0})}}let rI=xV("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40/node_modules/@byted-lynx/tasm/index.js");class rN{options;isGenerateKeystore=!1;constructor(x){this.options=x}apply(x){x.hooks.thisCompilation.tap(rN.name,e=>{e.hooks.processAssets.tapPromise({name:rN.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH},async()=>{let t=Date.now();try{let{RawSource:t}=x.webpack.sources,r=this.options.getAppAssetPath(),a=tQ(e,tI);for(let x of[r,a].filter(x=>!!x)){let a=e.getAsset(x);if(!a)throw Error(`未生成 Worker 入口产物:${x}`);let{buffer:_,encodeOptions:n,keystoreContent:A}=await this.encode([a]);if(e.updateAsset(x,new t(_,!1)),A){let x=new t(A,!1);e.getAsset(ry)?e.updateAsset(ry,x):e.emitAsset(ry,x)}ev()&&x===r&&e.emitAsset(`${y.dirname(x)}/tasm.json`,new t(JSON.stringify(n,null,2)))}}finally{this.options.onProcessDuration?.(Date.now()-t)}})})}async encode(x){let e={},{resolveSigningEncryptionOptions:t}=this.options;for(let t of x)t.name.endsWith(".js")&&(e[t.name.replace(/\.template\.js$/,"")]={content:t.source.source().toString()});let r={compilerOptions:{enableFiberArch:!0,targetSdkVersion:this.options.engineVersion??"3.5"},sourceContent:{appType:"DynamicComponent"},customSections:e},a=await t?.();if(a?.signing.enabled||a?.encryption.enabled){let{encode:x}=await import("node:module").then(function(x){return xV.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),22)}),e=this.options.metadata.appId,t=tv(a,{signing:{extra_config:{app_id:e,bundle_id:e}},encryption:{salt:e}}),{buffer:_,lepus_debug:n,status:A,error_msg:s}=await x(JSON.stringify(r),t);if(0!==A)throw Error(s);return!this.isGenerateKeystore&&t.encryption.enabled?(this.isGenerateKeystore=!0,{buffer:_,encodeOptions:r,debugInfo:n,keystoreContent:await rS({encryption:{...t.encryption}})}):{buffer:_,encodeOptions:r,debugInfo:n}}let _=(0,rI.getEncodeMode)(),{buffer:n}=await _(r);return{buffer:n,encodeOptions:r}}}function rB(x,t,r,a,_,n){let A=!1,s=n?.internal?n:void 0;return{name:rB.name,apply(n){let i=new n.webpack.experiments.VirtualModulesPlugin;i.apply(n),n.hooks.thisCompilation.tap(rB.name,()=>{Object.keys(r).forEach(x=>{i.writeModule(r[x].filename,r[x].toString())})}),n.hooks.thisCompilation.tap(rB.name,i=>{let o,l=()=>{void 0!==o&&_?.(Math.max(0,Date.now()-o))},c=x.getLynxTemplatePluginHooks(i);c.beforeEncode.tapPromise({name:rB.name,stage:1},async x=>{o??=Date.now();let e=x.chunkGroups?.find(({name:x})=>x&&Object.hasOwn(r,x))?.name;return x.encodeData.sourceContent.config=G({},x.encodeData.sourceContent.config,{mapContainerType:1,trailNewImage:!0,disableQuickTracingGC:!0},s?.config,e?s?.entries?.[e]:void 0),x}),c.encode.tapPromise({name:rB.name,stage:255},async x=>{let{encodeOptions:r}=x,_=await a?.();if(_?.signing.enabled||_?.encryption.enabled){let{encode:e}=await import("node:module").then(function(x){return xV.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),22)}),a=t.getData(),s=function(x,e){let t=(e??"").replaceAll("\\","/"),r=t.match(/(?:^|\/)(pages|widgets)\/(.+)$/);if(r){let[,e,t]=r,a=`${e}/${t}`;return"widgets"===e?x.widgets[a]?.id:x.pages[a]?.path}let a=y.posix.basename(t);return x.widgets[`widgets/${a}`]?.id??x.pages[`pages/${a}`]?.path}(a,x.intermediate),o=a.app.appId,c=tv(_,{signing:{extra_config:{app_id:o,bundle_id:s}},encryption:{salt:o}}),{buffer:v,lepus_debug:d,status:f,error_msg:b}=await e(JSON.stringify(r),c);if(0!==f)throw Error(b);if(!A&&c.encryption.enabled){A=!0;let x=await rS({encryption:{...c.encryption}}),e=new n.webpack.sources.RawSource(x,!1);i.getAsset(ry)?i.updateAsset(ry,e):i.emitAsset(ry,e)}return l(),{buffer:v,debugInfo:d}}let{buffer:s,lepus_debug:o}=await (e??=new xm({filename:new URL("./encode-worker.js",import.meta.url).href,maxThreads:x_()})).run({encodeOptions:r});return l(),{buffer:Buffer.from(s),debugInfo:o}})}),n.hooks.failed.tap(rB.name,x=>{ri.error("模板打包失败",{error:x})})}}}var rF="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",rw=new Uint8Array(64),rC=new Uint8Array(128);for(let x=0;x<rF.length;x++){let e=rF.charCodeAt(x);rw[x]=e,rC[e]=x}function rP(x,e){let t=0,r=0,a=0;do t|=(31&(a=rC[x.next()]))<<r,r+=5;while(32&a);let _=1&t;return t>>>=1,_&&(t=-0x80000000|-t),e+t}function rk(x,e){return!(x.pos>=e)&&44!==x.peek()}var rD=class{constructor(x){this.pos=0,this.buffer=x}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(x){let{buffer:e,pos:t}=this,r=e.indexOf(x,t);return -1===r?e.length:r}};function rL(x,e){return x[0]-e[0]}let rq=/^[\w+.-]+:\/\//,rT=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,rR=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function r$(x){return x.startsWith("/")}function rG(x){return/^[.?#]/.test(x)}function rO(x){let e=rT.exec(x);return rX(e[1],e[2]||"",e[3],e[4]||"",e[5]||"/",e[6]||"",e[7]||"")}function rX(x,e,t,r,a,_,n){return{scheme:x,user:e,host:t,port:r,path:a,query:_,hash:n,type:7}}function rK(x){if(x.startsWith("//")){let e=rO("http:"+x);return e.scheme="",e.type=6,e}if(r$(x)){let e=rO("http://foo.com"+x);return e.scheme="",e.host="",e.type=5,e}if(x.startsWith("file:")){let e,t;return t=(e=rR.exec(x))[2],rX("file:","",e[1]||"","",r$(t)?t:"/"+t,e[3]||"",e[4]||"")}if(rq.test(x))return rO(x);let e=rO("http://foo.com/"+x);return e.scheme="",e.host="",e.type=x?x.startsWith("?")?3:x.startsWith("#")?2:4:1,e}function rQ(x,e){let t=e<=4,r=x.path.split("/"),a=1,_=0,n=!1;for(let x=1;x<r.length;x++){let e=r[x];if(!e){n=!0;continue}if(n=!1,"."!==e){if(".."===e){_?(n=!0,_--,a--):t&&(r[a++]=e);continue}r[a++]=e,_++}}let A="";for(let x=1;x<a;x++)A+="/"+r[x];A&&(!n||A.endsWith("/.."))||(A+="/"),x.path=A}function rZ(x,e){for(let t=e;t<x.length;t++)if(!function(x){for(let e=1;e<x.length;e++)if(x[e][0]<x[e-1][0])return!1;return!0}(x[t]))return t;return x.length}function rM(x,e){return x[0]-e[0]}var rJ=!1,rV=class{constructor(x,e){var t;let r,a,_="string"==typeof x;if(!_&&x._decodedMemo)return x;let n="string"==typeof(t=x)?JSON.parse(t):t,{version:A,file:s,names:i,sourceRoot:o,sources:l,sourcesContent:c}=n;this.version=A,this.file=s,this.names=i||[],this.sourceRoot=o,this.sources=l,this.sourcesContent=c,this.ignoreList=n.ignoreList||n.x_google_ignoreList||void 0;let v=(r=function(x){if(!x)return"";let e=x.lastIndexOf("/");return x.slice(0,e+1)}(e),a=o?o+"/":"",x=>(function(x,e){if(!x&&!e)return"";let t=rK(x),r=t.type;if(e&&7!==r){let x=rK(e),a=x.type;switch(r){case 1:t.hash=x.hash;case 2:t.query=x.query;case 3:case 4:rQ(x,x.type),"/"===t.path?t.path=x.path:t.path=function(x){if(x.endsWith("/.."))return x;let e=x.lastIndexOf("/");return x.slice(0,e+1)}(x.path)+t.path;case 5:t.user=x.user,t.host=x.host,t.port=x.port;case 6:t.scheme=x.scheme}a>r&&(r=a)}rQ(t,r);let a=t.query+t.hash;switch(r){case 2:case 3:return a;case 4:{let r=t.path.slice(1);if(!r)return a||".";if(rG(e||x)&&!rG(r))return"./"+r+a;return r+a}case 5:return t.path+a;default:return t.scheme+"//"+t.user+t.host+t.port+t.path+a}})(a+(x||""),r));this.resolvedSources=l.map(v);let{mappings:d}=n;if("string"==typeof d)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=function(x,e){let t=rZ(x,0);if(t===x.length)return x;e||(x=x.slice());for(let a=t;a<x.length;a=rZ(x,a+1)){var r;x[a]=(r=x[a],e||(r=r.slice()),r.sort(rM))}return x}(d,_);else if(n.sections)throw Error("TraceMap passed sectioned source map, please use FlattenMap export instead");else throw Error(`invalid source map: ${JSON.stringify(n)}`);this._decodedMemo={lastKey:-1,lastNeedle:-1,lastIndex:-1},this._bySources=void 0,this._bySourceMemos=void 0}};function rH(x,e,t,r){return{source:x,line:e,column:t,name:r}}let rU=new Set(["@doubao-dev/template"]),rY=new Set(["@doubao-dev/template","@byted-doubao-apps/template","@doubao-dev/components","@byted-doubao-apps/components","@doubao-dev/framework","@byted-doubao-apps/framework"]),rz=/\.(css|scss|sass|less|styl|stylus)$/i;function rW(x){let e=x.split(/[?#]/)[0];try{return k(e)}catch{return y.resolve(e)}}class r0{widgetEntryPaths;constructor(x){this.widgetEntryPaths=x}apply(x){let e=rW(x.options.context??x.context);x.hooks.thisCompilation.tap(r0.name,t=>{t.hooks.finishModules.tap(r0.name,r=>{let a=new Set(this.widgetEntryPaths.map(rW)),_=new Set,n=[],A=new Set,s=new Set,i=new Map,o=x=>{if(s.has(x))return;s.add(x);let r=x.resourceResolveData?.descriptionFileData?.name;if(r&&rU.has(r)){let t=x.resourceResolveData?.descriptionFileData?.version;if(!function(x){if("string"!=typeof x)return!1;let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(x);return!!e&&(Number(e[1])>0||Number(e[2])>=5)}(t)){let r=eE(e,rW(x.resourceResolveData?.descriptionFilePath??x.resource));i.set(r,t??"未知")}}if(!(r&&rY.has(r)))for(let e of t.moduleGraph.getOutgoingConnections(x))e.module&&o(e.module)};for(let x of r){let e=x.resource;e&&a.has(rW(e))&&o(x)}if(i.size){let e=[...new Set(i.values())].sort().join("、"),r=`@doubao-dev/template 当前版本为 ${e},请升级到 0.5.0 或更高的正式版本。`;n.push({rule_id:"template.version",severity:"warning",file:[...i.keys()].sort()[0],field:"template.version",message:r,targets:[x.options.name??"default"]});let a=new j.WebpackError(`[卡片检查] ${r}`);a.name="CardTemplateVersionWarning",t.warnings.push(a),t.cardCheck={schema_version:1,rules_version:"1",execution_status:"completed",coverage:"partial",checked_widgets:[],diagnostics:n,total_count:1,truncated:!1};return}for(let x of r)for(let r of x.buildInfo?.cardDiagnostics??[]){let a=eE(e,rW(r.file)),_=r.line?`:${r.line}${r.column?`:${r.column}`:""}`:"",n="widget.root"===r.field?"":`${r.field}: `,A=new j.WebpackError(`[卡片检查] ${a}${_} ${n}${r.message}`);A.name="CardTemplateWarning",Object.assign(A,{module:x,file:`${a}${_}`}),t.warnings.push(A)}for(let s of r){let r=s.resource;if(!r||!a.has(rW(r)))continue;let i=eE(e,rW(r));A.add(i);let o=new Set,l=(a,A)=>{if(o.has(a))return;o.add(a);let s=a.resourceResolveData?.descriptionFileData?.name;if(s&&rY.has(s))return;for(let t of a.buildInfo?.cardDiagnostics??[])n.push({...t,widget:i,file:eE(e,rW(t.file)),targets:[x.options.name??"default"]});for(let x of t.moduleGraph.getOutgoingConnectionsInOrder(a))x.module&&l(x.module,x);if(!a.resource||!rz.test(a.resource.split(/[?#]/)[0]))return;let c=rW(a.resource),v=rW(r),d=`${v}:${c}`;if(_.has(d))return;_.add(d);let f=A?.originModule,b=eE(e,rW(f?.resource??c)),u=function(x){let e=x?.dependency.loc;if(!e||!("start"in e))return;let t={line:e.start.line,column:e.start.column??1},r=x?.originModule?.originalSource()?.map();if(!r)return t;let a=function(x,e){var t;let{line:r,column:a,bias:_}=e;if(--r<0)throw Error("`line` must be greater than 0 (lines start at line 1)");if(a<0)throw Error("`column` must be greater than or equal to 0 (columns start at column 0)");let n=(t=x)._decoded||(t._decoded=function(x){let{length:e}=x,t=new rD(x),r=[],a=0,_=0,n=0,A=0,s=0;do{let x=t.indexOf(";"),e=[],i=!0,o=0;for(a=0;t.pos<x;){let r;(a=rP(t,a))<o&&(i=!1),o=a,rk(t,x)?(_=rP(t,_),n=rP(t,n),A=rP(t,A),r=rk(t,x)?[a,_,n,A,s=rP(t,s)]:[a,_,n,A]):r=[a],e.push(r),t.pos++}i||e.sort(rL),r.push(e),t.pos=x+1}while(t.pos<=e);return r}(t._encoded));if(r>=n.length)return rH(null,null,null,null);let A=n[r],s=function(x,e,t,r,a){let _=function(x,e,t,r){let{lastKey:a,lastNeedle:_,lastIndex:n}=t,A=0,s=x.length-1;if(r===a){if(e===_)return rJ=-1!==n&&x[n][0]===e,n;e>=_?A=-1===n?0:n:s=n}return t.lastKey=r,t.lastNeedle=e,t.lastIndex=function(x,e,t,r){for(;t<=r;){let a=t+(r-t>>1),_=x[a][0]-e;if(0===_)return rJ=!0,a;_<0?t=a+1:r=a-1}return rJ=!1,t-1}(x,e,A,s)}(x,r,e,t);return(rJ?_=(-1===a?function(x,e,t){for(let r=t+1;r<x.length&&x[r][0]===e;t=r++);return t}:function(x,e,t){for(let r=t-1;r>=0&&x[r][0]===e;t=r--);return t})(x,r,_):-1===a&&_++,-1===_||_===x.length)?-1:_}(A,x._decodedMemo,r,a,_||1);if(-1===s)return rH(null,null,null,null);let i=A[s];if(1===i.length)return rH(null,null,null,null);let{names:o,resolvedSources:l}=x;return rH(l[i[1]],i[2]+1,i[3],5===i.length?o[i[4]]:null)}(new rV({...r,version:3}),{line:t.line,column:Math.max(0,t.column-1)});return null!==a.line&&null!==a.column?{line:a.line,column:a.column+1}:void 0}(A),p=u?.line,m=u?.column,h=p?`:${p}:${m}`:"",E="卡片不支持引入自定义样式文件,请使用模板提供的样式。";n.push({rule_id:"template.stylesheet",severity:"warning",widget:i,file:b,...p?{line:p,column:m}:{},field:"widget.styles",message:E,targets:[x.options.name??"default"]});let g=new j.WebpackError(`[卡片检查] ${b}${h} ${E}`);g.name="CardStyleWarning",Object.assign(g,{module:f??a,file:`${b}${h}`}),t.warnings.push(g)};l(s)}t.cardCheck={schema_version:1,rules_version:"1",execution_status:"completed",coverage:"partial",checked_widgets:[...A],diagnostics:n,total_count:n.length,truncated:!1}})})}}let r1=(x,e,t)=>{if(!ev())return void t();let r=process.hrtime.bigint(),a=x.method,_=x.url;e.on("finish",()=>{let x=Number(process.hrtime.bigint()-r)/1e6,t=_?new URL(_,"http://localhost").pathname:"",n=e.statusCode;rl.request({method:a||"UNKNOWN",url:t,statusCode:n,durationMs:x})}),t()},r2=new Set(["EACCES","EPERM"]),r3=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"]),r6=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_REQUEST_TIMEOUT"]),r4=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN","EPIPE"]),r5=new Set(["EEXIST","EISDIR","EMFILE","ENOENT","ENOSPC","ENOTDIR","EROFS"]),r7={SyntaxError:"syntax_error",TypeError:"type_error",ModuleNotFoundError:"dependency_error",ModuleBuildError:"compilation_error",ValidationError:"config_error",TimeoutError:"timeout_error",FetchError:"network_error",LoaderError:"loader_error",PluginError:"plugin_error"};function r8(x,e){if(!x||"object"!=typeof x||!(e in x))return;let t=x[e];return"string"==typeof t?t:void 0}function r9(x){if(!x||"object"!=typeof x)return[];if(Array.isArray(x.errors)&&x.errors.length>0)return x.errors;if(Array.isArray(x.stats))return x.stats.flatMap(r9);let e=x.stats&&"object"==typeof x.stats?x.stats:x;try{let x=e.toJson?.({all:!1,errors:!0}).errors;return Array.isArray(x)?x:[]}catch{return[]}}function ax(x){try{return P(x,"utf8").trim()||void 0}catch{return}}let ae=xV("../../../node_modules/.pnpm/@dp+tea-sdk-node@3.0.12/node_modules/@dp/tea-sdk-node/lib/index.js"),at=xV("../../../node_modules/.pnpm/@logsdk+node-plugin-http@4.0.8_patch_hash=d36ee5d841feee100de58867bba710d3ebdd5840c85f8_2a73615d04585e58fdd40bf5c6ccd254/node_modules/@logsdk/node-plugin-http/lib/index.js");class ar{constructor(x=function(x=y.join(xn(),".doubao-apps")){let e=y.join(x,"monitor-user-id"),t=ax(e);if(t)return t;let r=xj();try{return w(x,{recursive:!0,mode:448}),D(e,`${r}
231
- `,{encoding:"utf8",flag:"wx",mode:384}),r}catch{return ax(e)??"anonymous-unpersisted"}}()){this.pendingCount=0,this.sdk=new ae.TeaSDK({app_id:944787,logLevel:"silent"}),this.controller=(0,at.httpPlugin)({channel:"cn",retry:2,timeout:2e3}),this.controller.on("end",({hasSucceed:x})=>{this.pendingCount=Math.max(0,this.pendingCount-1),this.sdk.logger.trace("Tea event upload completed, hasSucceed: %s",x),x||this.sdk.logger.warn("Tea event upload did not succeed")}),this.controller.on("submit-error",({message:x})=>{this.sdk.logger.warn("Tea event upload failed: %s",x??"unknown network error")}),this.controller.on("submit-timeout",()=>{this.sdk.logger.warn("Tea event upload timed out after %d ms",2e3)}),this.sdk.use(this.controller),this.sdk.config({user:{user_unique_id:x}})}async upload(x){this.pendingCount+=1;try{this.sdk.collect(x.name,x.params)}catch(x){throw this.pendingCount-=1,x}}async flush(x){0!==this.pendingCount&&await new Promise(e=>{let t=()=>{clearTimeout(r),this.controller.off("drain",t),e()},r=setTimeout(t,x);this.controller.once("drain",t)})}}function aa(x){return!!(x&&!/<%=?\s*appId\s*%>/.test(x))}function a_(x){return{scene:void 0,commandStartTime:x,compileStartTime:void 0,builderInitStartTime:void 0,compilePhaseEndTimes:{moduleProcess:void 0,assetProcess:void 0},prepareDurations:{configLoadMs:0,projectScanMs:0,contextBootstrapMs:0,pluginBootstrapMs:0,builderInitMs:0},appInfoDurationMs:0,appInfoMeasured:!1,appTemplateProcessDurationMs:0,viewTemplateProcessDurationMs:0,reported:!1}}function an(x,e){Object.assign(x,a_(e))}function aA(x,{scene:e,commandStartTime:t,compileStartTime:r}){let a=x.commandStartTime===t,_=x.prepareDurations,n=x.builderInitStartTime,A=x.appInfoDurationMs,s=x.appInfoMeasured;a&&void 0!==n&&(_.builderInitMs=Math.max(0,r-n)),an(x,t),x.scene=e,x.compileStartTime=r,a&&(x.prepareDurations=_,x.appInfoDurationMs=A,x.appInfoMeasured=s)}function as(x,e,t){x.compilePhaseEndTimes[e]=Math.max(x.compilePhaseEndTimes[e]??0,t)}function ai(x){return Math.max(0,Math.round(Number.isFinite(x)?x:0))}let ao=new class{uploader;constructor(x){this.uploader=x}async reportEvent(x){try{await (this.uploader??=new ar).upload({name:x.name,params:{...x.params,kit_version:"0.8.0-rc.0",kit_node_version:process.version,kit_os_name:process.platform,kit_run_env:(process.env.BUILD_VERSION?"SCM":process.env.CI_REPO_NAME?"CI":"LOCAL").toLowerCase()}})}catch{}}async report(x){try{var e,t;let r,a,_,n,A,s,i,o=x.context?.compileLifecycle;if(o){if(o.reported)return;o.reported=!0}let l="dev_initial"===x.scene||"hot_update"===x.scene?"dev":x.scene,c={appDirectory:x.appDirectory,targetAppId:function(x){try{let e=x?.appId;return aa(e)?e:void 0}catch{return}}(x.context),scene:x.scene,command:l},v="failed"===x.status?{...c,status:x.status,errorStage:x.errorStage,error:r9(x.error)[0]??x.error}:{...c,status:x.status,pageCount:Object.keys(x.context.pages).length,widgetCount:Object.keys(x.context.widgets).length,securityMode:(r=x.context.signingEncryptionOptions,a=!!r?.signing.enabled,_=!!r?.encryption.enabled,a&&_?"signing_and_encryption":a?"signing":_?"encryption":"none"),durations:(e=x.context.compileLifecycle,t=x.compileEndTime,n=e.commandStartTime??t,A=e.compileStartTime??t,s=Math.min(t,Math.max(A,e.compilePhaseEndTimes.moduleProcess??t)),i=Math.min(t,Math.max(s,e.compilePhaseEndTimes.assetProcess??t)),{totalMs:t-n,prepareMs:A-n,compileMs:t-A,...e.prepareDurations,appInfoMs:e.appInfoDurationMs,appTemplateProcessMs:e.appTemplateProcessDurationMs,viewTemplateProcessMs:e.viewTemplateProcessDurationMs,moduleProcessMs:s-A,assetProcessMs:i-s,outputWriteMs:t-i})};await this.upload(v)}catch{}}async flush(x=3e3){try{await this.uploader?.flush?.(x)}catch{}}async upload(x){let{appDirectory:e,...t}=x;await this.reportEvent(function(x,e){let t={kit_compile_id:function(){let x="unknown";try{x=xA().username||x}catch{}return`${Date.now()}_${x}_${xj()}`}(),kit_compile_scene:x.scene,kit_command:x.command,kit_status:x.status};if(x.targetAppId&&(t.kit_appId=x.targetAppId),"success"===x.status)t.kit_page_count=x.pageCount,t.kit_widget_count=x.widgetCount,t.kit_security_mode=x.securityMode,t.kit_duration_ms_total=ai(x.durations.totalMs),t.kit_prepare_ms=ai(x.durations.prepareMs),t.kit_compile_ms=ai(x.durations.compileMs),t.kit_config_load_ms=ai(x.durations.configLoadMs),t.kit_project_scan_ms=ai(x.durations.projectScanMs),t.kit_context_bootstrap_ms=ai(x.durations.contextBootstrapMs),t.kit_app_info_ms=ai(x.durations.appInfoMs),t.kit_app_template_process_ms=ai(x.durations.appTemplateProcessMs),t.kit_view_template_process_ms=ai(x.durations.viewTemplateProcessMs),t.kit_plugin_bootstrap_ms=ai(x.durations.pluginBootstrapMs),t.kit_builder_init_ms=ai(x.durations.builderInitMs),t.kit_module_process_ms=ai(x.durations.moduleProcessMs),t.kit_asset_process_ms=ai(x.durations.assetProcessMs),t.kit_output_write_ms=ai(x.durations.outputWriteMs);else{t.kit_error_type=function(x){let e=r8(x,"code")?.toUpperCase();if(e){if(r2.has(e))return"permission_error";if(r3.has(e))return"dependency_error";if(r6.has(e))return"timeout_error";if(r4.has(e))return"network_error";if(r5.has(e))return"filesystem_error"}let t="string"==typeof x?x:r8(x,"message")??"";if(/cannot find module|can't resolve|cannot resolve|module not found|package .+ not found|无法解析以下候选包/i.test(t))return"dependency_error";if(/permission denied|operation not permitted/i.test(t))return"permission_error";if(/timed out|timeout/i.test(t))return"timeout_error";if(/connection (?:refused|reset)|getaddrinfo|network error|socket hang up|unable to connect/i.test(t))return"network_error";if(/no such file|file does not exist|not a directory|directory does not exist|配置的入口文件不存在/i.test(t))return"filesystem_error";if(/syntax\s*error|syntaxerror|unexpected token|failed to parse|pars(?:e|ing) error|解析 (?:tools\.json|manifest\.yaml) 失败/i.test(t))return"syntax_error";if(/\bTS\d{4}:|\btype\s*error\b|\btypeerror\b/i.test(t))return"type_error";if(/appId is required|entry config|invalid config|configuration (?:is )?(?:invalid|missing)|入口配置|(?:需要|提供) appId/i.test(t))return"config_error";if(/loader|加载器/i.test(t))return"loader_error";if(/plugin/i.test(t))return"plugin_error";let r=r8(x,"name");return r&&r7[r]||"unknown_error"}(x.error),x.errorStage&&(t.kit_error_stage=x.errorStage);let a=function(x){if("string"==typeof x)return x;if(!x||"object"!=typeof x||!("message"in x))return;let e=x.message;return"string"==typeof e?e:void 0}(x.error);if(a){var r;let x=(r=e.appDirectory,xN(a).replaceAll(y.resolve(r),"<project>").replaceAll(xn(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));x&&(t.kit_error_message=x)}}return{name:"kit_compile",params:t}}(t,{appDirectory:e}))}};function al(x,e,t){t?.hasErrors()?ao.report({appDirectory:x.appDirectory,context:x,scene:e,status:"failed",errorStage:"compile",error:r9(t)[0]}):ao.report({appDirectory:x.appDirectory,context:x,scene:e,status:"success",compileEndTime:Date.now()})}class ac{constructor(){this.assets={}}addAsset(x,e){this.assets[x]=e}deleteAsset(x){delete this.assets[x]}getAsset(x){return this.assets[x]}getAssets(){return this.assets}getManifestAsset(x){return this.getAsset(x)||(this.assets[x]=new ti(x,JSON.stringify({}))),this.getAsset(x)}}class av{options;constructor(x){this.options=x}apply(x){let e,{pluginSystem:t}=this.options;x.hooks.thisCompilation.tap({name:av.name,stage:x.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},r=>{r.hooks.processAssets.tapPromise({name:av.name,stage:x.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{e=new ac,r.getAssets().forEach(x=>{let t=new ts(x.name,x.source.source(),x.info.contenthash?.[0]);e.addAsset(x.name,t)});let{entrypoints:a}=r,_={};a.forEach((x,t)=>{_[t]=x.getFiles().map(x=>{let t=e.getAsset(x);if(!t)throw Error(`未找到构建产物 ${x}`);return new ts(t.source,t.content,t.hashCode)})});let n=this.options.context.appId;n&&B.mkdirSync(y.join(this.options.context.rootPath,n),{recursive:!0}),await t.callAssetsHooks("beforeEmit",{assets:e,chunks:_}),Object.keys(e.getAssets()).forEach(t=>{let a=e.getAsset(t);if(!a)return;let{source:_,destination:n}=a;if(!_||!n)return;r.getAsset(_)?r.renameAsset(_,n):r.emitAsset(n,new x.rspack.sources.RawSource(a.content));let A=r.getAsset(`${_}.map`);A&&r.renameAsset(A.name,`${n}.map`)}),await t.callAssetsHooks("afterEmit",{assets:{...e.getAssets()}})})})}}let ad=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class af{options;constructor(x){this.options=x}apply(x){x.hooks.thisCompilation.tap(af.name,x=>{x.hooks.finishModules.tap(af.name,()=>{let e=new Map,t=r=>{if(!r)return!1;let a=e.get(r);if(void 0!==a)return a;if(function(x){var e;let t=x.resourceResolveData?.descriptionFileData?.name;if("string"==typeof t&&ad.has(t))return!0;let r=(e=x.resource,e?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...ad].some(x=>r?.includes(`/node_modules/${x}/`))}(r))return e.set(r,!0),!0;for(let a of(e.set(r,!1),x.moduleGraph.getOutgoingConnections(r)))if(t(a.module))return e.set(r,!0),!0;return!1};x.entries.forEach((e,r)=>{e.dependencies.some(e=>t(x.moduleGraph.getModule(e)))&&this.options.markTemplateWidgetEntry(this.options.normalizeEntryName?.(r)??r)})})})}}class ab{options;constructor(x){this.options=x}apply(x){x.hooks.make.tapPromise(ab.name,async x=>{await this.options.pluginSystem.callViewHooks("collectMetaData",{collector:this.options.context.metadata}).catch(e=>x.errors.push(e))}),x.hooks.thisCompilation.tap(ab.name,x=>{x.hooks.optimizeTree.tapPromise(ab.name,async e=>{await this.options.pluginSystem.callViewHooks("build",{metadata:this.options.context.metadata,fileDependencies:x.fileDependencies}).catch(e=>x.errors.push(e))})}),x.hooks.done.tapPromise(ab.name,async x=>{await this.options.pluginSystem.callViewHooks("afterBuild",{stats:x})})}}function au(x){return x.replaceAll("\\","/")}function ap(x,e,t,r=`${e}.map`){return e!==t&&!!x.getAsset(e)&&(x.renameAsset(e,t),x.getAsset(r)&&x.renameAsset(r,`${t}.map`),!0)}class am{context;constructor(x){this.context=x}apply(x){x.hooks.thisCompilation.tap(am.name,e=>{e.hooks.processAssets.tapPromise({name:am.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{var x,t;let r=this.context.metadata.getData(),{pages:a,widgets:_}=this.context,n=r.app.appId||this.context.appId;if(!n&&Object.keys(a).length>0)throw Error("解析 Web 页面入口路径需要 appId");n&&(x=r.pages,Object.keys(a).forEach(t=>{let r=au(t),a=tG(r);ap(e,`${a}/template.js`,tc(n,x[t]?.path??tl(r),tT),`${a}/background.js.map`)})),t=r.widgets,Object.keys(_).forEach(x=>{var r;let a=tG(au(x));ap(e,`${a}/template.js`,(r=tO(_,t,x),`${r}/${tT}`),`${a}/background.js.map`)})})})}}class ah{entry;constructor(x){this.entry=x}apply(x){let e=new x.webpack.experiments.VirtualModulesPlugin;e.apply(x),x.hooks.thisCompilation.tap(ah.name,()=>{e.writeModule(e2,""),e.writeModule(e3,e6),Object.values(this.entry).forEach(x=>{e.writeModule(x.filename,x.toString())})})}}function aE(x,e){return x.isIdentifier(e)?e.text:x.isPropertyAccessExpression(e)?e.name.text:void 0}let aj={templatesByEntry:{},templatesByWidget:{}},ag="/doubao-apps-framework.template.js",ay="/doubao-apps-api.template.js",aS=(x,e,t="/assets/framework/")=>{let r=e?t.replace(/\/+$/,""):"",a=(x,t,a)=>({libraryName:a,url:`${r}${x}`,background:{sectionPath:t},mainThread:{sectionPath:`${t}__main-thread`},async:!!e});return{"@byted-doubao-apps/bridge-base":a(ay,"api"),"@byted-doubao-apps/open-api":a(ay,"api"),...Object.fromEntries(Object.entries(te).map(([e,t])=>[e,a(x?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",t])])),[`${tf}/api`]:a(ay,"api"),[`${tb}/api`]:a(ay,"api"),[tf]:a(ag,"framework"),[tb]:a(ag,"framework"),"@byted-doubao-apps/components":a(ag,"components"),[tp(tf)]:a(ag,"components"),[tp(tb)]:a(ag,"components")}},aI=u(import.meta.url);function aN(x,e){for(let t of x)try{return aI.resolve(t,{paths:e})}catch{}throw Error(`无法解析以下候选包:${x.join(", ")}`)}class aB{pluginSystem;constructor(x){this.pluginSystem=x}async createEntry(x){let{entry:e}=await this.pluginSystem.callViewHooks("modifyEntryOption",{entry:{}});return x.setPages(Object.fromEntries(Object.entries(x.pages).filter(([x])=>x in e))),x.setWidgets(Object.fromEntries(Object.entries(x.widgets).filter(([x])=>x in e))),e}async createConfig({config:x}){var e,t,r,a,_;let{context:n}=x,{appDirectory:A,command:s,metadata:i,rootPath:o}=n,l=x.context.environment,c="1"===process.env.ENABLE_SELF_CONTAINED;await this.pluginSystem.callViewHooks("modifyEnvironment",{environment:l}),x.context.setEnvironment(l);let v=s===x9.DEV,d=await this.createEntry(n),f=th(A),b=[A,y.dirname(xe(import.meta.url))],p=aI.resolve("@lynx-js/react/transform"),m=new Set([...Object.keys(x.context.widgets),...Object.keys(x.context.pages)]),h=m.size>0||n.normalizedAppConfig.tools.entryNames.length>0;h&&await rg({widgets:x.context.widgets,pages:x.context.pages,entries:d,collector:i,normalizedAppConfig:x.context.normalizedAppConfig,define:x.context.userConfig?.source?.define});let E={include:x.options.source?.include,exclude:x.options.source?.exclude,decorators:x.options.source?.decorators,define:{...x.options.source?.define,__DOUBAO__:JSON.stringify(!0),__MAIN_PROCESS__:JSON.stringify(!1),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__VERSION_TAG__:JSON.stringify(x.context.versionTag)??"undefined",__LEPUS__:JSON.stringify(!1),"process.env":"({})"}},j=x=>[e2,e3,x.filename],g={...E,entry:Object.fromEntries(Object.entries(d).map(([x,e])=>[x,j(e)]))},S=Object.fromEntries(Object.entries(d).filter(([x])=>m.has(x))),I=new Map(Object.keys(S).map(x=>[tG(x),x])),N={...g,entry:Object.fromEntries(Object.entries(S).map(([x,e])=>[tG(x),j(e)])),define:{...g.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},w=[...tw()?[]:[xc({externals:aS(v),globalObject:"lynx"})]],C=[function({metadata:x,resolveAppInfo:e,resolveVersionTag:t}){return{name:"ai-manifest-plugin",setup(r){r.modifyBundlerChain((r,a)=>{let _=a?.environment?.name==="web"?tL:tD;r.plugin(tq.name).use(tq,[{metadata:x,resolveAppInfo:e,resolveVersionTag:t,isNative:a?.environment?.name!=="web",shouldInjectAsset:_}])})}}}({metadata:i,resolveAppInfo:()=>x.context.resolveAppInfo(),resolveVersionTag:()=>x.context.versionTag})],P={source:{...g,define:{...g.define,...tw()?{__DOUBAO_APPS_SDK_VERSION__:JSON.stringify(aI(aI.resolve(`${f}/package.json`,{paths:[A]})).version)}:{}}},output:{distPath:{image:"base/static/image",svg:"base/static/svg"}},...!v?{tools:{rspack:{output:{publicPath:"/"}}}}:{},plugins:w},k=[function x({metadata:e,entry:t,lynxConfigs:r,resolveSigningEncryptionOptions:a,onProcessDuration:_}){return{name:x.name,setup(x){x.modifyBundlerChain((n,A)=>{if(A?.environment?.name==="web")return;let s=x.useExposed(Symbol.for("LynxTemplatePlugin"));n.plugin(rB.name).use(rB,[s.LynxTemplatePlugin,e,t,a,_,r])})}}}({metadata:i,entry:d,lynxConfigs:{internal:x.context.internal,config:x.context.appConfig.lynxConfig,entries:Object.fromEntries(Object.entries({...x.context.normalizedAppConfig.pages.entries,...x.context.normalizedAppConfig.widgets.entries}).map(([x,e])=>[x,e.lynxConfig]))},resolveSigningEncryptionOptions:()=>x.context.resolveSigningEncryptionOptions(),onProcessDuration:e=>{x.context.compileLifecycle.viewTemplateProcessDurationMs=Math.max(x.context.compileLifecycle.viewTemplateProcessDurationMs,e)}}),function({context:x,normalizeEntryName:e}){return{name:"template-widget-entry-plugin",setup(t){t.modifyBundlerChain((t,r)=>{let a=r?.environment?.name;t.plugin("template-widget-entry-plugin").use(af,[{markTemplateWidgetEntry:e=>{x.addTemplateWidgetEntry(e)},normalizeEntryName:x=>e?.(x,a)}])})}}}({context:x.context,normalizeEntryName:(x,e)=>"web"===e?I.get(x):x}),(e=this.pluginSystem,t=x.context,{name:"output-plugin",setup(x){let r={pluginSystem:e,context:t};x.modifyBundlerChain((x,e)=>{e?.environment?.name!=="web"&&x.plugin("output-plugin").use(av,[r])})}}),...s===x9.DEV&&h?[function({context:x}){let e;return x.getWidgetViewDataTemplates=async()=>{if(e)return e;try{e=function(x,e,t){let r=function(x){let e,t=u(y.join(x,"package.json"));try{e=t.resolve("typescript")}catch(x){return}return t(e)}(x);if(!r)return{templatesByEntry:{},templatesByWidget:{}};let a=[...new Set(Object.values(e).map(({filename:x})=>x))],_=r.createProgram({options:function(x,e){let t={allowJs:!0,checkJs:!1,jsx:x.JsxEmit.Preserve,noEmit:!0,skipLibCheck:!0,target:x.ScriptTarget.ESNext},r=x.findConfigFile(e,B.existsSync);if(!r)return t;let a=x.readConfigFile(r,x.sys.readFile);return a.error?t:{...x.parseJsonConfigFileContent(a.config,x.sys,y.dirname(r)).options,...t}}(r,x),rootNames:a}),n=_.getTypeChecker(),A=Object.fromEntries(Object.entries(e).map(([x,{filename:e}])=>{let t,a=_.getSourceFile(e);return[ew(x),a?(t={},!function x(e){if(r.isCallExpression(e)&&("getViewData"===aE(r,e.expression)||"useViewData"===aE(r,e.expression))&&e.typeArguments?.[0]){let x=n.getTypeFromTypeNode(e.typeArguments[0]);for(let a of n.getPropertiesOfType(x)){let _=a.valueDeclaration??a.declarations?.[0]??e;t[a.getName()]=function x(e,t,r,a,_){let n=(t.isUnion()?t.types:[t]).filter(x=>!(x.flags&(e.TypeFlags.Undefined|e.TypeFlags.Never)));if(n.some(x=>x.flags&e.TypeFlags.Null))return null;if(n.some(x=>x.flags&e.TypeFlags.StringLike))return"";if(n.some(x=>x.flags&(e.TypeFlags.NumberLike|e.TypeFlags.BigIntLike)))return 0;if(n.some(x=>x.flags&e.TypeFlags.BooleanLike))return!1;if(n.some(x=>r.isArrayType(x)||r.isTupleType(x)))return[];let A=n.find(x=>x.flags&e.TypeFlags.Object);if(!A||_.has(A))return{};_.add(A);let s=Object.fromEntries(r.getPropertiesOfType(A).map(t=>{let n=t.valueDeclaration??t.declarations?.[0]??a;return[t.getName(),x(e,r.getTypeOfSymbolAtLocation(t,n),r,n,_)]}));return _.delete(A),s}(r,n.getTypeOfSymbolAtLocation(a,_),n,_,new Set([x]))}}r.forEachChild(e,x)}(a),t):{}]})),s=Object.fromEntries(Object.keys(e).map(x=>{let r=ew(x);return[tO(e,t,x),A[r]??{}]}));return{templatesByEntry:A,templatesByWidget:s}}(x.appDirectory,x.widgets,x.metadata.getData().widgets)}catch{e=aj}return e},{name:"WidgetViewDataPlugin",setup(x){x.onAfterDevCompile(({stats:x})=>{x.hasErrors()||(e=void 0)})}}}({context:x.context})]:[],(({context:x,startDebug:e})=>({name:"DevServerLogPlugin",setup(t){let r,a=!1,_=!1,n=process.env.DEV_SERVER_HOST;if("dev"===t.context.action&&void 0!==n){let x=new URL(n),e="https:"===x.protocol?"wss":"ws";t.modifyEnvironmentConfig({order:"post",handler:(t,{mergeEnvironmentConfig:r})=>r(t,{dev:{assetPrefix:n,client:{host:x.hostname,port:x.port,protocol:e}},output:{assetPrefix:n}})}),t.modifyBundlerChain({order:"post",handler(t){let r=t.resolve.alias.get("@lynx-js/webpack-dev-transport/client");if("string"!=typeof r)return;let[a,_]=r.split("?"),n=new URLSearchParams(_);n.set("hostname",x.hostname),n.set("port",x.port),n.set("protocol",e),t.resolve.alias.set("@lynx-js/webpack-dev-transport/client",`${a}?${n}`)}})}t.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{server:{setup({server:x}){x.middlewares.use(r1)}}})),t.onAfterCreateCompiler(({compiler:e})=>{for(let t of"compilers"in e?e.compilers:[e])t.hooks.failed.tap("DevServerLogPlugin",e=>x.finishInitialDevCompile(e))}),t.onAfterDevCompile(async({stats:n})=>{if(n.hasErrors())return void x.finishInitialDevCompile(Error(n.toString({all:!1,errors:!0,colors:!1})));if(a)return;let{devServer:A}=t.context;A&&(a=!0,await e?.(A.port,x=>{_?x():r=x}),_||x.finishInitialDevCompile())}),t.onCloseDevServer(()=>{_=!0,x.devServerAbort.abort(),r?.(),r=void 0})}}))({context:x.context}),function({context:x}){let e="KitMonitorPlugin";return{name:e,setup(t){if(t.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.finishMake.tap(e,()=>{as(x.compileLifecycle,"moduleProcess",Date.now())}),r.hooks.emit.tap(e,()=>{as(x.compileLifecycle,"assetProcess",Date.now())}),r.hooks.failed.tap(e,e=>{ao.report({appDirectory:x.appDirectory,context:x,scene:x.compileLifecycle.scene??(x.command===x9.DEV?"dev_initial":x.command),status:"failed",errorStage:"compile",error:e})})}),x.command!==x9.DEV){let e=x.command;t.onBeforeBuild(()=>{let t=Date.now();aA(x.compileLifecycle,{scene:e,commandStartTime:x.compileLifecycle.commandStartTime??t,compileStartTime:t})}),t.onAfterBuild(({stats:t})=>{al(x,e,t)})}else t.onBeforeDevCompile(({isFirstCompile:e})=>{let t=Date.now();aA(x.compileLifecycle,{scene:e?"dev_initial":"hot_update",commandStartTime:e?x.compileLifecycle.commandStartTime??t:t,compileStartTime:t})}),t.onAfterDevCompile(({stats:e})=>{al(x,x.compileLifecycle.scene??"dev_initial",e)})}}}({context:x.context}),..."true"===process.env.BYTED_RSDOCTOR?[{name:"doubao-apps:byted-rsdoctor",setup(x){x.onBeforeCreateCompiler(({bundlerConfigs:x})=>{let{BytedRsdoctorPlugin:e}=aI(aN(["@byted/rsdoctor"],b));for(let t of x){let x=y.join(t.output?.path??"",`.rsdoctor-${t.name}`);t.plugins??=[],t.plugins.push(new e({disableClientServer:!0,supports:{banner:!0},output:{reportDir:x}}))}})}}]:[],(r=this.pluginSystem,a=x.context,{name:"view-hooks-plugin",setup(x){x.modifyBundlerChain((x,e)=>{e?.environment?.name==="web"||x.plugin("view-hooks-plugin").use(ab,[{pluginSystem:r,context:a}])})}}),(({getAppAssetPath:x,getAppMapAssetPath:e,engineVersion:t,metadata:r,resolveSigningEncryptionOptions:a,onProcessDuration:_})=>({name:"lynx:encode-worker",async setup(n){tC()||n.modifyBundlerChain((n,A)=>{A?.environment?.name!=="web"&&n.plugin(rN.name).use(rN,[{getAppAssetPath:x,getAppMapAssetPath:e,engineVersion:t,metadata:r,resolveSigningEncryptionOptions:a,onProcessDuration:_}]).end()})}}))({getAppAssetPath:()=>x.context.appAssetPath,getAppMapAssetPath:()=>x.context.appMapAssetPath,metadata:x.context.metadata,resolveSigningEncryptionOptions:()=>x.context.resolveSigningEncryptionOptions(),onProcessDuration:e=>{x.context.compileLifecycle.appTemplateProcessDurationMs+=e}}),...x.rsbuildPlugins||[]],D=[{name:"web-virtual-entry-plugin",setup(x){x.modifyBundlerChain((x,{environment:e})=>{"web"===e.name&&x.plugin(ah.name).use(ah,[S])})}},(_=x.context,{name:"web-output-plugin",setup(x){x.modifyBundlerChain({order:"post",handler(x,{environment:e}){if("web"===e.name){let e=".rspeedy/";for(let t of Object.keys(x.plugins.entries()??{}))t.startsWith("lynx:template-")&&x.plugin(t).tap(x=>{let t=x[0];return t?.intermediate?.startsWith(e)&&(t.intermediate=t.intermediate.slice(e.length)),x});x.plugins.has("lynx:sourcemap")&&x.plugin("lynx:sourcemap").tap(x=>{var e;let t,r=x[0];return r.ignoreList=[/^(?!file:\/\/\/)/,/\/(?:externals-loading-runtime|webpack\/runtime)(?:\/|$)/,/\/node_modules\//,/\.(?:css|less|sass|scss)(?:[?#]|$)/],e=_.appDirectory,t=y.resolve(e),r.moduleFilenameTemplate=({absoluteResourcePath:x,query:e=""})=>{let r=y.relative(t,x),a=".."!==r&&!r.startsWith(`..${y.sep}`)&&!y.isAbsolute(r),_=a?au(r):au(x).replace(/^\/+/,"");return`${a?"file":"webpack"}:///${_}${e}`},x}),x.plugin(am.name).use(am,[_])}}})}})],L=W({mode:s===x9.DEV?"development":"production",environments:h?{lynx:P,web:{source:N,output:{distPath:{css:"base/web-common",js:"base/web-common",image:"base/web-static/image",svg:"base/web-static/svg",font:"base/web-static/font",media:"base/web-static/media"},cleanDistPath:!1,filename:{assets:"[name]/web.bundle"},sourceMap:{js:!!v&&"cheap-module-source-map",css:!1}},plugins:[xc({externals:aS(s===x9.DEV,!0,x.options.frameworkPrefix),globalObject:"lynx"})]}}:{lynx:P},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(x,e,t=y.join(y.dirname(xe(import.meta.url)),"components-loader.js"),r=aN){for(let x of[y.join(y.dirname(xe(import.meta.url)),"../loader/components-loader/index.js"),t])if(F(x))return x;return r(e===tb?["@doubao-dev/kit/components-loader","@byted-doubao-apps/kit/components-loader"]:["@byted-doubao-apps/kit/components-loader","@doubao-dev/kit/components-loader"],x)}(b,f),options:{frameworkPackage:f,widgetEntryPaths:Object.values(x.context.widgets??{}).filter(({internal:x})=>!x).map(({filename:x})=>y.resolve(A,x))}}]},plugins:[new r0(Object.values(x.context.widgets??{}).filter(({internal:x})=>!x).map(({filename:x})=>y.resolve(A,x))),new xx.BannerPlugin({banner:'"use registerWorkletInternal";',raw:!0,entryOnly:!0,stage:xx.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE+1,test:/\.js$/})]}},source:{...E,entry:{}},server:{cors:!0,host:x.context.devServerHost,port:v&&process.env.DEV_SERVER_PORT?Number(process.env.DEV_SERVER_PORT):void 0},dev:{writeToDisk:ev(),hmr:s===x9.DEV},output:{distPath:{js:"base/common",root:o||"dist"},cleanDistPath:!1,filename:{bundle:"[name]/template.js"},dataUriLimit:5120},resolve:{alias:{...x.options.resolve?.alias||{}}},performance:{printFileSize:ev(),...tw()&&!c?{chunkSplit:{strategy:"split-by-experience"}}:{}},...c?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(x){xv({LAYERS:U,lazy:!1,rootPath:y.dirname(xe(import.meta.url))}).setup(x)}},{name:"set-server.printUrls-false",setup(x){x.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{server:{printUrls:!1}}))}},Y({compat:{componentsPkg:[],newRuntimePkg:f,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...tu]}}),{name:"pin-react-transform-path",pre:["lynx:react"],setup(x){x.modifyBundlerChain((x,{CHAIN_ID:e})=>{let t=x.module.rule(e.RULE.JS).oneOf(e.ONE_OF.JS_MAIN);for(let x of[U.BACKGROUND,U.MAIN_THREAD]){let e=t.oneOfs.get(x)?.uses.get(x);if(!e)throw Error(`未找到该层的 React 转换加载器:${x}`);e.tap(x=>({...x,transformPath:p}))}})}},function(x){let{compilerOptionsKeys:e=xo,configKeys:t=xl,validate:r=r_,dslPluginName2PkgName:a=rn,upgradeRspeedyLink:_="https://www.npmjs.com/package/upgrade-rspeedy"}=(void 0)??{};return r(x),{name:"lynx:config",async setup(r){r.expose(Symbol.for("lynx.config"),{config:x}),"rstest"!==r.context.callerName&&r.modifyBundlerChain(n=>{let A=r.useExposed(Symbol.for("LynxTemplatePlugin"));if(!A){let x="Rspeedy and plugins";throw Object.entries(a).forEach(([e,t])=>{r.isPluginExists(e)&&(x=t)}),Error(`\
231
+ `,{encoding:"utf8",flag:"wx",mode:384}),r}catch{return ax(e)??"anonymous-unpersisted"}}()){this.pendingCount=0,this.sdk=new ae.TeaSDK({app_id:944787,logLevel:"silent"}),this.controller=(0,at.httpPlugin)({channel:"cn",retry:2,timeout:2e3}),this.controller.on("end",({hasSucceed:x})=>{this.pendingCount=Math.max(0,this.pendingCount-1),this.sdk.logger.trace("Tea event upload completed, hasSucceed: %s",x),x||this.sdk.logger.warn("Tea event upload did not succeed")}),this.controller.on("submit-error",({message:x})=>{this.sdk.logger.warn("Tea event upload failed: %s",x??"unknown network error")}),this.controller.on("submit-timeout",()=>{this.sdk.logger.warn("Tea event upload timed out after %d ms",2e3)}),this.sdk.use(this.controller),this.sdk.config({user:{user_unique_id:x}})}async upload(x){this.pendingCount+=1;try{this.sdk.collect(x.name,x.params)}catch(x){throw this.pendingCount-=1,x}}async flush(x){0!==this.pendingCount&&await new Promise(e=>{let t=()=>{clearTimeout(r),this.controller.off("drain",t),e()},r=setTimeout(t,x);this.controller.once("drain",t)})}}function aa(x){return!!(x&&!/<%=?\s*appId\s*%>/.test(x))}function a_(x){return{scene:void 0,commandStartTime:x,compileStartTime:void 0,builderInitStartTime:void 0,compilePhaseEndTimes:{moduleProcess:void 0,assetProcess:void 0},prepareDurations:{configLoadMs:0,projectScanMs:0,contextBootstrapMs:0,pluginBootstrapMs:0,builderInitMs:0},appInfoDurationMs:0,appInfoMeasured:!1,appTemplateProcessDurationMs:0,viewTemplateProcessDurationMs:0,reported:!1}}function an(x,e){Object.assign(x,a_(e))}function aA(x,{scene:e,commandStartTime:t,compileStartTime:r}){let a=x.commandStartTime===t,_=x.prepareDurations,n=x.builderInitStartTime,A=x.appInfoDurationMs,s=x.appInfoMeasured;a&&void 0!==n&&(_.builderInitMs=Math.max(0,r-n)),an(x,t),x.scene=e,x.compileStartTime=r,a&&(x.prepareDurations=_,x.appInfoDurationMs=A,x.appInfoMeasured=s)}function as(x,e,t){x.compilePhaseEndTimes[e]=Math.max(x.compilePhaseEndTimes[e]??0,t)}function ai(x){return Math.max(0,Math.round(Number.isFinite(x)?x:0))}let ao=new class{uploader;constructor(x){this.uploader=x}async reportEvent(x){try{await (this.uploader??=new ar).upload({name:x.name,params:{...x.params,kit_version:"0.8.0-rc.2",kit_node_version:process.version,kit_os_name:process.platform,kit_run_env:(process.env.BUILD_VERSION?"SCM":process.env.CI_REPO_NAME?"CI":"LOCAL").toLowerCase()}})}catch{}}async report(x){try{var e,t;let r,a,_,n,A,s,i,o=x.context?.compileLifecycle;if(o){if(o.reported)return;o.reported=!0}let l="dev_initial"===x.scene||"hot_update"===x.scene?"dev":x.scene,c={appDirectory:x.appDirectory,targetAppId:function(x){try{let e=x?.appId;return aa(e)?e:void 0}catch{return}}(x.context),scene:x.scene,command:l},v="failed"===x.status?{...c,status:x.status,errorStage:x.errorStage,error:r9(x.error)[0]??x.error}:{...c,status:x.status,pageCount:Object.keys(x.context.pages).length,widgetCount:Object.keys(x.context.widgets).length,securityMode:(r=x.context.signingEncryptionOptions,a=!!r?.signing.enabled,_=!!r?.encryption.enabled,a&&_?"signing_and_encryption":a?"signing":_?"encryption":"none"),durations:(e=x.context.compileLifecycle,t=x.compileEndTime,n=e.commandStartTime??t,A=e.compileStartTime??t,s=Math.min(t,Math.max(A,e.compilePhaseEndTimes.moduleProcess??t)),i=Math.min(t,Math.max(s,e.compilePhaseEndTimes.assetProcess??t)),{totalMs:t-n,prepareMs:A-n,compileMs:t-A,...e.prepareDurations,appInfoMs:e.appInfoDurationMs,appTemplateProcessMs:e.appTemplateProcessDurationMs,viewTemplateProcessMs:e.viewTemplateProcessDurationMs,moduleProcessMs:s-A,assetProcessMs:i-s,outputWriteMs:t-i})};await this.upload(v)}catch{}}async flush(x=3e3){try{await this.uploader?.flush?.(x)}catch{}}async upload(x){let{appDirectory:e,...t}=x;await this.reportEvent(function(x,e){let t={kit_compile_id:function(){let x="unknown";try{x=xA().username||x}catch{}return`${Date.now()}_${x}_${xj()}`}(),kit_compile_scene:x.scene,kit_command:x.command,kit_status:x.status};if(x.targetAppId&&(t.kit_appId=x.targetAppId),"success"===x.status)t.kit_page_count=x.pageCount,t.kit_widget_count=x.widgetCount,t.kit_security_mode=x.securityMode,t.kit_duration_ms_total=ai(x.durations.totalMs),t.kit_prepare_ms=ai(x.durations.prepareMs),t.kit_compile_ms=ai(x.durations.compileMs),t.kit_config_load_ms=ai(x.durations.configLoadMs),t.kit_project_scan_ms=ai(x.durations.projectScanMs),t.kit_context_bootstrap_ms=ai(x.durations.contextBootstrapMs),t.kit_app_info_ms=ai(x.durations.appInfoMs),t.kit_app_template_process_ms=ai(x.durations.appTemplateProcessMs),t.kit_view_template_process_ms=ai(x.durations.viewTemplateProcessMs),t.kit_plugin_bootstrap_ms=ai(x.durations.pluginBootstrapMs),t.kit_builder_init_ms=ai(x.durations.builderInitMs),t.kit_module_process_ms=ai(x.durations.moduleProcessMs),t.kit_asset_process_ms=ai(x.durations.assetProcessMs),t.kit_output_write_ms=ai(x.durations.outputWriteMs);else{t.kit_error_type=function(x){let e=r8(x,"code")?.toUpperCase();if(e){if(r2.has(e))return"permission_error";if(r3.has(e))return"dependency_error";if(r6.has(e))return"timeout_error";if(r4.has(e))return"network_error";if(r5.has(e))return"filesystem_error"}let t="string"==typeof x?x:r8(x,"message")??"";if(/cannot find module|can't resolve|cannot resolve|module not found|package .+ not found|无法解析以下候选包/i.test(t))return"dependency_error";if(/permission denied|operation not permitted/i.test(t))return"permission_error";if(/timed out|timeout/i.test(t))return"timeout_error";if(/connection (?:refused|reset)|getaddrinfo|network error|socket hang up|unable to connect/i.test(t))return"network_error";if(/no such file|file does not exist|not a directory|directory does not exist|配置的入口文件不存在/i.test(t))return"filesystem_error";if(/syntax\s*error|syntaxerror|unexpected token|failed to parse|pars(?:e|ing) error|解析 (?:tools\.json|manifest\.yaml) 失败/i.test(t))return"syntax_error";if(/\bTS\d{4}:|\btype\s*error\b|\btypeerror\b/i.test(t))return"type_error";if(/appId is required|entry config|invalid config|configuration (?:is )?(?:invalid|missing)|入口配置|(?:需要|提供) appId/i.test(t))return"config_error";if(/loader|加载器/i.test(t))return"loader_error";if(/plugin/i.test(t))return"plugin_error";let r=r8(x,"name");return r&&r7[r]||"unknown_error"}(x.error),x.errorStage&&(t.kit_error_stage=x.errorStage);let a=function(x){if("string"==typeof x)return x;if(!x||"object"!=typeof x||!("message"in x))return;let e=x.message;return"string"==typeof e?e:void 0}(x.error);if(a){var r;let x=(r=e.appDirectory,xN(a).replaceAll(y.resolve(r),"<project>").replaceAll(xn(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));x&&(t.kit_error_message=x)}}return{name:"kit_compile",params:t}}(t,{appDirectory:e}))}};function al(x,e,t){t?.hasErrors()?ao.report({appDirectory:x.appDirectory,context:x,scene:e,status:"failed",errorStage:"compile",error:r9(t)[0]}):ao.report({appDirectory:x.appDirectory,context:x,scene:e,status:"success",compileEndTime:Date.now()})}class ac{constructor(){this.assets={}}addAsset(x,e){this.assets[x]=e}deleteAsset(x){delete this.assets[x]}getAsset(x){return this.assets[x]}getAssets(){return this.assets}getManifestAsset(x){return this.getAsset(x)||(this.assets[x]=new ti(x,JSON.stringify({}))),this.getAsset(x)}}class av{options;constructor(x){this.options=x}apply(x){let e,{pluginSystem:t}=this.options;x.hooks.thisCompilation.tap({name:av.name,stage:x.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},r=>{r.hooks.processAssets.tapPromise({name:av.name,stage:x.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{e=new ac,r.getAssets().forEach(x=>{let t=new ts(x.name,x.source.source(),x.info.contenthash?.[0]);e.addAsset(x.name,t)});let{entrypoints:a}=r,_={};a.forEach((x,t)=>{_[t]=x.getFiles().map(x=>{let t=e.getAsset(x);if(!t)throw Error(`未找到构建产物 ${x}`);return new ts(t.source,t.content,t.hashCode)})});let n=this.options.context.appId;n&&B.mkdirSync(y.join(this.options.context.rootPath,n),{recursive:!0}),await t.callAssetsHooks("beforeEmit",{assets:e,chunks:_}),Object.keys(e.getAssets()).forEach(t=>{let a=e.getAsset(t);if(!a)return;let{source:_,destination:n}=a;if(!_||!n)return;r.getAsset(_)?r.renameAsset(_,n):r.emitAsset(n,new x.rspack.sources.RawSource(a.content));let A=r.getAsset(`${_}.map`);A&&r.renameAsset(A.name,`${n}.map`)}),await t.callAssetsHooks("afterEmit",{assets:{...e.getAssets()}})})})}}let ad=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class af{options;constructor(x){this.options=x}apply(x){x.hooks.thisCompilation.tap(af.name,x=>{x.hooks.finishModules.tap(af.name,()=>{let e=new Map,t=r=>{if(!r)return!1;let a=e.get(r);if(void 0!==a)return a;if(function(x){var e;let t=x.resourceResolveData?.descriptionFileData?.name;if("string"==typeof t&&ad.has(t))return!0;let r=(e=x.resource,e?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...ad].some(x=>r?.includes(`/node_modules/${x}/`))}(r))return e.set(r,!0),!0;for(let a of(e.set(r,!1),x.moduleGraph.getOutgoingConnections(r)))if(t(a.module))return e.set(r,!0),!0;return!1};x.entries.forEach((e,r)=>{e.dependencies.some(e=>t(x.moduleGraph.getModule(e)))&&this.options.markTemplateWidgetEntry(this.options.normalizeEntryName?.(r)??r)})})})}}class ab{options;constructor(x){this.options=x}apply(x){x.hooks.make.tapPromise(ab.name,async x=>{await this.options.pluginSystem.callViewHooks("collectMetaData",{collector:this.options.context.metadata}).catch(e=>x.errors.push(e))}),x.hooks.thisCompilation.tap(ab.name,x=>{x.hooks.optimizeTree.tapPromise(ab.name,async e=>{await this.options.pluginSystem.callViewHooks("build",{metadata:this.options.context.metadata,fileDependencies:x.fileDependencies}).catch(e=>x.errors.push(e))})}),x.hooks.done.tapPromise(ab.name,async x=>{await this.options.pluginSystem.callViewHooks("afterBuild",{stats:x})})}}function au(x){return x.replaceAll("\\","/")}function ap(x,e,t,r=`${e}.map`){return e!==t&&!!x.getAsset(e)&&(x.renameAsset(e,t),x.getAsset(r)&&x.renameAsset(r,`${t}.map`),!0)}class am{context;constructor(x){this.context=x}apply(x){x.hooks.thisCompilation.tap(am.name,e=>{e.hooks.processAssets.tapPromise({name:am.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{var x,t;let r=this.context.metadata.getData(),{pages:a,widgets:_}=this.context,n=r.app.appId||this.context.appId;if(!n&&Object.keys(a).length>0)throw Error("解析 Web 页面入口路径需要 appId");n&&(x=r.pages,Object.keys(a).forEach(t=>{let r=au(t),a=tG(r);ap(e,`${a}/template.js`,tc(n,x[t]?.path??tl(r),tT),`${a}/background.js.map`)})),t=r.widgets,Object.keys(_).forEach(x=>{var r;let a=tG(au(x));ap(e,`${a}/template.js`,(r=tO(_,t,x),`${r}/${tT}`),`${a}/background.js.map`)})})})}}class ah{entry;constructor(x){this.entry=x}apply(x){let e=new x.webpack.experiments.VirtualModulesPlugin;e.apply(x),x.hooks.thisCompilation.tap(ah.name,()=>{e.writeModule(e2,""),e.writeModule(e3,e6),Object.values(this.entry).forEach(x=>{e.writeModule(x.filename,x.toString())})})}}function aE(x,e){return x.isIdentifier(e)?e.text:x.isPropertyAccessExpression(e)?e.name.text:void 0}let aj={templatesByEntry:{},templatesByWidget:{}},ag="/doubao-apps-framework.template.js",ay="/doubao-apps-api.template.js",aS=(x,e,t="/assets/framework/")=>{let r=e?t.replace(/\/+$/,""):"",a=(x,t,a)=>({libraryName:a,url:`${r}${x}`,background:{sectionPath:t},mainThread:{sectionPath:`${t}__main-thread`},async:!!e});return{"@byted-doubao-apps/bridge-base":a(ay,"api"),"@byted-doubao-apps/open-api":a(ay,"api"),...Object.fromEntries(Object.entries(te).map(([e,t])=>[e,a(x?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",t])])),[`${tf}/api`]:a(ay,"api"),[`${tb}/api`]:a(ay,"api"),[tf]:a(ag,"framework"),[tb]:a(ag,"framework"),"@byted-doubao-apps/components":a(ag,"components"),[tp(tf)]:a(ag,"components"),[tp(tb)]:a(ag,"components")}},aI=u(import.meta.url);function aN(x,e){for(let t of x)try{return aI.resolve(t,{paths:e})}catch{}throw Error(`无法解析以下候选包:${x.join(", ")}`)}class aB{pluginSystem;constructor(x){this.pluginSystem=x}async createEntry(x){let{entry:e}=await this.pluginSystem.callViewHooks("modifyEntryOption",{entry:{}});return x.setPages(Object.fromEntries(Object.entries(x.pages).filter(([x])=>x in e))),x.setWidgets(Object.fromEntries(Object.entries(x.widgets).filter(([x])=>x in e))),e}async createConfig({config:x}){var e,t,r,a,_;let{context:n}=x,{appDirectory:A,command:s,metadata:i,rootPath:o}=n,l=x.context.environment,c="1"===process.env.ENABLE_SELF_CONTAINED;await this.pluginSystem.callViewHooks("modifyEnvironment",{environment:l}),x.context.setEnvironment(l);let v=s===x9.DEV,d=await this.createEntry(n),f=th(A),b=[A,y.dirname(xe(import.meta.url))],p=aI.resolve("@lynx-js/react/transform"),m=new Set([...Object.keys(x.context.widgets),...Object.keys(x.context.pages)]),h=m.size>0||n.normalizedAppConfig.tools.entryNames.length>0;h&&await rg({widgets:x.context.widgets,pages:x.context.pages,entries:d,collector:i,normalizedAppConfig:x.context.normalizedAppConfig,define:x.context.userConfig?.source?.define});let E={include:x.options.source?.include,exclude:x.options.source?.exclude,decorators:x.options.source?.decorators,define:{...x.options.source?.define,__DOUBAO__:JSON.stringify(!0),__MAIN_PROCESS__:JSON.stringify(!1),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__VERSION_TAG__:JSON.stringify(x.context.versionTag)??"undefined",__LEPUS__:JSON.stringify(!1),"process.env":"({})"}},j=x=>[e2,e3,x.filename],g={...E,entry:Object.fromEntries(Object.entries(d).map(([x,e])=>[x,j(e)]))},S=Object.fromEntries(Object.entries(d).filter(([x])=>m.has(x))),I=new Map(Object.keys(S).map(x=>[tG(x),x])),N={...g,entry:Object.fromEntries(Object.entries(S).map(([x,e])=>[tG(x),j(e)])),define:{...g.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},w=[...tw()?[]:[xc({externals:aS(v),globalObject:"lynx"})]],C=[function({metadata:x,resolveAppInfo:e,resolveVersionTag:t}){return{name:"ai-manifest-plugin",setup(r){r.modifyBundlerChain((r,a)=>{let _=a?.environment?.name==="web"?tL:tD;r.plugin(tq.name).use(tq,[{metadata:x,resolveAppInfo:e,resolveVersionTag:t,isNative:a?.environment?.name!=="web",shouldInjectAsset:_}])})}}}({metadata:i,resolveAppInfo:()=>x.context.resolveAppInfo(),resolveVersionTag:()=>x.context.versionTag})],P={source:{...g,define:{...g.define,...tw()?{__DOUBAO_APPS_SDK_VERSION__:JSON.stringify(aI(aI.resolve(`${f}/package.json`,{paths:[A]})).version)}:{}}},output:{distPath:{image:"base/static/image",svg:"base/static/svg"}},...!v?{tools:{rspack:{output:{publicPath:"/"}}}}:{},plugins:w},k=[function x({metadata:e,entry:t,lynxConfigs:r,resolveSigningEncryptionOptions:a,onProcessDuration:_}){return{name:x.name,setup(x){x.modifyBundlerChain((n,A)=>{if(A?.environment?.name==="web")return;let s=x.useExposed(Symbol.for("LynxTemplatePlugin"));n.plugin(rB.name).use(rB,[s.LynxTemplatePlugin,e,t,a,_,r])})}}}({metadata:i,entry:d,lynxConfigs:{internal:x.context.internal,config:x.context.appConfig.lynxConfig,entries:Object.fromEntries(Object.entries({...x.context.normalizedAppConfig.pages.entries,...x.context.normalizedAppConfig.widgets.entries}).map(([x,e])=>[x,e.lynxConfig]))},resolveSigningEncryptionOptions:()=>x.context.resolveSigningEncryptionOptions(),onProcessDuration:e=>{x.context.compileLifecycle.viewTemplateProcessDurationMs=Math.max(x.context.compileLifecycle.viewTemplateProcessDurationMs,e)}}),function({context:x,normalizeEntryName:e}){return{name:"template-widget-entry-plugin",setup(t){t.modifyBundlerChain((t,r)=>{let a=r?.environment?.name;t.plugin("template-widget-entry-plugin").use(af,[{markTemplateWidgetEntry:e=>{x.addTemplateWidgetEntry(e)},normalizeEntryName:x=>e?.(x,a)}])})}}}({context:x.context,normalizeEntryName:(x,e)=>"web"===e?I.get(x):x}),(e=this.pluginSystem,t=x.context,{name:"output-plugin",setup(x){let r={pluginSystem:e,context:t};x.modifyBundlerChain((x,e)=>{e?.environment?.name!=="web"&&x.plugin("output-plugin").use(av,[r])})}}),...s===x9.DEV&&h?[function({context:x}){let e;return x.getWidgetViewDataTemplates=async()=>{if(e)return e;try{e=function(x,e,t){let r=function(x){let e,t=u(y.join(x,"package.json"));try{e=t.resolve("typescript")}catch(x){return}return t(e)}(x);if(!r)return{templatesByEntry:{},templatesByWidget:{}};let a=[...new Set(Object.values(e).map(({filename:x})=>x))],_=r.createProgram({options:function(x,e){let t={allowJs:!0,checkJs:!1,jsx:x.JsxEmit.Preserve,noEmit:!0,skipLibCheck:!0,target:x.ScriptTarget.ESNext},r=x.findConfigFile(e,B.existsSync);if(!r)return t;let a=x.readConfigFile(r,x.sys.readFile);return a.error?t:{...x.parseJsonConfigFileContent(a.config,x.sys,y.dirname(r)).options,...t}}(r,x),rootNames:a}),n=_.getTypeChecker(),A=Object.fromEntries(Object.entries(e).map(([x,{filename:e}])=>{let t,a=_.getSourceFile(e);return[ew(x),a?(t={},!function x(e){if(r.isCallExpression(e)&&("getViewData"===aE(r,e.expression)||"useViewData"===aE(r,e.expression))&&e.typeArguments?.[0]){let x=n.getTypeFromTypeNode(e.typeArguments[0]);for(let a of n.getPropertiesOfType(x)){let _=a.valueDeclaration??a.declarations?.[0]??e;t[a.getName()]=function x(e,t,r,a,_){let n=(t.isUnion()?t.types:[t]).filter(x=>!(x.flags&(e.TypeFlags.Undefined|e.TypeFlags.Never)));if(n.some(x=>x.flags&e.TypeFlags.Null))return null;if(n.some(x=>x.flags&e.TypeFlags.StringLike))return"";if(n.some(x=>x.flags&(e.TypeFlags.NumberLike|e.TypeFlags.BigIntLike)))return 0;if(n.some(x=>x.flags&e.TypeFlags.BooleanLike))return!1;if(n.some(x=>r.isArrayType(x)||r.isTupleType(x)))return[];let A=n.find(x=>x.flags&e.TypeFlags.Object);if(!A||_.has(A))return{};_.add(A);let s=Object.fromEntries(r.getPropertiesOfType(A).map(t=>{let n=t.valueDeclaration??t.declarations?.[0]??a;return[t.getName(),x(e,r.getTypeOfSymbolAtLocation(t,n),r,n,_)]}));return _.delete(A),s}(r,n.getTypeOfSymbolAtLocation(a,_),n,_,new Set([x]))}}r.forEachChild(e,x)}(a),t):{}]})),s=Object.fromEntries(Object.keys(e).map(x=>{let r=ew(x);return[tO(e,t,x),A[r]??{}]}));return{templatesByEntry:A,templatesByWidget:s}}(x.appDirectory,x.widgets,x.metadata.getData().widgets)}catch{e=aj}return e},{name:"WidgetViewDataPlugin",setup(x){x.onAfterDevCompile(({stats:x})=>{x.hasErrors()||(e=void 0)})}}}({context:x.context})]:[],(({context:x,startDebug:e})=>({name:"DevServerLogPlugin",setup(t){let r,a=!1,_=!1,n=process.env.DEV_SERVER_HOST;if("dev"===t.context.action&&void 0!==n){let x=new URL(n),e="https:"===x.protocol?"wss":"ws";t.modifyEnvironmentConfig({order:"post",handler:(t,{mergeEnvironmentConfig:r})=>r(t,{dev:{assetPrefix:n,client:{host:x.hostname,port:x.port,protocol:e}},output:{assetPrefix:n}})}),t.modifyBundlerChain({order:"post",handler(t){let r=t.resolve.alias.get("@lynx-js/webpack-dev-transport/client");if("string"!=typeof r)return;let[a,_]=r.split("?"),n=new URLSearchParams(_);n.set("hostname",x.hostname),n.set("port",x.port),n.set("protocol",e),t.resolve.alias.set("@lynx-js/webpack-dev-transport/client",`${a}?${n}`)}})}t.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{server:{setup({server:x}){x.middlewares.use(r1)}}})),t.onAfterCreateCompiler(({compiler:e})=>{for(let t of"compilers"in e?e.compilers:[e])t.hooks.failed.tap("DevServerLogPlugin",e=>x.finishInitialDevCompile(e))}),t.onAfterDevCompile(async({stats:n})=>{if(n.hasErrors())return void x.finishInitialDevCompile(Error(n.toString({all:!1,errors:!0,colors:!1})));if(a)return;let{devServer:A}=t.context;A&&(a=!0,await e?.(A.port,x=>{_?x():r=x}),_||x.finishInitialDevCompile())}),t.onCloseDevServer(()=>{_=!0,x.devServerAbort.abort(),r?.(),r=void 0})}}))({context:x.context}),function({context:x}){let e="KitMonitorPlugin";return{name:e,setup(t){if(t.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.finishMake.tap(e,()=>{as(x.compileLifecycle,"moduleProcess",Date.now())}),r.hooks.emit.tap(e,()=>{as(x.compileLifecycle,"assetProcess",Date.now())}),r.hooks.failed.tap(e,e=>{ao.report({appDirectory:x.appDirectory,context:x,scene:x.compileLifecycle.scene??(x.command===x9.DEV?"dev_initial":x.command),status:"failed",errorStage:"compile",error:e})})}),x.command!==x9.DEV){let e=x.command;t.onBeforeBuild(()=>{let t=Date.now();aA(x.compileLifecycle,{scene:e,commandStartTime:x.compileLifecycle.commandStartTime??t,compileStartTime:t})}),t.onAfterBuild(({stats:t})=>{al(x,e,t)})}else t.onBeforeDevCompile(({isFirstCompile:e})=>{let t=Date.now();aA(x.compileLifecycle,{scene:e?"dev_initial":"hot_update",commandStartTime:e?x.compileLifecycle.commandStartTime??t:t,compileStartTime:t})}),t.onAfterDevCompile(({stats:e})=>{al(x,x.compileLifecycle.scene??"dev_initial",e)})}}}({context:x.context}),..."true"===process.env.BYTED_RSDOCTOR?[{name:"doubao-apps:byted-rsdoctor",setup(x){x.onBeforeCreateCompiler(({bundlerConfigs:x})=>{let{BytedRsdoctorPlugin:e}=aI(aN(["@byted/rsdoctor"],b));for(let t of x){let x=y.join(t.output?.path??"",`.rsdoctor-${t.name}`);t.plugins??=[],t.plugins.push(new e({disableClientServer:!0,supports:{banner:!0},output:{reportDir:x}}))}})}}]:[],(r=this.pluginSystem,a=x.context,{name:"view-hooks-plugin",setup(x){x.modifyBundlerChain((x,e)=>{e?.environment?.name==="web"||x.plugin("view-hooks-plugin").use(ab,[{pluginSystem:r,context:a}])})}}),(({getAppAssetPath:x,getAppMapAssetPath:e,engineVersion:t,metadata:r,resolveSigningEncryptionOptions:a,onProcessDuration:_})=>({name:"lynx:encode-worker",async setup(n){tC()||n.modifyBundlerChain((n,A)=>{A?.environment?.name!=="web"&&n.plugin(rN.name).use(rN,[{getAppAssetPath:x,getAppMapAssetPath:e,engineVersion:t,metadata:r,resolveSigningEncryptionOptions:a,onProcessDuration:_}]).end()})}}))({getAppAssetPath:()=>x.context.appAssetPath,getAppMapAssetPath:()=>x.context.appMapAssetPath,metadata:x.context.metadata,resolveSigningEncryptionOptions:()=>x.context.resolveSigningEncryptionOptions(),onProcessDuration:e=>{x.context.compileLifecycle.appTemplateProcessDurationMs+=e}}),...x.rsbuildPlugins||[]],D=[{name:"web-virtual-entry-plugin",setup(x){x.modifyBundlerChain((x,{environment:e})=>{"web"===e.name&&x.plugin(ah.name).use(ah,[S])})}},(_=x.context,{name:"web-output-plugin",setup(x){x.modifyBundlerChain({order:"post",handler(x,{environment:e}){if("web"===e.name){let e=".rspeedy/";for(let t of Object.keys(x.plugins.entries()??{}))t.startsWith("lynx:template-")&&x.plugin(t).tap(x=>{let t=x[0];return t?.intermediate?.startsWith(e)&&(t.intermediate=t.intermediate.slice(e.length)),x});x.plugins.has("lynx:sourcemap")&&x.plugin("lynx:sourcemap").tap(x=>{var e;let t,r=x[0];return r.ignoreList=[/^(?!file:\/\/\/)/,/\/(?:externals-loading-runtime|webpack\/runtime)(?:\/|$)/,/\/node_modules\//,/\.(?:css|less|sass|scss)(?:[?#]|$)/],e=_.appDirectory,t=y.resolve(e),r.moduleFilenameTemplate=({absoluteResourcePath:x,query:e=""})=>{let r=y.relative(t,x),a=".."!==r&&!r.startsWith(`..${y.sep}`)&&!y.isAbsolute(r),_=a?au(r):au(x).replace(/^\/+/,"");return`${a?"file":"webpack"}:///${_}${e}`},x}),x.plugin(am.name).use(am,[_])}}})}})],L=W({mode:s===x9.DEV?"development":"production",environments:h?{lynx:P,web:{source:N,output:{distPath:{css:"base/web-common",js:"base/web-common",image:"base/web-static/image",svg:"base/web-static/svg",font:"base/web-static/font",media:"base/web-static/media"},cleanDistPath:!1,filename:{assets:"[name]/web.bundle"},sourceMap:{js:!!v&&"cheap-module-source-map",css:!1}},plugins:[xc({externals:aS(s===x9.DEV,!0,x.options.frameworkPrefix),globalObject:"lynx"})]}}:{lynx:P},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(x,e,t=y.join(y.dirname(xe(import.meta.url)),"components-loader.js"),r=aN){for(let x of[y.join(y.dirname(xe(import.meta.url)),"../loader/components-loader/index.js"),t])if(F(x))return x;return r(e===tb?["@doubao-dev/kit/components-loader","@byted-doubao-apps/kit/components-loader"]:["@byted-doubao-apps/kit/components-loader","@doubao-dev/kit/components-loader"],x)}(b,f),options:{frameworkPackage:f,widgetEntryPaths:Object.values(x.context.widgets??{}).filter(({internal:x})=>!x).map(({filename:x})=>y.resolve(A,x))}}]},plugins:[new r0(Object.values(x.context.widgets??{}).filter(({internal:x})=>!x).map(({filename:x})=>y.resolve(A,x))),new xx.BannerPlugin({banner:'"use registerWorkletInternal";',raw:!0,entryOnly:!0,stage:xx.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE+1,test:/\.js$/})]}},source:{...E,entry:{}},server:{cors:!0,host:x.context.devServerHost,port:v&&process.env.DEV_SERVER_PORT?Number(process.env.DEV_SERVER_PORT):void 0},dev:{writeToDisk:ev(),hmr:s===x9.DEV},output:{distPath:{js:"base/common",root:o||"dist"},cleanDistPath:!1,filename:{bundle:"[name]/template.js"},dataUriLimit:5120},resolve:{alias:{...x.options.resolve?.alias||{}}},performance:{printFileSize:ev(),...tw()&&!c?{chunkSplit:{strategy:"split-by-experience"}}:{}},...c?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(x){xv({LAYERS:U,lazy:!1,rootPath:y.dirname(xe(import.meta.url))}).setup(x)}},{name:"set-server.printUrls-false",setup(x){x.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{server:{printUrls:!1}}))}},Y({experimental_reEvalJSOnReload:"1"!==process.env.DISABLE_RE_EVAL_JS_ON_RELOAD,compat:{componentsPkg:[],newRuntimePkg:f,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...tu]}}),{name:"pin-react-transform-path",pre:["lynx:react"],setup(x){x.modifyBundlerChain((x,{CHAIN_ID:e})=>{let t=x.module.rule(e.RULE.JS).oneOf(e.ONE_OF.JS_MAIN);for(let x of[U.BACKGROUND,U.MAIN_THREAD]){let e=t.oneOfs.get(x)?.uses.get(x);if(!e)throw Error(`未找到该层的 React 转换加载器:${x}`);e.tap(x=>({...x,transformPath:p}))}})}},function(x){let{compilerOptionsKeys:e=xo,configKeys:t=xl,validate:r=r_,dslPluginName2PkgName:a=rn,upgradeRspeedyLink:_="https://www.npmjs.com/package/upgrade-rspeedy"}=(void 0)??{};return r(x),{name:"lynx:config",async setup(r){r.expose(Symbol.for("lynx.config"),{config:x}),"rstest"!==r.context.callerName&&r.modifyBundlerChain(n=>{let A=r.useExposed(Symbol.for("LynxTemplatePlugin"));if(!A){let x="Rspeedy and plugins";throw Object.entries(a).forEach(([e,t])=>{r.isPluginExists(e)&&(x=t)}),Error(`\
232
232
  [pluginLynxConfig] No \`LynxTemplatePlugin\` exposed to ${t5("the plugin API","https://rsbuild.rs/plugins/dev/core#apiexpose")}.
233
233
 
234
234
  Please upgrade ${x} to latest version.
@@ -393,7 +393,7 @@ data: ${JSON.stringify({jsonrpc:"2.0",id:E,result:{resultType:"complete",_meta:{
393
393
  `),g=!0;try{v?.()}catch(x){t?.(x instanceof Error?x:Error(String(x)))}void 0!==d&&clearInterval(d),f?.(),_.delete(I);try{c.close()}catch{}}},N=new ReadableStream({start(x){c=x;let t=pc({method:"notifications/subscriptions/acknowledged",params:{notifications:h}},E);S(t.method,t.params),v=e.subscribe(x=>{if(g||!function(x,e){switch(e.kind){case"tools_list_changed":return!0===x.toolsListChanged;case"prompts_list_changed":return!0===x.promptsListChanged;case"resources_list_changed":return!0===x.resourcesListChanged;case"resource_updated":return void 0!==x.resourceSubscriptions&&x.resourceSubscriptions.includes(e.uri)}}(h,x))return;let e=pc(function(x){switch(x.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:x.uri}}}}(x),E);S(e.method,e.params)}),d=pi(a,()=>y(": keepalive\n\n")),_.add(I)},cancel(){I(!1)}});if(void 0!==n)if(n.aborted)I(!1);else{let x=()=>I(!1);n.addEventListener("abort",x,{once:!0}),f=()=>n.removeEventListener("abort",x)}return new Response(N,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let x of _)x(!0)},get openCount(){return _.size}}}({bus:v,maxSubscriptions:e.maxSubscriptions??1024,keepAliveMs:e.keepAliveMs??15e3,onerror:c});"json"===_&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let b="reject"===r?void 0:(t=e.keepAliveMs,async(e,r)=>{if("POST"!==e.method.toUpperCase())return pC(405,-32e3,"Method not allowed.");try{let a=await x({era:"legacy",...r?.authInfo!==void 0&&{authInfo:r.authInfo},requestInfo:e}),_=new pF({sessionIdGenerator:void 0,...void 0!==t&&{keepAliveMs:t}});await a.connect(_);let n=()=>{_.close().catch(()=>{}),a.close().catch(()=>{})};e.signal?.addEventListener("abort",n,{once:!0});let A=await _.handleRequest(e,{...r?.authInfo!==void 0&&{authInfo:r.authInfo},...r?.parsedBody!==void 0&&{parsedBody:r.parsedBody}});if(null===A.body||"text/event-stream"!==bh(A.headers.get("content-type")))return n(),A;let s=A.body.getReader(),i=!1,o=()=>{i||(i=!0,n())},l=new ReadableStream({pull:async x=>{try{let{done:e,value:t}=await s.read();if(e){o(),x.close();return}void 0!==t&&x.enqueue(t)}catch(e){o(),x.error(e)}},cancel:x=>(o(),s.cancel(x).catch(()=>{}))});return new Response(l,{status:A.status,statusText:A.statusText,headers:A.headers})}catch(x){try{c?.(pk(x))}catch{}return pD(pw(r?.parsedBody))}});async function u(t,r,a){var l,v;let d=t.classification.revision;if(void 0===d||!dT.includes(d)){let x=new f_({supported:[...dT],requested:d??"unknown"});return c(x),pC(400,x.code,x.message,x.data,pw(t.message))}let b=function(x,e){if("request"!==e.messageKind)return;let t=e.message.method;if(void 0===x.mcpMethodHeader)return fz("method-header-missing","(missing)",`the body names method ${t} but the required Mcp-Method header is absent`,"standard-header-validation");let r=Object.hasOwn(fW,t)?fW[t]:void 0;if(void 0===r)return;let a=e.message.params?.[r],_="string"==typeof a?a:void 0;if(void 0===x.mcpNameHeader){if(void 0===_)return;return fz("name-header-missing","(missing)",`the body carries params.${r}="${_}" but the required Mcp-Name header is absent`,"standard-header-validation")}let n=f0(x.mcpNameHeader),A=fJ(n);return void 0===A?fz("name-header-invalid-encoding",n,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==_&&A!==_?fz("name-header-mismatch",n,`the body carries params.${r}="${_}" but the Mcp-Name header names "${A}"`,"standard-header-validation"):void 0}({httpMethod:r.method,mcpMethodHeader:r.headers.get("mcp-method")??void 0,mcpNameHeader:r.headers.get("mcp-name")??void 0},t);if(void 0!==b)return c(Error(`Rejected inbound request (${b.cell}): ${b.message}`)),pP(b,pw(t.message));let u="request"===t.messageKind?fB(t.message.params):void 0,p=u?.[lq];if("request"===t.messageKind){let x=Object.hasOwn(dk,l=t.message.method)?dk[l]:void 0;if(void 0!==x){let e=dL(x,p);if(void 0!==e){let x=new fn({requiredCapabilities:e});return c(x),pC(fU[x.code]??400,x.code,x.message,x.data,t.message.id)}}}let m=await x({era:"modern",...void 0!==a&&{authInfo:a},requestInfo:r}),h=m instanceof pp?m.server:m;if("request"===t.messageKind&&"subscriptions/listen"===t.message.method){let x=h.getCapabilities(),e=o(h);return m.close().catch(c),f.serve(t.message,r.signal,x,e)}if("request"===t.messageKind&&"tools/call"===t.message.method&&m instanceof pp){let x=t.message.params,e="string"==typeof x?.name?x.name:void 0,a=void 0===e?void 0:m.toolInputSchemaJson(e);if(void 0!==a){let e=fO(a);if(e.valid&&e.declarations.length>0){let a=function(x,e,t){for(let r of x){let x=`Mcp-Param-${r.headerName}`,a=t.get(x),_=function(x,e){let t=x;for(let x of e){if(null===t||"object"!=typeof t)return;t=t[x]}return t}(e,r.path);if(null==_)continue;let n=function(x){if("string"==typeof x)return x;if("boolean"==typeof x)return x?"true":"false";if("number"==typeof x){if(!Number.isFinite(x)||Number.isInteger(x)&&!Number.isSafeInteger(x))return;return String(x)}}(_);if(void 0===n)continue;if(null===a)return fV("param-header-missing",x,`the body carries ${fQ(r.path)}=${JSON.stringify(_)} but the ${x} header is absent`);let A=fJ(a);if(void 0===A)return fV("param-header-invalid-encoding",x,`the ${x} header carries an invalid Base64 sentinel value`);if(!(("integer"===r.type||"number"===r.type)&&fM.test(A)&&"number"==typeof _?Number(A)===_:A===n))return fV("param-header-mismatch",x,`the ${x} header decodes to ${JSON.stringify(A)} but the body carries ${fQ(r.path)}=${JSON.stringify(_)}`)}}(e.declarations,x?.arguments,r.headers);if(void 0!==a)return m.close().catch(c),c(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),pP(a,t.message.id)}}}A(h,d),i(h,dT),void 0!==u&&(v={clientInfo:u[lD],clientCapabilities:p},s(h,v));let E=h.onclose;n.add(h),h.onclose=()=>{n.delete(h),E?.()};try{let x=await pB(m,t.message,{classification:t.classification,request:r,...void 0!==a&&{authInfo:a},...void 0!==_&&{responseMode:_},...void 0!==e.keepAliveMs&&{keepAliveMs:e.keepAliveMs}});return"notification"===t.messageKind&&queueMicrotask(()=>void h.close().catch(()=>{})),x}catch(x){if(x instanceof dP&&x.code===dC.ConnectionClosed)return new Response(null,{status:499});return await h.close().catch(()=>{}),n.delete(h),c(pk(x)),pD(pw(t.message))}}async function p(x,e,t,r){if(void 0!==b)return b(e,{...void 0!==t&&{authInfo:t},...void 0!==r&&{parsedBody:r}});let a=function(x,e){switch(x.reason){case"http-method":return fY("http-method","modern-only-method-not-allowed",405,new ft(-32e3,"Method not allowed."),!0);case"batch":return fY("jsonrpc-shape","modern-only-batch-not-supported",400,new ft(fe.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return fY("jsonrpc-shape","modern-only-response-post",400,new ft(fe.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let t=x.requestedVersion;return fY("era-classification","modern-only-missing-envelope",400,void 0===t?new ft(fe.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...e]}):new f_({supported:[...e],requested:t}),!0)}}}(x,dT);return void 0===a?new Response(null,{status:202}):(c(Error(`Rejected 2025-era request on a modern-only endpoint (${a.cell}): ${a.message}`)),pP(a,pw(r)))}async function m(x,e){let t=e?.authInfo;if("POST"===x.method.toUpperCase()&&!bE(x.headers.get("content-type")))return c(Error("Unsupported Media Type: Content-Type must be application/json")),pC(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let r=await pL(x,e?.parsedBody);if("unreadable-body"===r.step)return pC(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===r.step)return void 0!==b?b(r.forwardRequest,{...void 0!==t&&{authInfo:t}}):pC(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:a,body:_,parsedBody:n,forwardRequest:A}=r;try{switch(a.kind){case"reject":return c(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),pP(a,pw(_));case"modern":return await u(a,x,t);case"legacy":return await p(a,A,t,n)}}catch(x){return c(pk(x)),pD(pw(_))}}return{fetch:async(x,e)=>{if(l)throw Error("This MCP handler has been closed");try{return await m(x,e)}catch(x){return c(pk(x)),pD(pw(e?.parsedBody))}},notify:d,bus:v,close:async()=>{l=!0,f.closeAll();let x=[...n].map(x=>x.close().catch(()=>{}));n.clear(),await Promise.all(x)}}}var pT=global.Request,pR=class extends pT{constructor(x,e){"object"==typeof x&&pG in x&&(x=x[pG]()),void 0!==e?.body?.getReader&&(e.duplex??="half"),super(x,e)}},p$=Symbol("wrapBodyStream"),pG=Symbol("getRequestCache"),pO=Symbol("requestCache"),pX=Symbol("incomingKey"),pK=Symbol("urlKey"),pQ=Symbol("headersKey"),pZ=Symbol("abortControllerKey"),pM=Symbol("getAbortController"),pJ={get method(){return this[pX].method||"GET"},get url(){return this[pK]},get headers(){return this[pQ]||=(x=>{let e=[],t=x.rawHeaders;for(let x=0;x<t.length;x+=2){let{[x]:r,[x+1]:a}=t;58!==r.charCodeAt(0)&&e.push([r,a])}return new Headers(e)})(this[pX])},[pM](){return this[pG](),this[pZ]},[pG](){return this[pZ]||=new AbortController,this[pO]||=((x,e,t,r,a)=>{let _={method:x,headers:t,signal:a.signal};if("TRACE"===x){_.method="GET";let x=new pR(e,_);return Object.defineProperty(x,"method",{get:()=>"TRACE"}),x}if("GET"!==x&&"HEAD"!==x)if("rawBody"in r&&r.rawBody instanceof Buffer)_.body=new ReadableStream({start(x){x.enqueue(r.rawBody),x.close()}});else if(r[p$]){let x;_.body=new ReadableStream({async pull(e){try{x||=xO.toWeb(r).getReader();let{done:t,value:a}=await x.read();t?e.close():e.enqueue(a)}catch(x){e.error(x)}}})}else _.body=xO.toWeb(r);return new pR(e,_)})(this.method,this[pK],this.headers,this[pX],this[pZ])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(x=>{Object.defineProperty(pJ,x,{get(){return this[pG]()[x]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(x=>{Object.defineProperty(pJ,x,{value:function(){return this[pG]()[x]()}})}),Object.defineProperty(pJ,Symbol.for("nodejs.util.inspect.custom"),{value:function(x,e,t){let r={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[pO]};return`Request (lightweight) ${t(r,{...e,depth:null==x?null:x-1})}`}}),Object.setPrototypeOf(pJ,pR.prototype);var pV=Symbol("responseCache"),pH=Symbol("getResponseCache"),pU=Symbol("cache"),pY=global.Response,pz=class x{#xu;#xp;[pH](){return delete this[pU],this[pV]||=new pY(this.#xu,this.#xp)}constructor(e,t){let r;if(this.#xu=e,t instanceof x){let x=t[pV];if(x){this.#xp=x,this[pH]();return}this.#xp=t.#xp,r=new Headers(t.#xp.headers)}else this.#xp=t;("string"==typeof e||void 0!==e?.getReader||e instanceof Blob||e instanceof Uint8Array)&&(this[pU]=[t?.status||200,e,r||t?.headers])}get headers(){let x=this[pU];return x?(x[2]instanceof Headers||(x[2]=new Headers(x[2]||{"content-type":"text/plain; charset=UTF-8"})),x[2]):this[pH]().headers}get status(){return this[pU]?.[0]??this[pH]().status}get ok(){let x=this.status;return x>=200&&x<300}};function pW(x,e){return async(t,r,a)=>{let _,n;"function"==typeof a&&(a=void 0);let A=!1,s=new AbortController;r.on("close",()=>{A||s.abort()}),!0===r.destroyed&&s.abort();try{let e=await p1(t,a,{signal:s.signal});_=await x.fetch(e,{...void 0!==t.auth&&{authInfo:t.auth},...void 0!==a&&{parsedBody:a}})}catch(x){var i;try{e?.onerror?.(x instanceof Error?x:Error(String(x)))}catch{}i=function(x){if(null===x||"object"!=typeof x||Array.isArray(x))return null;let{method:e,id:t}=x;return"string"!=typeof e?null:"string"==typeof t||"number"==typeof t?t:null}(a),_=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:i},{status:500})}let o={};for(let[x,e]of _.headers)o[x]=e;if(r.writeHead(_.status,o),null===_.body){A=!0,r.end();return}r.on("drain",()=>{n?.(),n=void 0});let l=new Promise(x=>{s.signal.addEventListener("abort",()=>x(),{once:!0})});try{for await(let x of _.body){if(s.signal.aborted)break;!1===r.write(x)&&await Promise.race([new Promise(x=>{n=x}),l])}}catch{}A=!0,r.end()}}function p0(x){return Array.isArray(x)?x[0]:x}async function p1(x,e,t){let r,a=(x.method??"GET").toUpperCase(),_=`http://${p0(x.headers.host)??p0(x.headers[":authority"])??"localhost"}${x.url??"/"}`,n=new Headers;for(let[e,t]of Object.entries(x.headers))if(!(void 0===t||e.startsWith(":")))if(Array.isArray(t))for(let x of t)n.append(e,x);else n.set(e,t);if("GET"!==a&&"HEAD"!==a)if(void 0===e){let e=new TextDecoder,t="";for await(let r of x)t+="string"==typeof r?r:e.decode(r,{stream:!0});(t+=e.decode()).length>0&&(r=t)}else{let x=JSON.stringify(e);n.delete("content-encoding"),n.delete("transfer-encoding"),void 0===x?n.delete("content-length"):(r=x,n.set("content-length",String(new TextEncoder().encode(x).byteLength)))}return new Request(_,{method:a,headers:n,...t?.signal!==void 0&&{signal:t.signal},...void 0!==r&&{body:r}})}["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(x=>{Object.defineProperty(pz.prototype,x,{get(){return this[pH]()[x]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(x=>{Object.defineProperty(pz.prototype,x,{value:function(){return this[pH]()[x]()}})}),Object.defineProperty(pz.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(x,e,t){let r={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[pV]};return`Response (lightweight) ${t(r,{...e,depth:null==x?null:x-1})}`}}),Object.setPrototypeOf(pz,pY),Object.setPrototypeOf(pz.prototype,pY.prototype),void 0===global.crypto&&(global.crypto=O),Symbol("outgoingEnded"),Symbol("incomingDraining"),xV("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js"),xV("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js"),xV("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js"),xV("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js"),xV("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js"),xV("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js");let p2=xV("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js"),p3=xV("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js");function p6(x,e,t){x.readyState!==p2.OPEN||x.bufferedAmount>0xa00000?x.terminate():x.send(JSON.stringify({type:e,data:t}))}let p4=new Set(["DEBUGGER_NOT_CONNECTED","DEBUGGER_DISCONNECTED","TARGET_NOT_FOUND","ELEMENT_NOT_FOUND","RENDER_FAILED","RENDER_TIMEOUT","VIEWPORT_FAILED","INSPECTION_FAILED","SCROLL_FAILED","SCREENSHOT_FAILED","SNAPSHOT_FAILED","CHAT_NOT_READY","CHAT_BUSY","CHAT_SUBMIT_FAILED","CHAT_TIMEOUT","TOOL_CALL_FAILED","COMMAND_TIMEOUT"]);class p5 extends Error{code;constructor(x,e){super(e),this.name="DebuggerControlError",this.code=x}}function p7(x){return"render_page"===x||"render_widget"===x}function p8(x){return"number"==typeof x&&Number.isFinite(x)}function p9(x){return"number"==typeof x&&Number.isInteger(x)&&x>=1&&x<=9999}function mx(x){if("submit_chat_query"===x.type)return 12e4;if("execute_sandbox_tool_call"===x.type){let e=x.toolCall?.tool_call?.deadline_ms;if("number"==typeof e&&Number.isFinite(e))return Math.max(1,e-Date.now()+1e3)}return 15e3}class me{clients=new Map;lastSnapshotAtByClientId=new Map;snapshotStore;snapshotsByClientId=new Map;nextCommandId=0;constructor(x){this.snapshotStore=x}registerClient(x,e){let t=this.getSnapshotStore(x),r=this.clients.get(x);r&&this.disconnectClient(r,"Debugger control connection was replaced");let a={clientId:x,lastSnapshotAtMs:this.lastSnapshotAtByClientId.get(x)??0,parallelJobs:new Map,queue:[],socket:e};this.clients.set(x,a),this.snapshotsByClientId.set(x,t),e.once("close",()=>{this.disconnectClient(a,"Debugger control connection was closed",!1)})}getSnapshotStore(x){return this.snapshotsByClientId.get(x)??{}}noteSnapshot(x){if(!x)return;let e=this.getSnapshotStore(x);Object.assign(e,this.snapshotStore),this.snapshotsByClientId.set(x,e);let t=Date.now();this.lastSnapshotAtByClientId.set(x,t);let r=this.clients.get(x);r&&(r.lastSnapshotAtMs=t)}execute(x,e,t){let r=void 0!==t?this.clients.get(t):"execute_sandbox_tool_call"===x?this.getToolCallClient():this.getActiveClient();if(!r||r.socket.readyState!==p2.OPEN)return Promise.reject(new p5("DEBUGGER_NOT_CONNECTED","execute_sandbox_tool_call"===x?"No Web SDK debugger is connected":"No Web SDK debugger with a stored snapshot is connected"));let a=`control-${Date.now()}-${++this.nextCommandId}`;return new Promise((t,_)=>{let n={command:{...e,commandId:a,type:x},reject:_,resolve:t};"execute_sandbox_tool_call"===x?this.startParallelJob(r,n):(r.queue.push(n),this.flushClient(r))})}handleResult(x){var e,t;let r,a=x.clientId?.trim(),_=x.commandId?.trim(),n=a?this.clients.get(a):void 0,A=_?n?.parallelJobs.get(_):void 0,s=A??n?.activeJob;if(!n||!s||s.command.commandId!==_)return!1;if(!0===x.ok&&p7(s.command.type)&&(e=x.snapshot,e.snapshot.command_id===_&&e.snapshot.runtime_snapshot)?(this.snapshotStore.snapshot=x.snapshot,this.snapshotStore.updatedAtMs=Date.now(),this.noteSnapshot(a),r={target:x.target}):!0===x.ok&&!p7(s.command.type)&&(r=function(x,e){if("set_viewport"===x)return p9(e.width)&&p9(e.height)?e:void 0;if("submit_chat_query"===x)return!0===e.completed&&e.query?.trim()&&e.requestId?.trim()?e:void 0;if("take_snapshot"===x){let x=e.runtimeSnapshot;return x?.target?{runtimeSnapshot:x}:void 0}if("execute_sandbox_tool_call"===x)return!0===e.reported&&e.request_id?.trim()&&e.tool_call_id?.trim()?e:void 0;if("take_screenshot"===x||e.uid?.trim()){if("get_computed_style"===x){if(!Array.isArray(e.computedStyle)||!e.computedStyle.every(x=>!!x.name?.trim()&&"string"==typeof x.value))return;return e}if("get_element_rect"===x)return[e.x,e.y,e.width,e.height].every(p8)?e:void 0;if("scroll_to"===x)return[e.x,e.y,e.maxX,e.maxY,e.viewportWidth,e.viewportHeight].every(x=>p8(x)&&x>=0)&&e.x<=e.maxX&&e.y<=e.maxY?e:void 0;if("take_screenshot"===x){let x="png"===e.format?"image/png":"jpeg"===e.format?"image/jpeg":"webp"===e.format?"image/webp":void 0;return"string"==typeof e.data&&e.data.length>0&&e.mimeType===x&&p8(e.width)&&p8(e.height)&&(void 0===e.uid||e.uid?.trim())?e:void 0}}}(s.command.type,x.result),"take_snapshot"===s.command.type&&r&&"runtimeSnapshot"in r&&this.storeRuntimeSnapshot(n.clientId,r.runtimeSnapshot)),r)s.resolve(r);else{let e=x.error??{},r=e.code?.trim(),a=r&&p4.has(r)?r:void 0;s.reject(new p5(a??(p7(t=s.command.type)?"RENDER_FAILED":"set_viewport"===t?"VIEWPORT_FAILED":"scroll_to"===t?"SCROLL_FAILED":"submit_chat_query"===t?"CHAT_SUBMIT_FAILED":"take_snapshot"===t?"SNAPSHOT_FAILED":"execute_sandbox_tool_call"===t?"TOOL_CALL_FAILED":"take_screenshot"===t?"SCREENSHOT_FAILED":"INSPECTION_FAILED"),e.message?.trim()||"Debugger control command failed"))}return s.timeout&&clearTimeout(s.timeout),A?n.parallelJobs.delete(_):n.activeJob=void 0,this.flushClient(n),!0}getActiveClient(){return[...this.clients.values()].filter(x=>x.socket.readyState===p2.OPEN&&x.lastSnapshotAtMs>0).sort((x,e)=>e.lastSnapshotAtMs-x.lastSnapshotAtMs)[0]}storeRuntimeSnapshot(x,e){let t=this.getSnapshotStore(x).snapshot,r=t?.snapshot;if(!t||!r||r.client_id!==x)return;let a=t.debug_snapshot,{root:_,...n}=e,A=Date.now();this.snapshotStore.snapshot={...t,stored_at:new Date(A).toISOString(),stored_at_ms:A,snapshot:{...r,runtime_snapshot:e},...a?{debug_snapshot:{...a,runtime_snapshot:n}}:{}},this.snapshotStore.updatedAtMs=A,this.noteSnapshot(x)}getConnectedClient(){return[...this.clients.values()].reverse().find(x=>x.socket.readyState===p2.OPEN)}getToolCallClient(){return[...this.clients.values()].reverse().find(x=>x.socket.readyState===p2.OPEN&&x.activeJob?.command.type==="submit_chat_query")??this.getActiveClient()??this.getConnectedClient()}startParallelJob(x,e){let t=e.command.commandId;x.parallelJobs.set(t,e),e.timeout=setTimeout(()=>{x.parallelJobs.delete(t)&&e.reject(new p5("TOOL_CALL_FAILED","Debugger control command timed out"))},mx(e.command));try{p6(x.socket,"control",e.command)}catch{this.disconnectClient(x,"Debugger control connection was closed")}}flushClient(x){if(x.activeJob||x.socket.readyState!==p2.OPEN)return;let e=x.queue.shift();if(e){x.activeJob=e,e.timeout=setTimeout(()=>{if(x.activeJob===e){if("submit_chat_query"===e.command.type){e.timeout=void 0,e.reject(new p5("CHAT_TIMEOUT","Debugger control command timed out"));try{p6(x.socket,"control",{commandId:e.command.commandId,type:"cancel_chat_query"})}catch{this.disconnectClient(x,"Debugger control connection was closed");return}e.timeout=setTimeout(()=>{x.activeJob===e&&this.disconnectClient(x,"Debugger chat cancellation was not acknowledged")},5e3);return}x.activeJob=void 0,e.reject(new p5(p7(e.command.type)?"RENDER_TIMEOUT":"COMMAND_TIMEOUT","Debugger control command timed out")),this.flushClient(x)}},mx(e.command));try{p6(x.socket,"control",e.command)}catch{this.disconnectClient(x,"Debugger control connection was closed")}}}disconnectClient(x,e,t=!0){if(this.clients.get(x.clientId)!==x)return;this.clients.delete(x.clientId),this.snapshotsByClientId.delete(x.clientId);let r=new p5("DEBUGGER_DISCONNECTED",e);for(let e of(x.activeJob?.timeout&&clearTimeout(x.activeJob.timeout),x.activeJob?.reject(r),x.activeJob=void 0,x.parallelJobs.values()))e.timeout&&clearTimeout(e.timeout),e.reject(r);for(let e of(x.parallelJobs.clear(),x.queue.splice(0)))e.reject(r);t&&x.socket.readyState===p2.OPEN&&x.socket.close()}}let mt=["page","widget","app"],mr=["log","info","warn","error","debug","eval"],ma=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function m_(x,e){let t=e.pageIdx??0,r=e.pageSize??50,a=t*r,_=x.slice(a,a+r);return{pageIdx:t,pageSize:r,total:x.length,hasMore:a+_.length<x.length,items:_}}function mn(x){if(!x.snapshot)return{stored:!1,updatedAtMs:x.updatedAtMs};let{debug_snapshot:e,...t}=x.snapshot;return{stored:!0,storedAt:t.stored_at,updatedAtMs:t.stored_at_ms??x.updatedAtMs,snapshot:t.snapshot}}function mA(x){return x.value??x.unserializableValue??x.description??x.type??""}function ms(x,e){var t,r;let a;return(t=x,"all"===(r=e)?mt:"page"===r||"widget"===r||"app"===r?[r]:(a=t.context,a?.page_id||a?.page_path?["page","app"]:a?.widget_id?["widget"]:mt)).flatMap(e=>{let t,r=(t=x.runtime_console?.[e],{entries:t?.entries??[],updatedAtMs:t?.updated_at_ms??t?.updatedAtMs});return r.entries.map((x,t)=>{var a;let _,n,A,s;return a=r.updatedAtMs,_=x.url??x.location?.url,n=x.lineNumber??x.location?.lineNumber,A=x.columnNumber??x.location?.columnNumber,s=x.id??String(t),{msgid:`${e}:${s}`,target:e,level:x.level??"log",source:x.source??"",timestamp:x.timestamp??0,text:x.message??(x.args??[]).map(mA).filter(Boolean).join(" "),..._?{url:_}:{},...void 0===n?{}:{lineNumber:n},...void 0===A?{}:{columnNumber:A},...void 0===a?{}:{updatedAtMs:a},entry:x}})})}function mi(x,e){return{id:x.toolCallId??x.id??`tool-call:${e}`,requestId:x.requestId??x.request_id??"",toolCallId:x.toolCallId??x.id??"",toolName:x.toolName??x.name??"",serverId:x.serverId??x.server_id??"",appKey:x.appKey??x.app_key??"",status:x.status??"",createdAtMs:x.createdAtMs??x.created_at_ms??0,updatedAtMs:x.updatedAtMs??x.updated_at_ms??0,requiresUserApproval:!0===x.requiresUserApproval,isMiniApp:!0===x.isMiniApp,message:x.message??"",resultSummary:x.resultSummary??x.structuredResultSummary}}function mo(x,e){if("page"===e){let{pageId:e,path:t}=x;if(!e||!t)return;return{pageId:e,path:t,name:x.name??e,isHome:!0===x.isHome}}let{widgetId:t}=x;if(t)return{widgetId:t,name:x.name??t}}let ml={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},mc={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},mv={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function md(x,e={}){return{structuredContent:x,content:e.image?[{type:"image",...e.image}]:[{type:"text",text:e.text??JSON.stringify(x,null,2)}],...e.isError?{isError:!0}:{}}}async function mf(x,e={}){try{return await x()}catch(x){return function(x,e={}){let t=x instanceof p5?x:new p5("INSPECTION_FAILED",String(x));return md({...e,error:{code:t.code,message:t.message}},{isError:!0})}(x,e)}}function mb(x,e,t,r){let a=lx(t.inputSchema);x.registerTool(e,{...t,inputSchema:a},r)}let mu="/__wsd_mcp";async function mp({request:x,response:e,url:t},r,a){if("OPTIONS"===x.method){nD(e),e.writeHead(204),e.end();return}if("POST"!==x.method)return void nL(e,405,"Method not allowed");let _=t.searchParams.get("clientId")??void 0,n=void 0===_?r:a.getSnapshotStore(_),A=pq(()=>{let x,e;return x=new pp({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),e=async x=>{var e;let t=mn(n);if(!t.stored)return md(t);let r=m_((e=t.snapshot,[{source:"simulator",events:e.simulator?.trace_events??[]},{source:"widget_runtime",events:e.widget_runtime_trace_events??[]},{source:"page_runtime",events:e.page_runtime_trace_events??[]}].flatMap(({source:x,events:e})=>e.map((e,t)=>{let r;return r=e.payload??{},{source:x,id:e.id??`${x}:${t}`,timestamp:e.timestamp??0,category:r.category??e.display?.category??"",event:r.event??e.event??"",requestId:r.request_id??r.requestId??r.trace_id??r.trace?.trace_id??"",payload:e.payload??e}}))).filter(e=>{let t,r,a;return t=x.category??[],r=x.event?.trim(),a=x.requestId?.trim(),(0===t.length||t.includes(e.category))&&(!r||e.event===r)&&(!a||e.requestId===a)}),x);return md({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,events:r.items})},mb(x,"list_chat_messages",{annotations:ml,description:"List conversation messages in chronological order from the latest debugger snapshot, including message content and generation status.",inputSchema:{}},async()=>{let x=mn(n);if(!x.stored)return md(x);let e=n.snapshot?.debug_snapshot?.simulator??x.snapshot.simulator;return md({stored:!0,storedAt:x.storedAt,updatedAtMs:x.updatedAtMs,streamStatus:e?.stream_status,messages:e?.messages??[]})}),mb(x,"list_console_messages",{annotations:ml,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:o8(ll(mr)).optional(),pageIdx:oU().int().min(0).optional(),pageSize:oU().int().min(1).max(200).optional(),query:oB().optional(),target:ll(["current","page","widget","app","all"]).optional()}},async x=>{let e=mn(n);if(!e.stored)return md(e);let t=m_(ms(e.snapshot,x.target).filter(e=>{let t,r;return t=x.levels??[],r=x.query?.trim().toLowerCase(),(!(t.length>0)||!!t.includes(e.level))&&(!r||[e.text,e.url,e.source,e.target].filter(x=>"string"==typeof x).some(x=>x.toLowerCase().includes(r)))}),x);return md({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,total:t.total,pageIdx:t.pageIdx,pageSize:t.pageSize,hasMore:t.hasMore,messages:t.items.map(({entry:x,...e})=>e)})}),mb(x,"get_console_message",{annotations:ml,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:oB()}},async x=>{let e=mn(n);if(!e.stored)return md(e);let t=ms(e.snapshot,"all").find(e=>e.msgid===x.msgid);return md({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,found:!!t,...t?{message:t}:{msgid:x.msgid}})}),mb(x,"get_log_snapshot",{annotations:ml,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let x=mn(n);return x.stored?md({stored:!0,storedAt:x.storedAt,updatedAtMs:x.updatedAtMs,snapshot:x.snapshot}):md(x)}),mb(x,"list_render_targets",{annotations:ml,description:"List Page and Widget targets that can be rendered by the Web SDK debugger.",inputSchema:{type:ll(["all","page","widget"]).optional()}},async x=>{var e,t;let r,a=mn(n);return a.stored?md({stored:!0,storedAt:a.storedAt,updatedAtMs:a.updatedAtMs,...(e=a.snapshot,t=x.type??"all",r=e.render_targets??{},{pages:"widget"===t?[]:(r.pages??[]).map(x=>mo(x,"page")).filter(Boolean),widgets:"page"===t?[]:(r.widgets??[]).map(x=>mo(x,"widget")).filter(Boolean),...r.currentTarget?{currentTarget:r.currentTarget}:{}})}):md(a)}),mb(x,"take_snapshot",{annotations:ml,description:"Capture and return a fresh text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:ll(["current","page","widget"]).optional(),verbose:o0().optional()}},x=>mf(async()=>{let e=function(x,e){var t,r;let a,_,n,A=x.runtime_snapshot;if(!A?.target)return{available:!1,reason:"NO_RUNTIME_SNAPSHOT"};let s=A.target,i=s.type,o=e.target??"current";if(("page"===o||"widget"===o)&&i!==o)return{available:!1,reason:"TARGET_MISMATCH",requestedTarget:o,currentTarget:s};if(!A.root)return{available:!1,reason:"NO_RENDERED_TARGET",currentTarget:s};let l=A.selectedUid,c=(t=A.root,r=!0===e.verbose,a=[],_=0,(n=(x,e)=>{var t,A;let{name:s,uid:i}=x;if(!i||!s)return;_+=1;let o=" ".repeat(e);if("text"===x.type)return void a.push(`${o}uid=${i} text ${JSON.stringify(x.text??"")}`);let c=[`uid=${i}`,s],{keyboardFocusable:v=!1,name:d,role:f}=x.accessibility??{};for(let e of(f&&(r||"generic"!==f)&&c.push(`role=${JSON.stringify(f)}`),d&&c.push(`name=${JSON.stringify(d)}`),(r||v)&&c.push(`focusable=${String(v)}`),(x.attributes??[]).map(x=>({name:x.name,value:x.value})).filter(x=>x.name&&(r||ma.has(x.name)||x.name.startsWith("aria-")))))c.push((t=e.name,(A=e.value)?`${t}=${JSON.stringify(A)}`:t));for(let t of(i===l&&c.push("[selected]"),a.push(`${o}${c.join(" ")}`),x.children??[]))n(t,e+1)})(t,0),{actualNodeCount:_,text:a.join("\n")});return{available:!0,target:s,nodeCount:A.nodeCount??c.actualNodeCount,...l?{selectedUid:l}:{},truncated:!0===A.truncated,snapshot:c.text,snapshotUpdatedAtMs:A.updatedAtMs}}({runtime_snapshot:(await a.execute("take_snapshot",{target:x.target??"current"},_)).runtimeSnapshot},x),t=mn(n),r={stored:t.stored,...t.stored?{storedAt:t.storedAt,updatedAtMs:t.updatedAtMs}:{},...e};return md(r,{text:e.available?e.snapshot:JSON.stringify(r,null,2)})},{available:!1,stored:!1})),mb(x,"get_computed_style",{annotations:ml,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:o8(oB().min(1)).max(100).optional(),uid:oB().min(1)}},({properties:x,uid:e})=>mf(async()=>md(await a.execute("get_computed_style",{uid:e,...x?{properties:x}:{}},_)))),mb(x,"get_element_rect",{annotations:ml,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:oB().min(1)}},({uid:x})=>mf(async()=>md(await a.execute("get_element_rect",{uid:x},_)))),mb(x,"take_screenshot",{annotations:ml,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:ll(["png","jpeg","webp"]).optional(),quality:oU().min(0).max(100).optional(),uid:oB().min(1).optional()}},({format:x="png",quality:e,uid:t})=>mf(async()=>{let r=await a.execute("take_screenshot",{format:x,...void 0!==e?{quality:e}:{},...t?{uid:t}:{}},_),{data:n,...A}=r;return md({captured:!0,...A},{image:{data:n,mimeType:r.mimeType}})},{captured:!1})),mb(x,"scroll_to",{annotations:mv,description:"Scroll a Page or Widget container to absolute coordinates, or return its current scroll position.",inputSchema:{uid:oB().min(1).optional(),x:oU().min(0).optional(),y:oU().min(0).optional()}},({uid:x,x:e,y:t})=>mf(async()=>md({scrolled:!0,...await a.execute("scroll_to",{uid:x,x:e,y:t},_)}),{scrolled:!1})),mb(x,"set_viewport",{annotations:mv,description:"Set the current Page or Widget emulated viewport size.",inputSchema:{height:oU().int().min(1).max(9999),width:oU().int().min(1).max(9999)}},({height:x,width:e})=>mf(async()=>md({updated:!0,viewport:await a.execute("set_viewport",{height:x,width:e},_)}),{updated:!1})),mb(x,"render_page",{annotations:mc,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:oB().min(1)}},({url:x})=>mf(async()=>md({rendered:!0,target:(await a.execute("render_page",{url:x},_)).target}),{rendered:!1})),mb(x,"render_widget",{annotations:mc,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:li(oB(),o4()).optional(),widgetId:oB().min(1)}},({structuredContent:x,widgetId:e})=>mf(async()=>md({rendered:!0,target:(await a.execute("render_widget",{structuredContent:x??{},widgetId:e},_)).target}),{rendered:!1})),mb(x,"submit_chat_query",{annotations:mc,description:"Submit a chat query through the connected Web SDK debugger and wait for the simulator response to complete.",inputSchema:{query:oB().trim().min(1)}},({query:x})=>mf(async()=>md({submitted:!0,...await a.execute("submit_chat_query",{query:x},_)}),{submitted:!1})),mb(x,"list_agent_trace_events",{annotations:ml,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:o8(oB()).optional(),event:oB().optional(),pageIdx:oU().int().min(0).optional(),pageSize:oU().int().min(1).max(200).optional(),requestId:oB().optional()}},e),mb(x,"list_agent_tool_calls",{annotations:ml,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:oU().int().min(0).optional(),pageSize:oU().int().min(1).max(200).optional(),query:oB().optional(),requestId:oB().optional(),status:o8(oB()).optional(),toolName:oB().optional()}},async x=>{var e;let t=mn(n);if(!t.stored)return md(t);let r=m_((e=t.snapshot,(e.simulator?.tool_calls??[]).map(mi)).filter(e=>{let t,r,a,_;return t=x.requestId?.trim(),r=x.toolName?.trim(),a=x.status??[],_=x.query?.trim().toLowerCase(),(!t||e.requestId===t)&&(!r||e.toolName===r)&&(!(a.length>0)||!!a.includes(e.status))&&(!_||[e.toolName,e.serverId,e.appKey,e.status,e.message,"string"==typeof e.resultSummary?e.resultSummary:void 0].filter(x=>"string"==typeof x).some(x=>x.toLowerCase().includes(_)))}),x);return md({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,toolCalls:r.items})}),x}),s=pW(A);try{await s(x,e)}catch(x){e.headersSent?e.destroy(x instanceof Error?x:void 0):nL(e,500,x instanceof Error?x.message:String(x))}finally{await A.close().catch(()=>void 0)}}let mm="/__web_sdk_debug_scenes",mh="/__web_sdk_widget_view_data_templates",mE={"Cache-Control":"no-cache"};async function mj(x,e){try{let t=await e?.()??{templatesByEntry:{},templatesByWidget:{}};nq(x,200,t,mE)}catch(e){nj.error("加载 Widget viewData 模板失败",{error:e}),nq(x,500,{templatesByEntry:{},templatesByWidget:{}},mE)}}let mg="Action HUB request failed or returned an invalid response",my=x=>null!=x&&0!==x&&"0"!==x;async function mS(x,e){if(!function({request:x,response:e}){return!function(x){if(!["127.0.0.1","::1","::ffff:127.0.0.1"].includes(x.socket.remoteAddress??""))return!1;try{let e=x.headers.host;if(!e)return!1;let t=new URL(`http://${e}`);if(!["127.0.0.1","[::1]","localhost"].includes(t.hostname)||t.username||t.password||"/"!==t.pathname||t.search||t.hash)return!1;let r=x.headers.origin;return!r||r===t.origin}catch{return!1}}(x)?(nL(e,403,"Forbidden origin or host"),!1):"OPTIONS"===x.method?(e.writeHead(204).end(),!1):"POST"!==x.method?(nL(e,405,"Method not allowed"),!1):x.headers["content-type"]?.split(";")[0].trim().toLowerCase()==="application/json"||(nL(e,415,"Content-Type must be application/json"),!1)}(x))return;let{request:t,response:r}=x,a=new AbortController,_=()=>a.abort(),n=pq(()=>(function(x,e){let t=new pu({name:"doubao-action-hub",version:"1.0.0"},{capabilities:{tools:{}}});for(let r of["tools/list","tools/call"])t.setRequestHandler(r,(t,r)=>mB(x,t,AbortSignal.any([e,r.mcpReq.signal])));return t})(e,a.signal)),A=setTimeout(()=>{a.abort(),r.headersSent||r.destroyed?(r.destroy(),t.destroy()):(r.once("finish",()=>t.destroy()),nL(r,504,"Action HUB request timed out"))},6e4);t.once("aborted",_),r.once("close",_);try{let e=await mI(x);void 0===e||a.signal.aborted||await pW(n)(t,r,e)}finally{clearTimeout(A),t.off("aborted",_),r.off("close",_),a.abort(),await n.close()}}async function mI({request:x,response:e}){let t;try{t=await nR(x,e,1048576)}catch{e.destroyed||e.writableEnded||nL(e,413,"Request body is too large or incomplete");return}try{return JSON.parse(t)}catch{nL(e,400,"Invalid JSON request");return}}async function mN(x){if(!x.ok||!x.body)throw await x.body?.cancel(),Error(mg);let e=[],t=0;for await(let r of x.body){if((t+=r.byteLength)>4194304)throw Error(mg);e.push(r)}return JSON.parse(Buffer.concat(e).toString("utf8"))}async function mB(x,e,t){try{let r=await (x.fetcher??fetch)(`https://mcp.bytedance.net/mcp/proxy/${e.method}`,{method:"POST",redirect:"error",signal:t,headers:{..._c(),"Content-Type":"application/json","X-Access-Key":x.accessKey,"X-Client-Version":"doubao-web-simulator",...x.cluster?{cluster:x.cluster}:{}},body:JSON.stringify({mcp_server_names:[x.serverName],..."tools/call"===e.method?{name:e.params.name,arguments:JSON.stringify({...e.params.arguments,from_mcp_call:!0})}:{},...x.headers?{extra_info:{headers:JSON.stringify(x.headers)}}:{}})}),a=await mN(r);if(!eT(a))throw Error(mg);let _=a.result;if("string"==typeof _)try{_=JSON.parse(_)}catch{}for(let t of(_=function x(e,t){return"string"==typeof e?e.split(t).join("[redacted]"):Array.isArray(e)?e.map(e=>x(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e.split(t).join("[redacted]"),x(r,t)])):e}(_,x.accessKey),"tools/list"===e.method?[a,_]:[a]))if(!eT(t)||void 0!==t.base_resp&&!eT(t.base_resp)||[t.error_code,t.code,t.status_code,t.base_resp?.status_code].some(my)||!1===t.success||t.error||void 0!==t.status&&![0,"0","success","ok"].includes(t.status))throw Error(mg);if("tools/call"===e.method&&"string"==typeof _)return{content:[{type:"text",text:_}],structuredContent:{result:_}};if(!eT(_)||void 0!==_.base_resp&&(!eT(_.base_resp)||my(_.base_resp.status_code)))throw Error(mg);if("tools/list"===e.method){if(!Array.isArray(_.tools))throw Error(mg);return{tools:_.tools.map(x=>{if(!eT(x))throw Error(mg);let e=x.input_schema??x.inputSchema,t={name:x.name,...void 0===x.description?{}:{description:x.description},inputSchema:"string"==typeof e?JSON.parse(e):e};if(!bi.Tool(t))throw Error(mg);return t})}}return{content:Array.isArray(_.content)&&_.content.every(bi.ContentBlock)?_.content:[{type:"text",text:JSON.stringify(_)}],structuredContent:_,...my(_.error_code)||my(_.errorCode)||!0===_.isError?{isError:!0}:{}}}catch{throw Error(mg)}}let mF="/__dbx_real_device_debug",mw=`${mF}/state`,mC=`${mF}/start`,mP=`${mF}/cancel`,mk=`${mF}/qr`;class mD{accessToken;provider;getDebugContext(){if(this.provider&&this.accessToken)return{stateEndpoint:mw,startEndpoint:mC,cancelEndpoint:mP,qrEndpoint:mk,accessToken:this.accessToken,pollIntervalMs:500}}setProvider(x){this.provider=x,this.accessToken=x?xh.randomBytes(32).toString("hex"):void 0}dispose(){this.setProvider(void 0)}getRequestRoutes(){return[{match:x=>x.pathname.startsWith(mF),handle:({request:x,response:e,url:t})=>this.serveRequest(x,e,t)}]}async serveRequest(x,e,t){if(!this.validateRequest(x,e))return;let r=this.provider;if(!r)return this.writeError(e,503,"REAL_DEVICE_DEBUG_UNAVAILABLE","Physical device debugging is unavailable");let a=await this.readJsonBody(x,e);if(a)try{if(t.pathname===mw||t.pathname===mC){if(Object.keys(a).length>0)return this.writeError(e,400,"INVALID_REQUEST","Unexpected request fields");let x=t.pathname===mw?await r.getState():await r.start();nq(e,200,x);return}if(t.pathname===mP){let x=a.operationId;if("string"!=typeof x||!x||1!==Object.keys(a).length)return this.writeError(e,400,"INVALID_REQUEST","Invalid operationId");nq(e,200,await r.cancel(x));return}if(t.pathname===mk){let{operationId:x,kind:t}=a;if("string"!=typeof x||!x||"modern"!==t&&"legacy"!==t||2!==Object.keys(a).length)return this.writeError(e,400,"INVALID_REQUEST","Invalid QR request");let _=await r.getQrImage(x,t);if(!_)return this.writeError(e,404,"QR_NOT_FOUND","QR image is unavailable");nD(e),e.writeHead(200,{"Content-Length":_.body.byteLength,"Content-Type":_.contentType}),e.end(_.body);return}return this.writeError(e,404,"NOT_FOUND","Not found")}catch{return this.writeError(e,500,"REAL_DEVICE_DEBUG_FAILED","Physical device debugging failed")}}validateRequest(x,e){var t,r;let a,_,n;if(!function(x){if(!x)return!1;try{let e=new URL(`http://${x}`).hostname.toLowerCase();return"127.0.0.1"===e||"[::1]"===e||"localhost"===e}catch{return!1}}(x.headers.host))return this.writeError(e,403,"FORBIDDEN_HOST","Forbidden host"),!1;let A=x.headers["x-dbx-real-device-token"];if("string"!=typeof A||!this.accessToken||(t=A,r=this.accessToken,_=(a=new TextEncoder).encode(t),n=a.encode(r),!(_.length===n.length&&xh.timingSafeEqual(_,n))))return this.writeError(e,401,"UNAUTHORIZED","Unauthorized"),!1;if("POST"!==x.method)return this.writeError(e,405,"METHOD_NOT_ALLOWED","Method must be POST"),!1;if(!(x.headers["content-type"]?.toLowerCase()??"").startsWith("application/json"))return this.writeError(e,415,"UNSUPPORTED_MEDIA_TYPE","Content-Type must be application/json"),!1;let s=x.headers.origin;return!s||s===`http://${x.headers.host}`||(this.writeError(e,403,"FORBIDDEN_ORIGIN","Forbidden origin"),!1)}async readJsonBody(x,e){let t,r;try{t=await nR(x,e,4096)}catch{return this.writeError(e,413,"PAYLOAD_TOO_LARGE","Request body is too large")}if(!t.trim())return{};try{r=JSON.parse(t)}catch{return this.writeError(e,400,"INVALID_REQUEST","Invalid JSON body")}return!r||"object"!=typeof r||Array.isArray(r)?this.writeError(e,400,"INVALID_REQUEST","Invalid JSON body"):r}writeError(x,e,t,r){x.writableEnded||x.destroyed||nq(x,e,{error:{code:t,message:r}})}}async function mL(x,e,t,r,a){let _="POST",n=t;for(let t=0;;t++){if(!["http:","https:"].includes(x.protocol)||x.username||x.password)throw Error("Invalid upload URL");n&&e.set("content-length",String(n.length));let A=await new Promise((t,A)=>{let s=!1,i=("https:"===x.protocol?xG:xq).request(x,{method:_,headers:Object.fromEntries(e),signal:r},x=>{s=!0,i.end(),t(x)});i.once("error",A);let o=0,l=-1,c=x=>{if(x)return void i.destroy(x);if(s||r.aborted)return;if(n&&o>0){let x=Math.floor(100*o/n.length);x!==l&&(l=x,a(o,n.length))}if(!n||o===n.length)return void i.end();let e=n.subarray(o,o+65536);o+=e.length,i.write(e,c)};c()}),s=A.statusCode??502,i=A.headers.location;if([301,302,303,307,308].includes(s)&&i){if(A.destroy(),20===t)throw Error("Too many upload redirects");let r=new URL(i,x);if(r.origin!==x.origin)for(let x of["authorization","cookie","proxy-authorization"])e.delete(x);(303===s||(301===s||302===s)&&"POST"===_)&&(_="GET",n=void 0,e.delete("content-length"),e.delete("content-type")),x=r;continue}let o=new Headers;for(let[x,e]of Object.entries(A.headers))for(let t of Array.isArray(e)?e:void 0===e?[]:[e])o.append(x,t);if([204,205,304].includes(s))return A.resume(),new Response(null,{status:s,headers:o});let l=o.get("content-encoding"),c="gzip"===l?xM():"deflate"===l?xJ():"br"===l?xZ():void 0;return c&&xQ(A,c,x=>{x&&c.destroy(x)}),new Response(xX.toWeb(c??A),{status:s,headers:o})}}let mq="x-web-sdk-file-transfer";function mT(x){let e=new Headers(x);return["connection","content-length","host","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"].forEach(x=>e.delete(x)),e}function mR(x){let e={};return x.forEach((x,t)=>{e[t]=x}),e}async function m$(x,e){let t=x.headers[mq];if("string"==typeof t)return void await mG(x,e,t);if("POST"!==x.method)return void nq(e,405,{message:"不支持的请求方法"});let r=nK(x,e);try{let t=JSON.parse(await nR(x,e,0xa00000)),a=function(x){if("string"!=typeof x||!["GET","POST","PUT","DELETE","HEAD","OPTIONS"].includes(x))throw Error(`Unsupported request method: ${String(x)}`);return x}(t.method),_=nw(t.url),n=await fetch(_,{signal:r,body:"GET"!==a&&"HEAD"!==a?function(x){if(void 0!==x.data&&null!==x.data){if("base64"===x.dataEncoding&&"string"==typeof x.data){var e;let t;return t=new ArrayBuffer((e=Buffer.from(x.data,"base64")).byteLength),new Uint8Array(t).set(e),t}if(void 0===x.dataEncoding&&"string"==typeof x.data)return x.data;throw Error("Invalid prepared request body")}}(t):void 0,headers:mT(t.header),method:a}),A=Buffer.from(await n.arrayBuffer()).toString("base64");nq(e,200,{data:A,dataEncoding:"base64",header:mR(n.headers),statusCode:n.status})}catch(x){if(r.aborted||e.destroyed)return;nq(e,500,{message:x instanceof Error?x.message:String(x)})}}async function mG(x,e,t){if("GET"!==x.method&&"POST"!==x.method)return void nq(e,405,{message:"不支持的传输方法"});let r=nK(x,e);try{let a=JSON.parse(decodeURIComponent(t)),_=nw(a.url),n=mT(a.header);if(n.delete("referer"),n.delete("user-agent"),"POST"===x.method){n.set("content-type",x.headers["content-type"]??"application/octet-stream");let t=await nT(x,e,0xc800000);e.setHeader("content-type","application/x-ndjson"),e.setHeader("cache-control","no-store"),e.flushHeaders();let a=x=>e.write(`${JSON.stringify(x)}
394
394
  `),A=await mL(_,n,t,r,(x,e)=>{a({type:"progress",totalBytesSent:x,totalBytesExpectedToSend:e})});a({type:"headers",statusCode:A.status,header:mR(A.headers)}),a({type:"result",data:await A.text()}),e.end();return}let A=await fetch(_,{signal:r,headers:n});e.setHeader("content-type","application/octet-stream"),e.setHeader("cache-control","no-store"),e.setHeader(mq,encodeURIComponent(JSON.stringify({statusCode:A.status,header:mR(A.headers)})));let s=A.headers.get("content-length");A.body&&null!==s&&!A.headers.has("content-encoding")&&e.setHeader("content-length",s),e.flushHeaders(),A.body?await R(xX.fromWeb(A.body),e):e.end()}catch(a){if(r.aborted||e.destroyed)return;let t=a instanceof Error?a.message:String(a);if(e.headersSent)return void("POST"===x.method?e.end(`${JSON.stringify({type:"error",message:t})}
395
395
  `):e.destroy(a instanceof Error?a:Error(t)));nq(e,502,{message:t})}}let mO={"Cache-Control":"no-cache"},mX="/app_developer/api/sandbox/",mK=`${mX}session/business_info/update`,mQ=new Set([`${mX}resources/notices/pull`,`${mX}resources/tasks/pull`]),mZ={"Access-Control-Expose-Headers":nB},mM=new Set;function mJ(x,e,t,r,a,_){if(!ev())return!1;let n=`${a[nN]??""} ${x} ${e.pathname}`,A=mQ.has(e.pathname);if(A&&t>=500){if(mM.has(n))return!1;mM.add(n)}else A&&t<500&&mM.delete(n);let s=Number(process.hrtime.bigint()-r)/1e6;return nj.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:s,headers:a,logId:_}),!0}function mV({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:_,targetUrl:n}){nX({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:_,targetUrl:n})}function mH(x,e,t){return t&&!(mQ.has(x.pathname)&&e>=500)}function mU(x,e){if(x.pathname!==mK||!e)return e;try{let x=JSON.parse(e);return JSON.stringify({...x,..."csr_pem"in x?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]"})}catch{return JSON.stringify({omitted:"Sandbox 业务信息请求无效"})}}async function mY({method:x,request:e,requestBody:t,requestHeaders:r,response:a,targetUrl:_,usePlatformFetch:n}){let A=process.hrtime.bigint(),s=nK(e,a);try{let e,i=n?await _f({internal:!0,path:`${_.pathname}${_.search}`,method:x,body:t,headers:r,signal:s}):await fetch(_,{body:"GET"===x||"HEAD"===x?void 0:t,headers:r,method:x,signal:s}),o=mJ(x,_,i.status,A,r,i.headers.get(nB)??void 0);if(a.destroyed||a.writableEnded)return void i.body?.cancel().catch(()=>void 0);let l=await n$(i);return mH(_,i.status,o)&&mV({method:x,requestBody:mU(_,t),requestHeaders:r,responseBody:l,responseHeaders:i.headers,statusCode:i.status,targetUrl:_}),a.destroyed||a.writableEnded||(e=nk(i.headers,[nB]),nD(a,mZ),a.writeHead(i.status,e),a.end(l)),{body:l,ok:i.ok}}catch(i){if(a.destroyed||a.writableEnded||s.aborted)return;let e=`代理 Sandbox 请求失败:${i instanceof Error?i.message:String(i)}`,n=mJ(x,_,502,A,r);mH(_,502,n)&&mV({method:x,requestBody:mU(_,t),requestHeaders:r,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:_}),nL(a,502,e,mZ)}}async function mz(x,e,t={}){let r;if("POST"!==x.method)return void nL(e,405,"不支持的请求方法",mZ);try{r=JSON.parse(await nR(x,e,0xa00000))}catch(x){nL(e,400,`Sandbox 代理请求内容无效:${x.message}`,mZ);return}let a=function(x,e){if(!x.url)return;let t=new URL(x.url,e);if(!t.pathname.startsWith(mX))return;let r=new URL(`${t.pathname}${t.search}`,e);var a=x.params;if(a)for(let[x,e]of Object.entries(a))null!=e&&r.searchParams.set(x,String(e));return r}(r,t.targetOrigin??e$);if(!a)return void nL(e,404,"未找到 Sandbox endpoint",mZ);if(!t.sandboxSessionId)return void nq(e,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},mZ);let _=function(x,e,t,r){if(e.pathname.startsWith(`${mX}session/`)&&e.pathname!==`${mX}session/create`)return JSON.stringify({..."object"==typeof x.data&&null!==x.data?x.data:{},sandbox_session_id:r});if(void 0===x.data)return;if("object"!=typeof x.data||null===x.data||!t)return JSON.stringify(x.data);let a={...x.data};return e.pathname.startsWith(`${mX}jsb/`)&&"app_key"in a&&(a.app_key=t),e.pathname===`${mX}passport/open/auth`&&"client_key"in a&&(a.client_key=t),JSON.stringify(a)}(r,a,t.sandboxAppId,t.sandboxSessionId),n=r.method||"POST",A=function(x,e,t,r,a){let _=Object.fromEntries(Object.entries(nC({...x.headers,...t,...void 0===r?{}:{"content-length":String(Buffer.byteLength(r))},"content-type":"application/json"},e,{..._c(),...a?{[nN]:a}:{}})).filter(([x,e])=>"host"!==x.toLowerCase()&&void 0!==e).map(([x,e])=>[x,Array.isArray(e)?e.join(", "):String(e)]));for(let x of Object.keys(_))"accept-encoding"===x.toLowerCase()&&delete _[x];return _["accept-encoding"]="identity",_}(x,a,r.headers,_,t.sandboxSessionId),s=await mY({method:n,request:x,requestBody:_,requestHeaders:A,response:e,targetUrl:a,usePlatformFetch:!t.targetOrigin});if(a.pathname===mK&&s?.ok)try{let x=JSON.parse(s.body.toString("utf8"));(void 0===x.code||0===x.code)&&t.onBusinessInfoUpdated?.(function(x){if(!x||"object"!=typeof x||Array.isArray(x))return;let e="string"==typeof x.csr_pem?x.csr_pem.trim():"",t="string"==typeof x.phone_num?x.phone_num.trim():"";return t?{...e?{csrPem:e}:{},phoneNum:t}:void 0}(r.data))}catch{}}let mW="/app_developer/api/sandbox/bridge/events",m0="/app_developer/api/sandbox/bridge/response",m1=new Set(["connection","content-length","host"]),m2=new Set(["heartbeat"]),m3=[500,1e3,2e3,5e3],m6=0;function m4(x){return x.length<=8?x:`${x.slice(0,4)}...${x.slice(-4)}`}function m5(x,e=new Headers,t=""){return{response:x,responseHeaders:Object.fromEntries(e),statusText:t}}async function m7(x){let e,t,r=x.request_id||"";if(!r)return m5({error_message:"Bridge 请求缺少 request_id",http_status:0,request_id:r,success:!1});if(!x.path?.startsWith("/"))return m5({error_message:`Bridge 请求路径无效:${x.path??""}`,http_status:0,request_id:r,success:!1});let a=function(x){if(x.origin)try{var e;return new URL(x.path??"/",(e=x.origin).endsWith("/")?e:`${e}/`)}catch{return}}(x);if(!a)return m5({error_message:`Bridge 请求 origin 无效:${x.origin??""}`,http_status:0,request_id:r,success:!1});let _=(x.method||"GET").toUpperCase(),n=function(x){let e={};for(let[t,r]of Object.entries(x??{}))!t||m1.has(t.toLowerCase())||(e[t]=r);return e}(x.headers),A="GET"===_||"HEAD"===_?void 0:x.body??"",s=new AbortController,i=setTimeout(()=>s.abort(),(e="number"==typeof x.timeout_ms?x.timeout_ms:3e3,t="number"==typeof x.deadline_ms?x.deadline_ms-Date.now():e,Math.max(1,Math.min(e,t))));try{var o;let x=await fetch(a,{body:A,headers:n,method:_,redirect:"manual",signal:s.signal}),e=await x.text();return o={method:_,requestBody:A,requestHeaders:n,responseBody:e,responseHeaders:x.headers,statusCode:x.status,targetUrl:a},nX(o),m5({body:e,http_status:x.status,request_id:r,success:!0},x.headers,x.statusText)}catch(x){return nX({method:_,requestBody:A,requestHeaders:n,responseBody:x instanceof Error?x.message:String(x),responseHeaders:new Headers,statusCode:0,targetUrl:a}),m5({error_message:x instanceof Error?x.message:String(x),http_status:0,request_id:r,success:!1})}finally{clearTimeout(i)}}function m8(x,e=new Set){if(Array.isArray(x)){for(let t of x)m8(t,e);return[...e]}if(!x||"object"!=typeof x)return[...e];for(let[t,r]of Object.entries(x)){if(t.toLowerCase().replace(/[_-]/g,"").includes("logid")){if("string"==typeof r&&r)e.add(r);else if(Array.isArray(r))for(let x of r)"string"==typeof x&&x&&e.add(x);continue}m8(r,e)}return[...e]}function m9(x,e){x.onLog?.(e)}function hx(x){try{return JSON.parse(x)}catch{return}}function he({detail:x,requestHeaders:e,status:t,targetUrl:r}){if(ev()){if("number"==typeof t)return void nj.request({method:"CONNECT",url:r.pathname,statusCode:t,headers:e,context:{detail:x}});nj.info("Bridge 连接等待中",{url:r.pathname,detail:x,ppe:eu(e)})}}function ht(x,e={}){ev()&&nj.info(x,e)}async function hr(x,e){let t=JSON.stringify({sandbox_session_id:x.sandboxSessionId,...e}),r={"content-type":"application/json",[nN]:x.sandboxSessionId,..._c()};if(x.targetOrigin){let e=new URL(m0,x.targetOrigin),a=await fetch(e,{body:t,headers:r,method:"POST"}),_=await a.text();if(nX({method:"POST",requestBody:t,requestHeaders:r,responseBody:_,responseHeaders:a.headers,statusCode:a.status,targetUrl:e}),!a.ok)throw Error(`上传 Bridge 响应失败:${a.status} ${_}`);return{responseBody:_,responseHeaders:Object.fromEntries(a.headers),responsePayload:hx(_)}}let a=new URL(m0,e$),_=await _f({body:t,headers:r,internal:!0,method:"POST",path:m0}),n=await _.text();if(nX({method:"POST",requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:_.headers,statusCode:_.status,targetUrl:a}),!_.ok)throw Error(`上传 Bridge 响应失败:${_.status} ${n}`);return{responseBody:n,responseHeaders:Object.fromEntries(_.headers),responsePayload:hx(n)}}async function ha(x,e){let t;try{t=JSON.parse(e)}catch(x){nj.warn("Sandbox Bridge 请求解析失败",{reason:x.message});return}let r=Date.now(),a=`bridge-${r}-${++m6}`,_=t.request_id||"",n={id:a,request:t,requestId:_,sandboxSessionId:x.sandboxSessionId,timestamp:r};m9(x,{...n,logIds:m8(t),status:"pending",updatedAtMs:r});let A=await m7(t),s={...A.response,headers:A.responseHeaders,status_text:A.statusText};try{let e=await hr(x,A.response);m9(x,{...n,logIds:m8([t,s,e]),response:s,status:A.response.success?"success":"error",updatedAtMs:Date.now()})}catch(e){throw m9(x,{...n,errorMessage:e instanceof Error?e.message:String(e),logIds:m8([t,s]),response:s,status:"error",updatedAtMs:Date.now()}),e}}async function h_(x,e,t){let r={sandbox_session_id:x.sandboxSessionId},a=new URL(`${mW}?sandbox_session_id=${encodeURIComponent(x.sandboxSessionId)}`,e$),_=(o=x.sandboxSessionId,{accept:"text/event-stream",host:a.host,[nN]:o,..._c()});he({detail:`host=${_.host} session=${m4(x.sandboxSessionId)}`,requestHeaders:_,status:"pending",targetUrl:a}),ht("bridge/events request",{headers:{accept:_.accept,host:_.host,[nN]:m4(x.sandboxSessionId),"x-tt-env":_["x-tt-env"],"x-use-ppe":_["x-use-ppe"]},path:mW,query:r});let n=await _f({headers:_,internal:!0,method:"GET",path:mW,query:r,signal:e});if(he({detail:`content-type=${n.headers.get("content-type")??""}`,requestHeaders:_,status:n.status,targetUrl:a}),!n.ok||!n.body){let x=await n.text().catch(()=>"");nX({method:"GET",requestBody:void 0,requestHeaders:_,responseBody:x,responseHeaders:n.headers,statusCode:n.status,targetUrl:a}),nj.warn("Sandbox Bridge 事件请求失败",{status:n.status,body:x.slice(0,500)});let e=Error(`Sandbox Bridge SSE 请求失败:${n.status} ${x}`);throw e.status=n.status,e}nX({method:"GET",requestBody:void 0,requestHeaders:_,responseBody:"",responseHeaders:n.headers,statusCode:n.status,targetUrl:a}),t?.();let A=n.body.getReader(),s=new xg,i="";for(;!e.aborted;){let{done:e,value:t}=await A.read();if(e){ht("Bridge events 流已结束",{session:m4(x.sandboxSessionId)});break}let r=(i+=s.decode(t,{stream:!0})).search(/\r?\n\r?\n/);for(;r>=0;){let e=i.slice(0,r),t=i.slice(r).match(/^\r?\n\r?\n/);i=i.slice(r+(t?.[0].length??2));let A=function(x){let e="message",t=[];for(let r of x.split(/\r?\n/)){if(r.startsWith("event:")){e=r.slice(6).trim();continue}r.startsWith("data:")&&t.push(r.slice(5).trimStart())}return{data:t.join("\n"),name:e}}(e);if(!function(x,e){if(!ev()||m2.has(x.name))return;let t=function(x){try{let e=JSON.parse(x);return"string"==typeof e.request_id?e.request_id:void 0}catch{return}}(x.data);nj.info("已收到 Bridge 事件",{event:x.name,requestId:t,ppe:eu(e)}),nj.info(`事件详情
396
- ${x.data}`)}(A,_),"bridge_request"===A.name){var o,l,c=n.headers,v=n.status;nX({method:`EVENT ${A.name}`,requestBody:A.data,requestHeaders:_,responseBody:"",responseHeaders:c,statusCode:v,targetUrl:a}),ha(x,A.data).catch(x=>{nj.warn("Sandbox Bridge 请求处理失败",{reason:x.message})})}else if("TOOL_CALL"===A.name){let e="object"==typeof(l=hx(A.data))&&l?.tool_call?l:void 0;e?Promise.resolve(x.onSimulatorToolCall?.(e)).catch(x=>{nj.warn("Sandbox Tool 调用转发失败",{reason:x instanceof Error?x.message:String(x),requestId:e.request_id,toolCallId:e.tool_call.tool_call_id})}):nj.warn("Sandbox Tool 调用事件解析失败")}else if("sandbox_resource_changed"===A.name){let e=function(x){let e=hx(x);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.data&&"object"==typeof e.data&&!Array.isArray(e.data)?e.data:void 0,r=t?.resource,a=t?.action,_=t?.resource_id,n=t?.revision;if(("notice"===r||"task"===r)&&("upsert"===a||"remove"===a)&&"string"==typeof _&&_&&("number"==typeof n||"string"==typeof n))return{action:a,eventId:"string"==typeof e.event_id?e.event_id:"",occurredAtMs:"number"==typeof e.occurred_at_ms?e.occurred_at_ms:void 0,resource:r,resourceId:_,revision:n}}(A.data);e?x.onResourceChanged?.(e):nj.warn("Sandbox 资源事件解析失败")}else if("card_delta"===A.name){let e=function(x){let e=hx(x);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.data&&"object"==typeof e.data&&!Array.isArray(e.data)?e.data:void 0,r=t?.card_delta;if(!("card_delta"!==e.type||!r||"object"!=typeof r||Array.isArray(r)))return r}(A.data);e?x.onSimulatorEvent?.({payload:e,type:"card_delta"}):nj.warn("Sandbox 模拟器事件解析失败",{event:A.name})}else if("get_simulator_card_snapshots"===A.name){let e=hx(A.data);e&&"object"==typeof e&&!Array.isArray(e)?x.onSimulatorEvent?.({payload:e,type:A.name}):nj.warn("Sandbox 模拟器事件解析失败",{event:A.name})}r=i.search(/\r?\n\r?\n/)}}}async function hn(x,e){let t=0,r=!1;for(;!e.aborted;){try{await h_(x,e,()=>{r=!1,x.onConnectionStatusChange?.("connected")}),t=0}catch(t){if(e.aborted)return;let x=t.status;if(r||(nj.warn("无法接收来自平台服务的请求",{reason:t.message}),r=!0),401===x||403===x||404===x)return}x.onConnectionStatusChange?.("reconnecting"),await xC(m3[Math.min(t,m3.length-1)],void 0,{signal:e}).catch(()=>void 0),t+=1}}let hA="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",hs="/app_developer/api/sandbox/session/business_info/update";function hi(x){if(!x)return!1;try{return B.statSync(x).isFile()}catch{return!1}}async function ho({body:x,headers:e,method:t,sandboxPath:r,targetOrigin:a,targetUrl:_}){let n=new AbortController,A=setTimeout(()=>n.abort(),3e4);try{return a?await fetch(_,{body:x,headers:e,method:t,signal:n.signal}):await _f({internal:!0,path:r,body:x,headers:e,method:t,signal:n.signal})}catch(x){if(n.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${_}`);throw x}finally{clearTimeout(A)}}function hl(x,e){return(x?.[e]??process.env[e])?.trim()??""}function hc(x,e,t,r,a,_){if(!ev())return;let n=Number(process.hrtime.bigint()-r)/1e6;nj.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:n,headers:a,logId:_})}function hv({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:_,targetUrl:n}){nX({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:_,targetUrl:n})}async function hd(x,e,t,r,a,_){let n,A,s="/app_developer/api/sandbox/session/create",i="POST",o=function(){let x=new Set;for(let e of(process.env[hA]??"").split(",")){let t=e.trim();if(t)try{let e=new URL(t),r=e.hostname.replace(/^\[|\]$/g,"").toLowerCase(),a="localhost"===r||"::1"===r||4===x$(r)&&r.startsWith("127.");if("http:"!==e.protocol&&"https:"!==e.protocol||!a)throw Error("仅允许本机回环 HTTP(S) origin");x.add(e.origin)}catch(x){throw Error(`${hA} 包含无效 origin:${t}(${x instanceof Error?x.message:String(x)})`)}}return[...x]}(),l=JSON.stringify({sandbox_project_id:x,manifest:t?.()??(hi(e)?B.readFileSync(e,"utf8"):""),business_templates:hi(r)?B.readFileSync(r,"utf8"):"",..._?{app_id:_}:{},...o.length>0?{bridge_origins:o}:{}}),c={"content-type":"application/json",..._c()},v=new URL(s,a??e$),d=process.hrtime.bigint();try{n=await ho({body:l,headers:c,method:i,sandboxPath:s,targetOrigin:a,targetUrl:v})}catch(e){let x=`创建 Sandbox session 请求失败:${e instanceof Error?e.message:String(e)}`;throw hc(i,v,502,d,c),hv({method:i,requestBody:l,requestHeaders:c,responseBody:x,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:v}),e}let f=n.headers.get(nB)||"",b=await n.text();hc(i,v,n.status,d,c,f),hv({method:i,requestBody:l,requestHeaders:c,responseBody:b,responseHeaders:n.headers,statusCode:n.status,targetUrl:v});try{A=JSON.parse(b||"{}")}catch{throw Error(`创建 Sandbox session 失败:HTTP ${n.status} ${n.statusText||b||"响应不是有效 JSON"}${f?`,log_id=${f}`:""}`)}if(!n.ok||0!==A.code)throw Error(`创建 Sandbox session 失败:${A.message||n.statusText||n.status}${A.log_id||f?`,log_id=${A.log_id||f}`:""}`);let u=A.data?.sandbox_session_id,p=A.data?.sandbox_appid;if(!u||!p)throw Error(`创建 Sandbox session 失败:响应缺少 ${u?"sandbox_appid":"sandbox_session_id"}${A.log_id||f?`,log_id=${A.log_id||f}`:""}`);return{appId:p,sessionId:u}}async function hf(x,e,t,r,a,_){try{return await hd(x,e,t,r,a,_)}catch(x){return nj.warn(`Sandbox 平台服务模拟已跳过:${x instanceof Error?x.message:String(x)}`),{appId:"",sessionId:""}}}function hb(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function hu(x){return{csrUploaded:!!x,phoneNumberUploaded:!0}}async function hp(x,e){let t,r,a="/app_developer/api/sandbox/session/business_info/get",_="POST",n=JSON.stringify({sandbox_session_id:x}),A={"content-type":"application/json",..._c()},s=new URL(a,e??e$),i=process.hrtime.bigint();try{t=await ho({body:n,headers:A,method:_,sandboxPath:a,targetOrigin:e,targetUrl:s})}catch(x){throw hc(_,s,502,i,A),x}let o=t.headers.get(nB)||"",l=await t.text();hc(_,s,t.status,i,A,o);try{r=JSON.parse(l||"{}")}catch{throw hv({method:_,requestBody:n,requestHeaders:A,responseBody:JSON.stringify({omitted:"Sandbox 业务信息响应无效"}),responseHeaders:t.headers,statusCode:t.status,targetUrl:s}),Error(`获取 Sandbox session 信息失败:HTTP ${t.status} 响应不是有效 JSON${o?`,log_id=${o}`:""}`)}let c={csrUploaded:!!r.data?.csr_pem?.trim(),phoneNumberUploaded:!!r.data?.phone_num?.trim()};if(hv({method:_,requestBody:n,requestHeaders:A,responseBody:JSON.stringify({code:r.code,data:c,log_id:r.log_id}),responseHeaders:t.headers,statusCode:t.status,targetUrl:s}),!t.ok||void 0!==r.code&&0!==r.code)throw Error(`获取 Sandbox session 信息失败:${r.message||t.statusText||t.status}${r.log_id||o?`,log_id=${r.log_id||o}`:""}`);return c}async function hm(x,e){if(!x)return hb();try{return await hp(x,e)}catch(x){return nj.warn(`Sandbox session 信息查询已跳过:${x instanceof Error?x.message:String(x)}`),hb()}}async function hh(x,e,t){let r,a,_="POST",n=JSON.stringify({...x.csrPem?{csr_pem:x.csrPem}:{},phone_num:x.phoneNum,sandbox_session_id:e}),A={"content-type":"application/json",..._c(),[nN]:e},s=new URL(hs,t??e$),i=process.hrtime.bigint();try{r=await ho({body:n,headers:A,method:_,sandboxPath:hs,targetOrigin:t,targetUrl:s})}catch(x){throw hc(_,s,502,i,A),x}let o=r.headers.get(nB)||"",l=await r.text();hc(_,s,r.status,i,A,o),hv({method:_,requestBody:JSON.stringify({...x.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:e}),requestHeaders:A,responseBody:l,responseHeaders:r.headers,statusCode:r.status,targetUrl:s});try{a=JSON.parse(l||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${o?`,log_id=${o}`:""}`)}if(!r.ok||void 0!==a.code&&0!==a.code)throw Error(`更新 Sandbox session 信息失败:${a.message||r.statusText||r.status}${a.log_id||o?`,log_id=${a.log_id||o}`:""}`)}async function hE(x,e,t,r){if(x&&e.phoneNum&&(!t||e.csrPem))try{return await hh({...e.csrPem?{csrPem:e.csrPem}:{},phoneNum:e.phoneNum},x,r),nj.info("Sandbox 业务信息已自动上传",{sessionId:x}),hu(e.csrPem)}catch(x){nj.warn(`Sandbox 业务信息自动上传已跳过:${x instanceof Error?x.message:String(x)}`);return}}async function hj(x,e){let t,r="/app_developer/api/sandbox/session/revoke",a="POST",_=JSON.stringify({sandbox_session_id:x}),n={"content-type":"application/json",..._c()},A=new URL(r,e??e$),s=process.hrtime.bigint();try{t=await ho({body:_,headers:n,method:a,sandboxPath:r,targetOrigin:e,targetUrl:A})}catch(e){let x=`撤回 Sandbox session 请求失败:${e instanceof Error?e.message:String(e)}`;throw hc(a,A,502,s,n),hv({method:a,requestBody:_,requestHeaders:n,responseBody:x,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:A}),e}let i=t.headers.get(nB)||"",o=await t.text();hc(a,A,t.status,s,n,i),hv({method:a,requestBody:_,requestHeaders:n,responseBody:o,responseHeaders:t.headers,statusCode:t.status,targetUrl:A});let l=JSON.parse(o||"{}");if(!t.ok||0!==l.code)throw Error(`撤回 Sandbox session 失败:${l.message||t.statusText||t.status}${l.log_id||i?`,log_id=${l.log_id||i}`:""}`)}async function hg(x){if(x.recreatePromise)return x.recreatePromise;x.recreatePromise=(async()=>{var e;let t=x.sandboxSessionId;t&&await hj(t,x.sandboxTargetOrigin),x.bridge?.close(),x.bridge=void 0;let r=await hd(x.sandboxProjectId,x.simulatorManifestPath,x.simulatorManifestReader,x.simulatorBusinessTemplatesPath,x.sandboxTargetOrigin,x.sandboxSessionAppId),a=r.sessionId,_=!x.sandboxSessionAppId,n=await hE(a,x.businessInfoInput,_,x.sandboxTargetOrigin)??await hm(a,x.sandboxTargetOrigin);return x.sandboxAppId=r.appId,x.sandboxSessionId=a,x.businessInfo=n,(e=x).resourceConnectionStatus="connecting",e.resourceEventSequence=0,e.resourceEvents.length=0,e.simulatorEventSequence=0,e.simulatorEvents.length=0,e.resourceGeneration+=1,hI(e),x.bridge=hN(x,a),nj.info("Sandbox session 已重建",{sessionId:a}),{...r,businessInfoUploaded:n.phoneNumberUploaded&&(!_||n.csrUploaded)}})();try{return await x.recreatePromise}finally{x.recreatePromise=void 0}}function hy(x){return{bridgeLogs:x.bridgeLogs,bridgeLogsUpdatedAtMs:x.bridgeLogsUpdatedAtMs,connectionStatus:x.resourceConnectionStatus,events:x.resourceEvents,generation:x.resourceGeneration,instanceId:x.resourceInstanceId,simulatorEvents:x.simulatorEvents,updatedAtMs:x.resourceEventsUpdatedAtMs}}function hS(x){clearTimeout(x.logBroadcastTimer),x.logBroadcastTimer=void 0;let e=hy(x);for(let t of x.eventListeners)t(e)}function hI(x){x.resourceEventsUpdatedAtMs=Math.max(Date.now(),x.resourceEventsUpdatedAtMs+1),hS(x)}function hN(x,e){var t={onConnectionStatusChange:e=>{x.resourceConnectionStatus!==e&&(x.resourceConnectionStatus=e,hI(x))},onLog:e=>{let t=x.bridgeLogs.findIndex(x=>x.id===e.id);t>=0?x.bridgeLogs[t]=e:(x.bridgeLogs.push(e),x.bridgeLogs.length>200&&x.bridgeLogs.splice(0,x.bridgeLogs.length-200)),x.bridgeLogsUpdatedAtMs=Math.max(Date.now(),x.bridgeLogsUpdatedAtMs+1),x.logBroadcastTimer??=setTimeout(()=>hS(x),50)},onResourceChanged:e=>{x.resourceEvents.push({...e,sequence:++x.resourceEventSequence}),x.resourceEvents.length>200&&x.resourceEvents.splice(0,x.resourceEvents.length-200),hI(x)},onSimulatorEvent:e=>{x.simulatorEvents.push({...e,sequence:++x.simulatorEventSequence}),x.simulatorEvents.length>200&&x.simulatorEvents.splice(0,x.simulatorEvents.length-200),hI(x)},onSimulatorToolCall:x.onSimulatorToolCall,sandboxSessionId:e,targetOrigin:x.sandboxTargetOrigin};if(!t.sandboxSessionId)return void nj.warn("已跳过 Sandbox Bridge:缺少 Sandbox session id");let r=new AbortController;return ht("正在启动 Sandbox Bridge",{session:m4(t.sandboxSessionId)}),t.onConnectionStatusChange?.("connecting"),hn(t,r.signal),{close:()=>r.abort()}}async function hB(x,e,t,r){if("POST"!==x.method)return void nL(e,405,"不支持的请求方法");if(hF(x,e,r)){if(!t)return void nL(e,503,"Sandbox session 尚未初始化");try{let r=await nR(x,e,1048576);if(r){let x=JSON.parse(r);if(void 0!==x.csrPem&&"string"!=typeof x.csrPem||"string"!=typeof x.phoneNum)return void nL(e,400,"Sandbox 业务信息无效");t.businessInfoInput={..."string"==typeof x.csrPem&&x.csrPem.trim()?{csrPem:x.csrPem.trim()}:{},phoneNum:x.phoneNum.trim()}}let a=await hg(t);nq(e,200,{code:0,data:{sandbox_appid:a.appId,business_info_uploaded:a.businessInfoUploaded,sandbox_session_id:a.sessionId},message:"ok"})}catch(x){nL(e,500,x.message)}}}function hF(x,e,t){let r=x.headers.origin;return"string"==typeof r&&!!t.includes(r)||(nL(e,403,"Sandbox 控制请求来源无效"),!1)}function hw(x){let e=x.appId?.trim(),t=e&&!e.startsWith("doubao-sandbox-app-")?e:void 0,r=function(x){let e=y.resolve(x??process.cwd()),t=e;try{t=B.realpathSync.native(e)}catch{}return xE("sha256").update(t).digest("hex")}(x.appDirectory),a=function(x,e){let t=hl(x,"DOUBAO_SANDBOX_PHONE_NUM"),r=hl(x,"DOUBAO_SANDBOX_CSR_FILE"),a=function(x,e){if(!x)return;let t=y.isAbsolute(x)?x:y.resolve(e??process.cwd(),x);return hi(t)?t:void 0}(r,e),_="";if(r&&!a)nj.warn(`Sandbox CSR 文件不存在:${r}`);else if(a)try{_=B.readFileSync(a,"utf8").trim()}catch(x){nj.warn(`Sandbox CSR 文件读取失败:${x instanceof Error?x.message:String(x)}`)}return{...t?{phoneNum:t}:{},..._?{csrPem:_}:{}}}(x.env,x.appDirectory),_=`${a.phoneNum??""}\0${a.csrPem??""}`;return{businessInfoInput:a,businessInfoInputKey:_,businessTemplatesPath:x.businessTemplatesPath,key:JSON.stringify([_,r,t,x.targetOrigin,x.businessTemplatesPath,x.manifestPath]),manifestReader:x.manifestReader,manifestPath:x.manifestPath,onSimulatorToolCall:x.onSimulatorToolCall,projectId:r,sessionAppId:t,targetOrigin:x.targetOrigin}}class hC{configKey;manifestReader;state;constructor(x,e,t){this.state=x,this.configKey=e,this.manifestReader=t}static async start(x){let e=hw(x),t=await hf(e.projectId,e.manifestPath,e.manifestReader,e.businessTemplatesPath,e.targetOrigin,e.sessionAppId),r=!e.sessionAppId,a={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await hE(t.sessionId,e.businessInfoInput,r,e.targetOrigin)??await hm(t.sessionId,e.targetOrigin),businessInfoInput:e.businessInfoInput,eventListeners:new Set,onSimulatorToolCall:e.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,resourceInstanceId:xj(),simulatorEventSequence:0,simulatorEvents:[],sandboxAppId:t.appId,sandboxProjectId:e.projectId,sandboxSessionAppId:e.sessionAppId,sandboxSessionId:t.sessionId,sandboxTargetOrigin:e.targetOrigin,simulatorBusinessTemplatesPath:e.businessTemplatesPath,simulatorManifestReader:e.manifestReader,simulatorManifestPath:e.manifestPath},_=new hC(a,e.key,e.manifestReader);return a.bridge=t.sessionId?hN(a,t.sessionId):void 0,_}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close(),clearTimeout(this.state.logBroadcastTimer),this.state.eventListeners.clear()}subscribeEvents(x){return this.state.eventListeners.add(x),x(hy(this.state)),()=>{this.state.eventListeners.delete(x)}}clearBridgeLogs(){this.state.bridgeLogs.length=0,this.state.bridgeLogsUpdatedAtMs=Math.max(Date.now(),this.state.bridgeLogsUpdatedAtMs+1),hS(this.state)}matches(x){let e=hw(x);return this.configKey===e.key&&this.manifestReader===e.manifestReader}getDebugContext(){var x;let e;return{fileSystemNamespace:(e=(x=this.state).sandboxSessionAppId?`real-app\0${x.sandboxSessionAppId}`:`virtual-app\0${x.sandboxAppId}\0${x.sandboxProjectId}`,`sandbox-v1:${xE("sha256").update(e).digest("hex")}`),sandboxSessionAvailable:!!this.state.sandboxSessionId,sandboxCsrRequired:!this.state.sandboxSessionAppId,sandboxCsrUploaded:this.state.businessInfo.csrUploaded,sandboxPhoneNumberUploaded:this.state.businessInfo.phoneNumberUploaded,sandboxEventsAvailable:!0,...this.state.businessInfoInput.csrPem?{sandboxCsrPem:this.state.businessInfoInput.csrPem}:{},...this.state.businessInfoInput.phoneNum?{sandboxPhoneNum:this.state.businessInfoInput.phoneNum}:{}}}getRequestRoutes(x=[]){return[{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>{hF(e,t,x)&&mz(e,t,{onBusinessInfoUpdated:x=>{this.state.businessInfo=hu(x?.csrPem),x&&(this.state.businessInfoInput=x)},sandboxAppId:this.state.sandboxAppId,sandboxSessionId:this.state.sandboxSessionId,targetOrigin:this.state.sandboxTargetOrigin})}},{match:"/__web_sdk_sandbox_session_recreate__",handle:({request:e,response:t})=>hB(e,t,this.state,x)}]}}function hP(x,e){return x.relativePath<e.relativePath?-1:+(x.relativePath>e.relativePath)}let hk="/__tools/tools.json",hD="/__events/events.json",hL="manifest.yaml",hq="skill";function hT(x){if(!x)return!1;try{return B.statSync(x).isFile()}catch{return!1}}function hR(x,e){if(!x)return;let t=y.isAbsolute(x)?x:y.resolve(e??process.cwd(),x);return hT(t)?t:void 0}function h$(x,e){if(x&&e)return y.relative(e,x).split(y.sep).join("/")||"."}function hG(x){let e=y.resolve(x);for(;;){if(hT(y.join(e,hL)))return e;let x=y.dirname(e);if(x===e)return;e=x}}function hO(x){try{return B.lstatSync(x),!0}catch{return!1}}function hX(x,e,t,r){let a;if(!e.reader&&hT(e.sourcePath)){var _;let t,a=B.statSync(e.sourcePath);nD(x),x.writeHead(200,{"Cache-Control":"no-cache","Content-Length":a.size,"Content-Type":r}),_=e.sourcePath,(t=B.createReadStream(_)).once("error",()=>x.destroy()),t.pipe(x);return}try{a=e.reader?.()}catch{a=void 0}void 0===a?nL(x,404,`未找到 ${t}`):(nD(x),x.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(a),"Content-Type":r}),x.end(a))}function hK(x,e){return function(x){let e,t;if(!x)return{layout:"missing",entries:[]};let r=y.resolve(x);try{e=B.lstatSync(r)}catch(x){if("ENOENT"===x.code)return{directory:r,layout:"missing",entries:[]};return{directory:r,layout:"invalid",entries:[],error:`skill path cannot be inspected: ${r}: ${x.message}`}}if(e.isSymbolicLink()||!e.isDirectory())return{directory:r,layout:"invalid",entries:[],error:`skill path must be a non-symlink directory: ${r}`};try{var a;let x;a=r,x=[],function e(t){for(let r of B.readdirSync(t,{withFileTypes:!0})){if(r.isSymbolicLink())continue;let _=y.join(t,r.name);r.isDirectory()?e(_):r.isFile()&&"SKILL.md"===r.name&&x.push(function(x,e){let t=y.relative(x,e).split(y.sep).join("/");return{content:B.readFileSync(e,"utf8"),relativePath:t}}(a,_))}}(a),t=x}catch(x){return{directory:r,layout:"invalid",entries:[],error:`skill directory is not readable: ${r}: ${x.message}`}}return t.sort(hP),t.length>0?{directory:r,layout:"resolved",entries:t}:{directory:r,layout:"missing",entries:[]}}(function(x,e){if(e){if(!e)return;if(y.isAbsolute(e))return e;let t=x?hG(x):void 0,r=[x,t,process.cwd()].map(x=>y.resolve(x??process.cwd(),e));return[...new Set(r)].find(hO)??r[0]}if(!x)return;let t=hG(x);return[...new Set([t?y.join(t,hq):void 0,y.join(x,hq),y.join(process.cwd(),hq)].filter(Boolean))].find(hO)}(x,e))}class hQ{appDirectory;businessTemplatesPath;manifestPath;manifestReader;eventsConfigReader;eventsConfigSource;toolsConfigReader;toolsConfigSource;manifestSource;skillsDirectory;skillsReader;sourceKey;constructor(x){var e,t,r;this.appDirectory=x.appDirectory,this.manifestPath=x.manifestPath?hR(x.manifestPath,x.appDirectory):x.manifestSourcePath??(x.manifestReader?void 0:function(x){if(!x)return;let e=hG(x);return[...new Set([e?y.join(e,hL):void 0,y.join(process.cwd(),hL)].filter(Boolean))].find(hT)}(x.appDirectory)),this.businessTemplatesPath=(e=this.manifestPath,t=x.businessTemplatesPath,r=x.appDirectory,t?hR(t,r):e?hR(y.join(y.dirname(e),"business-templates.yaml"),r):void 0),this.manifestReader=x.manifestReader,this.eventsConfigReader=x.eventsConfigReader,this.toolsConfigReader=x.toolsConfigReader,this.eventsConfigSource={reader:x.eventsConfigReader,sourcePath:x.eventsConfigSourcePath},this.skillsDirectory=x.skillsDirectory,this.skillsReader=x.skillsReader;let a=x.skillsReader?void 0:hK(x.appDirectory,this.skillsDirectory);if(!x.skillsReader&&x.skillsDirectory&&a?.layout!=="resolved")throw Error(a?.error??`Simulator skills directory contains no runtime Skill: ${x.skillsDirectory}`);this.toolsConfigSource={reader:x.toolsConfigReader,sourcePath:x.toolsConfigSourcePath},this.manifestSource={reader:x.manifestReader,sourcePath:x.manifestSourcePath??this.manifestPath},this.sourceKey=JSON.stringify([this.appDirectory,this.businessTemplatesPath,this.manifestPath,this.eventsConfigSource.sourcePath,this.toolsConfigSource.sourcePath,this.manifestSource.sourcePath,this.skillsDirectory])}matches(x){let e=new hQ(x);return this.sourceKey===e.sourceKey&&this.eventsConfigReader===e.eventsConfigReader&&this.toolsConfigReader===e.toolsConfigReader&&this.manifestReader===e.manifestReader&&this.skillsReader===e.skillsReader}getDebugContext(){let x=this.skillsReader?void 0:hK(this.appDirectory,this.skillsDirectory),e=x?.layout==="resolved"?x.directory:void 0,t=h$(this.businessTemplatesPath,this.appDirectory),r=h$(this.eventsConfigSource.sourcePath,this.appDirectory),a=h$(this.toolsConfigSource.sourcePath,this.appDirectory),_=h$(this.manifestSource.sourcePath,this.appDirectory),n=h$(e,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:hD,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...r?{eventsConfigRelativePath:r}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:hk,...a?{toolsConfigRelativePath:a}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,..._?{simulatorManifestRelativePath:_}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...t?{simulatorBusinessTemplatesRelativePath:t}:{}}:{},...e?{simulatorSkillsDirectoryOriginalUrl:e,...n?{simulatorSkillsDirectoryRelativePath:n}:{}}:{}}}getRequestRoutes(){return[{match:hD,handle:({response:x})=>hX(x,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:hk,handle:({response:x})=>hX(x,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:x})=>hX(x,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:x})=>{let e;if(this.skillsReader){try{nq(x,200,{skills:this.skillsReader()},{"Cache-Control":"no-cache"})}catch{nL(x,422,"无法读取项目 Skills")}return}"missing"===(e=hK(this.appDirectory,this.skillsDirectory)).layout?nL(x,404,"未找到模拟器 Skill 目录"):"invalid"===e.layout?nL(x,422,e.error??"模拟器 Skill 目录结构无效"):nq(x,200,{skills:e.entries},{"Cache-Control":"no-cache"})}}]}}let hZ="/app_developer/api",hM=`${hZ}/simulator/images/upload`,hJ=new Set([`${hZ}/simulator/chat`,hM,`${hZ}/simulator/tool/report`]),hV={"Access-Control-Expose-Headers":nB};async function hH(x,e,t,r){if(!hJ.has(t.pathname))return void nL(e,404,"未找到模拟器接口",hV);let a=r.targetOrigin??e$,_=new URL(`${t.pathname}${t.search}`,a),n=nK(x,e);try{var A;let a=x.method??"GET",s=process.hrtime.bigint(),i=function(x,e,t){return Object.fromEntries(Object.entries(nC(x.headers,e,{..._c(),...t?{[nN]:t}:{}})).filter(([x,e])=>"host"!==x.toLowerCase()&&void 0!==e).map(([x,e])=>[x,Array.isArray(e)?e.join(", "):String(e)]))}(x,_,r.getSandboxSessionId?.()),o=await hU(x,e,t,a),l=r.targetOrigin?await fetch(_,{body:o,headers:i,method:a,signal:n}):await _f({internal:!0,path:`${t.pathname}${t.search}`,method:a,body:o,headers:i,signal:n});if(function(x,e,t,r,a,_){if(!ev())return;let n=Number(process.hrtime.bigint()-r)/1e6;nj.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:n,headers:a,logId:_})}(a,t,l.status,s,i,l.headers.get(nB)??void 0),e.destroyed||e.writableEnded)return void l.body?.cancel().catch(()=>void 0);await hY({method:a,requestBody:(A=o)instanceof Uint8Array?`(binary, ${A.byteLength} bytes)`:A,requestHeaders:i,requestUrl:t,response:e,upstreamResponse:l})}catch(x){if(e.destroyed||e.writableEnded||n.aborted)return;nL(e,502,`代理模拟器请求失败:${x instanceof Error?x.message:String(x)}`,hV)}}async function hU(x,e,t,r){if("GET"!==r&&"HEAD"!==r)return t.pathname===hM?await nT(x,e,0xb00000):await nR(x,e,0xb00000)}async function hY({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:_}){var n,A;if(nD(a,hV),a.writeHead(_.status,nk(_.headers,[nB])),n=r,A=_,n.pathname===`${hZ}/simulator/chat`||A.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await hz({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:_});if(!ev())return _.body?void await R(xX.fromWeb(_.body),a):void a.end();let s=await n$(_);nX({method:x,requestBody:e,requestHeaders:t,responseBody:s,responseHeaders:_.headers,statusCode:_.status,targetUrl:r}),a.end(s)}async function hz({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:_}){if(!_.body){nX({method:x,requestBody:e,requestHeaders:t,responseBody:"",responseHeaders:_.headers,statusCode:_.status,targetUrl:r}),a.end();return}let n=xX.fromWeb(_.body);if(!ev())return void await R(n,a);nX({method:x,requestBody:e,requestHeaders:t,responseBody:"(event stream)",responseHeaders:_.headers,statusCode:_.status,targetUrl:r});let A=new xK({transform(x,e,t){let a;try{a=String(x).split("\n\n").filter(Boolean)}catch(e){return nj.error(`事件流分片解码失败:${e?.toString()}`),t(null,x)}for(let x of a)nj.info(`来自 ${r.pathname}${r.search} 的事件
396
+ ${x.data}`)}(A,_),"bridge_request"===A.name){var o,l,c=n.headers,v=n.status;nX({method:`EVENT ${A.name}`,requestBody:A.data,requestHeaders:_,responseBody:"",responseHeaders:c,statusCode:v,targetUrl:a}),ha(x,A.data).catch(x=>{nj.warn("Sandbox Bridge 请求处理失败",{reason:x.message})})}else if("TOOL_CALL"===A.name){let e="object"==typeof(l=hx(A.data))&&l?.tool_call?l:void 0;e?Promise.resolve(x.onSimulatorToolCall?.(e)).catch(x=>{nj.warn("Sandbox Tool 调用转发失败",{reason:x instanceof Error?x.message:String(x),requestId:e.request_id,toolCallId:e.tool_call.tool_call_id})}):nj.warn("Sandbox Tool 调用事件解析失败")}else if("sandbox_resource_changed"===A.name){let e=function(x){let e=hx(x);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.data&&"object"==typeof e.data&&!Array.isArray(e.data)?e.data:void 0,r=t?.resource,a=t?.action,_=t?.resource_id,n=t?.revision;if(("notice"===r||"task"===r)&&("upsert"===a||"remove"===a)&&"string"==typeof _&&_&&("number"==typeof n||"string"==typeof n))return{action:a,eventId:"string"==typeof e.event_id?e.event_id:"",occurredAtMs:"number"==typeof e.occurred_at_ms?e.occurred_at_ms:void 0,resource:r,resourceId:_,revision:n}}(A.data);e?x.onResourceChanged?.(e):nj.warn("Sandbox 资源事件解析失败")}else if("card_delta"===A.name){let e=function(x){let e=hx(x);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.data&&"object"==typeof e.data&&!Array.isArray(e.data)?e.data:void 0,r=t?.card_delta;if(!("card_delta"!==e.type||!r||"object"!=typeof r||Array.isArray(r)))return r}(A.data);e?x.onSimulatorEvent?.({payload:e,type:"card_delta"}):nj.warn("Sandbox 模拟器事件解析失败",{event:A.name})}else if("get_simulator_card_snapshots"===A.name){let e=hx(A.data);e&&"object"==typeof e&&!Array.isArray(e)?x.onSimulatorEvent?.({payload:e,type:A.name}):nj.warn("Sandbox 模拟器事件解析失败",{event:A.name})}r=i.search(/\r?\n\r?\n/)}}}async function hn(x,e){let t=0,r=!1;for(;!e.aborted;){try{await h_(x,e,()=>{r=!1,x.onConnectionStatusChange?.("connected")}),t=0}catch(t){if(e.aborted)return;let x=t.status;if(r||(nj.warn("无法接收来自平台服务的请求",{reason:t.message}),r=!0),401===x||403===x||404===x)return}x.onConnectionStatusChange?.("reconnecting"),await xC(m3[Math.min(t,m3.length-1)],void 0,{signal:e}).catch(()=>void 0),t+=1}}let hA="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",hs="/app_developer/api/sandbox/session/business_info/update";function hi(x){if(!x)return!1;try{return B.statSync(x).isFile()}catch{return!1}}async function ho({body:x,headers:e,method:t,sandboxPath:r,targetOrigin:a,targetUrl:_}){let n=new AbortController,A=setTimeout(()=>n.abort(),3e4);try{return a?await fetch(_,{body:x,headers:e,method:t,signal:n.signal}):await _f({internal:!0,path:r,body:x,headers:e,method:t,signal:n.signal})}catch(x){if(n.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${_}`);throw x}finally{clearTimeout(A)}}function hl(x,e){return(x?.[e]??process.env[e])?.trim()??""}function hc(x,e,t,r,a,_){if(!ev())return;let n=Number(process.hrtime.bigint()-r)/1e6;nj.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:n,headers:a,logId:_})}function hv({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:_,targetUrl:n}){nX({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:_,targetUrl:n})}async function hd(x,e,t,r,a,_){let n,A,s="/app_developer/api/sandbox/session/create",i="POST",o=function(){let x=new Set;for(let e of(process.env[hA]??"").split(",")){let t=e.trim();if(t)try{let e=new URL(t),r=e.hostname.replace(/^\[|\]$/g,"").toLowerCase(),a="localhost"===r||"::1"===r||4===x$(r)&&r.startsWith("127.");if("http:"!==e.protocol&&"https:"!==e.protocol||!a)throw Error("仅允许本机回环 HTTP(S) origin");x.add(e.origin)}catch(x){throw Error(`${hA} 包含无效 origin:${t}(${x instanceof Error?x.message:String(x)})`)}}return[...x]}(),l=JSON.stringify({sandbox_project_id:x,manifest:t?.()??(hi(e)?B.readFileSync(e,"utf8"):""),business_templates:hi(r)?B.readFileSync(r,"utf8"):"",..._?{app_id:_}:{},...o.length>0?{bridge_origins:o}:{}}),c={"content-type":"application/json",..._c()},v=new URL(s,a??e$),d=process.hrtime.bigint();try{n=await ho({body:l,headers:c,method:i,sandboxPath:s,targetOrigin:a,targetUrl:v})}catch(e){let x=`创建 Sandbox session 请求失败:${e instanceof Error?e.message:String(e)}`;throw hc(i,v,502,d,c),hv({method:i,requestBody:l,requestHeaders:c,responseBody:x,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:v}),e}let f=n.headers.get(nB)||"",b=await n.text();hc(i,v,n.status,d,c,f),hv({method:i,requestBody:l,requestHeaders:c,responseBody:b,responseHeaders:n.headers,statusCode:n.status,targetUrl:v});try{A=JSON.parse(b||"{}")}catch{throw Error(`创建 Sandbox session 失败:HTTP ${n.status} ${n.statusText||b||"响应不是有效 JSON"}${f?`,log_id=${f}`:""}`)}if(!n.ok||0!==A.code)throw Error(`创建 Sandbox session 失败:${A.message||n.statusText||n.status}${A.log_id||f?`,log_id=${A.log_id||f}`:""}`);let u=A.data?.sandbox_session_id,p=A.data?.sandbox_appid;if(!u||!p)throw Error(`创建 Sandbox session 失败:响应缺少 ${u?"sandbox_appid":"sandbox_session_id"}${A.log_id||f?`,log_id=${A.log_id||f}`:""}`);return{appId:p,sessionId:u}}async function hf(x,e,t,r,a,_){try{return await hd(x,e,t,r,a,_)}catch(x){return nj.warn(`Sandbox 平台服务模拟已跳过:${x instanceof Error?x.message:String(x)}`),{appId:"",sessionId:""}}}function hb(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function hu(x){return{csrUploaded:!!x,phoneNumberUploaded:!0}}async function hp(x,e){let t,r,a="/app_developer/api/sandbox/session/business_info/get",_="POST",n=JSON.stringify({sandbox_session_id:x}),A={"content-type":"application/json",..._c()},s=new URL(a,e??e$),i=process.hrtime.bigint();try{t=await ho({body:n,headers:A,method:_,sandboxPath:a,targetOrigin:e,targetUrl:s})}catch(x){throw hc(_,s,502,i,A),x}let o=t.headers.get(nB)||"",l=await t.text();hc(_,s,t.status,i,A,o);try{r=JSON.parse(l||"{}")}catch{throw hv({method:_,requestBody:n,requestHeaders:A,responseBody:JSON.stringify({omitted:"Sandbox 业务信息响应无效"}),responseHeaders:t.headers,statusCode:t.status,targetUrl:s}),Error(`获取 Sandbox session 信息失败:HTTP ${t.status} 响应不是有效 JSON${o?`,log_id=${o}`:""}`)}let c={csrUploaded:!!r.data?.csr_pem?.trim(),phoneNumberUploaded:!!r.data?.phone_num?.trim()};if(hv({method:_,requestBody:n,requestHeaders:A,responseBody:JSON.stringify({code:r.code,data:c,log_id:r.log_id}),responseHeaders:t.headers,statusCode:t.status,targetUrl:s}),!t.ok||void 0!==r.code&&0!==r.code)throw Error(`获取 Sandbox session 信息失败:${r.message||t.statusText||t.status}${r.log_id||o?`,log_id=${r.log_id||o}`:""}`);return c}async function hm(x,e){if(!x)return hb();try{return await hp(x,e)}catch(x){return nj.warn(`Sandbox session 信息查询已跳过:${x instanceof Error?x.message:String(x)}`),hb()}}async function hh(x,e,t){let r,a,_="POST",n=JSON.stringify({...x.csrPem?{csr_pem:x.csrPem}:{},phone_num:x.phoneNum,sandbox_session_id:e}),A={"content-type":"application/json",..._c(),[nN]:e},s=new URL(hs,t??e$),i=process.hrtime.bigint();try{r=await ho({body:n,headers:A,method:_,sandboxPath:hs,targetOrigin:t,targetUrl:s})}catch(x){throw hc(_,s,502,i,A),x}let o=r.headers.get(nB)||"",l=await r.text();hc(_,s,r.status,i,A,o),hv({method:_,requestBody:JSON.stringify({...x.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:e}),requestHeaders:A,responseBody:l,responseHeaders:r.headers,statusCode:r.status,targetUrl:s});try{a=JSON.parse(l||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${o?`,log_id=${o}`:""}`)}if(!r.ok||void 0!==a.code&&0!==a.code)throw Error(`更新 Sandbox session 信息失败:${a.message||r.statusText||r.status}${a.log_id||o?`,log_id=${a.log_id||o}`:""}`)}async function hE(x,e,t,r){if(x&&e.phoneNum&&(!t||e.csrPem))try{return await hh({...e.csrPem?{csrPem:e.csrPem}:{},phoneNum:e.phoneNum},x,r),nj.info("Sandbox 业务信息已自动上传",{sessionId:x}),hu(e.csrPem)}catch(x){nj.warn(`Sandbox 业务信息自动上传已跳过:${x instanceof Error?x.message:String(x)}`);return}}async function hj(x,e){let t,r="/app_developer/api/sandbox/session/revoke",a="POST",_=JSON.stringify({sandbox_session_id:x}),n={"content-type":"application/json",..._c()},A=new URL(r,e??e$),s=process.hrtime.bigint();try{t=await ho({body:_,headers:n,method:a,sandboxPath:r,targetOrigin:e,targetUrl:A})}catch(e){let x=`撤回 Sandbox session 请求失败:${e instanceof Error?e.message:String(e)}`;throw hc(a,A,502,s,n),hv({method:a,requestBody:_,requestHeaders:n,responseBody:x,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:A}),e}let i=t.headers.get(nB)||"",o=await t.text();hc(a,A,t.status,s,n,i),hv({method:a,requestBody:_,requestHeaders:n,responseBody:o,responseHeaders:t.headers,statusCode:t.status,targetUrl:A});let l=JSON.parse(o||"{}");if(!t.ok||0!==l.code)throw Error(`撤回 Sandbox session 失败:${l.message||t.statusText||t.status}${l.log_id||i?`,log_id=${l.log_id||i}`:""}`)}async function hg(x){if(x.recreatePromise)return x.recreatePromise;x.recreatePromise=(async()=>{var e;let t=x.sandboxSessionId;t&&await hj(t,x.sandboxTargetOrigin),x.bridge?.close(),x.bridge=void 0;let r=await hd(x.sandboxProjectId,x.simulatorManifestPath,x.simulatorManifestReader,x.simulatorBusinessTemplatesPath,x.sandboxTargetOrigin,x.sandboxSessionAppId),a=r.sessionId,_=!x.sandboxSessionAppId,n=await hE(a,x.businessInfoInput,_,x.sandboxTargetOrigin)??await hm(a,x.sandboxTargetOrigin);return x.sandboxAppId=r.appId,x.sandboxSessionId=a,x.businessInfo=n,(e=x).resourceConnectionStatus="connecting",e.resourceEventSequence=0,e.resourceEvents.length=0,e.simulatorEventSequence=0,e.simulatorEvents.length=0,e.resourceGeneration+=1,hI(e),x.bridge=hN(x,a),nj.info("Sandbox session 已重建",{sessionId:a}),{...r,businessInfoUploaded:n.phoneNumberUploaded&&(!_||n.csrUploaded)}})();try{return await x.recreatePromise}finally{x.recreatePromise=void 0}}function hy(x){return{bridgeLogs:x.bridgeLogs,bridgeLogsUpdatedAtMs:x.bridgeLogsUpdatedAtMs,connectionStatus:x.resourceConnectionStatus,events:x.resourceEvents,generation:x.resourceGeneration,instanceId:x.resourceInstanceId,simulatorEvents:x.simulatorEvents,updatedAtMs:x.resourceEventsUpdatedAtMs}}function hS(x){clearTimeout(x.logBroadcastTimer),x.logBroadcastTimer=void 0;let e=hy(x);for(let t of x.eventListeners)t(e)}function hI(x){x.resourceEventsUpdatedAtMs=Math.max(Date.now(),x.resourceEventsUpdatedAtMs+1),hS(x)}function hN(x,e){var t={onConnectionStatusChange:e=>{x.resourceConnectionStatus!==e&&(x.resourceConnectionStatus=e,hI(x))},onLog:e=>{let t=x.bridgeLogs.findIndex(x=>x.id===e.id);t>=0?x.bridgeLogs[t]=e:(x.bridgeLogs.push(e),x.bridgeLogs.length>200&&x.bridgeLogs.splice(0,x.bridgeLogs.length-200)),x.bridgeLogsUpdatedAtMs=Math.max(Date.now(),x.bridgeLogsUpdatedAtMs+1),x.logBroadcastTimer??=setTimeout(()=>hS(x),50)},onResourceChanged:e=>{x.resourceEvents.push({...e,sequence:++x.resourceEventSequence}),x.resourceEvents.length>200&&x.resourceEvents.splice(0,x.resourceEvents.length-200),hI(x)},onSimulatorEvent:e=>{x.simulatorEvents.push({...e,sequence:++x.simulatorEventSequence}),x.simulatorEvents.length>200&&x.simulatorEvents.splice(0,x.simulatorEvents.length-200),hI(x)},onSimulatorToolCall:x.onSimulatorToolCall,sandboxSessionId:e,targetOrigin:x.sandboxTargetOrigin};if(!t.sandboxSessionId)return void nj.warn("已跳过 Sandbox Bridge:缺少 Sandbox session id");let r=new AbortController;return ht("正在启动 Sandbox Bridge",{session:m4(t.sandboxSessionId)}),t.onConnectionStatusChange?.("connecting"),hn(t,r.signal),{close:()=>r.abort()}}async function hB(x,e,t,r){if("POST"!==x.method)return void nL(e,405,"不支持的请求方法");if(hF(x,e,r)){if(!t)return void nL(e,503,"Sandbox session 尚未初始化");try{let r=await nR(x,e,1048576);if(r){let x=JSON.parse(r);if(void 0!==x.csrPem&&"string"!=typeof x.csrPem||"string"!=typeof x.phoneNum)return void nL(e,400,"Sandbox 业务信息无效");t.businessInfoInput={..."string"==typeof x.csrPem&&x.csrPem.trim()?{csrPem:x.csrPem.trim()}:{},phoneNum:x.phoneNum.trim()}}let a=await hg(t);nq(e,200,{code:0,data:{sandbox_appid:a.appId,business_info_uploaded:a.businessInfoUploaded,sandbox_session_id:a.sessionId},message:"ok"})}catch(x){nL(e,500,x.message)}}}function hF(x,e,t){let r=x.headers.origin;return"string"==typeof r&&!!t.includes(r)||(nL(e,403,"Sandbox 控制请求来源无效"),!1)}function hw(x){let e=x.appId?.trim(),t=e&&!e.startsWith("doubao-sandbox-app-")?e:void 0,r=function(x){let e=y.resolve(x??process.cwd()),t=e;try{t=B.realpathSync.native(e)}catch{}return xE("sha256").update(t).digest("hex")}(x.appDirectory),a=function(x,e){let t=hl(x,"DOUBAO_SANDBOX_PHONE_NUM"),r=hl(x,"DOUBAO_SANDBOX_CSR_FILE"),a=function(x,e){if(!x)return;let t=y.isAbsolute(x)?x:y.resolve(e??process.cwd(),x);return hi(t)?t:void 0}(r,e),_="";if(r&&!a)nj.warn(`Sandbox CSR 文件不存在:${r}`);else if(a)try{_=B.readFileSync(a,"utf8").trim()}catch(x){nj.warn(`Sandbox CSR 文件读取失败:${x instanceof Error?x.message:String(x)}`)}return{...t?{phoneNum:t}:{},..._?{csrPem:_}:{}}}(x.env,x.appDirectory),_=`${a.phoneNum??""}\0${a.csrPem??""}`;return{businessInfoInput:a,businessInfoInputKey:_,businessTemplatesPath:x.businessTemplatesPath,key:JSON.stringify([_,r,t,x.targetOrigin,x.businessTemplatesPath,x.manifestPath]),manifestReader:x.manifestReader,manifestPath:x.manifestPath,onSimulatorToolCall:x.onSimulatorToolCall,projectId:r,sessionAppId:t,targetOrigin:x.targetOrigin}}class hC{configKey;manifestReader;state;constructor(x,e,t){this.state=x,this.configKey=e,this.manifestReader=t}static async start(x){let e=hw(x),t=await hf(e.projectId,e.manifestPath,e.manifestReader,e.businessTemplatesPath,e.targetOrigin,e.sessionAppId),r=!e.sessionAppId,a={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await hE(t.sessionId,e.businessInfoInput,r,e.targetOrigin)??await hm(t.sessionId,e.targetOrigin),businessInfoInput:e.businessInfoInput,eventListeners:new Set,onSimulatorToolCall:e.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,resourceInstanceId:xj(),simulatorEventSequence:0,simulatorEvents:[],sandboxAppId:t.appId,sandboxProjectId:e.projectId,sandboxSessionAppId:e.sessionAppId,sandboxSessionId:t.sessionId,sandboxTargetOrigin:e.targetOrigin,simulatorBusinessTemplatesPath:e.businessTemplatesPath,simulatorManifestReader:e.manifestReader,simulatorManifestPath:e.manifestPath},_=new hC(a,e.key,e.manifestReader);return a.bridge=t.sessionId?hN(a,t.sessionId):void 0,_}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close(),clearTimeout(this.state.logBroadcastTimer),this.state.eventListeners.clear()}subscribeEvents(x){return this.state.eventListeners.add(x),x(hy(this.state)),()=>{this.state.eventListeners.delete(x)}}clearBridgeLogs(){this.state.bridgeLogs.length=0,this.state.bridgeLogsUpdatedAtMs=Math.max(Date.now(),this.state.bridgeLogsUpdatedAtMs+1),hS(this.state)}matches(x){let e=hw(x);return this.configKey===e.key&&this.manifestReader===e.manifestReader}getDebugContext(){var x;let e;return{fileSystemNamespace:(e=(x=this.state).sandboxSessionAppId?`real-app\0${x.sandboxSessionAppId}`:`virtual-app\0${x.sandboxAppId}\0${x.sandboxProjectId}`,`sandbox-v1:${xE("sha256").update(e).digest("hex")}`),sandboxSessionAvailable:!!this.state.sandboxSessionId,sandboxAppId:this.state.sandboxAppId,sandboxCsrRequired:!this.state.sandboxSessionAppId,sandboxCsrUploaded:this.state.businessInfo.csrUploaded,sandboxPhoneNumberUploaded:this.state.businessInfo.phoneNumberUploaded,sandboxEventsAvailable:!0,...this.state.businessInfoInput.csrPem?{sandboxCsrPem:this.state.businessInfoInput.csrPem}:{},...this.state.businessInfoInput.phoneNum?{sandboxPhoneNum:this.state.businessInfoInput.phoneNum}:{}}}getRequestRoutes(x=[]){return[{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>{hF(e,t,x)&&mz(e,t,{onBusinessInfoUpdated:x=>{this.state.businessInfo=hu(x?.csrPem),x&&(this.state.businessInfoInput=x)},sandboxAppId:this.state.sandboxAppId,sandboxSessionId:this.state.sandboxSessionId,targetOrigin:this.state.sandboxTargetOrigin})}},{match:"/__web_sdk_sandbox_session_recreate__",handle:({request:e,response:t})=>hB(e,t,this.state,x)}]}}function hP(x,e){return x.relativePath<e.relativePath?-1:+(x.relativePath>e.relativePath)}let hk="/__tools/tools.json",hD="/__events/events.json",hL="manifest.yaml",hq="skill";function hT(x){if(!x)return!1;try{return B.statSync(x).isFile()}catch{return!1}}function hR(x,e){if(!x)return;let t=y.isAbsolute(x)?x:y.resolve(e??process.cwd(),x);return hT(t)?t:void 0}function h$(x,e){if(x&&e)return y.relative(e,x).split(y.sep).join("/")||"."}function hG(x){let e=y.resolve(x);for(;;){if(hT(y.join(e,hL)))return e;let x=y.dirname(e);if(x===e)return;e=x}}function hO(x){try{return B.lstatSync(x),!0}catch{return!1}}function hX(x,e,t,r){let a;if(!e.reader&&hT(e.sourcePath)){var _;let t,a=B.statSync(e.sourcePath);nD(x),x.writeHead(200,{"Cache-Control":"no-cache","Content-Length":a.size,"Content-Type":r}),_=e.sourcePath,(t=B.createReadStream(_)).once("error",()=>x.destroy()),t.pipe(x);return}try{a=e.reader?.()}catch{a=void 0}void 0===a?nL(x,404,`未找到 ${t}`):(nD(x),x.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(a),"Content-Type":r}),x.end(a))}function hK(x,e){return function(x){let e,t;if(!x)return{layout:"missing",entries:[]};let r=y.resolve(x);try{e=B.lstatSync(r)}catch(x){if("ENOENT"===x.code)return{directory:r,layout:"missing",entries:[]};return{directory:r,layout:"invalid",entries:[],error:`skill path cannot be inspected: ${r}: ${x.message}`}}if(e.isSymbolicLink()||!e.isDirectory())return{directory:r,layout:"invalid",entries:[],error:`skill path must be a non-symlink directory: ${r}`};try{var a;let x;a=r,x=[],function e(t){for(let r of B.readdirSync(t,{withFileTypes:!0})){if(r.isSymbolicLink())continue;let _=y.join(t,r.name);r.isDirectory()?e(_):r.isFile()&&"SKILL.md"===r.name&&x.push(function(x,e){let t=y.relative(x,e).split(y.sep).join("/");return{content:B.readFileSync(e,"utf8"),relativePath:t}}(a,_))}}(a),t=x}catch(x){return{directory:r,layout:"invalid",entries:[],error:`skill directory is not readable: ${r}: ${x.message}`}}return t.sort(hP),t.length>0?{directory:r,layout:"resolved",entries:t}:{directory:r,layout:"missing",entries:[]}}(function(x,e){if(e){if(!e)return;if(y.isAbsolute(e))return e;let t=x?hG(x):void 0,r=[x,t,process.cwd()].map(x=>y.resolve(x??process.cwd(),e));return[...new Set(r)].find(hO)??r[0]}if(!x)return;let t=hG(x);return[...new Set([t?y.join(t,hq):void 0,y.join(x,hq),y.join(process.cwd(),hq)].filter(Boolean))].find(hO)}(x,e))}class hQ{appDirectory;businessTemplatesPath;manifestPath;manifestReader;eventsConfigReader;eventsConfigSource;toolsConfigReader;toolsConfigSource;manifestSource;skillsDirectory;skillsReader;sourceKey;constructor(x){var e,t,r;this.appDirectory=x.appDirectory,this.manifestPath=x.manifestPath?hR(x.manifestPath,x.appDirectory):x.manifestSourcePath??(x.manifestReader?void 0:function(x){if(!x)return;let e=hG(x);return[...new Set([e?y.join(e,hL):void 0,y.join(process.cwd(),hL)].filter(Boolean))].find(hT)}(x.appDirectory)),this.businessTemplatesPath=(e=this.manifestPath,t=x.businessTemplatesPath,r=x.appDirectory,t?hR(t,r):e?hR(y.join(y.dirname(e),"business-templates.yaml"),r):void 0),this.manifestReader=x.manifestReader,this.eventsConfigReader=x.eventsConfigReader,this.toolsConfigReader=x.toolsConfigReader,this.eventsConfigSource={reader:x.eventsConfigReader,sourcePath:x.eventsConfigSourcePath},this.skillsDirectory=x.skillsDirectory,this.skillsReader=x.skillsReader;let a=x.skillsReader?void 0:hK(x.appDirectory,this.skillsDirectory);if(!x.skillsReader&&x.skillsDirectory&&a?.layout!=="resolved")throw Error(a?.error??`Simulator skills directory contains no runtime Skill: ${x.skillsDirectory}`);this.toolsConfigSource={reader:x.toolsConfigReader,sourcePath:x.toolsConfigSourcePath},this.manifestSource={reader:x.manifestReader,sourcePath:x.manifestSourcePath??this.manifestPath},this.sourceKey=JSON.stringify([this.appDirectory,this.businessTemplatesPath,this.manifestPath,this.eventsConfigSource.sourcePath,this.toolsConfigSource.sourcePath,this.manifestSource.sourcePath,this.skillsDirectory])}matches(x){let e=new hQ(x);return this.sourceKey===e.sourceKey&&this.eventsConfigReader===e.eventsConfigReader&&this.toolsConfigReader===e.toolsConfigReader&&this.manifestReader===e.manifestReader&&this.skillsReader===e.skillsReader}getDebugContext(){let x=this.skillsReader?void 0:hK(this.appDirectory,this.skillsDirectory),e=x?.layout==="resolved"?x.directory:void 0,t=h$(this.businessTemplatesPath,this.appDirectory),r=h$(this.eventsConfigSource.sourcePath,this.appDirectory),a=h$(this.toolsConfigSource.sourcePath,this.appDirectory),_=h$(this.manifestSource.sourcePath,this.appDirectory),n=h$(e,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:hD,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...r?{eventsConfigRelativePath:r}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:hk,...a?{toolsConfigRelativePath:a}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,..._?{simulatorManifestRelativePath:_}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...t?{simulatorBusinessTemplatesRelativePath:t}:{}}:{},...e?{simulatorSkillsDirectoryOriginalUrl:e,...n?{simulatorSkillsDirectoryRelativePath:n}:{}}:{}}}getRequestRoutes(){return[{match:hD,handle:({response:x})=>hX(x,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:hk,handle:({response:x})=>hX(x,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:x})=>hX(x,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:x})=>{let e;if(this.skillsReader){try{nq(x,200,{skills:this.skillsReader()},{"Cache-Control":"no-cache"})}catch{nL(x,422,"无法读取项目 Skills")}return}"missing"===(e=hK(this.appDirectory,this.skillsDirectory)).layout?nL(x,404,"未找到模拟器 Skill 目录"):"invalid"===e.layout?nL(x,422,e.error??"模拟器 Skill 目录结构无效"):nq(x,200,{skills:e.entries},{"Cache-Control":"no-cache"})}}]}}let hZ="/app_developer/api",hM=`${hZ}/simulator/images/upload`,hJ=new Set([`${hZ}/simulator/chat`,hM,`${hZ}/simulator/tool/report`]),hV={"Access-Control-Expose-Headers":nB};async function hH(x,e,t,r){if(!hJ.has(t.pathname))return void nL(e,404,"未找到模拟器接口",hV);let a=r.targetOrigin??e$,_=new URL(`${t.pathname}${t.search}`,a),n=nK(x,e);try{var A;let a=x.method??"GET",s=process.hrtime.bigint(),i=function(x,e,t){return Object.fromEntries(Object.entries(nC(x.headers,e,{..._c(),...t?{[nN]:t}:{}})).filter(([x,e])=>"host"!==x.toLowerCase()&&void 0!==e).map(([x,e])=>[x,Array.isArray(e)?e.join(", "):String(e)]))}(x,_,r.getSandboxSessionId?.()),o=await hU(x,e,t,a),l=r.targetOrigin?await fetch(_,{body:o,headers:i,method:a,signal:n}):await _f({internal:!0,path:`${t.pathname}${t.search}`,method:a,body:o,headers:i,signal:n});if(function(x,e,t,r,a,_){if(!ev())return;let n=Number(process.hrtime.bigint()-r)/1e6;nj.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:n,headers:a,logId:_})}(a,t,l.status,s,i,l.headers.get(nB)??void 0),e.destroyed||e.writableEnded)return void l.body?.cancel().catch(()=>void 0);await hY({method:a,requestBody:(A=o)instanceof Uint8Array?`(binary, ${A.byteLength} bytes)`:A,requestHeaders:i,requestUrl:t,response:e,upstreamResponse:l})}catch(x){if(e.destroyed||e.writableEnded||n.aborted)return;nL(e,502,`代理模拟器请求失败:${x instanceof Error?x.message:String(x)}`,hV)}}async function hU(x,e,t,r){if("GET"!==r&&"HEAD"!==r)return t.pathname===hM?await nT(x,e,0xb00000):await nR(x,e,0xb00000)}async function hY({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:_}){var n,A;if(nD(a,hV),a.writeHead(_.status,nk(_.headers,[nB])),n=r,A=_,n.pathname===`${hZ}/simulator/chat`||A.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await hz({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:_});if(!ev())return _.body?void await R(xX.fromWeb(_.body),a):void a.end();let s=await n$(_);nX({method:x,requestBody:e,requestHeaders:t,responseBody:s,responseHeaders:_.headers,statusCode:_.status,targetUrl:r}),a.end(s)}async function hz({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:_}){if(!_.body){nX({method:x,requestBody:e,requestHeaders:t,responseBody:"",responseHeaders:_.headers,statusCode:_.status,targetUrl:r}),a.end();return}let n=xX.fromWeb(_.body);if(!ev())return void await R(n,a);nX({method:x,requestBody:e,requestHeaders:t,responseBody:"(event stream)",responseHeaders:_.headers,statusCode:_.status,targetUrl:r});let A=new xK({transform(x,e,t){let a;try{a=String(x).split("\n\n").filter(Boolean)}catch(e){return nj.error(`事件流分片解码失败:${e?.toString()}`),t(null,x)}for(let x of a)nj.info(`来自 ${r.pathname}${r.search} 的事件
397
397
  ${x}`);t(null,x)}});await R(n,A,a)}let hW=xV("../../../node_modules/.pnpm/send@1.2.0/node_modules/send/index.js");var h0=xV.n(hW);let h1="/__web_artifacts",h2="/assets/framework";function h3(x,e,t,r,a={}){nD(e,a.headers),h0()(x,r,{root:t}).once("error",r=>{if(404===r.statusCode&&a.fallbackPath)return void h3(x,e,t,a.fallbackPath,{headers:a.headers});if(e.headersSent)return void e.destroy(r);let _=r.statusCode??500;nL(e,_,xT[_]??"Internal Server Error")}).pipe(e)}let h6="/__webview",h4=`${h6}/client.js`,h5=`${h6}/page`,h7=`${h6}/runtime`,h8=`${h6}/sw.js`,h9="x-doubao-web-view-target",Ex="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",Ee=new URL(xV("../../debugger-server/dist/web-view-proxy-bootstrap.js"),xV.b),Et=new URL(xV("../../debugger-server/dist/web-view-proxy-page-client.js"),xV.b),Er=new URL(xV("../../debugger-server/dist/web-view-proxy-service-worker.js"),xV.b);function Ea(x,e,t,r=!1){if("GET"!==x.method&&"HEAD"!==x.method)return void nL(e,405,"不支持的请求方法");let a=B.readFileSync(t,"utf8");nD(e,{"Cross-Origin-Resource-Policy":"cross-origin"}),e.writeHead(200,{"cache-control":"no-store","content-length":Buffer.byteLength(a),"content-type":"text/javascript; charset=utf-8",...r?{"service-worker-allowed":"/"}:{}}),e.end("HEAD"===x.method?void 0:a)}function E_(x,e){let t=x.searchParams.get("parentOrigin")??e[0];if(!e.includes(t))throw Error("WebView 父级 origin 无效");return t}async function En(x,e,t,r){if("GET"!==x.method&&"HEAD"!==x.method)return void nL(e,405,"不支持的请求方法");let a=nK(x,e);try{let _=E_(t,r),n=nw(t.searchParams.get("url")??void 0),A=await fetch(n,{signal:a,headers:{"user-agent":Ex,..."string"==typeof x.headers.accept?{accept:x.headers.accept}:{},..."string"==typeof x.headers["accept-language"]?{"accept-language":x.headers["accept-language"]}:{}},method:x.method}),s=A.url?new URL(A.url):n;s.hash=n.hash;let i=A.headers.get("content-type")??"",o=nk(A.headers);if(o["cache-control"]="no-cache",o["cross-origin-resource-policy"]="cross-origin",o["x-doubao-web-view-parent-origin"]=_,"HEAD"===x.method||!i.includes("text/html")){let t="HEAD"===x.method?void 0:Buffer.from(await A.arrayBuffer());nD(e),e.writeHead(A.status,{...o,[h9]:s.toString(),...t?{"content-length":t.byteLength}:{}}),e.end(t);return}let l=function(x,e,t){let r=new URLSearchParams({mobileUserAgent:Ex,originalPath:`${e.pathname}${e.search}${e.hash}`,parentOrigin:t}).toString().replaceAll("&","&amp;"),a=`<script src="${h4}?${r}"></script>`,_=/<head[^>]*>/i.exec(x);if(_){let e=_.index+_[0].length;return`${x.slice(0,e)}${a}${x.slice(e)}`}return`${a}${x}`}(await A.text(),s,_);nD(e),e.writeHead(A.status,{...o,[h9]:s.toString(),"content-length":Buffer.byteLength(l)}),e.end(l)}catch(x){if(a.aborted||e.destroyed)return;nL(e,502,`代理 web-view 页面失败: ${x instanceof Error?x.message:String(x)}`)}}let EA=xV("../../../node_modules/.pnpm/better-opn@3.0.2/node_modules/better-opn/dist/index.js");var Es=xV.n(EA);let Ei=/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/;async function Eo(x){let e=new URL(x).toString();try{await Es()(e)}catch(x){nj.error("打开 Web 模拟器失败",{error:x}),nj.info("请手动打开 Web 模拟器(本地)",{url:e})}}async function El(x,e){await new Promise((t,r)=>{let a=e=>{x.off("listening",_),r(e)},_=()=>{x.off("error",a),t()};x.once("error",a),x.once("listening",_),x.listen(e,"127.0.0.1")})}async function Ec(x){let e=await nE(9e3),t=[`http://127.0.0.1:${e}`,`http://localhost:${e}`],r=xq.createServer(nM([{match:`${h6}/bootstrap`,handle:({request:x,response:e,url:r})=>{if("GET"!==x.method&&"HEAD"!==x.method)return void nL(e,405,"不支持的请求方法");try{nw(r.searchParams.get("url")??void 0),E_(r,t)}catch{nL(e,400,"WebView URL 无效");return}nD(e,{"Cross-Origin-Resource-Policy":"cross-origin"}),e.writeHead(200,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),e.end("HEAD"===x.method?void 0:'<!doctype html><meta charset="utf-8"><script src="/__webview/bootstrap.js"><\/script>')}},{match:`${h6}/bootstrap.js`,handle:({request:x,response:e})=>Ea(x,e,Ee)},{match:h8,handle:({request:x,response:e})=>Ea(x,e,Er,!0)},{match:h4,handle:({request:x,response:e})=>Ea(x,e,Et)},{match:h7,handle:({request:x,response:e,url:t})=>(function(x,e,t){let r;try{r=nw(t.searchParams.get("url")??void 0)}catch(x){nL(e,400,`无效的 web-view 请求地址: ${x instanceof Error?x.message:String(x)}`);return}let a=nC(x.headers,r,{"user-agent":Ex});for(let x of Object.keys(a))x.startsWith("sec-fetch-")&&delete a[x];nQ(x,e,{createResponseHeaders:x=>{let e=nP(x),t=Array.isArray(x.location)?x.location[0]:x.location;if(t&&URL.canParse(t,r)){let x=new URL(t,r);e.location=`${h7}?url=${encodeURIComponent(x.toString())}`}return e["cache-control"]="no-cache",e},errorMessage:"代理 web-view 运行时请求失败",requestHeaders:a,targetUrl:r})})(x,e,t)},{match:h5,handle:({request:x,response:e,url:r})=>En(x,e,r,t)}],({response:x})=>{nL(x,404,"未找到 WebView 资源")}));await El(r,0);let a=r.address(),_=`http://127.0.0.1:${a.port}`,n=xq.createServer(function({artifactOrigin:x,debugScenes:e,debuggerOrigins:t,debuggerProtocol:r,distPath:a,getWidgetViewDataTemplates:_,mcp:n,physicalDeviceDebugGateway:A,sandboxRuntime:s,simulatorAssets:i,simulatorTargetOrigin:o,webViewOrigin:l}){var c;let v={routes:[{match:x=>x.pathname.startsWith(h1),handle:({request:e,response:t,url:r})=>(function(x,e,t,r){let a=t.pathname.slice(h1.length)||"/";if(a.startsWith("//"))return void nL(e,400,"Web 产物路径无效");let _=new URL(r),n=a.startsWith("/")?a:`/${a}`,A=new URL(`${n}${t.search}`,_);A.origin!==_.origin?nL(e,400,"Web 产物路径无效"):nQ(x,e,{createResponseHeaders:x=>({...nP(x),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:nC(x.headers,A),targetUrl:A})})(e,t,r,x)},{match:x=>x.pathname===h2||x.pathname.startsWith(`${h2}/`),handle:({request:x,response:e,url:t})=>{let r;!(r=t.pathname.slice(`${h2}/`.length))||r!==y.basename(r)?nL(e,404,"未找到资源"):h3(x,e,y.join(a,h2.slice(1)),r,{headers:{"Cache-Control":"no-cache"}})}},{match:"/__web_sdk_request_proxy__",handle:({request:x,response:e})=>m$(x,e)},{match:"/__webview/page",handle:({request:x,response:e,url:t})=>{"GET"!==x.method&&"HEAD"!==x.method?nL(e,405,"不支持的请求方法"):(nD(e),e.writeHead(302,{"cache-control":"no-store",location:`${l}/__webview/bootstrap${t.search}`}),e.end())}},{match:"/__webview/sw.js",handle:({response:x})=>{nD(x),x.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript","service-worker-allowed":"/"}),x.end(`self.addEventListener('install', e => e.waitUntil(self.skipWaiting()));
398
398
  self.addEventListener('activate', e => e.waitUntil((async () => {
399
399
  await self.clients.claim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doubao-dev/kit",
3
- "version": "0.8.0-rc.0",
3
+ "version": "0.8.0-rc.2",
4
4
  "type": "module",
5
5
  "types": "./dist/types.d.ts",
6
6
  "bin": {
@@ -40,13 +40,13 @@
40
40
  ],
41
41
  "dependencies": {
42
42
  "@lynx-js/external-bundle-rsbuild-plugin": "0.4.3",
43
- "@lynx-js/react": "0.126.2",
44
- "@lynx-js/react-alias-rsbuild-plugin": "0.20.3",
45
- "@lynx-js/react-rsbuild-plugin": "0.20.3",
43
+ "@lynx-js/react": "0.129.0",
44
+ "@lynx-js/react-alias-rsbuild-plugin": "0.22.0",
45
+ "@lynx-js/react-rsbuild-plugin": "0.22.0",
46
46
  "@lynx-js/rspeedy": "0.18.0",
47
- "@lynx-js/runtime-wrapper-webpack-plugin": "0.2.4",
47
+ "@lynx-js/runtime-wrapper-webpack-plugin": "0.2.5",
48
48
  "@lynx-js/type-config": "4.2.0",
49
- "@lynx-js/web-core": "0.26.2",
49
+ "@lynx-js/web-core": "0.26.5",
50
50
  "@manypkg/get-packages": "2.2.0",
51
51
  "@pnpm/lockfile.fs": "1001.1.18",
52
52
  "@rsbuild/core": "2.2.4",