@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
@@ -74,7 +74,8 @@ const LEGACY_SERVER = /\.server(\.(?:[cm]?[jt]sx?|svelte|vue|mdx))$/
74
74
  const RETIRED_SPECIFIERS: Readonly<Record<string, string>> = {
75
75
  "@nifrajs/web/server-only": "@nifrajs/web/backend-only",
76
76
  }
77
- /** Scripts and config that name app files by path: scanned for paths that moved, never rewritten. */
77
+ /** Scripts and config that name app files by path: scanned for paths that moved. Only the app's own
78
+ * package.json is rewritten, in the fields `rewritePackagePaths` reads. */
78
79
  const TOOLING_FILE =
79
80
  /(?:\.(?:json|jsonc|ya?ml|toml|sh|bash|zsh|ps1)|(?:^|\/)(?:Dockerfile|Makefile|Procfile))$/
80
81
  const SELF_LOCATION = /\bimport\.meta\.(?:dirname|dir|filename|url)\b|\b__(?:dirname|filename)\b/
@@ -121,7 +122,8 @@ export interface LayoutMigrationIssue {
121
122
  export interface LayoutMigrationFollowUp {
122
123
  readonly file: string
123
124
  readonly reason: string
124
- readonly command: string
125
+ /** The command that settles it; absent when the step is an edit, such as a comment to update. */
126
+ readonly command?: string
125
127
  }
126
128
 
127
129
  export interface LayoutMigrationResult {
@@ -1134,6 +1136,129 @@ function importsOf(ts: typeof TS, file: string, text: string): ImportRef[] {
1134
1136
  return refs
1135
1137
  }
1136
1138
 
1139
+ /** One `import.meta.glob(...)` call and the spans of its pattern literals, quotes excluded. */
1140
+ interface GlobCall {
1141
+ readonly patterns: ReadonlyArray<{
1142
+ readonly text: string
1143
+ readonly start: number
1144
+ readonly end: number
1145
+ }>
1146
+ /** `false` when a pattern is computed, so what the call loads cannot be read. */
1147
+ readonly literal: boolean
1148
+ readonly line: number
1149
+ }
1150
+
1151
+ /** The `import.meta.glob` calls of a JS/TS module. */
1152
+ function globCalls(ts: typeof TS, file: string, text: string): GlobCall[] {
1153
+ if (!/\.[cm]?[jt]sx?$/.test(file) || !text.includes("import.meta.glob")) return []
1154
+ const sf = ts.createSourceFile(
1155
+ file,
1156
+ text,
1157
+ ts.ScriptTarget.Latest,
1158
+ true,
1159
+ file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
1160
+ )
1161
+ const calls: GlobCall[] = []
1162
+ const visit = (node: TS.Node): void => {
1163
+ if (
1164
+ ts.isCallExpression(node) &&
1165
+ ts.isPropertyAccessExpression(node.expression) &&
1166
+ node.expression.name.text === "glob" &&
1167
+ ts.isMetaProperty(node.expression.expression) &&
1168
+ node.expression.expression.keywordToken === ts.SyntaxKind.ImportKeyword
1169
+ ) {
1170
+ const arg = node.arguments[0]
1171
+ const elements =
1172
+ arg === undefined ? [] : ts.isArrayLiteralExpression(arg) ? [...arg.elements] : [arg]
1173
+ const literals = elements.filter(ts.isStringLiteralLike)
1174
+ const literal = literals.length > 0 && literals.length === elements.length
1175
+ calls.push({
1176
+ patterns: literal
1177
+ ? literals.map((element) => ({
1178
+ text: element.text,
1179
+ start: element.getStart(sf) + 1,
1180
+ end: element.getEnd() - 1,
1181
+ }))
1182
+ : [],
1183
+ literal,
1184
+ line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1,
1185
+ })
1186
+ }
1187
+ ts.forEachChild(node, visit)
1188
+ }
1189
+ visit(sf)
1190
+ return calls
1191
+ }
1192
+
1193
+ /** A glob pattern written in `file` as an app-relative glob, by Vite's rules: `./` and `../` from the
1194
+ * file's folder, `/` from the app root. `undefined` for any other shape, such as an alias. */
1195
+ function appGlob(file: string, pattern: string): string | undefined {
1196
+ if (pattern.startsWith("/")) return pattern.slice(1)
1197
+ if (!pattern.startsWith("./") && !pattern.startsWith("../")) return undefined
1198
+ const at = posix.normalize(posix.join(posix.dirname(file), pattern))
1199
+ return at.startsWith("../") ? undefined : at
1200
+ }
1201
+
1202
+ /** The files among `files` a glob call in `file` loads, a `!` pattern excluding; `undefined` when a
1203
+ * pattern cannot be read from the app. */
1204
+ function globTargets(
1205
+ file: string,
1206
+ patterns: readonly string[],
1207
+ files: Iterable<string>,
1208
+ ): string[] | undefined {
1209
+ const include: Bun.Glob[] = []
1210
+ const exclude: Bun.Glob[] = []
1211
+ for (const raw of patterns) {
1212
+ const at = appGlob(file, raw.startsWith("!") ? raw.slice(1) : raw)
1213
+ if (at === undefined) return undefined
1214
+ ;(raw.startsWith("!") ? exclude : include).push(new Bun.Glob(at))
1215
+ }
1216
+ return [...files].filter(
1217
+ (candidate) =>
1218
+ candidate !== file &&
1219
+ include.some((glob) => glob.match(candidate)) &&
1220
+ !exclude.some((glob) => glob.match(candidate)),
1221
+ )
1222
+ }
1223
+
1224
+ /**
1225
+ * `pattern`, written in `from` (now `to`), re-pointed at the folder its matches `before` moved to: the
1226
+ * part before the first wildcard is the folder, and every match must keep its path below it.
1227
+ * `undefined` when the matches did not move as one folder.
1228
+ */
1229
+ function repointGlob(
1230
+ from: string,
1231
+ to: string,
1232
+ pattern: string,
1233
+ before: readonly string[],
1234
+ newPath: (file: string) => string,
1235
+ ): string | undefined {
1236
+ const negated = pattern.startsWith("!")
1237
+ const written = negated ? pattern.slice(1) : pattern
1238
+ const at = appGlob(from, written)
1239
+ if (at === undefined) return undefined
1240
+ const segments = at.split("/")
1241
+ const wild = segments.findIndex((segment) => /[*?[\]{}]/.test(segment))
1242
+ const base = (wild === -1 ? segments.slice(0, -1) : segments.slice(0, wild)).join("/")
1243
+ const rest = segments.slice(base === "" ? 0 : base.split("/").length).join("/")
1244
+ let moved: string | undefined
1245
+ for (const file of before) {
1246
+ if (base !== "" && !file.startsWith(`${base}/`)) continue
1247
+ const tail = base === "" ? file : file.slice(base.length + 1)
1248
+ const now = newPath(file)
1249
+ if (!now.endsWith(`/${tail}`) && now !== tail) return undefined
1250
+ const folder = now === tail ? "" : now.slice(0, now.length - tail.length - 1)
1251
+ if (moved !== undefined && folder !== moved) return undefined
1252
+ moved = folder
1253
+ }
1254
+ if (moved === undefined) return pattern
1255
+ const folder = posix.relative(posix.dirname(to), moved)
1256
+ const next = written.startsWith("/")
1257
+ ? `/${moved === "" ? "" : `${moved}/`}${rest}`
1258
+ : `${folder === "" ? "." : folder.startsWith("..") ? folder : `./${folder}`}/${rest}`
1259
+ return negated ? `!${next}` : next
1260
+ }
1261
+
1137
1262
  /** Resolve a relative specifier against the file map, the way a bundler would. */
1138
1263
  function resolveIn(
1139
1264
  files: ReadonlySet<string>,
@@ -1176,8 +1301,140 @@ function liveSpecifierSpans(
1176
1301
  return spans
1177
1302
  }
1178
1303
 
1304
+ /**
1305
+ * The comment spans of a JS/TS module: the leading and trailing trivia of each token. Empty when the
1306
+ * compiler cannot walk the tokens, so every mention in the file stays an issue.
1307
+ */
1308
+ function triviaCommentRanges(
1309
+ ts: typeof TS,
1310
+ file: string,
1311
+ text: string,
1312
+ ): Array<readonly [number, number]> {
1313
+ const spans = new Map<number, number>()
1314
+ const add = (ranges: readonly TS.CommentRange[] | undefined): void => {
1315
+ for (const range of ranges ?? []) spans.set(range.pos, range.end)
1316
+ }
1317
+ try {
1318
+ const kind = /x$/.test(file) ? ts.ScriptKind.TSX : ts.ScriptKind.TS
1319
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind)
1320
+ const visit = (node: TS.Node): void => {
1321
+ // A JSDoc block is itself one of the comments its token's trivia holds; JSX text is not trivia.
1322
+ if (node.kind >= ts.SyntaxKind.FirstJSDocNode && node.kind <= ts.SyntaxKind.LastJSDocNode)
1323
+ return
1324
+ if (ts.isJsxText(node)) return
1325
+ const children = node.getChildren(source)
1326
+ if (children.length > 0) {
1327
+ for (const child of children) visit(child)
1328
+ return
1329
+ }
1330
+ add(ts.getLeadingCommentRanges(text, node.pos))
1331
+ add(ts.getTrailingCommentRanges(text, node.end))
1332
+ }
1333
+ visit(source)
1334
+ } catch {
1335
+ return []
1336
+ }
1337
+ return [...spans]
1338
+ }
1339
+
1179
1340
  const OWN_DIR = new Set(["import.meta.dir", "import.meta.dirname", "__dirname"])
1180
1341
 
1342
+ /**
1343
+ * The path `relative` names from the folder of `from`, named from the folder of `to`; `undefined` when
1344
+ * neither the file nor the target moved, so a file that stays keeps its spelling.
1345
+ */
1346
+ function rebaseRelative(
1347
+ from: string,
1348
+ to: string,
1349
+ relative: string,
1350
+ locate: (target: string) => string,
1351
+ ): string | undefined {
1352
+ const before = posix.normalize(posix.join(posix.dirname(from), relative))
1353
+ const target = locate(before)
1354
+ if (from === to && target === before) return undefined
1355
+ const next = posix.relative(posix.dirname(to), target) || "."
1356
+ return relative.endsWith("/") && next !== "." ? `${next}/` : next
1357
+ }
1358
+
1359
+ /** A shell script's own folder: `$(dirname "$0")`, `$(dirname "${BASH_SOURCE[0]}")`, `${0%/*}`. */
1360
+ const SHELL_OWN_DIR =
1361
+ /\$\(\s*dirname\s+("?)\$(?:0|\{BASH_SOURCE(?:\[0\])?\}|BASH_SOURCE)\1\s*\)|`dirname\s+("?)\$0\2`|\$\{(?:0|BASH_SOURCE(?:\[0\])?)%\/\*\}/g
1362
+ const SHELL_FILE = /\.(?:sh|bash|zsh)$/
1363
+
1364
+ /**
1365
+ * Re-point the paths a shell script moving from `from` to `to` builds from its own folder
1366
+ * (`cd "$(dirname "$0")/.."`), as `rebaseOwnPaths` does for a module. Returns the new text and the
1367
+ * first use of the script's folder with no literal path after it, which the migration cannot follow.
1368
+ */
1369
+ function rebaseShellPaths(
1370
+ from: string,
1371
+ to: string,
1372
+ text: string,
1373
+ locate: (target: string) => string,
1374
+ ): { readonly text: string; readonly unfollowed: string | undefined } {
1375
+ let unfollowed: string | undefined
1376
+ const edits: Array<{ start: number; end: number; text: string }> = []
1377
+ for (const match of text.matchAll(SHELL_OWN_DIR)) {
1378
+ const start = match.index + match[0].length
1379
+ const trailing = /^\/([\w.@-]+(?:\/[\w.@-]+)*\/?)/.exec(text.slice(start))?.[1]
1380
+ if (trailing === undefined) {
1381
+ unfollowed ??= match[0]
1382
+ continue
1383
+ }
1384
+ const rebased = rebaseRelative(from, to, trailing, locate)
1385
+ if (rebased !== undefined)
1386
+ edits.push({ start, end: start + 1 + trailing.length, text: `/${rebased}` })
1387
+ }
1388
+ let next = text
1389
+ for (const edit of edits.reverse())
1390
+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end)
1391
+ return { text: next, unfollowed }
1392
+ }
1393
+
1394
+ interface OwnDirAlias {
1395
+ readonly name: TS.Identifier
1396
+ readonly initializer: TS.Expression
1397
+ }
1398
+
1399
+ /**
1400
+ * Top-level `const dir = import.meta.dir` (or `.dirname`, `__dirname`) bindings, by name. A name the
1401
+ * file declares anywhere else (a parameter, an inner `let`) is left out: a use could be that binding.
1402
+ */
1403
+ function ownDirAliases(ts: typeof TS, sf: TS.SourceFile): Map<string, OwnDirAlias> {
1404
+ const aliases = new Map<string, OwnDirAlias>()
1405
+ for (const statement of sf.statements) {
1406
+ if (!ts.isVariableStatement(statement)) continue
1407
+ if ((statement.declarationList.flags & ts.NodeFlags.Const) === 0) continue
1408
+ for (const declaration of statement.declarationList.declarations) {
1409
+ const { name, initializer } = declaration
1410
+ if (
1411
+ ts.isIdentifier(name) &&
1412
+ initializer !== undefined &&
1413
+ OWN_DIR.has(initializer.getText(sf))
1414
+ )
1415
+ aliases.set(name.text, { name, initializer })
1416
+ }
1417
+ }
1418
+ if (aliases.size === 0) return aliases
1419
+ const declared = new Map<string, number>()
1420
+ const count = (node: TS.Node): void => {
1421
+ const name =
1422
+ ts.isVariableDeclaration(node) ||
1423
+ ts.isParameter(node) ||
1424
+ ts.isFunctionDeclaration(node) ||
1425
+ ts.isClassDeclaration(node) ||
1426
+ ts.isBindingElement(node)
1427
+ ? node.name
1428
+ : undefined
1429
+ if (name !== undefined && ts.isIdentifier(name))
1430
+ declared.set(name.text, (declared.get(name.text) ?? 0) + 1)
1431
+ ts.forEachChild(node, count)
1432
+ }
1433
+ count(sf)
1434
+ for (const name of [...aliases.keys()]) if (declared.get(name) !== 1) aliases.delete(name)
1435
+ return aliases
1436
+ }
1437
+
1181
1438
  /**
1182
1439
  * Re-point the paths a module moving from `from` to `to` builds from its own location, so each still
1183
1440
  * reaches what it did: `join(import.meta.dir, "..", "x")` (or `resolve`), `import.meta.dir + "/../x"`,
@@ -1201,8 +1458,10 @@ function rebaseOwnPaths(
1201
1458
  )
1202
1459
  const edits: Array<{ start: number; end: number; text: string }> = []
1203
1460
  const followed: Array<readonly [number, number]> = []
1461
+ const aliases = ownDirAliases(ts, sf)
1204
1462
  const isOwnDir = (node: TS.Node | undefined): node is TS.Expression =>
1205
- node !== undefined && OWN_DIR.has(node.getText(sf))
1463
+ node !== undefined &&
1464
+ (OWN_DIR.has(node.getText(sf)) || (ts.isIdentifier(node) && aliases.has(node.text)))
1206
1465
  const isLiteral = (
1207
1466
  node: TS.Node | undefined,
1208
1467
  ): node is TS.StringLiteral | TS.NoSubstitutionTemplateLiteral =>
@@ -1211,15 +1470,8 @@ function rebaseOwnPaths(
1211
1470
  const quote = node.getText(sf)[0] ?? '"'
1212
1471
  return `${quote}${value}${quote}`
1213
1472
  }
1214
- // The path `relative` names from the module's old folder, named from its new folder; `undefined`
1215
- // when neither moved, so a module that stays keeps its spelling.
1216
- const rebased = (relative: string): string | undefined => {
1217
- const before = posix.normalize(posix.join(posix.dirname(from), relative))
1218
- const target = locate(before)
1219
- if (from === to && target === before) return undefined
1220
- const next = posix.relative(posix.dirname(to), target) || "."
1221
- return relative.endsWith("/") && next !== "." ? `${next}/` : next
1222
- }
1473
+ const rebased = (relative: string): string | undefined =>
1474
+ rebaseRelative(from, to, relative, locate)
1223
1475
  const follow = (
1224
1476
  anchor: TS.Node,
1225
1477
  start: number,
@@ -1300,6 +1552,20 @@ function rebaseOwnPaths(
1300
1552
  ts.forEachChild(node, visit)
1301
1553
  }
1302
1554
  visit(sf)
1555
+ // An alias whose every use was re-pointed is followed too; one left in a call the migration cannot
1556
+ // read keeps its `import.meta.dir` unfollowed.
1557
+ for (const [name, declaration] of aliases) {
1558
+ const isFollowed = (node: TS.Node): boolean =>
1559
+ followed.some(([start, end]) => start <= node.getStart(sf) && node.getEnd() <= end)
1560
+ const uses: TS.Identifier[] = []
1561
+ const collect = (node: TS.Node): void => {
1562
+ if (ts.isIdentifier(node) && node.text === name && node !== declaration.name) uses.push(node)
1563
+ ts.forEachChild(node, collect)
1564
+ }
1565
+ collect(sf)
1566
+ if (uses.every(isFollowed))
1567
+ followed.push([declaration.initializer.getStart(sf), declaration.initializer.getEnd()])
1568
+ }
1303
1569
 
1304
1570
  const unfollowed = [...text.matchAll(new RegExp(SELF_LOCATION.source, "g"))].find(
1305
1571
  (match) => !followed.some(([start, end]) => start <= match.index && match.index < end),
@@ -1623,7 +1889,8 @@ function workspaceSiblings(root: string): readonly string[] | undefined {
1623
1889
  * Where code in a workspace sibling names an app file that moves: a relative import into the app, or
1624
1890
  * the file's path in a string or command (`bun -e 'import("./src/x.ts")'` with the app as its working
1625
1891
  * directory). Only files that mention the app's folder or package name are read further, and a path
1626
- * the sibling's own package holds is its own file. Report-only: the migration never edits a sibling.
1892
+ * the sibling's own package holds is its own file. Every line that names a path is listed, each marked
1893
+ * when it lies only in a comment. Report-only: the migration never edits a sibling.
1627
1894
  */
1628
1895
  function siblingReferences(
1629
1896
  ts: typeof TS,
@@ -1634,17 +1901,27 @@ function siblingReferences(
1634
1901
  moves: ReadonlyMap<string, string>,
1635
1902
  known: ReadonlySet<string>,
1636
1903
  ownName: string | undefined,
1637
- ): Array<{ readonly from: string; readonly to: string; readonly line: number }> {
1904
+ ): Array<{
1905
+ readonly from: string
1906
+ readonly to: string
1907
+ readonly lines: readonly number[]
1908
+ readonly commentLines: readonly number[]
1909
+ }> {
1638
1910
  const abs = join(pkg, file)
1639
1911
  // A process started in the app (`cwd: \`${repo}apps/web\``) reads its paths from the app root.
1640
1912
  const runsInApp = new RegExp(
1641
1913
  `\\bcwd\\s*:[^,\\n]*\\b${escapeRegExp(posix.basename(toPosix(root)))}\\b`,
1642
1914
  ).test(text)
1643
- const found = new Map<string, { from: string; to: string; line: number }>()
1644
- const report = (from: string, index: number): void => {
1915
+ const comments = /\.[cm]?[jt]sx?$/.test(file) ? triviaCommentRanges(ts, file, text) : []
1916
+ const found = new Map<string, { to: string; lines: Set<number>; commentLines: Set<number> }>()
1917
+ const report = (from: string, index: number, length: number): void => {
1645
1918
  const to = moves.get(from)
1646
- if (to === undefined || found.has(from)) return
1647
- found.set(from, { from, to, line: text.slice(0, index).split("\n").length })
1919
+ if (to === undefined) return
1920
+ const entry = found.get(from) ?? { to, lines: new Set(), commentLines: new Set() }
1921
+ found.set(from, entry)
1922
+ const line = text.slice(0, index).split("\n").length
1923
+ const inComment = comments.some(([start, end]) => start <= index && index + length <= end)
1924
+ ;(inComment ? entry.commentLines : entry.lines).add(line)
1648
1925
  }
1649
1926
  if (/\.(?:[cm]?[jt]sx?)$/.test(file)) {
1650
1927
  for (const { specifier } of importsOf(ts, file, text)) {
@@ -1656,7 +1933,7 @@ function siblingReferences(
1656
1933
  : undefined
1657
1934
  if (inApp === undefined || inApp.startsWith("../") || isAbsolute(inApp)) continue
1658
1935
  const target = resolveIn(known, "index.ts", `./${inApp}`)
1659
- if (target !== undefined) report(target, text.indexOf(specifier))
1936
+ if (target !== undefined) report(target, text.indexOf(specifier), specifier.length)
1660
1937
  }
1661
1938
  }
1662
1939
  for (const from of moves.keys()) {
@@ -1675,11 +1952,16 @@ function siblingReferences(
1675
1952
  if (prefix !== "" && !bases.some((base) => resolve(base, prefix) === root)) continue
1676
1953
  const own = existsSync(join(pkg, from)) || existsSync(join(dirname(abs), from))
1677
1954
  if (prefix === "" && own && !runsInApp) continue
1678
- report(from, match.index)
1679
- break
1955
+ report(from, match.index, match[0].length)
1680
1956
  }
1681
1957
  }
1682
- return [...found.values()]
1958
+ const byNumber = (a: number, b: number): number => a - b
1959
+ return [...found].map(([from, { to, lines, commentLines }]) => ({
1960
+ from,
1961
+ to,
1962
+ lines: [...lines].sort(byNumber),
1963
+ commentLines: [...commentLines].filter((line) => !lines.has(line)).sort(byNumber),
1964
+ }))
1683
1965
  }
1684
1966
 
1685
1967
  /** The package folder an app without its own package.json sits in (`--dir src`), at most two levels
@@ -2201,6 +2483,24 @@ export async function migrateLayout(
2201
2483
  })
2202
2484
  }
2203
2485
  }
2486
+ // What a glob loads is imported too: the files it matches go where the module that loads them goes.
2487
+ for (const call of globCalls(ts, file, text)) {
2488
+ const targets = call.literal
2489
+ ? globTargets(
2490
+ file,
2491
+ call.patterns.map((pattern) => pattern.text),
2492
+ known,
2493
+ )
2494
+ : undefined
2495
+ if (targets === undefined) {
2496
+ issues.push({
2497
+ file,
2498
+ 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`,
2499
+ })
2500
+ continue
2501
+ }
2502
+ for (const target of targets) refs.push({ target, typeOnly: false })
2503
+ }
2204
2504
  edges.set(file, refs)
2205
2505
  }
2206
2506
  // The config's module paths are entries too: the browser loads `clientModule`.
@@ -2513,6 +2813,47 @@ export async function migrateLayout(
2513
2813
  rewritten.push(file)
2514
2814
  }
2515
2815
 
2816
+ // A glob names its files by pattern, which no import rewrite reads: each one must still load, from
2817
+ // the module's new folder, the files it loaded before. A pattern whose matches moved together
2818
+ // into one folder is re-pointed at it; any other change is reported.
2819
+ for (const file of next.keys()) {
2820
+ const at = newPath(file)
2821
+ const text = final.get(at)
2822
+ if (text === undefined) continue
2823
+ const edits: Array<{ start: number; end: number; text: string }> = []
2824
+ for (const call of globCalls(ts, at, text)) {
2825
+ if (!call.literal) continue
2826
+ const written = call.patterns.map((pattern) => pattern.text)
2827
+ const before = globTargets(file, written, known)
2828
+ if (before === undefined || before.length === 0) continue
2829
+ const expected = before.map(newPath).sort(codeUnitOrder)
2830
+ const same = (patterns: readonly string[]): boolean => {
2831
+ const after = globTargets(at, patterns, planned)?.sort(codeUnitOrder)
2832
+ return after !== undefined && after.join("\n") === expected.join("\n")
2833
+ }
2834
+ if (same(written)) continue
2835
+ const repointed = written.map((pattern) => repointGlob(file, at, pattern, before, newPath))
2836
+ if (repointed.every((pattern) => pattern !== undefined) && same(repointed)) {
2837
+ call.patterns.forEach((pattern, index) => {
2838
+ const value = repointed[index]
2839
+ if (value !== undefined && value !== pattern.text)
2840
+ edits.push({ start: pattern.start, end: pattern.end, text: value })
2841
+ })
2842
+ continue
2843
+ }
2844
+ issues.push({
2845
+ file: at,
2846
+ 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`,
2847
+ })
2848
+ }
2849
+ if (edits.length === 0) continue
2850
+ let updated = text
2851
+ for (const edit of edits.sort((a, b) => b.start - a.start))
2852
+ updated = updated.slice(0, edit.start) + edit.text + updated.slice(edit.end)
2853
+ final.set(at, updated)
2854
+ if (!moveMap.has(file) && !rewritten.includes(file)) rewritten.push(file)
2855
+ }
2856
+
2516
2857
  // A config string names its module from the app root, so it follows the module, never the config
2517
2858
  // file; a path joined onto the config's folder is re-pointed with the module's own paths below.
2518
2859
  for (const configFile of CONFIG_FILES) {
@@ -2544,7 +2885,18 @@ export async function migrateLayout(
2544
2885
  // A moved module's paths from its own location now start from its new folder: re-point the ones it
2545
2886
  // spells out, and report the first one it cannot follow.
2546
2887
  const unfollowed = new Map<string, string>()
2888
+ /** Moved shell scripts whose own-folder paths were re-pointed: new path -> text. */
2889
+ const scriptWrites = new Map<string, string>()
2547
2890
  for (const { from, to } of moves) {
2891
+ if (SHELL_FILE.test(to) && !original.has(from)) {
2892
+ const script = readFileSync(join(root, from), "utf8")
2893
+ const result = rebaseShellPaths(from, to, script, (target) =>
2894
+ known.has(target) ? newPath(target) : target,
2895
+ )
2896
+ if (result.text !== script) scriptWrites.set(to, result.text)
2897
+ if (result.unfollowed !== undefined) unfollowed.set(to, result.unfollowed)
2898
+ continue
2899
+ }
2548
2900
  const text = final.get(to)
2549
2901
  if (text === undefined || !SELF_LOCATION.test(text)) continue
2550
2902
  if (!/\.[cm]?[jt]sx?$/.test(to)) {
@@ -2584,6 +2936,11 @@ export async function migrateLayout(
2584
2936
  .filter((file) => next.has(file) || !original.has(file))
2585
2937
  .map((file) => ({ from: splitFrom.get(file) ?? file, to: newPath(file) }))
2586
2938
  const tsconfigs = followTsconfigs(ts, root, moveMap, layout)
2939
+ // The app's own package.json names files from the app root: its scripts and entry fields follow.
2940
+ const manifestPath = join(root, "package.json")
2941
+ const manifest = existsSync(manifestPath)
2942
+ ? rewritePackagePaths(ts, readFileSync(manifestPath, "utf8"), moveMap)
2943
+ : undefined
2587
2944
  const scanned: Array<readonly [string, string]> = [...final]
2588
2945
  for (const file of everyFile) {
2589
2946
  if (
@@ -2593,17 +2950,22 @@ export async function migrateLayout(
2593
2950
  )
2594
2951
  scanned.push([
2595
2952
  newPath(file),
2596
- tsconfigs.files.get(file)?.text ?? readFileSync(join(root, file), "utf8"),
2953
+ (file === "package.json" ? manifest?.text : undefined) ??
2954
+ tsconfigs.files.get(file)?.text ??
2955
+ readFileSync(join(root, file), "utf8"),
2597
2956
  ])
2598
2957
  }
2958
+ // A mention only in comments is worth updating, not a decision: it never changes what runs.
2959
+ const commentFollowUps: LayoutMigrationFollowUp[] = []
2599
2960
  for (const [file, text] of scanned) {
2600
2961
  let live: ReadonlyArray<readonly [number, number]> | undefined
2962
+ let comments: ReadonlyArray<readonly [number, number]> | undefined
2601
2963
  for (const [from, to] of moveMap) {
2602
2964
  // `shared/lib/x.ts` contains `lib/x.ts`; that is the new path, not a stale one.
2603
2965
  const newPrefix = to.endsWith(from) ? to.slice(0, to.length - from.length) : undefined
2604
2966
  const stale = [
2605
2967
  ...text.matchAll(new RegExp(`(?<![\\w.-])${escapeRegExp(from)}(?![\\w])`, "g")),
2606
- ].some((match) => {
2968
+ ].filter((match) => {
2607
2969
  if (newPrefix !== undefined && text.slice(0, match.index).endsWith(newPrefix)) return false
2608
2970
  // An import that resolves after the moves is current, even when it still reads like the old
2609
2971
  // path: `./x.json` from a module that moved together with `x.json`.
@@ -2611,7 +2973,16 @@ export async function migrateLayout(
2611
2973
  const end = match.index + from.length
2612
2974
  return !live.some(([start, stop]) => start <= match.index && end <= stop)
2613
2975
  })
2614
- if (stale) issues.push({ file, reason: `mentions "${from}" by path; it moved to "${to}"` })
2976
+ if (stale.length === 0) continue
2977
+ comments ??= /\.[cm]?[jt]sx?$/.test(file) ? triviaCommentRanges(ts, file, text) : []
2978
+ const inComments = stale.every((match) =>
2979
+ comments?.some(
2980
+ ([start, stop]) => start <= match.index && match.index + from.length <= stop,
2981
+ ),
2982
+ )
2983
+ if (inComments)
2984
+ commentFollowUps.push({ file, reason: `a comment names "${from}", which moved to "${to}"` })
2985
+ else issues.push({ file, reason: `mentions "${from}" by path; it moved to "${to}"` })
2615
2986
  }
2616
2987
  }
2617
2988
 
@@ -2665,7 +3036,9 @@ export async function migrateLayout(
2665
3036
  if (!mentionsApp.test(text) && (ownName === undefined || !text.includes(`${ownName}/`)))
2666
3037
  continue
2667
3038
  const at = toPosix(relative(root, join(sibling, file)))
2668
- for (const { from, to, line } of siblingReferences(
3039
+ const onLines = (lines: readonly number[]): string =>
3040
+ `on line${lines.length === 1 ? "" : "s"} ${lines.join(", ")}`
3041
+ for (const { from, to, lines, commentLines } of siblingReferences(
2669
3042
  ts,
2670
3043
  root,
2671
3044
  sibling,
@@ -2675,10 +3048,18 @@ export async function migrateLayout(
2675
3048
  known,
2676
3049
  ownName,
2677
3050
  )) {
2678
- issues.push({
2679
- file: at,
2680
- reason: `names "${from}" on line ${line}, and it moves to "${to}" - it is outside the app, so the migration does not rewrite it`,
2681
- })
3051
+ const comments =
3052
+ commentLines.length === 0 ? "" : ` (and in a comment ${onLines(commentLines)})`
3053
+ if (lines.length > 0)
3054
+ issues.push({
3055
+ file: at,
3056
+ reason: `names "${from}" ${onLines(lines)}${comments}, and it moves to "${to}" - it is outside the app, so the migration does not rewrite it`,
3057
+ })
3058
+ else
3059
+ commentFollowUps.push({
3060
+ file: at,
3061
+ reason: `a comment ${onLines(commentLines)} names "${from}", which moved to "${to}"`,
3062
+ })
2682
3063
  }
2683
3064
  }
2684
3065
  }
@@ -2735,7 +3116,7 @@ export async function migrateLayout(
2735
3116
  })
2736
3117
  for (const [file, text] of schemaPlan?.edits ?? []) final.set(file, text)
2737
3118
  const schemas = (schemaPlan?.entries ?? []).filter((entry) => entry.status === "missing")
2738
- const followUps: LayoutMigrationFollowUp[] = []
3119
+ const followUps: LayoutMigrationFollowUp[] = [...commentFollowUps]
2739
3120
  for (const [file, text] of final) {
2740
3121
  if (!file.startsWith("routes/") || !/\.backend\.[cm]?[jt]s$/.test(file)) continue
2741
3122
  for (const { name, schema } of missingOutputSchemas(text)) {
@@ -2812,6 +3193,14 @@ export async function migrateLayout(
2812
3193
  toolingWrites.set("package.json", kind.text)
2813
3194
  tooling.push({ file: "package.json", change: '"nifra": { "kind": "api" }' })
2814
3195
  }
3196
+ if (manifest !== undefined && manifest.count > 0) {
3197
+ const current = toolingWrites.get("package.json") ?? readFileSync(manifestPath, "utf8")
3198
+ toolingWrites.set("package.json", rewritePackagePaths(ts, current, moveMap).text)
3199
+ tooling.push({
3200
+ file: "package.json",
3201
+ change: `${manifest.count} file path(s) in scripts and entry fields follow their moved files`,
3202
+ })
3203
+ }
2815
3204
 
2816
3205
  if (options.write === true) {
2817
3206
  for (const [file, text] of toolingWrites) writeFileSync(join(root, file), text)
@@ -2833,6 +3222,7 @@ export async function migrateLayout(
2833
3222
  renameSync(join(root, from), join(root, to))
2834
3223
  vacated.push(from)
2835
3224
  }
3225
+ for (const [file, text] of scriptWrites) writeFileSync(join(root, file), text)
2836
3226
  pruneVacatedDirs(root, vacated)
2837
3227
  }
2838
3228
  return {
@@ -3354,6 +3744,80 @@ function declareApiKind(ts: typeof TS, root: string): { text?: string; issue?: s
3354
3744
  return { text: insertProperty(source, text, nifra.initializer, '"kind": "api"') }
3355
3745
  }
3356
3746
 
3747
+ /** package.json fields whose string values name files from the package folder. */
3748
+ const PACKAGE_PATH_FIELDS = new Set([
3749
+ "main",
3750
+ "module",
3751
+ "types",
3752
+ "typings",
3753
+ "browser",
3754
+ "source",
3755
+ "bin",
3756
+ "exports",
3757
+ "imports",
3758
+ "files",
3759
+ "scripts",
3760
+ ])
3761
+
3762
+ /**
3763
+ * `text` (a package.json at the app root) with each moved file it names by its exact path, in the
3764
+ * fields above, named at its new path; `./` kept as written. A value with a `*` outside `scripts` is a
3765
+ * pattern over a folder, which no single move settles, so it stays and the path scan reports it.
3766
+ */
3767
+ function rewritePackagePaths(
3768
+ ts: typeof TS,
3769
+ text: string,
3770
+ moves: ReadonlyMap<string, string>,
3771
+ ): { readonly text: string; readonly count: number } {
3772
+ const source = ts.parseJsonText("package.json", text)
3773
+ const top = source.statements[0]?.expression
3774
+ if (top === undefined || !ts.isObjectLiteralExpression(top) || moves.size === 0)
3775
+ return { text, count: 0 }
3776
+ // Longest first, so `lib/a.test.ts` is not read as `lib/a.ts` with a tail.
3777
+ const ordered = [...moves].sort(([a], [b]) => b.length - a.length)
3778
+ const pattern = new RegExp(
3779
+ `(?<![\\w.@/-])(\\./)?(${ordered.map(([from]) => escapeRegExp(from)).join("|")})(?![\\w/-]|\\.\\w)`,
3780
+ "g",
3781
+ )
3782
+ const edits: Array<{ start: number; end: number; text: string }> = []
3783
+ let count = 0
3784
+ const visit = (node: TS.Node, field: string): void => {
3785
+ if (ts.isStringLiteral(node)) {
3786
+ if (field !== "scripts" && node.text.includes("*")) return
3787
+ const value = node.text.replace(pattern, (_match, dot: string | undefined, from: string) => {
3788
+ count += 1
3789
+ return `${dot ?? ""}${moves.get(from) ?? from}`
3790
+ })
3791
+ if (value !== node.text)
3792
+ edits.push({
3793
+ start: node.getStart(source),
3794
+ end: node.getEnd(),
3795
+ text: JSON.stringify(value),
3796
+ })
3797
+ return
3798
+ }
3799
+ if (ts.isArrayLiteralExpression(node)) {
3800
+ for (const element of node.elements) visit(element, field)
3801
+ return
3802
+ }
3803
+ if (!ts.isObjectLiteralExpression(node)) return
3804
+ for (const property of node.properties) {
3805
+ if (!ts.isPropertyAssignment(property)) continue
3806
+ // `"//x"` keys are comments by npm convention.
3807
+ if (ts.isStringLiteral(property.name) && property.name.text.startsWith("//")) continue
3808
+ visit(property.initializer, field)
3809
+ }
3810
+ }
3811
+ for (const property of top.properties) {
3812
+ if (!ts.isPropertyAssignment(property) || !ts.isStringLiteral(property.name)) continue
3813
+ if (PACKAGE_PATH_FIELDS.has(property.name.text)) visit(property.initializer, property.name.text)
3814
+ }
3815
+ let next = text
3816
+ for (const edit of edits.sort((a, b) => b.start - a.start))
3817
+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end)
3818
+ return { text: next, count }
3819
+ }
3820
+
3357
3821
  /** Tailwind `content` globs that matched a moved file at its old path and match nothing at its new one. */
3358
3822
  function staleContentGlobs(
3359
3823
  ts: typeof TS,