@runic-artifex/vite-plugin-runic 0.19.0 → 0.20.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.
@@ -0,0 +1,72 @@
1
+ import type { RunicInspectComponent, RunicInspectLocation } from "./inspect-data.js";
2
+ /** What the lookups read from a DOM node; plain objects stand in for elements in tests. */
3
+ export type NodeLike = Record<string, unknown> & {
4
+ readonly parentElement?: NodeLike | null;
5
+ };
6
+ /** `path` as an absolute file path: relative paths are relative to the Vite root. */
7
+ export declare function absolutePath(path: string, root: string | undefined): string;
8
+ /** The React component of an element and its owners, with the element fiber's `_debugStack`. */
9
+ export declare function reactComponent(node: NodeLike): {
10
+ component: RunicInspectComponent;
11
+ stack: string | undefined;
12
+ } | undefined;
13
+ /** A frame of an `Error.stack` in the V8 (`at f (url:1:2)`) or JavaScriptCore/Gecko (`f@url:1:2`) form. */
14
+ export interface StackFrame {
15
+ readonly name: string;
16
+ readonly url: string;
17
+ /** 1-based. */
18
+ readonly line: number;
19
+ /** 1-based. */
20
+ readonly column: number;
21
+ }
22
+ export declare function parseStack(stack: string): StackFrame[];
23
+ /** The first frame of application code: not React's, not a pre-bundled dependency, not a Vite client module. */
24
+ export declare function applicationFrame(frames: readonly StackFrame[]): StackFrame | undefined;
25
+ /** Decodes source map `mappings`: per generated line, segments of `[column, source, line, column]` (0-based, absolute). */
26
+ export declare function decodeMappings(mappings: string): number[][][];
27
+ export interface SourceMapLike {
28
+ readonly sources: readonly (string | null)[];
29
+ readonly sourceRoot?: string;
30
+ readonly mappings: string;
31
+ }
32
+ /** The original `{ source, line, column }` (1-based) of a generated 1-based position, or undefined. */
33
+ export declare function originalPosition(map: SourceMapLike, line: number, column: number): {
34
+ source: string;
35
+ line: number;
36
+ column: number;
37
+ } | undefined;
38
+ /** The inline source map of a served module's code (`//# sourceMappingURL=data:application/json;base64,…`). */
39
+ export declare function inlineSourceMap(code: string): SourceMapLike | undefined;
40
+ /**
41
+ * The file of a source map's `source` for a module served at `url`: an absolute path as it is (Vite's maps name the
42
+ * file), a path relative to the module resolved as a URL path below the Vite root, `/@fs/` stripped.
43
+ */
44
+ export declare function sourceFile(source: string, url: string, root: string | undefined): string;
45
+ /** Resolves a frame of a served module to its original location through the module's inline source map. */
46
+ export declare function resolveFrame(frame: StackFrame, root: string | undefined, fetchText: (url: string) => Promise<string | undefined>): Promise<RunicInspectLocation>;
47
+ export declare function vueComponent(node: NodeLike): RunicInspectComponent | undefined;
48
+ export declare function svelteComponent(node: NodeLike, root: string | undefined): RunicInspectComponent | undefined;
49
+ /** The global `ng` of an Angular application in development mode. */
50
+ export interface AngularDebug {
51
+ getComponent?(element: unknown): unknown;
52
+ getOwningComponent?(element: unknown): unknown;
53
+ getHostElement?(component: unknown): unknown;
54
+ }
55
+ export declare function angularComponent(node: NodeLike, ng: AngularDebug | undefined, root: string | undefined): RunicInspectComponent | undefined;
56
+ /**
57
+ * The framework component of a node or its nearest ancestor that has one, without a React element's location, and the
58
+ * stack frame that location comes from.
59
+ */
60
+ export declare function findComponentSync(start: NodeLike, root: string | undefined, ng: AngularDebug | undefined): {
61
+ readonly component: RunicInspectComponent;
62
+ readonly frame?: StackFrame;
63
+ } | undefined;
64
+ /**
65
+ * The framework component of a node or its nearest ancestor that has one. A React element's location needs the
66
+ * module's source map, so `fetchText` reads served modules.
67
+ */
68
+ export declare function findComponent(start: NodeLike, options: {
69
+ readonly root?: string | undefined;
70
+ readonly ng?: AngularDebug | undefined;
71
+ readonly fetchText: (url: string) => Promise<string | undefined>;
72
+ }): Promise<RunicInspectComponent | undefined>;
@@ -0,0 +1,333 @@
1
+ // Runic Inspect: an element's framework component, from each framework's own development metadata. Nothing here is
2
+ // an API of the frameworks; each lookup is best effort and gives up quietly.
3
+ //
4
+ // - React 19: the element's fiber (`__reactFiber$…`), its owning components, and its `_debugStack` (the stack where
5
+ // the JSX element was created), resolved to the original file through the served module's source map.
6
+ // - Vue 3: `__vueParentComponent` and the component's `__file` (file only).
7
+ // - Svelte 5: `__svelte_meta.loc`, the element's `{ file, line, column }` in its component.
8
+ // - Angular: `ng.getComponent`/`ng.getOwningComponent` and the class's `ɵcmp.debugInfo` (Angular 17.1+).
9
+ const maximumOwners = 8;
10
+ const maximumAncestors = 50;
11
+ function basename(file) {
12
+ const name = file.split(/[\\/]/u).pop() ?? file;
13
+ const dot = name.lastIndexOf(".");
14
+ return dot > 0 ? name.slice(0, dot) : name;
15
+ }
16
+ /** `path` as an absolute file path: relative paths are relative to the Vite root. */
17
+ export function absolutePath(path, root) {
18
+ if (root === undefined || /^(?:[a-z]:)?[\\/]/iu.test(path))
19
+ return path;
20
+ return `${root.replace(/[\\/]+$/u, "")}/${path.replace(/^\.\//u, "")}`;
21
+ }
22
+ function reactFiber(node) {
23
+ for (const key of Object.keys(node)) {
24
+ if (key.startsWith("__reactFiber$"))
25
+ return node[key];
26
+ }
27
+ return undefined;
28
+ }
29
+ function reactName(type) {
30
+ if (typeof type === "function") {
31
+ const named = type;
32
+ return typeof named.displayName === "string" ? named.displayName : typeof named.name === "string" && named.name !== "" ? named.name : undefined;
33
+ }
34
+ if (typeof type === "object" && type !== null) {
35
+ const wrapped = type;
36
+ if (typeof wrapped.displayName === "string")
37
+ return wrapped.displayName;
38
+ return reactName(wrapped.render) ?? reactName(wrapped.type);
39
+ }
40
+ return undefined;
41
+ }
42
+ /** The React component of an element and its owners, with the element fiber's `_debugStack`. */
43
+ export function reactComponent(node) {
44
+ const fiber = reactFiber(node);
45
+ if (fiber === undefined)
46
+ return undefined;
47
+ const owners = [];
48
+ for (let current = fiber.return; current && owners.length <= maximumOwners; current = current.return) {
49
+ // Host components (strings) and React's own wrappers (Fragment, Context, Suspense) have no name of their own.
50
+ if (typeof current.type === "string")
51
+ continue;
52
+ const name = reactName(current.type);
53
+ if (name !== undefined)
54
+ owners.push(name);
55
+ }
56
+ if (owners.length === 0)
57
+ return undefined;
58
+ let stack;
59
+ try {
60
+ const value = fiber._debugStack?.stack;
61
+ if (typeof value === "string")
62
+ stack = value;
63
+ }
64
+ catch { /* Not readable. */ }
65
+ return { component: { framework: "react", name: owners[0], owners: owners.slice(1) }, stack };
66
+ }
67
+ export function parseStack(stack) {
68
+ const frames = [];
69
+ for (const raw of stack.split("\n")) {
70
+ const line = raw.trim();
71
+ const v8 = /^at (?:(.*?) \()?(?:async )?(.+?):(\d+):(\d+)\)?$/u.exec(line);
72
+ const other = v8 === null ? /^(.*?)@(.+?):(\d+):(\d+)$/u.exec(line) : null;
73
+ const match = v8 ?? other;
74
+ if (match === null)
75
+ continue;
76
+ frames.push({ name: match[1] ?? "", url: match[2], line: Number(match[3]), column: Number(match[4]) });
77
+ }
78
+ return frames;
79
+ }
80
+ /** The first frame of application code: not React's, not a pre-bundled dependency, not a Vite client module. */
81
+ export function applicationFrame(frames) {
82
+ return frames.find((frame) => /^https?:/u.test(frame.url)
83
+ && !/\/node_modules\/|\/\.vite\/deps\/|\/@vite\/|\/@id\/|\/@react-refresh/u.test(frame.url));
84
+ }
85
+ // Source maps: the inline map Vite adds to each served module, decoded far enough to map one position.
86
+ const base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
87
+ const base64Values = new Map([...base64].map((character, index) => [character, index]));
88
+ /** Decodes source map `mappings`: per generated line, segments of `[column, source, line, column]` (0-based, absolute). */
89
+ export function decodeMappings(mappings) {
90
+ const lines = [];
91
+ let source = 0, originalLine = 0, originalColumn = 0;
92
+ for (const text of mappings.split(";")) {
93
+ const segments = [];
94
+ let column = 0;
95
+ for (const segmentText of text.split(",")) {
96
+ if (segmentText.length === 0)
97
+ continue;
98
+ const values = [];
99
+ let value = 0, shift = 0;
100
+ for (const character of segmentText) {
101
+ const digit = base64Values.get(character);
102
+ if (digit === undefined)
103
+ return lines;
104
+ value += (digit & 31) << shift;
105
+ if (digit & 32) {
106
+ shift += 5;
107
+ continue;
108
+ }
109
+ values.push(value & 1 ? -(value >>> 1) : value >>> 1);
110
+ value = 0;
111
+ shift = 0;
112
+ }
113
+ column += values[0] ?? 0;
114
+ if (values.length >= 4) {
115
+ source += values[1];
116
+ originalLine += values[2];
117
+ originalColumn += values[3];
118
+ segments.push([column, source, originalLine, originalColumn]);
119
+ }
120
+ }
121
+ lines.push(segments);
122
+ }
123
+ return lines;
124
+ }
125
+ /** The original `{ source, line, column }` (1-based) of a generated 1-based position, or undefined. */
126
+ export function originalPosition(map, line, column) {
127
+ const segments = decodeMappings(map.mappings)[line - 1];
128
+ if (segments === undefined || segments.length === 0)
129
+ return undefined;
130
+ let best;
131
+ for (const segment of segments) {
132
+ if (segment[0] <= column - 1)
133
+ best = segment;
134
+ else
135
+ break;
136
+ }
137
+ best ??= segments[0];
138
+ const source = map.sources[best[1]];
139
+ if (typeof source !== "string")
140
+ return undefined;
141
+ const root = map.sourceRoot ?? "";
142
+ return { source: root === "" || /^(?:[a-z]+:|\/)/iu.test(source) ? source : `${root.replace(/\/?$/u, "/")}${source}`, line: best[2] + 1, column: best[3] + 1 };
143
+ }
144
+ /** The inline source map of a served module's code (`//# sourceMappingURL=data:application/json;base64,…`). */
145
+ export function inlineSourceMap(code) {
146
+ const match = /\/\/[#@] sourceMappingURL=data:application\/json[^,]*;base64,([A-Za-z0-9+/=]+)\s*$/u.exec(code);
147
+ if (match === null)
148
+ return undefined;
149
+ try {
150
+ const binary = atob(match[1]);
151
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
152
+ const map = JSON.parse(new TextDecoder().decode(bytes));
153
+ return typeof map.mappings === "string" && Array.isArray(map.sources) ? map : undefined;
154
+ }
155
+ catch {
156
+ return undefined;
157
+ }
158
+ }
159
+ /**
160
+ * The file of a source map's `source` for a module served at `url`: an absolute path as it is (Vite's maps name the
161
+ * file), a path relative to the module resolved as a URL path below the Vite root, `/@fs/` stripped.
162
+ */
163
+ export function sourceFile(source, url, root) {
164
+ if (root !== undefined && source.startsWith(root))
165
+ return source;
166
+ if (/^[a-z]:[\\/]/iu.test(source))
167
+ return source;
168
+ if (source.startsWith("/") && root === undefined)
169
+ return source;
170
+ let path;
171
+ try {
172
+ path = decodeURIComponent(new URL(source, url).pathname);
173
+ }
174
+ catch {
175
+ return source;
176
+ }
177
+ if (path.startsWith("/@fs/"))
178
+ return path.slice(4);
179
+ // A rooted source outside the Vite root (a monorepo package) is a file path already.
180
+ if (source.startsWith("/") && !source.startsWith("/src/"))
181
+ return source;
182
+ return absolutePath(path.replace(/^\//u, ""), root);
183
+ }
184
+ /** Resolves a frame of a served module to its original location through the module's inline source map. */
185
+ export async function resolveFrame(frame, root, fetchText) {
186
+ const fallback = () => {
187
+ let path = frame.url;
188
+ try {
189
+ path = decodeURIComponent(new URL(frame.url).pathname);
190
+ }
191
+ catch { /* keep the URL */ }
192
+ return { file: path.startsWith("/@fs/") ? path.slice(4) : absolutePath(path.replace(/^\//u, ""), root),
193
+ line: frame.line, column: frame.column, editor: "vite" };
194
+ };
195
+ const code = await fetchText(frame.url);
196
+ const map = code === undefined ? undefined : inlineSourceMap(code);
197
+ const position = map === undefined ? undefined : originalPosition(map, frame.line, frame.column);
198
+ if (position === undefined)
199
+ return fallback();
200
+ return { file: sourceFile(position.source, frame.url, root), line: position.line, column: position.column, editor: "vite" };
201
+ }
202
+ function vueName(instance) {
203
+ const type = instance.type;
204
+ if (type === undefined)
205
+ return undefined;
206
+ if (typeof type.name === "string" && type.name !== "")
207
+ return type.name;
208
+ if (typeof type.__name === "string" && type.__name !== "")
209
+ return type.__name;
210
+ return typeof type.__file === "string" ? basename(type.__file) : undefined;
211
+ }
212
+ export function vueComponent(node) {
213
+ const instance = node["__vueParentComponent"];
214
+ if (typeof instance !== "object" || instance === null)
215
+ return undefined;
216
+ const name = vueName(instance) ?? "Anonymous";
217
+ const owners = [];
218
+ for (let parent = instance.parent; parent && owners.length < maximumOwners; parent = parent.parent) {
219
+ const owner = vueName(parent);
220
+ if (owner !== undefined)
221
+ owners.push(owner);
222
+ }
223
+ const file = instance.type?.__file;
224
+ return {
225
+ framework: "vue", name, owners,
226
+ ...(typeof file === "string" ? { location: { file, line: 1, column: 1, editor: "vite" } } : {}),
227
+ };
228
+ }
229
+ export function svelteComponent(node, root) {
230
+ const meta = node["__svelte_meta"];
231
+ const loc = meta?.loc;
232
+ if (typeof loc?.file !== "string")
233
+ return undefined;
234
+ const owners = [];
235
+ for (let parent = meta.parent; parent && owners.length < maximumOwners; parent = parent.parent) {
236
+ if (parent.type === "component" && typeof parent.file === "string")
237
+ owners.push(basename(parent.file));
238
+ }
239
+ const line = typeof loc.line === "number" ? loc.line : 1;
240
+ // Svelte's column is 0-based.
241
+ const column = typeof loc.column === "number" ? loc.column + 1 : 1;
242
+ return {
243
+ framework: "svelte", name: basename(loc.file), owners: owners.filter((owner) => owner !== basename(loc.file)),
244
+ location: { file: absolutePath(loc.file, root), line, column, editor: "vite" },
245
+ };
246
+ }
247
+ function angularClass(instance) {
248
+ return typeof instance === "object" && instance !== null ? instance.constructor : undefined;
249
+ }
250
+ function angularName(type) {
251
+ const className = type?.ɵcmp?.debugInfo?.className;
252
+ if (typeof className === "string")
253
+ return className;
254
+ return typeof type?.name === "string" && type.name !== "" ? type.name : undefined;
255
+ }
256
+ export function angularComponent(node, ng, root) {
257
+ if (ng === undefined || typeof ng.getOwningComponent !== "function")
258
+ return undefined;
259
+ let instance;
260
+ try {
261
+ instance = ng.getComponent?.(node) ?? ng.getOwningComponent(node);
262
+ }
263
+ catch {
264
+ return undefined;
265
+ }
266
+ const type = angularClass(instance);
267
+ const name = angularName(type);
268
+ if (name === undefined)
269
+ return undefined;
270
+ const owners = [];
271
+ let current = instance;
272
+ try {
273
+ while (owners.length < maximumOwners) {
274
+ const host = ng.getHostElement?.(current);
275
+ const parentElement = host?.parentElement;
276
+ if (!parentElement)
277
+ break;
278
+ current = ng.getOwningComponent(parentElement);
279
+ const owner = angularName(angularClass(current));
280
+ if (owner === undefined)
281
+ break;
282
+ owners.push(owner);
283
+ }
284
+ }
285
+ catch { /* Owners are a bonus. */ }
286
+ const debugInfo = type?.ɵcmp?.debugInfo;
287
+ const file = debugInfo?.filePath;
288
+ return {
289
+ framework: "angular", name, owners,
290
+ ...(typeof file === "string" ? {
291
+ location: {
292
+ file: absolutePath(file, root),
293
+ // Angular's line is 0-based.
294
+ line: typeof debugInfo?.lineNumber === "number" ? debugInfo.lineNumber + 1 : 1,
295
+ column: 1, editor: "vite",
296
+ },
297
+ } : {}),
298
+ };
299
+ }
300
+ // -------------------------------------------------------------------------------------------------------------------
301
+ /**
302
+ * The framework component of a node or its nearest ancestor that has one, without a React element's location, and the
303
+ * stack frame that location comes from.
304
+ */
305
+ export function findComponentSync(start, root, ng) {
306
+ let node = start;
307
+ for (let depth = 0; node && depth < maximumAncestors; depth++, node = node.parentElement) {
308
+ const react = reactComponent(node);
309
+ if (react !== undefined) {
310
+ const frame = react.stack === undefined ? undefined : applicationFrame(parseStack(react.stack));
311
+ return frame === undefined ? { component: react.component } : { component: react.component, frame };
312
+ }
313
+ const component = svelteComponent(node, root) ?? vueComponent(node) ?? angularComponent(node, ng, root);
314
+ if (component !== undefined)
315
+ return { component };
316
+ }
317
+ return undefined;
318
+ }
319
+ /**
320
+ * The framework component of a node or its nearest ancestor that has one. A React element's location needs the
321
+ * module's source map, so `fetchText` reads served modules.
322
+ */
323
+ export async function findComponent(start, options) {
324
+ const found = findComponentSync(start, options.root, options.ng);
325
+ if (found?.frame === undefined)
326
+ return found?.component;
327
+ try {
328
+ return { ...found.component, location: await resolveFrame(found.frame, options.root, options.fetchText) };
329
+ }
330
+ catch {
331
+ return found.component;
332
+ }
333
+ }
@@ -0,0 +1,84 @@
1
+ import type { RunicHandlerAnalysis, RunicHandlerBinding, RunicHandlerCall } from "./handlers.js";
2
+ import { type AngularDebug, type NodeLike } from "./inspect-frameworks.js";
3
+ /** Where an element's bindings are: a source position (React, Svelte) or its listeners in components' files (Vue, Angular). */
4
+ export type HandlerProbe = {
5
+ readonly kind: "location";
6
+ readonly file: string;
7
+ readonly line: number;
8
+ readonly column: number;
9
+ readonly tag: string;
10
+ readonly events?: readonly string[];
11
+ } | {
12
+ readonly kind: "listeners";
13
+ readonly framework: "vue" | "angular";
14
+ readonly files: readonly string[];
15
+ readonly tag: string;
16
+ readonly listeners: readonly {
17
+ readonly event: string;
18
+ readonly text: string;
19
+ readonly value?: unknown;
20
+ /**
21
+ * Where the element is among the elements of its component with the same tag and a listener for the event,
22
+ * in document order (Angular, whose listeners do not show their template code).
23
+ */
24
+ readonly position?: {
25
+ readonly index: number;
26
+ readonly count: number;
27
+ };
28
+ }[];
29
+ /** A value of the component of `file`, by a template path such as `increment` or `step.commit`. */
30
+ readonly resolve?: (file: string, path: string) => unknown;
31
+ };
32
+ /** What the analysis says about an element. */
33
+ export interface SourceBindings {
34
+ readonly bindings: readonly RunicHandlerBinding[];
35
+ readonly calls: readonly RunicHandlerCall[];
36
+ readonly external: readonly {
37
+ readonly name: string;
38
+ readonly source: string;
39
+ }[];
40
+ /** Files whose analysis was not available, with the server's note. */
41
+ readonly unavailable: readonly string[];
42
+ }
43
+ /** The element's React probes: its own JSX, then up to three components around it. */
44
+ export declare function reactProbes(node: NodeLike, root: string | undefined, fetchText: (url: string) => Promise<string | undefined>): Promise<HandlerProbe[]>;
45
+ /** The element's Svelte probes: its own position, then the component tags around it. */
46
+ export declare function svelteProbes(node: NodeLike, root: string | undefined): HandlerProbe[];
47
+ /** The element's Vue probe: its listeners, in the files of its component and the components around it. */
48
+ export declare function vueProbes(node: NodeLike, root: string | undefined): HandlerProbe[];
49
+ interface AngularDebugWithListeners extends AngularDebug {
50
+ getListeners?(element: unknown): unknown;
51
+ }
52
+ /**
53
+ * The element's Angular probe: `ng.getListeners`, in the file of its component and the components around it. Angular
54
+ * 17+ gives the listener's wrapper, not the template's code, so each listener carries the element's position among
55
+ * its component's elements with the same tag and event.
56
+ */
57
+ export declare function angularProbes(node: NodeLike, ng: AngularDebugWithListeners | undefined, root: string | undefined): HandlerProbe[];
58
+ /** All probes of an element, by whichever framework rendered it. */
59
+ export declare function findProbes(node: NodeLike, options: {
60
+ readonly root?: string | undefined;
61
+ readonly ng?: AngularDebug | undefined;
62
+ readonly fetchText: (url: string) => Promise<string | undefined>;
63
+ }): Promise<HandlerProbe[]>;
64
+ /** The files the probes need the analysis of. */
65
+ export declare function probeFiles(probes: readonly HandlerProbe[]): string[];
66
+ /**
67
+ * Handler text as tokens, without what the compilers add: `$setup.`/`_ctx.` (Vue), `ctx.`/`ctx_r1.`/`i0.` and
68
+ * `ɵɵresetView` (Angular), `return`, parentheses and semicolons. Tokens are separated by single spaces, with a space
69
+ * at both ends, so that a handler is found in compiled code only as whole tokens.
70
+ */
71
+ export declare function normalizeHandler(text: string): string;
72
+ /**
73
+ * An analysis with the path it was asked for: Angular names a component's file relative to the project (under the
74
+ * Angular CLI the client has no root), the analysis by its absolute path.
75
+ */
76
+ export type RequestedAnalysis = RunicHandlerAnalysis & {
77
+ readonly requested?: string;
78
+ };
79
+ /**
80
+ * The bindings of an element: of its own position or listeners first; components around it only while nothing with
81
+ * calls matched (`<Button onClick={…}>` around a `<button onClick={props.onClick}>`).
82
+ */
83
+ export declare function matchBindings(probes: readonly HandlerProbe[], analyses: readonly RequestedAnalysis[]): SourceBindings;
84
+ export {};