@eventra_dev/cli-plugin-vue 1.1.1 → 1.2.1
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/README.md +28 -2
- package/dist/component.d.ts +34 -0
- package/dist/component.d.ts.map +1 -0
- package/dist/component.js +245 -0
- package/dist/parse-vue-sfc.d.ts +19 -1
- package/dist/parse-vue-sfc.d.ts.map +1 -1
- package/dist/parse-vue-sfc.js +94 -14
- package/dist/transform.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<p align="center">
|
|
8
8
|
<a href="https://www.npmjs.com/package/@eventra_dev/cli-plugin-vue"><img alt="npm version" src="https://img.shields.io/npm/v/@eventra_dev/cli-plugin-vue.svg?style=flat-square&color=blue"></a>
|
|
9
9
|
<a href="https://www.npmjs.com/package/@eventra_dev/cli-plugin-vue"><img alt="npm downloads" src="https://img.shields.io/npm/dm/@eventra_dev/cli-plugin-vue.svg?style=flat-square&color=blue"></a>
|
|
10
|
-
<img alt="tests passing" src="https://img.shields.io/badge/tests-
|
|
10
|
+
<img alt="tests passing" src="https://img.shields.io/badge/tests-127%20passing-brightgreen?style=flat-square&logo=vitest&logoColor=white">
|
|
11
11
|
<img alt="coverage" src="https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square&logo=vitest&logoColor=white">
|
|
12
12
|
<img alt="node" src="https://img.shields.io/node/v/@eventra_dev/cli-plugin-vue?style=flat-square&color=darkgreen&logo=node.js&logoColor=white">
|
|
13
13
|
<a href="https://www.typescriptlang.org/"><img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-blue?style=flat-square&logo=typescript&logoColor=white"></a>
|
|
@@ -105,6 +105,31 @@ Tracking calls written in the template itself are read, not only `event` attribu
|
|
|
105
105
|
|
|
106
106
|
Read: `@click` / `v-on` handlers (one or several statements, multi-line arrow functions), `{{ }}` interpolations the source of `v-for` (`item in items()`), dynamic arguments (`:[name()]`, `@[event()]`) and the expressions of `v-bind`, `v-if`, `v-else-if`, `v-show`, `v-model`, `v-html` and `v-text`. They are placed in the same module as the script, so a function imported or defined there resolves normally; an argument that comes from a `v-for` variable is reported as a dynamic occurrence. The loop variables of `v-for` and `v-slot` parameters are not code and are skipped; the value of a custom directive (`v-focus="x"`) is left alone.
|
|
107
107
|
|
|
108
|
+
### Props of a component, whatever they are called
|
|
109
|
+
|
|
110
|
+
The prop does not have to be named `event`. If a component sends one of its props to a tracking call, every place that uses the component with a value for that prop is an event:
|
|
111
|
+
|
|
112
|
+
```vue
|
|
113
|
+
<!-- Button.vue -->
|
|
114
|
+
<script setup lang="ts">
|
|
115
|
+
import { Eventra } from '@eventra_dev/eventra-sdk'
|
|
116
|
+
const tracker = new Eventra({ apiKey: 'YOUR_KEY' })
|
|
117
|
+
const props = defineProps<{ analyticsName: string }>()
|
|
118
|
+
function onClick() { tracker.track(props.analyticsName) }
|
|
119
|
+
</script>
|
|
120
|
+
<template><button @click="onClick"><slot /></button></template>
|
|
121
|
+
|
|
122
|
+
<!-- Page.vue -->
|
|
123
|
+
<script setup lang="ts">
|
|
124
|
+
import Button from './Button.vue'
|
|
125
|
+
</script>
|
|
126
|
+
<template><Button analytics-name="checkout.cta">Pay</Button></template>
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`checkout.cta` is found. It works with `defineProps<{ ... }>()`, `defineProps([...])`, `defineProps({ ... })`, `withDefaults(...)`, a props object (`const props = defineProps(...)`) and a destructuring (`const { analyticsName } = defineProps(...)`), and also when the template reads the prop by its bare name (`@click="tracker.track(analyticsName)"`). A prop handed on to another component (`<Inner :name="props.analyticsName" />`) is followed. Props the component never tracks are not events. A prop that comes from a `v-for` variable is reported as a dynamic occurrence.
|
|
130
|
+
|
|
131
|
+
Not followed: Options API components (`props: [...]` read through `this`), `v-bind="obj"` spreads, components registered by name instead of imported, and a component whose normal `<script>` has its own `export default`.
|
|
132
|
+
|
|
108
133
|
## Nuxt
|
|
109
134
|
|
|
110
135
|
Nuxt pages, layouts, and components are ordinary `.vue` SFCs — parsed identically, no extra configuration needed.
|
|
@@ -149,7 +174,7 @@ No dependency on `@eventra_dev/eventra-cli` - the CLI adapts this shape internal
|
|
|
149
174
|
|
|
150
175
|
**100% statement/branch/function/line coverage** (v8 provider, `pnpm test:coverage`), enforced via a `coverage.thresholds` block in `vitest.config.ts`.
|
|
151
176
|
|
|
152
|
-
**
|
|
177
|
+
**127 unit tests** (vitest), covering:
|
|
153
178
|
|
|
154
179
|
| Area | Covers |
|
|
155
180
|
|---|---|
|
|
@@ -157,6 +182,7 @@ No dependency on `@eventra_dev/eventra-cli` - the CLI adapts this shape internal
|
|
|
157
182
|
| Template — literal | Nested elements, `v-if`/`v-for`, slots, multiple template roots |
|
|
158
183
|
| Template — dynamic | Raw expression passthrough, resolution through the merged script scope |
|
|
159
184
|
| Script-setup macros | All five compiler macros (`defineProps`/`defineEmits`/`defineExpose`/`defineOptions`/`withDefaults`) pass through without special-casing |
|
|
185
|
+
| Component props | `defineProps` in every spelling, props read through an object, a destructuring and bare template names, child components called with their props, name matching of tags to imports |
|
|
160
186
|
| Virtual module output | Single combined `.vue.ts`, export stub when script/template are empty |
|
|
161
187
|
| Plugin contract | `match()`, `includeGlobs`, `staticSinks`, `transform()` |
|
|
162
188
|
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { VueScriptBlock } from "./parse-vue-sfc";
|
|
2
|
+
export interface ComponentModule {
|
|
3
|
+
/** The `<script setup>` text with a function header in front of its statements; the closing `}` is the caller's. */
|
|
4
|
+
readonly code: string;
|
|
5
|
+
/** Names the template (and `v-bind` of a parent) can pass as props. */
|
|
6
|
+
readonly propNames: readonly string[];
|
|
7
|
+
/** The function's name, which the module exports as its default after the closing brace. */
|
|
8
|
+
readonly name: string;
|
|
9
|
+
}
|
|
10
|
+
/** Everything a script block declares at its top level, which the template can name. */
|
|
11
|
+
export interface ScriptBindings {
|
|
12
|
+
/** Local names of default imports (`import Button from "./Button.vue"`): the components a template can use. */
|
|
13
|
+
readonly components: readonly string[];
|
|
14
|
+
readonly declared: ReadonlySet<string>;
|
|
15
|
+
/** Some block has `export default`, which a component function exported as the default would clash with. */
|
|
16
|
+
readonly hasDefaultExport: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** The names a script block makes available to the template, or an empty set when it does not parse. */
|
|
19
|
+
export declare function scriptBindings(blocks: readonly VueScriptBlock[]): ScriptBindings;
|
|
20
|
+
/**
|
|
21
|
+
* Turns a `<script setup>` that declares props into the body of a function taking them, so the code
|
|
22
|
+
* the compiler already understands (a parameter flowing into a track() call) applies to a component:
|
|
23
|
+
*
|
|
24
|
+
* const props = defineProps<{ track: string }>() -> function Button(props) {
|
|
25
|
+
* const { track } = defineProps<...>() -> function Button({ track }) {
|
|
26
|
+
* defineProps(["track"]) -> function Button({ track }) {
|
|
27
|
+
*
|
|
28
|
+
* The imports stay above it, as they must; statements keep their line numbers. Returns null when the
|
|
29
|
+
* block is not a setup block that declares props, or is written in a way this does not follow
|
|
30
|
+
* (`export`s other than types, imports after other code, an external `src`), in which case the
|
|
31
|
+
* component is scanned as before.
|
|
32
|
+
*/
|
|
33
|
+
export declare function wrapScriptSetup(block: VueScriptBlock, componentName: string, declaredElsewhere: ReadonlySet<string>): ComponentModule | null;
|
|
34
|
+
//# sourceMappingURL=component.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"component.d.ts","sourceRoot":"","sources":["../src/component.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAWtD,MAAM,WAAW,eAAe;IAC9B,oHAAoH;IACpH,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,uEAAuE;IACvE,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,4FAA4F;IAC5F,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAID,wFAAwF;AACxF,MAAM,WAAW,cAAc;IAC7B,+GAA+G;IAC/G,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACvC,4GAA4G;IAC5G,QAAQ,CAAC,gBAAgB,EAAE,OAAO,CAAC;CACpC;AAuCD,wGAAwG;AACxG,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,GAAG,cAAc,CAiBhF;AA+DD;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,EAAE,iBAAiB,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,eAAe,GAAG,IAAI,CAwE5I"}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.scriptBindings = scriptBindings;
|
|
4
|
+
exports.wrapScriptSetup = wrapScriptSetup;
|
|
5
|
+
const compiler_sfc_1 = require("@vue/compiler-sfc");
|
|
6
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
7
|
+
function parseScript(block) {
|
|
8
|
+
const ts = block.lang === "ts" || block.lang === "tsx";
|
|
9
|
+
const plugins = [];
|
|
10
|
+
if (ts)
|
|
11
|
+
plugins.push("typescript");
|
|
12
|
+
if (block.lang === "tsx" || block.lang === "jsx")
|
|
13
|
+
plugins.push("jsx");
|
|
14
|
+
try {
|
|
15
|
+
return (0, compiler_sfc_1.babelParse)(block.content, { sourceType: "module", plugins }).program.body;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function patternNames(pattern, out) {
|
|
22
|
+
if (!pattern)
|
|
23
|
+
return;
|
|
24
|
+
if (pattern.type === "Identifier")
|
|
25
|
+
out.add(pattern.name);
|
|
26
|
+
else if (pattern.type === "ObjectPattern")
|
|
27
|
+
for (const property of pattern.properties)
|
|
28
|
+
patternNames(property.type === "RestElement" ? property.argument : property.value, out);
|
|
29
|
+
else if (pattern.type === "ArrayPattern")
|
|
30
|
+
for (const element of pattern.elements)
|
|
31
|
+
patternNames(element, out);
|
|
32
|
+
else if (pattern.type === "AssignmentPattern")
|
|
33
|
+
patternNames(pattern.left, out);
|
|
34
|
+
else
|
|
35
|
+
patternNames(pattern.argument, out); // RestElement
|
|
36
|
+
}
|
|
37
|
+
/** `export const a = 1` is the declaration it exports; anything else is itself. */
|
|
38
|
+
function unexported(statement) {
|
|
39
|
+
return statement.type === "ExportNamedDeclaration" && statement.declaration ? statement.declaration : statement;
|
|
40
|
+
}
|
|
41
|
+
function declaredNames(statements) {
|
|
42
|
+
const out = new Set();
|
|
43
|
+
for (const raw of statements) {
|
|
44
|
+
const statement = unexported(raw);
|
|
45
|
+
if (statement.type === "VariableDeclaration")
|
|
46
|
+
for (const declarator of statement.declarations)
|
|
47
|
+
patternNames(declarator.id, out);
|
|
48
|
+
else if ((statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") && statement.id)
|
|
49
|
+
out.add(statement.id.name);
|
|
50
|
+
else if (statement.type === "ImportDeclaration")
|
|
51
|
+
for (const specifier of statement.specifiers)
|
|
52
|
+
out.add(specifier.local.name);
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
/** The names a script block makes available to the template, or an empty set when it does not parse. */
|
|
57
|
+
function scriptBindings(blocks) {
|
|
58
|
+
const components = [];
|
|
59
|
+
const declared = new Set();
|
|
60
|
+
let hasDefaultExport = false;
|
|
61
|
+
for (const block of blocks) {
|
|
62
|
+
const statements = parseScript(block);
|
|
63
|
+
if (!statements)
|
|
64
|
+
continue;
|
|
65
|
+
hasDefaultExport ||= statements.some((statement) => statement.type === "ExportDefaultDeclaration");
|
|
66
|
+
for (const name of declaredNames(statements))
|
|
67
|
+
declared.add(name);
|
|
68
|
+
for (const statement of statements) {
|
|
69
|
+
if (statement.type !== "ImportDeclaration" || statement.importKind === "type")
|
|
70
|
+
continue;
|
|
71
|
+
for (const specifier of statement.specifiers) {
|
|
72
|
+
if (specifier.type === "ImportDefaultSpecifier")
|
|
73
|
+
components.push(specifier.local.name);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { components, declared, hasDefaultExport };
|
|
78
|
+
}
|
|
79
|
+
const isMacroCall = (node, name) => node?.type === "CallExpression" && node.callee.name === name;
|
|
80
|
+
/** `defineProps(...)` or `withDefaults(defineProps(...), {...})`, the call that declares the props. */
|
|
81
|
+
function propsCall(node) {
|
|
82
|
+
// `isMacroCall` is false for a missing node, so the assertions below only run on a real call
|
|
83
|
+
if (isMacroCall(node, "defineProps"))
|
|
84
|
+
return node;
|
|
85
|
+
if (isMacroCall(node, "withDefaults") && isMacroCall(node.arguments[0], "defineProps"))
|
|
86
|
+
return node.arguments[0];
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
function memberKeys(members, out) {
|
|
90
|
+
for (const member of members) {
|
|
91
|
+
if (member.type !== "TSPropertySignature" && member.type !== "TSMethodSignature")
|
|
92
|
+
continue;
|
|
93
|
+
const key = member.key;
|
|
94
|
+
if (key.type === "Identifier")
|
|
95
|
+
out.add(key.name);
|
|
96
|
+
else if (key.type === "StringLiteral")
|
|
97
|
+
out.add(key.value);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function typeKeys(type, statements, out, depth = 0) {
|
|
101
|
+
if (depth > 4)
|
|
102
|
+
return;
|
|
103
|
+
if (type.type === "TSTypeLiteral") {
|
|
104
|
+
memberKeys(type.members, out);
|
|
105
|
+
}
|
|
106
|
+
else if (type.type === "TSIntersectionType") {
|
|
107
|
+
for (const part of type.types)
|
|
108
|
+
typeKeys(part, statements, out, depth + 1);
|
|
109
|
+
}
|
|
110
|
+
else if (type.type === "TSTypeReference") {
|
|
111
|
+
for (const raw of statements) {
|
|
112
|
+
const statement = unexported(raw);
|
|
113
|
+
if (statement.type === "TSInterfaceDeclaration" && statement.id.name === type.typeName.name) {
|
|
114
|
+
memberKeys(statement.body.body, out);
|
|
115
|
+
for (const parent of statement.extends ?? []) {
|
|
116
|
+
typeKeys({ type: "TSTypeReference", typeName: parent.expression, start: 0, end: 0 }, statements, out, depth + 1);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else if (statement.type === "TSTypeAliasDeclaration" && statement.id.name === type.typeName.name) {
|
|
120
|
+
typeKeys(statement.typeAnnotation, statements, out, depth + 1);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function propKeys(call, statements) {
|
|
126
|
+
const out = new Set();
|
|
127
|
+
const typeArgument = call.typeParameters?.params?.[0];
|
|
128
|
+
if (typeArgument)
|
|
129
|
+
typeKeys(typeArgument, statements, out);
|
|
130
|
+
const argument = call.arguments[0];
|
|
131
|
+
if (argument?.type === "ArrayExpression") {
|
|
132
|
+
for (const element of argument.elements)
|
|
133
|
+
if (element?.type === "StringLiteral")
|
|
134
|
+
out.add(element.value);
|
|
135
|
+
}
|
|
136
|
+
else if (argument?.type === "ObjectExpression") {
|
|
137
|
+
for (const property of argument.properties) {
|
|
138
|
+
if (property.type !== "ObjectProperty" && property.type !== "ObjectMethod")
|
|
139
|
+
continue;
|
|
140
|
+
if (property.key.type === "Identifier" && !property.computed)
|
|
141
|
+
out.add(property.key.name);
|
|
142
|
+
else if (property.key.type === "StringLiteral")
|
|
143
|
+
out.add(property.key.value);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
/** Same text with every line break kept, so the lines after a removed statement keep their numbers. */
|
|
149
|
+
const blank = (text) => text.replace(/[^\n]/g, "");
|
|
150
|
+
/**
|
|
151
|
+
* Turns a `<script setup>` that declares props into the body of a function taking them, so the code
|
|
152
|
+
* the compiler already understands (a parameter flowing into a track() call) applies to a component:
|
|
153
|
+
*
|
|
154
|
+
* const props = defineProps<{ track: string }>() -> function Button(props) {
|
|
155
|
+
* const { track } = defineProps<...>() -> function Button({ track }) {
|
|
156
|
+
* defineProps(["track"]) -> function Button({ track }) {
|
|
157
|
+
*
|
|
158
|
+
* The imports stay above it, as they must; statements keep their line numbers. Returns null when the
|
|
159
|
+
* block is not a setup block that declares props, or is written in a way this does not follow
|
|
160
|
+
* (`export`s other than types, imports after other code, an external `src`), in which case the
|
|
161
|
+
* component is scanned as before.
|
|
162
|
+
*/
|
|
163
|
+
function wrapScriptSetup(block, componentName, declaredElsewhere) {
|
|
164
|
+
if (!block.setup || block.startLine === undefined)
|
|
165
|
+
return null;
|
|
166
|
+
const statements = parseScript(block);
|
|
167
|
+
if (!statements)
|
|
168
|
+
return null;
|
|
169
|
+
let firstBody = -1;
|
|
170
|
+
const edits = [];
|
|
171
|
+
let call = null;
|
|
172
|
+
let id = null;
|
|
173
|
+
for (const [index, statement] of statements.entries()) {
|
|
174
|
+
if (statement.type === "ImportDeclaration") {
|
|
175
|
+
if (firstBody !== -1)
|
|
176
|
+
return null;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (firstBody === -1)
|
|
180
|
+
firstBody = index;
|
|
181
|
+
if (statement.type === "ExportNamedDeclaration") {
|
|
182
|
+
const declaration = statement.declaration;
|
|
183
|
+
if (!declaration || (declaration.type !== "TSInterfaceDeclaration" && declaration.type !== "TSTypeAliasDeclaration"))
|
|
184
|
+
return null;
|
|
185
|
+
edits.push({ start: statement.start, end: declaration.start, text: blank(block.content.slice(statement.start, declaration.start)) });
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (statement.type === "ExportDefaultDeclaration" || statement.type === "ExportAllDeclaration")
|
|
189
|
+
return null;
|
|
190
|
+
const found = statement.type === "ExpressionStatement" ? propsCall(statement.expression) : statement.type === "VariableDeclaration" && statement.declarations.length === 1 ? propsCall(statement.declarations[0].init) : null;
|
|
191
|
+
if (found && !call) {
|
|
192
|
+
call = found;
|
|
193
|
+
id = statement.type === "VariableDeclaration" ? statement.declarations[0].id : null;
|
|
194
|
+
edits.push({ start: statement.start, end: statement.end, text: blank(block.content.slice(statement.start, statement.end)) });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (!call)
|
|
198
|
+
return null;
|
|
199
|
+
const names = [...propKeys(call, statements)];
|
|
200
|
+
const present = new Set();
|
|
201
|
+
let parameter;
|
|
202
|
+
let aliases = "";
|
|
203
|
+
if (id?.type === "Identifier") {
|
|
204
|
+
parameter = id.name;
|
|
205
|
+
// the template names props bare, so each one is also a local that reads the same parameter path
|
|
206
|
+
const bare = names.filter((name) => IDENTIFIER.test(name) && !declaredElsewhere.has(name) && name !== id.name);
|
|
207
|
+
if (bare.length > 0)
|
|
208
|
+
aliases = ` const { ${bare.join(", ")} } = ${parameter};`;
|
|
209
|
+
}
|
|
210
|
+
else if (id?.type === "ObjectPattern") {
|
|
211
|
+
// a rest element has to stay last, so nothing can be added after it
|
|
212
|
+
if (id.properties.some((property) => property.type === "RestElement"))
|
|
213
|
+
return null;
|
|
214
|
+
// the keys read from the props, not the local names they are bound to: `{ track: renamed }` reads `track`
|
|
215
|
+
for (const property of id.properties) {
|
|
216
|
+
const key = property.key;
|
|
217
|
+
if (key.type === "Identifier")
|
|
218
|
+
present.add(key.name);
|
|
219
|
+
else if (key.type === "StringLiteral")
|
|
220
|
+
present.add(key.value);
|
|
221
|
+
}
|
|
222
|
+
const missing = names.filter((name) => IDENTIFIER.test(name) && !present.has(name) && !declaredElsewhere.has(name));
|
|
223
|
+
const text = block.content.slice(id.start, id.typeAnnotation ? id.typeAnnotation.start : id.end).trim();
|
|
224
|
+
parameter = missing.length > 0 ? text.replace(/\s*\}$/, `${id.properties.length > 0 ? "," : ""} ${missing.join(", ")} }`) : text;
|
|
225
|
+
}
|
|
226
|
+
else if (id === null) {
|
|
227
|
+
const bare = names.filter((name) => IDENTIFIER.test(name) && !declaredElsewhere.has(name));
|
|
228
|
+
if (bare.length === 0)
|
|
229
|
+
return null;
|
|
230
|
+
parameter = `{ ${bare.join(", ")} }`;
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
const header = `${/\bawait\b/.test(block.content) ? "async " : ""}function ${componentName}(${parameter}: any) {${aliases}`;
|
|
236
|
+
// last edit first, so the offsets of the ones before it still hold
|
|
237
|
+
let code = block.content;
|
|
238
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) {
|
|
239
|
+
code = code.slice(0, edit.start) + edit.text + code.slice(edit.end);
|
|
240
|
+
}
|
|
241
|
+
// the header goes in front of the first statement, which no edit starts before
|
|
242
|
+
const headerAt = statements[firstBody].start;
|
|
243
|
+
code = code.slice(0, headerAt) + header + code.slice(headerAt);
|
|
244
|
+
return { code, propNames: names, name: componentName };
|
|
245
|
+
}
|
package/dist/parse-vue-sfc.d.ts
CHANGED
|
@@ -16,6 +16,18 @@ export interface TemplateHandler {
|
|
|
16
16
|
readonly handler: boolean;
|
|
17
17
|
readonly code: string;
|
|
18
18
|
}
|
|
19
|
+
/** A prop passed to a child component in the template: `track="x"` (literal), `:track="expr"` (expression). */
|
|
20
|
+
export interface TemplateComponentProp {
|
|
21
|
+
/** camelCased, the way the child declares it */
|
|
22
|
+
readonly name: string;
|
|
23
|
+
readonly kind: "literal" | "expression";
|
|
24
|
+
readonly value: string;
|
|
25
|
+
}
|
|
26
|
+
/** An element that may be a child component, with the props written on it. Whether it is one depends on the script's imports. */
|
|
27
|
+
export interface TemplateComponentUsage {
|
|
28
|
+
readonly tag: string;
|
|
29
|
+
readonly props: readonly TemplateComponentProp[];
|
|
30
|
+
}
|
|
19
31
|
export interface ParsedVueSfc {
|
|
20
32
|
readonly scripts: readonly VueScriptBlock[];
|
|
21
33
|
readonly templateEvents: readonly TemplateEventBinding[];
|
|
@@ -25,6 +37,8 @@ export interface ParsedVueSfc {
|
|
|
25
37
|
* Any call to a tracking function in there is an event the component fires.
|
|
26
38
|
*/
|
|
27
39
|
readonly templateHandlers: readonly TemplateHandler[];
|
|
40
|
+
/** Every element in the template that carries props, for the ones that turn out to be imported components. */
|
|
41
|
+
readonly componentUsages?: readonly TemplateComponentUsage[];
|
|
28
42
|
readonly errors: readonly string[];
|
|
29
43
|
}
|
|
30
44
|
/** Parse a Vue SFC via the real `@vue/compiler-sfc` parser (handles comments, `src=`, malformed markup, etc). */
|
|
@@ -40,6 +54,10 @@ export declare function scriptVirtualPath(vuePath: string): string;
|
|
|
40
54
|
* const) resolves through the same checker-based pipeline as any other TS
|
|
41
55
|
* expression; anything that doesn't resolve (e.g. a `v-for` loop variable)
|
|
42
56
|
* is correctly reported as a dynamic occurrence rather than silently dropped.
|
|
57
|
+
*
|
|
58
|
+
* A component that declares props (`defineProps`) is also exported as a function of them, and every
|
|
59
|
+
* use of it in another template becomes a call of that function. The prop that reaches a tracking
|
|
60
|
+
* call is then found by what the component does with it, whatever the prop is called.
|
|
43
61
|
*/
|
|
44
|
-
export declare function buildScriptModule(parsed: ParsedVueSfc): string;
|
|
62
|
+
export declare function buildScriptModule(parsed: ParsedVueSfc, filePath?: string): string;
|
|
45
63
|
//# sourceMappingURL=parse-vue-sfc.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-vue-sfc.d.ts","sourceRoot":"","sources":["../src/parse-vue-sfc.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"parse-vue-sfc.d.ts","sourceRoot":"","sources":["../src/parse-vue-sfc.ts"],"names":[],"mappings":"AAgBA,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,+FAA+F;IAC/F,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,8EAA8E;AAC9E,MAAM,WAAW,oBAAoB;IACnC,0GAA0G;IAC1G,QAAQ,CAAC,IAAI,EAAE,SAAS,GAAG,SAAS,CAAC;IACrC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED,6GAA6G;AAC7G,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,+GAA+G;AAC/G,MAAM,WAAW,qBAAqB;IACpC,gDAAgD;IAChD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,SAAS,GAAG,YAAY,CAAC;IACxC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED,iIAAiI;AACjI,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,KAAK,EAAE,SAAS,qBAAqB,EAAE,CAAC;CAClD;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,OAAO,EAAE,SAAS,cAAc,EAAE,CAAC;IAC5C,QAAQ,CAAC,cAAc,EAAE,SAAS,oBAAoB,EAAE,CAAC;IACzD;;;;OAIG;IACH,QAAQ,CAAC,gBAAgB,EAAE,SAAS,eAAe,EAAE,CAAC;IACtD,8GAA8G;IAC9G,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS,sBAAsB,EAAE,CAAC;IAC7D,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;CACpC;AA8GD,iHAAiH;AACjH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,YAAY,CAoD1E;AAED,gFAAgF;AAChF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEzD;AAID;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,SAAK,GAAG,MAAM,CAsD7E"}
|
package/dist/parse-vue-sfc.js
CHANGED
|
@@ -9,6 +9,7 @@ exports.buildScriptModule = buildScriptModule;
|
|
|
9
9
|
const node_fs_1 = __importDefault(require("node:fs"));
|
|
10
10
|
const node_path_1 = __importDefault(require("node:path"));
|
|
11
11
|
const compiler_sfc_1 = require("@vue/compiler-sfc");
|
|
12
|
+
const component_1 = require("./component");
|
|
12
13
|
const layout_1 = require("./layout");
|
|
13
14
|
const compiler_dom_1 = require("@vue/compiler-dom");
|
|
14
15
|
const compiler_core_1 = require("@vue/compiler-core");
|
|
@@ -21,17 +22,37 @@ function readSrcFile(sfcPath, src) {
|
|
|
21
22
|
return null;
|
|
22
23
|
}
|
|
23
24
|
}
|
|
25
|
+
const camelize = (name) => name.replace(/-(\w)/g, (_, letter) => letter.toUpperCase());
|
|
24
26
|
// the part of `item in items()` / `(item, i) of items()` that is an expression: after the `in` / `of`
|
|
25
27
|
const V_FOR_SOURCE = /\s(?:in|of)\s+([\s\S]+)$/;
|
|
26
28
|
// directives whose value is plain JS. `v-for` is handled apart (its value is `item in source`), and
|
|
27
29
|
// `v-slot` (a parameter list), `v-pre` and `v-cloak` hold no expression
|
|
28
30
|
const CODE_DIRECTIVES = new Set(["on", "bind", "if", "else-if", "show", "html", "text", "model"]);
|
|
29
|
-
function collectEventBindings(root, out, handlers) {
|
|
31
|
+
function collectEventBindings(root, out, handlers, usages) {
|
|
30
32
|
function visitChildren(children) {
|
|
31
33
|
for (const child of children) {
|
|
32
34
|
visitNode(child);
|
|
33
35
|
}
|
|
34
36
|
}
|
|
37
|
+
function collectComponentProps(tag, props) {
|
|
38
|
+
const found = [];
|
|
39
|
+
for (const prop of props) {
|
|
40
|
+
if (prop.type === compiler_core_1.NodeTypes.ATTRIBUTE) {
|
|
41
|
+
if (prop.value)
|
|
42
|
+
found.push({ name: camelize(prop.name), kind: "literal", value: prop.value.content });
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
// `:track="expr"`; the same-name shorthand `:track` has no expression and reads the variable of that name
|
|
46
|
+
if (prop.name === "bind" && prop.arg?.type === compiler_core_1.NodeTypes.SIMPLE_EXPRESSION && prop.arg.isStatic) {
|
|
47
|
+
const name = camelize(prop.arg.content);
|
|
48
|
+
const expression = prop.exp?.type === compiler_core_1.NodeTypes.SIMPLE_EXPRESSION ? prop.exp.content.trim() : name;
|
|
49
|
+
if (expression)
|
|
50
|
+
found.push({ name, kind: "expression", value: expression });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (found.length > 0)
|
|
54
|
+
usages.push({ tag, props: found });
|
|
55
|
+
}
|
|
35
56
|
function visitElementProps(props) {
|
|
36
57
|
for (const prop of props) {
|
|
37
58
|
if (prop.type === compiler_core_1.NodeTypes.ATTRIBUTE && prop.name === "event") {
|
|
@@ -78,6 +99,7 @@ function collectEventBindings(root, out, handlers) {
|
|
|
78
99
|
// handle here.
|
|
79
100
|
function visitNode(node) {
|
|
80
101
|
if (node.type === compiler_core_1.NodeTypes.ELEMENT) {
|
|
102
|
+
collectComponentProps(node.tag, node.props);
|
|
81
103
|
visitElementProps(node.props);
|
|
82
104
|
visitChildren(node.children);
|
|
83
105
|
return;
|
|
@@ -110,10 +132,11 @@ function parseVueSfc(source, filePath) {
|
|
|
110
132
|
}
|
|
111
133
|
const templateEvents = [];
|
|
112
134
|
const templateHandlers = [];
|
|
135
|
+
const componentUsages = [];
|
|
113
136
|
const template = descriptor.template;
|
|
114
137
|
if (template) {
|
|
115
138
|
if (template.ast) {
|
|
116
|
-
collectEventBindings(template.ast, templateEvents, templateHandlers);
|
|
139
|
+
collectEventBindings(template.ast, templateEvents, templateHandlers, componentUsages);
|
|
117
140
|
}
|
|
118
141
|
else {
|
|
119
142
|
// @vue/compiler-sfc only ever leaves `ast` unset when `src` is set
|
|
@@ -123,7 +146,7 @@ function parseVueSfc(source, filePath) {
|
|
|
123
146
|
if (template.src) {
|
|
124
147
|
const external = readSrcFile(filePath, template.src);
|
|
125
148
|
if (external) {
|
|
126
|
-
collectEventBindings((0, compiler_dom_1.parse)(external), templateEvents, templateHandlers);
|
|
149
|
+
collectEventBindings((0, compiler_dom_1.parse)(external), templateEvents, templateHandlers, componentUsages);
|
|
127
150
|
}
|
|
128
151
|
}
|
|
129
152
|
}
|
|
@@ -133,6 +156,7 @@ function parseVueSfc(source, filePath) {
|
|
|
133
156
|
templateEvents,
|
|
134
157
|
// an empty expression (`@click=""`) holds no code
|
|
135
158
|
templateHandlers: templateHandlers.filter((handler) => handler.code !== ""),
|
|
159
|
+
componentUsages,
|
|
136
160
|
errors: errors.map((error) => {
|
|
137
161
|
// @vue/compiler-sfc errors are always Error instances
|
|
138
162
|
/* v8 ignore else */
|
|
@@ -157,36 +181,92 @@ const TEMPLATE_EVENT_CALLEE = "__eventra_vue_template_event__";
|
|
|
157
181
|
* const) resolves through the same checker-based pipeline as any other TS
|
|
158
182
|
* expression; anything that doesn't resolve (e.g. a `v-for` loop variable)
|
|
159
183
|
* is correctly reported as a dynamic occurrence rather than silently dropped.
|
|
184
|
+
*
|
|
185
|
+
* A component that declares props (`defineProps`) is also exported as a function of them, and every
|
|
186
|
+
* use of it in another template becomes a call of that function. The prop that reaches a tracking
|
|
187
|
+
* call is then found by what the component does with it, whatever the prop is called.
|
|
160
188
|
*/
|
|
161
|
-
function buildScriptModule(parsed) {
|
|
189
|
+
function buildScriptModule(parsed, filePath = "") {
|
|
162
190
|
const parts = [];
|
|
163
|
-
|
|
191
|
+
const bindings = (0, component_1.scriptBindings)(parsed.scripts);
|
|
192
|
+
let scripts = parsed.scripts;
|
|
193
|
+
let component;
|
|
194
|
+
// only the last block can be wrapped: the function it opens stays open to the end of the module
|
|
195
|
+
const last = parsed.scripts[parsed.scripts.length - 1];
|
|
196
|
+
const others = last ? (0, component_1.scriptBindings)(parsed.scripts.slice(0, -1)) : undefined;
|
|
197
|
+
if (last && !others?.hasDefaultExport) {
|
|
198
|
+
const wrapped = (0, component_1.wrapScriptSetup)(last, componentName(filePath, bindings.declared), others.declared);
|
|
199
|
+
if (wrapped) {
|
|
200
|
+
scripts = [...parsed.scripts.slice(0, -1), { ...last, content: wrapped.code }];
|
|
201
|
+
component = wrapped.name;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (scripts.length === 0) {
|
|
164
205
|
parts.push("export {}");
|
|
165
206
|
}
|
|
166
207
|
else {
|
|
167
208
|
// Only a leading `@ts-nocheck` is honoured by TypeScript, so only the
|
|
168
209
|
// first block decides. Blocks keep their original line numbers.
|
|
169
|
-
const first =
|
|
210
|
+
const first = scripts[0];
|
|
170
211
|
const noCheck = first.lang !== "ts" && first.lang !== "tsx";
|
|
171
|
-
parts.push((0, layout_1.placeBlocks)(
|
|
212
|
+
parts.push((0, layout_1.placeBlocks)(scripts, noCheck ? "// @ts-nocheck" : undefined));
|
|
172
213
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
"function __eventraVueTemplate() {",
|
|
214
|
+
const usages = componentCalls(parsed.componentUsages ?? [], bindings.components);
|
|
215
|
+
if (parsed.templateEvents.length > 0 || parsed.templateHandlers.length > 0 || usages.length > 0) {
|
|
216
|
+
const marker = "// --- vue template (auto-generated) ---";
|
|
217
|
+
const body = [
|
|
178
218
|
// template code goes through the same detection as script code, so a call to a tracking
|
|
179
219
|
// function inside a handler or an interpolation is an event like any other
|
|
180
220
|
...parsed.templateHandlers.map(renderTemplateCode),
|
|
221
|
+
...usages,
|
|
181
222
|
...parsed.templateEvents.map((binding) => binding.kind === "literal"
|
|
182
223
|
? ` ${TEMPLATE_EVENT_CALLEE}("${escapeString(binding.value)}");`
|
|
183
224
|
: ` ${TEMPLATE_EVENT_CALLEE}(${binding.value});`),
|
|
184
|
-
"}",
|
|
185
225
|
];
|
|
186
|
-
|
|
226
|
+
const declaration = `declare function ${TEMPLATE_EVENT_CALLEE}(name: string): void;`;
|
|
227
|
+
if (component) {
|
|
228
|
+
// inside the component function, where its props and script variables are in scope
|
|
229
|
+
parts[0] = `${parts[0]}\n${[marker, ...body].join("\n")}\n// --- end template ---\n}\nexport default ${component};`;
|
|
230
|
+
parts.push(declaration);
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
parts.push([marker, declaration, "function __eventraVueTemplate() {", ...body, "}"].join("\n"));
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else if (component) {
|
|
237
|
+
parts[0] = `${parts[0]}\n}\nexport default ${component};`;
|
|
187
238
|
}
|
|
188
239
|
return `${parts.join("\n\n")}\n`;
|
|
189
240
|
}
|
|
241
|
+
/** `Button.vue` -> `Button`: the name the component is reported under, kept clear of the script's own names. */
|
|
242
|
+
function componentName(filePath, taken) {
|
|
243
|
+
const base = node_path_1.default.basename(filePath).replace(/\.vue$/i, "");
|
|
244
|
+
const name = base.replace(/(?:^|[^A-Za-z0-9]+)(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^\w$]/g, "");
|
|
245
|
+
const valid = /^[A-Za-z_$][\w$]*$/.test(name) ? name : "VueComponent";
|
|
246
|
+
return taken.has(valid) ? `${valid}Component` : valid;
|
|
247
|
+
}
|
|
248
|
+
const KEY = /^[A-Za-z_$][\w$]*$/;
|
|
249
|
+
/**
|
|
250
|
+
* A use of an imported component in the template is a call of that component with its props object:
|
|
251
|
+
* `<Button track="x" :label="text" />` is `Button({ track: "x", label: (text) })`. The tag is matched to
|
|
252
|
+
* the import the way Vue does (`Button`, `button`, `my-button` for `MyButton`).
|
|
253
|
+
*/
|
|
254
|
+
function componentCalls(usages, components) {
|
|
255
|
+
const calls = [];
|
|
256
|
+
for (const usage of usages) {
|
|
257
|
+
const camel = usage.tag.replace(/-(\w)/g, (_, letter) => letter.toUpperCase());
|
|
258
|
+
const pascal = camel.charAt(0).toUpperCase() + camel.slice(1);
|
|
259
|
+
const binding = [usage.tag, camel, pascal].find((candidate) => components.includes(candidate));
|
|
260
|
+
if (!binding)
|
|
261
|
+
continue;
|
|
262
|
+
const props = usage.props.map((prop) => {
|
|
263
|
+
const key = KEY.test(prop.name) ? prop.name : `"${escapeString(prop.name)}"`;
|
|
264
|
+
return `${key}: ${prop.kind === "literal" ? `"${escapeString(prop.value)}"` : `(${prop.value}\n)`}`;
|
|
265
|
+
});
|
|
266
|
+
calls.push(` ${binding}({ ${props.join(", ")} });`);
|
|
267
|
+
}
|
|
268
|
+
return calls;
|
|
269
|
+
}
|
|
190
270
|
/**
|
|
191
271
|
* A handler is a statement list when it is written as one (`a(); b()`), an expression otherwise
|
|
192
272
|
* (`() => a()`, `handler`); both are valid as the body of a block, except a bare `function` which
|
package/dist/transform.js
CHANGED
|
@@ -20,7 +20,7 @@ async function transformVueSfc(input) {
|
|
|
20
20
|
modules: [
|
|
21
21
|
{
|
|
22
22
|
path: (0, parse_vue_sfc_1.scriptVirtualPath)(input.path),
|
|
23
|
-
content: (0, parse_vue_sfc_1.buildScriptModule)(parsed),
|
|
23
|
+
content: (0, parse_vue_sfc_1.buildScriptModule)(parsed, input.path),
|
|
24
24
|
},
|
|
25
25
|
],
|
|
26
26
|
};
|