gt 2.23.2 → 2.24.0

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 (79) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/cli/base.js +23 -15
  3. package/dist/cli/base.js.map +1 -1
  4. package/dist/cli/flags.js +3 -2
  5. package/dist/cli/flags.js.map +1 -1
  6. package/dist/formats/files/postprocess/localizeMintlifyRedirects.d.ts +16 -0
  7. package/dist/formats/files/postprocess/localizeMintlifyRedirects.js +122 -0
  8. package/dist/formats/files/postprocess/localizeMintlifyRedirects.js.map +1 -0
  9. package/dist/fs/config/setupConfig.d.ts +14 -1
  10. package/dist/fs/config/setupConfig.js +33 -9
  11. package/dist/fs/config/setupConfig.js.map +1 -1
  12. package/dist/fs/createLoadTranslationsFile.js +1 -1
  13. package/dist/fs/createLoadTranslationsFile.js.map +1 -1
  14. package/dist/generated/version.d.ts +1 -1
  15. package/dist/generated/version.js +1 -1
  16. package/dist/generated/version.js.map +1 -1
  17. package/dist/react/config/createESBuildConfig.d.ts +1 -1
  18. package/dist/react/config/createESBuildConfig.js.map +1 -1
  19. package/dist/react/parse/createDictionaryUpdates.d.ts +1 -1
  20. package/dist/react/parse/createDictionaryUpdates.js +1 -1
  21. package/dist/react/parse/createDictionaryUpdates.js.map +1 -1
  22. package/dist/setup/buildTools/index.d.ts +2 -0
  23. package/dist/setup/buildTools/index.js +2 -1
  24. package/dist/setup/buildTools/index.js.map +1 -1
  25. package/dist/setup/buildTools/tanstackStart/edits.d.ts +21 -0
  26. package/dist/setup/buildTools/tanstackStart/edits.js +44 -0
  27. package/dist/setup/buildTools/tanstackStart/edits.js.map +1 -0
  28. package/dist/setup/buildTools/tanstackStart/index.d.ts +2 -0
  29. package/dist/setup/buildTools/tanstackStart/index.js +127 -0
  30. package/dist/setup/buildTools/tanstackStart/index.js.map +1 -0
  31. package/dist/setup/buildTools/tanstackStart/middleware.d.ts +9 -0
  32. package/dist/setup/buildTools/tanstackStart/middleware.js +59 -0
  33. package/dist/setup/buildTools/tanstackStart/middleware.js.map +1 -0
  34. package/dist/setup/buildTools/tanstackStart/root.d.ts +30 -0
  35. package/dist/setup/buildTools/tanstackStart/root.js +178 -0
  36. package/dist/setup/buildTools/tanstackStart/root.js.map +1 -0
  37. package/dist/setup/buildTools/tanstackStart/router.d.ts +15 -0
  38. package/dist/setup/buildTools/tanstackStart/router.js +64 -0
  39. package/dist/setup/buildTools/tanstackStart/router.js.map +1 -0
  40. package/dist/setup/buildTools/tanstackStart/source.d.ts +19 -0
  41. package/dist/setup/buildTools/tanstackStart/source.js +66 -0
  42. package/dist/setup/buildTools/tanstackStart/source.js.map +1 -0
  43. package/dist/setup/buildTools/vite.d.ts +1 -0
  44. package/dist/setup/buildTools/vite.js +3 -3
  45. package/dist/setup/buildTools/vite.js.map +1 -1
  46. package/dist/setup/detectFramework.d.ts +1 -1
  47. package/dist/setup/detectFramework.js +5 -1
  48. package/dist/setup/detectFramework.js.map +1 -1
  49. package/dist/setup/developmentCredentials.d.ts +1 -0
  50. package/dist/setup/developmentCredentials.js +12 -4
  51. package/dist/setup/developmentCredentials.js.map +1 -1
  52. package/dist/setup/frameworkUtils.js +4 -1
  53. package/dist/setup/frameworkUtils.js.map +1 -1
  54. package/dist/setup/onboarding.js +3 -3
  55. package/dist/setup/onboarding.js.map +1 -1
  56. package/dist/setup/setupViteSPA.d.ts +10 -1
  57. package/dist/setup/setupViteSPA.js +16 -3
  58. package/dist/setup/setupViteSPA.js.map +1 -1
  59. package/dist/setup/wizard.js +13 -2
  60. package/dist/setup/wizard.js.map +1 -1
  61. package/dist/state/orphanedFileNames.d.ts +4 -0
  62. package/dist/state/orphanedFileNames.js +16 -0
  63. package/dist/state/orphanedFileNames.js.map +1 -0
  64. package/dist/types/index.d.ts +2 -1
  65. package/dist/types/index.js +2 -1
  66. package/dist/types/index.js.map +1 -1
  67. package/dist/utils/constants.d.ts +1 -0
  68. package/dist/utils/constants.js +2 -1
  69. package/dist/utils/constants.js.map +1 -1
  70. package/dist/utils/credentials.js +2 -1
  71. package/dist/utils/credentials.js.map +1 -1
  72. package/dist/utils/localizeStaticUrls.d.ts +6 -0
  73. package/dist/utils/localizeStaticUrls.js +1 -1
  74. package/dist/utils/localizeStaticUrls.js.map +1 -1
  75. package/dist/utils/packageManager.js +21 -11
  76. package/dist/utils/packageManager.js.map +1 -1
  77. package/dist/workflows/steps/UploadSourcesStep.js +3 -0
  78. package/dist/workflows/steps/UploadSourcesStep.js.map +1 -1
  79. package/package.json +4 -3
