@prosopo/config 3.4.1 → 3.4.3

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 (74) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +9 -11
  2. package/.turbo/turbo-build$colon$tsc.log +4 -7
  3. package/.turbo/turbo-build.log +10 -15
  4. package/CHANGELOG.md +18 -0
  5. package/LICENSE +201 -0
  6. package/dist/cjs/dependencies.cjs +86 -46
  7. package/dist/cjs/vite/testFileGlobs.cjs +31 -0
  8. package/dist/cjs/vite/vite.frontend.config.cjs +7 -0
  9. package/dist/cjs/vite/vite.test.config.cjs +9 -8
  10. package/dist/cjs/vite/vite.threads.test.config.cjs +9 -8
  11. package/dist/cjs/webpack/webpack.config.cjs +8 -8
  12. package/dist/dependencies.d.ts.map +1 -1
  13. package/dist/dependencies.js +85 -44
  14. package/dist/dependencies.js.map +1 -1
  15. package/dist/getDependencies.test.js +151 -125
  16. package/dist/getDependencies.test.js.map +1 -1
  17. package/dist/vite/configs.test.js +6 -19
  18. package/dist/vite/configs.test.js.map +1 -1
  19. package/dist/vite/testFileGlobs.d.ts +8 -0
  20. package/dist/vite/testFileGlobs.d.ts.map +1 -0
  21. package/dist/vite/testFileGlobs.js +29 -0
  22. package/dist/vite/testFileGlobs.js.map +1 -0
  23. package/dist/vite/testFileGlobs.test.d.ts +2 -0
  24. package/dist/vite/testFileGlobs.test.d.ts.map +1 -0
  25. package/dist/vite/testFileGlobs.test.js +113 -0
  26. package/dist/vite/testFileGlobs.test.js.map +1 -0
  27. package/dist/vite/vite.frontend.config.d.ts.map +1 -1
  28. package/dist/vite/vite.frontend.config.js +8 -1
  29. package/dist/vite/vite.frontend.config.js.map +1 -1
  30. package/dist/vite/vite.test.config.d.ts.map +1 -1
  31. package/dist/vite/vite.test.config.js +9 -8
  32. package/dist/vite/vite.test.config.js.map +1 -1
  33. package/dist/vite/vite.threads.test.config.d.ts.map +1 -1
  34. package/dist/vite/vite.threads.test.config.js +9 -8
  35. package/dist/vite/vite.threads.test.config.js.map +1 -1
  36. package/dist/webpack/webpack.config.d.ts +2 -0
  37. package/dist/webpack/webpack.config.d.ts.map +1 -1
  38. package/dist/webpack/webpack.config.js +8 -8
  39. package/dist/webpack/webpack.config.js.map +1 -1
  40. package/package.json +106 -103
  41. package/src/dependencies.test.ts +0 -249
  42. package/src/dependencies.ts +0 -259
  43. package/src/getDependencies.test.ts +0 -385
  44. package/src/index.ts +0 -16
  45. package/src/vite/CopyAssetsPlugin.ts +0 -49
  46. package/src/vite/NodejsPolarsDirnamePlugin.ts +0 -50
  47. package/src/vite/NodejsPolarsNativeFilePlugin.ts +0 -105
  48. package/src/vite/TsNoCheckPlugin.ts +0 -31
  49. package/src/vite/bundleConfigs.test.ts +0 -461
  50. package/src/vite/configs.test.ts +0 -235
  51. package/src/vite/index.ts +0 -30
  52. package/src/vite/modifyExportsFiles.test.ts +0 -56
  53. package/src/vite/plugins.test.ts +0 -365
  54. package/src/vite/translations.test.ts +0 -164
  55. package/src/vite/types.ts +0 -13
  56. package/src/vite/vite-plugin-close-and-copy.ts +0 -76
  57. package/src/vite/vite-plugin-copy.ts +0 -67
  58. package/src/vite/vite-plugin-externalize-obfuscator-deadcode.ts +0 -43
  59. package/src/vite/vite-plugin-fix-absolute-imports.ts +0 -40
  60. package/src/vite/vite-plugin-modify-exports-files.ts +0 -64
  61. package/src/vite/vite-plugin-remove-unused-translations.ts +0 -128
  62. package/src/vite/vite-plugin-sourcemap-exclude.ts +0 -36
  63. package/src/vite/vite.backend.config.ts +0 -172
  64. package/src/vite/vite.commonjs.config.ts +0 -98
  65. package/src/vite/vite.esm.config.ts +0 -99
  66. package/src/vite/vite.frontend.config.ts +0 -340
  67. package/src/vite/vite.test.config.ts +0 -121
  68. package/src/vite/vite.threads.test.config.ts +0 -106
  69. package/src/webpack/index.ts +0 -14
  70. package/src/webpack/webpack.config.ts +0 -159
  71. package/tsconfig.cjs.json +0 -9
  72. package/tsconfig.json +0 -17
  73. package/tsconfig.tsbuildinfo +0 -1
  74. package/tsconfig.types.json +0 -9
