@lensmcp/vite-plugin 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,80 @@
1
+ # @lensmcp/vite-plugin
2
+
3
+ > The single Vite plugin that makes a frontend app observable by [LensMCP](https://github.com/kiwiapps-ltd/lensmcp).
4
+
5
+ LensMCP is an observability lens for coding agents. `@lensmcp/vite-plugin` is how a Vite-based frontend opts into that lens: add it to your `vite.config.ts` and your app starts streaming React renders, Valtio state changes, console output, network calls, route changes, runtime errors, and build events back to LensMCP — with no other source changes.
6
+
7
+ Under the hood the plugin does three things: it aliases `valtio` to the instrumented drop-in [`@lensmcp/valtio-instrumentation`](https://www.npmjs.com/package/@lensmcp/valtio-instrumentation), it applies the [`@lensmcp/react-instrumentation`](https://www.npmjs.com/package/@lensmcp/react-instrumentation) Babel source transform to your JSX/TSX, and it injects a browser event bridge (a client runtime) that ships captured events to the lens over a local WebSocket. The plugin is **passive** — it never mutates your app's state or behaviour — and is meant to run in dev only.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ yarn add -D @lensmcp/vite-plugin
13
+ ```
14
+
15
+ `vite` is a peer dependency (`^5 || ^6 || ^7 || ^8`).
16
+
17
+ ## Usage
18
+
19
+ Add `lensmcpVitePlugin()` to your `plugins` array. Zero config is the intended path — every capability is on by default:
20
+
21
+ ```ts
22
+ // vite.config.ts
23
+ import { defineConfig } from 'vite';
24
+ import react from '@vitejs/plugin-react';
25
+ import { lensmcpVitePlugin } from '@lensmcp/vite-plugin';
26
+
27
+ export default defineConfig({
28
+ plugins: [
29
+ react(),
30
+ lensmcpVitePlugin(),
31
+ ],
32
+ });
33
+ ```
34
+
35
+ The plugin runs at `enforce: 'pre'`, so its source transform sees raw JSX/TSX before `@vitejs/plugin-react` (Babel), `@vitejs/plugin-react@6` (oxc), or `@vitejs/plugin-react-swc` (SWC) turn JSX into calls — it coexists with whichever React compiler you use.
36
+
37
+ To keep it dev-only, gate it on the command:
38
+
39
+ ```ts
40
+ export default defineConfig(({ command }) => ({
41
+ plugins: [
42
+ react(),
43
+ lensmcpVitePlugin({ enabled: command === 'serve' }),
44
+ ],
45
+ }));
46
+ ```
47
+
48
+ ## What it does
49
+
50
+ - **`valtio` → `@lensmcp/valtio-instrumentation` alias.** A `config()` hook rewrites bare `import … from 'valtio'` to the instrumented drop-in, so existing Valtio stores become observable without edits. The alias uses an exact `/^valtio$/` match so the drop-in's own `valtio/vanilla` and `valtio/react` imports are left untouched. (Toggle with `aliasValtio`.)
51
+ - **`@lensmcp/react-instrumentation` Babel transform.** A `transform()` hook runs the LensMCP Babel plugin (`lensmcpBabelPlugin`) over every `.jsx`/`.tsx` file outside `node_modules`, wrapping the app root, instrumenting hooks, and stamping JSX identity props. The output is plain JSX/TSX that downstream React compilers preserve. (Toggle with `transformSource`.)
52
+ - **Browser event bridge / client runtime injection.** `transformIndexHtml()` injects `<script type="module" src="/@lensmcp/client-runtime">` into the page head; the plugin resolves that virtual module to a small client runtime. The runtime opens a WebSocket back to the plugin and forwards browser events — runtime errors, unhandled rejections, `console.*`, `fetch`, History/route changes, plus the pre-formed `publish` envelopes from the in-page React and Valtio instrumentation (via `window.__LENSMCP_PUBLISH__`). Each tab gets a stable per-tab id so multiple tabs stay distinct.
53
+ - **Build + HMR events.** `handleHotUpdate()` emits an HMR event with the affected files, and `generateBundle()` emits a bundle-size report (per-chunk and per-module byte sizes). Vite's native `vite:error` stream is forwarded too.
54
+
55
+ Incoming browser envelopes and Vite/Rollup events are normalised into LensMCP's `BaseEvent` shape and published. When an in-process `EventBus` is bound the plugin publishes directly; otherwise it forwards events cross-process over the same env-configured sink as the NestJS instrumentation — `LENSMCP_EVENT_FILE`, `LENSMCP_UDS`, or `LENSMCP_IPC_SOCKET` (`host:port`) — falling back to `console.debug` only for error-severity events when no sink is set.
56
+
57
+ ## Options
58
+
59
+ `lensmcpVitePlugin(options?)` accepts `LensmcpViteOptions` — all fields are optional:
60
+
61
+ | Option | Type | Default | Description |
62
+ | --- | --- | --- | --- |
63
+ | `enabled` | `boolean` | `true` | Whether the plugin attaches anything. Set `false` for production. |
64
+ | `wsPort` | `number` | ephemeral | WebSocket port the client runtime posts events to. An unused port is chosen automatically when omitted. |
65
+ | `wsHost` | `string` | `'127.0.0.1'` | Bind address for the WebSocket. |
66
+ | `injectClient` | `boolean` | `true` | Inject the client runtime via a `<script>` tag. |
67
+ | `aliasValtio` | `boolean` | `true` | Alias `valtio` to the instrumented drop-in in dev. |
68
+ | `transformSource` | `boolean` | `true` | Run the LensMCP source transform (root-wrap + hooks + JSX ids). |
69
+
70
+ The returned plugin also exposes a `wsPort(): number \| undefined` accessor (`LensmcpViteRuntime`), available after Vite's `configureServer` hook fires.
71
+
72
+ ## How it fits
73
+
74
+ `@lensmcp/vite-plugin` is the front door for the browser-side of LensMCP. It pulls in [`@lensmcp/react-instrumentation`](https://www.npmjs.com/package/@lensmcp/react-instrumentation) (the Babel transform) and [`@lensmcp/valtio-instrumentation`](https://www.npmjs.com/package/@lensmcp/valtio-instrumentation) (the Valtio drop-in), then injects the bridge that those instrumentation layers publish through. The bridge ships the resulting events to the LensMCP runtime, where the gateway / MCP server collect and reduce them into resources (`react://`, `valtio://`, `runtime://browser/*`, `browser://tabs`) that a coding agent can query through the lens.
75
+
76
+ You typically add this one plugin to a frontend app, pair it with the NestJS instrumentation on the backend, and the agent sees both sides of the running system.
77
+
78
+ ---
79
+
80
+ Part of [LensMCP](https://github.com/kiwiapps-ltd/lensmcp). Apache-2.0.
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { lensmcpVitePlugin, handleClientEnvelope } from './lib/plugin.js';
2
+ export type { LensmcpViteOptions, LensmcpViteRuntime, ClientEnvelope } from './lib/types.js';
3
+ export { envelopeToEvent } from './lib/event-mappers.js';
4
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,YAAY,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAC7F,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC"}
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { lensmcpVitePlugin, handleClientEnvelope } from './lib/plugin.js';
2
+ export { envelopeToEvent } from './lib/event-mappers.js';
@@ -0,0 +1,10 @@
1
+ import type { BaseEvent } from '@lensmcp/protocol-types';
2
+ import type { ClientEnvelope } from './types.js';
3
+ /**
4
+ * Translate a single client-runtime envelope into the normalised
5
+ * `BaseEvent` consumed by the LensMCP event bus. The Vite plugin
6
+ * publishes these; reducers in `@lensmcp/<app>` materialise them into
7
+ * `runtime://browser/*` resources.
8
+ */
9
+ export declare function envelopeToEvent(env: ClientEnvelope, sessionId?: string): BaseEvent;
10
+ //# sourceMappingURL=event-mappers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-mappers.d.ts","sourceRoot":"","sources":["../../src/lib/event-mappers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAIjD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,cAAc,EAAE,SAAS,SAAyB,GAAG,SAAS,CAuIlG"}
@@ -0,0 +1,169 @@
1
+ import { fingerprint, ulid } from '@lensmcp/core';
2
+ const SESSION_ID_PLACEHOLDER = 'pending';
3
+ /**
4
+ * Translate a single client-runtime envelope into the normalised
5
+ * `BaseEvent` consumed by the LensMCP event bus. The Vite plugin
6
+ * publishes these; reducers in `@lensmcp/<app>` materialise them into
7
+ * `runtime://browser/*` resources.
8
+ */
9
+ export function envelopeToEvent(env, sessionId = SESSION_ID_PLACEHOLDER) {
10
+ // Per-tab identity stamped by the client runtime — keys browser://tabs.
11
+ const tab = env.tabId ? { tabId: env.tabId } : {};
12
+ switch (env.kind) {
13
+ case 'error':
14
+ return {
15
+ id: ulid(),
16
+ sessionId,
17
+ timestamp: env.at,
18
+ source: 'client-runtime',
19
+ category: 'runtime',
20
+ severity: 'error',
21
+ context: { sessionId, ...tab },
22
+ fingerprint: fingerprint({
23
+ kind: 'runtime',
24
+ identity: `error:${normaliseStackTopFrame(env.stack)}`,
25
+ file: env.source,
26
+ detail: env.message,
27
+ }),
28
+ title: env.message,
29
+ message: env.stack ?? env.message,
30
+ location: env.source
31
+ ? { file: env.source, line: env.lineno, column: env.colno }
32
+ : undefined,
33
+ raw: env,
34
+ };
35
+ case 'unhandledrejection':
36
+ return {
37
+ id: ulid(),
38
+ sessionId,
39
+ timestamp: env.at,
40
+ source: 'client-runtime',
41
+ category: 'runtime',
42
+ severity: 'error',
43
+ context: { sessionId, ...tab },
44
+ fingerprint: fingerprint({
45
+ kind: 'runtime',
46
+ identity: `unhandledrejection:${env.reason.slice(0, 80)}`,
47
+ }),
48
+ title: 'Unhandled promise rejection',
49
+ message: env.reason,
50
+ raw: env,
51
+ };
52
+ case 'console': {
53
+ const severity = env.level === 'error' ? 'error' : env.level === 'warn' ? 'warning' : 'info';
54
+ const text = env.args.map(stringify).join(' ');
55
+ return {
56
+ id: ulid(),
57
+ sessionId,
58
+ timestamp: env.at,
59
+ source: 'client-runtime',
60
+ category: 'runtime',
61
+ severity,
62
+ context: { sessionId, ...tab },
63
+ fingerprint: fingerprint({
64
+ kind: 'runtime',
65
+ identity: `console:${env.level}:${text.slice(0, 80)}`,
66
+ }),
67
+ title: `console.${env.level}`,
68
+ message: text,
69
+ raw: env,
70
+ };
71
+ }
72
+ case 'fetch': {
73
+ const failed = env.error !== undefined || (env.status !== undefined && env.status >= 400);
74
+ return {
75
+ id: ulid(),
76
+ sessionId,
77
+ timestamp: env.at,
78
+ source: 'client-runtime',
79
+ category: 'network',
80
+ severity: failed ? 'error' : 'info',
81
+ context: { sessionId, ...tab },
82
+ fingerprint: fingerprint({
83
+ kind: 'network',
84
+ identity: `${env.method}:${normaliseUrl(env.url)}:${env.status ?? 'err'}`,
85
+ }),
86
+ title: `${env.method} ${env.url}${env.status !== undefined ? ` → ${env.status}` : ''}`,
87
+ message: env.error,
88
+ relatedUrls: [env.url],
89
+ raw: env,
90
+ };
91
+ }
92
+ case 'route':
93
+ return {
94
+ id: ulid(),
95
+ sessionId,
96
+ timestamp: env.at,
97
+ source: 'client-runtime',
98
+ category: 'runtime',
99
+ severity: 'info',
100
+ context: { sessionId, url: env.url, ...tab },
101
+ fingerprint: fingerprint({ kind: 'runtime', identity: `route:${env.url}` }),
102
+ title: `Route → ${env.url}`,
103
+ raw: env,
104
+ };
105
+ case 'ready':
106
+ return {
107
+ id: ulid(),
108
+ sessionId,
109
+ timestamp: env.at,
110
+ source: 'client-runtime',
111
+ category: 'runtime',
112
+ severity: 'info',
113
+ context: { sessionId, url: env.url, ...tab },
114
+ fingerprint: fingerprint({ kind: 'runtime', identity: 'client-ready' }),
115
+ title: 'Client runtime ready',
116
+ message: env.userAgent,
117
+ raw: env,
118
+ };
119
+ case 'publish':
120
+ // Pre-formed publish envelope from in-page instrumentation. Trust
121
+ // its source/category (the producer is our own injected code); the
122
+ // reducers gate on those, and the context carries the flow id so
123
+ // React renders correlate with the originating user action.
124
+ return {
125
+ id: ulid(),
126
+ sessionId,
127
+ timestamp: env.at,
128
+ source: env.source,
129
+ category: env.category,
130
+ severity: (env.severity ?? 'info'),
131
+ context: { sessionId, ...tab, ...(env.context ?? {}) },
132
+ fingerprint: env.fingerprint ?? fingerprint({ kind: 'publish', identity: env.title }),
133
+ title: env.title,
134
+ message: env.message,
135
+ raw: env.raw,
136
+ };
137
+ }
138
+ }
139
+ // --- helpers ---
140
+ function normaliseStackTopFrame(stack) {
141
+ if (!stack)
142
+ return 'unknown';
143
+ const lines = stack.split('\n').slice(0, 2);
144
+ for (const line of lines) {
145
+ const m = line.match(/at\s+(\S+)/);
146
+ if (m && m[1])
147
+ return m[1];
148
+ }
149
+ return 'unknown';
150
+ }
151
+ function normaliseUrl(url) {
152
+ try {
153
+ const u = new URL(url, 'http://x');
154
+ return `${u.pathname}`;
155
+ }
156
+ catch {
157
+ return url;
158
+ }
159
+ }
160
+ function stringify(v) {
161
+ if (typeof v === 'string')
162
+ return v;
163
+ try {
164
+ return JSON.stringify(v);
165
+ }
166
+ catch {
167
+ return String(v);
168
+ }
169
+ }
@@ -0,0 +1,36 @@
1
+ import type { Plugin } from 'vite';
2
+ import { type EventBus } from '@lensmcp/core';
3
+ import type { LensmcpViteOptions, LensmcpViteRuntime } from './types.js';
4
+ interface BoundDeps {
5
+ /**
6
+ * EventBus to publish onto (in-process, e.g. tests). If undefined, events are
7
+ * forwarded cross-process via the env sink — `LENSMCP_EVENT_FILE` / `LENSMCP_UDS`
8
+ * / `LENSMCP_IPC_SOCKET` (the same contract as the NestJS sink); console.debug
9
+ * is only the last-resort fallback for error-severity events when no sink is set.
10
+ */
11
+ bus?: EventBus;
12
+ /** Session id stamped onto each event. */
13
+ sessionId?: string;
14
+ }
15
+ /**
16
+ * Vite plugin that:
17
+ * 1. Stands up a tiny WebSocket so the injected @lensmcp/client-runtime
18
+ * can post browser events back into the LensMCP event bus.
19
+ * 2. Injects a `<script type="module" src="/@lensmcp/client-runtime">`
20
+ * into served HTML.
21
+ * 3. Resolves that virtual module to the bundled client runtime
22
+ * (during Phase 1 — a minimal inline implementation; the real
23
+ * package import lands in Phase 2/3).
24
+ * 4. Emits HMR + module-graph events for the build reducer.
25
+ *
26
+ * The plugin is *passive*: it never mutates app state or behaviour.
27
+ */
28
+ export declare function lensmcpVitePlugin(options?: LensmcpViteOptions, deps?: BoundDeps): Plugin & LensmcpViteRuntime;
29
+ /**
30
+ * Parse one raw WebSocket message from the injected client runtime and
31
+ * publish the resulting event. Exported so it can be exercised over a
32
+ * real WebSocket without booting Vite (see the react-bridge smoke).
33
+ */
34
+ export declare function handleClientEnvelope(raw: string, deps: BoundDeps): void;
35
+ export {};
36
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/lib/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAiB,MAAM,MAAM,CAAC;AAMlD,OAAO,EAAqB,KAAK,QAAQ,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAkB,MAAM,YAAY,CAAC;AAMzF,UAAU,SAAS;IACjB;;;;;OAKG;IACH,GAAG,CAAC,EAAE,QAAQ,CAAC;IACf,0CAA0C;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,GAAE,kBAAuB,EAChC,IAAI,GAAE,SAAc,GACnB,MAAM,GAAG,kBAAkB,CA+K7B;AAqCD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,IAAI,CASvE"}
package/lib/plugin.js ADDED
@@ -0,0 +1,514 @@
1
+ import { createServer as createNetServer, connect } from 'node:net';
2
+ import { createSocket } from 'node:dgram';
3
+ import { appendFileSync } from 'node:fs';
4
+ import { WebSocketServer } from 'ws';
5
+ import { fingerprint, ulid } from '@lensmcp/core';
6
+ import { envelopeToEvent } from './event-mappers.js';
7
+ const CLIENT_VIRTUAL_ID = '/@lensmcp/client-runtime';
8
+ const RESOLVED_CLIENT_VIRTUAL_ID = '\0lensmcp-client-runtime';
9
+ /**
10
+ * Vite plugin that:
11
+ * 1. Stands up a tiny WebSocket so the injected @lensmcp/client-runtime
12
+ * can post browser events back into the LensMCP event bus.
13
+ * 2. Injects a `<script type="module" src="/@lensmcp/client-runtime">`
14
+ * into served HTML.
15
+ * 3. Resolves that virtual module to the bundled client runtime
16
+ * (during Phase 1 — a minimal inline implementation; the real
17
+ * package import lands in Phase 2/3).
18
+ * 4. Emits HMR + module-graph events for the build reducer.
19
+ *
20
+ * The plugin is *passive*: it never mutates app state or behaviour.
21
+ */
22
+ export function lensmcpVitePlugin(options = {}, deps = {}) {
23
+ const enabled = options.enabled ?? true;
24
+ const wsHost = options.wsHost ?? '127.0.0.1';
25
+ const injectClient = options.injectClient ?? true;
26
+ let wssPort;
27
+ let wss;
28
+ const aliasValtio = options.aliasValtio ?? true;
29
+ const transformSource = options.transformSource ?? true;
30
+ return {
31
+ name: '@lensmcp/vite-plugin',
32
+ apply: enabled ? undefined : () => false,
33
+ enforce: 'pre',
34
+ wsPort: () => wssPort,
35
+ config() {
36
+ if (!enabled || !aliasValtio)
37
+ return;
38
+ // Zero-config (Phase 8): make `import { proxy } from 'valtio'`
39
+ // resolve to the instrumented drop-in, so existing Valtio code
40
+ // becomes observable without edits. Dev-only.
41
+ //
42
+ // EXACT match (`/^valtio$/`) only — a bare-string alias does prefix
43
+ // matching, which would also rewrite the drop-in's own
44
+ // `valtio/vanilla` + `valtio/react` imports and self-loop.
45
+ return {
46
+ resolve: {
47
+ alias: [
48
+ { find: /^valtio$/, replacement: '@lensmcp/valtio-instrumentation' },
49
+ ],
50
+ },
51
+ };
52
+ },
53
+ async configureServer(server) {
54
+ if (!enabled)
55
+ return;
56
+ const port = options.wsPort ?? (await findFreePort());
57
+ wssPort = port;
58
+ wss = new WebSocketServer({ host: wsHost, port });
59
+ wss.on('connection', (socket) => {
60
+ socket.on('message', (raw) => {
61
+ handleClientEnvelope(raw.toString(), deps);
62
+ });
63
+ });
64
+ // Vite native error stream → our bus.
65
+ server.ws.on('vite:error', (data) => {
66
+ publish(deps, viteErrorToEvent(data, deps.sessionId));
67
+ });
68
+ },
69
+ resolveId(id) {
70
+ if (id === CLIENT_VIRTUAL_ID)
71
+ return RESOLVED_CLIENT_VIRTUAL_ID;
72
+ return null;
73
+ },
74
+ load(id) {
75
+ if (id !== RESOLVED_CLIENT_VIRTUAL_ID)
76
+ return null;
77
+ const port = wssPort ?? options.wsPort ?? 0;
78
+ return buildInlineClientRuntime({ host: wsHost, port });
79
+ },
80
+ // Zero-config source transform. Runs in our OWN transform hook at
81
+ // enforce:'pre', so it's independent of whichever compiler the React
82
+ // plugin uses — it runs on the raw JSX/TSX BEFORE @vitejs/plugin-react
83
+ // (Babel), @vitejs/plugin-react@6 (oxc, which dropped the `babel` hook)
84
+ // or @vitejs/plugin-react-swc (SWC) turn JSX into calls. The LensMCP
85
+ // output is plain JSX/TSX (LensmcpRoot/withFlow/traced* + data-* props),
86
+ // which every downstream compiler preserves (see swc-coexistence smoke).
87
+ // A native SWC/oxc rewrite would only be a perf optimisation.
88
+ async transform(code, id) {
89
+ if (!enabled || !transformSource)
90
+ return null;
91
+ const file = id.split('?')[0] ?? id;
92
+ if (file.includes('/node_modules/'))
93
+ return null;
94
+ if (!/\.[jt]sx$/.test(file))
95
+ return null;
96
+ const result = await runLensmcpBabel(code, file);
97
+ if (!result)
98
+ return null;
99
+ // Babel's source map is a valid Rollup map object at runtime; the
100
+ // cast just bridges the nominal type gap.
101
+ return { code: result.code, map: result.map };
102
+ },
103
+ transformIndexHtml() {
104
+ if (!injectClient || !enabled)
105
+ return;
106
+ return [
107
+ {
108
+ tag: 'script',
109
+ attrs: { type: 'module', src: CLIENT_VIRTUAL_ID },
110
+ injectTo: 'head-prepend',
111
+ },
112
+ ];
113
+ },
114
+ handleHotUpdate(ctx) {
115
+ if (!enabled)
116
+ return;
117
+ const affected = ctx.modules
118
+ .map((m) => m.file ?? m.id ?? null)
119
+ .filter((f) => !!f);
120
+ publish(deps, {
121
+ id: ulid(),
122
+ sessionId: deps.sessionId ?? 'pending',
123
+ timestamp: Date.now(),
124
+ source: 'vite',
125
+ category: 'build',
126
+ severity: 'info',
127
+ context: { sessionId: deps.sessionId ?? 'pending' },
128
+ fingerprint: fingerprint({
129
+ kind: 'hmr',
130
+ identity: ctx.file,
131
+ }),
132
+ title: `HMR ${ctx.file}`,
133
+ relatedFiles: affected,
134
+ });
135
+ },
136
+ generateBundle(_opts, bundle) {
137
+ if (!enabled)
138
+ return;
139
+ const chunks = [];
140
+ let totalBytes = 0;
141
+ for (const file of Object.values(bundle)) {
142
+ const item = file;
143
+ const name = item.fileName;
144
+ let sizeBytes;
145
+ if (item.type === 'chunk') {
146
+ sizeBytes = (item.code ?? '').length;
147
+ }
148
+ else {
149
+ const src = item.source;
150
+ sizeBytes =
151
+ typeof src === 'string' ? src.length : src instanceof Uint8Array ? src.byteLength : 0;
152
+ }
153
+ totalBytes += sizeBytes;
154
+ const modules = [];
155
+ if (item.type === 'chunk' && item.modules) {
156
+ for (const [id, mod] of Object.entries(item.modules)) {
157
+ const ml = mod.renderedLength ?? mod.originalLength ?? 0;
158
+ modules.push({ id, sizeBytes: ml });
159
+ }
160
+ modules.sort((a, b) => b.sizeBytes - a.sizeBytes);
161
+ }
162
+ chunks.push({ name, sizeBytes, modules });
163
+ }
164
+ const report = { timestamp: Date.now(), totalBytes, chunks };
165
+ publish(deps, {
166
+ id: ulid(),
167
+ sessionId: deps.sessionId ?? 'pending',
168
+ timestamp: Date.now(),
169
+ source: 'rollup',
170
+ category: 'build',
171
+ severity: 'info',
172
+ context: { sessionId: deps.sessionId ?? 'pending' },
173
+ fingerprint: fingerprint({ kind: 'bundle', identity: 'report' }),
174
+ title: `Bundle report: ${chunks.length} chunks, ${totalBytes} bytes`,
175
+ raw: { kind: 'bundle-report', report },
176
+ });
177
+ },
178
+ async closeBundle() {
179
+ if (wss) {
180
+ await new Promise((res) => wss?.close(() => res()));
181
+ }
182
+ },
183
+ };
184
+ }
185
+ // --- helpers ---
186
+ /**
187
+ * Run the LensMCP Babel transform on one module's source. Lazily loads
188
+ * `@babel/core` + the plugin so they're only touched in dev when a
189
+ * `.jsx`/`.tsx` file is transformed. Returns null on parse error (let
190
+ * Vite proceed with the untransformed source).
191
+ */
192
+ async function runLensmcpBabel(code, filename) {
193
+ try {
194
+ const [{ transformSync }, { lensmcpBabelPlugin }] = await Promise.all([
195
+ import('@babel/core'),
196
+ import('@lensmcp/react-instrumentation'),
197
+ ]);
198
+ const result = transformSync(code, {
199
+ filename,
200
+ babelrc: false,
201
+ configFile: false,
202
+ sourceMaps: true,
203
+ parserOpts: { plugins: ['jsx', 'typescript'] },
204
+ plugins: [[lensmcpBabelPlugin, { rootDir: process.cwd(), production: false }]],
205
+ code: true,
206
+ });
207
+ if (!result?.code)
208
+ return null;
209
+ return { code: result.code, map: result.map };
210
+ }
211
+ catch {
212
+ return null;
213
+ }
214
+ }
215
+ /**
216
+ * Parse one raw WebSocket message from the injected client runtime and
217
+ * publish the resulting event. Exported so it can be exercised over a
218
+ * real WebSocket without booting Vite (see the react-bridge smoke).
219
+ */
220
+ export function handleClientEnvelope(raw, deps) {
221
+ let env;
222
+ try {
223
+ env = JSON.parse(raw);
224
+ }
225
+ catch {
226
+ return; // ignore malformed
227
+ }
228
+ if (!env || typeof env !== 'object' || !('kind' in env))
229
+ return;
230
+ publish(deps, envelopeToEvent(env, deps.sessionId));
231
+ }
232
+ function publish(deps, event) {
233
+ if (deps.bus) {
234
+ deps.bus.publish(event);
235
+ return;
236
+ }
237
+ // Cross-process: the MCP server runs in a separate process during
238
+ // `agent-dev`, so when no in-process bus is bound we forward events
239
+ // over the same transport the NestJS sink uses (resolved from env).
240
+ // The server's `startEventIngest` republishes them onto its bus.
241
+ const sink = resolveEnvSink();
242
+ if (sink) {
243
+ sink(event);
244
+ return;
245
+ }
246
+ if (event.severity === 'error' || event.severity === 'fatal') {
247
+ // Standalone fallback so the plugin is debuggable without a bus.
248
+ console.debug(`[lensmcp-vite] ${event.severity}: ${event.title}`);
249
+ }
250
+ }
251
+ let cachedEnvSink;
252
+ /**
253
+ * Resolve a cross-process event sink from env, mirroring
254
+ * `@lensmcp/nest-instrumentation`'s `defaultEventSink`:
255
+ * 1. `LENSMCP_EVENT_FILE` — append one JSON line per event.
256
+ * 2. `LENSMCP_UDS` — Unix domain socket, framed NDJSON, reconnecting.
257
+ * 3. `LENSMCP_IPC_SOCKET` (`host:port`) — one UDP datagram per event.
258
+ * Cached after first resolution; returns null when none is set.
259
+ */
260
+ function resolveEnvSink() {
261
+ if (cachedEnvSink !== undefined)
262
+ return cachedEnvSink;
263
+ const filePath = process.env['LENSMCP_EVENT_FILE'];
264
+ if (filePath) {
265
+ cachedEnvSink = (event) => {
266
+ try {
267
+ appendFileSync(filePath, JSON.stringify(event) + '\n');
268
+ }
269
+ catch {
270
+ /* swallow */
271
+ }
272
+ };
273
+ return cachedEnvSink;
274
+ }
275
+ const udsPath = process.env['LENSMCP_UDS'];
276
+ if (udsPath) {
277
+ cachedEnvSink = udsEnvSink(udsPath);
278
+ return cachedEnvSink;
279
+ }
280
+ const socketPath = process.env['LENSMCP_IPC_SOCKET'];
281
+ if (socketPath) {
282
+ const [host, portStr] = socketPath.split(':');
283
+ const port = Number(portStr);
284
+ if (host && Number.isFinite(port)) {
285
+ const sock = createSocket('udp4');
286
+ sock.unref();
287
+ cachedEnvSink = (event) => {
288
+ try {
289
+ const buf = Buffer.from(JSON.stringify(event));
290
+ sock.send(buf, port, host, () => undefined);
291
+ }
292
+ catch {
293
+ /* swallow */
294
+ }
295
+ };
296
+ return cachedEnvSink;
297
+ }
298
+ }
299
+ cachedEnvSink = null;
300
+ return null;
301
+ }
302
+ /** Reconnecting NDJSON client over a Unix domain socket (see session/uds.ts). */
303
+ function udsEnvSink(path) {
304
+ const queue = [];
305
+ let sock = null;
306
+ let connecting = false;
307
+ const flush = () => {
308
+ if (!sock || !sock.writable)
309
+ return;
310
+ while (queue.length > 0)
311
+ sock.write(queue.shift());
312
+ };
313
+ const open = () => {
314
+ if (connecting || sock)
315
+ return;
316
+ connecting = true;
317
+ const s = connect(path);
318
+ s.on('connect', () => {
319
+ connecting = false;
320
+ sock = s;
321
+ flush();
322
+ });
323
+ s.on('drain', flush);
324
+ s.on('error', () => {
325
+ connecting = false;
326
+ sock = null;
327
+ });
328
+ s.on('close', () => {
329
+ sock = null;
330
+ });
331
+ s.unref();
332
+ };
333
+ open();
334
+ return (event) => {
335
+ queue.push(JSON.stringify(event) + '\n');
336
+ while (queue.length > 10000)
337
+ queue.shift();
338
+ if (sock && sock.writable) {
339
+ flush();
340
+ return;
341
+ }
342
+ // Dead socket (server restart) — drop it so open() reconnects.
343
+ if (sock) {
344
+ try {
345
+ sock.destroy();
346
+ }
347
+ catch {
348
+ /* ignore */
349
+ }
350
+ sock = null;
351
+ }
352
+ open();
353
+ };
354
+ }
355
+ function viteErrorToEvent(data, sessionId) {
356
+ const message = data.err?.message ?? 'Vite error';
357
+ const stack = data.err?.stack;
358
+ return {
359
+ id: ulid(),
360
+ sessionId: sessionId ?? 'pending',
361
+ timestamp: Date.now(),
362
+ source: 'vite',
363
+ category: 'build',
364
+ severity: 'error',
365
+ context: { sessionId: sessionId ?? 'pending' },
366
+ fingerprint: fingerprint({ kind: 'vite', identity: data.type ?? message }),
367
+ title: message,
368
+ message: stack,
369
+ };
370
+ }
371
+ function findFreePort() {
372
+ return new Promise((resolve, reject) => {
373
+ const s = createNetServer();
374
+ s.unref();
375
+ s.on('error', reject);
376
+ s.listen(0, () => {
377
+ const addr = s.address();
378
+ if (!addr) {
379
+ s.close();
380
+ reject(new Error('Could not allocate free port'));
381
+ return;
382
+ }
383
+ const port = addr.port;
384
+ s.close(() => resolve(port));
385
+ });
386
+ });
387
+ }
388
+ /**
389
+ * Minimal browser-side runtime that mirrors what `@lensmcp/client-runtime`
390
+ * will eventually own. Inlined here so Phase 1 has no cross-build
391
+ * coupling. Future: replace with a real import of the published
392
+ * package's browser bundle.
393
+ */
394
+ function buildInlineClientRuntime(opts) {
395
+ return `// @lensmcp/client-runtime (inlined by @lensmcp/vite-plugin)
396
+ (() => {
397
+ if (typeof window === 'undefined') return;
398
+ if (window.__LENSMCP_CLIENT__) return;
399
+ window.__LENSMCP_CLIENT__ = true;
400
+
401
+ const WS_URL = 'ws://${opts.host}:${opts.port}';
402
+ let ws = null;
403
+ let queue = [];
404
+ let openOnce = false;
405
+
406
+ // Per-TAB identity: sessionStorage is scoped to the tab (and survives
407
+ // reloads in it), so each browser tab gets a stable id — this is what
408
+ // lets browser://tabs show every open tab instead of one 'default'.
409
+ const TAB_ID = (() => {
410
+ try {
411
+ let t = sessionStorage.getItem('lensmcp:tabId');
412
+ if (!t) { t = 'tab-' + Math.random().toString(36).slice(2, 10); sessionStorage.setItem('lensmcp:tabId', t); }
413
+ return t;
414
+ } catch (e) { return 'tab-' + Math.random().toString(36).slice(2, 10); }
415
+ })();
416
+
417
+ function send(env) {
418
+ env.at = Date.now();
419
+ env.tabId = TAB_ID;
420
+ if (ws && ws.readyState === 1) ws.send(JSON.stringify(env));
421
+ else queue.push(env);
422
+ }
423
+ function open() {
424
+ try { ws = new WebSocket(WS_URL); } catch (e) { setTimeout(open, 1000); return; }
425
+ ws.addEventListener('open', () => {
426
+ openOnce = true;
427
+ while (queue.length) { try { ws.send(JSON.stringify(queue.shift())); } catch {} }
428
+ send({ kind: 'ready', userAgent: navigator.userAgent, url: location.href });
429
+ });
430
+ ws.addEventListener('close', () => { if (openOnce) setTimeout(open, 1000); });
431
+ ws.addEventListener('error', () => { /* ignore — close handler reconnects */ });
432
+ }
433
+ open();
434
+
435
+ // Bridge for in-page instrumentation (@lensmcp/react-instrumentation,
436
+ // @lensmcp/valtio-instrumentation). Their publish() calls land here and
437
+ // ride the same WS as a 'publish' envelope, so React renders + Valtio
438
+ // updates reach react:// / valtio://.
439
+ window.__LENSMCP_PUBLISH__ = (envelope) => {
440
+ try {
441
+ send({
442
+ kind: 'publish',
443
+ source: envelope.source,
444
+ category: envelope.category,
445
+ severity: envelope.severity,
446
+ title: envelope.title,
447
+ message: envelope.message,
448
+ fingerprint: envelope.fingerprint,
449
+ context: envelope.context,
450
+ raw: envelope.raw,
451
+ });
452
+ } catch {}
453
+ };
454
+
455
+ // Errors
456
+ window.addEventListener('error', (e) => {
457
+ send({
458
+ kind: 'error',
459
+ message: e.message,
460
+ stack: e.error && e.error.stack,
461
+ source: e.filename,
462
+ lineno: e.lineno,
463
+ colno: e.colno,
464
+ });
465
+ }, true);
466
+ window.addEventListener('unhandledrejection', (e) => {
467
+ send({
468
+ kind: 'unhandledrejection',
469
+ reason: e.reason && (e.reason.stack || e.reason.message || String(e.reason)),
470
+ });
471
+ });
472
+
473
+ // Console
474
+ for (const level of ['log','info','warn','error','debug']) {
475
+ const original = console[level];
476
+ console[level] = function(...args) {
477
+ try { send({ kind: 'console', level, args: args.map((a) => safe(a)) }); } catch {}
478
+ return original.apply(this, args);
479
+ };
480
+ }
481
+
482
+ // fetch
483
+ const origFetch = window.fetch.bind(window);
484
+ window.fetch = async function(input, init) {
485
+ const method = (init && init.method) || (input && input.method) || 'GET';
486
+ const url = typeof input === 'string' ? input : (input && (input.url || String(input)));
487
+ const start = Date.now();
488
+ try {
489
+ const res = await origFetch(input, init);
490
+ send({ kind: 'fetch', method, url, status: res.status, ok: res.ok, durationMs: Date.now() - start });
491
+ return res;
492
+ } catch (err) {
493
+ send({ kind: 'fetch', method, url, error: err && (err.message || String(err)), durationMs: Date.now() - start });
494
+ throw err;
495
+ }
496
+ };
497
+
498
+ // Route changes (History API + popstate)
499
+ const origPush = history.pushState;
500
+ const origReplace = history.replaceState;
501
+ function notify(from) { send({ kind: 'route', url: location.href, from }); }
502
+ history.pushState = function(...args) { const from = location.href; const r = origPush.apply(this, args); notify(from); return r; };
503
+ history.replaceState = function(...args) { const from = location.href; const r = origReplace.apply(this, args); notify(from); return r; };
504
+ window.addEventListener('popstate', () => notify(undefined));
505
+
506
+ function safe(v) {
507
+ if (v === null) return null;
508
+ const t = typeof v;
509
+ if (t === 'string' || t === 'number' || t === 'boolean') return v;
510
+ try { return JSON.parse(JSON.stringify(v)); } catch { return String(v); }
511
+ }
512
+ })();
513
+ `;
514
+ }
package/lib/types.d.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The wire format used between the injected `@lensmcp/client-runtime`
3
+ * and the Vite plugin's WebSocket. Kept intentionally narrow — the
4
+ * client runtime *only* emits these envelopes, never anything else.
5
+ */
6
+ export type ClientEnvelope = ({
7
+ kind: 'error';
8
+ at: number;
9
+ message: string;
10
+ stack?: string;
11
+ source?: string;
12
+ lineno?: number;
13
+ colno?: number;
14
+ } | {
15
+ kind: 'unhandledrejection';
16
+ at: number;
17
+ reason: string;
18
+ } | {
19
+ kind: 'console';
20
+ at: number;
21
+ level: 'log' | 'info' | 'warn' | 'error' | 'debug';
22
+ args: unknown[];
23
+ } | {
24
+ kind: 'fetch';
25
+ at: number;
26
+ method: string;
27
+ url: string;
28
+ status?: number;
29
+ durationMs?: number;
30
+ ok?: boolean;
31
+ error?: string;
32
+ } | {
33
+ kind: 'route';
34
+ at: number;
35
+ url: string;
36
+ from?: string;
37
+ } | {
38
+ kind: 'ready';
39
+ at: number;
40
+ userAgent: string;
41
+ url: string;
42
+ } | {
43
+ kind: 'publish';
44
+ at: number;
45
+ source: string;
46
+ category: string;
47
+ severity?: string;
48
+ title: string;
49
+ message?: string;
50
+ fingerprint?: string;
51
+ context?: Record<string, unknown>;
52
+ raw?: unknown;
53
+ }) & {
54
+ /** Per-tab identity stamped by the client runtime (sessionStorage is per-tab) — keys `browser://tabs`. */
55
+ tabId?: string;
56
+ };
57
+ export interface LensmcpViteOptions {
58
+ /** Whether the plugin should attach anything. Production: false. */
59
+ enabled?: boolean;
60
+ /** Override the WS port. By default an ephemeral port is selected. */
61
+ wsPort?: number;
62
+ /** Bind address for the WS. Localhost by default. */
63
+ wsHost?: string;
64
+ /** Inject the client runtime via <script>. Default true. */
65
+ injectClient?: boolean;
66
+ /** Alias `valtio` → the instrumented drop-in in dev. Default true. */
67
+ aliasValtio?: boolean;
68
+ /** Run the LensMCP source transform (root-wrap + hooks + JSX ids). Default true. */
69
+ transformSource?: boolean;
70
+ }
71
+ export interface LensmcpViteRuntime {
72
+ /**
73
+ * The WS port the plugin is listening on. Available after Vite's
74
+ * `configureServer` hook fires.
75
+ */
76
+ wsPort(): number | undefined;
77
+ }
78
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/lib/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,cAAc,GAAG,CACzB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAChH;IAAE,IAAI,EAAE,oBAAoB,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC1D;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;IAAC,IAAI,EAAE,OAAO,EAAE,CAAA;CAAE,GACpG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAC9H;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GACzD;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAK7D;IACE,IAAI,EAAE,SAAS,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,GAAG,CAAC,EAAE,OAAO,CAAC;CACf,CACJ,GAAG;IACF,0GAA0G;IAC1G,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,MAAM,WAAW,kBAAkB;IACjC,oEAAoE;IACpE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,sEAAsE;IACtE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4DAA4D;IAC5D,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,sEAAsE;IACtE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,oFAAoF;IACpF,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,MAAM,IAAI,MAAM,GAAG,SAAS,CAAC;CAC9B"}
package/lib/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@lensmcp/vite-plugin",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "main": "./index.js",
6
+ "module": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ "./package.json": "./package.json",
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "import": "./index.js",
13
+ "default": "./index.js"
14
+ }
15
+ },
16
+ "dependencies": {
17
+ "@babel/core": "^7.0.0",
18
+ "@lensmcp/core": "1.0.0",
19
+ "@lensmcp/protocol-types": "1.0.0",
20
+ "@lensmcp/react-instrumentation": "1.0.0",
21
+ "@lensmcp/valtio-instrumentation": "1.0.0",
22
+ "tslib": "^2.3.0",
23
+ "ws": "^8.21.0"
24
+ },
25
+ "peerDependencies": {
26
+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
27
+ },
28
+ "license": "Apache-2.0",
29
+ "homepage": "https://github.com/kiwiapps-ltd/lensmcp#readme",
30
+ "bugs": {
31
+ "url": "https://github.com/kiwiapps-ltd/lensmcp/issues"
32
+ },
33
+ "engines": {
34
+ "node": ">=18"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "description": "LensMCP Vite plugin — valtio alias, source transform, and browser event bridge.",
40
+ "keywords": [
41
+ "lensmcp",
42
+ "mcp",
43
+ "observability",
44
+ "ai-agents",
45
+ "claude",
46
+ "vite",
47
+ "vite-plugin"
48
+ ],
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/kiwiapps-ltd/lensmcp.git",
52
+ "directory": "libs/vite-plugin"
53
+ }
54
+ }