@fluentic/i18n 0.1.0-beta.1 → 0.1.0-beta.2

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.
Files changed (121) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +9 -1
  3. package/dist/adapter.d.ts +6 -4
  4. package/dist/adapter.js +4 -3
  5. package/dist/compiled.d.ts +26 -24
  6. package/dist/compiled.js +4 -2
  7. package/dist/compiled.js.map +1 -1
  8. package/dist/compiler-support.d.ts +4 -0
  9. package/dist/compiler-support.js +4 -0
  10. package/dist/core/format.d.ts +11 -0
  11. package/dist/core/i18n.d.ts +26 -0
  12. package/dist/core/index.d.ts +1 -5
  13. package/dist/core/index.js +3 -2
  14. package/dist/core/types.d.ts +79 -0
  15. package/dist/hash-VJlyT31Z.js +90 -0
  16. package/dist/hash-VJlyT31Z.js.map +1 -0
  17. package/dist/hydration-store-BK6UxrtJ.js +13 -0
  18. package/dist/hydration-store-BK6UxrtJ.js.map +1 -0
  19. package/dist/hydration-store.d.ts +29 -0
  20. package/dist/hydration.d.ts +7 -0
  21. package/dist/hydration.js +35 -0
  22. package/dist/hydration.js.map +1 -0
  23. package/dist/index.d.ts +6 -6
  24. package/dist/index.js +3 -2
  25. package/dist/{interpreter-Dld8QyOI.js → interpreter-BfzvLLrD.js} +4 -3
  26. package/dist/interpreter-BfzvLLrD.js.map +1 -0
  27. package/dist/{manager-BW778X1Y.js → manager-BgMJWXWY.js} +21 -31
  28. package/dist/manager-BgMJWXWY.js.map +1 -0
  29. package/dist/manager.d.ts +62 -0
  30. package/dist/message-D4jK2Lzc.js +9 -0
  31. package/dist/message-D4jK2Lzc.js.map +1 -0
  32. package/dist/react.d.ts +41 -46
  33. package/dist/react.js +12 -8
  34. package/dist/react.js.map +1 -1
  35. package/dist/registry-manager.d.ts +7 -0
  36. package/dist/runtime-DXnGeCBw.js +110 -0
  37. package/dist/runtime-DXnGeCBw.js.map +1 -0
  38. package/dist/shared/compact.d.ts +5 -0
  39. package/dist/shared/formatting.d.ts +11 -0
  40. package/dist/shared/hash.d.ts +7 -0
  41. package/dist/shared/interpreter.d.ts +2 -0
  42. package/dist/shared/message.d.ts +2 -0
  43. package/dist/shared/runtime.d.ts +49 -0
  44. package/dist/{src-BovRx-mX.js → src-ON68XIog.js} +9 -7
  45. package/dist/src-ON68XIog.js.map +1 -0
  46. package/dist/state-manager.d.ts +6 -0
  47. package/dist/state.d.ts +8 -0
  48. package/dist/storage-manager.d.ts +14 -0
  49. package/dist/{translation-manager-C79eKu2K.js → translation-manager-BkmFnlb_.js} +5 -104
  50. package/dist/translation-manager-BkmFnlb_.js.map +1 -0
  51. package/dist/translation-manager.d.ts +34 -0
  52. package/dist/translation.d.ts +20 -0
  53. package/dist/types-BkDsJfVD.js.map +1 -1
  54. package/dist/types.d.ts +3 -2
  55. package/package.json +20 -54
  56. package/dist/adapter-CWC8rng-.d.ts +0 -178
  57. package/dist/analyze-CdXCxQDg.d.ts +0 -14
  58. package/dist/compact-CJ0OWoIv.d.ts +0 -7
  59. package/dist/compiler-BZtB9WLi.js +0 -365
  60. package/dist/compiler-BZtB9WLi.js.map +0 -1
  61. package/dist/compiler.d.ts +0 -35
  62. package/dist/compiler.js +0 -3
  63. package/dist/i18n-CfYNwubL.d.ts +0 -25
  64. package/dist/interpreter-Dld8QyOI.js.map +0 -1
  65. package/dist/manager-BW778X1Y.js.map +0 -1
  66. package/dist/options-DE7vYj0e.d.ts +0 -7
  67. package/dist/options-Dxxx0aOz.js +0 -23
  68. package/dist/options-Dxxx0aOz.js.map +0 -1
  69. package/dist/plugin/babel.d.ts +0 -11
  70. package/dist/plugin/babel.js +0 -31
  71. package/dist/plugin/babel.js.map +0 -1
  72. package/dist/plugin/esbuild.d.ts +0 -7
  73. package/dist/plugin/esbuild.js +0 -37
  74. package/dist/plugin/esbuild.js.map +0 -1
  75. package/dist/plugin/rollup.d.ts +0 -30
  76. package/dist/plugin/rollup.js +0 -34
  77. package/dist/plugin/rollup.js.map +0 -1
  78. package/dist/plugin/vite.d.ts +0 -31
  79. package/dist/plugin/vite.js +0 -11
  80. package/dist/plugin/vite.js.map +0 -1
  81. package/dist/plugin/webpack-loader.d.ts +0 -3
  82. package/dist/plugin/webpack-loader.js +0 -21
  83. package/dist/plugin/webpack-loader.js.map +0 -1
  84. package/dist/plugin/webpack.d.ts +0 -8
  85. package/dist/plugin/webpack.js +0 -22
  86. package/dist/plugin/webpack.js.map +0 -1
  87. package/dist/src-BovRx-mX.js.map +0 -1
  88. package/dist/translation-manager-C79eKu2K.js.map +0 -1
  89. package/dist/types-BuGoCU3P.d.ts +0 -75
  90. package/dist-cjs/babel.cjs +0 -379
  91. package/dist-cjs/babel.cjs.map +0 -1
  92. package/src/adapter.ts +0 -6
  93. package/src/compiled.ts +0 -116
  94. package/src/compiler/analyze.ts +0 -182
  95. package/src/compiler/index.ts +0 -208
  96. package/src/compiler/message.ts +0 -74
  97. package/src/core/format.ts +0 -40
  98. package/src/core/i18n.ts +0 -124
  99. package/src/core/index.ts +0 -1
  100. package/src/core/types.ts +0 -121
  101. package/src/index.ts +0 -9
  102. package/src/manager.ts +0 -175
  103. package/src/plugin/babel.ts +0 -34
  104. package/src/plugin/esbuild.ts +0 -45
  105. package/src/plugin/options.ts +0 -24
  106. package/src/plugin/rollup.ts +0 -29
  107. package/src/plugin/vite.ts +0 -6
  108. package/src/plugin/webpack-loader.ts +0 -22
  109. package/src/plugin/webpack.ts +0 -15
  110. package/src/react.ts +0 -97
  111. package/src/registry-manager.ts +0 -3
  112. package/src/shared/compact.ts +0 -51
  113. package/src/shared/formatting.ts +0 -121
  114. package/src/shared/interpreter.ts +0 -128
  115. package/src/shared/runtime.ts +0 -131
  116. package/src/state-manager.ts +0 -29
  117. package/src/state.ts +0 -20
  118. package/src/storage-manager.ts +0 -47
  119. package/src/translation-manager.ts +0 -82
  120. package/src/translation.ts +0 -106
  121. package/src/types.ts +0 -2
