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,50 @@
1
+ import { getLocalImport, getPropertyName } from "./source.js";
2
+ import path from "node:path";
3
+ import * as t from "@babel/types";
4
+ //#region src/setup/buildTools/shared/initializeGT.ts
5
+ /** The module-scope `initializeGT(...)` call, which must run before requests. */
6
+ function findInitializeCall(file, source) {
7
+ const local = getLocalImport(file, "initializeGT", source);
8
+ if (!local) return void 0;
9
+ for (const statement of file.statements ?? []) if (statement.type === "ExpressionStatement" && statement.expression.type === "CallExpression" && t.isIdentifier(statement.expression.callee, { name: local })) return statement.expression;
10
+ }
11
+ /**
12
+ * Whether the initializeGT options pass a loader: false for the config alone,
13
+ * undefined when the options hide it (other spreads, variables, computed keys).
14
+ * Callers report a mismatch only when this is certain.
15
+ */
16
+ function passesLoader(file, options, { appDirectory, configFilepath }) {
17
+ const configPath = path.resolve(appDirectory, configFilepath);
18
+ const fileDirectory = path.dirname(path.join(appDirectory, file.path));
19
+ const configBinding = file.statements?.filter((statement) => statement.type === "ImportDeclaration").find((statement) => path.resolve(fileDirectory, statement.source.value) === configPath)?.specifiers.find((specifier) => specifier.type === "ImportDefaultSpecifier")?.local.name;
20
+ const isConfig = (node) => node.type === "Identifier" && node.name === configBinding;
21
+ if (!options) return void 0;
22
+ if (isConfig(options)) return false;
23
+ if (options.type !== "ObjectExpression") return void 0;
24
+ let loader = false;
25
+ for (const property of options.properties) {
26
+ if (property.type === "SpreadElement") {
27
+ if (!isConfig(property.argument)) return void 0;
28
+ continue;
29
+ }
30
+ const name = getPropertyName(property);
31
+ if (name === void 0) return void 0;
32
+ if (name === "loadTranslations") loader = true;
33
+ }
34
+ return loader;
35
+ }
36
+ /**
37
+ * The change an initializeGT call needs when translations moved between local
38
+ * files and the CDN since setup ran. Callers quote the call and loader import
39
+ * they would write.
40
+ */
41
+ function getStorageChangeAction(file, { translationsDir }, loaderPassed, { call, loaderImport, docsUrl }) {
42
+ return {
43
+ whatHappened: `${file.path} initializes GT for ${loaderPassed ? "local translation files" : "CDN translations"}, but translations are now ${translationsDir ? `stored in ${translationsDir}` : "loaded from the CDN"}`,
44
+ fix: `Change the initializeGT call in ${file.path} to ${call}${loaderImport ? ` and add ${loaderImport}` : " and remove the loadTranslations import"} (see ${docsUrl})`
45
+ };
46
+ }
47
+ //#endregion
48
+ export { findInitializeCall, getStorageChangeAction, passesLoader };
49
+
50
+ //# sourceMappingURL=initializeGT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initializeGT.js","names":[],"sources":["../../../../src/setup/buildTools/shared/initializeGT.ts"],"sourcesContent":["// The initializeGT call an app entry makes, the loader it passes, and the\n// change it needs when translation storage moved.\nimport * as t from '@babel/types';\nimport path from 'node:path';\nimport type { BuildToolContext, ManualAction } from '../index.js';\nimport { getLocalImport, getPropertyName, type SourceFile } from './source.js';\n\n/** The module-scope `initializeGT(...)` call, which must run before requests. */\nexport function findInitializeCall(\n file: SourceFile,\n source: string\n): t.CallExpression | undefined {\n const local = getLocalImport(file, 'initializeGT', source);\n if (!local) return undefined;\n for (const statement of file.statements ?? []) {\n if (\n statement.type === 'ExpressionStatement' &&\n statement.expression.type === 'CallExpression' &&\n t.isIdentifier(statement.expression.callee, { name: local })\n ) {\n return statement.expression;\n }\n }\n return undefined;\n}\n\n/**\n * Whether the initializeGT options pass a loader: false for the config alone,\n * undefined when the options hide it (other spreads, variables, computed keys).\n * Callers report a mismatch only when this is certain.\n */\nexport function passesLoader(\n file: SourceFile,\n options: t.Node | undefined,\n { appDirectory, configFilepath }: BuildToolContext\n): boolean | undefined {\n const configPath = path.resolve(appDirectory, configFilepath);\n const fileDirectory = path.dirname(path.join(appDirectory, file.path));\n const configBinding = file.statements\n ?.filter((statement) => statement.type === 'ImportDeclaration')\n .find(\n (statement) =>\n path.resolve(fileDirectory, statement.source.value) === configPath\n )\n ?.specifiers.find(\n (specifier) => specifier.type === 'ImportDefaultSpecifier'\n )?.local.name;\n const isConfig = (node: t.Node) =>\n node.type === 'Identifier' && node.name === configBinding;\n if (!options) return undefined;\n if (isConfig(options)) return false;\n if (options.type !== 'ObjectExpression') return undefined;\n let loader = false;\n for (const property of options.properties) {\n if (property.type === 'SpreadElement') {\n if (!isConfig(property.argument)) return undefined;\n continue;\n }\n const name = getPropertyName(property);\n if (name === undefined) return undefined;\n if (name === 'loadTranslations') loader = true;\n }\n return loader;\n}\n\n/**\n * The change an initializeGT call needs when translations moved between local\n * files and the CDN since setup ran. Callers quote the call and loader import\n * they would write.\n */\nexport function getStorageChangeAction(\n file: SourceFile,\n { translationsDir }: Pick<BuildToolContext, 'translationsDir'>,\n loaderPassed: boolean,\n {\n call,\n loaderImport,\n docsUrl,\n }: { call: string; loaderImport?: string; docsUrl: string }\n): ManualAction {\n return {\n whatHappened: `${file.path} initializes GT for ${loaderPassed ? 'local translation files' : 'CDN translations'}, but translations are now ${translationsDir ? `stored in ${translationsDir}` : 'loaded from the CDN'}`,\n fix: `Change the initializeGT call in ${file.path} to ${call}${loaderImport ? ` and add ${loaderImport}` : ' and remove the loadTranslations import'} (see ${docsUrl})`,\n };\n}\n"],"mappings":";;;;;AAQA,SAAgB,mBACd,MACA,QAC8B;CAC9B,MAAM,QAAQ,eAAe,MAAM,gBAAgB,OAAO;AAC1D,KAAI,CAAC,MAAO,QAAO,KAAA;AACnB,MAAK,MAAM,aAAa,KAAK,cAAc,EAAE,CAC3C,KACE,UAAU,SAAS,yBACnB,UAAU,WAAW,SAAS,oBAC9B,EAAE,aAAa,UAAU,WAAW,QAAQ,EAAE,MAAM,OAAO,CAAC,CAE5D,QAAO,UAAU;;;;;;;AAWvB,SAAgB,aACd,MACA,SACA,EAAE,cAAc,kBACK;CACrB,MAAM,aAAa,KAAK,QAAQ,cAAc,eAAe;CAC7D,MAAM,gBAAgB,KAAK,QAAQ,KAAK,KAAK,cAAc,KAAK,KAAK,CAAC;CACtE,MAAM,gBAAgB,KAAK,YACvB,QAAQ,cAAc,UAAU,SAAS,oBAAoB,CAC9D,MACE,cACC,KAAK,QAAQ,eAAe,UAAU,OAAO,MAAM,KAAK,WAC3D,EACC,WAAW,MACV,cAAc,UAAU,SAAS,yBACnC,EAAE,MAAM;CACX,MAAM,YAAY,SAChB,KAAK,SAAS,gBAAgB,KAAK,SAAS;AAC9C,KAAI,CAAC,QAAS,QAAO,KAAA;AACrB,KAAI,SAAS,QAAQ,CAAE,QAAO;AAC9B,KAAI,QAAQ,SAAS,mBAAoB,QAAO,KAAA;CAChD,IAAI,SAAS;AACb,MAAK,MAAM,YAAY,QAAQ,YAAY;AACzC,MAAI,SAAS,SAAS,iBAAiB;AACrC,OAAI,CAAC,SAAS,SAAS,SAAS,CAAE,QAAO,KAAA;AACzC;;EAEF,MAAM,OAAO,gBAAgB,SAAS;AACtC,MAAI,SAAS,KAAA,EAAW,QAAO,KAAA;AAC/B,MAAI,SAAS,mBAAoB,UAAS;;AAE5C,QAAO;;;;;;;AAQT,SAAgB,uBACd,MACA,EAAE,mBACF,cACA,EACE,MACA,cACA,WAEY;AACd,QAAO;EACL,cAAc,GAAG,KAAK,KAAK,sBAAsB,eAAe,4BAA4B,mBAAmB,6BAA6B,kBAAkB,aAAa,oBAAoB;EAC/L,KAAK,mCAAmC,KAAK,KAAK,MAAM,OAAO,eAAe,YAAY,iBAAiB,0CAA0C,QAAQ,QAAQ;EACtK"}
@@ -0,0 +1,6 @@
1
+ import type { ViteLoaderExport } from '../../setupViteSPA.js';
2
+ import type { ManualAction } from '../index.js';
3
+ /** A loader left unchanged may not read the newly chosen directory. */
4
+ export declare function getLoaderUpdateActions(loaderFile: string, translationsDir: string, previousTranslationsDir: string | undefined, custom: boolean): ManualAction[];
5
+ /** A custom loader setup preserved, which needs an export initializeGT can pass. */
6
+ export declare function getCustomLoaderAction(loaderFile: string, translationsDir: string, loaderExport: ViteLoaderExport): ManualAction;
@@ -0,0 +1,24 @@
1
+ //#region src/setup/buildTools/shared/loader.ts
2
+ /** A loader left unchanged may not read the newly chosen directory. */
3
+ function getLoaderUpdateActions(loaderFile, translationsDir, previousTranslationsDir, custom) {
4
+ if (translationsDir === previousTranslationsDir) return [];
5
+ const fix = `Update ${custom ? "your custom " : ""}${loaderFile} to load translations from ${translationsDir}`;
6
+ return [{
7
+ whatHappened: custom ? `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}` : `${loaderFile} was left unchanged because the React setup was skipped, but translations now go to ${translationsDir}`,
8
+ fix
9
+ }];
10
+ }
11
+ /** A custom loader setup preserved, which needs an export initializeGT can pass. */
12
+ function getCustomLoaderAction(loaderFile, translationsDir, loaderExport) {
13
+ return loaderExport ? {
14
+ whatHappened: `Your custom ${loaderFile} was preserved`,
15
+ fix: `Verify ${loaderFile} loads translations from ${translationsDir}`
16
+ } : {
17
+ whatHappened: `Your custom ${loaderFile} has no runtime loadTranslations export`,
18
+ fix: `Export a default or named loadTranslations function from ${loaderFile} that loads translations from ${translationsDir}, then rerun gt init`
19
+ };
20
+ }
21
+ //#endregion
22
+ export { getCustomLoaderAction, getLoaderUpdateActions };
23
+
24
+ //# sourceMappingURL=loader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader.js","names":[],"sources":["../../../../src/setup/buildTools/shared/loader.ts"],"sourcesContent":["import type { ViteLoaderExport } from '../../setupViteSPA.js';\nimport type { ManualAction } from '../index.js';\n\n/** A loader left unchanged may not read the newly chosen directory. */\nexport function getLoaderUpdateActions(\n loaderFile: string,\n translationsDir: string,\n previousTranslationsDir: string | undefined,\n custom: boolean\n): ManualAction[] {\n if (translationsDir === previousTranslationsDir) return [];\n const fix = `Update ${custom ? 'your custom ' : ''}${loaderFile} to load translations from ${translationsDir}`;\n return [\n {\n whatHappened: custom\n ? `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}`\n : `${loaderFile} was left unchanged because the React setup was skipped, but translations now go to ${translationsDir}`,\n fix,\n },\n ];\n}\n\n/** A custom loader setup preserved, which needs an export initializeGT can pass. */\nexport function getCustomLoaderAction(\n loaderFile: string,\n translationsDir: string,\n loaderExport: ViteLoaderExport\n): ManualAction {\n return loaderExport\n ? {\n whatHappened: `Your custom ${loaderFile} was preserved`,\n fix: `Verify ${loaderFile} loads translations from ${translationsDir}`,\n }\n : {\n whatHappened: `Your custom ${loaderFile} has no runtime loadTranslations export`,\n fix: `Export a default or named loadTranslations function from ${loaderFile} that loads translations from ${translationsDir}, then rerun gt init`,\n };\n}\n"],"mappings":";;AAIA,SAAgB,uBACd,YACA,iBACA,yBACA,QACgB;AAChB,KAAI,oBAAoB,wBAAyB,QAAO,EAAE;CAC1D,MAAM,MAAM,UAAU,SAAS,iBAAiB,KAAK,WAAW,6BAA6B;AAC7F,QAAO,CACL;EACE,cAAc,SACV,eAAe,WAAW,kDAAkD,oBAC5E,GAAG,WAAW,sFAAsF;EACxG;EACD,CACF;;;AAIH,SAAgB,sBACd,YACA,iBACA,cACc;AACd,QAAO,eACH;EACE,cAAc,eAAe,WAAW;EACxC,KAAK,UAAU,WAAW,2BAA2B;EACtD,GACD;EACE,cAAc,eAAe,WAAW;EACxC,KAAK,4DAA4D,WAAW,gCAAgC,gBAAgB;EAC7H"}
@@ -6,7 +6,33 @@ export type SourceFile = {
6
6
  /** Undefined when the file cannot be parsed. */
7
7
  statements?: t.Statement[];
8
8
  };
