gt 2.25.2 → 2.26.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 (70) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/api/downloadFileBatch.js +8 -9
  3. package/dist/api/downloadFileBatch.js.map +1 -1
  4. package/dist/bin/bin-entry.js +1 -1
  5. package/dist/cli/base.js +9 -7
  6. package/dist/cli/base.js.map +1 -1
  7. package/dist/generated/version.d.ts +1 -1
  8. package/dist/generated/version.js +1 -1
  9. package/dist/generated/version.js.map +1 -1
  10. package/dist/main.js +1 -1
  11. package/dist/setup/buildTools/index.d.ts +6 -0
  12. package/dist/setup/buildTools/index.js +6 -1
  13. package/dist/setup/buildTools/index.js.map +1 -1
  14. package/dist/setup/buildTools/reactRouter/index.d.ts +2 -0
  15. package/dist/setup/buildTools/reactRouter/index.js +127 -0
  16. package/dist/setup/buildTools/reactRouter/index.js.map +1 -0
  17. package/dist/setup/buildTools/reactRouter/root.d.ts +23 -0
  18. package/dist/setup/buildTools/reactRouter/root.js +218 -0
  19. package/dist/setup/buildTools/reactRouter/root.js.map +1 -0
  20. package/dist/setup/buildTools/reactRouter/source.d.ts +8 -0
  21. package/dist/setup/buildTools/reactRouter/source.js +106 -0
  22. package/dist/setup/buildTools/reactRouter/source.js.map +1 -0
  23. package/dist/setup/buildTools/shared/document.d.ts +29 -0
  24. package/dist/setup/buildTools/shared/document.js +76 -0
  25. package/dist/setup/buildTools/shared/document.js.map +1 -0
  26. package/dist/setup/buildTools/shared/edits.d.ts +1 -2
  27. package/dist/setup/buildTools/shared/edits.js.map +1 -1
  28. package/dist/setup/buildTools/shared/initializeGT.d.ts +21 -0
  29. package/dist/setup/buildTools/shared/initializeGT.js +50 -0
  30. package/dist/setup/buildTools/shared/initializeGT.js.map +1 -0
  31. package/dist/setup/buildTools/shared/loader.d.ts +6 -0
  32. package/dist/setup/buildTools/shared/loader.js +24 -0
  33. package/dist/setup/buildTools/shared/loader.js.map +1 -0
  34. package/dist/setup/buildTools/shared/source.d.ts +29 -3
  35. package/dist/setup/buildTools/shared/source.js +44 -7
  36. package/dist/setup/buildTools/shared/source.js.map +1 -1
  37. package/dist/setup/buildTools/tanstackStart/index.js +17 -12
  38. package/dist/setup/buildTools/tanstackStart/index.js.map +1 -1
  39. package/dist/setup/buildTools/tanstackStart/root.d.ts +1 -4
  40. package/dist/setup/buildTools/tanstackStart/root.js +17 -57
  41. package/dist/setup/buildTools/tanstackStart/root.js.map +1 -1
  42. package/dist/setup/buildTools/tanstackStart/router.d.ts +1 -9
  43. package/dist/setup/buildTools/tanstackStart/router.js +7 -39
  44. package/dist/setup/buildTools/tanstackStart/router.js.map +1 -1
  45. package/dist/setup/buildTools/vite.js +3 -11
  46. package/dist/setup/buildTools/vite.js.map +1 -1
  47. package/dist/setup/detectFramework.d.ts +1 -1
  48. package/dist/setup/detectFramework.js +5 -1
  49. package/dist/setup/detectFramework.js.map +1 -1
  50. package/dist/setup/developmentCredentials.js +39 -8
  51. package/dist/setup/developmentCredentials.js.map +1 -1
  52. package/dist/setup/frameworkUtils.js +1 -0
  53. package/dist/setup/frameworkUtils.js.map +1 -1
  54. package/dist/setup/wizard.js +4 -0
  55. package/dist/setup/wizard.js.map +1 -1
  56. package/dist/types/index.d.ts +1 -1
  57. package/dist/types/index.js +2 -1
  58. package/dist/types/index.js.map +1 -1
  59. package/dist/utils/constants.d.ts +1 -0
  60. package/dist/utils/constants.js +2 -1
  61. package/dist/utils/constants.js.map +1 -1
  62. package/dist/utils/credentials.js +2 -1
  63. package/dist/utils/credentials.js.map +1 -1
  64. package/dist/utils/loadEnv.d.ts +2 -0
  65. package/dist/utils/loadEnv.js +10 -9
  66. package/dist/utils/loadEnv.js.map +1 -1
  67. package/dist/utils/reactPackageCompatibility.d.ts +5 -0
  68. package/dist/utils/reactPackageCompatibility.js +11 -7
  69. package/dist/utils/reactPackageCompatibility.js.map +1 -1
  70. package/package.json +5 -5
