@nifrajs/cli 5.1.0 → 5.2.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 (201) hide show
  1. package/CHANGELOG.md +3211 -0
  2. package/README.md +3 -0
  3. package/dist/agent-files.d.ts +19 -11
  4. package/dist/agent-files.d.ts.map +1 -1
  5. package/dist/agent-files.js +26 -18
  6. package/dist/agent-files.js.map +1 -1
  7. package/dist/assure-hydration.d.ts.map +1 -1
  8. package/dist/assure-hydration.js +1 -0
  9. package/dist/assure-hydration.js.map +1 -1
  10. package/dist/assure.d.ts.map +1 -1
  11. package/dist/assure.js +14 -1
  12. package/dist/assure.js.map +1 -1
  13. package/dist/capabilities-tool.d.ts.map +1 -1
  14. package/dist/capabilities-tool.js +131 -45
  15. package/dist/capabilities-tool.js.map +1 -1
  16. package/dist/check-diagnostics.d.ts +5 -0
  17. package/dist/check-diagnostics.d.ts.map +1 -1
  18. package/dist/check-diagnostics.js +3 -0
  19. package/dist/check-diagnostics.js.map +1 -1
  20. package/dist/check-scan.d.ts.map +1 -1
  21. package/dist/check-scan.js +6 -3
  22. package/dist/check-scan.js.map +1 -1
  23. package/dist/check.d.ts.map +1 -1
  24. package/dist/check.js +52 -12
  25. package/dist/check.js.map +1 -1
  26. package/dist/cli.d.ts.map +1 -1
  27. package/dist/cli.js +23 -12
  28. package/dist/cli.js.map +1 -1
  29. package/dist/command-catalog.d.ts.map +1 -1
  30. package/dist/command-catalog.js +9 -5
  31. package/dist/command-catalog.js.map +1 -1
  32. package/dist/dev-bun-config.d.ts +6 -3
  33. package/dist/dev-bun-config.d.ts.map +1 -1
  34. package/dist/dev-bun-config.js +13 -10
  35. package/dist/dev-bun-config.js.map +1 -1
  36. package/dist/dev-feed-tool.d.ts +3 -2
  37. package/dist/dev-feed-tool.d.ts.map +1 -1
  38. package/dist/dev-feed-tool.js +26 -5
  39. package/dist/dev-feed-tool.js.map +1 -1
  40. package/dist/doctor.d.ts +15 -1
  41. package/dist/doctor.d.ts.map +1 -1
  42. package/dist/doctor.js +79 -61
  43. package/dist/doctor.js.map +1 -1
  44. package/dist/i18n-check.d.ts +11 -1
  45. package/dist/i18n-check.d.ts.map +1 -1
  46. package/dist/i18n-check.js +170 -17
  47. package/dist/i18n-check.js.map +1 -1
  48. package/dist/init-agents.d.ts +46 -6
  49. package/dist/init-agents.d.ts.map +1 -1
  50. package/dist/init-agents.js +193 -31
  51. package/dist/init-agents.js.map +1 -1
  52. package/dist/internal/project-specifiers.d.ts.map +1 -1
  53. package/dist/internal/project-specifiers.js +9 -1
  54. package/dist/internal/project-specifiers.js.map +1 -1
  55. package/dist/internal/source-facts.d.ts +6 -0
  56. package/dist/internal/source-facts.d.ts.map +1 -1
  57. package/dist/internal/source-facts.js +106 -0
  58. package/dist/internal/source-facts.js.map +1 -1
  59. package/dist/internal/workspace-packages.d.ts +22 -0
  60. package/dist/internal/workspace-packages.d.ts.map +1 -0
  61. package/dist/internal/workspace-packages.js +215 -0
  62. package/dist/internal/workspace-packages.js.map +1 -0
  63. package/dist/load.d.ts +7 -2
  64. package/dist/load.d.ts.map +1 -1
  65. package/dist/load.js +11 -2
  66. package/dist/load.js.map +1 -1
  67. package/dist/lock-links.d.ts +42 -0
  68. package/dist/lock-links.d.ts.map +1 -0
  69. package/dist/lock-links.js +144 -0
  70. package/dist/lock-links.js.map +1 -0
  71. package/dist/mcp-exec.d.ts.map +1 -1
  72. package/dist/mcp-exec.js +5 -2
  73. package/dist/mcp-exec.js.map +1 -1
  74. package/dist/mcp-http.js +1 -1
  75. package/dist/mcp-root.d.ts +6 -4
  76. package/dist/mcp-root.d.ts.map +1 -1
  77. package/dist/mcp-root.js +12 -8
  78. package/dist/mcp-root.js.map +1 -1
  79. package/dist/migrate-layout.d.ts +2 -1
  80. package/dist/migrate-layout.d.ts.map +1 -1
  81. package/dist/migrate-layout.js +434 -29
  82. package/dist/migrate-layout.js.map +1 -1
  83. package/dist/project-site.d.ts +7 -0
  84. package/dist/project-site.d.ts.map +1 -0
  85. package/dist/project-site.js +19 -0
  86. package/dist/project-site.js.map +1 -0
  87. package/dist/recipes/4.0.0.d.ts.map +1 -1
  88. package/dist/recipes/4.0.0.js +2 -0
  89. package/dist/recipes/4.0.0.js.map +1 -1
  90. package/dist/recipes/5.1.0.d.ts +9 -0
  91. package/dist/recipes/5.1.0.d.ts.map +1 -0
  92. package/dist/recipes/5.1.0.js +22 -0
  93. package/dist/recipes/5.1.0.js.map +1 -0
  94. package/dist/recipes/5.2.0.d.ts +10 -0
  95. package/dist/recipes/5.2.0.d.ts.map +1 -0
  96. package/dist/recipes/5.2.0.js +32 -0
  97. package/dist/recipes/5.2.0.js.map +1 -0
  98. package/dist/recipes/index.d.ts +3 -0
  99. package/dist/recipes/index.d.ts.map +1 -1
  100. package/dist/recipes/index.js +7 -0
  101. package/dist/recipes/index.js.map +1 -1
  102. package/dist/review.d.ts.map +1 -1
  103. package/dist/review.js +2 -0
  104. package/dist/review.js.map +1 -1
  105. package/dist/rule-explain.d.ts +26 -0
  106. package/dist/rule-explain.d.ts.map +1 -0
  107. package/dist/rule-explain.js +49 -0
  108. package/dist/rule-explain.js.map +1 -0
  109. package/dist/rules/codes.d.ts +2 -0
  110. package/dist/rules/codes.d.ts.map +1 -1
  111. package/dist/rules/codes.js +2 -0
  112. package/dist/rules/codes.js.map +1 -1
  113. package/dist/rules/contract-visibility.d.ts.map +1 -1
  114. package/dist/rules/contract-visibility.js +93 -21
  115. package/dist/rules/contract-visibility.js.map +1 -1
  116. package/dist/rules/explanations.d.ts +14 -0
  117. package/dist/rules/explanations.d.ts.map +1 -0
  118. package/dist/rules/explanations.js +316 -0
  119. package/dist/rules/explanations.js.map +1 -0
  120. package/dist/rules/legacy.d.ts.map +1 -1
  121. package/dist/rules/legacy.js +24 -1
  122. package/dist/rules/legacy.js.map +1 -1
  123. package/dist/rules/merge-auth.d.ts +12 -0
  124. package/dist/rules/merge-auth.d.ts.map +1 -0
  125. package/dist/rules/merge-auth.js +52 -0
  126. package/dist/rules/merge-auth.js.map +1 -0
  127. package/dist/rules/pages.d.ts +27 -0
  128. package/dist/rules/pages.d.ts.map +1 -1
  129. package/dist/rules/pages.js +177 -2
  130. package/dist/rules/pages.js.map +1 -1
  131. package/dist/rules/routes.d.ts +3 -2
  132. package/dist/rules/routes.d.ts.map +1 -1
  133. package/dist/rules/routes.js +4 -3
  134. package/dist/rules/routes.js.map +1 -1
  135. package/dist/rules/zones.d.ts.map +1 -1
  136. package/dist/rules/zones.js +3 -2
  137. package/dist/rules/zones.js.map +1 -1
  138. package/dist/typecheck-coverage.d.ts +11 -0
  139. package/dist/typecheck-coverage.d.ts.map +1 -1
  140. package/dist/typecheck-coverage.js +50 -7
  141. package/dist/typecheck-coverage.js.map +1 -1
  142. package/dist/upgrade.d.ts +37 -1
  143. package/dist/upgrade.d.ts.map +1 -1
  144. package/dist/upgrade.js +171 -20
  145. package/dist/upgrade.js.map +1 -1
  146. package/dist/verification-plan.d.ts.map +1 -1
  147. package/dist/verification-plan.js +2 -0
  148. package/dist/verification-plan.js.map +1 -1
  149. package/dist/version-drift.d.ts.map +1 -1
  150. package/dist/version-drift.js +12 -1
  151. package/dist/version-drift.js.map +1 -1
  152. package/dist/web-app-options.d.ts +1 -1
  153. package/dist/web-app-options.d.ts.map +1 -1
  154. package/dist/web-app-options.js.map +1 -1
  155. package/docs/examples.json +19 -1
  156. package/docs/llms-full.txt +625 -130
  157. package/docs/types.json +396 -50
  158. package/package.json +13 -12
  159. package/src/agent-files.ts +27 -17
  160. package/src/assure-hydration.ts +1 -0
  161. package/src/assure.ts +11 -1
  162. package/src/capabilities-tool.ts +159 -50
  163. package/src/check-diagnostics.ts +8 -0
  164. package/src/check-scan.ts +9 -3
  165. package/src/check.ts +67 -12
  166. package/src/cli.ts +24 -11
  167. package/src/command-catalog.ts +16 -8
  168. package/src/dev-bun-config.ts +13 -9
  169. package/src/dev-feed-tool.ts +40 -6
  170. package/src/doctor.ts +102 -66
  171. package/src/i18n-check.ts +254 -18
  172. package/src/init-agents.ts +221 -41
  173. package/src/internal/project-specifiers.ts +9 -1
  174. package/src/internal/source-facts.ts +124 -0
  175. package/src/internal/workspace-packages.ts +218 -0
  176. package/src/load.ts +19 -3
  177. package/src/lock-links.ts +173 -0
  178. package/src/mcp-exec.ts +5 -2
  179. package/src/mcp-http.ts +1 -1
  180. package/src/mcp-root.ts +14 -8
  181. package/src/migrate-layout.ts +495 -31
  182. package/src/project-site.ts +18 -0
  183. package/src/recipes/4.0.0.ts +2 -0
  184. package/src/recipes/5.1.0.ts +23 -0
  185. package/src/recipes/5.2.0.ts +33 -0
  186. package/src/recipes/index.ts +7 -0
  187. package/src/review.ts +2 -0
  188. package/src/rule-explain.ts +75 -0
  189. package/src/rules/codes.ts +2 -0
  190. package/src/rules/contract-visibility.ts +118 -20
  191. package/src/rules/explanations.ts +329 -0
  192. package/src/rules/legacy.ts +24 -1
  193. package/src/rules/merge-auth.ts +55 -0
  194. package/src/rules/pages.ts +221 -2
  195. package/src/rules/routes.ts +4 -3
  196. package/src/rules/zones.ts +3 -2
  197. package/src/typecheck-coverage.ts +51 -6
  198. package/src/upgrade.ts +227 -22
  199. package/src/verification-plan.ts +6 -0
  200. package/src/version-drift.ts +15 -0
  201. package/src/web-app-options.ts +9 -1