@@ -0,0 +1,16 @@
1
+ import type { Settings } from '../../../types/index.js';
2
+ type Redirect = {
3
+ source: string;
4
+ destination: string;
5
+ permanent?: unknown;
6
+ };
7
+ /**
8
+ * Adds localized copies of the English redirects whose source is a renamed or
9
+ * removed page, and returns the redirects it added. Orphaned file names come
10
+ * from the upload step, so redirects for pages GT never translated are never
11
+ * localized. URLs are localized like links inside
12
+ * pages: with docsUrlPattern, and not for locales missing the destination's
13
+ * translation.
14
+ */
15
+ export declare function localizeMintlifyRedirects(settings: Settings, orphanedFileNames: string[]): Redirect[];
16
+ export {};
@@ -0,0 +1,122 @@
1
+ import { logger } from "../../../console/logger.js";
2
+ import { getRelative } from "../../../fs/findFilepath.js";
3
+ import loadJSON from "../../../fs/loadJSON.js";
4
+ import { createFileMapping } from "../fileMapping.js";
5
+ import { PAGE_EXTENSIONS, transformUrlPath, translationMissing } from "../../../utils/localizeStaticUrls.js";
6
+ import path from "node:path";
7
+ import fs from "node:fs";
8
+ import { createDiagnosticMessage } from "generaltranslation/diagnostics";
9
+ //#region src/formats/files/postprocess/localizeMintlifyRedirects.ts
10
+ const missingDocsUrlPatternWarning = createDiagnosticMessage({
11
+ source: "gt",
12
+ severity: "Warning",
13
+ whatHappened: "Localized redirects were not added",
14
+ why: "options.mintlify.localizeRedirects uses options.docsUrlPattern to place the locale in redirect URLs",
15
+ fix: "Set options.docsUrlPattern in gt.config.json, such as \"/docs/[locale]\""
16
+ });
17
+ /**
18
+ * Adds localized copies of the English redirects whose source is a renamed or
19
+ * removed page, and returns the redirects it added. Orphaned file names come
20
+ * from the upload step, so redirects for pages GT never translated are never
21
+ * localized. URLs are localized like links inside
22
+ * pages: with docsUrlPattern, and not for locales missing the destination's
23
+ * translation.
24
+ */
25
+ function localizeMintlifyRedirects(settings, orphanedFileNames) {
26
+ if (settings.options?.mintlify?.localizeRedirects !== true || !settings.files) return [];
27
+ const urlPattern = settings.options.docsUrlPattern;
28
+ if (!urlPattern) {
29
+ logger.warn(missingDocsUrlPatternWarning);
30
+ return [];
31
+ }
32
+ const location = readRedirects(path.resolve("docs.json"));
33
+ if (!location) return [];
34
+ const oldPageUrls = new Set(orphanedFileNames.filter((fileName) => PAGE_EXTENSIONS.includes(path.extname(fileName))).map(pageUrl));
35
+ const targetLocales = settings.locales.filter((locale) => locale !== settings.defaultLocale);
36
+ const { files } = settings;
37
+ const fileMapping = createFileMapping(files.resolvedPaths, files.placeholderPaths, files.transformPaths, files.transformFormats, targetLocales, settings.defaultLocale);
38
+ const urlPatternHead = urlPattern.split("[locale]")[0];
39
+ const localizeUrl = (url, locale) => {
40
+ const localized = transformUrlPath(url, urlPatternHead, locale, settings.defaultLocale, settings.options?.experimentalHideDefaultLocale ?? false);
41
+ return localized === null ? null : normalizeUrl(localized);
42
+ };
43
+ const takenSources = new Set(location.redirects.filter(isRedirect).map((r) => normalizeUrl(r.source)));
44
+ const added = [];
45
+ const updated = location.redirects.flatMap((entry) => {
46
+ if (!isRedirect(entry)) return [entry];
47
+ const [destinationPath, anchor] = splitAnchor(entry.destination);
48
+ const sourceUrl = normalizeUrl(entry.source);
49
+ const destinationUrl = normalizeUrl(destinationPath);
50
+ if (!oldPageUrls.has(sourceUrl)) return [entry];
51
+ const localized = [];
52
+ for (const locale of targetLocales) {
53
+ const localizedSource = localizeUrl(sourceUrl, locale);
54
+ const localizedDestination = localizeUrl(destinationUrl, locale);
55
+ if (!localizedSource || !localizedDestination || localizedSource === localizedDestination || takenSources.has(localizedSource) || translationMissing(destinationUrl, localizedDestination, fileMapping[locale] ?? {})) continue;
56
+ takenSources.add(localizedSource);
57
+ localized.push({
58
+ source: localizedSource,
59
+ destination: `${localizedDestination}${anchor}`,
60
+ ..."permanent" in entry && { permanent: entry.permanent }
61
+ });
62
+ }
63
+ added.push(...localized);
64
+ return [entry, ...localized];
65
+ });
66
+ if (added.length > 0) location.write(updated);
67
+ return added;
68
+ }
69
+ function isRedirect(entry) {
70
+ return typeof entry?.source === "string" && typeof entry?.destination === "string";
71
+ }
72
+ /** Splits `/docs/page#section` into `/docs/page` and `#section`. */
73
+ function splitAnchor(url) {
74
+ const anchorStart = url.indexOf("#");
75
+ return anchorStart === -1 ? [url, ""] : [url.slice(0, anchorStart), url.slice(anchorStart)];
76
+ }
77
+ /**
78
+ * The URL of a page file: its path without the extension. Like static URL
79
+ * localization, URLs are relative to the working directory.
80
+ */
81
+ function pageUrl(fileName) {
82
+ const relative = getRelative(fileName);
83
+ return normalizeUrl(relative.slice(0, relative.length - path.extname(relative).length).split(path.sep).join("/"));
84
+ }
85
+ /**
86
+ * Leading slash, no trailing slash, and index pages named by their folder, so
87
+ * equivalent spellings compare equal.
88
+ */
89
+ function normalizeUrl(url) {
90
+ const segments = url.split("/").filter(Boolean);
91
+ if (segments.at(-1) === "index") segments.pop();
92
+ return `/${segments.join("/")}`;
93
+ }
94
+ /**
95
+ * Finds the redirects array in docs.json, either inline or at the end of its
96
+ * `$ref` chain, and returns a writer for the file that holds it.
97
+ */
98
+ function readRedirects(docsJsonPath) {
99
+ const docsJson = loadJSON(docsJsonPath);
100
+ let holder = docsJsonPath;
101
+ let value = docsJson?.redirects;
102
+ const visited = new Set([holder]);
103
+ while (typeof value?.$ref === "string") {
104
+ holder = path.resolve(path.dirname(holder), value.$ref);
105
+ if (visited.has(holder)) return null;
106
+ visited.add(holder);
107
+ value = loadJSON(holder);
108
+ }
109
+ if (!Array.isArray(value)) return null;
110
+ const redirectsFile = holder;
111
+ return {
112
+ redirects: value,
113
+ write: (updated) => fs.writeFileSync(redirectsFile, JSON.stringify(redirectsFile === docsJsonPath ? {
114
+ ...docsJson,
115
+ redirects: updated
116
+ } : updated, null, 2))
117
+ };
118
+ }
119
+ //#endregion
120
+ export { localizeMintlifyRedirects };
121
+
122
+ //# sourceMappingURL=localizeMintlifyRedirects.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localizeMintlifyRedirects.js","names":[],"sources":["../../../../src/formats/files/postprocess/localizeMintlifyRedirects.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { logger } from '../../../console/logger.js';\nimport { getRelative } from '../../../fs/findFilepath.js';\nimport loadJSON from '../../../fs/loadJSON.js';\nimport type { Settings } from '../../../types/index.js';\nimport {\n INDEX_PAGE,\n PAGE_EXTENSIONS,\n transformUrlPath,\n translationMissing,\n} from '../../../utils/localizeStaticUrls.js';\nimport { createFileMapping } from '../fileMapping.js';\n\ntype Redirect = { source: string; destination: string; permanent?: unknown };\n\nconst missingDocsUrlPatternWarning = createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: 'Localized redirects were not added',\n why: 'options.mintlify.localizeRedirects uses options.docsUrlPattern to place the locale in redirect URLs',\n fix: 'Set options.docsUrlPattern in gt.config.json, such as \"/docs/[locale]\"',\n});\n\n/**\n * Adds localized copies of the English redirects whose source is a renamed or\n * removed page, and returns the redirects it added. Orphaned file names come\n * from the upload step, so redirects for pages GT never translated are never\n * localized. URLs are localized like links inside\n * pages: with docsUrlPattern, and not for locales missing the destination's\n * translation.\n */\nexport function localizeMintlifyRedirects(\n settings: Settings,\n orphanedFileNames: string[]\n): Redirect[] {\n if (\n settings.options?.mintlify?.localizeRedirects !== true ||\n !settings.files\n ) {\n return [];\n }\n const urlPattern = settings.options.docsUrlPattern;\n if (!urlPattern) {\n logger.warn(missingDocsUrlPatternWarning);\n return [];\n }\n const location = readRedirects(path.resolve('docs.json'));\n if (!location) return [];\n\n const oldPageUrls = new Set(\n orphanedFileNames\n .filter((fileName) => PAGE_EXTENSIONS.includes(path.extname(fileName)))\n .map(pageUrl)\n );\n\n const targetLocales = settings.locales.filter(\n (locale) => locale !== settings.defaultLocale\n );\n const { files } = settings;\n const fileMapping = createFileMapping(\n files.resolvedPaths,\n files.placeholderPaths,\n files.transformPaths,\n files.transformFormats,\n targetLocales,\n settings.defaultLocale\n );\n // Localize URLs the way links inside pages are localized\n const urlPatternHead = urlPattern.split('[locale]')[0];\n const localizeUrl = (url: string, locale: string) => {\n const localized = transformUrlPath(\n url,\n urlPatternHead,\n locale,\n settings.defaultLocale,\n settings.options?.experimentalHideDefaultLocale ?? false\n );\n return localized === null ? null : normalizeUrl(localized);\n };\n const takenSources = new Set(\n location.redirects.filter(isRedirect).map((r) => normalizeUrl(r.source))\n );\n\n const added: Redirect[] = [];\n const updated = location.redirects.flatMap((entry) => {\n if (!isRedirect(entry)) return [entry];\n const [destinationPath, anchor] = splitAnchor(entry.destination);\n const sourceUrl = normalizeUrl(entry.source);\n const destinationUrl = normalizeUrl(destinationPath);\n if (!oldPageUrls.has(sourceUrl)) return [entry];\n\n const localized: Redirect[] = [];\n for (const locale of targetLocales) {\n const localizedSource = localizeUrl(sourceUrl, locale);\n const localizedDestination = localizeUrl(destinationUrl, locale);\n if (\n !localizedSource ||\n !localizedDestination ||\n localizedSource === localizedDestination ||\n takenSources.has(localizedSource) ||\n translationMissing(\n destinationUrl,\n localizedDestination,\n fileMapping[locale] ?? {}\n )\n ) {\n continue;\n }\n takenSources.add(localizedSource);\n localized.push({\n source: localizedSource,\n destination: `${localizedDestination}${anchor}`,\n ...('permanent' in entry && { permanent: entry.permanent }),\n });\n }\n added.push(...localized);\n return [entry, ...localized];\n });\n\n if (added.length > 0) location.write(updated);\n return added;\n}\n\nfunction isRedirect(entry: unknown): entry is Redirect {\n return (\n typeof (entry as Redirect)?.source === 'string' &&\n typeof (entry as Redirect)?.destination === 'string'\n );\n}\n\n/** Splits `/docs/page#section` into `/docs/page` and `#section`. */\nfunction splitAnchor(url: string): [string, string] {\n const anchorStart = url.indexOf('#');\n return anchorStart === -1\n ? [url, '']\n : [url.slice(0, anchorStart), url.slice(anchorStart)];\n}\n\n/**\n * The URL of a page file: its path without the extension. Like static URL\n * localization, URLs are relative to the working directory.\n */\nfunction pageUrl(fileName: string): string {\n const relative = getRelative(fileName);\n return normalizeUrl(\n relative\n .slice(0, relative.length - path.extname(relative).length)\n .split(path.sep)\n .join('/')\n );\n}\n\n/**\n * Leading slash, no trailing slash, and index pages named by their folder, so\n * equivalent spellings compare equal.\n */\nfunction normalizeUrl(url: string): string {\n const segments = url.split('/').filter(Boolean);\n if (segments.at(-1) === INDEX_PAGE) segments.pop();\n return `/${segments.join('/')}`;\n}\n\n/**\n * Finds the redirects array in docs.json, either inline or at the end of its\n * `$ref` chain, and returns a writer for the file that holds it.\n */\nfunction readRedirects(\n docsJsonPath: string\n): { redirects: unknown[]; write: (redirects: unknown[]) => void } | null {\n const docsJson = loadJSON(docsJsonPath);\n let holder = docsJsonPath;\n let value: unknown = docsJson?.redirects;\n const visited = new Set([holder]);\n while (typeof (value as { $ref?: unknown })?.$ref === 'string') {\n holder = path.resolve(\n path.dirname(holder),\n (value as { $ref: string }).$ref\n );\n if (visited.has(holder)) return null;\n visited.add(holder);\n value = loadJSON(holder);\n }\n if (!Array.isArray(value)) return null;\n\n const redirectsFile = holder;\n return {\n redirects: value,\n write: (updated) =>\n fs.writeFileSync(\n redirectsFile,\n JSON.stringify(\n redirectsFile === docsJsonPath\n ? { ...docsJson, redirects: updated }\n : updated,\n null,\n 2\n )\n ),\n };\n}\n"],"mappings":";;;;;;;;;AAiBA,MAAM,+BAA+B,wBAAwB;CAC3D,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACL,KAAK;CACN,CAAC;;;;;;;;;AAUF,SAAgB,0BACd,UACA,mBACY;AACZ,KACE,SAAS,SAAS,U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O,OAAQ,OAA8B,SAAS,UAAU;AAC9D,WAAS,KAAK,QACZ,KAAK,QAAQ,OAAO,EACnB,MAA2B,KAC7B;AACD,MAAI,QAAQ,IAAI,OAAO,CAAE,QAAO;AAChC,UAAQ,IAAI,OAAO;AACnB,UAAQ,SAAS,OAAO;;AAE1B,KAAI,CAAC,MAAM,QAAQ,MAAM,CAAE,QAAO;CAElC,MAAM,gBAAgB;AACtB,QAAO;EACL,WAAW;EACX,QAAQ,YACN,GAAG,cACD,eACA,KAAK,UACH,kBAAkB,eACd;GAAE,GAAG;GAAU,WAAW;GAAS,GACnC,SACJ,MACA,EACD,CACF;EACJ"}
@@ -20,10 +20,23 @@ export type SetupConfigUpdate = {
20
20
  * Unrelated fields and per-format options are kept; locales are replaced.
21
21
  */
22
22
  export declare function mergeSetupConfig(oldContent: Record<string, unknown>, options: SetupConfigUpdate): Record<string, unknown>;
23
+ export type SetupConfigChange = 'created' | 'updated' | 'unchanged';
23
24
  /**
24
- * Creates the config file, or applies the update to the existing one.
25
+ * Creates the config file, or applies the update to the existing one. An
26
+ * update keeps the file's indentation and trailing newline; a config that
27
+ * already has the update is not rewritten.
25
28
  * @param {string} configFilepath - The path to the config file.
26
29
  * @param {SetupConfigUpdate} options - The values setup resolved.
30
+ * @returns Whether the config was created, updated, or left unchanged.
31
+ * @throws When the existing file is not valid JSON or cannot be written.
32
+ */
33
+ export declare function applySetupConfig(configFilepath: string, options: SetupConfigUpdate): Promise<SetupConfigChange>;
34
+ /**
35
+ * Same as {@link applySetupConfig}, keeping the published contract of
36
+ * returning the config filepath.
37
+ * @param {string} configFilepath - The path to the config file.
38
+ * @param {SetupConfigUpdate} options - The values setup resolved.
39
+ * @returns The config filepath.
27
40
  * @throws When the existing file is not valid JSON or cannot be written.
28
41
  */
29
42
  export declare function createOrUpdateConfig(configFilepath: string, options: SetupConfigUpdate): Promise<string>;
@@ -1,7 +1,8 @@
1
1
  import { GT_CONFIG_SCHEMA_URL } from "../../utils/constants.js";
2
- import { displayCreatedConfigFile } from "../../console/logging.js";
2
+ import { displayCreatedConfigFile, displayUpdatedConfigFile } from "../../console/logging.js";
3
3
  import { createDiagnosticMessage, formatDiagnosticErrorDetails } from "generaltranslation/internal";
4
4
  import fs from "node:fs";
5
+ import { isDeepStrictEqual } from "node:util";
5
6
  //#region src/fs/config/setupConfig.ts
6
7
  function asObject(value) {
7
8
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -46,22 +47,34 @@ function mergeSetupConfig(oldContent, options) {
46
47
  return mergedContent;
47
48
  }
48
49
  /**
49
- * Creates the config file, or applies the update to the existing one.
50
+ * Creates the config file, or applies the update to the existing one. An
51
+ * update keeps the file's indentation and trailing newline; a config that
52
+ * already has the update is not rewritten.
50
53
  * @param {string} configFilepath - The path to the config file.
51
54
  * @param {SetupConfigUpdate} options - The values setup resolved.
55
+ * @returns Whether the config was created, updated, or left unchanged.
52
56
  * @throws When the existing file is not valid JSON or cannot be written.
53
57
  */
54
- async function createOrUpdateConfig(configFilepath, options) {
58
+ async function applySetupConfig(configFilepath, options) {
55
59
  try {
56
60
  let oldContent = {};
57
- if (fs.existsSync(configFilepath)) {
58
- const parsed = JSON.parse(await fs.promises.readFile(configFilepath, "utf-8"));
61
+ const oldText = fs.existsSync(configFilepath) ? await fs.promises.readFile(configFilepath, "utf-8") : void 0;
62
+ if (oldText !== void 0) {
63
+ const parsed = JSON.parse(oldText);
59
64
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("the file does not contain a JSON object");
60
65
  oldContent = parsed;
61
66
  }
62
- const mergedJsonContent = JSON.stringify(mergeSetupConfig(oldContent, options), null, 2);
63
- await fs.promises.writeFile(configFilepath, mergedJsonContent, "utf-8");
64
- displayCreatedConfigFile(configFilepath);
67
+ const mergedContent = mergeSetupConfig(oldContent, options);
68
+ if (oldText !== void 0 && isDeepStrictEqual(mergedContent, oldContent)) return "unchanged";
69
+ const indent = [...(oldText ?? "").matchAll(/^[ \t]+(?=")/gm)].map(([match]) => match).sort((a, b) => a.length - b.length)[0] ?? 2;
70
+ const newline = oldText === void 0 || oldText.endsWith("\n") ? "\n" : "";
71
+ await fs.promises.writeFile(configFilepath, `${JSON.stringify(mergedContent, null, indent)}${newline}`, "utf-8");
72
+ if (oldText === void 0) {
73
+ displayCreatedConfigFile(configFilepath);
74
+ return "created";
75
+ }
76
+ displayUpdatedConfigFile(configFilepath);
77
+ return "updated";
65
78
  } catch (error) {
66
79
  throw new Error(createDiagnosticMessage({
67
80
  source: "gt",
@@ -71,9 +84,20 @@ async function createOrUpdateConfig(configFilepath, options) {
71
84
  fix: "Fix or remove the file, then rerun the command"
72
85
  }));
73
86
  }
87
+ }
88
+ /**
89
+ * Same as {@link applySetupConfig}, keeping the published contract of
90
+ * returning the config filepath.
91
+ * @param {string} configFilepath - The path to the config file.
92
+ * @param {SetupConfigUpdate} options - The values setup resolved.
93
+ * @returns The config filepath.
94
+ * @throws When the existing file is not valid JSON or cannot be written.
95
+ */
96
+ async function createOrUpdateConfig(configFilepath, options) {
97
+ await applySetupConfig(configFilepath, options);
74
98
  return configFilepath;
75
99
  }
76
100
  //#endregion
77
- export { createOrUpdateConfig, mergeSetupConfig };
101
+ export { applySetupConfig, createOrUpdateConfig, mergeSetupConfig };
78
102
 
79
103
  //# sourceMappingURL=setupConfig.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"setupConfig.js","names":[],"sources":["../../../src/fs/config/setupConfig.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { displayCreatedConfigFile } from '../../console/logging.js';\nimport { FilesOptions, SupportedFrameworks } from '../../types/index.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\nimport { GT_CONFIG_SCHEMA_URL } from '../../utils/constants.js';\n\nexport type SetupConfigUpdate = {\n projectId?: string;\n defaultLocale?: string;\n locales?: string[];\n src?: string[];\n files?: FilesOptions;\n framework?: SupportedFrameworks;\n baseUrl?: string;\n publish?: boolean;\n /** Removes stale global CDN intent when the selected runtime forbids it. */\n clearPublish?: boolean;\n /** File format entries deselected by an explicit format list. */\n removeFiles?: string[];\n /** Drops files.gt.output after an explicit switch to CDN storage. */\n clearGtOutput?: boolean;\n};\n\nfunction asObject(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\n/**\n * The config setup writes: the existing content with the update applied.\n * Unrelated fields and per-format options are kept; locales are replaced.\n */\nexport function mergeSetupConfig(\n oldContent: Record<string, unknown>,\n options: SetupConfigUpdate\n): Record<string, unknown> {\n // Filter out empty string values from the config object\n const newContent = {\n ...(options.projectId && { projectId: options.projectId }),\n ...(options.defaultLocale && { defaultLocale: options.defaultLocale }),\n ...(options.src && { src: options.src }),\n ...(options.framework && { framework: options.framework }),\n ...(options.baseUrl && { baseUrl: options.baseUrl }),\n ...(options.publish && { publish: options.publish }),\n };\n const mergedContent: Record<string, unknown> = {\n $schema: GT_CONFIG_SCHEMA_URL,\n ...oldContent,\n ...newContent,\n };\n\n if (options.clearPublish) {\n delete mergedContent.publish;\n }\n\n // Preserve unrelated file configuration and nested GT options when setup\n // only needs to add or update a translation output path.\n if (options.files || options.removeFiles?.length || options.clearGtOutput) {\n const oldFiles = asObject(oldContent.files);\n const files: Record<string, unknown> = { ...oldFiles, ...options.files };\n const gt = { ...asObject(oldFiles.gt), ...options.files?.gt };\n if (options.clearGtOutput) delete gt.output;\n if (Object.keys(gt).length > 0) files.gt = gt;\n else delete files.gt;\n for (const format of options.removeFiles ?? []) delete files[format];\n if (Object.keys(files).length > 0) mergedContent.files = files;\n else delete mergedContent.files;\n }\n\n // The selected locale list replaces the configured one.\n if (options.locales) {\n mergedContent.locales = options.locales;\n }\n return mergedContent;\n}\n\n/**\n * Creates the config file, or applies the update to the existing one.\n * @param {string} configFilepath - The path to the config file.\n * @param {SetupConfigUpdate} options - The values setup resolved.\n * @throws When the existing file is not valid JSON or cannot be written.\n */\nexport async function createOrUpdateConfig(\n configFilepath: string,\n options: SetupConfigUpdate\n): Promise<string> {\n try {\n let oldContent: Record<string, unknown> = {};\n if (fs.existsSync(configFilepath)) {\n const parsed = JSON.parse(\n await fs.promises.readFile(configFilepath, 'utf-8')\n );\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Array.isArray(parsed)\n )\n throw new Error('the file does not contain a JSON object');\n oldContent = parsed as Record<string, unknown>;\n }\n\n const mergedJsonContent = JSON.stringify(\n mergeSetupConfig(oldContent, options),\n null,\n 2\n );\n await fs.promises.writeFile(configFilepath, mergedJsonContent, 'utf-8');\n\n // show update in console\n displayCreatedConfigFile(configFilepath);\n } catch (error) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not update ${configFilepath}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Fix or remove the file, then rerun the command',\n })\n );\n }\n return configFilepath;\n}\n"],"mappings":";;;;;AA0BA,SAAS,SAAS,OAAyC;AACzD,QAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM,GAC7D,QACD,EAAE;;;;;;AAOR,SAAgB,iBACd,YACA,SACyB;CAEzB,MAAM,aAAa;EACjB,GAAI,QAAQ,aAAa,EAAE,WAAW,QAAQ,WAAW;EACzD,GAAI,QAAQ,iBAAiB,EAAE,eAAe,QAAQ,eAAe;EACrE,GAAI,QAAQ,OAAO,EAAE,KAAK,QAAQ,KAAK;EACvC,GAAI,QAAQ,aAAa,EAAE,WAAW,QAAQ,WAAW;EACzD,GAAI,QAAQ,WAAW,EAAE,SAAS,QAAQ,SAAS;EACnD,GAAI,QAAQ,WAAW,EAAE,SAAS,QAAQ,SAAS;EACpD;CACD,MAAM,gBAAyC;EAC7C,SAAS;EACT,GAAG;EACH,GAAG;EACJ;AAED,KAAI,QAAQ,aACV,QAAO,cAAc;AAKvB,KAAI,QAAQ,SAAS,QAAQ,aAAa,UAAU,QAAQ,eAAe;EACzE,MAAM,WAAW,SAAS,WAAW,MAAM;EAC3C,MAAM,QAAiC;GAAE,GAAG;GAAU,GAAG,QAAQ;GAAO;EACxE,MAAM,KAAK;GAAE,GAAG,SAAS,SAAS,GAAG;GAAE,GAAG,QAAQ,OAAO;GAAI;AAC7D,MAAI,QAAQ,cAAe,QAAO,GAAG;AACrC,MAAI,OAAO,KAAK,GAAG,CAAC,SAAS,EAAG,OAAM,KAAK;MACtC,QAAO,MAAM;AAClB,OAAK,MAAM,UAAU,QAAQ,eAAe,EAAE,CAAE,QAAO,MAAM;AAC7D,MAAI,OAAO,KAAK,MAAM,CAAC,SAAS,EAAG,eAAc,QAAQ;MACpD,QAAO,cAAc;;AAI5B,KAAI,QAAQ,QACV,eAAc,UAAU,QAAQ;AAElC,QAAO;;;;;;;;AAST,eAAsB,qBACpB,gBACA,SACiB;AACjB,KAAI;EACF,IAAI,aAAsC,EAAE;AAC5C,MAAI,GAAG,WAAW,eAAe,EAAE;GACjC,MAAM,SAAS,KAAK,MAClB,MAAM,GAAG,SAAS,SAAS,gBAAgB,QAAQ,CACpD;AACD,OACE,OAAO,WAAW,YAClB,WAAW,QACX,MAAM,QAAQ,OAAO,CAErB,OAAM,IAAI,MAAM,0CAA0C;AAC5D,gBAAa;;EAGf,MAAM,oBAAoB,KAAK,UAC7B,iBAAiB,YAAY,QAAQ,EACrC,MACA,EACD;AACD,QAAM,GAAG,SAAS,UAAU,gBAAgB,mBAAmB,QAAQ;AAGvE,2BAAyB,eAAe;UACjC,OAAO;AACd,QAAM,IAAI,MACR,wBAAwB;GACtB,QAAQ;GACR,UAAU;GACV,cAAc,oBAAoB;GAClC,SAAS,6BAA6B,MAAM;GAC5C,KAAK;GACN,CAAC,CACH;;AAEH,QAAO"}
1
+ {"version":3,"file":"setupConfig.js","names":[],"sources":["../../../src/fs/config/setupConfig.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { isDeepStrictEqual } from 'node:util';\nimport {\n displayCreatedConfigFile,\n displayUpdatedConfigFile,\n} from '../../console/logging.js';\nimport { FilesOptions, SupportedFrameworks } from '../../types/index.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\nimport { GT_CONFIG_SCHEMA_URL } from '../../utils/constants.js';\n\nexport type SetupConfigUpdate = {\n projectId?: string;\n defaultLocale?: string;\n locales?: string[];\n src?: string[];\n files?: FilesOptions;\n framework?: SupportedFrameworks;\n baseUrl?: string;\n publish?: boolean;\n /** Removes stale global CDN intent when the selected runtime forbids it. */\n clearPublish?: boolean;\n /** File format entries deselected by an explicit format list. */\n removeFiles?: string[];\n /** Drops files.gt.output after an explicit switch to CDN storage. */\n clearGtOutput?: boolean;\n};\n\nfunction asObject(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\n/**\n * The config setup writes: the existing content with the update applied.\n * Unrelated fields and per-format options are kept; locales are replaced.\n */\nexport function mergeSetupConfig(\n oldContent: Record<string, unknown>,\n options: SetupConfigUpdate\n): Record<string, unknown> {\n // Filter out empty string values from the config object\n const newContent = {\n ...(options.projectId && { projectId: options.projectId }),\n ...(options.defaultLocale && { defaultLocale: options.defaultLocale }),\n ...(options.src && { src: options.src }),\n ...(options.framework && { framework: options.framework }),\n ...(options.baseUrl && { baseUrl: options.baseUrl }),\n ...(options.publish && { publish: options.publish }),\n };\n const mergedContent: Record<string, unknown> = {\n $schema: GT_CONFIG_SCHEMA_URL,\n ...oldContent,\n ...newContent,\n };\n\n if (options.clearPublish) {\n delete mergedContent.publish;\n }\n\n // Preserve unrelated file configuration and nested GT options when setup\n // only needs to add or update a translation output path.\n if (options.files || options.removeFiles?.length || options.clearGtOutput) {\n const oldFiles = asObject(oldContent.files);\n const files: Record<string, unknown> = { ...oldFiles, ...options.files };\n const gt = { ...asObject(oldFiles.gt), ...options.files?.gt };\n if (options.clearGtOutput) delete gt.output;\n if (Object.keys(gt).length > 0) files.gt = gt;\n else delete files.gt;\n for (const format of options.removeFiles ?? []) delete files[format];\n if (Object.keys(files).length > 0) mergedContent.files = files;\n else delete mergedContent.files;\n }\n\n // The selected locale list replaces the configured one.\n if (options.locales) {\n mergedContent.locales = options.locales;\n }\n return mergedContent;\n}\n\nexport type SetupConfigChange = 'created' | 'updated' | 'unchanged';\n\n/**\n * Creates the config file, or applies the update to the existing one. An\n * update keeps the file's indentation and trailing newline; a config that\n * already has the update is not rewritten.\n * @param {string} configFilepath - The path to the config file.\n * @param {SetupConfigUpdate} options - The values setup resolved.\n * @returns Whether the config was created, updated, or left unchanged.\n * @throws When the existing file is not valid JSON or cannot be written.\n */\nexport async function applySetupConfig(\n configFilepath: string,\n options: SetupConfigUpdate\n): Promise<SetupConfigChange> {\n try {\n let oldContent: Record<string, unknown> = {};\n const oldText = fs.existsSync(configFilepath)\n ? await fs.promises.readFile(configFilepath, 'utf-8')\n : undefined;\n if (oldText !== undefined) {\n const parsed = JSON.parse(oldText);\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Array.isArray(parsed)\n )\n throw new Error('the file does not contain a JSON object');\n oldContent = parsed as Record<string, unknown>;\n }\n\n const mergedContent = mergeSetupConfig(oldContent, options);\n if (oldText !== undefined && isDeepStrictEqual(mergedContent, oldContent))\n return 'unchanged';\n\n // Nested keys are indented further, so the shallowest key line is the\n // file's own indent unit.\n const indent =\n [...(oldText ?? '').matchAll(/^[ \\t]+(?=\")/gm)]\n .map(([match]) => match)\n .sort((a, b) => a.length - b.length)[0] ?? 2;\n const newline = oldText === undefined || oldText.endsWith('\\n') ? '\\n' : '';\n await fs.promises.writeFile(\n configFilepath,\n `${JSON.stringify(mergedContent, null, indent)}${newline}`,\n 'utf-8'\n );\n\n if (oldText === undefined) {\n displayCreatedConfigFile(configFilepath);\n return 'created';\n }\n displayUpdatedConfigFile(configFilepath);\n return 'updated';\n } catch (error) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not update ${configFilepath}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Fix or remove the file, then rerun the command',\n })\n );\n }\n}\n\n/**\n * Same as {@link applySetupConfig}, keeping the published contract of\n * returning the config filepath.\n * @param {string} configFilepath - The path to the config file.\n * @param {SetupConfigUpdate} options - The values setup resolved.\n * @returns The config filepath.\n * @throws When the existing file is not valid JSON or cannot be written.\n */\nexport async function createOrUpdateConfig(\n configFilepath: string,\n options: SetupConfigUpdate\n): Promise<string> {\n await applySetupConfig(configFilepath, options);\n return configFilepath;\n}\n"],"mappings":";;;;;;AA8BA,SAAS,SAAS,OAAyC;AACzD,QAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM,GAC7D,QACD,EAAE;;;;;;AAOR,SAAgB,iBACd,YACA,SACyB;CAEzB,MAAM,aAAa;EACjB,GAAI,QAAQ,aAAa,EAAE,WAAW,QAAQ,WAAW;EACzD,GAAI,QAAQ,iBAAiB,EAAE,eAAe,QAAQ,eAAe;EACrE,GAAI,QAAQ,OAAO,EAAE,KAAK,QAAQ,KAAK;EACvC,GAAI,QAAQ,aAAa,EAAE,WAAW,QAAQ,WAAW;EACzD,GAAI,QAAQ,WAAW,EAAE,SAAS,QAAQ,SAAS;EACnD,GAAI,QAAQ,WAAW,EAAE,SAAS,QAAQ,SAAS;EACpD;CACD,MAAM,gBAAyC;EAC7C,SAAS;EACT,GAAG;EACH,GAAG;EACJ;AAED,KAAI,QAAQ,aACV,QAAO,cAAc;AAKvB,KAAI,QAAQ,SAAS,QAAQ,aAAa,UAAU,QAAQ,eAAe;EACzE,MAAM,WAAW,SAAS,WAAW,MAAM;EAC3C,MAAM,QAAiC;GAAE,GAAG;GAAU,GAAG,QAAQ;GAAO;EACxE,MAAM,KAAK;GAAE,GAAG,SAAS,SAAS,GAAG;GAAE,GAAG,QAAQ,OAAO;GAAI;AAC7D,MAAI,QAAQ,cAAe,QAAO,GAAG;AACrC,MAAI,OAAO,KAAK,GAAG,CAAC,SAAS,EAAG,OAAM,KAAK;MACtC,QAAO,MA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qBACpB,gBACA,SACiB;AACjB,OAAM,iBAAiB,gBAAgB,QAAQ;AAC/C,QAAO"}
@@ -59,7 +59,7 @@ async function createLoadTranslationsFile({ appDirectory, translationsDir = DEFA
59
59
  logger.info(`Found a custom ${chalk.cyan(path.basename(loaderPath ?? filePath))} at ${chalk.cyan(loaderPath ?? filePath)}; leaving it unchanged.`);
60
60
  return "custom";
61
61
  }
62
- if (existing === content) return "unchanged";
62
+ if (existing === content || existing !== void 0 && previousTranslationsDir !== void 0 && path.resolve(appDirectory, previousTranslationsDir) === translationsPath) return "unchanged";
63
63
  await fs.promises.writeFile(filePath, content);
64
64
  logger.info(`${existing === void 0 ? "Created" : "Updated"} ${chalk.cyan("loadTranslations.js")} at ${chalk.cyan(filePath)}.`);
65
65
  return existing === void 0 ? "created" : "updated";
@@ -1 +1 @@
1
- {"version":3,"file":"createLoadTranslationsFile.js","names":[],"sources":["../../src/fs/createLoadTranslationsFile.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport chalk from 'chalk';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\n\nfunction toRelativeImportPath(relativePath: string) {\n const normalizedPath = relativePath.split(path.sep).join(path.posix.sep);\n\n if (!normalizedPath) {\n return './';\n }\n\n // Dynamic imports must use explicit relative specifiers; values like\n // \"src/_gt\" are otherwise treated as package names by Vite and Node.\n const hasExplicitRelativePrefix =\n normalizedPath === '..' ||\n normalizedPath.startsWith('../') ||\n normalizedPath.startsWith('./');\n\n return hasExplicitRelativePrefix\n ? `${normalizedPath}/`\n : `./${normalizedPath}/`;\n}\n\nfunction getLoaderContent(translationsDir: string, publicPath: string) {\n return `\nexport default async function loadTranslations(locale) {\n try {\n // Load translations from ${translationsDir} directory\n // This matches the GT config files.gt.output path\n const t = await import(\\`${publicPath}\\${locale}.json\\`);\n return t.default;\n } catch (error) {\n console.warn(\\`Failed to load translations for locale \\${locale}:\\`, error);\n return {};\n }\n}\n`;\n}\n\n/**\n * Every loadTranslations file the app has, in gt-next's lookup order\n * (resolveConfigFilepath): root before src, .ts before .js. gt-next uses the\n * first one, and falls back to the next when it is deleted.\n */\nexport function findLoadTranslationsFiles(appDirectory: string): string[] {\n return ['', 'src']\n .flatMap((directory) =>\n ['.ts', '.js'].map((extension) =>\n path.join(appDirectory, directory, `loadTranslations${extension}`)\n )\n )\n .filter((candidate) => fs.existsSync(candidate));\n}\n\nexport type LoadTranslationsFileResult =\n | 'created'\n | 'updated'\n | 'unchanged'\n | 'custom';\n\n/**\n * Creates or updates the generated loadTranslations.js for translationsDir\n * (relative to appDirectory) and empty stubs for non-default locales. A\n * loader that was not matching the previous config's generated template, or\n * another loadTranslations file the app uses instead, is left untouched and\n * reported as 'custom'.\n * Directory and stub failures propagate.\n */\nexport async function createLoadTranslationsFile({\n appDirectory,\n translationsDir = DEFAULT_TRANSLATIONS_DIR,\n defaultLocale,\n locales,\n previousTranslationsDir,\n}: {\n appDirectory: string;\n translationsDir?: string;\n defaultLocale: string;\n locales: string[];\n previousTranslationsDir?: string;\n}): Promise<LoadTranslationsFileResult> {\n const usingSrcDirectory = fs.existsSync(path.join(appDirectory, 'src'));\n\n const loadTranslationsDir = usingSrcDirectory\n ? path.join(appDirectory, 'src')\n : appDirectory;\n const translationsPath = path.resolve(appDirectory, translationsDir);\n const publicPath = toRelativeImportPath(\n path.relative(loadTranslationsDir, translationsPath)\n );\n const filePath = path.join(loadTranslationsDir, 'loadTranslations.js');\n const content = getLoaderContent(translationsDir, publicPath);\n // Config paths lose leading ./ and trailing / through path.join, but\n // legacy generated comments retain them. Keep the import and body exact.\n const previousContents =\n previousTranslationsDir === undefined\n ? []\n : [\n previousTranslationsDir,\n ...(!path.isAbsolute(previousTranslationsDir)\n ? [`./${previousTranslationsDir}`]\n : []),\n ]\n .flatMap((directory) => [directory, `${directory}/`])\n .map((directory) =>\n getLoaderContent(\n directory,\n toRelativeImportPath(\n path.relative(\n loadTranslationsDir,\n path.resolve(appDirectory, previousTranslationsDir)\n )\n )\n )\n );\n\n const [loaderPath] = findLoadTranslationsFiles(appDirectory);\n const existing =\n loaderPath === filePath\n ? await fs.promises.readFile(filePath, 'utf8')\n : undefined;\n // Stubs first, so a directory failure leaves no loader pointing at it; a\n // custom loader also gets them, like the Vite loader.\n await fs.promises.mkdir(translationsPath, { recursive: true });\n for (const locale of new Set(locales)) {\n // Default-locale content lives in source, so it never needs a stub.\n if (locale === defaultLocale) continue;\n const stubPath = path.join(translationsPath, `${locale}.json`);\n if (!fs.existsSync(stubPath)) await fs.promises.writeFile(stubPath, '{}');\n }\n // Another loader wins over the generated one, so writing it would not help.\n if (\n (loaderPath !== undefined && loaderPath !== filePath) ||\n (existing !== undefined &&\n existing !== content &&\n !previousContents.includes(existing))\n ) {\n logger.info(\n `Found a custom ${chalk.cyan(\n path.basename(loaderPath ?? filePath)\n )} at ${chalk.cyan(loaderPath ?? filePath)}; leaving it unchanged.`\n );\n return 'custom';\n }\n\n if (existing === content) return 'unchanged';\n await fs.promises.writeFile(filePath, content);\n logger.info(\n `${existing === undefined ? 'Created' : 'Updated'} ${chalk.cyan(\n 'loadTranslations.js'\n )} at ${chalk.cyan(filePath)}.`\n );\n return existing === undefined ? 'created' : 'updated';\n}\n"],"mappings":";;;;;;AAMA,SAAS,qBAAqB,cAAsB;CAClD,MAAM,iBAAiB,aAAa,MAAM,KAAK,IAAI,CAAC,KAAK,KAAK,MAAM,IAAI;AAExE,KAAI,CAAC,eACH,QAAO;AAUT,QAJE,mBAAmB,QACnB,eAAe,WAAW,MAAM,IAChC,eAAe,WAAW,KAAK,GAG7B,GAAG,eAAe,KAClB,KAAK,eAAe;;AAG1B,SAAS,iBAAiB,iBAAyB,YAAoB;AACrE,QAAO;;;gCAGuB,gBAAgB;;+BAEjB,WAAW;;;;;;;;;;;;;;AAe1C,SAAgB,0BAA0B,cAAgC;AACxE,QAAO,CAAC,IAAI,MAAM,CACf,SAAS,cACR,CAAC,OAAO,MAAM,CAAC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,WACb,CAAC,iBAAiB,SAAS,SAAS,EACtC;AACA,SAAO,KACL,kBAAkB,MAAM,KACtB,KAAK,SAAS,cAAc,SAAS,CACtC,CAAC,MAAM,MAAM,KAAK,cAAc,SAAS,CAAC,yBAC5C;AACD,SAAO;;AAGT,KAAI,aAAa,QAAS,QAAO;AACjC,OAAM,GAAG,SAAS,UAAU,UAAU,QAAQ;AAC9C,QAAO,KACL,GAAG,aAAa,KAAA,IAAY,YAAY,UAAU,GAAG,MAAM,KACzD,sBACD,CAAC,MAAM,MAAM,KAAK,SAAS,CAAC,GAC9B;AACD,QAAO,aAAa,KAAA,IAAY,YAAY"}
1
+ {"version":3,"file":"createLoadTranslationsFile.js","names":[],"sources":["../../src/fs/createLoadTranslationsFile.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport chalk from 'chalk';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\n\nfunction toRelativeImportPath(relativePath: string) {\n const normalizedPath = relativePath.split(path.sep).join(path.posix.sep);\n\n if (!normalizedPath) {\n return './';\n }\n\n // Dynamic imports must use explicit relative specifiers; values like\n // \"src/_gt\" are otherwise treated as package names by Vite and Node.\n const hasExplicitRelativePrefix =\n normalizedPath === '..' ||\n normalizedPath.startsWith('../') ||\n normalizedPath.startsWith('./');\n\n return hasExplicitRelativePrefix\n ? `${normalizedPath}/`\n : `./${normalizedPath}/`;\n}\n\nfunction getLoaderContent(translationsDir: string, publicPath: string) {\n return `\nexport default async function loadTranslations(locale) {\n try {\n // Load translations from ${translationsDir} directory\n // This matches the GT config files.gt.output path\n const t = await import(\\`${publicPath}\\${locale}.json\\`);\n return t.default;\n } catch (error) {\n console.warn(\\`Failed to load translations for locale \\${locale}:\\`, error);\n return {};\n }\n}\n`;\n}\n\n/**\n * Every loadTranslations file the app has, in gt-next's lookup order\n * (resolveConfigFilepath): root before src, .ts before .js. gt-next uses the\n * first one, and falls back to the next when it is deleted.\n */\nexport function findLoadTranslationsFiles(appDirectory: string): string[] {\n return ['', 'src']\n .flatMap((directory) =>\n ['.ts', '.js'].map((extension) =>\n path.join(appDirectory, directory, `loadTranslations${extension}`)\n )\n )\n .filter((candidate) => fs.existsSync(candidate));\n}\n\nexport type LoadTranslationsFileResult =\n | 'created'\n | 'updated'\n | 'unchanged'\n | 'custom';\n\n/**\n * Creates or updates the generated loadTranslations.js for translationsDir\n * (relative to appDirectory) and empty stubs for non-default locales. A\n * loader that was not matching the previous config's generated template, or\n * another loadTranslations file the app uses instead, is left untouched and\n * reported as 'custom'.\n * Directory and stub failures propagate.\n */\nexport async function createLoadTranslationsFile({\n appDirectory,\n translationsDir = DEFAULT_TRANSLATIONS_DIR,\n defaultLocale,\n locales,\n previousTranslationsDir,\n}: {\n appDirectory: string;\n translationsDir?: string;\n defaultLocale: string;\n locales: string[];\n previousTranslationsDir?: string;\n}): Promise<LoadTranslationsFileResult> {\n const usingSrcDirectory = fs.existsSync(path.join(appDirectory, 'src'));\n\n const loadTranslationsDir = usingSrcDirectory\n ? path.join(appDirectory, 'src')\n : appDirectory;\n const translationsPath = path.resolve(appDirectory, translationsDir);\n const publicPath = toRelativeImportPath(\n path.relative(loadTranslationsDir, translationsPath)\n );\n const filePath = path.join(loadTranslationsDir, 'loadTranslations.js');\n const content = getLoaderContent(translationsDir, publicPath);\n // Config paths lose leading ./ and trailing / through path.join, but\n // legacy generated comments retain them. Keep the import and body exact.\n const previousContents =\n previousTranslationsDir === undefined\n ? []\n : [\n previousTranslationsDir,\n ...(!path.isAbsolute(previousTranslationsDir)\n ? [`./${previousTranslationsDir}`]\n : []),\n ]\n .flatMap((directory) => [directory, `${directory}/`])\n .map((directory) =>\n getLoaderContent(\n directory,\n toRelativeImportPath(\n path.relative(\n loadTranslationsDir,\n path.resolve(appDirectory, previousTranslationsDir)\n )\n )\n )\n );\n\n const [loaderPath] = findLoadTranslationsFiles(appDirectory);\n const existing =\n loaderPath === filePath\n ? await fs.promises.readFile(filePath, 'utf8')\n : undefined;\n // Stubs first, so a directory failure leaves no loader pointing at it; a\n // custom loader also gets them, like the Vite loader.\n await fs.promises.mkdir(translationsPath, { recursive: true });\n for (const locale of new Set(locales)) {\n // Default-locale content lives in source, so it never needs a stub.\n if (locale === defaultLocale) continue;\n const stubPath = path.join(translationsPath, `${locale}.json`);\n if (!fs.existsSync(stubPath)) await fs.promises.writeFile(stubPath, '{}');\n }\n // Another loader wins over the generated one, so writing it would not help.\n if (\n (loaderPath !== undefined && loaderPath !== filePath) ||\n (existing !== undefined &&\n existing !== content &&\n !previousContents.includes(existing))\n ) {\n logger.info(\n `Found a custom ${chalk.cyan(\n path.basename(loaderPath ?? filePath)\n )} at ${chalk.cyan(loaderPath ?? filePath)}; leaving it unchanged.`\n );\n return 'custom';\n }\n\n // A loader for the same directory, spelled differently, already works.\n if (\n existing === content ||\n (existing !== undefined &&\n previousTranslationsDir !== undefined &&\n path.resolve(appDirectory, previousTranslationsDir) === translationsPath)\n )\n return 'unchanged';\n await fs.promises.writeFile(filePath, content);\n logger.info(\n `${existing === undefined ? 'Created' : 'Updated'} ${chalk.cyan(\n 'loadTranslations.js'\n )} at ${chalk.cyan(filePath)}.`\n );\n return existing === undefined ? 'created' : 'updated';\n}\n"],"mappings":";;;;;;AAMA,SAAS,qBAAqB,cAAsB;CAClD,MAAM,iBAAiB,aAAa,MAAM,KAAK,IAAI,CAAC,KAAK,KAAK,MAAM,IAAI;AAExE,KAAI,CAAC,eACH,QAAO;AAUT,QAJE,mBAAmB,QACnB,eAAe,WAAW,MAAM,IAChC,eAAe,WAAW,KAAK,GAG7B,GAAG,eAAe,KAClB,KAAK,eAAe;;AAG1B,SAAS,iBAAiB,iBAAyB,YAAoB;AACrE,QAAO;;;gCAGuB,gBAAgB;;+BAEjB,WAAW;;;;;;;;;;;;;;AAe1C,SAAgB,0BAA0B,cAAgC;AACxE,QAAO,CAAC,IAAI,MAAM,CACf,SAAS,cACR,CAAC,OAAO,MAAM,CAAC,KAAK,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AAC,iBAAiB,SAAS,SAAS,EACtC;AACA,SAAO,KACL,kBAAkB,MAAM,KACtB,KAAK,SAAS,cAAc,SAAS,CACtC,CAAC,MAAM,MAAM,KAAK,cAAc,SAAS,CAAC,yBAC5C;AACD,SAAO;;AAIT,KACE,aAAa,WACZ,aAAa,KAAA,KACZ,4BAA4B,KAAA,KAC5B,KAAK,QAAQ,cAAc,wBAAwB,KAAK,iBAE1D,QAAO;AACT,OAAM,GAAG,SAAS,UAAU,UAAU,QAAQ;AAC9C,QAAO,KACL,GAAG,aAAa,KAAA,IAAY,YAAY,UAAU,GAAG,MAAM,KACzD,sBACD,CAAC,MAAM,MAAM,KAAK,SAAS,CAAC,GAC9B;AACD,QAAO,aAAa,KAAA,IAAY,YAAY"}
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.23.2";
1
+ export declare const PACKAGE_VERSION = "2.24.0";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.23.2";
2
+ const PACKAGE_VERSION = "2.24.0";
3
3
  //#endregion
4
4
  export { PACKAGE_VERSION };
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.23.2';\n"],"mappings":";AACA,MAAa,kBAAkB"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.24.0';\n"],"mappings":";AACA,MAAa,kBAAkB"}
@@ -1,4 +1,4 @@
1
- import esbuild from 'esbuild';
1
+ import esbuild from 'esbuild-wasm';
2
2
  type TSConfig = {
3
3
  compilerOptions?: {
4
4
  paths?: Record<string, string[]>;
@@ -1 +1 @@
1
- {"version":3,"file":"createESBuildConfig.js","names":[],"sources":["../../../src/react/config/createESBuildConfig.ts"],"sourcesContent":["import esbuild from 'esbuild';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { displayResolvedPaths } from '../../console/logging.js';\n\ntype TSConfig = {\n compilerOptions?: {\n paths?: Record<string, string[]>;\n };\n};\n\nexport default function createESBuildConfig(config: TSConfig = {}) {\n const esbuildOptions: esbuild.BuildOptions = {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n target: 'es2021',\n loader: {\n '.js': 'jsx',\n '.ts': 'ts',\n '.css': 'css', // Add CSS loader\n },\n sourcemap: 'inline',\n external: ['server-only'],\n define: {\n React: 'global.React',\n },\n plugins: [],\n };\n\n // Add the custom plugin to handle 'server-only' imports\n esbuildOptions.plugins?.push({\n name: 'ignore-server-only',\n setup(build: esbuild.PluginBuild) {\n build.onResolve({ filter: /^server-only$/ }, () => {\n return {\n path: 'server-only',\n namespace: 'ignore-server-only',\n };\n });\n\n build.onLoad(\n { filter: /^server-only$/, namespace: 'ignore-server-only' },\n () => {\n return {\n contents: 'module.exports = {};',\n loader: 'js',\n };\n }\n );\n },\n });\n\n // Add a plugin to handle CSS imports\n esbuildOptions.plugins?.push({\n name: 'css-module',\n setup(build: esbuild.PluginBuild) {\n build.onResolve({ filter: /\\.css$/ }, (args: esbuild.OnResolveArgs) => {\n return {\n path: path.resolve(args.resolveDir, args.path),\n namespace: 'css-module',\n };\n });\n\n build.onLoad(\n { filter: /\\.css$/, namespace: 'css-module' },\n async (args: esbuild.OnLoadArgs) => {\n const css = await fs.promises.readFile(args.path, 'utf8');\n const contents = `\n const style = document.createElement('style');\n style.textContent = ${JSON.stringify(css)};\n document.head.appendChild(style);\n `;\n return { contents, loader: 'js' };\n }\n );\n },\n });\n\n if (config.compilerOptions) {\n if (config.compilerOptions.paths) {\n const aliases: Record<string, string> = {};\n\n const resolvedPaths: [string, string][] = [];\n for (const [key, value] of Object.entries(config.compilerOptions.paths)) {\n if (Array.isArray(value) && typeof value[0] === 'string') {\n const resolvedPath = path.resolve(\n process.cwd(),\n value[0].replace('/*', '')\n );\n aliases[key.replace('/*', '')] = resolvedPath;\n resolvedPaths.push([key, resolvedPath]);\n }\n }\n if (resolvedPaths.length) {\n displayResolvedPaths(resolvedPaths);\n }\n\n esbuildOptions.plugins = esbuildOptions.plugins || [];\n\n esbuildOptions.plugins.push({\n name: 'alias',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n for (const [aliasKey, aliasPath] of Object.entries(aliases)) {\n if (args.path.startsWith(`${aliasKey}/`)) {\n const resolvedPath = path.resolve(\n aliasPath as string,\n args.path.slice(aliasKey.length + 1)\n );\n\n const extensions = ['.js', '.ts', '.css']; // Add .css to extensions\n\n function resolveWithExtensions(\n basePath: string\n ): string | null {\n for (const ext of extensions) {\n const fullPath = `${basePath}${ext}`;\n try {\n const realPath = fs.realpathSync(fullPath);\n return realPath;\n } catch {\n continue;\n }\n }\n return null;\n }\n\n try {\n const realPath = fs.realpathSync(resolvedPath);\n return { path: realPath };\n } catch {\n const hasExtension = extensions.some((ext) =>\n resolvedPath.endsWith(ext)\n );\n if (!hasExtension) {\n const resolvedWithExt = resolveWithExtensions(resolvedPath);\n if (resolvedWithExt) {\n return { path: resolvedWithExt };\n }\n }\n\n throw new Error(`Unable to resolve path: ${resolvedPath}`);\n }\n }\n }\n });\n },\n });\n }\n }\n\n return esbuildOptions;\n}\n"],"mappings":";;;;AAWA,SAAwB,oBAAoB,SAAmB,EAAE,EAAE;CACjE,MAAM,iBAAuC;EAC3C,QAAQ;EACR,QAAQ;EACR,UAAU;EACV,QAAQ;EACR,QAAQ;GACN,OAAO;GACP,OAAO;GACP,QAAQ;GACT;EACD,WAAW;EACX,UAAU,CAAC,cAAc;EACzB,QAAQ,EACN,OAAO,gBACR;EACD,SAAS,EAAE;EACZ;AAGD,gBAAe,SAAS,KAAK;EAC3B,MAAM;EACN,MAAM,OAA4B;AAChC,SAAM,UAAU,EAAE,QAAQ,iBAAiB,QAAQ;AACjD,WAAO;KACL,MAAM;KACN,WAAW;KACZ;KACD;AAEF,SAAM,OACJ;IAAE,QAAQ;I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,QACxB,WACA,KAAK,KAAK,MAAM,SAAS,SAAS,EAAE,CACrC;OAED,MAAM,aAAa;QAAC;QAAO;QAAO;QAAO;OAEzC,SAAS,sBACP,UACe;AACf,aAAK,MAAM,OAAO,YAAY;SAC5B,MAAM,WAAW,GAAG,WAAW;AAC/B,aAAI;AAEF,iBADiB,GAAG,aAAa,SAClB;iBACT;AACN;;;AAGJ,eAAO;;AAGT,WAAI;AAEF,eAAO,EAAE,MADQ,GAAG,aAAa,aACV,EAAE;eACnB;AAIN,YAAI,CAHiB,WAAW,MAAM,QACpC,aAAa,SAAS,IAAI,CAEX,EAAE;SACjB,MAAM,kBAAkB,sBAAsB,aAAa;AAC3D,aAAI,gBACF,QAAO,EAAE,MAAM,iBAAiB;;AAIpC,cAAM,IAAI,MAAM,2BAA2B,eAAe;;;OAIhE;;IAEL,CAAC;;;AAIN,QAAO"}
1
+ {"version":3,"file":"createESBuildConfig.js","names":[],"sources":["../../../src/react/config/createESBuildConfig.ts"],"sourcesContent":["import esbuild from 'esbuild-wasm';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { displayResolvedPaths } from '../../console/logging.js';\n\ntype TSConfig = {\n compilerOptions?: {\n paths?: Record<string, string[]>;\n };\n};\n\nexport default function createESBuildConfig(config: TSConfig = {}) {\n const esbuildOptions: esbuild.BuildOptions = {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n target: 'es2021',\n loader: {\n '.js': 'jsx',\n '.ts': 'ts',\n '.css': 'css', // Add CSS loader\n },\n sourcemap: 'inline',\n external: ['server-only'],\n define: {\n React: 'global.React',\n },\n plugins: [],\n };\n\n // Add the custom plugin to handle 'server-only' imports\n esbuildOptions.plugins?.push({\n name: 'ignore-server-only',\n setup(build: esbuild.PluginBuild) {\n build.onResolve({ filter: /^server-only$/ }, () => {\n return {\n path: 'server-only',\n namespace: 'ignore-server-only',\n };\n });\n\n build.onLoad(\n { filter: /^server-only$/, namespace: 'ignore-server-only' },\n () => {\n return {\n contents: 'module.exports = {};',\n loader: 'js',\n };\n }\n );\n },\n });\n\n // Add a plugin to handle CSS imports\n esbuildOptions.plugins?.push({\n name: 'css-module',\n setup(build: esbuild.PluginBuild) {\n build.onResolve({ filter: /\\.css$/ }, (args: esbuild.OnResolveArgs) => {\n return {\n path: path.resolve(args.resolveDir, args.path),\n namespace: 'css-module',\n };\n });\n\n build.onLoad(\n { filter: /\\.css$/, namespace: 'css-module' },\n async (args: esbuild.OnLoadArgs) => {\n const css = await fs.promises.readFile(args.path, 'utf8');\n const contents = `\n const style = document.createElement('style');\n style.textContent = ${JSON.stringify(css)};\n document.head.appendChild(style);\n `;\n return { contents, loader: 'js' };\n }\n );\n },\n });\n\n if (config.compilerOptions) {\n if (config.compilerOptions.paths) {\n const aliases: Record<string, string> = {};\n\n const resolvedPaths: [string, string][] = [];\n for (const [key, value] of Object.entries(config.compilerOptions.paths)) {\n if (Array.isArray(value) && typeof value[0] === 'string') {\n const resolvedPath = path.resolve(\n process.cwd(),\n value[0].replace('/*', '')\n );\n aliases[key.replace('/*', '')] = resolvedPath;\n resolvedPaths.push([key, resolvedPath]);\n }\n }\n if (resolvedPaths.length) {\n displayResolvedPaths(resolvedPaths);\n }\n\n esbuildOptions.plugins = esbuildOptions.plugins || [];\n\n esbuildOptions.plugins.push({\n name: 'alias',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n for (const [aliasKey, aliasPath] of Object.entries(aliases)) {\n if (args.path.startsWith(`${aliasKey}/`)) {\n const resolvedPath = path.resolve(\n aliasPath as string,\n args.path.slice(aliasKey.length + 1)\n );\n\n const extensions = ['.js', '.ts', '.css']; // Add .css to extensions\n\n function resolveWithExtensions(\n basePath: string\n ): string | null {\n for (const ext of extensions) {\n const fullPath = `${basePath}${ext}`;\n try {\n const realPath = fs.realpathSync(fullPath);\n return realPath;\n } catch {\n continue;\n }\n }\n return null;\n }\n\n try {\n const realPath = fs.realpathSync(resolvedPath);\n return { path: realPath };\n } catch {\n const hasExtension = extensions.some((ext) =>\n resolvedPath.endsWith(ext)\n );\n if (!hasExtension) {\n const resolvedWithExt = resolveWithExtensions(resolvedPath);\n if (resolvedWithExt) {\n return { path: resolvedWithExt };\n }\n }\n\n throw new Error(`Unable to resolve path: ${resolvedPath}`);\n }\n }\n }\n });\n },\n });\n }\n }\n\n return esbuildOptions;\n}\n"],"mappings":";;;;AAWA,SAAwB,oBAAoB,SAAmB,EAAE,EAAE;CACjE,MAAM,iBAAuC;EAC3C,QAAQ;EACR,QAAQ;EACR,UAAU;EACV,QAAQ;EACR,QAAQ;GACN,OAAO;GACP,OAAO;GACP,QAAQ;GACT;EACD,WAAW;EACX,UAAU,CAAC,cAAc;EACzB,QAAQ,EACN,OAAO,gBACR;EACD,SAAS,EAAE;EACZ;AAGD,gBAAe,SAAS,KAAK;EAC3B,MAAM;EACN,MAAM,OAA4B;AAChC,SAAM,UAAU,EAAE,QAAQ,iBAAiB,QAAQ;AACjD,WAAO;KACL,MAAM;KACN,WAAW;KACZ;KACD;AAEF,SAAM,OACJ;IAAE,QAAQ;IAAiB,WAAW;IAAsB,QACtD;AACJ,WAAO;KACL,UAAU;KACV,QAAQ;KACT;KAEJ;;EAEJ,CAAC;AAGF,gBAAe,SAAS,KAAK;EAC3B,MAAM;EACN,MAAM,OAA4B;AAChC,SAAM,UAAU,EAAE,QAAQ,UAAU,GAAG,SAAgC;AACrE,WAAO;KACL,MAAM,KAAK,QAAQ,KAAK,YAAY,KAAK,KAAK;KAC9C,WAAW;KACZ;KACD;AAEF,SAAM,OACJ;IAAE,QAAQ;IAAU,WAAW;IAAc,EAC7C,OAAO,SAA6B;IAClC,MAAM,MAAM,MAAM,GAAG,SAAS,SAAS,KAAK,MAAM,OAAO;AAMzD,WAAO;KAAE,UAAA;;0CAHuB,KAAK,UAAU,IAAI,CAAC;;;KAGjC,QAAQ;KAAM;KAEpC;;EAEJ,CAAC;AAEF,KAAI,OAAO;MACL,OAAO,gBAAgB,OAAO;GAChC,MAAM,UAAkC,EAAE;GAE1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uild';
1
+ import { BuildOptions } from 'esbuild-wasm';
2
2
  import { Updates } from '../../types/index.js';
3
3
  export declare function createDictionaryUpdates(dictionaryPath: string, errors: string[], warnings: string[], esbuildConfig?: BuildOptions): Promise<Updates>;
@@ -9,7 +9,7 @@ import { randomUUID } from "node:crypto";
9
9
  import path from "node:path";
10
10
  import fs from "node:fs";
11
11
  import os from "os";
12
- import { build } from "esbuild";
12
+ import { build } from "esbuild-wasm";
13
13
  import { hashSource } from "generaltranslation/id";
14
14
  //#region src/react/parse/createDictionaryUpdates.ts
15
15
  async function createDictionaryUpdates(dictionaryPath, errors, warnings, esbuildConfig) {
@@ -1 +1 @@
1
- {"version":3,"file":"createDictionaryUpdates.js","names":[],"sources":["../../../src/react/parse/createDictionaryUpdates.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport os from 'os';\nimport { build, BuildOptions } from 'esbuild';\nimport { Updates } from '../../types/index.js';\nimport flattenDictionary from '../utils/flattenDictionary.js';\nimport loadJSON from '../../fs/loadJSON.js';\nimport { hashSource } from 'generaltranslation/id';\nimport getEntryAndMetadata from '../utils/getEntryAndMetadata.js';\nimport { logger } from '../../console/logger.js';\nimport { randomUUID } from 'node:crypto';\nimport { isValidIcu } from '../jsx/evaluateJsx.js';\nimport {\n warnInvalidIcuSync,\n warnInvalidMaxCharsSync,\n} from '../../console/index.js';\nimport { exitSync } from '../../console/logging.js';\nimport type { Dictionary, DictionaryEntry } from '../../types/data.js';\n\nexport async function createDictionaryUpdates(\n dictionaryPath: string,\n errors: string[],\n warnings: string[],\n esbuildConfig?: BuildOptions\n): Promise<Updates> {\n let dictionary: Dictionary = {};\n // ---- HANDLE JSON STRING DICTIONARY ----- //\n\n if (dictionaryPath.endsWith('.json')) {\n dictionary = flattenDictionary(\n (loadJSON(dictionaryPath) || {}) as Dictionary\n );\n }\n\n // ----- HANDLE REACT DICTIONARY ---- //\n else {\n const result = await build({\n ...esbuildConfig,\n entryPoints: [dictionaryPath],\n write: false,\n });\n\n const bundledCode = result.outputFiles[0].text;\n const tempFilePath = path.join(\n os.tmpdir(),\n `bundled-dictionary-${randomUUID()}.js`\n );\n await fs.promises.writeFile(tempFilePath, bundledCode);\n\n // Load the module using dynamic import\n let dictionaryModule;\n try {\n dictionaryModule = await import(tempFilePath);\n } catch (error) {\n logger.error(`Failed to load the bundled dictionary code: ${error}`);\n exitSync(1);\n } finally {\n // Clean up the temporary file\n await fs.promises.unlink(tempFilePath);\n }\n const unwrappedDictionary = unwrapDictionaryModule(dictionaryModule);\n dictionary = flattenDictionary(unwrappedDictionary as Dictionary);\n }\n\n // ----- CREATE PARTIAL UPDATES ----- //\n\n const updates: Updates = [];\n\n for (const id of Object.keys(dictionary)) {\n const {\n entry,\n metadata: props, // context, etc.\n } = getEntryAndMetadata(dictionary[id] as DictionaryEntry);\n\n // Validate ICU\n const { isValid, error } = isValidIcu(entry);\n if (!isValid) {\n warnings.push(\n warnInvalidIcuSync(dictionaryPath, entry, error ?? 'Unknown error')\n );\n continue;\n }\n\n // Validate maxChars\n if (\n props?.$maxChars &&\n (isNaN(props.$maxChars) || !Number.isInteger(props.$maxChars))\n ) {\n errors.push(\n warnInvalidMaxCharsSync(dictionaryPath, String(props.$maxChars), id)\n );\n continue;\n }\n\n // Map $context to context\n const context = props?.$context;\n const maxChars = props?.$maxChars;\n const metadata: Record<string, unknown> = {\n id,\n ...(context && { context }),\n ...(maxChars != null && { maxChars: Math.abs(maxChars) }),\n // This hash isn't actually used by the GT API, just for consistency sake\n hash: hashSource({\n source: entry,\n ...(context && { context }),\n ...(maxChars != null && { maxChars: Math.abs(maxChars) }),\n dataFormat: 'ICU',\n }),\n };\n updates.push({\n dataFormat: 'ICU',\n source: entry,\n metadata,\n });\n }\n\n return updates;\n}\n\nfunction unwrapDictionaryModule(mod: unknown): Dictionary {\n let current = mod;\n\n // Keep unwrapping until we get to the actual dictionary\n while (current && typeof current === 'object') {\n const currentObject = current as Record<string, unknown>;\n const keys = Object.keys(currentObject);\n\n // Check if this looks like a module namespace object (has only module-related keys)\n const isModuleNamespace = keys.every(\n (key) =>\n key === 'default' || key === 'module.exports' || key === '__esModule'\n );\n\n // Check if this is a module with named exports (has 'dictionary' export)\n // Only check for named exports if it's NOT a pure module namespace\n const hasNamedDictionary =\n !isModuleNamespace &&\n 'dictionary' in currentObject &&\n currentObject.dictionary &&\n typeof currentObject.dictionary === 'object' &&\n !Array.isArray(currentObject.dictionary);\n\n if (hasNamedDictionary) {\n // If there's a named 'dictionary' export, use that\n return currentObject.dictionary as Dictionary;\n } else if (isModuleNamespace) {\n // Try to get the default export\n if ('default' in currentObject) {\n let result = currentObject.default;\n\n // If the default export is a function (getter), call it\n if (typeof result === 'function') {\n try {\n result = result();\n } catch {\n // If calling fails, break the loop\n break;\n }\n }\n\n // If we have a valid object, check if we should continue unwrapping\n if (result && typeof result === 'object' && !Array.isArray(result)) {\n const resultKeys = Object.keys(result);\n // Only continue unwrapping if this looks like a getter-based module layer\n // We should NOT continue if this is just a user dictionary with a 'default' property\n const hasGetterProperties = resultKeys.some((key) => {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(result, key);\n return descriptor && typeof descriptor.get === 'function';\n } catch {\n return false;\n }\n });\n\n if (hasGetterProperties) {\n current = result;\n continue;\n } else {\n // This is the actual dictionary, return it\n return result as Dictionary;\n }\n }\n }\n\n // Try module.exports as fallback\n if ('module.exports' in currentObject) {\n let result = currentObject['module.exports'];\n\n if (typeof result === 'function') {\n try {\n result = result();\n } catch {\n // If calling fails, break the loop\n break;\n }\n }\n\n if (result && typeof result === 'object' && !Array.isArray(result)) {\n const resultKeys = Object.keys(result);\n // Only continue unwrapping if this looks like a getter-based module layer\n // We should NOT continue if this is just a user dictionary with a 'default' property\n const hasGetterProperties = resultKeys.some((key) => {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(result, key);\n return descriptor && typeof descriptor.get === 'function';\n } catch {\n return false;\n }\n });\n\n if (hasGetterProperties) {\n current = result;\n continue;\n } else {\n // This is the actual dictionary, return it\n return result as Dictionary;\n }\n }\n }\n\n // If we can't unwrap further, break\n break;\n } else {\n // This appears to be the actual dictionary object, not a module wrapper\n break;\n }\n }\n\n return (current || {}) as Dictionary;\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,eAAsB,wBACpB,gBACA,QACA,UACA,eACkB;CAClB,IAAI,aAAyB,EAAE;AAG/B,KAAI,eAAe,SAAS,QAAQ,CAClC,cAAa,kBACV,SAAS,eAAe,IAAI,EAAE,CAChC;MAIE;EAOH,MAAM,eAAc,MANC,MAAM;GACzB,GAAG;GACH,aAAa,CAAC,eAAe;GAC7B,OAAO;GACR,CAAC,EAEyB,YAAY,GAAG;EAC1C,MAAM,eAAe,KAAK,KACxB,GAAG,QAAQ,EACX,sBAAsB,YAAY,CAAC,KACpC;AACD,QAAM,GAAG,SAAS,UAAU,cAAc,YAAY;EAGtD,IAAI;AACJ,MAAI;AACF,sBAAmB,MAAM,OAAO;WACzB,OAAO;AACd,UAAO,MAAM,+CAA+C,QAAQ;AACpE,YAAS,EAAE;YACH;AAER,SAAM,GAAG,SAAS,OAAO,aAAa;;AAGxC,eAAa,kBADe,uBAAuB,iBACD,CAAe;;CAKnE,MAAM,UAAmB,EAAE;AAE3B,MAAK,MAAM,MAAM,OAAO,KAAK,WAAW,EAAE;EACxC,MAAM,EACJ,OACA,UAAU,UACR,oBAAoB,WAAW,IAAuB;EAG1D,MAAM,EAAE,SAAS,UAAU,WAAW,MAAM;AAC5C,MAAI,CAAC,SAAS;AACZ,YAAS,KACP,mBAAmB,gBAAgB,OAAO,SAAS,gBAAgB,CACpE;AACD;;AAIF,MACE,OAAO,cACN,MAAM,MAAM,UAAU,IAAI,CAAC,OAAO,UAAU,MAAM,UAAU,GAC7D;AACA,UAAO,KACL,wBAAwB,gBAAgB,OAAO,MAAM,UAAU,EAAE,GAAG,CACrE;AACD;;EAIF,MAAM,UAAU,OAAO;EACvB,MAAM,WAAW,OAAO;EACxB,MAAM,WAAoC;GACxC;GAC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OAAO,KAAK,OAGO,CAAC,MAAM,QAAQ;AACnD,SAAI;MACF,MAAM,aAAa,OAAO,yBAAyB,QAAQ,IAAI;AAC/D,aAAO,cAAc,OAAO,WAAW,QAAQ;aACzC;AACN,aAAO;;MAIY,EAAE;AACvB,eAAU;AACV;UAGA,QAAO;;AAMb;QAGA;;AAIJ,QAAQ,WAAW,EAAE"}
1
+ {"version":3,"file":"createDictionaryUpdates.js","names":[],"sources":["../../../src/react/parse/createDictionaryUpdates.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport os from 'os';\nimport { build, BuildOptions } from 'esbuild-wasm';\nimport { Updates } from '../../types/index.js';\nimport flattenDictionary from '../utils/flattenDictionary.js';\nimport loadJSON from '../../fs/loadJSON.js';\nimport { hashSource } from 'generaltranslation/id';\nimport getEntryAndMetadata from '../utils/getEntryAndMetadata.js';\nimport { logger } from '../../console/logger.js';\nimport { randomUUID } from 'node:crypto';\nimport { isValidIcu } from '../jsx/evaluateJsx.js';\nimport {\n warnInvalidIcuSync,\n warnInvalidMaxCharsSync,\n} from '../../console/index.js';\nimport { exitSync } from '../../console/logging.js';\nimport type { Dictionary, DictionaryEntry } from '../../types/data.js';\n\nexport async function createDictionaryUpdates(\n dictionaryPath: string,\n errors: string[],\n warnings: string[],\n esbuildConfig?: BuildOptions\n): Promise<Updates> {\n let dictionary: Dictionary = {};\n // ---- HANDLE JSON STRING DICTIONARY ----- //\n\n if (dictionaryPath.endsWith('.json')) {\n dictionary = flattenDictionary(\n (loadJSON(dictionaryPath) || {}) as Dictionary\n );\n }\n\n // ----- HANDLE REACT DICTIONARY ---- //\n else {\n const result = await build({\n ...esbuildConfig,\n entryPoints: [dictionaryPath],\n write: false,\n });\n\n const bundledCode = result.outputFiles[0].text;\n const tempFilePath = path.join(\n os.tmpdir(),\n `bundled-dictionary-${randomUUID()}.js`\n );\n await fs.promises.writeFile(tempFilePath, bundledCode);\n\n // Load the module using dynamic import\n let dictionaryModule;\n try {\n dictionaryModule = await import(tempFilePath);\n } catch (error) {\n logger.error(`Failed to load the bundled dictionary code: ${error}`);\n exitSync(1);\n } finally {\n // Clean up the temporary file\n await fs.promises.unlink(tempFilePath);\n }\n const unwrappedDictionary = unwrapDictionaryModule(dictionaryModule);\n dictionary = flattenDictionary(unwrappedDictionary as Dictionary);\n }\n\n // ----- CREATE PARTIAL UPDATES ----- //\n\n const updates: Updates = [];\n\n for (const id of Object.keys(dictionary)) {\n const {\n entry,\n metadata: props, // context, etc.\n } = getEntryAndMetadata(dictionary[id] as DictionaryEntry);\n\n // Validate ICU\n const { isValid, error } = isValidIcu(entry);\n if (!isValid) {\n warnings.push(\n warnInvalidIcuSync(dictionaryPath, entry, error ?? 'Unknown error')\n );\n continue;\n }\n\n // Validate maxChars\n if (\n props?.$maxChars &&\n (isNaN(props.$maxChars) || !Number.isInteger(props.$maxChars))\n ) {\n errors.push(\n warnInvalidMaxCharsSync(dictionaryPath, String(props.$maxChars), id)\n );\n continue;\n }\n\n // Map $context to context\n const context = props?.$context;\n const maxChars = props?.$maxChars;\n const metadata: Record<string, unknown> = {\n id,\n ...(context && { context }),\n ...(maxChars != null && { maxChars: Math.abs(maxChars) }),\n // This hash isn't actually used by the GT API, just for consistency sake\n hash: hashSource({\n source: entry,\n ...(context && { context }),\n ...(maxChars != null && { maxChars: Math.abs(maxChars) }),\n dataFormat: 'ICU',\n }),\n };\n updates.push({\n dataFormat: 'ICU',\n source: entry,\n metadata,\n });\n }\n\n return updates;\n}\n\nfunction unwrapDictionaryModule(mod: unknown): Dictionary {\n let current = mod;\n\n // Keep unwrapping until we get to the actual dictionary\n while (current && typeof current === 'object') {\n const currentObject = current as Record<string, unknown>;\n const keys = Object.keys(currentObject);\n\n // Check if this looks like a module namespace object (has only module-related keys)\n const isModuleNamespace = keys.every(\n (key) =>\n key === 'default' || key === 'module.exports' || key === '__esModule'\n );\n\n // Check if this is a module with named exports (has 'dictionary' export)\n // Only check for named exports if it's NOT a pure module namespace\n const hasNamedDictionary =\n !isModuleNamespace &&\n 'dictionary' in currentObject &&\n currentObject.dictionary &&\n typeof currentObject.dictionary === 'object' &&\n !Array.isArray(currentObject.dictionary);\n\n if (hasNamedDictionary) {\n // If there's a named 'dictionary' export, use that\n return currentObject.dictionary as Dictionary;\n } else if (isModuleNamespace) {\n // Try to get the default export\n if ('default' in currentObject) {\n let result = currentObject.default;\n\n // If the default export is a function (getter), call it\n if (typeof result === 'function') {\n try {\n result = result();\n } catch {\n // If calling fails, break the loop\n break;\n }\n }\n\n // If we have a valid object, check if we should continue unwrapping\n if (result && typeof result === 'object' && !Array.isArray(result)) {\n const resultKeys = Object.keys(result);\n // Only continue unwrapping if this looks like a getter-based module layer\n // We should NOT continue if this is just a user dictionary with a 'default' property\n const hasGetterProperties = resultKeys.some((key) => {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(result, key);\n return descriptor && typeof descriptor.get === 'function';\n } catch {\n return false;\n }\n });\n\n if (hasGetterProperties) {\n current = result;\n continue;\n } else {\n // This is the actual dictionary, return it\n return result as Dictionary;\n }\n }\n }\n\n // Try module.exports as fallback\n if ('module.exports' in currentObject) {\n let result = currentObject['module.exports'];\n\n if (typeof result === 'function') {\n try {\n result = result();\n } catch {\n // If calling fails, break the loop\n break;\n }\n }\n\n if (result && typeof result === 'object' && !Array.isArray(result)) {\n const resultKeys = Object.keys(result);\n // Only continue unwrapping if this looks like a getter-based module layer\n // We should NOT continue if this is just a user dictionary with a 'default' property\n const hasGetterProperties = resultKeys.some((key) => {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(result, key);\n return descriptor && typeof descriptor.get === 'function';\n } catch {\n return false;\n }\n });\n\n if (hasGetterProperties) {\n current = result;\n continue;\n } else {\n // This is the actual dictionary, return it\n return result as Dictionary;\n }\n }\n }\n\n // If we can't unwrap further, break\n break;\n } else {\n // This appears to be the actual dictionary object, not a module wrapper\n break;\n }\n }\n\n return (current || {}) as Dictionary;\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,e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,eAAU;AACV;UAGA,QAAO;;AAMb;QAGA;;AAIJ,QAAQ,WAAW,EAAE"}
@@ -28,6 +28,8 @@ export type BuildToolSetup = {
28
28
  /** Loads local translations itself instead of loadTranslations.js. */
29
29
  ownsLoader: boolean;
30
30
  skipsGTInstall(isUsingGT: boolean): boolean;
31
+ /** Setup guide linked after setup; the React quickstart otherwise. */
32
+ docsUrl?: string;
31
33
  /** The development credentials question asked with local storage. */
32
34
  devCredentialsOption: '--live-translations' | '--dev-credentials';
33
35
  /** Rejects an app layout it cannot configure, before any change. */
@@ -1,6 +1,7 @@
1
1
  import { viteSetup } from "./vite.js";
2
+ import { tanstackStartSetup } from "./tanstackStart/index.js";
2
3
  //#region src/setup/buildTools/index.ts
3
- const BUILD_TOOL_SETUPS = [viteSetup];
4
+ const BUILD_TOOL_SETUPS = [viteSetup, tanstackStartSetup];
4
5
  function getBuildToolSetup(framework) {
5
6
  return BUILD_TOOL_SETUPS.find((setup) => setup.framework === framework);
6
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/setup/buildTools/index.ts"],"sourcesContent":["import type { SupportedReactFrameworks } from '../../types/index.js';\nimport { viteSetup } from './vite.js';\n\n/** A change setup left to a person, reported as a warning. */\nexport type ManualAction = { whatHappened: string; fix: string };\n\n/** What a build-tool hook changed, and what a person still has to do. */\nexport type SetupResult = { steps: string[]; manualActions: ManualAction[] };\n\nexport type BuildToolContext = {\n appDirectory: string;\n configFilepath: string;\n defaultLocale: string;\n locales: string[];\n /** Set when translations are stored locally. */\n translationsDir?: string;\n /** The translations directory in the existing config. */\n previousTranslationsDir?: string;\n};\n\n/** Setup steps for a build tool whose app entry GT configures itself. */\nexport type BuildToolSetup = {\n framework: SupportedReactFrameworks;\n defaultTranslationsDir: string;\n /** The runtime entry named in the defaults text. */\n initializer: string;\n /** Loads local translations itself instead of loadTranslations.js. */\n ownsLoader: boolean;\n skipsGTInstall(isUsingGT: boolean): boolean;\n /** The development credentials question asked with local storage. */\n devCredentialsOption: '--live-translations' | '--dev-credentials';\n /** Rejects an app layout it cannot configure, before any change. */\n preflight(appDirectory: string): Promise<void>;\n /** Keeps an existing loader in sync when the React setup is skipped. */\n syncLoader(\n ctx: BuildToolContext & { translationsDir: string; keepAppSource?: boolean }\n ): Promise<SetupResult>;\n /** Configures the app entry after gt.config.json is written. */\n apply(ctx: BuildToolContext): Promise<SetupResult>;\n};\n\nexport const BUILD_TOOL_SETUPS: BuildToolSetup[] = [viteSetup];\n\nexport function getBuildToolSetup(\n framework?: string\n): BuildToolSetup | undefined {\n return BUILD_TOOL_SETUPS.find((setup) => setup.framework === framework);\n}\n"],"mappings":";;AAyCA,MAAa,oBAAsC,CAAC,UAAU;AAE9D,SAAgB,kBACd,WAC4B;AAC5B,QAAO,kBAAkB,MAAM,UAAU,MAAM,cAAc,UAAU"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/setup/buildTools/index.ts"],"sourcesContent":["import type { SupportedReactFrameworks } from '../../types/index.js';\nimport { tanstackStartSetup } from './tanstackStart/index.js';\nimport { viteSetup } from './vite.js';\n\n/** A change setup left to a person, reported as a warning. */\nexport type ManualAction = { whatHappened: string; fix: string };\n\n/** What a build-tool hook changed, and what a person still has to do. */\nexport type SetupResult = { steps: string[]; manualActions: ManualAction[] };\n\nexport type BuildToolContext = {\n appDirectory: string;\n configFilepath: string;\n defaultLocale: string;\n locales: string[];\n /** Set when translations are stored locally. */\n translationsDir?: string;\n /** The translations directory in the existing config. */\n previousTranslationsDir?: string;\n};\n\n/** Setup steps for a build tool whose app entry GT configures itself. */\nexport type BuildToolSetup = {\n framework: SupportedReactFrameworks;\n defaultTranslationsDir: string;\n /** The runtime entry named in the defaults text. */\n initializer: string;\n /** Loads local translations itself instead of loadTranslations.js. */\n ownsLoader: boolean;\n skipsGTInstall(isUsingGT: boolean): boolean;\n /** Setup guide linked after setup; the React quickstart otherwise. */\n docsUrl?: string;\n /** The development credentials question asked with local storage. */\n devCredentialsOption: '--live-translations' | '--dev-credentials';\n /** Rejects an app layout it cannot configure, before any change. */\n preflight(appDirectory: string): Promise<void>;\n /** Keeps an existing loader in sync when the React setup is skipped. */\n syncLoader(\n ctx: BuildToolContext & { translationsDir: string; keepAppSource?: boolean }\n ): Promise<SetupResult>;\n /** Configures the app entry after gt.config.json is written. */\n apply(ctx: BuildToolContext): Promise<SetupResult>;\n};\n\nexport const BUILD_TOOL_SETUPS: BuildToolSetup[] = [\n viteSetup,\n tanstackStartSetup,\n];\n\nexport function getBuildToolSetup(\n framework?: string\n): BuildToolSetup | undefined {\n return BUILD_TOOL_SETUPS.find((setup) => setup.framework === framework);\n}\n"],"mappings":";;;AA4CA,MAAa,oBAAsC,CACjD,WACA,mBACD;AAED,SAAgB,kBACd,WAC4B;AAC5B,QAAO,kBAAkB,MAAM,UAAU,MAAM,cAAc,UAAU"}
@@ -0,0 +1,21 @@
1
+ import * as t from '@babel/types';
2
+ type Edit = {
3
+ start: number;
4
+ end?: number;
5
+ text: string;
6
+ };
7
+ export type CodeStyle = {
8
+ quote: string;
9
+ semi: string;
10
+ eol: string;
11
+ indent: string;
12
+ };
13
+ /** Generated lines follow the file's last import, so they read as its own. */
14
+ export declare function getCodeStyle(content: string, statements: t.Statement[]): CodeStyle;
15
+ export declare function getLineIndent(content: string, position: number): string;
16
+ /** The indent before position, or undefined when code precedes it. */
17
+ export declare function getOwnLineIndent(content: string, position: number): string | undefined;
18
+ /** Inserts at original offsets, last first, so earlier offsets stay valid. */
19
+ export declare function applyEdits(content: string, edits: Edit[]): string;
20
+ export declare function getImportEdit(statements: t.Statement[], lines: string[], eol: string): Edit;
21
+ export {};
@@ -0,0 +1,44 @@
1
+ //#region src/setup/buildTools/tanstackStart/edits.ts
2
+ function getImports(statements) {
3
+ return statements.filter((statement) => statement.type === "ImportDeclaration");
4
+ }
5
+ /** Generated lines follow the file's last import, so they read as its own. */
6
+ function getCodeStyle(content, statements) {
7
+ const lastImport = getImports(statements).at(-1);
8
+ return {
9
+ quote: lastImport ? content[lastImport.source.start] : "'",
10
+ semi: lastImport && !content.slice(lastImport.start, lastImport.end).endsWith(";") ? "" : ";",
11
+ eol: content.includes("\r\n") ? "\r\n" : "\n",
12
+ indent: /^([ \t]+)[^\s*]/m.exec(content)?.[1] ?? " "
13
+ };
14
+ }
15
+ function getLineStart(content, position) {
16
+ return content.lastIndexOf("\n", position - 1) + 1;
17
+ }
18
+ function getLineIndent(content, position) {
19
+ return /^[ \t]*/.exec(content.slice(getLineStart(content, position)))[0];
20
+ }
21
+ /** The indent before position, or undefined when code precedes it. */
22
+ function getOwnLineIndent(content, position) {
23
+ const prefix = content.slice(getLineStart(content, position), position);
24
+ return /^[ \t]*$/.test(prefix) ? prefix : void 0;
25
+ }
26
+ /** Inserts at original offsets, last first, so earlier offsets stay valid. */
27
+ function applyEdits(content, edits) {
28
+ return [...edits].sort((a, b) => b.start - a.start).reduce((result, { start, end, text }) => result.slice(0, start) + text + result.slice(end ?? start), content);
29
+ }
30
+ function getImportEdit(statements, lines, eol) {
31
+ const lastImport = getImports(statements).at(-1);
32
+ if (!lastImport) return {
33
+ start: 0,
34
+ text: lines.join(eol) + eol + eol
35
+ };
36
+ return {
37
+ start: (lastImport.trailingComments?.filter((comment) => comment.loc.start.line === lastImport.loc.end.line).at(-1))?.end ?? lastImport.end,
38
+ text: eol + lines.join(eol)
39
+ };
40
+ }
41
+ //#endregion
42
+ export { applyEdits, getCodeStyle, getImportEdit, getLineIndent, getOwnLineIndent };
43
+
44
+ //# sourceMappingURL=edits.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"edits.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/edits.ts"],"sourcesContent":["// Offset-based source edits that follow the file's own code style.\nimport * as t from '@babel/types';\n\ntype Edit = { start: number; end?: number; text: string };\n\nexport type CodeStyle = {\n quote: string;\n semi: string;\n eol: string;\n indent: string;\n};\n\nfunction getImports(statements: t.Statement[]): t.ImportDeclaration[] {\n return statements.filter(\n (statement): statement is t.ImportDeclaration =>\n statement.type === 'ImportDeclaration'\n );\n}\n\n/** Generated lines follow the file's last import, so they read as its own. */\nexport function getCodeStyle(\n content: string,\n statements: t.Statement[]\n): CodeStyle {\n const lastImport = getImports(statements).at(-1);\n return {\n quote: lastImport ? content[lastImport.source.start!] : \"'\",\n semi:\n lastImport &&\n !content.slice(lastImport.start!, lastImport.end!).endsWith(';')\n ? ''\n : ';',\n eol: content.includes('\\r\\n') ? '\\r\\n' : '\\n',\n // Skips JSDoc continuation lines, whose ` * ` is not an indent unit.\n indent: /^([ \\t]+)[^\\s*]/m.exec(content)?.[1] ?? ' ',\n };\n}\n\nfunction getLineStart(content: string, position: number): number {\n return content.lastIndexOf('\\n', position - 1) + 1;\n}\n\nexport function getLineIndent(content: string, position: number): string {\n return /^[ \\t]*/.exec(content.slice(getLineStart(content, position)))![0];\n}\n\n/** The indent before position, or undefined when code precedes it. */\nexport function getOwnLineIndent(\n content: string,\n position: number\n): string | undefined {\n const prefix = content.slice(getLineStart(content, position), position);\n return /^[ \\t]*$/.test(prefix) ? prefix : undefined;\n}\n\n/** Inserts at original offsets, last first, so earlier offsets stay valid. */\nexport function applyEdits(content: string, edits: Edit[]): string {\n return [...edits]\n .sort((a, b) => b.start - a.start)\n .reduce(\n (result, { start, end, text }) =>\n result.slice(0, start) + text + result.slice(end ?? start),\n content\n );\n}\n\nexport function getImportEdit(\n statements: t.Statement[],\n lines: string[],\n eol: string\n): Edit {\n const lastImport = getImports(statements).at(-1);\n if (!lastImport) return { start: 0, text: lines.join(eol) + eol + eol };\n // A same-line comment such as `// eslint-disable-line` stays on its import.\n const lineComment = lastImport.trailingComments\n ?.filter((comment) => comment.loc!.start.line === lastImport.loc!.end.line)\n .at(-1);\n return {\n start: lineComment?.end ?? lastImport.end!,\n text: eol + lines.join(eol),\n };\n}\n"],"mappings":";AAYA,SAAS,WAAW,YAAkD;AACpE,QAAO,WAAW,QACf,cACC,UAAU,SAAS,oBACtB;;;AAIH,SAAgB,a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