@@ -0,0 +1,23 @@
1
+ import * as t from '@babel/types';
2
+ import { type ViteLoaderExport } from '../../setupViteSPA.js';
3
+ import type { BuildToolContext, ManualAction } from '../index.js';
4
+ import { type SourceFile } from '../shared/source.js';
5
+ /**
6
+ * Configures a root module shaped like the create-react-router or Hydrogen
7
+ * starters. Returns undefined, for manual setup, for any other shape.
8
+ */
9
+ export declare function configureRoot(root: SourceFile, { configImport, loaderExport, }: {
10
+ configImport: string;
11
+ loaderExport: ViteLoaderExport;
12
+ }): string | undefined;
13
+ /**
14
+ * For a root that initializes GT, the change its initializeGT call needs when
15
+ * translations moved between local files and the CDN since setup ran: null
16
+ * when the call already matches, undefined when its options hide the loader.
17
+ */
18
+ export declare function getStorageAction(root: SourceFile, initializeCall: t.CallExpression, ctx: BuildToolContext, loaderExport: ViteLoaderExport): ManualAction | null | undefined;
19
+ /** The manual setup for a root module configureRoot leaves unchanged. */
20
+ export declare function getRootFix(rootPath: string, { configImport, loaderExport, }: {
21
+ configImport: string;
22
+ loaderExport: ViteLoaderExport;
23
+ }): string;
@@ -0,0 +1,218 @@
1
+ import "../../../types/libraries.js";
2
+ import { parseModule } from "../../setupViteSPA.js";
3
+ import { findDeclaredFunction, getLocalImport, getPropertyName, usesName } from "../shared/source.js";
4
+ import { getStorageChangeAction, passesLoader } from "../shared/initializeGT.js";
5
+ import { getDevelopmentEnvNames } from "../../../utils/credentials.js";
6
+ import { applyEdits, getCodeStyle, getImportEdit, getLineIndent, getOwnLineIndent } from "../shared/edits.js";
7
+ import { isChildrenSlot, rendersElement } from "../shared/jsx.js";
8
+ import { LOADER_TRANSLATIONS, findHtmlDocument, getLangEdit, getWrapEdit } from "../shared/document.js";
9
+ import { DOCS_URL } from "./source.js";
10
+ import * as t from "@babel/types";
11
+ //#region src/setup/buildTools/reactRouter/root.ts
12
+ /** The component setup wraps Layout's content in. */
13
+ const ROOT_PROVIDER = "RootGTProvider";
14
+ const ROOT_PROVIDER_COMMENT = [
15
+ "// Renders GTProvider only with root loader data. Without it (a 404, or a",
16
+ "// loader or action error), GTProvider would save the default locale over the",
17
+ "// visitor's. GT components need GTProvider, so render them only with data."
18
+ ];
19
+ /** How the root imports loadTranslations from the loader file. */
20
+ function getLoaderBinding(loaderExport) {
21
+ return loaderExport === "default" ? "loadTranslations" : "{ loadTranslations }";
22
+ }
23
+ /** The style manual steps quote code in. */
24
+ const PROSE = {
25
+ quote: "'",
26
+ semi: ""
27
+ };
28
+ function getLoaderImport({ quote, semi }, loaderExport) {
29
+ return `import ${getLoaderBinding(loaderExport)} from ${quote}./loadTranslations${quote}${semi}`;
30
+ }
31
+ /** Where init saves the project ID, which Vite inlines into app code. */
32
+ const PROJECT_ID_ENV = getDevelopmentEnvNames("react-router").projectId;
33
+ /**
34
+ * The initializeGT call. Local translations pass the loader. CDN translations
35
+ * pass the project ID from app code, since gt-react sits outside the server
36
+ * build and cannot read it there; a nonempty gtConfig.projectId still wins.
37
+ */
38
+ function getInitializeCall({ quote, semi }, loaderExport) {
39
+ const configured = `${quote}projectId${quote} in gtConfig && typeof gtConfig.projectId === ${quote}string${quote} && gtConfig.projectId`;
40
+ return `initializeGT(${loaderExport ? "{ ...gtConfig, loadTranslations }" : `{ ...gtConfig, projectId: (${configured}) || import.meta.env.${PROJECT_ID_ENV} }`})${semi}`;
41
+ }
42
+ /** The imports, initializeGT call and RootGTProvider setup adds. */
43
+ function getSetupLines(style, { configImport, loaderExport, rootData, typed }) {
44
+ const { quote, semi, indent } = style;
45
+ const from = (bindings, source) => `import ${bindings} from ${quote}${source}${quote}${semi}`;
46
+ return [
47
+ from("{ GTProvider, getTranslationsSnapshot, initializeGT, parseLocale }", "gt-react"),
48
+ from("gtConfig", configImport),
49
+ ...loaderExport ? [getLoaderImport(style, loaderExport)] : [],
50
+ "",
51
+ getInitializeCall(style, loaderExport),
52
+ "",
53
+ ...ROOT_PROVIDER_COMMENT,
54
+ `function ${ROOT_PROVIDER}({ children }${typed ? ": { children: React.ReactNode }" : ""}) {`,
55
+ `${indent}const data = ${rootData}${semi}`,
56
+ `${indent}if (!data) return <>{children}</>${semi}`,
57
+ `${indent}return (`,
58
+ `${indent.repeat(2)}<GTProvider locale={data.locale} translations={data.translations}>`,
59
+ `${indent.repeat(3)}{children}`,
60
+ `${indent.repeat(2)}</GTProvider>`,
61
+ `${indent})${semi}`,
62
+ "}"
63
+ ];
64
+ }
65
+ /** Adds the hook to the module's own react-router import, in its style. */
66
+ function getHookImportEdit(statements, content, eol) {
67
+ const last = statements.find((statement) => statement.type === "ImportDeclaration" && statement.source.value === "react-router" && statement.importKind !== "type" && statement.specifiers.at(-1)?.type === "ImportSpecifier")?.specifiers.at(-1);
68
+ if (!last) return void 0;
69
+ const lineIndent = getOwnLineIndent(content, last.start);
70
+ return {
71
+ start: last.end,
72
+ text: lineIndent === void 0 ? ", useRouteLoaderData" : `,${eol}${lineIndent}useRouteLoaderData`
73
+ };
74
+ }
75
+ /** The expression a loader's first parameter gives for the request. */
76
+ function getRequest(param) {
77
+ if (param?.type === "Identifier") return `${param.name}.request`;
78
+ if (param?.type !== "ObjectPattern") return void 0;
79
+ for (const property of param.properties) if (property.type === "ObjectProperty" && t.isIdentifier(property.key, { name: "request" }) && property.value.type === "Identifier") return property.value.name;
80
+ }
81
+ /**
82
+ * Edits that return the locale and translations from the root loader: a new
83
+ * loader before Layout, or additions to an `export async function loader`
84
+ * whose only return is its last statement and returns an object literal.
85
+ */
86
+ function getLoaderEdits(root, layout, { semi, eol, indent }, typed) {
87
+ const { content, statements } = root;
88
+ const localeLine = (request) => `const locale = parseLocale(${request})${semi}`;
89
+ const loader = findDeclaredFunction(statements, "loader", { exported: true });
90
+ if (!loader) {
91
+ if (usesName(statements, ["loader"])) return void 0;
92
+ const start = layout.statement.leadingComments?.find((comment) => getOwnLineIndent(content, comment.start) !== void 0)?.start ?? layout.statement.start;
93
+ const lineIndent = getLineIndent(content, start);
94
+ const routeTypes = typed && getLocalImport(root, "Route", "./+types/root", { types: true });
95
+ return [{
96
+ start,
97
+ text: [
98
+ `export async function loader(${!typed ? "{ request }" : `{ request }: ${routeTypes ? `${routeTypes}.LoaderArgs` : "{ request: Request }"}`}) {`,
99
+ `${lineIndent}${indent}${localeLine("request")}`,
100
+ `${lineIndent}${indent}return { locale, ${LOADER_TRANSLATIONS} }${semi}`,
101
+ `${lineIndent}}`,
102
+ "",
103
+ lineIndent
104
+ ].join(eol)
105
+ }];
106
+ }
107
+ const { fn } = loader;
108
+ const request = getRequest(fn.params[0]);
109
+ if (fn.type !== "FunctionDeclaration" || !fn.async || fn.returnType) return;
110
+ const returns = [];
111
+ t.traverseFast(fn.body, (node) => {
112
+ if (node.type === "ReturnStatement") returns.push(node);
113
+ });
114
+ const [returned] = returns;
115
+ const object = returned?.argument;
116
+ if (!request || returns.length !== 1 || fn.body.body.at(-1) !== returned || object?.type !== "ObjectExpression" || object.properties.length === 0 || object.properties.some((property) => property.type !== "SpreadElement" && getPropertyName(property) === void 0) || /\b(?:locale|translations)\b/.test(content.slice(fn.start, fn.end))) return;
117
+ const returnIndent = getOwnLineIndent(content, returned.start);
118
+ if (returnIndent === void 0) return void 0;
119
+ const [first] = object.properties;
120
+ const propertyIndent = getOwnLineIndent(content, first.start);
121
+ return [{
122
+ start: returned.start,
123
+ text: `${localeLine(request)}${eol}${returnIndent}`
124
+ }, {
125
+ start: first.start,
126
+ text: propertyIndent === void 0 ? `locale, ${LOADER_TRANSLATIONS}, ` : `locale,${eol}${propertyIndent}${LOADER_TRANSLATIONS},${eol}${propertyIndent}`
127
+ }];
128
+ }
129
+ /** Whether every reference to `name` inside `node` calls it. */
130
+ function onlyCalls(node, name) {
131
+ let calls = true;
132
+ t.traverse(node, (child, ancestors) => {
133
+ const parent = ancestors.at(-1);
134
+ if (t.isIdentifier(child, { name }) && !(parent?.key === "callee" && t.isCallExpression(parent.node))) calls = false;
135
+ });
136
+ return calls;
137
+ }
138
+ /**
139
+ * Configures a root module shaped like the create-react-router or Hydrogen
140
+ * starters. Returns undefined, for manual setup, for any other shape.
141
+ */
142
+ function configureRoot(root, { configImport, loaderExport }) {
143
+ const { content, statements } = root;
144
+ if (!statements) return void 0;
145
+ const hookImport = getLocalImport(root, "useRouteLoaderData", "react-router");
146
+ if (hookImport !== void 0 && hookImport !== "useRouteLoaderData" || usesName(statements, [
147
+ "GTProvider",
148
+ "initializeGT",
149
+ "gtConfig",
150
+ "getTranslationsSnapshot",
151
+ "parseLocale",
152
+ "loadTranslations",
153
+ ROOT_PROVIDER,
154
+ "clientLoader",
155
+ ...hookImport ? [] : ["useRouteLoaderData"]
156
+ ])) return;
157
+ const layout = findDeclaredFunction(statements, "Layout", { exported: true });
158
+ if (layout?.fn.body.type !== "BlockStatement" || usesName([layout.fn], ["locale", "loader"]) || !onlyCalls(layout.fn, "useRouteLoaderData")) return;
159
+ const document = findHtmlDocument(layout.fn.body, isChildrenSlot);
160
+ if (!document || !rendersElement([document.html], "Scripts")) return;
161
+ const style = getCodeStyle(content, statements);
162
+ const { quote, semi, eol, indent } = style;
163
+ const hookEdit = hookImport ? void 0 : getHookImportEdit(statements, content, eol);
164
+ if (!hookImport && !hookEdit) return void 0;
165
+ const typed = /\.tsx?$/.test(root.path);
166
+ const loaderEdits = getLoaderEdits({
167
+ ...root,
168
+ statements
169
+ }, layout, style, typed);
170
+ if (!loaderEdits) return void 0;
171
+ const rootData = `useRouteLoaderData${typed ? "<typeof loader>" : ""}(${quote}root${quote})`;
172
+ const [first] = layout.fn.body.body;
173
+ if (!semi && first && "[(`+-/".includes(content[first.start])) return;
174
+ const statementIndent = (first && getOwnLineIndent(content, first.start)) ?? getLineIndent(content, layout.statement.start) + indent;
175
+ const configured = applyEdits(content, [
176
+ getImportEdit(statements, getSetupLines(style, {
177
+ configImport,
178
+ loaderExport,
179
+ rootData,
180
+ typed
181
+ }), eol),
182
+ ...hookEdit ? [hookEdit] : [],
183
+ ...loaderEdits,
184
+ {
185
+ start: layout.fn.body.start + 1,
186
+ text: `${eol}${statementIndent}const locale = ${rootData}?.locale ?? gtConfig.defaultLocale${semi}`
187
+ },
188
+ getLangEdit(document),
189
+ getWrapEdit(content, document, {
190
+ open: `<${ROOT_PROVIDER}>`,
191
+ close: `</${ROOT_PROVIDER}>`
192
+ }, style)
193
+ ]);
194
+ return parseModule(configured, root.path) ? configured : void 0;
195
+ }
196
+ /**
197
+ * For a root that initializes GT, the change its initializeGT call needs when
198
+ * translations moved between local files and the CDN since setup ran: null
199
+ * when the call already matches, undefined when its options hide the loader.
200
+ */
201
+ function getStorageAction(root, initializeCall, ctx, loaderExport) {
202
+ const loaderPassed = passesLoader(root, initializeCall.arguments[0], ctx);
203
+ if (loaderPassed === void 0) return void 0;
204
+ if (loaderPassed === Boolean(loaderExport)) return null;
205
+ return getStorageChangeAction(root, ctx, loaderPassed, {
206
+ call: getInitializeCall(PROSE, loaderExport),
207
+ loaderImport: loaderExport && getLoaderImport(PROSE, loaderExport),
208
+ docsUrl: DOCS_URL
209
+ });
210
+ }
211
+ /** The manual setup for a root module configureRoot leaves unchanged. */
212
+ function getRootFix(rootPath, { configImport, loaderExport }) {
213
+ return `In ${rootPath}, import GTProvider, getTranslationsSnapshot, initializeGT and parseLocale from 'gt-react', useRouteLoaderData from 'react-router', gtConfig from '${configImport}'${loaderExport ? ` and ${getLoaderBinding(loaderExport)} from './loadTranslations'` : ""}, then call ${getInitializeCall(PROSE, loaderExport)}. Return the locale from parseLocale(request) and translations from await getTranslationsSnapshot(locale) in the root loader. In Layout, set <html lang> to that locale, and wrap what <body> renders before <Scripts /> in a GTProvider that renders only when the root loader returned data (see ${DOCS_URL})`;
214
+ }
215
+ //#endregion
216
+ export { configureRoot, getRootFix, getStorageAction };
217
+
218
+ //# sourceMappingURL=root.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"root.js","names":[],"sources":["../../../../src/setup/buildTools/reactRouter/root.ts"],"sourcesContent":["// app/root.tsx: recognizing and configuring the React Router root module.\nimport * as t from '@babel/types';\nimport { Libraries } from '../../../types/libraries.js';\nimport { getDevelopmentEnvNames } from '../../../utils/credentials.js';\nimport { parseModule, type ViteLoaderExport } from '../../setupViteSPA.js';\nimport type { BuildToolContext, ManualAction } from '../index.js';\nimport {\n findHtmlDocument,\n getLangEdit,\n getWrapEdit,\n LOADER_TRANSLATIONS,\n} from '../shared/document.js';\nimport {\n applyEdits,\n getCodeStyle,\n getImportEdit,\n getLineIndent,\n getOwnLineIndent,\n type CodeStyle,\n type Edit,\n} from '../shared/edits.js';\nimport {\n getStorageChangeAction,\n passesLoader,\n} from '../shared/initializeGT.js';\nimport { isChildrenSlot, rendersElement } from '../shared/jsx.js';\nimport {\n findDeclaredFunction,\n getLocalImport,\n getPropertyName,\n usesName,\n type DeclaredFunction,\n type SourceFile,\n} from '../shared/source.js';\nimport { DOCS_URL } from './source.js';\n\n/** The component setup wraps Layout's content in. */\nconst ROOT_PROVIDER = 'RootGTProvider';\n\nconst ROOT_PROVIDER_COMMENT = [\n '// Renders GTProvider only with root loader data. Without it (a 404, or a',\n '// loader or action error), GTProvider would save the default locale over the',\n \"// visitor's. GT components need GTProvider, so render them only with data.\",\n];\n\n/** How the root imports loadTranslations from the loader file. */\nfunction getLoaderBinding(loaderExport: NonNullable<ViteLoaderExport>) {\n return loaderExport === 'default'\n ? 'loadTranslations'\n : '{ loadTranslations }';\n}\n\ntype Style = Pick<CodeStyle, 'quote' | 'semi'>;\n\n/** The style manual steps quote code in. */\nconst PROSE: Style = { quote: \"'\", semi: '' };\n\nfunction getLoaderImport(\n { quote, semi }: Style,\n loaderExport: NonNullable<ViteLoaderExport>\n): string {\n return `import ${getLoaderBinding(loaderExport)} from ${quote}./loadTranslations${quote}${semi}`;\n}\n\n/** Where init saves the project ID, which Vite inlines into app code. */\nconst PROJECT_ID_ENV = getDevelopmentEnvNames('react-router').projectId;\n\n/**\n * The initializeGT call. Local translations pass the loader. CDN translations\n * pass the project ID from app code, since gt-react sits outside the server\n * build and cannot read it there; a nonempty gtConfig.projectId still wins.\n */\nfunction getInitializeCall(\n { quote, semi }: Style,\n loaderExport: ViteLoaderExport\n) {\n const configured = `${quote}projectId${quote} in gtConfig && typeof gtConfig.projectId === ${quote}string${quote} && gtConfig.projectId`;\n const options = loaderExport\n ? '{ ...gtConfig, loadTranslations }'\n : `{ ...gtConfig, projectId: (${configured}) || import.meta.env.${PROJECT_ID_ENV} }`;\n return `initializeGT(${options})${semi}`;\n}\n\n/** The imports, initializeGT call and RootGTProvider setup adds. */\nfunction getSetupLines(\n style: CodeStyle,\n {\n configImport,\n loaderExport,\n rootData,\n typed,\n }: {\n configImport: string;\n loaderExport: ViteLoaderExport;\n rootData: string;\n typed: boolean;\n }\n): string[] {\n const { quote, semi, indent } = style;\n const from = (bindings: string, source: string) =>\n `import ${bindings} from ${quote}${source}${quote}${semi}`;\n return [\n from(\n '{ GTProvider, getTranslationsSnapshot, initializeGT, parseLocale }',\n Libraries.GT_REACT\n ),\n from('gtConfig', configImport),\n ...(loaderExport ? [getLoaderImport(style, loaderExport)] : []),\n '',\n getInitializeCall(style, loaderExport),\n '',\n ...ROOT_PROVIDER_COMMENT,\n `function ${ROOT_PROVIDER}({ children }${typed ? ': { children: React.ReactNode }' : ''}) {`,\n `${indent}const data = ${rootData}${semi}`,\n `${indent}if (!data) return <>{children}</>${semi}`,\n `${indent}return (`,\n `${indent.repeat(2)}<GTProvider locale={data.locale} translations={data.translations}>`,\n `${indent.repeat(3)}{children}`,\n `${indent.repeat(2)}</GTProvider>`,\n `${indent})${semi}`,\n '}',\n ];\n}\n\n/** Adds the hook to the module's own react-router import, in its style. */\nfunction getHookImportEdit(\n statements: t.Statement[],\n content: string,\n eol: string\n): Edit | undefined {\n const routerImport = statements.find(\n (statement): statement is t.ImportDeclaration =>\n statement.type === 'ImportDeclaration' &&\n statement.source.value === 'react-router' &&\n statement.importKind !== 'type' &&\n statement.specifiers.at(-1)?.type === 'ImportSpecifier'\n );\n const last = routerImport?.specifiers.at(-1);\n if (!last) return undefined;\n const lineIndent = getOwnLineIndent(content, last.start!);\n return {\n start: last.end!,\n text:\n lineIndent === undefined\n ? ', useRouteLoaderData'\n : `,${eol}${lineIndent}useRouteLoaderData`,\n };\n}\n\n/** The expression a loader's first parameter gives for the request. */\nfunction getRequest(param: t.Node | undefined): string | undefined {\n if (param?.type === 'Identifier') return `${param.name}.request`;\n if (param?.type !== 'ObjectPattern') return undefined;\n for (const property of param.properties) {\n if (\n property.type === 'ObjectProperty' &&\n t.isIdentifier(property.key, { name: 'request' }) &&\n property.value.type === 'Identifier'\n ) {\n return property.value.name;\n }\n }\n return undefined;\n}\n\n/**\n * Edits that return the locale and translations from the root loader: a new\n * loader before Layout, or additions to an `export async function loader`\n * whose only return is its last statement and returns an object literal.\n */\nfunction getLoaderEdits(\n root: SourceFile & { statements: t.Statement[] },\n layout: DeclaredFunction,\n { semi, eol, indent }: CodeStyle,\n typed: boolean\n): Edit[] | undefined {\n const { content, statements } = root;\n const localeLine = (request: string) =>\n `const locale = parseLocale(${request})${semi}`;\n const loader = findDeclaredFunction(statements, 'loader', { exported: true });\n if (!loader) {\n // Another `loader` binding, such as a re-export, would collide with a new one.\n if (usesName(statements, ['loader'])) return undefined;\n // Before the comments on the lines above Layout, so they stay attached to\n // Layout, and after a comment that ends the line before it.\n const start =\n layout.statement.leadingComments?.find(\n (comment) => getOwnLineIndent(content, comment.start!) !== undefined\n )?.start ?? layout.statement.start!;\n const lineIndent = getLineIndent(content, start);\n // Strict TypeScript needs a typed parameter.\n const routeTypes =\n typed && getLocalImport(root, 'Route', './+types/root', { types: true });\n const param = !typed\n ? '{ request }'\n : `{ request }: ${routeTypes ? `${routeTypes}.LoaderArgs` : '{ request: Request }'}`;\n return [\n {\n start,\n text: [\n `export async function loader(${param}) {`,\n `${lineIndent}${indent}${localeLine('request')}`,\n `${lineIndent}${indent}return { locale, ${LOADER_TRANSLATIONS} }${semi}`,\n `${lineIndent}}`,\n '',\n lineIndent,\n ].join(eol),\n },\n ];\n }\n\n const { fn } = loader;\n const request = getRequest(fn.params[0]);\n // A declared return type would not include the data setup adds.\n if (fn.type !== 'FunctionDeclaration' || !fn.async || fn.returnType) {\n return undefined;\n }\n const returns: t.ReturnStatement[] = [];\n t.traverseFast(fn.body, (node) => {\n if (node.type === 'ReturnStatement') returns.push(node);\n });\n const [returned] = returns;\n const object = returned?.argument;\n if (\n !request ||\n returns.length !== 1 ||\n fn.body.body.at(-1) !== returned ||\n object?.type !== 'ObjectExpression' ||\n object.properties.length === 0 ||\n object.properties.some(\n (property) =>\n property.type !== 'SpreadElement' &&\n getPropertyName(property) === undefined\n ) ||\n // The app's own locale or translations would collide with GT's.\n /\\b(?:locale|translations)\\b/.test(content.slice(fn.start!, fn.end!))\n ) {\n return undefined;\n }\n const returnIndent = getOwnLineIndent(content, returned.start!);\n if (returnIndent === undefined) return undefined;\n // Listed first, so the app's own properties still take precedence.\n const [first] = object.properties;\n const propertyIndent = getOwnLineIndent(content, first.start!);\n return [\n {\n start: returned.start!,\n text: `${localeLine(request)}${eol}${returnIndent}`,\n },\n {\n start: first.start!,\n text:\n propertyIndent === undefined\n ? `locale, ${LOADER_TRANSLATIONS}, `\n : `locale,${eol}${propertyIndent}${LOADER_TRANSLATIONS},${eol}${propertyIndent}`,\n },\n ];\n}\n\n/** Whether every reference to `name` inside `node` calls it. */\nfunction onlyCalls(node: t.Node, name: string): boolean {\n let calls = true;\n t.traverse(node, (child, ancestors) => {\n const parent = ancestors.at(-1);\n if (\n t.isIdentifier(child, { name }) &&\n !(parent?.key === 'callee' && t.isCallExpression(parent.node))\n ) {\n calls = false;\n }\n });\n return calls;\n}\n\n/**\n * Configures a root module shaped like the create-react-router or Hydrogen\n * starters. Returns undefined, for manual setup, for any other shape.\n */\nexport function configureRoot(\n root: SourceFile,\n {\n configImport,\n loaderExport,\n }: { configImport: string; loaderExport: ViteLoaderExport }\n): string | undefined {\n const { content, statements } = root;\n if (!statements) return undefined;\n const hookImport = getLocalImport(root, 'useRouteLoaderData', 'react-router');\n // Setup's bindings must not collide with the app's, and a clientLoader's\n // data would replace the loader's while the page hydrates. A hook imported\n // under another name is left for manual setup too.\n if (\n (hookImport !== undefined && hookImport !== 'useRouteLoaderData') ||\n usesName(statements, [\n 'GTProvider',\n 'initializeGT',\n 'gtConfig',\n 'getTranslationsSnapshot',\n 'parseLocale',\n 'loadTranslations',\n ROOT_PROVIDER,\n 'clientLoader',\n ...(hookImport ? [] : ['useRouteLoaderData']),\n ])\n ) {\n return undefined;\n }\n const layout = findDeclaredFunction(statements, 'Layout', { exported: true });\n // Layout's new locale line must reach the module's loader and hook.\n if (\n layout?.fn.body.type !== 'BlockStatement' ||\n usesName([layout.fn], ['locale', 'loader']) ||\n !onlyCalls(layout.fn, 'useRouteLoaderData')\n ) {\n return undefined;\n }\n const document = findHtmlDocument(layout.fn.body, isChildrenSlot);\n // Every starter Layout renders <Scripts />; RSC Framework Mode roots don't.\n if (!document || !rendersElement([document.html], 'Scripts')) {\n return undefined;\n }\n const style = getCodeStyle(content, statements);\n const { quote, semi, eol, indent } = style;\n const hookEdit = hookImport\n ? undefined\n : getHookImportEdit(statements, content, eol);\n if (!hookImport && !hookEdit) return undefined;\n const typed = /\\.tsx?$/.test(root.path);\n const loaderEdits = getLoaderEdits(\n { ...root, statements },\n layout,\n style,\n typed\n );\n if (!loaderEdits) return undefined;\n\n const rootData = `useRouteLoaderData${typed ? '<typeof loader>' : ''}(${quote}root${quote})`;\n const [first] = layout.fn.body.body;\n // Without semicolons, Layout's new first line would join a statement that\n // starts with one of these.\n if (!semi && first && '[(`+-/'.includes(content[first.start!])) {\n return undefined;\n }\n const statementIndent =\n (first && getOwnLineIndent(content, first.start!)) ??\n getLineIndent(content, layout.statement.start!) + indent;\n const configured = applyEdits(content, [\n getImportEdit(\n statements,\n getSetupLines(style, {\n configImport,\n loaderExport,\n rootData,\n typed,\n }),\n eol\n ),\n ...(hookEdit ? [hookEdit] : []),\n ...loaderEdits,\n {\n start: layout.fn.body.start! + 1,\n text: `${eol}${statementIndent}const locale = ${rootData}?.locale ?? gtConfig.defaultLocale${semi}`,\n },\n getLangEdit(document),\n getWrapEdit(\n content,\n document,\n { open: `<${ROOT_PROVIDER}>`, close: `</${ROOT_PROVIDER}>` },\n style\n ),\n ]);\n // An edit that breaks the module's syntax falls back to manual setup.\n return parseModule(configured, root.path) ? configured : undefined;\n}\n\n/**\n * For a root that initializes GT, the change its initializeGT call needs when\n * translations moved between local files and the CDN since setup ran: null\n * when the call already matches, undefined when its options hide the loader.\n */\nexport function getStorageAction(\n root: SourceFile,\n initializeCall: t.CallExpression,\n ctx: BuildToolContext,\n loaderExport: ViteLoaderExport\n): ManualAction | null | undefined {\n const loaderPassed = passesLoader(root, initializeCall.arguments[0], ctx);\n if (loaderPassed === undefined) return undefined;\n if (loaderPassed === Boolean(loaderExport)) return null;\n return getStorageChangeAction(root, ctx, loaderPassed, {\n call: getInitializeCall(PROSE, loaderExport),\n loaderImport: loaderExport && getLoaderImport(PROSE, loaderExport),\n docsUrl: DOCS_URL,\n });\n}\n\n/** The manual setup for a root module configureRoot leaves unchanged. */\nexport function getRootFix(\n rootPath: string,\n {\n configImport,\n loaderExport,\n }: { configImport: string; loaderExport: ViteLoaderExport }\n): string {\n const loaderImport = loaderExport\n ? ` and ${getLoaderBinding(loaderExport)} from './loadTranslations'`\n : '';\n return `In ${rootPath}, import GTProvider, getTranslationsSnapshot, initializeGT and parseLocale from '${Libraries.GT_REACT}', useRouteLoaderData from 'react-router', gtConfig from '${configImport}'${loaderImport}, then call ${getInitializeCall(PROSE, loaderExport)}. Return the locale from parseLocale(request) and translations from await getTranslationsSnapshot(locale) in the root loader. In Layout, set <html lang> to that locale, and wrap what <body> renders before <Scripts /> in a GTProvider that renders only when the root loader returned data (see ${DOCS_URL})`;\n}\n"],"mappings":";;;;;;;;;;;;AAqCA,MAAM,gBAAgB;AAEtB,MAAM,wBAAwB;CAC5B;CACA;CACA;CACD;;AAGD,SAAS,iBAAiB,cAA6C;AACrE,QAAO,iBAAiB,YACpB,qBACA;;;AAMN,MAAM,QAAe;CAAE,OAAO;C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GACA;GACA;GACA;GACD,CAAC,EACF,IACD;EACD,GAAI,WAAW,CAAC,SAAS,GAAG,EAAE;EAC9B,GAAG;EACH;GACE,OAAO,OAAO,GAAG,KAAK,QAAS;GAC/B,MAAM,GAAG,MAAM,gBAAgB,iBAAiB,SAAS,oCAAoC;GAC9F;EACD,YAAY,SAAS;EACrB,YACE,SACA,UACA;GAAE,MAAM,IAAI,cAAc;GAAI,OAAO,KAAK,cAAc;GAAI,EAC5D,MACD;EACF,CAAC;AAEF,QAAO,YAAY,YAAY,KAAK,KAAK,GAAG,aAAa,KAAA;;;;;;;AAQ3D,SAAgB,iBACd,MACA,gBACA,KACA,cACiC;CACjC,MAAM,eAAe,aAAa,MAAM,eAAe,UAAU,IAAI,IAAI;AACzE,KAAI,iBAAiB,KAAA,EAAW,QAAO,KAAA;AACvC,KAAI,iBAAiB,QAAQ,aAAa,CAAE,QAAO;AACnD,QAAO,uBAAuB,MAAM,KAAK,cAAc;EACrD,MAAM,kBAAkB,OAAO,aAAa;EAC5C,cAAc,gBAAgB,gBAAgB,OAAO,aAAa;EAClE,SAAS;EACV,CAAC;;;AAIJ,SAAgB,WACd,UACA,EACE,cACA,gBAEM;AAIR,QAAO,MAAM,SAAS,qJAAkK,aAAa,GAHhL,eACjB,QAAQ,iBAAiB,aAAa,CAAC,8BACvC,GACiN,cAAc,kBAAkB,OAAO,aAAa,CAAC,qSAAqS,SAAS"}
@@ -0,0 +1,8 @@
1
+ import { type SourceFile } from '../shared/source.js';
2
+ export declare const DOCS_URL = "https://generaltranslation.com/docs/react/react-quickstart";
3
+ /** React Router's app directory, where the root module and loader live. */
4
+ export declare const SOURCE_DIRECTORY = "app";
5
+ export declare const ROOT_MODULE = "app/root";
6
+ export declare const LOADER_FILE = "app/loadTranslations.ts";
7
+ /** Reads the root module, refusing an app setup cannot configure. */
8
+ export declare function inspectReactRouter(appDirectory: string): Promise<SourceFile>;
@@ -0,0 +1,106 @@
1
+ import { getPackageJson, getPackageVersion, isPackageInstalled } from "../../../utils/packageJson.js";
2
+ import "../../../types/libraries.js";
3
+ import { getPropertyName, readSourceFile } from "../shared/source.js";
4
+ import { permitsVersionBelow } from "../../../utils/reactPackageCompatibility.js";
5
+ import { createDiagnosticMessage } from "generaltranslation/internal";
6
+ import path from "node:path";
7
+ import * as t from "@babel/types";
8
+ //#region src/setup/buildTools/reactRouter/source.ts
9
+ const DOCS_URL = "https://generaltranslation.com/docs/react/react-quickstart";
10
+ /** React Router's app directory, where the root module and loader live. */
11
+ const SOURCE_DIRECTORY = "app";
12
+ const ROOT_MODULE = `app/root`;
13
+ const LOADER_FILE = `app/loadTranslations.ts`;
14
+ /**
15
+ * The configured root imports parseLocale, new in gt-react 11.0.4, and
16
+ * Oxygen's worker build resolves gt-react's server entry from 11.1.3.
17
+ */
18
+ const MINIMUM_GT_REACT = "11.1.3";
19
+ /** The extensions React Router resolves react-router.config with. */
20
+ const CONFIG_EXTENSIONS = [
21
+ ".js",
22
+ ".jsx",
23
+ ".ts",
24
+ ".tsx",
25
+ ".mjs",
26
+ ".mts"
27
+ ];
28
+ function getRefusal(why, fix = "With gt-react installed, rerun `npx gt@latest init --no-react-setup` to set up everything except the React code, and set that up manually") {
29
+ return createDiagnosticMessage({
30
+ source: "gt",
31
+ severity: "Error",
32
+ whatHappened: "GT cannot configure this React Router app automatically",
33
+ why,
34
+ reassurance: "Nothing was changed",
35
+ fix,
36
+ docsUrl: DOCS_URL
37
+ });
38
+ }
39
+ const notFrameworkRefusal = getRefusal("it has neither @react-router/dev nor a react-router.config", "If the app uses React Router as a library in a Vite app, rerun `npx gt@latest init --framework vite`");
40
+ const missingRootRefusal = getRefusal("app/root.tsx was not found", "Run `npx gt@latest init` from the app directory");
41
+ const unreadableConfigRefusal = getRefusal("setup cannot read the options react-router.config exports");
42
+ const spaModeRefusal = getRefusal("react-router.config sets ssr: false, so the root loader cannot read each visitor's locale");
43
+ const prerenderRefusal = getRefusal("react-router.config pre-renders pages, which cannot read each visitor's locale");
44
+ const appDirectoryRefusal = getRefusal("react-router.config sets an appDirectory other than app");
45
+ const outdatedGtReactRefusal = getRefusal(`package.json allows gt-react versions older than ${MINIMUM_GT_REACT}, which the configured root needs`, `Upgrade gt-react to ${MINIMUM_GT_REACT} or later, then rerun \`npx gt@latest init\``);
46
+ const rscRefusal = getRefusal("it installs @vitejs/plugin-rsc, which React Router's experimental RSC Framework Mode uses");
47
+ /** Unwraps `satisfies Config` and `as const`. */
48
+ function unwrap(node) {
49
+ while (node?.type === "TSSatisfiesExpression" || node?.type === "TSAsExpression") node = node.expression;
50
+ return node;
51
+ }
52
+ /**
53
+ * The object the config exports by default, directly or through a const that
54
+ * nothing else refers to, so nothing can change it after its declaration.
55
+ */
56
+ function getOptions(statements) {
57
+ const options = unwrap(statements.find((statement) => statement.type === "ExportDefaultDeclaration")?.declaration);
58
+ if (options?.type !== "Identifier") return options;
59
+ const { name } = options;
60
+ let references = 0;
61
+ for (const statement of statements) t.traverseFast(statement, (node) => {
62
+ if (t.isIdentifier(node, { name })) references++;
63
+ });
64
+ if (references !== 2) return void 0;
65
+ return unwrap(statements.flatMap((statement) => statement.type === "VariableDeclaration" && statement.kind === "const" ? statement.declarations : []).find((candidate) => t.isIdentifier(candidate.id, { name }))?.init);
66
+ }
67
+ /**
68
+ * Throws unless the config renders on each request from app/: each option it
69
+ * sets must be one React Router treats like its default. Presets, such as
70
+ * Hydrogen's, are trusted.
71
+ */
72
+ function checkConfig({ statements }, appDirectory) {
73
+ const options = statements && getOptions(statements);
74
+ if (options?.type !== "ObjectExpression") throw new Error(unreadableConfigRefusal);
75
+ for (const property of options.properties) {
76
+ const name = getPropertyName(property);
77
+ if (name === void 0) throw new Error(unreadableConfigRefusal);
78
+ const value = property.type === "ObjectProperty" ? unwrap(property.value) : void 0;
79
+ if (name === "ssr") {
80
+ if (!t.isBooleanLiteral(value)) throw new Error(unreadableConfigRefusal);
81
+ if (!value.value) throw new Error(spaModeRefusal);
82
+ }
83
+ if (name === "prerender" && !t.isBooleanLiteral(value, { value: false }) && !(t.isArrayExpression(value) && value.elements.length === 0)) throw new Error(prerenderRefusal);
84
+ if (name === "appDirectory" && !(t.isStringLiteral(value) && path.resolve(appDirectory, value.value) === path.resolve(appDirectory, "app"))) throw new Error(appDirectoryRefusal);
85
+ }
86
+ }
87
+ /** Reads the root module, refusing an app setup cannot configure. */
88
+ async function inspectReactRouter(appDirectory) {
89
+ const config = await readSourceFile(appDirectory, "react-router.config", { extensions: CONFIG_EXTENSIONS });
90
+ const packageJson = await getPackageJson(appDirectory);
91
+ if (packageJson) {
92
+ const installed = (name) => isPackageInstalled(name, packageJson, false, true);
93
+ if (!config && !installed("@react-router/dev")) throw new Error(notFrameworkRefusal);
94
+ if (installed("@vitejs/plugin-rsc")) throw new Error(rscRefusal);
95
+ const gtReact = getPackageVersion("gt-react", packageJson);
96
+ if (gtReact && permitsVersionBelow(gtReact, MINIMUM_GT_REACT)) throw new Error(outdatedGtReactRefusal);
97
+ }
98
+ if (config) checkConfig(config, appDirectory);
99
+ const root = await readSourceFile(appDirectory, ROOT_MODULE);
100
+ if (!root) throw new Error(missingRootRefusal);
101
+ return root;
102
+ }
103
+ //#endregion
104
+ export { DOCS_URL, LOADER_FILE, ROOT_MODULE, SOURCE_DIRECTORY, inspectReactRouter };
105
+
106
+ //# sourceMappingURL=source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"source.js","names":[],"sources":["../../../../src/setup/buildTools/reactRouter/source.ts"],"sourcesContent":["// Reads the React Router config and root module, and stops setup before any\n// change for an app it cannot configure.\nimport path from 'node:path';\nimport * as t from '@babel/types';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { Libraries } from '../../../types/libraries.js';\nimport {\n getPackageJson,\n getPackageVersion,\n isPackageInstalled,\n} from '../../../utils/packageJson.js';\nimport { permitsVersionBelow } from '../../../utils/reactPackageCompatibility.js';\nimport {\n getPropertyName,\n readSourceFile,\n type SourceFile,\n} from '../shared/source.js';\n\nexport const DOCS_URL =\n 'https://generaltranslation.com/docs/react/react-quickstart';\n\n/** React Router's app directory, where the root module and loader live. */\nexport const SOURCE_DIRECTORY = 'app';\n\nexport const ROOT_MODULE = `${SOURCE_DIRECTORY}/root`;\n\nexport const LOADER_FILE = `${SOURCE_DIRECTORY}/loadTranslations.ts`;\n\n/**\n * The configured root imports parseLocale, new in gt-react 11.0.4, and\n * Oxygen's worker build resolves gt-react's server entry from 11.1.3.\n */\nconst MINIMUM_GT_REACT = '11.1.3';\n\n/** The extensions React Router resolves react-router.config with. */\nconst CONFIG_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.mts'];\n\nfunction getRefusal(\n why: string,\n fix = 'With gt-react installed, rerun `npx gt@latest init --no-react-setup` to set up everything except the React code, and set that up manually'\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'GT cannot configure this React Router app automatically',\n why,\n reassurance: 'Nothing was changed',\n fix,\n docsUrl: DOCS_URL,\n });\n}\n\nconst notFrameworkRefusal = getRefusal(\n 'it has neither @react-router/dev nor a react-router.config',\n 'If the app uses React Router as a library in a Vite app, rerun `npx gt@latest init --framework vite`'\n);\nconst missingRootRefusal = getRefusal(\n 'app/root.tsx was not found',\n 'Run `npx gt@latest init` from the app directory'\n);\nconst unreadableConfigRefusal = getRefusal(\n 'setup cannot read the options react-router.config exports'\n);\nconst spaModeRefusal = getRefusal(\n \"react-router.config sets ssr: false, so the root loader cannot read each visitor's locale\"\n);\nconst prerenderRefusal = getRefusal(\n \"react-router.config pre-renders pages, which cannot read each visitor's locale\"\n);\nconst appDirectoryRefusal = getRefusal(\n 'react-router.config sets an appDirectory other than app'\n);\nconst outdatedGtReactRefusal = getRefusal(\n `package.json allows gt-react versions older than ${MINIMUM_GT_REACT}, which the configured root needs`,\n `Upgrade gt-react to ${MINIMUM_GT_REACT} or later, then rerun \\`npx gt@latest init\\``\n);\nconst rscRefusal = getRefusal(\n \"it installs @vitejs/plugin-rsc, which React Router's experimental RSC Framework Mode uses\"\n);\n\n/** Unwraps `satisfies Config` and `as const`. */\nfunction unwrap(node: t.Node | null | undefined) {\n while (\n node?.type === 'TSSatisfiesExpression' ||\n node?.type === 'TSAsExpression'\n ) {\n node = node.expression;\n }\n return node;\n}\n\n/**\n * The object the config exports by default, directly or through a const that\n * nothing else refers to, so nothing can change it after its declaration.\n */\nfunction getOptions(statements: t.Statement[]) {\n const options = unwrap(\n statements.find(\n (statement) => statement.type === 'ExportDefaultDeclaration'\n )?.declaration\n );\n if (options?.type !== 'Identifier') return options;\n const { name } = options;\n let references = 0;\n for (const statement of statements) {\n t.traverseFast(statement, (node) => {\n if (t.isIdentifier(node, { name })) references++;\n });\n }\n if (references !== 2) return undefined;\n const declarator = statements\n .flatMap((statement) =>\n statement.type === 'VariableDeclaration' && statement.kind === 'const'\n ? statement.declarations\n : []\n )\n .find((candidate) => t.isIdentifier(candidate.id, { name }));\n return unwrap(declarator?.init);\n}\n\n/**\n * Throws unless the config renders on each request from app/: each option it\n * sets must be one React Router treats like its default. Presets, such as\n * Hydrogen's, are trusted.\n */\nfunction checkConfig({ statements }: SourceFile, appDirectory: string) {\n const options = statements && getOptions(statements);\n if (options?.type !== 'ObjectExpression') {\n throw new Error(unreadableConfigRefusal);\n }\n for (const property of options.properties) {\n const name = getPropertyName(property);\n if (name === undefined) throw new Error(unreadableConfigRefusal);\n const value =\n property.type === 'ObjectProperty' ? unwrap(property.value) : undefined;\n if (name === 'ssr') {\n if (!t.isBooleanLiteral(value)) throw new Error(unreadableConfigRefusal);\n if (!value.value) throw new Error(spaModeRefusal);\n }\n if (\n name === 'prerender' &&\n !t.isBooleanLiteral(value, { value: false }) &&\n !(t.isArrayExpression(value) && value.elements.length === 0)\n ) {\n throw new Error(prerenderRefusal);\n }\n // React Router resolves it from the project directory.\n if (\n name === 'appDirectory' &&\n !(\n t.isStringLiteral(value) &&\n path.resolve(appDirectory, value.value) ===\n path.resolve(appDirectory, SOURCE_DIRECTORY)\n )\n ) {\n throw new Error(appDirectoryRefusal);\n }\n }\n}\n\n/** Reads the root module, refusing an app setup cannot configure. */\nexport async function inspectReactRouter(appDirectory: string) {\n const config = await readSourceFile(appDirectory, 'react-router.config', {\n extensions: CONFIG_EXTENSIONS,\n });\n // Framework mode installs @react-router/dev, which a monorepo may install\n // at its root, so a config also counts.\n const packageJson = await getPackageJson(appDirectory);\n if (packageJson) {\n const installed = (name: string) =>\n isPackageInstalled(name, packageJson, false, true);\n if (!config && !installed('@react-router/dev')) {\n throw new Error(notFrameworkRefusal);\n }\n if (installed('@vitejs/plugin-rsc')) throw new Error(rscRefusal);\n // An undeclared gt-react is installed at its latest version.\n const gtReact = getPackageVersion(Libraries.GT_REACT, packageJson);\n if (gtReact && permitsVersionBelow(gtReact, MINIMUM_GT_REACT)) {\n throw new Error(outdatedGtReactRefusal);\n }\n }\n if (config) checkConfig(config, appDirectory);\n const root = await readSourceFile(appDirectory, ROOT_MODULE);\n if (!root) throw new Error(missingRootRefusal);\n return root;\n}\n"],"mappings":";;;;;;;;AAkBA,MAAa,WACX;;AAGF,MAAa,mBAAmB;AAEhC,MAAa,cAAc;AAE3B,MAAa,cAAc;;;;;AAM3B,MAAM,mBAAmB;;AAGzB,MAAM,oBAAoB;CAAC;CAAO;CAAQ;CAAO;CAAQ;CAAQ;CAAO;AAExE,SAAS,WACP,KACA,MAAM,6IACE;AACR,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc;EACd;EACA,aAAa;EACb;EACA,SAAS;EACV,CAAC;;AAGJ,MAAM,sBAAsB,WAC1B,8DACA,uGACD;AACD,MAAM,qBAAqB,WACzB,8BACA,kDACD;AACD,MAAM,0BAA0B,WAC9B,4DACD;AACD,MAAM,iBAAiB,WACrB,4FACD;AACD,MAAM,mBAAmB,WACvB,iFACD;AACD,MAAM,sBAAsB,WAC1B,0DACD;AACD,MAAM,yBAAyB,WAC7B,oDAAoD,iBAAiB,oCACrE,uBAAuB,iBAAiB,8CACzC;AACD,MAAM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M,SAAS,WAAW,GAE1D,OAAM,IAAI,MAAM,iBAAiB;AAGnC,MACE,SAAS,kBACT,EACE,EAAE,gBAAgB,MAAM,IACxB,KAAK,QAAQ,cAAc,MAAM,MAAM,KACrC,KAAK,QAAQ,cAAA,MAA+B,EAGhD,OAAM,IAAI,MAAM,oBAAoB;;;;AAM1C,eAAsB,mBAAmB,cAAsB;CAC7D,MAAM,SAAS,MAAM,eAAe,cAAc,uBAAuB,EACvE,YAAY,mBACb,CAAC;CAGF,MAAM,cAAc,MAAM,eAAe,aAAa;AACtD,KAAI,aAAa;EACf,MAAM,aAAa,SACjB,mBAAmB,MAAM,aAAa,OAAO,KAAK;AACpD,MAAI,CAAC,UAAU,CAAC,UAAU,oBAAoB,CAC5C,OAAM,IAAI,MAAM,oBAAoB;AAEtC,MAAI,UAAU,qBAAqB,CAAE,OAAM,IAAI,MAAM,WAAW;EAEhE,MAAM,UAAU,kBAAA,YAAsC,YAAY;AAClE,MAAI,WAAW,oBAAoB,SAAS,iBAAiB,CAC3D,OAAM,IAAI,MAAM,uBAAuB;;AAG3C,KAAI,OAAQ,aAAY,QAAQ,aAAa;CAC7C,MAAM,OAAO,MAAM,eAAe,cAAc,YAAY;AAC5D,KAAI,CAAC,KAAM,OAAM,IAAI,MAAM,mBAAmB;AAC9C,QAAO"}
@@ -0,0 +1,29 @@
1
+ import * as t from '@babel/types';
2
+ import { type CodeStyle, type Edit } from './edits.js';
3
+ /** The translations property the root loader returns for the document. */
4
+ export declare const LOADER_TRANSLATIONS = "translations: await getTranslationsSnapshot(locale)";
5
+ export type HtmlDocument = {
6
+ html: t.JSXElement;
7
+ /** The literal `lang` attribute, when the document sets one. */
8
+ lang?: t.JSXAttribute;
9
+ /** What `<body>` renders before `<Scripts />`: the content setup wraps. */
10
+ wrapped: t.JSXElement['children'];
11
+ /** Set when reindenting the wrapped content would change a literal. */
12
+ multilineLiteral: boolean;
13
+ };
14
+ /**
15
+ * The single `<html>` a root function body renders, its literal `lang` if any,
16
+ * and the content setup wraps, which must render the route's slot exactly
17
+ * once. Returns undefined for any other shape.
18
+ */
19
+ export declare function findHtmlDocument(functionBody: t.BlockStatement, isSlot: (node: t.Node) => boolean): HtmlDocument | undefined;
20
+ /** Renders the document in the locale setup reads, replacing a literal lang. */
21
+ export declare function getLangEdit({ html, lang }: HtmlDocument): Edit;
22
+ /**
23
+ * Wraps the document's content in the element `open` and `close` delimit,
24
+ * reindented to the depth the element adds.
25
+ */
26
+ export declare function getWrapEdit(content: string, { wrapped, multilineLiteral }: HtmlDocument, { open, close }: {
27
+ open: string;
28
+ close: string;
29
+ }, { eol, indent }: Pick<CodeStyle, 'eol' | 'indent'>): Edit;
@@ -0,0 +1,76 @@
1
+ import { getOwnLineIndent } from "./edits.js";
2
+ import { isJsxElementNamed } from "./jsx.js";
3
+ import * as t from "@babel/types";
4
+ //#region src/setup/buildTools/shared/document.ts
5
+ /** The translations property the root loader returns for the document. */
6
+ const LOADER_TRANSLATIONS = "translations: await getTranslationsSnapshot(locale)";
7
+ /**
8
+ * The single `<html>` a root function body renders, its literal `lang` if any,
9
+ * and the content setup wraps, which must render the route's slot exactly
10
+ * once. Returns undefined for any other shape.
11
+ */
12
+ function findHtmlDocument(functionBody, isSlot) {
13
+ const htmlElements = [];
14
+ t.traverseFast(functionBody, (node) => {
15
+ if (isJsxElementNamed(node, "html")) htmlElements.push(node);
16
+ });
17
+ if (htmlElements.length !== 1) return void 0;
18
+ const [html] = htmlElements;
19
+ const bodies = html.children.filter((child) => isJsxElementNamed(child, "body"));
20
+ if (bodies.length !== 1) return void 0;
21
+ const bodyContent = bodies[0].children.filter((child) => child.type !== "JSXText" || child.value.trim() !== "");
22
+ const scriptsIndex = bodyContent.findIndex((child) => isJsxElementNamed(child, "Scripts"));
23
+ const wrapped = scriptsIndex === -1 ? bodyContent : bodyContent.slice(0, scriptsIndex);
24
+ let slots = 0;
25
+ let multilineLiteral = false;
26
+ for (const child of wrapped) t.traverseFast(child, (node) => {
27
+ if (isSlot(node)) slots++;
28
+ if ((node.type === "TemplateLiteral" || node.type === "StringLiteral") && node.loc.start.line !== node.loc.end.line) multilineLiteral = true;
29
+ });
30
+ if (slots !== 1) return void 0;
31
+ const { attributes } = html.openingElement;
32
+ if (attributes.some((attribute) => attribute.type === "JSXSpreadAttribute")) return;
33
+ const lang = attributes.find((attribute) => attribute.type === "JSXAttribute" && t.isJSXIdentifier(attribute.name, { name: "lang" }));
34
+ if (lang && lang.value?.type !== "StringLiteral") return void 0;
35
+ return {
36
+ html,
37
+ lang,
38
+ wrapped,
39
+ multilineLiteral
40
+ };
41
+ }
42
+ /** Renders the document in the locale setup reads, replacing a literal lang. */
43
+ function getLangEdit({ html, lang }) {
44
+ return lang ? {
45
+ start: lang.start,
46
+ end: lang.end,
47
+ text: "lang={locale}"
48
+ } : {
49
+ start: html.openingElement.name.end,
50
+ text: " lang={locale}"
51
+ };
52
+ }
53
+ /**
54
+ * Wraps the document's content in the element `open` and `close` delimit,
55
+ * reindented to the depth the element adds.
56
+ */
57
+ function getWrapEdit(content, { wrapped, multilineLiteral }, { open, close }, { eol, indent }) {
58
+ const first = wrapped[0];
59
+ const last = wrapped.at(-1);
60
+ const wrappedText = content.slice(first.start, last.end);
61
+ const wrappedIndent = getOwnLineIndent(content, first.start);
62
+ const nestedText = multilineLiteral ? wrappedText : wrappedText.replace(/\n(?=[ \t]*\S)/g, `\n${indent}`);
63
+ return {
64
+ start: first.start,
65
+ end: last.end,
66
+ text: wrappedIndent === void 0 ? `${open}${wrappedText}${close}` : [
67
+ open,
68
+ `${wrappedIndent}${indent}${nestedText}`,
69
+ `${wrappedIndent}${close}`
70
+ ].join(eol)
71
+ };
72
+ }
73
+ //#endregion
74
+ export { LOADER_TRANSLATIONS, findHtmlDocument, getLangEdit, getWrapEdit };
75
+
76
+ //# sourceMappingURL=document.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document.js","names":[],"sources":["../../../../src/setup/buildTools/shared/document.ts"],"sourcesContent":["// What setup writes into a root module: the translations its loader returns,\n// and the edits that wrap the <html> document it renders.\nimport * as t from '@babel/types';\nimport { getOwnLineIndent, type CodeStyle, type Edit } from './edits.js';\nimport { isJsxElementNamed } from './jsx.js';\n\n/** The translations property the root loader returns for the document. */\nexport const LOADER_TRANSLATIONS =\n 'translations: await getTranslationsSnapshot(locale)';\n\nexport type HtmlDocument = {\n html: t.JSXElement;\n /** The literal `lang` attribute, when the document sets one. */\n lang?: t.JSXAttribute;\n /** What `<body>` renders before `<Scripts />`: the content setup wraps. */\n wrapped: t.JSXElement['children'];\n /** Set when reindenting the wrapped content would change a literal. */\n multilineLiteral: boolean;\n};\n\n/**\n * The single `<html>` a root function body renders, its literal `lang` if any,\n * and the content setup wraps, which must render the route's slot exactly\n * once. Returns undefined for any other shape.\n */\nexport function findHtmlDocument(\n functionBody: t.BlockStatement,\n isSlot: (node: t.Node) => boolean\n): HtmlDocument | undefined {\n const htmlElements: t.JSXElement[] = [];\n t.traverseFast(functionBody, (node) => {\n if (isJsxElementNamed(node, 'html')) htmlElements.push(node);\n });\n if (htmlElements.length !== 1) return undefined;\n const [html] = htmlElements;\n const bodies = html.children.filter((child) =>\n isJsxElementNamed(child, 'body')\n );\n if (bodies.length !== 1) return undefined;\n // Headers, footers and app providers around the slot render GT too, so the\n // provider wraps everything the body renders before <Scripts />.\n const bodyContent = bodies[0].children.filter(\n (child) => child.type !== 'JSXText' || child.value.trim() !== ''\n );\n const scriptsIndex = bodyContent.findIndex((child) =>\n isJsxElementNamed(child, 'Scripts')\n );\n const wrapped =\n scriptsIndex === -1 ? bodyContent : bodyContent.slice(0, scriptsIndex);\n let slots = 0;\n let multilineLiteral = false;\n for (const child of wrapped) {\n t.traverseFast(child, (node) => {\n if (isSlot(node)) slots++;\n if (\n (node.type === 'TemplateLiteral' || node.type === 'StringLiteral') &&\n node.loc!.start.line !== node.loc!.end.line\n ) {\n multilineLiteral = true;\n }\n });\n }\n if (slots !== 1) return undefined;\n const { attributes } = html.openingElement;\n if (attributes.some((attribute) => attribute.type === 'JSXSpreadAttribute')) {\n return undefined;\n }\n const lang = attributes.find(\n (attribute): attribute is t.JSXAttribute =>\n attribute.type === 'JSXAttribute' &&\n t.isJSXIdentifier(attribute.name, { name: 'lang' })\n );\n // A computed lang is the app's own locale logic.\n if (lang && lang.value?.type !== 'StringLiteral') return undefined;\n return { html, lang, wrapped, multilineLiteral };\n}\n\n/** Renders the document in the locale setup reads, replacing a literal lang. */\nexport function getLangEdit({ html, lang }: HtmlDocument): Edit {\n return lang\n ? { start: lang.start!, end: lang.end!, text: 'lang={locale}' }\n : { start: html.openingElement.name.end!, text: ' lang={locale}' };\n}\n\n/**\n * Wraps the document's content in the element `open` and `close` delimit,\n * reindented to the depth the element adds.\n */\nexport function getWrapEdit(\n content: string,\n { wrapped, multilineLiteral }: HtmlDocument,\n { open, close }: { open: string; close: string },\n { eol, indent }: Pick<CodeStyle, 'eol' | 'indent'>\n): Edit {\n const first = wrapped[0];\n const last = wrapped.at(-1)!;\n const wrappedText = content.slice(first.start!, last.end!);\n const wrappedIndent = getOwnLineIndent(content, first.start!);\n // Reindenting would change the value of a literal that spans lines, such\n // as a template, a backslash-continued string or a JSX attribute string.\n const nestedText = multilineLiteral\n ? wrappedText\n : wrappedText.replace(/\\n(?=[ \\t]*\\S)/g, `\\n${indent}`);\n return {\n start: first.start!,\n end: last.end!,\n text:\n wrappedIndent === undefined\n ? `${open}${wrappedText}${close}`\n : [\n open,\n `${wrappedIndent}${indent}${nestedText}`,\n `${wrappedIndent}${close}`,\n ].join(eol),\n };\n}\n"],"mappings":";;;;;AAOA,MAAa,sBACX;;;;;;AAiBF,SAAgB,iBACd,cACA,QAC0B;CAC1B,MAAM,eAA+B,EAAE;AACvC,GAAE,aAAa,eAAe,SAAS;AACrC,MAAI,kBAAkB,MAAM,OAAO,CAAE,cAAa,KAAK,KAAK;GAC5D;AACF,KAAI,aAAa,WAAW,EAAG,QAAO,KAAA;CACtC,MAAM,CAAC,QAAQ;CACf,MAA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cAAc,QAAQ,MAAM,MAAM,OAAQ,KAAK,IAAK;CAC1D,MAAM,gBAAgB,iBAAiB,SAAS,MAAM,MAAO;CAG7D,MAAM,aAAa,mBACf,cACA,YAAY,QAAQ,mBAAmB,KAAK,SAAS;AACzD,QAAO;EACL,OAAO,MAAM;EACb,KAAK,KAAK;EACV,MACE,kBAAkB,KAAA,IACd,GAAG,OAAO,cAAc,UACxB;GACE;GACA,GAAG,gBAAgB,SAAS;GAC5B,GAAG,gBAAgB;GACpB,CAAC,KAAK,IAAI;EAClB"}
@@ -1,5 +1,5 @@
1
1
  import * as t from '@babel/types';