@@ -60,7 +60,8 @@ const LEGACY_SERVER = /\.server(\.(?:[cm]?[jt]sx?|svelte|vue|mdx))$/;
60
60
  const RETIRED_SPECIFIERS = {
61
61
  "@nifrajs/web/server-only": "@nifrajs/web/backend-only",
62
62
  };
63
- /** Scripts and config that name app files by path: scanned for paths that moved, never rewritten. */
63
+ /** Scripts and config that name app files by path: scanned for paths that moved. Only the app's own
64
+ * package.json is rewritten, in the fields `rewritePackagePaths` reads. */
64
65
  const TOOLING_FILE = /(?:\.(?:json|jsonc|ya?ml|toml|sh|bash|zsh|ps1)|(?:^|\/)(?:Dockerfile|Makefile|Procfile))$/;
65
66
  const SELF_LOCATION = /\bimport\.meta\.(?:dirname|dir|filename|url)\b|\b__(?:dirname|filename)\b/;
66
67
  const SKIP_DIRS = new Set(["node_modules", "dist", "build", "coverage", ".git", ".vite", "public"]);
@@ -919,6 +920,100 @@ function importsOf(ts, file, text) {
919
920
  visit(sf);
920
921
  return refs;
921
922
  }
923
+ /** The `import.meta.glob` calls of a JS/TS module. */
924
+ function globCalls(ts, file, text) {
925
+ if (!/\.[cm]?[jt]sx?$/.test(file) || !text.includes("import.meta.glob"))
926
+ return [];
927
+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
928
+ const calls = [];
929
+ const visit = (node) => {
930
+ if (ts.isCallExpression(node) &&
931
+ ts.isPropertyAccessExpression(node.expression) &&
932
+ node.expression.name.text === "glob" &&
933
+ ts.isMetaProperty(node.expression.expression) &&
934
+ node.expression.expression.keywordToken === ts.SyntaxKind.ImportKeyword) {
935
+ const arg = node.arguments[0];
936
+ const elements = arg === undefined ? [] : ts.isArrayLiteralExpression(arg) ? [...arg.elements] : [arg];
937
+ const literals = elements.filter(ts.isStringLiteralLike);
938
+ const literal = literals.length > 0 && literals.length === elements.length;
939
+ calls.push({
940
+ patterns: literal
941
+ ? literals.map((element) => ({
942
+ text: element.text,
943
+ start: element.getStart(sf) + 1,
944
+ end: element.getEnd() - 1,
945
+ }))
946
+ : [],
947
+ literal,
948
+ line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1,
949
+ });
950
+ }
951
+ ts.forEachChild(node, visit);
952
+ };
953
+ visit(sf);
954
+ return calls;
955
+ }
956
+ /** A glob pattern written in `file` as an app-relative glob, by Vite's rules: `./` and `../` from the
957
+ * file's folder, `/` from the app root. `undefined` for any other shape, such as an alias. */
958
+ function appGlob(file, pattern) {
959
+ if (pattern.startsWith("/"))
960
+ return pattern.slice(1);
961
+ if (!pattern.startsWith("./") && !pattern.startsWith("../"))
962
+ return undefined;
963
+ const at = posix.normalize(posix.join(posix.dirname(file), pattern));
964
+ return at.startsWith("../") ? undefined : at;
965
+ }
966
+ /** The files among `files` a glob call in `file` loads, a `!` pattern excluding; `undefined` when a
967
+ * pattern cannot be read from the app. */
968
+ function globTargets(file, patterns, files) {
969
+ const include = [];
970
+ const exclude = [];
971
+ for (const raw of patterns) {
972
+ const at = appGlob(file, raw.startsWith("!") ? raw.slice(1) : raw);
973
+ if (at === undefined)
974
+ return undefined;
975
+ (raw.startsWith("!") ? exclude : include).push(new Bun.Glob(at));
976
+ }
977
+ return [...files].filter((candidate) => candidate !== file &&
978
+ include.some((glob) => glob.match(candidate)) &&
979
+ !exclude.some((glob) => glob.match(candidate)));
980
+ }
981
+ /**
982
+ * `pattern`, written in `from` (now `to`), re-pointed at the folder its matches `before` moved to: the
983
+ * part before the first wildcard is the folder, and every match must keep its path below it.
984
+ * `undefined` when the matches did not move as one folder.
985
+ */
986
+ function repointGlob(from, to, pattern, before, newPath) {
987
+ const negated = pattern.startsWith("!");
988
+ const written = negated ? pattern.slice(1) : pattern;
989
+ const at = appGlob(from, written);
990
+ if (at === undefined)
991
+ return undefined;
992
+ const segments = at.split("/");
993
+ const wild = segments.findIndex((segment) => /[*?[\]{}]/.test(segment));
994
+ const base = (wild === -1 ? segments.slice(0, -1) : segments.slice(0, wild)).join("/");
995
+ const rest = segments.slice(base === "" ? 0 : base.split("/").length).join("/");
996
+ let moved;
997
+ for (const file of before) {
998
+ if (base !== "" && !file.startsWith(`${base}/`))
999
+ continue;
1000
+ const tail = base === "" ? file : file.slice(base.length + 1);
1001
+ const now = newPath(file);
1002
+ if (!now.endsWith(`/${tail}`) && now !== tail)
1003
+ return undefined;
1004
+ const folder = now === tail ? "" : now.slice(0, now.length - tail.length - 1);
1005
+ if (moved !== undefined && folder !== moved)
1006
+ return undefined;
1007
+ moved = folder;
1008
+ }
1009
+ if (moved === undefined)
1010
+ return pattern;
1011
+ const folder = posix.relative(posix.dirname(to), moved);
1012
+ const next = written.startsWith("/")
1013
+ ? `/${moved === "" ? "" : `${moved}/`}${rest}`
1014
+ : `${folder === "" ? "." : folder.startsWith("..") ? folder : `./${folder}`}/${rest}`;
1015
+ return negated ? `!${next}` : next;
1016
+ }
922
1017
  /** Resolve a relative specifier against the file map, the way a bundler would. */