9
- export declare function readSourceFile(appDirectory: string, basename: string): Promise<SourceFile | undefined>;
10
- /** The local name `name` is imported as from `source`. */
11
- export declare function getLocalImport(file: SourceFile, name: string, source: string): string | undefined;
9
+ export declare function readSourceFile(appDirectory: string, basename: string, { extensions }?: {
10
+ extensions?: string[];
11
+ }): Promise<SourceFile | undefined>;
12
+ /**
13
+ * The local name `name` is imported as from `source`. With `types`, type-only
14
+ * imports count too.
15
+ */
16
+ export declare function getLocalImport(file: SourceFile, name: string, source: string, { types }?: {
17
+ types?: boolean;
18
+ }): string | undefined;
19
+ /**
20
+ * Whether code uses a name as an identifier: a binding, a reference, or a
21
+ * property name such as `obj.name` or `{ name: 1 }`. Deliberately broad, since
22
+ * a false match only sends setup to manual steps. Strings, comments, JSX
23
+ * attributes and JSX element names are not identifiers, so they do not count.
24
+ */
25
+ export declare function usesName(nodes: t.Node[], names: string[]): boolean;
26
+ export type DeclaredFunction = {
27
+ /** The statement that declares it, which may be an export. */
28
+ statement: t.Statement;
29
+ fn: t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression;
30
+ };
31
+ /**
32
+ * The `function name` or `const name = () => ...` a module declares, with the
33
+ * statement declaring it. With `exported`, only an exported one counts.
34
+ */
35
+ export declare function findDeclaredFunction(statements: t.Statement[], name: string, { exported }?: {
36
+ exported?: boolean;
37
+ }): DeclaredFunction | undefined;
12
38
  export declare function getPropertyName(property: t.ObjectExpression['properties'][number]): string | undefined;
@@ -9,8 +9,8 @@ const SOURCE_EXTENSIONS = [
9
9
  ".jsx",
10
10
  ".js"
11
11
  ];
12
- async function readSourceFile(appDirectory, basename) {
13
- for (const extension of SOURCE_EXTENSIONS) {
12
+ async function readSourceFile(appDirectory, basename, { extensions = SOURCE_EXTENSIONS } = {}) {
13
+ for (const extension of extensions) {
14
14
  const relativePath = `${basename}${extension}`;
15
15
  const absolutePath = path.join(appDirectory, relativePath);
16
16
  if (!fs.existsSync(absolutePath)) continue;
@@ -22,11 +22,48 @@ async function readSourceFile(appDirectory, basename) {
22
22
  };
23
23
  }
24
24
  }
25
- /** The local name `name` is imported as from `source`. */
26
- function getLocalImport(file, name, source) {
25
+ /**
26
+ * The local name `name` is imported as from `source`. With `types`, type-only
27
+ * imports count too.
28
+ */
29
+ function getLocalImport(file, name, source, { types = false } = {}) {
27
30
  for (const statement of file.statements ?? []) {
28
- if (statement.type !== "ImportDeclaration" || statement.source.value !== source || statement.importKind === "type") continue;
29
- for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && t.isIdentifier(specifier.imported, { name })) return specifier.local.name;
31
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== source || !types && statement.importKind === "type") continue;
32
+ for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && (types || specifier.importKind !== "type") && t.isIdentifier(specifier.imported, { name })) return specifier.local.name;
33
+ }
34
+ }
35
+ /**
36
+ * Whether code uses a name as an identifier: a binding, a reference, or a
37
+ * property name such as `obj.name` or `{ name: 1 }`. Deliberately broad, since
38
+ * a false match only sends setup to manual steps. Strings, comments, JSX
39
+ * attributes and JSX element names are not identifiers, so they do not count.
40
+ */
41
+ function usesName(nodes, names) {
42
+ let used = false;
43
+ for (const node of nodes) t.traverseFast(node, (child) => {
44
+ if (child.type === "Identifier" && names.includes(child.name)) used = true;
45
+ });
46
+ return used;
47
+ }
48
+ /**
49
+ * The `function name` or `const name = () => ...` a module declares, with the
50
+ * statement declaring it. With `exported`, only an exported one counts.
51
+ */
52
+ function findDeclaredFunction(statements, name, { exported = false } = {}) {
53
+ for (const statement of statements) {
54
+ const isExport = statement.type === "ExportNamedDeclaration";
55
+ if (exported && !isExport) continue;
56
+ const declaration = isExport ? statement.declaration : statement;
57
+ if (declaration?.type === "FunctionDeclaration" && declaration.id?.name === name) return {
58
+ statement,
59
+ fn: declaration
60
+ };
61
+ if (declaration?.type !== "VariableDeclaration") continue;
62
+ if (declaration.kind !== "const") continue;
63
+ for (const declarator of declaration.declarations) if (t.isIdentifier(declarator.id, { name }) && (declarator.init?.type === "ArrowFunctionExpression" || declarator.init?.type === "FunctionExpression")) return {
64
+ statement,
65
+ fn: declarator.init
66
+ };
30
67
  }
31
68
  }
