@gtkx/cli 1.6.0 → 2.0.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 (309) hide show
  1. package/README.md +5 -5
  2. package/dist/builder.d.ts +1 -0
  3. package/dist/builder.d.ts.map +1 -1
  4. package/dist/builder.js +17 -5
  5. package/dist/builder.js.map +1 -1
  6. package/dist/cli.js +2 -0
  7. package/dist/cli.js.map +1 -1
  8. package/dist/codegen/freshness.d.ts.map +1 -1
  9. package/dist/codegen/freshness.js +45 -16
  10. package/dist/codegen/freshness.js.map +1 -1
  11. package/dist/codegen/reference.d.ts.map +1 -1
  12. package/dist/codegen/reference.js +1 -7
  13. package/dist/codegen/reference.js.map +1 -1
  14. package/dist/codegen/report.d.ts.map +1 -1
  15. package/dist/codegen/report.js +5 -16
  16. package/dist/codegen/report.js.map +1 -1
  17. package/dist/codegen/run-codegen.d.ts +7 -7
  18. package/dist/codegen/run-codegen.d.ts.map +1 -1
  19. package/dist/codegen/run-codegen.js +35 -107
  20. package/dist/codegen/run-codegen.js.map +1 -1
  21. package/dist/codegen/store-resolver.d.ts +1 -2
  22. package/dist/codegen/store-resolver.d.ts.map +1 -1
  23. package/dist/codegen/store-resolver.js +10 -19
  24. package/dist/codegen/store-resolver.js.map +1 -1
  25. package/dist/commands/build.d.ts +5 -0
  26. package/dist/commands/build.d.ts.map +1 -1
  27. package/dist/commands/build.js +83 -10
  28. package/dist/commands/build.js.map +1 -1
  29. package/dist/commands/codegen.d.ts +1 -0
  30. package/dist/commands/codegen.d.ts.map +1 -1
  31. package/dist/commands/codegen.js +6 -5
  32. package/dist/commands/codegen.js.map +1 -1
  33. package/dist/commands/deploy.d.ts +1 -0
  34. package/dist/commands/deploy.d.ts.map +1 -1
  35. package/dist/commands/deploy.js +4 -2
  36. package/dist/commands/deploy.js.map +1 -1
  37. package/dist/commands/dev.d.ts +8 -0
  38. package/dist/commands/dev.d.ts.map +1 -1
  39. package/dist/commands/dev.js +19 -1
  40. package/dist/commands/dev.js.map +1 -1
  41. package/dist/commands/docs.d.ts.map +1 -1
  42. package/dist/commands/docs.js +5 -15
  43. package/dist/commands/docs.js.map +1 -1
  44. package/dist/deploy/freedesktop/copyright.d.ts.map +1 -1
  45. package/dist/deploy/freedesktop/copyright.js +2 -13
  46. package/dist/deploy/freedesktop/copyright.js.map +1 -1
  47. package/dist/deploy/freedesktop/metainfo.d.ts.map +1 -1
  48. package/dist/deploy/freedesktop/metainfo.js +41 -2
  49. package/dist/deploy/freedesktop/metainfo.js.map +1 -1
  50. package/dist/deploy/freedesktop/xml.d.ts.map +1 -1
  51. package/dist/deploy/freedesktop/xml.js +21 -25
  52. package/dist/deploy/freedesktop/xml.js.map +1 -1
  53. package/dist/deploy/nfpm/config.d.ts.map +1 -1
  54. package/dist/deploy/nfpm/config.js +5 -2
  55. package/dist/deploy/nfpm/config.js.map +1 -1
  56. package/dist/deploy/nfpm/contents.d.ts.map +1 -1
  57. package/dist/deploy/nfpm/contents.js +8 -0
  58. package/dist/deploy/nfpm/contents.js.map +1 -1
  59. package/dist/deploy/node-runtime/elf.d.ts +2 -1
  60. package/dist/deploy/node-runtime/elf.d.ts.map +1 -1
  61. package/dist/deploy/node-runtime/elf.js +32 -5
  62. package/dist/deploy/node-runtime/elf.js.map +1 -1
  63. package/dist/deploy/node-runtime/index.d.ts +2 -1
  64. package/dist/deploy/node-runtime/index.d.ts.map +1 -1
  65. package/dist/deploy/node-runtime/index.js +73 -4
  66. package/dist/deploy/node-runtime/index.js.map +1 -1
  67. package/dist/deploy/node-runtime/license.d.ts.map +1 -1
  68. package/dist/deploy/node-runtime/license.js +2 -9
  69. package/dist/deploy/node-runtime/license.js.map +1 -1
  70. package/dist/deploy/notices/node-runtime.js +2 -2
  71. package/dist/deploy/notices/node-runtime.js.map +1 -1
  72. package/dist/deploy/notices/packages.d.ts.map +1 -1
  73. package/dist/deploy/notices/packages.js +3 -10
  74. package/dist/deploy/notices/packages.js.map +1 -1
  75. package/dist/deploy/payload/copy-tree.d.ts.map +1 -1
  76. package/dist/deploy/payload/copy-tree.js +3 -3
  77. package/dist/deploy/payload/copy-tree.js.map +1 -1
  78. package/dist/deploy/payload/launcher.d.ts.map +1 -1
  79. package/dist/deploy/payload/launcher.js +14 -1
  80. package/dist/deploy/payload/launcher.js.map +1 -1
  81. package/dist/deploy/payload/stage.d.ts.map +1 -1
  82. package/dist/deploy/payload/stage.js +2 -4
  83. package/dist/deploy/payload/stage.js.map +1 -1
  84. package/dist/deploy/run-deploy.d.ts +1 -0
  85. package/dist/deploy/run-deploy.d.ts.map +1 -1
  86. package/dist/deploy/run-deploy.js +100 -14
  87. package/dist/deploy/run-deploy.js.map +1 -1
  88. package/dist/deploy/settings/build-manifest.d.ts +6 -1
  89. package/dist/deploy/settings/build-manifest.d.ts.map +1 -1
  90. package/dist/deploy/settings/build-manifest.js +17 -17
  91. package/dist/deploy/settings/build-manifest.js.map +1 -1
  92. package/dist/deploy/settings/extra-files.d.ts +1 -1
  93. package/dist/deploy/settings/extra-files.d.ts.map +1 -1
  94. package/dist/deploy/settings/extra-files.js +22 -1
  95. package/dist/deploy/settings/extra-files.js.map +1 -1
  96. package/dist/deploy/settings/index.d.ts +1 -0
  97. package/dist/deploy/settings/index.d.ts.map +1 -1
  98. package/dist/deploy/settings/index.js +2 -1
  99. package/dist/deploy/settings/index.js.map +1 -1
  100. package/dist/deploy/settings/libraries.d.ts.map +1 -1
  101. package/dist/deploy/settings/libraries.js +2 -19
  102. package/dist/deploy/settings/libraries.js.map +1 -1
  103. package/dist/deploy/settings/paths.d.ts +2 -2
  104. package/dist/deploy/settings/paths.d.ts.map +1 -1
  105. package/dist/deploy/settings/paths.js +110 -12
  106. package/dist/deploy/settings/paths.js.map +1 -1
  107. package/dist/deploy/settings/screenshots.d.ts.map +1 -1
  108. package/dist/deploy/settings/screenshots.js +6 -31
  109. package/dist/deploy/settings/screenshots.js.map +1 -1
  110. package/dist/deploy/targets/flatpak-pnpm.js +4 -4
  111. package/dist/deploy/targets/flatpak-pnpm.js.map +1 -1
  112. package/dist/deploy/targets/flatpak-source.d.ts.map +1 -1
  113. package/dist/deploy/targets/flatpak-source.js +15 -6
  114. package/dist/deploy/targets/flatpak-source.js.map +1 -1
  115. package/dist/deploy/targets/flatpak-sources.js +1 -1
  116. package/dist/deploy/targets/flatpak-sources.js.map +1 -1
  117. package/dist/deploy/types.d.ts +1 -0
  118. package/dist/deploy/types.d.ts.map +1 -1
  119. package/dist/deploy/types.js.map +1 -1
  120. package/dist/dev/headless.d.ts +3 -0
  121. package/dist/dev/headless.d.ts.map +1 -0
  122. package/dist/dev/headless.js +35 -0
  123. package/dist/dev/headless.js.map +1 -0
  124. package/dist/dev/runner-deps.js +1 -1
  125. package/dist/dev/runner-deps.js.map +1 -1
  126. package/dist/dev/runner-main.d.ts.map +1 -1
  127. package/dist/dev/runner-main.js +1 -2
  128. package/dist/dev/runner-main.js.map +1 -1
  129. package/dist/dev/schema-dir.d.ts +1 -1
  130. package/dist/dev/schema-dir.d.ts.map +1 -1
  131. package/dist/dev/schema-dir.js +2 -4
  132. package/dist/dev/schema-dir.js.map +1 -1
  133. package/dist/i18n/catalogs.d.ts.map +1 -1
  134. package/dist/i18n/catalogs.js +2 -1
  135. package/dist/i18n/catalogs.js.map +1 -1
  136. package/dist/i18n/metadata-templates.d.ts.map +1 -1
  137. package/dist/i18n/metadata-templates.js +2 -1
  138. package/dist/i18n/metadata-templates.js.map +1 -1
  139. package/dist/i18n/source-messages.d.ts +3 -21
  140. package/dist/i18n/source-messages.d.ts.map +1 -1
  141. package/dist/i18n/source-messages.js +900 -85
  142. package/dist/i18n/source-messages.js.map +1 -1
  143. package/dist/i18n/types.d.ts +6 -7
  144. package/dist/i18n/types.d.ts.map +1 -1
  145. package/dist/i18n/types.js +83 -96
  146. package/dist/i18n/types.js.map +1 -1
  147. package/dist/internal/build-manifest.d.ts +5 -2
  148. package/dist/internal/build-manifest.d.ts.map +1 -1
  149. package/dist/internal/build-manifest.js +15 -2
  150. package/dist/internal/build-manifest.js.map +1 -1
  151. package/dist/internal/build-output.d.ts +8 -0
  152. package/dist/internal/build-output.d.ts.map +1 -0
  153. package/dist/internal/build-output.js +69 -0
  154. package/dist/internal/build-output.js.map +1 -0
  155. package/dist/internal/docs-elements.js +2 -2
  156. package/dist/internal/docs-elements.js.map +1 -1
  157. package/dist/internal/entry-arg.d.ts +4 -1
  158. package/dist/internal/entry-arg.d.ts.map +1 -1
  159. package/dist/internal/entry-arg.js +7 -1
  160. package/dist/internal/entry-arg.js.map +1 -1
  161. package/dist/internal/icon-path.d.ts.map +1 -1
  162. package/dist/internal/icon-path.js +5 -16
  163. package/dist/internal/icon-path.js.map +1 -1
  164. package/dist/internal/output-directory.d.ts +15 -0
  165. package/dist/internal/output-directory.d.ts.map +1 -0
  166. package/dist/internal/output-directory.js +490 -0
  167. package/dist/internal/output-directory.js.map +1 -0
  168. package/dist/internal/prepare-project.d.ts +2 -0
  169. package/dist/internal/prepare-project.d.ts.map +1 -1
  170. package/dist/internal/prepare-project.js +3 -3
  171. package/dist/internal/prepare-project.js.map +1 -1
  172. package/dist/internal/source-imports.d.ts.map +1 -1
  173. package/dist/internal/source-imports.js +10 -41
  174. package/dist/internal/source-imports.js.map +1 -1
  175. package/dist/mcp/client.js +2 -2
  176. package/dist/mcp/client.js.map +1 -1
  177. package/dist/settings/render.d.ts +0 -1
  178. package/dist/settings/render.d.ts.map +1 -1
  179. package/dist/settings/render.js +1 -11
  180. package/dist/settings/render.js.map +1 -1
  181. package/dist/settings/schema.d.ts +2 -2
  182. package/dist/settings/schema.d.ts.map +1 -1
  183. package/dist/settings/schema.js +21 -62
  184. package/dist/settings/schema.js.map +1 -1
  185. package/dist/vite-plugins/asset-imports.d.ts +1 -2
  186. package/dist/vite-plugins/asset-imports.d.ts.map +1 -1
  187. package/dist/vite-plugins/asset-imports.js +19 -32
  188. package/dist/vite-plugins/asset-imports.js.map +1 -1
  189. package/dist/vite-plugins/asset-specifier.d.ts +1 -3
  190. package/dist/vite-plugins/asset-specifier.d.ts.map +1 -1
  191. package/dist/vite-plugins/asset-specifier.js +1 -4
  192. package/dist/vite-plugins/asset-specifier.js.map +1 -1
  193. package/dist/vite-plugins/build-manifest.d.ts +5 -1
  194. package/dist/vite-plugins/build-manifest.d.ts.map +1 -1
  195. package/dist/vite-plugins/build-manifest.js +2 -1
  196. package/dist/vite-plugins/build-manifest.js.map +1 -1
  197. package/dist/vite-plugins/i18n.d.ts.map +1 -1
  198. package/dist/vite-plugins/i18n.js +59 -6
  199. package/dist/vite-plugins/i18n.js.map +1 -1
  200. package/dist/vite-plugins/index.d.ts +8 -1
  201. package/dist/vite-plugins/index.d.ts.map +1 -1
  202. package/dist/vite-plugins/index.js +8 -6
  203. package/dist/vite-plugins/index.js.map +1 -1
  204. package/dist/vite-plugins/resources.d.ts.map +1 -1
  205. package/dist/vite-plugins/resources.js +32 -97
  206. package/dist/vite-plugins/resources.js.map +1 -1
  207. package/dist/vite-plugins/self-contained.d.ts.map +1 -1
  208. package/dist/vite-plugins/self-contained.js +159 -158
  209. package/dist/vite-plugins/self-contained.js.map +1 -1
  210. package/dist/vite-plugins/settings-worker-env.d.ts.map +1 -1
  211. package/dist/vite-plugins/settings-worker-env.js +2 -4
  212. package/dist/vite-plugins/settings-worker-env.js.map +1 -1
  213. package/dist/vite-plugins/settings.d.ts +1 -2
  214. package/dist/vite-plugins/settings.d.ts.map +1 -1
  215. package/dist/vite-plugins/settings.js +8 -14
  216. package/dist/vite-plugins/settings.js.map +1 -1
  217. package/dist/vite-plugins/undeclared-library.d.ts.map +1 -1
  218. package/dist/vite-plugins/undeclared-library.js +10 -13
  219. package/dist/vite-plugins/undeclared-library.js.map +1 -1
  220. package/dist/vite-plugins/worker.d.ts.map +1 -1
  221. package/dist/vite-plugins/worker.js +0 -1
  222. package/dist/vite-plugins/worker.js.map +1 -1
  223. package/package.json +21 -15
  224. package/src/builder.ts +18 -5
  225. package/src/cli.ts +3 -0
  226. package/src/codegen/freshness.ts +66 -17
  227. package/src/codegen/reference.ts +1 -8
  228. package/src/codegen/report.ts +5 -21
  229. package/src/codegen/run-codegen.ts +42 -151
  230. package/src/codegen/store-resolver.ts +10 -26
  231. package/src/commands/build.ts +13 -2
  232. package/src/commands/codegen.ts +6 -5
  233. package/src/commands/deploy.ts +4 -2
  234. package/src/commands/dev.ts +20 -1
  235. package/src/commands/docs.ts +5 -17
  236. package/src/deploy/freedesktop/copyright.ts +2 -14
  237. package/src/deploy/freedesktop/metainfo.ts +73 -21
  238. package/src/deploy/freedesktop/xml.ts +24 -32
  239. package/src/deploy/nfpm/config.ts +5 -2
  240. package/src/deploy/nfpm/contents.ts +8 -0
  241. package/src/deploy/node-runtime/elf.ts +43 -5
  242. package/src/deploy/node-runtime/index.ts +105 -5
  243. package/src/deploy/node-runtime/license.ts +2 -8
  244. package/src/deploy/notices/node-runtime.ts +2 -2
  245. package/src/deploy/notices/packages.ts +3 -11
  246. package/src/deploy/payload/copy-tree.ts +3 -4
  247. package/src/deploy/payload/launcher.ts +20 -1
  248. package/src/deploy/payload/stage.ts +3 -7
  249. package/src/deploy/run-deploy.ts +56 -16
  250. package/src/deploy/settings/build-manifest.ts +30 -17
  251. package/src/deploy/settings/extra-files.ts +26 -2
  252. package/src/deploy/settings/index.ts +3 -1
  253. package/src/deploy/settings/libraries.ts +1 -22
  254. package/src/deploy/settings/paths.ts +68 -13
  255. package/src/deploy/settings/screenshots.ts +8 -46
  256. package/src/deploy/targets/flatpak-pnpm.ts +4 -4
  257. package/src/deploy/targets/flatpak-source.ts +17 -6
  258. package/src/deploy/targets/flatpak-sources.ts +1 -1
  259. package/src/deploy/types.ts +1 -0
  260. package/src/dev/headless.ts +40 -0
  261. package/src/dev/runner-deps.ts +1 -1
  262. package/src/dev/runner-main.ts +1 -2
  263. package/src/dev/schema-dir.ts +2 -4
  264. package/src/i18n/catalogs.ts +2 -1
  265. package/src/i18n/metadata-templates.ts +2 -1
  266. package/src/i18n/source-messages.ts +1442 -262
  267. package/src/i18n/types.ts +97 -131
  268. package/src/internal/build-manifest.ts +25 -1
  269. package/src/internal/build-output.ts +99 -0
  270. package/src/internal/docs-elements.ts +2 -2
  271. package/src/internal/entry-arg.ts +8 -1
  272. package/src/internal/icon-path.ts +6 -19
  273. package/src/internal/output-directory.ts +699 -0
  274. package/src/internal/prepare-project.ts +5 -5
  275. package/src/internal/source-imports.ts +14 -50
  276. package/src/mcp/client.ts +2 -2
  277. package/src/settings/render.ts +1 -13
  278. package/src/settings/schema.ts +19 -81
  279. package/src/vite-plugins/asset-imports.ts +20 -44
  280. package/src/vite-plugins/asset-specifier.ts +0 -5
  281. package/src/vite-plugins/build-manifest.ts +7 -1
  282. package/src/vite-plugins/i18n.ts +87 -5
  283. package/src/vite-plugins/index.ts +16 -11
  284. package/src/vite-plugins/resources.ts +37 -140
  285. package/src/vite-plugins/self-contained.ts +184 -185
  286. package/src/vite-plugins/settings-worker-env.ts +2 -4
  287. package/src/vite-plugins/settings.ts +11 -20
  288. package/src/vite-plugins/undeclared-library.ts +14 -20
  289. package/src/vite-plugins/worker.ts +0 -1
  290. package/dist/i18n/binding-extractor.d.ts +0 -30
  291. package/dist/i18n/binding-extractor.d.ts.map +0 -1
  292. package/dist/i18n/binding-extractor.js +0 -1324
  293. package/dist/i18n/binding-extractor.js.map +0 -1
  294. package/dist/i18n/extractor-plugin.d.ts +0 -8
  295. package/dist/i18n/extractor-plugin.d.ts.map +0 -1
  296. package/dist/i18n/extractor-plugin.js +0 -247
  297. package/dist/i18n/extractor-plugin.js.map +0 -1
  298. package/dist/internal/data-dir.d.ts +0 -4
  299. package/dist/internal/data-dir.d.ts.map +0 -1
  300. package/dist/internal/data-dir.js +0 -52
  301. package/dist/internal/data-dir.js.map +0 -1
  302. package/dist/vite-plugins/animated.d.ts +0 -5
  303. package/dist/vite-plugins/animated.d.ts.map +0 -1
  304. package/dist/vite-plugins/animated.js +0 -325
  305. package/dist/vite-plugins/animated.js.map +0 -1
  306. package/src/i18n/binding-extractor.ts +0 -1969
  307. package/src/i18n/extractor-plugin.ts +0 -413
  308. package/src/internal/data-dir.ts +0 -70
  309. package/src/vite-plugins/animated.ts +0 -486
