Skip to content

feat(component-meta): extend component meta #5169

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions packages/component-meta/lib/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,8 +266,9 @@
let _events: ReturnType<typeof getEvents> | undefined;
let _slots: ReturnType<typeof getSlots> | undefined;
let _exposed: ReturnType<typeof getExposed> | undefined;
let _extended_meta: ReturnType<typeof getExtendedMeta> | undefined;

return {
const meta = {
get type() {
return _type ?? (_type = getType());
},
Expand All @@ -282,8 +283,16 @@
},
get exposed() {
return _exposed ?? (_exposed = getExposed());
},
};
}
}

return new Proxy(meta, {
get(target, prop) {
if (prop in target) return target[prop as keyof typeof target]
const extendedMeta = _extended_meta ?? (_extended_meta = getExtendedMeta())
return extendedMeta?.[prop as string]
}
})

function getType() {

Expand All @@ -297,6 +306,36 @@
return 0;
}


function getExtendedMeta() {
let meta: Record<string, any> = {};
const snapshot = language.scripts.get(componentPath)?.snapshot!;
const fileText = snapshot.getText(0, snapshot.getLength());
const ast = ts.createSourceFile('/temp', fileText, ts.ScriptTarget.Latest, true);
Copy link
Member

@KazariEX KazariEX Feb 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See:

const vueFile = sourceScript.generated?.root;
const vueDefaults = vueFile && exportName === 'default'
? (vueFile instanceof vue.VueVirtualCode ? readVueComponentDefaultProps(vueFile, printer, ts) : {})
: {};
const tsDefaults = !vueFile ? readTsComponentDefaultProps(
componentPath.slice(componentPath.lastIndexOf('.') + 1), // ts | js | tsx | jsx
snapshot.getText(0, snapshot.getLength()),
exportName,
printer,
ts
) : {};

We can read ast from sourceFile.generated.root._sfc if it's a .vue file, or try sharing parsed ast if it's a .ts file.

const identifier = 'defineComponentMeta'
const printer = ts.createPrinter(checkerOptions.printer);

if (!ast.identifiers.get(identifier)) return

Check failure on line 318 in packages/component-meta/lib/base.ts

View workflow job for this annotation

GitHub Actions / build

Property 'identifiers' does not exist on type 'SourceFile'.

Check failure on line 318 in packages/component-meta/lib/base.ts

View workflow job for this annotation

GitHub Actions / build (18, macos-latest)

Property 'identifiers' does not exist on type 'SourceFile'.

Check failure on line 318 in packages/component-meta/lib/base.ts

View workflow job for this annotation

GitHub Actions / build (18, ubuntu-latest)

Property 'identifiers' does not exist on type 'SourceFile'.

function traverse(node: ts.Node): void {
if (ts.isIdentifier(node) && node.text === identifier) {
const argument = node.parent.arguments[0];

Check failure on line 322 in packages/component-meta/lib/base.ts

View workflow job for this annotation

GitHub Actions / build

Property 'arguments' does not exist on type 'Node'.

Check failure on line 322 in packages/component-meta/lib/base.ts

View workflow job for this annotation

GitHub Actions / build (18, macos-latest)

Property 'arguments' does not exist on type 'Node'.

Check failure on line 322 in packages/component-meta/lib/base.ts

View workflow job for this annotation

GitHub Actions / build (18, ubuntu-latest)

Property 'arguments' does not exist on type 'Node'.
if (ts.isObjectLiteralExpression(argument)) {
argument.properties.forEach(property => {
if (!ts.isPropertyAssignment(property)) return
const key = property.name.getText();
const valueNode = resolveDefaultOptionExpression(property.initializer, ts);
meta[key] = printer?.printNode(ts.EmitHint.Expression, valueNode, ast) ?? valueNode.getText(ast)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@KazariEX I'm wondering if it's a good idea to parse nested objects and arrays by traversing the rest of the AST here. I tried to match the parser for prop default values.

On one side it would be nice for end users to receive plain objects / arrays, but might be a bit heavy on performances.

});
}
}
return ts.forEachChild(node, traverse)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bit aggressive since it'll walk the entire AST. I'll look into restraining it to the top level of <script setup> and defineComponent.

Copy link
Member

@KazariEX KazariEX Feb 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if we can parse defineComponentMeta at language-core so that we can read the node directly without repeat traversal, since it's not useful for tsc and IDE.

Copy link
Author

@romhml romhml Feb 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into it!

}

traverse(ast);
return meta;
}

function getProps() {

const $props = symbolProperties.find(prop => prop.escapedName === 'props');
Expand Down
1 change: 1 addition & 0 deletions packages/component-meta/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface ComponentMeta {
events: EventMeta[];
slots: SlotMeta[];
exposed: ExposeMeta[];
[key: string]: any
}

export enum TypeMeta {
Expand Down
21 changes: 21 additions & 0 deletions packages/component-meta/tests/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,27 @@ const worker = (checker: ComponentMetaChecker, withTsconfig: boolean) => describ
expect(a).toBeDefined();
expect(b).toBeDefined();
});

test('component-define-meta', () => {
const componentPath = path.resolve(__dirname, '../../../test-workspace/component-meta/define-meta/component-define-meta.vue');
const meta = checker.getComponentMeta(componentPath);
expect(meta.foo).toMatch('bar')
expect(meta.nested).toMatch(`{ foo: 'baz', arr: [1, 2] }`)
});

test('component-define-meta.ts', () => {
const componentPath = path.resolve(__dirname, '../../../test-workspace/component-meta/define-meta/component-define-meta.ts');
const meta = checker.getComponentMeta(componentPath);
expect(meta.foo).toMatch('bar')
expect(meta.nested).toMatch(`{ foo: 'baz', arr: [1, 2] }`)
});

test('component-define-meta.tsx', () => {
const componentPath = path.resolve(__dirname, '../../../test-workspace/component-meta/define-meta/component-define-meta.tsx');
const meta = checker.getComponentMeta(componentPath);
expect(meta.foo).toMatch('bar')
expect(meta.nested).toMatch(`{ foo: 'baz', arr: [1, 2] }`)
});
});

const checkerOptions: MetaCheckerOptions = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { h, defineComponent } from 'vue';

export default defineComponent(() => {
defineComponentMeta({ foo: 'bar', nested: { foo: 'baz', arr: [1, 2] } })
return () => h('span');
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { defineComponent } from 'vue';

export default defineComponent(() => {
defineComponentMeta({ foo: 'bar', nested: { foo: 'baz', arr: [1, 2] } })
return () => <span />
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script setup lang="ts">
defineComponentMeta({ foo: 'bar', nested: { foo: 'baz', arr: [1, 2] } })
</script>

<template>
<span />
</template>
Loading