Website Structure

This commit is contained in:
supalerk-ar66 2026-01-13 10:46:40 +07:00
parent 62812f2090
commit 71f0676a62
22365 changed files with 4265753 additions and 791 deletions

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025-PRESENT Anthony Fu <https://github.com/antfu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,106 @@
# vite-plugin-vue-tracer
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![bundle][bundle-src]][bundle-href]
[![JSDocs][jsdocs-src]][jsdocs-href]
[![License][license-src]][license-href]
Tracer for the source code of elements and vdoms in Vue SFC.
This is a designed to be a replacement of [`vite-plugin-vue-inspector`](https://www.npmjs.com/package/vite-plugin-vue-inspector) with a new approach, that utilize Vite's internal source map to resolve the source location, without injecting data-attributes to the DOM.
This plugin is also designed to be more modular, where you can use it as a standalone inspector plugin, or as a headless APIs to build your own inspector.
## Usage
```bash
npm i -D vite-plugin-vue-tracer
```
```ts
import { defineConfig } from 'vite'
import { VueTracer } from 'vite-plugin-vue-tracer'
export default defineConfig({
plugins: [
VueTracer(),
],
})
```
In the your entry file, add the following code:
```ts
// Only apply in development
if (import.meta.hot) {
import('vite-plugin-vue-tracer/client/overlay').then(({ events, state }) => {
// Enables the overlay
state.isEnabled = true
events.on('hover', (info) => {
// ...
})
events.on('click', (info) => {
// ...
openInEditor(info.fullpath) // 'src/app.vue:10:1'
state.isEnabled = false
})
})
}
```
Of if you want headless APIs, import `vite-plugin-vue-tracer/client/record` instead.
```ts
if (import.meta.hot) {
import('vite-plugin-vue-tracer/client/record')
.then(({
hasData,
findTraceFromElement,
findraceFromVNode,
findTraceAtPointer,
}) => {
const el = document.querySelector('.foo')
const trace = findTraceFromElement(el)
if (trace) {
console.log(trace)
}
})
}
```
## References
### Exports
- `vite-plugin-vue-tracer` - The Vite plugin entry, should be used in `vite.config.ts`
- `vite-plugin-vue-tracer/client/record` - The client entry for recording the trace data, this will be automatically injected into each component by the plugin. You don't normally need to import this.
- `vite-plugin-vue-tracer/client/listener` - The client entry for adding event listeners to the DOM and listening to the mouse events. It expose a ref `isEnabled` to control if the listeners are active. A `events` object is exposed for listening to those events. This entry is purely headless, does not come with any UI or styling.
- `vite-plugin-vue-tracer/client/overlay` - The builtin overlay UI for easier to use. A reactive `state` object is exposed to control the overlay's state. If you want to build your own UI, you can use the `listener` entry instead.
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © [Anthony Fu](https://github.com/antfu)
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/vite-plugin-vue-tracer?style=flat&colorA=080f12&colorB=1fa669
[npm-version-href]: https://npmjs.com/package/vite-plugin-vue-tracer
[npm-downloads-src]: https://img.shields.io/npm/dm/vite-plugin-vue-tracer?style=flat&colorA=080f12&colorB=1fa669
[npm-downloads-href]: https://npmjs.com/package/vite-plugin-vue-tracer
[bundle-src]: https://img.shields.io/bundlephobia/minzip/vite-plugin-vue-tracer?style=flat&colorA=080f12&colorB=1fa669&label=minzip
[bundle-href]: https://bundlephobia.com/result?p=vite-plugin-vue-tracer
[license-src]: https://img.shields.io/github/license/antfu/vite-plugin-vue-tracer.svg?style=flat&colorA=080f12&colorB=1fa669
[license-href]: https://github.com/antfu/vite-plugin-vue-tracer/blob/main/LICENSE
[jsdocs-src]: https://img.shields.io/badge/jsdocs-reference-080f12?style=flat&colorA=080f12&colorB=1fa669
[jsdocs-href]: https://www.jsdocs.io/package/vite-plugin-vue-tracer

View file

@ -0,0 +1,75 @@
import * as vue from 'vue';
import { ElementTraceInfo } from './record.mjs';
export { PositionInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition } from './record.mjs';
interface EventsMap {
[event: string]: any
}
interface DefaultEvents extends EventsMap {
[event: string]: (...args: any) => void
}
interface Unsubscribe {
(): void
}
interface Emitter<Events extends EventsMap = DefaultEvents> {
/**
* Calls each of the listeners registered for a given event.
*
* ```js
* ee.emit('tick', tickType, tickDuration)
* ```
*
* @param event The event name.
* @param args The arguments for listeners.
*/
emit<K extends keyof Events>(
this: this,
event: K,
...args: Parameters<Events[K]>
): void
/**
* Event names in keys and arrays with listeners in values.
*
* ```js
* emitter1.events = emitter2.events
* emitter2.events = { }
* ```
*/
events: Partial<{ [E in keyof Events]: Events[E][] }>
/**
* Add a listener for a given event.
*
* ```js
* const unbind = ee.on('tick', (tickType, tickDuration) => {
* count += 1
* })
*
* disable () {
* unbind()
* }
* ```
*
* @param event The event name.
* @param cb The listener function.
* @returns Unbind listener from event.
*/
on<K extends keyof Events>(this: this, event: K, cb: Events[K]): Unsubscribe
}
declare const lastMatchedElement: vue.ShallowRef<ElementTraceInfo | undefined, ElementTraceInfo | undefined>;
interface Events {
hover: (info: ElementTraceInfo | undefined, event: MouseEvent | PointerEvent) => void;
click: (info: ElementTraceInfo, event: MouseEvent | PointerEvent) => void;
enabled: () => void;
disabled: () => void;
}
declare const events: Emitter<Events>;
declare const isEnabled: vue.Ref<boolean, boolean>;
export { ElementTraceInfo, events, isEnabled, lastMatchedElement };
export type { Events };

View file

@ -0,0 +1,70 @@
import { shallowRef, customRef, ref } from 'vue';
import { getInternalStore, findTraceAtPointer } from './record.mjs';
export { ElementTraceInfo, findTraceFromElement, findTraceFromVNode, hasData, recordPosition } from './record.mjs';
let createNanoEvents = () => ({
emit(event, ...args) {
for (
let callbacks = this.events[event] || [],
i = 0,
length = callbacks.length;
i < length;
i++
) {
callbacks[i](...args);
}
},
events: {},
on(event, cb) {
(this.events[event] ||= []).push(cb);
return () => {
this.events[event] = this.events[event]?.filter(i => cb !== i);
}
}
});
const lastMatchedElement = shallowRef();
const _store = getInternalStore();
const events = _store.events ||= createNanoEvents();
const isEnabled = customRef(() => {
const value = ref(false);
return {
get() {
return value.value;
},
set(newValue) {
if (newValue === value.value)
return;
value.value = newValue;
if (newValue)
events.emit("enabled");
else
events.emit("disabled");
}
};
});
if (typeof document !== "undefined") {
document.addEventListener("pointermove", (e) => {
if (!isEnabled.value)
return;
const result = findTraceAtPointer({ x: e.clientX, y: e.clientY });
if (result?.el === lastMatchedElement.value?.el)
return;
lastMatchedElement.value = result;
events.emit("hover", result, e);
});
document.addEventListener("click", (e) => {
if (!isEnabled.value)
return;
const result = findTraceAtPointer({ x: e.clientX, y: e.clientY });
if (result) {
events.emit("click", result, e);
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}
}, true);
}
export { events, findTraceAtPointer, getInternalStore, isEnabled, lastMatchedElement };

View file

@ -0,0 +1,50 @@
import * as vue from 'vue';
import { ElementTraceInfo } from './record.mjs';
export { PositionInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition } from './record.mjs';
export { Events, events, isEnabled, lastMatchedElement } from './listeners.mjs';
declare const state: {
isEnabled: boolean;
isVisible: boolean;
isAnimated: boolean;
isFocused: boolean;
main?: {
pos: [source: string, line: number, column: number];
vnode: vue.VNode | undefined;
el: Element | undefined;
readonly filepath: string;
readonly fullpath: string;
readonly rect: {
height: number;
width: number;
x: number;
y: number;
readonly bottom: number;
readonly left: number;
readonly right: number;
readonly top: number;
toJSON: () => any;
} | undefined;
getElementsSameFile: () => Element[] | undefined;
getParent: () => ElementTraceInfo | undefined;
getElementsSamePosition: () => Element[] | undefined;
} | undefined;
sub: {
rects?: {
id: string;
rect: {
height: number;
width: number;
x: number;
y: number;
readonly bottom: number;
readonly left: number;
readonly right: number;
readonly top: number;
toJSON: () => any;
};
}[] | undefined;
};
};
export { ElementTraceInfo, state };

View file

@ -0,0 +1,193 @@
import { reactive, watchEffect } from 'vue';
import { isEnabled, events, lastMatchedElement } from './listeners.mjs';
export { ElementTraceInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition } from './record.mjs';
const state = reactive({
isEnabled,
isVisible: false,
isFocused: false,
isAnimated: true,
sub: {}
});
const ANIMATE_DURATION = "0.15s";
const PADDING_FOCUSED = 10;
function createOverlay() {
const overlay = document.createElement("div");
overlay.id = "vue-tracer-overlay";
Object.assign(overlay.style, {
position: "fixed",
top: "0",
left: "0",
bottom: "0",
right: "0",
zIndex: "999999",
pointerEvents: "none",
opacity: "0"
});
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
Object.assign(svg.style, {
position: "fixed",
top: "0",
left: "0",
bottom: "0",
pointerEvents: "none",
right: "0"
});
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
const mainText = document.createElement("div");
Object.assign(mainText.style, {
position: "fixed",
top: "0",
left: "0",
transition: `all ${ANIMATE_DURATION}`,
backgroundColor: "#197",
color: "#fff",
borderBottomLeftRadius: "4px",
borderBottomRightRadius: "4px",
padding: "1px 4px",
pointerEvents: "none",
fontSize: "10px",
fontFamily: "monospace",
display: "flex",
gap: "0.25rem",
boxShadow: "0 0 2px rgba(0,0,0,0.2)"
});
const mainTextTag = document.createElement("div");
const mainTextPath = document.createElement("div");
Object.assign(mainTextPath.style, {
opacity: "0.75",
fontSize: "9px"
});
mainText.appendChild(mainTextTag);
mainText.appendChild(mainTextPath);
const mainRect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
mainRect.setAttribute("fill", "#1972");
mainRect.setAttribute("stroke", "#197");
mainRect.setAttribute("rx", "4");
mainRect.setAttribute("ry", "4");
overlay.appendChild(svg);
overlay.appendChild(mainText);
svg.appendChild(mainRect);
document.body.appendChild(overlay);
watchEffect(() => {
overlay.style.transition = state.isAnimated ? `all ${ANIMATE_DURATION}` : "none";
mainText.style.transition = state.isAnimated ? `all ${ANIMATE_DURATION}` : "none";
mainRect.style.transition = state.isAnimated ? `all ${ANIMATE_DURATION}` : "none";
overlay.style.opacity = state.isVisible ? "1" : "0";
});
watchEffect(() => {
if (state.main && state.main.rect) {
const rect = state.main.rect;
mainRect.style.opacity = "1";
if (state.isFocused) {
mainRect.setAttribute("rx", "8");
mainRect.setAttribute("ry", "8");
mainRect.setAttribute("x", String(rect.left - PADDING_FOCUSED));
mainRect.setAttribute("y", String(rect.top - PADDING_FOCUSED));
mainRect.setAttribute("width", String(rect.width + PADDING_FOCUSED * 2));
mainRect.setAttribute("height", String(rect.height + PADDING_FOCUSED * 2));
mainRect.style.filter = "blur(1px)";
} else {
mainRect.setAttribute("rx", "4");
mainRect.setAttribute("ry", "4");
mainRect.setAttribute("x", String(rect.left));
mainRect.setAttribute("y", String(rect.top));
mainRect.setAttribute("width", String(rect.width));
mainRect.setAttribute("height", String(rect.height));
mainRect.style.filter = "";
}
mainRect.style.fill = state.isFocused ? "transparent" : "#1972";
mainText.style.opacity = state.isFocused ? "0" : "1";
mainTextTag.textContent = "";
let tagName = "";
if (state.main?.vnode?.type) {
if (typeof state.main?.vnode?.type === "string")
tagName = state.main.vnode.type;
else
tagName = state.main.vnode.type.name;
}
mainTextTag.textContent = tagName ? `<${tagName}>` : "";
mainTextPath.textContent = `${state.main.pos[0]}:${state.main.pos[1]}:${state.main.pos[2]}`;
Object.assign(mainText.style, {
left: `${rect.left + 3}px`,
top: `${rect.top + rect.height - 1}px`
});
} else {
mainText.style.opacity = "0";
mainRect.style.opacity = "0";
}
});
const subMap = /* @__PURE__ */ new Map();
watchEffect(() => {
const toRemove = new Set(subMap.keys());
for (const { id, rect } of state.sub.rects || []) {
toRemove.delete(id);
let cover = subMap.get(id);
if (!cover) {
cover = document.createElementNS("http://www.w3.org/2000/svg", "rect");
cover.setAttribute("fill", "#8482");
cover.setAttribute("stroke", "#848");
cover.setAttribute("rx", "4");
cover.setAttribute("ry", "4");
svg.appendChild(cover);
subMap.set(id, cover);
}
cover.style.transition = state.isAnimated ? `all ${ANIMATE_DURATION}` : "none";
cover.setAttribute("x", String(rect.left));
cover.setAttribute("y", String(rect.top));
cover.setAttribute("width", String(rect.width));
cover.setAttribute("height", String(rect.height));
cover.style.opacity = "1";
}
for (const id of toRemove) {
const cover = subMap.get(id);
if (cover) {
cover.style.opacity = "0";
setTimeout(() => cover.remove(), 300);
subMap.delete(id);
}
}
});
}
const elementId = /* @__PURE__ */ new WeakMap();
function getElementId(el) {
let id = elementId.get(el);
if (!id) {
id = Math.random().toString(16).slice(2);
elementId.set(el, id);
}
return id;
}
function update(result) {
if (!result) {
state.isVisible = false;
state.sub.rects = void 0;
state.main = void 0;
return;
}
state.isVisible = true;
state.main = result;
const samePos = result.getElementsSamePosition();
state.sub.rects = samePos?.map((el) => ({
id: getElementId(el),
rect: el.getBoundingClientRect()
}));
}
function init() {
createOverlay();
events.on("hover", (result) => {
update(result);
});
document.addEventListener("scroll", () => {
if (state.isVisible)
update(lastMatchedElement.value);
});
window.addEventListener("resize", () => {
if (state.isVisible)
update(lastMatchedElement.value);
});
}
init();
export { events, isEnabled, lastMatchedElement, state };

View file

@ -0,0 +1,44 @@
import { VNode } from 'vue';
type PositionInfo = [
source: string,
line: number,
column: number
];
interface Store {
hasData: boolean;
vnodeToPos: WeakMap<any, PositionInfo>;
fileToVNode: Map<string, WeakSet<any>>;
posToVNode: Map<string, Map<number, Map<number, WeakSet<any>>>>;
events?: any;
}
/**
* @internal
*/
declare function getInternalStore(): Store;
/**
* @internal
*/
declare function recordPosition(source: string, line: number, column: number, node: VNode): VNode;
declare class ElementTraceInfo {
pos: PositionInfo;
vnode: VNode | undefined;
el: Element | undefined;
constructor(pos: PositionInfo, el?: Element, vnode?: VNode);
get filepath(): string;
get fullpath(): string;
get rect(): DOMRect | undefined;
getElementsSameFile(): Element[] | undefined;
getParent(): ElementTraceInfo | undefined;
getElementsSamePosition(): Element[] | undefined;
}
declare function findTraceFromElement(el?: Element | null): ElementTraceInfo | undefined;
declare function findTraceFromVNode(vnode?: VNode, el?: Element): ElementTraceInfo | undefined;
declare function findTraceAtPointer(e: {
x: number;
y: number;
}): ElementTraceInfo | undefined;
declare function hasData(): boolean;
export { ElementTraceInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition };
export type { PositionInfo };

View file

@ -0,0 +1,123 @@
const KEY_IGNORE = "data-v-inspector-ignore";
const KEY_GLOBAL = "__vue_tracer__";
let _store = globalThis[KEY_GLOBAL];
if (!_store) {
_store = {
hasData: false,
vnodeToPos: /* @__PURE__ */ new WeakMap(),
fileToVNode: /* @__PURE__ */ new Map(),
posToVNode: /* @__PURE__ */ new Map()
};
Object.defineProperty(globalThis, KEY_GLOBAL, {
value: _store,
configurable: true,
enumerable: false
});
}
function getInternalStore() {
return _store;
}
function recordPosition(source, line, column, node) {
if (!node || typeof node === "string" || typeof node === "number")
return node;
if (!_store.hasData)
_store.hasData = true;
const props = node.props ||= {};
_store.vnodeToPos.set(props, [source, line, column]);
if (!_store.fileToVNode.has(source))
_store.fileToVNode.set(source, /* @__PURE__ */ new WeakSet());
_store.fileToVNode.get(source).add(props);
if (!_store.posToVNode.has(source))
_store.posToVNode.set(source, /* @__PURE__ */ new Map());
const lineMap = _store.posToVNode.get(source);
if (!lineMap.has(line))
lineMap.set(line, /* @__PURE__ */ new Map());
const columnMap = lineMap.get(line);
if (!columnMap.has(column))
columnMap.set(column, /* @__PURE__ */ new WeakSet());
columnMap.get(column).add(props);
return node;
}
function getPositionFromVNode(node) {
const props = node?.props;
if (props)
return _store.vnodeToPos.get(props);
}
class ElementTraceInfo {
pos;
vnode;
el;
constructor(pos, el, vnode) {
this.vnode = vnode;
this.pos = pos;
this.el = el;
}
get filepath() {
return this.pos[0];
}
get fullpath() {
let path = this.pos[0];
if (this.pos[1]) {
path += `:${this.pos[1]}`;
if (this.pos[2])
path += `:${this.pos[2]}`;
}
return path;
}
get rect() {
return this.el?.getBoundingClientRect();
}
getElementsSameFile() {
const pos = this.pos;
const fileVNodeSet = _store.fileToVNode.get(pos[0]);
if (!fileVNodeSet)
return;
const sameFile = fileVNodeSet ? Array.from(document.querySelectorAll("*")).filter((e) => e !== this.el && e.__vnode?.props && fileVNodeSet.has(e.__vnode?.props)) : [];
return sameFile;
}
getParent() {
const parentVNode = this.vnode?.parent;
const parentEl = this.el?.parentElement;
return findTraceFromVNode(parentVNode) ?? findTraceFromElement(parentEl);
}
getElementsSamePosition() {
if (typeof this.vnode?.type !== "string")
return;
const pos = this.pos;
const posVNodeSet = _store.posToVNode.get(pos[0])?.get(pos[1])?.get(pos[2]);
if (!posVNodeSet)
return;
const samePos = posVNodeSet ? Array.from(document.querySelectorAll(this.vnode.type)).filter((e) => e !== this.el && e.__vnode?.props && posVNodeSet.has(e.__vnode?.props)) : [];
return samePos;
}
}
function findTraceFromElement(el) {
if (!el)
return;
const vnode = el.__vnode;
return findTraceFromVNode(vnode, el);
}
function findTraceFromVNode(vnode, el) {
if (!vnode)
return;
const pos = getPositionFromVNode(vnode);
if (!pos)
return;
return new ElementTraceInfo(pos, el ?? vnode?.el ?? void 0, vnode);
}
function findTraceAtPointer(e) {
let elements = document.elementsFromPoint(e.x, e.y);
const ignoreIndex = elements.findIndex((node) => node?.hasAttribute?.(KEY_IGNORE));
if (ignoreIndex !== -1)
elements = elements.slice(ignoreIndex);
for (const el of elements) {
const match = findTraceFromElement(el);
if (match)
return match;
}
}
function hasData() {
return _store.hasData;
}
export { ElementTraceInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition };

View file

@ -0,0 +1,5 @@
import { DockClientScriptContext } from '@vitejs/devtools-kit/client';
declare function clientScriptSetup(ctx: DockClientScriptContext): void;
export { clientScriptSetup as default };

View file

@ -0,0 +1,21 @@
import { events, isEnabled } from 'vite-plugin-vue-tracer/client/listeners';
import { state } from 'vite-plugin-vue-tracer/client/overlay';
function clientScriptSetup(ctx) {
ctx.current.events.on("entry:activated", () => {
events.on("click", (e) => {
ctx.rpc.call("vite:core:open-in-editor", `${e.pos[0]}:${e.pos[1]}:${e.pos[2]}`);
state.isVisible = false;
state.isEnabled = false;
ctx.docks.switchEntry(null);
});
isEnabled.value = true;
state.isVisible = true;
});
ctx.current.events.on("entry:deactivated", () => {
isEnabled.value = false;
state.isVisible = false;
});
}
export { clientScriptSetup as default };

View file

@ -0,0 +1,26 @@
import { Plugin } from 'vite';
interface VueTracerOptions {
/**
* Enable this plugin or not, or only enable in certain environment.
*
* @default 'dev'
*/
enabled?: boolean | 'dev' | 'prod';
/**
* Resolve the record entry path to relative path.
* Normally, it should be true.
*
* @default true
*/
resolveRecordEntryPath?: boolean;
/**
* Enable Vite DevTools integration.
*
* @default false
*/
viteDevtools?: boolean;
}
declare function VueTracer(options?: VueTracerOptions): Plugin | undefined;
export { VueTracer, VueTracer as default };

View file

@ -0,0 +1,115 @@
import process from 'node:process';
import { walk } from 'estree-walker';
import { resolveModulePath } from 'exsolve';
import MagicString from 'magic-string';
import { relative, dirname, isAbsolute } from 'pathe';
import { SourceMapConsumer } from 'source-map-js';
const functions = [
"h",
"_createElementVNode",
"_createElementBlock",
"_createBlock",
"_createVNode",
"_createStaticVNode"
];
const testRe = new RegExp(`\\b(?:${functions.join("|")})\\(`);
function VueTracer(options) {
let {
enabled = "dev",
resolveRecordEntryPath = true,
viteDevtools = false
} = options || {};
if (enabled === false)
return;
const pathRecordDist = resolveModulePath("vite-plugin-vue-tracer/client/record", { from: import.meta.url });
const getRecordPath = (id) => {
if (!resolveRecordEntryPath)
return "vite-plugin-vue-tracer/client/record";
let related = relative(dirname(id), pathRecordDist);
if (!related.startsWith("./") && !isAbsolute(related))
related = `./${related}`;
return related;
};
return {
name: "vite-plugin-vue-tracer",
enforce: "post",
configResolved(config) {
if (enabled === "dev")
enabled = config.command === "serve";
else if (enabled === "prod")
enabled = config.command === "build";
},
transform(code, id) {
if (!enabled)
return;
if (this.environment.name !== "client")
return;
if (!code.includes("_sfc_render("))
return;
if (!code.match(testRe))
return;
if (code.includes("_tracer("))
return;
function offsetToPos(index) {
const lines = code.slice(0, index).split("\n");
return {
line: lines.length,
column: lines[lines.length - 1].length
};
}
const map = this.getCombinedSourcemap();
const consumer = new SourceMapConsumer(map);
const s = new MagicString(code);
const ast = this.parse(code);
let hit = false;
walk(ast, {
enter(node) {
if (node.type !== "CallExpression" || node.callee.type !== "Identifier")
return;
if (!functions.includes(node.callee.name))
return;
const { start, end } = node;
const pos = offsetToPos(start);
const original = consumer.originalPositionFor(pos);
if (original.source === null)
return;
hit = true;
s.appendLeft(start, `_tracer(${original.line},${original.column},`);
s.appendRight(end, `)`);
}
});
if (!hit)
return;
const related = relative(process.cwd(), id);
s.prepend(`import { recordPosition as _tracerRecordPosition } from ${JSON.stringify(getRecordPath(id))}
`);
s.append(`
function _tracer(line, column, vnode) { return _tracerRecordPosition(${JSON.stringify(related)}, line, column, vnode) }
`);
return {
code: s.toString(),
map: s.generateMap({ hires: true })
};
},
// Vite DevTools integration
...viteDevtools ? {
devtools: {
setup(ctx) {
ctx.docks.register({
id: "vue-tracer",
title: "Vue Tracer",
icon: "ph:crosshair-simple-duotone",
type: "action",
action: {
importFrom: "vite-plugin-vue-tracer/client/vite-devtools",
importName: "default"
}
});
}
}
} : {}
};
}
export { VueTracer, VueTracer as default };

View file

@ -0,0 +1,7 @@
Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,48 @@
# estree-walker
Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn).
## Installation
```bash
npm i estree-walker
```
## Usage
```js
var walk = require('estree-walker').walk;
var acorn = require('acorn');
ast = acorn.parse(sourceCode, options); // https://github.com/acornjs/acorn
walk(ast, {
enter(node, parent, prop, index) {
// some code happens
},
leave(node, parent, prop, index) {
// some code happens
}
});
```
Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called.
Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one.
Call `this.remove()` in either `enter` or `leave` to remove the current node.
## Why not use estraverse?
The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys.
estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.)
None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful.
## License
MIT

