@objectstack/service-i18n 3.0.7
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/.turbo/turbo-build.log +22 -0
- package/LICENSE +202 -0
- package/dist/index.cjs +147 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +104 -0
- package/dist/index.d.ts +104 -0
- package/dist/index.js +109 -0
- package/dist/index.js.map +1 -0
- package/package.json +29 -0
- package/src/file-i18n-adapter.test.ts +185 -0
- package/src/file-i18n-adapter.ts +164 -0
- package/src/i18n-service-plugin.ts +66 -0
- package/src/index.ts +6 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
> @objectstack/service-i18n@3.0.7 build /home/runner/work/spec/spec/packages/services/service-i18n
|
|
3
|
+
> tsup --config ../../../tsup.config.ts
|
|
4
|
+
|
|
5
|
+
[34mCLI[39m Building entry: src/index.ts
|
|
6
|
+
[34mCLI[39m Using tsconfig: tsconfig.json
|
|
7
|
+
[34mCLI[39m tsup v8.5.1
|
|
8
|
+
[34mCLI[39m Using tsup config: /home/runner/work/spec/spec/tsup.config.ts
|
|
9
|
+
[34mCLI[39m Target: es2020
|
|
10
|
+
[34mCLI[39m Cleaning output folder
|
|
11
|
+
[34mESM[39m Build start
|
|
12
|
+
[34mCJS[39m Build start
|
|
13
|
+
[32mCJS[39m [1mdist/index.cjs [22m[32m4.85 KB[39m
|
|
14
|
+
[32mCJS[39m [1mdist/index.cjs.map [22m[32m9.95 KB[39m
|
|
15
|
+
[32mCJS[39m ⚡️ Build success in 46ms
|
|
16
|
+
[32mESM[39m [1mdist/index.js [22m[32m3.19 KB[39m
|
|
17
|
+
[32mESM[39m [1mdist/index.js.map [22m[32m9.54 KB[39m
|
|
18
|
+
[32mESM[39m ⚡️ Build success in 48ms
|
|
19
|
+
[34mDTS[39m Build start
|
|
20
|
+
[32mDTS[39m ⚡️ Build success in 4626ms
|
|
21
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m3.29 KB[39m
|
|
22
|
+
[32mDTS[39m [1mdist/index.d.cts [22m[32m3.29 KB[39m
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute
|
|
108
|
+
must include a readable copy of the attribution notices
|
|
109
|
+
contained within such NOTICE file, excluding those notices
|
|
110
|
+
that do not pertain to any part of the Derivative Works,
|
|
111
|
+
in at least one of the following places: within a NOTICE
|
|
112
|
+
text file distributed as part of the Derivative Works; within
|
|
113
|
+
the Source form or documentation, if provided along with
|
|
114
|
+
the Derivative Works; or, within a display generated by the
|
|
115
|
+
Derivative Works, if and wherever such third-party notices
|
|
116
|
+
normally appear. The contents of the NOTICE file are for
|
|
117
|
+
informational purposes only and do not modify the License.
|
|
118
|
+
You may add Your own attribution notices within Derivative
|
|
119
|
+
Works that You distribute, alongside or as an addendum to
|
|
120
|
+
the NOTICE text from the Work, provided that such additional
|
|
121
|
+
attribution notices cannot be construed as modifying the
|
|
122
|
+
License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 ObjectStack
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
FileI18nAdapter: () => FileI18nAdapter,
|
|
34
|
+
I18nServicePlugin: () => I18nServicePlugin
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(index_exports);
|
|
37
|
+
|
|
38
|
+
// src/file-i18n-adapter.ts
|
|
39
|
+
var fs = __toESM(require("fs"), 1);
|
|
40
|
+
var path = __toESM(require("path"), 1);
|
|
41
|
+
function resolveKey(data, key) {
|
|
42
|
+
const parts = key.split(".");
|
|
43
|
+
let current = data;
|
|
44
|
+
for (const part of parts) {
|
|
45
|
+
if (current == null || typeof current !== "object") return void 0;
|
|
46
|
+
current = current[part];
|
|
47
|
+
}
|
|
48
|
+
return typeof current === "string" ? current : void 0;
|
|
49
|
+
}
|
|
50
|
+
function interpolate(template, params) {
|
|
51
|
+
return template.replace(/\{\{(\w+)\}\}/g, (_match, key) => {
|
|
52
|
+
return params[key] != null ? String(params[key]) : `{{${key}}}`;
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
var FileI18nAdapter = class {
|
|
56
|
+
constructor(options = {}) {
|
|
57
|
+
this.translations = /* @__PURE__ */ new Map();
|
|
58
|
+
this.defaultLocale = options.defaultLocale ?? "en";
|
|
59
|
+
this.fallbackLocale = options.fallbackLocale;
|
|
60
|
+
if (options.localesDir) {
|
|
61
|
+
this.loadFromDirectory(options.localesDir);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
t(key, locale, params) {
|
|
65
|
+
let value = this.resolveFromLocale(key, locale);
|
|
66
|
+
if (value === void 0 && this.fallbackLocale && this.fallbackLocale !== locale) {
|
|
67
|
+
value = this.resolveFromLocale(key, this.fallbackLocale);
|
|
68
|
+
}
|
|
69
|
+
if (value === void 0) return key;
|
|
70
|
+
if (params && Object.keys(params).length > 0) {
|
|
71
|
+
return interpolate(value, params);
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
getTranslations(locale) {
|
|
76
|
+
return this.translations.get(locale) ?? {};
|
|
77
|
+
}
|
|
78
|
+
loadTranslations(locale, translations) {
|
|
79
|
+
const existing = this.translations.get(locale);
|
|
80
|
+
if (existing) {
|
|
81
|
+
this.translations.set(locale, { ...existing, ...translations });
|
|
82
|
+
} else {
|
|
83
|
+
this.translations.set(locale, { ...translations });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
getLocales() {
|
|
87
|
+
return Array.from(this.translations.keys());
|
|
88
|
+
}
|
|
89
|
+
getDefaultLocale() {
|
|
90
|
+
return this.defaultLocale;
|
|
91
|
+
}
|
|
92
|
+
setDefaultLocale(locale) {
|
|
93
|
+
this.defaultLocale = locale;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Load all JSON translation files from a directory.
|
|
97
|
+
* Each file should be named `{locale}.json`.
|
|
98
|
+
*/
|
|
99
|
+
loadFromDirectory(dir) {
|
|
100
|
+
if (!fs.existsSync(dir)) return;
|
|
101
|
+
const files = fs.readdirSync(dir);
|
|
102
|
+
for (const file of files) {
|
|
103
|
+
if (!file.endsWith(".json")) continue;
|
|
104
|
+
const locale = file.replace(/\.json$/, "");
|
|
105
|
+
const filePath = path.join(dir, file);
|
|
106
|
+
try {
|
|
107
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
108
|
+
const data = JSON.parse(content);
|
|
109
|
+
this.translations.set(locale, data);
|
|
110
|
+
} catch {
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
resolveFromLocale(key, locale) {
|
|
115
|
+
const data = this.translations.get(locale);
|
|
116
|
+
if (!data) return void 0;
|
|
117
|
+
return resolveKey(data, key);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
// src/i18n-service-plugin.ts
|
|
122
|
+
var I18nServicePlugin = class {
|
|
123
|
+
constructor(options = {}) {
|
|
124
|
+
this.name = "com.objectstack.service.i18n";
|
|
125
|
+
this.version = "1.0.0";
|
|
126
|
+
this.type = "standard";
|
|
127
|
+
this.options = options;
|
|
128
|
+
}
|
|
129
|
+
async init(ctx) {
|
|
130
|
+
const adapterOptions = {
|
|
131
|
+
defaultLocale: this.options.defaultLocale,
|
|
132
|
+
localesDir: this.options.localesDir,
|
|
133
|
+
fallbackLocale: this.options.fallbackLocale
|
|
134
|
+
};
|
|
135
|
+
const i18n = new FileI18nAdapter(adapterOptions);
|
|
136
|
+
ctx.registerService("i18n", i18n);
|
|
137
|
+
ctx.logger.info(
|
|
138
|
+
`I18nServicePlugin: registered file-based i18n adapter (default: ${i18n.getDefaultLocale()})`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
143
|
+
0 && (module.exports = {
|
|
144
|
+
FileI18nAdapter,
|
|
145
|
+
I18nServicePlugin
|
|
146
|
+
});
|
|
147
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/file-i18n-adapter.ts","../src/i18n-service-plugin.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport { I18nServicePlugin } from './i18n-service-plugin.js';\nexport type { I18nServicePluginOptions } from './i18n-service-plugin.js';\nexport { FileI18nAdapter } from './file-i18n-adapter.js';\nexport type { FileI18nAdapterOptions } from './file-i18n-adapter.js';\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { II18nService } from '@objectstack/spec/contracts';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Configuration options for FileI18nAdapter.\n */\nexport interface FileI18nAdapterOptions {\n /** Default locale (e.g. 'en') */\n defaultLocale?: string;\n /** Directory containing locale files (JSON). Each file should be named `{locale}.json`. */\n localesDir?: string;\n /** Fallback locale when a key is not found in the requested locale */\n fallbackLocale?: string;\n}\n\n/**\n * Resolve a nested key in a translations object using dot notation.\n *\n * @param data - Translation data object\n * @param key - Dot-separated key (e.g. 'objects.account.label')\n * @returns The resolved string value, or undefined if not found\n */\nfunction resolveKey(data: Record<string, unknown>, key: string): string | undefined {\n const parts = key.split('.');\n let current: unknown = data;\n for (const part of parts) {\n if (current == null || typeof current !== 'object') return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return typeof current === 'string' ? current : undefined;\n}\n\n/**\n * Interpolate parameters into a translated string.\n * Replaces `{{paramName}}` with the corresponding value from params.\n *\n * @param template - Template string with `{{key}}` placeholders\n * @param params - Parameter map\n * @returns Interpolated string\n */\nfunction interpolate(template: string, params: Record<string, unknown>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => {\n return params[key] != null ? String(params[key]) : `{{${key}}}`;\n });\n}\n\n/**\n * File-based I18n adapter implementing II18nService.\n *\n * Loads JSON translation files from a directory on disk.\n * Each file should be named `{locale}.json` and contain a flat or nested\n * key-value map of translations.\n *\n * Supports:\n * - Dot-notation key resolution (e.g. 'objects.account.label')\n * - Parameter interpolation via `{{paramName}}` syntax\n * - Fallback locale for missing translations\n * - Runtime translation loading via loadTranslations()\n *\n * Suitable for server-side rendering, CLI tools, and development environments.\n *\n * @example\n * ```ts\n * const i18n = new FileI18nAdapter({\n * defaultLocale: 'en',\n * localesDir: './i18n',\n * fallbackLocale: 'en',\n * });\n *\n * i18n.t('objects.account.label', 'zh-CN'); // '客户'\n * i18n.t('greeting', 'en', { name: 'World' }); // 'Hello, World!'\n * ```\n */\nexport class FileI18nAdapter implements II18nService {\n private readonly translations = new Map<string, Record<string, unknown>>();\n private defaultLocale: string;\n private readonly fallbackLocale: string | undefined;\n\n constructor(options: FileI18nAdapterOptions = {}) {\n this.defaultLocale = options.defaultLocale ?? 'en';\n this.fallbackLocale = options.fallbackLocale;\n\n if (options.localesDir) {\n this.loadFromDirectory(options.localesDir);\n }\n }\n\n t(key: string, locale: string, params?: Record<string, unknown>): string {\n // Try requested locale\n let value = this.resolveFromLocale(key, locale);\n\n // Try fallback locale\n if (value === undefined && this.fallbackLocale && this.fallbackLocale !== locale) {\n value = this.resolveFromLocale(key, this.fallbackLocale);\n }\n\n // Return key if not found\n if (value === undefined) return key;\n\n // Interpolate parameters\n if (params && Object.keys(params).length > 0) {\n return interpolate(value, params);\n }\n\n return value;\n }\n\n getTranslations(locale: string): Record<string, unknown> {\n return this.translations.get(locale) ?? {};\n }\n\n loadTranslations(locale: string, translations: Record<string, unknown>): void {\n const existing = this.translations.get(locale);\n if (existing) {\n // Merge into existing translations\n this.translations.set(locale, { ...existing, ...translations });\n } else {\n this.translations.set(locale, { ...translations });\n }\n }\n\n getLocales(): string[] {\n return Array.from(this.translations.keys());\n }\n\n getDefaultLocale(): string {\n return this.defaultLocale;\n }\n\n setDefaultLocale(locale: string): void {\n this.defaultLocale = locale;\n }\n\n /**\n * Load all JSON translation files from a directory.\n * Each file should be named `{locale}.json`.\n */\n private loadFromDirectory(dir: string): void {\n if (!fs.existsSync(dir)) return;\n\n const files = fs.readdirSync(dir);\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const locale = file.replace(/\\.json$/, '');\n const filePath = path.join(dir, file);\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n const data = JSON.parse(content) as Record<string, unknown>;\n this.translations.set(locale, data);\n } catch {\n // Skip files that can't be parsed\n }\n }\n }\n\n private resolveFromLocale(key: string, locale: string): string | undefined {\n const data = this.translations.get(locale);\n if (!data) return undefined;\n return resolveKey(data, key);\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { FileI18nAdapter } from './file-i18n-adapter.js';\nimport type { FileI18nAdapterOptions } from './file-i18n-adapter.js';\n\n/**\n * Configuration options for the I18nServicePlugin.\n */\nexport interface I18nServicePluginOptions {\n /** Default locale (default: 'en') */\n defaultLocale?: string;\n /** Directory containing locale JSON files */\n localesDir?: string;\n /** Fallback locale for missing translations */\n fallbackLocale?: string;\n}\n\n/**\n * I18nServicePlugin — Production II18nService implementation.\n *\n * Registers an i18n service with the kernel during the init phase.\n * Uses file-based locale loading with JSON files.\n *\n * @example\n * ```ts\n * import { ObjectKernel } from '@objectstack/core';\n * import { I18nServicePlugin } from '@objectstack/service-i18n';\n *\n * const kernel = new ObjectKernel();\n * kernel.use(new I18nServicePlugin({\n * defaultLocale: 'en',\n * localesDir: './i18n',\n * fallbackLocale: 'en',\n * }));\n * await kernel.bootstrap();\n *\n * const i18n = kernel.getService('i18n');\n * i18n.t('objects.account.label', 'en'); // 'Account'\n * ```\n */\nexport class I18nServicePlugin implements Plugin {\n name = 'com.objectstack.service.i18n';\n version = '1.0.0';\n type = 'standard';\n\n private readonly options: I18nServicePluginOptions;\n\n constructor(options: I18nServicePluginOptions = {}) {\n this.options = options;\n }\n\n async init(ctx: PluginContext): Promise<void> {\n const adapterOptions: FileI18nAdapterOptions = {\n defaultLocale: this.options.defaultLocale,\n localesDir: this.options.localesDir,\n fallbackLocale: this.options.fallbackLocale,\n };\n\n const i18n = new FileI18nAdapter(adapterOptions);\n ctx.registerService('i18n', i18n);\n ctx.logger.info(\n `I18nServicePlugin: registered file-based i18n adapter (default: ${i18n.getDefaultLocale()})`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGA,SAAoB;AACpB,WAAsB;AAqBtB,SAAS,WAAW,MAA+B,KAAiC;AAClF,QA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I,gBAAgB,cAAc;AAC/C,QAAI,gBAAgB,QAAQ,IAAI;AAChC,QAAI,OAAO;AAAA,MACT,mEAAmE,KAAK,iBAAiB,CAAC;AAAA,IAC5F;AAAA,EACF;AACF;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { Plugin, PluginContext } from '@objectstack/core';
|
|
2
|
+
import { II18nService } from '@objectstack/spec/contracts';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Configuration options for the I18nServicePlugin.
|
|
6
|
+
*/
|
|
7
|
+
interface I18nServicePluginOptions {
|
|
8
|
+
/** Default locale (default: 'en') */
|
|
9
|
+
defaultLocale?: string;
|
|
10
|
+
/** Directory containing locale JSON files */
|
|
11
|
+
localesDir?: string;
|
|
12
|
+
/** Fallback locale for missing translations */
|
|
13
|
+
fallbackLocale?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* I18nServicePlugin — Production II18nService implementation.
|
|
17
|
+
*
|
|
18
|
+
* Registers an i18n service with the kernel during the init phase.
|
|
19
|
+
* Uses file-based locale loading with JSON files.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* import { ObjectKernel } from '@objectstack/core';
|
|
24
|
+
* import { I18nServicePlugin } from '@objectstack/service-i18n';
|
|
25
|
+
*
|
|
26
|
+
* const kernel = new ObjectKernel();
|
|
27
|
+
* kernel.use(new I18nServicePlugin({
|
|
28
|
+
* defaultLocale: 'en',
|
|
29
|
+
* localesDir: './i18n',
|
|
30
|
+
* fallbackLocale: 'en',
|
|
31
|
+
* }));
|
|
32
|
+
* await kernel.bootstrap();
|
|
33
|
+
*
|
|
34
|
+
* const i18n = kernel.getService('i18n');
|
|
35
|
+
* i18n.t('objects.account.label', 'en'); // 'Account'
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
declare class I18nServicePlugin implements Plugin {
|
|
39
|
+
name: string;
|
|
40
|
+
version: string;
|
|
41
|
+
type: string;
|
|
42
|
+
private readonly options;
|
|
43
|
+
constructor(options?: I18nServicePluginOptions);
|
|
44
|
+
init(ctx: PluginContext): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Configuration options for FileI18nAdapter.
|
|
49
|
+
*/
|
|
50
|
+
interface FileI18nAdapterOptions {
|
|
51
|
+
/** Default locale (e.g. 'en') */
|
|
52
|
+
defaultLocale?: string;
|
|
53
|
+
/** Directory containing locale files (JSON). Each file should be named `{locale}.json`. */
|
|
54
|
+
localesDir?: string;
|
|
55
|
+
/** Fallback locale when a key is not found in the requested locale */
|
|
56
|
+
fallbackLocale?: string;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* File-based I18n adapter implementing II18nService.
|
|
60
|
+
*
|
|
61
|
+
* Loads JSON translation files from a directory on disk.
|
|
62
|
+
* Each file should be named `{locale}.json` and contain a flat or nested
|
|
63
|
+
* key-value map of translations.
|
|
64
|
+
*
|
|
65
|
+
* Supports:
|
|
66
|
+
* - Dot-notation key resolution (e.g. 'objects.account.label')
|
|
67
|
+
* - Parameter interpolation via `{{paramName}}` syntax
|
|
68
|
+
* - Fallback locale for missing translations
|
|
69
|
+
* - Runtime translation loading via loadTranslations()
|
|
70
|
+
*
|
|
71
|
+
* Suitable for server-side rendering, CLI tools, and development environments.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* const i18n = new FileI18nAdapter({
|
|
76
|
+
* defaultLocale: 'en',
|
|
77
|
+
* localesDir: './i18n',
|
|
78
|
+
* fallbackLocale: 'en',
|
|
79
|
+
* });
|
|
80
|
+
*
|
|
81
|
+
* i18n.t('objects.account.label', 'zh-CN'); // '客户'
|
|
82
|
+
* i18n.t('greeting', 'en', { name: 'World' }); // 'Hello, World!'
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
declare class FileI18nAdapter implements II18nService {
|
|
86
|
+
private readonly translations;
|
|
87
|
+
private defaultLocale;
|
|
88
|
+
private readonly fallbackLocale;
|
|
89
|
+
constructor(options?: FileI18nAdapterOptions);
|
|
90
|
+
t(key: string, locale: string, params?: Record<string, unknown>): string;
|
|
91
|
+
getTranslations(locale: string): Record<string, unknown>;
|
|
92
|
+
loadTranslations(locale: string, translations: Record<string, unknown>): void;
|
|
93
|
+
getLocales(): string[];
|
|
94
|
+
getDefaultLocale(): string;
|
|
95
|
+
setDefaultLocale(locale: string): void;
|
|
96
|
+
/**
|
|
97
|
+
* Load all JSON translation files from a directory.
|
|
98
|
+
* Each file should be named `{locale}.json`.
|
|
99
|
+
*/
|
|
100
|
+
private loadFromDirectory;
|
|
101
|
+
private resolveFromLocale;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export { FileI18nAdapter, type FileI18nAdapterOptions, I18nServicePlugin, type I18nServicePluginOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { Plugin, PluginContext } from '@objectstack/core';
|
|
2
|
+
import { II18nService } from '@objectstack/spec/contracts';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Configuration options for the I18nServicePlugin.
|
|
6
|
+
*/
|
|
7
|
+
interface I18nServicePluginOptions {
|
|
8
|
+
/** Default locale (default: 'en') */
|
|
9
|
+
defaultLocale?: string;
|
|
10
|
+
/** Directory containing locale JSON files */
|
|
11
|
+
localesDir?: string;
|
|
12
|
+
/** Fallback locale for missing translations */
|
|
13
|
+
fallbackLocale?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* I18nServicePlugin — Production II18nService implementation.
|
|
17
|
+
*
|
|
18
|
+
* Registers an i18n service with the kernel during the init phase.
|
|
19
|
+
* Uses file-based locale loading with JSON files.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* import { ObjectKernel } from '@objectstack/core';
|
|
24
|
+
* import { I18nServicePlugin } from '@objectstack/service-i18n';
|
|
25
|
+
*
|
|
26
|
+
* const kernel = new ObjectKernel();
|
|
27
|
+
* kernel.use(new I18nServicePlugin({
|
|
28
|
+
* defaultLocale: 'en',
|
|
29
|
+
* localesDir: './i18n',
|
|
30
|
+
* fallbackLocale: 'en',
|
|
31
|
+
* }));
|
|
32
|
+
* await kernel.bootstrap();
|
|
33
|
+
*
|
|
34
|
+
* const i18n = kernel.getService('i18n');
|
|
35
|
+
* i18n.t('objects.account.label', 'en'); // 'Account'
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
declare class I18nServicePlugin implements Plugin {
|
|
39
|
+
name: string;
|
|
40
|
+
version: string;
|
|
41
|
+
type: string;
|
|
42
|
+
private readonly options;
|
|
43
|
+
constructor(options?: I18nServicePluginOptions);
|
|
44
|
+
init(ctx: PluginContext): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Configuration options for FileI18nAdapter.
|
|
49
|
+
*/
|
|
50
|
+
interface FileI18nAdapterOptions {
|
|
51
|
+
/** Default locale (e.g. 'en') */
|
|
52
|
+
defaultLocale?: string;
|
|
53
|
+
/** Directory containing locale files (JSON). Each file should be named `{locale}.json`. */
|
|
54
|
+
localesDir?: string;
|
|
55
|
+
/** Fallback locale when a key is not found in the requested locale */
|
|
56
|
+
fallbackLocale?: string;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* File-based I18n adapter implementing II18nService.
|
|
60
|
+
*
|
|
61
|
+
* Loads JSON translation files from a directory on disk.
|
|
62
|
+
* Each file should be named `{locale}.json` and contain a flat or nested
|
|
63
|
+
* key-value map of translations.
|
|
64
|
+
*
|
|
65
|
+
* Supports:
|
|
66
|
+
* - Dot-notation key resolution (e.g. 'objects.account.label')
|
|
67
|
+
* - Parameter interpolation via `{{paramName}}` syntax
|
|
68
|
+
* - Fallback locale for missing translations
|
|
69
|
+
* - Runtime translation loading via loadTranslations()
|
|
70
|
+
*
|
|
71
|
+
* Suitable for server-side rendering, CLI tools, and development environments.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* const i18n = new FileI18nAdapter({
|
|
76
|
+
* defaultLocale: 'en',
|
|
77
|
+
* localesDir: './i18n',
|
|
78
|
+
* fallbackLocale: 'en',
|
|
79
|
+
* });
|
|
80
|
+
*
|
|
81
|
+
* i18n.t('objects.account.label', 'zh-CN'); // '客户'
|
|
82
|
+
* i18n.t('greeting', 'en', { name: 'World' }); // 'Hello, World!'
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
declare class FileI18nAdapter implements II18nService {
|
|
86
|
+
private readonly translations;
|
|
87
|
+
private defaultLocale;
|
|
88
|
+
private readonly fallbackLocale;
|
|
89
|
+
constructor(options?: FileI18nAdapterOptions);
|
|
90
|
+
t(key: string, locale: string, params?: Record<string, unknown>): string;
|
|
91
|
+
getTranslations(locale: string): Record<string, unknown>;
|
|
92
|
+
loadTranslations(locale: string, translations: Record<string, unknown>): void;
|
|
93
|
+
getLocales(): string[];
|
|
94
|
+
getDefaultLocale(): string;
|
|
95
|
+
setDefaultLocale(locale: string): void;
|
|
96
|
+
/**
|
|
97
|
+
* Load all JSON translation files from a directory.
|
|
98
|
+
* Each file should be named `{locale}.json`.
|
|
99
|
+
*/
|
|
100
|
+
private loadFromDirectory;
|
|
101
|
+
private resolveFromLocale;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export { FileI18nAdapter, type FileI18nAdapterOptions, I18nServicePlugin, type I18nServicePluginOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// src/file-i18n-adapter.ts
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
function resolveKey(data, key) {
|
|
5
|
+
const parts = key.split(".");
|
|
6
|
+
let current = data;
|
|
7
|
+
for (const part of parts) {
|
|
8
|
+
if (current == null || typeof current !== "object") return void 0;
|
|
9
|
+
current = current[part];
|
|
10
|
+
}
|
|
11
|
+
return typeof current === "string" ? current : void 0;
|
|
12
|
+
}
|
|
13
|
+
function interpolate(template, params) {
|
|
14
|
+
return template.replace(/\{\{(\w+)\}\}/g, (_match, key) => {
|
|
15
|
+
return params[key] != null ? String(params[key]) : `{{${key}}}`;
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
var FileI18nAdapter = class {
|
|
19
|
+
constructor(options = {}) {
|
|
20
|
+
this.translations = /* @__PURE__ */ new Map();
|
|
21
|
+
this.defaultLocale = options.defaultLocale ?? "en";
|
|
22
|
+
this.fallbackLocale = options.fallbackLocale;
|
|
23
|
+
if (options.localesDir) {
|
|
24
|
+
this.loadFromDirectory(options.localesDir);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
t(key, locale, params) {
|
|
28
|
+
let value = this.resolveFromLocale(key, locale);
|
|
29
|
+
if (value === void 0 && this.fallbackLocale && this.fallbackLocale !== locale) {
|
|
30
|
+
value = this.resolveFromLocale(key, this.fallbackLocale);
|
|
31
|
+
}
|
|
32
|
+
if (value === void 0) return key;
|
|
33
|
+
if (params && Object.keys(params).length > 0) {
|
|
34
|
+
return interpolate(value, params);
|
|
35
|
+
}
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
getTranslations(locale) {
|
|
39
|
+
return this.translations.get(locale) ?? {};
|
|
40
|
+
}
|
|
41
|
+
loadTranslations(locale, translations) {
|
|
42
|
+
const existing = this.translations.get(locale);
|
|
43
|
+
if (existing) {
|
|
44
|
+
this.translations.set(locale, { ...existing, ...translations });
|
|
45
|
+
} else {
|
|
46
|
+
this.translations.set(locale, { ...translations });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
getLocales() {
|
|
50
|
+
return Array.from(this.translations.keys());
|
|
51
|
+
}
|
|
52
|
+
getDefaultLocale() {
|
|
53
|
+
return this.defaultLocale;
|
|
54
|
+
}
|
|
55
|
+
setDefaultLocale(locale) {
|
|
56
|
+
this.defaultLocale = locale;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Load all JSON translation files from a directory.
|
|
60
|
+
* Each file should be named `{locale}.json`.
|
|
61
|
+
*/
|
|
62
|
+
loadFromDirectory(dir) {
|
|
63
|
+
if (!fs.existsSync(dir)) return;
|
|
64
|
+
const files = fs.readdirSync(dir);
|
|
65
|
+
for (const file of files) {
|
|
66
|
+
if (!file.endsWith(".json")) continue;
|
|
67
|
+
const locale = file.replace(/\.json$/, "");
|
|
68
|
+
const filePath = path.join(dir, file);
|
|
69
|
+
try {
|
|
70
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
71
|
+
const data = JSON.parse(content);
|
|
72
|
+
this.translations.set(locale, data);
|
|
73
|
+
} catch {
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
resolveFromLocale(key, locale) {
|
|
78
|
+
const data = this.translations.get(locale);
|
|
79
|
+
if (!data) return void 0;
|
|
80
|
+
return resolveKey(data, key);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// src/i18n-service-plugin.ts
|
|
85
|
+
var I18nServicePlugin = class {
|
|
86
|
+
constructor(options = {}) {
|
|
87
|
+
this.name = "com.objectstack.service.i18n";
|
|
88
|
+
this.version = "1.0.0";
|
|
89
|
+
this.type = "standard";
|
|
90
|
+
this.options = options;
|
|
91
|
+
}
|
|
92
|
+
async init(ctx) {
|
|
93
|
+
const adapterOptions = {
|
|
94
|
+
defaultLocale: this.options.defaultLocale,
|
|
95
|
+
localesDir: this.options.localesDir,
|
|
96
|
+
fallbackLocale: this.options.fallbackLocale
|
|
97
|
+
};
|
|
98
|
+
const i18n = new FileI18nAdapter(adapterOptions);
|
|
99
|
+
ctx.registerService("i18n", i18n);
|
|
100
|
+
ctx.logger.info(
|
|
101
|
+
`I18nServicePlugin: registered file-based i18n adapter (default: ${i18n.getDefaultLocale()})`
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
export {
|
|
106
|
+
FileI18nAdapter,
|
|
107
|
+
I18nServicePlugin
|
|
108
|
+
};
|
|
109
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/file-i18n-adapter.ts","../src/i18n-service-plugin.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { II18nService } from '@objectstack/spec/contracts';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Configuration options for FileI18nAdapter.\n */\nexport interface FileI18nAdapterOptions {\n /** Default locale (e.g. 'en') */\n defaultLocale?: string;\n /** Directory containing locale files (JSON). Each file should be named `{locale}.json`. */\n localesDir?: string;\n /** Fallback locale when a key is not found in the requested locale */\n fallbackLocale?: string;\n}\n\n/**\n * Resolve a nested key in a translations object using dot notation.\n *\n * @param data - Translation data object\n * @param key - Dot-separated key (e.g. 'objects.account.label')\n * @returns The resolved string value, or undefined if not found\n */\nfunction resolveKey(data: Record<string, unknown>, key: string): string | undefined {\n const parts = key.split('.');\n let current: unknown = data;\n for (const part of parts) {\n if (current == null || typeof current !== 'object') return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return typeof current === 'string' ? current : undefined;\n}\n\n/**\n * Interpolate parameters into a translated string.\n * Replaces `{{paramName}}` with the corresponding value from params.\n *\n * @param template - Template string with `{{key}}` placeholders\n * @param params - Parameter map\n * @returns Interpolated string\n */\nfunction interpolate(template: string, params: Record<string, unknown>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => {\n return params[key] != null ? String(params[key]) : `{{${key}}}`;\n });\n}\n\n/**\n * File-based I18n adapter implementing II18nService.\n *\n * Loads JSON translation files from a directory on disk.\n * Each file should be named `{locale}.json` and contain a flat or nested\n * key-value map of translations.\n *\n * Supports:\n * - Dot-notation key resolution (e.g. 'objects.account.label')\n * - Parameter interpolation via `{{paramName}}` syntax\n * - Fallback locale for missing translations\n * - Runtime translation loading via loadTranslations()\n *\n * Suitable for server-side rendering, CLI tools, and development environments.\n *\n * @example\n * ```ts\n * const i18n = new FileI18nAdapter({\n * defaultLocale: 'en',\n * localesDir: './i18n',\n * fallbackLocale: 'en',\n * });\n *\n * i18n.t('objects.account.label', 'zh-CN'); // '客户'\n * i18n.t('greeting', 'en', { name: 'World' }); // 'Hello, World!'\n * ```\n */\nexport class FileI18nAdapter implements II18nService {\n private readonly translations = new Map<string, Record<string, unknown>>();\n private defaultLocale: string;\n private readonly fallbackLocale: string | undefined;\n\n constructor(options: FileI18nAdapterOptions = {}) {\n this.defaultLocale = options.defaultLocale ?? 'en';\n this.fallbackLocale = options.fallbackLocale;\n\n if (options.localesDir) {\n this.loadFromDirectory(options.localesDir);\n }\n }\n\n t(key: string, locale: string, params?: Record<string, unknown>): string {\n // Try requested locale\n let value = this.resolveFromLocale(key, locale);\n\n // Try fallback locale\n if (value === undefined && this.fallbackLocale && this.fallbackLocale !== locale) {\n value = this.resolveFromLocale(key, this.fallbackLocale);\n }\n\n // Return key if not found\n if (value === undefined) return key;\n\n // Interpolate parameters\n if (params && Object.keys(params).length > 0) {\n return interpolate(value, params);\n }\n\n return value;\n }\n\n getTranslations(locale: string): Record<string, unknown> {\n return this.translations.get(locale) ?? {};\n }\n\n loadTranslations(locale: string, translations: Record<string, unknown>): void {\n const existing = this.translations.get(locale);\n if (existing) {\n // Merge into existing translations\n this.translations.set(locale, { ...existing, ...translations });\n } else {\n this.translations.set(locale, { ...translations });\n }\n }\n\n getLocales(): string[] {\n return Array.from(this.translations.keys());\n }\n\n getDefaultLocale(): string {\n return this.defaultLocale;\n }\n\n setDefaultLocale(locale: string): void {\n this.defaultLocale = locale;\n }\n\n /**\n * Load all JSON translation files from a directory.\n * Each file should be named `{locale}.json`.\n */\n private loadFromDirectory(dir: string): void {\n if (!fs.existsSync(dir)) return;\n\n const files = fs.readdirSync(dir);\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const locale = file.replace(/\\.json$/, '');\n const filePath = path.join(dir, file);\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n const data = JSON.parse(content) as Record<string, unknown>;\n this.translations.set(locale, data);\n } catch {\n // Skip files that can't be parsed\n }\n }\n }\n\n private resolveFromLocale(key: string, locale: string): string | undefined {\n const data = this.translations.get(locale);\n if (!data) return undefined;\n return resolveKey(data, key);\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { FileI18nAdapter } from './file-i18n-adapter.js';\nimport type { FileI18nAdapterOptions } from './file-i18n-adapter.js';\n\n/**\n * Configuration options for the I18nServicePlugin.\n */\nexport interface I18nServicePluginOptions {\n /** Default locale (default: 'en') */\n defaultLocale?: string;\n /** Directory containing locale JSON files */\n localesDir?: string;\n /** Fallback locale for missing translations */\n fallbackLocale?: string;\n}\n\n/**\n * I18nServicePlugin — Production II18nService implementation.\n *\n * Registers an i18n service with the kernel during the init phase.\n * Uses file-based locale loading with JSON files.\n *\n * @example\n * ```ts\n * import { ObjectKernel } from '@objectstack/core';\n * import { I18nServicePlugin } from '@objectstack/service-i18n';\n *\n * const kernel = new ObjectKernel();\n * kernel.use(new I18nServicePlugin({\n * defaultLocale: 'en',\n * localesDir: './i18n',\n * fallbackLocale: 'en',\n * }));\n * await kernel.bootstrap();\n *\n * const i18n = kernel.getService('i18n');\n * i18n.t('objects.account.label', 'en'); // 'Account'\n * ```\n */\nexport class I18nServicePlugin implements Plugin {\n name = 'com.objectstack.service.i18n';\n version = '1.0.0';\n type = 'standard';\n\n private readonly options: I18nServicePluginOptions;\n\n constructor(options: I18nServicePluginOptions = {}) {\n this.options = options;\n }\n\n async init(ctx: PluginContext): Promise<void> {\n const adapterOptions: FileI18nAdapterOptions = {\n defaultLocale: this.options.defaultLocale,\n localesDir: this.options.localesDir,\n fallbackLocale: this.options.fallbackLocale,\n };\n\n const i18n = new FileI18nAdapter(adapterOptions);\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ACjB;AAAA,EAEA,MAAM,KAAK,KAAmC;AAC5C,UAAM,iBAAyC;AAAA,MAC7C,eAAe,KAAK,QAAQ;AAAA,MAC5B,YAAY,KAAK,QAAQ;AAAA,MACzB,gBAAgB,KAAK,QAAQ;AAAA,IAC/B;AAEA,UAAM,OAAO,IAAI,gBAAgB,cAAc;AAC/C,QAAI,gBAAgB,QAAQ,IAAI;AAChC,QAAI,OAAO;AAAA,MACT,mEAAmE,KAAK,iBAAiB,CAAC;AAAA,IAC5F;AAAA,EACF;AACF;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@objectstack/service-i18n",
|
|
3
|
+
"version": "3.0.7",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"description": "I18n Service for ObjectStack — implements II18nService with file-based locale loading",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.mjs",
|
|
13
|
+
"require": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@objectstack/core": "3.0.7",
|
|
18
|
+
"@objectstack/spec": "3.0.7"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"typescript": "^5.0.0",
|
|
22
|
+
"vitest": "^4.0.18",
|
|
23
|
+
"@types/node": "^25.2.3"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsup --config ../../../tsup.config.ts",
|
|
27
|
+
"test": "vitest run"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
|
4
|
+
import { FileI18nAdapter } from './file-i18n-adapter';
|
|
5
|
+
import type { II18nService } from '@objectstack/spec/contracts';
|
|
6
|
+
import * as fs from 'node:fs';
|
|
7
|
+
import * as path from 'node:path';
|
|
8
|
+
import * as os from 'node:os';
|
|
9
|
+
|
|
10
|
+
describe('FileI18nAdapter', () => {
|
|
11
|
+
it('should implement II18nService contract', () => {
|
|
12
|
+
const i18n: II18nService = new FileI18nAdapter();
|
|
13
|
+
expect(typeof i18n.t).toBe('function');
|
|
14
|
+
expect(typeof i18n.getTranslations).toBe('function');
|
|
15
|
+
expect(typeof i18n.loadTranslations).toBe('function');
|
|
16
|
+
expect(typeof i18n.getLocales).toBe('function');
|
|
17
|
+
expect(typeof i18n.getDefaultLocale).toBe('function');
|
|
18
|
+
expect(typeof i18n.setDefaultLocale).toBe('function');
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('should default to "en" locale', () => {
|
|
22
|
+
const i18n = new FileI18nAdapter();
|
|
23
|
+
expect(i18n.getDefaultLocale()).toBe('en');
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('should use custom default locale', () => {
|
|
27
|
+
const i18n = new FileI18nAdapter({ defaultLocale: 'zh-CN' });
|
|
28
|
+
expect(i18n.getDefaultLocale()).toBe('zh-CN');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('should set and get default locale', () => {
|
|
32
|
+
const i18n = new FileI18nAdapter();
|
|
33
|
+
i18n.setDefaultLocale('ja');
|
|
34
|
+
expect(i18n.getDefaultLocale()).toBe('ja');
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('should return empty translations for unknown locale', () => {
|
|
38
|
+
const i18n = new FileI18nAdapter();
|
|
39
|
+
expect(i18n.getTranslations('fr')).toEqual({});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('should return empty locales when no translations loaded', () => {
|
|
43
|
+
const i18n = new FileI18nAdapter();
|
|
44
|
+
expect(i18n.getLocales()).toEqual([]);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('should load and retrieve translations', () => {
|
|
48
|
+
const i18n = new FileI18nAdapter();
|
|
49
|
+
i18n.loadTranslations('en', { greeting: 'Hello' });
|
|
50
|
+
i18n.loadTranslations('zh-CN', { greeting: '你好' });
|
|
51
|
+
|
|
52
|
+
expect(i18n.getLocales()).toContain('en');
|
|
53
|
+
expect(i18n.getLocales()).toContain('zh-CN');
|
|
54
|
+
expect(i18n.getTranslations('en')).toEqual({ greeting: 'Hello' });
|
|
55
|
+
expect(i18n.getTranslations('zh-CN')).toEqual({ greeting: '你好' });
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('should merge translations when loading into existing locale', () => {
|
|
59
|
+
const i18n = new FileI18nAdapter();
|
|
60
|
+
i18n.loadTranslations('en', { greeting: 'Hello' });
|
|
61
|
+
i18n.loadTranslations('en', { farewell: 'Goodbye' });
|
|
62
|
+
|
|
63
|
+
expect(i18n.getTranslations('en')).toEqual({
|
|
64
|
+
greeting: 'Hello',
|
|
65
|
+
farewell: 'Goodbye',
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('should translate a simple key', () => {
|
|
70
|
+
const i18n = new FileI18nAdapter();
|
|
71
|
+
i18n.loadTranslations('en', { greeting: 'Hello' });
|
|
72
|
+
|
|
73
|
+
expect(i18n.t('greeting', 'en')).toBe('Hello');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('should return key when translation is missing', () => {
|
|
77
|
+
const i18n = new FileI18nAdapter();
|
|
78
|
+
expect(i18n.t('missing.key', 'en')).toBe('missing.key');
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('should resolve nested dot-notation keys', () => {
|
|
82
|
+
const i18n = new FileI18nAdapter();
|
|
83
|
+
i18n.loadTranslations('en', {
|
|
84
|
+
objects: {
|
|
85
|
+
account: {
|
|
86
|
+
label: 'Account',
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
expect(i18n.t('objects.account.label', 'en')).toBe('Account');
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('should interpolate parameters', () => {
|
|
95
|
+
const i18n = new FileI18nAdapter();
|
|
96
|
+
i18n.loadTranslations('en', { greeting: 'Hello, {{name}}!' });
|
|
97
|
+
|
|
98
|
+
expect(i18n.t('greeting', 'en', { name: 'World' })).toBe('Hello, World!');
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('should keep placeholder when parameter is missing', () => {
|
|
102
|
+
const i18n = new FileI18nAdapter();
|
|
103
|
+
i18n.loadTranslations('en', { greeting: 'Hello, {{name}}!' });
|
|
104
|
+
|
|
105
|
+
expect(i18n.t('greeting', 'en', {})).toBe('Hello, {{name}}!');
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('should fallback to fallback locale when key not found', () => {
|
|
109
|
+
const i18n = new FileI18nAdapter({ fallbackLocale: 'en' });
|
|
110
|
+
i18n.loadTranslations('en', { greeting: 'Hello' });
|
|
111
|
+
|
|
112
|
+
expect(i18n.t('greeting', 'zh-CN')).toBe('Hello');
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('should not fallback when key exists in requested locale', () => {
|
|
116
|
+
const i18n = new FileI18nAdapter({ fallbackLocale: 'en' });
|
|
117
|
+
i18n.loadTranslations('en', { greeting: 'Hello' });
|
|
118
|
+
i18n.loadTranslations('zh-CN', { greeting: '你好' });
|
|
119
|
+
|
|
120
|
+
expect(i18n.t('greeting', 'zh-CN')).toBe('你好');
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('should return key when neither locale nor fallback has translation', () => {
|
|
124
|
+
const i18n = new FileI18nAdapter({ fallbackLocale: 'en' });
|
|
125
|
+
i18n.loadTranslations('en', { greeting: 'Hello' });
|
|
126
|
+
|
|
127
|
+
expect(i18n.t('missing.key', 'zh-CN')).toBe('missing.key');
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe('file-based loading', () => {
|
|
131
|
+
let tmpDir: string;
|
|
132
|
+
|
|
133
|
+
beforeEach(() => {
|
|
134
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'i18n-test-'));
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
afterEach(() => {
|
|
138
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('should load translations from JSON files in a directory', () => {
|
|
142
|
+
fs.writeFileSync(
|
|
143
|
+
path.join(tmpDir, 'en.json'),
|
|
144
|
+
JSON.stringify({ greeting: 'Hello', objects: { account: { label: 'Account' } } }),
|
|
145
|
+
);
|
|
146
|
+
fs.writeFileSync(
|
|
147
|
+
path.join(tmpDir, 'zh-CN.json'),
|
|
148
|
+
JSON.stringify({ greeting: '你好', objects: { account: { label: '客户' } } }),
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
const i18n = new FileI18nAdapter({ localesDir: tmpDir });
|
|
152
|
+
|
|
153
|
+
expect(i18n.getLocales()).toContain('en');
|
|
154
|
+
expect(i18n.getLocales()).toContain('zh-CN');
|
|
155
|
+
expect(i18n.t('greeting', 'en')).toBe('Hello');
|
|
156
|
+
expect(i18n.t('greeting', 'zh-CN')).toBe('你好');
|
|
157
|
+
expect(i18n.t('objects.account.label', 'en')).toBe('Account');
|
|
158
|
+
expect(i18n.t('objects.account.label', 'zh-CN')).toBe('客户');
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('should ignore non-JSON files in the directory', () => {
|
|
162
|
+
fs.writeFileSync(path.join(tmpDir, 'en.json'), JSON.stringify({ greeting: 'Hello' }));
|
|
163
|
+
fs.writeFileSync(path.join(tmpDir, 'notes.txt'), 'not a translation file');
|
|
164
|
+
|
|
165
|
+
const i18n = new FileI18nAdapter({ localesDir: tmpDir });
|
|
166
|
+
|
|
167
|
+
expect(i18n.getLocales()).toEqual(['en']);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it('should skip malformed JSON files gracefully', () => {
|
|
171
|
+
fs.writeFileSync(path.join(tmpDir, 'en.json'), JSON.stringify({ greeting: 'Hello' }));
|
|
172
|
+
fs.writeFileSync(path.join(tmpDir, 'bad.json'), '{invalid json');
|
|
173
|
+
|
|
174
|
+
const i18n = new FileI18nAdapter({ localesDir: tmpDir });
|
|
175
|
+
|
|
176
|
+
expect(i18n.getLocales()).toEqual(['en']);
|
|
177
|
+
expect(i18n.t('greeting', 'en')).toBe('Hello');
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it('should handle non-existent directory gracefully', () => {
|
|
181
|
+
const i18n = new FileI18nAdapter({ localesDir: '/nonexistent/path' });
|
|
182
|
+
expect(i18n.getLocales()).toEqual([]);
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
});
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import type { II18nService } from '@objectstack/spec/contracts';
|
|
4
|
+
import * as fs from 'node:fs';
|
|
5
|
+
import * as path from 'node:path';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Configuration options for FileI18nAdapter.
|
|
9
|
+
*/
|
|
10
|
+
export interface FileI18nAdapterOptions {
|
|
11
|
+
/** Default locale (e.g. 'en') */
|
|
12
|
+
defaultLocale?: string;
|
|
13
|
+
/** Directory containing locale files (JSON). Each file should be named `{locale}.json`. */
|
|
14
|
+
localesDir?: string;
|
|
15
|
+
/** Fallback locale when a key is not found in the requested locale */
|
|
16
|
+
fallbackLocale?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Resolve a nested key in a translations object using dot notation.
|
|
21
|
+
*
|
|
22
|
+
* @param data - Translation data object
|
|
23
|
+
* @param key - Dot-separated key (e.g. 'objects.account.label')
|
|
24
|
+
* @returns The resolved string value, or undefined if not found
|
|
25
|
+
*/
|
|
26
|
+
function resolveKey(data: Record<string, unknown>, key: string): string | undefined {
|
|
27
|
+
const parts = key.split('.');
|
|
28
|
+
let current: unknown = data;
|
|
29
|
+
for (const part of parts) {
|
|
30
|
+
if (current == null || typeof current !== 'object') return undefined;
|
|
31
|
+
current = (current as Record<string, unknown>)[part];
|
|
32
|
+
}
|
|
33
|
+
return typeof current === 'string' ? current : undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Interpolate parameters into a translated string.
|
|
38
|
+
* Replaces `{{paramName}}` with the corresponding value from params.
|
|
39
|
+
*
|
|
40
|
+
* @param template - Template string with `{{key}}` placeholders
|
|
41
|
+
* @param params - Parameter map
|
|
42
|
+
* @returns Interpolated string
|
|
43
|
+
*/
|
|
44
|
+
function interpolate(template: string, params: Record<string, unknown>): string {
|
|
45
|
+
return template.replace(/\{\{(\w+)\}\}/g, (_match, key: string) => {
|
|
46
|
+
return params[key] != null ? String(params[key]) : `{{${key}}}`;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* File-based I18n adapter implementing II18nService.
|
|
52
|
+
*
|
|
53
|
+
* Loads JSON translation files from a directory on disk.
|
|
54
|
+
* Each file should be named `{locale}.json` and contain a flat or nested
|
|
55
|
+
* key-value map of translations.
|
|
56
|
+
*
|
|
57
|
+
* Supports:
|
|
58
|
+
* - Dot-notation key resolution (e.g. 'objects.account.label')
|
|
59
|
+
* - Parameter interpolation via `{{paramName}}` syntax
|
|
60
|
+
* - Fallback locale for missing translations
|
|
61
|
+
* - Runtime translation loading via loadTranslations()
|
|
62
|
+
*
|
|
63
|
+
* Suitable for server-side rendering, CLI tools, and development environments.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```ts
|
|
67
|
+
* const i18n = new FileI18nAdapter({
|
|
68
|
+
* defaultLocale: 'en',
|
|
69
|
+
* localesDir: './i18n',
|
|
70
|
+
* fallbackLocale: 'en',
|
|
71
|
+
* });
|
|
72
|
+
*
|
|
73
|
+
* i18n.t('objects.account.label', 'zh-CN'); // '客户'
|
|
74
|
+
* i18n.t('greeting', 'en', { name: 'World' }); // 'Hello, World!'
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
export class FileI18nAdapter implements II18nService {
|
|
78
|
+
private readonly translations = new Map<string, Record<string, unknown>>();
|
|
79
|
+
private defaultLocale: string;
|
|
80
|
+
private readonly fallbackLocale: string | undefined;
|
|
81
|
+
|
|
82
|
+
constructor(options: FileI18nAdapterOptions = {}) {
|
|
83
|
+
this.defaultLocale = options.defaultLocale ?? 'en';
|
|
84
|
+
this.fallbackLocale = options.fallbackLocale;
|
|
85
|
+
|
|
86
|
+
if (options.localesDir) {
|
|
87
|
+
this.loadFromDirectory(options.localesDir);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
t(key: string, locale: string, params?: Record<string, unknown>): string {
|
|
92
|
+
// Try requested locale
|
|
93
|
+
let value = this.resolveFromLocale(key, locale);
|
|
94
|
+
|
|
95
|
+
// Try fallback locale
|
|
96
|
+
if (value === undefined && this.fallbackLocale && this.fallbackLocale !== locale) {
|
|
97
|
+
value = this.resolveFromLocale(key, this.fallbackLocale);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Return key if not found
|
|
101
|
+
if (value === undefined) return key;
|
|
102
|
+
|
|
103
|
+
// Interpolate parameters
|
|
104
|
+
if (params && Object.keys(params).length > 0) {
|
|
105
|
+
return interpolate(value, params);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
getTranslations(locale: string): Record<string, unknown> {
|
|
112
|
+
return this.translations.get(locale) ?? {};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
loadTranslations(locale: string, translations: Record<string, unknown>): void {
|
|
116
|
+
const existing = this.translations.get(locale);
|
|
117
|
+
if (existing) {
|
|
118
|
+
// Merge into existing translations
|
|
119
|
+
this.translations.set(locale, { ...existing, ...translations });
|
|
120
|
+
} else {
|
|
121
|
+
this.translations.set(locale, { ...translations });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
getLocales(): string[] {
|
|
126
|
+
return Array.from(this.translations.keys());
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
getDefaultLocale(): string {
|
|
130
|
+
return this.defaultLocale;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
setDefaultLocale(locale: string): void {
|
|
134
|
+
this.defaultLocale = locale;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Load all JSON translation files from a directory.
|
|
139
|
+
* Each file should be named `{locale}.json`.
|
|
140
|
+
*/
|
|
141
|
+
private loadFromDirectory(dir: string): void {
|
|
142
|
+
if (!fs.existsSync(dir)) return;
|
|
143
|
+
|
|
144
|
+
const files = fs.readdirSync(dir);
|
|
145
|
+
for (const file of files) {
|
|
146
|
+
if (!file.endsWith('.json')) continue;
|
|
147
|
+
const locale = file.replace(/\.json$/, '');
|
|
148
|
+
const filePath = path.join(dir, file);
|
|
149
|
+
try {
|
|
150
|
+
const content = fs.readFileSync(filePath, 'utf-8');
|
|
151
|
+
const data = JSON.parse(content) as Record<string, unknown>;
|
|
152
|
+
this.translations.set(locale, data);
|
|
153
|
+
} catch {
|
|
154
|
+
// Skip files that can't be parsed
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
private resolveFromLocale(key: string, locale: string): string | undefined {
|
|
160
|
+
const data = this.translations.get(locale);
|
|
161
|
+
if (!data) return undefined;
|
|
162
|
+
return resolveKey(data, key);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import type { Plugin, PluginContext } from '@objectstack/core';
|
|
4
|
+
import { FileI18nAdapter } from './file-i18n-adapter.js';
|
|
5
|
+
import type { FileI18nAdapterOptions } from './file-i18n-adapter.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Configuration options for the I18nServicePlugin.
|
|
9
|
+
*/
|
|
10
|
+
export interface I18nServicePluginOptions {
|
|
11
|
+
/** Default locale (default: 'en') */
|
|
12
|
+
defaultLocale?: string;
|
|
13
|
+
/** Directory containing locale JSON files */
|
|
14
|
+
localesDir?: string;
|
|
15
|
+
/** Fallback locale for missing translations */
|
|
16
|
+
fallbackLocale?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* I18nServicePlugin — Production II18nService implementation.
|
|
21
|
+
*
|
|
22
|
+
* Registers an i18n service with the kernel during the init phase.
|
|
23
|
+
* Uses file-based locale loading with JSON files.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { ObjectKernel } from '@objectstack/core';
|
|
28
|
+
* import { I18nServicePlugin } from '@objectstack/service-i18n';
|
|
29
|
+
*
|
|
30
|
+
* const kernel = new ObjectKernel();
|
|
31
|
+
* kernel.use(new I18nServicePlugin({
|
|
32
|
+
* defaultLocale: 'en',
|
|
33
|
+
* localesDir: './i18n',
|
|
34
|
+
* fallbackLocale: 'en',
|
|
35
|
+
* }));
|
|
36
|
+
* await kernel.bootstrap();
|
|
37
|
+
*
|
|
38
|
+
* const i18n = kernel.getService('i18n');
|
|
39
|
+
* i18n.t('objects.account.label', 'en'); // 'Account'
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export class I18nServicePlugin implements Plugin {
|
|
43
|
+
name = 'com.objectstack.service.i18n';
|
|
44
|
+
version = '1.0.0';
|
|
45
|
+
type = 'standard';
|
|
46
|
+
|
|
47
|
+
private readonly options: I18nServicePluginOptions;
|
|
48
|
+
|
|
49
|
+
constructor(options: I18nServicePluginOptions = {}) {
|
|
50
|
+
this.options = options;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async init(ctx: PluginContext): Promise<void> {
|
|
54
|
+
const adapterOptions: FileI18nAdapterOptions = {
|
|
55
|
+
defaultLocale: this.options.defaultLocale,
|
|
56
|
+
localesDir: this.options.localesDir,
|
|
57
|
+
fallbackLocale: this.options.fallbackLocale,
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const i18n = new FileI18nAdapter(adapterOptions);
|
|
61
|
+
ctx.registerService('i18n', i18n);
|
|
62
|
+
ctx.logger.info(
|
|
63
|
+
`I18nServicePlugin: registered file-based i18n adapter (default: ${i18n.getDefaultLocale()})`,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
export { I18nServicePlugin } from './i18n-service-plugin.js';
|
|
4
|
+
export type { I18nServicePluginOptions } from './i18n-service-plugin.js';
|
|
5
|
+
export { FileI18nAdapter } from './file-i18n-adapter.js';
|
|
6
|
+
export type { FileI18nAdapterOptions } from './file-i18n-adapter.js';
|