dev3000 0.0.115 → 0.0.117

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 (61) hide show
  1. package/dist/cdp-monitor.d.ts.map +1 -1
  2. package/dist/cdp-monitor.js +20 -28
  3. package/dist/cdp-monitor.js.map +1 -1
  4. package/dist/cli.js +42 -20
  5. package/dist/cli.js.map +1 -1
  6. package/dist/dev-environment.d.ts.map +1 -1
  7. package/dist/dev-environment.js +83 -11
  8. package/dist/dev-environment.js.map +1 -1
  9. package/mcp-server/.next/BUILD_ID +1 -1
  10. package/mcp-server/.next/build-manifest.json +2 -2
  11. package/mcp-server/.next/fallback-build-manifest.json +2 -2
  12. package/mcp-server/.next/prerender-manifest.json +3 -3
  13. package/mcp-server/.next/server/app/_global-error.html +2 -2
  14. package/mcp-server/.next/server/app/_global-error.rsc +1 -1
  15. package/mcp-server/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  16. package/mcp-server/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  17. package/mcp-server/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  18. package/mcp-server/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  19. package/mcp-server/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  20. package/mcp-server/.next/server/app/_not-found.html +1 -1
  21. package/mcp-server/.next/server/app/_not-found.rsc +1 -1
  22. package/mcp-server/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  23. package/mcp-server/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  24. package/mcp-server/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  25. package/mcp-server/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  26. package/mcp-server/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  27. package/mcp-server/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  28. package/mcp-server/.next/server/app/auth/error.html +1 -1
  29. package/mcp-server/.next/server/app/auth/error.rsc +1 -1
  30. package/mcp-server/.next/server/app/auth/error.segments/_full.segment.rsc +1 -1
  31. package/mcp-server/.next/server/app/auth/error.segments/_head.segment.rsc +1 -1
  32. package/mcp-server/.next/server/app/auth/error.segments/_index.segment.rsc +1 -1
  33. package/mcp-server/.next/server/app/auth/error.segments/_tree.segment.rsc +1 -1
  34. package/mcp-server/.next/server/app/auth/error.segments/auth/error/__PAGE__.segment.rsc +1 -1
  35. package/mcp-server/.next/server/app/auth/error.segments/auth/error.segment.rsc +1 -1
  36. package/mcp-server/.next/server/app/auth/error.segments/auth.segment.rsc +1 -1
  37. package/mcp-server/.next/server/app/index.html +1 -1
  38. package/mcp-server/.next/server/app/index.rsc +1 -1
  39. package/mcp-server/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  40. package/mcp-server/.next/server/app/index.segments/_full.segment.rsc +1 -1
  41. package/mcp-server/.next/server/app/index.segments/_head.segment.rsc +1 -1
  42. package/mcp-server/.next/server/app/index.segments/_index.segment.rsc +1 -1
  43. package/mcp-server/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  44. package/mcp-server/.next/server/app/mcp/route.js +2 -2
  45. package/mcp-server/.next/server/chunks/[root-of-the-server]__157de66b._.js +199 -17
  46. package/mcp-server/.next/server/chunks/[root-of-the-server]__157de66b._.js.map +1 -1
  47. package/mcp-server/.next/server/chunks/[root-of-the-server]__748f411f._.js +1 -1
  48. package/mcp-server/.next/server/chunks/[root-of-the-server]__748f411f._.js.map +1 -1
  49. package/mcp-server/.next/server/chunks/[root-of-the-server]__8a84f9f4._.js +20 -20
  50. package/mcp-server/.next/server/chunks/[root-of-the-server]__8a84f9f4._.js.map +1 -1
  51. package/mcp-server/.next/server/chunks/mcp-server_app_api_cloud_fix-workflow_steps_ts_b65f3271._.js +106 -26
  52. package/mcp-server/.next/server/chunks/mcp-server_app_api_cloud_fix-workflow_steps_ts_b65f3271._.js.map +1 -1
  53. package/mcp-server/.next/server/server-reference-manifest.js +1 -1
  54. package/mcp-server/.next/server/server-reference-manifest.json +1 -1
  55. package/mcp-server/app/api/cloud/fix-workflow/steps.ts +92 -0
  56. package/mcp-server/app/api/tools/route.ts +11 -12
  57. package/mcp-server/app/mcp/tools.ts +58 -98
  58. package/package.json +1 -1
  59. /package/mcp-server/.next/static/{5zfTZk2QSS7WLdL1K8Q5I → 3tu8GDHzRVmtUnaVw3VqB}/_buildManifest.js +0 -0
  60. /package/mcp-server/.next/static/{5zfTZk2QSS7WLdL1K8Q5I → 3tu8GDHzRVmtUnaVw3VqB}/_clientMiddlewareManifest.json +0 -0
  61. /package/mcp-server/.next/static/{5zfTZk2QSS7WLdL1K8Q5I → 3tu8GDHzRVmtUnaVw3VqB}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- module.exports=[24836,(e,t,r)=>{t.exports=e.x("https",()=>require("https"))},31258,(e,t,r)=>{"use strict";let s=["nodebuffer","arraybuffer","fragments"],i="undefined"!=typeof Blob;i&&s.push("blob"),t.exports={BINARY_TYPES:s,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:i,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},39078,(e,t,r)=>{"use strict";let{EMPTY_BUFFER:s}=e.r(31258),i=Buffer[Symbol.species];function n(e,t,r,s,i){for(let n=0;n<i;n++)r[s+n]=e[n]^t[3&n]}function o(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}function a(e){let t;return(a.readOnly=!0,Buffer.isBuffer(e))?e:(e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),a.readOnly=!1),t)}if(t.exports={concat:function(e,t){if(0===e.length)return s;if(1===e.length)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let t=0;t<e.length;t++){let s=e[t];r.set(s,n),n+=s.length}return n<t?new i(r.buffer,r.byteOffset,n):r},mask:n,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:a,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=(()=>{let e=Error("Cannot find module 'bufferutil'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.mask=function(t,r,s,i,o){o<48?n(t,r,s,i,o):e.mask(t,r,s,i,o)},t.exports.unmask=function(t,r){t.length<32?o(t,r):e.unmask(t,r)}}catch(e){}},15735,(e,t,r)=>{"use strict";let s=Symbol("kDone"),i=Symbol("kRun");t.exports=class{constructor(e){this[s]=()=>{this.pending--,this[i]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[i]()}[i](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[s])}}}},97012,(e,t,r)=>{"use strict";let s,i=e.r(6461),n=e.r(39078),o=e.r(15735),{kStatusCode:a}=e.r(31258),l=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),h=Symbol("permessage-deflate"),u=Symbol("total-length"),d=Symbol("callback"),p=Symbol("buffers"),f=Symbol("error");function m(e){this[p].push(e),this[u]+=e.length}function g(e){(this[u]+=e.length,this[h]._maxPayload<1||this[u]<=this[h]._maxPayload)?this[p].push(e):(this[f]=RangeError("Max payload size exceeded"),this[f].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[f][a]=1009,this.removeListener("data",g),this.reset())}function y(e){(this[h]._inflate=null,this[f])?this[d](this[f]):(e[a]=1007,this[d](e))}t.exports=class{constructor(e,t,r){this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,s||(s=new o(void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10))}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(e=>(!1!==t.serverNoContextTakeover||!e.server_no_context_takeover)&&(!e.server_max_window_bits||!1!==t.serverMaxWindowBits&&("number"!=typeof t.serverMaxWindowBits||!(t.serverMaxWindowBits>e.server_max_window_bits)))&&("number"!=typeof t.clientMaxWindowBits||!!e.client_max_window_bits));if(!r)throw Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:(!0===r.client_max_window_bits||!1===t.clientMaxWindowBits)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let r=e[t];if(r.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){let e=+r;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){let e=+r;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if("client_no_context_takeover"===t||"server_no_context_takeover"===t){if(!0!==r)throw TypeError(`Invalid value for parameter "${t}": ${r}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=r})}),e}decompress(e,t,r){s.add(s=>{this._decompress(e,t,(e,t)=>{s(),r(e,t)})})}compress(e,t,r){s.add(s=>{this._compress(e,t,(e,t)=>{s(),r(e,t)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=i.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[h]=this,this._inflate[u]=0,this._inflate[p]=[],this._inflate.on("error",y),this._inflate.on("data",g)}this._inflate[d]=r,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,r(e);return}let i=n.concat(this._inflate[p],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[p]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,i)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=i.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[p]=[],this._deflate.on("data",m)}this._deflate[d]=r,this._deflate.write(e),this._deflate.flush(i.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=n.concat(this._deflate[p],this._deflate[u]);t&&(e=new l(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[p]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)})}}},97112,(e,t,r)=>{"use strict";let{isUtf8:s}=e.r(874),{hasBlob:i}=e.r(31258);function n(e){let t=e.length,r=0;for(;r<t;)if((128&e[r])==0)r++;else if((224&e[r])==192){if(r+1===t||(192&e[r+1])!=128||(254&e[r])==192)return!1;r+=2}else if((240&e[r])==224){if(r+2>=t||(192&e[r+1])!=128||(192&e[r+2])!=128||224===e[r]&&(224&e[r+1])==128||237===e[r]&&(224&e[r+1])==160)return!1;r+=3}else{if((248&e[r])!=240||r+3>=t||(192&e[r+1])!=128||(192&e[r+2])!=128||(192&e[r+3])!=128||240===e[r]&&(240&e[r+1])==128||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(t.exports={isBlob:function(e){return i&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:n,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},s)t.exports.isValidUTF8=function(e){return e.length<24?n(e):s(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=(()=>{let e=Error("Cannot find module 'utf-8-validate'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.isValidUTF8=function(t){return t.length<32?n(t):e(t)}}catch(e){}},17953,(e,t,r)=>{"use strict";let{Writable:s}=e.r(88947),i=e.r(97012),{BINARY_TYPES:n,EMPTY_BUFFER:o,kStatusCode:a,kWebSocket:l}=e.r(31258),{concat:c,toArrayBuffer:h,unmask:u}=e.r(39078),{isValidStatusCode:d,isValidUTF8:p}=e.r(97112),f=Buffer[Symbol.species];t.exports=class extends s{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||n[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[l]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new f(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0)return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop)this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((48&t[0])!=0)return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));let r=(64&t[0])==64;if(r&&!this._extensions[i.extensionName])return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._fin=(128&t[0])==128,this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=r}else{if(!(this._opcode>7)||!(this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(r)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=(128&t[1])==128,this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),r=t.readUInt32BE(0);r>2097151?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=0x100000000*r+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!=0&&u(t,this._mask)}if(this._opcode>7)return void this.controlMessage(t,e);if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return void t(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let s;s="nodebuffer"===this._binaryType?c(r,t):"arraybuffer"===this._binaryType?h(c(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",s,!0),this._state=0,this.startLoop(e)}))}else{let s=c(r,t);if(!this._skipUTF8Validation&&!p(s))return void e(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));5===this._state||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",s,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8===this._opcode){if(0===e.length)this._loop=!1,this.emit("conclude",1005,o),this.end();else{let r=e.readUInt16BE(0);if(!d(r))return void t(this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE"));let s=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(s))return void t(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let n=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(n,this.createError),n.code=i,n[a]=s,n}}},60238,(e,t,r)=>{"use strict";let s,{Duplex:i}=e.r(88947),{randomFillSync:n}=e.r(54799),o=e.r(97012),{EMPTY_BUFFER:a,kWebSocket:l,NOOP:c}=e.r(31258),{isBlob:h,isValidStatusCode:u}=e.r(97112),{mask:d,toBuffer:p}=e.r(39078),f=Symbol("kByteLength"),m=Buffer.alloc(4),g=8192;class y{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[l]=void 0}static frame(e,t){let r,i,o=!1,a=2,l=!1;t.mask&&(r=t.maskBuffer||m,t.generateMask?t.generateMask(r):(8192===g&&(void 0===s&&(s=Buffer.alloc(8192)),n(s,0,8192),g=0),r[0]=s[g++],r[1]=s[g++],r[2]=s[g++],r[3]=s[g++]),l=(r[0]|r[1]|r[2]|r[3])==0,a=6),"string"==typeof e?i=(!t.mask||l)&&void 0!==t[f]?t[f]:(e=Buffer.from(e)).length:(i=e.length,o=t.mask&&t.readOnly&&!l);let c=i;i>=65536?(a+=8,c=127):i>125&&(a+=2,c=126);let h=Buffer.allocUnsafe(o?i+a:a);return(h[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(h[0]|=64),h[1]=c,126===c?h.writeUInt16BE(i,2):127===c&&(h[2]=h[3]=0,h.writeUIntBE(i,4,6)),t.mask)?(h[1]|=128,h[a-4]=r[0],h[a-3]=r[1],h[a-2]=r[2],h[a-1]=r[3],l)?[h,e]:o?(d(e,r,h,a,i),[h]):(d(e,r,e,0,i),[h,e]):[h,e]}close(e,t,r,s){let i;if(void 0===e)i=a;else if("number"==typeof e&&u(e))if(void 0!==t&&t.length){let r=Buffer.byteLength(t);if(r>123)throw RangeError("The message must not be greater than 123 bytes");(i=Buffer.allocUnsafe(2+r)).writeUInt16BE(e,0),"string"==typeof t?i.write(t,2):i.set(t,2)}else(i=Buffer.allocUnsafe(2)).writeUInt16BE(e,0);else throw TypeError("First argument must be a valid error code number");let n={[f]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,n,s]):this.sendFrame(y.frame(i,n),s)}ping(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):h(e)?(s=e.size,i=!1):(s=(e=p(e)).length,i=p.readOnly),s>125)throw RangeError("The data size must not be greater than 125 bytes");let n={[f]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,n,r]):this.getBlobData(e,!1,n,r):0!==this._state?this.enqueue([this.dispatch,e,!1,n,r]):this.sendFrame(y.frame(e,n),r)}pong(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):h(e)?(s=e.size,i=!1):(s=(e=p(e)).length,i=p.readOnly),s>125)throw RangeError("The data size must not be greater than 125 bytes");let n={[f]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,n,r]):this.getBlobData(e,!1,n,r):0!==this._state?this.enqueue([this.dispatch,e,!1,n,r]):this.sendFrame(y.frame(e,n),r)}send(e,t,r){let s,i,n=this._extensions[o.extensionName],a=t.binary?2:1,l=t.compress;"string"==typeof e?(s=Buffer.byteLength(e),i=!1):h(e)?(s=e.size,i=!1):(s=(e=p(e)).length,i=p.readOnly),this._firstFragment?(this._firstFragment=!1,l&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=s>=n._threshold),this._compress=l):(l=!1,a=0),t.fin&&(this._firstFragment=!0);let c={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:i,rsv1:l};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[f],this._state=2,e.arrayBuffer().then(e=>{if(this._socket.destroyed){let e=Error("The socket was closed while the blob was being read");process.nextTick(v,this,e,s);return}this._bufferedBytes-=r[f];let i=p(e);t?this.dispatch(i,t,r,s):(this._state=0,this.sendFrame(y.frame(i,r),s),this.dequeue())}).catch(e=>{process.nextTick(_,this,e,s)})}dispatch(e,t,r,s){if(!t)return void this.sendFrame(y.frame(e,r),s);let i=this._extensions[o.extensionName];this._bufferedBytes+=r[f],this._state=1,i.compress(e,r.fin,(e,t)=>{this._socket.destroyed?v(this,Error("The socket was closed while data was being compressed"),s):(this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(y.frame(t,r),s),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}function v(e,t,r){"function"==typeof r&&r(t);for(let r=0;r<e._queue.length;r++){let s=e._queue[r],i=s[s.length-1];"function"==typeof i&&i(t)}}function _(e,t,r){v(e,t,r),e.onerror(t)}t.exports=y},85205,(e,t,r)=>{"use strict";let{kForOnEventAttribute:s,kListener:i}=e.r(31258),n=Symbol("kCode"),o=Symbol("kData"),a=Symbol("kError"),l=Symbol("kMessage"),c=Symbol("kReason"),h=Symbol("kTarget"),u=Symbol("kType"),d=Symbol("kWasClean");class p{constructor(e){this[h]=null,this[u]=e}get target(){return this[h]}get type(){return this[u]}}Object.defineProperty(p.prototype,"target",{enumerable:!0}),Object.defineProperty(p.prototype,"type",{enumerable:!0});class f extends p{constructor(e,t={}){super(e),this[n]=void 0===t.code?0:t.code,this[c]=void 0===t.reason?"":t.reason,this[d]=void 0!==t.wasClean&&t.wasClean}get code(){return this[n]}get reason(){return this[c]}get wasClean(){return this[d]}}Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});class m extends p{constructor(e,t={}){super(e),this[a]=void 0===t.error?null:t.error,this[l]=void 0===t.message?"":t.message}get error(){return this[a]}get message(){return this[l]}}Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});class g extends p{constructor(e,t={}){super(e),this[o]=void 0===t.data?null:t.data}get data(){return this[o]}}function y(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}Object.defineProperty(g.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:f,ErrorEvent:m,Event:p,EventTarget:{addEventListener(e,t,r={}){let n;for(let n of this.listeners(e))if(!r[s]&&n[i]===t&&!n[s])return;if("message"===e)n=function(e,r){let s=new g("message",{data:r?e:e.toString()});s[h]=this,y(t,this,s)};else if("close"===e)n=function(e,r){let s=new f("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[h]=this,y(t,this,s)};else if("error"===e)n=function(e){let r=new m("error",{error:e,message:e.message});r[h]=this,y(t,this,r)};else{if("open"!==e)return;n=function(){let e=new p("open");e[h]=this,y(t,this,e)}}n[s]=!!r[s],n[i]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[i]===t&&!r[s]){this.removeListener(e,r);break}}},MessageEvent:g}},94393,(e,t,r)=>{"use strict";let{tokenChars:s}=e.r(97112);function i(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}t.exports={format:function(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>[t].concat(Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){let t,r,n=Object.create(null),o=Object.create(null),a=!1,l=!1,c=!1,h=-1,u=-1,d=-1,p=0;for(;p<e.length;p++)if(u=e.charCodeAt(p),void 0===t)if(-1===d&&1===s[u])-1===h&&(h=p);else if(0!==p&&(32===u||9===u))-1===d&&-1!==h&&(d=p);else if(59===u||44===u){if(-1===h)throw SyntaxError(`Unexpected character at index ${p}`);-1===d&&(d=p);let r=e.slice(h,d);44===u?(i(n,r,o),o=Object.create(null)):t=r,h=d=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(void 0===r)if(-1===d&&1===s[u])-1===h&&(h=p);else if(32===u||9===u)-1===d&&-1!==h&&(d=p);else if(59===u||44===u){if(-1===h)throw SyntaxError(`Unexpected character at index ${p}`);-1===d&&(d=p),i(o,e.slice(h,d),!0),44===u&&(i(n,t,o),o=Object.create(null),t=void 0),h=d=-1}else if(61===u&&-1!==h&&-1===d)r=e.slice(h,p),h=d=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(l){if(1!==s[u])throw SyntaxError(`Unexpected character at index ${p}`);-1===h?h=p:a||(a=!0),l=!1}else if(c)if(1===s[u])-1===h&&(h=p);else if(34===u&&-1!==h)c=!1,d=p;else if(92===u)l=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(34===u&&61===e.charCodeAt(p-1))c=!0;else if(-1===d&&1===s[u])-1===h&&(h=p);else if(-1!==h&&(32===u||9===u))-1===d&&(d=p);else if(59===u||44===u){if(-1===h)throw SyntaxError(`Unexpected character at index ${p}`);-1===d&&(d=p);let s=e.slice(h,d);a&&(s=s.replace(/\\/g,""),a=!1),i(o,r,s),44===u&&(i(n,t,o),o=Object.create(null),t=void 0),r=void 0,h=d=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(-1===h||c||32===u||9===u)throw SyntaxError("Unexpected end of input");-1===d&&(d=p);let f=e.slice(h,d);return void 0===t?i(n,f,o):(void 0===r?i(o,f,!0):a?i(o,r,f.replace(/\\/g,"")):i(o,r,f),i(n,t,o)),n}}},6281,(e,t,r)=>{"use strict";let s=e.r(27699),i=e.r(24836),n=e.r(21517),o=e.r(4446),a=e.r(55004),{randomBytes:l,createHash:c}=e.r(54799),{Duplex:h,Readable:u}=e.r(88947),{URL:d}=e.r(92509),p=e.r(97012),f=e.r(17953),m=e.r(60238),{isBlob:g}=e.r(97112),{BINARY_TYPES:y,EMPTY_BUFFER:v,GUID:_,kForOnEventAttribute:w,kListener:S,kStatusCode:E,kWebSocket:b,NOOP:x}=e.r(31258),{EventTarget:{addEventListener:T,removeEventListener:C}}=e.r(85205),{format:R,parse:N}=e.r(94393),{toBuffer:k}=e.r(39078),I=Symbol("kAborted"),O=[8,13],P=["CONNECTING","OPEN","CLOSING","CLOSED"],A=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class $ extends s{constructor(e,t,r){super(),this._binaryType=y[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=$.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),function e(t,r,s,o){let a,h,u,f,m={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:O[1],maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=m.autoPong,!O.includes(m.protocolVersion))throw RangeError(`Unsupported protocol version: ${m.protocolVersion} (supported versions: ${O.join(", ")})`);if(r instanceof d)a=r;else try{a=new d(r)}catch(e){throw SyntaxError(`Invalid URL: ${r}`)}"http:"===a.protocol?a.protocol="ws:":"https:"===a.protocol&&(a.protocol="wss:"),t._url=a.href;let g="wss:"===a.protocol,y="ws+unix:"===a.protocol;if("ws:"===a.protocol||g||y?y&&!a.pathname?h="The URL's pathname is empty":a.hash&&(h="The URL contains a fragment identifier"):h='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',h){let e=SyntaxError(h);if(0!==t._redirects)return void D(t,e);throw e}let v=g?443:80,w=l(16).toString("base64"),S=g?i.request:n.request,E=new Set;if(m.createConnection=m.createConnection||(g?M:L),m.defaultPort=m.defaultPort||v,m.port=a.port||v,m.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,m.headers={...m.headers,"Sec-WebSocket-Version":m.protocolVersion,"Sec-WebSocket-Key":w,Connection:"Upgrade",Upgrade:"websocket"},m.path=a.pathname+a.search,m.timeout=m.handshakeTimeout,m.perMessageDeflate&&(u=new p(!0!==m.perMessageDeflate?m.perMessageDeflate:{},!1,m.maxPayload),m.headers["Sec-WebSocket-Extensions"]=R({[p.extensionName]:u.offer()})),s.length){for(let e of s){if("string"!=typeof e||!A.test(e)||E.has(e))throw SyntaxError("An invalid or duplicated subprotocol was specified");E.add(e)}m.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(m.origin&&(m.protocolVersion<13?m.headers["Sec-WebSocket-Origin"]=m.origin:m.headers.Origin=m.origin),(a.username||a.password)&&(m.auth=`${a.username}:${a.password}`),y){let e=m.path.split(":");m.socketPath=e[0],m.path=e[1]}if(m.followRedirects){if(0===t._redirects){t._originalIpc=y,t._originalSecure=g,t._originalHostOrSocketPath=y?m.socketPath:a.host;let e=o&&o.headers;if(o={...o,headers:{}},e)for(let[t,r]of Object.entries(e))o.headers[t.toLowerCase()]=r}else if(0===t.listenerCount("redirect")){let e=y?!!t._originalIpc&&m.socketPath===t._originalHostOrSocketPath:!t._originalIpc&&a.host===t._originalHostOrSocketPath;e&&(!t._originalSecure||g)||(delete m.headers.authorization,delete m.headers.cookie,e||delete m.headers.host,m.auth=void 0)}m.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(m.auth).toString("base64")),f=t._req=S(m),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=S(m);m.timeout&&f.on("timeout",()=>{U(t,f,"Opening handshake has timed out")}),f.on("error",e=>{null===f||f[I]||(f=t._req=null,D(t,e))}),f.on("response",i=>{let n=i.headers.location,a=i.statusCode;if(n&&m.followRedirects&&a>=300&&a<400){let i;if(++t._redirects>m.maxRedirects)return void U(t,f,"Maximum redirects exceeded");f.abort();try{i=new d(n,r)}catch(e){D(t,SyntaxError(`Invalid URL: ${n}`));return}e(t,i,s,o)}else t.emit("unexpected-response",f,i)||U(t,f,`Unexpected server response: ${i.statusCode}`)}),f.on("upgrade",(e,r,s)=>{let i;if(t.emit("upgrade",e),t.readyState!==$.CONNECTING)return;f=t._req=null;let n=e.headers.upgrade;if(void 0===n||"websocket"!==n.toLowerCase())return void U(t,r,"Invalid Upgrade header");let o=c("sha1").update(w+_).digest("base64");if(e.headers["sec-websocket-accept"]!==o)return void U(t,r,"Invalid Sec-WebSocket-Accept header");let a=e.headers["sec-websocket-protocol"];if(void 0!==a?E.size?E.has(a)||(i="Server sent an invalid subprotocol"):i="Server sent a subprotocol but none was requested":E.size&&(i="Server sent no subprotocol"),i)return void U(t,r,i);a&&(t._protocol=a);let l=e.headers["sec-websocket-extensions"];if(void 0!==l){let e;if(!u)return void U(t,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");try{e=N(l)}catch(e){U(t,r,"Invalid Sec-WebSocket-Extensions header");return}let s=Object.keys(e);if(1!==s.length||s[0]!==p.extensionName)return void U(t,r,"Server indicated an extension that was not requested");try{u.accept(e[p.extensionName])}catch(e){U(t,r,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[p.extensionName]=u}t.setSocket(r,s,{allowSynchronousEvents:m.allowSynchronousEvents,generateMask:m.generateMask,maxPayload:m.maxPayload,skipUTF8Validation:m.skipUTF8Validation})}),m.finishRequest?m.finishRequest(f,t):f.end()}(this,e,t,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){y.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){let s=new f({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new m(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[b]=this,i[b]=this,e[b]=this,s.on("conclude",j),s.on("drain",B),s.on("error",W),s.on("message",V),s.on("ping",H),s.on("pong",z),i.onerror=Y,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",X),e.on("data",K),e.on("end",Z),e.on("error",Q),this._readyState=$.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=$.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=$.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==$.CLOSED){if(this.readyState===$.CONNECTING)return void U(this,this._req,"WebSocket was closed before the connection was established");if(this.readyState===$.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=$.CLOSING,this._sender.close(e,t,!this._isServer,e=>{!e&&(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),J(this)}}pause(){this.readyState!==$.CONNECTING&&this.readyState!==$.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===$.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==$.OPEN)?F(this,e,r):(void 0===t&&(t=!this._isServer),this._sender.ping(e||v,t,r))}pong(e,t,r){if(this.readyState===$.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==$.OPEN)?F(this,e,r):(void 0===t&&(t=!this._isServer),this._sender.pong(e||v,t,r))}resume(){this.readyState!==$.CONNECTING&&this.readyState!==$.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===$.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==$.OPEN)return void F(this,e,r);let s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[p.extensionName]||(s.compress=!1),this._sender.send(e||v,s,r)}terminate(){if(this.readyState!==$.CLOSED){if(this.readyState===$.CONNECTING)return void U(this,this._req,"WebSocket was closed before the connection was established");this._socket&&(this._readyState=$.CLOSING,this._socket.destroy())}}}function D(e,t){e._readyState=$.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function L(e){return e.path=e.socketPath,o.connect(e)}function M(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=o.isIP(e.host)?"":e.host),a.connect(e)}function U(e,t,r){e._readyState=$.CLOSING;let s=Error(r);Error.captureStackTrace(s,U),t.setHeader?(t[I]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(D,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function F(e,t,r){if(t){let r=g(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${P[e.readyState]})`);process.nextTick(r,t)}}function j(e,t){let r=this[b];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[b]&&(r._socket.removeListener("data",K),process.nextTick(q,r._socket),1005===e?r.close():r.close(e,t))}function B(){let e=this[b];e.isPaused||e._socket.resume()}function W(e){let t=this[b];void 0!==t._socket[b]&&(t._socket.removeListener("data",K),process.nextTick(q,t._socket),t.close(e[E])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function G(){this[b].emitClose()}function V(e,t){this[b].emit("message",e,t)}function H(e){let t=this[b];t._autoPong&&t.pong(e,!this._isServer,x),t.emit("ping",e)}function z(e){this[b].emit("pong",e)}function q(e){e.resume()}function Y(e){let t=this[b];t.readyState!==$.CLOSED&&(t.readyState===$.OPEN&&(t._readyState=$.CLOSING,J(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function J(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function X(){let e,t=this[b];this.removeListener("close",X),this.removeListener("data",K),this.removeListener("end",Z),t._readyState=$.CLOSING,this._readableState.endEmitted||t._closeFrameReceived||t._receiver._writableState.errorEmitted||null===(e=t._socket.read())||t._receiver.write(e),t._receiver.end(),this[b]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",G),t._receiver.on("finish",G))}function K(e){this[b]._receiver.write(e)||this.pause()}function Z(){let e=this[b];e._readyState=$.CLOSING,e._receiver.end(),this.end()}function Q(){let e=this[b];this.removeListener("error",Q),this.on("error",x),e&&(e._readyState=$.CLOSING,this.destroy())}Object.defineProperty($,"CONNECTING",{enumerable:!0,value:P.indexOf("CONNECTING")}),Object.defineProperty($.prototype,"CONNECTING",{enumerable:!0,value:P.indexOf("CONNECTING")}),Object.defineProperty($,"OPEN",{enumerable:!0,value:P.indexOf("OPEN")}),Object.defineProperty($.prototype,"OPEN",{enumerable:!0,value:P.indexOf("OPEN")}),Object.defineProperty($,"CLOSING",{enumerable:!0,value:P.indexOf("CLOSING")}),Object.defineProperty($.prototype,"CLOSING",{enumerable:!0,value:P.indexOf("CLOSING")}),Object.defineProperty($,"CLOSED",{enumerable:!0,value:P.indexOf("CLOSED")}),Object.defineProperty($.prototype,"CLOSED",{enumerable:!0,value:P.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty($.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty($.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[w])return t[S];return null},set(t){for(let t of this.listeners(e))if(t[w]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[w]:!0})}})}),$.prototype.addEventListener=T,$.prototype.removeEventListener=C,t.exports=$},66212,(e,t,r)=>{"use strict";e.r(6281);let{Duplex:s}=e.r(88947);function i(e){e.emit("close")}function n(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener("error",o),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}t.exports=function(e,t){let r=!0,a=new s({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,r){let s=!r&&a._readableState.objectMode?t.toString():t;a.push(s)||e.pause()}),e.once("error",function(e){a.destroyed||(r=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,s){if(e.readyState===e.CLOSED){s(t),process.nextTick(i,a);return}let n=!1;e.once("error",function(e){n=!0,s(e)}),e.once("close",function(){n||s(t),process.nextTick(i,a)}),r&&e.terminate()},a._final=function(t){e.readyState===e.CONNECTING?e.once("open",function(){a._final(t)}):null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close()))},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,r,s){e.readyState===e.CONNECTING?e.once("open",function(){a._write(t,r,s)}):e.send(t,s)},a.on("end",n),a.on("error",o),a}},9915,(e,t,r)=>{"use strict";let{tokenChars:s}=e.r(97112);t.exports={parse:function(e){let t=new Set,r=-1,i=-1,n=0;for(;n<e.length;n++){let o=e.charCodeAt(n);if(-1===i&&1===s[o])-1===r&&(r=n);else if(0!==n&&(32===o||9===o))-1===i&&-1!==r&&(i=n);else if(44===o){if(-1===r)throw SyntaxError(`Unexpected character at index ${n}`);-1===i&&(i=n);let s=e.slice(r,i);if(t.has(s))throw SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),r=i=-1}else throw SyntaxError(`Unexpected character at index ${n}`)}if(-1===r||-1!==i)throw SyntaxError("Unexpected end of input");let o=e.slice(r,n);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}}},3441,(e,t,r)=>{"use strict";let s=e.r(27699),i=e.r(21517),{Duplex:n}=e.r(88947),{createHash:o}=e.r(54799),a=e.r(94393),l=e.r(97012),c=e.r(9915),h=e.r(6281),{GUID:u,kWebSocket:d}=e.r(31258),p=/^[+/0-9A-Za-z]{22}==$/;function f(e){e._state=2,e.emit("close")}function m(){this.destroy()}function g(e,t,r,s){r=r||i.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r
1
+ module.exports=[24836,(e,t,r)=>{t.exports=e.x("https",()=>require("https"))},31258,(e,t,r)=>{"use strict";let s=["nodebuffer","arraybuffer","fragments"],i="undefined"!=typeof Blob;i&&s.push("blob"),t.exports={BINARY_TYPES:s,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:i,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},39078,(e,t,r)=>{"use strict";let{EMPTY_BUFFER:s}=e.r(31258),i=Buffer[Symbol.species];function n(e,t,r,s,i){for(let n=0;n<i;n++)r[s+n]=e[n]^t[3&n]}function o(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}function a(e){let t;return(a.readOnly=!0,Buffer.isBuffer(e))?e:(e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),a.readOnly=!1),t)}if(t.exports={concat:function(e,t){if(0===e.length)return s;if(1===e.length)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let t=0;t<e.length;t++){let s=e[t];r.set(s,n),n+=s.length}return n<t?new i(r.buffer,r.byteOffset,n):r},mask:n,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:a,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=(()=>{let e=Error("Cannot find module 'bufferutil'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.mask=function(t,r,s,i,o){o<48?n(t,r,s,i,o):e.mask(t,r,s,i,o)},t.exports.unmask=function(t,r){t.length<32?o(t,r):e.unmask(t,r)}}catch(e){}},15735,(e,t,r)=>{"use strict";let s=Symbol("kDone"),i=Symbol("kRun");t.exports=class{constructor(e){this[s]=()=>{this.pending--,this[i]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[i]()}[i](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[s])}}}},97012,(e,t,r)=>{"use strict";let s,i=e.r(6461),n=e.r(39078),o=e.r(15735),{kStatusCode:a}=e.r(31258),l=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),h=Symbol("permessage-deflate"),u=Symbol("total-length"),d=Symbol("callback"),p=Symbol("buffers"),f=Symbol("error");function m(e){this[p].push(e),this[u]+=e.length}function g(e){(this[u]+=e.length,this[h]._maxPayload<1||this[u]<=this[h]._maxPayload)?this[p].push(e):(this[f]=RangeError("Max payload size exceeded"),this[f].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[f][a]=1009,this.removeListener("data",g),this.reset())}function y(e){(this[h]._inflate=null,this[f])?this[d](this[f]):(e[a]=1007,this[d](e))}t.exports=class{constructor(e,t,r){this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,s||(s=new o(void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10))}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(e=>(!1!==t.serverNoContextTakeover||!e.server_no_context_takeover)&&(!e.server_max_window_bits||!1!==t.serverMaxWindowBits&&("number"!=typeof t.serverMaxWindowBits||!(t.serverMaxWindowBits>e.server_max_window_bits)))&&("number"!=typeof t.clientMaxWindowBits||!!e.client_max_window_bits));if(!r)throw Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:(!0===r.client_max_window_bits||!1===t.clientMaxWindowBits)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let r=e[t];if(r.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){let e=+r;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){let e=+r;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if("client_no_context_takeover"===t||"server_no_context_takeover"===t){if(!0!==r)throw TypeError(`Invalid value for parameter "${t}": ${r}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=r})}),e}decompress(e,t,r){s.add(s=>{this._decompress(e,t,(e,t)=>{s(),r(e,t)})})}compress(e,t,r){s.add(s=>{this._compress(e,t,(e,t)=>{s(),r(e,t)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=i.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[h]=this,this._inflate[u]=0,this._inflate[p]=[],this._inflate.on("error",y),this._inflate.on("data",g)}this._inflate[d]=r,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,r(e);return}let i=n.concat(this._inflate[p],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[p]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,i)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=i.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[p]=[],this._deflate.on("data",m)}this._deflate[d]=r,this._deflate.write(e),this._deflate.flush(i.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=n.concat(this._deflate[p],this._deflate[u]);t&&(e=new l(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[p]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)})}}},97112,(e,t,r)=>{"use strict";let{isUtf8:s}=e.r(874),{hasBlob:i}=e.r(31258);function n(e){let t=e.length,r=0;for(;r<t;)if((128&e[r])==0)r++;else if((224&e[r])==192){if(r+1===t||(192&e[r+1])!=128||(254&e[r])==192)return!1;r+=2}else if((240&e[r])==224){if(r+2>=t||(192&e[r+1])!=128||(192&e[r+2])!=128||224===e[r]&&(224&e[r+1])==128||237===e[r]&&(224&e[r+1])==160)return!1;r+=3}else{if((248&e[r])!=240||r+3>=t||(192&e[r+1])!=128||(192&e[r+2])!=128||(192&e[r+3])!=128||240===e[r]&&(240&e[r+1])==128||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(t.exports={isBlob:function(e){return i&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:n,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},s)t.exports.isValidUTF8=function(e){return e.length<24?n(e):s(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=(()=>{let e=Error("Cannot find module 'utf-8-validate'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.isValidUTF8=function(t){return t.length<32?n(t):e(t)}}catch(e){}},17953,(e,t,r)=>{"use strict";let{Writable:s}=e.r(88947),i=e.r(97012),{BINARY_TYPES:n,EMPTY_BUFFER:o,kStatusCode:a,kWebSocket:l}=e.r(31258),{concat:c,toArrayBuffer:h,unmask:u}=e.r(39078),{isValidStatusCode:d,isValidUTF8:p}=e.r(97112),f=Buffer[Symbol.species];t.exports=class extends s{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||n[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[l]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new f(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0)return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop)this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((48&t[0])!=0)return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));let r=(64&t[0])==64;if(r&&!this._extensions[i.extensionName])return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._fin=(128&t[0])==128,this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=r}else{if(!(this._opcode>7)||!(this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(r)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=(128&t[1])==128,this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),r=t.readUInt32BE(0);r>2097151?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=0x100000000*r+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!=0&&u(t,this._mask)}if(this._opcode>7)return void this.controlMessage(t,e);if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return void t(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let s;s="nodebuffer"===this._binaryType?c(r,t):"arraybuffer"===this._binaryType?h(c(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",s,!0),this._state=0,this.startLoop(e)}))}else{let s=c(r,t);if(!this._skipUTF8Validation&&!p(s))return void e(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));5===this._state||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",s,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8===this._opcode){if(0===e.length)this._loop=!1,this.emit("conclude",1005,o),this.end();else{let r=e.readUInt16BE(0);if(!d(r))return void t(this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE"));let s=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(s))return void t(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let n=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(n,this.createError),n.code=i,n[a]=s,n}}},60238,(e,t,r)=>{"use strict";let s,{Duplex:i}=e.r(88947),{randomFillSync:n}=e.r(54799),o=e.r(97012),{EMPTY_BUFFER:a,kWebSocket:l,NOOP:c}=e.r(31258),{isBlob:h,isValidStatusCode:u}=e.r(97112),{mask:d,toBuffer:p}=e.r(39078),f=Symbol("kByteLength"),m=Buffer.alloc(4),g=8192;class y{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[l]=void 0}static frame(e,t){let r,i,o=!1,a=2,l=!1;t.mask&&(r=t.maskBuffer||m,t.generateMask?t.generateMask(r):(8192===g&&(void 0===s&&(s=Buffer.alloc(8192)),n(s,0,8192),g=0),r[0]=s[g++],r[1]=s[g++],r[2]=s[g++],r[3]=s[g++]),l=(r[0]|r[1]|r[2]|r[3])==0,a=6),"string"==typeof e?i=(!t.mask||l)&&void 0!==t[f]?t[f]:(e=Buffer.from(e)).length:(i=e.length,o=t.mask&&t.readOnly&&!l);let c=i;i>=65536?(a+=8,c=127):i>125&&(a+=2,c=126);let h=Buffer.allocUnsafe(o?i+a:a);return(h[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(h[0]|=64),h[1]=c,126===c?h.writeUInt16BE(i,2):127===c&&(h[2]=h[3]=0,h.writeUIntBE(i,4,6)),t.mask)?(h[1]|=128,h[a-4]=r[0],h[a-3]=r[1],h[a-2]=r[2],h[a-1]=r[3],l)?[h,e]:o?(d(e,r,h,a,i),[h]):(d(e,r,e,0,i),[h,e]):[h,e]}close(e,t,r,s){let i;if(void 0===e)i=a;else if("number"==typeof e&&u(e))if(void 0!==t&&t.length){let r=Buffer.byteLength(t);if(r>123)throw RangeError("The message must not be greater than 123 bytes");(i=Buffer.allocUnsafe(2+r)).writeUInt16BE(e,0),"string"==typeof t?i.write(t,2):i.set(t,2)}else(i=Buffer.allocUnsafe(2)).writeUInt16BE(e,0);else throw TypeError("First argument must be a valid error code number");let n={[f]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,n,s]):this.sendFrame(y.frame(i,n),s)}ping(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):h(e)?(s=e.size,i=!1):(s=(e=p(e)).length,i=p.readOnly),s>125)throw RangeError("The data size must not be greater than 125 bytes");let n={[f]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,n,r]):this.getBlobData(e,!1,n,r):0!==this._state?this.enqueue([this.dispatch,e,!1,n,r]):this.sendFrame(y.frame(e,n),r)}pong(e,t,r){let s,i;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):h(e)?(s=e.size,i=!1):(s=(e=p(e)).length,i=p.readOnly),s>125)throw RangeError("The data size must not be greater than 125 bytes");let n={[f]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,n,r]):this.getBlobData(e,!1,n,r):0!==this._state?this.enqueue([this.dispatch,e,!1,n,r]):this.sendFrame(y.frame(e,n),r)}send(e,t,r){let s,i,n=this._extensions[o.extensionName],a=t.binary?2:1,l=t.compress;"string"==typeof e?(s=Buffer.byteLength(e),i=!1):h(e)?(s=e.size,i=!1):(s=(e=p(e)).length,i=p.readOnly),this._firstFragment?(this._firstFragment=!1,l&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=s>=n._threshold),this._compress=l):(l=!1,a=0),t.fin&&(this._firstFragment=!0);let c={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:i,rsv1:l};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[f],this._state=2,e.arrayBuffer().then(e=>{if(this._socket.destroyed){let e=Error("The socket was closed while the blob was being read");process.nextTick(v,this,e,s);return}this._bufferedBytes-=r[f];let i=p(e);t?this.dispatch(i,t,r,s):(this._state=0,this.sendFrame(y.frame(i,r),s),this.dequeue())}).catch(e=>{process.nextTick(_,this,e,s)})}dispatch(e,t,r,s){if(!t)return void this.sendFrame(y.frame(e,r),s);let i=this._extensions[o.extensionName];this._bufferedBytes+=r[f],this._state=1,i.compress(e,r.fin,(e,t)=>{this._socket.destroyed?v(this,Error("The socket was closed while data was being compressed"),s):(this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(y.frame(t,r),s),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}function v(e,t,r){"function"==typeof r&&r(t);for(let r=0;r<e._queue.length;r++){let s=e._queue[r],i=s[s.length-1];"function"==typeof i&&i(t)}}function _(e,t,r){v(e,t,r),e.onerror(t)}t.exports=y},85205,(e,t,r)=>{"use strict";let{kForOnEventAttribute:s,kListener:i}=e.r(31258),n=Symbol("kCode"),o=Symbol("kData"),a=Symbol("kError"),l=Symbol("kMessage"),c=Symbol("kReason"),h=Symbol("kTarget"),u=Symbol("kType"),d=Symbol("kWasClean");class p{constructor(e){this[h]=null,this[u]=e}get target(){return this[h]}get type(){return this[u]}}Object.defineProperty(p.prototype,"target",{enumerable:!0}),Object.defineProperty(p.prototype,"type",{enumerable:!0});class f extends p{constructor(e,t={}){super(e),this[n]=void 0===t.code?0:t.code,this[c]=void 0===t.reason?"":t.reason,this[d]=void 0!==t.wasClean&&t.wasClean}get code(){return this[n]}get reason(){return this[c]}get wasClean(){return this[d]}}Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});class m extends p{constructor(e,t={}){super(e),this[a]=void 0===t.error?null:t.error,this[l]=void 0===t.message?"":t.message}get error(){return this[a]}get message(){return this[l]}}Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});class g extends p{constructor(e,t={}){super(e),this[o]=void 0===t.data?null:t.data}get data(){return this[o]}}function y(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}Object.defineProperty(g.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:f,ErrorEvent:m,Event:p,EventTarget:{addEventListener(e,t,r={}){let n;for(let n of this.listeners(e))if(!r[s]&&n[i]===t&&!n[s])return;if("message"===e)n=function(e,r){let s=new g("message",{data:r?e:e.toString()});s[h]=this,y(t,this,s)};else if("close"===e)n=function(e,r){let s=new f("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[h]=this,y(t,this,s)};else if("error"===e)n=function(e){let r=new m("error",{error:e,message:e.message});r[h]=this,y(t,this,r)};else{if("open"!==e)return;n=function(){let e=new p("open");e[h]=this,y(t,this,e)}}n[s]=!!r[s],n[i]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[i]===t&&!r[s]){this.removeListener(e,r);break}}},MessageEvent:g}},94393,(e,t,r)=>{"use strict";let{tokenChars:s}=e.r(97112);function i(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}t.exports={format:function(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>[t].concat(Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){let t,r,n=Object.create(null),o=Object.create(null),a=!1,l=!1,c=!1,h=-1,u=-1,d=-1,p=0;for(;p<e.length;p++)if(u=e.charCodeAt(p),void 0===t)if(-1===d&&1===s[u])-1===h&&(h=p);else if(0!==p&&(32===u||9===u))-1===d&&-1!==h&&(d=p);else if(59===u||44===u){if(-1===h)throw SyntaxError(`Unexpected character at index ${p}`);-1===d&&(d=p);let r=e.slice(h,d);44===u?(i(n,r,o),o=Object.create(null)):t=r,h=d=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(void 0===r)if(-1===d&&1===s[u])-1===h&&(h=p);else if(32===u||9===u)-1===d&&-1!==h&&(d=p);else if(59===u||44===u){if(-1===h)throw SyntaxError(`Unexpected character at index ${p}`);-1===d&&(d=p),i(o,e.slice(h,d),!0),44===u&&(i(n,t,o),o=Object.create(null),t=void 0),h=d=-1}else if(61===u&&-1!==h&&-1===d)r=e.slice(h,p),h=d=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(l){if(1!==s[u])throw SyntaxError(`Unexpected character at index ${p}`);-1===h?h=p:a||(a=!0),l=!1}else if(c)if(1===s[u])-1===h&&(h=p);else if(34===u&&-1!==h)c=!1,d=p;else if(92===u)l=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(34===u&&61===e.charCodeAt(p-1))c=!0;else if(-1===d&&1===s[u])-1===h&&(h=p);else if(-1!==h&&(32===u||9===u))-1===d&&(d=p);else if(59===u||44===u){if(-1===h)throw SyntaxError(`Unexpected character at index ${p}`);-1===d&&(d=p);let s=e.slice(h,d);a&&(s=s.replace(/\\/g,""),a=!1),i(o,r,s),44===u&&(i(n,t,o),o=Object.create(null),t=void 0),r=void 0,h=d=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(-1===h||c||32===u||9===u)throw SyntaxError("Unexpected end of input");-1===d&&(d=p);let f=e.slice(h,d);return void 0===t?i(n,f,o):(void 0===r?i(o,f,!0):a?i(o,r,f.replace(/\\/g,"")):i(o,r,f),i(n,t,o)),n}}},6281,(e,t,r)=>{"use strict";let s=e.r(27699),i=e.r(24836),n=e.r(21517),o=e.r(4446),a=e.r(55004),{randomBytes:l,createHash:c}=e.r(54799),{Duplex:h,Readable:u}=e.r(88947),{URL:d}=e.r(92509),p=e.r(97012),f=e.r(17953),m=e.r(60238),{isBlob:g}=e.r(97112),{BINARY_TYPES:y,EMPTY_BUFFER:v,GUID:_,kForOnEventAttribute:b,kListener:w,kStatusCode:S,kWebSocket:E,NOOP:x}=e.r(31258),{EventTarget:{addEventListener:C,removeEventListener:T}}=e.r(85205),{format:k,parse:N}=e.r(94393),{toBuffer:$}=e.r(39078),R=Symbol("kAborted"),O=[8,13],P=["CONNECTING","OPEN","CLOSING","CLOSED"],I=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class A extends s{constructor(e,t,r){super(),this._binaryType=y[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=A.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),function e(t,r,s,o){let a,h,u,f,m={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:O[1],maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=m.autoPong,!O.includes(m.protocolVersion))throw RangeError(`Unsupported protocol version: ${m.protocolVersion} (supported versions: ${O.join(", ")})`);if(r instanceof d)a=r;else try{a=new d(r)}catch(e){throw SyntaxError(`Invalid URL: ${r}`)}"http:"===a.protocol?a.protocol="ws:":"https:"===a.protocol&&(a.protocol="wss:"),t._url=a.href;let g="wss:"===a.protocol,y="ws+unix:"===a.protocol;if("ws:"===a.protocol||g||y?y&&!a.pathname?h="The URL's pathname is empty":a.hash&&(h="The URL contains a fragment identifier"):h='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',h){let e=SyntaxError(h);if(0!==t._redirects)return void D(t,e);throw e}let v=g?443:80,b=l(16).toString("base64"),w=g?i.request:n.request,S=new Set;if(m.createConnection=m.createConnection||(g?M:L),m.defaultPort=m.defaultPort||v,m.port=a.port||v,m.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,m.headers={...m.headers,"Sec-WebSocket-Version":m.protocolVersion,"Sec-WebSocket-Key":b,Connection:"Upgrade",Upgrade:"websocket"},m.path=a.pathname+a.search,m.timeout=m.handshakeTimeout,m.perMessageDeflate&&(u=new p(!0!==m.perMessageDeflate?m.perMessageDeflate:{},!1,m.maxPayload),m.headers["Sec-WebSocket-Extensions"]=k({[p.extensionName]:u.offer()})),s.length){for(let e of s){if("string"!=typeof e||!I.test(e)||S.has(e))throw SyntaxError("An invalid or duplicated subprotocol was specified");S.add(e)}m.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(m.origin&&(m.protocolVersion<13?m.headers["Sec-WebSocket-Origin"]=m.origin:m.headers.Origin=m.origin),(a.username||a.password)&&(m.auth=`${a.username}:${a.password}`),y){let e=m.path.split(":");m.socketPath=e[0],m.path=e[1]}if(m.followRedirects){if(0===t._redirects){t._originalIpc=y,t._originalSecure=g,t._originalHostOrSocketPath=y?m.socketPath:a.host;let e=o&&o.headers;if(o={...o,headers:{}},e)for(let[t,r]of Object.entries(e))o.headers[t.toLowerCase()]=r}else if(0===t.listenerCount("redirect")){let e=y?!!t._originalIpc&&m.socketPath===t._originalHostOrSocketPath:!t._originalIpc&&a.host===t._originalHostOrSocketPath;e&&(!t._originalSecure||g)||(delete m.headers.authorization,delete m.headers.cookie,e||delete m.headers.host,m.auth=void 0)}m.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(m.auth).toString("base64")),f=t._req=w(m),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=w(m);m.timeout&&f.on("timeout",()=>{U(t,f,"Opening handshake has timed out")}),f.on("error",e=>{null===f||f[R]||(f=t._req=null,D(t,e))}),f.on("response",i=>{let n=i.headers.location,a=i.statusCode;if(n&&m.followRedirects&&a>=300&&a<400){let i;if(++t._redirects>m.maxRedirects)return void U(t,f,"Maximum redirects exceeded");f.abort();try{i=new d(n,r)}catch(e){D(t,SyntaxError(`Invalid URL: ${n}`));return}e(t,i,s,o)}else t.emit("unexpected-response",f,i)||U(t,f,`Unexpected server response: ${i.statusCode}`)}),f.on("upgrade",(e,r,s)=>{let i;if(t.emit("upgrade",e),t.readyState!==A.CONNECTING)return;f=t._req=null;let n=e.headers.upgrade;if(void 0===n||"websocket"!==n.toLowerCase())return void U(t,r,"Invalid Upgrade header");let o=c("sha1").update(b+_).digest("base64");if(e.headers["sec-websocket-accept"]!==o)return void U(t,r,"Invalid Sec-WebSocket-Accept header");let a=e.headers["sec-websocket-protocol"];if(void 0!==a?S.size?S.has(a)||(i="Server sent an invalid subprotocol"):i="Server sent a subprotocol but none was requested":S.size&&(i="Server sent no subprotocol"),i)return void U(t,r,i);a&&(t._protocol=a);let l=e.headers["sec-websocket-extensions"];if(void 0!==l){let e;if(!u)return void U(t,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");try{e=N(l)}catch(e){U(t,r,"Invalid Sec-WebSocket-Extensions header");return}let s=Object.keys(e);if(1!==s.length||s[0]!==p.extensionName)return void U(t,r,"Server indicated an extension that was not requested");try{u.accept(e[p.extensionName])}catch(e){U(t,r,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[p.extensionName]=u}t.setSocket(r,s,{allowSynchronousEvents:m.allowSynchronousEvents,generateMask:m.generateMask,maxPayload:m.maxPayload,skipUTF8Validation:m.skipUTF8Validation})}),m.finishRequest?m.finishRequest(f,t):f.end()}(this,e,t,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){y.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){let s=new f({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new m(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[E]=this,i[E]=this,e[E]=this,s.on("conclude",F),s.on("drain",B),s.on("error",W),s.on("message",V),s.on("ping",z),s.on("pong",H),i.onerror=J,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",K),e.on("data",X),e.on("end",Z),e.on("error",Q),this._readyState=A.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=A.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=A.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==A.CLOSED){if(this.readyState===A.CONNECTING)return void U(this,this._req,"WebSocket was closed before the connection was established");if(this.readyState===A.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=A.CLOSING,this._sender.close(e,t,!this._isServer,e=>{!e&&(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Y(this)}}pause(){this.readyState!==A.CONNECTING&&this.readyState!==A.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===A.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==A.OPEN)?j(this,e,r):(void 0===t&&(t=!this._isServer),this._sender.ping(e||v,t,r))}pong(e,t,r){if(this.readyState===A.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==A.OPEN)?j(this,e,r):(void 0===t&&(t=!this._isServer),this._sender.pong(e||v,t,r))}resume(){this.readyState!==A.CONNECTING&&this.readyState!==A.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===A.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==A.OPEN)return void j(this,e,r);let s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[p.extensionName]||(s.compress=!1),this._sender.send(e||v,s,r)}terminate(){if(this.readyState!==A.CLOSED){if(this.readyState===A.CONNECTING)return void U(this,this._req,"WebSocket was closed before the connection was established");this._socket&&(this._readyState=A.CLOSING,this._socket.destroy())}}}function D(e,t){e._readyState=A.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function L(e){return e.path=e.socketPath,o.connect(e)}function M(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=o.isIP(e.host)?"":e.host),a.connect(e)}function U(e,t,r){e._readyState=A.CLOSING;let s=Error(r);Error.captureStackTrace(s,U),t.setHeader?(t[R]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(D,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function j(e,t,r){if(t){let r=g(t)?t.size:$(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${P[e.readyState]})`);process.nextTick(r,t)}}function F(e,t){let r=this[E];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[E]&&(r._socket.removeListener("data",X),process.nextTick(q,r._socket),1005===e?r.close():r.close(e,t))}function B(){let e=this[E];e.isPaused||e._socket.resume()}function W(e){let t=this[E];void 0!==t._socket[E]&&(t._socket.removeListener("data",X),process.nextTick(q,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function G(){this[E].emitClose()}function V(e,t){this[E].emit("message",e,t)}function z(e){let t=this[E];t._autoPong&&t.pong(e,!this._isServer,x),t.emit("ping",e)}function H(e){this[E].emit("pong",e)}function q(e){e.resume()}function J(e){let t=this[E];t.readyState!==A.CLOSED&&(t.readyState===A.OPEN&&(t._readyState=A.CLOSING,Y(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Y(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function K(){let e,t=this[E];this.removeListener("close",K),this.removeListener("data",X),this.removeListener("end",Z),t._readyState=A.CLOSING,this._readableState.endEmitted||t._closeFrameReceived||t._receiver._writableState.errorEmitted||null===(e=t._socket.read())||t._receiver.write(e),t._receiver.end(),this[E]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",G),t._receiver.on("finish",G))}function X(e){this[E]._receiver.write(e)||this.pause()}function Z(){let e=this[E];e._readyState=A.CLOSING,e._receiver.end(),this.end()}function Q(){let e=this[E];this.removeListener("error",Q),this.on("error",x),e&&(e._readyState=A.CLOSING,this.destroy())}Object.defineProperty(A,"CONNECTING",{enumerable:!0,value:P.indexOf("CONNECTING")}),Object.defineProperty(A.prototype,"CONNECTING",{enumerable:!0,value:P.indexOf("CONNECTING")}),Object.defineProperty(A,"OPEN",{enumerable:!0,value:P.indexOf("OPEN")}),Object.defineProperty(A.prototype,"OPEN",{enumerable:!0,value:P.indexOf("OPEN")}),Object.defineProperty(A,"CLOSING",{enumerable:!0,value:P.indexOf("CLOSING")}),Object.defineProperty(A.prototype,"CLOSING",{enumerable:!0,value:P.indexOf("CLOSING")}),Object.defineProperty(A,"CLOSED",{enumerable:!0,value:P.indexOf("CLOSED")}),Object.defineProperty(A.prototype,"CLOSED",{enumerable:!0,value:P.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(A.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(A.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[w];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[b]:!0})}})}),A.prototype.addEventListener=C,A.prototype.removeEventListener=T,t.exports=A},66212,(e,t,r)=>{"use strict";e.r(6281);let{Duplex:s}=e.r(88947);function i(e){e.emit("close")}function n(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener("error",o),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}t.exports=function(e,t){let r=!0,a=new s({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,r){let s=!r&&a._readableState.objectMode?t.toString():t;a.push(s)||e.pause()}),e.once("error",function(e){a.destroyed||(r=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,s){if(e.readyState===e.CLOSED){s(t),process.nextTick(i,a);return}let n=!1;e.once("error",function(e){n=!0,s(e)}),e.once("close",function(){n||s(t),process.nextTick(i,a)}),r&&e.terminate()},a._final=function(t){e.readyState===e.CONNECTING?e.once("open",function(){a._final(t)}):null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close()))},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,r,s){e.readyState===e.CONNECTING?e.once("open",function(){a._write(t,r,s)}):e.send(t,s)},a.on("end",n),a.on("error",o),a}},9915,(e,t,r)=>{"use strict";let{tokenChars:s}=e.r(97112);t.exports={parse:function(e){let t=new Set,r=-1,i=-1,n=0;for(;n<e.length;n++){let o=e.charCodeAt(n);if(-1===i&&1===s[o])-1===r&&(r=n);else if(0!==n&&(32===o||9===o))-1===i&&-1!==r&&(i=n);else if(44===o){if(-1===r)throw SyntaxError(`Unexpected character at index ${n}`);-1===i&&(i=n);let s=e.slice(r,i);if(t.has(s))throw SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),r=i=-1}else throw SyntaxError(`Unexpected character at index ${n}`)}if(-1===r||-1!==i)throw SyntaxError("Unexpected end of input");let o=e.slice(r,n);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}}},3441,(e,t,r)=>{"use strict";let s=e.r(27699),i=e.r(21517),{Duplex:n}=e.r(88947),{createHash:o}=e.r(54799),a=e.r(94393),l=e.r(97012),c=e.r(9915),h=e.r(6281),{GUID:u,kWebSocket:d}=e.r(31258),p=/^[+/0-9A-Za-z]{22}==$/;function f(e){e._state=2,e.emit("close")}function m(){this.destroy()}function g(e,t,r,s){r=r||i.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r
2
2
  `+Object.keys(s).map(e=>`${e}: ${s[e]}`).join("\r\n")+"\r\n\r\n"+r)}function y(e,t,r,s,i,n){if(e.listenerCount("wsClientError")){let s=Error(i);Error.captureStackTrace(s,y),e.emit("wsClientError",s,r,t)}else g(r,s,i,n)}t.exports=class extends s{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:h,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=i.createServer((e,t)=>{let r=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return function(){for(let r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,s)=>{this.handleUpgrade(t,r,s,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state){e&&this.once("close",()=>{e(Error("The server is not running"))}),process.nextTick(f,this);return}if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(f,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{f(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",m);let i=e.headers["sec-websocket-key"],n=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void y(this,e,t,405,"Invalid HTTP method");if(void 0===n||"websocket"!==n.toLowerCase())return void y(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!p.test(i))return void y(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(13!==o&&8!==o)return void y(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});if(!this.shouldHandle(e))return void g(t,400);let h=e.headers["sec-websocket-protocol"],u=new Set;if(void 0!==h)try{u=c.parse(h)}catch(r){y(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&void 0!==d){let r=new l(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=a.parse(d);e[l.extensionName]&&(r.accept(e[l.extensionName]),f[l.extensionName]=r)}catch(r){y(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let n={origin:e.headers[`${8===o?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(n,(n,o,a,l)=>{if(!n)return g(t,o||401,a,l);this.completeUpgrade(f,i,u,e,t,r,s)});if(!this.options.verifyClient(n))return g(t,401)}this.completeUpgrade(f,i,u,e,t,r,s)}completeUpgrade(e,t,r,s,i,n,c){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return g(i,503);let h=o("sha1").update(t+u).digest("base64"),p=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${h}`],y=new this.options.WebSocket(null,void 0,this.options);if(r.size){let e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(p.push(`Sec-WebSocket-Protocol: ${e}`),y._protocol=e)}if(e[l.extensionName]){let t=e[l.extensionName].params,r=a.format({[l.extensionName]:[t]});p.push(`Sec-WebSocket-Extensions: ${r}`),y._extensions=e}this.emit("headers",p,s),i.write(p.concat("\r\n").join("\r\n")),i.removeListener("error",m),y.setSocket(i,n,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(y),y.on("close",()=>{this.clients.delete(y),this._shouldEmitClose&&!this.clients.size&&process.nextTick(f,this)})),c(y,s)}}},56891,e=>{"use strict";var t=e.i(33405),r=e.i(22734),s=e.i(46786),i=e.i(14747),n=e.i(73169),o=e.i(60801),a=e.i(24361);e.i(66212),e.i(17953),e.i(60238);var l=e.i(6281);e.i(3441),l.default;let c=(0,a.promisify)(t.exec);function h(e,t,r,s){let i=0;"build"===t?i=1e3:"server"===t?i=500:"browser"===t?i=300:"network"===t?i=200:"warning"===t&&(i=100),/CRITICAL|FATAL|crashed/i.test(e)?i*=2:/ERROR|Exception|FAIL/i.test(e)&&(i*=1.5);let n=e.replace(/\d+/g,"\\d+").substring(0,100),o=s.filter(e=>new RegExp(n).test(e)).length;o>1&&(i+=(o-1)*50),r.length>0&&(i+=50);let a=e.match(/\[(\d{2}):(\d{2}):(\d{2})\.\d{3}\]/);if(a){let e=new Date,t=new Date;t.setHours(parseInt(a[1],10)),t.setMinutes(parseInt(a[2],10)),t.setSeconds(parseInt(a[3],10)),(e.getTime()-t.getTime())/1e3/60<1&&(i+=100)}return i}async function u(e,t){try{let t=e.category.toUpperCase(),r=e.error.replace(/\[[^\]]+\]/g,"").trim().substring(0,100),s=`Fix: ${t} - ${r}`,i=`## 🐛 Bug Fix - ${e.category} Error
3
3
 
4
4
  **Priority Score:** ${e.priorityScore} (${e.severity})
@@ -35,10 +35,10 @@ Next steps:
35
35
  2. Commit and push changes
36
36
  3. PR is ready for review!`}catch(e){return`❌ Failed to create PR: ${e instanceof Error?e.message:String(e)}
37
37
 
38
- You can manually create a PR with the error details above.`}}function d(){let e=(0,i.join)((0,s.homedir)(),".d3k");if(!(0,r.existsSync)(e))return[];try{return(0,r.readdirSync)(e).filter(e=>e.endsWith(".json")).map(t=>{let s=(0,i.join)(e,t),n=JSON.parse((0,r.readFileSync)(s,"utf-8")),o=(0,r.statSync)(s);return{...n,sessionFile:s,lastModified:o.mtime}}).filter(e=>{if(!e.pid)return!1;try{return process.kill(e.pid,0),!0}catch{return!1}}).sort((e,t)=>new Date(t.startTime).getTime()-new Date(e.startTime).getTime())}catch(e){return[]}}function p(e){if(e){let t=d().find(t=>t.projectName===e);if(t)return t.logFilePath}let t=process.env.LOG_FILE_PATH;return t||null}async function f({projectName:t,focusArea:s="all",mode:i="snapshot",waitForUserInteraction:n=!1,timeRangeMinutes:o=10,includeTimestampInstructions:a=!0,integrateNextjs:l=!1,integrateChromeDevtools:c=!1,returnRawData:f=!1,createPR:m=!1}){let{getMCPClientManager:g}=await e.A(20654),y=g().getConnectedMCPs(),v=y.includes("nextjs-dev"),_=y.includes("chrome-devtools");y.length>0&&A(`Fix My App: Connected to downstream MCPs: ${y.join(", ")}`),v&&!1===l&&(l=!0),_&&!1===c&&(c=!0);let w=await b();w&&A("Fix My App: Recommending dev3000-nextjs-dev MCP for Next.js-specific analysis");let S=p(t);if(!S){let e=d();if(0===e.length)return{content:[{type:"text",text:"❌ No active dev3000 sessions found. Make sure dev3000 is running!"}]};if(A(`fix_my_app: Found ${e.length} sessions`),1===e.length){if(S=p(t=e[0].projectName),A(`fix_my_app: Auto-selected single session: ${t}, logPath: ${S}`),!S)return{content:[{type:"text",text:`❌ Could not find log file for project "${t}". The session may not be properly initialized yet.`}]}}else{let t=e.map(e=>`• ${e.projectName} (started ${new Date(e.startTime).toLocaleString()})`).join("\n");return{content:[{type:"text",text:`🔍 Found ${e.length} dev3000 sessions. Please specify which project to fix:
38
+ You can manually create a PR with the error details above.`}}function d(){let e=(0,i.join)((0,s.homedir)(),".d3k");if(!(0,r.existsSync)(e))return[];try{return(0,r.readdirSync)(e).filter(e=>e.endsWith(".json")).map(t=>{let s=(0,i.join)(e,t),n=JSON.parse((0,r.readFileSync)(s,"utf-8")),o=(0,r.statSync)(s);return{...n,sessionFile:s,lastModified:o.mtime}}).filter(e=>{if(!e.pid)return!1;try{return process.kill(e.pid,0),!0}catch{return!1}}).sort((e,t)=>new Date(t.startTime).getTime()-new Date(e.startTime).getTime())}catch(e){return[]}}function p(e){if(e){let t=d().find(t=>t.projectName===e);if(t)return t.logFilePath}let t=process.env.LOG_FILE_PATH;return t||null}async function f({projectName:t,focusArea:s="all",mode:i="snapshot",waitForUserInteraction:n=!1,timeRangeMinutes:o=10,includeTimestampInstructions:a=!0,integrateNextjs:l=!1,integrateChromeDevtools:c=!1,returnRawData:f=!1,createPR:m=!1}){let{getMCPClientManager:g}=await e.A(20654),y=g().getConnectedMCPs(),v=y.includes("nextjs-dev"),_=y.includes("chrome-devtools");y.length>0&&I(`Fix My App: Connected to downstream MCPs: ${y.join(", ")}`),v&&!1===l&&(l=!0),_&&!1===c&&(c=!0);let b=await E();b&&I("Fix My App: Recommending dev3000-nextjs-dev MCP for Next.js-specific analysis");let w=p(t);if(!w){let e=d();if(0===e.length)return{content:[{type:"text",text:"❌ No active dev3000 sessions found. Make sure dev3000 is running!"}]};if(I(`fix_my_app: Found ${e.length} sessions`),1===e.length){if(w=p(t=e[0].projectName),I(`fix_my_app: Auto-selected single session: ${t}, logPath: ${w}`),!w)return{content:[{type:"text",text:`❌ Could not find log file for project "${t}". The session may not be properly initialized yet.`}]}}else{let t=e.map(e=>`• ${e.projectName} (started ${new Date(e.startTime).toLocaleString()})`).join("\n");return{content:[{type:"text",text:`🔍 Found ${e.length} dev3000 sessions. Please specify which project to fix:
39
39
  ${t}
40
40
 
41
- 💡 Use: projectName: "your-project-name" parameter`}]}}}let x=[];if("bisect"===i&&n){let e=new Date().toISOString();return x.push("🕐 **TIMESTAMP BISECT MODE ACTIVATED**"),x.push(`📍 Start Time: ${e}`),x.push(""),x.push("🎯 **NOW INTERACT WITH YOUR APP TO REPRODUCE THE ISSUE!**"),x.push("• Click buttons, navigate, submit forms, etc."),x.push("• Reproduce the exact error scenario"),x.push("• When done, run this tool again WITHOUT waitForUserInteraction"),x.push(""),x.push("💡 I'll analyze everything that happens between these timestamps!"),{content:[{type:"text",text:x.join("\n")}]}}try{if(!(0,r.existsSync)(S))return x.push("📋 Log file doesn't exist yet. The dev server may still be starting up."),x.push("💡 Wait a few seconds for the server to generate logs, then try again."),{content:[{type:"text",text:x.join("\n")}]};let e=(0,r.readFileSync)(S,"utf-8").trim().split("\n").filter(Boolean);if(0===e.length)return x.push("📋 Log file is empty. Make sure your app is running and generating logs."),{content:[{type:"text",text:x.join("\n")}]};x.push(`🔍 **FIX MY APP ANALYSIS** - Mode: ${i.toUpperCase()}`),x.push(`📁 Log file: ${S}`),x.push(`📊 Total log entries: ${e.length}`),x.push("");let n=new Date,p=new Date(n.getTime()-60*o*1e3),g=[/ERROR/i,/FAIL/i,/Exception/i,/CRITICAL/i,/FATAL/i,/crashed/i,/undefined/i,/null reference/i,/cannot read/i,/cannot find/i,/not found/i,/timeout/i,/refused/i,/denied/i,/unauthorized/i,/404/,/500/,/503/,/WARN/i,/WARNING/i,/deprecated/i,/slow/i,/retry/i,/RUNTIME\.ERROR/,/hydration.*mismatch/i,/Uncaught/i,/throwOnHydrationMismatch/i],y=e.filter(e=>{let t=e.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/);if(t)return new Date(t[1])>=p;let r=e.match(/\[(\d{2}):(\d{2}):(\d{2})\.(\d{3})\]/);if(r){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate(),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[3],10),parseInt(r[4],10));return t>e&&t.setDate(t.getDate()-1),t>=p}return!0}),v=y.filter(e=>g.some(t=>t.test(e))),_=y.filter(e=>e.includes("react-scan")||e.includes("ReactScan")||e.includes("React render")),b={unnecessaryRenders:_.filter(e=>e.includes("unnecessary")||e.includes("re-render")||e.includes("wasted")),slowComponents:_.filter(e=>e.includes("slow")||e.includes("performance")||/\d+ms/.test(e)),totalRenders:_.filter(e=>e.includes("render")).length},T=[/link rel=preload.*must have.*valid.*as/i,/next\/font/i,/automatically generated/i,/\[NETWORK\].*\b(200|201|204|304)\b\s+(OK|Created|No Content|Not Modified)/i],C=v.filter(e=>!T.some(t=>t.test(e))),R={serverErrors:C.filter(e=>e.includes("[SERVER]")&&(e.includes("ERROR")||e.includes("Exception"))),browserErrors:C.filter(e=>e.includes("[BROWSER]")&&(e.includes("ERROR")||e.includes("CONSOLE ERROR")||e.includes("RUNTIME.ERROR"))),buildErrors:C.filter(e=>e.includes("Failed to compile")||e.includes("Type error")||e.includes("Build failed")),networkErrors:C.filter(e=>!/\b(200|201|204|304)\b/.test(e)&&(e.includes("NETWORK")||e.includes("404")||e.includes("500")||e.includes("timeout"))),warnings:C.filter(e=>/WARN|WARNING|deprecated/i.test(e)&&!/ERROR|Exception|FAIL/i.test(e))},N=C.length,k=N-R.warnings.length,I=e.filter(e=>g.some(t=>t.test(e))),O=I.length>N,$=(e,t)=>{let r=t.indexOf(e);if(-1===r)return[];let s=[];for(let e=r-1;e>=Math.max(0,r-20)&&s.length<5;e--)(t[e].includes("[INTERACTION]")||t[e].includes("[NAVIGATION]")||t[e].includes("[PAGE]"))&&s.unshift(t[e]);return s};if(0!==N||O)if(0===N&&O)x.push(`⚠️ **NO ERRORS IN LAST ${o} MINUTES** - But found ${I.length} errors in the full log`),x.push(""),x.push("📋 **RECENT ERRORS (outside time range):**"),I.slice(-5).forEach(t=>{let r=$(t,e);if(r.length>0)for(let e of(x.push(" 📍 Preceding interactions:"),r))x.push(` ${e}`);x.push(` ❌ ${t}`),x.push("")}),x.push("💡 **TIP:** Increase timeRangeMinutes parameter to analyze these errors"),x.push("💡 **TIP:** Or use timeRangeMinutes=60 to check the last hour");else{if(x.push(`🚨 **${N} ISSUES DETECTED** (${k} critical, ${R.warnings.length} warnings)`),x.push(""),R.serverErrors.length>0&&(x.push("🔥 **SERVER ERRORS:**"),R.serverErrors.slice(-5).forEach(t=>{let r=$(t,e);if(r.length>0)for(let e of(x.push(" 📍 Preceding interactions:"),r))x.push(` ${e}`);x.push(` ❌ ${t}`),x.push("")})),R.browserErrors.length>0&&(x.push("🌐 **BROWSER/CONSOLE ERRORS:**"),R.browserErrors.slice(-5).forEach(t=>{let r=$(t,e);if(r.length>0)for(let e of(x.push(" 📍 Preceding interactions:"),r))x.push(` ${e}`);x.push(` ❌ ${t}`),x.push("")})),R.buildErrors.length>0&&(x.push("🔨 **BUILD/COMPILATION ERRORS:**"),R.buildErrors.slice(-5).forEach(t=>{let r=$(t,e);if(r.length>0)for(let e of(x.push(" 📍 Preceding interactions:"),r))x.push(` ${e}`);x.push(` ❌ ${t}`),x.push("")})),R.networkErrors.length>0&&(x.push("🌐 **NETWORK/API ERRORS:**"),R.networkErrors.slice(-5).forEach(t=>{let r=$(t,e);if(r.length>0)for(let e of(x.push(" 📍 Preceding interactions:"),r))x.push(` ${e}`);x.push(` ❌ ${t}`),x.push("")})),R.warnings.length>0&&"all"===s&&(x.push(`⚠️ **WARNINGS** (${R.warnings.length} found, showing recent):`),x.push(R.warnings.slice(-3).join("\n")),x.push("")),x.push("🪄 **ULTIMATE DEV3000 FIX-IT MAGIC READY:**"),x.push("🎯 **I don't just find errors - I FIX them instantly!**"),x.push(""),x.push("📍 **INTERACTION-BASED VERIFICATION WORKFLOW:**"),x.push("• Each error shows the EXACT user interactions that triggered it"),x.push("• Use these interactions to reproduce the error with execute_browser_action"),x.push("• After fixing, replay the SAME interactions to verify the fix works"),x.push("• Example: If error shows [INTERACTION] Click at (x:450, y:300), use:"),x.push(" execute_browser_action(action='click', params={x:450, y:300})"),x.push(""),x.push("🔧 **FIX WORKFLOW:**"),x.push("1. Analyze error patterns and preceding interactions"),x.push("2. Provide exact fix code with file locations"),x.push("3. Guide you through implementing the fixes"),x.push("4. Use execute_browser_action to replay the interactions"),x.push("5. Verify the error no longer occurs!"),x.push("• Dev3000 AUTO-CAPTURES screenshots during all interactions!"),x.push("• No manual screenshots needed - dev3000 handles it all!"),x.push(""),x.push("📸 **AUTO-SCREENSHOT MAGIC:**"),x.push("• Screenshots captured on EVERY page navigation"),x.push("• Screenshots captured on EVERY error/exception"),x.push("• Screenshots captured on manual triggers"),x.push("• All screenshots timestamped and linked to events!"),l||c){let e=[];l&&e.push("Next.js"),c&&e.push("Chrome DevTools"),A(`Fix Analysis: Using active MCP integrations [${e.join(", ")}] for enhanced error analysis`,t),x.push(""),x.push("🎼 **MCP INTEGRATION ENHANCEMENTS:**"),l&&(x.push(""),x.push("⚛️ **Next.js Integration Active:**"),(await L(v.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";x.push(`• Use nextjs-dev.${e.function}${t}`),x.push(` → ${e.reason}`)}),R.serverErrors.length>0&&(x.push("• Correlate server errors with Next.js build/runtime logs"),x.push("• Check for SSR/hydration mismatches in Next.js context"))),c&&(x.push(""),x.push("🌐 **Chrome DevTools Integration Active:**"),(await M(v.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";x.push(`• Use chrome-devtools.${e.function}${t}`),x.push(` → ${e.reason}`)}),R.browserErrors.length>0&&(x.push("• Cross-reference browser console errors with Chrome DevTools"),x.push("• Use DOM inspection for UI interaction failures")),R.networkErrors.length>0&&(x.push("• Analyze network requests timing with Chrome DevTools"),x.push("• Inspect failed requests for detailed error context"))),l&&c&&(x.push(""),x.push("🚀 **TRIPLE-STACK DEBUGGING POWER:**"),x.push("• dev3000 provides interaction replay + error correlation"),x.push("• nextjs-dev provides server-side framework context"),x.push("• chrome-devtools provides precise browser state inspection"),x.push("• Combined = 90%+ issue resolution rate!"))}let r=function(e,t,r){let s=[],i=e=>{let t=r.indexOf(e);if(-1===t)return[];let s=[];for(let e=t-1;e>=Math.max(0,t-20)&&s.length<5;e--)(r[e].includes("[INTERACTION]")||r[e].includes("[NAVIGATION]")||r[e].includes("[PAGE]"))&&s.unshift(r[e]);return s};for(let r of e.buildErrors){let e=i(r);s.push({error:r,category:"build",severity:"critical",priorityScore:h(r,"build",e,t),interactions:e})}for(let r of e.serverErrors){let e=i(r),n=/CRITICAL|FATAL/i.test(r)?"critical":"error";s.push({error:r,category:"server",severity:n,priorityScore:h(r,"server",e,t),interactions:e})}for(let r of e.browserErrors){let e=i(r),n=/CRITICAL|FATAL/i.test(r)?"critical":"error";s.push({error:r,category:"browser",severity:n,priorityScore:h(r,"browser",e,t),interactions:e})}for(let r of e.networkErrors){let e=i(r);s.push({error:r,category:"network",severity:"error",priorityScore:h(r,"network",e,t),interactions:e})}if(0===s.length)for(let r of e.warnings){let e=i(r);s.push({error:r,category:"warning",severity:"warning",priorityScore:h(r,"warning",e,t),interactions:e})}return s.sort((e,t)=>t.priorityScore-e.priorityScore),s[0]||null}(R,C,e);if(r)if(x.push(""),x.push("🎯 **HIGHEST PRIORITY ISSUE:**"),x.push(`📊 Priority Score: ${r.priorityScore}`),x.push(`🏷️ Category: ${r.category.toUpperCase()}`),x.push(`⚠️ Severity: ${r.severity.toUpperCase()}`),x.push(""),x.push("❌ **Error:**"),x.push(` ${r.error}`),r.interactions.length>0&&(x.push(""),x.push("📍 **Reproduction Steps:**"),r.interactions.forEach((e,t)=>{x.push(` ${t+1}. ${e}`)})),m){x.push(""),x.push("🚀 **CREATING PR FOR THIS ISSUE...**");let e=await u(r,t||"");x.push(e)}else x.push(""),x.push("💡 **To create a PR for this issue:**"),x.push(" Run: fix_my_app(createPR=true)"),x.push(""),x.push(" This will:"),x.push(" • Create a new branch for the fix"),x.push(" • Generate a PR with full error context"),x.push(" • Include reproduction steps"),x.push(" • Focus on fixing just this ONE issue")}else x.push(`✅ **SYSTEM HEALTHY** - No errors found in last ${o} minutes`),x.push("🎯 App appears to be running smoothly!"),a&&"monitor"!==i&&(x.push(""),x.push("💡 **PROACTIVE MONITORING TIPS:**"),x.push("• Use mode='bisect' with waitForUserInteraction=true before testing new features"),x.push("• Use mode='monitor' for continuous background monitoring"),x.push("• Increase timeRangeMinutes to analyze longer periods"));let U=e.filter(e=>e.includes("[SCREENSHOT]")||e.includes("Screenshot captured"));if(U.length>0&&(x.push(""),x.push(`📸 **SCREENSHOTS CAPTURED** (${U.length} total):`),U.slice(-5).forEach(e=>{let t=e.match(/Screenshot captured: (.+)$/);t&&x.push(`• ${t[1]}`)}),x.push(""),x.push("💡 **TIP**: Use analyze_visual_diff tool to compare screenshots and identify changes"),x.push(" (Advanced: screenshots are also accessible via curl if needed)")),"performance"===s||"all"===s){let e=await P(t);if(e.detections.length>0){let r=d().find(e=>e.projectName===t),s=r&&r.sessionFile.match(/"mcpPort":\s*"(\d+)"/)?.[1]||"3684",i=`http://localhost:${s}/video/${e.sessionId}`;x.push(""),e.realCLS?x.push(`🚨 **LAYOUT SHIFT DETECTED** (${e.detections.length} ${1===e.detections.length?"shift":"shifts"} during page load):`):x.push(`🚨 **LOADING JANK DETECTED** (${e.detections.length} layout ${1===e.detections.length?"shift":"shifts"} found):`);let n="navigation"===e.captureTrigger?"Navigation complete":"load"===e.captureTrigger?"Load complete":"View all frames";x.push(`📹 **${n}**: ${i}`),x.push(`🎞️ **Session ID**: ${e.sessionId} (${e.totalFrames} frames)`),x.push(""),e.detections.forEach(e=>{let t="high"===e.severity?"🔴":"medium"===e.severity?"🟡":"🟢";if(e.uxImpact?(x.push(`${t} **${e.timeSinceStart}ms** - ${e.element}`),x.push(` ${e.uxImpact}`)):x.push(`${t} **${e.timeSinceStart}ms**: ${e.visualDiff.toFixed(1)}% of screen changed (${e.severity} severity)`),e.beforeFrameUrl&&e.afterFrameUrl&&(x.push(` 📸 Before: ${e.beforeFrameUrl}`),x.push(` 📸 After: ${e.afterFrameUrl}`),x.push(` 💡 Use analyze_visual_diff tool with these URLs to get a detailed description of what changed`),e.element)){let t=e.element.match(/<(\w+)>/);if(t){let e=t[1].toLowerCase();x.push(` 💡 Use find_component_source tool with selector "${e}" to locate the source code`)}}}),x.push(""),e.detections.some(e=>"high"===e.severity)&&e.realCLS&&(x.push("🎯 **WHY DEV3000 CAUGHT THIS BUT CHROME MIGHT NOT:**"),x.push("• dev3000's PerformanceObserver is installed immediately at page load and buffers ALL shifts from the start"),x.push("• Chrome DevTools performance trace may start AFTER initial load, missing early navigation shifts"),x.push("• Our UX-focused detection flags critical element shifts (nav/header) even when CLS score is technically 'good'"),x.push("")),x.push("✅ **DEV3000'S CLS DETECTION IS AUTHORITATIVE**"),x.push("If Chrome DevTools reports CLS: 0.00 but dev3000 detected shifts, TRUST DEV3000."),x.push("• Chrome DevTools trace may start AFTER the shifts occurred"),x.push("• dev3000's PerformanceObserver captures ALL shifts from page start"),x.push("• CLS: 0.00 in Chrome just means the trace missed the early shifts"),x.push(""),x.push("💡 **LAYOUT SHIFT DEBUGGING TIPS:**"),x.push("• Add explicit width/height to images and media"),x.push("• Reserve space for dynamic content (ads, embeds, etc.)"),x.push("• Avoid inserting content above existing content"),x.push("• Use CSS aspect-ratio for responsive elements"),x.push("• Check for web fonts causing text reflow (font-display: swap)"),x.push(`• Raw screenshots: ${e.screenshotDir}`),x.push(""),x.push("📸 **ANALYZING SCREENSHOTS:**"),x.push("• RECOMMENDED: Use analyze_visual_diff tool with before/after URLs (shown above)"),x.push("• The tool provides structured instructions for comparing frames"),x.push("• Advanced: Screenshots are also accessible via curl if needed"),x.push(""),x.push(`🎬 **IMPORTANT**: Share this frame sequence link with the user: ${i}`)}}if((b.totalRenders>0||"performance"===s||"all"===s)&&(b.unnecessaryRenders.length>0||b.slowComponents.length>0)&&(x.push(""),x.push("⚛️ **REACT PERFORMANCE ANALYSIS (react-scan):**"),b.unnecessaryRenders.length>0&&(x.push(`🔄 **Unnecessary Re-renders Detected (${b.unnecessaryRenders.length}):**`),b.unnecessaryRenders.slice(-5).forEach(e=>{x.push(`• ${e}`)}),x.push("")),b.slowComponents.length>0&&(x.push(`🐌 **Slow Components Found (${b.slowComponents.length}):**`),b.slowComponents.slice(-5).forEach(e=>{x.push(`• ${e}`)}),x.push("")),x.push("💡 **REACT OPTIMIZATION TIPS:**"),x.push("• Use React.memo() for components with expensive renders"),x.push("• Use useMemo/useCallback to prevent unnecessary re-renders"),x.push("• Check for unstable prop references (objects/arrays created in render)"),x.push("• Consider using React DevTools Profiler for deeper analysis")),0===N&&"all"===s){let t=e.filter(e=>e.includes("took")&&e.includes("ms"));t.length>0&&(x.push(""),x.push("⚡ **PERFORMANCE INSIGHTS:**"),t.slice(-5).forEach(e=>{x.push(`• ${e}`)}))}if(f){let r;A(`Structured Output: Returning structured data for Claude orchestration with ${N} errors and ${l||c?"active":"no"} integrations`,t);let i=v.map(t=>{let r=$(t,e),s=R.serverErrors.includes(t)?"server":R.browserErrors.includes(t)?"browser":R.buildErrors.includes(t)?"build":R.networkErrors.includes(t)?"network":R.warnings.includes(t)?"warning":"general",i=R.warnings.includes(t)?"warning":t.includes("CRITICAL")||t.includes("FATAL")||t.includes("crashed")?"critical":"error",n=t.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/)||t.match(/\[(\d{2}:\d{2}:\d{2}\.\d{3})\]/);return{timestamp:n?n[1]:new Date().toISOString(),category:s,message:t,interactions:r,severity:i}}),n=[];i.forEach(e=>{("hydration"===e.category||e.message.includes("hydration"))&&n.push({file:"pages/_app.js or components/[component].tsx",description:"Fix hydration mismatch",code:`// Ensure server and client render the same content
41
+ 💡 Use: projectName: "your-project-name" parameter`}]}}}let x=[];if("bisect"===i&&n){let e=new Date().toISOString();return x.push("🕐 **TIMESTAMP BISECT MODE ACTIVATED**"),x.push(`📍 Start Time: ${e}`),x.push(""),x.push("🎯 **NOW INTERACT WITH YOUR APP TO REPRODUCE THE ISSUE!**"),x.push("• Click buttons, navigate, submit forms, etc."),x.push("• Reproduce the exact error scenario"),x.push("• When done, run this tool again WITHOUT waitForUserInteraction"),x.push(""),x.push("💡 I'll analyze everything that happens between these timestamps!"),{content:[{type:"text",text:x.join("\n")}]}}try{if(!(0,r.existsSync)(w))return x.push("📋 Log file doesn't exist yet. The dev server may still be starting up."),x.push("💡 Wait a few seconds for the server to generate logs, then try again."),{content:[{type:"text",text:x.join("\n")}]};let e=(0,r.readFileSync)(w,"utf-8").trim().split("\n").filter(Boolean);if(0===e.length)return x.push("📋 Log file is empty. Make sure your app is running and generating logs."),{content:[{type:"text",text:x.join("\n")}]};x.push(`🔍 **FIX MY APP ANALYSIS** - Mode: ${i.toUpperCase()}`),x.push(`📁 Log file: ${w}`),x.push(`📊 Total log entries: ${e.length}`),x.push("");let n=new Date,p=new Date(n.getTime()-60*o*1e3),g=[/ERROR/i,/FAIL/i,/Exception/i,/CRITICAL/i,/FATAL/i,/crashed/i,/undefined/i,/null reference/i,/cannot read/i,/cannot find/i,/not found/i,/timeout/i,/refused/i,/denied/i,/unauthorized/i,/404/,/500/,/503/,/WARN/i,/WARNING/i,/deprecated/i,/slow/i,/retry/i,/RUNTIME\.ERROR/,/hydration.*mismatch/i,/Uncaught/i,/throwOnHydrationMismatch/i],y=e.filter(e=>{let t=e.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/);if(t)return new Date(t[1])>=p;let r=e.match(/\[(\d{2}):(\d{2}):(\d{2})\.(\d{3})\]/);if(r){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate(),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[3],10),parseInt(r[4],10));return t>e&&t.setDate(t.getDate()-1),t>=p}return!0}),v=y.filter(e=>g.some(t=>t.test(e))),_=y.filter(e=>e.includes("react-scan")||e.includes("ReactScan")||e.includes("React render")),E={unnecessaryRenders:_.filter(e=>e.includes("unnecessary")||e.includes("re-render")||e.includes("wasted")),slowComponents:_.filter(e=>e.includes("slow")||e.includes("performance")||/\d+ms/.test(e)),totalRenders:_.filter(e=>e.includes("render")).length},C=[/link rel=preload.*must have.*valid.*as/i,/next\/font/i,/automatically generated/i,/\[NETWORK\].*\b(200|201|204|304)\b\s+(OK|Created|No Content|Not Modified)/i],T=v.filter(e=>!C.some(t=>t.test(e))),k={serverErrors:T.filter(e=>e.includes("[SERVER]")&&(e.includes("ERROR")||e.includes("Exception"))),browserErrors:T.filter(e=>e.includes("[BROWSER]")&&(e.includes("ERROR")||e.includes("CONSOLE ERROR")||e.includes("RUNTIME.ERROR"))),buildErrors:T.filter(e=>e.includes("Failed to compile")||e.includes("Type error")||e.includes("Build failed")),networkErrors:T.filter(e=>!/\b(200|201|204|304)\b/.test(e)&&(e.includes("NETWORK")||e.includes("404")||e.includes("500")||e.includes("timeout"))),warnings:T.filter(e=>/WARN|WARNING|deprecated/i.test(e)&&!/ERROR|Exception|FAIL/i.test(e))},N=T.length,$=N-k.warnings.length,R=e.filter(e=>g.some(t=>t.test(e))),O=R.length>N,A=(e,t)=>{let r=t.indexOf(e);if(-1===r)return[];let s=[];for(let e=r-1;e>=Math.max(0,r-20)&&s.length<5;e--)(t[e].includes("[INTERACTION]")||t[e].includes("[NAVIGATION]")||t[e].includes("[PAGE]"))&&s.unshift(t[e]);return s};if(0!==N||O)if(0===N&&O)x.push(`No errors in last ${o} minutes, but found ${R.length} errors in full log.`),x.push(""),x.push("Older errors (outside time range):"),R.slice(-5).forEach(t=>{let r=A(t,e);if(r.length>0)for(let e of(x.push(" Preceding interactions:"),r))x.push(` ${e}`);x.push(` - ${t}`),x.push("")}),x.push("To analyze these errors, increase timeRangeMinutes (e.g., timeRangeMinutes=60)");else{if(x.push(`**${N} ISSUES DETECTED** (${$} critical, ${k.warnings.length} warnings)`),x.push(""),x.push("**ACTION REQUIRED:** Fix the highest-priority error below, then call fix_my_app again to verify."),x.push(""),k.serverErrors.length>0&&(x.push("SERVER ERRORS:"),k.serverErrors.slice(-5).forEach(t=>{let r=A(t,e);if(r.length>0)for(let e of(x.push(" Preceding interactions:"),r))x.push(` ${e}`);x.push(` - ${t}`),x.push("")})),k.browserErrors.length>0&&(x.push("BROWSER/CONSOLE ERRORS:"),k.browserErrors.slice(-5).forEach(t=>{let r=A(t,e);if(r.length>0)for(let e of(x.push(" Preceding interactions:"),r))x.push(` ${e}`);x.push(` - ${t}`),x.push("")})),k.buildErrors.length>0&&(x.push("BUILD/COMPILATION ERRORS:"),k.buildErrors.slice(-5).forEach(t=>{let r=A(t,e);if(r.length>0)for(let e of(x.push(" Preceding interactions:"),r))x.push(` ${e}`);x.push(` - ${t}`),x.push("")})),k.networkErrors.length>0&&(x.push("NETWORK/API ERRORS:"),k.networkErrors.slice(-5).forEach(t=>{let r=A(t,e);if(r.length>0)for(let e of(x.push(" Preceding interactions:"),r))x.push(` ${e}`);x.push(` - ${t}`),x.push("")})),k.warnings.length>0&&"all"===s&&(x.push(`WARNINGS (${k.warnings.length} found, showing recent):`),x.push(k.warnings.slice(-3).join("\n")),x.push("")),x.push("---"),x.push("**NEXT: Fix the highest-priority issue, then call fix_my_app again to verify.**"),x.push(""),x.push("Keep calling fix_my_app after each fix until no errors remain."),l||c){let e=[];l&&e.push("Next.js"),c&&e.push("Chrome DevTools"),I(`Fix Analysis: Using active MCP integrations [${e.join(", ")}] for enhanced error analysis`,t),x.push(""),x.push("**Available MCP integrations:**"),l&&(x.push(""),x.push("Next.js MCP (nextjs-dev):"),(await L(v.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";x.push(` • nextjs-dev.${e.function}${t}`),x.push(` Reason: ${e.reason}`)}),k.serverErrors.length>0&&x.push(" • Check Next.js build/runtime logs for SSR/hydration issues")),c&&(x.push(""),x.push("Chrome DevTools MCP (chrome-devtools):"),(await M(v.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";x.push(` • chrome-devtools.${e.function}${t}`),x.push(` Reason: ${e.reason}`)}),k.browserErrors.length>0&&x.push(" • Use DOM inspection for UI issues"),k.networkErrors.length>0&&x.push(" • Inspect network requests for detailed error context"))}let r=function(e,t,r){let s=[],i=e=>{let t=r.indexOf(e);if(-1===t)return[];let s=[];for(let e=t-1;e>=Math.max(0,t-20)&&s.length<5;e--)(r[e].includes("[INTERACTION]")||r[e].includes("[NAVIGATION]")||r[e].includes("[PAGE]"))&&s.unshift(r[e]);return s};for(let r of e.buildErrors){let e=i(r);s.push({error:r,category:"build",severity:"critical",priorityScore:h(r,"build",e,t),interactions:e})}for(let r of e.serverErrors){let e=i(r),n=/CRITICAL|FATAL/i.test(r)?"critical":"error";s.push({error:r,category:"server",severity:n,priorityScore:h(r,"server",e,t),interactions:e})}for(let r of e.browserErrors){let e=i(r),n=/CRITICAL|FATAL/i.test(r)?"critical":"error";s.push({error:r,category:"browser",severity:n,priorityScore:h(r,"browser",e,t),interactions:e})}for(let r of e.networkErrors){let e=i(r);s.push({error:r,category:"network",severity:"error",priorityScore:h(r,"network",e,t),interactions:e})}if(0===s.length)for(let r of e.warnings){let e=i(r);s.push({error:r,category:"warning",severity:"warning",priorityScore:h(r,"warning",e,t),interactions:e})}return s.sort((e,t)=>t.priorityScore-e.priorityScore),s[0]||null}(k,T,e);if(r)if(x.push(""),x.push("---"),x.push("**HIGHEST PRIORITY ISSUE (fix this first):**"),x.push(`Priority Score: ${r.priorityScore}`),x.push(`Category: ${r.category.toUpperCase()}`),x.push(`Severity: ${r.severity.toUpperCase()}`),x.push(""),x.push("Error:"),x.push(` ${r.error}`),r.interactions.length>0&&(x.push(""),x.push("Reproduction steps:"),r.interactions.forEach((e,t)=>{x.push(` ${t+1}. ${e}`)})),m){x.push(""),x.push("Creating PR branch for this issue...");let e=await u(r,t||"");x.push(e)}else x.push(""),x.push("To create a PR branch for this issue, run: fix_my_app(createPR=true)")}else x.push(`No errors found in last ${o} minutes.`),x.push("Application appears healthy."),a&&"monitor"!==i&&(x.push(""),x.push("Options:"),x.push("• Use mode='bisect' to compare before/after states during testing"),x.push("• Use mode='monitor' for continuous monitoring"),x.push("• Increase timeRangeMinutes to analyze a longer period"));let U=e.filter(e=>e.includes("[SCREENSHOT]")||e.includes("Screenshot captured"));if(U.length>0&&(x.push(""),x.push(`📸 **SCREENSHOTS CAPTURED** (${U.length} total):`),U.slice(-5).forEach(e=>{let t=e.match(/Screenshot captured: (.+)$/);t&&x.push(`• ${t[1]}`)}),x.push(""),x.push("💡 **TIP**: Use analyze_visual_diff tool to compare screenshots and identify changes"),x.push(" (Advanced: screenshots are also accessible via curl if needed)")),"performance"===s||"all"===s){let e=await P(t);if(e.detections.length>0){let r=d().find(e=>e.projectName===t),s=r&&r.sessionFile.match(/"mcpPort":\s*"(\d+)"/)?.[1]||"3684",i=`http://localhost:${s}/video/${e.sessionId}`;x.push(""),e.realCLS?x.push(`🚨 **LAYOUT SHIFT DETECTED** (${e.detections.length} ${1===e.detections.length?"shift":"shifts"} during page load):`):x.push(`🚨 **LOADING JANK DETECTED** (${e.detections.length} layout ${1===e.detections.length?"shift":"shifts"} found):`);let n="navigation"===e.captureTrigger?"Navigation complete":"load"===e.captureTrigger?"Load complete":"View all frames";x.push(`📹 **${n}**: ${i}`),x.push(`🎞️ **Session ID**: ${e.sessionId} (${e.totalFrames} frames)`),x.push(""),e.detections.forEach(e=>{let t="high"===e.severity?"🔴":"medium"===e.severity?"🟡":"🟢";if(e.uxImpact?(x.push(`${t} **${e.timeSinceStart}ms** - ${e.element}`),x.push(` ${e.uxImpact}`)):x.push(`${t} **${e.timeSinceStart}ms**: ${e.visualDiff.toFixed(1)}% of screen changed (${e.severity} severity)`),e.beforeFrameUrl&&e.afterFrameUrl&&(x.push(` 📸 Before: ${e.beforeFrameUrl}`),x.push(` 📸 After: ${e.afterFrameUrl}`),x.push(` 💡 Use analyze_visual_diff tool with these URLs to get a detailed description of what changed`),e.element)){let t=e.element.match(/<(\w+)>/);if(t){let e=t[1].toLowerCase();x.push(` 💡 Use find_component_source tool with selector "${e}" to locate the source code`)}}}),x.push(""),e.detections.some(e=>"high"===e.severity)&&e.realCLS&&(x.push("🎯 **WHY DEV3000 CAUGHT THIS BUT CHROME MIGHT NOT:**"),x.push("• dev3000's PerformanceObserver is installed immediately at page load and buffers ALL shifts from the start"),x.push("• Chrome DevTools performance trace may start AFTER initial load, missing early navigation shifts"),x.push("• Our UX-focused detection flags critical element shifts (nav/header) even when CLS score is technically 'good'"),x.push("")),x.push("✅ **DEV3000'S CLS DETECTION IS AUTHORITATIVE**"),x.push("If Chrome DevTools reports CLS: 0.00 but dev3000 detected shifts, TRUST DEV3000."),x.push("• Chrome DevTools trace may start AFTER the shifts occurred"),x.push("• dev3000's PerformanceObserver captures ALL shifts from page start"),x.push("• CLS: 0.00 in Chrome just means the trace missed the early shifts"),x.push(""),x.push("💡 **LAYOUT SHIFT DEBUGGING TIPS:**"),x.push("• Add explicit width/height to images and media"),x.push("• Reserve space for dynamic content (ads, embeds, etc.)"),x.push("• Avoid inserting content above existing content"),x.push("• Use CSS aspect-ratio for responsive elements"),x.push("• Check for web fonts causing text reflow (font-display: swap)"),x.push(`• Raw screenshots: ${e.screenshotDir}`),x.push(""),x.push("📸 **ANALYZING SCREENSHOTS:**"),x.push("• RECOMMENDED: Use analyze_visual_diff tool with before/after URLs (shown above)"),x.push("• The tool provides structured instructions for comparing frames"),x.push("• Advanced: Screenshots are also accessible via curl if needed"),x.push(""),x.push(`🎬 **IMPORTANT**: Share this frame sequence link with the user: ${i}`)}}if((E.totalRenders>0||"performance"===s||"all"===s)&&(E.unnecessaryRenders.length>0||E.slowComponents.length>0)&&(x.push(""),x.push("⚛️ **REACT PERFORMANCE ANALYSIS (react-scan):**"),E.unnecessaryRenders.length>0&&(x.push(`🔄 **Unnecessary Re-renders Detected (${E.unnecessaryRenders.length}):**`),E.unnecessaryRenders.slice(-5).forEach(e=>{x.push(`• ${e}`)}),x.push("")),E.slowComponents.length>0&&(x.push(`🐌 **Slow Components Found (${E.slowComponents.length}):**`),E.slowComponents.slice(-5).forEach(e=>{x.push(`• ${e}`)}),x.push("")),x.push("💡 **REACT OPTIMIZATION TIPS:**"),x.push("• Use React.memo() for components with expensive renders"),x.push("• Use useMemo/useCallback to prevent unnecessary re-renders"),x.push("• Check for unstable prop references (objects/arrays created in render)"),x.push("• Consider using React DevTools Profiler for deeper analysis")),0===N&&"all"===s){let t=e.filter(e=>e.includes("took")&&e.includes("ms"));t.length>0&&(x.push(""),x.push("⚡ **PERFORMANCE INSIGHTS:**"),t.slice(-5).forEach(e=>{x.push(`• ${e}`)}))}if(f){let r;I(`Structured Output: Returning structured data for Claude orchestration with ${N} errors and ${l||c?"active":"no"} integrations`,t);let i=v.map(t=>{let r=A(t,e),s=k.serverErrors.includes(t)?"server":k.browserErrors.includes(t)?"browser":k.buildErrors.includes(t)?"build":k.networkErrors.includes(t)?"network":k.warnings.includes(t)?"warning":"general",i=k.warnings.includes(t)?"warning":t.includes("CRITICAL")||t.includes("FATAL")||t.includes("crashed")?"critical":"error",n=t.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/)||t.match(/\[(\d{2}:\d{2}:\d{2}\.\d{3})\]/);return{timestamp:n?n[1]:new Date().toISOString(),category:s,message:t,interactions:r,severity:i}}),n=[];i.forEach(e=>{("hydration"===e.category||e.message.includes("hydration"))&&n.push({file:"pages/_app.js or components/[component].tsx",description:"Fix hydration mismatch",code:`// Ensure server and client render the same content
42
42
  // Use useEffect for client-only logic
43
43
  useEffect(() => {
44
44
  // Client-only code here
@@ -49,7 +49,7 @@ if (data && data.property) {
49
49
  // Or use optional chaining
50
50
  const value = data?.property?.nestedProperty`,reason:"Prevent TypeError by checking for undefined/null values"}),(e.message.includes("404")||e.message.includes("not found"))&&n.push({file:"routing configuration or API endpoints",description:"Fix missing route or resource",code:`// Check route configuration
51
51
  // Ensure API endpoint exists
52
- // Verify file paths are correct`,reason:"404 errors indicate missing resources or incorrect paths"})});let o={};l&&(o.nextjs=await L(v.join(" "))),c&&(o.chrome=await M(v.join(" "))),(l||c)&&(r={phase1:{name:"Data Collection",description:"Parallel data gathering across all available MCPs",actions:[{mcp:"dev3000",function:"fix_my_app",params:{focusArea:s,integrateNextjs:l,integrateChromeDevtools:c,returnRawData:!0},reason:"Get comprehensive error analysis with interaction data"}],estimatedTime:"2-3 minutes"},phase2:{name:"Deep Analysis",description:"Cross-MCP correlation and targeted investigation",actions:[{mcp:"dev3000",function:"fix_my_app",params:{mode:"bisect"},reason:"Regression analysis if needed"}],estimatedTime:"3-5 minutes"},phase3:{name:"Fix & Verify",description:"Implementation and verification across all layers",actions:[{mcp:"dev3000",function:"execute_browser_action",reason:"Replay interactions to verify fixes"}],estimatedTime:"5-10 minutes"}},l&&o.nextjs&&(r.phase1.actions.push(...o.nextjs.filter(e=>"high"===e.priority).map(e=>({mcp:"nextjs-dev",function:e.function,params:e.params,reason:e.reason}))),r.phase3.actions.push({mcp:"nextjs-dev",function:"check_build_status",reason:"Verify build success after fixes"})),c&&o.chrome&&r.phase1.actions.push(...o.chrome.filter(e=>"high"===e.priority).map(e=>({mcp:"chrome-devtools",function:e.function,params:e.params,reason:e.reason}))));let a={errors:i,fixes:n,suggestedIntegrations:o,workflowPlan:r,summary:{totalErrors:N,criticalErrors:k,hasIntegrations:l||c,estimatedFixTime:D(N,l||c)}};return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}let F=await E("profile_performance");return(w||F)&&(x.push(""),x.push("🔗 **AUGMENTED ANALYSIS AVAILABLE**"),x.push(""),x.push("dev3000 provided the core log analysis above. For deeper insights, consider also gathering:"),x.push(""),w&&(x.push("**Next.js Framework Analysis:**"),(await L(v.join(" "))).slice(0,3).forEach(e=>{x.push(`• \`dev3000-nextjs-dev:${e.function}()\` - ${e.reason}`)}),x.push("")),F&&(x.push("**Browser-Side Analysis:**"),(await M(v.join(" "))).slice(0,3).forEach(e=>{x.push(`• \`dev3000-chrome-devtools:${e.function}()\` - ${e.reason}`)}),x.push("")),x.push("💡 **Best approach:** Use dev3000's log analysis as your foundation, then gather specific additional data as needed for a complete picture.")),{content:[{type:"text",text:x.join("\n")}]}}catch(e){return{content:[{type:"text",text:`Error analyzing logs: ${e instanceof Error?e.message:String(e)}`}]}}}let m=new Map,g={chrome:["inspect","debug","profile","performance","console","devtools","breakpoint","intercept","storage","memory","trace"],nextjs:["build","hydration","ssr","routing","analyze","debug","render","middleware","optimization"]},y=["screenshot","navigate","click","type","scroll","evaluate","simple_script","get_logs","basic_build_status","simple_error_check"];async function v(e){let t=m.get(e);if(t&&Date.now()-t.timestamp<3e5)return A(`Capability Discovery: Using cached capabilities for ${e} (${t.capabilities.length} functions)`),t.capabilities;A(`Capability Discovery: Fetching fresh capabilities for ${e}`);try{let t=await _(e);if(t.length>0)return m.set(e,{timestamp:Date.now(),capabilities:t}),A(`Capability Discovery: Successfully discovered ${t.length} capabilities for ${e}`),t;let r=await S(e);return m.set(e,{timestamp:Date.now(),capabilities:r}),A(`Capability Discovery: Using fallback inference for ${e} (${r.length} functions)`),r}catch(t){return A(`Capability Discovery: Failed to discover capabilities for ${e} - ${t}`),[]}}async function _(t){try{let s=`/Users/${process.env.USER}/Library/Caches/claude-cli-nodejs`,{readdirSync:i,existsSync:n,readFileSync:o}=await e.A(23970);if(!n(s))return[];let a=i(s).find(e=>e.includes(process.cwd().replace(/\//g,"-")));if(!a)return[];let l=`${s}/${a}/mcp-logs-${t}`;if(!n(l))return[];let c=i(l),h=[];for(let e of c.slice(-5))try{let r=`${l}/${e}`,s=o(r,"utf8"),i=function(e,t){let r=[],s=t.includes("chrome")?"chrome":t.includes("nextjs")?"nextjs":"chrome",i=g[s];for(let t of[/"name":\s*"([^"]+)"/g,/(\w+)\s*\([^)]*\)/g,/tool:\s*(\w+)/g,/unknown function[:\s]+(\w+)/gi,/exports\.(\w+)/g]){let n=t.exec(e);for(;null!==n;){let o=n[1];if(y.some(e=>o.toLowerCase().includes(e))){n=t.exec(e);continue}let a=i.some(e=>o.toLowerCase().includes(e)),l=w(o,s,a);r.push({function:o,description:void 0,category:a?"advanced":"basic",reason:l}),n=t.exec(e)}}return r}(s,t);h.push(...i)}catch(e){}var r=h;let u=new Map;for(let e of r){let t=u.get(e.function);(!t||e.description&&!t.description||e.reason.length>t.reason.length)&&u.set(e.function,e)}return Array.from(u.values())}catch(e){return A(`MCP Introspection: Failed to introspect ${t} - ${e}`),[]}}function w(e,t,r){let s=e.toLowerCase();if("chrome"===t){if(s.includes("inspect"))return"Deep DOM inspection with DevTools-level detail";if(s.includes("console"))return"Direct browser console access and manipulation";if(s.includes("debug")||s.includes("breakpoint"))return"JavaScript debugging with breakpoints and call stack";if(s.includes("profile")||s.includes("performance"))return"Advanced performance profiling and analysis";if(s.includes("network")||s.includes("request"))return"Network request interception and analysis";if(s.includes("storage"))return"Browser storage manipulation (cookies, localStorage, etc.)";if(s.includes("trace")||s.includes("memory"))return"Memory usage and execution tracing"}if("nextjs"===t){if(s.includes("build"))return"Advanced Next.js build system analysis";if(s.includes("hydration"))return"Client-server hydration debugging and analysis";if(s.includes("ssr")||s.includes("render"))return"Server-side rendering debugging";if(s.includes("route")||s.includes("routing"))return"Next.js routing system inspection and debugging";if(s.includes("middleware"))return"Next.js middleware analysis and debugging";if(s.includes("optimization")||s.includes("performance"))return"Next.js-specific performance optimization"}return r?`Advanced ${t} capability beyond dev3000's basic automation`:`${t} capability for specialized analysis`}async function S(e){let t=e.includes("chrome")?"chrome":e.includes("nextjs")?"nextjs":"unknown",r=[];if("chrome"===t)for(let e of["inspect_element","access_console","start_performance_profile","intercept_requests","set_breakpoint","take_screenshot","get_dom_snapshot","modify_storage","execute_script"])r.push({function:e,category:y.includes(e)?"basic":"advanced",reason:w(e,t,!0)});if("nextjs"===t)for(let e of["analyze_build_process","debug_server_rendering","debug_hydration","inspect_routing","analyze_next_performance","get_build_info","check_build_status","get_server_logs"])r.push({function:e,category:y.includes(e)?"basic":"advanced",reason:w(e,t,!0)});return A(`Capability Inference: Generated ${r.length} inferred capabilities for ${e}`),r}async function E(e){try{if(!(await I()).includes("dev3000-chrome-devtools"))return!1;if(!e)return!0;return(await v("dev3000-chrome-devtools")).some(t=>t.function.toLowerCase().includes(e.toLowerCase())||"advanced"===t.category)}catch(e){return A(`Chrome DevTools delegation check failed: ${e}`),!1}}async function b(){try{if(!(await I()).includes("dev3000-nextjs-dev"))return!1;return(await v("dev3000-nextjs-dev")).some(e=>"advanced"===e.category)}catch(e){return A(`NextJS delegation check failed: ${e}`),!1}}async function x(e,t){let r=(await v("dev3000-chrome-devtools")).find(t=>t.function.toLowerCase().includes(e.toLowerCase())||t.description?.toLowerCase().includes(e.toLowerCase()));if(!r)throw Error(`Action ${e} cannot be delegated to chrome-devtools`);return{content:[{type:"text",text:`🔗 **ADVANCED BROWSER DEBUGGING AVAILABLE**
52
+ // Verify file paths are correct`,reason:"404 errors indicate missing resources or incorrect paths"})});let o={};l&&(o.nextjs=await L(v.join(" "))),c&&(o.chrome=await M(v.join(" "))),(l||c)&&(r={phase1:{name:"Data Collection",description:"Parallel data gathering across all available MCPs",actions:[{mcp:"dev3000",function:"fix_my_app",params:{focusArea:s,integrateNextjs:l,integrateChromeDevtools:c,returnRawData:!0},reason:"Get comprehensive error analysis with interaction data"}],estimatedTime:"2-3 minutes"},phase2:{name:"Deep Analysis",description:"Cross-MCP correlation and targeted investigation",actions:[{mcp:"dev3000",function:"fix_my_app",params:{mode:"bisect"},reason:"Regression analysis if needed"}],estimatedTime:"3-5 minutes"},phase3:{name:"Fix & Verify",description:"Implementation and verification across all layers",actions:[{mcp:"dev3000",function:"execute_browser_action",reason:"Replay interactions to verify fixes"}],estimatedTime:"5-10 minutes"}},l&&o.nextjs&&(r.phase1.actions.push(...o.nextjs.filter(e=>"high"===e.priority).map(e=>({mcp:"nextjs-dev",function:e.function,params:e.params,reason:e.reason}))),r.phase3.actions.push({mcp:"nextjs-dev",function:"check_build_status",reason:"Verify build success after fixes"})),c&&o.chrome&&r.phase1.actions.push(...o.chrome.filter(e=>"high"===e.priority).map(e=>({mcp:"chrome-devtools",function:e.function,params:e.params,reason:e.reason}))));let a={errors:i,fixes:n,suggestedIntegrations:o,workflowPlan:r,summary:{totalErrors:N,criticalErrors:$,hasIntegrations:l||c,estimatedFixTime:D(N,l||c)}};return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}let j=await S("profile_performance");return(b||j)&&(x.push(""),x.push("🔗 **AUGMENTED ANALYSIS AVAILABLE**"),x.push(""),x.push("dev3000 provided the core log analysis above. For deeper insights, consider also gathering:"),x.push(""),b&&(x.push("**Next.js Framework Analysis:**"),(await L(v.join(" "))).slice(0,3).forEach(e=>{x.push(`• \`dev3000-nextjs-dev:${e.function}()\` - ${e.reason}`)}),x.push("")),j&&(x.push("**Browser-Side Analysis:**"),(await M(v.join(" "))).slice(0,3).forEach(e=>{x.push(`• \`dev3000-chrome-devtools:${e.function}()\` - ${e.reason}`)}),x.push("")),x.push("💡 **Best approach:** Use dev3000's log analysis as your foundation, then gather specific additional data as needed for a complete picture.")),{content:[{type:"text",text:x.join("\n")}]}}catch(e){return{content:[{type:"text",text:`Error analyzing logs: ${e instanceof Error?e.message:String(e)}`}]}}}let m=new Map,g={chrome:["inspect","debug","profile","performance","console","devtools","breakpoint","intercept","storage","memory","trace"],nextjs:["build","hydration","ssr","routing","analyze","debug","render","middleware","optimization"]},y=["screenshot","navigate","click","type","scroll","evaluate","simple_script","get_logs","basic_build_status","simple_error_check"];async function v(e){let t=m.get(e);if(t&&Date.now()-t.timestamp<3e5)return I(`Capability Discovery: Using cached capabilities for ${e} (${t.capabilities.length} functions)`),t.capabilities;I(`Capability Discovery: Fetching fresh capabilities for ${e}`);try{let t=await _(e);if(t.length>0)return m.set(e,{timestamp:Date.now(),capabilities:t}),I(`Capability Discovery: Successfully discovered ${t.length} capabilities for ${e}`),t;let r=await w(e);return m.set(e,{timestamp:Date.now(),capabilities:r}),I(`Capability Discovery: Using fallback inference for ${e} (${r.length} functions)`),r}catch(t){return I(`Capability Discovery: Failed to discover capabilities for ${e} - ${t}`),[]}}async function _(t){try{let s=`/Users/${process.env.USER}/Library/Caches/claude-cli-nodejs`,{readdirSync:i,existsSync:n,readFileSync:o}=await e.A(23970);if(!n(s))return[];let a=i(s).find(e=>e.includes(process.cwd().replace(/\//g,"-")));if(!a)return[];let l=`${s}/${a}/mcp-logs-${t}`;if(!n(l))return[];let c=i(l),h=[];for(let e of c.slice(-5))try{let r=`${l}/${e}`,s=o(r,"utf8"),i=function(e,t){let r=[],s=t.includes("chrome")?"chrome":t.includes("nextjs")?"nextjs":"chrome",i=g[s];for(let t of[/"name":\s*"([^"]+)"/g,/(\w+)\s*\([^)]*\)/g,/tool:\s*(\w+)/g,/unknown function[:\s]+(\w+)/gi,/exports\.(\w+)/g]){let n=t.exec(e);for(;null!==n;){let o=n[1];if(y.some(e=>o.toLowerCase().includes(e))){n=t.exec(e);continue}let a=i.some(e=>o.toLowerCase().includes(e)),l=b(o,s,a);r.push({function:o,description:void 0,category:a?"advanced":"basic",reason:l}),n=t.exec(e)}}return r}(s,t);h.push(...i)}catch(e){}var r=h;let u=new Map;for(let e of r){let t=u.get(e.function);(!t||e.description&&!t.description||e.reason.length>t.reason.length)&&u.set(e.function,e)}return Array.from(u.values())}catch(e){return I(`MCP Introspection: Failed to introspect ${t} - ${e}`),[]}}function b(e,t,r){let s=e.toLowerCase();if("chrome"===t){if(s.includes("inspect"))return"Deep DOM inspection with DevTools-level detail";if(s.includes("console"))return"Direct browser console access and manipulation";if(s.includes("debug")||s.includes("breakpoint"))return"JavaScript debugging with breakpoints and call stack";if(s.includes("profile")||s.includes("performance"))return"Advanced performance profiling and analysis";if(s.includes("network")||s.includes("request"))return"Network request interception and analysis";if(s.includes("storage"))return"Browser storage manipulation (cookies, localStorage, etc.)";if(s.includes("trace")||s.includes("memory"))return"Memory usage and execution tracing"}if("nextjs"===t){if(s.includes("build"))return"Advanced Next.js build system analysis";if(s.includes("hydration"))return"Client-server hydration debugging and analysis";if(s.includes("ssr")||s.includes("render"))return"Server-side rendering debugging";if(s.includes("route")||s.includes("routing"))return"Next.js routing system inspection and debugging";if(s.includes("middleware"))return"Next.js middleware analysis and debugging";if(s.includes("optimization")||s.includes("performance"))return"Next.js-specific performance optimization"}return r?`Advanced ${t} capability beyond dev3000's basic automation`:`${t} capability for specialized analysis`}async function w(e){let t=e.includes("chrome")?"chrome":e.includes("nextjs")?"nextjs":"unknown",r=[];if("chrome"===t)for(let e of["inspect_element","access_console","start_performance_profile","intercept_requests","set_breakpoint","take_screenshot","get_dom_snapshot","modify_storage","execute_script"])r.push({function:e,category:y.includes(e)?"basic":"advanced",reason:b(e,t,!0)});if("nextjs"===t)for(let e of["analyze_build_process","debug_server_rendering","debug_hydration","inspect_routing","analyze_next_performance","get_build_info","check_build_status","get_server_logs"])r.push({function:e,category:y.includes(e)?"basic":"advanced",reason:b(e,t,!0)});return I(`Capability Inference: Generated ${r.length} inferred capabilities for ${e}`),r}async function S(e){try{if(!(await R()).includes("dev3000-chrome-devtools"))return!1;if(!e)return!0;return(await v("dev3000-chrome-devtools")).some(t=>t.function.toLowerCase().includes(e.toLowerCase())||"advanced"===t.category)}catch(e){return I(`Chrome DevTools delegation check failed: ${e}`),!1}}async function E(){try{if(!(await R()).includes("dev3000-nextjs-dev"))return!1;return(await v("dev3000-nextjs-dev")).some(e=>"advanced"===e.category)}catch(e){return I(`NextJS delegation check failed: ${e}`),!1}}async function x(e,t){let r=(await v("dev3000-chrome-devtools")).find(t=>t.function.toLowerCase().includes(e.toLowerCase())||t.description?.toLowerCase().includes(e.toLowerCase()));if(!r)throw Error(`Action ${e} cannot be delegated to chrome-devtools`);return{content:[{type:"text",text:`🔗 **ADVANCED BROWSER DEBUGGING AVAILABLE**
53
53
 
54
54
  For advanced debugging capabilities, use the \`dev3000-chrome-devtools\` MCP:
55
55
 
@@ -63,7 +63,7 @@ dev3000-chrome-devtools:${r.function}(${JSON.stringify(t,null,2)})
63
63
  • **dev3000**: Basic browser automation (screenshots, navigation, clicks, simple scripts)
64
64
  • **dev3000-chrome-devtools**: Advanced debugging (DOM inspection, breakpoints, performance profiling, network interception)
65
65
 
66
- ⚡ **Both tools share the same Chrome instance** - no conflicts or duplicate browsers`}]}}async function T({action:e,params:t={}}){try{if(await E(e))return A(`Browser Action Delegation: Routing '${e}' to chrome-devtools MCP`),await x(e,t);A(`Browser Action Fallback: Using dev3000's execute_browser_action for '${e}'`);let s=d();if(0===s.length)return{content:[{type:"text",text:"❌ No active dev3000 sessions found. Make sure dev3000 is running with a browser!"}]};let i=JSON.parse((0,r.readFileSync)(s[0].sessionFile,"utf-8")),n=i.cdpUrl;if(!n)try{let e=await fetch("http://localhost:9222/json"),t=(await e.json()).find(e=>"page"===e.type&&!e.url.startsWith("chrome://"));t&&(n=t.webSocketDebuggerUrl,A(`CDP Discovery: Found fallback CDP URL ${n}`,s[0].projectName))}catch(e){A(`CDP Discovery: Failed to find fallback CDP URL - ${e}`,s[0].projectName)}if(!n)return{content:[{type:"text",text:`❌ No Chrome DevTools Protocol URL found. Make sure dev3000 is running with browser monitoring enabled (not --servers-only mode). Session CDP URL: ${i.cdpUrl||"null"}`}]};let o=await new Promise((r,s)=>{let i=new l.default(n),o=setTimeout(()=>{i.close(),s(Error(`Browser action '${e}' timed out after 60 seconds. This may indicate an issue with the browser or invalid parameters.`))},6e4);i.on("open",async()=>{try{i.send(JSON.stringify({id:1,method:"Target.getTargets",params:{}}));let a=null,l=2;async function n(e,t,r,s){return new Promise((i,n)=>{let o=r=>{let s=JSON.parse(r.toString());s.id===t&&(e.removeListener("message",o),s.error?n(Error(s.error.message)):i(s.result))};e.on("message",o),e.send(JSON.stringify({id:t,method:r,params:s})),setTimeout(()=>{e.removeListener("message",o),n(Error(`CDP command timeout after 30s: ${r}`))},3e4)})}i.on("message",async c=>{try{let h=JSON.parse(c.toString());if(1===h.id){let e=h.result.targetInfos.find(e=>"page"===e.type);if(!e){i.close(),s(Error("No page targets found"));return}a=e.targetId,i.send(JSON.stringify({id:l++,method:"Target.attachToTarget",params:{targetId:a,flatten:!0}}));return}if("Target.attachedToTarget"===h.method){let s;switch(h.params.sessionId,e){case"click":{let e,r;if("string"==typeof t.selector){let s=await n(i,l++,"Runtime.evaluate",{expression:`(() => {
66
+ ⚡ **Both tools share the same Chrome instance** - no conflicts or duplicate browsers`}]}}async function C({action:e,params:t={}}){try{if(await S(e))return I(`Browser Action Delegation: Routing '${e}' to chrome-devtools MCP`),await x(e,t);I(`Browser Action Fallback: Using dev3000's execute_browser_action for '${e}'`);let s=d();if(0===s.length)return{content:[{type:"text",text:"❌ No active dev3000 sessions found. Make sure dev3000 is running with a browser!"}]};let i=JSON.parse((0,r.readFileSync)(s[0].sessionFile,"utf-8")),n=i.cdpUrl;if(!n)try{let e=await fetch("http://localhost:9222/json"),t=(await e.json()).find(e=>"page"===e.type&&!e.url.startsWith("chrome://"));t&&(n=t.webSocketDebuggerUrl,I(`CDP Discovery: Found fallback CDP URL ${n}`,s[0].projectName))}catch(e){I(`CDP Discovery: Failed to find fallback CDP URL - ${e}`,s[0].projectName)}if(!n)return{content:[{type:"text",text:`❌ No Chrome DevTools Protocol URL found. Make sure dev3000 is running with browser monitoring enabled (not --servers-only mode). Session CDP URL: ${i.cdpUrl||"null"}`}]};let o=await new Promise((r,s)=>{let i=new l.default(n),o=setTimeout(()=>{i.close(),s(Error(`Browser action '${e}' timed out after 60 seconds. This may indicate an issue with the browser or invalid parameters.`))},6e4);i.on("open",async()=>{try{i.send(JSON.stringify({id:1,method:"Target.getTargets",params:{}}));let a=null,l=2;async function n(e,t,r,s){return new Promise((i,n)=>{let o=r=>{let s=JSON.parse(r.toString());s.id===t&&(e.removeListener("message",o),s.error?n(Error(s.error.message)):i(s.result))};e.on("message",o),e.send(JSON.stringify({id:t,method:r,params:s})),setTimeout(()=>{e.removeListener("message",o),n(Error(`CDP command timeout after 30s: ${r}`))},3e4)})}i.on("message",async c=>{try{let h=JSON.parse(c.toString());if(1===h.id){let e=h.result.targetInfos.find(e=>"page"===e.type);if(!e){i.close(),s(Error("No page targets found"));return}a=e.targetId,i.send(JSON.stringify({id:l++,method:"Target.attachToTarget",params:{targetId:a,flatten:!0}}));return}if("Target.attachedToTarget"===h.method){let s;switch(h.params.sessionId,e){case"click":{let e,r;if("string"==typeof t.selector){let s=await n(i,l++,"Runtime.evaluate",{expression:`(() => {
67
67
  const el = document.querySelector(${JSON.stringify(t.selector)});
68
68
  if (!el) return { found: false };
69
69
  const rect = el.getBoundingClientRect();
@@ -82,9 +82,9 @@ dev3000-chrome-devtools:${r.function}(${JSON.stringify(t,null,2)})
82
82
  elementAtPoint: elementAtPoint?.tagName + (elementAtPoint?.className ? '.' + elementAtPoint.className : ''),
83
83
  isCorrectElement: isCorrectElement
84
84
  };
85
- })()`,returnByValue:!0});if(s.result?.value?.found===!0&&"number"==typeof s.result.value.x&&"number"==typeof s.result.value.y)e=s.result.value.x,r=s.result.value.y,!1===s.result.value.isCorrectElement&&console.warn(`[execute_browser_action] Warning: Center point (${e}, ${r}) is over ${s.result.value.elementAtPoint}, not the target element. This may cause unexpected click behavior. Element size: ${s.result.value.width}x${s.result.value.height}`);else throw Error(`Element not found for selector: ${t.selector}`)}else if("number"==typeof t.x&&"number"==typeof t.y)e=t.x,r=t.y;else throw Error("Click action requires either {x, y} coordinates or a {selector} CSS selector");s=await n(i,l++,"Input.dispatchMouseEvent",{type:"mousePressed",x:e,y:r,button:"left",clickCount:1}),await n(i,l++,"Input.dispatchMouseEvent",{type:"mouseReleased",x:e,y:r,button:"left",clickCount:1});break}case"navigate":if("string"!=typeof t.url)throw Error("Navigate action requires url parameter as string");s=await n(i,l++,"Page.navigate",{url:t.url});break;case"screenshot":i.close(),r({warning:"Screenshot action is not recommended!",advice:"Dev3000 automatically captures screenshots during interactions. Instead of manual screenshots, use click/navigate/scroll/type actions to reproduce user workflows, and dev3000 will capture screenshots at optimal times.",suggestion:"Run fix_my_app to see all auto-captured screenshots from your session."});return;case"evaluate":{if("string"!=typeof t.expression)throw Error("Evaluate action requires expression parameter as string");let e=t.expression;if([/eval\s*\(/,/Function\s*\(/,/setTimeout/,/setInterval/,/\.innerHTML\s*=/,/\.outerHTML\s*=/,/document\.write/,/document\.cookie\s*=/,/localStorage\.setItem/,/sessionStorage\.setItem/,/\.src\s*=/,/\.href\s*=/,/location\s*=/,/\.addEventListener/,/\.removeEventListener/,/new\s+Function/,/import\s*\(/,/fetch\s*\(/,/XMLHttpRequest/].some(t=>t.test(e)))throw Error("Expression contains dangerous patterns. Only safe read-only expressions allowed.");s=await n(i,l++,"Runtime.evaluate",{expression:e,returnByValue:!0});break}case"scroll":{let e="number"==typeof t.deltaX?t.deltaX:0,r="number"==typeof t.deltaY?t.deltaY:0;s=await n(i,l++,"Input.dispatchMouseEvent",{type:"mouseWheel",x:"number"==typeof t.x?t.x:500,y:"number"==typeof t.y?t.y:500,deltaX:e,deltaY:r});break}case"type":if("string"!=typeof t.text)throw Error("Type action requires text parameter as string");for(let e of t.text)await n(i,l++,"Input.dispatchKeyEvent",{type:"char",text:e});s={action:"type",text:t.text};break;default:throw Error(`Unsupported action: ${e}`)}i.close(),clearTimeout(o),r(s)}}catch(e){i.close(),clearTimeout(o),s(e instanceof Error?e:Error(`Browser action failed: ${e instanceof Error?e.message:String(e)}`))}}),i.on("error",e=>{clearTimeout(o),s(e)})}catch(e){i.close(),clearTimeout(o),s(e)}}),i.on("error",e=>{clearTimeout(o),s(e)})}),a=`Browser action '${e}' executed successfully. Result: ${JSON.stringify(o,null,2)}`;return await E("inspect_element")&&(a+="\n\n🔗 **ENHANCED BROWSER ANALYSIS AVAILABLE**\n\ndev3000 completed the basic browser action above. For deeper browser insights, consider also:",(await M(e)).filter(t=>{let r=t.function.toLowerCase(),s=e.toLowerCase();return!!("screenshot"===s&&(r.includes("inspect")||r.includes("performance"))||"evaluate"===s&&(r.includes("console")||r.includes("inspect"))||"navigate"===s&&(r.includes("network")||r.includes("performance"))||"click"===s&&(r.includes("console")||r.includes("inspect")))||"high"===t.priority}).slice(0,2).forEach(e=>{a+=`
86
- • \`dev3000-chrome-devtools:${e.function}()\` - ${e.reason}`}),a+="\n\n💡 **Augmented approach:** Use dev3000 for basic automation, chrome-devtools for detailed analysis and debugging."),{content:[{type:"text",text:a}]}}catch(e){return{content:[{type:"text",text:`Browser action failed: ${e instanceof Error?e.message:String(e)}`}]}}}let C={"nextjs-dev":["nextjs-dev","nextjs-dev-mcp","@modelcontextprotocol/server-nextjs-dev","mcp-server-nextjs-dev","nextjs-mcp"],"chrome-devtools":["chrome-devtools","chrome-devtools-mcp","@modelcontextprotocol/server-chrome-devtools","mcp-server-chrome-devtools","chrome-mcp"]},R={"nextjs-dev":[3001,3002,8080,8081],"chrome-devtools":[9222,9223,9224,3003]};async function N(){let e=[];try{process.platform;let{stdout:t}=await c("ps aux"),r=t.toLowerCase();for(let[t,s]of Object.entries(C))for(let i of s)if(r.includes(i.toLowerCase())){e.includes(t)||(e.push(t),A(`MCP Discovery: Found ${t} MCP via process detection [${i}]`));break}}catch(e){A(`MCP Discovery: Process detection failed - ${e instanceof Error?e.message:String(e)}`)}return e}async function k(){let e=[];for(let[t,r]of Object.entries(R))for(let s of r)try{if((await fetch(`http://localhost:${s}/health`,{method:"GET",signal:AbortSignal.timeout(2e3)})).ok){e.push(t),A(`MCP Discovery: Found ${t} MCP via HTTP ping on port ${s}`);break}}catch{try{let r=new l.default(`ws://localhost:${s}`);await new Promise((i,n)=>{let o=setTimeout(()=>{r.close(),n(Error("timeout"))},1e3);r.on("open",()=>{clearTimeout(o),r.close(),e.push(t),A(`MCP Discovery: Found ${t} MCP via WebSocket ping on port ${s}`),i(null)}),r.on("error",()=>{clearTimeout(o),n(Error("connection failed"))})});break}catch{}}return e}async function I(t){A("MCP Discovery: Starting proactive MCP discovery",t);let r=new Set;for(let e of(await N()))r.add(e);try{let s=`/Users/${process.env.USER}/Library/Caches/claude-cli-nodejs`,{readdirSync:i,existsSync:n}=await e.A(23970);if(n(s)){let e=i(s).find(e=>e.includes(process.cwd().replace(/\//g,"-")));if(e){let o=`${s}/${e}`,a=`${o}/mcp-logs-dev3000-chrome-devtools`;n(a)&&i(a).length>0&&(r.add("dev3000-chrome-devtools"),A("MCP Discovery: Found dev3000-chrome-devtools via Claude cache logs",t));let l=`${o}/mcp-logs-dev3000-nextjs-dev`;n(l)&&i(l).length>0&&(r.add("dev3000-nextjs-dev"),A("MCP Discovery: Found dev3000-nextjs-dev via Claude cache logs",t))}}}catch(e){A("MCP Discovery: Claude cache check failed, falling back to port detection",t)}if(0===r.size)for(let e of(A("MCP Discovery: No MCPs found via process or cache detection, trying port pinging",t),await k()))r.add(e);let s=Array.from(r);return s.length>0?A(`MCP Discovery: Successfully discovered MCPs [${s.join(", ")}]`,t):A("MCP Discovery: No MCPs detected - will run in standalone mode",t),s}async function O({mcpName:e}={}){let t=[];t.push("🔍 **MCP CAPABILITY INSPECTOR**"),t.push("");try{let r=await I();if(0===r.length)return t.push("❌ **NO MCPs DETECTED**"),t.push("No dev3000-chrome-devtools or dev3000-nextjs-dev MCPs found."),t.push(""),t.push("💡 **To enable enhanced capabilities:**"),t.push("• Ensure Chrome DevTools MCP is configured: `dev3000-chrome-devtools`"),t.push("• Ensure Next.js Dev MCP is configured: `dev3000-nextjs-dev`"),t.push("• Check that Claude Code has MCPs properly configured"),{content:[{type:"text",text:t.join("\n")}]};t.push(`✅ **DISCOVERED MCPs:** ${r.join(", ")}`),t.push("");let s=e?r.filter(t=>t.includes(e)):r;if(0===s.length&&e)return t.push(`❌ **MCP NOT FOUND:** ${e}`),t.push(`Available MCPs: ${r.join(", ")}`),{content:[{type:"text",text:t.join("\n")}]};for(let e of s){t.push(`📋 **${e.toUpperCase()} CAPABILITIES:**`),t.push("");let r=await v(e);if(0===r.length){t.push(" ❌ No capabilities discovered"),t.push(" 💡 This might indicate the MCP is not properly configured or accessible"),t.push("");continue}let s=r.filter(e=>"advanced"===e.category),i=r.filter(e=>"basic"===e.category);t.push(` 🚀 **ADVANCED CAPABILITIES** (${s.length} functions):`),s.length>0?s.forEach(e=>{t.push(` • \`${e.function}()\` - ${e.reason}`)}):t.push(" No advanced capabilities discovered"),t.push(""),t.push(` ⚙️ **BASIC CAPABILITIES** (${i.length} functions):`),i.length>0?i.forEach(e=>{t.push(` • \`${e.function}()\` - ${e.reason}`)}):t.push(" No basic capabilities discovered"),t.push("");let n=m.get(e);if(n){let e=Date.now()-n.timestamp,r=Math.floor(e/6e4);t.push(` 📝 **CACHE INFO:** Discovered ${r} minutes ago`),e>24e4&&t.push(" ⚠️ Cache will refresh soon on next use")}t.push("")}let i=s.reduce(async(e,t)=>{let r=await e,s=await v(t);return r+s.length},Promise.resolve(0));return t.push("🎯 **AUGMENTED DELEGATION STATUS:**"),t.push(`• Total discovered capabilities: ${await i}`),t.push(`• MCPs with advanced capabilities: ${s.filter(async e=>(await v(e)).some(e=>"advanced"===e.category)).length}`),t.push("• Dynamic discovery: ✅ Active (updates automatically)"),t.push("• Cache TTL: 5 minutes"),t.push(""),t.push("💡 **These capabilities are automatically suggested in dev3000's enhanced responses!**"),{content:[{type:"text",text:t.join("\n")}]}}catch(e){return t.push(`❌ **ERROR INSPECTING CAPABILITIES:** ${e instanceof Error?e.message:String(e)}`),t.push(""),t.push("💡 **Troubleshooting:**"),t.push("• Check that MCPs are properly configured in Claude Code"),t.push("• Verify dev3000 can access Claude cache directories"),t.push("• Try running `discover_available_mcps()` first"),{content:[{type:"text",text:t.join("\n")}]}}}async function P(e){let t,a,l=process.env.SCREENSHOT_DIR||(0,i.join)((0,s.tmpdir)(),"dev3000-mcp-deps","public","screenshots");if(!(0,r.existsSync)(l))return{detections:[],sessionId:"",totalFrames:0,screenshotDir:l};let c=(0,r.readdirSync)(l).filter(e=>e.includes("-jank-")&&e.endsWith(".png")).sort().reverse();if(0===c.length)return{detections:[],sessionId:"",totalFrames:0,screenshotDir:l};let h=c[0].split("-jank-")[0],u=c.filter(e=>e.startsWith(h)).sort((e,t)=>parseInt(e.match(/-(\d+)ms\.png$/)?.[1]||"0",10)-parseInt(t.match(/-(\d+)ms\.png$/)?.[1]||"0",10));if(u.length<2)return{detections:[],sessionId:h,totalFrames:u.length,screenshotDir:l};let d=(0,i.join)(l,`${h}-metadata.json`);if((0,r.existsSync)(d))try{let e=JSON.parse((0,r.readFileSync)(d,"utf-8"));a=e.captureTrigger,void 0!==e.layoutShifts&&(t={score:e.totalCLS||0,grade:e.clsGrade||"unknown",shifts:e.layoutShifts})}catch{}let f=[],m=new Map;try{let t=p(e);if(t&&(0,r.existsSync)(t)){let e=(0,r.readFileSync)(t,"utf-8").split("\n");for(let t=0;t<e.length;t++){let r=e[t].match(/\[CDP\] CLS #\d+ \(score: [\d.]+, time: (\d+)ms\):/);if(r){let s=parseInt(r[1],10),i=null,n=null;for(let r=t+1;r<Math.min(t+10,e.length);r++){if(!i){let t=e[r].match(/Before:\s+(http:\/\/\S+)/);t&&(i=t[1])}if(!n){let t=e[r].match(/After:\s+(http:\/\/\S+)/);t&&(n=t[1])}if(i&&n){m.set(s,{before:i,after:n});break}}}}}}catch(e){}if(t){if(0===t.shifts.length){let e=u.filter(e=>{let t=e.match(/-(\d+)ms\.png$/);return(t?parseInt(t[1],10):0)<1500}),s=!1;for(let t=1;t<e.length&&t<10;t++){let n=(0,i.join)(l,e[t-1]),a=(0,i.join)(l,e[t]);try{let i=o.PNG.sync.read((0,r.readFileSync)(n)),l=o.PNG.sync.read((0,r.readFileSync)(a));if(i.width!==l.width||i.height!==l.height)continue;let c=function(e,t){let r=e.width,s=e.height,i=Array(s).fill(0);for(let n=0;n<s;n++)for(let s=0;s<r;s++){let o=r*n+s<<2,a=Math.abs(e.data[o]-t.data[o]),l=Math.abs(e.data[o+1]-t.data[o+1]),c=Math.abs(e.data[o+2]-t.data[o+2]);(a>30||l>30||c>30)&&i[n]++}let n=i.map(e=>e/r*100),o=0,a=0;for(let e=0;e<s;e++)n[e]>50?o=Math.max(o,++a):a=0;let l=0;for(let e=5;e<s-5;e++){let t=n.slice(e-5,e).reduce((e,t)=>e+t,0)/5,r=n[e],s=n.slice(e+1,e+5+1).reduce((e,t)=>e+t,0)/5;t<10&&r>60&&s<10&&l++}let c=0;for(let e=0;e<s;e++)n[e]>5&&n[e]<25&&c++;let h=c>.3*s,u=Math.floor(s/8),d=Array(8).fill(0);for(let e=0;e<s;e++){let t=Math.min(Math.floor(e/u),7);d[t]+=i[e]}let p=r*u,f=d.map(e=>e/p*100),m=(f[0]+f[1])/2,g=(f[6]+f[7])/2,y=f.reduce((e,t)=>e+t,0)/f.length,v=f.reduce((e,t)=>e+(t-y)**2,0)/f.length,_=o>20,w=l>=3,S=h||w&&!_&&(v>500||y<10),E=!S&&(_||m>5&&g<2&&m>2*g||v<200&&y>10),b=d.reduce((e,t)=>e+t,0),x=r*s;return{isLayoutShift:E,shiftScore:b/x*.1,isOverlayNoise:S}}(i,l);if(c.isOverlayNoise){A(`Pixel Diff Hydration: Skipping frame ${t} - detected overlay noise (fixed/absolute elements), not true CLS`);continue}if(c.isLayoutShift){s=!0;let r=e[t].match(/-(\d+)ms\.png$/),i=r?parseInt(r[1],10):0;A(`Pixel Diff Hydration: Detected true layout shift at ${i}ms (score: ${c.shiftScore.toFixed(4)})`);let n=process.env.MCP_PORT||"3684";f.push({timestamp:`${i}ms`,timeSinceStart:i,visualDiff:100*c.shiftScore,severity:"high",element:"Hydration-related element",clsScore:c.shiftScore,uxImpact:"🚨 CRITICAL: Fast hydration shift detected - Chrome's observer missed this early shift",beforeFrameUrl:`http://localhost:${n}/api/screenshots/${e[t-1]}`,afterFrameUrl:`http://localhost:${n}/api/screenshots/${e[t]}`})}}catch{}}return s?{detections:f,sessionId:h,totalFrames:u.length,screenshotDir:l,realCLS:{score:.05,grade:"good"}}:{detections:[],sessionId:h,totalFrames:u.length,screenshotDir:l,realCLS:{score:0,grade:t.grade}}}return t.shifts.forEach(e=>{let t=e.sources?.[0]?.node||"unknown",r=e.sources?.[0]?.position;if(!e.sources?.[0]||"unknown"===t||null==r)return void A(`Chrome CLS: Skipping unidentified shift (score: ${e.score.toFixed(4)}) - cannot verify if it's a true CLS or fixed overlay noise`);if("fixed"===r||"absolute"===r)return void A(`Chrome CLS: Filtering out ${t} shift (position: ${r}) - fixed/absolute elements don't cause true layout shifts`);let s=["NAV","HEADER","BUTTON","A"].includes(t.toUpperCase()),i=e.timestamp<1e3,n={NAV:"Navigation header (<nav>)",HEADER:"Page header (<header>)",BUTTON:"Button (<button>)",A:"Link (<a>)"}[t.toUpperCase()]||t,o="low",a="Minor visual adjustment";s&&i?(o="high",a=`🚨 CRITICAL: ${n} shifted during initial load - highly visible and disruptive to user interaction`):s?(o="medium",a=`⚠️ ${n} shifted - affects navigation/interaction`):i&&(o="medium",a="Shift during page load - may cause mis-clicks");let l=Math.round(e.timestamp),c=m.get(l);f.push({timestamp:`${e.timestamp.toFixed(0)}ms`,timeSinceStart:l,visualDiff:100*e.score,severity:o,element:n,clsScore:e.score,uxImpact:a,beforeFrameUrl:c?.before,afterFrameUrl:c?.after})}),{detections:f,sessionId:h,totalFrames:u.length,screenshotDir:l,realCLS:{score:t.score,grade:t.grade}}}for(let e=1;e<u.length;e++){let t=(0,i.join)(l,u[e-1]),s=(0,i.join)(l,u[e]);try{let i=o.PNG.sync.read((0,r.readFileSync)(t)),a=o.PNG.sync.read((0,r.readFileSync)(s));if(i.width!==a.width||i.height!==a.height)continue;let l=new o.PNG({width:i.width,height:i.height}),c=(0,n.default)(i.data,a.data,l.data,i.width,i.height,{threshold:.1}),d=i.width*i.height,p=c/d*100;if(p>1){let t=u[e].match(/-(\d+)ms\.png$/),r=t?parseInt(t[1],10):0;f.push({timestamp:h,timeSinceStart:r,visualDiff:p,severity:p>10?"high":p>5?"medium":"low"})}}catch{}}return{detections:f,sessionId:h,totalFrames:u.length,screenshotDir:l,captureTrigger:a}}function A(e,t){try{let s=process.env.HOME||process.env.USERPROFILE;if(!s)return;let n=(0,i.join)(s,".d3k","logs");(0,r.existsSync)(n)||(0,r.mkdirSync)(n,{recursive:!0});let o=t||function(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let t=(0,i.join)(e,".d3k");if(!(0,r.existsSync)(t))return null;let s=(0,r.readdirSync)(t).filter(e=>e.endsWith(".json"));if(0===s.length)return null;let n=(0,i.join)(t,s[0]);return JSON.parse((0,r.readFileSync)(n,"utf8")).projectName||null}catch{return null}}();if(!o)return;let a=(0,i.join)(n,`dev3000-${o}-d3k.log`),l=new Date().toISOString(),c=`[${l}] [D3K] ${e}
87
- `;(0,r.appendFileSync)(a,c)}catch(e){}}function $(e,t){let r=e.includes("nextjs-dev"),s=e.includes("chrome-devtools");if(e.length>0){A(`MCP Detection: Available MCPs [${e.join(", ")}]`,t);let i=[];r&&i.push("Next.js"),s&&i.push("Chrome DevTools"),i.length>0?A(`MCP Integration: Activated integrations [${i.join(", ")}]`,t):A("MCP Integration: No compatible MCPs detected - running in standalone mode",t)}else A("MCP Detection: No MCPs provided - running in standalone mode",t);return{integrateNextjs:r,integrateChromeDevtools:s}}function D(e,t){let r=Math.ceil(Math.min(2*e,20)*(t?.5:1));return r<=5||r<=60?`${r} minutes`:`${Math.ceil(r/60)} hours`}async function L(e){try{let t=await v("dev3000-nextjs-dev"),r=t.filter(e=>"advanced"===e.category).slice(0,8).map(t=>({function:t.function,reason:t.reason,priority:U(t.function,e)}));return A(`Dynamic Suggestions: Generated ${r.length} Next.js suggestions from ${t.length} discovered capabilities`),r}catch(e){return A(`Dynamic Suggestions: Failed to generate Next.js suggestions - ${e}`),[{function:"analyze_build_process",reason:"Advanced Next.js build system analysis",priority:"high"},{function:"debug_server_rendering",reason:"Server-side rendering debugging",priority:"high"}]}}async function M(e){try{let t=await v("dev3000-chrome-devtools"),r=t.filter(e=>"advanced"===e.category).slice(0,8).map(t=>({function:t.function,reason:t.reason,priority:U(t.function,e)}));return A(`Dynamic Suggestions: Generated ${r.length} Chrome DevTools suggestions from ${t.length} discovered capabilities`),r}catch(e){return A(`Dynamic Suggestions: Failed to generate Chrome DevTools suggestions - ${e}`),[{function:"inspect_element",reason:"Deep DOM inspection with DevTools-level detail",priority:"high"},{function:"access_console",reason:"Direct browser console access and manipulation",priority:"high"}]}}function U(e,t){let r=e.toLowerCase(),s=t?.toLowerCase()||"";for(let{pattern:e,keywords:t}of[{pattern:/hydration/,keywords:["hydration","ssr","render"]},{pattern:/build|compile/,keywords:["build","compile","analyze"]},{pattern:/network|fetch|api/,keywords:["network","request","intercept","performance"]},{pattern:/console|error/,keywords:["console","error","debug"]},{pattern:/click|interaction/,keywords:["dom","element","inspect"]}])if(e.test(s)&&t.some(e=>r.includes(e)))return"high";return["debug","profile","analyze","trace","inspect"].some(e=>r.includes(e))?"medium":"low"}async function F({availableMcps:e,focusArea:t="all",errorContext:r}){let s=[];A(`Workflow Creation: Creating integrated workflow with focus area [${t}]${r?`, error context [${r}]`:""}`);let i=e||[];e&&0!==e.length||(A("Workflow Creation: No MCPs provided, starting proactive discovery"),i=await I());let{integrateNextjs:n,integrateChromeDevtools:o}=$(i);s.push("🎼 **INTELLIGENT DEBUGGING ORCHESTRATOR**"),s.push(`🔍 Available MCPs: ${i.length>0?i.join(", "):"none (will attempt discovery)"}`),s.push(`⚡ Integrations: ${n?"✅ Next.js":"❌ Next.js"} | ${o?"✅ Chrome DevTools":"❌ Chrome DevTools"}`),r&&s.push(`🎯 Error Context: ${r}`),s.push("");let a=n?await L(r):[],l=o?await M(r):[];if(!n&&!o)return s.push("⚠️ **NO INTEGRATIONS DETECTED**"),s.push("Running in standalone mode. For enhanced debugging:"),s.push("• Add 'nextjs-dev' MCP for Next.js-specific analysis"),s.push("• Add 'chrome-devtools' MCP for browser inspection"),s.push(""),s.push("💡 **STANDALONE WORKFLOW:**"),s.push("1. Use fix_my_app(mode='snapshot') to analyze current issues"),s.push("2. Use execute_browser_action to reproduce and verify fixes"),s.push("3. Implement suggested code fixes"),{content:[{type:"text",text:s.join("\n")}]};s.push("🎪 **3-PHASE INTEGRATED WORKFLOW**"),s.push(""),s.push("🕐 **PHASE 1: PARALLEL DATA COLLECTION** (2-3 minutes)"),s.push("Execute these functions in parallel across all available MCPs:"),s.push(""),s.push("📊 **dev3000 (this MCP):**"),s.push(`• fix_my_app(focusArea='${t}', integrateNextjs=${n}, integrateChromeDevtools=${o}, returnRawData=true)`),s.push(" → Get comprehensive error analysis with interaction data"),s.push(""),n&&(s.push("⚛️ **nextjs-dev MCP:**"),a.filter(e=>"high"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";s.push(`• ${e.function}${t}`),s.push(` → ${e.reason}`)}),s.push("")),o&&(s.push("🌐 **chrome-devtools MCP:**"),l.filter(e=>"high"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";s.push(`• ${e.function}${t}`),s.push(` → ${e.reason}`)}),s.push("")),s.push("🕑 **PHASE 2: DEEP TARGETED ANALYSIS** (3-5 minutes)"),s.push("Based on Phase 1 findings, execute these functions sequentially:"),s.push(""),s.push("🔗 **Cross-MCP Correlation:**"),s.push("• Compare dev3000 interaction data with browser console errors"),n&&(s.push("• Correlate dev3000 server errors with Next.js build/runtime logs"),s.push("• Match interaction timestamps with Next.js request handling")),s.push("• Identify root cause by combining all data sources"),s.push(""),s.push("🎯 **Targeted Deep Dive:**"),s.push("• Use fix_my_app(mode='bisect') for regression analysis if needed"),o&&l.filter(e=>"medium"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";s.push(`• ${e.function}${t} - ${e.reason}`)}),s.push(""),s.push("🕒 **PHASE 3: FIX IMPLEMENTATION & VERIFICATION** (5-10 minutes)"),s.push("Orchestrated fix implementation with cross-MCP verification:"),s.push(""),s.push("🔧 **Implementation:**"),s.push("• Apply code fixes identified by dev3000 error analysis"),n&&s.push("• Address Next.js-specific issues (hydration, build, etc.)"),s.push("• Use dev3000's interaction data to create comprehensive test scenarios"),s.push(""),s.push("✅ **Verification Workflow:**"),s.push("• Use execute_browser_action to replay exact user interactions that caused errors"),o&&(s.push("• Use chrome-devtools to monitor console for error resolution"),s.push("• Take before/after screenshots to verify UI fixes")),n&&s.push("• Use nextjs-dev to verify build success and runtime stability"),s.push("• Re-run fix_my_app to confirm error resolution"),s.push(""),s.push("🚀 **INTEGRATION BENEFITS:**"),n&&o?(s.push("🎯 **Triple-Stack Coverage:**"),s.push("• dev3000: AI-powered error correlation + interaction replay"),s.push("• nextjs-dev: Framework-specific server-side analysis"),s.push("• chrome-devtools: Precise browser state inspection"),s.push("• Combined: Complete full-stack debugging with 90%+ issue resolution"),s.push(""),s.push("⚡ **Expected Results:**"),s.push("• 3x faster debugging vs using tools individually"),s.push("• AI-powered error correlation across all layers"),s.push("• Systematic fix verification workflow"),s.push("• Comprehensive interaction-based testing")):n?(s.push("🎯 **Server-Side Enhanced Coverage:**"),s.push("• dev3000: Client error analysis + interaction data"),s.push("• nextjs-dev: Server-side logs and build analysis"),s.push("• Combined: Full-stack Next.js debugging coverage")):o&&(s.push("🎯 **Browser-Enhanced Coverage:**"),s.push("• dev3000: Error detection + interaction replay"),s.push("• chrome-devtools: Detailed browser state inspection"),s.push("• Combined: Complete client-side debugging workflow"));let c=D(5,n||o);return s.push(""),s.push(`⏱️ **ESTIMATED TOTAL TIME:** ${c}`),s.push(`🎼 **dev3000 orchestrates ${i.length} MCPs for maximum debugging power!**`),{content:[{type:"text",text:s.join("\n")}]}}async function j(e){let{beforeImageUrl:t,afterImageUrl:r,context:s}=e,i=[];return i.push("🔍 **VISUAL DIFF ANALYSIS**"),i.push(""),i.push("To analyze the visual differences between these two screenshots:"),i.push(""),i.push("**Step 1: Fetch and analyze the BEFORE image**"),i.push(`Use WebFetch with URL: \`${t}\``),i.push('Prompt: "Describe this screenshot in detail, focusing on layout and visible elements"'),i.push(""),i.push("**Step 2: Fetch and analyze the AFTER image**"),i.push(`Use WebFetch with URL: \`${r}\``),i.push('Prompt: "Describe this screenshot in detail, focusing on layout and visible elements"'),i.push(""),i.push("**Step 3: Compare and describe the differences**"),s?i.push(`Focus on: ${s}`):(i.push("Look for:"),i.push("• Elements that appeared or disappeared"),i.push("• Elements that moved or changed position"),i.push("• Elements that changed size or style"),i.push("• New content that pushed existing content")),i.push(""),i.push("**Step 4: Identify the layout shift cause**"),i.push("Describe what visual change occurred that caused the layout shift."),i.push("Be specific about:"),i.push("• Which element(s) changed"),i.push("• What appeared/moved/resized"),i.push("• Why this caused other elements to shift"),{content:[{type:"text",text:i.join("\n")}]}}async function B(e){let{selector:t}=e;try{let e=d();if(0===e.length)return{content:[{type:"text",text:"❌ **NO ACTIVE SESSIONS**\n\nNo active dev3000 sessions found. Make sure your app is running with dev3000."}]};let s=JSON.parse((0,r.readFileSync)(e[0].sessionFile,"utf-8")).cdpUrl;if(!s)try{let e=await fetch("http://localhost:9222/json"),t=(await e.json()).find(e=>"page"===e.type&&!e.url.startsWith("chrome://"));t&&(s=t.webSocketDebuggerUrl)}catch{return{content:[{type:"text",text:"❌ **NO CDP CONNECTION**\n\nFailed to find Chrome DevTools Protocol URL."}]}}if(!s)return{content:[{type:"text",text:"❌ **NO CDP CONNECTION**\n\nNo Chrome DevTools Protocol URL found."}]};let i=`
85
+ })()`,returnByValue:!0});if(s.result?.value?.found===!0&&"number"==typeof s.result.value.x&&"number"==typeof s.result.value.y)e=s.result.value.x,r=s.result.value.y,!1===s.result.value.isCorrectElement&&console.warn(`[execute_browser_action] Warning: Center point (${e}, ${r}) is over ${s.result.value.elementAtPoint}, not the target element. This may cause unexpected click behavior. Element size: ${s.result.value.width}x${s.result.value.height}`);else throw Error(`Element not found for selector: ${t.selector}`)}else if("number"==typeof t.x&&"number"==typeof t.y)e=t.x,r=t.y;else throw Error("Click action requires either {x, y} coordinates or a {selector} CSS selector");s=await n(i,l++,"Input.dispatchMouseEvent",{type:"mousePressed",x:e,y:r,button:"left",clickCount:1}),await n(i,l++,"Input.dispatchMouseEvent",{type:"mouseReleased",x:e,y:r,button:"left",clickCount:1});break}case"navigate":if("string"!=typeof t.url)throw Error("Navigate action requires url parameter as string");s=await n(i,l++,"Page.navigate",{url:t.url});break;case"screenshot":i.close(),r({warning:"Screenshot action is not recommended!",advice:"Dev3000 automatically captures screenshots during interactions. Instead of manual screenshots, use click/navigate/scroll/type actions to reproduce user workflows, and dev3000 will capture screenshots at optimal times.",suggestion:"Run fix_my_app to see all auto-captured screenshots from your session."});return;case"evaluate":{if("string"!=typeof t.expression)throw Error("Evaluate action requires expression parameter as string");let e=t.expression;if([/eval\s*\(/,/Function\s*\(/,/setTimeout/,/setInterval/,/\.innerHTML\s*=/,/\.outerHTML\s*=/,/document\.write/,/document\.cookie\s*=/,/localStorage\.setItem/,/sessionStorage\.setItem/,/\.src\s*=/,/\.href\s*=/,/location\s*=/,/\.addEventListener/,/\.removeEventListener/,/new\s+Function/,/import\s*\(/,/fetch\s*\(/,/XMLHttpRequest/].some(t=>t.test(e)))throw Error("Expression contains dangerous patterns. Only safe read-only expressions allowed.");s=await n(i,l++,"Runtime.evaluate",{expression:e,returnByValue:!0});break}case"scroll":{let e="number"==typeof t.deltaX?t.deltaX:0,r="number"==typeof t.deltaY?t.deltaY:0;s=await n(i,l++,"Input.dispatchMouseEvent",{type:"mouseWheel",x:"number"==typeof t.x?t.x:500,y:"number"==typeof t.y?t.y:500,deltaX:e,deltaY:r});break}case"type":if("string"!=typeof t.text)throw Error("Type action requires text parameter as string");for(let e of t.text)await n(i,l++,"Input.dispatchKeyEvent",{type:"char",text:e});s={action:"type",text:t.text};break;default:throw Error(`Unsupported action: ${e}`)}i.close(),clearTimeout(o),r(s)}}catch(e){i.close(),clearTimeout(o),s(e instanceof Error?e:Error(`Browser action failed: ${e instanceof Error?e.message:String(e)}`))}}),i.on("error",e=>{clearTimeout(o),s(e)})}catch(e){i.close(),clearTimeout(o),s(e)}}),i.on("error",e=>{clearTimeout(o),s(e)})}),a=`Browser action '${e}' executed successfully. Result: ${JSON.stringify(o,null,2)}`;return await S("inspect_element")&&(a+="\n\n🔗 **ENHANCED BROWSER ANALYSIS AVAILABLE**\n\ndev3000 completed the basic browser action above. For deeper browser insights, consider also:",(await M(e)).filter(t=>{let r=t.function.toLowerCase(),s=e.toLowerCase();return!!("screenshot"===s&&(r.includes("inspect")||r.includes("performance"))||"evaluate"===s&&(r.includes("console")||r.includes("inspect"))||"navigate"===s&&(r.includes("network")||r.includes("performance"))||"click"===s&&(r.includes("console")||r.includes("inspect")))||"high"===t.priority}).slice(0,2).forEach(e=>{a+=`
86
+ • \`dev3000-chrome-devtools:${e.function}()\` - ${e.reason}`}),a+="\n\n💡 **Augmented approach:** Use dev3000 for basic automation, chrome-devtools for detailed analysis and debugging."),{content:[{type:"text",text:a}]}}catch(e){return{content:[{type:"text",text:`Browser action failed: ${e instanceof Error?e.message:String(e)}`}]}}}let T={"nextjs-dev":["nextjs-dev","nextjs-dev-mcp","@modelcontextprotocol/server-nextjs-dev","mcp-server-nextjs-dev","nextjs-mcp"],"chrome-devtools":["chrome-devtools","chrome-devtools-mcp","@modelcontextprotocol/server-chrome-devtools","mcp-server-chrome-devtools","chrome-mcp"]},k={"nextjs-dev":[3001,3002,8080,8081],"chrome-devtools":[9222,9223,9224,3003]};async function N(){let e=[];try{process.platform;let{stdout:t}=await c("ps aux"),r=t.toLowerCase();for(let[t,s]of Object.entries(T))for(let i of s)if(r.includes(i.toLowerCase())){e.includes(t)||(e.push(t),I(`MCP Discovery: Found ${t} MCP via process detection [${i}]`));break}}catch(e){I(`MCP Discovery: Process detection failed - ${e instanceof Error?e.message:String(e)}`)}return e}async function $(){let e=[];for(let[t,r]of Object.entries(k))for(let s of r)try{if((await fetch(`http://localhost:${s}/health`,{method:"GET",signal:AbortSignal.timeout(2e3)})).ok){e.push(t),I(`MCP Discovery: Found ${t} MCP via HTTP ping on port ${s}`);break}}catch{try{let r=new l.default(`ws://localhost:${s}`);await new Promise((i,n)=>{let o=setTimeout(()=>{r.close(),n(Error("timeout"))},1e3);r.on("open",()=>{clearTimeout(o),r.close(),e.push(t),I(`MCP Discovery: Found ${t} MCP via WebSocket ping on port ${s}`),i(null)}),r.on("error",()=>{clearTimeout(o),n(Error("connection failed"))})});break}catch{}}return e}async function R(t){I("MCP Discovery: Starting proactive MCP discovery",t);let r=new Set;for(let e of(await N()))r.add(e);try{let s=`/Users/${process.env.USER}/Library/Caches/claude-cli-nodejs`,{readdirSync:i,existsSync:n}=await e.A(23970);if(n(s)){let e=i(s).find(e=>e.includes(process.cwd().replace(/\//g,"-")));if(e){let o=`${s}/${e}`,a=`${o}/mcp-logs-dev3000-chrome-devtools`;n(a)&&i(a).length>0&&(r.add("dev3000-chrome-devtools"),I("MCP Discovery: Found dev3000-chrome-devtools via Claude cache logs",t));let l=`${o}/mcp-logs-dev3000-nextjs-dev`;n(l)&&i(l).length>0&&(r.add("dev3000-nextjs-dev"),I("MCP Discovery: Found dev3000-nextjs-dev via Claude cache logs",t))}}}catch(e){I("MCP Discovery: Claude cache check failed, falling back to port detection",t)}if(0===r.size)for(let e of(I("MCP Discovery: No MCPs found via process or cache detection, trying port pinging",t),await $()))r.add(e);let s=Array.from(r);return s.length>0?I(`MCP Discovery: Successfully discovered MCPs [${s.join(", ")}]`,t):I("MCP Discovery: No MCPs detected - will run in standalone mode",t),s}async function O({mcpName:e}={}){let t=[];t.push("🔍 **MCP CAPABILITY INSPECTOR**"),t.push("");try{let r=await R();if(0===r.length)return t.push("❌ **NO MCPs DETECTED**"),t.push("No dev3000-chrome-devtools or dev3000-nextjs-dev MCPs found."),t.push(""),t.push("💡 **To enable enhanced capabilities:**"),t.push("• Ensure Chrome DevTools MCP is configured: `dev3000-chrome-devtools`"),t.push("• Ensure Next.js Dev MCP is configured: `dev3000-nextjs-dev`"),t.push("• Check that Claude Code has MCPs properly configured"),{content:[{type:"text",text:t.join("\n")}]};t.push(`✅ **DISCOVERED MCPs:** ${r.join(", ")}`),t.push("");let s=e?r.filter(t=>t.includes(e)):r;if(0===s.length&&e)return t.push(`❌ **MCP NOT FOUND:** ${e}`),t.push(`Available MCPs: ${r.join(", ")}`),{content:[{type:"text",text:t.join("\n")}]};for(let e of s){t.push(`📋 **${e.toUpperCase()} CAPABILITIES:**`),t.push("");let r=await v(e);if(0===r.length){t.push(" ❌ No capabilities discovered"),t.push(" 💡 This might indicate the MCP is not properly configured or accessible"),t.push("");continue}let s=r.filter(e=>"advanced"===e.category),i=r.filter(e=>"basic"===e.category);t.push(` 🚀 **ADVANCED CAPABILITIES** (${s.length} functions):`),s.length>0?s.forEach(e=>{t.push(` • \`${e.function}()\` - ${e.reason}`)}):t.push(" No advanced capabilities discovered"),t.push(""),t.push(` ⚙️ **BASIC CAPABILITIES** (${i.length} functions):`),i.length>0?i.forEach(e=>{t.push(` • \`${e.function}()\` - ${e.reason}`)}):t.push(" No basic capabilities discovered"),t.push("");let n=m.get(e);if(n){let e=Date.now()-n.timestamp,r=Math.floor(e/6e4);t.push(` 📝 **CACHE INFO:** Discovered ${r} minutes ago`),e>24e4&&t.push(" ⚠️ Cache will refresh soon on next use")}t.push("")}let i=s.reduce(async(e,t)=>{let r=await e,s=await v(t);return r+s.length},Promise.resolve(0));return t.push("🎯 **AUGMENTED DELEGATION STATUS:**"),t.push(`• Total discovered capabilities: ${await i}`),t.push(`• MCPs with advanced capabilities: ${s.filter(async e=>(await v(e)).some(e=>"advanced"===e.category)).length}`),t.push("• Dynamic discovery: ✅ Active (updates automatically)"),t.push("• Cache TTL: 5 minutes"),t.push(""),t.push("💡 **These capabilities are automatically suggested in dev3000's enhanced responses!**"),{content:[{type:"text",text:t.join("\n")}]}}catch(e){return t.push(`❌ **ERROR INSPECTING CAPABILITIES:** ${e instanceof Error?e.message:String(e)}`),t.push(""),t.push("💡 **Troubleshooting:**"),t.push("• Check that MCPs are properly configured in Claude Code"),t.push("• Verify dev3000 can access Claude cache directories"),t.push("• Try running `discover_available_mcps()` first"),{content:[{type:"text",text:t.join("\n")}]}}}async function P(e){let t,a,l=process.env.SCREENSHOT_DIR||(0,i.join)((0,s.tmpdir)(),"dev3000-mcp-deps","public","screenshots");if(!(0,r.existsSync)(l))return{detections:[],sessionId:"",totalFrames:0,screenshotDir:l};let c=(0,r.readdirSync)(l).filter(e=>e.includes("-jank-")&&e.endsWith(".png")).sort().reverse();if(0===c.length)return{detections:[],sessionId:"",totalFrames:0,screenshotDir:l};let h=c[0].split("-jank-")[0],u=c.filter(e=>e.startsWith(h)).sort((e,t)=>parseInt(e.match(/-(\d+)ms\.png$/)?.[1]||"0",10)-parseInt(t.match(/-(\d+)ms\.png$/)?.[1]||"0",10));if(u.length<2)return{detections:[],sessionId:h,totalFrames:u.length,screenshotDir:l};let d=(0,i.join)(l,`${h}-metadata.json`);if((0,r.existsSync)(d))try{let e=JSON.parse((0,r.readFileSync)(d,"utf-8"));a=e.captureTrigger,void 0!==e.layoutShifts&&(t={score:e.totalCLS||0,grade:e.clsGrade||"unknown",shifts:e.layoutShifts})}catch{}let f=[],m=new Map;try{let t=p(e);if(t&&(0,r.existsSync)(t)){let e=(0,r.readFileSync)(t,"utf-8").split("\n");for(let t=0;t<e.length;t++){let r=e[t].match(/\[CDP\] CLS #\d+ \(score: [\d.]+, time: (\d+)ms\):/);if(r){let s=parseInt(r[1],10),i=null,n=null;for(let r=t+1;r<Math.min(t+10,e.length);r++){if(!i){let t=e[r].match(/Before:\s+(http:\/\/\S+)/);t&&(i=t[1])}if(!n){let t=e[r].match(/After:\s+(http:\/\/\S+)/);t&&(n=t[1])}if(i&&n){m.set(s,{before:i,after:n});break}}}}}}catch(e){}if(t){if(0===t.shifts.length){let e=u.filter(e=>{let t=e.match(/-(\d+)ms\.png$/);return(t?parseInt(t[1],10):0)<1500}),s=!1;for(let t=1;t<e.length&&t<10;t++){let n=(0,i.join)(l,e[t-1]),a=(0,i.join)(l,e[t]);try{let i=o.PNG.sync.read((0,r.readFileSync)(n)),l=o.PNG.sync.read((0,r.readFileSync)(a));if(i.width!==l.width||i.height!==l.height)continue;let c=function(e,t){let r=e.width,s=e.height,i=Array(s).fill(0);for(let n=0;n<s;n++)for(let s=0;s<r;s++){let o=r*n+s<<2,a=Math.abs(e.data[o]-t.data[o]),l=Math.abs(e.data[o+1]-t.data[o+1]),c=Math.abs(e.data[o+2]-t.data[o+2]);(a>30||l>30||c>30)&&i[n]++}let n=i.map(e=>e/r*100),o=0,a=0;for(let e=0;e<s;e++)n[e]>50?o=Math.max(o,++a):a=0;let l=0;for(let e=5;e<s-5;e++){let t=n.slice(e-5,e).reduce((e,t)=>e+t,0)/5,r=n[e],s=n.slice(e+1,e+5+1).reduce((e,t)=>e+t,0)/5;t<10&&r>60&&s<10&&l++}let c=0;for(let e=0;e<s;e++)n[e]>5&&n[e]<25&&c++;let h=c>.3*s,u=Math.floor(s/8),d=Array(8).fill(0);for(let e=0;e<s;e++){let t=Math.min(Math.floor(e/u),7);d[t]+=i[e]}let p=r*u,f=d.map(e=>e/p*100),m=(f[0]+f[1])/2,g=(f[6]+f[7])/2,y=f.reduce((e,t)=>e+t,0)/f.length,v=f.reduce((e,t)=>e+(t-y)**2,0)/f.length,_=o>20,b=l>=3,w=h||b&&!_&&(v>500||y<10),S=!w&&(_||m>5&&g<2&&m>2*g||v<200&&y>10),E=d.reduce((e,t)=>e+t,0),x=r*s;return{isLayoutShift:S,shiftScore:E/x*.1,isOverlayNoise:w}}(i,l);if(c.isOverlayNoise){I(`Pixel Diff Hydration: Skipping frame ${t} - detected overlay noise (fixed/absolute elements), not true CLS`);continue}if(c.isLayoutShift){s=!0;let r=e[t].match(/-(\d+)ms\.png$/),i=r?parseInt(r[1],10):0;I(`Pixel Diff Hydration: Detected true layout shift at ${i}ms (score: ${c.shiftScore.toFixed(4)})`);let n=process.env.MCP_PORT||"3684";f.push({timestamp:`${i}ms`,timeSinceStart:i,visualDiff:100*c.shiftScore,severity:"high",element:"Hydration-related element",clsScore:c.shiftScore,uxImpact:"🚨 CRITICAL: Fast hydration shift detected - Chrome's observer missed this early shift",beforeFrameUrl:`http://localhost:${n}/api/screenshots/${e[t-1]}`,afterFrameUrl:`http://localhost:${n}/api/screenshots/${e[t]}`})}}catch{}}return s?{detections:f,sessionId:h,totalFrames:u.length,screenshotDir:l,realCLS:{score:.05,grade:"good"}}:{detections:[],sessionId:h,totalFrames:u.length,screenshotDir:l,realCLS:{score:0,grade:t.grade}}}return t.shifts.forEach(e=>{let t=e.sources?.[0]?.node||"unknown",r=e.sources?.[0]?.position;if(!e.sources?.[0]||"unknown"===t||null==r)return void I(`Chrome CLS: Skipping unidentified shift (score: ${e.score.toFixed(4)}) - cannot verify if it's a true CLS or fixed overlay noise`);if("fixed"===r||"absolute"===r)return void I(`Chrome CLS: Filtering out ${t} shift (position: ${r}) - fixed/absolute elements don't cause true layout shifts`);let s=["NAV","HEADER","BUTTON","A"].includes(t.toUpperCase()),i=e.timestamp<1e3,n={NAV:"Navigation header (<nav>)",HEADER:"Page header (<header>)",BUTTON:"Button (<button>)",A:"Link (<a>)"}[t.toUpperCase()]||t,o="low",a="Minor visual adjustment";s&&i?(o="high",a=`🚨 CRITICAL: ${n} shifted during initial load - highly visible and disruptive to user interaction`):s?(o="medium",a=`⚠️ ${n} shifted - affects navigation/interaction`):i&&(o="medium",a="Shift during page load - may cause mis-clicks");let l=Math.round(e.timestamp),c=m.get(l);f.push({timestamp:`${e.timestamp.toFixed(0)}ms`,timeSinceStart:l,visualDiff:100*e.score,severity:o,element:n,clsScore:e.score,uxImpact:a,beforeFrameUrl:c?.before,afterFrameUrl:c?.after})}),{detections:f,sessionId:h,totalFrames:u.length,screenshotDir:l,realCLS:{score:t.score,grade:t.grade}}}for(let e=1;e<u.length;e++){let t=(0,i.join)(l,u[e-1]),s=(0,i.join)(l,u[e]);try{let i=o.PNG.sync.read((0,r.readFileSync)(t)),a=o.PNG.sync.read((0,r.readFileSync)(s));if(i.width!==a.width||i.height!==a.height)continue;let l=new o.PNG({width:i.width,height:i.height}),c=(0,n.default)(i.data,a.data,l.data,i.width,i.height,{threshold:.1}),d=i.width*i.height,p=c/d*100;if(p>1){let t=u[e].match(/-(\d+)ms\.png$/),r=t?parseInt(t[1],10):0;f.push({timestamp:h,timeSinceStart:r,visualDiff:p,severity:p>10?"high":p>5?"medium":"low"})}}catch{}}return{detections:f,sessionId:h,totalFrames:u.length,screenshotDir:l,captureTrigger:a}}function I(e,t){try{let s=process.env.HOME||process.env.USERPROFILE;if(!s)return;let n=(0,i.join)(s,".d3k","logs");(0,r.existsSync)(n)||(0,r.mkdirSync)(n,{recursive:!0});let o=t||function(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let t=(0,i.join)(e,".d3k");if(!(0,r.existsSync)(t))return null;let s=(0,r.readdirSync)(t).filter(e=>e.endsWith(".json"));if(0===s.length)return null;let n=(0,i.join)(t,s[0]);return JSON.parse((0,r.readFileSync)(n,"utf8")).projectName||null}catch{return null}}();if(!o)return;let a=(0,i.join)(n,`dev3000-${o}-d3k.log`),l=new Date().toISOString(),c=`[${l}] [D3K] ${e}
87
+ `;(0,r.appendFileSync)(a,c)}catch(e){}}function A(e,t){let r=e.includes("nextjs-dev"),s=e.includes("chrome-devtools");if(e.length>0){I(`MCP Detection: Available MCPs [${e.join(", ")}]`,t);let i=[];r&&i.push("Next.js"),s&&i.push("Chrome DevTools"),i.length>0?I(`MCP Integration: Activated integrations [${i.join(", ")}]`,t):I("MCP Integration: No compatible MCPs detected - running in standalone mode",t)}else I("MCP Detection: No MCPs provided - running in standalone mode",t);return{integrateNextjs:r,integrateChromeDevtools:s}}function D(e,t){let r=Math.ceil(Math.min(2*e,20)*(t?.5:1));return r<=5||r<=60?`${r} minutes`:`${Math.ceil(r/60)} hours`}async function L(e){try{let t=await v("dev3000-nextjs-dev"),r=t.filter(e=>"advanced"===e.category).slice(0,8).map(t=>({function:t.function,reason:t.reason,priority:U(t.function,e)}));return I(`Dynamic Suggestions: Generated ${r.length} Next.js suggestions from ${t.length} discovered capabilities`),r}catch(e){return I(`Dynamic Suggestions: Failed to generate Next.js suggestions - ${e}`),[{function:"analyze_build_process",reason:"Advanced Next.js build system analysis",priority:"high"},{function:"debug_server_rendering",reason:"Server-side rendering debugging",priority:"high"}]}}async function M(e){try{let t=await v("dev3000-chrome-devtools"),r=t.filter(e=>"advanced"===e.category).slice(0,8).map(t=>({function:t.function,reason:t.reason,priority:U(t.function,e)}));return I(`Dynamic Suggestions: Generated ${r.length} Chrome DevTools suggestions from ${t.length} discovered capabilities`),r}catch(e){return I(`Dynamic Suggestions: Failed to generate Chrome DevTools suggestions - ${e}`),[{function:"inspect_element",reason:"Deep DOM inspection with DevTools-level detail",priority:"high"},{function:"access_console",reason:"Direct browser console access and manipulation",priority:"high"}]}}function U(e,t){let r=e.toLowerCase(),s=t?.toLowerCase()||"";for(let{pattern:e,keywords:t}of[{pattern:/hydration/,keywords:["hydration","ssr","render"]},{pattern:/build|compile/,keywords:["build","compile","analyze"]},{pattern:/network|fetch|api/,keywords:["network","request","intercept","performance"]},{pattern:/console|error/,keywords:["console","error","debug"]},{pattern:/click|interaction/,keywords:["dom","element","inspect"]}])if(e.test(s)&&t.some(e=>r.includes(e)))return"high";return["debug","profile","analyze","trace","inspect"].some(e=>r.includes(e))?"medium":"low"}async function j({availableMcps:e,focusArea:t="all",errorContext:r}){let s=[];I(`Workflow Creation: Creating integrated workflow with focus area [${t}]${r?`, error context [${r}]`:""}`);let i=e||[];e&&0!==e.length||(I("Workflow Creation: No MCPs provided, starting proactive discovery"),i=await R());let{integrateNextjs:n,integrateChromeDevtools:o}=A(i);s.push("🎼 **INTELLIGENT DEBUGGING ORCHESTRATOR**"),s.push(`🔍 Available MCPs: ${i.length>0?i.join(", "):"none (will attempt discovery)"}`),s.push(`⚡ Integrations: ${n?"✅ Next.js":"❌ Next.js"} | ${o?"✅ Chrome DevTools":"❌ Chrome DevTools"}`),r&&s.push(`🎯 Error Context: ${r}`),s.push("");let a=n?await L(r):[],l=o?await M(r):[];if(!n&&!o)return s.push("⚠️ **NO INTEGRATIONS DETECTED**"),s.push("Running in standalone mode. For enhanced debugging:"),s.push("• Add 'nextjs-dev' MCP for Next.js-specific analysis"),s.push("• Add 'chrome-devtools' MCP for browser inspection"),s.push(""),s.push("💡 **STANDALONE WORKFLOW:**"),s.push("1. Use fix_my_app(mode='snapshot') to analyze current issues"),s.push("2. Use execute_browser_action to reproduce and verify fixes"),s.push("3. Implement suggested code fixes"),{content:[{type:"text",text:s.join("\n")}]};s.push("🎪 **3-PHASE INTEGRATED WORKFLOW**"),s.push(""),s.push("🕐 **PHASE 1: PARALLEL DATA COLLECTION** (2-3 minutes)"),s.push("Execute these functions in parallel across all available MCPs:"),s.push(""),s.push("📊 **dev3000 (this MCP):**"),s.push(`• fix_my_app(focusArea='${t}', integrateNextjs=${n}, integrateChromeDevtools=${o}, returnRawData=true)`),s.push(" → Get comprehensive error analysis with interaction data"),s.push(""),n&&(s.push("⚛️ **nextjs-dev MCP:**"),a.filter(e=>"high"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";s.push(`• ${e.function}${t}`),s.push(` → ${e.reason}`)}),s.push("")),o&&(s.push("🌐 **chrome-devtools MCP:**"),l.filter(e=>"high"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";s.push(`• ${e.function}${t}`),s.push(` → ${e.reason}`)}),s.push("")),s.push("🕑 **PHASE 2: DEEP TARGETED ANALYSIS** (3-5 minutes)"),s.push("Based on Phase 1 findings, execute these functions sequentially:"),s.push(""),s.push("🔗 **Cross-MCP Correlation:**"),s.push("• Compare dev3000 interaction data with browser console errors"),n&&(s.push("• Correlate dev3000 server errors with Next.js build/runtime logs"),s.push("• Match interaction timestamps with Next.js request handling")),s.push("• Identify root cause by combining all data sources"),s.push(""),s.push("🎯 **Targeted Deep Dive:**"),s.push("• Use fix_my_app(mode='bisect') for regression analysis if needed"),o&&l.filter(e=>"medium"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";s.push(`• ${e.function}${t} - ${e.reason}`)}),s.push(""),s.push("🕒 **PHASE 3: FIX IMPLEMENTATION & VERIFICATION** (5-10 minutes)"),s.push("Orchestrated fix implementation with cross-MCP verification:"),s.push(""),s.push("🔧 **Implementation:**"),s.push("• Apply code fixes identified by dev3000 error analysis"),n&&s.push("• Address Next.js-specific issues (hydration, build, etc.)"),s.push("• Use dev3000's interaction data to create comprehensive test scenarios"),s.push(""),s.push("✅ **Verification Workflow:**"),s.push("• Use execute_browser_action to replay exact user interactions that caused errors"),o&&(s.push("• Use chrome-devtools to monitor console for error resolution"),s.push("• Take before/after screenshots to verify UI fixes")),n&&s.push("• Use nextjs-dev to verify build success and runtime stability"),s.push("• Re-run fix_my_app to confirm error resolution"),s.push(""),s.push("🚀 **INTEGRATION BENEFITS:**"),n&&o?(s.push("🎯 **Triple-Stack Coverage:**"),s.push("• dev3000: AI-powered error correlation + interaction replay"),s.push("• nextjs-dev: Framework-specific server-side analysis"),s.push("• chrome-devtools: Precise browser state inspection"),s.push("• Combined: Complete full-stack debugging with 90%+ issue resolution"),s.push(""),s.push("⚡ **Expected Results:**"),s.push("• 3x faster debugging vs using tools individually"),s.push("• AI-powered error correlation across all layers"),s.push("• Systematic fix verification workflow"),s.push("• Comprehensive interaction-based testing")):n?(s.push("🎯 **Server-Side Enhanced Coverage:**"),s.push("• dev3000: Client error analysis + interaction data"),s.push("• nextjs-dev: Server-side logs and build analysis"),s.push("• Combined: Full-stack Next.js debugging coverage")):o&&(s.push("🎯 **Browser-Enhanced Coverage:**"),s.push("• dev3000: Error detection + interaction replay"),s.push("• chrome-devtools: Detailed browser state inspection"),s.push("• Combined: Complete client-side debugging workflow"));let c=D(5,n||o);return s.push(""),s.push(`⏱️ **ESTIMATED TOTAL TIME:** ${c}`),s.push(`🎼 **dev3000 orchestrates ${i.length} MCPs for maximum debugging power!**`),{content:[{type:"text",text:s.join("\n")}]}}async function F(e){let{beforeImageUrl:t,afterImageUrl:r,context:s}=e,i=[];return i.push("🔍 **VISUAL DIFF ANALYSIS**"),i.push(""),i.push("To analyze the visual differences between these two screenshots:"),i.push(""),i.push("**Step 1: Fetch and analyze the BEFORE image**"),i.push(`Use WebFetch with URL: \`${t}\``),i.push('Prompt: "Describe this screenshot in detail, focusing on layout and visible elements"'),i.push(""),i.push("**Step 2: Fetch and analyze the AFTER image**"),i.push(`Use WebFetch with URL: \`${r}\``),i.push('Prompt: "Describe this screenshot in detail, focusing on layout and visible elements"'),i.push(""),i.push("**Step 3: Compare and describe the differences**"),s?i.push(`Focus on: ${s}`):(i.push("Look for:"),i.push("• Elements that appeared or disappeared"),i.push("• Elements that moved or changed position"),i.push("• Elements that changed size or style"),i.push("• New content that pushed existing content")),i.push(""),i.push("**Step 4: Identify the layout shift cause**"),i.push("Describe what visual change occurred that caused the layout shift."),i.push("Be specific about:"),i.push("• Which element(s) changed"),i.push("• What appeared/moved/resized"),i.push("• Why this caused other elements to shift"),{content:[{type:"text",text:i.join("\n")}]}}async function B(e){let{selector:t}=e;try{let e=d();if(0===e.length)return{content:[{type:"text",text:"❌ **NO ACTIVE SESSIONS**\n\nNo active dev3000 sessions found. Make sure your app is running with dev3000."}]};let s=JSON.parse((0,r.readFileSync)(e[0].sessionFile,"utf-8")).cdpUrl;if(!s)try{let e=await fetch("http://localhost:9222/json"),t=(await e.json()).find(e=>"page"===e.type&&!e.url.startsWith("chrome://"));t&&(s=t.webSocketDebuggerUrl)}catch{return{content:[{type:"text",text:"❌ **NO CDP CONNECTION**\n\nFailed to find Chrome DevTools Protocol URL."}]}}if(!s)return{content:[{type:"text",text:"❌ **NO CDP CONNECTION**\n\nNo Chrome DevTools Protocol URL found."}]};let i=`
88
88
  (function() {
89
89
  try {
90
90
  const element = document.querySelector(${JSON.stringify(t)});
@@ -141,14 +141,14 @@ ${n.error}
141
141
  • Ensure the element is rendered by a React component
142
142
  • Try a simpler selector like 'nav' or '.header'`}]};if(!n.success)return{content:[{type:"text",text:"❌ **FAILED TO EXTRACT COMPONENT**\n\nUnexpected result format."}]};let{componentName:o,sourceCode:a}=n,c=[],h=/<([A-Z][a-zA-Z0-9]*)/g,u=new Set,p=h.exec(a);for(;null!==p;)u.add(p[1]),p=h.exec(a);let f=/className=["']([^"']+)["']/g,m=new Set,g=f.exec(a);for(;null!==g;)m.add(g[1]),g=f.exec(a);let y=[];if(y.push("🔍 **COMPONENT SOURCE FINDER**"),y.push(""),y.push(`**Selector:** \`${t}\``),y.push(`**Component:** ${o}`),y.push(""),"Anonymous"!==o&&(c.push(`function ${o}`),c.push(`const ${o} =`),c.push(`export default function ${o}`)),u.size>0){let e=Array.from(u).filter(e=>!["Fragment","Suspense","ErrorBoundary"].includes(e));e.length>0&&c.push(`<${e[0]}`)}if(m.size>0){let e=Array.from(m)[0];c.push(`className="${e}"`)}if(0===c.length)y.push("⚠️ **NO UNIQUE PATTERNS FOUND**"),y.push(""),y.push("The component source code doesn't contain distinctive patterns to search for."),y.push("You may need to manually search for the component.");else{for(let e of(y.push("📍 **SEARCH PATTERNS**"),y.push(""),y.push("Use these grep patterns to find the source file:"),y.push(""),c.slice(0,3)))y.push("```"),y.push(`grep -r "${e.replace(/"/g,'\\"')}" .`),y.push("```"),y.push("");y.push("💡 **TIP:** Start with the first pattern. If it returns multiple results, try combining patterns.")}let v=a.substring(0,300);return y.push(""),y.push("**Source Code Preview:**"),y.push("```javascript"),y.push(`${v}...`),y.push("```"),{content:[{type:"text",text:y.join("\n")}]}}catch(e){return{content:[{type:"text",text:`❌ **ERROR**
143
143
 
144
- ${e instanceof Error?e.message:String(e)}`}]}}}async function W(e){let{projectName:s}=e;try{let e=d();if(0===e.length)return{content:[{type:"text",text:"❌ **NO ACTIVE SESSIONS**\n\nNo active dev3000 sessions found. Make sure your app is running with dev3000."}]};let i=e[0];if(s){let t=e.find(e=>e.projectName===s);t&&(i=t)}let n=JSON.parse((0,r.readFileSync)(i.sessionFile,"utf-8")),o=n.appPort,a=n.serverCommand,l=n.cwd;if(!o)return{content:[{type:"text",text:"❌ **NO APP PORT FOUND**\n\nSession file doesn't contain app port information."}]};if(!a)return{content:[{type:"text",text:"❌ **NO SERVER COMMAND FOUND**\n\nSession file doesn't contain the original server command. This session may have been created with an older version of dev3000."}]};A(`Restart Dev Server: Starting restart for project [${i.projectName}] on port ${o} with command [${a}]`);let h=(await I(i.projectName)).includes("nextjs-dev");if(A(`Restart Dev Server: Has nextjs-dev MCP: ${h}`),h)try{A("Restart Dev Server: Attempting to use nextjs-dev MCP restart");let e=await O({mcpName:"nextjs-dev"}),t=e.content[0]&&"text"in e.content[0]?e.content[0].text:"";if(t.includes("restart")||t.includes("reload"))return A("Restart Dev Server: nextjs-dev MCP has restart capability, delegating"),{content:[{type:"text",text:"✅ **DELEGATING TO NEXTJS-DEV MCP**\n\nThe nextjs-dev MCP has restart capabilities. Please use the nextjs-dev MCP restart tool directly for better integration with Next.js."}]};A("Restart Dev Server: nextjs-dev MCP doesn't have restart capability, falling back")}catch(e){A(`Restart Dev Server: Failed to check nextjs-dev capabilities - ${e}`)}A("Restart Dev Server: Using dev3000 restart mechanism");let u=`lsof -ti :${o} | xargs kill 2>/dev/null || true`;A(`Restart Dev Server: Executing kill command: ${u}`);try{await c(u),A("Restart Dev Server: Kill command executed successfully")}catch(e){A(`Restart Dev Server: Kill command failed (may be ok) - ${e}`)}await new Promise(e=>setTimeout(e,2e3));let p=`lsof -ti :${o}`,f=!1;try{let{stdout:e}=await c(p);f=""===e.trim(),A(`Restart Dev Server: Port check result - free: ${f}`)}catch{f=!0,A("Restart Dev Server: Port is free (lsof returned no results)")}if(!f)return{content:[{type:"text",text:`⚠️ **PORT STILL IN USE**
144
+ ${e instanceof Error?e.message:String(e)}`}]}}}async function W(e){let{projectName:s}=e;try{let e=d();if(0===e.length)return{content:[{type:"text",text:"❌ **NO ACTIVE SESSIONS**\n\nNo active dev3000 sessions found. Make sure your app is running with dev3000."}]};let i=e[0];if(s){let t=e.find(e=>e.projectName===s);t&&(i=t)}let n=JSON.parse((0,r.readFileSync)(i.sessionFile,"utf-8")),o=n.appPort,a=n.serverCommand,l=n.cwd;if(!o)return{content:[{type:"text",text:"❌ **NO APP PORT FOUND**\n\nSession file doesn't contain app port information."}]};if(!a)return{content:[{type:"text",text:"❌ **NO SERVER COMMAND FOUND**\n\nSession file doesn't contain the original server command. This session may have been created with an older version of dev3000."}]};I(`Restart Dev Server: Starting restart for project [${i.projectName}] on port ${o} with command [${a}]`);let h=(await R(i.projectName)).includes("nextjs-dev");if(I(`Restart Dev Server: Has nextjs-dev MCP: ${h}`),h)try{I("Restart Dev Server: Attempting to use nextjs-dev MCP restart");let e=await O({mcpName:"nextjs-dev"}),t=e.content[0]&&"text"in e.content[0]?e.content[0].text:"";if(t.includes("restart")||t.includes("reload"))return I("Restart Dev Server: nextjs-dev MCP has restart capability, delegating"),{content:[{type:"text",text:"✅ **DELEGATING TO NEXTJS-DEV MCP**\n\nThe nextjs-dev MCP has restart capabilities. Please use the nextjs-dev MCP restart tool directly for better integration with Next.js."}]};I("Restart Dev Server: nextjs-dev MCP doesn't have restart capability, falling back")}catch(e){I(`Restart Dev Server: Failed to check nextjs-dev capabilities - ${e}`)}I("Restart Dev Server: Using dev3000 restart mechanism");let u=`lsof -ti :${o} | xargs kill 2>/dev/null || true`;I(`Restart Dev Server: Executing kill command: ${u}`);try{await c(u),I("Restart Dev Server: Kill command executed successfully")}catch(e){I(`Restart Dev Server: Kill command failed (may be ok) - ${e}`)}await new Promise(e=>setTimeout(e,2e3));let p=`lsof -ti :${o}`,f=!1;try{let{stdout:e}=await c(p);f=""===e.trim(),I(`Restart Dev Server: Port check result - free: ${f}`)}catch{f=!0,I("Restart Dev Server: Port is free (lsof returned no results)")}if(!f)return{content:[{type:"text",text:`⚠️ **PORT STILL IN USE**
145
145
 
146
146
  Failed to free port ${o}. There may be a process that couldn't be killed.
147
147
 
148
148
  Try manually killing the process:
149
149
  \`\`\`bash
150
150
  lsof -ti :${o} | xargs kill -9
151
- \`\`\``}]};A("Restart Dev Server: Port is now free, spawning new server process");try{let e=(0,t.spawn)(a,{stdio:"inherit",shell:!0,detached:!0,cwd:l||process.cwd()});e.unref(),A(`Restart Dev Server: Spawned new server process with PID ${e.pid}`),await new Promise(e=>setTimeout(e,1e3));try{let{stdout:t}=await c(`lsof -ti :${o}`);if(""!==t.trim())return A("Restart Dev Server: Server successfully restarted and running on port"),{content:[{type:"text",text:`✅ **DEV SERVER RESTARTED**
151
+ \`\`\``}]};I("Restart Dev Server: Port is now free, spawning new server process");try{let e=(0,t.spawn)(a,{stdio:"inherit",shell:!0,detached:!0,cwd:l||process.cwd()});e.unref(),I(`Restart Dev Server: Spawned new server process with PID ${e.pid}`),await new Promise(e=>setTimeout(e,1e3));try{let{stdout:t}=await c(`lsof -ti :${o}`);if(""!==t.trim())return I("Restart Dev Server: Server successfully restarted and running on port"),{content:[{type:"text",text:`✅ **DEV SERVER RESTARTED**
152
152
 
153
153
  Successfully restarted the development server on port ${o}.
154
154
 
@@ -159,7 +159,7 @@ Successfully restarted the development server on port ${o}.
159
159
  • Browser monitoring: Unchanged
160
160
  • Logs: Still being captured
161
161
 
162
- 💡 The server has been restarted while keeping dev3000's monitoring, screenshots, and logging intact.`}]};A("Restart Dev Server: Server process spawned but not yet listening on port (may still be starting)")}catch{A("Restart Dev Server: Server process spawned but not yet listening on port (may still be starting)")}return{content:[{type:"text",text:`🔄 **DEV SERVER RESTARTING**
162
+ 💡 The server has been restarted while keeping dev3000's monitoring, screenshots, and logging intact.`}]};I("Restart Dev Server: Server process spawned but not yet listening on port (may still be starting)")}catch{I("Restart Dev Server: Server process spawned but not yet listening on port (may still be starting)")}return{content:[{type:"text",text:`🔄 **DEV SERVER RESTARTING**
163
163
 
164
164
  Started a new server process (PID ${e.pid}).
165
165
 
@@ -169,7 +169,7 @@ Started a new server process (PID ${e.pid}).
169
169
  • Command: \`${a}\`
170
170
  • Port: ${o}
171
171
 
172
- The server is restarting. Check the dev3000 logs to see when it's ready.`}]}}catch(e){return A(`Restart Dev Server: Failed to spawn new server process - ${e}`),{content:[{type:"text",text:`❌ **RESTART FAILED**
172
+ The server is restarting. Check the dev3000 logs to see when it's ready.`}]}}catch(e){return I(`Restart Dev Server: Failed to spawn new server process - ${e}`),{content:[{type:"text",text:`❌ **RESTART FAILED**
173
173
 
174
174
  Failed to start new server process.
175
175
 
@@ -177,9 +177,9 @@ Failed to start new server process.
177
177
 
178
178
  **Command:** \`${a}\`
179
179
 
180
- The old server was killed but the new one failed to start. You may need to manually restart dev3000.`}]}}}catch(e){return A(`Restart Dev Server: Error - ${e}`),{content:[{type:"text",text:`❌ **ERROR**
180
+ The old server was killed but the new one failed to start. You may need to manually restart dev3000.`}]}}}catch(e){return I(`Restart Dev Server: Error - ${e}`),{content:[{type:"text",text:`❌ **ERROR**
181
181
 
182
- ${e instanceof Error?e.message:String(e)}`}]}}}async function G(e){let{depth:t=1,limit:s=3,projectName:i}=e;try{let e=d(),n=i?e.find(e=>e.projectName===i):e[0];if(!n)return{content:[{type:"text",text:i?`❌ No active session found for project "${i}". Available projects: ${e.map(e=>e.projectName).join(", ")||"none"}`:"❌ No active dev3000 sessions found. Start dev3000 first with `d3k` in your project directory."}]};let o=JSON.parse((0,r.readFileSync)(n.sessionFile,"utf-8")),a=o.cdpUrl?.replace("http://","ws://"),c=o.appPort||"3000",h=`http://localhost:${c}`;if(!a)return{content:[{type:"text",text:"❌ No Chrome DevTools connection found. Browser monitoring must be active to crawl."}]};A(`Crawl App: Starting crawl at depth ${t} with limit ${s} for ${h}`);let u=new l.default(a);await new Promise((e,t)=>{u.on("open",e),u.on("error",t),setTimeout(()=>t(Error("CDP connection timeout")),5e3)});let p=2e3,f=(e,t={})=>new Promise((r,s)=>{let i=p++,n=JSON.stringify({id:i,method:e,params:t}),o=e=>{let t=JSON.parse(e.toString());t.id===i&&(u.off("message",o),t.error?s(Error(t.error.message)):r(t.result))};u.on("message",o),u.send(n),setTimeout(()=>{u.off("message",o),s(Error("Command timeout"))},1e4)});await f("Runtime.enable"),await f("Page.enable");let m=new Set([h]),g=new Set,y=[h],v=0,_="all"===t?1/0:t;for(;y.length>0&&v<=_;){let e=[...y];for(let t of(y.length=0,A(`Crawl App: Processing depth ${v} with ${e.length} URLs`),e))if(!g.has(t)){g.add(t);try{A(`Crawl App: Visiting ${t}`),await f("Page.navigate",{url:t}),await new Promise(e=>setTimeout(e,2e3));let e=await f("Runtime.evaluate",{expression:`
182
+ ${e instanceof Error?e.message:String(e)}`}]}}}async function G(e){let{depth:t=1,limit:s=3,projectName:i}=e;try{let e=d(),n=i?e.find(e=>e.projectName===i):e[0];if(!n)return{content:[{type:"text",text:i?`❌ No active session found for project "${i}". Available projects: ${e.map(e=>e.projectName).join(", ")||"none"}`:"❌ No active dev3000 sessions found. Start dev3000 first with `d3k` in your project directory."}]};let o=JSON.parse((0,r.readFileSync)(n.sessionFile,"utf-8")),a=o.cdpUrl?.replace("http://","ws://"),c=o.appPort||"3000",h=`http://localhost:${c}`;if(!a)return{content:[{type:"text",text:"❌ No Chrome DevTools connection found. Browser monitoring must be active to crawl."}]};I(`Crawl App: Starting crawl at depth ${t} with limit ${s} for ${h}`);let u=new l.default(a);await new Promise((e,t)=>{u.on("open",e),u.on("error",t),setTimeout(()=>t(Error("CDP connection timeout")),5e3)});let p=2e3,f=(e,t={})=>new Promise((r,s)=>{let i=p++,n=JSON.stringify({id:i,method:e,params:t}),o=e=>{let t=JSON.parse(e.toString());t.id===i&&(u.off("message",o),t.error?s(Error(t.error.message)):r(t.result))};u.on("message",o),u.send(n),setTimeout(()=>{u.off("message",o),s(Error("Command timeout"))},1e4)});await f("Runtime.enable"),await f("Page.enable");let m=new Set([h]),g=new Set,y=[h],v=0,_="all"===t?1/0:t;for(;y.length>0&&v<=_;){let e=[...y];for(let t of(y.length=0,I(`Crawl App: Processing depth ${v} with ${e.length} URLs`),e))if(!g.has(t)){g.add(t);try{I(`Crawl App: Visiting ${t}`),await f("Page.navigate",{url:t}),await new Promise(e=>setTimeout(e,2e3));let e=await f("Runtime.evaluate",{expression:`
183
183
  Array.from(document.querySelectorAll('a[href]')).map(a => {
184
184
  try {
185
185
  const url = new URL(a.href, window.location.href);
@@ -191,21 +191,21 @@ ${e instanceof Error?e.message:String(e)}`}]}}}async function G(e){let{depth:t=1
191
191
  } catch {}
192
192
  return null;
193
193
  }).filter(Boolean)
194
- `,returnByValue:!0}),r=e.result?.value||[],i=0;for(let e of r)!m.has(e)&&(m.add(e),v<_&&i<s&&(y.push(e),i++));A(`Crawl App: Found ${r.length} links on ${t}, added ${i} to queue (limit: ${s})`)}catch(e){A(`Crawl App: Error visiting ${t} - ${e}`)}}if(v++,"all"===t&&0===y.length)break}u.close();let w=Array.from(m).sort(),S="all"===t?v-1:Math.min(v-1,_);return A(`Crawl App: Complete - discovered ${w.length} URLs at depth ${S}`),{content:[{type:"text",text:`🕷️ **APP CRAWL COMPLETE**
194
+ `,returnByValue:!0}),r=e.result?.value||[],i=0;for(let e of r)!m.has(e)&&(m.add(e),v<_&&i<s&&(y.push(e),i++));I(`Crawl App: Found ${r.length} links on ${t}, added ${i} to queue (limit: ${s})`)}catch(e){I(`Crawl App: Error visiting ${t} - ${e}`)}}if(v++,"all"===t&&0===y.length)break}u.close();let b=Array.from(m).sort(),w="all"===t?v-1:Math.min(v-1,_);return I(`Crawl App: Complete - discovered ${b.length} URLs at depth ${w}`),{content:[{type:"text",text:`🕷️ **APP CRAWL COMPLETE**
195
195
 
196
196
  📊 **SUMMARY:**
197
197
  • Base URL: ${h}
198
- • Depth: ${S}${"all"===t?" (exhaustive)":""}
199
- • Total URLs: ${w.length}
198
+ • Depth: ${w}${"all"===t?" (exhaustive)":""}
199
+ • Total URLs: ${b.length}
200
200
 
201
201
  📍 **DISCOVERED URLs:**
202
- ${w.map(e=>`• ${e}`).join("\n")}
202
+ ${b.map(e=>`• ${e}`).join("\n")}
203
203
 
204
204
  💡 **NEXT STEPS:**
205
205
  • Use fix_my_app to check for errors across all pages
206
206
  • Use execute_browser_action to test specific pages
207
- • Verify all routes are working correctly`}]}}catch(e){return A(`Crawl App: Error - ${e}`),{content:[{type:"text",text:`❌ **CRAWL FAILED**
207
+ • Verify all routes are working correctly`}]}}catch(e){return I(`Crawl App: Error - ${e}`),{content:[{type:"text",text:`❌ **CRAWL FAILED**
208
208
 
209
- ${e instanceof Error?e.message:String(e)}`}]}}}e.s(["TOOL_DESCRIPTIONS",0,{fix_my_app:"🔧 **THE ULTIMATE FIND→FIX→VERIFY MACHINE!** This tool doesn't just find bugs - it FIXES them! Pure dev3000 magic that identifies issues, prioritizes them, and creates focused PRs for the worst issue! 🪄\n\n🔥 **INSTANT FIXING SUPERPOWERS:**\n• Detects ALL error types: server crashes, browser errors, build failures, API issues, performance problems, React/Next.js warnings (hydration errors, Suspense warnings, SSR issues, cache warnings), TypeScript errors, runtime errors\n• **AUTO-DETECTS NEXT.JS** and integrates with nextjs-devtools-mcp for framework-specific analysis\n **PRIORITIZES errors** using smart scoring (build > server > browser > network > warnings)\n **Identifies the SINGLE WORST issue** that needs fixing right now\n• **Creates ONE focused PR** per run - no overwhelming multi-issue PRs!\n Shows EXACT user interactions that triggered each error (clicks, navigation, etc.)\n Provides EXACT fix code with file locations and line numbers\n Verifies fixes by replaying the same interactions that caused the error!\n\n🎯 **SMART PRIORITIZATION:**\n• Build errors: 1000+ priority (blocks development)\n• Server errors: 500+ priority (affects functionality)\n• Browser errors: 300+ priority (user-facing issues)\n• Network errors: 200+ priority (intermittent issues)\n• Warnings: 100+ priority (nice to fix)\n• +Modifiers: Multiple occurrences, recency, reproducibility\n\n🚀 **ONE-PR-PER-RUN WORKFLOW:**\n1️⃣ I FIND all issues and their interactions\n2️⃣ I PRIORITIZE using smart scoring algorithm\n3️⃣ I IDENTIFY the single worst issue\n4️⃣ Set createPR=true to CREATE A FOCUSED PR for just that issue\n5️⃣ Fix that ONE issue, then run again for the next worst issue\n\n📍 **INTERACTION-BASED VERIFICATION:**\nEvery error includes the user interactions that led to it\n• Use execute_browser_action to replay these exact interactions\n• Verify your fix works by confirming the error doesn't reoccur\n• Example: Error shows '[INTERACTION] Click at (450,300)' → After fix, use execute_browser_action(action='click', params={x:450, y:300}) to verify\n\n⚡ **3 ACTION MODES:**\n• FIX NOW: 'What's broken RIGHT NOW?' → Find worst issue and optionally create PR\n• FIX REGRESSION: 'What broke during testing?' → Compare before/after and fix worst issue\n• FIX CONTINUOUSLY: 'Fix issues as they appear' → Monitor and fix proactively\n\n⚛️ **NEXT.JS/REACT SUPPORT:**\nAutomatically detects and fixes Next.js-specific issues like:\n\"Accessing uncached data outside <Suspense>\" warnings\n• Hydration mismatches between server and client\n• SSR/RSC rendering errors\n• Middleware and routing issues\n• Dynamic import and code-splitting problems\n\n💡 **PERFECT FOR:** 'fix my app', 'debug my app', 'fix the Suspense warning', 'fix hydration error', 'fix the Next.js warning', 'create pr for worst issue'. This tool identifies problems, ranks them by severity, and creates focused single-issue PRs - not giant multi-fix PRs!\n\n🏷️ **ATTRIBUTION REQUIREMENT:** When creating commits or PRs based on dev3000 logs/analysis, ALWAYS include attribution to both Claude Code AND dev3000:\n```\n🤖 Generated with [Claude Code](https://claude.com/claude-code) using [d3k](https://d3k.dev)\n\nCo-Authored-By: Claude <noreply@anthropic.com>\n```",execute_browser_action:"🌐 **INTELLIGENT BROWSER AUTOMATION** - Smart browser action routing that automatically delegates to chrome-devtools MCP when available for superior automation capabilities.\n\n🎯 **INTELLIGENT DELEGATION:**\n• Screenshots chrome-devtools MCP (better quality, no conflicts)\n• Navigation chrome-devtools MCP (more reliable page handling)\n• Clicks chrome-devtools MCP (precise coordinate-based interaction)\n• JavaScript evaluation chrome-devtools MCP (enhanced debugging)\n• Scrolling & typing → dev3000 fallback (specialized actions)\n\n**PROGRESSIVE ENHANCEMENT:**\n• Uses chrome-devtools MCP when available for best results\n• Falls back to dev3000's native implementation when chrome-devtools unavailable\n• Shares the same Chrome instance via CDP URL coordination\n• Eliminates browser conflicts between tools\n\n💡 **PERFECT FOR:** Browser automation that automatically chooses the best tool for each action, ensuring optimal results whether chrome-devtools MCP is available or not.",analyze_visual_diff:"🔍 **VISUAL DIFF ANALYZER** - Analyzes two screenshots to identify and describe visual differences. Returns detailed instructions for Claude to load and compare the images, focusing on what changed that could cause layout shifts.\n\n🎯 **WHAT IT PROVIDES:**\n• Direct instructions to load both images via Read tool\n• Context about what to look for\n• Guidance on identifying layout shift causes\n• Structured format for easy analysis\n\n💡 **PERFECT FOR:** Understanding what visual changes occurred between before/after frames in CLS detection, identifying elements that appeared/moved/resized.",find_component_source:"🔍 **COMPONENT SOURCE FINDER** - Maps DOM elements to their source code by extracting the React component function and finding unique patterns to search for.\n\n🎯 **HOW IT WORKS:**\n• Inspects the element via Chrome DevTools Protocol\n• Extracts the React component function source using .toString()\n• Identifies unique code patterns (specific JSX, classNames, imports)\n• Returns targeted grep patterns to find the exact source file\n\n💡 **PERFECT FOR:** Finding which file contains the code for a specific element, especially useful for CLS debugging when you need to fix layout shifts in specific components.",restart_dev_server:"🔄 **DEV SERVER RESTART** - Safely restarts the development server while preserving dev3000's monitoring, logs, and browser connection.\n\n🎯 **SMART RESTART LOGIC:**\n• First tries nextjs-dev MCP restart (if available and user has Next.js canary)\n• Falls back to dev3000's own restart mechanism:\n - Kills the old server process on the app port\n - Waits for clean shutdown\n - Spawns a new server with the same command that was originally used\n - Keeps dev3000's MCP server, browser monitoring, and screenshot capture running\n• All logging continues seamlessly - no data loss\n Browser monitoring stays connected - no need to relaunch Chrome\n\n⚡ **WHEN TO USE:**\n• After modifying next.config.js, middleware, or environment variables\n• When you need a clean restart to clear server state\n• After significant code changes that Next.js HMR can't handle\n• When debugging persistent state or memory issues\n\n⚠️ **CRITICAL - DO NOT:**\n• NEVER manually run kill commands on the dev server like `pkill -f \"next dev\"` or `lsof -ti :3000 | xargs kill`\n• NEVER manually start the dev server with `npm run dev`, `pnpm dev`, `next dev`, etc.\n• ✅ ALWAYS use this tool for dev server restarts - it preserves all dev3000 infrastructure\n\n⚠️ **IMPORTANT:**\nAVOID using this unnecessarily - Next.js HMR handles most changes automatically\n• Only restart when truly needed for config changes or state issues\n• The server will be offline for a few seconds during restart\n• Browser may show connection error briefly while server restarts\n\n💡 **PERFECT FOR:** 'restart the dev server', 'clean restart', 'reload the server' - but only when actually needed, not for regular code changes.",crawl_app:"🕷️ **APP CRAWLER** - Discovers all URLs in your app by crawling links starting from the homepage. Perfect for finding every page before running fixes or tests across your entire site.\n\n🎯 **SMART CRAWLING:**\n• Starts at your app's homepage (localhost)\n• Discovers all unique URLs at specified depth\n• Depth 1 = homepage links only\n• Depth 2 = homepage + links from those pages\n• Depth 'all' = exhaustive crawl until no new links found\n• Limit controls max links followed per page (default 3)\n• Only follows same-origin links (stays within your app)\n• Deduplicates URLs automatically\n\n⚙️ **PARAMETERS:**\n• depth: How many levels to crawl (1, 2, 3... or 'all')\n• limit: Max links to follow per page (default 3, prevents following 100+ links from homepage)\n• Higher limit = more thorough but slower crawl\n\n📊 **OUTPUT:**\n• List of all discovered URLs\n• Total count of unique pages\n• Depth reached\n• Ready to use with fix_my_app or other tools\n\n💡 **PERFECT FOR:**\n• 'crawl my app' or 'crawl my shit' - discover all pages\n• 'crawl my app and fix my shit' - find all pages then run fixes\n• Site-wide testing and debugging\n• Verifying all routes work before deployment\n\n⚡ **USAGE:**\n• Default: depth 1, limit 3 (just first 3 homepage links)\n• Specify depth: 'crawl at depth 2' or depth=2\n• Specify limit: 'crawl with limit 10' or limit=10\n• Full crawl: 'crawl all pages' or depth='all'"},"analyzeVisualDiff",()=>j,"calculateEstimatedTime",()=>D,"crawlApp",()=>G,"createIntegratedWorkflow",()=>F,"detectMcpIntegrations",()=>$,"discoverAvailableMcps",()=>I,"executeBrowserAction",()=>T,"findActiveSessions",()=>d,"findComponentSource",()=>B,"fixMyApp",()=>f,"generateChromeDevtoolsSuggestions",()=>M,"generateNextjsSuggestions",()=>L,"getLogPath",()=>p,"getMcpCapabilities",()=>O,"restartDevServer",()=>W],56891)}];
209
+ ${e instanceof Error?e.message:String(e)}`}]}}}e.s(["TOOL_DESCRIPTIONS",0,{fix_my_app:"Diagnoses application errors from dev3000 logs. Returns a prioritized list of issues requiring fixes.\n\n**CRITICAL: You MUST use this tool in a loop until all errors are resolved:**\n\n```\nwhile (errors exist) {\n 1. DIAGNOSE: Call fix_my_app to get current errors\n 2. FIX: Implement a fix for the highest-priority error\n 3. VERIFY: Call fix_my_app again to confirm the error is gone\n 4. REPEAT: Continue until no errors remain\n}\n```\n\n**This tool does NOT fix anything automatically.** It returns diagnostic data. You must:\n- Read the error output\n- Investigate and fix each issue\n- Call this tool again to verify your fix worked\n- Keep looping until the app is healthy\n\n**What it analyzes:**\n• Server logs, browser console, network requests\n• Categorizes: build errors, server crashes, browser errors, network issues, warnings\n• Prioritizes by severity (fix build errors first, then server, then browser, etc.)\n• Shows user interactions that triggered each error\n\n**Parameters:**\n• focusArea: 'build', 'runtime', 'network', 'ui', 'performance', or 'all' (default)\n• mode: 'snapshot' (current state), 'bisect' (before/after comparison), 'monitor' (continuous)\n• timeRangeMinutes: How far back to analyze (default: 10)\n• createPR: If true, creates a PR branch for the highest-priority issue\n\n**Framework support:** Auto-detects Next.js for framework-specific analysis.\n\n**Attribution for commits/PRs:**\n```\nGenerated with Claude Code using d3k (https://d3k.dev)\nCo-Authored-By: Claude <noreply@anthropic.com>\n```",execute_browser_action:"Executes browser actions (click, navigate, scroll, type, evaluate JS) in the dev3000-managed Chrome instance.\n\n**Routing behavior:**\n• Delegates to chrome-devtools MCP when available for screenshots, navigation, clicks, and JS evaluation\n• Falls back to dev3000's native CDP implementation otherwise\n• Shares the same Chrome instance - no conflicts between tools\n\n**Available actions:**\n• screenshot: Capture current page state\n• navigate: Go to a URL\n• click: Click at coordinates {x, y}\n• scroll: Scroll by {x, y} pixels\n• type: Type text into focused element\n• evaluate: Execute JavaScript (read-only operations recommended)\n\n**Use cases:**\n• Reproducing user interactions that triggered errors\n• Verifying fixes by replaying the error scenario\n• Testing specific UI workflows",analyze_visual_diff:"Compares two screenshots and returns analysis instructions for identifying visual differences.\n\n**What it provides:**\n• Instructions to load both images for comparison\n• Context about what visual changes to look for\n• Guidance on identifying layout shift causes\n\n**Use cases:**\n• Analyzing before/after frames from CLS detection\n• Identifying elements that appeared, moved, or resized\n• Debugging visual regressions",find_component_source:"Maps a DOM element to its React component source code location.\n\n**How it works:**\n1. Inspects the element via Chrome DevTools Protocol\n2. Extracts the React component function source\n3. Identifies unique code patterns (JSX, classNames, etc.)\n4. Returns grep patterns to locate the source file\n\n**Use cases:**\n• Finding which file contains a specific UI element\n• Locating components responsible for layout shifts\n• Tracing DOM elements back to source code",restart_dev_server:"Restarts the development server while preserving dev3000's monitoring infrastructure.\n\n**Restart process:**\n1. Tries nextjs-dev MCP restart if available\n2. Falls back to killing and respawning the server process\n3. Preserves: MCP server, browser connection, log capture, screenshots\n\n**When to use:**\n• After modifying config files (next.config.js, middleware, .env)\n• To clear persistent server state\n• For changes that HMR cannot handle\n\n**Important:**\n• Do NOT manually kill the dev server with pkill/kill commands\n• Do NOT manually start the server with npm/pnpm/yarn\n• Server will be offline briefly during restart\n• Most code changes are handled by HMR - only restart when necessary",crawl_app:"Discovers URLs in the application by crawling links from the homepage.\n\n**Parameters:**\n• depth: How many link levels to follow (1, 2, 3, or 'all')\n• limit: Max links per page (default: 3)\n\n**Behavior:**\n• Starts at localhost homepage\n• Follows same-origin links only\n• Deduplicates discovered URLs\n• Returns list of all found pages\n\n**Use cases:**\n• Discovering all routes before running diagnostics\n• Site-wide testing coverage\n• Verifying all pages load without errors"},"analyzeVisualDiff",()=>F,"calculateEstimatedTime",()=>D,"crawlApp",()=>G,"createIntegratedWorkflow",()=>j,"detectMcpIntegrations",()=>A,"discoverAvailableMcps",()=>R,"executeBrowserAction",()=>C,"findActiveSessions",()=>d,"findComponentSource",()=>B,"fixMyApp",()=>f,"generateChromeDevtoolsSuggestions",()=>M,"generateNextjsSuggestions",()=>L,"getLogPath",()=>p,"getMcpCapabilities",()=>O,"restartDevServer",()=>W],56891)}];
210
210
 
211
211
  //# sourceMappingURL=%5Broot-of-the-server%5D__8a84f9f4._.js.map