923
1018
  function resolveIn(files, from, specifier) {
924
1019
  if (!specifier.startsWith("."))
@@ -952,7 +1047,121 @@ function liveSpecifierSpans(ts, file, text, files) {
952
1047
  }
953
1048
  return spans;
954
1049
  }
1050
+ /**
1051
+ * The comment spans of a JS/TS module: the leading and trailing trivia of each token. Empty when the
1052
+ * compiler cannot walk the tokens, so every mention in the file stays an issue.
1053
+ */
1054
+ function triviaCommentRanges(ts, file, text) {
1055
+ const spans = new Map();
1056
+ const add = (ranges) => {
1057
+ for (const range of ranges ?? [])
1058
+ spans.set(range.pos, range.end);
1059
+ };
1060
+ try {
1061
+ const kind = /x$/.test(file) ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
1062
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
1063
+ const visit = (node) => {
1064
+ // A JSDoc block is itself one of the comments its token's trivia holds; JSX text is not trivia.
1065
+ if (node.kind >= ts.SyntaxKind.FirstJSDocNode && node.kind <= ts.SyntaxKind.LastJSDocNode)
1066
+ return;
1067
+ if (ts.isJsxText(node))
1068
+ return;
1069
+ const children = node.getChildren(source);
1070
+ if (children.length > 0) {
1071
+ for (const child of children)
1072
+ visit(child);
1073
+ return;
1074
+ }
1075
+ add(ts.getLeadingCommentRanges(text, node.pos));
1076
+ add(ts.getTrailingCommentRanges(text, node.end));
1077
+ };
1078
+ visit(source);
1079
+ }
1080
+ catch {
1081
+ return [];
1082
+ }
1083
+ return [...spans];
1084
+ }
955
1085
  const OWN_DIR = new Set(["import.meta.dir", "import.meta.dirname", "__dirname"]);
