@gtkx/cli 2.0.0-beta.1 → 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 (165) hide show
  1. package/dist/builder.d.ts +1 -0
  2. package/dist/builder.d.ts.map +1 -1
  3. package/dist/builder.js +17 -5
  4. package/dist/builder.js.map +1 -1
  5. package/dist/cli.js +2 -0
  6. package/dist/cli.js.map +1 -1
  7. package/dist/codegen/run-codegen.d.ts +4 -2
  8. package/dist/codegen/run-codegen.d.ts.map +1 -1
  9. package/dist/codegen/run-codegen.js +13 -8
  10. package/dist/codegen/run-codegen.js.map +1 -1
  11. package/dist/codegen/store-resolver.d.ts +1 -1
  12. package/dist/codegen/store-resolver.d.ts.map +1 -1
  13. package/dist/codegen/store-resolver.js +2 -2
  14. package/dist/codegen/store-resolver.js.map +1 -1
  15. package/dist/commands/build.d.ts +5 -0
  16. package/dist/commands/build.d.ts.map +1 -1
  17. package/dist/commands/build.js +83 -10
  18. package/dist/commands/build.js.map +1 -1
  19. package/dist/commands/codegen.d.ts +1 -0
  20. package/dist/commands/codegen.d.ts.map +1 -1
  21. package/dist/commands/codegen.js +6 -5
  22. package/dist/commands/codegen.js.map +1 -1
  23. package/dist/commands/deploy.d.ts +1 -0
  24. package/dist/commands/deploy.d.ts.map +1 -1
  25. package/dist/commands/deploy.js +4 -2
  26. package/dist/commands/deploy.js.map +1 -1
  27. package/dist/commands/dev.d.ts +8 -0
  28. package/dist/commands/dev.d.ts.map +1 -1
  29. package/dist/commands/dev.js +19 -1
  30. package/dist/commands/dev.js.map +1 -1
  31. package/dist/deploy/freedesktop/metainfo.d.ts.map +1 -1
  32. package/dist/deploy/freedesktop/metainfo.js +41 -2
  33. package/dist/deploy/freedesktop/metainfo.js.map +1 -1
  34. package/dist/deploy/nfpm/config.d.ts.map +1 -1
  35. package/dist/deploy/nfpm/config.js +5 -2
  36. package/dist/deploy/nfpm/config.js.map +1 -1
  37. package/dist/deploy/nfpm/contents.d.ts.map +1 -1
  38. package/dist/deploy/nfpm/contents.js +8 -0
  39. package/dist/deploy/nfpm/contents.js.map +1 -1
  40. package/dist/deploy/node-runtime/elf.d.ts +2 -1
  41. package/dist/deploy/node-runtime/elf.d.ts.map +1 -1
  42. package/dist/deploy/node-runtime/elf.js +32 -5
  43. package/dist/deploy/node-runtime/elf.js.map +1 -1
  44. package/dist/deploy/node-runtime/index.d.ts +2 -1
  45. package/dist/deploy/node-runtime/index.d.ts.map +1 -1
  46. package/dist/deploy/node-runtime/index.js +73 -4
  47. package/dist/deploy/node-runtime/index.js.map +1 -1
  48. package/dist/deploy/notices/node-runtime.js +2 -2
  49. package/dist/deploy/notices/node-runtime.js.map +1 -1
  50. package/dist/deploy/payload/launcher.d.ts.map +1 -1
  51. package/dist/deploy/payload/launcher.js +14 -1
  52. package/dist/deploy/payload/launcher.js.map +1 -1
  53. package/dist/deploy/payload/stage.js +1 -1
  54. package/dist/deploy/payload/stage.js.map +1 -1
  55. package/dist/deploy/run-deploy.d.ts +1 -0
  56. package/dist/deploy/run-deploy.d.ts.map +1 -1
  57. package/dist/deploy/run-deploy.js +100 -14
  58. package/dist/deploy/run-deploy.js.map +1 -1
  59. package/dist/deploy/settings/build-manifest.d.ts +6 -1
  60. package/dist/deploy/settings/build-manifest.d.ts.map +1 -1
  61. package/dist/deploy/settings/build-manifest.js +15 -4
  62. package/dist/deploy/settings/build-manifest.js.map +1 -1
  63. package/dist/deploy/settings/extra-files.d.ts +1 -1
  64. package/dist/deploy/settings/extra-files.d.ts.map +1 -1
  65. package/dist/deploy/settings/extra-files.js +22 -1
  66. package/dist/deploy/settings/extra-files.js.map +1 -1
  67. package/dist/deploy/settings/index.d.ts +1 -0
  68. package/dist/deploy/settings/index.d.ts.map +1 -1
  69. package/dist/deploy/settings/index.js +2 -1
  70. package/dist/deploy/settings/index.js.map +1 -1
  71. package/dist/deploy/settings/paths.d.ts +2 -1
  72. package/dist/deploy/settings/paths.d.ts.map +1 -1
  73. package/dist/deploy/settings/paths.js +113 -5
  74. package/dist/deploy/settings/paths.js.map +1 -1
  75. package/dist/deploy/targets/flatpak-source.d.ts.map +1 -1
  76. package/dist/deploy/targets/flatpak-source.js +11 -2
  77. package/dist/deploy/targets/flatpak-source.js.map +1 -1
  78. package/dist/deploy/types.d.ts +1 -0
  79. package/dist/deploy/types.d.ts.map +1 -1
  80. package/dist/deploy/types.js.map +1 -1
  81. package/dist/dev/headless.d.ts +3 -0
  82. package/dist/dev/headless.d.ts.map +1 -0
  83. package/dist/dev/headless.js +35 -0
  84. package/dist/dev/headless.js.map +1 -0
  85. package/dist/dev/runner-deps.js +1 -1
  86. package/dist/dev/runner-deps.js.map +1 -1
  87. package/dist/i18n/source-messages.d.ts.map +1 -1
  88. package/dist/i18n/source-messages.js +835 -1
  89. package/dist/i18n/source-messages.js.map +1 -1
  90. package/dist/internal/build-manifest.d.ts +5 -2
  91. package/dist/internal/build-manifest.d.ts.map +1 -1
  92. package/dist/internal/build-manifest.js +15 -2
  93. package/dist/internal/build-manifest.js.map +1 -1
  94. package/dist/internal/build-output.d.ts +8 -0
  95. package/dist/internal/build-output.d.ts.map +1 -0
  96. package/dist/internal/build-output.js +69 -0
  97. package/dist/internal/build-output.js.map +1 -0
  98. package/dist/internal/entry-arg.d.ts +4 -1
  99. package/dist/internal/entry-arg.d.ts.map +1 -1
  100. package/dist/internal/entry-arg.js +7 -1
  101. package/dist/internal/entry-arg.js.map +1 -1
  102. package/dist/internal/output-directory.d.ts +15 -0
  103. package/dist/internal/output-directory.d.ts.map +1 -0
  104. package/dist/internal/output-directory.js +490 -0
  105. package/dist/internal/output-directory.js.map +1 -0
  106. package/dist/internal/prepare-project.d.ts +2 -0
  107. package/dist/internal/prepare-project.d.ts.map +1 -1
  108. package/dist/internal/prepare-project.js +3 -3
  109. package/dist/internal/prepare-project.js.map +1 -1
  110. package/dist/internal/source-imports.js +1 -1
  111. package/dist/internal/source-imports.js.map +1 -1
  112. package/dist/mcp/client.js +2 -2
  113. package/dist/mcp/client.js.map +1 -1
  114. package/dist/vite-plugins/build-manifest.d.ts +5 -1
  115. package/dist/vite-plugins/build-manifest.d.ts.map +1 -1
  116. package/dist/vite-plugins/build-manifest.js +2 -1
  117. package/dist/vite-plugins/build-manifest.js.map +1 -1
  118. package/dist/vite-plugins/i18n.d.ts.map +1 -1
  119. package/dist/vite-plugins/i18n.js +58 -6
  120. package/dist/vite-plugins/i18n.js.map +1 -1
  121. package/dist/vite-plugins/index.d.ts +8 -1
  122. package/dist/vite-plugins/index.d.ts.map +1 -1
  123. package/dist/vite-plugins/index.js +6 -2
  124. package/dist/vite-plugins/index.js.map +1 -1
  125. package/dist/vite-plugins/self-contained.d.ts.map +1 -1
  126. package/dist/vite-plugins/self-contained.js +159 -158
  127. package/dist/vite-plugins/self-contained.js.map +1 -1
  128. package/package.json +9 -9
  129. package/src/builder.ts +18 -5
  130. package/src/cli.ts +3 -0
  131. package/src/codegen/run-codegen.ts +15 -7
  132. package/src/codegen/store-resolver.ts +2 -2
  133. package/src/commands/build.ts +13 -2
  134. package/src/commands/codegen.ts +6 -5
  135. package/src/commands/deploy.ts +4 -2
  136. package/src/commands/dev.ts +20 -1
  137. package/src/deploy/freedesktop/metainfo.ts +73 -21
  138. package/src/deploy/nfpm/config.ts +5 -2
  139. package/src/deploy/nfpm/contents.ts +8 -0
  140. package/src/deploy/node-runtime/elf.ts +43 -5
  141. package/src/deploy/node-runtime/index.ts +105 -5
  142. package/src/deploy/notices/node-runtime.ts +2 -2
  143. package/src/deploy/payload/launcher.ts +20 -1
  144. package/src/deploy/payload/stage.ts +1 -1
  145. package/src/deploy/run-deploy.ts +56 -16
  146. package/src/deploy/settings/build-manifest.ts +28 -3
  147. package/src/deploy/settings/extra-files.ts +26 -2
  148. package/src/deploy/settings/index.ts +3 -1
  149. package/src/deploy/settings/paths.ts +70 -5
  150. package/src/deploy/targets/flatpak-source.ts +13 -2
  151. package/src/deploy/types.ts +1 -0
  152. package/src/dev/headless.ts +40 -0
  153. package/src/dev/runner-deps.ts +1 -1
  154. package/src/i18n/source-messages.ts +1220 -2
  155. package/src/internal/build-manifest.ts +25 -1
  156. package/src/internal/build-output.ts +99 -0
  157. package/src/internal/entry-arg.ts +8 -1
  158. package/src/internal/output-directory.ts +699 -0
  159. package/src/internal/prepare-project.ts +5 -5
  160. package/src/internal/source-imports.ts +1 -1
  161. package/src/mcp/client.ts +2 -2
  162. package/src/vite-plugins/build-manifest.ts +7 -1
  163. package/src/vite-plugins/i18n.ts +86 -5
  164. package/src/vite-plugins/index.ts +14 -7
  165. package/src/vite-plugins/self-contained.ts +184 -185