View file

@ -0,0 +1,38 @@
{
"name": "estree-walker",
"description": "Traverse an ESTree-compliant AST",
"version": "3.0.3",
"private": false,
"author": "Rich Harris",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Rich-Harris/estree-walker"
},
"type": "module",
"module": "./src/index.js",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./types/index.d.ts",
"import": "./src/index.js"
}
},
"types": "types/index.d.ts",
"scripts": {
"prepublishOnly": "tsc && npm test",
"test": "uvu test"
},
"dependencies": {
"@types/estree": "^1.0.0"
},
"devDependencies": {
"typescript": "^4.9.0",
"uvu": "^0.5.1"
},
"files": [
"src",
"types",
"README.md"
]
}

View file

@ -0,0 +1,152 @@
import { WalkerBase } from './walker.js';
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => Promise<void>} AsyncHandler
*/
export class AsyncWalker extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {AsyncHandler | undefined} */
this.enter = enter;
/** @type {AsyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
async visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
await this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!(await this.visit(item, node, key, i))) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
await this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
await this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}

View file

@ -0,0 +1,34 @@
import { SyncWalker } from './sync.js';
import { AsyncWalker } from './async.js';
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
export function walk(ast, { enter, leave }) {
const instance = new SyncWalker(enter, leave);
return instance.visit(ast, null);
}
/**
* @param {Node} ast
* @param {{
* enter?: AsyncHandler
* leave?: AsyncHandler
* }} walker
* @returns {Promise<Node | null>}
*/
export async function asyncWalk(ast, { enter, leave }) {
const instance = new AsyncWalker(enter, leave);
return await instance.visit(ast, null);
}