1086
+ /**
1087
+ * The path `relative` names from the folder of `from`, named from the folder of `to`; `undefined` when
1088
+ * neither the file nor the target moved, so a file that stays keeps its spelling.
1089
+ */
1090
+ function rebaseRelative(from, to, relative, locate) {
1091
+ const before = posix.normalize(posix.join(posix.dirname(from), relative));
1092
+ const target = locate(before);
1093
+ if (from === to && target === before)
1094
+ return undefined;
1095
+ const next = posix.relative(posix.dirname(to), target) || ".";
1096
+ return relative.endsWith("/") && next !== "." ? `${next}/` : next;
1097
+ }
1098
+ /** A shell script's own folder: `$(dirname "$0")`, `$(dirname "${BASH_SOURCE[0]}")`, `${0%/*}`. */
1099
+ const SHELL_OWN_DIR = /\$\(\s*dirname\s+("?)\$(?:0|\{BASH_SOURCE(?:\[0\])?\}|BASH_SOURCE)\1\s*\)|`dirname\s+("?)\$0\2`|\$\{(?:0|BASH_SOURCE(?:\[0\])?)%\/\*\}/g;
1100
+ const SHELL_FILE = /\.(?:sh|bash|zsh)$/;
1101
+ /**
1102
+ * Re-point the paths a shell script moving from `from` to `to` builds from its own folder
1103
+ * (`cd "$(dirname "$0")/.."`), as `rebaseOwnPaths` does for a module. Returns the new text and the
1104
+ * first use of the script's folder with no literal path after it, which the migration cannot follow.
1105
+ */
1106
+ function rebaseShellPaths(from, to, text, locate) {
1107
+ let unfollowed;
1108
+ const edits = [];
1109
+ for (const match of text.matchAll(SHELL_OWN_DIR)) {
1110
+ const start = match.index + match[0].length;
1111
+ const trailing = /^\/([\w.@-]+(?:\/[\w.@-]+)*\/?)/.exec(text.slice(start))?.[1];
1112
+ if (trailing === undefined) {
1113
+ unfollowed ??= match[0];
1114
+ continue;
1115
+ }
1116
+ const rebased = rebaseRelative(from, to, trailing, locate);
1117
+ if (rebased !== undefined)
1118
+ edits.push({ start, end: start + 1 + trailing.length, text: `/${rebased}` });
1119
+ }
1120
+ let next = text;
1121
+ for (const edit of edits.reverse())
1122
+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);
1123
+ return { text: next, unfollowed };
1124
+ }
1125
+ /**
1126
+ * Top-level `const dir = import.meta.dir` (or `.dirname`, `__dirname`) bindings, by name. A name the
1127
+ * file declares anywhere else (a parameter, an inner `let`) is left out: a use could be that binding.
1128
+ */
1129
+ function ownDirAliases(ts, sf) {
1130
+ const aliases = new Map();
1131
+ for (const statement of sf.statements) {
1132
+ if (!ts.isVariableStatement(statement))
1133
+ continue;
1134
+ if ((statement.declarationList.flags & ts.NodeFlags.Const) === 0)
1135
+ continue;
1136
+ for (const declaration of statement.declarationList.declarations) {
1137
+ const { name, initializer } = declaration;
1138
+ if (ts.isIdentifier(name) &&
1139
+ initializer !== undefined &&
1140
+ OWN_DIR.has(initializer.getText(sf)))
1141
+ aliases.set(name.text, { name, initializer });
1142
+ }
1143
+ }
1144
+ if (aliases.size === 0)
1145
+ return aliases;
1146
+ const declared = new Map();
1147
+ const count = (node) => {
1148
+ const name = ts.isVariableDeclaration(node) ||
1149
+ ts.isParameter(node) ||
1150
+ ts.isFunctionDeclaration(node) ||
1151
+ ts.isClassDeclaration(node) ||
1152
+ ts.isBindingElement(node)
1153
+ ? node.name
1154
+ : undefined;
1155
+ if (name !== undefined && ts.isIdentifier(name))
1156
+ declared.set(name.text, (declared.get(name.text) ?? 0) + 1);
1157
+ ts.forEachChild(node, count);
1158
+ };
1159
+ count(sf);
1160
+ for (const name of [...aliases.keys()])
1161
+ if (declared.get(name) !== 1)
1162
+ aliases.delete(name);
1163
+ return aliases;
1164
+ }
956
1165
  /**
957
1166
  * Re-point the paths a module moving from `from` to `to` builds from its own location, so each still
958
1167
  * reaches what it did: `join(import.meta.dir, "..", "x")` (or `resolve`), `import.meta.dir + "/../x"`,
@@ -964,22 +1173,15 @@ function rebaseOwnPaths(ts, from, to, text, locate) {
964
1173
  const sf = ts.createSourceFile(to, text, ts.ScriptTarget.Latest, true, to.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
965
1174
  const edits = [];
966
1175
  const followed = [];
967
- const isOwnDir = (node) => node !== undefined && OWN_DIR.has(node.getText(sf));
1176
+ const aliases = ownDirAliases(ts, sf);
1177
+ const isOwnDir = (node) => node !== undefined &&
1178
+ (OWN_DIR.has(node.getText(sf)) || (ts.isIdentifier(node) && aliases.has(node.text)));
968
1179
  const isLiteral = (node) => node !== undefined && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node));
969
1180
  const quoted = (node, value) => {
970
1181
  const quote = node.getText(sf)[0] ?? '"';
971
1182
  return `${quote}${value}${quote}`;
972
1183
  };
973
- // The path `relative` names from the module's old folder, named from its new folder; `undefined`
974
- // when neither moved, so a module that stays keeps its spelling.
975
- const rebased = (relative) => {
976
- const before = posix.normalize(posix.join(posix.dirname(from), relative));
977
- const target = locate(before);
978
- if (from === to && target === before)
979
- return undefined;
980
- const next = posix.relative(posix.dirname(to), target) || ".";
981
- return relative.endsWith("/") && next !== "." ? `${next}/` : next;
982
- };
1184
+ const rebased = (relative) => rebaseRelative(from, to, relative, locate);
983
1185
  const follow = (anchor, start, end, replacement) => {
984
1186
  followed.push([anchor.getStart(sf), anchor.getEnd()]);
985
1187
  if (replacement !== undefined && text.slice(start, end) !== replacement)
@@ -1040,6 +1242,20 @@ function rebaseOwnPaths(ts, from, to, text, locate) {
1040
1242
  ts.forEachChild(node, visit);
1041
1243
  };
1042
1244
  visit(sf);
1245
+ // An alias whose every use was re-pointed is followed too; one left in a call the migration cannot
1246
+ // read keeps its `import.meta.dir` unfollowed.
1247
+ for (const [name, declaration] of aliases) {
1248
+ const isFollowed = (node) => followed.some(([start, end]) => start <= node.getStart(sf) && node.getEnd() <= end);
1249
+ const uses = [];
1250
+ const collect = (node) => {
1251
+ if (ts.isIdentifier(node) && node.text === name && node !== declaration.name)
1252
+ uses.push(node);
1253
+ ts.forEachChild(node, collect);
1254
+ };
1255
+ collect(sf);
1256
+ if (uses.every(isFollowed))
1257
+ followed.push([declaration.initializer.getStart(sf), declaration.initializer.getEnd()]);
1258
+ }
1043
1259
  const unfollowed = [...text.matchAll(new RegExp(SELF_LOCATION.source, "g"))].find((match) => !followed.some(([start, end]) => start <= match.index && match.index < end))?.[0];
1044
1260
  let next = text;
1045
1261
  for (const edit of edits.sort((a, b) => b.start - a.start))
@@ -1308,18 +1524,24 @@ function workspaceSiblings(root) {
1308
1524
  * Where code in a workspace sibling names an app file that moves: a relative import into the app, or
1309
1525
  * the file's path in a string or command (`bun -e 'import("./src/x.ts")'` with the app as its working
1310
1526
  * directory). Only files that mention the app's folder or package name are read further, and a path
1311
- * the sibling's own package holds is its own file. Report-only: the migration never edits a sibling.
1527
+ * the sibling's own package holds is its own file. Every line that names a path is listed, each marked
1528
+ * when it lies only in a comment. Report-only: the migration never edits a sibling.
1312
1529
  */
1313
1530
  function siblingReferences(ts, root, pkg, file, text, moves, known, ownName) {
1314
1531
  const abs = join(pkg, file);
1315
1532
  // A process started in the app (`cwd: \`${repo}apps/web\``) reads its paths from the app root.
