check module scripts for message definitions - CLI

This commit is contained in:
Denis Richard 2021-09-01 08:00:51 +02:00 committed by Christian Kaisermann
parent 64e8ae2bd3
commit 721e991d90
2 changed files with 26 additions and 16 deletions

View File

@ -50,12 +50,14 @@ function isMessagesDefinitionCall(node: Node, methodName: string) {
}
function getLibImportDeclarations(ast: Ast) {
return (ast.instance
? ast.instance.content.body.filter(
(node) =>
node.type === 'ImportDeclaration' && node.source.value === LIB_NAME,
)
: []) as ImportDeclaration[];
return (
ast.instance
? ast.instance.content.body.filter(
(node) =>
node.type === 'ImportDeclaration' && node.source.value === LIB_NAME,
)
: []
) as ImportDeclaration[];
}
function getDefineMessagesSpecifier(decl: ImportDeclaration) {
@ -107,10 +109,10 @@ export function collectMessageDefinitions(ast: Ast) {
if (defineImportDecl == null) return [];
const defineMethodName = getDefineMessagesSpecifier(defineImportDecl).local
.name;
const defineMethodName =
getDefineMessagesSpecifier(defineImportDecl).local.name;
walk(ast.instance as any, {
const nodeStepInstructions = {
enter(node: Node) {
if (isMessagesDefinitionCall(node, defineMethodName) === false) return;
const [arg] = (node as CallExpression).arguments;
@ -120,7 +122,10 @@ export function collectMessageDefinitions(ast: Ast) {
this.skip();
}
},
});
};
walk(ast.instance as any, nodeStepInstructions);
walk(ast.module as any, nodeStepInstructions);
return definitions.flatMap((definitionDict) =>
definitionDict.properties.map((propNode) => {

View File

@ -85,7 +85,13 @@ describe('collecting message definitions', () => {
});
it('gets all message definition objects', () => {
const ast = parse(`<script>
const ast = parse(`
<script context="module">
import { defineMessages } from 'svelte-i18n';
defineMessages({ quux: { id: 'quux' }, quuz: { id: 'quuz' } })
defineMessages({ corge: { id: 'corge' }, grault: { id: 'grault' } })
</script>
<script>
import { defineMessages } from 'svelte-i18n';
defineMessages({ foo: { id: 'foo' }, bar: { id: 'bar' } })
defineMessages({ baz: { id: 'baz' }, quix: { id: 'qux' } })
@ -93,11 +99,10 @@ describe('collecting message definitions', () => {
const definitions = collectMessageDefinitions(ast);
expect(definitions).toHaveLength(4);
expect(definitions[0]).toMatchObject({ type: 'ObjectExpression' });
expect(definitions[1]).toMatchObject({ type: 'ObjectExpression' });
expect(definitions[2]).toMatchObject({ type: 'ObjectExpression' });
expect(definitions[3]).toMatchObject({ type: 'ObjectExpression' });
expect(definitions).toHaveLength(8);
definitions.forEach((definition) => {
expect(definition).toMatchObject({ type: 'ObjectExpression' });
});
});
it('throws an error if an spread is found', () => {