View file

@ -0,0 +1,152 @@
import { WalkerBase } from './walker.js';
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
export class SyncWalker extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {SyncHandler | undefined} */
this.enter = enter;
/** @type {SyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}

View file

@ -0,0 +1,61 @@
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
export class WalkerBase {
constructor() {
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) {
if (index != null) {
/** @type {Array<Node>} */ (parent[prop])[index] = node;
} else {
/** @type {Node} */ (parent[prop]) = node;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== undefined) {
/** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
} else {
delete parent[prop];
}
}
}
}

View file

@ -0,0 +1,36 @@
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => Promise<void>} AsyncHandler
*/
export class AsyncWalker extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter?: AsyncHandler | undefined, leave?: AsyncHandler | undefined);
/** @type {AsyncHandler | undefined} */
enter: AsyncHandler | undefined;
/** @type {AsyncHandler | undefined} */
leave: AsyncHandler | undefined;
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
visit<Parent extends import("estree").Node>(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Promise<Node | null>;
}
export type Node = import('estree').Node;
export type WalkerContext = import('./walker.js').WalkerContext;
export type AsyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => Promise<void>;
import { WalkerBase } from "./walker.js";

View file

@ -0,0 +1,32 @@
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
export function walk(ast: Node, { enter, leave }: {
enter?: SyncHandler;
leave?: SyncHandler;
}): Node | null;
/**
* @param {Node} ast
* @param {{
* enter?: AsyncHandler
* leave?: AsyncHandler
* }} walker
* @returns {Promise<Node | null>}
*/
export function asyncWalk(ast: Node, { enter, leave }: {
enter?: AsyncHandler;
leave?: AsyncHandler;
}): Promise<Node | null>;
export type Node = import('estree').Node;
export type SyncHandler = import('./sync.js').SyncHandler;
export type AsyncHandler = import('./async.js').AsyncHandler;

