@abinnovision/nestjs-i18n 0.0.0-stage → 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 (57) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +127 -2
  3. package/dist/exceptions/default-messages.cjs +12 -0
  4. package/dist/exceptions/default-messages.d.cts +13 -0
  5. package/dist/exceptions/default-messages.d.mts +13 -0
  6. package/dist/exceptions/default-messages.mjs +13 -0
  7. package/dist/exceptions/exception-messages.d.cts +20 -0
  8. package/dist/exceptions/exception-messages.d.mts +20 -0
  9. package/dist/exceptions/i18n-exception-localizer.cjs +75 -0
  10. package/dist/exceptions/i18n-exception-localizer.d.cts +27 -0
  11. package/dist/exceptions/i18n-exception-localizer.d.mts +27 -0
  12. package/dist/exceptions/i18n-exception-localizer.mjs +70 -0
  13. package/dist/exceptions.cjs +10 -0
  14. package/dist/exceptions.d.cts +4 -0
  15. package/dist/exceptions.d.mts +4 -0
  16. package/dist/exceptions.mjs +3 -0
  17. package/dist/i18n.context.cjs +26 -0
  18. package/dist/i18n.context.d.cts +21 -0
  19. package/dist/i18n.context.d.mts +21 -0
  20. package/dist/i18n.context.mjs +21 -0
  21. package/dist/i18n.middleware.cjs +39 -0
  22. package/dist/i18n.middleware.mjs +34 -0
  23. package/dist/i18n.module-config.cjs +4 -0
  24. package/dist/i18n.module-config.d.cts +42 -0
  25. package/dist/i18n.module-config.d.mts +42 -0
  26. package/dist/i18n.module-config.mjs +4 -0
  27. package/dist/i18n.module.cjs +54 -0
  28. package/dist/i18n.module.d.cts +12 -0
  29. package/dist/i18n.module.d.mts +12 -0
  30. package/dist/i18n.module.mjs +49 -0
  31. package/dist/i18n.registry.cjs +8 -0
  32. package/dist/i18n.registry.d.cts +53 -0
  33. package/dist/i18n.registry.d.mts +53 -0
  34. package/dist/i18n.registry.mjs +8 -0
  35. package/dist/i18n.service.cjs +107 -0
  36. package/dist/i18n.service.d.cts +52 -0
  37. package/dist/i18n.service.d.mts +52 -0
  38. package/dist/i18n.service.mjs +102 -0
  39. package/dist/index.cjs +25 -0
  40. package/dist/index.d.cts +7 -0
  41. package/dist/index.d.mts +7 -0
  42. package/dist/index.mjs +7 -0
  43. package/dist/internal/formatter.cjs +30 -0
  44. package/dist/internal/formatter.mjs +29 -0
  45. package/dist/internal/icu-params.d.cts +35 -0
  46. package/dist/internal/icu-params.d.mts +35 -0
  47. package/dist/internal/negotiate.cjs +18 -0
  48. package/dist/internal/negotiate.mjs +18 -0
  49. package/dist/resolvers.cjs +38 -0
  50. package/dist/resolvers.d.cts +19 -0
  51. package/dist/resolvers.d.mts +19 -0
  52. package/dist/resolvers.mjs +36 -0
  53. package/dist/testing.cjs +59 -0
  54. package/dist/testing.d.cts +21 -0
  55. package/dist/testing.d.mts +21 -0
  56. package/dist/testing.mjs +59 -0
  57. package/package.json +114 -4
