Skip to content

Commit

Permalink
fix: Fix marker function parsing when used after bracket syntax casti…
Browse files Browse the repository at this point in the history
…ng expression (#45)

Fixes #43
  • Loading branch information
pmpak committed May 14, 2024
1 parent 75b697b commit 1bd6d8b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/parsers/marker.parser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { tsquery } from '@phenomnomnominal/tsquery';
import { ScriptKind, tsquery } from '@phenomnomnominal/tsquery';
import { extname } from 'path';

import { ParserInterface } from './parser.interface.js';
import { TranslationCollection } from '../utils/translation.collection.js';
Expand All @@ -9,7 +10,16 @@ const MARKER_IMPORT_NAME = 'marker';

export class MarkerParser implements ParserInterface {
public extract(source: string, filePath: string): TranslationCollection | null {
const sourceFile = tsquery.ast(source, filePath);
const supportedScriptTypes: Record<string, ScriptKind> = {
'.js': ScriptKind.JS,
'.jsx': ScriptKind.JSX,
'.ts': ScriptKind.TS,
'.tsx': ScriptKind.TSX
};

const scriptKind = supportedScriptTypes[extname(filePath)] ?? ScriptKind.TS;

const sourceFile = tsquery.ast(source, filePath, scriptKind);

const markerImportName = getNamedImportAlias(sourceFile, MARKER_MODULE_NAME, MARKER_IMPORT_NAME);
if (!markerImportName) {
Expand Down
16 changes: 16 additions & 0 deletions tests/parsers/marker.parser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,20 @@ describe('MarkerParser', () => {
const keys = parser.extract(contents, componentFilename).keys();
expect(keys).to.deep.equal(['Hello world']);
});

it('should not break after bracket syntax casting', () => {
const contents = `
import { marker } from '@colsen1991/ngx-translate-extract-marker';
marker('hello');
const input: unknown = 'hello';
const myNiceVar1 = input as string;
marker('hello.after.as.syntax');
const myNiceVar2 = <string>input;
marker('hello.after.bracket.syntax');
`;
const keys = parser.extract(contents, componentFilename).keys();
expect(keys).to.deep.equal(['hello', 'hello.after.as.syntax', 'hello.after.bracket.syntax']);
});
});

0 comments on commit 1bd6d8b

Please sign in to comment.