View file

@ -0,0 +1,36 @@
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
export class SyncWalker extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter?: SyncHandler | undefined, leave?: SyncHandler | undefined);
/** @type {SyncHandler | undefined} */
enter: SyncHandler | undefined;
/** @type {SyncHandler | undefined} */
leave: SyncHandler | undefined;
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit<Parent extends import("estree").Node>(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Node | null;
}
export type Node = import('estree').Node;
export type WalkerContext = import('./walker.js').WalkerContext;
export type SyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => void;
import { WalkerBase } from "./walker.js";

View file

@ -0,0 +1,39 @@
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
export class WalkerBase {
/** @type {boolean} */
should_skip: boolean;
/** @type {boolean} */
should_remove: boolean;
/** @type {Node | null} */
replacement: Node | null;
/** @type {WalkerContext} */
context: WalkerContext;
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace<Parent extends import("estree").Node>(parent: Parent | null | undefined, prop: keyof Parent | null | undefined, index: number | null | undefined, node: Node): void;
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove<Parent_1 extends import("estree").Node>(parent: Parent_1 | null | undefined, prop: keyof Parent_1 | null | undefined, index: number | null | undefined): void;
}
export type Node = import('estree').Node;
export type WalkerContext = {
skip: () => void;
remove: () => void;
replace: (node: Node) => void;
};

