@parlajs/x18n-plugin 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +23 -2
- package/build/ast.d.ts +29 -0
- package/build/ast.d.ts.map +1 -0
- package/build/ast.js +64 -0
- package/build/bindings.d.ts +31 -0
- package/build/bindings.d.ts.map +1 -0
- package/build/bindings.js +177 -0
- package/build/configs.d.ts +7 -0
- package/build/configs.d.ts.map +1 -0
- package/build/configs.js +46 -0
- package/build/declare.d.ts +8 -0
- package/build/declare.d.ts.map +1 -0
- package/build/declare.js +69 -0
- package/build/index.d.ts +10 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +23 -0
- package/build/namespaces.d.ts +11 -0
- package/build/namespaces.d.ts.map +1 -0
- package/build/namespaces.js +72 -0
- package/build/paths.d.ts +3 -0
- package/build/paths.d.ts.map +1 -0
- package/build/paths.js +7 -0
- package/build/placeholders.d.ts +3 -0
- package/build/placeholders.d.ts.map +1 -0
- package/build/placeholders.js +58 -0
- package/build/scanner.d.ts +4 -0
- package/build/scanner.d.ts.map +1 -0
- package/build/scanner.js +154 -0
- package/build/templates.d.ts +8 -0
- package/build/templates.d.ts.map +1 -0
- package/build/templates.js +107 -0
- package/build/types.d.ts +21 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.js +1 -0
- package/build/values.d.ts +4 -0
- package/build/values.d.ts.map +1 -0
- package/build/values.js +29 -0
- package/package.json +64 -3
- package/src/ast.ts +90 -0
- package/src/bindings.ts +226 -0
- package/src/configs.ts +58 -0
- package/src/declare.ts +94 -0
- package/src/index.ts +34 -0
- package/src/namespaces.ts +93 -0
- package/src/paths.ts +9 -0
- package/src/placeholders.ts +63 -0
- package/src/scanner.ts +175 -0
- package/src/templates.ts +115 -0
- package/src/types.ts +27 -0
- package/src/values.ts +33 -0
package/src/scanner.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// x18n's JS scanner does not read accessor chains yet, so Parla's `t.cart.items()` needs its own.
|
|
2
|
+
import type { Scanner } from '@x18n/core';
|
|
3
|
+
import { parseSync, Visitor } from 'oxc-parser';
|
|
4
|
+
|
|
5
|
+
import { isNode, keyOf, memberChain, staticKeys } from './ast.ts';
|
|
6
|
+
import type { Chain, Node, Segment } from './ast.ts';
|
|
7
|
+
import { collectBindings, resolve } from './bindings.ts';
|
|
8
|
+
import type { Binding } from './bindings.ts';
|
|
9
|
+
import { namespaceImports } from './namespaces.ts';
|
|
10
|
+
import { scriptView, viewName } from './templates.ts';
|
|
11
|
+
import type { Declared, Usage } from './types.ts';
|
|
12
|
+
import { valuesIn } from './values.ts';
|
|
13
|
+
|
|
14
|
+
/** The keys a call passes: none without an argument, unknown when they are not static. */
|
|
15
|
+
const paramKeys = (params: Node | undefined): Array<string> | undefined =>
|
|
16
|
+
params ? staticKeys(params) : [];
|
|
17
|
+
|
|
18
|
+
// Offsets in the view are the file's, so usages point into the template itself.
|
|
19
|
+
const TEMPLATE = /\.(?:vue|svelte|astro)$/;
|
|
20
|
+
|
|
21
|
+
type KeyChain = Chain & { namespace: string; key: ReadonlyArray<Segment> };
|
|
22
|
+
|
|
23
|
+
/** `t.ns.…` on a bound `t`, with the key split from its namespace. */
|
|
24
|
+
function keyChainOf(node: Node, bindings: ReadonlyArray<Binding>): KeyChain | undefined {
|
|
25
|
+
const chain = memberChain(node);
|
|
26
|
+
const binding =
|
|
27
|
+
chain && resolve(bindings, { name: chain.root['name'] as string, position: node.start });
|
|
28
|
+
if (!binding) {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
if ('namespace' in binding) {
|
|
32
|
+
return { ...chain, namespace: binding.namespace, key: chain.segments };
|
|
33
|
+
}
|
|
34
|
+
if ('promise' in binding) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
let { segments } = chain;
|
|
38
|
+
if ('hook' in binding) {
|
|
39
|
+
// A hook's result not destructured: `messages.t.checkout.title()`.
|
|
40
|
+
if (segments[0]?.name !== 't') {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
segments = segments.slice(1);
|
|
44
|
+
}
|
|
45
|
+
const namespaces = 'hook' in binding ? binding.hook : binding.namespaces;
|
|
46
|
+
// Vue's ref: `t.value.checkout.title()`.
|
|
47
|
+
if (segments[0]?.name === 'value' && !namespaces.includes('value')) {
|
|
48
|
+
segments = segments.slice(1);
|
|
49
|
+
}
|
|
50
|
+
// `t` is keyed by namespace: `t.checkout.title()`.
|
|
51
|
+
const [namespace, ...key] = segments;
|
|
52
|
+
return namespace && namespaces.includes(namespace.name)
|
|
53
|
+
? { ...chain, namespace: namespace.name, key }
|
|
54
|
+
: undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A namespace taken out of a load, then passed on: any key may be used. */
|
|
58
|
+
function passedOn(
|
|
59
|
+
root: Node,
|
|
60
|
+
{ bindings, read }: { bindings: ReadonlyArray<Binding>; read: ReadonlySet<Node> },
|
|
61
|
+
): Array<Usage> {
|
|
62
|
+
const usages: Array<Usage> = [];
|
|
63
|
+
const values: Array<Node> = [];
|
|
64
|
+
if (bindings.some((binding) => 'namespace' in binding)) {
|
|
65
|
+
valuesIn(root, values);
|
|
66
|
+
}
|
|
67
|
+
for (const node of values) {
|
|
68
|
+
const binding = read.has(node)
|
|
69
|
+
? undefined
|
|
70
|
+
: resolve(bindings, { name: node['name'] as string, position: node.start });
|
|
71
|
+
if (binding && 'namespace' in binding) {
|
|
72
|
+
usages.push({
|
|
73
|
+
kind: 'accessor',
|
|
74
|
+
namespace: binding.namespace,
|
|
75
|
+
raw: '',
|
|
76
|
+
range: { start: node.start, end: node.end },
|
|
77
|
+
dynamic: 'prefix',
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return usages;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function accessorScanner(callees: ReadonlySet<string>, declared: Declared): Scanner {
|
|
85
|
+
return {
|
|
86
|
+
id: 'parla:accessor',
|
|
87
|
+
extensions: ['js', 'jsx', 'mjs', 'ts', 'tsx', 'mts', 'vue', 'svelte', 'astro'],
|
|
88
|
+
scan(file): { usages: Array<Usage> } {
|
|
89
|
+
const template = TEMPLATE.test(file.path);
|
|
90
|
+
const { program } = template
|
|
91
|
+
? parseSync(viewName(file.path), scriptView(file.path, file.text))
|
|
92
|
+
: parseSync(file.path, file.text);
|
|
93
|
+
const bindings: Array<Binding> = [];
|
|
94
|
+
const root = program as unknown as Node;
|
|
95
|
+
collectBindings(root, {
|
|
96
|
+
scope: root,
|
|
97
|
+
callees,
|
|
98
|
+
imports: namespaceImports(root),
|
|
99
|
+
out: bindings,
|
|
100
|
+
});
|
|
101
|
+
const usages: Array<Usage> = [];
|
|
102
|
+
// A chain is read whole, from its outermost member.
|
|
103
|
+
const read = new Set<Node>();
|
|
104
|
+
|
|
105
|
+
const keyChain = (node: Node): KeyChain | undefined => keyChainOf(node, bindings);
|
|
106
|
+
const markRead = ({ root: name, members }: Chain): void => {
|
|
107
|
+
read.add(name);
|
|
108
|
+
for (const member of members) {
|
|
109
|
+
read.add(member);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
new Visitor({
|
|
114
|
+
CallExpression(expression): void {
|
|
115
|
+
const call = expression as unknown as Node;
|
|
116
|
+
const { callee } = call;
|
|
117
|
+
const chain = isNode(callee) ? keyChain(callee) : undefined;
|
|
118
|
+
const [first] = chain?.key ?? [];
|
|
119
|
+
const last = chain?.key.at(-1);
|
|
120
|
+
if (!chain?.isStatic || !first || !last) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
markRead(chain);
|
|
124
|
+
const { namespace } = chain;
|
|
125
|
+
const [params] = call['arguments'] as Array<Node>;
|
|
126
|
+
const raw = keyOf(chain.key);
|
|
127
|
+
usages.push({
|
|
128
|
+
raw,
|
|
129
|
+
range: { start: first.start, end: last.end },
|
|
130
|
+
expression: { start: call.start, end: call.end },
|
|
131
|
+
// TypeScript checks such a select's params per key; x18n compares one flat list.
|
|
132
|
+
params: declared.branchy.has(`${namespace}:${raw}`) ? undefined : paramKeys(params),
|
|
133
|
+
kind: 'accessor',
|
|
134
|
+
dynamic: false,
|
|
135
|
+
namespace,
|
|
136
|
+
});
|
|
137
|
+
},
|
|
138
|
+
// Not called: a group, a message passed on, or a key chosen at run time.
|
|
139
|
+
MemberExpression(expression): void {
|
|
140
|
+
const node = expression as unknown as Node;
|
|
141
|
+
const chain = read.has(node) ? undefined : keyChain(node);
|
|
142
|
+
if (!chain) {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
markRead(chain);
|
|
146
|
+
const { namespace, key, isStatic } = chain;
|
|
147
|
+
const raw = keyOf(key);
|
|
148
|
+
const usage = { kind: 'accessor' as const, namespace };
|
|
149
|
+
const [first] = key;
|
|
150
|
+
const last = key.at(-1);
|
|
151
|
+
if (isStatic && first && last) {
|
|
152
|
+
usages.push({
|
|
153
|
+
...usage,
|
|
154
|
+
raw,
|
|
155
|
+
range: { start: first.start, end: last.end },
|
|
156
|
+
dynamic: false,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
usages.push({
|
|
160
|
+
...usage,
|
|
161
|
+
// A `keyPrefix`, as x18n would write `raw` over the range on a rename, dot included; the
|
|
162
|
+
// dot keeps `status` from reaching `statusText`.
|
|
163
|
+
raw: '',
|
|
164
|
+
keyPrefix: raw ? `${raw}.` : undefined,
|
|
165
|
+
// Not the key's range: x18n keeps one usage per range.
|
|
166
|
+
range: { start: node.start, end: node.end },
|
|
167
|
+
dynamic: 'prefix',
|
|
168
|
+
});
|
|
169
|
+
},
|
|
170
|
+
}).visit(program);
|
|
171
|
+
|
|
172
|
+
return { usages: [...usages, ...passedOn(root, { bindings, read })] };
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
}
|
package/src/templates.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { parseSync } from 'oxc-parser';
|
|
2
|
+
|
|
3
|
+
type Range = readonly [start: number, end: number];
|
|
4
|
+
|
|
5
|
+
/** Where a comment that starts at `j` ends, or `j` when none does. */
|
|
6
|
+
function pastComment(text: string, j: number): number {
|
|
7
|
+
const close = { '//': '\n', '/*': '*/' }[text.slice(j, j + 2)];
|
|
8
|
+
if (close === undefined) {
|
|
9
|
+
return j;
|
|
10
|
+
}
|
|
11
|
+
const end = text.indexOf(close, j + 2);
|
|
12
|
+
return end === -1 ? text.length : end + close.length - 1;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** `{expr}` in Svelte and Astro markup, past a block's keyword: `{#if expr}`, `{@html expr}`. */
|
|
16
|
+
function* braceExpressions(text: string, blocks: ReadonlyArray<Range>): Generator<Range> {
|
|
17
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
18
|
+
if (text[i] !== '{') {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
// A script's `don't` would open a string that never closes.
|
|
22
|
+
const block = blocks.find(([from, to]) => from <= i && i < to);
|
|
23
|
+
if (block) {
|
|
24
|
+
i = block[1] - 1;
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
let depth = 0;
|
|
28
|
+
let quote: string | undefined;
|
|
29
|
+
let j = i;
|
|
30
|
+
for (; j < text.length; j += 1) {
|
|
31
|
+
const c = text[j];
|
|
32
|
+
if (quote) {
|
|
33
|
+
if (c === '\\') {
|
|
34
|
+
j += 1;
|
|
35
|
+
} else if (c === quote) {
|
|
36
|
+
quote = undefined;
|
|
37
|
+
}
|
|
38
|
+
} else if (c === '"' || c === "'" || c === '`') {
|
|
39
|
+
quote = c;
|
|
40
|
+
} else if (c === '/') {
|
|
41
|
+
j = pastComment(text, j);
|
|
42
|
+
} else if (c === '{') {
|
|
43
|
+
depth += 1;
|
|
44
|
+
} else if (c === '}') {
|
|
45
|
+
depth -= 1;
|
|
46
|
+
if (depth === 0) {
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const keyword = /^\s*(?:[#:@/]\w+(?:\s+if)?)?/.exec(text.slice(i + 1, j))?.[0].length ?? 0;
|
|
52
|
+
yield [i + 1 + keyword, j];
|
|
53
|
+
i = j;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const MUSTACHE = /\{\{(?<expr>[\s\S]*?)\}\}/g;
|
|
58
|
+
// `v-for` holds `item in items`, which is not an expression.
|
|
59
|
+
const DIRECTIVE =
|
|
60
|
+
/\s(?::|@|v-bind:|v-on:|v-(?:if|else-if|show|html|text|model)\b)[\w.:-]*="(?<expr>[^"]*)"/g;
|
|
61
|
+
|
|
62
|
+
/** `{{ expr }}` and directive values in a Vue template. */
|
|
63
|
+
function* vueExpressions(text: string): Generator<Range> {
|
|
64
|
+
for (const pattern of [MUSTACHE, DIRECTIVE]) {
|
|
65
|
+
for (const match of text.matchAll(pattern)) {
|
|
66
|
+
const expr = match.groups?.['expr'] ?? '';
|
|
67
|
+
const start = match.index + match[0].lastIndexOf(expr);
|
|
68
|
+
yield [start, start + expr.length];
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const BLOCK = /<(?<tag>script|style)\b[^>]*>(?<body>[\s\S]*?)<\/\k<tag>>|<!--[\s\S]*?-->/g;
|
|
74
|
+
const FRONTMATTER = /^---\r?\n(?<body>[\s\S]*?)\r?\n---/;
|
|
75
|
+
|
|
76
|
+
/** The parser's file name: Astro's markup is JSX, and a Vue or Svelte script is TypeScript. */
|
|
77
|
+
export const viewName = (path: string): string =>
|
|
78
|
+
`${path}.${path.endsWith('.astro') ? 'tsx' : 'ts'}`;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* A Vue, Svelte or Astro file as one script, every character at its own offset: the scripts and
|
|
82
|
+
* the template expressions that parse, joined by `;`, and blanks for the rest.
|
|
83
|
+
*/
|
|
84
|
+
export function scriptView(path: string, text: string): string {
|
|
85
|
+
// By UTF-16 unit, as offsets count: a spread would split by code point.
|
|
86
|
+
const view = Array.from({ length: text.length }, (_, i): string =>
|
|
87
|
+
text[i] === '\n' ? '\n' : ' ',
|
|
88
|
+
);
|
|
89
|
+
const copy = (start: number, end: number): void => {
|
|
90
|
+
for (let i = start; i < end; i += 1) {
|
|
91
|
+
view[i] = text[i] ?? ' ';
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const blocks: Array<Range> = [];
|
|
95
|
+
const frontmatter = path.endsWith('.astro') ? FRONTMATTER.exec(text) : null;
|
|
96
|
+
for (const match of [...(frontmatter ? [frontmatter] : []), ...text.matchAll(BLOCK)]) {
|
|
97
|
+
blocks.push([match.index, match.index + match[0].length]);
|
|
98
|
+
const body = match.groups?.['body'];
|
|
99
|
+
if (body !== undefined && match.groups?.['tag'] !== 'style') {
|
|
100
|
+
const start = match.index + match[0].indexOf(body);
|
|
101
|
+
copy(start, start + body.length);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const name = viewName(path);
|
|
105
|
+
const expressions = path.endsWith('.vue') ? vueExpressions(text) : braceExpressions(text, blocks);
|
|
106
|
+
for (const [start, end] of expressions) {
|
|
107
|
+
const inBlock = blocks.some(([from, to]) => from <= start && start < to);
|
|
108
|
+
if (!inBlock && parseSync(name, `(${text.slice(start, end)})`).errors.length === 0) {
|
|
109
|
+
copy(start, end);
|
|
110
|
+
view[start - 1] = ';';
|
|
111
|
+
view[end] = ';';
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return view.join('');
|
|
115
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { CustomFunctions, FormatAdapter } from '@parlajs/compiler';
|
|
2
|
+
import type { Plugin, Scanner } from '@x18n/core';
|
|
3
|
+
|
|
4
|
+
export type Usage = Awaited<ReturnType<Scanner['scan']>>['usages'][number];
|
|
5
|
+
|
|
6
|
+
export type PlaceholderSyntax = NonNullable<Plugin['placeholders']>[number];
|
|
7
|
+
|
|
8
|
+
export type Placeholder = ReturnType<PlaceholderSyntax['find']>[number];
|
|
9
|
+
|
|
10
|
+
export type LocaleFinder = NonNullable<Plugin['localeFinders']>[number];
|
|
11
|
+
|
|
12
|
+
export type Host = Parameters<LocaleFinder['find']>[0]['host'];
|
|
13
|
+
|
|
14
|
+
export type ReadFile = (path: string) => Promise<string | undefined>;
|
|
15
|
+
|
|
16
|
+
/** What the configs declare, filled once `configFinder` has loaded them. */
|
|
17
|
+
export interface Declared {
|
|
18
|
+
readonly functions: Record<string, CustomFunctions[string]>;
|
|
19
|
+
/** The configs' `formats` by name, the first config's winning. */
|
|
20
|
+
readonly formats: Map<string, FormatAdapter>;
|
|
21
|
+
/** Each message of a namespace in a format other than `icu` and `mf2`, to its parser. */
|
|
22
|
+
readonly syntaxes: Map<string, FormatAdapter>;
|
|
23
|
+
/** The configs' `markup`, which a call may leave out. */
|
|
24
|
+
readonly markup: Array<string>;
|
|
25
|
+
/** `ns:key` of each `:string` select whose keys need different params. */
|
|
26
|
+
readonly branchy: Set<string>;
|
|
27
|
+
}
|
package/src/values.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { isNode } from './ast.ts';
|
|
2
|
+
import type { Node } from './ast.ts';
|
|
3
|
+
|
|
4
|
+
/** Children that name something, rather than read a value. */
|
|
5
|
+
const NAMES: Readonly<Record<string, string>> = {
|
|
6
|
+
VariableDeclarator: 'id',
|
|
7
|
+
FunctionDeclaration: 'params',
|
|
8
|
+
FunctionExpression: 'params',
|
|
9
|
+
ArrowFunctionExpression: 'params',
|
|
10
|
+
CatchClause: 'param',
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const KEYED = new Set(['MemberExpression', 'Property', 'PropertyDefinition', 'MethodDefinition']);
|
|
14
|
+
|
|
15
|
+
/** Every identifier read as a value: no declaration, key or type. */
|
|
16
|
+
export function valuesIn(node: Node, out: Array<Node>): void {
|
|
17
|
+
if (node.type === 'Identifier') {
|
|
18
|
+
out.push(node);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const isType = node.type.startsWith('TS');
|
|
22
|
+
for (const [name, value] of Object.entries(node)) {
|
|
23
|
+
const isKey = KEYED.has(node.type) && !node['computed'] && /^(?:key|property)$/.test(name);
|
|
24
|
+
// Of TypeScript's nodes, only `x as T` and its like hold a value.
|
|
25
|
+
if (NAMES[node.type] !== name && !isKey && (!isType || name === 'expression')) {
|
|
26
|
+
for (const child of Array.isArray(value) ? value : [value]) {
|
|
27
|
+
if (isNode(child)) {
|
|
28
|
+
valuesIn(child, out);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|