@0x1f320.sh/why-did-you-render-mcp 1.1.0-dev.6 → 1.1.0-dev.7
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 +14 -14
- package/package.json +1 -1
package/dist/server/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
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 f from"xxhash-wasm";import p from"node:http";import{Server as ee}from"socket.io";let m=null,h=4649;function te(e){h=e}function g(){return m||=n(`http://127.0.0.1:${h}`,{transports:[`websocket`],reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:3}),m}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 f from"xxhash-wasm";import p from"node:http";import{Server as ee}from"socket.io";let m=null,h=4649;function te(e){h=e}function g(){return m||=n(`http://127.0.0.1:${h}`,{transports:[`websocket`],reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:3}),m}function ne(e){g().emit(`relay-pause`,e)}function re(e){g().emit(`relay-resume`,e)}function ie(){m&&=(m.close(),null)}const _=`@@dict`,v=`@@ref:`;let y;const ae=f().then(e=>{y=e.h64ToString});function oe(){return ae}function b(e){return y(JSON.stringify(e))}function x(e){return typeof e==`object`&&!!e}function S(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;if(x(n)){let e=b(n);t[e]??=n,n=`${v}${e}`}if(x(r)){let e=b(r);t[e]??=r,r=`${v}${e}`}return n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function se(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=S(n,t),o=S(r,t),s=S(i,t);return a===n&&o===r&&s===i?e:{...e,reason:{propsDifferences:a,stateDifferences:o,hookDifferences:s}}}function C(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 ce(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 w(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=>ce(e,n)):s}function T(e){return e.replaceAll(/[^a-zA-Z0-9_.-]/g,`_`)}function E(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 D=`nocommit`;var O=class{dir;buffers=new Map;timers=new Map;dicts=new Map;bufferMeta=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 oe(),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=>se(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
|
-
`)}`)}function
|
|
13
|
-
`))})}function
|
|
14
|
-
`)}`)})}let W=null;function G(e){W=e}function K(){return W}const q=new Set;function
|
|
15
|
-
`));return}setTimeout(a,500)}a()}))})}function
|
|
16
|
-
`)}function
|
|
5
|
+
`).filter(e=>!(!e||e.startsWith(`{"@@dict"`))):[]}getAllRenders(e){return this.flush(e),e?this.projectFiles(e).flatMap(e=>w(d(this.dir,e)).map(E)):this.jsonlFiles().flatMap(e=>w(d(this.dir,e)).map(E))}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=w(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=w(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),w(this.commitFile(t,e)).map(E);this.flush();let n=`_commit_${e}.jsonl`;return this.jsonlFiles().filter(e=>e.endsWith(n)).flatMap(e=>w(d(this.dir,e)).map(E))}getRendersSince(e,t){return this.getAllRenders(t).filter(t=>t.timestamp!=null&&t.timestamp>e)}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(T(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??D}`}bufferKeysForProject(e){let t=`${e}\0`;return[...this.buffers.keys()].filter(e=>e.startsWith(t))}commitFile(e,t){let n=T(e),r=t==null?`_${D}`:`_commit_${t}`;return d(this.dir,`${n}${r}.jsonl`)}projectFiles(e){let t=T(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`))}},k=class{dir;constructor(e){this.dir=e??d(u(),`.wdyr-mcp`,`snapshots`)}save(e,t){a(this.dir,{recursive:!0});let n={name:e,timestamp:Date.now(),data:t};l(d(this.dir,`${e}.json`),JSON.stringify(n,null,2))}list(){return i(this.dir)?s(this.dir).filter(e=>e.endsWith(`.json`)).map(e=>{let t=o(d(this.dir,e),`utf-8`),n=JSON.parse(t);return{name:n.name,timestamp:n.timestamp}}):[]}get(e){let t=d(this.dir,`${e}.json`);return i(t)?JSON.parse(o(t,`utf-8`)):null}delete(e){let t=d(this.dir,`${e}.json`);return i(t)?(c(t),!0):!1}},le=class{trackedComponents=new Map;wdyrConfigs=new Map;hmrTimestamps=new Map;setTrackedComponents(e,t){this.trackedComponents.set(t,e)}getTrackedComponents(e){return this.trackedComponents.get(e)??[]}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}recordHmr(e){this.hmrTimestamps.set(e,Date.now())}getLastHmrTimestamp(e){return this.hmrTimestamps.get(e)??null}};function A(e){let t={};for(let n of e){t[n.project]??={};let e=t[n.project];e[n.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=e[n.displayName];r.count++,Array.isArray(n.reason.propsDifferences)&&r.reasons.props++,Array.isArray(n.reason.stateDifferences)&&r.reasons.state++,Array.isArray(n.reason.hookDifferences)&&r.reasons.hooks++,typeof n.actualDuration==`number`&&(r.totalDuration=(r.totalDuration??0)+n.actualDuration)}return t}function ue(e){let t={};for(let n of e){if(n.commitId==null)continue;t[n.project]??={},t[n.project][n.commitId]??={};let e=t[n.project][n.commitId];e[n.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=e[n.displayName];r.count++,Array.isArray(n.reason.propsDifferences)&&r.reasons.props++,Array.isArray(n.reason.stateDifferences)&&r.reasons.state++,Array.isArray(n.reason.hookDifferences)&&r.reasons.hooks++,typeof n.actualDuration==`number`&&(r.totalDuration=(r.totalDuration??0)+n.actualDuration)}return t}const j=new O,M=new k,N=new le;function P(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 F(e){return{content:[{type:`text`,text:e}]}}function de(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=P(e);return r.error?F(r.error):t?F(`Cleared ${j.clearRendersByComponent(t,r.projectId)} render(s) for component "${t}".`):n==null?(j.clearRenders(r.projectId),F(r.projectId?`Render data cleared for ${r.projectId}.`:`All render data cleared.`)):F(`Cleared renders from ${j.clearRendersByCommit(n,r.projectId)} commit file(s) before commit #${n}.`)})}function I(e){e.registerTool(`compare_snapshots`,{title:`Compare Snapshots`,description:`Compares two saved render snapshots and shows per-component render count changes.`,inputSchema:{before:r.string().describe(`The name of the baseline snapshot.`),after:r.string().describe(`The name of the snapshot to compare against the baseline.`)}},async({before:e,after:t})=>{let n=M.get(e);if(!n)return F(`Snapshot "${e}" not found.`);let r=M.get(t);if(!r)return F(`Snapshot "${t}" not found.`);let i=new Set([...Object.keys(n.data),...Object.keys(r.data)]);if(i.size===0)return F(`Both snapshots are empty.`);let a=[],o=0,s=0,c=0,l=0,u=!1;for(let e of[...i].sort()){a.push(`[${e}]`);let t=n.data[e]??{},i=r.data[e]??{},d=new Set([...Object.keys(t),...Object.keys(i)]);for(let e of[...d].sort()){let n=t[e],r=i[e],d=n?.count??0,f=r?.count??0;o+=d,s+=f;let p=``;if(n?.totalDuration!=null||r?.totalDuration!=null){u=!0;let e=n?.totalDuration??0,t=r?.totalDuration??0;c+=e,l+=t,p=` [${e.toFixed(1)}ms → ${t.toFixed(1)}ms]`}a.push(` ${e}: ${d} → ${f} (${L(d,f)})${p}`)}}a.push(``);let d=`Total: ${o} → ${s} (${L(o,s)})`;return u&&(d+=` [${c.toFixed(1)}ms → ${l.toFixed(1)}ms]`),a.push(d),F(`Snapshot comparison: "${e}" → "${t}"\n\n${a.join(`
|
|
9
|
+
`)}`)})}function L(e,t){if(e===0&&t===0)return`no change`;if(e===0)return`new`;if(t===0)return`removed`;if(e===t)return`no change`;let n=((t-e)/e*100).toFixed(1);return`${Number(n)>0?`+`:``}${n}%`}function R(e){e.registerTool(`delete_snapshot`,{title:`Delete Snapshot`,description:`Deletes a saved render snapshot by name.`,inputSchema:{name:r.string().describe(`The name of the snapshot to delete.`)}},async({name:e})=>M.delete(e)?F(`Snapshot "${e}" deleted.`):F(`Snapshot "${e}" not found.`))}function z(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=P(e);if(t.error)return F(t.error);let n=j.getCommits(t.projectId);return n.length===0?F(`No commits recorded yet. Make sure the browser is connected and triggering re-renders.`):F(JSON.stringify(n,null,2))})}function B(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?F(`No projects have recorded render data yet.`):F(`Active projects:\n${e.map(e=>`- ${e}`).join(`
|
|
10
|
+
`)}`)})}function V(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=P(e);return n.error?F(n.error):t===`commit`?pe(n.projectId):fe(n.projectId)})}function H(e){return e==null?``:` (${e.toFixed(1)}ms)`}function U(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 fe(e){let t=A(j.getAllRenders(e));if(Object.keys(t).length===0)return F(`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)${U(i)}${H(a)}`)}return F(`Re-render summary:\n\n${n.join(`
|
|
11
|
+
`)}`)}function pe(e){let t=ue(j.getAllRenders(e));if(Object.keys(t).length===0)return F(`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}${U(i)}${H(a)}`)}}return F(`Re-render summary (by commit):\n\n${n.join(`
|
|
12
|
+
`)}`)}function me(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=P(n);if(r.error)return F(r.error);let i=j.getRendersByCommit(e,r.projectId);return t&&(i=i.filter(e=>e.displayName===t)),i.length===0?F(t?`No renders recorded for component "${t}" in commit ${e}.`:`No renders recorded for commit ${e}.`):F(JSON.stringify(i,null,2))})}function he(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=P(t);if(n.error)return F(n.error);let r=e?j.getRendersByComponent(e,n.projectId):j.getAllRenders(n.projectId);return r.length===0?F(e?`No renders recorded for "${e}".`:`No renders recorded yet. Make sure the browser is connected and triggering re-renders.`):F(JSON.stringify(r,null,2))})}function ge(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 _e(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=P(e);if(t.error)return F(t.error);let n=N.getWdyrConfig(t.projectId),r=t.projectId?[t.projectId]:j.getProjects(),i={};for(let e of r){let t=[...new Set(j.getAllRenders(e).map(e=>e.displayName))];i[e]={registered:N.getTrackedComponents(e),observed:t}}let a=Object.keys(n).length>0,o=Object.keys(i).length>0;if(!a&&!o)return F(`No configuration or tracked components found. Make sure the browser is connected and triggering re-renders.`);let s=[],c=new Set([...Object.keys(n),...Object.keys(i)]);for(let e of c){s.push(`[${e}]`);let t=n[e];if(t){s.push(`Configuration:`);let e=ge(t);e.length>0?s.push(...e):s.push(` (default options)`)}let r=i[e];if(r?.observed.length){s.push(`Observed in renders:`);for(let e of r.observed)s.push(` - ${e}`)}}return F(s.join(`
|
|
13
|
+
`))})}function ve(e){e.registerTool(`list_snapshots`,{title:`List Snapshots`,description:`Lists all saved render snapshots with their timestamps.`,inputSchema:{}},async()=>{let e=M.list();return e.length===0?F(`No snapshots saved yet.`):F(`Saved snapshots:\n\n${e.map(e=>`- ${e.name} (${new Date(e.timestamp).toISOString()})`).join(`
|
|
14
|
+
`)}`)})}let W=null;function G(e){W=e}function K(){return W}const q=new Set;function ye(){return q.has(null)}function J(e){return q.has(null)||q.has(e)}function Y(e){q.add(e)}function X(e){e===null?q.clear():q.delete(e)}function be(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=P(e);if(t.error)return F(t.error);Y(t.projectId??null);let n=K();if(!n)return ne(t.projectId??void 0),F(`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 F(`Paused render collection for ${t.projectId}.`)}return n.emit(`pause`),F(`Paused render collection for all projects.`)})}function xe(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=P(e);if(t.error)return F(t.error);X(t.projectId??null);let n=K();if(!n)return re(t.projectId??void 0),F(`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 F(`Resumed render collection for ${t.projectId}.`)}return n.emit(`resume`),F(`Resumed render collection for all projects.`)})}function Z(e){e.registerTool(`save_snapshot`,{title:`Save Snapshot`,description:`Saves the current render summary as a named snapshot for later comparison. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{name:r.string().describe(`A name for this snapshot (used to reference it later).`),project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({name:e,project:t})=>{let n=P(t);return n.error?F(n.error):(M.save(e,A(j.getAllRenders(n.projectId))),F(`Snapshot "${e}" saved.`))})}function Se(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 Ce(e){e.registerTool(`wait_for_renders`,{title:`Wait for Renders`,description:`Waits for new renders to arrive after a code change. Call this after modifying code to wait for HMR to complete and measure the resulting re-renders. Returns a summary of new renders received during the wait period.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),timeout:r.number().optional().describe(`Maximum time to wait in milliseconds (default 10000, max 30000).`)}},async({project:e,timeout:t})=>{let n=P(e);if(n.error)return F(n.error);let r=Math.min(t??1e4,3e4),i=Date.now();return F(await new Promise(e=>{let t=!1;function a(){let o=Date.now()-i;if(n.projectId){let e=N.getLastHmrTimestamp(n.projectId);e!=null&&e>=i&&(t=!0)}let s=j.getRendersSince(i,n.projectId);if(s.length>0){let n=we(s),r=((Date.now()-i)/1e3).toFixed(1),a=t?` after HMR update`:``;e(`Received ${s.length} new render(s)${a} (waited ${r}s):\n\n${n}`);return}if(o>=r){let n=(r/1e3).toFixed(1);e(t?`Timed out after ${n}s — HMR was detected but no new renders were received.`:[`Timed out after ${n}s — no new renders received.`,`No HMR signal was detected. Verify that:`,`- The dev server is running with HMR enabled`,`- The browser tab is open and connected`].join(`
|
|
15
|
+
`));return}setTimeout(a,500)}a()}))})}function we(e){let t={};for(let n of e){t[n.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let e=t[n.displayName];e.count++,Array.isArray(n.reason.propsDifferences)&&e.reasons.props++,Array.isArray(n.reason.stateDifferences)&&e.reasons.state++,Array.isArray(n.reason.hookDifferences)&&e.reasons.hooks++}let n=[];for(let[e,{count:r,reasons:i}]of Object.entries(t))n.push(` ${e}: ${r} re-render(s)${Se(i)}`);return n.join(`
|
|
16
|
+
`)}function Te(e){he(e),V(e),z(e),me(e),B(e),_e(e),de(e),be(e),xe(e),Z(e),ve(e),I(e),R(e),Ce(e)}const Q=3e3;function Ee(e,t){e.on(`connection`,n=>{console.error(`[wdyr-mcp] browser connected (http://localhost:${t})`),n.data.projectId=null,ye()&&n.emit(`pause`),n.on(`render`,(e,t,r)=>{n.data.projectId=t,!J(t)&&j.addRender(e,t,r)}),n.on(`render-batch`,(e,t,r)=>{if(n.data.projectId=t,!J(t))for(let n of e)j.addRender(n,t,r)}),n.on(`register`,(e,t)=>{n.data.projectId=t,N.setTrackedComponents(e,t),J(t)&&n.emit(`pause`)}),n.on(`config`,(e,t)=>{n.data.projectId=t,N.setWdyrConfig(e,t)}),n.on(`relay-pause`,async t=>{if(Y(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(`hmr`,e=>{n.data.projectId=e,N.recordHmr(e)}),n.on(`relay-resume`,async t=>{if(X(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 De(e){let t=null,n=null,r=null,i=!1;function a(){i||(r=p.createServer(),n=new ee(r,{cors:{origin:`*`},serveClient:!1,transports:[`websocket`],maxHttpBufferSize:5e7}),Ee(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,G(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}`),G(n),s()}))}function o(){t||i||(t=setInterval(a,Q))}function s(){t&&=(clearInterval(t),null)}return a(),{close(){i=!0,s(),n?.close(),G(null)}}}const $=new e({name:`why-did-you-render`,version:`0.0.0`});Te($);async function Oe(){let e=Number(process.env.WDYR_WS_PORT)||4649;te(e);let n=De(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)}Oe().catch(e=>{console.error(`[wdyr-mcp] Fatal error:`,e),process.exit(1)});export{};
|
package/package.json
CHANGED