@0x1f320.sh/why-did-you-render-mcp 1.1.0-dev.3 → 1.1.0-dev.4
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.
- package/dist/server/index.js +10 -10
- package/package.json +1 -1
package/dist/server/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{McpServer as e}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as t}from"@modelcontextprotocol/sdk/server/stdio.js";import{io as n}from"socket.io-client";import{z as r}from"zod";import{existsSync as i,mkdirSync as a,readFileSync as o,readdirSync as s,unlinkSync as c,writeFileSync as l}from"node:fs";import{homedir as u}from"node:os";import{join as d}from"node:path";import ee from"xxhash-wasm";import f from"node:http";import{Server as te}from"socket.io";let p=null,m=4649;function h(e){m=e}function g(){return p||=n(`http://127.0.0.1:${m}`,{transports:[`websocket`],reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:3}),p}function
|
|
3
|
-
`).filter(Boolean);if(t.length===0)return[];let n,r=0,a=JSON.parse(t[0]);`@@dict`in a&&(n=a[
|
|
2
|
+
import{McpServer as e}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as t}from"@modelcontextprotocol/sdk/server/stdio.js";import{io as n}from"socket.io-client";import{z as r}from"zod";import{existsSync as i,mkdirSync as a,readFileSync as o,readdirSync as s,unlinkSync as c,writeFileSync as l}from"node:fs";import{homedir as u}from"node:os";import{join as d}from"node:path";import ee from"xxhash-wasm";import f from"node:http";import{Server as te}from"socket.io";let p=null,m=4649;function h(e){m=e}function g(){return p||=n(`http://127.0.0.1:${m}`,{transports:[`websocket`],reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:3}),p}function ne(e){g().emit(`relay-pause`,e)}function re(e){g().emit(`relay-resume`,e)}function ie(){p&&=(p.close(),null)}const _=`@@dict`,v=`@@ref:`;let y;const ae=ee().then(e=>{y=e.h64ToString});function b(){return ae}function x(e){return y(JSON.stringify(e))}function S(e){return typeof e==`object`&&!!e}function C(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;if(S(n)){let e=x(n);t[e]??=n,n=`${v}${e}`}if(S(r)){let e=x(r);t[e]??=r,r=`${v}${e}`}return n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function w(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=C(n,t),o=C(r,t),s=C(i,t);return a===n&&o===r&&s===i?e:{...e,reason:{propsDifferences:a,stateDifferences:o,hookDifferences:s}}}function T(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;return typeof n==`string`&&n.startsWith(v)&&(n=t[n.slice(6)]??n),typeof r==`string`&&r.startsWith(v)&&(r=t[r.slice(6)]??r),n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function E(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=T(n,t),o=T(r,t),s=T(i,t);return a===n&&o===r&&s===i?e:{...e,reason:{propsDifferences:a,stateDifferences:o,hookDifferences:s}}}function D(e){if(!i(e))return[];let t=o(e,`utf-8`).split(`
|
|
3
|
+
`).filter(Boolean);if(t.length===0)return[];let n,r=0,a=JSON.parse(t[0]);`@@dict`in a&&(n=a[_],r=1);let s=t.slice(r).map(e=>JSON.parse(e));return n?s.map(e=>E(e,n)):s}function O(e){return e.replaceAll(/[^a-zA-Z0-9_.-]/g,`_`)}function k(e){return{project:e.projectId,displayName:e.displayName,reason:e.reason,...e.hookName!=null&&{hookName:e.hookName},...e.commitId!=null&&{commitId:e.commitId},...e.timestamp!=null&&{timestamp:e.timestamp},...e.stackFrames!=null&&e.stackFrames.length>0&&{stackFrames:e.stackFrames}}}const A=`nocommit`,j=new class{dir;buffers=new Map;timers=new Map;dicts=new Map;bufferMeta=new Map;trackedComponents=new Map;wdyrConfigs=new Map;constructor(e){this.dir=e??d(u(),`.wdyr-mcp`,`renders`),a(this.dir,{recursive:!0})}addRender(e,t,n){let r={...e,projectId:t,timestamp:Date.now(),...n!=null&&{commitId:n}},i=this.bufferKey(t,n),a=this.buffers.get(i);a||(a=[],this.buffers.set(i,a),this.bufferMeta.set(i,{projectId:t,commitId:n})),a.push(r);let o=this.timers.get(i);o&&clearTimeout(o),this.timers.set(i,setTimeout(()=>{this.flushAsync(t,n).catch(e=>console.error(`[wdyr-mcp] flush error for ${i}:`,e))},200))}async flushAsync(e,t){await b(),this.flush(e,t)}flush(e,t){if(e!=null&&t!==void 0)this.flushBuffer(this.bufferKey(e,t));else if(e!=null)for(let t of this.bufferKeysForProject(e))this.flushBuffer(t);else for(let e of[...this.buffers.keys()])this.flushBuffer(e)}flushBuffer(e){let t=this.buffers.get(e);if(!t||t.length===0)return;let n=this.bufferMeta.get(e);if(!n)return;let r=this.dicts.get(e);r||(r={},this.dicts.set(e,r));let i=t.map(e=>w(e,r)),a=this.commitFile(n.projectId,n.commitId),o=this.readDataLines(a),s=i.map(e=>JSON.stringify(e)),c=[...o,...s];l(a,`${(Object.keys(r).length>0?[JSON.stringify({[_]:r}),...c]:c).join(`
|
|
4
4
|
`)}\n`),t.length=0;let u=this.timers.get(e);u&&(clearTimeout(u),this.timers.delete(e))}readDataLines(e){return i(e)?o(e,`utf-8`).split(`
|
|
5
|
-
`).filter(e=>!(!e||e.startsWith(`{"@@dict"`))):[]}getAllRenders(e){return this.flush(e),e?this.projectFiles(e).flatMap(e=>
|
|
6
|
-
`);for(let t of i){if(!t)continue;let n=JSON.parse(t);if(!(`@@dict`in n)){e.add(n.projectId);break}}}return[...e]}getCommitIds(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=new Set;for(let e of t){let t=this.parseFilename(e);t?.commitId!=null&&n.add(t.commitId)}return[...n].sort((e,t)=>e-t)}getCommits(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=[];for(let e of t){let t=this.parseFilename(e);if(t?.commitId==null)continue;let r=
|
|
7
|
-
`)}\n`)}clearBuffersForFile(e){let t=this.parseFilename(e);if(t)for(let[e,n]of this.bufferMeta){if(
|
|
8
|
-
`)}}function
|
|
9
|
-
`)}`)})}function
|
|
10
|
-
`)}`)}function
|
|
11
|
-
`)}`)}function
|
|
12
|
-
`))})}let
|
|
5
|
+
`).filter(e=>!(!e||e.startsWith(`{"@@dict"`))):[]}getAllRenders(e){return this.flush(e),e?this.projectFiles(e).flatMap(e=>D(d(this.dir,e)).map(k)):this.jsonlFiles().flatMap(e=>D(d(this.dir,e)).map(k))}getRendersByComponent(e,t){return this.getAllRenders(t).filter(t=>t.displayName===e)}clearRenders(e){if(e){for(let t of this.bufferKeysForProject(e)){this.buffers.delete(t),this.dicts.delete(t),this.bufferMeta.delete(t);let e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}for(let t of this.projectFiles(e))c(d(this.dir,t))}else{for(let[,e]of this.timers)clearTimeout(e);this.buffers.clear(),this.timers.clear(),this.dicts.clear(),this.bufferMeta.clear();for(let e of this.jsonlFiles())c(d(this.dir,e))}}clearRendersByComponent(e,t){this.flush(t);let n=t?this.projectFiles(t):this.jsonlFiles(),r=0;for(let t of n){let n=d(this.dir,t),i=D(n),a=i.length,o=i.filter(t=>t.displayName!==e);r+=a-o.length,o.length===0?(c(n),this.clearBuffersForFile(t)):o.length<a&&(this.rewriteFile(n,o),this.clearBuffersForFile(t))}return r}clearRendersByCommit(e,t){this.flush(t);let n=t?this.projectFiles(t):this.jsonlFiles(),r=0;for(let t of n){let n=this.parseFilename(t);n?.commitId!=null&&n.commitId<e&&(c(d(this.dir,t)),this.clearBuffersForFile(t),r++)}return r}getProjects(){this.flush();let e=new Set,t=new Set;for(let n of this.jsonlFiles()){let r=this.parseFilename(n);if(!r||t.has(r.projectSanitized))continue;t.add(r.projectSanitized);let i=o(d(this.dir,n),`utf-8`).split(`
|
|
6
|
+
`);for(let t of i){if(!t)continue;let n=JSON.parse(t);if(!(`@@dict`in n)){e.add(n.projectId);break}}}return[...e]}getCommitIds(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=new Set;for(let e of t){let t=this.parseFilename(e);t?.commitId!=null&&n.add(t.commitId)}return[...n].sort((e,t)=>e-t)}getCommits(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=[];for(let e of t){let t=this.parseFilename(e);if(t?.commitId==null)continue;let r=D(d(this.dir,e));r.length!==0&&n.push({commitId:t.commitId,timestamp:r.find(e=>e.timestamp!=null)?.timestamp??null,renderCount:r.length,components:[...new Set(r.map(e=>e.displayName))]})}return n.sort((e,t)=>e.commitId-t.commitId)}getRendersByCommit(e,t){if(t)return this.flush(t,e),D(this.commitFile(t,e)).map(k);this.flush();let n=`_commit_${e}.jsonl`;return this.jsonlFiles().filter(e=>e.endsWith(n)).flatMap(e=>D(d(this.dir,e)).map(k))}getSummary(e){let t=this.getAllRenders(e),n={};for(let e of t){n[e.project]??={};let t=n[e.project];t[e.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=t[e.displayName];r.count++,Array.isArray(e.reason.propsDifferences)&&r.reasons.props++,Array.isArray(e.reason.stateDifferences)&&r.reasons.state++,Array.isArray(e.reason.hookDifferences)&&r.reasons.hooks++,typeof e.actualDuration==`number`&&(r.totalDuration=(r.totalDuration??0)+e.actualDuration)}return n}getSummaryByCommit(e){let t=this.getAllRenders(e),n={};for(let e of t){if(e.commitId==null)continue;n[e.project]??={},n[e.project][e.commitId]??={};let t=n[e.project][e.commitId];t[e.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=t[e.displayName];r.count++,Array.isArray(e.reason.propsDifferences)&&r.reasons.props++,Array.isArray(e.reason.stateDifferences)&&r.reasons.state++,Array.isArray(e.reason.hookDifferences)&&r.reasons.hooks++,typeof e.actualDuration==`number`&&(r.totalDuration=(r.totalDuration??0)+e.actualDuration)}return n}setTrackedComponents(e,t){this.trackedComponents.set(t,e)}getTrackedComponents(e){let t={},n=e?[e]:this.getProjects();for(let e of n){let n=[...new Set(this.getAllRenders(e).map(e=>e.displayName))];t[e]={registered:this.trackedComponents.get(e)??[],observed:n}}return t}setWdyrConfig(e,t){this.wdyrConfigs.set(t,e)}getWdyrConfig(e){let t={};if(e){let n=this.wdyrConfigs.get(e);n&&(t[e]=n)}else for(let[e,n]of this.wdyrConfigs)t[e]=n;return t}rewriteFile(e,t){l(e,`${t.map(e=>JSON.stringify(e)).join(`
|
|
7
|
+
`)}\n`)}clearBuffersForFile(e){let t=this.parseFilename(e);if(t)for(let[e,n]of this.bufferMeta){if(O(n.projectId)!==t.projectSanitized||!(t.commitId==null?n.commitId==null:n.commitId===t.commitId))continue;this.buffers.delete(e),this.dicts.delete(e),this.bufferMeta.delete(e);let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}}bufferKey(e,t){return`${e}\0${t??A}`}bufferKeysForProject(e){let t=`${e}\0`;return[...this.buffers.keys()].filter(e=>e.startsWith(t))}commitFile(e,t){let n=O(e),r=t==null?`_${A}`:`_commit_${t}`;return d(this.dir,`${n}${r}.jsonl`)}projectFiles(e){let t=O(e);return s(this.dir).filter(e=>e.startsWith(t)&&e.endsWith(`.jsonl`))}parseFilename(e){if(!e.endsWith(`.jsonl`))return null;let t=e.slice(0,-6),n=t.match(/^(.+)_commit_(\d+)$/);if(n)return{projectSanitized:n[1],commitId:Number(n[2])};let r=t.match(/^(.+)_nocommit$/);return r?{projectSanitized:r[1]}:{projectSanitized:t}}jsonlFiles(){return s(this.dir).filter(e=>e.endsWith(`.jsonl`))}};function M(e){if(e)return{projectId:e};let t=j.getProjects();return t.length===0?{projectId:void 0}:t.length===1?{projectId:t[0]}:{projectId:void 0,error:[`Multiple projects are recording render data. Ask the user which project they are working on (e.g. their dev server URL like http://localhost:3000).`,``,`Active projects:`,...t.map(e=>`- ${e}`)].join(`
|
|
8
|
+
`)}}function N(e){return{content:[{type:`text`,text:e}]}}function oe(e){e.registerTool(`clear_renders`,{title:`Clear Renders`,description:`Clears collected render data. Supports filtering by component name or by commit ID threshold. When no filter is given, clears all data. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),component:r.string().optional().describe(`Clear only renders for this component (by displayName).`),beforeCommit:r.number().optional().describe(`Clear all renders from commits with an ID strictly less than this value.`)}},async({project:e,component:t,beforeCommit:n})=>{let r=M(e);return r.error?N(r.error):t?N(`Cleared ${j.clearRendersByComponent(t,r.projectId)} render(s) for component "${t}".`):n==null?(j.clearRenders(r.projectId),N(r.projectId?`Render data cleared for ${r.projectId}.`:`All render data cleared.`)):N(`Cleared renders from ${j.clearRendersByCommit(n,r.projectId)} commit file(s) before commit #${n}.`)})}function P(e){e.registerTool(`get_commits`,{title:`Get Commits`,description:`Returns a list of React commit IDs that have recorded render data for a project. Use these IDs with get_renders_by_commit to inspect individual commits.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=M(e);if(t.error)return N(t.error);let n=j.getCommits(t.projectId);return n.length===0?N(`No commits recorded yet. Make sure the browser is connected and triggering re-renders.`):N(JSON.stringify(n,null,2))})}function F(e){e.registerTool(`get_projects`,{title:`Get Projects`,description:`Returns a list of project identifiers (browser origin URLs) that have recorded render data.`,inputSchema:{}},async()=>{let e=j.getProjects();return e.length===0?N(`No projects have recorded render data yet.`):N(`Active projects:\n${e.map(e=>`- ${e}`).join(`
|
|
9
|
+
`)}`)})}function I(e){e.registerTool(`get_render_summary`,{title:`Get Render Summary`,description:`Returns a summary of re-renders grouped by component name with counts. Use groupBy: 'commit' to get per-commit breakdowns instead of a single aggregate. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),groupBy:r.enum([`commit`]).optional().describe(`Group results by commit. When set to 'commit', returns per-commit render summaries instead of a single aggregate.`)}},async({project:e,groupBy:t})=>{let n=M(e);return n.error?N(n.error):t===`commit`?B(n.projectId):z(n.projectId)})}function L(e){return e==null?``:` (${e.toFixed(1)}ms)`}function R(e){let t=[];return e.props>0&&t.push(`props: ${e.props}`),e.state>0&&t.push(`state: ${e.state}`),e.hooks>0&&t.push(`hooks: ${e.hooks}`),t.length>0?` — ${t.join(`, `)}`:``}function z(e){let t=j.getSummary(e);if(Object.keys(t).length===0)return N(`No renders recorded yet.`);let n=[];for(let[e,r]of Object.entries(t)){n.push(`[${e}]`);for(let[e,{count:t,reasons:i,totalDuration:a}]of Object.entries(r))n.push(` ${e}: ${t} re-render(s)${R(i)}${L(a)}`)}return N(`Re-render summary:\n\n${n.join(`
|
|
10
|
+
`)}`)}function B(e){let t=j.getSummaryByCommit(e);if(Object.keys(t).length===0)return N(`No renders with commit IDs recorded yet.`);let n=[];for(let[e,r]of Object.entries(t)){n.push(`[${e}]`);let t=Object.keys(r).map(Number).sort((e,t)=>e-t);for(let e of t){let t=r[e],i=Object.values(t).reduce((e,t)=>e+t.count,0);n.push(` Commit #${e} (${i} re-render(s)):`);for(let[e,{count:r,reasons:i,totalDuration:a}]of Object.entries(t))n.push(` ${e}: ${r}${R(i)}${L(a)}`)}}return N(`Re-render summary (by commit):\n\n${n.join(`
|
|
11
|
+
`)}`)}function V(e){e.registerTool(`get_renders_by_commit`,{title:`Get Renders by Commit`,description:`Returns all re-renders for a specific React commit ID, including stack traces that show the hook chain and component tree that triggered each render. Use the stackFrames field to locate the exact source file and line. Use get_commits first to discover available commit IDs.`,inputSchema:{commitId:r.number().describe(`The React commit ID to filter by.`),component:r.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({commitId:e,component:t,project:n})=>{let r=M(n);if(r.error)return N(r.error);let i=j.getRendersByCommit(e,r.projectId);return t&&(i=i.filter(e=>e.displayName===t)),i.length===0?N(t?`No renders recorded for component "${t}" in commit ${e}.`:`No renders recorded for commit ${e}.`):N(JSON.stringify(i,null,2))})}function H(e){e.registerTool(`get_renders`,{title:`Get Renders`,description:`Returns all re-renders collected from the browser, including stack traces that show the hook chain and component tree that triggered each render. Use the stackFrames field to locate the exact source file and line. If multiple projects are active and no project is specified, the tool will ask you to disambiguate by asking the user for their dev server URL.`,inputSchema:{component:r.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({component:e,project:t})=>{let n=M(t);if(n.error)return N(n.error);let r=e?j.getRendersByComponent(e,n.projectId):j.getAllRenders(n.projectId);return r.length===0?N(e?`No renders recorded for "${e}".`:`No renders recorded yet. Make sure the browser is connected and triggering re-renders.`):N(JSON.stringify(r,null,2))})}function U(e){let t=[];if(e.include?.length){t.push(` include:`);for(let n of e.include)t.push(` - /${n}/`)}if(e.exclude?.length){t.push(` exclude:`);for(let n of e.exclude)t.push(` - /${n}/`)}if(e.trackAllPureComponents!=null&&t.push(` trackAllPureComponents: ${e.trackAllPureComponents}`),e.trackHooks!=null&&t.push(` trackHooks: ${e.trackHooks}`),e.trackExtraHooks?.length){t.push(` trackExtraHooks:`);for(let n of e.trackExtraHooks)t.push(` - ${n}`)}return e.logOnDifferentValues!=null&&t.push(` logOnDifferentValues: ${e.logOnDifferentValues}`),e.logOwnerReasons!=null&&t.push(` logOwnerReasons: ${e.logOwnerReasons}`),t}function W(e){e.registerTool(`get_tracked_components`,{title:`Get Tracked Components`,description:`Returns the why-did-you-render configuration for the connected project, including include/exclude filters and tracking options. Also shows components observed in render data. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=M(e);if(t.error)return N(t.error);let n=j.getWdyrConfig(t.projectId),r=j.getTrackedComponents(t.projectId),i=Object.keys(n).length>0,a=Object.keys(r).length>0;if(!i&&!a)return N(`No configuration or tracked components found. Make sure the browser is connected and triggering re-renders.`);let o=[],s=new Set([...Object.keys(n),...Object.keys(r)]);for(let e of s){o.push(`[${e}]`);let t=n[e];if(t){o.push(`Configuration:`);let e=U(t);e.length>0?o.push(...e):o.push(` (default options)`)}let i=r[e];if(i?.observed.length){o.push(`Observed in renders:`);for(let e of i.observed)o.push(` - ${e}`)}}return N(o.join(`
|
|
12
|
+
`))})}let G=null;function K(e){G=e}function q(){return G}const J=new Set;function se(){return J.has(null)}function Y(e){return J.has(null)||J.has(e)}function X(e){J.add(e)}function Z(e){e===null?J.clear():J.delete(e)}function ce(e){e.registerTool(`pause_renders`,{title:`Pause Render Collection`,description:`Pauses render data collection in the browser. Connected clients will stop reporting renders until resume_renders is called. Useful when you want to ignore renders from irrelevant interactions. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=M(e);if(t.error)return N(t.error);X(t.projectId??null);let n=q();if(!n)return ne(t.projectId??void 0),N(`Paused render collection for ${t.projectId??`all projects`} (relayed via WS owner).`);if(t.projectId){let e=await n.fetchSockets();for(let n of e)n.data.projectId===t.projectId&&n.emit(`pause`);return N(`Paused render collection for ${t.projectId}.`)}return n.emit(`pause`),N(`Paused render collection for all projects.`)})}function le(e){e.registerTool(`resume_renders`,{title:`Resume Render Collection`,description:`Resumes render data collection that was previously paused with pause_renders. Connected clients will start reporting renders again. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=M(e);if(t.error)return N(t.error);Z(t.projectId??null);let n=q();if(!n)return re(t.projectId??void 0),N(`Resumed render collection for ${t.projectId??`all projects`} (relayed via WS owner).`);if(t.projectId){let e=await n.fetchSockets();for(let n of e)n.data.projectId===t.projectId&&n.emit(`resume`);return N(`Resumed render collection for ${t.projectId}.`)}return n.emit(`resume`),N(`Resumed render collection for all projects.`)})}function ue(e){H(e),I(e),P(e),V(e),F(e),W(e),oe(e),ce(e),le(e)}const Q=3e3;function de(e,t){e.on(`connection`,n=>{console.error(`[wdyr-mcp] browser connected (http://localhost:${t})`),n.data.projectId=null,se()&&n.emit(`pause`),n.on(`render`,(e,t,r)=>{n.data.projectId=t,!Y(t)&&j.addRender(e,t,r)}),n.on(`render-batch`,(e,t,r)=>{if(n.data.projectId=t,!Y(t))for(let n of e)j.addRender(n,t,r)}),n.on(`register`,(e,t)=>{n.data.projectId=t,j.setTrackedComponents(e,t),Y(t)&&n.emit(`pause`)}),n.on(`config`,(e,t)=>{n.data.projectId=t,j.setWdyrConfig(e,t)}),n.on(`relay-pause`,async t=>{if(X(t??null),t){let n=await e.fetchSockets();for(let e of n)e.data.projectId===t&&e.emit(`pause`)}else e.emit(`pause`)}),n.on(`relay-resume`,async t=>{if(Z(t??null),t){let n=await e.fetchSockets();for(let e of n)e.data.projectId===t&&e.emit(`resume`)}else e.emit(`resume`)}),n.on(`disconnect`,()=>{console.error(`[wdyr-mcp] browser disconnected`);let t=n.data.projectId;t&&([...e.sockets.sockets.values()].some(e=>e.id!==n.id&&e.data.projectId===t)||(console.error(`[wdyr-mcp] last client for ${t} disconnected, clearing render data`),j.clearRenders(t)))})})}function fe(e){let t=null,n=null,r=null,i=!1;function a(){i||(r=f.createServer(),n=new te(r,{cors:{origin:`*`},serveClient:!1,transports:[`websocket`],maxHttpBufferSize:5e7}),de(n,e),r.once(`error`,t=>{t.code===`EADDRINUSE`?(console.error(`[wdyr-mcp] Port ${e} in use, will retry every ${Q/1e3}s`),n?.close(),n=null,K(null),r=null,o()):console.error(`[wdyr-mcp] server error:`,t)}),r.listen(e,`127.0.0.1`,()=>{console.error(`[wdyr-mcp] socket.io server listening on http://localhost:${e}`),K(n),s()}))}function o(){t||i||(t=setInterval(a,Q))}function s(){t&&=(clearInterval(t),null)}return a(),{close(){i=!0,s(),n?.close(),K(null)}}}const $=new e({name:`why-did-you-render`,version:`0.0.0`});ue($);async function pe(){let e=Number(process.env.WDYR_WS_PORT)||4649;h(e);let n=fe(e),r=new t;await $.connect(r),console.error(`[wdyr-mcp] MCP server running on stdio`);let i=!1;async function a(){i||(i=!0,console.error(`[wdyr-mcp] Shutting down…`),ie(),n.close(),await $.close(),process.exit(0))}process.stdin.on(`end`,a),process.on(`SIGTERM`,a),process.on(`SIGINT`,a)}pe().catch(e=>{console.error(`[wdyr-mcp] Fatal error:`,e),process.exit(1)});export{};
|
package/package.json
CHANGED