32
69
  function getPropertyName(property) {
@@ -35,6 +72,6 @@ function getPropertyName(property) {
35
72
  if (property.key.type === "StringLiteral") return property.key.value;
36
73
  }
37
74
  //#endregion
38
- export { getLocalImport, getPropertyName, readSourceFile };
75
+ export { findDeclaredFunction, getLocalImport, getPropertyName, readSourceFile, usesName };
39
76
 
40
77
  //# sourceMappingURL=source.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"source.js","names":[],"sources":["../../../../src/setup/buildTools/shared/source.ts"],"sourcesContent":["// Source-file reading and AST lookups shared by framework setups.\nimport * as t from '@babel/types';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { parseModule } from '../../setupViteSPA.js';\n\n// Frameworks resolve entries by basename, so any of these may be the entry.\nconst SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];\n\nexport type SourceFile = {\n /** Relative to the app, with forward slashes. */\n path: string;\n content: string;\n /** Undefined when the file cannot be parsed. */\n statements?: t.Statement[];\n};\n\nexport async function readSourceFile(\n appDirectory: string,\n basename: string\n): Promise<SourceFile | undefined> {\n for (const extension of SOURCE_EXTENSIONS) {\n const relativePath = `${basename}${extension}`;\n const absolutePath = path.join(appDirectory, relativePath);\n if (!fs.existsSync(absolutePath)) continue;\n const content = await fs.promises.readFile(absolutePath, 'utf8');\n return {\n path: relativePath,\n content,\n statements: parseModule(content, relativePath),\n };\n }\n return undefined;\n}\n\n/** The local name `name` is imported as from `source`. */\nexport function getLocalImport(\n file: SourceFile,\n name: string,\n source: string\n): string | undefined {\n for (const statement of file.statements ?? []) {\n if (\n statement.type !== 'ImportDeclaration' ||\n statement.source.value !== source ||\n statement.importKind === 'type'\n ) {\n continue;\n }\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === 'ImportSpecifier' &&\n specifier.importKind !== 'type' &&\n t.isIdentifier(specifier.imported, { name })\n ) {\n return specifier.local.name;\n }\n }\n }\n return undefined;\n}\n\nexport function getPropertyName(\n property: t.ObjectExpression['properties'][number]\n): string | undefined {\n if (property.type === 'SpreadElement' || property.computed) return undefined;\n if (property.key.type === 'Identifier') return property.key.name;\n if (property.key.type === 'StringLiteral') return property.key.value;\n return undefined;\n}\n"],"mappings":";;;;;AAOA,MAAM,oBAAoB;CAAC;CAAQ;CAAO;CAAQ;CAAM;AAUxD,eAAsB,eACpB,cACA,UACiC;AACjC,MAAK,MAAM,aAAa,mBAAmB;EACzC,MAAM,eAAe,GAAG,WAAW;EACnC,MAAM,eAAe,KAAK,KAAK,cAAc,aAAa;AAC1D,MAAI,CAAC,GAAG,WAAW,aAAa,CAAE;EAClC,MAAM,UAAU,MAAM,GAAG,SAAS,SAAS,cAAc,OAAO;AAChE,SAAO;GACL,MAAM;GACN;GACA,YAAY,YAAY,SAAS,aAAa;GAC/C;;;;AAML,SAAgB,eACd,MACA,MACA,QACoB;AACpB,MAAK,MAAM,aAAa,KAAK,cAAc,EAAE,EAAE;AAC7C,MACE,UAAU,SAAS,uBACnB,UAAU,OAAO,UAAU,UAC3B,UAAU,eAAe,OAEzB;AAEF,OAAK,MAAM,aAAa,UAAU,WAChC,KACE,UAAU,SAAS,qBACnB,UAAU,eAAe,UACzB,EAAE,aAAa,UAAU,UAAU,EAAE,MAAM,CAAC,CAE5C,QAAO,UAAU,MAAM;;;AAO/B,SAAgB,gBACd,UACoB;AACpB,KAAI,SAAS,SAAS,mBAAmB,SAAS,SAAU,QAAO,KAAA;AACnE,KAAI,SAAS,IAAI,SAAS,aAAc,QAAO,SAAS,IAAI;AAC5D,KAAI,SAAS,IAAI,SAAS,gBAAiB,QAAO,SAAS,IAAI"}
1
+ {"version":3,"file":"source.js","names":[],"sources":["../../../../src/setup/buildTools/shared/source.ts"],"sourcesContent":["// Source-file reading and AST lookups shared by framework setups.\nimport * as t from '@babel/types';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { parseModule } from '../../setupViteSPA.js';\n\n// Frameworks resolve entries by basename, so any of these may be the entry.\nconst SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];\n\nexport type SourceFile = {\n /** Relative to the app, with forward slashes. */\n path: string;\n content: string;\n /** Undefined when the file cannot be parsed. */\n statements?: t.Statement[];\n};\n\nexport async function readSourceFile(\n appDirectory: string,\n basename: string,\n { extensions = SOURCE_EXTENSIONS }: { extensions?: string[] } = {}\n): Promise<SourceFile | undefined> {\n for (const extension of extensions) {\n const relativePath = `${basename}${extension}`;\n const absolutePath = path.join(appDirectory, relativePath);\n if (!fs.existsSync(absolutePath)) continue;\n const content = await fs.promises.readFile(absolutePath, 'utf8');\n return {\n path: relativePath,\n content,\n statements: parseModule(content, relativePath),\n };\n }\n return undefined;\n}\n\n/**\n * The local name `name` is imported as from `source`. With `types`, type-only\n * imports count too.\n */\nexport function getLocalImport(\n file: SourceFile,\n name: string,\n source: string,\n { types = false }: { types?: boolean } = {}\n): string | undefined {\n for (const statement of file.statements ?? []) {\n if (\n statement.type !== 'ImportDeclaration' ||\n statement.source.value !== source ||\n (!types && statement.importKind === 'type')\n ) {\n continue;\n }\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === 'ImportSpecifier' &&\n (types || specifier.importKind !== 'type') &&\n t.isIdentifier(specifier.imported, { name })\n ) {\n return specifier.local.name;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Whether code uses a name as an identifier: a binding, a reference, or a\n * property name such as `obj.name` or `{ name: 1 }`. Deliberately broad, since\n * a false match only sends setup to manual steps. Strings, comments, JSX\n * attributes and JSX element names are not identifiers, so they do not count.\n */\nexport function usesName(nodes: t.Node[], names: string[]): boolean {\n let used = false;\n for (const node of nodes) {\n t.traverseFast(node, (child) => {\n if (child.type === 'Identifier' && names.includes(child.name)) {\n used = true;\n }\n });\n }\n return used;\n}\n\nexport type DeclaredFunction = {\n /** The statement that declares it, which may be an export. */\n statement: t.Statement;\n fn: t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression;\n};\n\n/**\n * The `function name` or `const name = () => ...` a module declares, with the\n * statement declaring it. With `exported`, only an exported one counts.\n */\nexport function findDeclaredFunction(\n statements: t.Statement[],\n name: string,\n { exported = false }: { exported?: boolean } = {}\n): DeclaredFunction | undefined {\n for (const statement of statements) {\n const isExport = statement.type === 'ExportNamedDeclaration';\n if (exported && !isExport) continue;\n const declaration = isExport ? statement.declaration : statement;\n if (\n declaration?.type === 'FunctionDeclaration' &&\n declaration.id?.name === name\n ) {\n return { statement, fn: declaration };\n }\n if (declaration?.type !== 'VariableDeclaration') continue;\n if (declaration.kind !== 'const') continue;\n for (const declarator of declaration.declarations) {\n if (\n t.isIdentifier(declarator.id, { name }) &&\n (declarator.init?.type === 'ArrowFunctionExpression' ||\n declarator.init?.type === 'FunctionExpression')\n ) {\n return { statement, fn: declarator.init };\n }\n }\n }\n return undefined;\n}\n\nexport function getPropertyName(\n property: t.ObjectExpression['properties'][number]\n): string | undefined {\n if (property.type === 'SpreadElement' || property.computed) return undefined;\n if (property.key.type === 'Identifier') return property.key.name;\n if (property.key.type === 'StringLiteral') return property.key.value;\n return undefined;\n}\n"],"mappings":";;;;;AAOA,MAAM,oBAAoB;CAAC;CAAQ;CAAO;CAAQ;CAAM;AAUxD,eAAsB,eACpB,cACA,UACA,EAAE,aAAa,sBAAiD,EAAE,EACjC;AACjC,MAAK,MAAM,aAAa,YAAY;EAClC,MAAM,eAAe,GAAG,WAAW;EACnC,MAAM,eAAe,KAAK,KAAK,cAAc,aAAa;AAC1D,MAAI,CAAC,GAAG,WAAW,aAAa,CAAE;EAClC,MAAM,UAAU,MAAM,GAAG,SAAS,SAAS,cAAc,OAAO;AAChE,SAAO;GACL,MAAM;GACN;GACA,YAAY,YAAY,SAAS,aAAa;GAC/C;;;;;;;AASL,SAAgB,eACd,MACA,MACA,QACA,EAAE,QAAQ,UAA+B,EAAE,EACvB;AACpB,MAAK,MAAM,aAAa,KAAK,cAAc,EAAE,EAAE;AAC7C,MACE,UAAU,SAAS,uBACnB,UAAU,OAAO,UAAU,UAC1B,CAAC,SAAS,UAAU,eAAe,OAEpC;AAEF,OAAK,MAAM,aAAa,UAAU,WAChC,KACE,UAAU,SAAS,sBAClB,SAAS,UAAU,eAAe,WACnC,EAAE,aAAa,UAAU,UAAU,EAAE,MAAM,CAAC,CAE5C,QAAO,UAAU,MAAM;;;;;;;;;AAa/B,SAAgB,SAAS,OAAiB,OAA0B;CAClE,IAAI,OAAO;AACX,MAAK,MAAM,QAAQ,MACjB,GAAE,aAAa,OAAO,UAAU;AAC9B,MAAI,MAAM,SAAS,gBAAgB,MAAM,SAAS,MAAM,KAAK,CAC3D,QAAO;GAET;AAEJ,QAAO;;;;;;AAaT,SAAgB,qBACd,YACA,MACA,EAAE,WAAW,UAAkC,EAAE,EACnB;AAC9B,MAAK,MAAM,aAAa,YAAY;EAClC,MAAM,WAAW,UAAU,SAAS;AACpC,MAAI,YAAY,CAAC,SAAU;EAC3B,MAAM,cAAc,WAAW,UAAU,cAAc;AACvD,MACE,aAAa,SAAS,yBACtB,YAAY,IAAI,SAAS,KAEzB,QAAO;GAAE;GAAW,IAAI;GAAa;AAEvC,MAAI,aAAa,SAAS,sBAAuB;AACjD,MAAI,YAAY,SAAS,QAAS;AAClC,OAAK,MAAM,cAAc,YAAY,aACnC,KACE,EAAE,aAAa,WAAW,IAAI,EAAE,MAAM,CAAC,KACtC,WAAW,MAAM,SAAS,6BACzB,WAAW,MAAM,SAAS,sBAE5B,QAAO;GAAE;GAAW,IAAI,WAAW;GAAM;;;AAOjD,SAAgB,gBACd,UACoB;AACpB,KAAI,SAAS,SAAS,mBAAmB,SAAS,SAAU,QAAO,KAAA;AACnE,KAAI,SAAS,IAAI,SAAS,aAAc,QAAO,SAAS,IAAI;AAC5D,KAAI,SAAS,IAAI,SAAS,gBAAiB,QAAO,SAAS,IAAI"}
@@ -1,13 +1,16 @@
1
1
  import { DEFAULT_VITE_TRANSLATIONS_DIR } from "../../../utils/constants.js";
2
+ import "../../../types/libraries.js";
2
3
  import { getViteLoaderExport, parseModule, writeViteLoader } from "../../setupViteSPA.js";
3
- import { VITE_LOADER_FILE, viteSetup } from "../vite.js";
4
+ import { readSourceFile } from "../shared/source.js";
5
+ import { findInitializeCall, passesLoader } from "../shared/initializeGT.js";
6
+ import { getCustomLoaderAction } from "../shared/loader.js";
4
7
  import { applyEdits, getCodeStyle, getImportEdit } from "../shared/edits.js";
5
8
  import { rendersElement } from "../shared/jsx.js";
6
- import { readSourceFile } from "../shared/source.js";
9
+ import { VITE_LOADER_FILE, viteSetup } from "../vite.js";
7
10
  import { DOCS_URL, inspectTanStackStart } from "./source.js";
8
11
  import { START_CONTENT, getMiddlewareAction, registersMiddleware } from "./middleware.js";
9
12
  import { configureRootRoute, findRootComponent, getRootFix } from "./root.js";
10
- import { findInitializeCall, getRouterLines, getStorageAction, passesLoader } from "./router.js";
13
+ import { getRouterLines, getStorageAction } from "./router.js";
11
14
  import path from "node:path";
12
15
  import fs from "node:fs";
13
16
  //#region src/setup/buildTools/tanstackStart/index.ts
@@ -32,11 +35,19 @@ const tanstackStartSetup = {
32
35
  async preflight(appDirectory) {
33
36
  await inspectTanStackStart(appDirectory);
34
37
  },
38
+ async getCDNStorageAction(ctx) {
39
+ const router = await readSourceFile(ctx.appDirectory, "src/router");
40
+ const initializeCall = router && findInitializeCall(router, "gt-tanstack-start");
41
+ if (!router || !initializeCall) return void 0;
42
+ const loaderPassed = passesLoader(router, initializeCall.arguments[0], ctx);
43
+ if (loaderPassed === void 0) return void 0;
44
+ return loaderPassed ? getStorageAction(router, ctx, void 0, true) : null;
45
+ },
35
46
  async syncLoader(ctx) {
36
47
  const result = await viteSetup.syncLoader(ctx);
37
48
  if (ctx.keepAppSource) return result;
38
49
  const router = await readSourceFile(ctx.appDirectory, "src/router");
39
- const initializeCall = router && findInitializeCall(router);
50
+ const initializeCall = router && findInitializeCall(router, "gt-tanstack-start");
40
51
  if (!initializeCall || passesLoader(router, initializeCall.arguments[0], ctx) !== false) return result;
41
52
  const { loader, steps } = await writeLoader(ctx);
42
53
  const loaderExport = await getViteLoaderExport(ctx.appDirectory, loader);
@@ -61,16 +72,10 @@ const tanstackStartSetup = {
61
72
  });
62
73
  steps.push(...loaderSteps);
63
74
  loaderExport = await getViteLoaderExport(appDirectory, loader);
64
- if (loader === "custom") manualActions.push(loaderExport ? {
65
- whatHappened: `Your custom ${VITE_LOADER_FILE} was preserved`,
66
- fix: `Verify ${VITE_LOADER_FILE} loads translations from ${translationsDir}`
67
- } : {
68
- whatHappened: `Your custom ${VITE_LOADER_FILE} has no runtime loadTranslations export`,
69
- fix: `Export a default or named loadTranslations function from ${VITE_LOADER_FILE} that loads translations from ${translationsDir}, then rerun gt init`
70
- });
75
+ if (loader === "custom") manualActions.push(getCustomLoaderAction(VITE_LOADER_FILE, translationsDir, loaderExport));
71
76
  }
72
77
  const parses = (file, content) => content !== void 0 && parseModule(content, file.path) !== void 0 ? content : void 0;
73
- const initializeCall = findInitializeCall(router);
78
+ const initializeCall = findInitializeCall(router, "gt-tanstack-start");
74
79
  let routerReady = initializeCall !== void 0;
75
80
  let configuredRouter;
76
81
  const wantsLoader = Boolean(translationsDir);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/index.ts"],"sourcesContent":["// TanStack Start setup: configures src/router.tsx, src/start.ts and\n// src/routes/__root.tsx in dependency order, or reports manual steps.\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { DEFAULT_VITE_TRANSLATIONS_DIR } from '../../../utils/constants.js';\nimport {\n getViteLoaderExport,\n parseModule,\n writeViteLoader,\n type ViteLoaderExport,\n type ViteLoaderResult,\n} from '../../setupViteSPA.js';\nimport type {\n BuildToolContext,\n BuildToolSetup,\n ManualAction,\n} from '../index.js';\nimport { VITE_LOADER_FILE, viteSetup } from '../vite.js';\nimport { applyEdits, getCodeStyle, getImportEdit } from '../shared/edits.js';\nimport { rendersElement } from '../shared/jsx.js';\nimport { readSourceFile, type SourceFile } from '../shared/source.js';\nimport {\n getMiddlewareAction,\n registersMiddleware,\n START_CONTENT,\n} from './middleware.js';\nimport { configureRootRoute, findRootComponent, getRootFix } from './root.js';\nimport {\n findInitializeCall,\n getRouterLines,\n getStorageAction,\n passesLoader,\n} from './router.js';\nimport { DOCS_URL, inspectTanStackStart } from './source.js';\n\nasync function writeLoader(\n ctx: BuildToolContext & { translationsDir: string }\n): Promise<{ loader: ViteLoaderResult; steps: string[] }> {\n const loader = await writeViteLoader({ ...ctx, create: true });\n const changed = loader === 'created' || loader === 'updated';\n return { loader, steps: changed ? [`${loader} ${VITE_LOADER_FILE}`] : [] };\n}\n\nexport const tanstackStartSetup: BuildToolSetup = {\n framework: 'tanstack-start',\n defaultTranslationsDir: DEFAULT_VITE_TRANSLATIONS_DIR,\n initializer: 'initializeGT',\n ownsLoader: true,\n skipsGTInstall: () => false,\n devCredentialsOption: '--live-translations',\n docsUrl: DOCS_URL,\n async preflight(appDirectory) {\n await inspectTanStackStart(appDirectory);\n },\n // The loader is the same file Vite generates, but a router that loads from\n // the CDN also needs the loader passed to initializeGT.\n async syncLoader(ctx) {\n const result = await viteSetup.syncLoader(ctx);\n if (ctx.keepAppSource) return result;\n const router = await readSourceFile(ctx.appDirectory, 'src/router');\n const initializeCall = router && findInitializeCall(router);\n if (\n !initializeCall ||\n passesLoader(router, initializeCall.arguments[0], ctx) !== false\n ) {\n return result;\n }\n const { loader, steps } = await writeLoader(ctx);\n const loaderExport = await getViteLoaderExport(ctx.appDirectory, loader);\n return {\n steps: [...result.steps, ...steps],\n manualActions: loaderExport\n ? [\n ...result.manualActions,\n getStorageAction(router, ctx, loaderExport, false),\n ]\n : result.manualActions,\n };\n },\n async apply(ctx) {\n const { appDirectory, translationsDir } = ctx;\n const { router, root, start } = await inspectTanStackStart(appDirectory);\n const steps: string[] = [];\n const manualActions: ManualAction[] = [];\n const writeSource = async (file: string, content: string) => {\n await fs.promises.writeFile(path.join(appDirectory, file), content);\n };\n\n let loaderExport: ViteLoaderExport;\n if (translationsDir) {\n const { loader, steps: loaderSteps } = await writeLoader({\n ...ctx,\n translationsDir,\n });\n steps.push(...loaderSteps);\n loaderExport = await getViteLoaderExport(appDirectory, loader);\n if (loader === 'custom') {\n manualActions.push(\n loaderExport\n ? {\n whatHappened: `Your custom ${VITE_LOADER_FILE} was preserved`,\n fix: `Verify ${VITE_LOADER_FILE} loads translations from ${translationsDir}`,\n }\n : {\n whatHappened: `Your custom ${VITE_LOADER_FILE} has no runtime loadTranslations export`,\n fix: `Export a default or named loadTranslations function from ${VITE_LOADER_FILE} that loads translations from ${translationsDir}, then rerun gt init`,\n }\n );\n }\n }\n\n // An insertion that breaks the file's syntax falls back to manual setup.\n const parses = (file: SourceFile, content: string | undefined) =>\n content !== undefined && parseModule(content, file.path) !== undefined\n ? content\n : undefined;\n\n const initializeCall = findInitializeCall(router);\n let routerReady = initializeCall !== undefined;\n let configuredRouter: string | undefined;\n // Storage chosen on a rerun must match how the router loads translations.\n const wantsLoader = Boolean(translationsDir);\n const loaderPassed = passesLoader(\n router,\n initializeCall?.arguments[0],\n ctx\n );\n if (\n loaderPassed !== undefined &&\n loaderPassed !== wantsLoader &&\n (!translationsDir || loaderExport)\n ) {\n manualActions.push(\n getStorageAction(router, ctx, loaderExport, loaderPassed)\n );\n }\n // A custom loader without an export already has its own action.\n if (!routerReady && (!translationsDir || loaderExport)) {\n // Any other mention may be an app-owned initializer; a second\n // initializeGT call would override it.\n if (router.statements && !/\\binitializeGT\\b/.test(router.content)) {\n const style = getCodeStyle(router.content, router.statements);\n configuredRouter = parses(\n router,\n applyEdits(router.content, [\n getImportEdit(\n router.statements,\n getRouterLines(router, ctx, loaderExport, style),\n style.eol\n ),\n ])\n );\n }\n routerReady = configuredRouter !== undefined;\n if (!routerReady) {\n const lines = getRouterLines(router, ctx, loaderExport, {\n quote: \"'\",\n semi: ';',\n });\n manualActions.push({\n whatHappened: `${router.path} was not configured automatically`,\n fix: `Initialize GT after the imports in ${router.path}: ${lines.filter(Boolean).join(' ')}, then rerun gt init (see ${DOCS_URL})`,\n });\n }\n }\n\n const startReady = !start || registersMiddleware(start);\n if (!startReady) {\n manualActions.push(getMiddlewareAction(start!.path));\n }\n\n const rootComponent = root.statements && findRootComponent(root.statements);\n const rootConfigured = rendersElement(\n [rootComponent?.component, rootComponent?.document],\n 'GTProvider'\n );\n // A provider elsewhere may wrap the document indirectly; adding a second\n // one could nest them, so a person decides.\n const providerElsewhere =\n !rootConfigured && rendersElement(root.statements ?? [], 'GTProvider');\n const configuredRoot =\n rootConfigured || providerElsewhere\n ? undefined\n : parses(root, configureRootRoute(root));\n if (!rootConfigured && !configuredRoot) {\n manualActions.push({\n whatHappened: providerElsewhere\n ? `${root.path} renders GTProvider outside the root route's document`\n : `${root.path} does not match the create-start root route`,\n fix: getRootFix(root.path),\n });\n }\n\n // gtMiddleware and the root loader need initializeGT to have run, so\n // they are only added alongside a router that calls it; the actions\n // above ask for a rerun to finish.\n if (routerReady) {\n if (!start) {\n await writeSource('src/start.ts', START_CONTENT);\n steps.push('created src/start.ts');\n }\n if (configuredRouter) {\n await writeSource(router.path, configuredRouter);\n steps.push(`configured ${router.path}`);\n }\n // The root loader reads the request scope gtMiddleware sets up, so\n // without it every page would fail to render.\n if (configuredRoot && startReady) {\n await writeSource(root.path, configuredRoot);\n steps.push(`configured ${root.path}`);\n }\n }\n\n return { steps, manualActions };\n },\n};\n"],"mappings":";;;;;;;;;;;;;AAmCA,eAAe,YACb,KACwD;CACxD,MAAM,SAAS,MAAM,gBAAgB;EAAE,GAAG;EAAK,QAAQ;EAAM,CAAC;AAE9D,QAAO;EAAE;EAAQ,OADD,WAAW,aAAa,WAAW,YACjB,CAAC,GAAG,OAAO,GAAG,mBAAmB,GAAG,EAAE;EAAE;;AAG5E,MAAa,qBAAqC;CAChD,WAAW;CACX,wBAAwB;CACxB,aAAa;CACb,YAAY;CACZ,sBAAsB;CACtB,sBAAsB;CACtB,SAAS;CACT,MAAM,UAAU,cAAc;AAC5B,QAAM,qBAAqB,aAAa;;CAI1C,MAAM,WAAW,KAAK;EACpB,MAAM,SAAS,MAAM,UAAU,WAAW,IAAI;AAC9C,MAAI,IAAI,cAAe,QAAO;EAC9B,MAAM,SAAS,MAAM,eAAe,IAAI,cAAc,aAAa;EACnE,MAAM,iBAAiB,UAAU,mBAAmB,OAAO;AAC3D,MACE,CAAC,kBACD,aAAa,QAAQ,eAAe,UAAU,IAAI,IAAI,KAAK,MAE3D,QAAO;EAET,MAAM,EAAE,QAAQ,UAAU,MAAM,YAAY,IAAI;EAChD,MAAM,eAAe,MAAM,oBAAoB,IAAI,cAAc,OAAO;AACxE,SAAO;GACL,OAAO,CAAC,GAAG,OAAO,OAAO,GAAG,MAAM;GAClC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kBAAkB,YAAY;AAChC,UAAM,YAAY,KAAK,MAAM,eAAe;AAC5C,UAAM,KAAK,cAAc,KAAK,OAAO;;;AAIzC,SAAO;GAAE;GAAO;GAAe;;CAElC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/index.ts"],"sourcesContent":["// TanStack Start setup: configures src/router.tsx, src/start.ts and\n// src/routes/__root.tsx in dependency order, or reports manual steps.\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Libraries } from '../../../types/libraries.js';\nimport { DEFAULT_VITE_TRANSLATIONS_DIR } from '../../../utils/constants.js';\nimport {\n getViteLoaderExport,\n parseModule,\n writeViteLoader,\n type ViteLoaderExport,\n type ViteLoaderResult,\n} from '../../setupViteSPA.js';\nimport type {\n BuildToolContext,\n BuildToolSetup,\n ManualAction,\n} from '../index.js';\nimport { VITE_LOADER_FILE, viteSetup } from '../vite.js';\nimport { applyEdits, getCodeStyle, getImportEdit } from '../shared/edits.js';\nimport { findInitializeCall, passesLoader } from '../shared/initializeGT.js';\nimport { rendersElement } from '../shared/jsx.js';\nimport { getCustomLoaderAction } from '../shared/loader.js';\nimport { readSourceFile, type SourceFile } from '../shared/source.js';\nimport {\n getMiddlewareAction,\n registersMiddleware,\n START_CONTENT,\n} from './middleware.js';\nimport { configureRootRoute, findRootComponent, getRootFix } from './root.js';\nimport { getRouterLines, getStorageAction } from './router.js';\nimport { DOCS_URL, inspectTanStackStart } from './source.js';\n\nasync function writeLoader(\n ctx: BuildToolContext & { translationsDir: string }\n): Promise<{ loader: ViteLoaderResult; steps: string[] }> {\n const loader = await writeViteLoader({ ...ctx, create: true });\n const changed = loader === 'created' || loader === 'updated';\n return { loader, steps: changed ? [`${loader} ${VITE_LOADER_FILE}`] : [] };\n}\n\nexport const tanstackStartSetup: BuildToolSetup = {\n framework: 'tanstack-start',\n defaultTranslationsDir: DEFAULT_VITE_TRANSLATIONS_DIR,\n initializer: 'initializeGT',\n ownsLoader: true,\n skipsGTInstall: () => false,\n devCredentialsOption: '--live-translations',\n docsUrl: DOCS_URL,\n async preflight(appDirectory) {\n await inspectTanStackStart(appDirectory);\n },\n async getCDNStorageAction(ctx) {\n const router = await readSourceFile(ctx.appDirectory, 'src/router');\n const initializeCall =\n router && findInitializeCall(router, Libraries.GT_TANSTACK_START);\n if (!router || !initializeCall) return undefined;\n const loaderPassed = passesLoader(router, initializeCall.arguments[0], ctx);\n if (loaderPassed === undefined) return undefined;\n return loaderPassed ? getStorageAction(router, ctx, undefined, true) : null;\n },\n // The loader is the same file Vite generates, but a router that loads from\n // the CDN also needs the loader passed to initializeGT.\n async syncLoader(ctx) {\n const result = await viteSetup.syncLoader(ctx);\n if (ctx.keepAppSource) return result;\n const router = await readSourceFile(ctx.appDirectory, 'src/router');\n const initializeCall =\n router && findInitializeCall(router, Libraries.GT_TANSTACK_START);\n if (\n !initializeCall ||\n passesLoader(router, initializeCall.arguments[0], ctx) !== false\n ) {\n return result;\n }\n const { loader, steps } = await writeLoader(ctx);\n const loaderExport = await getViteLoaderExport(ctx.appDirectory, loader);\n return {\n steps: [...result.steps, ...steps],\n manualActions: loaderExport\n ? [\n ...result.manualActions,\n getStorageAction(router, ctx, loaderExport, false),\n ]\n : result.manualActions,\n };\n },\n async apply(ctx) {\n const { appDirectory, translationsDir } = ctx;\n const { router, root, start } = await inspectTanStackStart(appDirectory);\n const steps: string[] = [];\n const manualActions: ManualAction[] = [];\n const writeSource = async (file: string, content: string) => {\n await fs.promises.writeFile(path.join(appDirectory, file), content);\n };\n\n let loaderExport: ViteLoaderExport;\n if (translationsDir) {\n const { loader, steps: loaderSteps } = await writeLoader({\n ...ctx,\n translationsDir,\n });\n steps.push(...loaderSteps);\n loaderExport = await getViteLoaderExport(appDirectory, loader);\n if (loader === 'custom') {\n manualActions.push(\n getCustomLoaderAction(VITE_LOADER_FILE, translationsDir, loaderExport)\n );\n }\n }\n\n // An insertion that breaks the file's syntax falls back to manual setup.\n const parses = (file: SourceFile, content: string | undefined) =>\n content !== undefined && parseModule(content, file.path) !== undefined\n ? content\n : undefined;\n\n const initializeCall = findInitializeCall(\n router,\n Libraries.GT_TANSTACK_START\n );\n let routerReady = initializeCall !== undefined;\n let configuredRouter: string | undefined;\n // Storage chosen on a rerun must match how the router loads translations.\n const wantsLoader = Boolean(translationsDir);\n const loaderPassed = passesLoader(\n router,\n initializeCall?.arguments[0],\n ctx\n );\n if (\n loaderPassed !== undefined &&\n loaderPassed !== wantsLoader &&\n (!translationsDir || loaderExport)\n ) {\n manualActions.push(\n getStorageAction(router, ctx, loaderExport, loaderPassed)\n );\n }\n // A custom loader without an export already has its own action.\n if (!routerReady && (!translationsDir || loaderExport)) {\n // Any other mention may be an app-owned initializer; a second\n // initializeGT call would override it.\n if (router.statements && !/\\binitializeGT\\b/.test(router.content)) {\n const style = getCodeStyle(router.content, router.statements);\n configuredRouter = parses(\n router,\n applyEdits(router.content, [\n getImportEdit(\n router.statements,\n getRouterLines(router, ctx, loaderExport, style),\n style.eol\n ),\n ])\n );\n }\n routerReady = configuredRouter !== undefined;\n if (!routerReady) {\n const lines = getRouterLines(router, ctx, loaderExport, {\n quote: \"'\",\n semi: ';',\n });\n manualActions.push({\n whatHappened: `${router.path} was not configured automatically`,\n fix: `Initialize GT after the imports in ${router.path}: ${lines.filter(Boolean).join(' ')}, then rerun gt init (see ${DOCS_URL})`,\n });\n }\n }\n\n const startReady = !start || registersMiddleware(start);\n if (!startReady) {\n manualActions.push(getMiddlewareAction(start!.path));\n }\n\n const rootComponent = root.statements && findRootComponent(root.statements);\n const rootConfigured = rendersElement(\n [rootComponent?.component, rootComponent?.document],\n 'GTProvider'\n );\n // A provider elsewhere may wrap the document indirectly; adding a second\n // one could nest them, so a person decides.\n const providerElsewhere =\n !rootConfigured && rendersElement(root.statements ?? [], 'GTProvider');\n const configuredRoot =\n rootConfigured || providerElsewhere\n ? undefined\n : parses(root, configureRootRoute(root));\n if (!rootConfigured && !configuredRoot) {\n manualActions.push({\n whatHappened: providerElsewhere\n ? `${root.path} renders GTProvider outside the root route's document`\n : `${root.path} does not match the create-start root route`,\n fix: getRootFix(root.path),\n });\n }\n\n // gtMiddleware and the root loader need initializeGT to have run, so\n // they are only added alongside a router that calls it; the actions\n // above ask for a rerun to finish.\n if (routerReady) {\n if (!start) {\n await writeSource('src/start.ts', START_CONTENT);\n steps.push('created src/start.ts');\n }\n if (configuredRouter) {\n await writeSource(router.path, configuredRouter);\n steps.push(`configured ${router.path}`);\n }\n // The root loader reads the request scope gtMiddleware sets up, so\n // without it every page would fail to render.\n if (configuredRoot && startReady) {\n await writeSource(root.path, configuredRoot);\n steps.push(`configured ${root.path}`);\n }\n }\n\n return { steps, manualActions };\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAiCA,eAAe,YACb,KACwD;CACxD,MAAM,SAAS,MAAM,gBAAgB;EAAE,GAAG;EAAK,QAAQ;EAAM,CAAC;AAE9D,QAAO;EAAE;EAAQ,OADD,WAAW,aAAa,WAAW,YACjB,CAAC,GAAG,OAAO,GAAG,mBAAmB,GAAG,EAAE;EAAE;;AAG5E,MAAa,qBAAqC;CAChD,WAAW;CACX,wBAAwB;CACxB,aAAa;CACb,YAAY;CACZ,sBAAsB;CACtB,sBAAsB;CACtB,SAAS;CACT,MAAM,UAAU,cAAc;AAC5B,QAAM,qBAAqB,aAAa;;CAE1C,MAAM,oBAAoB,KAAK;EAC7B,MAAM,SAAS,MAAM,eAAe,IAAI,cAAc,aAAa;EACnE,MAAM,iBACJ,UAAU,mBAAmB,QAAA,oBAAoC;AACnE,MAAI,CAAC,UAAU,CAAC,eAAgB,QAAO,KAAA;EACvC,MAAM,eAAe,aAAa,QAAQ,eAAe,UAAU,IAAI,IAAI;AAC3E,MAAI,iBAAiB,KAAA,EAAW,QAAO,KAAA;AACvC,SAAO,eAAe,iBAAiB,QAAQ,KAAK,KAAA,GAAW,KAAK,GAAG;;CAIzE,MAAM,WAAW,KAAK;EACpB,MAAM,SAAS,MAAM,UAAU,WAAW,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;GACjB,KAAK,WAAW,KAAK,KAAK;GAC3B,CAAC;AAMJ,MAAI,aAAa;AACf,OAAI,CAAC,OAAO;AACV,UAAM,YAAY,gBAAgB,cAAc;AAChD,UAAM,KAAK,uBAAuB;;AAEpC,OAAI,kBAAkB;AACpB,UAAM,YAAY,OAAO,MAAM,iBAAiB;AAChD,UAAM,KAAK,cAAc,OAAO,OAAO;;AAIzC,OAAI,kBAAkB,YAAY;AAChC,UAAM,YAAY,KAAK,MAAM,eAAe;AAC5C,UAAM,KAAK,cAAc,KAAK,OAAO;;;AAIzC,SAAO;GAAE;GAAO;GAAe;;CAElC"}
@@ -1,7 +1,5 @@
1
1
  import * as t from '@babel/types';
2
2
  import { type SourceFile } from '../shared/source.js';
3
- declare function findLocalFunction(statements: t.Statement[], name: string): t.ArrowFunctionExpression | t.FunctionDeclaration | t.FunctionExpression | undefined;
4
- type LocalFunction = NonNullable<ReturnType<typeof findLocalFunction>>;
5
3
  /**
6
4
  * The root route, the local function its shellComponent or component names,
7
5
  * and the local function that renders its document.
@@ -14,7 +12,7 @@ export declare function findRootComponent(statements: t.Statement[]): {
14
12
  componentProperty: t.ObjectMethod | t.ObjectProperty | t.SpreadElement | undefined;
15
13
  component: t.ArrowFunctionExpression | t.FunctionDeclaration | t.FunctionExpression | undefined;
16
14
  isShell: boolean;
17
- document: LocalFunction | undefined;
15
+ document: t.ArrowFunctionExpression | t.FunctionDeclaration | t.FunctionExpression | undefined;
18
16
  } | undefined;
19
17
  /**
20
18
  * Configures the create-start root route: `createRootRoute({...})` (or its
@@ -26,4 +24,3 @@ export declare function findRootComponent(statements: t.Statement[]): {
26
24
  */
27
25
  export declare function configureRootRoute({ content, statements, }: SourceFile): string | undefined;
28
26
  export declare function getRootFix(rootPath: string): string;
29
- export {};
@@ -1,18 +1,15 @@
1
1
  import "../../../types/libraries.js";
2
+ import { findDeclaredFunction, getPropertyName, usesName } from "../shared/source.js";
2
3
  import { applyEdits, getCodeStyle, getImportEdit, getLineIndent, getOwnLineIndent } from "../shared/edits.js";
3
4
  import { isChildrenSlot, isJsxElementNamed, rendersElement } from "../shared/jsx.js";
4
- import { getPropertyName } from "../shared/source.js";
5
+ import { LOADER_TRANSLATIONS, findHtmlDocument, getLangEdit, getWrapEdit } from "../shared/document.js";
5
6
  import { DOCS_URL } from "./source.js";
6
7
  import * as t from "@babel/types";
7
8
  //#region src/setup/buildTools/tanstackStart/root.ts
9
+ /** The provider the document is wrapped in, reading the root loader's data. */
10
+ const PROVIDER_TAG = "<GTProvider locale={locale} translations={translations}>";
8
11
  function findLocalFunction(statements, name) {
9
- for (const statement of statements) {
10
- const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
11
- if (declaration?.type === "FunctionDeclaration" && declaration.id?.name === name) return declaration;
12
- if (declaration?.type !== "VariableDeclaration") continue;
13
- if (declaration.kind !== "const") continue;
14
- for (const declarator of declaration.declarations) if (t.isIdentifier(declarator.id, { name }) && (declarator.init?.type === "ArrowFunctionExpression" || declarator.init?.type === "FunctionExpression")) return declarator.init;
15
- }
12
+ return findDeclaredFunction(statements, name)?.fn;
16
13
  }
17
14
  function findRootRoute(statements) {
18
15
  for (const statement of statements) {
@@ -79,7 +76,7 @@ function findRootComponent(statements) {
79
76
  */
80
77
  function configureRootRoute({ content, statements }) {
81
78
  if (!statements) return void 0;
82
- if (/\b(?:getLocale|getTranslationsSnapshot)\b/.test(content)) return;
79
+ if (usesName(statements, ["getLocale", "getTranslationsSnapshot"])) return;
83
80
  const found = findRootComponent(statements);
84
81
  if (!found) return void 0;
85
82
  const { rootRoute, componentProperty, component, isShell, document } = found;
@@ -90,37 +87,12 @@ function configureRootRoute({ content, statements }) {
90
87
  })) return;
91
88
  if (componentProperty?.type !== "ObjectProperty" || !component || document?.body.type !== "BlockStatement" || [component, document].some((fn) => /\b(?:locale|translations)\b/.test(content.slice(fn.start, fn.end)))) return;
92
89
  const slotIsChildren = isShell || document !== component;
93
- const htmlElements = [];
94
- t.traverseFast(document.body, (node) => {
95
- if (isJsxElementNamed(node, "html")) htmlElements.push(node);
96
- });
97
- if (htmlElements.length !== 1) return void 0;
98
- const [html] = htmlElements;
99
- const bodies = html.children.filter((child) => isJsxElementNamed(child, "body"));
100
- if (bodies.length !== 1) return void 0;
101
- const bodyContent = bodies[0].children.filter((child) => child.type !== "JSXText" || child.value.trim() !== "");
102
- const scriptsIndex = bodyContent.findIndex((child) => isJsxElementNamed(child, "Scripts"));
103
- const wrapped = scriptsIndex === -1 ? bodyContent : bodyContent.slice(0, scriptsIndex);
104
- let slots = 0;
105
- let multilineLiteral = false;
106
- for (const child of wrapped) t.traverseFast(child, (node) => {
107
- if (slotIsChildren ? isChildrenSlot(node) : isJsxElementNamed(node, "Outlet")) slots++;
108
- if ((node.type === "TemplateLiteral" || node.type === "StringLiteral") && node.loc.start.line !== node.loc.end.line) multilineLiteral = true;
109
- });
110
- if (slots !== 1) return void 0;
111
- const { attributes } = html.openingElement;
112
- if (attributes.some((attribute) => attribute.type === "JSXSpreadAttribute")) return;
113
- const lang = attributes.find((attribute) => attribute.type === "JSXAttribute" && t.isJSXIdentifier(attribute.name, { name: "lang" }));
114
- if (lang && lang.value?.type !== "StringLiteral") return void 0;
90
+ const htmlDocument = findHtmlDocument(document.body, (node) => slotIsChildren ? isChildrenSlot(node) : isJsxElementNamed(node, "Outlet"));
91
+ if (!htmlDocument) return void 0;
115
92
  const propertyIndent = getOwnLineIndent(content, componentProperty.start);
116
93
  if (propertyIndent === void 0) return void 0;
117
- const { quote, semi, eol, indent } = getCodeStyle(content, statements);
118
- const first = wrapped[0];
119
- const last = wrapped.at(-1);
120
- const wrappedText = content.slice(first.start, last.end);
121
- const wrappedIndent = getOwnLineIndent(content, first.start);
122
- const nestedText = multilineLiteral ? wrappedText : wrappedText.replace(/\n(?=[ \t]*\S)/g, `\n${indent}`);
123
- const provider = "<GTProvider locale={locale} translations={translations}>";
94
+ const style = getCodeStyle(content, statements);
95
+ const { quote, semi, eol, indent } = style;
124
96
  const firstStatement = document.body.body[0];
125
97
  const statementIndent = (firstStatement && getOwnLineIndent(content, firstStatement.start)) ?? getLineIndent(content, document.start) + indent;
126
98
  return applyEdits(content, [
@@ -130,7 +102,7 @@ function configureRootRoute({ content, statements }) {
130
102
  text: [
131
103
  "loader: async () => {",
132
104
  `${propertyIndent}${indent}const locale = getLocale()${semi}`,
133
- `${propertyIndent}${indent}return { locale, translations: await getTranslationsSnapshot(locale) }${semi}`,
105
+ `${propertyIndent}${indent}return { locale, ${LOADER_TRANSLATIONS} }${semi}`,
134
106
  `${propertyIndent}},`,
135
107
  propertyIndent
136
108
  ].join(eol)
@@ -139,27 +111,15 @@ function configureRootRoute({ content, statements }) {
139
111
  start: document.body.start + 1,
140
112
  text: `${eol}${statementIndent}const { locale, translations } = ${rootRoute.routeName}.useLoaderData()${semi}`
141
113
  },
142
- lang ? {
143
- start: lang.start,
144
- end: lang.end,
145
- text: "lang={locale}"
146
- } : {
147
- start: html.openingElement.name.end,
148
- text: " lang={locale}"
149
- },
150
- {
151
- start: first.start,
152
- end: last.end,
153
- text: wrappedIndent === void 0 ? `${provider}${wrappedText}</GTProvider>` : [
154
- provider,
155
- `${wrappedIndent}${indent}${nestedText}`,
156
- `${wrappedIndent}</GTProvider>`
157
- ].join(eol)
158
- }
114
+ getLangEdit(htmlDocument),
115
+ getWrapEdit(content, htmlDocument, {
116
+ open: PROVIDER_TAG,
117
+ close: "</GTProvider>"
118
+ }, style)
159
119
  ]);
160
120
  }
161
121
  function getRootFix(rootPath) {
162
- return `In ${rootPath}, add loader: async () => { const locale = getLocale(); return { locale, translations: await getTranslationsSnapshot(locale) }; } to the root route options, read const { locale, translations } = Route.useLoaderData() in the document, set <html lang={locale}>, and wrap everything its <body> renders before <Scripts /> in <GTProvider locale={locale} translations={translations}>, importing GTProvider, getLocale and getTranslationsSnapshot from 'gt-tanstack-start' (see ${DOCS_URL})`;
122
+ return `In ${rootPath}, add loader: async () => { const locale = getLocale(); return { locale, ${LOADER_TRANSLATIONS} }; } to the root route options, read const { locale, translations } = Route.useLoaderData() in the document, set <html lang={locale}>, and wrap everything its <body> renders before <Scripts /> in ${PROVIDER_TAG}, importing GTProvider, getLocale and getTranslationsSnapshot from 'gt-tanstack-start' (see ${DOCS_URL})`;
163
123
  }
164
124
  //#endregion
165
125
  export { configureRootRoute, findRootComponent, getRootFix };
@@ -1 +1 @@
1
- {"version":3,"file":"root.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/root.ts"],"sourcesContent":["// src/routes/__root.tsx: recognizing and configuring the root route.\nimport * as t from '@babel/types';\nimport { Libraries } from '../../../types/libraries.js';\nimport {\n applyEdits,\n getCodeStyle,\n getImportEdit,\n getLineIndent,\n getOwnLineIndent,\n} from '../shared/edits.js';\nimport {\n isChildrenSlot,\n isJsxElementNamed,\n rendersElement,\n} from '../shared/jsx.js';\nimport { getPropertyName, type SourceFile } from '../shared/source.js';\nimport { DOCS_URL } from './source.js';\n\nfunction findLocalFunction(statements: t.Statement[], name: string) {\n for (const statement of statements) {\n const declaration =\n statement.type === 'ExportNamedDeclaration'\n ? statement.declaration\n : statement;\n if (\n declaration?.type === 'FunctionDeclaration' &&\n declaration.id?.name === name\n ) {\n return declaration;\n }\n if (declaration?.type !== 'VariableDeclaration') continue;\n if (declaration.kind !== 'const') continue;\n for (const declarator of declaration.declarations) {\n if (\n t.isIdentifier(declarator.id, { name }) &&\n (declarator.init?.type === 'ArrowFunctionExpression' ||\n declarator.init?.type === 'FunctionExpression')\n ) {\n return declarator.init;\n }\n }\n }\n return undefined;\n}\n\nfunction findRootRoute(statements: t.Statement[]) {\n for (const statement of statements) {\n const declaration =\n statement.type === 'ExportNamedDeclaration'\n ? statement.declaration\n : statement;\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const { id, init } of declaration.declarations) {\n if (\n id.type !== 'Identifier' ||\n init?.type !== 'CallExpression' ||\n init.arguments[0]?.type !== 'ObjectExpression'\n ) {\n continue;\n }\n const { callee } = init;\n // Router context adds a call: createRootRouteWithContext<Ctx>()({...}).\n if (\n (callee.type === 'Identifier' && callee.name === 'createRootRoute') ||\n (callee.type === 'CallExpression' &&\n callee.arguments.length === 0 &&\n callee.callee.type === 'Identifier' &&\n callee.callee.name === 'createRootRouteWithContext')\n ) {\n return { routeName: id.name, options: init.arguments[0] };\n }\n }\n }\n return undefined;\n}\n\ntype LocalFunction = NonNullable<ReturnType<typeof findLocalFunction>>;\n\n/**\n * The local function that renders the document: the route component itself\n * when it renders `<html>`, or the one local component it returns with only\n * the route's slot as its child. A followed document must render nowhere\n * else: another render, such as an errorComponent, has no loader data.\n */\nfunction findDocument(\n statements: t.Statement[],\n component: LocalFunction,\n isShell: boolean\n): LocalFunction | undefined {\n if (rendersElement([component.body], 'html')) return component;\n const { body } = component;\n const returned =\n body.type !== 'BlockStatement'\n ? body\n : body.body.length === 1 && body.body[0].type === 'ReturnStatement'\n ? body.body[0].argument\n : undefined;\n if (\n returned?.type !== 'JSXElement' ||\n returned.openingElement.name.type !== 'JSXIdentifier'\n ) {\n return undefined;\n }\n const children = returned.children.filter(\n (child) => child.type !== 'JSXText' || child.value.trim() !== ''\n );\n if (\n children.length !== 1 ||\n !(isShell\n ? isChildrenSlot(children[0])\n : isJsxElementNamed(children[0], 'Outlet'))\n ) {\n return undefined;\n }\n const { name } = returned.openingElement.name;\n // Its declaration and the route component's element are the only uses.\n let uses = 0;\n for (const statement of statements) {\n t.traverseFast(statement, (node) => {\n if (isJsxElementNamed(node, name) || t.isIdentifier(node, { name })) {\n uses++;\n }\n });\n }\n if (uses !== 2) return undefined;\n const document = findLocalFunction(statements, name);\n return document && rendersElement([document.body], 'html')\n ? document\n : undefined;\n}\n\n/**\n * The root route, the local function its shellComponent or component names,\n * and the local function that renders its document.\n */\nexport function findRootComponent(statements: t.Statement[]) {\n const rootRoute = findRootRoute(statements);\n if (!rootRoute) return undefined;\n const { properties } = rootRoute.options;\n const componentProperty =\n properties.find((p) => getPropertyName(p) === 'shellComponent') ??\n properties.find((p) => getPropertyName(p) === 'component');\n const component =\n componentProperty?.type === 'ObjectProperty' &&\n componentProperty.value.type === 'Identifier'\n ? findLocalFunction(statements, componentProperty.value.name)\n : undefined;\n const isShell =\n componentProperty !== undefined &&\n getPropertyName(componentProperty) === 'shellComponent';\n const document = component && findDocument(statements, component, isShell);\n return { rootRoute, componentProperty, component, isShell, document };\n}\n\n/**\n * Configures the create-start root route: `createRootRoute({...})` (or its\n * router-context form) without a loader, whose shellComponent renders\n * `{children}` (or whose component renders `<Outlet />`) once in the `<body>`\n * of a local `<html>` document, either directly or through one local document\n * component that renders its `{children}` there. Returns undefined for any\n * other shape.\n */\nexport function configureRootRoute({\n content,\n statements,\n}: SourceFile): string | undefined {\n if (!statements) return undefined;\n // Generated bindings must not shadow or collide with the app's own.\n if (/\\b(?:getLocale|getTranslationsSnapshot)\\b/.test(content)) {\n return undefined;\n }\n const found = findRootComponent(statements);\n if (!found) return undefined;\n const { rootRoute, componentProperty, component, isShell, document } = found;\n const { properties } = rootRoute.options;\n if (\n properties.some((property) => {\n const name = getPropertyName(property);\n // A spread or computed key could be any of the options below.\n // A throwing beforeLoad or validateSearch skips the loader, so the\n // shell would render without the locale and translations it reads.\n return (\n name === undefined ||\n name === 'loader' ||\n name === 'beforeLoad' ||\n name === 'validateSearch'\n );\n })\n ) {\n return undefined;\n }\n if (\n componentProperty?.type !== 'ObjectProperty' ||\n !component ||\n document?.body.type !== 'BlockStatement' ||\n [component, document].some((fn) =>\n /\\b(?:locale|translations)\\b/.test(content.slice(fn.start!, fn.end!))\n )\n ) {\n return undefined;\n }\n // A followed document receives the route's slot as its children.\n const slotIsChildren = isShell || document !== component;\n const htmlElements: t.JSXElement[] = [];\n t.traverseFast(document.body, (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 (\n slotIsChildren\n ? isChildrenSlot(node)\n : isJsxElementNamed(node, 'Outlet')\n ) {\n slots++;\n }\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 const propertyIndent = getOwnLineIndent(content, componentProperty.start!);\n if (propertyIndent === undefined) return undefined;\n\n const { quote, semi, eol, indent } = getCodeStyle(content, statements);\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 const provider = '<GTProvider locale={locale} translations={translations}>';\n const firstStatement = document.body.body[0];\n const statementIndent =\n (firstStatement && getOwnLineIndent(content, firstStatement.start!)) ??\n getLineIndent(content, document.start!) + indent;\n return applyEdits(content, [\n getImportEdit(\n statements,\n [\n `import { GTProvider, getLocale, getTranslationsSnapshot } from ${quote}${Libraries.GT_TANSTACK_START}${quote}${semi}`,\n ],\n eol\n ),\n {\n start: componentProperty.start!,\n text: [\n 'loader: async () => {',\n `${propertyIndent}${indent}const locale = getLocale()${semi}`,\n `${propertyIndent}${indent}return { locale, translations: await getTranslationsSnapshot(locale) }${semi}`,\n `${propertyIndent}},`,\n propertyIndent,\n ].join(eol),\n },\n {\n start: document.body.start! + 1,\n text: `${eol}${statementIndent}const { locale, translations } = ${rootRoute.routeName}.useLoaderData()${semi}`,\n },\n lang\n ? { start: lang.start!, end: lang.end!, text: 'lang={locale}' }\n : { start: html.openingElement.name.end!, text: ' lang={locale}' },\n {\n start: first.start!,\n end: last.end!,\n text:\n wrappedIndent === undefined\n ? `${provider}${wrappedText}</GTProvider>`\n : [\n provider,\n `${wrappedIndent}${indent}${nestedText}`,\n `${wrappedIndent}</GTProvider>`,\n ].join(eol),\n },\n ]);\n}\n\nexport function getRootFix(rootPath: string): string {\n return `In ${rootPath}, add loader: async () => { const locale = getLocale(); return { locale, translations: await getTranslationsSnapshot(locale) }; } to the root route options, read const { locale, translations } = Route.useLoaderData() in the document, set <html lang={locale}>, and wrap everything its <body> renders before <Scripts /> in <GTProvider locale={locale} translations={translations}>, importing GTProvider, getLocale and getTranslationsSnapshot from '${Libraries.GT_TANSTACK_START}' (see ${DOCS_URL})`;\n}\n"],"mappings":";;;;;;;AAkBA,SAAS,kBAAkB,YAA2B,MAAc;AAClE,MAAK,MAAM,aAAa,YAAY;EAClC,MAAM,cACJ,UAAU,SAAS,2BACf,UAAU,cACV;AACN,MACE,aAAa,SAAS,yBACtB,YAAY,IAAI,SAAS,KAEzB,QAAO;AAET,MAAI,aAAa,SAAS,sBAAuB;AACjD,MAAI,YAAY,SAAS,QAAS;AAClC,OAAK,MAAM,cAAc,YAAY,aACnC,KACE,EAAE,aAAa,WAAW,IAAI,EAAE,MAAM,CAAC,KACtC,WAAW,MAAM,SAAS,6BACzB,WAAW,MAAM,SAAS,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AE,OAAO,MAAM,KAAK,WAAW,aAAa,SAAS,WAAW;CACtE,MAAM,QAAQ,QAAQ;CACtB,MAAM,OAAO,QAAQ,GAAG,GAAG;CAC3B,MAAM,cAAc,QAAQ,MAAM,MAAM,OAAQ,KAAK,IAAK;CAC1D,MAAM,gBAAgB,iBAAiB,SAAS,MAAM,MAAO;CAG7D,MAAM,aAAa,mBACf,cACA,YAAY,QAAQ,mBAAmB,KAAK,SAAS;CACzD,MAAM,WAAW;CACjB,MAAM,iBAAiB,SAAS,KAAK,KAAK;CAC1C,MAAM,mBACH,kBAAkB,iBAAiB,SAAS,eAAe,MAAO,KACnE,cAAc,SAAS,SAAS,MAAO,GAAG;AAC5C,QAAO,WAAW,SAAS;EACzB,cACE,YACA,CACE,kEAAkE,yBAAsC,QAAQ,OACjH,EACD,IACD;EACD;GACE,OAAO,kBAAkB;GACzB,MAAM;IACJ;IACA,GAAG,iBAAiB,OAAO,4BAA4B;IACvD,GAAG,iBAAiB,OAAO,wEAAwE;IACnG,GAAG,eAAe;IAClB;IACD,CAAC,KAAK,IAAI;GACZ;EACD;GACE,OAAO,SAAS,KAAK,QAAS;GAC9B,MAAM,GAAG,MAAM,gBAAgB,mCAAmC,UAAU,UAAU,kBAAkB;GACzG;EACD,OACI;GAAE,OAAO,KAAK;GAAQ,KAAK,KAAK;GAAM,MAAM;GAAiB,GAC7D;GAAE,OAAO,KAAK,eAAe,KAAK;GAAM,MAAM;GAAkB;EACpE;GACE,OAAO,MAAM;GACb,KAAK,KAAK;GACV,MACE,kBAAkB,KAAA,IACd,GAAG,WAAW,YAAY,iBAC1B;IACE;IACA,GAAG,gBAAgB,SAAS;IAC5B,GAAG,cAAc;IAClB,CAAC,KAAK,IAAI;GAClB;EACF,CAAC;;AAGJ,SAAgB,WAAW,UAA0B;AACnD,QAAO,MAAM,SAAS,udAAoe,SAAS"}
1
+ {"version":3,"file":"root.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/root.ts"],"sourcesContent":["// src/routes/__root.tsx: recognizing and configuring the root route.\nimport * as t from '@babel/types';\nimport { Libraries } from '../../../types/libraries.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} from '../shared/edits.js';\nimport {\n isChildrenSlot,\n isJsxElementNamed,\n rendersElement,\n} from '../shared/jsx.js';\nimport {\n findDeclaredFunction,\n getPropertyName,\n usesName,\n type DeclaredFunction,\n type SourceFile,\n} from '../shared/source.js';\nimport { DOCS_URL } from './source.js';\n\n/** The provider the document is wrapped in, reading the root loader's data. */\nconst PROVIDER_TAG = '<GTProvider locale={locale} translations={translations}>';\n\ntype LocalFunction = DeclaredFunction['fn'];\n\nfunction findLocalFunction(\n statements: t.Statement[],\n name: string\n): LocalFunction | undefined {\n return findDeclaredFunction(statements, name)?.fn;\n}\n\nfunction findRootRoute(statements: t.Statement[]) {\n for (const statement of statements) {\n const declaration =\n statement.type === 'ExportNamedDeclaration'\n ? statement.declaration\n : statement;\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const { id, init } of declaration.declarations) {\n if (\n id.type !== 'Identifier' ||\n init?.type !== 'CallExpression' ||\n init.arguments[0]?.type !== 'ObjectExpression'\n ) {\n continue;\n }\n const { callee } = init;\n // Router context adds a call: createRootRouteWithContext<Ctx>()({...}).\n if (\n (callee.type === 'Identifier' && callee.name === 'createRootRoute') ||\n (callee.type === 'CallExpression' &&\n callee.arguments.length === 0 &&\n callee.callee.type === 'Identifier' &&\n callee.callee.name === 'createRootRouteWithContext')\n ) {\n return { routeName: id.name, options: init.arguments[0] };\n }\n }\n }\n return undefined;\n}\n\n/**\n * The local function that renders the document: the route component itself\n * when it renders `<html>`, or the one local component it returns with only\n * the route's slot as its child. A followed document must render nowhere\n * else: another render, such as an errorComponent, has no loader data.\n */\nfunction findDocument(\n statements: t.Statement[],\n component: LocalFunction,\n isShell: boolean\n): LocalFunction | undefined {\n if (rendersElement([component.body], 'html')) return component;\n const { body } = component;\n const returned =\n body.type !== 'BlockStatement'\n ? body\n : body.body.length === 1 && body.body[0].type === 'ReturnStatement'\n ? body.body[0].argument\n : undefined;\n if (\n returned?.type !== 'JSXElement' ||\n returned.openingElement.name.type !== 'JSXIdentifier'\n ) {\n return undefined;\n }\n const children = returned.children.filter(\n (child) => child.type !== 'JSXText' || child.value.trim() !== ''\n );\n if (\n children.length !== 1 ||\n !(isShell\n ? isChildrenSlot(children[0])\n : isJsxElementNamed(children[0], 'Outlet'))\n ) {\n return undefined;\n }\n const { name } = returned.openingElement.name;\n // Its declaration and the route component's element are the only uses.\n let uses = 0;\n for (const statement of statements) {\n t.traverseFast(statement, (node) => {\n if (isJsxElementNamed(node, name) || t.isIdentifier(node, { name })) {\n uses++;\n }\n });\n }\n if (uses !== 2) return undefined;\n const document = findLocalFunction(statements, name);\n return document && rendersElement([document.body], 'html')\n ? document\n : undefined;\n}\n\n/**\n * The root route, the local function its shellComponent or component names,\n * and the local function that renders its document.\n */\nexport function findRootComponent(statements: t.Statement[]) {\n const rootRoute = findRootRoute(statements);\n if (!rootRoute) return undefined;\n const { properties } = rootRoute.options;\n const componentProperty =\n properties.find((p) => getPropertyName(p) === 'shellComponent') ??\n properties.find((p) => getPropertyName(p) === 'component');\n const component =\n componentProperty?.type === 'ObjectProperty' &&\n componentProperty.value.type === 'Identifier'\n ? findLocalFunction(statements, componentProperty.value.name)\n : undefined;\n const isShell =\n componentProperty !== undefined &&\n getPropertyName(componentProperty) === 'shellComponent';\n const document = component && findDocument(statements, component, isShell);\n return { rootRoute, componentProperty, component, isShell, document };\n}\n\n/**\n * Configures the create-start root route: `createRootRoute({...})` (or its\n * router-context form) without a loader, whose shellComponent renders\n * `{children}` (or whose component renders `<Outlet />`) once in the `<body>`\n * of a local `<html>` document, either directly or through one local document\n * component that renders its `{children}` there. Returns undefined for any\n * other shape.\n */\nexport function configureRootRoute({\n content,\n statements,\n}: SourceFile): string | undefined {\n if (!statements) return undefined;\n // Generated bindings must not shadow or collide with the app's own.\n if (usesName(statements, ['getLocale', 'getTranslationsSnapshot'])) {\n return undefined;\n }\n const found = findRootComponent(statements);\n if (!found) return undefined;\n const { rootRoute, componentProperty, component, isShell, document } = found;\n const { properties } = rootRoute.options;\n if (\n properties.some((property) => {\n const name = getPropertyName(property);\n // A spread or computed key could be any of the options below.\n // A throwing beforeLoad or validateSearch skips the loader, so the\n // shell would render without the locale and translations it reads.\n return (\n name === undefined ||\n name === 'loader' ||\n name === 'beforeLoad' ||\n name === 'validateSearch'\n );\n })\n ) {\n return undefined;\n }\n if (\n componentProperty?.type !== 'ObjectProperty' ||\n !component ||\n document?.body.type !== 'BlockStatement' ||\n // Deliberately text, not usesName: a component taking a locale or\n // translations prop has its own plumbing, and a JSX attribute name is not\n // an identifier.\n [component, document].some((fn) =>\n /\\b(?:locale|translations)\\b/.test(content.slice(fn.start!, fn.end!))\n )\n ) {\n return undefined;\n }\n // A followed document receives the route's slot as its children.\n const slotIsChildren = isShell || document !== component;\n const htmlDocument = findHtmlDocument(document.body, (node) =>\n slotIsChildren ? isChildrenSlot(node) : isJsxElementNamed(node, 'Outlet')\n );\n if (!htmlDocument) return undefined;\n const propertyIndent = getOwnLineIndent(content, componentProperty.start!);\n if (propertyIndent === undefined) return undefined;\n\n const style = getCodeStyle(content, statements);\n const { quote, semi, eol, indent } = style;\n const firstStatement = document.body.body[0];\n const statementIndent =\n (firstStatement && getOwnLineIndent(content, firstStatement.start!)) ??\n getLineIndent(content, document.start!) + indent;\n return applyEdits(content, [\n getImportEdit(\n statements,\n [\n `import { GTProvider, getLocale, getTranslationsSnapshot } from ${quote}${Libraries.GT_TANSTACK_START}${quote}${semi}`,\n ],\n eol\n ),\n {\n start: componentProperty.start!,\n text: [\n 'loader: async () => {',\n `${propertyIndent}${indent}const locale = getLocale()${semi}`,\n `${propertyIndent}${indent}return { locale, ${LOADER_TRANSLATIONS} }${semi}`,\n `${propertyIndent}},`,\n propertyIndent,\n ].join(eol),\n },\n {\n start: document.body.start! + 1,\n text: `${eol}${statementIndent}const { locale, translations } = ${rootRoute.routeName}.useLoaderData()${semi}`,\n },\n getLangEdit(htmlDocument),\n getWrapEdit(\n content,\n htmlDocument,\n { open: PROVIDER_TAG, close: '</GTProvider>' },\n style\n ),\n ]);\n}\n\nexport function getRootFix(rootPath: string): string {\n return `In ${rootPath}, add loader: async () => { const locale = getLocale(); return { locale, ${LOADER_TRANSLATIONS} }; } to the root route options, read const { locale, translations } = Route.useLoaderData() in the document, set <html lang={locale}>, and wrap everything its <body> renders before <Scripts /> in ${PROVIDER_TAG}, importing GTProvider, getLocale and getTranslationsSnapshot from '${Libraries.GT_TANSTACK_START}' (see ${DOCS_URL})`;\n}\n"],"mappings":";;;;;;;;;AA+BA,MAAM,eAAe;AAIrB,SAAS,kBACP,YACA,MAC2B;AAC3B,QAAO,qBAAqB,YAAY,KAAK,EAAE;;AAGjD,SAAS,cAAc,YAA2B;AAChD,MAAK,MAAM,aAAa,YAAY;EAClC,MAAM,cACJ,UAAU,SAAS,2BACf,UAAU,cACV;AACN,MAAI,aAAa,SAAS,sBAAuB;AACjD,OAAK,MAAM,EAAE,IAAI,UAAU,YAAY,cAAc;AACnD,OACE,GAAG,SAAS,gBACZ,MAAM,SAAS,oBACf,KAAK,UAAU,IAAI,SAAS,mBAE5B;GAEF,MAAM,EAAE,WAAW;AAEnB,OACG,OAAO,SAAS,gBAAgB,OAAO,SAAS,qBAChD,OAAO,SAAS,oBACf,OAAO,UAAU,WAAW,KAC5B,OAAO,OAAO,SAAS,gBACvB,OAAO,OAAO,SAAS,6BAEzB,QAAO;IAAE,WAAW,GAAG;IAAM,SAAS,KAAK,UAAU;IAAI;;;;;;;;;;AAajE,SAAS,aACP,YACA,WACA,SAC2B;AAC3B,KAAI,eAAe,CAAC,UAAU,KAAK,EAAE,OAAO,CAAE,QAAO;CACrD,MAAM,EAAE,SAAS;CACjB,MAAM,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vD,GAAG,iBAAiB,OAAO,mBAAmB,oBAAoB,IAAI;IACtE,GAAG,eAAe;IAClB;IACD,CAAC,KAAK,IAAI;GACZ;EACD;GACE,OAAO,SAAS,KAAK,QAAS;GAC9B,MAAM,GAAG,MAAM,gBAAgB,mCAAmC,UAAU,UAAU,kBAAkB;GACzG;EACD,YAAY,aAAa;EACzB,YACE,SACA,cACA;GAAE,MAAM;GAAc,OAAO;GAAiB,EAC9C,MACD;EACF,CAAC;;AAGJ,SAAgB,WAAW,UAA0B;AACnD,QAAO,MAAM,SAAS,2EAA2E,oBAAoB,uMAAuM,aAAa,8FAA2G,SAAS"}
@@ -1,15 +1,7 @@
1
- import * as t from '@babel/types';
2
1
  import { type ViteLoaderExport } from '../../setupViteSPA.js';
3
2
  import type { BuildToolContext, ManualAction } from '../index.js';
4
3
  import type { CodeStyle } from '../shared/edits.js';
5
- import { type SourceFile } from '../shared/source.js';
6
- /** The module-scope `initializeGT(...)` call, which must run before requests. */
7
- export declare function findInitializeCall(file: SourceFile): t.CallExpression | undefined;
8
- /**
9
- * Whether the initializeGT options pass a loader: false for the config alone,
10
- * undefined when the options hide it (other spreads, variables, computed keys).
11
- */
12
- export declare function passesLoader(router: SourceFile, options: t.Node | undefined, { appDirectory, configFilepath }: BuildToolContext): boolean | undefined;
4
+ import type { SourceFile } from '../shared/source.js';
13
5
  export declare function getRouterLines(router: SourceFile, { appDirectory, configFilepath }: BuildToolContext, loaderExport: ViteLoaderExport, { quote, semi }: Pick<CodeStyle, 'quote' | 'semi'>): string[];
14
6
  /** The initializeGT change for a router whose storage no longer matches. */
15
7
  export declare function getStorageAction(router: SourceFile, ctx: BuildToolContext, loaderExport: ViteLoaderExport, loaderPassed: boolean): ManualAction;