1316
1533
  const runsInApp = new RegExp(`\\bcwd\\s*:[^,\\n]*\\b${escapeRegExp(posix.basename(toPosix(root)))}\\b`).test(text);
1534
+ const comments = /\.[cm]?[jt]sx?$/.test(file) ? triviaCommentRanges(ts, file, text) : [];
1317
1535
  const found = new Map();
1318
- const report = (from, index) => {
1536
+ const report = (from, index, length) => {
1319
1537
  const to = moves.get(from);
1320
- if (to === undefined || found.has(from))
1538
+ if (to === undefined)
1321
1539
  return;
1322
- found.set(from, { from, to, line: text.slice(0, index).split("\n").length });
1540
+ const entry = found.get(from) ?? { to, lines: new Set(), commentLines: new Set() };
1541
+ found.set(from, entry);
1542
+ const line = text.slice(0, index).split("\n").length;
1543
+ const inComment = comments.some(([start, end]) => start <= index && index + length <= end);
1544
+ (inComment ? entry.commentLines : entry.lines).add(line);
1323
1545
  };
1324
1546
  if (/\.(?:[cm]?[jt]sx?)$/.test(file)) {
1325
1547
  for (const { specifier } of importsOf(ts, file, text)) {
@@ -1333,7 +1555,7 @@ function siblingReferences(ts, root, pkg, file, text, moves, known, ownName) {
1333
1555
  continue;
1334
1556
  const target = resolveIn(known, "index.ts", `./${inApp}`);
1335
1557
  if (target !== undefined)
1336
- report(target, text.indexOf(specifier));
1558
+ report(target, text.indexOf(specifier), specifier.length);
1337
1559
  }
1338
1560
  }
1339
1561
  for (const from of moves.keys()) {
@@ -1351,11 +1573,16 @@ function siblingReferences(ts, root, pkg, file, text, moves, known, ownName) {
1351
1573
  const own = existsSync(join(pkg, from)) || existsSync(join(dirname(abs), from));
1352
1574
  if (prefix === "" && own && !runsInApp)
1353
1575
  continue;
1354
- report(from, match.index);
1355
- break;
1576
+ report(from, match.index, match[0].length);
1356
1577
  }
1357
1578
  }
1358
- return [...found.values()];
1579
+ const byNumber = (a, b) => a - b;
1580
+ return [...found].map(([from, { to, lines, commentLines }]) => ({
1581
+ from,
1582
+ to,
1583
+ lines: [...lines].sort(byNumber),
1584
+ commentLines: [...commentLines].filter((line) => !lines.has(line)).sort(byNumber),
1585
+ }));
1359
1586
  }
1360
1587
  /** The package folder an app without its own package.json sits in (`--dir src`), at most two levels
1361
1588
  * up and never a workspace root, so the scan beside it stays inside one package. */
@@ -1830,6 +2057,21 @@ export async function migrateLayout(appRoot, options = {}) {
1830
2057
  });