View file

@ -0,0 +1,81 @@
{
"name": "vite-plugin-vue-tracer",
"type": "module",
"version": "1.2.0",
"description": "Tracer for the source code of elements and vdoms in Vue SFC",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/antfu/vite-plugin-vue-tracer#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu/vite-plugin-vue-tracer.git"
},
"bugs": "https://github.com/antfu/vite-plugin-vue-tracer/issues",
"keywords": [
"vue",
"vite-plugin",
"devtools"
],
"exports": {
".": "./dist/index.mjs",
"./client/record": "./dist/client/record.mjs",
"./client/overlay": "./dist/client/overlay.mjs",
"./client/listeners": "./dist/client/listeners.mjs",
"./client/vite-devtools": "./dist/client/vite-devtools.mjs"
},
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"files": [
"dist"
],
"peerDependencies": {
"vite": "^6.0.0 || ^7.0.0",
"vue": "^3.5.0"
},
"dependencies": {
"estree-walker": "^3.0.3",
"exsolve": "^1.0.8",
"magic-string": "^0.30.21",
"pathe": "^2.0.3",
"source-map-js": "^1.2.1"
},
"devDependencies": {
"@antfu/eslint-config": "^6.7.1",
"@antfu/ni": "^28.0.0",
"@antfu/utils": "^9.3.0",
"@types/node": "^25.0.2",
"@vitejs/devtools": "^0.0.0-alpha.20",
"@vitejs/devtools-kit": "^0.0.0-alpha.20",
"bumpp": "^10.3.2",
"eslint": "^9.39.2",
"lint-staged": "^16.2.7",
"nanoevents": "^9.1.0",
"simple-git-hooks": "^2.13.1",
"tsx": "^4.21.0",
"typescript": "^5.9.3",
"unbuild": "^3.6.1",
"vite": "^7.3.0",
"vitest": "^4.0.15",
"vue": "^3.5.25",
"vue-tsc": "^3.1.8",
"vite-plugin-vue-tracer": "1.2.0"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
},
"lint-staged": {
"*": "eslint --fix"
},
"scripts": {
"build": "unbuild",
"dev": "unbuild --stub",
"lint": "eslint .",
"play": "nr -C playground play",
"release": "bumpp",
"start": "tsx src/index.ts",
"test": "vitest",
"typecheck": "vue-tsc --noEmit"
}
}