/
collect-translation-ids.ts
67 lines (61 loc) · 1.81 KB
/
collect-translation-ids.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import type { TSESLint } from "@typescript-eslint/utils";
import { translationCallTracker } from "../common-trackers";
import { DefReference, lookupDefinitionSource } from "../def-location";
export type TranslationUsage = {
id: string;
bookLocation: DefReference;
};
export type CollectTranslationIdsCallback = (record: TranslationUsage) => void;
type MessageIds = never;
export const meta: TSESLint.RuleMetaData<MessageIds> = {
type: "problem",
docs: {
description: "an internal rule to collect translation ids",
recommended: false,
},
messages: {},
schema: {},
};
export function create(
context: Readonly<
TSESLint.RuleContext<MessageIds, [CollectTranslationIdsCallback]>
>
): TSESLint.RuleListener {
if (context.options[0] === undefined) {
throw new Error(
"Callback not found\nNote: this rule is for an internal use."
);
}
if (typeof context.options[0] !== "function")
throw new Error("invalid callback");
const collectIdsCallback = context.options[0];
const tracker = translationCallTracker();
tracker.listen("translation", (node, captured) => {
// This is usually an excess during tracking
if (node.type === "Identifier") return;
const idNode = captured["id"]!;
if (idNode.type !== "Literal" || typeof idNode.value !== "string") {
return;
}
const id: string = idNode.value;
const bookNode = captured["book"]!;
if (bookNode.type !== "Identifier") {
return;
}
const bookLocation = lookupDefinitionSource(
context.getSourceCode().scopeManager!,
context.getFilename(),
bookNode
);
if (!bookLocation) return;
collectIdsCallback({
id,
bookLocation,
});
});
return {
ImportDeclaration(node) {
tracker.trackImport(context.getSourceCode().scopeManager!, node);
},
};
}