1831
2058
  }
1832
2059
  }
2060
+ // What a glob loads is imported too: the files it matches go where the module that loads them goes.
2061
+ for (const call of globCalls(ts, file, text)) {
2062
+ const targets = call.literal
2063
+ ? globTargets(file, call.patterns.map((pattern) => pattern.text), known)
2064
+ : undefined;
2065
+ if (targets === undefined) {
2066
+ issues.push({
2067
+ file,
2068
+ reason: `the import.meta.glob on line ${call.line} takes a pattern the migration cannot read (computed, or not starting with ./, ../ or /), so the files it loads stay where they are; check it by hand`,
2069
+ });
2070
+ continue;
2071
+ }
2072
+ for (const target of targets)
2073
+ refs.push({ target, typeOnly: false });
2074
+ }
1833
2075
  edges.set(file, refs);
1834
2076
  }
1835
2077
  // The config's module paths are entries too: the browser loads `clientModule`.
@@ -2123,6 +2365,52 @@ export async function migrateLayout(appRoot, options = {}) {
2123
2365
  (redirectedFiles.has(file) || (updated !== text && original.get(file) === text)))
2124
2366
  rewritten.push(file);
2125
2367
  }
2368
+ // A glob names its files by pattern, which no import rewrite reads: each one must still load, from
2369
+ // the module's new folder, the files it loaded before. A pattern whose matches moved together
2370
+ // into one folder is re-pointed at it; any other change is reported.
2371
+ for (const file of next.keys()) {
2372
+ const at = newPath(file);
2373
+ const text = final.get(at);
2374
+ if (text === undefined)
2375
+ continue;
2376
+ const edits = [];
2377
+ for (const call of globCalls(ts, at, text)) {
2378
+ if (!call.literal)
2379
+ continue;
2380
+ const written = call.patterns.map((pattern) => pattern.text);
2381
+ const before = globTargets(file, written, known);
2382
+ if (before === undefined || before.length === 0)
2383
+ continue;
2384
+ const expected = before.map(newPath).sort(codeUnitOrder);
2385
+ const same = (patterns) => {
2386
+ const after = globTargets(at, patterns, planned)?.sort(codeUnitOrder);
2387
+ return after !== undefined && after.join("\n") === expected.join("\n");
2388
+ };
2389
+ if (same(written))
2390
+ continue;
2391
+ const repointed = written.map((pattern) => repointGlob(file, at, pattern, before, newPath));
2392
+ if (repointed.every((pattern) => pattern !== undefined) && same(repointed)) {
2393
+ call.patterns.forEach((pattern, index) => {
2394
+ const value = repointed[index];
2395
+ if (value !== undefined && value !== pattern.text)
2396
+ edits.push({ start: pattern.start, end: pattern.end, text: value });
2397
+ });
2398
+ continue;
2399
+ }
2400
+ issues.push({
2401
+ file: at,
2402
+ reason: `the import.meta.glob on line ${call.line} loaded ${before.length} file(s) such as "${before[0]}", which do not stay together under one folder after the moves, so its pattern cannot follow them; move them together or point the pattern at them by hand`,
2403
+ });
2404
+ }
2405
+ if (edits.length === 0)
2406
+ continue;
2407
+ let updated = text;
2408
+ for (const edit of edits.sort((a, b) => b.start - a.start))
2409
+ updated = updated.slice(0, edit.start) + edit.text + updated.slice(edit.end);
2410
+ final.set(at, updated);
2411
+ if (!moveMap.has(file) && !rewritten.includes(file))
2412
+ rewritten.push(file);
2413
+ }
2126
2414
  // A config string names its module from the app root, so it follows the module, never the config
2127
2415
  // file; a path joined onto the config's folder is re-pointed with the module's own paths below.
