@wolfstar/i18next-type-generator 3.1.0-next-20260830180323

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE 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 2022 Wolfstar Project
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 ADDED
@@ -0,0 +1,72 @@
1
+ # `@wolfstar/i18next-type-generator`
2
+
3
+ A fast and modern type augmentation generator for the [`@wolfstar/i18next-backend`](https://www.npmjs.com/package/@wolfstar/i18next-backend) filesystem-based [`i18next`](https://www.npmjs.com/package/i18next) backend for Node.js.
4
+
5
+ ## Usage
6
+
7
+ ```bash
8
+ $ i18next-type-generator [options] [source] [destination]
9
+
10
+ # Arguments:
11
+ # source The directory to generate types from (default: "./src/locales/en-US/")
12
+ # destination The directory to generate types to (default: "./src/@types/i18next.d.ts")
13
+ #
14
+ # Options:
15
+ # -V, --version output the version number
16
+ # -v, --verbose Verbose output
17
+ # -i, --indentation <value> Indentation for generated output (number of spaces or "tabs", default: tabs)
18
+ # --no-prettier Disable prettier
19
+ # -h, --help display help for command
20
+ ```
21
+
22
+ This CLI tool generates a `.d.ts` file with the following structure:
23
+
24
+ ```typescript
25
+ // This file is automatically generated, do not edit it.
26
+ /* eslint-disable */
27
+ /* oxlint-disable */
28
+ // oxfmt-ignore
29
+ // prettier-ignore
30
+ import 'i18next';
31
+
32
+ // oxfmt-ignore
33
+ // prettier-ignore
34
+ declare module 'i18next' {
35
+ interface CustomTypeOptions {
36
+ resources: {
37
+ 'commands/choice': {
38
+ name: 'choice';
39
+ description: 'Get a random value from a set of choices';
40
+ // ...
41
+ };
42
+ // ...
43
+ } & CustomResources;
44
+ }
45
+
46
+ interface CustomResources {}
47
+ }
48
+ ```
49
+
50
+ The generated `resources` type is intersected with an empty, mergeable `CustomResources` interface. This is the supported extension point: it lets you add resource keys that are not present in your locale JSON (for example keys whose runtime translation is supplied by the consuming application) without redeclaring `CustomTypeOptions.resources`, which would otherwise trigger `TS2717` for consumers that build with `skipLibCheck: false`.
51
+
52
+ The output includes `eslint-disable` / `oxlint-disable` comments to suppress linting, and `oxfmt-ignore` / `prettier-ignore` comments before each top-level statement to prevent formatters from rewriting the generated file. These ignore directives are always emitted; the `--no-oxfmt` and `--no-prettier` flags only affect the internal formatting pass used to produce the resource block, not the emitted ignore comments.
53
+
54
+ The command reads the JSON files inside a directory writes their contents into the `.d.ts` file. This is needed because `typeof import(pathToJSON)` requires the JSON files to be included in `tsconfig.json`, which may be undesirable, and because it types the keys and their inferred types, but does not load the exact values, which breaks i18next's ability to extract arguments from strings.
55
+
56
+ You can control indentation with `-i` / `--indentation` (a space count or `tabs`). `prettier` is also used under the hood to format output before writing to a file; opt out with `--no-prettier` if you want to use a different tool.
57
+
58
+ > **Note**: To add resource keys that are not generated from your locale JSON, merge them into `CustomResources` from a separate declaration file:
59
+ >
60
+ > ```typescript
61
+ > import 'i18next';
62
+ >
63
+ > declare module 'i18next' {
64
+ > interface CustomResources {
65
+ > 'commands/shared': {
66
+ > extraKey: string;
67
+ > };
68
+ > }
69
+ > }
70
+ > ```
71
+ >
72
+ > To add other [`CustomTypeOptions` options](https://www.i18next.com/overview/typescript) (such as `defaultNS`), create a separate file too; TypeScript merges the augmentations.
package/dist/cli.js ADDED
@@ -0,0 +1,196 @@
1
+ #!/usr/bin/env node
2
+ import { defineCommand, runCommand, showUsage } from "citty";
3
+ import { mkdir, opendir, readFile, writeFile } from "node:fs/promises";
4
+ import { gray, green, italic, yellow } from "colorette";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { inspect } from "node:util";
7
+
8
+ //#region src/generate.ts
9
+ const ci = "CI" in process.env && process.env.CI !== "false";
10
+ const FileIcon = ci ? "📄" : "";
11
+ const DirectoryIcon = ci ? "📂" : "";
12
+ const GENERATED_FILE_HEADER = [
13
+ "// This file is automatically generated, do not edit it.",
14
+ "/* eslint-disable */",
15
+ "/* oxlint-disable */"
16
+ ];
17
+ const FORMATTER_IGNORE = ["// oxfmt-ignore", "// prettier-ignore"];
18
+ /**
19
+ * Inject formatter and linter ignore directives into the already-formatted output.
20
+ *
21
+ * The file-level `eslint-disable` / `oxlint-disable` comments suppress all lint rules, while the
22
+ * per-statement `oxfmt-ignore` / `prettier-ignore` comments protect the two top-level statements
23
+ * (the `i18next` import and the `declare module` block), since neither formatter supports a
24
+ * whole-file inline ignore.
25
+ * @param source The formatted generated source.
26
+ */
27
+ function annotateGeneratedFile(source) {
28
+ const ignore = FORMATTER_IGNORE.join("\n");
29
+ const annotated = source.replace(/^(import\s+['"]i18next['"])/m, `${ignore}\n$1`).replace(/^(declare\s+module\s+['"]i18next['"])/m, `${ignore}\n$1`);
30
+ return `${GENERATED_FILE_HEADER.join("\n")}\n${annotated}`;
31
+ }
32
+ /**
33
+ * Recursively walk through the directory and generate the types.
34
+ * @param path The path to walk through.
35
+ * @param namespace The namespace to use.
36
+ */
37
+ async function recurse(lines, path, namespace, options) {
38
+ const indent = options.indentation.repeat(3);
39
+ if (options.verbose) console.log(gray(`Reading directory ${DirectoryIcon} ${green(path)}...`));
40
+ const entries = [];
41
+ for await (const dirent of await opendir(path)) entries.push(dirent);
42
+ entries.sort((a, b) => a.name.localeCompare(b.name));
43
+ for (const dirent of entries) {
44
+ const file = join(path, dirent.name);
45
+ if (dirent.isFile()) {
46
+ if (!dirent.name.endsWith(".json")) continue;
47
+ if (options.verbose) console.log(gray(`Processing ${FileIcon} ${green(file)}...`));
48
+ const name = dirent.name.slice(0, -5);
49
+ const key = JSON.stringify(namespace ? `${namespace}/${name}` : name);
50
+ const data = JSON.stringify(JSON.parse(await readFile(file, "utf8")), void 0, options.indentation);
51
+ lines.push(`${indent}${key}: ${data.replaceAll("\n", `\n${indent}`)};`);
52
+ } else if (dirent.isDirectory()) await recurse(lines, file, namespace ? `${namespace}/${dirent.name}` : dirent.name, options);
53
+ }
54
+ }
55
+ async function formatWithOxfmt(source, destination, options) {
56
+ if (!options.oxfmt) return;
57
+ try {
58
+ if (options.verbose) console.log(gray("Loading oxfmt..."));
59
+ const { format } = await import("oxfmt");
60
+ const { code, errors } = await format(destination, source);
61
+ if (errors.length > 0) throw new Error(errors.map((error) => error.message).join("\n"));
62
+ if (options.verbose) console.log(gray("Formatting with oxfmt."));
63
+ return code;
64
+ } catch (error) {
65
+ const message = error instanceof Error ? error.message : String(error);
66
+ console.warn(yellow(options.verbose ? `Failed to format with oxfmt: ${message}. Continuing with unformatted output.` : "Failed to format with oxfmt; install it as a dependency or use --no-oxfmt. Continuing with unformatted output."));
67
+ }
68
+ }
69
+ async function formatWithPrettier(source, destination, options) {
70
+ if (!options.prettier) return;
71
+ try {
72
+ if (options.verbose) console.log(gray("Loading prettier..."));
73
+ const { resolveConfig, format } = await import("prettier");
74
+ const config = await resolveConfig(destination);
75
+ if (options.verbose) console.log(gray(`Formatting with prettier config: ${inspect(config, { colors: true })}`));
76
+ return await format(source, {
77
+ ...config,
78
+ filepath: destination
79
+ });
80
+ } catch (error) {
81
+ const message = error instanceof Error ? error.message : String(error);
82
+ console.warn(yellow(options.verbose ? `Failed to format with prettier: ${message}. Continuing with unformatted output.` : "Failed to format with prettier; install it as a dependency or use --no-prettier. Continuing with unformatted output."));
83
+ }
84
+ }
85
+ async function formatSource(source, destination, options) {
86
+ return await formatWithOxfmt(source, destination, options) ?? await formatWithPrettier(source, destination, options) ?? source;
87
+ }
88
+ async function generate([source, destination], options) {
89
+ const sourceDirectory = resolve(source);
90
+ const destinationFile = resolve(destination);
91
+ const i1 = options.indentation;
92
+ const i2 = i1.repeat(2);
93
+ if (options.verbose) {
94
+ const lines = [
95
+ `Source: ${DirectoryIcon} ${green(sourceDirectory)}...`,
96
+ `Output: ${FileIcon} ${green(destinationFile)}...`,
97
+ "",
98
+ "Options:",
99
+ ` - Verbose: ${green(options.verbose ? "yes" : "no")}`,
100
+ ` - Indentation: ${green(JSON.stringify(options.indentation))}`
101
+ ];
102
+ console.log(italic(gray(lines.join("\n"))));
103
+ }
104
+ const lines = [
105
+ "import 'i18next';",
106
+ "",
107
+ "declare module 'i18next' {",
108
+ `${i1}interface CustomTypeOptions {`,
109
+ `${i2}resources: {`
110
+ ];
111
+ await recurse(lines, sourceDirectory, "", options);
112
+ lines.push(`${i2}} & CustomResources;`, `${i1}}`, "", `${i1}interface CustomResources {}`, "}", "");
113
+ let generatedSource = lines.join("\n");
114
+ generatedSource = await formatSource(generatedSource, destinationFile, options);
115
+ generatedSource = annotateGeneratedFile(generatedSource);
116
+ await mkdir(dirname(destinationFile), { recursive: true });
117
+ await writeFile(destinationFile, generatedSource, "utf8");
118
+ }
119
+
120
+ //#endregion
121
+ //#region src/cli.ts
122
+ const packageFile = new URL("../package.json", import.meta.url);
123
+ const packageJson = JSON.parse(await readFile(packageFile, "utf-8"));
124
+ const parseIndentation = (value) => {
125
+ if (value === "tabs") return " ";
126
+ const parsed = Number(value);
127
+ if (Number.isNaN(parsed)) throw new Error("The indentation must be a number or \"tabs\"");
128
+ return " ".repeat(parsed);
129
+ };
130
+ const main = defineCommand({
131
+ meta: {
132
+ name: "i18next-type-generator",
133
+ version: packageJson.version,
134
+ description: packageJson.description
135
+ },
136
+ args: {
137
+ source: {
138
+ type: "positional",
139
+ description: "The directory to generate types from",
140
+ default: "./src/locales/en-US/"
141
+ },
142
+ destination: {
143
+ type: "positional",
144
+ description: "The directory to generate types to",
145
+ default: "./src/@types/i18next.d.ts"
146
+ },
147
+ indentation: {
148
+ type: "string",
149
+ description: "The indentation to use",
150
+ alias: "i",
151
+ default: "tabs"
152
+ },
153
+ verbose: {
154
+ type: "boolean",
155
+ description: "Verbose output",
156
+ alias: "v"
157
+ },
158
+ prettier: {
159
+ type: "boolean",
160
+ description: "Format output with prettier",
161
+ default: true
162
+ },
163
+ oxfmt: {
164
+ type: "boolean",
165
+ description: "Format output with oxfmt",
166
+ default: true
167
+ }
168
+ },
169
+ async run({ args }) {
170
+ await generate([args.source, args.destination], {
171
+ verbose: args.verbose,
172
+ oxfmt: args.oxfmt,
173
+ prettier: args.prettier,
174
+ indentation: parseIndentation(args.indentation)
175
+ });
176
+ }
177
+ });
178
+ const rawArgs = process.argv.slice(2);
179
+ if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
180
+ await showUsage(main);
181
+ process.exit(0);
182
+ }
183
+ if (rawArgs.includes("--version")) {
184
+ console.log(packageJson.version);
185
+ process.exit(0);
186
+ }
187
+ try {
188
+ await runCommand(main, { rawArgs });
189
+ } catch (error) {
190
+ console.error(error instanceof Error ? error.message : error);
191
+ process.exit(1);
192
+ }
193
+
194
+ //#endregion
195
+ export { };
196
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/generate.ts","../src/cli.ts"],"sourcesContent":["import { gray, green, italic, yellow } from 'colorette';\nimport { mkdir, opendir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { inspect } from 'node:util';\n\nconst ci = 'CI' in process.env && process.env.CI !== 'false';\n\nconst FileIcon = ci ? '📄' : '\\uE628';\nconst DirectoryIcon = ci ? '📂' : '\\uF413';\n\nconst GENERATED_FILE_HEADER = ['// This file is automatically generated, do not edit it.', '/* eslint-disable */', '/* oxlint-disable */'] as const;\n\nconst FORMATTER_IGNORE = ['// oxfmt-ignore', '// prettier-ignore'] as const;\n\n/**\n * Inject formatter and linter ignore directives into the already-formatted output.\n *\n * The file-level `eslint-disable` / `oxlint-disable` comments suppress all lint rules, while the\n * per-statement `oxfmt-ignore` / `prettier-ignore` comments protect the two top-level statements\n * (the `i18next` import and the `declare module` block), since neither formatter supports a\n * whole-file inline ignore.\n * @param source The formatted generated source.\n */\nexport function annotateGeneratedFile(source: string): string {\n\tconst ignore = FORMATTER_IGNORE.join('\\n');\n\tconst annotated = source\n\t\t.replace(/^(import\\s+['\"]i18next['\"])/m, `${ignore}\\n$1`)\n\t\t.replace(/^(declare\\s+module\\s+['\"]i18next['\"])/m, `${ignore}\\n$1`);\n\n\treturn `${GENERATED_FILE_HEADER.join('\\n')}\\n${annotated}`;\n}\n\n/**\n * Recursively walk through the directory and generate the types.\n * @param path The path to walk through.\n * @param namespace The namespace to use.\n */\nasync function recurse(lines: string[], path: string, namespace: string, options: GenerateOptions) {\n\tconst indent = options.indentation.repeat(3);\n\n\tif (options.verbose) console.log(gray(`Reading directory ${DirectoryIcon} ${green(path)}...`));\n\n\tconst entries = [];\n\tfor await (const dirent of await opendir(path)) {\n\t\tentries.push(dirent);\n\t}\n\tentries.sort((a, b) => a.name.localeCompare(b.name));\n\n\tfor (const dirent of entries) {\n\t\tconst file = join(path, dirent.name);\n\t\tif (dirent.isFile()) {\n\t\t\tif (!dirent.name.endsWith('.json')) continue;\n\t\t\tif (options.verbose) console.log(gray(`Processing ${FileIcon} ${green(file)}...`));\n\n\t\t\tconst name = dirent.name.slice(0, -5);\n\t\t\tconst key = JSON.stringify(namespace ? `${namespace}/${name}` : name);\n\t\t\tconst data = JSON.stringify(JSON.parse(await readFile(file, 'utf8')), undefined, options.indentation);\n\t\t\tlines.push(`${indent}${key}: ${data.replaceAll('\\n', `\\n${indent}`)};`);\n\t\t} else if (dirent.isDirectory()) {\n\t\t\tawait recurse(lines, file, namespace ? `${namespace}/${dirent.name}` : dirent.name, options);\n\t\t}\n\t}\n}\n\nasync function formatWithOxfmt(source: string, destination: string, options: GenerateOptions): Promise<string | undefined> {\n\tif (!options.oxfmt) return;\n\n\ttry {\n\t\tif (options.verbose) console.log(gray('Loading oxfmt...'));\n\n\t\tconst { format } = await import('oxfmt');\n\t\tconst { code, errors } = await format(destination, source);\n\t\tif (errors.length > 0) {\n\t\t\tthrow new Error(errors.map((error) => error.message).join('\\n'));\n\t\t}\n\n\t\tif (options.verbose) console.log(gray('Formatting with oxfmt.'));\n\n\t\treturn code;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.warn(\n\t\t\tyellow(\n\t\t\t\toptions.verbose\n\t\t\t\t\t? `Failed to format with oxfmt: ${message}. Continuing with unformatted output.`\n\t\t\t\t\t: 'Failed to format with oxfmt; install it as a dependency or use --no-oxfmt. Continuing with unformatted output.'\n\t\t\t)\n\t\t);\n\t}\n\n\treturn undefined;\n}\n\nasync function formatWithPrettier(source: string, destination: string, options: GenerateOptions): Promise<string | undefined> {\n\tif (!options.prettier) return;\n\n\ttry {\n\t\tif (options.verbose) console.log(gray('Loading prettier...'));\n\n\t\tconst { resolveConfig, format } = await import('prettier');\n\t\tconst config = await resolveConfig(destination);\n\t\tif (options.verbose) console.log(gray(`Formatting with prettier config: ${inspect(config, { colors: true })}`));\n\n\t\treturn await format(source, { ...config, filepath: destination });\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.warn(\n\t\t\tyellow(\n\t\t\t\toptions.verbose\n\t\t\t\t\t? `Failed to format with prettier: ${message}. Continuing with unformatted output.`\n\t\t\t\t\t: 'Failed to format with prettier; install it as a dependency or use --no-prettier. Continuing with unformatted output.'\n\t\t\t)\n\t\t);\n\t}\n\n\treturn undefined;\n}\n\nasync function formatSource(source: string, destination: string, options: GenerateOptions) {\n\treturn (await formatWithOxfmt(source, destination, options)) ?? (await formatWithPrettier(source, destination, options)) ?? source;\n}\n\nexport async function generate([source, destination]: string[], options: GenerateOptions) {\n\tconst sourceDirectory = resolve(source);\n\tconst destinationFile = resolve(destination);\n\tconst i1 = options.indentation;\n\tconst i2 = i1.repeat(2);\n\n\tif (options.verbose) {\n\t\tconst lines = [\n\t\t\t`Source: ${DirectoryIcon} ${green(sourceDirectory)}...`,\n\t\t\t`Output: ${FileIcon} ${green(destinationFile)}...`,\n\t\t\t'',\n\t\t\t'Options:',\n\t\t\t` - Verbose: ${green(options.verbose ? 'yes' : 'no')}`,\n\t\t\t` - Indentation: ${green(JSON.stringify(options.indentation))}`\n\t\t];\n\t\tconsole.log(italic(gray(lines.join('\\n'))));\n\t}\n\n\tconst lines = [\"import 'i18next';\", '', \"declare module 'i18next' {\", `${i1}interface CustomTypeOptions {`, `${i2}resources: {`];\n\n\tawait recurse(lines, sourceDirectory, '', options);\n\t// Intersecting with the mergeable `CustomResources` interface lets consumers add extra keys (e.g. keys\n\t// whose runtime data is provided externally) from their own declaration file without redeclaring\n\t// `resources`, which would otherwise trigger TS2717 (conflicting property declarations).\n\tlines.push(`${i2}} & CustomResources;`, `${i1}}`, '', `${i1}interface CustomResources {}`, '}', '');\n\n\tlet generatedSource = lines.join('\\n');\n\tgeneratedSource = await formatSource(generatedSource, destinationFile, options);\n\tgeneratedSource = annotateGeneratedFile(generatedSource);\n\n\tawait mkdir(dirname(destinationFile), { recursive: true });\n\tawait writeFile(destinationFile, generatedSource, 'utf8');\n}\n\ninterface GenerateOptions {\n\tverbose: boolean;\n\toxfmt: boolean;\n\tprettier: boolean;\n\tindentation: string;\n}\n","#!/usr/bin/env node\n\nimport { defineCommand, runCommand, showUsage } from 'citty';\nimport { readFile } from 'node:fs/promises';\nimport { generate } from './generate.js';\n\nconst packageFile = new URL('../package.json', import.meta.url);\nconst packageJson = JSON.parse(await readFile(packageFile, 'utf-8'));\n\nconst parseIndentation = (value: string): string => {\n\tif (value === 'tabs') return '\\t';\n\n\tconst parsed = Number(value);\n\tif (Number.isNaN(parsed)) throw new Error('The indentation must be a number or \"tabs\"');\n\treturn ' '.repeat(parsed);\n};\n\nconst main = defineCommand({\n\tmeta: {\n\t\tname: 'i18next-type-generator',\n\t\tversion: packageJson.version,\n\t\tdescription: packageJson.description\n\t},\n\targs: {\n\t\tsource: {\n\t\t\ttype: 'positional',\n\t\t\tdescription: 'The directory to generate types from',\n\t\t\tdefault: './src/locales/en-US/'\n\t\t},\n\t\tdestination: {\n\t\t\ttype: 'positional',\n\t\t\tdescription: 'The directory to generate types to',\n\t\t\tdefault: './src/@types/i18next.d.ts'\n\t\t},\n\t\tindentation: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'The indentation to use',\n\t\t\talias: 'i',\n\t\t\tdefault: 'tabs'\n\t\t},\n\t\tverbose: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Verbose output',\n\t\t\talias: 'v'\n\t\t},\n\t\tprettier: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Format output with prettier',\n\t\t\tdefault: true\n\t\t},\n\t\toxfmt: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Format output with oxfmt',\n\t\t\tdefault: true\n\t\t}\n\t},\n\tasync run({ args }) {\n\t\tawait generate([args.source, args.destination], {\n\t\t\tverbose: args.verbose,\n\t\t\toxfmt: args.oxfmt,\n\t\t\tprettier: args.prettier,\n\t\t\tindentation: parseIndentation(args.indentation)\n\t\t});\n\t}\n});\n\nconst rawArgs = process.argv.slice(2);\n\nif (rawArgs.includes('--help') || rawArgs.includes('-h')) {\n\tawait showUsage(main);\n\tprocess.exit(0);\n}\n\nif (rawArgs.includes('--version')) {\n\tconsole.log(packageJson.version);\n\tprocess.exit(0);\n}\n\ntry {\n\tawait runCommand(main, { rawArgs });\n} catch (error) {\n\tconsole.error(error instanceof Error ? error.message : error);\n\tprocess.exit(1);\n}\n"],"mappings":";;;;;;;;AAKA,MAAM,KAAK,QAAQ,QAAQ,OAAO,QAAQ,IAAI,OAAO;AAErD,MAAM,WAAW,KAAK,OAAO;AAC7B,MAAM,gBAAgB,KAAK,OAAO;AAElC,MAAM,wBAAwB;CAAC;CAA4D;CAAwB;AAAsB;AAEzI,MAAM,mBAAmB,CAAC,mBAAmB,oBAAoB;;;;;;;;;;AAWjE,SAAgB,sBAAsB,QAAwB;CAC7D,MAAM,SAAS,iBAAiB,KAAK,IAAI;CACzC,MAAM,YAAY,OAChB,QAAQ,gCAAgC,GAAG,OAAO,KAAK,CAAC,CACxD,QAAQ,0CAA0C,GAAG,OAAO,KAAK;CAEnE,OAAO,GAAG,sBAAsB,KAAK,IAAI,EAAE,IAAI;AAChD;;;;;;AAOA,eAAe,QAAQ,OAAiB,MAAc,WAAmB,SAA0B;CAClG,MAAM,SAAS,QAAQ,YAAY,OA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N,aAAa;GACb,OAAO;GACP,SAAS;EACV;EACA,SAAS;GACR,MAAM;GACN,aAAa;GACb,OAAO;EACR;EACA,UAAU;GACT,MAAM;GACN,aAAa;GACb,SAAS;EACV;EACA,OAAO;GACN,MAAM;GACN,aAAa;GACb,SAAS;EACV;CACD;CACA,MAAM,IAAI,EAAE,QAAQ;EACnB,MAAM,SAAS,CAAC,KAAK,QAAQ,KAAK,WAAW,GAAG;GAC/C,SAAS,KAAK;GACd,OAAO,KAAK;GACZ,UAAU,KAAK;GACf,aAAa,iBAAiB,KAAK,WAAW;EAC/C,CAAC;CACF;AACD,CAAC;AAED,MAAM,UAAU,QAAQ,KAAK,MAAM,CAAC;AAEpC,IAAI,QAAQ,SAAS,QAAQ,KAAK,QAAQ,SAAS,IAAI,GAAG;CACzD,MAAM,UAAU,IAAI;CACpB,QAAQ,KAAK,CAAC;AACf;AAEA,IAAI,QAAQ,SAAS,WAAW,GAAG;CAClC,QAAQ,IAAI,YAAY,OAAO;CAC/B,QAAQ,KAAK,CAAC;AACf;AAEA,IAAI;CACH,MAAM,WAAW,MAAM,EAAE,QAAQ,CAAC;AACnC,SAAS,OAAO;CACf,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,KAAK;CAC5D,QAAQ,KAAK,CAAC;AACf"}
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@wolfstar/i18next-type-generator",
3
+ "version": "3.1.0-next-20260830180323",
4
+ "description": "A fast utility that generates the TypeScript augmentation for i18next.",
5
+ "keywords": [
6
+ "api",
7
+ "discord",
8
+ "http",
9
+ "i18next",
10
+ "pnpm",
11
+ "ts",
12
+ "typescript",
13
+ "wolfstar"
14
+ ],
15
+ "homepage": "https://github.com/wolfstar-project/stars-components/tree/main/packages/i18next-type-generator",
16
+ "bugs": {
17
+ "url": "https://github.com/wolfstar-project/stars-components/issues"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": "@wolfstar",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/wolfstar-project/stars-components.git",
24
+ "directory": "packages/i18next-type-generator"
25
+ },
26
+ "bin": {
27
+ "i18next-type-generator": "./dist/cli.js"
28
+ },
29
+ "files": [
30
+ "dist/"
31
+ ],
32
+ "type": "module",
33
+ "sideEffects": false,
34
+ "main": "dist/cli.js",
35
+ "exports": {
36
+ ".": {
37
+ "default": "./dist/cli.js"
38
+ }
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "dependencies": {
44
+ "citty": "^0.1.6",
45
+ "colorette": "^2.0.20",
46
+ "tslib": "^2.8.1"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "22.15.21",
50
+ "@vitest/coverage-v8": "^4.1.8",
51
+ "tsdown": "^0.22.2",
52
+ "typescript": "~5.8.3",
53
+ "vitest": "^4.1.8"
54
+ },
55
+ "optionalDependencies": {
56
+ "oxfmt": "^0.53.0",
57
+ "prettier": "^3.5.3"
58
+ },
59
+ "engines": {
60
+ "node": ">=20"
61
+ },
62
+ "scripts": {
63
+ "test": "vitest run",
64
+ "build": "tsdown --config-loader unrun",
65
+ "watch": "tsdown --config-loader unrun --watch",
66
+ "typecheck": "tsc -p ../../tsconfig.json",
67
+ "lint": "oxlint src --fix"
68
+ }
69
+ }