@0x1f320.sh/why-did-you-render-mcp 1.0.0-dev.19 → 1.0.0-dev.20

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.
@@ -1,223 +1 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let socket_io_client = require("socket.io-client");
3
- //#region src/client/utils/describe-value.ts
4
- const MAX_DEPTH = 8;
5
- const REACT_ELEMENT_SYMBOL = Symbol.for("react.element");
6
- const REACT_TRANSITIONAL_ELEMENT_SYMBOL = Symbol.for("react.transitional.element");
7
- const REACT_MEMO_TYPE = Symbol.for("react.memo");
8
- const REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
9
- function isReactElement(value) {
10
- if (typeof value !== "object" || value === null) return false;
11
- const v = value;
12
- return v.$$typeof === REACT_ELEMENT_SYMBOL || v.$$typeof === REACT_TRANSITIONAL_ELEMENT_SYMBOL || v.$$typeof === 60103;
13
- }
14
- function resolveComponentInfo(type) {
15
- let memo = false;
16
- let forwardRef = false;
17
- let current = type;
18
- for (let i = 0; i < 5; i++) {
19
- if (typeof current !== "object" || current === null) break;
20
- const wrapper = current;
21
- if (wrapper.$$typeof === REACT_MEMO_TYPE) {
22
- memo = true;
23
- current = wrapper.type;
24
- } else if (wrapper.$$typeof === REACT_FORWARD_REF_TYPE) {
25
- forwardRef = true;
26
- current = wrapper.render;
27
- } else break;
28
- }
29
- let name = "Unknown";
30
- if (typeof current === "string") name = current;
31
- else if (typeof current === "function") name = current.displayName || current.name || "Anonymous";
32
- return {
33
- name,
34
- memo,
35
- forwardRef
36
- };
37
- }
38
- function serializeReactElement(el, seen, depth) {
39
- const component = resolveComponentInfo(el.type);
40
- const props = {};
41
- if (el.props && typeof el.props === "object") for (const key of Object.keys(el.props)) {
42
- if (key === "children") continue;
43
- props[key] = serialize(el.props[key], seen, depth + 1);
44
- }
45
- return {
46
- type: "react-node",
47
- component,
48
- props
49
- };
50
- }
51
- function serialize(value, seen, depth) {
52
- if (value === null) return null;
53
- if (value === void 0) return null;
54
- if (typeof value === "function") return {
55
- type: "function",
56
- name: value.name || "anonymous"
57
- };
58
- if (typeof value === "boolean") return value;
59
- if (typeof value === "number") {
60
- if (Number.isNaN(value)) return "NaN";
61
- if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
62
- if (Object.is(value, -0)) return "-0";
63
- return value;
64
- }
65
- if (typeof value === "string") return value;
66
- if (typeof value === "bigint") return value.toString();
67
- if (typeof value === "symbol") return value.toString();
68
- if (seen.has(value)) return "[Circular]";
69
- if (depth >= MAX_DEPTH) return "[MaxDepth]";
70
- seen.add(value);
71
- if (isReactElement(value)) return serializeReactElement(value, seen, depth);
72
- if (Array.isArray(value)) return value.map((item) => serialize(item, seen, depth + 1));
73
- const ctorName = Object.getPrototypeOf(value)?.constructor?.name;
74
- if (ctorName && ctorName !== "Object") {
75
- if (value instanceof Date) return value.toISOString();
76
- if (value instanceof RegExp) return String(value);
77
- if (value instanceof Map) {
78
- const entries = {};
79
- for (const [k, v] of value.entries()) entries[String(k)] = serialize(v, seen, depth + 1);
80
- return {
81
- type: "Map",
82
- entries
83
- };
84
- }
85
- if (value instanceof Set) return {
86
- type: "Set",
87
- values: [...value].map((v) => serialize(v, seen, depth + 1))
88
- };
89
- if (value instanceof Promise) return "Promise";
90
- if (value instanceof Error) return {
91
- type: "Error",
92
- name: value.name,
93
- message: value.message
94
- };
95
- if (typeof Node !== "undefined" && value instanceof Node && value instanceof Element) {
96
- const attrs = {};
97
- for (const attr of value.attributes) attrs[attr.name] = attr.value;
98
- return {
99
- type: "dom",
100
- tagName: value.tagName.toLowerCase(),
101
- attrs
102
- };
103
- }
104
- return {
105
- type: "class",
106
- name: ctorName
107
- };
108
- }
109
- const result = {};
110
- for (const key of Object.keys(value)) result[key] = serialize(value[key], seen, depth + 1);
111
- return result;
112
- }
113
- function describeValue(value) {
114
- return serialize(value, /* @__PURE__ */ new WeakSet(), 0);
115
- }
116
- //#endregion
117
- //#region src/client/utils/sanitize-differences.ts
118
- function sanitizeDifferences(diffs) {
119
- if (!Array.isArray(diffs)) return false;
120
- return diffs.map((diff) => ({
121
- pathString: diff.pathString,
122
- diffType: diff.diffType,
123
- prevValue: describeValue(diff.prevValue),
124
- nextValue: describeValue(diff.nextValue)
125
- }));
126
- }
127
- //#endregion
128
- //#region src/client/utils/sanitize-reason.ts
129
- function sanitizeReason(reason) {
130
- return {
131
- propsDifferences: sanitizeDifferences(reason.propsDifferences),
132
- stateDifferences: sanitizeDifferences(reason.stateDifferences),
133
- hookDifferences: sanitizeDifferences(reason.hookDifferences)
134
- };
135
- }
136
- //#endregion
137
- //#region src/client/index.ts
138
- const DEFAULT_URL = "http://localhost:4649";
139
- const PREFIX_STYLE = "color: #38bdf8; font-weight: bold";
140
- const RESET_STYLE = "color: inherit; font-weight: normal";
141
- function log(message) {
142
- console.log(`%c[WDYR MCP]%c ${message}`, PREFIX_STYLE, RESET_STYLE);
143
- }
144
- function patchDevToolsHook(onCommit) {
145
- if (!globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__) globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
146
- supportsFiber: true,
147
- inject() {},
148
- onCommitFiberRoot() {},
149
- onCommitFiberUnmount() {}
150
- };
151
- const hook = globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__;
152
- const original = hook.onCommitFiberRoot.bind(hook);
153
- hook.onCommitFiberRoot = (...args) => {
154
- onCommit();
155
- return original(...args);
156
- };
157
- }
158
- function serializeConfig(opts) {
159
- const config = {};
160
- if (opts.include) config.include = opts.include.map((r) => r.source);
161
- if (opts.exclude) config.exclude = opts.exclude.map((r) => r.source);
162
- if (opts.trackAllPureComponents != null) config.trackAllPureComponents = opts.trackAllPureComponents;
163
- if (opts.trackHooks != null) config.trackHooks = opts.trackHooks;
164
- if (opts.trackExtraHooks) config.trackExtraHooks = opts.trackExtraHooks.map(([, name]) => name);
165
- if (opts.logOnDifferentValues != null) config.logOnDifferentValues = opts.logOnDifferentValues;
166
- if (opts.logOwnerReasons != null) config.logOwnerReasons = opts.logOwnerReasons;
167
- return config;
168
- }
169
- function buildOptions(opts) {
170
- const { wsUrl: _wsUrl, projectId: _projectId, notifier: userNotifier, ...wdyrOpts } = opts ?? {};
171
- const url = _wsUrl ?? DEFAULT_URL;
172
- const projectId = _projectId ?? globalThis.location?.origin ?? "default";
173
- let commitId = 0;
174
- patchDevToolsHook(() => {
175
- commitId++;
176
- });
177
- const socket = (0, socket_io_client.io)(url, {
178
- reconnection: true,
179
- reconnectionDelay: 1e3,
180
- reconnectionDelayMax: 3e4,
181
- transports: ["websocket"]
182
- });
183
- socket.on("connect", () => {
184
- log(`Connected to ${url}`);
185
- if (opts) socket.emit("config", serializeConfig(opts), projectId);
186
- });
187
- socket.on("disconnect", () => {
188
- log("Disconnected, reconnecting...");
189
- });
190
- let pendingBatch = null;
191
- let flushScheduled = false;
192
- function flushBatch() {
193
- flushScheduled = false;
194
- if (!pendingBatch || pendingBatch.reports.length === 0) return;
195
- socket.emit("render-batch", pendingBatch.reports, projectId, pendingBatch.commitId);
196
- pendingBatch = null;
197
- }
198
- return {
199
- ...wdyrOpts,
200
- notifier(info) {
201
- const report = {
202
- displayName: info.displayName,
203
- reason: sanitizeReason(info.reason),
204
- hookName: info.hookName
205
- };
206
- if (pendingBatch && pendingBatch.commitId === commitId) pendingBatch.reports.push(report);
207
- else {
208
- if (pendingBatch) flushBatch();
209
- pendingBatch = {
210
- commitId,
211
- reports: [report]
212
- };
213
- }
214
- if (!flushScheduled) {
215
- flushScheduled = true;
216
- queueMicrotask(flushBatch);
217
- }
218
- if (userNotifier) userNotifier(info);
219
- }
220
- };
221
- }
222
- //#endregion
223
- exports.buildOptions = buildOptions;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`socket.io-client`),l=require(`error-stack-parser`);l=s(l);const u=[`whyDidYouRender`,`react-dom`,`react.development`,`react.production`,`scheduler.`,`installHook`,`console.`],d=[`trackHookChanges`,`WDYRFunctionalComponent`,`Object.notifier`,`notifier`,`console.trace`];function f(e){return u.some(t=>e.includes(t))}function p(e){return d.some(t=>e===t)}function m(e){return e.replace(/WDYR$/,``)}function h(e){let t=e.startsWith(`new `)?e.slice(4):e,n=t.lastIndexOf(`.`);return m(n>=0?t.slice(n+1):t)}function g(e){return/^use[A-Z]/.test(e)}function _(e){let t;try{t=l.default.parse(e)}catch{return[]}let n=[];for(let e of t){let t=e.fileName??``;if(!t||f(t))continue;let r=e.functionName;if(!r||p(r))continue;let i=h(r);i&&n.push({type:g(i)?`hook`:`component`,name:i,location:{path:t,line:e.lineNumber??0}})}return n}const v=Symbol.for(`react.element`),y=Symbol.for(`react.transitional.element`),b=Symbol.for(`react.memo`),x=Symbol.for(`react.forward_ref`);function S(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.$$typeof===v||t.$$typeof===y||t.$$typeof===60103}function C(e){let t=!1,n=!1,r=e;for(let e=0;e<5&&!(typeof r!=`object`||!r);e++){let e=r;if(e.$$typeof===b)t=!0,r=e.type;else if(e.$$typeof===x)n=!0,r=e.render;else break}let i=`Unknown`;return typeof r==`string`?i=r:typeof r==`function`&&(i=r.displayName||r.name||`Anonymous`),{name:i,memo:t,forwardRef:n}}function w(e,t,n){let r=C(e.type),i={};if(e.props&&typeof e.props==`object`)for(let r of Object.keys(e.props))r!==`children`&&(i[r]=T(e.props[r],t,n+1));return{type:`react-node`,component:r,props:i}}function T(e,t,n){if(e==null)return null;if(typeof e==`function`)return{type:`function`,name:e.name||`anonymous`};if(typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isNaN(e)?`NaN`:Number.isFinite(e)?Object.is(e,-0)?`-0`:e:e>0?`Infinity`:`-Infinity`;if(typeof e==`string`)return e;if(typeof e==`bigint`||typeof e==`symbol`)return e.toString();if(t.has(e))return`[Circular]`;if(n>=8)return`[MaxDepth]`;if(t.add(e),S(e))return w(e,t,n);if(Array.isArray(e))return e.map(e=>T(e,t,n+1));let r=Object.getPrototypeOf(e)?.constructor?.name;if(r&&r!==`Object`){if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return String(e);if(e instanceof Map){let r={};for(let[i,a]of e.entries())r[String(i)]=T(a,t,n+1);return{type:`Map`,entries:r}}if(e instanceof Set)return{type:`Set`,values:[...e].map(e=>T(e,t,n+1))};if(e instanceof Promise)return`Promise`;if(e instanceof Error)return{type:`Error`,name:e.name,message:e.message};if(typeof Node<`u`&&e instanceof Node&&e instanceof Element){let t={};for(let n of e.attributes)t[n.name]=n.value;return{type:`dom`,tagName:e.tagName.toLowerCase(),attrs:t}}return{type:`class`,name:r}}let i={};for(let r of Object.keys(e))i[r]=T(e[r],t,n+1);return i}function E(e){return T(e,new WeakSet,0)}function D(e){return Array.isArray(e)?e.map(e=>({pathString:e.pathString,diffType:e.diffType,prevValue:E(e.prevValue),nextValue:E(e.nextValue)})):!1}function O(e){return{propsDifferences:D(e.propsDifferences),stateDifferences:D(e.stateDifferences),hookDifferences:D(e.hookDifferences)}}function k(e){console.log(`%c[WDYR MCP]%c ${e}`,`color: #38bdf8; font-weight: bold`,`color: inherit; font-weight: normal`)}function A(e){globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__||(globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__={supportsFiber:!0,inject(){},onCommitFiberRoot(){},onCommitFiberUnmount(){}});let t=globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__,n=t.onCommitFiberRoot.bind(t);t.onCommitFiberRoot=(...t)=>(e(),n(...t))}function j(e){let t={};return e.include&&(t.include=e.include.map(e=>e.source)),e.exclude&&(t.exclude=e.exclude.map(e=>e.source)),e.trackAllPureComponents!=null&&(t.trackAllPureComponents=e.trackAllPureComponents),e.trackHooks!=null&&(t.trackHooks=e.trackHooks),e.trackExtraHooks&&(t.trackExtraHooks=e.trackExtraHooks.map(([,e])=>e)),e.logOnDifferentValues!=null&&(t.logOnDifferentValues=e.logOnDifferentValues),e.logOwnerReasons!=null&&(t.logOwnerReasons=e.logOwnerReasons),t}function M(e){let{wsUrl:t,projectId:n,notifier:r,...i}=e??{},a=t??`http://localhost:4649`,o=n??globalThis.location?.origin??`default`,s=0;A(()=>{s++});let l=(0,c.io)(a,{reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,transports:[`websocket`]});l.on(`connect`,()=>{k(`Connected to ${a}`),e&&l.emit(`config`,j(e),o)}),l.on(`disconnect`,()=>{k(`Disconnected, reconnecting...`)});let u=null,d=!1;function f(){d=!1,!(!u||u.reports.length===0)&&(l.emit(`render-batch`,u.reports,o,u.commitId),u=null)}return{...i,notifier(e){let t=_(Error()),n={displayName:e.displayName,reason:O(e.reason),hookName:e.hookName,...t.length>0&&{stackFrames:t}};u&&u.commitId===s?u.reports.push(n):(u&&f(),u={commitId:s,reports:[n]}),d||(d=!0,queueMicrotask(f)),r&&r(e)}}}exports.buildOptions=M;
@@ -1,222 +1 @@
1
- import { io } from "socket.io-client";
2
- //#region src/client/utils/describe-value.ts
3
- const MAX_DEPTH = 8;
4
- const REACT_ELEMENT_SYMBOL = Symbol.for("react.element");
5
- const REACT_TRANSITIONAL_ELEMENT_SYMBOL = Symbol.for("react.transitional.element");
6
- const REACT_MEMO_TYPE = Symbol.for("react.memo");
7
- const REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
8
- function isReactElement(value) {
9
- if (typeof value !== "object" || value === null) return false;
10
- const v = value;
11
- return v.$$typeof === REACT_ELEMENT_SYMBOL || v.$$typeof === REACT_TRANSITIONAL_ELEMENT_SYMBOL || v.$$typeof === 60103;
12
- }
13
- function resolveComponentInfo(type) {
14
- let memo = false;
15
- let forwardRef = false;
16
- let current = type;
17
- for (let i = 0; i < 5; i++) {
18
- if (typeof current !== "object" || current === null) break;
19
- const wrapper = current;
20
- if (wrapper.$$typeof === REACT_MEMO_TYPE) {
21
- memo = true;
22
- current = wrapper.type;
23
- } else if (wrapper.$$typeof === REACT_FORWARD_REF_TYPE) {
24
- forwardRef = true;
25
- current = wrapper.render;
26
- } else break;
27
- }
28
- let name = "Unknown";
29
- if (typeof current === "string") name = current;
30
- else if (typeof current === "function") name = current.displayName || current.name || "Anonymous";
31
- return {
32
- name,
33
- memo,
34
- forwardRef
35
- };
36
- }
37
- function serializeReactElement(el, seen, depth) {
38
- const component = resolveComponentInfo(el.type);
39
- const props = {};
40
- if (el.props && typeof el.props === "object") for (const key of Object.keys(el.props)) {
41
- if (key === "children") continue;
42
- props[key] = serialize(el.props[key], seen, depth + 1);
43
- }
44
- return {
45
- type: "react-node",
46
- component,
47
- props
48
- };
49
- }
50
- function serialize(value, seen, depth) {
51
- if (value === null) return null;
52
- if (value === void 0) return null;
53
- if (typeof value === "function") return {
54
- type: "function",
55
- name: value.name || "anonymous"
56
- };
57
- if (typeof value === "boolean") return value;
58
- if (typeof value === "number") {
59
- if (Number.isNaN(value)) return "NaN";
60
- if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
61
- if (Object.is(value, -0)) return "-0";
62
- return value;
63
- }
64
- if (typeof value === "string") return value;
65
- if (typeof value === "bigint") return value.toString();
66
- if (typeof value === "symbol") return value.toString();
67
- if (seen.has(value)) return "[Circular]";
68
- if (depth >= MAX_DEPTH) return "[MaxDepth]";
69
- seen.add(value);
70
- if (isReactElement(value)) return serializeReactElement(value, seen, depth);
71
- if (Array.isArray(value)) return value.map((item) => serialize(item, seen, depth + 1));
72
- const ctorName = Object.getPrototypeOf(value)?.constructor?.name;
73
- if (ctorName && ctorName !== "Object") {
74
- if (value instanceof Date) return value.toISOString();
75
- if (value instanceof RegExp) return String(value);
76
- if (value instanceof Map) {
77
- const entries = {};
78
- for (const [k, v] of value.entries()) entries[String(k)] = serialize(v, seen, depth + 1);
79
- return {
80
- type: "Map",
81
- entries
82
- };
83
- }
84
- if (value instanceof Set) return {
85
- type: "Set",
86
- values: [...value].map((v) => serialize(v, seen, depth + 1))
87
- };
88
- if (value instanceof Promise) return "Promise";
89
- if (value instanceof Error) return {
90
- type: "Error",
91
- name: value.name,
92
- message: value.message
93
- };
94
- if (typeof Node !== "undefined" && value instanceof Node && value instanceof Element) {
95
- const attrs = {};
96
- for (const attr of value.attributes) attrs[attr.name] = attr.value;
97
- return {
98
- type: "dom",
99
- tagName: value.tagName.toLowerCase(),
100
- attrs
101
- };
102
- }
103
- return {
104
- type: "class",
105
- name: ctorName
106
- };
107
- }
108
- const result = {};
109
- for (const key of Object.keys(value)) result[key] = serialize(value[key], seen, depth + 1);
110
- return result;
111
- }
112
- function describeValue(value) {
113
- return serialize(value, /* @__PURE__ */ new WeakSet(), 0);
114
- }
115
- //#endregion
116
- //#region src/client/utils/sanitize-differences.ts
117
- function sanitizeDifferences(diffs) {
118
- if (!Array.isArray(diffs)) return false;
119
- return diffs.map((diff) => ({
120
- pathString: diff.pathString,
121
- diffType: diff.diffType,
122
- prevValue: describeValue(diff.prevValue),
123
- nextValue: describeValue(diff.nextValue)
124
- }));
125
- }
126
- //#endregion
127
- //#region src/client/utils/sanitize-reason.ts
128
- function sanitizeReason(reason) {
129
- return {
130
- propsDifferences: sanitizeDifferences(reason.propsDifferences),
131
- stateDifferences: sanitizeDifferences(reason.stateDifferences),
132
- hookDifferences: sanitizeDifferences(reason.hookDifferences)
133
- };
134
- }
135
- //#endregion
136
- //#region src/client/index.ts
137
- const DEFAULT_URL = "http://localhost:4649";
138
- const PREFIX_STYLE = "color: #38bdf8; font-weight: bold";
139
- const RESET_STYLE = "color: inherit; font-weight: normal";
140
- function log(message) {
141
- console.log(`%c[WDYR MCP]%c ${message}`, PREFIX_STYLE, RESET_STYLE);
142
- }
143
- function patchDevToolsHook(onCommit) {
144
- if (!globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__) globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
145
- supportsFiber: true,
146
- inject() {},
147
- onCommitFiberRoot() {},
148
- onCommitFiberUnmount() {}
149
- };
150
- const hook = globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__;
151
- const original = hook.onCommitFiberRoot.bind(hook);
152
- hook.onCommitFiberRoot = (...args) => {
153
- onCommit();
154
- return original(...args);
155
- };
156
- }
157
- function serializeConfig(opts) {
158
- const config = {};
159
- if (opts.include) config.include = opts.include.map((r) => r.source);
160
- if (opts.exclude) config.exclude = opts.exclude.map((r) => r.source);
161
- if (opts.trackAllPureComponents != null) config.trackAllPureComponents = opts.trackAllPureComponents;
162
- if (opts.trackHooks != null) config.trackHooks = opts.trackHooks;
163
- if (opts.trackExtraHooks) config.trackExtraHooks = opts.trackExtraHooks.map(([, name]) => name);
164
- if (opts.logOnDifferentValues != null) config.logOnDifferentValues = opts.logOnDifferentValues;
165
- if (opts.logOwnerReasons != null) config.logOwnerReasons = opts.logOwnerReasons;
166
- return config;
167
- }
168
- function buildOptions(opts) {
169
- const { wsUrl: _wsUrl, projectId: _projectId, notifier: userNotifier, ...wdyrOpts } = opts ?? {};
170
- const url = _wsUrl ?? DEFAULT_URL;
171
- const projectId = _projectId ?? globalThis.location?.origin ?? "default";
172
- let commitId = 0;
173
- patchDevToolsHook(() => {
174
- commitId++;
175
- });
176
- const socket = io(url, {
177
- reconnection: true,
178
- reconnectionDelay: 1e3,
179
- reconnectionDelayMax: 3e4,
180
- transports: ["websocket"]
181
- });
182
- socket.on("connect", () => {
183
- log(`Connected to ${url}`);
184
- if (opts) socket.emit("config", serializeConfig(opts), projectId);
185
- });
186
- socket.on("disconnect", () => {
187
- log("Disconnected, reconnecting...");
188
- });
189
- let pendingBatch = null;
190
- let flushScheduled = false;
191
- function flushBatch() {
192
- flushScheduled = false;
193
- if (!pendingBatch || pendingBatch.reports.length === 0) return;
194
- socket.emit("render-batch", pendingBatch.reports, projectId, pendingBatch.commitId);
195
- pendingBatch = null;
196
- }
197
- return {
198
- ...wdyrOpts,
199
- notifier(info) {
200
- const report = {
201
- displayName: info.displayName,
202
- reason: sanitizeReason(info.reason),
203
- hookName: info.hookName
204
- };
205
- if (pendingBatch && pendingBatch.commitId === commitId) pendingBatch.reports.push(report);
206
- else {
207
- if (pendingBatch) flushBatch();
208
- pendingBatch = {
209
- commitId,
210
- reports: [report]
211
- };
212
- }
213
- if (!flushScheduled) {
214
- flushScheduled = true;
215
- queueMicrotask(flushBatch);
216
- }
217
- if (userNotifier) userNotifier(info);
218
- }
219
- };
220
- }
221
- //#endregion
222
- export { buildOptions };
1
+ import{io as e}from"socket.io-client";import t from"error-stack-parser";const n=[`whyDidYouRender`,`react-dom`,`react.development`,`react.production`,`scheduler.`,`installHook`,`console.`],r=[`trackHookChanges`,`WDYRFunctionalComponent`,`Object.notifier`,`notifier`,`console.trace`];function i(e){return n.some(t=>e.includes(t))}function a(e){return r.some(t=>e===t)}function o(e){return e.replace(/WDYR$/,``)}function s(e){let t=e.startsWith(`new `)?e.slice(4):e,n=t.lastIndexOf(`.`);return o(n>=0?t.slice(n+1):t)}function c(e){return/^use[A-Z]/.test(e)}function l(e){let n;try{n=t.parse(e)}catch{return[]}let r=[];for(let e of n){let t=e.fileName??``;if(!t||i(t))continue;let n=e.functionName;if(!n||a(n))continue;let o=s(n);o&&r.push({type:c(o)?`hook`:`component`,name:o,location:{path:t,line:e.lineNumber??0}})}return r}const u=Symbol.for(`react.element`),d=Symbol.for(`react.transitional.element`),f=Symbol.for(`react.memo`),p=Symbol.for(`react.forward_ref`);function m(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.$$typeof===u||t.$$typeof===d||t.$$typeof===60103}function h(e){let t=!1,n=!1,r=e;for(let e=0;e<5&&!(typeof r!=`object`||!r);e++){let e=r;if(e.$$typeof===f)t=!0,r=e.type;else if(e.$$typeof===p)n=!0,r=e.render;else break}let i=`Unknown`;return typeof r==`string`?i=r:typeof r==`function`&&(i=r.displayName||r.name||`Anonymous`),{name:i,memo:t,forwardRef:n}}function g(e,t,n){let r=h(e.type),i={};if(e.props&&typeof e.props==`object`)for(let r of Object.keys(e.props))r!==`children`&&(i[r]=_(e.props[r],t,n+1));return{type:`react-node`,component:r,props:i}}function _(e,t,n){if(e==null)return null;if(typeof e==`function`)return{type:`function`,name:e.name||`anonymous`};if(typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isNaN(e)?`NaN`:Number.isFinite(e)?Object.is(e,-0)?`-0`:e:e>0?`Infinity`:`-Infinity`;if(typeof e==`string`)return e;if(typeof e==`bigint`||typeof e==`symbol`)return e.toString();if(t.has(e))return`[Circular]`;if(n>=8)return`[MaxDepth]`;if(t.add(e),m(e))return g(e,t,n);if(Array.isArray(e))return e.map(e=>_(e,t,n+1));let r=Object.getPrototypeOf(e)?.constructor?.name;if(r&&r!==`Object`){if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return String(e);if(e instanceof Map){let r={};for(let[i,a]of e.entries())r[String(i)]=_(a,t,n+1);return{type:`Map`,entries:r}}if(e instanceof Set)return{type:`Set`,values:[...e].map(e=>_(e,t,n+1))};if(e instanceof Promise)return`Promise`;if(e instanceof Error)return{type:`Error`,name:e.name,message:e.message};if(typeof Node<`u`&&e instanceof Node&&e instanceof Element){let t={};for(let n of e.attributes)t[n.name]=n.value;return{type:`dom`,tagName:e.tagName.toLowerCase(),attrs:t}}return{type:`class`,name:r}}let i={};for(let r of Object.keys(e))i[r]=_(e[r],t,n+1);return i}function v(e){return _(e,new WeakSet,0)}function y(e){return Array.isArray(e)?e.map(e=>({pathString:e.pathString,diffType:e.diffType,prevValue:v(e.prevValue),nextValue:v(e.nextValue)})):!1}function b(e){return{propsDifferences:y(e.propsDifferences),stateDifferences:y(e.stateDifferences),hookDifferences:y(e.hookDifferences)}}function x(e){console.log(`%c[WDYR MCP]%c ${e}`,`color: #38bdf8; font-weight: bold`,`color: inherit; font-weight: normal`)}function S(e){globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__||(globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__={supportsFiber:!0,inject(){},onCommitFiberRoot(){},onCommitFiberUnmount(){}});let t=globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__,n=t.onCommitFiberRoot.bind(t);t.onCommitFiberRoot=(...t)=>(e(),n(...t))}function C(e){let t={};return e.include&&(t.include=e.include.map(e=>e.source)),e.exclude&&(t.exclude=e.exclude.map(e=>e.source)),e.trackAllPureComponents!=null&&(t.trackAllPureComponents=e.trackAllPureComponents),e.trackHooks!=null&&(t.trackHooks=e.trackHooks),e.trackExtraHooks&&(t.trackExtraHooks=e.trackExtraHooks.map(([,e])=>e)),e.logOnDifferentValues!=null&&(t.logOnDifferentValues=e.logOnDifferentValues),e.logOwnerReasons!=null&&(t.logOwnerReasons=e.logOwnerReasons),t}function w(t){let{wsUrl:n,projectId:r,notifier:i,...a}=t??{},o=n??`http://localhost:4649`,s=r??globalThis.location?.origin??`default`,c=0;S(()=>{c++});let u=e(o,{reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,transports:[`websocket`]});u.on(`connect`,()=>{x(`Connected to ${o}`),t&&u.emit(`config`,C(t),s)}),u.on(`disconnect`,()=>{x(`Disconnected, reconnecting...`)});let d=null,f=!1;function p(){f=!1,!(!d||d.reports.length===0)&&(u.emit(`render-batch`,d.reports,s,d.commitId),d=null)}return{...a,notifier(e){let t=l(Error()),n={displayName:e.displayName,reason:b(e.reason),hookName:e.hookName,...t.length>0&&{stackFrames:t}};d&&d.commitId===c?d.reports.push(n):(d&&p(),d={commitId:c,reports:[n]}),f||(f=!0,queueMicrotask(p)),i&&i(e)}}}export{w as buildOptions};
@@ -1,761 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
- import { z } from "zod";
5
- import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
6
- import { homedir } from "node:os";
7
- import { join } from "node:path";
8
- import xxhash from "xxhash-wasm";
9
- import http from "node:http";
10
- import { Server } from "socket.io";
11
- //#region src/server/store/utils/value-dict.ts
12
- const DICT_KEY = "@@dict";
13
- const REF_PREFIX = "@@ref:";
14
- let h64ToString;
15
- const ready = xxhash().then((api) => {
16
- h64ToString = api.h64ToString;
17
- });
18
- function ensureReady() {
19
- return ready;
20
- }
21
- function hashValue(value) {
22
- return h64ToString(JSON.stringify(value));
23
- }
24
- function shouldDehydrate(value) {
25
- return typeof value === "object" && value !== null;
26
- }
27
- function dehydrateDiffs(diffs, dict) {
28
- if (!diffs) return false;
29
- return diffs.map((d) => {
30
- let { prevValue, nextValue } = d;
31
- if (shouldDehydrate(prevValue)) {
32
- const hash = hashValue(prevValue);
33
- dict[hash] ??= prevValue;
34
- prevValue = `${REF_PREFIX}${hash}`;
35
- }
36
- if (shouldDehydrate(nextValue)) {
37
- const hash = hashValue(nextValue);
38
- dict[hash] ??= nextValue;
39
- nextValue = `${REF_PREFIX}${hash}`;
40
- }
41
- return prevValue === d.prevValue && nextValue === d.nextValue ? d : {
42
- ...d,
43
- prevValue,
44
- nextValue
45
- };
46
- });
47
- }
48
- function dehydrate(render, dict) {
49
- const { propsDifferences, stateDifferences, hookDifferences } = render.reason;
50
- const newProps = dehydrateDiffs(propsDifferences, dict);
51
- const newState = dehydrateDiffs(stateDifferences, dict);
52
- const newHooks = dehydrateDiffs(hookDifferences, dict);
53
- if (newProps === propsDifferences && newState === stateDifferences && newHooks === hookDifferences) return render;
54
- return {
55
- ...render,
56
- reason: {
57
- propsDifferences: newProps,
58
- stateDifferences: newState,
59
- hookDifferences: newHooks
60
- }
61
- };
62
- }
63
- function hydrateDiffs(diffs, dict) {
64
- if (!diffs) return false;
65
- return diffs.map((d) => {
66
- let { prevValue, nextValue } = d;
67
- if (typeof prevValue === "string" && prevValue.startsWith(REF_PREFIX)) prevValue = dict[prevValue.slice(6)] ?? prevValue;
68
- if (typeof nextValue === "string" && nextValue.startsWith(REF_PREFIX)) nextValue = dict[nextValue.slice(6)] ?? nextValue;
69
- return prevValue === d.prevValue && nextValue === d.nextValue ? d : {
70
- ...d,
71
- prevValue,
72
- nextValue
73
- };
74
- });
75
- }
76
- function hydrate(render, dict) {
77
- const { propsDifferences, stateDifferences, hookDifferences } = render.reason;
78
- const newProps = hydrateDiffs(propsDifferences, dict);
79
- const newState = hydrateDiffs(stateDifferences, dict);
80
- const newHooks = hydrateDiffs(hookDifferences, dict);
81
- if (newProps === propsDifferences && newState === stateDifferences && newHooks === hookDifferences) return render;
82
- return {
83
- ...render,
84
- reason: {
85
- propsDifferences: newProps,
86
- stateDifferences: newState,
87
- hookDifferences: newHooks
88
- }
89
- };
90
- }
91
- //#endregion
92
- //#region src/server/store/utils/read-jsonl.ts
93
- function readJsonl(file) {
94
- if (!existsSync(file)) return [];
95
- const lines = readFileSync(file, "utf-8").split("\n").filter(Boolean);
96
- if (lines.length === 0) return [];
97
- let dict;
98
- let startIdx = 0;
99
- const first = JSON.parse(lines[0]);
100
- if ("@@dict" in first) {
101
- dict = first[DICT_KEY];
102
- startIdx = 1;
103
- }
104
- const renders = lines.slice(startIdx).map((l) => JSON.parse(l));
105
- if (!dict) return renders;
106
- return renders.map((r) => hydrate(r, dict));
107
- }
108
- //#endregion
109
- //#region src/server/store/utils/sanitize-project-id.ts
110
- function sanitizeProjectId(projectId) {
111
- return projectId.replaceAll(/[^a-zA-Z0-9_.-]/g, "_");
112
- }
113
- //#endregion
114
- //#region src/server/store/utils/to-result.ts
115
- function toResult(stored) {
116
- return {
117
- project: stored.projectId,
118
- displayName: stored.displayName,
119
- reason: stored.reason,
120
- ...stored.hookName != null && { hookName: stored.hookName },
121
- ...stored.commitId != null && { commitId: stored.commitId },
122
- ...stored.timestamp != null && { timestamp: stored.timestamp }
123
- };
124
- }
125
- //#endregion
126
- //#region src/server/store/render-store.ts
127
- const FLUSH_DELAY_MS = 200;
128
- const NOCOMMIT = "nocommit";
129
- var RenderStore = class {
130
- dir;
131
- buffers = /* @__PURE__ */ new Map();
132
- timers = /* @__PURE__ */ new Map();
133
- dicts = /* @__PURE__ */ new Map();
134
- bufferMeta = /* @__PURE__ */ new Map();
135
- trackedComponents = /* @__PURE__ */ new Map();
136
- wdyrConfigs = /* @__PURE__ */ new Map();
137
- constructor(dir) {
138
- this.dir = dir ?? join(homedir(), ".wdyr-mcp", "renders");
139
- mkdirSync(this.dir, { recursive: true });
140
- }
141
- addRender(report, projectId, commitId) {
142
- const stored = {
143
- ...report,
144
- projectId,
145
- timestamp: Date.now(),
146
- ...commitId != null && { commitId }
147
- };
148
- const bk = this.bufferKey(projectId, commitId);
149
- let buf = this.buffers.get(bk);
150
- if (!buf) {
151
- buf = [];
152
- this.buffers.set(bk, buf);
153
- this.bufferMeta.set(bk, {
154
- projectId,
155
- commitId
156
- });
157
- }
158
- buf.push(stored);
159
- const existing = this.timers.get(bk);
160
- if (existing) clearTimeout(existing);
161
- this.timers.set(bk, setTimeout(() => {
162
- this.flushAsync(projectId, commitId).catch((err) => console.error(`[wdyr-mcp] flush error for ${bk}:`, err));
163
- }, FLUSH_DELAY_MS));
164
- }
165
- async flushAsync(projectId, commitId) {
166
- await ensureReady();
167
- this.flush(projectId, commitId);
168
- }
169
- flush(projectId, commitId) {
170
- if (projectId != null && commitId !== void 0) this.flushBuffer(this.bufferKey(projectId, commitId));
171
- else if (projectId != null) for (const bk of this.bufferKeysForProject(projectId)) this.flushBuffer(bk);
172
- else for (const bk of [...this.buffers.keys()]) this.flushBuffer(bk);
173
- }
174
- flushBuffer(bk) {
175
- const buf = this.buffers.get(bk);
176
- if (!buf || buf.length === 0) return;
177
- const meta = this.bufferMeta.get(bk);
178
- if (!meta) return;
179
- let dict = this.dicts.get(bk);
180
- if (!dict) {
181
- dict = {};
182
- this.dicts.set(bk, dict);
183
- }
184
- const dehydrated = buf.map((r) => dehydrate(r, dict));
185
- const file = this.commitFile(meta.projectId, meta.commitId);
186
- const existingLines = this.readDataLines(file);
187
- const newLines = dehydrated.map((r) => JSON.stringify(r));
188
- const allDataLines = [...existingLines, ...newLines];
189
- writeFileSync(file, `${(Object.keys(dict).length > 0 ? [JSON.stringify({ [DICT_KEY]: dict }), ...allDataLines] : allDataLines).join("\n")}\n`);
190
- buf.length = 0;
191
- const timer = this.timers.get(bk);
192
- if (timer) {
193
- clearTimeout(timer);
194
- this.timers.delete(bk);
195
- }
196
- }
197
- readDataLines(file) {
198
- if (!existsSync(file)) return [];
199
- return readFileSync(file, "utf-8").split("\n").filter((line) => {
200
- if (!line) return false;
201
- if (line.startsWith(`{"@@dict"`)) return false;
202
- return true;
203
- });
204
- }
205
- getAllRenders(projectId) {
206
- this.flush(projectId);
207
- if (projectId) return this.projectFiles(projectId).flatMap((f) => readJsonl(join(this.dir, f)).map(toResult));
208
- return this.jsonlFiles().flatMap((f) => readJsonl(join(this.dir, f)).map(toResult));
209
- }
210
- getRendersByComponent(componentName, projectId) {
211
- return this.getAllRenders(projectId).filter((r) => r.displayName === componentName);
212
- }
213
- clearRenders(projectId) {
214
- if (projectId) {
215
- for (const bk of this.bufferKeysForProject(projectId)) {
216
- this.buffers.delete(bk);
217
- this.dicts.delete(bk);
218
- this.bufferMeta.delete(bk);
219
- const timer = this.timers.get(bk);
220
- if (timer) {
221
- clearTimeout(timer);
222
- this.timers.delete(bk);
223
- }
224
- }
225
- for (const f of this.projectFiles(projectId)) unlinkSync(join(this.dir, f));
226
- } else {
227
- for (const [, timer] of this.timers) clearTimeout(timer);
228
- this.buffers.clear();
229
- this.timers.clear();
230
- this.dicts.clear();
231
- this.bufferMeta.clear();
232
- for (const f of this.jsonlFiles()) unlinkSync(join(this.dir, f));
233
- }
234
- }
235
- clearRendersByComponent(component, projectId) {
236
- this.flush(projectId);
237
- const files = projectId ? this.projectFiles(projectId) : this.jsonlFiles();
238
- let removed = 0;
239
- for (const f of files) {
240
- const filePath = join(this.dir, f);
241
- const renders = readJsonl(filePath);
242
- const before = renders.length;
243
- const remaining = renders.filter((r) => r.displayName !== component);
244
- removed += before - remaining.length;
245
- if (remaining.length === 0) {
246
- unlinkSync(filePath);
247
- this.clearBuffersForFile(f);
248
- } else if (remaining.length < before) {
249
- this.rewriteFile(filePath, remaining);
250
- this.clearBuffersForFile(f);
251
- }
252
- }
253
- return removed;
254
- }
255
- clearRendersByCommit(beforeCommit, projectId) {
256
- this.flush(projectId);
257
- const files = projectId ? this.projectFiles(projectId) : this.jsonlFiles();
258
- let deleted = 0;
259
- for (const f of files) {
260
- const parsed = this.parseFilename(f);
261
- if (parsed?.commitId != null && parsed.commitId < beforeCommit) {
262
- unlinkSync(join(this.dir, f));
263
- this.clearBuffersForFile(f);
264
- deleted++;
265
- }
266
- }
267
- return deleted;
268
- }
269
- getProjects() {
270
- this.flush();
271
- const projects = /* @__PURE__ */ new Set();
272
- const seen = /* @__PURE__ */ new Set();
273
- for (const f of this.jsonlFiles()) {
274
- const parsed = this.parseFilename(f);
275
- if (!parsed) continue;
276
- if (seen.has(parsed.projectSanitized)) continue;
277
- seen.add(parsed.projectSanitized);
278
- const lines = readFileSync(join(this.dir, f), "utf-8").split("\n");
279
- for (const line of lines) {
280
- if (!line) continue;
281
- const obj = JSON.parse(line);
282
- if ("@@dict" in obj) continue;
283
- projects.add(obj.projectId);
284
- break;
285
- }
286
- }
287
- return [...projects];
288
- }
289
- getCommitIds(projectId) {
290
- this.flush(projectId);
291
- const files = projectId ? this.projectFiles(projectId) : this.jsonlFiles();
292
- const ids = /* @__PURE__ */ new Set();
293
- for (const f of files) {
294
- const parsed = this.parseFilename(f);
295
- if (parsed?.commitId != null) ids.add(parsed.commitId);
296
- }
297
- return [...ids].sort((a, b) => a - b);
298
- }
299
- getCommits(projectId) {
300
- this.flush(projectId);
301
- const files = projectId ? this.projectFiles(projectId) : this.jsonlFiles();
302
- const commits = [];
303
- for (const f of files) {
304
- const parsed = this.parseFilename(f);
305
- if (parsed?.commitId == null) continue;
306
- const renders = readJsonl(join(this.dir, f));
307
- if (renders.length === 0) continue;
308
- commits.push({
309
- commitId: parsed.commitId,
310
- timestamp: renders.find((r) => r.timestamp != null)?.timestamp ?? null,
311
- renderCount: renders.length,
312
- components: [...new Set(renders.map((r) => r.displayName))]
313
- });
314
- }
315
- return commits.sort((a, b) => a.commitId - b.commitId);
316
- }
317
- getRendersByCommit(commitId, projectId) {
318
- if (projectId) {
319
- this.flush(projectId, commitId);
320
- return readJsonl(this.commitFile(projectId, commitId)).map(toResult);
321
- }
322
- this.flush();
323
- const suffix = `_commit_${commitId}.jsonl`;
324
- return this.jsonlFiles().filter((f) => f.endsWith(suffix)).flatMap((f) => readJsonl(join(this.dir, f)).map(toResult));
325
- }
326
- getSummary(projectId) {
327
- const renders = this.getAllRenders(projectId);
328
- const summary = {};
329
- for (const r of renders) {
330
- summary[r.project] ??= {};
331
- const project = summary[r.project];
332
- project[r.displayName] ??= {
333
- count: 0,
334
- reasons: {
335
- props: 0,
336
- state: 0,
337
- hooks: 0
338
- }
339
- };
340
- const entry = project[r.displayName];
341
- entry.count++;
342
- if (Array.isArray(r.reason.propsDifferences)) entry.reasons.props++;
343
- if (Array.isArray(r.reason.stateDifferences)) entry.reasons.state++;
344
- if (Array.isArray(r.reason.hookDifferences)) entry.reasons.hooks++;
345
- }
346
- return summary;
347
- }
348
- getSummaryByCommit(projectId) {
349
- const renders = this.getAllRenders(projectId);
350
- const summary = {};
351
- for (const r of renders) {
352
- if (r.commitId == null) continue;
353
- summary[r.project] ??= {};
354
- summary[r.project][r.commitId] ??= {};
355
- const commit = summary[r.project][r.commitId];
356
- commit[r.displayName] ??= {
357
- count: 0,
358
- reasons: {
359
- props: 0,
360
- state: 0,
361
- hooks: 0
362
- }
363
- };
364
- const entry = commit[r.displayName];
365
- entry.count++;
366
- if (Array.isArray(r.reason.propsDifferences)) entry.reasons.props++;
367
- if (Array.isArray(r.reason.stateDifferences)) entry.reasons.state++;
368
- if (Array.isArray(r.reason.hookDifferences)) entry.reasons.hooks++;
369
- }
370
- return summary;
371
- }
372
- setTrackedComponents(components, projectId) {
373
- this.trackedComponents.set(projectId, components);
374
- }
375
- getTrackedComponents(projectId) {
376
- const result = {};
377
- const projects = projectId ? [projectId] : this.getProjects();
378
- for (const proj of projects) {
379
- const observed = [...new Set(this.getAllRenders(proj).map((r) => r.displayName))];
380
- result[proj] = {
381
- registered: this.trackedComponents.get(proj) ?? [],
382
- observed
383
- };
384
- }
385
- return result;
386
- }
387
- setWdyrConfig(config, projectId) {
388
- this.wdyrConfigs.set(projectId, config);
389
- }
390
- getWdyrConfig(projectId) {
391
- const result = {};
392
- if (projectId) {
393
- const config = this.wdyrConfigs.get(projectId);
394
- if (config) result[projectId] = config;
395
- } else for (const [proj, config] of this.wdyrConfigs) result[proj] = config;
396
- return result;
397
- }
398
- rewriteFile(filePath, renders) {
399
- writeFileSync(filePath, `${renders.map((r) => JSON.stringify(r)).join("\n")}\n`);
400
- }
401
- clearBuffersForFile(filename) {
402
- const parsed = this.parseFilename(filename);
403
- if (!parsed) return;
404
- for (const [bk, meta] of this.bufferMeta) {
405
- if (sanitizeProjectId(meta.projectId) !== parsed.projectSanitized) continue;
406
- if (!(parsed.commitId != null ? meta.commitId === parsed.commitId : meta.commitId == null)) continue;
407
- this.buffers.delete(bk);
408
- this.dicts.delete(bk);
409
- this.bufferMeta.delete(bk);
410
- const timer = this.timers.get(bk);
411
- if (timer) {
412
- clearTimeout(timer);
413
- this.timers.delete(bk);
414
- }
415
- }
416
- }
417
- bufferKey(projectId, commitId) {
418
- return `${projectId}\0${commitId ?? NOCOMMIT}`;
419
- }
420
- bufferKeysForProject(projectId) {
421
- const prefix = `${projectId}\0`;
422
- return [...this.buffers.keys()].filter((bk) => bk.startsWith(prefix));
423
- }
424
- commitFile(projectId, commitId) {
425
- const sanitized = sanitizeProjectId(projectId);
426
- const suffix = commitId != null ? `_commit_${commitId}` : `_${NOCOMMIT}`;
427
- return join(this.dir, `${sanitized}${suffix}.jsonl`);
428
- }
429
- projectFiles(projectId) {
430
- const prefix = sanitizeProjectId(projectId);
431
- return readdirSync(this.dir).filter((f) => f.startsWith(prefix) && f.endsWith(".jsonl"));
432
- }
433
- parseFilename(filename) {
434
- if (!filename.endsWith(".jsonl")) return null;
435
- const base = filename.slice(0, -6);
436
- const commitMatch = base.match(/^(.+)_commit_(\d+)$/);
437
- if (commitMatch) return {
438
- projectSanitized: commitMatch[1],
439
- commitId: Number(commitMatch[2])
440
- };
441
- const nocommitMatch = base.match(/^(.+)_nocommit$/);
442
- if (nocommitMatch) return { projectSanitized: nocommitMatch[1] };
443
- return { projectSanitized: base };
444
- }
445
- jsonlFiles() {
446
- return readdirSync(this.dir).filter((f) => f.endsWith(".jsonl"));
447
- }
448
- };
449
- //#endregion
450
- //#region src/server/store/index.ts
451
- const store = new RenderStore();
452
- //#endregion
453
- //#region src/server/tools/utils/resolve-project.ts
454
- /**
455
- * Resolves the project to use. If a project is explicitly given, use it.
456
- * If only one project exists, auto-select it. If multiple exist, return
457
- * a message asking the agent to disambiguate.
458
- */
459
- function resolveProject(project) {
460
- if (project) return { projectId: project };
461
- const projects = store.getProjects();
462
- if (projects.length === 0) return { projectId: void 0 };
463
- if (projects.length === 1) return { projectId: projects[0] };
464
- return {
465
- projectId: void 0,
466
- error: [
467
- "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).",
468
- "",
469
- "Active projects:",
470
- ...projects.map((p) => `- ${p}`)
471
- ].join("\n")
472
- };
473
- }
474
- //#endregion
475
- //#region src/server/tools/utils/text-result.ts
476
- function textResult(text) {
477
- return { content: [{
478
- type: "text",
479
- text
480
- }] };
481
- }
482
- //#endregion
483
- //#region src/server/tools/clear-renders.ts
484
- function register$6(server) {
485
- server.registerTool("clear_renders", {
486
- title: "Clear Renders",
487
- 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.",
488
- inputSchema: {
489
- project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect."),
490
- component: z.string().optional().describe("Clear only renders for this component (by displayName)."),
491
- beforeCommit: z.number().optional().describe("Clear all renders from commits with an ID strictly less than this value.")
492
- }
493
- }, async ({ project, component, beforeCommit }) => {
494
- const resolved = resolveProject(project);
495
- if (resolved.error) return textResult(resolved.error);
496
- if (component) return textResult(`Cleared ${store.clearRendersByComponent(component, resolved.projectId)} render(s) for component "${component}".`);
497
- if (beforeCommit != null) return textResult(`Cleared renders from ${store.clearRendersByCommit(beforeCommit, resolved.projectId)} commit file(s) before commit #${beforeCommit}.`);
498
- store.clearRenders(resolved.projectId);
499
- return textResult(resolved.projectId ? `Render data cleared for ${resolved.projectId}.` : "All render data cleared.");
500
- });
501
- }
502
- //#endregion
503
- //#region src/server/tools/get-commits.ts
504
- function register$5(server) {
505
- server.registerTool("get_commits", {
506
- title: "Get Commits",
507
- 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.",
508
- inputSchema: { project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.") }
509
- }, async ({ project }) => {
510
- const resolved = resolveProject(project);
511
- if (resolved.error) return textResult(resolved.error);
512
- const commits = store.getCommits(resolved.projectId);
513
- if (commits.length === 0) return textResult("No commits recorded yet. Make sure the browser is connected and triggering re-renders.");
514
- return textResult(JSON.stringify(commits, null, 2));
515
- });
516
- }
517
- //#endregion
518
- //#region src/server/tools/get-projects.ts
519
- function register$4(server) {
520
- server.registerTool("get_projects", {
521
- title: "Get Projects",
522
- description: "Returns a list of project identifiers (browser origin URLs) that have recorded render data.",
523
- inputSchema: {}
524
- }, async () => {
525
- const projects = store.getProjects();
526
- if (projects.length === 0) return textResult("No projects have recorded render data yet.");
527
- return textResult(`Active projects:\n${projects.map((p) => `- ${p}`).join("\n")}`);
528
- });
529
- }
530
- //#endregion
531
- //#region src/server/tools/get-render-summary.ts
532
- function register$3(server) {
533
- server.registerTool("get_render_summary", {
534
- title: "Get Render Summary",
535
- 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.",
536
- inputSchema: {
537
- project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect."),
538
- groupBy: z.enum(["commit"]).optional().describe("Group results by commit. When set to 'commit', returns per-commit render summaries instead of a single aggregate.")
539
- }
540
- }, async ({ project, groupBy }) => {
541
- const resolved = resolveProject(project);
542
- if (resolved.error) return textResult(resolved.error);
543
- if (groupBy === "commit") return commitSummary(resolved.projectId);
544
- return aggregateSummary(resolved.projectId);
545
- });
546
- }
547
- function formatReasons(reasons) {
548
- const parts = [];
549
- if (reasons.props > 0) parts.push(`props: ${reasons.props}`);
550
- if (reasons.state > 0) parts.push(`state: ${reasons.state}`);
551
- if (reasons.hooks > 0) parts.push(`hooks: ${reasons.hooks}`);
552
- return parts.length > 0 ? ` — ${parts.join(", ")}` : "";
553
- }
554
- function aggregateSummary(projectId) {
555
- const summary = store.getSummary(projectId);
556
- if (Object.keys(summary).length === 0) return textResult("No renders recorded yet.");
557
- const lines = [];
558
- for (const [proj, components] of Object.entries(summary)) {
559
- lines.push(`[${proj}]`);
560
- for (const [name, { count, reasons }] of Object.entries(components)) lines.push(` ${name}: ${count} re-render(s)${formatReasons(reasons)}`);
561
- }
562
- return textResult(`Re-render summary:\n\n${lines.join("\n")}`);
563
- }
564
- function commitSummary(projectId) {
565
- const summary = store.getSummaryByCommit(projectId);
566
- if (Object.keys(summary).length === 0) return textResult("No renders with commit IDs recorded yet.");
567
- const lines = [];
568
- for (const [proj, commits] of Object.entries(summary)) {
569
- lines.push(`[${proj}]`);
570
- const sortedCommitIds = Object.keys(commits).map(Number).sort((a, b) => a - b);
571
- for (const commitId of sortedCommitIds) {
572
- const components = commits[commitId];
573
- const total = Object.values(components).reduce((s, c) => s + c.count, 0);
574
- lines.push(` Commit #${commitId} (${total} re-render(s)):`);
575
- for (const [name, { count, reasons }] of Object.entries(components)) lines.push(` ${name}: ${count}${formatReasons(reasons)}`);
576
- }
577
- }
578
- return textResult(`Re-render summary (by commit):\n\n${lines.join("\n")}`);
579
- }
580
- //#endregion
581
- //#region src/server/tools/get-renders-by-commit.ts
582
- function register$2(server) {
583
- server.registerTool("get_renders_by_commit", {
584
- title: "Get Renders by Commit",
585
- description: "Returns all re-renders for a specific React commit ID. Use get_commits first to discover available commit IDs.",
586
- inputSchema: {
587
- commitId: z.number().describe("The React commit ID to filter by."),
588
- component: z.string().optional().describe("Filter by component name. Omit to get all renders."),
589
- project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.")
590
- }
591
- }, async ({ commitId, component, project }) => {
592
- const resolved = resolveProject(project);
593
- if (resolved.error) return textResult(resolved.error);
594
- let renders = store.getRendersByCommit(commitId, resolved.projectId);
595
- if (component) renders = renders.filter((r) => r.displayName === component);
596
- if (renders.length === 0) return textResult(component ? `No renders recorded for component "${component}" in commit ${commitId}.` : `No renders recorded for commit ${commitId}.`);
597
- return textResult(JSON.stringify(renders, null, 2));
598
- });
599
- }
600
- //#endregion
601
- //#region src/server/tools/get-renders.ts
602
- function register$1(server) {
603
- server.registerTool("get_renders", {
604
- title: "Get Renders",
605
- description: "Returns all re-renders collected from the browser. 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.",
606
- inputSchema: {
607
- component: z.string().optional().describe("Filter by component name. Omit to get all renders."),
608
- project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.")
609
- }
610
- }, async ({ component, project }) => {
611
- const resolved = resolveProject(project);
612
- if (resolved.error) return textResult(resolved.error);
613
- const renders = component ? store.getRendersByComponent(component, resolved.projectId) : store.getAllRenders(resolved.projectId);
614
- if (renders.length === 0) return textResult(component ? `No renders recorded for "${component}".` : "No renders recorded yet. Make sure the browser is connected and triggering re-renders.");
615
- return textResult(JSON.stringify(renders, null, 2));
616
- });
617
- }
618
- //#endregion
619
- //#region src/server/tools/get-tracked-components.ts
620
- function formatConfig(config) {
621
- const lines = [];
622
- if (config.include?.length) {
623
- lines.push(" include:");
624
- for (const pattern of config.include) lines.push(` - /${pattern}/`);
625
- }
626
- if (config.exclude?.length) {
627
- lines.push(" exclude:");
628
- for (const pattern of config.exclude) lines.push(` - /${pattern}/`);
629
- }
630
- if (config.trackAllPureComponents != null) lines.push(` trackAllPureComponents: ${config.trackAllPureComponents}`);
631
- if (config.trackHooks != null) lines.push(` trackHooks: ${config.trackHooks}`);
632
- if (config.trackExtraHooks?.length) {
633
- lines.push(" trackExtraHooks:");
634
- for (const hook of config.trackExtraHooks) lines.push(` - ${hook}`);
635
- }
636
- if (config.logOnDifferentValues != null) lines.push(` logOnDifferentValues: ${config.logOnDifferentValues}`);
637
- if (config.logOwnerReasons != null) lines.push(` logOwnerReasons: ${config.logOwnerReasons}`);
638
- return lines;
639
- }
640
- function register(server) {
641
- server.registerTool("get_tracked_components", {
642
- title: "Get Tracked Components",
643
- 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.",
644
- inputSchema: { project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.") }
645
- }, async ({ project }) => {
646
- const resolved = resolveProject(project);
647
- if (resolved.error) return textResult(resolved.error);
648
- const configs = store.getWdyrConfig(resolved.projectId);
649
- const tracked = store.getTrackedComponents(resolved.projectId);
650
- const hasConfig = Object.keys(configs).length > 0;
651
- const hasTracked = Object.keys(tracked).length > 0;
652
- if (!hasConfig && !hasTracked) return textResult("No configuration or tracked components found. Make sure the browser is connected and triggering re-renders.");
653
- const lines = [];
654
- const projects = new Set([...Object.keys(configs), ...Object.keys(tracked)]);
655
- for (const proj of projects) {
656
- lines.push(`[${proj}]`);
657
- const config = configs[proj];
658
- if (config) {
659
- lines.push("Configuration:");
660
- const configLines = formatConfig(config);
661
- if (configLines.length > 0) lines.push(...configLines);
662
- else lines.push(" (default options)");
663
- }
664
- const t = tracked[proj];
665
- if (t?.observed.length) {
666
- lines.push("Observed in renders:");
667
- for (const name of t.observed) lines.push(` - ${name}`);
668
- }
669
- }
670
- return textResult(lines.join("\n"));
671
- });
672
- }
673
- //#endregion
674
- //#region src/server/tools/index.ts
675
- function registerTools(server) {
676
- register$1(server);
677
- register$3(server);
678
- register$5(server);
679
- register$2(server);
680
- register$4(server);
681
- register(server);
682
- register$6(server);
683
- }
684
- //#endregion
685
- //#region src/server/ws.ts
686
- function createWsServer(port) {
687
- const httpServer = http.createServer();
688
- const io = new Server(httpServer, {
689
- cors: { origin: "*" },
690
- serveClient: false
691
- });
692
- io.on("connection", (socket) => {
693
- console.error(`[wdyr-mcp] browser connected (http://localhost:${port})`);
694
- socket.data.projectId = null;
695
- socket.on("render", (payload, projectId, commitId) => {
696
- socket.data.projectId = projectId;
697
- store.addRender(payload, projectId, commitId);
698
- });
699
- socket.on("render-batch", (payload, projectId, commitId) => {
700
- socket.data.projectId = projectId;
701
- for (const report of payload) store.addRender(report, projectId, commitId);
702
- });
703
- socket.on("register", (components, projectId) => {
704
- socket.data.projectId = projectId;
705
- store.setTrackedComponents(components, projectId);
706
- });
707
- socket.on("config", (config, projectId) => {
708
- socket.data.projectId = projectId;
709
- store.setWdyrConfig(config, projectId);
710
- });
711
- socket.on("disconnect", () => {
712
- console.error("[wdyr-mcp] browser disconnected");
713
- const projectId = socket.data.projectId;
714
- if (!projectId) return;
715
- if (![...io.sockets.sockets.values()].some((s) => s.id !== socket.id && s.data.projectId === projectId)) {
716
- console.error(`[wdyr-mcp] last client for ${projectId} disconnected, clearing render data`);
717
- store.clearRenders(projectId);
718
- }
719
- });
720
- });
721
- httpServer.on("error", (err) => {
722
- if (err.code === "EADDRINUSE") console.error(`[wdyr-mcp] Port ${port} already in use, another instance owns the WS server. Skipping.`);
723
- else console.error("[wdyr-mcp] server error:", err);
724
- });
725
- httpServer.listen(port, "127.0.0.1", () => {
726
- console.error(`[wdyr-mcp] socket.io server listening on http://localhost:${port}`);
727
- });
728
- return io;
729
- }
730
- //#endregion
731
- //#region src/server/index.ts
732
- const DEFAULT_WS_PORT = 4649;
733
- const server = new McpServer({
734
- name: "why-did-you-render",
735
- version: "0.0.0"
736
- });
737
- registerTools(server);
738
- async function main() {
739
- const io = createWsServer(Number(process.env.WDYR_WS_PORT) || DEFAULT_WS_PORT);
740
- const transport = new StdioServerTransport();
741
- await server.connect(transport);
742
- console.error("[wdyr-mcp] MCP server running on stdio");
743
- let shuttingDown = false;
744
- async function shutdown() {
745
- if (shuttingDown) return;
746
- shuttingDown = true;
747
- console.error("[wdyr-mcp] Shutting down…");
748
- io?.close();
749
- await server.close();
750
- process.exit(0);
751
- }
752
- process.stdin.on("end", shutdown);
753
- process.on("SIGTERM", shutdown);
754
- process.on("SIGINT", shutdown);
755
- }
756
- main().catch((error) => {
757
- console.error("[wdyr-mcp] Fatal error:", error);
758
- process.exit(1);
759
- });
760
- //#endregion
761
- export {};
2
+ import{McpServer as e}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as t}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as n}from"zod";import{existsSync as r,mkdirSync as i,readFileSync as a,readdirSync as o,unlinkSync as s,writeFileSync as c}from"node:fs";import{homedir as l}from"node:os";import{join as u}from"node:path";import d from"xxhash-wasm";import f from"node:http";import{Server as p}from"socket.io";const m=`@@dict`,h=`@@ref:`;let g;const _=d().then(e=>{g=e.h64ToString});function v(){return _}function y(e){return g(JSON.stringify(e))}function b(e){return typeof e==`object`&&!!e}function x(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;if(b(n)){let e=y(n);t[e]??=n,n=`${h}${e}`}if(b(r)){let e=y(r);t[e]??=r,r=`${h}${e}`}return n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function S(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=x(n,t),o=x(r,t),s=x(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(h)&&(n=t[n.slice(6)]??n),typeof r==`string`&&r.startsWith(h)&&(r=t[r.slice(6)]??r),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){if(!r(e))return[];let t=a(e,`utf-8`).split(`
3
+ `).filter(Boolean);if(t.length===0)return[];let n,i=0,o=JSON.parse(t[0]);`@@dict`in o&&(n=o[m],i=1);let s=t.slice(i).map(e=>JSON.parse(e));return n?s.map(e=>w(e,n)):s}function E(e){return e.replaceAll(/[^a-zA-Z0-9_.-]/g,`_`)}function D(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}}}const O=`nocommit`,k=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??u(l(),`.wdyr-mcp`,`renders`),i(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 v(),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=>S(e,r)),a=this.commitFile(n.projectId,n.commitId),o=this.readDataLines(a),s=i.map(e=>JSON.stringify(e)),l=[...o,...s];c(a,`${(Object.keys(r).length>0?[JSON.stringify({[m]:r}),...l]:l).join(`
4
+ `)}\n`),t.length=0;let u=this.timers.get(e);u&&(clearTimeout(u),this.timers.delete(e))}readDataLines(e){return r(e)?a(e,`utf-8`).split(`
5
+ `).filter(e=>!(!e||e.startsWith(`{"@@dict"`))):[]}getAllRenders(e){return this.flush(e),e?this.projectFiles(e).flatMap(e=>T(u(this.dir,e)).map(D)):this.jsonlFiles().flatMap(e=>T(u(this.dir,e)).map(D))}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))s(u(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())s(u(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=u(this.dir,t),i=T(n),a=i.length,o=i.filter(t=>t.displayName!==e);r+=a-o.length,o.length===0?(s(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&&(s(u(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=a(u(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=T(u(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),T(this.commitFile(t,e)).map(D);this.flush();let n=`_commit_${e}.jsonl`;return this.jsonlFiles().filter(e=>e.endsWith(n)).flatMap(e=>T(u(this.dir,e)).map(D))}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++}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++}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){c(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(E(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??O}`}bufferKeysForProject(e){let t=`${e}\0`;return[...this.buffers.keys()].filter(e=>e.startsWith(t))}commitFile(e,t){let n=E(e),r=t==null?`_${O}`:`_commit_${t}`;return u(this.dir,`${n}${r}.jsonl`)}projectFiles(e){let t=E(e);return o(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 o(this.dir).filter(e=>e.endsWith(`.jsonl`))}};function A(e){if(e)return{projectId:e};let t=k.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 j(e){return{content:[{type:`text`,text:e}]}}function M(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:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),component:n.string().optional().describe(`Clear only renders for this component (by displayName).`),beforeCommit:n.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=A(e);return r.error?j(r.error):t?j(`Cleared ${k.clearRendersByComponent(t,r.projectId)} render(s) for component "${t}".`):n==null?(k.clearRenders(r.projectId),j(r.projectId?`Render data cleared for ${r.projectId}.`:`All render data cleared.`)):j(`Cleared renders from ${k.clearRendersByCommit(n,r.projectId)} commit file(s) before commit #${n}.`)})}function N(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:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=A(e);if(t.error)return j(t.error);let n=k.getCommits(t.projectId);return n.length===0?j(`No commits recorded yet. Make sure the browser is connected and triggering re-renders.`):j(JSON.stringify(n,null,2))})}function P(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=k.getProjects();return e.length===0?j(`No projects have recorded render data yet.`):j(`Active projects:\n${e.map(e=>`- ${e}`).join(`
9
+ `)}`)})}function F(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:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),groupBy:n.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=A(e);return n.error?j(n.error):t===`commit`?R(n.projectId):L(n.projectId)})}function I(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 L(e){let t=k.getSummary(e);if(Object.keys(t).length===0)return j(`No renders recorded yet.`);let n=[];for(let[e,r]of Object.entries(t)){n.push(`[${e}]`);for(let[e,{count:t,reasons:i}]of Object.entries(r))n.push(` ${e}: ${t} re-render(s)${I(i)}`)}return j(`Re-render summary:\n\n${n.join(`
10
+ `)}`)}function R(e){let t=k.getSummaryByCommit(e);if(Object.keys(t).length===0)return j(`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}]of Object.entries(t))n.push(` ${e}: ${r}${I(i)}`)}}return j(`Re-render summary (by commit):\n\n${n.join(`
11
+ `)}`)}function z(e){e.registerTool(`get_renders_by_commit`,{title:`Get Renders by Commit`,description:`Returns all re-renders for a specific React commit ID. Use get_commits first to discover available commit IDs.`,inputSchema:{commitId:n.number().describe(`The React commit ID to filter by.`),component:n.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:n.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=A(n);if(r.error)return j(r.error);let i=k.getRendersByCommit(e,r.projectId);return t&&(i=i.filter(e=>e.displayName===t)),i.length===0?j(t?`No renders recorded for component "${t}" in commit ${e}.`:`No renders recorded for commit ${e}.`):j(JSON.stringify(i,null,2))})}function B(e){e.registerTool(`get_renders`,{title:`Get Renders`,description:`Returns all re-renders collected from the browser. 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:n.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:n.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=A(t);if(n.error)return j(n.error);let r=e?k.getRendersByComponent(e,n.projectId):k.getAllRenders(n.projectId);return r.length===0?j(e?`No renders recorded for "${e}".`:`No renders recorded yet. Make sure the browser is connected and triggering re-renders.`):j(JSON.stringify(r,null,2))})}function V(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 H(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:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=A(e);if(t.error)return j(t.error);let n=k.getWdyrConfig(t.projectId),r=k.getTrackedComponents(t.projectId),i=Object.keys(n).length>0,a=Object.keys(r).length>0;if(!i&&!a)return j(`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=V(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 j(o.join(`
12
+ `))})}function U(e){B(e),F(e),N(e),z(e),P(e),H(e),M(e)}function W(e){let t=f.createServer(),n=new p(t,{cors:{origin:`*`},serveClient:!1});return n.on(`connection`,t=>{console.error(`[wdyr-mcp] browser connected (http://localhost:${e})`),t.data.projectId=null,t.on(`render`,(e,n,r)=>{t.data.projectId=n,k.addRender(e,n,r)}),t.on(`render-batch`,(e,n,r)=>{t.data.projectId=n;for(let t of e)k.addRender(t,n,r)}),t.on(`register`,(e,n)=>{t.data.projectId=n,k.setTrackedComponents(e,n)}),t.on(`config`,(e,n)=>{t.data.projectId=n,k.setWdyrConfig(e,n)}),t.on(`disconnect`,()=>{console.error(`[wdyr-mcp] browser disconnected`);let e=t.data.projectId;e&&([...n.sockets.sockets.values()].some(n=>n.id!==t.id&&n.data.projectId===e)||(console.error(`[wdyr-mcp] last client for ${e} disconnected, clearing render data`),k.clearRenders(e)))})}),t.on(`error`,t=>{t.code===`EADDRINUSE`?console.error(`[wdyr-mcp] Port ${e} already in use, another instance owns the WS server. Skipping.`):console.error(`[wdyr-mcp] server error:`,t)}),t.listen(e,`127.0.0.1`,()=>{console.error(`[wdyr-mcp] socket.io server listening on http://localhost:${e}`)}),n}const G=new e({name:`why-did-you-render`,version:`0.0.0`});U(G);async function K(){let e=W(Number(process.env.WDYR_WS_PORT)||4649),n=new t;await G.connect(n),console.error(`[wdyr-mcp] MCP server running on stdio`);let r=!1;async function i(){r||(r=!0,console.error(`[wdyr-mcp] Shutting down…`),e?.close(),await G.close(),process.exit(0))}process.stdin.on(`end`,i),process.on(`SIGTERM`,i),process.on(`SIGINT`,i)}K().catch(e=>{console.error(`[wdyr-mcp] Fatal error:`,e),process.exit(1)});export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0x1f320.sh/why-did-you-render-mcp",
3
- "version": "1.0.0-dev.19",
3
+ "version": "1.0.0-dev.20",
4
4
  "type": "module",
5
5
  "description": "MCP server that collects why-did-you-render data from browser and exposes it to coding agents",
6
6
  "license": "MIT",
@@ -47,6 +47,7 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@modelcontextprotocol/sdk": "^1.12.1",
50
+ "error-stack-parser": "^2.1.4",
50
51
  "socket.io": "^4.8.3",
51
52
  "socket.io-client": "^4.8.3",
52
53
  "xxhash-wasm": "^1.1.0",