@@ -1,182 +0,0 @@
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
- }
@@ -1,208 +0,0 @@
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
- }
@@ -1,74 +0,0 @@
1
- import { type MessageFormatElement, parse, TYPE } from '@formatjs/icu-messageformat-parser';
2
- import { createHash } from 'node:crypto';
3
- import type { CompactMessage, CompactPart } from '../shared/compact';
4
-
5
- export { COMPACT_VERSION } from '../shared/compact';
6
-
7
- export function messageIdentity(context: string | null, source: string): string {
8
- return context ? `${context}\0${source}` : source;
9
- }
10
-
11
- export function messageId(context: string | null, source: string): string {
12
- return createHash('sha256').update(messageIdentity(context, source)).digest('hex').slice(0, 24);
13
- }
14
-
15
- export function compileMessage(source: string): CompactMessage {
16
- const compact = (elements: MessageFormatElement[]): CompactMessage => {
17
- const result: CompactPart[] = elements.map((element): CompactPart => {
18
- switch (element.type) {
19
- case TYPE.literal:
20
- return element.value;
21
- case TYPE.argument:
22
- return [0, element.value];
23
- case TYPE.number:
24
- case TYPE.date:
25
- case TYPE.time:
26
- return [
27
- element.type === TYPE.number ? 1 : element.type === TYPE.date ? 2 : 3,
28
- element.value,
29
- typeof element.style === 'object' && element.style
30
- ? element.style.parsedOptions as Record<string, unknown>
31
- : element.style ?? null,
32
- ];
33
- case TYPE.select:
34
- return [
35
- 4,
36
- element.value,
37
- Object.fromEntries(Object.entries(element.options).map(([key, option]) => [key, compact(option.value)])),
38
- ];
39
- case TYPE.plural:
40
- return [
41
- 5,
42
- element.value,
43
- element.offset,
44
- element.pluralType === 'ordinal' ? 1 : 0,
45
- Object.fromEntries(Object.entries(element.options).map(([key, option]) => [key, compact(option.value)])),
46
- ];
47
- case TYPE.pound:
48
- return [6];
49
- case TYPE.tag:
50
- return [7, element.value, compact(element.children)];
51
- }
52
- });
53
-
54
- return result.every((part) => typeof part === 'string') ? result.join('') : result;
55
- };
56
-
57
- return compact(parse(source, { captureLocation: false }));
58
- }
59
-
60
- export function compileCatalog(
61
- records: Array<{ source: string; context: string | null; translation: string; }>,
62
- ): Array<[string, CompactMessage]> {
63
- const seen = new Map<string, string>();
64
-
65
- return records.flatMap((record) => {
66
- const id = messageId(record.context, record.source);
67
- const identity = messageIdentity(record.context, record.source);
68
-
69
- if (seen.has(id) && seen.get(id) !== identity) throw new Error('[i18n] message hash collision: ' + id);
70
- seen.set(id, identity);
71
-
72
- return record.translation === '' ? [] : [[id, compileMessage(record.translation)] as [string, CompactMessage]];
73
- });
74
- }
@@ -1,40 +0,0 @@
1
- import { sha256 } from '@noble/hashes/sha256';
2
- import { bytesToHex } from '@noble/hashes/utils';
3
- import { IntlMessageFormat } from 'intl-messageformat';
4
- import { createFormatting } from '../shared/formatting';
5
- import { interpret } from '../shared/interpreter';
6
-
7
- const cache = new Map<string, IntlMessageFormat>();
8
- const formatting = /* @__PURE__ */ createFormatting(
9
- (message, languageId, formats, values, compiled) => {
10
- if (compiled) return interpret(message, languageId, formats, values, true);
11
- if (typeof message !== 'string') throw new TypeError('[i18n] invalid translation');
12
-
13
- const key = JSON.stringify([message, languageId, formats]);
14
-
15
- let formatter = cache.get(key);
16
-
17
- if (!formatter) {
18
- formatter = new IntlMessageFormat(
19
- message,
20
- languageId,
21
- formats as ConstructorParameters<typeof IntlMessageFormat>[2],
22
- );
23
- if (cache.size >= 500) cache.delete(cache.keys().next().value!);
24
- cache.set(key, formatter);
25
- }
26
-
27
- return formatter.formatToParts(values as Parameters<IntlMessageFormat['formatToParts']>[0]).map((part) =>
28
- part.value
29
- );
30
- },
31
- false,
32
- (context, message) => bytesToHex(sha256(context ? `${context}\0${message}` : message)).slice(0, 24),
33
- );
34
- export * from '../shared/runtime';
35
-
36
- export const getText = (...args: Parameters<typeof formatting.getText>) => formatting.getText(...args);
37
- export const getJsx = (...args: Parameters<typeof formatting.getJsx>) => formatting.getJsx(...args);
38
- export const getMessageParts = (...args: Parameters<typeof formatting.getMessageParts>) =>
39
- formatting.getMessageParts(...args);
40
- export const formatMessage = getText;
package/src/core/i18n.ts DELETED
@@ -1,124 +0,0 @@
1
- import type { Formatting } from '../shared/formatting';
2
- import { createTagHandler, getRuntime, noTranslate } from '../shared/runtime';
3
- import type { I18nJsxOutput, I18nTagElement, I18nTagValue } from './types';
4
- import { isMessageDescriptor } from './types';
5
- import type {
6
- JsxRenderer,
7
- MessageDescriptor,
8
- MessageInput,
9
- MessageMeta,
10
- MessageParams,
11
- MessageSchema,
12
- MessageTagHandler,
13
- TextRenderer,
14
- TryRenderArgs,
15
- } from './types';
16
-
17
- type MessageScope = { context: string | null; notes: string[]; meta?: MessageMeta; };
18
-
19
- export type MessageApi<JsxOutput = unknown> = {
20
- context(name: string): MessageApi<JsxOutput>;
21
- note(note: string): MessageApi<JsxOutput>;
22
- meta(meta: MessageMeta): MessageApi<JsxOutput>;
23
- msg<const Text extends string, const Schema extends MessageSchema | undefined = undefined>(
24
- message: Text,
25
- schema?: Schema,
26
- ): MessageDescriptor<Text, Schema>;
27
- text: TextRenderer;
28
- jsx: JsxRenderer<JsxOutput>;
29
- };
30
-
31
- export type TApi<JsxOutput = unknown, TagValue = unknown> = MessageApi<JsxOutput> & {
32
- clone<const Text extends string, const Schema extends MessageSchema | undefined>(
33
- message: MessageDescriptor<Text, Schema>,
34
- ): MessageDescriptor<Text, Schema>;
35
- params<Params extends MessageParams>(params?: Params | null): Params;
36
- tag(element: I18nTagElement): MessageTagHandler<I18nTagValue, I18nTagElement>;
37
- tag<T = TagValue, R = TagValue>(handler: (chunks: Array<string | T>) => R): MessageTagHandler<T, R>;
38
- try<T>(
39
- renderer: TextRenderer,
40
- value: T,
41
- ...args: TryRenderArgs<T>
42
- ): T extends { readonly __fluenticMessage: true; } ? string : T;
43
- try<T>(
44
- renderer: JsxRenderer<JsxOutput>,
45
- value: T,
46
- ...args: TryRenderArgs<T>
47
- ): T extends { readonly __fluenticMessage: true; } ? JsxOutput : T;
48
- notranslate: typeof noTranslate;
49
- };
50
-
51
- export function createT({ getText, getJsx }: Formatting): TApi<I18nJsxOutput, I18nTagValue> {
52
- const createScope = (scope: MessageScope): MessageApi => {
53
- return {
54
- context(name) {
55
- return createScope({ ...scope, context: scope.context ? `${scope.context}.${name}` : name });
56
- },
57
- note(note) {
58
- return createScope({ ...scope, notes: [...scope.notes, note] });
59
- },
60
- meta(meta) {
61
- return createScope({ ...scope, meta });
62
- },
63
- msg(message, schema) {
64
- return createDescriptor(message, schema, scope);
65
- },
66
- text(message: MessageInput, params?: MessageParams) {
67
- return getText(toFormatOptions(message, params, scope));
68
- },
69
- jsx(message: MessageInput, params?: MessageParams) {
70
- return getJsx(toFormatOptions(message, params, scope));
71
- },
72
- };
73
- };
74
-
75
- const createDescriptor = <const Text extends string, const Schema extends MessageSchema | undefined>(
76
- message: Text,
77
- schema: Schema | undefined,
78
- scope: MessageScope,
79
- ): MessageDescriptor<Text, Schema> => {
80
- return Object.freeze({
81
- __fluenticMessage: true,
82
- text: Array.isArray(message) ? message[0] : message,
83
- ...(Array.isArray(message) ? { compiled: message } : {}),
84
- context: scope.context,
85
- schema: schema ?? {},
86
- notes: scope.notes,
87
- meta: scope.meta,
88
- }) as unknown as MessageDescriptor<Text, Schema>;
89
- };
90
-
91
- const toFormatOptions = (message: MessageInput, params: MessageParams | undefined, scope: MessageScope) => {
92
- if (isMessageDescriptor(message)) return { msg: message, params };
93
-
94
- return { msg: createDescriptor(message, undefined, scope), params };
95
- };
96
-
97
- const rootScope = createScope({ context: null, notes: [] });
98
-
99
- return Object.assign(rootScope, {
100
- clone(message: MessageDescriptor) {
101
- return Object.freeze({ ...message });
102
- },
103
- params<Params extends MessageParams>(params?: Params | null): Params {
104
- return (params ?? {}) as Params;
105
- },
106
- tag<T = unknown, R = unknown>(handler: (chunks: Array<string | T>) => R) {
107
- if (typeof handler !== 'function') {
108
- const adapt = getRuntime().tagElement;
109
-
110
- if (!adapt) throw new Error('[i18n] element tags require a platform adapter');
111
-
112
- return createTagHandler(adapt(handler));
113
- }
114
-
115
- return createTagHandler(handler);
116
- },
117
- try<T>(renderer: TextRenderer | JsxRenderer, value: T, params?: MessageParams) {
118
- return isMessageDescriptor(value)
119
- ? (renderer as (message: MessageInput, params?: MessageParams) => unknown)(value, params)
120
- : value;
121
- },
122
- notranslate: noTranslate,
123
- }) as TApi<I18nJsxOutput, I18nTagValue>;
124
- }
package/src/core/index.ts DELETED
@@ -1 +0,0 @@
1
- export * from '../index';