@@ -1,164 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import fs from "node:fs";
16
- import os from "node:os";
17
- import path from "node:path";
18
- import type { Rollup } from "vite";
19
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
20
- import VitePluginRemoveUnusedTranslations from "./vite-plugin-remove-unused-translations.js";
21
-
22
- let root: string;
23
- let cwd: string;
24
-
25
- beforeEach(() => {
26
- root = fs.mkdtempSync(path.join(os.tmpdir(), "prosopo-translations-test-"));
27
- cwd = process.cwd();
28
- process.chdir(root);
29
- });
30
-
31
- afterEach(() => {
32
- process.chdir(cwd);
33
- fs.rmSync(root, { recursive: true, force: true });
34
- });
35
-
36
- /** Vite plugin hooks may be a bare function or an object with a `handler`. */
37
- type Hook<A extends unknown[], R> =
38
- | ((...args: A) => R)
39
- | { handler: (...args: A) => R }
40
- | undefined;
41
-
42
- const callHook = <A extends unknown[], R>(hook: Hook<A, R>, ...args: A): R => {
43
- if (!hook) {
44
- throw new Error("plugin does not define the hook");
45
- }
46
- const handler = typeof hook === "function" ? hook : hook.handler;
47
- return handler(...args);
48
- };
49
-
50
- const writeJson = (name: string, data: unknown): string => {
51
- const filePath = path.join(root, name);
52
- fs.writeFileSync(filePath, JSON.stringify(data));
53
- return filePath;
54
- };
55
-
56
- const readJson = (filePath: string): unknown =>
57
- JSON.parse(fs.readFileSync(filePath, "utf-8"));
58
-
59
- const run = async (
60
- keys: string[],
61
- sources: string[],
62
- pattern: string,
63
- ): Promise<void> => {
64
- const plugin = VitePluginRemoveUnusedTranslations(keys, pattern);
65
- for (const source of sources) {
66
- callHook(plugin.transform, source, "id.ts");
67
- }
68
- await callHook(
69
- plugin.writeBundle,
70
- {} as Rollup.NormalizedOutputOptions,
71
- {} as Rollup.OutputBundle,
72
- );
73
- };
74
-
75
- describe("VitePluginRemoveUnusedTranslations", () => {
76
- it("runs after the other plugins, once the code is final", () => {
77
- expect(VitePluginRemoveUnusedTranslations([], "*.json").enforce).toBe(
78
- "post",
79
- );
80
- });
81
-
82
- it("returns the code it was given, unmodified", () => {
83
- const plugin = VitePluginRemoveUnusedTranslations(["zz"], "*.json");
84
- expect(callHook(plugin.transform, "uses zz", "id.ts")).toEqual({
85
- code: "uses zz",
86
- });
87
- });
88
-
89
- // The set of used keys lives at module scope, shared by every plugin
90
- // instance in the process, so each test below uses key names of its own.
91
-
92
- it("keeps only the keys the bundle actually references", async () => {
93
- const file = writeJson("en.json", { kept: "yes", dropped: "no" });
94
- await run(["kept", "dropped"], ["t('kept')"], `${root}/*.json`);
95
- expect(readJson(file)).toEqual({ kept: "yes" });
96
- });
97
-
98
- it("restores the nesting of the keys it keeps", async () => {
99
- const file = writeJson("en.json", {
100
- widget: { label: "Verify", hint: "Click" },
101
- });
102
- await run(
103
- ["widget.label", "widget.hint"],
104
- ["t('widget.label')"],
105
- `${root}/*.json`,
106
- );
107
- expect(readJson(file)).toEqual({ widget: { label: "Verify" } });
108
- });
109
-
110
- it("empties a file whose keys are all unused", async () => {
111
- const file = writeJson("en.json", { solo: "1" });
112
- await run(["solo"], ["nothing here"], `${root}/*.json`);
113
- expect(readJson(file)).toEqual({});
114
- });
115
-
116
- it("prunes every matching file", async () => {
117
- const en = writeJson("en.json", { pa: "en", pb: "en" });
118
- const fr = writeJson("fr.json", { pa: "fr", pb: "fr" });
119
- await run(["pa", "pb"], ["t('pa')"], `${root}/*.json`);
120
- expect(readJson(en)).toEqual({ pa: "en" });
121
- expect(readJson(fr)).toEqual({ pa: "fr" });
122
- });
123
-
124
- it("does nothing when the pattern matches no file", async () => {
125
- await expect(
126
- run(["nk"], ["t('nk')"], `${root}/none/*.json`),
127
- ).resolves.toBeUndefined();
128
- });
129
-
130
- it("leaves a malformed JSON file alone instead of failing the build", async () => {
131
- // A translation file is not worth aborting a release for; the bundle is
132
- // already written by the time this hook runs.
133
- const broken = path.join(root, "en.json");
134
- fs.writeFileSync(broken, "{ not json");
135
- await expect(
136
- run(["mk"], ["t('mk')"], `${root}/*.json`),
137
- ).resolves.toBeUndefined();
138
- expect(fs.readFileSync(broken, "utf-8")).toBe("{ not json");
139
- });
140
-
141
- it("declares no key used when the key list is empty", async () => {
142
- const file = writeJson("en.json", { ek: "1" });
143
- await run([], ["t('ek')"], `${root}/*.json`);
144
- expect(readJson(file)).toEqual({});
145
- });
146
-
147
- it("matches a key as a substring of the emitted code", async () => {
148
- // The keys are looked for with `includes`, not as whole tokens, so a key
149
- // that is a prefix of another is kept whenever the longer one is used.
150
- const file = writeJson("en.json", { sa: "1", sab: "2" });
151
- await run(["sa", "sab"], ["t('sab')"], `${root}/*.json`);
152
- expect(readJson(file)).toEqual({ sa: "1", sab: "2" });
153
- });
154
-
155
- it("accumulates used keys across every transformed module", async () => {
156
- const file = writeJson("en.json", { one: "1", two: "2", three: "3" });
157
- await run(
158
- ["one", "two", "three"],
159
- ["t('one')", "t('two')"],
160
- `${root}/*.json`,
161
- );
162
- expect(readJson(file)).toEqual({ one: "1", two: "2" });
163
- });
164
- });
package/src/vite/types.ts DELETED
@@ -1,13 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
@@ -1,76 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import fs from "node:fs";
16
- import path from "node:path";
17
- import type { Plugin } from "vite";
18
-
19
- export interface ClosePluginOptions {
20
- srcDir: string;
21
- destDir: string[];
22
- }
23
-
24
- /**
25
- * description: Closes Vite after the bundle has been build. Optionally copies the bundle to a different directory.
26
- * @param { ClosePluginOptions } options - The options object
27
- **/
28
- export default function VitePluginCloseAndCopy(
29
- options?: ClosePluginOptions,
30
- ): Plugin {
31
- const __dirname = path.resolve();
32
- return {
33
- name: "close-plugin", // required, will show up in warnings and errors
34
- buildStart() {
35
- console.info("Bundle build started");
36
- },
37
- buildEnd(error) {
38
- console.info("Build end");
39
- if (error) {
40
- console.log(error);
41
- console.error(error);
42
- }
43
- },
44
- closeBundle() {
45
- if (options) {
46
- for (const destDir of options.destDir) {
47
- clearOutputDirJS(__dirname, destDir);
48
- console.info(`Bundle cleared from ${options.destDir}`);
49
- copyBundle(__dirname, options.srcDir, destDir);
50
- console.info(`Bundle copied to ${options.destDir}`);
51
- }
52
- console.info("Bundle closed");
53
- }
54
- },
55
- };
56
- }
57
-
58
- const clearOutputDirJS = (__dirname: string, destDir: string) =>
59
- fs
60
- .readdirSync(path.resolve(__dirname, destDir))
61
- .filter((file) => file.endsWith("js"))
62
- .map((file) => {
63
- fs.rmSync(path.resolve(__dirname, destDir, file));
64
- });
65
-
66
- const copyBundle = (__dirname: string, srcDir: string, destDir: string) => {
67
- console.info(
68
- "Copying",
69
- path.resolve(__dirname, srcDir),
70
- "to",
71
- path.resolve(__dirname, destDir),
72
- );
73
- fs.cpSync(path.resolve(__dirname, srcDir), path.resolve(__dirname, destDir), {
74
- recursive: true,
75
- });
76
- };
@@ -1,67 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import fs from "node:fs";
16
- import path from "node:path";
17
- import fg from "fast-glob";
18
- import type { Plugin } from "vite";
19
-
20
- interface CopyPluginOptions {
21
- srcDir: string;
22
- destDir: string;
23
- include?: string[]; // Optional: glob patterns for files to include
24
- exclude?: string[]; // Optional: glob patterns for files to exclude
25
- }
26
-
27
- function ensureDirExists(filePath: string) {
28
- const dir = path.dirname(filePath);
29
- if (!fs.existsSync(dir)) {
30
- fs.mkdirSync(dir, { recursive: true });
31
- }
32
- }
33
-
34
- export default function VitePluginCopy(options: CopyPluginOptions): Plugin {
35
- const __dirname = path.resolve();
36
- return {
37
- name: "copy-plugin",
38
- async closeBundle() {
39
- const srcAbs = path.resolve(__dirname, options.srcDir);
40
- const destAbs = path.resolve(__dirname, options.destDir);
41
- const include =
42
- options.include && options.include.length > 0
43
- ? options.include
44
- : undefined;
45
- const exclude = options.exclude || [];
46
- if (!include) {
47
- console.info(
48
- "[copy-plugin] No include globs specified, nothing to copy.",
49
- );
50
- return;
51
- }
52
- const files = await fg(include, {
53
- cwd: srcAbs,
54
- ignore: exclude,
55
- onlyFiles: true,
56
- absolute: false,
57
- });
58
- for (const relFile of files) {
59
- const srcFile = path.join(srcAbs, relFile);
60
- const destFile = path.join(destAbs, relFile);
61
- ensureDirExists(destFile);
62
- console.info(`[copy-plugin] copying ${srcFile} to ${destFile}`);
63
- fs.copyFileSync(srcFile, destFile);
64
- }
65
- },
66
- };
67
- }
@@ -1,43 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
- import type { Plugin } from "vite";
15
-
16
- // js-confuser's `deadCode` transform injects a fixed set of fake `require()`
17
- // specifiers into obfuscated sources as unreachable dead code. Rollup (Vite 6)
18
- // left unresolved imports external with a warning, so these harmless specifiers
19
- // never broke the build. Rolldown (Vite 8) treats an unresolved import as a hard
20
- // error, so we restore the old behaviour by marking exactly these known
21
- // dead-code specifiers as external. They are never executed at runtime.
22
- const OBFUSCATOR_DEADCODE_SPECIFIERS: ReadonlySet<string> = new Set([
23
- "../../package",
24
- "../redacted.js",
25
- "../utils/isStandaloneExecutable",
26
- "./resolve-local-redacted-path",
27
- "@redacted/components/package",
28
- "@redacted/enterprise-plugin",
29
- "@redacted/enterprise-plugin/package",
30
- ]);
31
-
32
- export default function VitePluginExternalizeObfuscatorDeadCode(): Plugin {
33
- return {
34
- name: "externalize-obfuscator-deadcode",
35
- enforce: "pre",
36
- resolveId(source: string) {
37
- if (OBFUSCATOR_DEADCODE_SPECIFIERS.has(source)) {
38
- return { id: source, external: true };
39
- }
40
- return null;
41
- },
42
- };
43
- }
@@ -1,40 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
- import { builtinModules } from "node:module";
15
- import type { Plugin } from "vite";
16
-
17
- export default function VitePluginFixAbsoluteImports(): Plugin {
18
- return {
19
- name: "fix-absolute-imports",
20
- transform(code: string, id: string) {
21
- for (const module of builtinModules) {
22
- const moduleImportRegex = new RegExp(
23
- `from "(${module}(/.*)*/.*.js)";`,
24
- "g",
25
- );
26
- // if matches, replace match with _module
27
- const matches = code.match(moduleImportRegex);
28
- if (matches) {
29
- for (const match of matches) {
30
- code = code.replace(match, `from "${module}";`);
31
- }
32
- }
33
- }
34
- return {
35
- code,
36
- };
37
- },
38
- enforce: "post",
39
- };
40
- }
@@ -1,64 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
- import type { Plugin } from "vite";
15
-
16
- /**
17
- * Empties the generated `exports2.FILES` array in every emitted chunk so that
18
- * bundled file listings are not leaked into the output.
19
- */
20
- const ASSIGNMENT = "exports2.FILES = [";
21
- const TERMINATOR = "];";
22
- const REPLACEMENT = "exports2.FILES = [];\n";
23
-
24
- /**
25
- * Blank every `exports2.FILES = [...]` assignment in a chunk.
26
- *
27
- * Done with indexOf rather than a regex: `\[[\s\S]*?\];` backtracks
28
- * quadratically on a chunk holding many unterminated assignments, and chunk
29
- * contents are whatever the bundled sources happened to contain. Scanning
30
- * forward is linear regardless.
31
- */
32
- export const emptyExportsFiles = (code: string): string => {
33
- let out = "";
34
- let cursor = 0;
35
- for (;;) {
36
- const start = code.indexOf(ASSIGNMENT, cursor);
37
- if (start === -1) {
38
- break;
39
- }
40
- const end = code.indexOf(TERMINATOR, start + ASSIGNMENT.length);
41
- if (end === -1) {
42
- // Unterminated: leave it and everything after it alone rather than
43
- // truncating the chunk.
44
- break;
45
- }
46
- out += code.slice(cursor, start) + REPLACEMENT;
47
- cursor = end + TERMINATOR.length;
48
- }
49
- return out + code.slice(cursor);
50
- };
51
-
52
- export default function modifyExportsFilesPlugin(): Plugin {
53
- return {
54
- name: "modify-exports-files",
55
- generateBundle(_options, bundle) {
56
- for (const fileName in bundle) {
57
- const chunk = bundle[fileName];
58
- if (chunk && chunk.type === "chunk") {
59
- chunk.code = emptyExportsFiles(chunk.code);
60
- }
61
- }
62
- },
63
- };
64
- }
@@ -1,128 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
- import fs from "node:fs/promises";
15
- import glob from "fast-glob";
16
- import type { Plugin } from "vite";
17
-
18
- const used = new Set<string>();
19
-
20
- export const flatten = (obj: object, prefix = ""): Record<string, string> => {
21
- const flattenedObj: Record<string, string> = {};
22
- for (const [key, value] of Object.entries(obj)) {
23
- if (value instanceof Object) {
24
- Object.assign(flattenedObj, flatten(value, `${prefix + key}.`));
25
- } else {
26
- flattenedObj[prefix + key] = value;
27
- }
28
- }
29
- return flattenedObj;
30
- };
31
-
32
- type UnflattenObject =
33
- | Record<string, string | number | boolean | undefined>
34
- | string[]
35
- | number[]
36
- | boolean[];
37
-
38
- export const unflatten = (
39
- obj: Record<string, string | number | boolean>,
40
- ): Record<string, string | number | boolean | UnflattenObject> => {
41
- const result: Record<string, string | number | boolean | UnflattenObject> =
42
- {};
43
-
44
- for (const [key, value] of Object.entries(obj)) {
45
- const keys = key.split(".");
46
- keys.reduce((acc, k, i) => {
47
- if (i === keys.length - 1) {
48
- (acc as Record<string, string | number | boolean | UnflattenObject>)[
49
- k
50
- ] = value;
51
- } else {
52
- if (!acc[k]) {
53
- acc[k] = Number.isNaN(Number(keys[i + 1])) ? {} : [];
54
- }
55
- }
56
- return acc[k] as Record<
57
- string,
58
- string | number | boolean | UnflattenObject
59
- >;
60
- }, result);
61
- }
62
-
63
- return result;
64
- };
65
-
66
- export default function VitePluginRemoveUnusedTranslations(
67
- translationKeys: string[],
68
- jsonPattern: string,
69
- ): Plugin {
70
- return {
71
- name: "remove-unused-translations",
72
- transform(code: string) {
73
- // Collect translation keys used in the source files
74
- for (const key of translationKeys) {
75
- if (code.includes(key) && !used.has(key)) {
76
- console.info(`Found key: ${key}`);
77
- used.add(key);
78
- }
79
- }
80
- return { code };
81
- },
82
- enforce: "post",
83
-
84
- async writeBundle() {
85
- // Find all matching JSON files
86
- const jsonFiles = await glob(jsonPattern, { absolute: true });
87
-
88
- console.info(`Found ${jsonFiles.length} JSON files at ${jsonPattern}`);
89
-
90
- const filePromises = [];
91
- for (const filePath of jsonFiles) {
92
- try {
93
- const content = await fs.readFile(filePath, "utf-8");
94
- const jsonData = JSON.parse(content);
95
- const jsonDataFlattened = flatten(jsonData);
96
-
97
- // Remove keys that are not in `used`
98
- const filteredData = Object.fromEntries(
99
- Object.entries(jsonDataFlattened).filter(([key]) => used.has(key)),
100
- );
101
-
102
- const unflattened = unflatten(filteredData);
103
-
104
- // log.info(unflattened);
105
-
106
- // Write back the filtered JSON
107
- filePromises.push(
108
- fs
109
- .writeFile(
110
- filePath,
111
- JSON.stringify(unflattened, null, 2),
112
- "utf-8",
113
- )
114
- .then(() => {
115
- console.info(`Updated ${filePath}`);
116
- })
117
- .catch((e) => {
118
- console.error(`Failed to update ${filePath}:`, e);
119
- }),
120
- );
121
- } catch (error: unknown) {
122
- console.error(`Failed to process ${filePath}:`, error);
123
- }
124
- }
125
- await Promise.all(filePromises);
126
- },
127
- };
128
- }
@@ -1,36 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
- import type { Plugin } from "vite";
15
-
16
- interface SourcemapExclude {
17
- excludeNodeModules?: boolean;
18
- }
19
- // Taken from https://github.com/vitejs/vite/issues/2433#issuecomment-1487472995 to prevent memory leaks
20
- export default function VitePluginSourcemapExclude(
21
- opts?: SourcemapExclude,
22
- ): Plugin {
23
- return {
24
- name: "sourcemap-exclude",
25
- transform(code: string, id: string) {
26
- if (opts?.excludeNodeModules && id.includes("node_modules")) {
27
- return {
28
- code,
29
- // https://github.com/rollup/rollup/blob/master/docs/plugin-development/index.md#source-code-transformations
30
- map: { mappings: "" },
31
- };
32
- }
33
- return;
34
- },
35
- };
36
- }