@@ -1,4 +1,6 @@
1
1
  import type { ExtractedKey, ExtractedKeysMap, Logger, Plugin } from "i18next-cli";
2
+ import type { ESTree } from "vite";
3
+ import { type NodePath, parseSync as parseBabelSync, type Scope, traverse, types } from "@babel/core";
2
4
  import { isPathInside, isPathWithin, toPosixPath } from "@gtkx/utils";
3
5
  import { runExtractor } from "i18next-cli";
4
6
  import {
@@ -10,8 +12,10 @@ import {
10
12
  writeFileSync,
11
13
  } from "node:fs";
12
14
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
15
+ import { parseSync, Visitor } from "vite";
13
16
  import type { CatalogProject } from "./catalogs.js";
14
17
  import { runCliTool } from "../internal/run-cli-tool.js";
18
+ import { sourceLanguage } from "../internal/source-imports.js";
15
19
  import { replaceCatalogTemplate } from "./catalog-template.js";
16
20
  import { metadataTemplateFiles } from "./metadata-templates.js";
17
21
  import { clearI18nResources, i18nToolkitConfig } from "./types.js";
@@ -21,6 +25,7 @@ type SourceLocation = {
21
25
  line?: number | undefined;
22
26
  column?: number | undefined;
23
27
  };
28
+ type ExtractedLocation = NonNullable<ExtractedKey["locations"]>[number];
24
29
 
25
30
  type SourceMessage = {
26
31
  context: string | null;
@@ -62,10 +67,50 @@ type PluralGroup = {
62
67
  variants: PluralVariant[];
63
68
  };
64
69
 
70
+ type TranslationReferences = {
71
+ calls: Set<number>;
72
+ elements: Set<number>;
73
+ entryLocations: Map<string, SourcePoint[]>;
74
+ locations: Set<string>;
75
+ masks: SourceMask[];
76
+ };
77
+ type SourceMask = { end: number; start: number };
78
+ type SourcePoint = { column: number; line: number };
79
+ type TranslationCallKind = "alias" | "canonical";
80
+ type ImportedBinding = {
81
+ imported: string;
82
+ local: string;
83
+ source: string;
84
+ style: "default" | "named" | "namespace";
85
+ };
86
+ type TranslationHookBinding = { call: types.CallExpression; isCanonical: boolean };
87
+ type TranslationMemberExpression = types.MemberExpression | types.OptionalMemberExpression;
88
+ type ResolvedBinding = NonNullable<ReturnType<Scope["getBinding"]>>;
89
+
65
90
  const CONTEXT_SEPARATOR = "\u{4}";
66
91
  const DEFAULT_NAMESPACE = "translation";
67
92
  const POTFILES_FILENAME = "POTFILES.in";
68
93
  const SYNTHETIC_FILENAME = "messages.js";
94
+ const UNSUPPORTED_PLURAL_OPTION = /^defaultValue_(few|many|two|zero)$/u;
95
+ const STATIC_SOURCE_OPTION_NAMES: ReadonlySet<string> = new Set([
96
+ "context",
97
+ "defaultValue",
98
+ "defaultValue_one",
99
+ "defaultValue_other",
100
+ "keyPrefix",
101
+ ]);
102
+ const NESTED_CONTEXT = /["']?context["']?\s*:\s*(?:"([^"]*)"|'([^']*)')/u;
103
+ const NESTED_COUNT = /["']?count["']?\s*:/u;
104
+ const NESTED_STRUCTURE_TOKEN = /"[^"]*"|'[^']*'|[()]/gu;
105
+ const TRANSLATION_MODULES = new Set(["@gtkx/i18n", "i18next"]);
106
+ const TRANS_ELEMENTS: ReadonlySet<string> = new Set(["Trans", "TransWithoutContext"]);
107
+ const STATIC_KEY_WRAPPER_TYPES: ReadonlySet<string> = new Set([
108
+ "ParenthesizedExpression",
109
+ "TSAsExpression",
110
+ "TSSatisfiesExpression",
111
+ "TSTypeAssertion",
112
+ "TSNonNullExpression",
113
+ ]);
69
114
 
70
115
  const quietLogger = (): { logger: Logger; reports: string[] } => {
71
116
  const reports: string[] = [];
@@ -294,6 +339,1164 @@ const normalizedSourceFiles = (root: string, paths: string[]): string[] => {
294
339
  return new Set(files).values().toArray().toSorted((left, right) => left.localeCompare(right));
295
340
  };
296
341
 
342
+ type StaticKeyWrapper = ESTree.ParenthesizedExpression |
343
+ ESTree.TSAsExpression |
344
+ ESTree.TSSatisfiesExpression |
345
+ ESTree.TSTypeAssertion |
346
+ ESTree.TSNonNullExpression;
347
+
348
+ const isStaticKeyWrapper = (key: ESTree.Node): key is StaticKeyWrapper =>
349
+ STATIC_KEY_WRAPPER_TYPES.has(key.type);
350
+
351
+ const unwrapStaticWrapper = (node: ESTree.Node): ESTree.Node =>
352
+ isStaticKeyWrapper(node) ? unwrapStaticWrapper(node.expression) : node;
353
+
354
+ const isStaticTranslationKey = (key: ESTree.Node | null | undefined): boolean => {
355
+ if (key === undefined || key === null) {
356
+ return false;
357
+ }
358
+
359
+ if (key.type === "Literal") {
360
+ return typeof key.value === "string";
361
+ }
362
+
363
+ if (key.type === "TemplateLiteral") {
364
+ return key.expressions.length === 0;
365
+ }
366
+
367
+ if (key.type === "ParenthesizedExpression") {
368
+ return false;
369
+ }
370
+
371
+ if (isStaticKeyWrapper(key)) {
372
+ return isStaticTranslationKey(key.expression);
373
+ }
374
+
375
+ return false;
376
+ };
377
+
378
+ const assertStaticTranslationKey = (key: ESTree.Node | null | undefined): void => {
379
+ if (!isStaticTranslationKey(key)) {
380
+ throw new Error("Translation keys must be string literals");
381
+ }
382
+ };
383
+
384
+ const propertyName = (property: ESTree.ObjectProperty): string | null => {
385
+ if (!property.computed && property.key.type === "Identifier") {
386
+ return property.key.name;
387
+ }
388
+
389
+ return property.key.type === "Literal" && typeof property.key.value === "string"
390
+ ? property.key.value
391
+ : null;
392
+ };
393
+
394
+ const assertSupportedOptionProperty = (property: ESTree.ObjectPropertyKind): void => {
395
+ if (property.type === "SpreadElement") {
396
+ throw new Error("Translation extraction requires explicit option properties");
397
+ }
398
+
399
+ const name = propertyName(property);
400
+
401
+ if (name === null) {
402
+ throw new Error("Translation extraction requires static option property names");
403
+ }
404
+
405
+ if (UNSUPPORTED_PLURAL_OPTION.test(name)) {
406
+ throw new Error("GNU gettext accepts one singular and one plural source string");
407
+ }
408
+
409
+ if (STATIC_SOURCE_OPTION_NAMES.has(name)) {
410
+ assertStaticTranslationKey(property.value);
411
+ }
412
+ };
413
+
414
+ const assertSupportedOptionObject = (options: ESTree.Node | null | undefined): void => {
415
+ if (options === null || options === undefined) {
416
+ return;
417
+ }
418
+
419
+ if (isStaticKeyWrapper(options) && unwrapStaticWrapper(options).type === "ObjectExpression") {
420
+ throw new Error("Translation option objects cannot be wrapped in another expression");
421
+ }
422
+
423
+ if (options.type !== "ObjectExpression") {
424
+ throw new Error("Translation option objects must be inline object literals");
425
+ }
426
+
427
+ for (const property of options.properties) {
428
+ assertSupportedOptionProperty(property);
429
+ }
430
+ };
431
+
432
+ const namedImportedBinding = (path: NodePath, source: string): ImportedBinding | null => {
433
+ if (!path.isImportSpecifier() || path.node.importKind === "type") {
434
+ return null;
435
+ }
436
+
437
+ const imported = path.node.imported;
438
+
439
+ return {
440
+ imported: types.isIdentifier(imported) ? imported.name : imported.value,
441
+ local: path.node.local.name,
442
+ source,
443
+ style: "named",
444
+ };
445
+ };
446
+
447
+ const defaultImportedBinding = (path: NodePath, source: string): ImportedBinding | null =>
448
+ path.isImportDefaultSpecifier()
449
+ ? { imported: "default", local: path.node.local.name, source, style: "default" }
450
+ : null;
451
+
452
+ const namespaceImportedBinding = (path: NodePath, source: string): ImportedBinding | null =>
453
+ path.isImportNamespaceSpecifier()
454
+ ? { imported: "*", local: path.node.local.name, source, style: "namespace" }
455
+ : null;
456
+
457
+ const importedBinding = (binding: ResolvedBinding | undefined): ImportedBinding | null => {
458
+ if (binding === undefined) {
459
+ return null;
460
+ }
461
+
462
+ const path = binding.path;
463
+ const declaration = path.parentPath;
464
+
465
+ if (!declaration.isImportDeclaration() || declaration.node.importKind === "type") {
466
+ return null;
467
+ }
468
+
469
+ const source = declaration.node.source.value;
470
+
471
+ return namedImportedBinding(path, source) ??
472
+ defaultImportedBinding(path, source) ??
473
+ namespaceImportedBinding(path, source);
474
+ };
475
+
476
+ const babelPropertyName = (property: types.ObjectProperty): string | null => {
477
+ const key = property.key;
478
+
479
+ if (!property.computed && types.isIdentifier(key)) {
480
+ return key.name;
481
+ }
482
+
483
+ return types.isStringLiteral(key) ? key.value : null;
484
+ };
485
+
486
+ const isBoundIdentifier = (node: types.Node | null, name: string): boolean => {
487
+ if (types.isIdentifier(node)) {
488
+ return node.name === name;
489
+ }
490
+
491
+ if (types.isAssignmentPattern(node)) {
492
+ return types.isIdentifier(node.left) && node.left.name === name;
493
+ }
494
+
495
+ return false;
496
+ };
497
+
498
+ const isHookPatternBinding = (pattern: types.VariableDeclarator["id"], name: string): boolean => {
499
+ if (types.isObjectPattern(pattern)) {
500
+ return pattern.properties.some((property) =>
501
+ types.isObjectProperty(property) &&
502
+ babelPropertyName(property) === "t" &&
503
+ isBoundIdentifier(property.value, name));
504
+ }
505
+
506
+ if (types.isArrayPattern(pattern)) {
507
+ return isBoundIdentifier(pattern.elements[0] ?? null, name);
508
+ }
509
+
510
+ return false;
511
+ };
512
+
513
+ const importedTranslationHook = (scope: Scope, call: types.CallExpression): ImportedBinding | null => {
514
+ if (!types.isIdentifier(call.callee)) {
515
+ return null;
516
+ }
517
+
518
+ const imported = importedBinding(scope.getBinding(call.callee.name));
519
+
520
+ return imported?.imported === "useTranslation" && TRANSLATION_MODULES.has(imported.source)
521
+ ? imported
522
+ : null;
523
+ };
524
+
525
+ const translationHookBinding = (binding: ResolvedBinding): TranslationHookBinding | null => {
526
+ const path = binding.path;
527
+
528
+ if (!path.isVariableDeclarator()) {
529
+ return null;
530
+ }
531
+
532
+ const pattern = path.node.id;
533
+ const initializer = path.node.init;
534
+
535
+ if (!isHookPatternBinding(pattern, binding.identifier.name) ||
536
+ !types.isCallExpression(initializer)) {
537
+ return null;
538
+ }
539
+
540
+ const imported = importedTranslationHook(path.scope, initializer);
541
+
542
+ if (imported === null) {
543
+ return null;
544
+ }
545
+
546
+ return { call: initializer, isCanonical: imported.local === "useTranslation" };
547
+ };
548
+
549
+ const importedTranslationFunctionKind = (imported: ImportedBinding | null): TranslationCallKind | null => {
550
+ if (imported?.imported !== "t" || !TRANSLATION_MODULES.has(imported.source)) {
551
+ return null;
552
+ }
553
+
554
+ return imported.local === "t" ? "canonical" : "alias";
555
+ };
556
+
557
+ const hookTranslationFunctionKind = (binding: ResolvedBinding | undefined): TranslationCallKind | null => {
558
+ if (binding === undefined) {
559
+ return null;
560
+ }
561
+
562
+ const hook = translationHookBinding(binding);
563
+
564
+ if (hook === null) {
565
+ return null;
566
+ }
567
+
568
+ return binding.identifier.name === "t" && hook.isCanonical ? "canonical" : "alias";
569
+ };
570
+
571
+ const directTranslationFunctionKind = (scope: Scope, name: string): TranslationCallKind | null => {
572
+ const binding = scope.getBinding(name);
573
+
574
+ return importedTranslationFunctionKind(importedBinding(binding)) ?? hookTranslationFunctionKind(binding);
575
+ };
576
+
577
+ const babelMemberName = (member: TranslationMemberExpression): string | null => {
578
+ const property = member.property;
579
+
580
+ if (member.computed) {
581
+ return types.isStringLiteral(property) ? property.value : null;
582
+ }
583
+
584
+ return types.isIdentifier(property) ? property.name : null;
585
+ };
586
+
587
+ const isImportedTranslationObject = (scope: Scope, object: types.Node): boolean => {
588
+ if (!types.isIdentifier(object)) {
589
+ return false;
590
+ }
591
+
592
+ const imported = importedBinding(scope.getBinding(object.name));
593
+
594
+ return imported !== null &&
595
+ TRANSLATION_MODULES.has(imported.source) &&
596
+ (imported.style === "namespace" || (imported.source === "i18next" && imported.imported === "default"));
597
+ };
598
+
599
+ const constantVariableDeclarator = (binding: ResolvedBinding): NodePath<types.VariableDeclarator> | null => {
600
+ const path = binding.path;
601
+ const declaration = path.parentPath;
602
+
603
+ if (!path.isVariableDeclarator() ||
604
+ !declaration.isVariableDeclaration() ||
605
+ declaration.node.kind !== "const") {
606
+ return null;
607
+ }
608
+
609
+ return path;
610
+ };
611
+
612
+ const isTranslationHookResultBinding = (binding: ResolvedBinding | undefined): boolean => {
613
+ if (binding === undefined) {
614
+ return false;
615
+ }
616
+
617
+ const path = constantVariableDeclarator(binding);
618
+ const initializer = path?.node.init;
619
+
620
+ return path !== null &&
621
+ types.isIdentifier(path.node.id) &&
622
+ types.isCallExpression(initializer) &&
623
+ importedTranslationHook(path.scope, initializer) !== null;
624
+ };
625
+
626
+ const isHookTranslationMember = (scope: Scope, member: TranslationMemberExpression): boolean => {
627
+ if (babelMemberName(member) !== "t") {
628
+ return false;
629
+ }
630
+
631
+ const object = member.object;
632
+
633
+ if (types.isCallExpression(object)) {
634
+ return importedTranslationHook(scope, object) !== null;
635
+ }
636
+
637
+ return types.isIdentifier(object) && isTranslationHookResultBinding(scope.getBinding(object.name));
638
+ };
639
+
640
+ const isTranslationMember = (scope: Scope, member: TranslationMemberExpression): boolean =>
641
+ babelMemberName(member) === "t" &&
642
+ (isImportedTranslationObject(scope, member.object) || isHookTranslationMember(scope, member));
643
+
644
+ const isDirectTranslationFunction = (scope: Scope, node: types.Node): boolean =>
645
+ types.isIdentifier(node) && directTranslationFunctionKind(scope, node.name) !== null;
646
+
647
+ const isTranslationFunctionValue = (scope: Scope, node: types.Node): boolean => {
648
+ if (isDirectTranslationFunction(scope, node)) {
649
+ return true;
650
+ }
651
+
652
+ return (types.isMemberExpression(node) || types.isOptionalMemberExpression(node)) &&
653
+ isTranslationMember(scope, node);
654
+ };
655
+
656
+ const isTranslationBindCall = (scope: Scope, node: types.Node): boolean => {
657
+ if (!types.isCallExpression(node) || !types.isMemberExpression(node.callee)) {
658
+ return false;
659
+ }
660
+
661
+ return babelMemberName(node.callee) === "bind" &&
662
+ isTranslationFunctionValue(scope, node.callee.object);
663
+ };
664
+
665
+ const isTranslationObjectPatternAlias = (
666
+ path: NodePath<types.VariableDeclarator>,
667
+ binding: ResolvedBinding,
668
+ ): boolean => {
669
+ const pattern = path.node.id;
670
+ const initializer = path.node.init;
671
+
672
+ if (!types.isObjectPattern(pattern) ||
673
+ !isHookPatternBinding(pattern, binding.identifier.name) ||
674
+ !types.isIdentifier(initializer)) {
675
+ return false;
676
+ }
677
+
678
+ return isImportedTranslationObject(path.scope, initializer) ||
679
+ isTranslationHookResultBinding(path.scope.getBinding(initializer.name));
680
+ };
681
+
682
+ const isTranslationAliasBinding = (binding: ResolvedBinding | undefined): boolean => {
683
+ if (binding === undefined) {
684
+ return false;
685
+ }
686
+
687
+ const path = constantVariableDeclarator(binding);
688
+
689
+ if (path === null) {
690
+ return false;
691
+ }
692
+
693
+ if (isTranslationObjectPatternAlias(path, binding)) {
694
+ return true;
695
+ }
696
+
697
+ const initializer = path.node.init;
698
+
699
+ return types.isIdentifier(path.node.id) &&
700
+ initializer !== null &&
701
+ initializer !== undefined &&
702
+ (isTranslationFunctionValue(path.scope, initializer) || isTranslationBindCall(path.scope, initializer));
703
+ };
704
+
705
+ const translationFunctionKind = (scope: Scope, name: string): TranslationCallKind | null => {
706
+ const direct = directTranslationFunctionKind(scope, name);
707
+
708
+ if (direct !== null) {
709
+ return direct;
710
+ }
711
+
712
+ return isTranslationAliasBinding(scope.getBinding(name)) ? "alias" : null;
713
+ };
714
+
715
+ const translationElementKind = (path: NodePath, name: string): TranslationCallKind | null => {
716
+ const imported = importedBinding(path.scope.getBinding(name));
717
+
718
+ if (imported?.source !== "@gtkx/i18n" || !TRANS_ELEMENTS.has(imported.imported)) {
719
+ return null;
720
+ }
721
+
722
+ return imported.local === imported.imported ? "canonical" : "alias";
723
+ };
724
+
725
+ const nodeStart = (path: NodePath): number => {
726
+ const start = path.node.start;
727
+
728
+ if (start === null || start === undefined) {
729
+ throw new Error("Translation extraction could not locate a source expression");
730
+ }
731
+
732
+ return start;
733
+ };
734
+
735
+ const registerSourceMask = (node: types.Node, references: TranslationReferences): void => {
736
+ const { start, end } = node;
737
+
738
+ if (start === null || start === undefined || end === null || end === undefined) {
739
+ throw new Error("Translation extraction could not locate a source expression");
740
+ }
741
+
742
+ references.masks.push({ start, end });
743
+ };
744
+
745
+ const sourceLocationKey = (line: number, column: number): string => `${String(line)}:${String(column)}`;
746
+
747
+ const sourcePoint = (node: types.Node): SourcePoint | null => {
748
+ const location = node.loc?.start;
749
+
750
+ return location === undefined ? null : { column: location.column, line: location.line };
751
+ };
752
+
753
+ const registerSourceLocation = (node: types.Node, references: TranslationReferences): SourcePoint | null => {
754
+ const point = sourcePoint(node);
755
+
756
+ if (point !== null) {
757
+ references.locations.add(sourceLocationKey(point.line, point.column));
758
+ }
759
+
760
+ return point;
761
+ };
762
+
763
+ const babelStaticKey = (node: types.Node | null | undefined): string | null => {
764
+ if (node === null || node === undefined) {
765
+ return null;
766
+ }
767
+
768
+ if (types.isStringLiteral(node)) {
769
+ return node.value;
770
+ }
771
+
772
+ if (types.isTemplateLiteral(node) && node.expressions.length === 0) {
773
+ return node.quasis[0]?.value.cooked ?? null;
774
+ }
775
+
776
+ if (types.isParenthesizedExpression(node) ||
777
+ types.isTSAsExpression(node) ||
778
+ types.isTSSatisfiesExpression(node) ||
779
+ types.isTSTypeAssertion(node) ||
780
+ types.isTSNonNullExpression(node)) {
781
+ return babelStaticKey(node.expression);
782
+ }
783
+
784
+ return null;
785
+ };
786
+
787
+ const babelObjectExpression = (node: types.Node | null | undefined): types.ObjectExpression | null => {
788
+ if (node === null || node === undefined) {
789
+ return null;
790
+ }
791
+
792
+ if (types.isObjectExpression(node)) {
793
+ return node;
794
+ }
795
+
796
+ if (types.isParenthesizedExpression(node) ||
797
+ types.isTSAsExpression(node) ||
798
+ types.isTSSatisfiesExpression(node) ||
799
+ types.isTSTypeAssertion(node) ||
800
+ types.isTSNonNullExpression(node)) {
801
+ return babelObjectExpression(node.expression);
802
+ }
803
+
804
+ return null;
805
+ };
806
+
807
+ const babelNamedProperty = (
808
+ object: types.ObjectExpression | null,
809
+ name: string,
810
+ ): types.ObjectProperty | null => {
811
+ if (object === null) {
812
+ return null;
813
+ }
814
+
815
+ for (const property of object.properties) {
816
+ if (types.isObjectProperty(property) && babelPropertyName(property) === name) {
817
+ return property;
818
+ }
819
+ }
820
+
821
+ return null;
822
+ };
823
+
824
+ const babelStringProperty = (object: types.ObjectExpression | null, name: string): string | null => {
825
+ const property = babelNamedProperty(object, name);
826
+
827
+ if (property === null) {
828
+ return null;
829
+ }
830
+
831
+ const value = babelStaticKey(property.value);
832
+
833
+ if (value === null) {
834
+ throw new Error(`Translation ${name} values must be string literals`);
835
+ }
836
+
837
+ return value;
838
+ };
839
+
840
+ const callOptions = (call: types.CallExpression): types.ObjectExpression | null =>
841
+ babelObjectExpression(call.arguments[1]) ?? babelObjectExpression(call.arguments[2]);
842
+
843
+ const hookKeyPrefix = (callee: NodePath<types.Identifier>): string => {
844
+ const binding = callee.scope.getBinding(callee.node.name);
845
+ const hook = binding === undefined ? null : translationHookBinding(binding);
846
+
847
+ return babelStringProperty(
848
+ hook === null ? null : babelObjectExpression(hook.call.arguments[1]),
849
+ "keyPrefix",
850
+ ) ?? "";
851
+ };
852
+
853
+ const prefixedTranslationKey = (prefix: string, key: string): string => {
854
+ if (prefix.length === 0) {
855
+ return key;
856
+ }
857
+
858
+ return prefix.endsWith(".") ? `${prefix}${key}` : `${prefix}.${key}`;
859
+ };
860
+
861
+ const extractedEntryKey = (call: types.CallExpression, keyPrefix: string): string | null => {
862
+ const key = babelStaticKey(call.arguments[0]);
863
+
864
+ if (key === null) {
865
+ return null;
866
+ }
867
+
868
+ const options = callOptions(call);
869
+ const callPrefix = babelStringProperty(options, "keyPrefix");
870
+
871
+ if (callPrefix === "" && keyPrefix.length > 0) {
872
+ throw new Error("An empty call keyPrefix cannot override a hook keyPrefix during extraction");
873
+ }
874
+
875
+ const selectedPrefix = callPrefix ?? keyPrefix;
876
+ const prefixed = prefixedTranslationKey(selectedPrefix, key);
877
+ const context = babelStringProperty(options, "context");
878
+
879
+ return context === null ? prefixed : `${prefixed}${CONTEXT_SEPARATOR}${context}`;
880
+ };
881
+
882
+ const registerEntryLocation = (
883
+ key: string | null,
884
+ point: SourcePoint | null,
885
+ references: TranslationReferences,
886
+ ): void => {
887
+ if (key === null || point === null) {
888
+ return;
889
+ }
890
+
891
+ const locations = references.entryLocations.get(key) ?? [];
892
+ locations.push(point);
893
+ references.entryLocations.set(key, locations);
894
+ };
895
+
896
+ const registerCallReference = (
897
+ callPath: NodePath<types.CallExpression>,
898
+ references: TranslationReferences,
899
+ keyPrefix: string,
900
+ ): void => {
901
+ references.calls.add(nodeStart(callPath));
902
+ const firstArgument = callPath.node.arguments[0];
903
+ const point = registerSourceLocation(firstArgument ?? callPath.node, references);
904
+ registerEntryLocation(extractedEntryKey(callPath.node, keyPrefix), point, references);
905
+ };
906
+
907
+ const parserPlugins = (lang: ReturnType<typeof sourceLanguage>): ("decorators" | "jsx" | "typescript")[] => [
908
+ "decorators",
909
+ ...(lang === "ts" || lang === "tsx" ? ["typescript" as const] : []),
910
+ ...(lang === "jsx" || lang === "tsx" ? ["jsx" as const] : []),
911
+ ];
912
+
913
+ const registerIdentifierTranslationCall = (
914
+ callPath: NodePath<types.CallExpression>,
915
+ callee: NodePath,
916
+ references: TranslationReferences,
917
+ ): void => {
918
+ if (!callee.isIdentifier()) {
919
+ return;
920
+ }
921
+
922
+ const kind = translationFunctionKind(callee.scope, callee.node.name);
923
+
924
+ if (kind === "alias") {
925
+ throw new Error("Translation calls must use the imported name t");
926
+ }
927
+
928
+ if (kind === "canonical") {
929
+ registerCallReference(callPath, references, hookKeyPrefix(callee));
930
+ } else if (callee.node.name === "t") {
931
+ registerSourceMask(callee.node, references);
932
+ }
933
+ };
934
+
935
+ const registerTranslationCall = (
936
+ callPath: NodePath<types.CallExpression>,
937
+ references: TranslationReferences,
938
+ ): void => {
939
+ assertSupportedWrappedCallee(callPath);
940
+ const callee = callPath.get("callee");
941
+
942
+ if (callee.isIdentifier()) {
943
+ registerIdentifierTranslationCall(callPath, callee, references);
944
+
945
+ return;
946
+ }
947
+
948
+ if (callee.isMemberExpression() && isTranslationMember(callee.scope, callee.node)) {
949
+ throw new Error("Translation calls must use the named t export");
950
+ }
951
+ };
952
+
953
+ const unwrapTranslationCallee = (node: types.Node): types.Node => {
954
+ if (types.isParenthesizedExpression(node) ||
955
+ types.isTSAsExpression(node) ||
956
+ types.isTSSatisfiesExpression(node) ||
957
+ types.isTSTypeAssertion(node) ||
958
+ types.isTSNonNullExpression(node)) {
959
+ return unwrapTranslationCallee(node.expression);
960
+ }
961
+
962
+ return node;
963
+ };
964
+
965
+ const isTranslationCallee = (scope: Scope, node: types.Node): boolean => {
966
+ if (types.isIdentifier(node)) {
967
+ return translationFunctionKind(scope, node.name) !== null;
968
+ }
969
+
970
+ return (types.isMemberExpression(node) || types.isOptionalMemberExpression(node)) &&
971
+ isTranslationMember(scope, node);
972
+ };
973
+
974
+ const assertSupportedWrappedCallee = (callPath: NodePath<types.CallExpression>): void => {
975
+ const callee = callPath.node.callee;
976
+ const unwrapped = unwrapTranslationCallee(callee);
977
+
978
+ if (unwrapped !== callee && isTranslationCallee(callPath.scope, unwrapped)) {
979
+ throw new Error("Translation call expressions cannot wrap their callee");
980
+ }
981
+ };
982
+
983
+ const assertSupportedOptionalCall = (callPath: NodePath<types.OptionalCallExpression>): void => {
984
+ const callee = unwrapTranslationCallee(callPath.node.callee);
985
+
986
+ if (isTranslationCallee(callPath.scope, callee)) {
987
+ throw new Error("Translation calls cannot use optional chaining");
988
+ }
989
+ };
990
+
991
+ const assertUnsupportedTranslationTag = (tagPath: NodePath<types.TaggedTemplateExpression>): void => {
992
+ const tag = unwrapTranslationCallee(tagPath.node.tag);
993
+
994
+ if (isTranslationCallee(tagPath.scope, tag)) {
995
+ throw new Error("Translation calls cannot use tagged-template syntax");
996
+ }
997
+ };
998
+
999
+ const registerUnrecognizedElementMasks = (
1000
+ elementPath: NodePath,
1001
+ name: NodePath<types.JSXIdentifier>,
1002
+ references: TranslationReferences,
1003
+ ): void => {
1004
+ registerSourceMask(name.node, references);
1005
+ const parent = elementPath.parentPath.node;
1006
+ const closingName = types.isJSXElement(parent) ? parent.closingElement?.name : null;
1007
+
1008
+ if (types.isJSXIdentifier(closingName)) {
1009
+ registerSourceMask(closingName, references);
1010
+ }
1011
+ };
1012
+
1013
+ const registerTranslationElement = (elementPath: NodePath, references: TranslationReferences): void => {
1014
+ const name = elementPath.get("name");
1015
+
1016
+ if (!name.isJSXIdentifier()) {
1017
+ return;
1018
+ }
1019
+
1020
+ const kind = translationElementKind(name, name.node.name);
1021
+
1022
+ if (kind === "alias") {
1023
+ throw new Error("Translation components must use their imported names");
1024
+ }
1025
+
1026
+ if (kind === "canonical") {
1027
+ references.elements.add(nodeStart(elementPath));
1028
+ registerSourceLocation(elementPath.node, references);
1029
+ } else if (TRANS_ELEMENTS.has(name.node.name)) {
1030
+ registerUnrecognizedElementMasks(elementPath, name, references);
1031
+ }
1032
+ };
1033
+
1034
+ const maskUnrecognizedTranslations = (source: string, references: TranslationReferences): string => {
1035
+ let masked = source;
1036
+ const masks = references.masks.toSorted((left, right) => right.start - left.start);
1037
+
1038
+ for (const { start, end } of masks) {
1039
+ masked = `${masked.slice(0, start)}${"_".repeat(end - start)}${masked.slice(end)}`;
1040
+ }
1041
+
1042
+ return masked;
1043
+ };
1044
+
1045
+ const translationReferences = (
1046
+ path: string,
1047
+ source: string,
1048
+ lang: ReturnType<typeof sourceLanguage>,
1049
+ ): TranslationReferences => {
1050
+ const parsed = parseBabelSync(source, {
1051
+ ast: true,
1052
+ babelrc: false,
1053
+ configFile: false,
1054
+ filename: path,
1055
+ parserOpts: { createParenthesizedExpressions: true, plugins: parserPlugins(lang) },
1056
+ sourceType: "module",
1057
+ });
1058
+
1059
+ if (parsed === null) {
1060
+ throw new Error(`Translation extraction could not parse ${path}`);
1061
+ }
1062
+
1063
+ const references: TranslationReferences = {
1064
+ calls: new Set(),
1065
+ elements: new Set(),
1066
+ entryLocations: new Map(),
1067
+ locations: new Set(),
1068
+ masks: [],
1069
+ };
1070
+
1071
+ traverse(parsed, {
1072
+ CallExpression(callPath) {
1073
+ registerTranslationCall(callPath, references);
1074
+ },
1075
+ JSXOpeningElement(elementPath) {
1076
+ registerTranslationElement(elementPath, references);
1077
+ },
1078
+ OptionalCallExpression(callPath) {
1079
+ assertSupportedOptionalCall(callPath);
1080
+ },
1081
+ TaggedTemplateExpression(tagPath) {
1082
+ assertUnsupportedTranslationTag(tagPath);
1083
+ },
1084
+ });
1085
+
1086
+ return references;
1087
+ };
1088
+
1089
+ const assertSupportedTranslationCall = (node: ESTree.CallExpression, references: TranslationReferences): void => {
1090
+ if (!references.calls.has(node.start)) {
1091
+ return;
1092
+ }
1093
+
1094
+ assertStaticTranslationKey(node.arguments[0]);
1095
+ assertSupportedTranslationOptions(node.arguments[1], node.arguments[2]);
1096
+ };
1097
+
1098
+ const assertSupportedTranslationOptions = (
1099
+ second: ESTree.Node | null | undefined,
1100
+ third: ESTree.Node | null | undefined,
1101
+ ): void => {
1102
+ if (third !== undefined && third !== null) {
1103
+ assertStaticTranslationKey(second);
1104
+ assertSupportedOptionObject(third);
1105
+
1106
+ return;
1107
+ }
1108
+
1109
+ if (second === undefined || second === null || isStaticTranslationKey(second)) {
1110
+ return;
1111
+ }
1112
+
1113
+ assertSupportedOptionObject(second);
1114
+ };
1115
+
1116
+ const isNamedJsxAttribute = (attribute: ESTree.JSXAttribute, name: string): boolean =>
1117
+ attribute.name.type === "JSXIdentifier" && attribute.name.name === name;
1118
+
1119
+ const assertSupportedTransKey = (attribute: ESTree.JSXAttribute): void => {
1120
+ if (!isNamedJsxAttribute(attribute, "i18nKey")) {
1121
+ return;
1122
+ }
1123
+
1124
+ const key = attribute.value?.type === "JSXExpressionContainer"
1125
+ ? attribute.value.expression
1126
+ : attribute.value;
1127
+ assertStaticTranslationKey(key);
1128
+ };
1129
+
1130
+ const assertSupportedTransStringAttribute = (attribute: ESTree.JSXAttribute, name: string): void => {
1131
+ if (!isNamedJsxAttribute(attribute, name)) {
1132
+ return;
1133
+ }
1134
+
1135
+ const value = attribute.value?.type === "JSXExpressionContainer"
1136
+ ? attribute.value.expression
1137
+ : attribute.value;
1138
+ assertStaticTranslationKey(value);
1139
+ };
1140
+
1141
+ const assertSupportedTransOptions = (attribute: ESTree.JSXAttribute): void => {
1142
+ if (isNamedJsxAttribute(attribute, "tOptions") && attribute.value?.type === "JSXExpressionContainer") {
1143
+ assertSupportedOptionObject(attribute.value.expression);
1144
+ }
1145
+ };
1146
+
1147
+ const assertSupportedTransAttribute = (attribute: ESTree.JSXAttributeItem): void => {
1148
+ if (attribute.type === "JSXSpreadAttribute") {
1149
+ throw new Error("Translation extraction requires explicit component properties");
1150
+ }
1151
+
1152
+ assertSupportedTransKey(attribute);
1153
+ assertSupportedTransStringAttribute(attribute, "context");
1154
+ assertSupportedTransStringAttribute(attribute, "defaults");
1155
+ assertSupportedTransOptions(attribute);
1156
+ };
1157
+
1158
+ const assertSupportedTransElement = (node: ESTree.JSXOpeningElement, references: TranslationReferences): void => {
1159
+ if (!references.elements.has(node.start)) {
1160
+ return;
1161
+ }
1162
+
1163
+ for (const attribute of node.attributes) {
1164
+ assertSupportedTransAttribute(attribute);
1165
+ }
1166
+ };
1167
+
1168
+ const assertSupportedTranslationSyntax = (path: string, source: string): TranslationReferences => {
1169
+ const lang = sourceLanguage(path);
1170
+
1171
+ if (lang === undefined) {
1172
+ return { calls: new Set(), elements: new Set(), entryLocations: new Map(), locations: new Set(), masks: [] };
1173
+ }
1174
+
1175
+ const parsed = parseSync(path, source, { lang });
1176
+ const references = translationReferences(path, source, lang);
1177
+
1178
+ new Visitor({
1179
+ CallExpression(node) {
1180
+ assertSupportedTranslationCall(node, references);
1181
+ },
1182
+ JSXOpeningElement(node) {
1183
+ assertSupportedTransElement(node, references);
1184
+ },
1185
+ }).visit(parsed.program);
1186
+
1187
+ return references;
1188
+ };
1189
+
1190
+ const extractedLocationFile = (root: string, file: string): string =>
1191
+ resolve(root, file);
1192
+
1193
+ const isRecognizedLocation = (
1194
+ root: string,
1195
+ references: Map<string, TranslationReferences>,
1196
+ location: SourceLocation,
1197
+ ): boolean => {
1198
+ if (location.line === undefined || location.column === undefined) {
1199
+ return false;
1200
+ }
1201
+
1202
+ const sourceReferences = references.get(extractedLocationFile(root, location.file));
1203
+
1204
+ return sourceReferences?.locations.has(sourceLocationKey(location.line, location.column)) === true;
1205
+ };
1206
+
1207
+ const recognizedKeyLocations = (
1208
+ references: Map<string, TranslationReferences>,
1209
+ extractedKey: string,
1210
+ ): ExtractedLocation[] => {
1211
+ const locations: ExtractedLocation[] = [];
1212
+
1213
+ for (const [file, sourceReferences] of references) {
1214
+ const points = sourceReferences.entryLocations.get(extractedKey) ?? [];
1215
+
1216
+ for (const point of points) {
1217
+ locations.push({ file, column: point.column, line: point.line });
1218
+ }
1219
+ }
1220
+
1221
+ return locations;
1222
+ };
1223
+
1224
+ const recognizedEntry = (
1225
+ root: string,
1226
+ references: Map<string, TranslationReferences>,
1227
+ entry: ExtractedKey,
1228
+ ): ExtractedKey | null => {
1229
+ const extractedLocations = entry.locations ?? [];
1230
+ const locations = extractedLocations.length === 0
1231
+ ? recognizedKeyLocations(references, entry.key)
1232
+ : extractedLocations.filter((location) => isRecognizedLocation(root, references, location));
1233
+
1234
+ return locations.length === 0 ? null : { ...entry, locations };
1235
+ };
1236
+
1237
+ type NestedReferenceParts = { base: string; options: string };
1238
+
1239
+ const quotedNestedReferenceParts = (content: string, quote: string): NestedReferenceParts | null => {
1240
+ const end = content.indexOf(quote, 1);
1241
+
1242
+ return end === -1
1243
+ ? null
1244
+ : { base: content.slice(1, end), options: content.slice(end + 1) };
1245
+ };
1246
+
1247
+ const nestedReferenceParts = (value: string): NestedReferenceParts | null => {
1248
+ const content = value.trim();
1249
+ const quote = content[0];
1250
+
1251
+ if (quote === "\"" || quote === "'") {
1252
+ return quotedNestedReferenceParts(content, quote);
1253
+ }
1254
+
1255
+ const separator = content.indexOf(",");
1256
+ const base = (separator === -1 ? content : content.slice(0, separator)).trim();
1257
+
1258
+ return base.length === 0
1259
+ ? null
1260
+ : { base, options: separator === -1 ? "" : content.slice(separator + 1) };
1261
+ };
1262
+
1263
+ const nestedReferenceContext = (options: string): string | null => {
1264
+ const match = NESTED_CONTEXT.exec(options);
1265
+ const context = match?.[1] ?? match?.[2] ?? null;
1266
+
1267
+ return context === null || context.length === 0 ? null : context;
1268
+ };
1269
+
1270
+ const adjustedParenthesisDepth = (character: string | undefined, depth: number): number => {
1271
+ if (character === "(") {
1272
+ return depth + 1;
1273
+ }
1274
+
1275
+ return character === ")" ? depth - 1 : depth;
1276
+ };
1277
+
1278
+ const nestedReferenceEnd = (text: string, start: number): number => {
1279
+ let depth = 0;
1280
+ const tokens = text.slice(start).matchAll(NESTED_STRUCTURE_TOKEN);
1281
+
1282
+ for (const token of tokens) {
1283
+ const character = token[0];
1284
+
1285
+ if (character === ")" && depth === 0) {
1286
+ return start + token.index;
1287
+ }
1288
+
1289
+ depth = adjustedParenthesisDepth(character, depth);
1290
+ }
1291
+
1292
+ return -1;
1293
+ };
1294
+
1295
+ const nestedReferenceContents = (text: string): string[] => {
1296
+ const contents: string[] = [];
1297
+ let offset = 0;
1298
+
1299
+ while (offset < text.length) {
1300
+ const prefix = text.indexOf("$t(", offset);
1301
+
1302
+ if (prefix === -1) {
1303
+ break;
1304
+ }
1305
+
1306
+ const start = prefix + 3;
1307
+ const end = nestedReferenceEnd(text, start);
1308
+
1309
+ if (end === -1) {
1310
+ break;
1311
+ }
1312
+
1313
+ contents.push(text.slice(start, end));
1314
+ offset = end + 1;
1315
+ }
1316
+
1317
+ return contents;
1318
+ };
1319
+
1320
+ const nestedPluralKeys = (base: string, context: string | null): string[] => {
1321
+ const pluralBase = context === null ? base : `${base}${CONTEXT_SEPARATOR}${context}`;
1322
+
1323
+ return [`${pluralBase}_one`, `${pluralBase}_other`];
1324
+ };
1325
+
1326
+ const nestedReferenceKeys = (content: string): string[] => {
1327
+ const parts = nestedReferenceParts(content);
1328
+
1329
+ if (parts === null) {
1330
+ return [];
1331
+ }
1332
+
1333
+ const context = nestedReferenceContext(parts.options);
1334
+ const contextual = context === null
1335
+ ? []
1336
+ : [`${parts.base}_${context}`, `${parts.base}${CONTEXT_SEPARATOR}${context}`];
1337
+
1338
+ return NESTED_COUNT.test(parts.options)
1339
+ ? [parts.base, ...contextual, ...nestedPluralKeys(parts.base, context)]
1340
+ : [parts.base, ...contextual];
1341
+ };
1342
+
1343
+ const nestedEntryKeys = (text: string): Set<string> => {
1344
+ const keys: Set<string> = new Set();
1345
+
1346
+ for (const content of nestedReferenceContents(text)) {
1347
+ for (const key of nestedReferenceKeys(content)) {
1348
+ keys.add(key);
1349
+ }
1350
+ }
1351
+
1352
+ return keys;
1353
+ };
1354
+
1355
+ const registerNestedKeyLocations = (
1356
+ root: string,
1357
+ references: Map<string, TranslationReferences>,
1358
+ key: string,
1359
+ locations: ExtractedLocation[],
1360
+ ): void => {
1361
+ for (const location of locations) {
1362
+ if (location.line === undefined || location.column === undefined) {
1363
+ continue;
1364
+ }
1365
+
1366
+ const sourceReferences = references.get(resolve(root, location.file));
1367
+
1368
+ if (sourceReferences !== undefined) {
1369
+ registerEntryLocation(key, { column: location.column, line: location.line }, sourceReferences);
1370
+ }
1371
+ }
1372
+ };
1373
+
1374
+ const registerNestedTextLocations = (
1375
+ root: string,
1376
+ references: Map<string, TranslationReferences>,
1377
+ text: string,
1378
+ locations: ExtractedLocation[],
1379
+ ): void => {
1380
+ for (const key of nestedEntryKeys(text)) {
1381
+ registerNestedKeyLocations(root, references, key, locations);
1382
+ }
1383
+ };
1384
+
1385
+ const registerNestedEntryLocations = (
1386
+ root: string,
1387
+ references: Map<string, TranslationReferences>,
1388
+ entry: ExtractedKey,
1389
+ locations: ExtractedLocation[],
1390
+ ): void => {
1391
+ registerNestedTextLocations(root, references, entry.key, locations);
1392
+
1393
+ if (typeof entry.defaultValue === "string") {
1394
+ registerNestedTextLocations(root, references, entry.defaultValue, locations);
1395
+ }
1396
+ };
1397
+
1398
+ const didRegisterNestedLocationPass = (
1399
+ root: string,
1400
+ references: Map<string, TranslationReferences>,
1401
+ entries: ExtractedKeysMap,
1402
+ processed: Set<string>,
1403
+ ): boolean => {
1404
+ let didRegister = false;
1405
+
1406
+ for (const [mapKey, entry] of entries) {
1407
+ if (processed.has(mapKey)) {
1408
+ continue;
1409
+ }
1410
+
1411
+ const recognized = recognizedEntry(root, references, entry);
1412
+
1413
+ if (recognized !== null) {
1414
+ processed.add(mapKey);
1415
+ registerNestedEntryLocations(root, references, entry, recognized.locations ?? []);
1416
+ didRegister = true;
1417
+ }
1418
+ }
1419
+
1420
+ return didRegister;
1421
+ };
1422
+
1423
+ const registerNestedLocations = (
1424
+ root: string,
1425
+ references: Map<string, TranslationReferences>,
1426
+ entries: ExtractedKeysMap,
1427
+ ): void => {
1428
+ const processed: Set<string> = new Set();
1429
+ let hasRegisteredLocations = true;
1430
+
1431
+ while (hasRegisteredLocations) {
1432
+ hasRegisteredLocations = didRegisterNestedLocationPass(root, references, entries, processed);
1433
+ }
1434
+ };
1435
+
1436
+ const retainRecognizedEntries = (
1437
+ root: string,
1438
+ references: Map<string, TranslationReferences>,
1439
+ entries: ExtractedKeysMap,
1440
+ ): void => {
1441
+ for (const [mapKey, entry] of entries) {
1442
+ const recognized = recognizedEntry(root, references, entry);
1443
+
1444
+ if (recognized === null) {
1445
+ entries.delete(mapKey);
1446
+ } else {
1447
+ entries.set(mapKey, recognized);
1448
+ }
1449
+ }
1450
+ };
1451
+
1452
+ const fileSourcePointKey = (file: string, line: number, column: number): string =>
1453
+ `${file}\0${sourceLocationKey(line, column)}`;
1454
+
1455
+ const registerExtractedSourcePoint = (
1456
+ root: string,
1457
+ points: Set<string>,
1458
+ location: ExtractedLocation,
1459
+ ): void => {
1460
+ if (location.line !== undefined && location.column !== undefined) {
1461
+ points.add(fileSourcePointKey(resolve(root, location.file), location.line, location.column));
1462
+ }
1463
+ };
1464
+
1465
+ const extractedSourcePoints = (root: string, entries: ExtractedKeysMap): Set<string> => {
1466
+ const points: Set<string> = new Set();
1467
+
1468
+ for (const entry of entries.values()) {
1469
+ const locations = entry.locations ?? [];
1470
+
1471
+ for (const location of locations) {
1472
+ registerExtractedSourcePoint(root, points, location);
1473
+ }
1474
+ }
1475
+
1476
+ return points;
1477
+ };
1478
+
1479
+ const hasMissingSourcePoint = (
1480
+ file: string,
1481
+ references: TranslationReferences,
1482
+ extracted: Set<string>,
1483
+ ): boolean =>
1484
+ references.locations.values().some((location) => !extracted.has(`${file}\0${location}`));
1485
+
1486
+ const assertAllReferencesExtracted = (
1487
+ root: string,
1488
+ references: Map<string, TranslationReferences>,
1489
+ entries: ExtractedKeysMap,
1490
+ ): void => {
1491
+ const extracted = extractedSourcePoints(root, entries);
1492
+
1493
+ for (const [file, sourceReferences] of references) {
1494
+ if (hasMissingSourcePoint(file, sourceReferences, extracted)) {
1495
+ throw new Error("A translation expression could not be extracted safely");
1496
+ }
1497
+ }
1498
+ };
1499
+
297
1500
  const findSourceMessages = async (root: string, sourceFiles: string[]): Promise<SourceMessage[]> => {
298
1501
  if (sourceFiles.length === 0) {
299
1502
  clearI18nResources(root);
@@ -301,12 +1504,29 @@ const findSourceMessages = async (root: string, sourceFiles: string[]): Promise<
301
1504
  return [];
302
1505
  }
303
1506
 
1507
+ const sources = new Map(sourceFiles.map((file) => [file, readFileSync(file, "utf8")]));
1508
+ const references: Map<string, TranslationReferences> = new Map();
1509
+
1510
+ for (const [file, source] of sources) {
1511
+ references.set(file, assertSupportedTranslationSyntax(file, source));
1512
+ }
1513
+
304
1514
  let extracted: ExtractedKeysMap | undefined;
305
1515
  const { logger, reports } = quietLogger();
306
1516
 
307
1517
  const capture: Plugin = {
308
1518
  name: "gtkx-gettext",
1519
+ onLoad(code, path) {
1520
+ const sourceReferences = references.get(resolve(root, path));
1521
+
1522
+ return sourceReferences === undefined
1523
+ ? code
1524
+ : maskUnrecognizedTranslations(code, sourceReferences);
1525
+ },
309
1526
  onEnd(keys) {
1527
+ registerNestedLocations(root, references, keys);
1528
+ retainRecognizedEntries(root, references, keys);
1529
+ assertAllReferencesExtracted(root, references, keys);
310
1530
  extracted = keys;
311
1531
  },
312
1532
  };
@@ -322,8 +1542,6 @@ const findSourceMessages = async (root: string, sourceFiles: string[]): Promise<
322
1542
  throw new Error(reports.join("\n") || "i18next extraction failed");
323
1543
  }
324
1544
 
325
- const sources = new Map(sourceFiles.map((file) => [file, readFileSync(file, "utf8")]));
326
-
327
1545
  return sourceMessages(extracted.values().toArray())
328
1546
  .map((message) => inferLocations(message, sources))
329
1547
  .toSorted(compareMessages);