2
- type Edit = {
2
+ export type Edit = {
3
3
  start: number;
4
4
  end?: number;
5
5
  text: string;
@@ -18,4 +18,3 @@ export declare function getOwnLineIndent(content: string, position: number): str
18
18
  /** Inserts at original offsets, last first, so earlier offsets stay valid. */
19
19
  export declare function applyEdits(content: string, edits: Edit[]): string;
20
20
  export declare function getImportEdit(statements: t.Statement[], lines: string[], eol: string): Edit;
21
- export {};
@@ -1 +1 @@
1
- {"version":3,"file":"edits.js","names":[],"sources":["../../../../src/setup/buildTools/shared/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,aACd,SACA,YACW;CACX,MAAM,aAAa,WAAW,WAAW,CAAC,GAAG,GAAG;AAChD,QAAO;EACL,OAAO,aAAa,QAAQ,WAAW,OAAO,SAAU;EACxD,MACE,cACA,CAAC,QAAQ,MAAM,WAAW,OAAQ,WAAW,IAAK,CAAC,SAAS,IAAI,GAC5D,KACA;EACN,KAAK,QAAQ,SAAS,OAAO,GAAG,SAAS;EAEzC,QAAQ,mBAAmB,KAAK,QAAQ,GAAG,MAAM;EAClD;;AAGH,SAAS,aAAa,SAAiB,UAA0B;AAC/D,QAAO,QAAQ,YAAY,MAAM,WAAW,EAAE,GAAG;;AAGnD,SAAgB,cAAc,SAAiB,UAA0B;AACvE,QAAO,UAAU,KAAK,QAAQ,MAAM,aAAa,SAAS,SAAS,CAAC,CAAC,CAAE;;;AAIzE,SAAgB,iBACd,SACA,UACoB;CACpB,MAAM,SAAS,QAAQ,MAAM,aAAa,SAAS,SAAS,EAAE,SAAS;AACvE,QAAO,WAAW,KAAK,OAAO,GAAG,SAAS,KAAA;;;AAI5C,SAAgB,WAAW,SAAiB,OAAuB;AACjE,QAAO,CAAC,GAAG,MAAM,CACd,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,CACjC,QACE,QAAQ,EAAE,OAAO,KAAK,WACrB,OAAO,MAAM,GAAG,MAAM,GAAG,OAAO,OAAO,MAAM,OAAO,MAAM,EAC5D,QACD;;AAGL,SAAgB,cACd,YACA,OACA,KACM;CACN,MAAM,aAAa,WAAW,WAAW,CAAC,GAAG,GAAG;AAChD,KAAI,CAAC,WAAY,QAAO;EAAE,OAAO;EAAG,MAAM,MAAM,KAAK,IAAI,GAAG,MAAM;EAAK;AAKvE,QAAO;EACL,QAJkB,WAAW,kBAC3B,QAAQ,YAAY,QAAQ,IAAK,MAAM,SAAS,WAAW,IAAK,IAAI,KAAK,CAC1E,GAAG,GAAG,GAEa,OAAO,WAAW;EACtC,MAAM,MAAM,MAAM,KAAK,IAAI;EAC5B"}
1
+ {"version":3,"file":"edits.js","names":[],"sources":["../../../../src/setup/buildTools/shared/edits.ts"],"sourcesContent":["// Offset-based source edits that follow the file's own code style.\nimport * as t from '@babel/types';\n\nexport type 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,aACd,SACA,YACW;CACX,MAAM,aAAa,WAAW,WAAW,CAAC,GAAG,GAAG;AAChD,QAAO;EACL,OA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ile } from './source.js';
4
+ /** The module-scope `initializeGT(...)` call, which must run before requests. */
5
+ export declare function findInitializeCall(file: SourceFile, source: string): t.CallExpression | undefined;
6
+ /**
7
+ * Whether the initializeGT options pass a loader: false for the config alone,
8
+ * undefined when the options hide it (other spreads, variables, computed keys).
9
+ * Callers report a mismatch only when this is certain.
10
+ */
11
+ export declare function passesLoader(file: SourceFile, options: t.Node | undefined, { appDirectory, configFilepath }: BuildToolContext): boolean | undefined;
12
+ /**
13
+ * The change an initializeGT call needs when translations moved between local
14
+ * files and the CDN since setup ran. Callers quote the call and loader import
15
+ * they would write.
16
+ */
17
+ export declare function getStorageChangeAction(file: SourceFile, { translationsDir }: Pick<BuildToolContext, 'translationsDir'>, loaderPassed: boolean, { call, loaderImport, docsUrl, }: {
18
+ call: string;
19
+ loaderImport?: string;
20
+ docsUrl: string;
21
+ }): ManualAction;