package/LICENSE ADDED
@@ -0,0 +1,201 @@
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 must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ # @abinnovision/nestjs-i18n
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@abinnovision/nestjs-i18n?style=flat-square)](https://www.npmjs.com/package/@abinnovision/nestjs-i18n)
4
+
5
+ Type-safe backend i18n for NestJS. Messages use [ICU MessageFormat](https://formatjs.github.io/docs/core-concepts/icu-syntax) and are formatted with [`intl-messageformat`](https://formatjs.github.io/docs/intl-messageformat). Keys and parameters are inferred from the default-locale catalog.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ yarn add @abinnovision/nestjs-i18n
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ### 1. Define the catalogs
16
+
17
+ ```typescript
18
+ // i18n/en.ts
19
+ import { defineCatalog } from "@abinnovision/nestjs-i18n";
20
+
21
+ export const en = defineCatalog({
22
+ greeting: "Hello {name}",
23
+ items: "{count, plural, one {# item} other {# items}}",
24
+ });
25
+ ```
26
+
27
+ Other locales can be plain objects or JSON files with the same keys.
28
+
29
+ ### 2. Register the catalog type
30
+
31
+ ```typescript
32
+ declare module "@abinnovision/nestjs-i18n" {
33
+ interface I18nRegistry {
34
+ catalog: typeof en;
35
+ locales: "en" | "de";
36
+ }
37
+ }
38
+ ```
39
+
40
+ ### 3. Register the module
41
+
42
+ ```typescript
43
+ import {
44
+ I18nModule,
45
+ acceptLanguage,
46
+ fromRequest,
47
+ queryParam,
48
+ } from "@abinnovision/nestjs-i18n";
49
+
50
+ @Module({
51
+ imports: [
52
+ I18nModule.forRoot({
53
+ defaultLocale: "en",
54
+ catalogs: { en, de },
55
+ resolvers: [
56
+ queryParam("lang"),
57
+ fromRequest((req) => req.user?.locale),
58
+ acceptLanguage(),
59
+ ],
60
+ }),
61
+ ],
62
+ })
63
+ export class AppModule {}
64
+ ```
65
+
66
+ `forRootAsync({ inject, useFactory })` is available as well. The module throws at startup when `defaultLocale` has no catalog.
67
+
68
+ ### 4. Translate
69
+
70
+ ```typescript
71
+ @Injectable()
72
+ export class GreetingService {
73
+ public constructor(private readonly i18n: I18nService) {}
74
+
75
+ public greet(name: string): string {
76
+ return this.i18n.t("greeting", { name });
77
+ }
78
+ }
79
+ ```
80
+
81
+ The locale is taken from `opts.locale`, then from `i18n.run(locale, fn)`, then resolved from the current request, then `defaultLocale`. An explicit locale is matched against the catalogs like a request locale (`de-AT` uses `de`). It is resolved on every call, so a `req.user` set by a guard is picked up. A key missing in a locale falls back to the default locale.
82
+
83
+ Set `middleware: false` to disable the request context middleware. Then only an explicit `locale` and `run()` apply.
84
+
85
+ ## Localized exceptions
86
+
87
+ With `@abinnovision/nestjs-exceptions`, the `./exceptions` subpath localizes the `detail` of error responses with the `exceptions.<CODE>` messages. The exception `meta` is used as message parameters. Entity-focused exceptions also get an `entity` parameter from the `entities.<name>` message, or the raw entity name.
88
+
89
+ ```typescript
90
+ import {
91
+ ExceptionLocalizer,
92
+ GenericExceptionFilter,
93
+ } from "@abinnovision/nestjs-exceptions";
94
+ import {
95
+ I18nExceptionLocalizer,
96
+ defaultExceptionMessages,
97
+ } from "@abinnovision/nestjs-i18n/exceptions";
98
+
99
+ import type { ExceptionMessages } from "@abinnovision/nestjs-i18n/exceptions";
100
+
101
+ export const en = defineCatalog({
102
+ ...defaultExceptionMessages,
103
+ "exceptions.USER__EMAIL_TAKEN": "Email ''{email}'' is already taken",
104
+ "entities.user": "User",
105
+ }) satisfies ExceptionMessages<typeof EmailTakenException>;
106
+
107
+ @Module({
108
+ providers: [
109
+ { provide: ExceptionLocalizer, useClass: I18nExceptionLocalizer },
110
+ { provide: APP_FILTER, useClass: GenericExceptionFilter },
111
+ ],
112
+ })
113
+ export class AppModule {}
114
+ ```
115
+
116
+ Codes without a message keep the English `details`.
117
+
118
+ ## Testing
119
+
120
+ ```typescript
121
+ import { verifyCatalogs } from "@abinnovision/nestjs-i18n";
122
+
123
+ it("has complete catalogs", () => {
124
+ expect(verifyCatalogs({ en, de }, "en")).toEqual([]);
125
+ });
126
+ ```
127
+
128
+ `verifyCatalogs` reports missing keys, extra keys, messages that fail to parse, and arguments that the default-locale message does not have (for example a `{nmae}` typo).
@@ -0,0 +1,12 @@
1
+ //#region src/exceptions/default-messages.ts
2
+ /**
3
+ * English messages for the built-in exception codes. Spread them into the
4
+ * default-locale catalog.
5
+ */ const defaultExceptionMessages = require("../i18n.registry.cjs").defineCatalog({
6
+ "exceptions.COMMON__NOT_FOUND": "{entity} with ID ''{entityId}'' not found",
7
+ "exceptions.COMMON__MUTATION_FAILED": "Failed to {mutationType, select, create {create} update {update} other {delete}} {entity} with ID ''{entityId}''",
8
+ "exceptions.DEFAULT__INTERNAL_SERVER_ERROR": "An internal server error occurred",
9
+ "exceptions.DEFAULT__MULTIPLE_ERRORS": "Multiple errors occurred"
10
+ });
11
+ //#endregion
12
+ exports.defaultExceptionMessages = defaultExceptionMessages;
@@ -0,0 +1,13 @@
1
+ //#region src/exceptions/default-messages.d.ts
2
+ /**
3
+ * English messages for the built-in exception codes. Spread them into the
4
+ * default-locale catalog.
5
+ */
6
+ declare const defaultExceptionMessages: {
7
+ readonly "exceptions.COMMON__NOT_FOUND": "{entity} with ID ''{entityId}'' not found";
8
+ readonly "exceptions.COMMON__MUTATION_FAILED": "Failed to {mutationType, select, create {create} update {update} other {delete}} {entity} with ID ''{entityId}''";
9
+ readonly "exceptions.DEFAULT__INTERNAL_SERVER_ERROR": "An internal server error occurred";
10
+ readonly "exceptions.DEFAULT__MULTIPLE_ERRORS": "Multiple errors occurred";
11
+ };
12
+ //#endregion
13
+ export { defaultExceptionMessages };
@@ -0,0 +1,13 @@
1
+ //#region src/exceptions/default-messages.d.ts
2
+ /**
3
+ * English messages for the built-in exception codes. Spread them into the
4
+ * default-locale catalog.
5
+ */
6
+ declare const defaultExceptionMessages: {
7
+ readonly "exceptions.COMMON__NOT_FOUND": "{entity} with ID ''{entityId}'' not found";
8
+ readonly "exceptions.COMMON__MUTATION_FAILED": "Failed to {mutationType, select, create {create} update {update} other {delete}} {entity} with ID ''{entityId}''";
9
+ readonly "exceptions.DEFAULT__INTERNAL_SERVER_ERROR": "An internal server error occurred";
10
+ readonly "exceptions.DEFAULT__MULTIPLE_ERRORS": "Multiple errors occurred";
11
+ };
12
+ //#endregion
13
+ export { defaultExceptionMessages };
@@ -0,0 +1,13 @@
1
+ import { defineCatalog } from "../i18n.registry.mjs";
2
+ //#region src/exceptions/default-messages.ts
3
+ /**
4
+ * English messages for the built-in exception codes. Spread them into the
5
+ * default-locale catalog.
6
+ */ const defaultExceptionMessages = defineCatalog({
7
+ "exceptions.COMMON__NOT_FOUND": "{entity} with ID ''{entityId}'' not found",
8
+ "exceptions.COMMON__MUTATION_FAILED": "Failed to {mutationType, select, create {create} update {update} other {delete}} {entity} with ID ''{entityId}''",
9
+ "exceptions.DEFAULT__INTERNAL_SERVER_ERROR": "An internal server error occurred",
10
+ "exceptions.DEFAULT__MULTIPLE_ERRORS": "Multiple errors occurred"
11
+ });
12
+ //#endregion
13
+ export { defaultExceptionMessages };
@@ -0,0 +1,20 @@
1
+ import { AppExceptionClass, ExceptionCode } from "@abinnovision/nestjs-exceptions";
2
+
3
+ //#region src/exceptions/exception-messages.d.ts
4
+ /**
5
+ * Requires an `exceptions.<CODE>` message for each listed exception class.
6
+ *
7
+ * Apply `satisfies` to the `defineCatalog()` result, not to its argument,
8
+ * so the messages keep their literal types. Other keys are allowed.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const en = defineCatalog({
13
+ * ...defaultExceptionMessages,
14
+ * "exceptions.USER__EMAIL_TAKEN": "Email ''{email}'' is already taken",
15
+ * }) satisfies ExceptionMessages<typeof EmailTakenException>;
16
+ * ```
17
+ */
18
+ type ExceptionMessages<E extends AppExceptionClass> = { [K in `exceptions.${ExceptionCode<E>}`]: string };
19
+ //#endregion
20
+ export { ExceptionMessages };
@@ -0,0 +1,20 @@
1
+ import { AppExceptionClass, ExceptionCode } from "@abinnovision/nestjs-exceptions";
2
+
3
+ //#region src/exceptions/exception-messages.d.ts
4
+ /**
5
+ * Requires an `exceptions.<CODE>` message for each listed exception class.
6
+ *
7
+ * Apply `satisfies` to the `defineCatalog()` result, not to its argument,
8
+ * so the messages keep their literal types. Other keys are allowed.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const en = defineCatalog({
13
+ * ...defaultExceptionMessages,
14
+ * "exceptions.USER__EMAIL_TAKEN": "Email ''{email}'' is already taken",
15
+ * }) satisfies ExceptionMessages<typeof EmailTakenException>;
16
+ * ```
17
+ */
18
+ type ExceptionMessages<E extends AppExceptionClass> = { [K in `exceptions.${ExceptionCode<E>}`]: string };
19
+ //#endregion
20
+ export { ExceptionMessages };
@@ -0,0 +1,75 @@
1
+ const require_i18n_module_config = require("../i18n.module-config.cjs");
2
+ const require_i18n_service = require("../i18n.service.cjs");
3
+ let _nestjs_common = require("@nestjs/common");
4
+ let _abinnovision_nestjs_exceptions = require("@abinnovision/nestjs-exceptions");
5
+ let _abinnovision_nestjs_exceptions_entity = require("@abinnovision/nestjs-exceptions/entity");
6
+ //#region src/exceptions/i18n-exception-localizer.ts
7
+ function _ts_decorate(decorators, target, key, desc) {
8
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
9
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
10
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
11
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
12
+ }
13
+ function _ts_metadata(metadataKey, metadataValue) {
14
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
15
+ }
16
+ function _ts_param(paramIndex, decorator) {
17
+ return function(target, key) {
18
+ decorator(target, key, paramIndex);
19
+ };
20
+ }
21
+ var I18nExceptionLocalizer = class I18nExceptionLocalizer extends _abinnovision_nestjs_exceptions.ExceptionLocalizer {
22
+ i18n;
23
+ config;
24
+ logger = new _nestjs_common.Logger(I18nExceptionLocalizer.name);
25
+ constructor(i18n, config) {
26
+ super(), this.i18n = i18n, this.config = config;
27
+ }
28
+ localize(error, host) {
29
+ try {
30
+ const key = `exceptions.${error.code}`;
31
+ if (!this.hasMessage(key)) {
32
+ this.logger.debug(`No message for exception code '${error.code}'`);
33
+ return;
34
+ }
35
+ const request = this.requestOf(host);
36
+ const locale = request ? this.i18n.resolveLocale(request) : this.i18n.locale;
37
+ const t = this.i18n.t.bind(this.i18n);
38
+ const params = { ...typeof error.meta === "object" ? error.meta : {} };
39
+ if (error.exception instanceof _abinnovision_nestjs_exceptions_entity.EntityFocusedAppException) {
40
+ const entityKey = `entities.${error.exception.entity}`;
41
+ params["entity"] = this.hasMessage(entityKey) ? t(entityKey, {}, { locale }) : error.exception.entity;
42
+ }
43
+ return t(key, params, { locale });
44
+ } catch (localizeError) {
45
+ this.logger.warn(localizeError, "Failed to localize exception");
46
+ return;
47
+ }
48
+ }
49
+ hasMessage(key) {
50
+ const catalogs = this.config.catalogs;
51
+ return Object.hasOwn(catalogs[this.config.defaultLocale] ?? {}, key);
52
+ }
53
+ requestOf(host) {
54
+ const type = host.getType();
55
+ if (type === "http") return host.switchToHttp().getRequest();
56
+ if (type === "graphql") {
57
+ const context = host.getArgByIndex(2);
58
+ return context?.req ?? context?.request;
59
+ }
60
+ }
61
+ };
62
+ I18nExceptionLocalizer = _ts_decorate([
63
+ (0, _nestjs_common.Injectable)(),
64
+ _ts_param(0, (0, _nestjs_common.Inject)(require_i18n_service.I18nService)),
65
+ _ts_param(1, (0, _nestjs_common.Inject)(require_i18n_module_config.i18nModuleConfigToken)),
66
+ _ts_metadata("design:type", Function),
67
+ _ts_metadata("design:paramtypes", [typeof require_i18n_service.I18nService === "undefined" ? Object : require_i18n_service.I18nService, typeof I18nModuleConfig === "undefined" ? Object : I18nModuleConfig])
68
+ ], I18nExceptionLocalizer);
69
+ //#endregion
70
+ Object.defineProperty(exports, "I18nExceptionLocalizer", {
71
+ enumerable: true,
72
+ get: function() {
73
+ return I18nExceptionLocalizer;
74
+ }
75
+ });
@@ -0,0 +1,27 @@
1
+ import { I18nModuleConfig } from "../i18n.module-config.cjs";
2
+ import { I18nService } from "../i18n.service.cjs";
3
+ import { ExceptionLocalizer, LocalizableError } from "@abinnovision/nestjs-exceptions";
4
+ import { ArgumentsHost } from "@nestjs/common";
5
+
6
+ //#region src/exceptions/i18n-exception-localizer.d.ts
7
+ /**
8
+ * Localizes exception details with the `exceptions.<CODE>` messages.
9
+ *
10
+ * The exception `meta` is used as message parameters. Entity-focused
11
+ * exceptions also get an `entity` parameter, translated with the
12
+ * `entities.<name>` message or the raw entity name.
13
+ *
14
+ * Never throws: a missing message or a formatting error keeps the original
15
+ * detail.
16
+ */
17
+ declare class I18nExceptionLocalizer extends ExceptionLocalizer {
18
+ private readonly i18n;
19
+ private readonly config;
20
+ private readonly logger;
21
+ constructor(i18n: I18nService, config: I18nModuleConfig);
22
+ localize(error: LocalizableError, host: ArgumentsHost): string | undefined;
23
+ private hasMessage;
24
+ private requestOf;
25
+ }
26
+ //#endregion
27
+ export { I18nExceptionLocalizer };
@@ -0,0 +1,27 @@
1
+ import { I18nModuleConfig } from "../i18n.module-config.mjs";
2
+ import { I18nService } from "../i18n.service.mjs";
3
+ import { ArgumentsHost } from "@nestjs/common";
4
+ import { ExceptionLocalizer, LocalizableError } from "@abinnovision/nestjs-exceptions";
5
+
6
+ //#region src/exceptions/i18n-exception-localizer.d.ts
7
+ /**
8
+ * Localizes exception details with the `exceptions.<CODE>` messages.
9
+ *
10
+ * The exception `meta` is used as message parameters. Entity-focused
11
+ * exceptions also get an `entity` parameter, translated with the
12
+ * `entities.<name>` message or the raw entity name.
13
+ *
14
+ * Never throws: a missing message or a formatting error keeps the original
15
+ * detail.
16
+ */
17
+ declare class I18nExceptionLocalizer extends ExceptionLocalizer {
18
+ private readonly i18n;
19
+ private readonly config;
20
+ private readonly logger;
21
+ constructor(i18n: I18nService, config: I18nModuleConfig);
22
+ localize(error: LocalizableError, host: ArgumentsHost): string | undefined;
23
+ private hasMessage;
24
+ private requestOf;
25
+ }
26
+ //#endregion
27
+ export { I18nExceptionLocalizer };
@@ -0,0 +1,70 @@
1
+ import { i18nModuleConfigToken } from "../i18n.module-config.mjs";
2
+ import { I18nService } from "../i18n.service.mjs";
3
+ import { Inject, Injectable, Logger } from "@nestjs/common";
4
+ import { ExceptionLocalizer } from "@abinnovision/nestjs-exceptions";
5
+ import { EntityFocusedAppException } from "@abinnovision/nestjs-exceptions/entity";
6
+ //#region src/exceptions/i18n-exception-localizer.ts
7
+ function _ts_decorate(decorators, target, key, desc) {
8
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
9
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
10
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
11
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
12
+ }
13
+ function _ts_metadata(metadataKey, metadataValue) {
14
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
15
+ }
16
+ function _ts_param(paramIndex, decorator) {
17
+ return function(target, key) {
18
+ decorator(target, key, paramIndex);
19
+ };
20
+ }
21
+ var I18nExceptionLocalizer = class I18nExceptionLocalizer extends ExceptionLocalizer {
22
+ i18n;
23
+ config;
24
+ logger = new Logger(I18nExceptionLocalizer.name);
25
+ constructor(i18n, config) {
26
+ super(), this.i18n = i18n, this.config = config;
27
+ }
28
+ localize(error, host) {
29
+ try {
30
+ const key = `exceptions.${error.code}`;
31
+ if (!this.hasMessage(key)) {
32
+ this.logger.debug(`No message for exception code '${error.code}'`);
33
+ return;
34
+ }
35
+ const request = this.requestOf(host);
36
+ const locale = request ? this.i18n.resolveLocale(request) : this.i18n.locale;
37
+ const t = this.i18n.t.bind(this.i18n);
38
+ const params = { ...typeof error.meta === "object" ? error.meta : {} };
39
+ if (error.exception instanceof EntityFocusedAppException) {
40
+ const entityKey = `entities.${error.exception.entity}`;
41
+ params["entity"] = this.hasMessage(entityKey) ? t(entityKey, {}, { locale }) : error.exception.entity;
42
+ }
43
+ return t(key, params, { locale });
44
+ } catch (localizeError) {
45
+ this.logger.warn(localizeError, "Failed to localize exception");
46
+ return;
47
+ }
48
+ }
49
+ hasMessage(key) {
50
+ const catalogs = this.config.catalogs;
51
+ return Object.hasOwn(catalogs[this.config.defaultLocale] ?? {}, key);
52
+ }
53
+ requestOf(host) {
54
+ const type = host.getType();
55
+ if (type === "http") return host.switchToHttp().getRequest();
56
+ if (type === "graphql") {
57
+ const context = host.getArgByIndex(2);
58
+ return context?.req ?? context?.request;
59
+ }
60
+ }
61
+ };
62
+ I18nExceptionLocalizer = _ts_decorate([
63
+ Injectable(),
64
+ _ts_param(0, Inject(I18nService)),
65
+ _ts_param(1, Inject(i18nModuleConfigToken)),
66
+ _ts_metadata("design:type", Function),
67
+ _ts_metadata("design:paramtypes", [typeof I18nService === "undefined" ? Object : I18nService, typeof I18nModuleConfig === "undefined" ? Object : I18nModuleConfig])
68
+ ], I18nExceptionLocalizer);
69
+ //#endregion
70
+ export { I18nExceptionLocalizer };
@@ -0,0 +1,10 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_i18n_exception_localizer = require("./exceptions/i18n-exception-localizer.cjs");
3
+ const require_default_messages = require("./exceptions/default-messages.cjs");
4
+ Object.defineProperty(exports, "I18nExceptionLocalizer", {
5
+ enumerable: true,
6
+ get: function() {
7
+ return require_i18n_exception_localizer.I18nExceptionLocalizer;
8
+ }
9
+ });
10
+ exports.defaultExceptionMessages = require_default_messages.defaultExceptionMessages;
@@ -0,0 +1,4 @@
1
+ import { I18nExceptionLocalizer } from "./exceptions/i18n-exception-localizer.cjs";
2
+ import { defaultExceptionMessages } from "./exceptions/default-messages.cjs";
3
+ import { ExceptionMessages } from "./exceptions/exception-messages.cjs";
4
+ export { ExceptionMessages, I18nExceptionLocalizer, defaultExceptionMessages };
@@ -0,0 +1,4 @@
1
+ import { I18nExceptionLocalizer } from "./exceptions/i18n-exception-localizer.mjs";
2
+ import { defaultExceptionMessages } from "./exceptions/default-messages.mjs";
3
+ import { ExceptionMessages } from "./exceptions/exception-messages.mjs";
4
+ export { ExceptionMessages, I18nExceptionLocalizer, defaultExceptionMessages };
@@ -0,0 +1,3 @@
1
+ import { I18nExceptionLocalizer } from "./exceptions/i18n-exception-localizer.mjs";
2
+ import { defaultExceptionMessages } from "./exceptions/default-messages.mjs";
3
+ export { I18nExceptionLocalizer, defaultExceptionMessages };