2128
2416
  for (const configFile of CONFIG_FILES) {
@@ -2158,7 +2446,18 @@ export async function migrateLayout(appRoot, options = {}) {
2158
2446
  // A moved module's paths from its own location now start from its new folder: re-point the ones it
2159
2447
  // spells out, and report the first one it cannot follow.
2160
2448
  const unfollowed = new Map();
2449
+ /** Moved shell scripts whose own-folder paths were re-pointed: new path -> text. */
2450
+ const scriptWrites = new Map();
2161
2451
  for (const { from, to } of moves) {
2452
+ if (SHELL_FILE.test(to) && !original.has(from)) {
2453
+ const script = readFileSync(join(root, from), "utf8");
2454
+ const result = rebaseShellPaths(from, to, script, (target) => known.has(target) ? newPath(target) : target);
2455
+ if (result.text !== script)
2456
+ scriptWrites.set(to, result.text);
2457
+ if (result.unfollowed !== undefined)
2458
+ unfollowed.set(to, result.unfollowed);
2459
+ continue;
2460
+ }
2162
2461
  const text = final.get(to);
2163
2462
  if (text === undefined || !SELF_LOCATION.test(text))
2164
2463
  continue;
@@ -2196,6 +2495,11 @@ export async function migrateLayout(appRoot, options = {}) {
2196
2495
  .filter((file) => next.has(file) || !original.has(file))
2197
2496
  .map((file) => ({ from: splitFrom.get(file) ?? file, to: newPath(file) }));
2198
2497
  const tsconfigs = followTsconfigs(ts, root, moveMap, layout);
2498
+ // The app's own package.json names files from the app root: its scripts and entry fields follow.
2499
+ const manifestPath = join(root, "package.json");
2500
+ const manifest = existsSync(manifestPath)
2501
+ ? rewritePackagePaths(ts, readFileSync(manifestPath, "utf8"), moveMap)
2502
+ : undefined;
2199
2503
  const scanned = [...final];
2200
2504
  for (const file of everyFile) {
2201
2505
  if (!original.has(file) &&
@@ -2203,17 +2507,22 @@ export async function migrateLayout(appRoot, options = {}) {
2203
2507
  statSync(join(root, file)).size <= 256_000)
2204
2508
  scanned.push([
2205
2509
  newPath(file),
2206
- tsconfigs.files.get(file)?.text ?? readFileSync(join(root, file), "utf8"),
2510
+ (file === "package.json" ? manifest?.text : undefined) ??
2511
+ tsconfigs.files.get(file)?.text ??
2512
+ readFileSync(join(root, file), "utf8"),
2207
2513
  ]);
2208
2514
  }
2515
+ // A mention only in comments is worth updating, not a decision: it never changes what runs.
2516
+ const commentFollowUps = [];
2209
2517
  for (const [file, text] of scanned) {
2210
2518
  let live;
2519
+ let comments;
2211
2520
  for (const [from, to] of moveMap) {
2212
2521
  // `shared/lib/x.ts` contains `lib/x.ts`; that is the new path, not a stale one.
2213
2522
  const newPrefix = to.endsWith(from) ? to.slice(0, to.length - from.length) : undefined;
2214
2523
  const stale = [
2215
2524
  ...text.matchAll(new RegExp(`(?<![\\w.-])${escapeRegExp(from)}(?![\\w])`, "g")),
2216
- ].some((match) => {
2525
+ ].filter((match) => {
2217
2526
  if (newPrefix !== undefined && text.slice(0, match.index).endsWith(newPrefix))
2218
2527
  return false;
2219
2528
  // An import that resolves after the moves is current, even when it still reads like the old
@@ -2222,7 +2531,13 @@ export async function migrateLayout(appRoot, options = {}) {
2222
2531
  const end = match.index + from.length;
2223
2532
  return !live.some(([start, stop]) => start <= match.index && end <= stop);
2224
2533
  });
2225
- if (stale)
2534
+ if (stale.length === 0)
2535
+ continue;
2536
+ comments ??= /\.[cm]?[jt]sx?$/.test(file) ? triviaCommentRanges(ts, file, text) : [];
2537
+ const inComments = stale.every((match) => comments?.some(([start, stop]) => start <= match.index && match.index + from.length <= stop));
2538
+ if (inComments)
2539
+ commentFollowUps.push({ file, reason: `a comment names "${from}", which moved to "${to}"` });
2540
+ else
2226
2541
  issues.push({ file, reason: `mentions "${from}" by path; it moved to "${to}"` });
2227
2542
  }
2228
2543
  }
@@ -2273,11 +2588,19 @@ export async function migrateLayout(appRoot, options = {}) {
2273
2588
  if (!mentionsApp.test(text) && (ownName === undefined || !text.includes(`${ownName}/`)))
2274
2589
  continue;
2275
2590
  const at = toPosix(relative(root, join(sibling, file)));
2276
- for (const { from, to, line } of siblingReferences(ts, root, sibling, file, text, moveMap, known, ownName)) {
2277
- issues.push({
2278
- file: at,
2279
- reason: `names "${from}" on line ${line}, and it moves to "${to}" - it is outside the app, so the migration does not rewrite it`,
2280
- });
2591
+ const onLines = (lines) => `on line${lines.length === 1 ? "" : "s"} ${lines.join(", ")}`;
2592
+ for (const { from, to, lines, commentLines } of siblingReferences(ts, root, sibling, file, text, moveMap, known, ownName)) {
2593
+ const comments = commentLines.length === 0 ? "" : ` (and in a comment ${onLines(commentLines)})`;
2594
+ if (lines.length > 0)
2595
+ issues.push({
2596
+ file: at,
2597
+ reason: `names "${from}" ${onLines(lines)}${comments}, and it moves to "${to}" - it is outside the app, so the migration does not rewrite it`,
2598
+ });
2599
+ else
2600
+ commentFollowUps.push({
2601
+ file: at,
2602
+ reason: `a comment ${onLines(commentLines)} names "${from}", which moved to "${to}"`,
2603
+ });
2281
2604
  }
2282
2605
  }
2283
2606
  }
@@ -2329,7 +2652,7 @@ export async function migrateLayout(appRoot, options = {}) {
2329
2652
  for (const [file, text] of schemaPlan?.edits ?? [])
2330
2653
  final.set(file, text);
2331
2654
  const schemas = (schemaPlan?.entries ?? []).filter((entry) => entry.status === "missing");
2332
- const followUps = [];
2655
+ const followUps = [...commentFollowUps];
2333
2656
  for (const [file, text] of final) {
2334
2657
  if (!file.startsWith("routes/") || !/\.backend\.[cm]?[jt]s$/.test(file))
2335
2658
  continue;
@@ -2410,6 +2733,14 @@ export async function migrateLayout(appRoot, options = {}) {
2410
2733
  toolingWrites.set("package.json", kind.text);
2411
2734
  tooling.push({ file: "package.json", change: '"nifra": { "kind": "api" }' });
2412
2735
  }
2736
+ if (manifest !== undefined && manifest.count > 0) {
2737
+ const current = toolingWrites.get("package.json") ?? readFileSync(manifestPath, "utf8");
2738
+ toolingWrites.set("package.json", rewritePackagePaths(ts, current, moveMap).text);
2739
+ tooling.push({
2740
+ file: "package.json",
2741
+ change: `${manifest.count} file path(s) in scripts and entry fields follow their moved files`,
2742
+ });
2743
+ }
2413
2744
  if (options.write === true) {
2414
2745
  for (const [file, text] of toolingWrites)
2415
2746
  writeFileSync(join(root, file), text);
@@ -2434,6 +2765,8 @@ export async function migrateLayout(appRoot, options = {}) {
2434
2765
  renameSync(join(root, from), join(root, to));
2435
2766
  vacated.push(from);
2436
2767
  }
2768
+ for (const [file, text] of scriptWrites)
2769
+ writeFileSync(join(root, file), text);
2437
2770
  pruneVacatedDirs(root, vacated);
2438
2771
  }
2439
2772
  return {
@@ -2894,6 +3227,78 @@ function declareApiKind(ts, root) {
2894
3227
  return { issue: '"nifra" is not an object; add "kind": "api" to it by hand' };
2895
3228
  return { text: insertProperty(source, text, nifra.initializer, '"kind": "api"') };
2896
3229
  }
3230
+ /** package.json fields whose string values name files from the package folder. */
3231
+ const PACKAGE_PATH_FIELDS = new Set([
3232
+ "main",
3233
+ "module",
3234
+ "types",
3235
+ "typings",
3236
+ "browser",
3237
+ "source",
3238
+ "bin",
3239
+ "exports",
3240
+ "imports",
3241
+ "files",
3242
+ "scripts",
3243
+ ]);
3244
+ /**
3245
+ * `text` (a package.json at the app root) with each moved file it names by its exact path, in the
3246
+ * fields above, named at its new path; `./` kept as written. A value with a `*` outside `scripts` is a
3247
+ * pattern over a folder, which no single move settles, so it stays and the path scan reports it.
3248
+ */
3249
+ function rewritePackagePaths(ts, text, moves) {
3250
+ const source = ts.parseJsonText("package.json", text);
3251
+ const top = source.statements[0]?.expression;
3252
+ if (top === undefined || !ts.isObjectLiteralExpression(top) || moves.size === 0)
3253
+ return { text, count: 0 };
3254
+ // Longest first, so `lib/a.test.ts` is not read as `lib/a.ts` with a tail.
3255
+ const ordered = [...moves].sort(([a], [b]) => b.length - a.length);
3256
+ const pattern = new RegExp(`(?<![\\w.@/-])(\\./)?(${ordered.map(([from]) => escapeRegExp(from)).join("|")})(?![\\w/-]|\\.\\w)`, "g");
3257
+ const edits = [];
3258
+ let count = 0;
3259
+ const visit = (node, field) => {
3260
+ if (ts.isStringLiteral(node)) {
3261
+ if (field !== "scripts" && node.text.includes("*"))
3262
+ return;
3263
+ const value = node.text.replace(pattern, (_match, dot, from) => {
3264
+ count += 1;
3265
+ return `${dot ?? ""}${moves.get(from) ?? from}`;
3266
+ });
3267
+ if (value !== node.text)
3268
+ edits.push({
3269
+ start: node.getStart(source),
3270
+ end: node.getEnd(),
3271
+ text: JSON.stringify(value),
3272
+ });
3273
+ return;
3274
+ }
3275
+ if (ts.isArrayLiteralExpression(node)) {
3276
+ for (const element of node.elements)
3277
+ visit(element, field);
3278
+ return;
3279
+ }
3280
+ if (!ts.isObjectLiteralExpression(node))
3281
+ return;
3282
+ for (const property of node.properties) {
3283
+ if (!ts.isPropertyAssignment(property))
3284
+ continue;
3285
+ // `"//x"` keys are comments by npm convention.
3286
+ if (ts.isStringLiteral(property.name) && property.name.text.startsWith("//"))
3287
+ continue;
3288
+ visit(property.initializer, field);
3289
+ }
3290
+ };
3291
+ for (const property of top.properties) {
3292
+ if (!ts.isPropertyAssignment(property) || !ts.isStringLiteral(property.name))
3293
+ continue;
3294
+ if (PACKAGE_PATH_FIELDS.has(property.name.text))
3295
+ visit(property.initializer, property.name.text);
3296
+ }
3297
+ let next = text;
3298
+ for (const edit of edits.sort((a, b) => b.start - a.start))
3299
+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);
3300
+ return { text: next, count };
3301
+ }
2897
3302
  /** Tailwind `content` globs that matched a moved file at its old path and match nothing at its new one. */
2898
3303
  function staleContentGlobs(ts, text, moves) {
2899
3304
  const globs = [];