@@ -1,14 +1,38 @@
1
- import { findKeys } from "i18next-cli";
1
+ import { parseSync as parseBabelSync, traverse, types } from "@babel/core";
2
+ import { isPathInside, isPathWithin, toPosixPath } from "@gtkx/utils";
3
+ import { runExtractor } from "i18next-cli";
2
4
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
3
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
6
+ import { parseSync, Visitor } from "vite";
4
7
  import { runCliTool } from "../internal/run-cli-tool.js";
8
+ import { sourceLanguage } from "../internal/source-imports.js";
5
9
  import { replaceCatalogTemplate } from "./catalog-template.js";
6
- import { gtkxExtractorPlugin } from "./extractor-plugin.js";
7
10
  import { metadataTemplateFiles } from "./metadata-templates.js";
11
+ import { clearI18nResources, i18nToolkitConfig } from "./types.js";
8
12
  const CONTEXT_SEPARATOR = "\u{4}";
9
13
  const DEFAULT_NAMESPACE = "translation";
10
14
  const POTFILES_FILENAME = "POTFILES.in";
11
15
  const SYNTHETIC_FILENAME = "messages.js";
16
+ const UNSUPPORTED_PLURAL_OPTION = /^defaultValue_(few|many|two|zero)$/u;
17
+ const STATIC_SOURCE_OPTION_NAMES = new Set([
18
+ "context",
19
+ "defaultValue",
20
+ "defaultValue_one",
21
+ "defaultValue_other",
22
+ "keyPrefix",
23
+ ]);
24
+ const NESTED_CONTEXT = /["']?context["']?\s*:\s*(?:"([^"]*)"|'([^']*)')/u;
25
+ const NESTED_COUNT = /["']?count["']?\s*:/u;
26
+ const NESTED_STRUCTURE_TOKEN = /"[^"]*"|'[^']*'|[()]/gu;
27
+ const TRANSLATION_MODULES = new Set(["@gtkx/i18n", "i18next"]);
28
+ const TRANS_ELEMENTS = new Set(["Trans", "TransWithoutContext"]);
29
+ const STATIC_KEY_WRAPPER_TYPES = new Set([
30
+ "ParenthesizedExpression",
31
+ "TSAsExpression",
32
+ "TSSatisfiesExpression",
33
+ "TSTypeAssertion",
34
+ "TSNonNullExpression",
35
+ ]);
12
36
  const quietLogger = () => {
13
37
  const reports = [];
14
38
  return {
@@ -27,29 +51,6 @@ const quietLogger = () => {
27
51
  },
28
52
  };
29
53
  };
30
- const extractorConfig = (sourceFiles) => {
31
- const integration = gtkxExtractorPlugin();
32
- return {
33
- locales: ["en"],
34
- plugins: [integration.plugin],
35
- extract: {
36
- input: sourceFiles,
37
- output: "unused/{{language}}/{{namespace}}.json",
38
- contextSeparator: CONTEXT_SEPARATOR,
39
- defaultNS: DEFAULT_NAMESPACE,
40
- disablePlurals: false,
41
- extractFromComments: false,
42
- functions: [],
43
- generateBasePluralForms: false,
44
- keySeparator: ".",
45
- nsSeparator: false,
46
- pluralSeparator: "_",
47
- transComponents: integration.transComponents,
48
- useTranslationNames: [],
49
- warnOnConflicts: "error",
50
- },
51
- };
52
- };
53
54
  const splitContext = (key) => {
54
55
  const index = key.lastIndexOf(CONTEXT_SEPARATOR);
55
56
  if (index === -1) {
@@ -75,27 +76,30 @@ const normalizedLocations = (locations) => {
75
76
  return unique.values().toArray().toSorted(compareLocations);
76
77
  };
77
78
  const pointSource = (entry, msgid) => {
78
- if (entry.explicitDefault !== true || typeof entry.defaultValue !== "string") {
79
+ if (typeof entry.defaultValue !== "string") {
79
80
  return msgid;
80
81
  }
81
- return entry.defaultValue;
82
+ if (entry.explicitDefault === true) {
83
+ return entry.defaultValue;
84
+ }
85
+ return entry.defaultValue === msgid || msgid.endsWith(`.${entry.defaultValue}`)
86
+ ? msgid
87
+ : entry.defaultValue;
82
88
  };
83
89
  const pointMessage = (entry) => {
84
90
  const { context, msgid } = splitContext(entry.key);
85
91
  validateIdentity(context, msgid);
86
- const isDefaultExplicit = entry.explicitDefault === true;
87
92
  const singular = pointSource(entry, msgid);
88
93
  if (singular.length === 0) {
89
94
  throw new Error("Translation source strings cannot be empty");
90
95
  }
91
96
  return {
92
97
  context,
93
- kind: isDefaultExplicit ? "default" : "point",
94
98
  locations: normalizedLocations(entry.locations ?? []),
95
- msgid,
96
99
  namespace: namespaceFor(entry),
97
100
  plural: null,
98
101
  singular,
102
+ sourceKey: msgid,
99
103
  };
100
104
  };
101
105
  const expandedPlural = (entry) => {
@@ -145,20 +149,18 @@ const pluralMessage = ({ baseKey, namespace, variants }) => {
145
149
  const { one, other } = pairedVariants(variants);
146
150
  const { context, msgid } = splitContext(baseKey);
147
151
  validateIdentity(context, msgid);
148
- const hasStableKey = one.defaultValue !== other.defaultValue;
149
- const singular = hasStableKey ? one.defaultValue : msgid;
152
+ const singular = one.defaultValue;
150
153
  const plural = other.defaultValue;
151
154
  if (singular === plural || singular.length === 0 || plural.length === 0) {
152
155
  throw new Error("GNU gettext plural source strings must be distinct and non-empty");
153
156
  }
154
157
  return {
155
158
  context,
156
- kind: hasStableKey ? "pluralDefaults" : "plural",
157
159
  locations: normalizedLocations(variants.flatMap((variant) => variant.locations)),
158
- msgid,
159
160
  namespace,
160
161
  plural,
161
162
  singular,
163
+ sourceKey: msgid,
162
164
  };
163
165
  };
164
166
  const pluralMessages = (entries) => groupedPlurals(entries).map((group) => pluralMessage(group));
@@ -185,40 +187,872 @@ const sourceMessages = (entries) => {
185
187
  };
186
188
  const compareMessages = (left, right) => left.namespace.localeCompare(right.namespace) ||
187
189
  (left.context ?? "").localeCompare(right.context ?? "") ||
188
- left.msgid.localeCompare(right.msgid) ||
189
190
  left.singular.localeCompare(right.singular) ||
190
191
  (left.plural ?? "").localeCompare(right.plural ?? "");
192
+ const inferLocations = (message, sources) => {
193
+ if (message.locations.length > 0) {
194
+ return message;
195
+ }
196
+ const locations = [];
197
+ for (const [file, source] of sources) {
198
+ const index = source.indexOf(message.sourceKey);
199
+ if (index !== -1) {
200
+ locations.push({ file, line: source.slice(0, index).split("\n").length });
201
+ }
202
+ }
203
+ return { ...message, locations };
204
+ };
191
205
  const normalizedSourceFiles = (root, paths) => {
192
206
  const files = paths
193
207
  .map((path) => resolve(root, path))
194
- .filter((path) => {
195
- const projectPath = relative(root, path);
196
- return projectPath !== ".." && !projectPath.startsWith(`..${sep}`) && !isAbsolute(projectPath);
197
- });
208
+ .filter((path) => isPathWithin(root, path));
198
209
  return new Set(files).values().toArray().toSorted((left, right) => left.localeCompare(right));
199
210
  };
200
- const findSourceMessages = async (sourceFiles) => {
211
+ const isStaticKeyWrapper = (key) => STATIC_KEY_WRAPPER_TYPES.has(key.type);
212
+ const unwrapStaticWrapper = (node) => isStaticKeyWrapper(node) ? unwrapStaticWrapper(node.expression) : node;
213
+ const isStaticTranslationKey = (key) => {
214
+ if (key === undefined || key === null) {
215
+ return false;
216
+ }
217
+ if (key.type === "Literal") {
218
+ return typeof key.value === "string";
219
+ }
220
+ if (key.type === "TemplateLiteral") {
221
+ return key.expressions.length === 0;
222
+ }
223
+ if (key.type === "ParenthesizedExpression") {
224
+ return false;
225
+ }
226
+ if (isStaticKeyWrapper(key)) {
227
+ return isStaticTranslationKey(key.expression);
228
+ }
229
+ return false;
230
+ };
231
+ const assertStaticTranslationKey = (key) => {
232
+ if (!isStaticTranslationKey(key)) {
233
+ throw new Error("Translation keys must be string literals");
234
+ }
235
+ };
236
+ const propertyName = (property) => {
237
+ if (!property.computed && property.key.type === "Identifier") {
238
+ return property.key.name;
239
+ }
240
+ return property.key.type === "Literal" && typeof property.key.value === "string"
241
+ ? property.key.value
242
+ : null;
243
+ };
244
+ const assertSupportedOptionProperty = (property) => {
245
+ if (property.type === "SpreadElement") {
246
+ throw new Error("Translation extraction requires explicit option properties");
247
+ }
248
+ const name = propertyName(property);
249
+ if (name === null) {
250
+ throw new Error("Translation extraction requires static option property names");
251
+ }
252
+ if (UNSUPPORTED_PLURAL_OPTION.test(name)) {
253
+ throw new Error("GNU gettext accepts one singular and one plural source string");
254
+ }
255
+ if (STATIC_SOURCE_OPTION_NAMES.has(name)) {
256
+ assertStaticTranslationKey(property.value);
257
+ }
258
+ };
259
+ const assertSupportedOptionObject = (options) => {
260
+ if (options === null || options === undefined) {
261
+ return;
262
+ }
263
+ if (isStaticKeyWrapper(options) && unwrapStaticWrapper(options).type === "ObjectExpression") {
264
+ throw new Error("Translation option objects cannot be wrapped in another expression");
265
+ }
266
+ if (options.type !== "ObjectExpression") {
267
+ throw new Error("Translation option objects must be inline object literals");
268
+ }
269
+ for (const property of options.properties) {
270
+ assertSupportedOptionProperty(property);
271
+ }
272
+ };
273
+ const namedImportedBinding = (path, source) => {
274
+ if (!path.isImportSpecifier() || path.node.importKind === "type") {
275
+ return null;
276
+ }
277
+ const imported = path.node.imported;
278
+ return {
279
+ imported: types.isIdentifier(imported) ? imported.name : imported.value,
280
+ local: path.node.local.name,
281
+ source,
282
+ style: "named",
283
+ };
284
+ };
285
+ const defaultImportedBinding = (path, source) => path.isImportDefaultSpecifier()
286
+ ? { imported: "default", local: path.node.local.name, source, style: "default" }
287
+ : null;
288
+ const namespaceImportedBinding = (path, source) => path.isImportNamespaceSpecifier()
289
+ ? { imported: "*", local: path.node.local.name, source, style: "namespace" }
290
+ : null;
291
+ const importedBinding = (binding) => {
292
+ if (binding === undefined) {
293
+ return null;
294
+ }
295
+ const path = binding.path;
296
+ const declaration = path.parentPath;
297
+ if (!declaration.isImportDeclaration() || declaration.node.importKind === "type") {
298
+ return null;
299
+ }
300
+ const source = declaration.node.source.value;
301
+ return namedImportedBinding(path, source) ??
302
+ defaultImportedBinding(path, source) ??
303
+ namespaceImportedBinding(path, source);
304
+ };
305
+ const babelPropertyName = (property) => {
306
+ const key = property.key;
307
+ if (!property.computed && types.isIdentifier(key)) {
308
+ return key.name;
309
+ }
310
+ return types.isStringLiteral(key) ? key.value : null;
311
+ };
312
+ const isBoundIdentifier = (node, name) => {
313
+ if (types.isIdentifier(node)) {
314
+ return node.name === name;
315
+ }
316
+ if (types.isAssignmentPattern(node)) {
317
+ return types.isIdentifier(node.left) && node.left.name === name;
318
+ }
319
+ return false;
320
+ };
321
+ const isHookPatternBinding = (pattern, name) => {
322
+ if (types.isObjectPattern(pattern)) {
323
+ return pattern.properties.some((property) => types.isObjectProperty(property) &&
324
+ babelPropertyName(property) === "t" &&
325
+ isBoundIdentifier(property.value, name));
326
+ }
327
+ if (types.isArrayPattern(pattern)) {
328
+ return isBoundIdentifier(pattern.elements[0] ?? null, name);
329
+ }
330
+ return false;
331
+ };
332
+ const importedTranslationHook = (scope, call) => {
333
+ if (!types.isIdentifier(call.callee)) {
334
+ return null;
335
+ }
336
+ const imported = importedBinding(scope.getBinding(call.callee.name));
337
+ return imported?.imported === "useTranslation" && TRANSLATION_MODULES.has(imported.source)
338
+ ? imported
339
+ : null;
340
+ };
341
+ const translationHookBinding = (binding) => {
342
+ const path = binding.path;
343
+ if (!path.isVariableDeclarator()) {
344
+ return null;
345
+ }
346
+ const pattern = path.node.id;
347
+ const initializer = path.node.init;
348
+ if (!isHookPatternBinding(pattern, binding.identifier.name) ||
349
+ !types.isCallExpression(initializer)) {
350
+ return null;
351
+ }
352
+ const imported = importedTranslationHook(path.scope, initializer);
353
+ if (imported === null) {
354
+ return null;
355
+ }
356
+ return { call: initializer, isCanonical: imported.local === "useTranslation" };
357
+ };
358
+ const importedTranslationFunctionKind = (imported) => {
359
+ if (imported?.imported !== "t" || !TRANSLATION_MODULES.has(imported.source)) {
360
+ return null;
361
+ }
362
+ return imported.local === "t" ? "canonical" : "alias";
363
+ };
364
+ const hookTranslationFunctionKind = (binding) => {
365
+ if (binding === undefined) {
366
+ return null;
367
+ }
368
+ const hook = translationHookBinding(binding);
369
+ if (hook === null) {
370
+ return null;
371
+ }
372
+ return binding.identifier.name === "t" && hook.isCanonical ? "canonical" : "alias";
373
+ };
374
+ const directTranslationFunctionKind = (scope, name) => {
375
+ const binding = scope.getBinding(name);
376
+ return importedTranslationFunctionKind(importedBinding(binding)) ?? hookTranslationFunctionKind(binding);
377
+ };
378
+ const babelMemberName = (member) => {
379
+ const property = member.property;
380
+ if (member.computed) {
381
+ return types.isStringLiteral(property) ? property.value : null;
382
+ }
383
+ return types.isIdentifier(property) ? property.name : null;
384
+ };
385
+ const isImportedTranslationObject = (scope, object) => {
386
+ if (!types.isIdentifier(object)) {
387
+ return false;
388
+ }
389
+ const imported = importedBinding(scope.getBinding(object.name));
390
+ return imported !== null &&
391
+ TRANSLATION_MODULES.has(imported.source) &&
392
+ (imported.style === "namespace" || (imported.source === "i18next" && imported.imported === "default"));
393
+ };
394
+ const constantVariableDeclarator = (binding) => {
395
+ const path = binding.path;
396
+ const declaration = path.parentPath;
397
+ if (!path.isVariableDeclarator() ||
398
+ !declaration.isVariableDeclaration() ||
399
+ declaration.node.kind !== "const") {
400
+ return null;
401
+ }
402
+ return path;
403
+ };
404
+ const isTranslationHookResultBinding = (binding) => {
405
+ if (binding === undefined) {
406
+ return false;
407
+ }
408
+ const path = constantVariableDeclarator(binding);
409
+ const initializer = path?.node.init;
410
+ return path !== null &&
411
+ types.isIdentifier(path.node.id) &&
412
+ types.isCallExpression(initializer) &&
413
+ importedTranslationHook(path.scope, initializer) !== null;
414
+ };
415
+ const isHookTranslationMember = (scope, member) => {
416
+ if (babelMemberName(member) !== "t") {
417
+ return false;
418
+ }
419
+ const object = member.object;
420
+ if (types.isCallExpression(object)) {
421
+ return importedTranslationHook(scope, object) !== null;
422
+ }
423
+ return types.isIdentifier(object) && isTranslationHookResultBinding(scope.getBinding(object.name));
424
+ };
425
+ const isTranslationMember = (scope, member) => babelMemberName(member) === "t" &&
426
+ (isImportedTranslationObject(scope, member.object) || isHookTranslationMember(scope, member));
427
+ const isDirectTranslationFunction = (scope, node) => types.isIdentifier(node) && directTranslationFunctionKind(scope, node.name) !== null;
428
+ const isTranslationFunctionValue = (scope, node) => {
429
+ if (isDirectTranslationFunction(scope, node)) {
430
+ return true;
431
+ }
432
+ return (types.isMemberExpression(node) || types.isOptionalMemberExpression(node)) &&
433
+ isTranslationMember(scope, node);
434
+ };
435
+ const isTranslationBindCall = (scope, node) => {
436
+ if (!types.isCallExpression(node) || !types.isMemberExpression(node.callee)) {
437
+ return false;
438
+ }
439
+ return babelMemberName(node.callee) === "bind" &&
440
+ isTranslationFunctionValue(scope, node.callee.object);
441
+ };
442
+ const isTranslationObjectPatternAlias = (path, binding) => {
443
+ const pattern = path.node.id;
444
+ const initializer = path.node.init;
445
+ if (!types.isObjectPattern(pattern) ||
446
+ !isHookPatternBinding(pattern, binding.identifier.name) ||
447
+ !types.isIdentifier(initializer)) {
448
+ return false;
449
+ }
450
+ return isImportedTranslationObject(path.scope, initializer) ||
451
+ isTranslationHookResultBinding(path.scope.getBinding(initializer.name));
452
+ };
453
+ const isTranslationAliasBinding = (binding) => {
454
+ if (binding === undefined) {
455
+ return false;
456
+ }
457
+ const path = constantVariableDeclarator(binding);
458
+ if (path === null) {
459
+ return false;
460
+ }
461
+ if (isTranslationObjectPatternAlias(path, binding)) {
462
+ return true;
463
+ }
464
+ const initializer = path.node.init;
465
+ return types.isIdentifier(path.node.id) &&
466
+ initializer !== null &&
467
+ initializer !== undefined &&
468
+ (isTranslationFunctionValue(path.scope, initializer) || isTranslationBindCall(path.scope, initializer));
469
+ };
470
+ const translationFunctionKind = (scope, name) => {
471
+ const direct = directTranslationFunctionKind(scope, name);
472
+ if (direct !== null) {
473
+ return direct;
474
+ }
475
+ return isTranslationAliasBinding(scope.getBinding(name)) ? "alias" : null;
476
+ };
477
+ const translationElementKind = (path, name) => {
478
+ const imported = importedBinding(path.scope.getBinding(name));
479
+ if (imported?.source !== "@gtkx/i18n" || !TRANS_ELEMENTS.has(imported.imported)) {
480
+ return null;
481
+ }
482
+ return imported.local === imported.imported ? "canonical" : "alias";
483
+ };
484
+ const nodeStart = (path) => {
485
+ const start = path.node.start;
486
+ if (start === null || start === undefined) {
487
+ throw new Error("Translation extraction could not locate a source expression");
488
+ }
489
+ return start;
490
+ };
491
+ const registerSourceMask = (node, references) => {
492
+ const { start, end } = node;
493
+ if (start === null || start === undefined || end === null || end === undefined) {
494
+ throw new Error("Translation extraction could not locate a source expression");
495
+ }
496
+ references.masks.push({ start, end });
497
+ };
498
+ const sourceLocationKey = (line, column) => `${String(line)}:${String(column)}`;
499
+ const sourcePoint = (node) => {
500
+ const location = node.loc?.start;
501
+ return location === undefined ? null : { column: location.column, line: location.line };
502
+ };
503
+ const registerSourceLocation = (node, references) => {
504
+ const point = sourcePoint(node);
505
+ if (point !== null) {
506
+ references.locations.add(sourceLocationKey(point.line, point.column));
507
+ }
508
+ return point;
509
+ };
510
+ const babelStaticKey = (node) => {
511
+ if (node === null || node === undefined) {
512
+ return null;
513
+ }
514
+ if (types.isStringLiteral(node)) {
515
+ return node.value;
516
+ }
517
+ if (types.isTemplateLiteral(node) && node.expressions.length === 0) {
518
+ return node.quasis[0]?.value.cooked ?? null;
519
+ }
520
+ if (types.isParenthesizedExpression(node) ||
521
+ types.isTSAsExpression(node) ||
522
+ types.isTSSatisfiesExpression(node) ||
523
+ types.isTSTypeAssertion(node) ||
524
+ types.isTSNonNullExpression(node)) {
525
+ return babelStaticKey(node.expression);
526
+ }
527
+ return null;
528
+ };
529
+ const babelObjectExpression = (node) => {
530
+ if (node === null || node === undefined) {
531
+ return null;
532
+ }
533
+ if (types.isObjectExpression(node)) {
534
+ return node;
535
+ }
536
+ if (types.isParenthesizedExpression(node) ||
537
+ types.isTSAsExpression(node) ||
538
+ types.isTSSatisfiesExpression(node) ||
539
+ types.isTSTypeAssertion(node) ||
540
+ types.isTSNonNullExpression(node)) {
541
+ return babelObjectExpression(node.expression);
542
+ }
543
+ return null;
544
+ };
545
+ const babelNamedProperty = (object, name) => {
546
+ if (object === null) {
547
+ return null;
548
+ }
549
+ for (const property of object.properties) {
550
+ if (types.isObjectProperty(property) && babelPropertyName(property) === name) {
551
+ return property;
552
+ }
553
+ }
554
+ return null;
555
+ };
556
+ const babelStringProperty = (object, name) => {
557
+ const property = babelNamedProperty(object, name);
558
+ if (property === null) {
559
+ return null;
560
+ }
561
+ const value = babelStaticKey(property.value);
562
+ if (value === null) {
563
+ throw new Error(`Translation ${name} values must be string literals`);
564
+ }
565
+ return value;
566
+ };
567
+ const callOptions = (call) => babelObjectExpression(call.arguments[1]) ?? babelObjectExpression(call.arguments[2]);
568
+ const hookKeyPrefix = (callee) => {
569
+ const binding = callee.scope.getBinding(callee.node.name);
570
+ const hook = binding === undefined ? null : translationHookBinding(binding);
571
+ return babelStringProperty(hook === null ? null : babelObjectExpression(hook.call.arguments[1]), "keyPrefix") ?? "";
572
+ };
573
+ const prefixedTranslationKey = (prefix, key) => {
574
+ if (prefix.length === 0) {
575
+ return key;
576
+ }
577
+ return prefix.endsWith(".") ? `${prefix}${key}` : `${prefix}.${key}`;
578
+ };
579
+ const extractedEntryKey = (call, keyPrefix) => {
580
+ const key = babelStaticKey(call.arguments[0]);
581
+ if (key === null) {
582
+ return null;
583
+ }
584
+ const options = callOptions(call);
585
+ const callPrefix = babelStringProperty(options, "keyPrefix");
586
+ if (callPrefix === "" && keyPrefix.length > 0) {
587
+ throw new Error("An empty call keyPrefix cannot override a hook keyPrefix during extraction");
588
+ }
589
+ const selectedPrefix = callPrefix ?? keyPrefix;
590
+ const prefixed = prefixedTranslationKey(selectedPrefix, key);
591
+ const context = babelStringProperty(options, "context");
592
+ return context === null ? prefixed : `${prefixed}${CONTEXT_SEPARATOR}${context}`;
593
+ };
594
+ const registerEntryLocation = (key, point, references) => {
595
+ if (key === null || point === null) {
596
+ return;
597
+ }
598
+ const locations = references.entryLocations.get(key) ?? [];
599
+ locations.push(point);
600
+ references.entryLocations.set(key, locations);
601
+ };
602
+ const registerCallReference = (callPath, references, keyPrefix) => {
603
+ references.calls.add(nodeStart(callPath));
604
+ const firstArgument = callPath.node.arguments[0];
605
+ const point = registerSourceLocation(firstArgument ?? callPath.node, references);
606
+ registerEntryLocation(extractedEntryKey(callPath.node, keyPrefix), point, references);
607
+ };
608
+ const parserPlugins = (lang) => [
609
+ "decorators",
610
+ ...(lang === "ts" || lang === "tsx" ? ["typescript"] : []),
611
+ ...(lang === "jsx" || lang === "tsx" ? ["jsx"] : []),
612
+ ];
613
+ const registerIdentifierTranslationCall = (callPath, callee, references) => {
614
+ if (!callee.isIdentifier()) {
615
+ return;
616
+ }
617
+ const kind = translationFunctionKind(callee.scope, callee.node.name);
618
+ if (kind === "alias") {
619
+ throw new Error("Translation calls must use the imported name t");
620
+ }
621
+ if (kind === "canonical") {
622
+ registerCallReference(callPath, references, hookKeyPrefix(callee));
623
+ }
624
+ else if (callee.node.name === "t") {
625
+ registerSourceMask(callee.node, references);
626
+ }
627
+ };
628
+ const registerTranslationCall = (callPath, references) => {
629
+ assertSupportedWrappedCallee(callPath);
630
+ const callee = callPath.get("callee");
631
+ if (callee.isIdentifier()) {
632
+ registerIdentifierTranslationCall(callPath, callee, references);
633
+ return;
634
+ }
635
+ if (callee.isMemberExpression() && isTranslationMember(callee.scope, callee.node)) {
636
+ throw new Error("Translation calls must use the named t export");
637
+ }
638
+ };
639
+ const unwrapTranslationCallee = (node) => {
640
+ if (types.isParenthesizedExpression(node) ||
641
+ types.isTSAsExpression(node) ||
642
+ types.isTSSatisfiesExpression(node) ||
643
+ types.isTSTypeAssertion(node) ||
644
+ types.isTSNonNullExpression(node)) {
645
+ return unwrapTranslationCallee(node.expression);
646
+ }
647
+ return node;
648
+ };
649
+ const isTranslationCallee = (scope, node) => {
650
+ if (types.isIdentifier(node)) {
651
+ return translationFunctionKind(scope, node.name) !== null;
652
+ }
653
+ return (types.isMemberExpression(node) || types.isOptionalMemberExpression(node)) &&
654
+ isTranslationMember(scope, node);
655
+ };
656
+ const assertSupportedWrappedCallee = (callPath) => {
657
+ const callee = callPath.node.callee;
658
+ const unwrapped = unwrapTranslationCallee(callee);
659
+ if (unwrapped !== callee && isTranslationCallee(callPath.scope, unwrapped)) {
660
+ throw new Error("Translation call expressions cannot wrap their callee");
661
+ }
662
+ };
663
+ const assertSupportedOptionalCall = (callPath) => {
664
+ const callee = unwrapTranslationCallee(callPath.node.callee);
665
+ if (isTranslationCallee(callPath.scope, callee)) {
666
+ throw new Error("Translation calls cannot use optional chaining");
667
+ }
668
+ };
669
+ const assertUnsupportedTranslationTag = (tagPath) => {
670
+ const tag = unwrapTranslationCallee(tagPath.node.tag);
671
+ if (isTranslationCallee(tagPath.scope, tag)) {
672
+ throw new Error("Translation calls cannot use tagged-template syntax");
673
+ }
674
+ };
675
+ const registerUnrecognizedElementMasks = (elementPath, name, references) => {
676
+ registerSourceMask(name.node, references);
677
+ const parent = elementPath.parentPath.node;
678
+ const closingName = types.isJSXElement(parent) ? parent.closingElement?.name : null;
679
+ if (types.isJSXIdentifier(closingName)) {
680
+ registerSourceMask(closingName, references);
681
+ }
682
+ };
683
+ const registerTranslationElement = (elementPath, references) => {
684
+ const name = elementPath.get("name");
685
+ if (!name.isJSXIdentifier()) {
686
+ return;
687
+ }
688
+ const kind = translationElementKind(name, name.node.name);
689
+ if (kind === "alias") {
690
+ throw new Error("Translation components must use their imported names");
691
+ }
692
+ if (kind === "canonical") {
693
+ references.elements.add(nodeStart(elementPath));
694
+ registerSourceLocation(elementPath.node, references);
695
+ }
696
+ else if (TRANS_ELEMENTS.has(name.node.name)) {
697
+ registerUnrecognizedElementMasks(elementPath, name, references);
698
+ }
699
+ };
700
+ const maskUnrecognizedTranslations = (source, references) => {
701
+ let masked = source;
702
+ const masks = references.masks.toSorted((left, right) => right.start - left.start);
703
+ for (const { start, end } of masks) {
704
+ masked = `${masked.slice(0, start)}${"_".repeat(end - start)}${masked.slice(end)}`;
705
+ }
706
+ return masked;
707
+ };
708
+ const translationReferences = (path, source, lang) => {
709
+ const parsed = parseBabelSync(source, {
710
+ ast: true,
711
+ babelrc: false,
712
+ configFile: false,
713
+ filename: path,
714
+ parserOpts: { createParenthesizedExpressions: true, plugins: parserPlugins(lang) },
715
+ sourceType: "module",
716
+ });
717
+ if (parsed === null) {
718
+ throw new Error(`Translation extraction could not parse ${path}`);
719
+ }
720
+ const references = {
721
+ calls: new Set(),
722
+ elements: new Set(),
723
+ entryLocations: new Map(),
724
+ locations: new Set(),
725
+ masks: [],
726
+ };
727
+ traverse(parsed, {
728
+ CallExpression(callPath) {
729
+ registerTranslationCall(callPath, references);
730
+ },
731
+ JSXOpeningElement(elementPath) {
732
+ registerTranslationElement(elementPath, references);
733
+ },
734
+ OptionalCallExpression(callPath) {
735
+ assertSupportedOptionalCall(callPath);
736
+ },
737
+ TaggedTemplateExpression(tagPath) {
738
+ assertUnsupportedTranslationTag(tagPath);
739
+ },
740
+ });
741
+ return references;
742
+ };
743
+ const assertSupportedTranslationCall = (node, references) => {
744
+ if (!references.calls.has(node.start)) {
745
+ return;
746
+ }
747
+ assertStaticTranslationKey(node.arguments[0]);
748
+ assertSupportedTranslationOptions(node.arguments[1], node.arguments[2]);
749
+ };
750
+ const assertSupportedTranslationOptions = (second, third) => {
751
+ if (third !== undefined && third !== null) {
752
+ assertStaticTranslationKey(second);
753
+ assertSupportedOptionObject(third);
754
+ return;
755
+ }
756
+ if (second === undefined || second === null || isStaticTranslationKey(second)) {
757
+ return;
758
+ }
759
+ assertSupportedOptionObject(second);
760
+ };
761
+ const isNamedJsxAttribute = (attribute, name) => attribute.name.type === "JSXIdentifier" && attribute.name.name === name;
762
+ const assertSupportedTransKey = (attribute) => {
763
+ if (!isNamedJsxAttribute(attribute, "i18nKey")) {
764
+ return;
765
+ }
766
+ const key = attribute.value?.type === "JSXExpressionContainer"
767
+ ? attribute.value.expression
768
+ : attribute.value;
769
+ assertStaticTranslationKey(key);
770
+ };
771
+ const assertSupportedTransStringAttribute = (attribute, name) => {
772
+ if (!isNamedJsxAttribute(attribute, name)) {
773
+ return;
774
+ }
775
+ const value = attribute.value?.type === "JSXExpressionContainer"
776
+ ? attribute.value.expression
777
+ : attribute.value;
778
+ assertStaticTranslationKey(value);
779
+ };
780
+ const assertSupportedTransOptions = (attribute) => {
781
+ if (isNamedJsxAttribute(attribute, "tOptions") && attribute.value?.type === "JSXExpressionContainer") {
782
+ assertSupportedOptionObject(attribute.value.expression);
783
+ }
784
+ };
785
+ const assertSupportedTransAttribute = (attribute) => {
786
+ if (attribute.type === "JSXSpreadAttribute") {
787
+ throw new Error("Translation extraction requires explicit component properties");
788
+ }
789
+ assertSupportedTransKey(attribute);
790
+ assertSupportedTransStringAttribute(attribute, "context");
791
+ assertSupportedTransStringAttribute(attribute, "defaults");
792
+ assertSupportedTransOptions(attribute);
793
+ };
794
+ const assertSupportedTransElement = (node, references) => {
795
+ if (!references.elements.has(node.start)) {
796
+ return;
797
+ }
798
+ for (const attribute of node.attributes) {
799
+ assertSupportedTransAttribute(attribute);
800
+ }
801
+ };
802
+ const assertSupportedTranslationSyntax = (path, source) => {
803
+ const lang = sourceLanguage(path);
804
+ if (lang === undefined) {
805
+ return { calls: new Set(), elements: new Set(), entryLocations: new Map(), locations: new Set(), masks: [] };
806
+ }
807
+ const parsed = parseSync(path, source, { lang });
808
+ const references = translationReferences(path, source, lang);
809
+ new Visitor({
810
+ CallExpression(node) {
811
+ assertSupportedTranslationCall(node, references);
812
+ },
813
+ JSXOpeningElement(node) {
814
+ assertSupportedTransElement(node, references);
815
+ },
816
+ }).visit(parsed.program);
817
+ return references;
818
+ };
819
+ const extractedLocationFile = (root, file) => resolve(root, file);
820
+ const isRecognizedLocation = (root, references, location) => {
821
+ if (location.line === undefined || location.column === undefined) {
822
+ return false;
823
+ }
824
+ const sourceReferences = references.get(extractedLocationFile(root, location.file));
825
+ return sourceReferences?.locations.has(sourceLocationKey(location.line, location.column)) === true;
826
+ };
827
+ const recognizedKeyLocations = (references, extractedKey) => {
828
+ const locations = [];
829
+ for (const [file, sourceReferences] of references) {
830
+ const points = sourceReferences.entryLocations.get(extractedKey) ?? [];
831
+ for (const point of points) {
832
+ locations.push({ file, column: point.column, line: point.line });
833
+ }
834
+ }
835
+ return locations;
836
+ };
837
+ const recognizedEntry = (root, references, entry) => {
838
+ const extractedLocations = entry.locations ?? [];
839
+ const locations = extractedLocations.length === 0
840
+ ? recognizedKeyLocations(references, entry.key)
841
+ : extractedLocations.filter((location) => isRecognizedLocation(root, references, location));
842
+ return locations.length === 0 ? null : { ...entry, locations };
843
+ };
844
+ const quotedNestedReferenceParts = (content, quote) => {
845
+ const end = content.indexOf(quote, 1);
846
+ return end === -1
847
+ ? null
848
+ : { base: content.slice(1, end), options: content.slice(end + 1) };
849
+ };
850
+ const nestedReferenceParts = (value) => {
851
+ const content = value.trim();
852
+ const quote = content[0];
853
+ if (quote === "\"" || quote === "'") {
854
+ return quotedNestedReferenceParts(content, quote);
855
+ }
856
+ const separator = content.indexOf(",");
857
+ const base = (separator === -1 ? content : content.slice(0, separator)).trim();
858
+ return base.length === 0
859
+ ? null
860
+ : { base, options: separator === -1 ? "" : content.slice(separator + 1) };
861
+ };
862
+ const nestedReferenceContext = (options) => {
863
+ const match = NESTED_CONTEXT.exec(options);
864
+ const context = match?.[1] ?? match?.[2] ?? null;
865
+ return context === null || context.length === 0 ? null : context;
866
+ };
867
+ const adjustedParenthesisDepth = (character, depth) => {
868
+ if (character === "(") {
869
+ return depth + 1;
870
+ }
871
+ return character === ")" ? depth - 1 : depth;
872
+ };
873
+ const nestedReferenceEnd = (text, start) => {
874
+ let depth = 0;
875
+ const tokens = text.slice(start).matchAll(NESTED_STRUCTURE_TOKEN);
876
+ for (const token of tokens) {
877
+ const character = token[0];
878
+ if (character === ")" && depth === 0) {
879
+ return start + token.index;
880
+ }
881
+ depth = adjustedParenthesisDepth(character, depth);
882
+ }
883
+ return -1;
884
+ };
885
+ const nestedReferenceContents = (text) => {
886
+ const contents = [];
887
+ let offset = 0;
888
+ while (offset < text.length) {
889
+ const prefix = text.indexOf("$t(", offset);
890
+ if (prefix === -1) {
891
+ break;
892
+ }
893
+ const start = prefix + 3;
894
+ const end = nestedReferenceEnd(text, start);
895
+ if (end === -1) {
896
+ break;
897
+ }
898
+ contents.push(text.slice(start, end));
899
+ offset = end + 1;
900
+ }
901
+ return contents;
902
+ };
903
+ const nestedPluralKeys = (base, context) => {
904
+ const pluralBase = context === null ? base : `${base}${CONTEXT_SEPARATOR}${context}`;
905
+ return [`${pluralBase}_one`, `${pluralBase}_other`];
906
+ };
907
+ const nestedReferenceKeys = (content) => {
908
+ const parts = nestedReferenceParts(content);
909
+ if (parts === null) {
910
+ return [];
911
+ }
912
+ const context = nestedReferenceContext(parts.options);
913
+ const contextual = context === null
914
+ ? []
915
+ : [`${parts.base}_${context}`, `${parts.base}${CONTEXT_SEPARATOR}${context}`];
916
+ return NESTED_COUNT.test(parts.options)
917
+ ? [parts.base, ...contextual, ...nestedPluralKeys(parts.base, context)]
918
+ : [parts.base, ...contextual];
919
+ };
920
+ const nestedEntryKeys = (text) => {
921
+ const keys = new Set();
922
+ for (const content of nestedReferenceContents(text)) {
923
+ for (const key of nestedReferenceKeys(content)) {
924
+ keys.add(key);
925
+ }
926
+ }
927
+ return keys;
928
+ };
929
+ const registerNestedKeyLocations = (root, references, key, locations) => {
930
+ for (const location of locations) {
931
+ if (location.line === undefined || location.column === undefined) {
932
+ continue;
933
+ }
934
+ const sourceReferences = references.get(resolve(root, location.file));
935
+ if (sourceReferences !== undefined) {
936
+ registerEntryLocation(key, { column: location.column, line: location.line }, sourceReferences);
937
+ }
938
+ }
939
+ };
940
+ const registerNestedTextLocations = (root, references, text, locations) => {
941
+ for (const key of nestedEntryKeys(text)) {
942
+ registerNestedKeyLocations(root, references, key, locations);
943
+ }
944
+ };
945
+ const registerNestedEntryLocations = (root, references, entry, locations) => {
946
+ registerNestedTextLocations(root, references, entry.key, locations);
947
+ if (typeof entry.defaultValue === "string") {
948
+ registerNestedTextLocations(root, references, entry.defaultValue, locations);
949
+ }
950
+ };
951
+ const didRegisterNestedLocationPass = (root, references, entries, processed) => {
952
+ let didRegister = false;
953
+ for (const [mapKey, entry] of entries) {
954
+ if (processed.has(mapKey)) {
955
+ continue;
956
+ }
957
+ const recognized = recognizedEntry(root, references, entry);
958
+ if (recognized !== null) {
959
+ processed.add(mapKey);
960
+ registerNestedEntryLocations(root, references, entry, recognized.locations ?? []);
961
+ didRegister = true;
962
+ }
963
+ }
964
+ return didRegister;
965
+ };
966
+ const registerNestedLocations = (root, references, entries) => {
967
+ const processed = new Set();
968
+ let hasRegisteredLocations = true;
969
+ while (hasRegisteredLocations) {
970
+ hasRegisteredLocations = didRegisterNestedLocationPass(root, references, entries, processed);
971
+ }
972
+ };
973
+ const retainRecognizedEntries = (root, references, entries) => {
974
+ for (const [mapKey, entry] of entries) {
975
+ const recognized = recognizedEntry(root, references, entry);
976
+ if (recognized === null) {
977
+ entries.delete(mapKey);
978
+ }
979
+ else {
980
+ entries.set(mapKey, recognized);
981
+ }
982
+ }
983
+ };
984
+ const fileSourcePointKey = (file, line, column) => `${file}\0${sourceLocationKey(line, column)}`;
985
+ const registerExtractedSourcePoint = (root, points, location) => {
986
+ if (location.line !== undefined && location.column !== undefined) {
987
+ points.add(fileSourcePointKey(resolve(root, location.file), location.line, location.column));
988
+ }
989
+ };
990
+ const extractedSourcePoints = (root, entries) => {
991
+ const points = new Set();
992
+ for (const entry of entries.values()) {
993
+ const locations = entry.locations ?? [];
994
+ for (const location of locations) {
995
+ registerExtractedSourcePoint(root, points, location);
996
+ }
997
+ }
998
+ return points;
999
+ };
1000
+ const hasMissingSourcePoint = (file, references, extracted) => references.locations.values().some((location) => !extracted.has(`${file}\0${location}`));
1001
+ const assertAllReferencesExtracted = (root, references, entries) => {
1002
+ const extracted = extractedSourcePoints(root, entries);
1003
+ for (const [file, sourceReferences] of references) {
1004
+ if (hasMissingSourcePoint(file, sourceReferences, extracted)) {
1005
+ throw new Error("A translation expression could not be extracted safely");
1006
+ }
1007
+ }
1008
+ };
1009
+ const findSourceMessages = async (root, sourceFiles) => {
201
1010
  if (sourceFiles.length === 0) {
1011
+ clearI18nResources(root);
202
1012
  return [];
203
1013
  }
204
- const fileErrors = [];
1014
+ const sources = new Map(sourceFiles.map((file) => [file, readFileSync(file, "utf8")]));
1015
+ const references = new Map();
1016
+ for (const [file, source] of sources) {
1017
+ references.set(file, assertSupportedTranslationSyntax(file, source));
1018
+ }
1019
+ let extracted;
205
1020
  const { logger, reports } = quietLogger();
206
- const { allKeys } = await findKeys(extractorConfig(sourceFiles), logger, fileErrors);
207
- if (fileErrors.length > 0 || reports.length > 0) {
208
- throw new Error([...fileErrors, ...reports].join("\n"));
1021
+ const capture = {
1022
+ name: "gtkx-gettext",
1023
+ onLoad(code, path) {
1024
+ const sourceReferences = references.get(resolve(root, path));
1025
+ return sourceReferences === undefined
1026
+ ? code
1027
+ : maskUnrecognizedTranslations(code, sourceReferences);
1028
+ },
1029
+ onEnd(keys) {
1030
+ registerNestedLocations(root, references, keys);
1031
+ retainRecognizedEntries(root, references, keys);
1032
+ assertAllReferencesExtracted(root, references, keys);
1033
+ extracted = keys;
1034
+ },
1035
+ };
1036
+ const result = await runExtractor(i18nToolkitConfig(root, sourceFiles, [capture]), {
1037
+ logger,
1038
+ quiet: true,
1039
+ syncPrimaryWithDefaults: true,
1040
+ trustDerivedDefaults: true,
1041
+ });
1042
+ if (extracted === undefined || reports.length > 0 || result.hasErrors) {
1043
+ throw new Error(reports.join("\n") || "i18next extraction failed");
209
1044
  }
210
- return sourceMessages(allKeys.values().toArray()).toSorted(compareMessages);
1045
+ return sourceMessages(extracted.values().toArray())
1046
+ .map((message) => inferLocations(message, sources))
1047
+ .toSorted(compareMessages);
211
1048
  };
212
1049
  const projectPath = (root, path) => {
213
1050
  const absolute = isAbsolute(path) ? resolve(path) : resolve(root, path);
214
1051
  const projectRelative = relative(root, absolute);
215
- if (projectRelative === "" ||
216
- projectRelative === ".." ||
217
- projectRelative.startsWith(`..${sep}`) ||
218
- isAbsolute(projectRelative)) {
1052
+ if (!isPathInside(root, absolute)) {
219
1053
  return null;
220
1054
  }
221
- return projectRelative.replaceAll("\\", "/");
1055
+ return toPosixPath(projectRelative);
222
1056
  };
223
1057
  const writePotfiles = (project, sourceFiles) => {
224
1058
  const paths = sourceFiles
@@ -241,7 +1075,6 @@ const renderCatalogCall = (message) => {
241
1075
  ? `gettext(${msgid});`
242
1076
  : `pgettext(${JSON.stringify(message.context)}, ${msgid});`;
243
1077
  };
244
- const readSources = (sourceFiles) => new Map(sourceFiles.map((path) => [path, readFileSync(path, "utf8")]));
245
1078
  const locatedOwners = (project, message) => {
246
1079
  const owners = [];
247
1080
  for (const location of message.locations) {
@@ -253,30 +1086,14 @@ const locatedOwners = (project, message) => {
253
1086
  const unique = new Map(owners.map((owner) => [`${owner.path}\0${String(owner.line)}`, owner]));
254
1087
  return unique.values().toArray();
255
1088
  };
256
- const inferredOwner = (project, message, sources) => {
257
- for (const [path, source] of sources) {
258
- const index = source.indexOf(message.msgid);
259
- if (index !== -1) {
260
- return {
261
- path: projectPath(project.root, path) ?? SYNTHETIC_FILENAME,
262
- line: source.slice(0, index).split("\n").length,
263
- };
264
- }
265
- }
266
- return null;
267
- };
268
- const sourceOwners = (project, message, sources) => {
1089
+ const sourceOwners = (project, message) => {
269
1090
  const located = locatedOwners(project, message);
270
- if (located.length > 0) {
271
- return located;
272
- }
273
- return [inferredOwner(project, message, sources) ?? { path: SYNTHETIC_FILENAME, line: undefined }];
1091
+ return located.length > 0 ? located : [{ path: SYNTHETIC_FILENAME, line: undefined }];
274
1092
  };
275
- const syntheticEntries = (project, messages, sourceFiles) => {
276
- const sources = readSources(sourceFiles);
1093
+ const syntheticEntries = (project, messages) => {
277
1094
  const entries = new Map();
278
1095
  for (const message of messages) {
279
- for (const owner of sourceOwners(project, message, sources)) {
1096
+ for (const owner of sourceOwners(project, message)) {
280
1097
  const owned = entries.get(owner.path) ?? [];
281
1098
  owned.push({ call: renderCatalogCall(message), line: owner.line });
282
1099
  entries.set(owner.path, owned);
@@ -314,8 +1131,8 @@ const renderSyntheticSource = (entries) => {
314
1131
  }
315
1132
  return `${lines.join("\n")}\n`;
316
1133
  };
317
- const writeSyntheticSources = (workDir, project, messages, sourceFiles) => {
318
- const entries = syntheticEntries(project, messages, sourceFiles);
1134
+ const writeSyntheticSources = (workDir, project, messages) => {
1135
+ const entries = syntheticEntries(project, messages);
319
1136
  const paths = [];
320
1137
  for (const [path, owned] of entries) {
321
1138
  const target = join(workDir, path);
@@ -327,8 +1144,8 @@ const writeSyntheticSources = (workDir, project, messages, sourceFiles) => {
327
1144
  writeFileSync(potfiles, `${paths.toSorted((left, right) => left.localeCompare(right)).join("\n")}\n`);
328
1145
  return potfiles;
329
1146
  };
330
- const extractSourceMessages = ({ project, messages, sourceFiles, output, workDir }) => {
331
- const potfilesPath = writeSyntheticSources(workDir, project, messages, sourceFiles);
1147
+ const extractSourceMessages = ({ project, messages, output, workDir }) => {
1148
+ const potfilesPath = writeSyntheticSources(workDir, project, messages);
332
1149
  runCliTool({
333
1150
  tool: "xgettext",
334
1151
  args: [
@@ -365,7 +1182,7 @@ const joinMetadataFragment = (output, fragment) => {
365
1182
  target: output,
366
1183
  });
367
1184
  };
368
- const extractCatalogTemplate = ({ project, messages, sourceFiles, shouldPreserveMetadataMessages, output = resolve(project.poDir, `${project.domain}.pot`), }) => {
1185
+ const extractCatalogTemplate = ({ project, messages, shouldPreserveMetadataMessages, output = resolve(project.poDir, `${project.domain}.pot`), }) => {
369
1186
  const workDir = mkdtempSync(join(project.poDir, ".gtkx-i18n-"));
370
1187
  const source = join(workDir, "source.pot");
371
1188
  const hasPreviousTemplate = existsSync(output);
@@ -373,11 +1190,11 @@ const extractCatalogTemplate = ({ project, messages, sourceFiles, shouldPreserve
373
1190
  if (shouldPreserveMetadataMessages && hasPreviousTemplate) {
374
1191
  const fragment = join(workDir, "metadata.pot");
375
1192
  extractMetadataFragment(project, output, fragment);
376
- extractSourceMessages({ project, messages, sourceFiles, output: source, workDir });
1193
+ extractSourceMessages({ project, messages, output: source, workDir });
377
1194
  joinMetadataFragment(source, fragment);
378
1195
  }
379
1196
  else {
380
- extractSourceMessages({ project, messages, sourceFiles, output: source, workDir });
1197
+ extractSourceMessages({ project, messages, output: source, workDir });
381
1198
  }
382
1199
  replaceCatalogTemplate(source, output);
383
1200
  }
@@ -387,17 +1204,15 @@ const extractCatalogTemplate = ({ project, messages, sourceFiles, shouldPreserve
387
1204
  };
388
1205
  const extractSourceCatalogTo = async (project, paths, output) => {
389
1206
  const sourceFiles = normalizedSourceFiles(project.root, paths);
390
- const messages = await findSourceMessages(sourceFiles);
1207
+ const messages = await findSourceMessages(project.root, sourceFiles);
391
1208
  writePotfiles(project, sourceFiles);
392
- extractCatalogTemplate({ project, messages, sourceFiles, shouldPreserveMetadataMessages: false, output });
393
- return { messages, sourceFiles };
1209
+ extractCatalogTemplate({ project, messages, shouldPreserveMetadataMessages: false, output });
394
1210
  };
395
1211
  const extractSourceCatalog = async (project, paths, shouldPreserveMetadataMessages = true) => {
396
1212
  const sourceFiles = normalizedSourceFiles(project.root, paths);
397
- const messages = await findSourceMessages(sourceFiles);
1213
+ const messages = await findSourceMessages(project.root, sourceFiles);
398
1214
  writePotfiles(project, sourceFiles);
399
- extractCatalogTemplate({ project, messages, sourceFiles, shouldPreserveMetadataMessages });
400
- return { messages, sourceFiles };
1215
+ extractCatalogTemplate({ project, messages, shouldPreserveMetadataMessages });
401
1216
  };
402
1217
  export { extractSourceCatalog, extractSourceCatalogTo };
403
1218
  //# sourceMappingURL=source-messages.js.map