@fluentic/i18n 0.0.0-stage → 0.1.0-beta.1
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/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +21 -2
- package/dist/adapter-CWC8rng-.d.ts +178 -0
- package/dist/adapter.d.ts +4 -0
- package/dist/adapter.js +4 -0
- package/dist/analyze-CdXCxQDg.d.ts +14 -0
- package/dist/compact-CJ0OWoIv.d.ts +7 -0
- package/dist/compact-E3zj3Z8d.js +34 -0
- package/dist/compact-E3zj3Z8d.js.map +1 -0
- package/dist/compiled.d.ts +27 -0
- package/dist/compiled.js +51 -0
- package/dist/compiled.js.map +1 -0
- package/dist/compiler-BZtB9WLi.js +365 -0
- package/dist/compiler-BZtB9WLi.js.map +1 -0
- package/dist/compiler.d.ts +35 -0
- package/dist/compiler.js +3 -0
- package/dist/core/index.d.ts +5 -0
- package/dist/core/index.js +4 -0
- package/dist/i18n-CfYNwubL.d.ts +25 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/interpreter-Dld8QyOI.js +186 -0
- package/dist/interpreter-Dld8QyOI.js.map +1 -0
- package/dist/manager-BW778X1Y.js +193 -0
- package/dist/manager-BW778X1Y.js.map +1 -0
- package/dist/options-DE7vYj0e.d.ts +7 -0
- package/dist/options-Dxxx0aOz.js +23 -0
- package/dist/options-Dxxx0aOz.js.map +1 -0
- package/dist/plugin/babel.d.ts +11 -0
- package/dist/plugin/babel.js +31 -0
- package/dist/plugin/babel.js.map +1 -0
- package/dist/plugin/esbuild.d.ts +7 -0
- package/dist/plugin/esbuild.js +37 -0
- package/dist/plugin/esbuild.js.map +1 -0
- package/dist/plugin/rollup.d.ts +30 -0
- package/dist/plugin/rollup.js +34 -0
- package/dist/plugin/rollup.js.map +1 -0
- package/dist/plugin/vite.d.ts +31 -0
- package/dist/plugin/vite.js +11 -0
- package/dist/plugin/vite.js.map +1 -0
- package/dist/plugin/webpack-loader.d.ts +3 -0
- package/dist/plugin/webpack-loader.js +21 -0
- package/dist/plugin/webpack-loader.js.map +1 -0
- package/dist/plugin/webpack.d.ts +8 -0
- package/dist/plugin/webpack.js +22 -0
- package/dist/plugin/webpack.js.map +1 -0
- package/dist/react.d.ts +53 -0
- package/dist/react.js +60 -0
- package/dist/react.js.map +1 -0
- package/dist/src-BovRx-mX.js +142 -0
- package/dist/src-BovRx-mX.js.map +1 -0
- package/dist/translation-manager-C79eKu2K.js +213 -0
- package/dist/translation-manager-C79eKu2K.js.map +1 -0
- package/dist/types-BkDsJfVD.js +13 -0
- package/dist/types-BkDsJfVD.js.map +1 -0
- package/dist/types-BuGoCU3P.d.ts +75 -0
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -0
- package/dist-cjs/babel.cjs +379 -0
- package/dist-cjs/babel.cjs.map +1 -0
- package/package.json +130 -3
- package/src/adapter.ts +6 -0
- package/src/compiled.ts +116 -0
- package/src/compiler/analyze.ts +182 -0
- package/src/compiler/index.ts +208 -0
- package/src/compiler/message.ts +74 -0
- package/src/core/format.ts +40 -0
- package/src/core/i18n.ts +124 -0
- package/src/core/index.ts +1 -0
- package/src/core/types.ts +121 -0
- package/src/index.ts +9 -0
- package/src/manager.ts +175 -0
- package/src/plugin/babel.ts +34 -0
- package/src/plugin/esbuild.ts +45 -0
- package/src/plugin/options.ts +24 -0
- package/src/plugin/rollup.ts +29 -0
- package/src/plugin/vite.ts +6 -0
- package/src/plugin/webpack-loader.ts +22 -0
- package/src/plugin/webpack.ts +15 -0
- package/src/react.ts +97 -0
- package/src/registry-manager.ts +3 -0
- package/src/shared/compact.ts +51 -0
- package/src/shared/formatting.ts +121 -0
- package/src/shared/interpreter.ts +128 -0
- package/src/shared/runtime.ts +131 -0
- package/src/state-manager.ts +29 -0
- package/src/state.ts +20 -0
- package/src/storage-manager.ts +47 -0
- package/src/translation-manager.ts +82 -0
- package/src/translation.ts +106 -0
- package/src/types.ts +2 -0
package/package.json
CHANGED
|
@@ -1,6 +1,133 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fluentic/i18n",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-beta.1",
|
|
4
|
+
"description": "Framework-independent internationalization primitives for Fluentic applications.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/fluentic-dev/i18n.git",
|
|
9
|
+
"directory": "packages/i18n"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://fluenticstack.com/i18n/",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/fluentic-dev/i18n/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"keywords": [
|
|
17
|
+
"i18n",
|
|
18
|
+
"internationalization",
|
|
19
|
+
"localization",
|
|
20
|
+
"typescript"
|
|
21
|
+
],
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./src/index.ts",
|
|
28
|
+
"import": "./dist/index.js",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./core": {
|
|
32
|
+
"types": "./src/core/index.ts",
|
|
33
|
+
"import": "./dist/core/index.js",
|
|
34
|
+
"default": "./dist/core/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./adapter": {
|
|
37
|
+
"types": "./src/adapter.ts",
|
|
38
|
+
"import": "./dist/adapter.js",
|
|
39
|
+
"default": "./dist/adapter.js"
|
|
40
|
+
},
|
|
41
|
+
"./react": {
|
|
42
|
+
"types": "./src/react.ts",
|
|
43
|
+
"import": "./dist/react.js",
|
|
44
|
+
"default": "./dist/react.js"
|
|
45
|
+
},
|
|
46
|
+
"./types": {
|
|
47
|
+
"types": "./src/types.ts",
|
|
48
|
+
"import": "./dist/types.js",
|
|
49
|
+
"default": "./dist/types.js"
|
|
50
|
+
},
|
|
51
|
+
"./compiled": {
|
|
52
|
+
"types": "./src/compiled.ts",
|
|
53
|
+
"default": "./dist/compiled.js"
|
|
54
|
+
},
|
|
55
|
+
"./compiler": {
|
|
56
|
+
"types": "./src/compiler/index.ts",
|
|
57
|
+
"default": "./dist/compiler.js"
|
|
58
|
+
},
|
|
59
|
+
"./plugin/babel": {
|
|
60
|
+
"types": "./src/plugin/babel.ts",
|
|
61
|
+
"import": "./dist/plugin/babel.js",
|
|
62
|
+
"require": "./dist-cjs/babel.cjs"
|
|
63
|
+
},
|
|
64
|
+
"./plugin/vite": {
|
|
65
|
+
"types": "./src/plugin/vite.ts",
|
|
66
|
+
"default": "./dist/plugin/vite.js"
|
|
67
|
+
},
|
|
68
|
+
"./plugin/rollup": {
|
|
69
|
+
"types": "./src/plugin/rollup.ts",
|
|
70
|
+
"default": "./dist/plugin/rollup.js"
|
|
71
|
+
},
|
|
72
|
+
"./plugin/esbuild": {
|
|
73
|
+
"types": "./src/plugin/esbuild.ts",
|
|
74
|
+
"default": "./dist/plugin/esbuild.js"
|
|
75
|
+
},
|
|
76
|
+
"./plugin/webpack": {
|
|
77
|
+
"types": "./src/plugin/webpack.ts",
|
|
78
|
+
"default": "./dist/plugin/webpack.js"
|
|
79
|
+
},
|
|
80
|
+
"./plugin/webpack-loader": {
|
|
81
|
+
"types": "./src/plugin/webpack-loader.ts",
|
|
82
|
+
"default": "./dist/plugin/webpack-loader.js"
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
"files": [
|
|
86
|
+
"dist",
|
|
87
|
+
"src",
|
|
88
|
+
"README.md",
|
|
89
|
+
"CHANGELOG.md",
|
|
90
|
+
"LICENSE",
|
|
91
|
+
"dist-cjs"
|
|
92
|
+
],
|
|
93
|
+
"dependencies": {
|
|
94
|
+
"intl-messageformat": "^10.7.16",
|
|
95
|
+
"@babel/parser": "^7.28.4",
|
|
96
|
+
"@babel/traverse": "^7.28.4",
|
|
97
|
+
"@babel/types": "^7.28.4",
|
|
98
|
+
"@babel/generator": "^7.28.3",
|
|
99
|
+
"@formatjs/icu-messageformat-parser": "2.11.4",
|
|
100
|
+
"jiti": "^2.7.0",
|
|
101
|
+
"@jridgewell/remapping": "^2.3.5",
|
|
102
|
+
"@noble/hashes": "^1.8.0"
|
|
103
|
+
},
|
|
104
|
+
"devDependencies": {
|
|
105
|
+
"@types/react": "^19.2.14",
|
|
106
|
+
"react": "^19.2.0",
|
|
107
|
+
"react-test-renderer": "19.3.1",
|
|
108
|
+
"tsdown": "^0.22.1",
|
|
109
|
+
"typescript": "^5.9.3",
|
|
110
|
+
"@types/babel__traverse": "^7.20.7",
|
|
111
|
+
"@types/babel__generator": "^7.27.0",
|
|
112
|
+
"@types/node": "^22.15.0",
|
|
113
|
+
"@babel/core": "^7.28.4"
|
|
114
|
+
},
|
|
115
|
+
"peerDependencies": {
|
|
116
|
+
"react": ">=18"
|
|
117
|
+
},
|
|
118
|
+
"peerDependenciesMeta": {
|
|
119
|
+
"react": {
|
|
120
|
+
"optional": true
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
"sideEffects": [
|
|
124
|
+
"./dist/react.js"
|
|
125
|
+
],
|
|
126
|
+
"scripts": {
|
|
127
|
+
"build": "tsdown",
|
|
128
|
+
"dev": "tsdown --watch",
|
|
129
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
130
|
+
"test": "pnpm test:types && pnpm build && node --test test/*.test.mjs",
|
|
131
|
+
"test:types": "tsc --noEmit --strict --skipLibCheck --esModuleInterop --module ESNext --moduleResolution Bundler --target ES2020 --jsx react-jsx test/react.types.tsx test/compiled.types.ts"
|
|
132
|
+
}
|
|
6
133
|
}
|
package/src/adapter.ts
ADDED
package/src/compiled.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { type TApi } from './core/i18n';
|
|
2
|
+
import { isMessageDescriptor } from './core/types';
|
|
3
|
+
import type {
|
|
4
|
+
DescriptorRenderArgs,
|
|
5
|
+
I18nJsxOutput,
|
|
6
|
+
I18nTagValue,
|
|
7
|
+
MessageDescriptor,
|
|
8
|
+
MessageParams,
|
|
9
|
+
MessageSchema,
|
|
10
|
+
TryRenderArgs,
|
|
11
|
+
} from './core/types';
|
|
12
|
+
import type { CompactMessage } from './shared/compact';
|
|
13
|
+
import { createFormatting } from './shared/formatting';
|
|
14
|
+
import { interpret } from './shared/interpreter';
|
|
15
|
+
import { createTagHandler, getRuntime, noTranslate } from './shared/runtime';
|
|
16
|
+
|
|
17
|
+
export type CompiledPayload = readonly [id: string, fallback: CompactMessage];
|
|
18
|
+
|
|
19
|
+
export type CompiledTextRenderer = {
|
|
20
|
+
(message: CompiledPayload, params?: MessageParams): string;
|
|
21
|
+
<Text extends string, Schema extends MessageSchema | undefined>(
|
|
22
|
+
message: MessageDescriptor<Text, Schema>,
|
|
23
|
+
...args: DescriptorRenderArgs<Schema>
|
|
24
|
+
): string;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type CompiledJsxRenderer = {
|
|
28
|
+
(message: CompiledPayload, params?: MessageParams): I18nJsxOutput;
|
|
29
|
+
<Text extends string, Schema extends MessageSchema | undefined>(
|
|
30
|
+
message: MessageDescriptor<Text, Schema>,
|
|
31
|
+
...args: DescriptorRenderArgs<Schema>
|
|
32
|
+
): I18nJsxOutput;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export type CompiledTApi =
|
|
36
|
+
& Omit<TApi<I18nJsxOutput, I18nTagValue>, 'msg' | 'text' | 'jsx' | 'try' | 'context' | 'note' | 'meta'>
|
|
37
|
+
& {
|
|
38
|
+
msg<Schema extends MessageSchema | undefined = undefined>(
|
|
39
|
+
message: CompiledPayload,
|
|
40
|
+
schema?: Schema,
|
|
41
|
+
): MessageDescriptor<string, Schema>;
|
|
42
|
+
text: CompiledTextRenderer;
|
|
43
|
+
jsx: CompiledJsxRenderer;
|
|
44
|
+
try<T>(
|
|
45
|
+
renderer: CompiledTextRenderer,
|
|
46
|
+
value: T,
|
|
47
|
+
...args: TryRenderArgs<T>
|
|
48
|
+
): T extends { readonly __fluenticMessage: true; } ? string
|
|
49
|
+
: T;
|
|
50
|
+
try<T>(
|
|
51
|
+
renderer: CompiledJsxRenderer,
|
|
52
|
+
value: T,
|
|
53
|
+
...args: TryRenderArgs<T>
|
|
54
|
+
): T extends { readonly __fluenticMessage: true; } ? I18nJsxOutput : T;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const formatting = /* @__PURE__ */ createFormatting(interpret, true);
|
|
58
|
+
|
|
59
|
+
function descriptor<Schema extends MessageSchema | undefined = undefined>(
|
|
60
|
+
payload: CompiledPayload,
|
|
61
|
+
schema?: Schema,
|
|
62
|
+
): MessageDescriptor<string, Schema> {
|
|
63
|
+
if (!Array.isArray(payload) || payload.length !== 2 || typeof payload[0] !== 'string') {
|
|
64
|
+
throw new TypeError('[i18n] compiled runtime requires compiled messages; enable the Fluentic plugin');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return Object.freeze({
|
|
68
|
+
__fluenticMessage: true,
|
|
69
|
+
text: payload[0],
|
|
70
|
+
compiled: payload,
|
|
71
|
+
context: null,
|
|
72
|
+
schema: schema ?? {},
|
|
73
|
+
notes: [],
|
|
74
|
+
meta: undefined,
|
|
75
|
+
}) as unknown as MessageDescriptor<string, Schema>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function options(
|
|
79
|
+
message: CompiledPayload | MessageDescriptor<string, MessageSchema | undefined>,
|
|
80
|
+
params?: MessageParams,
|
|
81
|
+
) {
|
|
82
|
+
return { msg: isMessageDescriptor(message) ? message : descriptor(message), params };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export const t = {
|
|
86
|
+
msg: descriptor,
|
|
87
|
+
text(message: CompiledPayload | MessageDescriptor<string, MessageSchema | undefined>, params?: MessageParams) {
|
|
88
|
+
return formatting.getText(options(message, params));
|
|
89
|
+
},
|
|
90
|
+
jsx(message: CompiledPayload | MessageDescriptor<string, MessageSchema | undefined>, params?: MessageParams) {
|
|
91
|
+
return formatting.getJsx(options(message, params));
|
|
92
|
+
},
|
|
93
|
+
clone(message: MessageDescriptor) {
|
|
94
|
+
return Object.freeze({ ...message });
|
|
95
|
+
},
|
|
96
|
+
params(params: MessageParams | null = {}) {
|
|
97
|
+
return params ?? {};
|
|
98
|
+
},
|
|
99
|
+
tag(value: unknown) {
|
|
100
|
+
if (typeof value === 'function') return createTagHandler(value as (chunks: unknown[]) => unknown);
|
|
101
|
+
|
|
102
|
+
const adapt = getRuntime().tagElement;
|
|
103
|
+
|
|
104
|
+
if (!adapt) throw new Error('[i18n] element tags require a platform adapter');
|
|
105
|
+
|
|
106
|
+
return createTagHandler(adapt(value));
|
|
107
|
+
},
|
|
108
|
+
try(renderer: (message: unknown, params?: MessageParams) => unknown, value: unknown, params?: MessageParams) {
|
|
109
|
+
return isMessageDescriptor(value) ? renderer(value, params) : value;
|
|
110
|
+
},
|
|
111
|
+
notranslate: noTranslate,
|
|
112
|
+
} as unknown as CompiledTApi;
|
|
113
|
+
export * from './core/types';
|
|
114
|
+
export type { CompactMessage, CompactPart } from './shared/compact';
|
|
115
|
+
export { I18nRegistry, noTranslate, setFormats } from './shared/runtime';
|
|
116
|
+
export { defineTranslationLoader } from './translation-manager';
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { parse } from '@babel/parser';
|
|
2
|
+
import * as traverseModule from '@babel/traverse';
|
|
3
|
+
import type { Binding, NodePath } from '@babel/traverse';
|
|
4
|
+
import * as b from '@babel/types';
|
|
5
|
+
|
|
6
|
+
const traverse = ((traverseModule.default as unknown as { default?: typeof traverseModule.default; }).default ??
|
|
7
|
+
traverseModule.default) as typeof traverseModule.default;
|
|
8
|
+
export { traverse };
|
|
9
|
+
|
|
10
|
+
export const importMap: Record<string, string> = {
|
|
11
|
+
'@fluentic/i18n': '@fluentic/i18n/compiled',
|
|
12
|
+
'@fluentic/i18n/core': '@fluentic/i18n/compiled',
|
|
13
|
+
};
|
|
14
|
+
export type Scope = { context: string | null; notes: string[]; meta?: unknown; };
|
|
15
|
+
export type ExtractedMessage = Scope & { id: string; source: string; };
|
|
16
|
+
|
|
17
|
+
export function parseSource(code: string, filename: string) {
|
|
18
|
+
return parse(code, {
|
|
19
|
+
sourceFilename: filename,
|
|
20
|
+
sourceType: 'unambiguous',
|
|
21
|
+
plugins: [
|
|
22
|
+
...(/\.[cm]?tsx?$/.test(filename) ? ['typescript' as const] : []),
|
|
23
|
+
...(!/\.[cm]?ts$/.test(filename) ? ['jsx' as const] : []),
|
|
24
|
+
'decorators-legacy',
|
|
25
|
+
'importAttributes',
|
|
26
|
+
],
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function unwrap(path: NodePath): NodePath {
|
|
31
|
+
while (
|
|
32
|
+
path.isTSAsExpression() || path.isTSSatisfiesExpression() || path.isTSNonNullExpression() ||
|
|
33
|
+
path.isTypeCastExpression() || path.isParenthesizedExpression()
|
|
34
|
+
) path = path.get('expression') as NodePath;
|
|
35
|
+
|
|
36
|
+
return path;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function literal(path: NodePath, seen = new Set<Binding>()): string | null {
|
|
40
|
+
path = unwrap(path);
|
|
41
|
+
if (path.isStringLiteral()) return path.node.value;
|
|
42
|
+
if (path.isTemplateLiteral() && !path.node.expressions.length) return path.node.quasis[0].value.cooked ?? '';
|
|
43
|
+
if (path.isIdentifier()) {
|
|
44
|
+
const binding = path.scope.getBinding(path.node.name);
|
|
45
|
+
|
|
46
|
+
if (binding?.constant && binding.path.isVariableDeclarator() && !seen.has(binding)) {
|
|
47
|
+
seen.add(binding);
|
|
48
|
+
|
|
49
|
+
return literal(binding.path.get('init') as NodePath, seen);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function memberName(path: NodePath): string | null {
|
|
57
|
+
if (!path.isMemberExpression()) return null;
|
|
58
|
+
|
|
59
|
+
const property = path.get('property');
|
|
60
|
+
|
|
61
|
+
return !path.node.computed && property.isIdentifier()
|
|
62
|
+
? property.node.name
|
|
63
|
+
: property.isStringLiteral()
|
|
64
|
+
? property.node.value
|
|
65
|
+
: null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function analyzer(imports = Object.keys(importMap)) {
|
|
69
|
+
const memo = new Map<Binding, Scope | null>();
|
|
70
|
+
const scopedBindings = new Set<Binding>();
|
|
71
|
+
const scopeCalls = new Set<NodePath>();
|
|
72
|
+
|
|
73
|
+
const resolve = (path: NodePath, visiting = new Set<Binding>()): Scope | null => {
|
|
74
|
+
path = unwrap(path);
|
|
75
|
+
if (path.isIdentifier()) {
|
|
76
|
+
const binding = path.scope.getBinding(path.node.name);
|
|
77
|
+
|
|
78
|
+
if (!binding) return null;
|
|
79
|
+
if (memo.has(binding)) return memo.get(binding)!;
|
|
80
|
+
if (visiting.has(binding)) throw new Error('[i18n] circular translator alias');
|
|
81
|
+
if (binding.path.isImportSpecifier()) {
|
|
82
|
+
const declaration = binding.path.parentPath;
|
|
83
|
+
const imported = binding.path.node.imported;
|
|
84
|
+
|
|
85
|
+
return declaration.isImportDeclaration() && imports.includes(declaration.node.source.value) &&
|
|
86
|
+
(b.isIdentifier(imported) ? imported.name : imported.value) === 't' &&
|
|
87
|
+
declaration.node.importKind !== 'type'
|
|
88
|
+
? { context: null, notes: [] }
|
|
89
|
+
: null;
|
|
90
|
+
}
|
|
91
|
+
if (binding.path.isVariableDeclarator()) {
|
|
92
|
+
visiting.add(binding);
|
|
93
|
+
const scope = resolve(binding.path.get('init') as NodePath, visiting);
|
|
94
|
+
visiting.delete(binding);
|
|
95
|
+
if (scope && !binding.constant) {
|
|
96
|
+
throw new Error('[i18n] translator aliases must not be reassigned: ' + path.node.name);
|
|
97
|
+
}
|
|
98
|
+
memo.set(binding, scope);
|
|
99
|
+
if (scope) scopedBindings.add(binding);
|
|
100
|
+
|
|
101
|
+
return scope;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
if (path.isMemberExpression() && memberName(path) === 't') {
|
|
107
|
+
const object = path.get('object');
|
|
108
|
+
|
|
109
|
+
if (!object.isIdentifier()) return null;
|
|
110
|
+
|
|
111
|
+
const binding = object.scope.getBinding(object.node.name);
|
|
112
|
+
const declaration = binding?.path.parentPath;
|
|
113
|
+
|
|
114
|
+
if (
|
|
115
|
+
binding?.path.isImportNamespaceSpecifier() && declaration?.isImportDeclaration() &&
|
|
116
|
+
imports.includes(declaration.node.source.value)
|
|
117
|
+
) return { context: null, notes: [] };
|
|
118
|
+
}
|
|
119
|
+
if (!path.isCallExpression()) return null;
|
|
120
|
+
|
|
121
|
+
const callee = path.get('callee');
|
|
122
|
+
const method = memberName(callee);
|
|
123
|
+
|
|
124
|
+
if (!method || !['context', 'note', 'meta'].includes(method)) return null;
|
|
125
|
+
|
|
126
|
+
const parent = resolve((callee as NodePath<b.MemberExpression>).get('object'), visiting);
|
|
127
|
+
|
|
128
|
+
if (!parent) return null;
|
|
129
|
+
if (path.node.arguments.length !== 1) throw new Error('[i18n] scope methods require one static argument');
|
|
130
|
+
|
|
131
|
+
const argument = path.get('arguments.0') as NodePath;
|
|
132
|
+
scopeCalls.add(path);
|
|
133
|
+
if (method === 'meta') {
|
|
134
|
+
const evaluated = argument.evaluate();
|
|
135
|
+
|
|
136
|
+
if (!evaluated.confident) throw new Error('[i18n] metadata must be statically known');
|
|
137
|
+
|
|
138
|
+
return { ...parent, meta: evaluated.value };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const value = literal(argument);
|
|
142
|
+
|
|
143
|
+
if (value === null) throw new Error('[i18n] ' + method + ' must be a static string');
|
|
144
|
+
|
|
145
|
+
return method === 'note'
|
|
146
|
+
? { ...parent, notes: [...parent.notes, value] }
|
|
147
|
+
: { ...parent, context: parent.context ? `${parent.context}.${value}` : value };
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
return { resolve, scopedBindings, scopeCalls };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function collectMessages(code: string, filename: string, imports?: string[]): ExtractedMessage[] {
|
|
154
|
+
const ast = parseSource(code, filename);
|
|
155
|
+
const { resolve } = analyzer(imports);
|
|
156
|
+
const messages: ExtractedMessage[] = [];
|
|
157
|
+
traverse(ast, {
|
|
158
|
+
CallExpression(path) {
|
|
159
|
+
const callee = path.get('callee');
|
|
160
|
+
const method = memberName(callee);
|
|
161
|
+
|
|
162
|
+
if (!method || !['msg', 'text', 'jsx'].includes(method)) return;
|
|
163
|
+
|
|
164
|
+
const scope = resolve((callee as NodePath<b.MemberExpression>).get('object'));
|
|
165
|
+
|
|
166
|
+
if (!scope) return;
|
|
167
|
+
|
|
168
|
+
const source = literal(path.get('arguments.0') as NodePath);
|
|
169
|
+
|
|
170
|
+
if (source === null) {
|
|
171
|
+
if (method === 'msg') {
|
|
172
|
+
throw new Error(`[i18n] ${filename}:${path.node.loc?.start.line}: t.msg requires a static message`);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
messages.push({ ...scope, id: scope.context ? `${scope.context}\0${source}` : source, source });
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
return [...new Map(messages.map((message) => [message.id, message])).values()];
|
|
182
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import * as generatorModule from '@babel/generator';
|
|
2
|
+
import type { NodePath } from '@babel/traverse';
|
|
3
|
+
import * as b from '@babel/types';
|
|
4
|
+
import {
|
|
5
|
+
analyzer,
|
|
6
|
+
collectMessages,
|
|
7
|
+
type ExtractedMessage,
|
|
8
|
+
importMap,
|
|
9
|
+
literal,
|
|
10
|
+
memberName,
|
|
11
|
+
parseSource,
|
|
12
|
+
traverse,
|
|
13
|
+
} from './analyze';
|
|
14
|
+
import { compileMessage, messageId } from './message';
|
|
15
|
+
|
|
16
|
+
export { collectMessages } from './analyze';
|
|
17
|
+
export * from './message';
|
|
18
|
+
|
|
19
|
+
const generate = ((generatorModule.default as unknown as { default?: typeof generatorModule.default; }).default ??
|
|
20
|
+
generatorModule.default) as typeof generatorModule.default;
|
|
21
|
+
export type CompilerOptions = { compiled?: boolean; filename?: string; };
|
|
22
|
+
|
|
23
|
+
export function compileProgram(code: string, filename: string, options: CompilerOptions = {}) {
|
|
24
|
+
const ast = parseSource(code, filename);
|
|
25
|
+
const messages: ExtractedMessage[] = [];
|
|
26
|
+
|
|
27
|
+
if (options.compiled === false) return { ast, messages, changed: false };
|
|
28
|
+
|
|
29
|
+
const analysis = analyzer();
|
|
30
|
+
|
|
31
|
+
const plans: Array<
|
|
32
|
+
{
|
|
33
|
+
path: NodePath<b.CallExpression>;
|
|
34
|
+
source: string | null;
|
|
35
|
+
scope: NonNullable<ReturnType<typeof analysis.resolve>>;
|
|
36
|
+
}
|
|
37
|
+
> = [];
|
|
38
|
+
const declarations: NodePath<b.ImportDeclaration>[] = [];
|
|
39
|
+
|
|
40
|
+
let program: NodePath<b.Program> | undefined;
|
|
41
|
+
traverse(ast, {
|
|
42
|
+
Program(path) {
|
|
43
|
+
program = path;
|
|
44
|
+
},
|
|
45
|
+
ExportAllDeclaration(path) {
|
|
46
|
+
if (importMap[path.node.source.value]) {
|
|
47
|
+
throw new Error('[i18n] do not re-export the translator in compiled mode; import t directly at each use');
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
ExportNamedDeclaration(path) {
|
|
51
|
+
if (
|
|
52
|
+
path.node.source && importMap[path.node.source.value] &&
|
|
53
|
+
path.node.specifiers.some((specifier) =>
|
|
54
|
+
b.isExportSpecifier(specifier) && (b.isIdentifier(specifier.local) ? specifier.local.name : '') === 't'
|
|
55
|
+
)
|
|
56
|
+
) throw new Error('[i18n] do not re-export the translator in compiled mode; export message descriptors instead');
|
|
57
|
+
},
|
|
58
|
+
ImportDeclaration(path) {
|
|
59
|
+
if (importMap[path.node.source.value] && path.node.importKind !== 'type') declarations.push(path);
|
|
60
|
+
},
|
|
61
|
+
CallExpression(path) {
|
|
62
|
+
const callee = path.get('callee');
|
|
63
|
+
const method = memberName(callee);
|
|
64
|
+
|
|
65
|
+
if (!method || !['msg', 'jsx', 'text'].includes(method)) return;
|
|
66
|
+
|
|
67
|
+
const scope = analysis.resolve((callee as NodePath<b.MemberExpression>).get('object'));
|
|
68
|
+
|
|
69
|
+
if (!scope) return;
|
|
70
|
+
|
|
71
|
+
const source = literal(path.get('arguments.0') as NodePath);
|
|
72
|
+
|
|
73
|
+
if (source === null && method === 'msg') {
|
|
74
|
+
throw new Error(`[i18n] ${filename}:${path.node.loc?.start.line}: t.msg requires a static message`);
|
|
75
|
+
}
|
|
76
|
+
plans.push({ path, source, scope });
|
|
77
|
+
if (source !== null) {
|
|
78
|
+
messages.push({ ...scope, source, id: scope.context ? `${scope.context}\0${source}` : source });
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
// Discover unused/escaping scopes as well as scopes reached by message calls.
|
|
83
|
+
traverse(ast, {
|
|
84
|
+
VariableDeclarator(path) {
|
|
85
|
+
analysis.resolve(path.get('id') as NodePath);
|
|
86
|
+
},
|
|
87
|
+
CallExpression(path) {
|
|
88
|
+
const name = memberName(path.get('callee'));
|
|
89
|
+
|
|
90
|
+
if (name && ['context', 'note', 'meta'].includes(name)) analysis.resolve(path);
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
const expressionUse = (path: NodePath): NodePath => {
|
|
94
|
+
while (
|
|
95
|
+
path.parentPath &&
|
|
96
|
+
(path.parentPath.isTSAsExpression() || path.parentPath.isTSSatisfiesExpression() ||
|
|
97
|
+
path.parentPath.isTSNonNullExpression() || path.parentPath.isTypeCastExpression() ||
|
|
98
|
+
path.parentPath.isParenthesizedExpression())
|
|
99
|
+
) path = path.parentPath;
|
|
100
|
+
|
|
101
|
+
return path;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
for (const path of analysis.scopeCalls) {
|
|
105
|
+
const use = expressionUse(path);
|
|
106
|
+
const parent = use.parentPath;
|
|
107
|
+
|
|
108
|
+
if (parent?.isVariableDeclarator() || parent?.isExpressionStatement()) continue;
|
|
109
|
+
if (parent?.isMemberExpression() && parent.get('object') === use && parent.parentPath?.isCallExpression()) continue;
|
|
110
|
+
throw new Error('[i18n] scoped translator escapes same-file message calls');
|
|
111
|
+
}
|
|
112
|
+
for (const binding of analysis.scopedBindings) {
|
|
113
|
+
if (binding.path.parentPath?.parentPath?.isExportNamedDeclaration()) {
|
|
114
|
+
throw new Error('[i18n] scoped translators cannot be exported; repeat the context in the consuming file');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
for (const reference of binding.referencePaths) {
|
|
118
|
+
if (reference.findParent((parent) => parent.isTSType())) continue;
|
|
119
|
+
|
|
120
|
+
const use = expressionUse(reference);
|
|
121
|
+
const parent = use.parentPath;
|
|
122
|
+
|
|
123
|
+
if (parent?.isVariableDeclarator() && parent.get('init') === use) continue;
|
|
124
|
+
if (parent?.isMemberExpression() && parent.get('object') === use) {
|
|
125
|
+
const method = memberName(parent);
|
|
126
|
+
|
|
127
|
+
if (
|
|
128
|
+
method && ['msg', 'text', 'jsx', 'context', 'note', 'meta'].includes(method) &&
|
|
129
|
+
parent.parentPath?.isCallExpression()
|
|
130
|
+
) continue;
|
|
131
|
+
}
|
|
132
|
+
throw new Error('[i18n] scoped translator escapes same-file message calls: ' + binding.identifier.name);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (!declarations.length) return { ast, messages, changed: false };
|
|
136
|
+
|
|
137
|
+
const helper = program!.scope.generateUidIdentifier('tc');
|
|
138
|
+
|
|
139
|
+
if (plans.length) {
|
|
140
|
+
program!.unshiftContainer(
|
|
141
|
+
'body',
|
|
142
|
+
b.importDeclaration([b.importSpecifier(helper, b.identifier('t'))], b.stringLiteral('@fluentic/i18n/compiled')),
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
for (const { path, source, scope } of plans) {
|
|
147
|
+
const callee = path.get('callee') as NodePath<b.MemberExpression>;
|
|
148
|
+
callee.get('object').replaceWith(b.cloneNode(helper));
|
|
149
|
+
if (source !== null) {
|
|
150
|
+
const replacement = b.valueToNode([messageId(scope.context, source), compileMessage(source)]);
|
|
151
|
+
b.inherits(replacement, path.node.arguments[0]);
|
|
152
|
+
path.node.arguments[0] = replacement;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// All scope uses were checked before mutation. Remove aliases from leaves to roots.
|
|
156
|
+
let removed = true;
|
|
157
|
+
|
|
158
|
+
while (removed) {
|
|
159
|
+
removed = false;
|
|
160
|
+
program!.scope.crawl();
|
|
161
|
+
|
|
162
|
+
for (const binding of analysis.scopedBindings) {
|
|
163
|
+
if (binding.path.removed) continue;
|
|
164
|
+
|
|
165
|
+
const current = binding.path.scope.getBinding(binding.identifier.name);
|
|
166
|
+
|
|
167
|
+
if (current && !current.referenced) {
|
|
168
|
+
binding.path.remove();
|
|
169
|
+
removed = true;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
for (const path of analysis.scopeCalls) {
|
|
175
|
+
if (!path.removed) {
|
|
176
|
+
const use = expressionUse(path);
|
|
177
|
+
|
|
178
|
+
if (use.parentPath?.isExpressionStatement()) use.parentPath.remove();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
for (const declaration of declarations) declaration.node.source.value = importMap[declaration.node.source.value];
|
|
182
|
+
program!.scope.crawl();
|
|
183
|
+
|
|
184
|
+
for (const declaration of declarations) {
|
|
185
|
+
declaration.node.specifiers = declaration.node.specifiers.filter((specifier) => {
|
|
186
|
+
if (
|
|
187
|
+
!b.isImportSpecifier(specifier) ||
|
|
188
|
+
(b.isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value) !== 't'
|
|
189
|
+
) return true;
|
|
190
|
+
|
|
191
|
+
return Boolean(program!.scope.getBinding(specifier.local.name)?.referenced);
|
|
192
|
+
});
|
|
193
|
+
if (!declaration.node.specifiers.length) declaration.remove();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return { ast, messages, changed: true };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function transform(code: string, options: CompilerOptions = {}) {
|
|
200
|
+
const filename = options.filename ?? 'source.tsx';
|
|
201
|
+
const result = compileProgram(code, filename, options);
|
|
202
|
+
|
|
203
|
+
if (!result.changed) return null;
|
|
204
|
+
|
|
205
|
+
const output = generate(result.ast, { sourceMaps: true, sourceFileName: filename, comments: true }, code);
|
|
206
|
+
|
|
207
|
+
return { code: output.code, map: output.map, messages: result.messages };
|
|
208
|
+
}
|