@hyperfrontend/project-scope 0.1.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 (391) hide show
  1. package/ARCHITECTURE.md +370 -0
  2. package/CHANGELOG.md +10 -0
  3. package/FUNDING.md +141 -0
  4. package/LICENSE.md +21 -0
  5. package/README.md +242 -0
  6. package/SECURITY.md +82 -0
  7. package/analyze.d.ts +33 -0
  8. package/analyze.d.ts.map +1 -0
  9. package/cli/commands/analyze.d.ts +20 -0
  10. package/cli/commands/analyze.d.ts.map +1 -0
  11. package/cli/commands/config.d.ts +20 -0
  12. package/cli/commands/config.d.ts.map +1 -0
  13. package/cli/commands/deps.d.ts +18 -0
  14. package/cli/commands/deps.d.ts.map +1 -0
  15. package/cli/commands/tree.d.ts +24 -0
  16. package/cli/commands/tree.d.ts.map +1 -0
  17. package/cli/index.cjs.js +6639 -0
  18. package/cli/index.cjs.js.map +1 -0
  19. package/cli/index.d.ts +7 -0
  20. package/cli/index.d.ts.map +1 -0
  21. package/cli/index.esm.js +6629 -0
  22. package/cli/index.esm.js.map +1 -0
  23. package/cli/run.d.ts +25 -0
  24. package/cli/run.d.ts.map +1 -0
  25. package/cli/types.d.ts +55 -0
  26. package/cli/types.d.ts.map +1 -0
  27. package/core/cache.d.ts +157 -0
  28. package/core/cache.d.ts.map +1 -0
  29. package/core/encoding/convert.d.ts +32 -0
  30. package/core/encoding/convert.d.ts.map +1 -0
  31. package/core/encoding/detect.d.ts +86 -0
  32. package/core/encoding/detect.d.ts.map +1 -0
  33. package/core/encoding/index.cjs.js +751 -0
  34. package/core/encoding/index.cjs.js.map +1 -0
  35. package/core/encoding/index.d.ts +3 -0
  36. package/core/encoding/index.d.ts.map +1 -0
  37. package/core/encoding/index.esm.js +736 -0
  38. package/core/encoding/index.esm.js.map +1 -0
  39. package/core/errors/structured-errors.d.ts +64 -0
  40. package/core/errors/structured-errors.d.ts.map +1 -0
  41. package/core/fs/directory.d.ts +88 -0
  42. package/core/fs/directory.d.ts.map +1 -0
  43. package/core/fs/index.cjs.js +1079 -0
  44. package/core/fs/index.cjs.js.map +1 -0
  45. package/core/fs/index.d.ts +6 -0
  46. package/core/fs/index.d.ts.map +1 -0
  47. package/core/fs/index.esm.js +1056 -0
  48. package/core/fs/index.esm.js.map +1 -0
  49. package/core/fs/read.d.ts +86 -0
  50. package/core/fs/read.d.ts.map +1 -0
  51. package/core/fs/stat.d.ts +58 -0
  52. package/core/fs/stat.d.ts.map +1 -0
  53. package/core/fs/traversal.d.ts +26 -0
  54. package/core/fs/traversal.d.ts.map +1 -0
  55. package/core/fs/write.d.ts +75 -0
  56. package/core/fs/write.d.ts.map +1 -0
  57. package/core/index.cjs.js +2376 -0
  58. package/core/index.cjs.js.map +1 -0
  59. package/core/index.d.ts +9 -0
  60. package/core/index.d.ts.map +1 -0
  61. package/core/index.esm.js +2286 -0
  62. package/core/index.esm.js.map +1 -0
  63. package/core/logger.d.ts +111 -0
  64. package/core/logger.d.ts.map +1 -0
  65. package/core/path/index.cjs.js +254 -0
  66. package/core/path/index.cjs.js.map +1 -0
  67. package/core/path/index.d.ts +5 -0
  68. package/core/path/index.d.ts.map +1 -0
  69. package/core/path/index.esm.js +233 -0
  70. package/core/path/index.esm.js.map +1 -0
  71. package/core/path/join.d.ts +17 -0
  72. package/core/path/join.d.ts.map +1 -0
  73. package/core/path/normalize.d.ts +37 -0
  74. package/core/path/normalize.d.ts.map +1 -0
  75. package/core/path/resolve.d.ts +52 -0
  76. package/core/path/resolve.d.ts.map +1 -0
  77. package/core/path/segments.d.ts +59 -0
  78. package/core/path/segments.d.ts.map +1 -0
  79. package/core/patterns/glob.d.ts +46 -0
  80. package/core/patterns/glob.d.ts.map +1 -0
  81. package/core/platform/detect.d.ts +66 -0
  82. package/core/platform/detect.d.ts.map +1 -0
  83. package/core/platform/index.cjs.js +241 -0
  84. package/core/platform/index.cjs.js.map +1 -0
  85. package/core/platform/index.d.ts +3 -0
  86. package/core/platform/index.d.ts.map +1 -0
  87. package/core/platform/index.esm.js +226 -0
  88. package/core/platform/index.esm.js.map +1 -0
  89. package/core/platform/line-endings.d.ts +48 -0
  90. package/core/platform/line-endings.d.ts.map +1 -0
  91. package/heuristics/dependencies/analyze.d.ts +77 -0
  92. package/heuristics/dependencies/analyze.d.ts.map +1 -0
  93. package/heuristics/dependencies/index.cjs.js +1126 -0
  94. package/heuristics/dependencies/index.cjs.js.map +1 -0
  95. package/heuristics/dependencies/index.d.ts +2 -0
  96. package/heuristics/dependencies/index.d.ts.map +1 -0
  97. package/heuristics/dependencies/index.esm.js +1122 -0
  98. package/heuristics/dependencies/index.esm.js.map +1 -0
  99. package/heuristics/entry-points/discover.d.ts +86 -0
  100. package/heuristics/entry-points/discover.d.ts.map +1 -0
  101. package/heuristics/entry-points/index.cjs.js +1581 -0
  102. package/heuristics/entry-points/index.cjs.js.map +1 -0
  103. package/heuristics/entry-points/index.d.ts +2 -0
  104. package/heuristics/entry-points/index.d.ts.map +1 -0
  105. package/heuristics/entry-points/index.esm.js +1577 -0
  106. package/heuristics/entry-points/index.esm.js.map +1 -0
  107. package/heuristics/framework/identify.d.ts +84 -0
  108. package/heuristics/framework/identify.d.ts.map +1 -0
  109. package/heuristics/framework/index.cjs.js +3618 -0
  110. package/heuristics/framework/index.cjs.js.map +1 -0
  111. package/heuristics/framework/index.d.ts +2 -0
  112. package/heuristics/framework/index.d.ts.map +1 -0
  113. package/heuristics/framework/index.esm.js +3614 -0
  114. package/heuristics/framework/index.esm.js.map +1 -0
  115. package/heuristics/index.cjs.js +4833 -0
  116. package/heuristics/index.cjs.js.map +1 -0
  117. package/heuristics/index.d.ts +5 -0
  118. package/heuristics/index.d.ts.map +1 -0
  119. package/heuristics/index.esm.js +4822 -0
  120. package/heuristics/index.esm.js.map +1 -0
  121. package/heuristics/project-type/detect.d.ts +61 -0
  122. package/heuristics/project-type/detect.d.ts.map +1 -0
  123. package/heuristics/project-type/index.cjs.js +3633 -0
  124. package/heuristics/project-type/index.cjs.js.map +1 -0
  125. package/heuristics/project-type/index.d.ts +2 -0
  126. package/heuristics/project-type/index.d.ts.map +1 -0
  127. package/heuristics/project-type/index.esm.js +3631 -0
  128. package/heuristics/project-type/index.esm.js.map +1 -0
  129. package/index.cjs.js +10255 -0
  130. package/index.cjs.js.map +1 -0
  131. package/index.d.ts +10 -0
  132. package/index.d.ts.map +1 -0
  133. package/index.esm.js +10006 -0
  134. package/index.esm.js.map +1 -0
  135. package/models/index.cjs.js +3 -0
  136. package/models/index.cjs.js.map +1 -0
  137. package/models/index.d.ts +176 -0
  138. package/models/index.d.ts.map +1 -0
  139. package/models/index.esm.js +2 -0
  140. package/models/index.esm.js.map +1 -0
  141. package/nx/detect.d.ts +105 -0
  142. package/nx/detect.d.ts.map +1 -0
  143. package/nx/devkit-loader.d.ts +62 -0
  144. package/nx/devkit-loader.d.ts.map +1 -0
  145. package/nx/index.cjs.js +1302 -0
  146. package/nx/index.cjs.js.map +1 -0
  147. package/nx/index.d.ts +4 -0
  148. package/nx/index.d.ts.map +1 -0
  149. package/nx/index.esm.js +1286 -0
  150. package/nx/index.esm.js.map +1 -0
  151. package/nx/project-config.d.ts +109 -0
  152. package/nx/project-config.d.ts.map +1 -0
  153. package/package.json +218 -0
  154. package/project/config/detect.d.ts +77 -0
  155. package/project/config/detect.d.ts.map +1 -0
  156. package/project/config/index.cjs.js +1982 -0
  157. package/project/config/index.cjs.js.map +1 -0
  158. package/project/config/index.d.ts +4 -0
  159. package/project/config/index.d.ts.map +1 -0
  160. package/project/config/index.esm.js +1971 -0
  161. package/project/config/index.esm.js.map +1 -0
  162. package/project/config/parse.d.ts +53 -0
  163. package/project/config/parse.d.ts.map +1 -0
  164. package/project/config/patterns.d.ts +31 -0
  165. package/project/config/patterns.d.ts.map +1 -0
  166. package/project/index.cjs.js +2585 -0
  167. package/project/index.cjs.js.map +1 -0
  168. package/project/index.d.ts +5 -0
  169. package/project/index.d.ts.map +1 -0
  170. package/project/index.esm.js +2549 -0
  171. package/project/index.esm.js.map +1 -0
  172. package/project/package/dependencies.d.ts +101 -0
  173. package/project/package/dependencies.d.ts.map +1 -0
  174. package/project/package/index.cjs.js +972 -0
  175. package/project/package/index.cjs.js.map +1 -0
  176. package/project/package/index.d.ts +3 -0
  177. package/project/package/index.d.ts.map +1 -0
  178. package/project/package/index.esm.js +957 -0
  179. package/project/package/index.esm.js.map +1 -0
  180. package/project/package/read.d.ts +66 -0
  181. package/project/package/read.d.ts.map +1 -0
  182. package/project/root/detect.d.ts +65 -0
  183. package/project/root/detect.d.ts.map +1 -0
  184. package/project/root/index.cjs.js +860 -0
  185. package/project/root/index.cjs.js.map +1 -0
  186. package/project/root/index.d.ts +2 -0
  187. package/project/root/index.d.ts.map +1 -0
  188. package/project/root/index.esm.js +853 -0
  189. package/project/root/index.esm.js.map +1 -0
  190. package/project/traversal/index.cjs.js +1179 -0
  191. package/project/traversal/index.cjs.js.map +1 -0
  192. package/project/traversal/index.d.ts +3 -0
  193. package/project/traversal/index.d.ts.map +1 -0
  194. package/project/traversal/index.esm.js +1173 -0
  195. package/project/traversal/index.esm.js.map +1 -0
  196. package/project/traversal/search.d.ts +59 -0
  197. package/project/traversal/search.d.ts.map +1 -0
  198. package/project/traversal/walk.d.ts +63 -0
  199. package/project/traversal/walk.d.ts.map +1 -0
  200. package/tech/backend/detect-all.d.ts +13 -0
  201. package/tech/backend/detect-all.d.ts.map +1 -0
  202. package/tech/backend/express.d.ts +11 -0
  203. package/tech/backend/express.d.ts.map +1 -0
  204. package/tech/backend/fastify.d.ts +11 -0
  205. package/tech/backend/fastify.d.ts.map +1 -0
  206. package/tech/backend/hono.d.ts +11 -0
  207. package/tech/backend/hono.d.ts.map +1 -0
  208. package/tech/backend/index.cjs.js +939 -0
  209. package/tech/backend/index.cjs.js.map +1 -0
  210. package/tech/backend/index.d.ts +8 -0
  211. package/tech/backend/index.d.ts.map +1 -0
  212. package/tech/backend/index.esm.js +931 -0
  213. package/tech/backend/index.esm.js.map +1 -0
  214. package/tech/backend/koa.d.ts +11 -0
  215. package/tech/backend/koa.d.ts.map +1 -0
  216. package/tech/backend/nestjs.d.ts +11 -0
  217. package/tech/backend/nestjs.d.ts.map +1 -0
  218. package/tech/backend/types.d.ts +31 -0
  219. package/tech/backend/types.d.ts.map +1 -0
  220. package/tech/build/babel.d.ts +13 -0
  221. package/tech/build/babel.d.ts.map +1 -0
  222. package/tech/build/detect-all.d.ts +13 -0
  223. package/tech/build/detect-all.d.ts.map +1 -0
  224. package/tech/build/esbuild.d.ts +11 -0
  225. package/tech/build/esbuild.d.ts.map +1 -0
  226. package/tech/build/index.cjs.js +1118 -0
  227. package/tech/build/index.cjs.js.map +1 -0
  228. package/tech/build/index.d.ts +10 -0
  229. package/tech/build/index.d.ts.map +1 -0
  230. package/tech/build/index.esm.js +1102 -0
  231. package/tech/build/index.esm.js.map +1 -0
  232. package/tech/build/parcel.d.ts +13 -0
  233. package/tech/build/parcel.d.ts.map +1 -0
  234. package/tech/build/rollup.d.ts +13 -0
  235. package/tech/build/rollup.d.ts.map +1 -0
  236. package/tech/build/swc.d.ts +13 -0
  237. package/tech/build/swc.d.ts.map +1 -0
  238. package/tech/build/types.d.ts +31 -0
  239. package/tech/build/types.d.ts.map +1 -0
  240. package/tech/build/vite.d.ts +13 -0
  241. package/tech/build/vite.d.ts.map +1 -0
  242. package/tech/build/webpack.d.ts +13 -0
  243. package/tech/build/webpack.d.ts.map +1 -0
  244. package/tech/frontend/angular.d.ts +11 -0
  245. package/tech/frontend/angular.d.ts.map +1 -0
  246. package/tech/frontend/astro.d.ts +11 -0
  247. package/tech/frontend/astro.d.ts.map +1 -0
  248. package/tech/frontend/detect-all.d.ts +13 -0
  249. package/tech/frontend/detect-all.d.ts.map +1 -0
  250. package/tech/frontend/gatsby.d.ts +11 -0
  251. package/tech/frontend/gatsby.d.ts.map +1 -0
  252. package/tech/frontend/index.cjs.js +1310 -0
  253. package/tech/frontend/index.cjs.js.map +1 -0
  254. package/tech/frontend/index.d.ts +15 -0
  255. package/tech/frontend/index.d.ts.map +1 -0
  256. package/tech/frontend/index.esm.js +1295 -0
  257. package/tech/frontend/index.esm.js.map +1 -0
  258. package/tech/frontend/nextjs.d.ts +11 -0
  259. package/tech/frontend/nextjs.d.ts.map +1 -0
  260. package/tech/frontend/nuxt.d.ts +11 -0
  261. package/tech/frontend/nuxt.d.ts.map +1 -0
  262. package/tech/frontend/qwik.d.ts +11 -0
  263. package/tech/frontend/qwik.d.ts.map +1 -0
  264. package/tech/frontend/react.d.ts +11 -0
  265. package/tech/frontend/react.d.ts.map +1 -0
  266. package/tech/frontend/remix.d.ts +11 -0
  267. package/tech/frontend/remix.d.ts.map +1 -0
  268. package/tech/frontend/solid.d.ts +11 -0
  269. package/tech/frontend/solid.d.ts.map +1 -0
  270. package/tech/frontend/svelte.d.ts +11 -0
  271. package/tech/frontend/svelte.d.ts.map +1 -0
  272. package/tech/frontend/sveltekit.d.ts +11 -0
  273. package/tech/frontend/sveltekit.d.ts.map +1 -0
  274. package/tech/frontend/types.d.ts +35 -0
  275. package/tech/frontend/types.d.ts.map +1 -0
  276. package/tech/frontend/vue.d.ts +11 -0
  277. package/tech/frontend/vue.d.ts.map +1 -0
  278. package/tech/index.cjs.js +3684 -0
  279. package/tech/index.cjs.js.map +1 -0
  280. package/tech/index.d.ts +96 -0
  281. package/tech/index.d.ts.map +1 -0
  282. package/tech/index.esm.js +3603 -0
  283. package/tech/index.esm.js.map +1 -0
  284. package/tech/legacy/angularjs.d.ts +12 -0
  285. package/tech/legacy/angularjs.d.ts.map +1 -0
  286. package/tech/legacy/backbone.d.ts +11 -0
  287. package/tech/legacy/backbone.d.ts.map +1 -0
  288. package/tech/legacy/detect-all.d.ts +13 -0
  289. package/tech/legacy/detect-all.d.ts.map +1 -0
  290. package/tech/legacy/ember.d.ts +11 -0
  291. package/tech/legacy/ember.d.ts.map +1 -0
  292. package/tech/legacy/index.cjs.js +903 -0
  293. package/tech/legacy/index.cjs.js.map +1 -0
  294. package/tech/legacy/index.d.ts +7 -0
  295. package/tech/legacy/index.d.ts.map +1 -0
  296. package/tech/legacy/index.esm.js +896 -0
  297. package/tech/legacy/index.esm.js.map +1 -0
  298. package/tech/legacy/jquery.d.ts +11 -0
  299. package/tech/legacy/jquery.d.ts.map +1 -0
  300. package/tech/legacy/types.d.ts +33 -0
  301. package/tech/legacy/types.d.ts.map +1 -0
  302. package/tech/linting/biome.d.ts +11 -0
  303. package/tech/linting/biome.d.ts.map +1 -0
  304. package/tech/linting/detect-all.d.ts +13 -0
  305. package/tech/linting/detect-all.d.ts.map +1 -0
  306. package/tech/linting/eslint.d.ts +13 -0
  307. package/tech/linting/eslint.d.ts.map +1 -0
  308. package/tech/linting/index.cjs.js +992 -0
  309. package/tech/linting/index.cjs.js.map +1 -0
  310. package/tech/linting/index.d.ts +7 -0
  311. package/tech/linting/index.d.ts.map +1 -0
  312. package/tech/linting/index.esm.js +982 -0
  313. package/tech/linting/index.esm.js.map +1 -0
  314. package/tech/linting/prettier.d.ts +13 -0
  315. package/tech/linting/prettier.d.ts.map +1 -0
  316. package/tech/linting/stylelint.d.ts +13 -0
  317. package/tech/linting/stylelint.d.ts.map +1 -0
  318. package/tech/linting/types.d.ts +31 -0
  319. package/tech/linting/types.d.ts.map +1 -0
  320. package/tech/monorepo/detect-all.d.ts +13 -0
  321. package/tech/monorepo/detect-all.d.ts.map +1 -0
  322. package/tech/monorepo/index.cjs.js +1021 -0
  323. package/tech/monorepo/index.cjs.js.map +1 -0
  324. package/tech/monorepo/index.d.ts +10 -0
  325. package/tech/monorepo/index.d.ts.map +1 -0
  326. package/tech/monorepo/index.esm.js +1011 -0
  327. package/tech/monorepo/index.esm.js.map +1 -0
  328. package/tech/monorepo/lerna.d.ts +11 -0
  329. package/tech/monorepo/lerna.d.ts.map +1 -0
  330. package/tech/monorepo/npm-workspaces.d.ts +11 -0
  331. package/tech/monorepo/npm-workspaces.d.ts.map +1 -0
  332. package/tech/monorepo/nx.d.ts +11 -0
  333. package/tech/monorepo/nx.d.ts.map +1 -0
  334. package/tech/monorepo/pnpm-workspaces.d.ts +9 -0
  335. package/tech/monorepo/pnpm-workspaces.d.ts.map +1 -0
  336. package/tech/monorepo/rush.d.ts +11 -0
  337. package/tech/monorepo/rush.d.ts.map +1 -0
  338. package/tech/monorepo/turborepo.d.ts +11 -0
  339. package/tech/monorepo/turborepo.d.ts.map +1 -0
  340. package/tech/monorepo/types.d.ts +39 -0
  341. package/tech/monorepo/types.d.ts.map +1 -0
  342. package/tech/monorepo/yarn-workspaces.d.ts +11 -0
  343. package/tech/monorepo/yarn-workspaces.d.ts.map +1 -0
  344. package/tech/shared-utils/detector-helpers.d.ts +52 -0
  345. package/tech/shared-utils/detector-helpers.d.ts.map +1 -0
  346. package/tech/shared-utils/types.d.ts +41 -0
  347. package/tech/shared-utils/types.d.ts.map +1 -0
  348. package/tech/testing/cypress.d.ts +13 -0
  349. package/tech/testing/cypress.d.ts.map +1 -0
  350. package/tech/testing/detect-all.d.ts +13 -0
  351. package/tech/testing/detect-all.d.ts.map +1 -0
  352. package/tech/testing/index.cjs.js +1031 -0
  353. package/tech/testing/index.cjs.js.map +1 -0
  354. package/tech/testing/index.d.ts +8 -0
  355. package/tech/testing/index.d.ts.map +1 -0
  356. package/tech/testing/index.esm.js +1018 -0
  357. package/tech/testing/index.esm.js.map +1 -0
  358. package/tech/testing/jest.d.ts +13 -0
  359. package/tech/testing/jest.d.ts.map +1 -0
  360. package/tech/testing/mocha.d.ts +13 -0
  361. package/tech/testing/mocha.d.ts.map +1 -0
  362. package/tech/testing/playwright.d.ts +13 -0
  363. package/tech/testing/playwright.d.ts.map +1 -0
  364. package/tech/testing/types.d.ts +35 -0
  365. package/tech/testing/types.d.ts.map +1 -0
  366. package/tech/testing/vitest.d.ts +13 -0
  367. package/tech/testing/vitest.d.ts.map +1 -0
  368. package/tech/types/detectors.d.ts +67 -0
  369. package/tech/types/detectors.d.ts.map +1 -0
  370. package/tech/types/index.cjs.js +1045 -0
  371. package/tech/types/index.cjs.js.map +1 -0
  372. package/tech/types/index.d.ts +2 -0
  373. package/tech/types/index.d.ts.map +1 -0
  374. package/tech/types/index.esm.js +1039 -0
  375. package/tech/types/index.esm.js.map +1 -0
  376. package/vfs/commit.d.ts +32 -0
  377. package/vfs/commit.d.ts.map +1 -0
  378. package/vfs/diff.d.ts +73 -0
  379. package/vfs/diff.d.ts.map +1 -0
  380. package/vfs/factory.d.ts +37 -0
  381. package/vfs/factory.d.ts.map +1 -0
  382. package/vfs/fs-tree.d.ts +13 -0
  383. package/vfs/fs-tree.d.ts.map +1 -0
  384. package/vfs/index.cjs.js +1600 -0
  385. package/vfs/index.cjs.js.map +1 -0
  386. package/vfs/index.d.ts +6 -0
  387. package/vfs/index.d.ts.map +1 -0
  388. package/vfs/index.esm.js +1590 -0
  389. package/vfs/index.esm.js.map +1 -0
  390. package/vfs/types.d.ts +178 -0
  391. package/vfs/types.d.ts.map +1 -0
@@ -0,0 +1,1600 @@
1
+ 'use strict';
2
+
3
+ var node_fs = require('node:fs');
4
+ var node_path = require('node:path');
5
+
6
+ /**
7
+ * Safe copies of Error built-ins via factory functions.
8
+ *
9
+ * Since constructors cannot be safely captured via Object.assign, this module
10
+ * provides factory functions that use Reflect.construct internally.
11
+ *
12
+ * These references are captured at module initialization time to protect against
13
+ * prototype pollution attacks. Import only what you need for tree-shaking.
14
+ *
15
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/error
16
+ */
17
+ // Capture references at module initialization time
18
+ const _Error = globalThis.Error;
19
+ const _Reflect$2 = globalThis.Reflect;
20
+ /**
21
+ * (Safe copy) Creates a new Error using the captured Error constructor.
22
+ * Use this instead of `new Error()`.
23
+ *
24
+ * @param message - Optional error message.
25
+ * @param options - Optional error options.
26
+ * @returns A new Error instance.
27
+ */
28
+ const createError = (message, options) => _Reflect$2.construct(_Error, [message, options]);
29
+
30
+ /**
31
+ * Safe copies of JSON built-in methods.
32
+ *
33
+ * These references are captured at module initialization time to protect against
34
+ * prototype pollution attacks. Import only what you need for tree-shaking.
35
+ *
36
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/json
37
+ */
38
+ // Capture references at module initialization time
39
+ const _JSON = globalThis.JSON;
40
+ /**
41
+ * (Safe copy) Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
42
+ */
43
+ const stringify = _JSON.stringify;
44
+
45
+ /**
46
+ * Safe copies of Object built-in methods.
47
+ *
48
+ * These references are captured at module initialization time to protect against
49
+ * prototype pollution attacks. Import only what you need for tree-shaking.
50
+ *
51
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/object
52
+ */
53
+ // Capture references at module initialization time
54
+ const _Object = globalThis.Object;
55
+ /**
56
+ * (Safe copy) Prevents modification of existing property attributes and values,
57
+ * and prevents the addition of new properties.
58
+ */
59
+ const freeze = _Object.freeze;
60
+ /**
61
+ * (Safe copy) Returns the names of the enumerable string properties and methods of an object.
62
+ */
63
+ const keys = _Object.keys;
64
+ /**
65
+ * (Safe copy) Returns an array of key/values of the enumerable own properties of an object.
66
+ */
67
+ const entries = _Object.entries;
68
+ /**
69
+ * (Safe copy) Adds one or more properties to an object, and/or modifies attributes of existing properties.
70
+ */
71
+ const defineProperties = _Object.defineProperties;
72
+
73
+ /**
74
+ * Safe copies of Array built-in static methods.
75
+ *
76
+ * These references are captured at module initialization time to protect against
77
+ * prototype pollution attacks. Import only what you need for tree-shaking.
78
+ *
79
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/array
80
+ */
81
+ // Capture references at module initialization time
82
+ const _Array = globalThis.Array;
83
+ /**
84
+ * (Safe copy) Determines whether the passed value is an Array.
85
+ */
86
+ const isArray = _Array.isArray;
87
+ /**
88
+ * (Safe copy) Creates an array from an array-like or iterable object.
89
+ */
90
+ const from = _Array.from;
91
+
92
+ /**
93
+ * Safe copies of Console built-in methods.
94
+ *
95
+ * These references are captured at module initialization time to protect against
96
+ * prototype pollution attacks. Import only what you need for tree-shaking.
97
+ *
98
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/console
99
+ */
100
+ // Capture references at module initialization time
101
+ const _console = globalThis.console;
102
+ /**
103
+ * (Safe copy) Outputs a message to the console.
104
+ */
105
+ const log = _console.log.bind(_console);
106
+ /**
107
+ * (Safe copy) Outputs a warning message to the console.
108
+ */
109
+ const warn = _console.warn.bind(_console);
110
+ /**
111
+ * (Safe copy) Outputs an error message to the console.
112
+ */
113
+ const error = _console.error.bind(_console);
114
+ /**
115
+ * (Safe copy) Outputs an informational message to the console.
116
+ */
117
+ const info = _console.info.bind(_console);
118
+ /**
119
+ * (Safe copy) Outputs a debug message to the console.
120
+ */
121
+ const debug = _console.debug.bind(_console);
122
+ /**
123
+ * (Safe copy) Outputs a stack trace to the console.
124
+ */
125
+ _console.trace.bind(_console);
126
+ /**
127
+ * (Safe copy) Displays an interactive listing of the properties of a specified object.
128
+ */
129
+ _console.dir.bind(_console);
130
+ /**
131
+ * (Safe copy) Displays tabular data as a table.
132
+ */
133
+ _console.table.bind(_console);
134
+ /**
135
+ * (Safe copy) Writes an error message to the console if the assertion is false.
136
+ */
137
+ _console.assert.bind(_console);
138
+ /**
139
+ * (Safe copy) Clears the console.
140
+ */
141
+ _console.clear.bind(_console);
142
+ /**
143
+ * (Safe copy) Logs the number of times that this particular call to count() has been called.
144
+ */
145
+ _console.count.bind(_console);
146
+ /**
147
+ * (Safe copy) Resets the counter used with console.count().
148
+ */
149
+ _console.countReset.bind(_console);
150
+ /**
151
+ * (Safe copy) Creates a new inline group in the console.
152
+ */
153
+ _console.group.bind(_console);
154
+ /**
155
+ * (Safe copy) Creates a new inline group in the console that is initially collapsed.
156
+ */
157
+ _console.groupCollapsed.bind(_console);
158
+ /**
159
+ * (Safe copy) Exits the current inline group.
160
+ */
161
+ _console.groupEnd.bind(_console);
162
+ /**
163
+ * (Safe copy) Starts a timer with a name specified as an input parameter.
164
+ */
165
+ _console.time.bind(_console);
166
+ /**
167
+ * (Safe copy) Stops a timer that was previously started.
168
+ */
169
+ _console.timeEnd.bind(_console);
170
+ /**
171
+ * (Safe copy) Logs the current value of a timer that was previously started.
172
+ */
173
+ _console.timeLog.bind(_console);
174
+
175
+ /**
176
+ * Safe copies of Set built-in via factory function.
177
+ *
178
+ * Since constructors cannot be safely captured via Object.assign, this module
179
+ * provides a factory function that uses Reflect.construct internally.
180
+ *
181
+ * These references are captured at module initialization time to protect against
182
+ * prototype pollution attacks. Import only what you need for tree-shaking.
183
+ *
184
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/set
185
+ */
186
+ // Capture references at module initialization time
187
+ const _Set = globalThis.Set;
188
+ const _Reflect$1 = globalThis.Reflect;
189
+ /**
190
+ * (Safe copy) Creates a new Set using the captured Set constructor.
191
+ * Use this instead of `new Set()`.
192
+ *
193
+ * @param iterable - Optional iterable of values.
194
+ * @returns A new Set instance.
195
+ */
196
+ const createSet = (iterable) => _Reflect$1.construct(_Set, iterable ? [iterable] : []);
197
+
198
+ const registeredClasses = [];
199
+
200
+ /**
201
+ * Returns the data type of the target.
202
+ * Uses native `typeof` operator, however, makes distinction between `null`, `array`, and `object`.
203
+ * Also, when classes are registered via `registerClass`, it checks if objects are instance of any known registered class.
204
+ *
205
+ * @param target - The target to get the data type of.
206
+ * @returns The data type of the target.
207
+ */
208
+ const getType = (target) => {
209
+ if (target === null)
210
+ return 'null';
211
+ const nativeDataType = typeof target;
212
+ if (nativeDataType === 'object') {
213
+ if (isArray(target))
214
+ return 'array';
215
+ for (const registeredClass of registeredClasses) {
216
+ if (target instanceof registeredClass)
217
+ return registeredClass.name;
218
+ }
219
+ }
220
+ return nativeDataType;
221
+ };
222
+
223
+ /**
224
+ * Safe copies of Map built-in via factory function.
225
+ *
226
+ * Since constructors cannot be safely captured via Object.assign, this module
227
+ * provides a factory function that uses Reflect.construct internally.
228
+ *
229
+ * These references are captured at module initialization time to protect against
230
+ * prototype pollution attacks. Import only what you need for tree-shaking.
231
+ *
232
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/map
233
+ */
234
+ // Capture references at module initialization time
235
+ const _Map = globalThis.Map;
236
+ const _Reflect = globalThis.Reflect;
237
+ /**
238
+ * (Safe copy) Creates a new Map using the captured Map constructor.
239
+ * Use this instead of `new Map()`.
240
+ *
241
+ * @param iterable - Optional iterable of key-value pairs.
242
+ * @returns A new Map instance.
243
+ */
244
+ const createMap = (iterable) => _Reflect.construct(_Map, iterable ? [iterable] : []);
245
+
246
+ /**
247
+ * Safe copies of Math built-in methods.
248
+ *
249
+ * These references are captured at module initialization time to protect against
250
+ * prototype pollution attacks. Import only what you need for tree-shaking.
251
+ *
252
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/math
253
+ */
254
+ // Capture references at module initialization time
255
+ const _Math = globalThis.Math;
256
+ // ============================================================================
257
+ // Min/Max
258
+ // ============================================================================
259
+ /**
260
+ * (Safe copy) Returns the larger of zero or more numbers.
261
+ */
262
+ const max = _Math.max;
263
+ /**
264
+ * (Safe copy) Returns the smaller of zero or more numbers.
265
+ */
266
+ const min = _Math.min;
267
+
268
+ /* eslint-disable @typescript-eslint/no-explicit-any */
269
+ /**
270
+ * Creates a wrapper function that only executes the wrapped function if the condition function returns true.
271
+ *
272
+ * @param func - The function to be conditionally executed.
273
+ * @param conditionFunc - A function that returns a boolean, determining if `func` should be executed.
274
+ * @returns A wrapped version of `func` that executes conditionally.
275
+ */
276
+ function createConditionalExecutionFunction(func, conditionFunc) {
277
+ return function (...args) {
278
+ if (conditionFunc()) {
279
+ return func(...args);
280
+ }
281
+ };
282
+ }
283
+
284
+ /* eslint-disable @typescript-eslint/no-explicit-any */
285
+ /**
286
+ * Creates a wrapper function that silently ignores any errors thrown by the wrapped void function.
287
+ * This function is specifically for wrapping functions that do not return a value (void functions).
288
+ * Exceptions are swallowed without any logging or handling.
289
+ *
290
+ * @param func - The void function to be wrapped.
291
+ * @returns A wrapped version of the input function that ignores errors.
292
+ */
293
+ function createErrorIgnoringFunction(func) {
294
+ return function (...args) {
295
+ try {
296
+ func(...args);
297
+ }
298
+ catch {
299
+ // Deliberately swallowing/ignoring the exception
300
+ }
301
+ };
302
+ }
303
+
304
+ /* eslint-disable @typescript-eslint/no-unused-vars */
305
+ /**
306
+ * A no-operation function (noop) that does nothing regardless of the arguments passed.
307
+ * It is designed to be as permissive as possible in its typing without using the `Function` keyword.
308
+ *
309
+ * @param args - Any arguments passed to the function (ignored)
310
+ */
311
+ const noop = (...args) => {
312
+ // Intentionally does nothing
313
+ };
314
+
315
+ const logLevels = ['none', 'error', 'warn', 'log', 'info', 'debug'];
316
+ const priority = {
317
+ error: 4,
318
+ warn: 3,
319
+ log: 2,
320
+ info: 1,
321
+ debug: 0,
322
+ };
323
+ /**
324
+ * Validates whether a given string is a valid log level.
325
+ *
326
+ * @param level - The log level to validate
327
+ * @returns True if the level is valid, false otherwise
328
+ */
329
+ function isValidLogLevel(level) {
330
+ return logLevels.includes(level);
331
+ }
332
+ /**
333
+ * Creates a log level configuration manager for controlling logging behavior.
334
+ * Provides methods to get, set, and evaluate log levels based on priority.
335
+ *
336
+ * @param level - The initial log level (defaults to 'error')
337
+ * @returns A configuration object with log level management methods
338
+ * @throws {Error} When the provided level is not a valid log level
339
+ */
340
+ function createLogLevelConfig(level = 'error') {
341
+ if (!isValidLogLevel(level)) {
342
+ throw createError('Cannot create log level configuration with a valid default log level');
343
+ }
344
+ const state = { level };
345
+ const getLogLevel = () => state.level;
346
+ const setLogLevel = (level) => {
347
+ if (!isValidLogLevel(level)) {
348
+ throw createError(`Cannot set value '${level}' level. Expected levels are ${logLevels}.`);
349
+ }
350
+ state.level = level;
351
+ };
352
+ const shouldLog = (level) => {
353
+ if (state.level === 'none' || level === 'none' || !isValidLogLevel(level)) {
354
+ return false;
355
+ }
356
+ return priority[level] >= priority[state.level];
357
+ };
358
+ return freeze({
359
+ getLogLevel,
360
+ setLogLevel,
361
+ shouldLog,
362
+ });
363
+ }
364
+
365
+ /**
366
+ * Creates a logger instance with configurable log level filtering.
367
+ * Each log function is wrapped to respect the current log level setting.
368
+ *
369
+ * @param error - Function to handle error-level logs (required)
370
+ * @param warn - Function to handle warning-level logs (optional, defaults to noop)
371
+ * @param log - Function to handle standard logs (optional, defaults to noop)
372
+ * @param info - Function to handle info-level logs (optional, defaults to noop)
373
+ * @param debug - Function to handle debug-level logs (optional, defaults to noop)
374
+ * @returns A frozen logger object with log methods and level control
375
+ * @throws {ErrorLevelFn} When any provided log function is invalid
376
+ */
377
+ function createLogger(error, warn = noop, log = noop, info = noop, debug = noop) {
378
+ if (notValidLogFn(error)) {
379
+ throw createError(notFnMsg('error'));
380
+ }
381
+ if (notValidLogFn(warn)) {
382
+ throw createError(notFnMsg('warn'));
383
+ }
384
+ if (notValidLogFn(log)) {
385
+ throw createError(notFnMsg('log'));
386
+ }
387
+ if (notValidLogFn(info)) {
388
+ throw createError(notFnMsg('info'));
389
+ }
390
+ if (notValidLogFn(debug)) {
391
+ throw createError(notFnMsg('debug'));
392
+ }
393
+ const { setLogLevel, getLogLevel, shouldLog } = createLogLevelConfig();
394
+ const wrapLogFn = (fn, level) => {
395
+ if (fn === noop)
396
+ return fn;
397
+ const condition = () => shouldLog(level);
398
+ return createConditionalExecutionFunction(createErrorIgnoringFunction(fn), condition);
399
+ };
400
+ return freeze({
401
+ error: wrapLogFn(error, 'error'),
402
+ warn: wrapLogFn(warn, 'warn'),
403
+ log: wrapLogFn(log, 'log'),
404
+ info: wrapLogFn(info, 'info'),
405
+ debug: wrapLogFn(debug, 'debug'),
406
+ setLogLevel,
407
+ getLogLevel,
408
+ });
409
+ }
410
+ /**
411
+ * Validates whether a given value is a valid log function.
412
+ *
413
+ * @param fn - The value to validate
414
+ * @returns True if the value is not a function (invalid), false if it is valid
415
+ */
416
+ function notValidLogFn(fn) {
417
+ return getType(fn) !== 'function' && fn !== noop;
418
+ }
419
+ /**
420
+ * Generates an error message for invalid log function parameters.
421
+ *
422
+ * @param label - The name of the log function that failed validation
423
+ * @returns A formatted error message string
424
+ */
425
+ function notFnMsg(label) {
426
+ return `Cannot create a logger when ${label} is not a function`;
427
+ }
428
+
429
+ createLogger(error, warn, log, info, debug);
430
+
431
+ /**
432
+ * Global log level registry.
433
+ * Tracks all created scoped loggers to allow global log level changes.
434
+ */
435
+ const loggerRegistry = createSet();
436
+ /** Redacted placeholder for sensitive values */
437
+ const REDACTED = '[REDACTED]';
438
+ /**
439
+ * Patterns that indicate a sensitive key name.
440
+ * Keys containing these patterns will have their values sanitized.
441
+ */
442
+ const SENSITIVE_KEY_PATTERNS = [
443
+ /token/i,
444
+ /key/i,
445
+ /password/i,
446
+ /secret/i,
447
+ /credential/i,
448
+ /auth/i,
449
+ /bearer/i,
450
+ /api[_-]?key/i,
451
+ /private/i,
452
+ /passphrase/i,
453
+ ];
454
+ /**
455
+ * Checks if a key name indicates sensitive data.
456
+ *
457
+ * @param key - Key name to check
458
+ * @returns True if the key indicates sensitive data
459
+ */
460
+ function isSensitiveKey(key) {
461
+ return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
462
+ }
463
+ /**
464
+ * Sanitizes an object by replacing sensitive values with REDACTED.
465
+ * This function recursively processes nested objects and arrays.
466
+ *
467
+ * @param obj - Object to sanitize
468
+ * @returns New object with sensitive values redacted
469
+ */
470
+ function sanitize(obj) {
471
+ if (obj === null || obj === undefined) {
472
+ return obj;
473
+ }
474
+ if (isArray(obj)) {
475
+ return obj.map((item) => sanitize(item));
476
+ }
477
+ if (typeof obj === 'object') {
478
+ const result = {};
479
+ for (const [key, value] of entries(obj)) {
480
+ if (isSensitiveKey(key)) {
481
+ result[key] = REDACTED;
482
+ }
483
+ else if (typeof value === 'object' && value !== null) {
484
+ result[key] = sanitize(value);
485
+ }
486
+ else {
487
+ result[key] = value;
488
+ }
489
+ }
490
+ return result;
491
+ }
492
+ return obj;
493
+ }
494
+ /**
495
+ * Formats a log message with optional metadata.
496
+ *
497
+ * @param namespace - Logger namespace prefix
498
+ * @param message - Log message
499
+ * @param meta - Optional metadata object
500
+ * @returns Formatted log string
501
+ */
502
+ function formatMessage(namespace, message, meta) {
503
+ const prefix = `[${namespace}]`;
504
+ if (meta && keys(meta).length > 0) {
505
+ const sanitizedMeta = sanitize(meta);
506
+ return `${prefix} ${message} ${stringify(sanitizedMeta)}`;
507
+ }
508
+ return `${prefix} ${message}`;
509
+ }
510
+ /**
511
+ * Creates a scoped logger with namespace prefix and optional secret sanitization.
512
+ * All log messages will be prefixed with [namespace] and sensitive metadata
513
+ * values will be automatically redacted.
514
+ *
515
+ * @param namespace - Logger namespace (e.g., 'project-scope', 'analyze')
516
+ * @param options - Logger configuration options
517
+ * @returns A configured scoped logger instance
518
+ *
519
+ * @example
520
+ * ```typescript
521
+ * const logger = createScopedLogger('project-scope')
522
+ * logger.setLogLevel('debug')
523
+ *
524
+ * // Basic logging
525
+ * logger.info('Starting analysis', { path: './project' })
526
+ *
527
+ * // Sensitive data is automatically redacted
528
+ * logger.debug('Config loaded', { apiKey: 'secret123' })
529
+ * // Output: [project-scope] Config loaded {"apiKey":"[REDACTED]"}
530
+ * ```
531
+ */
532
+ function createScopedLogger(namespace, options = {}) {
533
+ const { level = 'error', sanitizeSecrets = true } = options;
534
+ // Create wrapper functions that add namespace prefix and sanitization
535
+ const createLogFn = (baseFn) => (message, meta) => {
536
+ const processedMeta = sanitizeSecrets && meta ? sanitize(meta) : meta;
537
+ baseFn(formatMessage(namespace, message, processedMeta));
538
+ };
539
+ // Create base logger with wrapped functions
540
+ const baseLogger = createLogger(createLogFn(error), createLogFn(warn), createLogFn(log), createLogFn(info), createLogFn(debug));
541
+ // Set initial log level (use global override if set)
542
+ baseLogger.setLogLevel(level);
543
+ const scopedLogger = freeze({
544
+ error: (message, meta) => baseLogger.error(message, meta),
545
+ warn: (message, meta) => baseLogger.warn(message, meta),
546
+ log: (message, meta) => baseLogger.log(message, meta),
547
+ info: (message, meta) => baseLogger.info(message, meta),
548
+ debug: (message, meta) => baseLogger.debug(message, meta),
549
+ setLogLevel: baseLogger.setLogLevel,
550
+ getLogLevel: baseLogger.getLogLevel,
551
+ });
552
+ // Register logger for global level management
553
+ loggerRegistry.add(scopedLogger);
554
+ return scopedLogger;
555
+ }
556
+ /**
557
+ * Default logger instance for the project-scope library.
558
+ * Use this for general logging within the library.
559
+ *
560
+ * @example
561
+ * ```typescript
562
+ * import { logger } from '@hyperfrontend/project-scope/core'
563
+ *
564
+ * logger.setLogLevel('debug')
565
+ * logger.debug('Analyzing project', { path: './src' })
566
+ * ```
567
+ */
568
+ createScopedLogger('project-scope');
569
+
570
+ createScopedLogger('project-scope:fs');
571
+ /**
572
+ * Create a file system error with code and context.
573
+ *
574
+ * @param message - The error message describing what went wrong
575
+ * @param code - The category code for this type of filesystem failure
576
+ * @param context - Additional context including path, operation, and cause
577
+ * @returns A configured Error object with code and context properties
578
+ */
579
+ function createFileSystemError(message, code, context) {
580
+ const error = createError(message);
581
+ defineProperties(error, {
582
+ code: { value: code, enumerable: true },
583
+ context: { value: context, enumerable: true },
584
+ });
585
+ return error;
586
+ }
587
+
588
+ const fsWriteLogger = createScopedLogger('project-scope:fs:write');
589
+ /**
590
+ * Ensure directory exists, create recursively if not.
591
+ *
592
+ * @param dirPath - Directory path to ensure exists
593
+ */
594
+ function ensureDir(dirPath) {
595
+ if (!node_fs.existsSync(dirPath)) {
596
+ fsWriteLogger.debug('Creating directory recursively', { path: dirPath });
597
+ node_fs.mkdirSync(dirPath, { recursive: true });
598
+ }
599
+ }
600
+
601
+ /**
602
+ * Get file stats with error handling.
603
+ *
604
+ * @param filePath - Path to file
605
+ * @param followSymlinks - Whether to follow symlinks (default: true)
606
+ * @returns File stats or null if path doesn't exist
607
+ */
608
+ function getFileStat(filePath, followSymlinks = true) {
609
+ if (!node_fs.existsSync(filePath)) {
610
+ return null;
611
+ }
612
+ try {
613
+ const stat = followSymlinks ? node_fs.statSync(filePath) : node_fs.lstatSync(filePath);
614
+ return {
615
+ isFile: stat.isFile(),
616
+ isDirectory: stat.isDirectory(),
617
+ isSymlink: stat.isSymbolicLink(),
618
+ size: stat.size,
619
+ created: stat.birthtime,
620
+ modified: stat.mtime,
621
+ accessed: stat.atime,
622
+ mode: stat.mode,
623
+ };
624
+ }
625
+ catch {
626
+ return null;
627
+ }
628
+ }
629
+ /**
630
+ * Check if path is a file.
631
+ *
632
+ * @param filePath - Path to check
633
+ * @returns True if path is a file
634
+ */
635
+ function isFile(filePath) {
636
+ const stats = getFileStat(filePath);
637
+ return stats?.isFile ?? false;
638
+ }
639
+ /**
640
+ * Check if path is a directory.
641
+ *
642
+ * @param dirPath - Path to check
643
+ * @returns True if path is a directory
644
+ */
645
+ function isDirectory(dirPath) {
646
+ const stats = getFileStat(dirPath);
647
+ return stats?.isDirectory ?? false;
648
+ }
649
+ /**
650
+ * Check if path exists.
651
+ *
652
+ * @param filePath - Path to check
653
+ * @returns True if path exists
654
+ */
655
+ function exists(filePath) {
656
+ return node_fs.existsSync(filePath);
657
+ }
658
+
659
+ const fsDirLogger = createScopedLogger('project-scope:fs:dir');
660
+ /**
661
+ * List immediate contents of a directory.
662
+ *
663
+ * @param dirPath - Absolute or relative path to the directory
664
+ * @returns Array of entries with metadata for each file/directory
665
+ * @throws {Error} If directory doesn't exist or isn't a directory
666
+ *
667
+ * @example
668
+ * ```typescript
669
+ * import { readDirectory } from '@hyperfrontend/project-scope'
670
+ *
671
+ * const entries = readDirectory('./src')
672
+ * for (const entry of entries) {
673
+ * console.log(entry.name, entry.isFile ? 'file' : 'directory')
674
+ * }
675
+ * ```
676
+ */
677
+ function readDirectory(dirPath) {
678
+ fsDirLogger.debug('Reading directory', { path: dirPath });
679
+ if (!node_fs.existsSync(dirPath)) {
680
+ fsDirLogger.debug('Directory not found', { path: dirPath });
681
+ throw createFileSystemError(`Directory not found: ${dirPath}`, 'FS_NOT_FOUND', { path: dirPath, operation: 'readdir' });
682
+ }
683
+ if (!isDirectory(dirPath)) {
684
+ fsDirLogger.debug('Path is not a directory', { path: dirPath });
685
+ throw createFileSystemError(`Not a directory: ${dirPath}`, 'FS_NOT_A_DIRECTORY', { path: dirPath, operation: 'readdir' });
686
+ }
687
+ try {
688
+ const entries = node_fs.readdirSync(dirPath, { withFileTypes: true });
689
+ fsDirLogger.debug('Directory read complete', { path: dirPath, entryCount: entries.length });
690
+ return entries.map((entry) => ({
691
+ name: entry.name,
692
+ path: node_path.join(dirPath, entry.name),
693
+ isFile: entry.isFile(),
694
+ isDirectory: entry.isDirectory(),
695
+ isSymlink: entry.isSymbolicLink(),
696
+ }));
697
+ }
698
+ catch (error) {
699
+ fsDirLogger.warn('Failed to read directory', { path: dirPath, error: error instanceof Error ? error.message : String(error) });
700
+ throw createFileSystemError(`Failed to read directory: ${dirPath}`, 'FS_READ_ERROR', {
701
+ path: dirPath,
702
+ operation: 'readdir',
703
+ cause: error,
704
+ });
705
+ }
706
+ }
707
+
708
+ /**
709
+ * Normalize path separators to forward slashes.
710
+ *
711
+ * @param filePath - Path to normalize
712
+ * @returns Normalized path with forward slashes
713
+ */
714
+ function normalizePath(filePath) {
715
+ if (!filePath)
716
+ return '';
717
+ // Normalize path and convert backslashes to forward slashes
718
+ const normalized = node_path.normalize(filePath);
719
+ return node_path.sep === '\\' ? normalized.replace(/\\/g, '/') : normalized;
720
+ }
721
+ /**
722
+ * Strip any trailing forward or back slashes from a path.
723
+ *
724
+ * @param filePath - Path that may have trailing slashes
725
+ * @returns Path with trailing slashes removed
726
+ */
727
+ function removeTrailingSlash(filePath) {
728
+ return filePath.replace(/[/\\]+$/, '');
729
+ }
730
+
731
+ /**
732
+ * Resolve path segments to an absolute path.
733
+ *
734
+ * @param segments - Path segments to resolve
735
+ * @returns Resolved absolute path with normalized separators
736
+ */
737
+ function resolvePath(...segments) {
738
+ return normalizePath(node_path.resolve(...segments));
739
+ }
740
+ /**
741
+ * Compute the normalized path from source directory to target.
742
+ *
743
+ * @param from - Source path (base directory)
744
+ * @param to - Target path to reach
745
+ * @returns Relative path from source to target with forward slashes
746
+ */
747
+ function relativePath(from, to) {
748
+ return normalizePath(node_path.relative(from, to));
749
+ }
750
+ /**
751
+ * Join path segments.
752
+ *
753
+ * @param segments - Path segments to join
754
+ * @returns Joined path with normalized separators
755
+ */
756
+ function joinPath(...segments) {
757
+ return normalizePath(node_path.join(...segments));
758
+ }
759
+ /**
760
+ * Check if path is absolute.
761
+ *
762
+ * @param filePath - Path to check
763
+ * @returns True if path is absolute
764
+ */
765
+ function isAbsolute(filePath) {
766
+ return node_path.isAbsolute(filePath);
767
+ }
768
+
769
+ /**
770
+ * Get directory name of path.
771
+ *
772
+ * @param filePath - Path to extract directory from
773
+ * @returns Directory name
774
+ */
775
+ function getDirname(filePath) {
776
+ return normalizePath(node_path.dirname(filePath));
777
+ }
778
+
779
+ createScopedLogger('project-scope:fs:traversal');
780
+
781
+ /**
782
+ * Write mode for file operations.
783
+ */
784
+ const Mode = freeze({
785
+ /** Overwrite existing files */
786
+ Overwrite: 'overwrite',
787
+ /** Fail if file exists */
788
+ ExclusiveCreate: 'exclusive',
789
+ /** Skip if file exists */
790
+ SkipIfExists: 'skip',
791
+ });
792
+
793
+ const fsTreeLogger = createScopedLogger('project-scope:vfs:tree');
794
+ /**
795
+ * Create a file system-backed tree implementation.
796
+ *
797
+ * Supports transactional modifications - all changes are buffered
798
+ * in memory and can be committed atomically or rolled back.
799
+ *
800
+ * @param root - Absolute path to the workspace root directory
801
+ * @param options - Configuration for verbose logging
802
+ * @returns A Tree instance
803
+ */
804
+ function createFsTree(root, options) {
805
+ const _root = removeTrailingSlash(normalizePath(root));
806
+ const _changes = createMap();
807
+ const _isVerbose = options?.verbose ?? false;
808
+ const _followSymlinks = options?.followSymlinks ?? true;
809
+ fsTreeLogger.debug('Creating VFS tree', { root: _root, verbose: _isVerbose, followSymlinks: _followSymlinks });
810
+ /**
811
+ * Normalize path to be relative from root.
812
+ *
813
+ * @param filePath - Path to normalize
814
+ * @returns Normalized relative path
815
+ * @throws {Error} if path traverses outside the tree root
816
+ */
817
+ function normalizeFilePath(filePath) {
818
+ const normalized = isAbsolute(filePath) ? relativePath(_root, filePath) : normalizePath(filePath);
819
+ const absoluteResolved = resolvePath(_root, normalized);
820
+ if (!absoluteResolved.startsWith(_root + '/') && absoluteResolved !== _root) {
821
+ throw createError(`Path escapes tree root: ${filePath}`);
822
+ }
823
+ return normalized;
824
+ }
825
+ /**
826
+ * Get absolute path on disk.
827
+ *
828
+ * @param filePath - Relative path from root
829
+ * @returns Absolute path on disk
830
+ */
831
+ function absolutePath(filePath) {
832
+ return joinPath(_root, normalizeFilePath(filePath));
833
+ }
834
+ /**
835
+ * Check if a normalized path is a symbolic link.
836
+ *
837
+ * @param normalPath - Already normalized path
838
+ * @returns True if path is a symlink
839
+ */
840
+ function isSymlinkNormalizedPath(normalPath) {
841
+ const absPath = absolutePath(normalPath);
842
+ try {
843
+ const stats = node_fs.lstatSync(absPath);
844
+ return stats.isSymbolicLink();
845
+ }
846
+ catch {
847
+ return false;
848
+ }
849
+ }
850
+ /**
851
+ * Validate that a symlink target stays within tree bounds.
852
+ *
853
+ * @param normalPath - Already normalized path to symlink
854
+ * @throws {Error} If symlink target escapes tree root or followSymlinks is disabled
855
+ */
856
+ function validateSymlink(normalPath) {
857
+ const absPath = absolutePath(normalPath);
858
+ if (!isSymlinkNormalizedPath(normalPath)) {
859
+ return;
860
+ }
861
+ if (!_followSymlinks) {
862
+ throw createError(`Cannot access symlink when followSymlinks is disabled: ${normalPath}`);
863
+ }
864
+ try {
865
+ const target = node_fs.readlinkSync(absPath);
866
+ let targetAbsolute;
867
+ if (isAbsolute(target)) {
868
+ targetAbsolute = target;
869
+ }
870
+ else {
871
+ const symlinkDir = getDirname(absPath);
872
+ targetAbsolute = resolvePath(symlinkDir, target);
873
+ }
874
+ const normalizedTarget = normalizePath(targetAbsolute);
875
+ if (!normalizedTarget.startsWith(_root + '/') && normalizedTarget !== _root) {
876
+ throw createError(`Symlink target escapes tree root: ${normalPath} -> ${target}`);
877
+ }
878
+ }
879
+ catch (error) {
880
+ /* istanbul ignore else -- other errors are rare edge cases (e.g., permission denied) */
881
+ if (error instanceof Error && error.message.includes('Symlink target escapes')) {
882
+ throw error;
883
+ }
884
+ if (error instanceof Error && error.message.includes('followSymlinks is disabled')) {
885
+ throw error;
886
+ }
887
+ throw createError(`Failed to validate symlink: ${normalPath}`);
888
+ }
889
+ }
890
+ /**
891
+ * Check if path exists on disk (not considering buffered changes).
892
+ *
893
+ * @param normalPath - Normalized path to check
894
+ * @returns True if exists on disk
895
+ */
896
+ function existsOnDisk(normalPath) {
897
+ const absPath = absolutePath(normalPath);
898
+ return exists(absPath);
899
+ }
900
+ /**
901
+ * Read from disk (not considering buffered changes).
902
+ *
903
+ * @param normalPath - Normalized path to read
904
+ * @returns File content or null
905
+ */
906
+ function readFromDisk(normalPath) {
907
+ validateSymlink(normalPath);
908
+ const absPath = absolutePath(normalPath);
909
+ if (!isFile(absPath)) {
910
+ return null;
911
+ }
912
+ try {
913
+ return node_fs.readFileSync(absPath);
914
+ }
915
+ catch {
916
+ return null;
917
+ }
918
+ }
919
+ const tree = {
920
+ get root() {
921
+ return _root;
922
+ },
923
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
924
+ read(filePath, encoding) {
925
+ const normalPath = normalizeFilePath(filePath);
926
+ const change = _changes.get(normalPath);
927
+ if (change) {
928
+ if (change.type === 'DELETE') {
929
+ return null;
930
+ }
931
+ if (change.content !== null) {
932
+ return encoding ? change.content.toString(encoding) : change.content;
933
+ }
934
+ }
935
+ validateSymlink(normalPath);
936
+ const absPath = absolutePath(normalPath);
937
+ if (!exists(absPath)) {
938
+ return null;
939
+ }
940
+ if (!isFile(absPath)) {
941
+ return null;
942
+ }
943
+ try {
944
+ const content = node_fs.readFileSync(absPath);
945
+ return encoding ? content.toString(encoding) : content;
946
+ }
947
+ catch {
948
+ return null;
949
+ }
950
+ },
951
+ write(filePath, content, options) {
952
+ const normalPath = normalizeFilePath(filePath);
953
+ const buffer = typeof content === 'string' ? Buffer.from(content, 'utf-8') : content;
954
+ fsTreeLogger.debug('write', { path: normalPath, size: buffer.length, mode: options?.mode ?? 'Overwrite' });
955
+ const mode = options?.mode ?? Mode.Overwrite;
956
+ if (mode === Mode.ExclusiveCreate && this.exists(normalPath)) {
957
+ throw createError(`File already exists: ${normalPath}`);
958
+ }
959
+ if (mode === Mode.SkipIfExists && this.exists(normalPath)) {
960
+ return;
961
+ }
962
+ const existingChange = _changes.get(normalPath);
963
+ const diskExists = existsOnDisk(normalPath);
964
+ let changeType;
965
+ let originalContent = null;
966
+ if (existingChange?.type === 'CREATE' || (!diskExists && !existingChange)) {
967
+ changeType = 'CREATE';
968
+ }
969
+ else {
970
+ changeType = 'UPDATE';
971
+ originalContent = existingChange?.originalContent ?? readFromDisk(normalPath);
972
+ }
973
+ _changes.set(normalPath, {
974
+ type: changeType,
975
+ content: buffer,
976
+ originalContent,
977
+ permissions: options?.permissions,
978
+ });
979
+ },
980
+ exists(filePath) {
981
+ const normalPath = normalizeFilePath(filePath);
982
+ const change = _changes.get(normalPath);
983
+ if (change) {
984
+ return change.type !== 'DELETE';
985
+ }
986
+ for (const [changedPath, record] of _changes) {
987
+ if (record.type !== 'DELETE' && changedPath.startsWith(normalPath + '/')) {
988
+ return true;
989
+ }
990
+ }
991
+ return existsOnDisk(normalPath);
992
+ },
993
+ delete(filePath) {
994
+ const normalPath = normalizeFilePath(filePath);
995
+ fsTreeLogger.debug('delete', { path: normalPath });
996
+ const existingChange = _changes.get(normalPath);
997
+ if (existingChange?.type === 'CREATE') {
998
+ _changes.delete(normalPath);
999
+ return;
1000
+ }
1001
+ if (!existsOnDisk(normalPath)) {
1002
+ return;
1003
+ }
1004
+ _changes.set(normalPath, {
1005
+ type: 'DELETE',
1006
+ content: null,
1007
+ originalContent: readFromDisk(normalPath),
1008
+ });
1009
+ },
1010
+ rename(from, to) {
1011
+ const content = this.read(from);
1012
+ if (content === null) {
1013
+ throw createError(`Source file not found: ${from}`);
1014
+ }
1015
+ this.write(to, content);
1016
+ this.delete(from);
1017
+ },
1018
+ isFile(filePath) {
1019
+ const normalPath = normalizeFilePath(filePath);
1020
+ const change = _changes.get(normalPath);
1021
+ if (change) {
1022
+ return change.type !== 'DELETE';
1023
+ }
1024
+ const absPath = absolutePath(normalPath);
1025
+ return isFile(absPath);
1026
+ },
1027
+ isDirectory(filePath) {
1028
+ const normalPath = normalizeFilePath(filePath);
1029
+ for (const [changedPath, change] of _changes) {
1030
+ if (change.type !== 'DELETE' && changedPath.startsWith(normalPath + '/')) {
1031
+ return true;
1032
+ }
1033
+ }
1034
+ const absPath = absolutePath(normalPath);
1035
+ return isDirectory(absPath);
1036
+ },
1037
+ isSymlink(filePath) {
1038
+ const normalPath = normalizeFilePath(filePath);
1039
+ return isSymlinkNormalizedPath(normalPath);
1040
+ },
1041
+ children(dirPath) {
1042
+ const normalPath = normalizeFilePath(dirPath);
1043
+ const childSet = createSet();
1044
+ const absPath = absolutePath(normalPath);
1045
+ try {
1046
+ if (exists(absPath) && isDirectory(absPath)) {
1047
+ const entries = readDirectory(absPath);
1048
+ for (const entry of entries) {
1049
+ childSet.add(entry.name);
1050
+ }
1051
+ }
1052
+ }
1053
+ catch {
1054
+ // Directory doesn't exist on disk
1055
+ }
1056
+ const prefix = normalPath === '.' || normalPath === '' ? '' : normalPath + '/';
1057
+ for (const [changedPath, change] of _changes) {
1058
+ // Handle root-level files
1059
+ if (prefix === '') {
1060
+ const childName = changedPath.split('/')[0];
1061
+ if (change.type === 'DELETE' && !changedPath.includes('/')) {
1062
+ childSet.delete(childName);
1063
+ }
1064
+ else if (change.type !== 'DELETE') {
1065
+ childSet.add(childName);
1066
+ }
1067
+ continue;
1068
+ }
1069
+ if (!changedPath.startsWith(prefix)) {
1070
+ continue;
1071
+ }
1072
+ const relativePath = changedPath.slice(prefix.length);
1073
+ const childName = relativePath.split('/')[0];
1074
+ if (change.type === 'DELETE') {
1075
+ // Only remove if it's a direct child being deleted
1076
+ if (!relativePath.includes('/')) {
1077
+ childSet.delete(childName);
1078
+ }
1079
+ }
1080
+ else {
1081
+ childSet.add(childName);
1082
+ }
1083
+ }
1084
+ return from(childSet).sort();
1085
+ },
1086
+ listChanges() {
1087
+ const changes = [];
1088
+ for (const [path, record] of _changes) {
1089
+ changes.push({
1090
+ path,
1091
+ type: record.type,
1092
+ content: record.content ?? undefined,
1093
+ originalContent: record.originalContent ?? undefined,
1094
+ mode: record.permissions,
1095
+ });
1096
+ }
1097
+ return changes.sort((a, b) => a.path.localeCompare(b.path));
1098
+ },
1099
+ changePermissions(filePath, mode) {
1100
+ const normalPath = normalizeFilePath(filePath);
1101
+ if (!this.exists(normalPath)) {
1102
+ throw createError(`File not found: ${normalPath}`);
1103
+ }
1104
+ const existingChange = _changes.get(normalPath);
1105
+ if (existingChange) {
1106
+ existingChange.permissions = mode;
1107
+ }
1108
+ else {
1109
+ const content = readFromDisk(normalPath);
1110
+ _changes.set(normalPath, {
1111
+ type: 'UPDATE',
1112
+ content,
1113
+ originalContent: content,
1114
+ permissions: mode,
1115
+ });
1116
+ }
1117
+ },
1118
+ changeFile(filePath, transform) {
1119
+ const content = this.read(filePath);
1120
+ if (content === null) {
1121
+ throw createError(`File not found: ${filePath}`);
1122
+ }
1123
+ const newContent = transform(content);
1124
+ this.write(filePath, newContent);
1125
+ },
1126
+ clearChanges() {
1127
+ _changes.clear();
1128
+ },
1129
+ };
1130
+ return tree;
1131
+ }
1132
+
1133
+ const factoryLogger = createScopedLogger('project-scope:vfs:factory');
1134
+ /**
1135
+ * Create a virtual file system tree.
1136
+ *
1137
+ * @param root - Root directory path
1138
+ * @param options - Tree creation options
1139
+ * @returns A new Tree instance
1140
+ * @throws {Error} If root doesn't exist or isn't a directory
1141
+ *
1142
+ * @example
1143
+ * ```typescript
1144
+ * import { createTree } from '@hyperfrontend/project-scope'
1145
+ *
1146
+ * const tree = createTree('./my-project')
1147
+ *
1148
+ * // Read files from tree
1149
+ * const content = tree.read('src/index.ts', 'utf-8')
1150
+ *
1151
+ * // Make changes (buffered in memory)
1152
+ * tree.write('src/new-file.ts', 'export const x = 1')
1153
+ *
1154
+ * // List pending changes
1155
+ * console.log(tree.listChanges())
1156
+ * ```
1157
+ */
1158
+ function createTree(root, options) {
1159
+ const normalizedRoot = normalizePath(root);
1160
+ factoryLogger.debug('createTree', { root: normalizedRoot });
1161
+ // Validate root exists
1162
+ if (!exists(normalizedRoot)) {
1163
+ factoryLogger.warn('createTree failed: root does not exist', { root: normalizedRoot });
1164
+ throw createError(`Root directory does not exist: ${normalizedRoot}`);
1165
+ }
1166
+ // Validate root is a directory
1167
+ if (!isDirectory(normalizedRoot)) {
1168
+ factoryLogger.warn('createTree failed: root is not a directory', { root: normalizedRoot });
1169
+ throw createError(`Root path is not a directory: ${normalizedRoot}`);
1170
+ }
1171
+ return createFsTree(normalizedRoot, options);
1172
+ }
1173
+ /**
1174
+ * Create a tree from disk.
1175
+ *
1176
+ * Convenience alias for createTree.
1177
+ *
1178
+ * @param root - Root directory path
1179
+ * @param options - Tree creation options
1180
+ * @returns A new Tree instance backed by disk
1181
+ */
1182
+ function createTreeFromDisk(root, options) {
1183
+ return createTree(root, options);
1184
+ }
1185
+
1186
+ const vfsLogger = createScopedLogger('project-scope:vfs');
1187
+ /**
1188
+ * Commit buffered changes to disk.
1189
+ *
1190
+ * @param tree - Virtual file system tree with pending modifications
1191
+ * @param options - Configuration for dry-run and verbosity
1192
+ * @returns Result of the commit operation
1193
+ *
1194
+ * @example
1195
+ * ```typescript
1196
+ * import { createTree, commitChanges } from '@hyperfrontend/project-scope'
1197
+ *
1198
+ * const tree = createTree('./my-project')
1199
+ * tree.write('src/new-file.ts', 'export const hello = "world"')
1200
+ *
1201
+ * // Preview changes without writing
1202
+ * const preview = commitChanges(tree, { dryRun: true })
1203
+ * console.log('Would create:', preview.created, 'files')
1204
+ *
1205
+ * // Actually commit changes
1206
+ * const result = commitChanges(tree)
1207
+ * console.log('Created:', result.created, 'Updated:', result.updated)
1208
+ * ```
1209
+ */
1210
+ function commitChanges(tree, options) {
1211
+ const changes = tree.listChanges();
1212
+ const appliedChanges = [];
1213
+ // Set log level based on verbose option
1214
+ if (options?.verbose) {
1215
+ vfsLogger.setLogLevel('debug');
1216
+ }
1217
+ vfsLogger.debug('Committing changes', { changeCount: changes.length, dryRun: options?.dryRun });
1218
+ const result = {
1219
+ created: 0,
1220
+ updated: 0,
1221
+ deleted: 0,
1222
+ changes: [],
1223
+ dryRun: options?.dryRun ?? false,
1224
+ };
1225
+ // Dry run - just count changes without writing
1226
+ if (options?.dryRun) {
1227
+ for (const change of changes) {
1228
+ switch (change.type) {
1229
+ case 'CREATE':
1230
+ result.created++;
1231
+ break;
1232
+ case 'UPDATE':
1233
+ result.updated++;
1234
+ break;
1235
+ case 'DELETE':
1236
+ result.deleted++;
1237
+ break;
1238
+ }
1239
+ }
1240
+ result.changes = changes;
1241
+ return result;
1242
+ }
1243
+ // Sort changes: deletes first (to free names), then creates, then updates
1244
+ const sortedChanges = [...changes].sort((a, b) => {
1245
+ const order = { DELETE: 0, CREATE: 1, UPDATE: 2 };
1246
+ return order[a.type] - order[b.type];
1247
+ });
1248
+ for (const change of sortedChanges) {
1249
+ const absPath = node_path.join(tree.root, change.path);
1250
+ try {
1251
+ switch (change.type) {
1252
+ case 'CREATE':
1253
+ case 'UPDATE':
1254
+ /* istanbul ignore if -- content is always defined for CREATE/UPDATE from tree.write() */
1255
+ if (change.content !== undefined) {
1256
+ // Ensure directory exists
1257
+ const dir = node_path.dirname(absPath);
1258
+ ensureDir(dir);
1259
+ node_fs.writeFileSync(absPath, change.content);
1260
+ // Apply permissions if specified
1261
+ if (change.mode !== undefined) {
1262
+ node_fs.chmodSync(absPath, change.mode);
1263
+ }
1264
+ if (change.type === 'CREATE') {
1265
+ result.created++;
1266
+ }
1267
+ else {
1268
+ result.updated++;
1269
+ }
1270
+ }
1271
+ break;
1272
+ case 'DELETE':
1273
+ if (exists(absPath)) {
1274
+ try {
1275
+ node_fs.unlinkSync(absPath);
1276
+ }
1277
+ catch {
1278
+ // Try recursive delete for directories
1279
+ node_fs.rmSync(absPath, { recursive: true });
1280
+ }
1281
+ }
1282
+ result.deleted++;
1283
+ break;
1284
+ }
1285
+ appliedChanges.push(change);
1286
+ if (options?.verbose) {
1287
+ const prefix = change.type === 'CREATE' ? '+' : change.type === 'DELETE' ? '-' : '~';
1288
+ vfsLogger.info(`${prefix} ${change.path}`);
1289
+ }
1290
+ }
1291
+ catch (error) {
1292
+ // On error, throw with context
1293
+ vfsLogger.error('Commit failed', { path: change.path, type: change.type });
1294
+ const message = error instanceof Error
1295
+ ? `Failed to ${change.type.toLowerCase()} ${change.path}: ${error.message}`
1296
+ : `Failed to ${change.type.toLowerCase()} ${change.path}`;
1297
+ throw createError(message);
1298
+ }
1299
+ }
1300
+ result.changes = appliedChanges;
1301
+ // Clear the tree's pending changes after successful commit
1302
+ tree.clearChanges();
1303
+ return result;
1304
+ }
1305
+ /**
1306
+ * Discard all pending changes.
1307
+ *
1308
+ * @param tree - Virtual file system tree
1309
+ */
1310
+ function rollbackChanges(tree) {
1311
+ tree.clearChanges();
1312
+ }
1313
+
1314
+ const diffLogger = createScopedLogger('project-scope:vfs:diff');
1315
+ const DEFAULT_CONTEXT_LINES = 3;
1316
+ /**
1317
+ * Compute the Longest Common Subsequence (LCS) table for two arrays of lines.
1318
+ * Uses dynamic programming for O(n*m) time complexity.
1319
+ *
1320
+ * @param oldLines - Lines from the original file version
1321
+ * @param newLines - Lines from the new file version
1322
+ * @returns Two-dimensional LCS table for backtracking
1323
+ */
1324
+ function computeLcsTable(oldLines, newLines) {
1325
+ const m = oldLines.length;
1326
+ const n = newLines.length;
1327
+ const table = from({ length: m + 1 }, () => Array(n + 1).fill(0));
1328
+ for (let i = 1; i <= m; i++) {
1329
+ for (let j = 1; j <= n; j++) {
1330
+ if (oldLines[i - 1] === newLines[j - 1]) {
1331
+ table[i][j] = table[i - 1][j - 1] + 1;
1332
+ }
1333
+ else {
1334
+ table[i][j] = max(table[i - 1][j], table[i][j - 1]);
1335
+ }
1336
+ }
1337
+ }
1338
+ return table;
1339
+ }
1340
+ /**
1341
+ * Backtrack through LCS table to produce diff operations.
1342
+ *
1343
+ * @param table - Two-dimensional LCS table from computeLcsTable
1344
+ * @param oldLines - Lines from the original file version
1345
+ * @param newLines - Lines from the new file version
1346
+ * @returns Array of diff operations (unfiltered, includes all lines)
1347
+ */
1348
+ function backtrackLcs(table, oldLines, newLines) {
1349
+ const result = [];
1350
+ let i = oldLines.length;
1351
+ let j = newLines.length;
1352
+ while (i > 0 || j > 0) {
1353
+ if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {
1354
+ result.unshift({ type: 'same', oldIdx: i - 1, newIdx: j - 1, content: oldLines[i - 1] });
1355
+ i--;
1356
+ j--;
1357
+ }
1358
+ else if (j > 0 && (i === 0 || table[i][j - 1] >= table[i - 1][j])) {
1359
+ result.unshift({ type: 'add', oldIdx: i - 1, newIdx: j - 1, content: newLines[j - 1] });
1360
+ j--;
1361
+ }
1362
+ else {
1363
+ result.unshift({ type: 'remove', oldIdx: i - 1, newIdx: -1, content: oldLines[i - 1] });
1364
+ i--;
1365
+ }
1366
+ }
1367
+ return result;
1368
+ }
1369
+ /**
1370
+ * Convert raw diff operations to DiffLine array with context filtering.
1371
+ *
1372
+ * @param operations - Raw diff operations
1373
+ * @param contextLines - Number of context lines to include
1374
+ * @returns Filtered DiffLine array
1375
+ */
1376
+ function operationsToDiffLines(operations, contextLines) {
1377
+ // Mark which lines should be included (changes + context)
1378
+ const include = new Array(operations.length).fill(false);
1379
+ // First pass: mark all changes
1380
+ for (let i = 0; i < operations.length; i++) {
1381
+ if (operations[i].type !== 'same') {
1382
+ // Mark this line and context around it
1383
+ for (let j = max(0, i - contextLines); j <= min(operations.length - 1, i + contextLines); j++) {
1384
+ include[j] = true;
1385
+ }
1386
+ }
1387
+ }
1388
+ // Second pass: convert to DiffLine
1389
+ const lines = [];
1390
+ let oldLineNum = 1;
1391
+ let newLineNum = 1;
1392
+ for (let i = 0; i < operations.length; i++) {
1393
+ const op = operations[i];
1394
+ if (include[i]) {
1395
+ if (op.type === 'same') {
1396
+ lines.push({ type: 'context', line: oldLineNum, content: op.content });
1397
+ oldLineNum++;
1398
+ newLineNum++;
1399
+ }
1400
+ else if (op.type === 'remove') {
1401
+ lines.push({ type: 'remove', line: oldLineNum, content: op.content });
1402
+ oldLineNum++;
1403
+ }
1404
+ else {
1405
+ lines.push({ type: 'add', line: newLineNum, content: op.content });
1406
+ newLineNum++;
1407
+ }
1408
+ }
1409
+ else {
1410
+ // Skip but update line numbers
1411
+ if (op.type === 'same') {
1412
+ oldLineNum++;
1413
+ newLineNum++;
1414
+ }
1415
+ else if (op.type === 'remove') {
1416
+ /* istanbul ignore next -- unreachable: remove operations always have include=true */
1417
+ oldLineNum++;
1418
+ }
1419
+ else {
1420
+ /* istanbul ignore next -- unreachable: add operations always have include=true */
1421
+ newLineNum++;
1422
+ }
1423
+ }
1424
+ }
1425
+ return lines;
1426
+ }
1427
+ /**
1428
+ * Split buffer content into lines.
1429
+ *
1430
+ * @param content - File content as Buffer, or undefined for empty
1431
+ * @returns Array of string lines from the buffer
1432
+ */
1433
+ function bufferToLines(content) {
1434
+ if (!content)
1435
+ return [];
1436
+ const text = content.toString('utf-8');
1437
+ // Split by newline, keeping empty last line if present
1438
+ return text.split('\n');
1439
+ }
1440
+ /**
1441
+ * Generate a diff for a single file change.
1442
+ *
1443
+ * @example
1444
+ * ```typescript
1445
+ * const change: FileChange = {
1446
+ * path: 'src/app.ts',
1447
+ * type: 'UPDATE',
1448
+ * originalContent: Buffer.from('const x = 1;\n'),
1449
+ * content: Buffer.from('const x = 2;\n'),
1450
+ * }
1451
+ * const diff = generateDiff(change)
1452
+ * // { path: 'src/app.ts', additions: 1, deletions: 1, lines: [...] }
1453
+ * ```
1454
+ *
1455
+ * @param change - File change to diff
1456
+ * @param options - Configuration for diff generation including context lines
1457
+ * @returns FileDiff object
1458
+ */
1459
+ function generateDiff(change, options = {}) {
1460
+ const contextLines = options.contextLines ?? DEFAULT_CONTEXT_LINES;
1461
+ diffLogger.debug('generateDiff', { path: change.path, type: change.type, contextLines });
1462
+ const oldLines = bufferToLines(change.originalContent);
1463
+ const newLines = bufferToLines(change.content);
1464
+ // Handle edge cases
1465
+ if (change.type === 'CREATE') {
1466
+ // All lines are additions
1467
+ const lines = newLines
1468
+ .filter((line) => line !== '' || newLines.indexOf(line) !== newLines.length - 1 || newLines.length === 1)
1469
+ .map((content, idx) => ({
1470
+ type: 'add',
1471
+ line: idx + 1,
1472
+ content,
1473
+ }));
1474
+ // Filter out empty trailing line from split
1475
+ const filteredLines = lines.filter((l, i) => !(i === lines.length - 1 && l.content === '' && lines.length > 1));
1476
+ return {
1477
+ path: change.path,
1478
+ lines: filteredLines,
1479
+ additions: filteredLines.length,
1480
+ deletions: 0,
1481
+ };
1482
+ }
1483
+ if (change.type === 'DELETE') {
1484
+ // All lines are deletions
1485
+ const lines = oldLines.map((content, idx) => ({
1486
+ type: 'remove',
1487
+ line: idx + 1,
1488
+ content,
1489
+ }));
1490
+ // Filter out empty trailing line from split
1491
+ const filteredLines = lines.filter((l, i) => !(i === lines.length - 1 && l.content === '' && lines.length > 1));
1492
+ return {
1493
+ path: change.path,
1494
+ lines: filteredLines,
1495
+ additions: 0,
1496
+ deletions: filteredLines.length,
1497
+ };
1498
+ }
1499
+ // UPDATE: compute actual diff
1500
+ const table = computeLcsTable(oldLines, newLines);
1501
+ const operations = backtrackLcs(table, oldLines, newLines);
1502
+ const lines = operationsToDiffLines(operations, contextLines);
1503
+ const additions = lines.filter((l) => l.type === 'add').length;
1504
+ const deletions = lines.filter((l) => l.type === 'remove').length;
1505
+ return {
1506
+ path: change.path,
1507
+ lines,
1508
+ additions,
1509
+ deletions,
1510
+ };
1511
+ }
1512
+ /**
1513
+ * Format a FileDiff as a unified diff string.
1514
+ *
1515
+ * @example
1516
+ * ```typescript
1517
+ * const formatted = formatUnifiedDiff(diff)
1518
+ * console.log(formatted)
1519
+ * // --- a/src/app.ts
1520
+ * // +++ b/src/app.ts
1521
+ * // @@ -1,3 +1,3 @@
1522
+ * // const x = 1;
1523
+ * // -const y = 2;
1524
+ * // +const y = 3;
1525
+ * // const z = 4;
1526
+ * ```
1527
+ *
1528
+ * @param diff - FileDiff to format
1529
+ * @returns Unified diff string
1530
+ */
1531
+ function formatUnifiedDiff(diff) {
1532
+ const lines = [];
1533
+ // Header
1534
+ lines.push(`--- a/${diff.path}`);
1535
+ lines.push(`+++ b/${diff.path}`);
1536
+ if (diff.lines.length === 0) {
1537
+ return lines.join('\n');
1538
+ }
1539
+ // Group lines into hunks
1540
+ const hunks = [];
1541
+ const currentHunk = [];
1542
+ for (const line of diff.lines) {
1543
+ currentHunk.push(line);
1544
+ }
1545
+ if (currentHunk.length > 0) {
1546
+ hunks.push(currentHunk);
1547
+ }
1548
+ // Output hunks
1549
+ for (const hunk of hunks) {
1550
+ // Calculate hunk header
1551
+ const contextAndRemove = hunk.filter((l) => l.type === 'context' || l.type === 'remove');
1552
+ const contextAndAdd = hunk.filter((l) => l.type === 'context' || l.type === 'add');
1553
+ const oldStart = hunk.find((l) => l.type === 'context' || l.type === 'remove')?.line ?? 1;
1554
+ const newStart = hunk.find((l) => l.type === 'context' || l.type === 'add')?.line ?? 1;
1555
+ const oldCount = contextAndRemove.length;
1556
+ const newCount = contextAndAdd.length;
1557
+ lines.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
1558
+ // Output lines
1559
+ for (const line of hunk) {
1560
+ const prefix = line.type === 'add' ? '+' : line.type === 'remove' ? '-' : ' ';
1561
+ lines.push(`${prefix}${line.content}`);
1562
+ }
1563
+ }
1564
+ return lines.join('\n');
1565
+ }
1566
+ /**
1567
+ * Generate diffs for all changes in a tree.
1568
+ *
1569
+ * @example
1570
+ * ```typescript
1571
+ * const tree = createTree('/workspace')
1572
+ * tree.write('new.txt', 'hello')
1573
+ * tree.delete('old.txt')
1574
+ *
1575
+ * const diffs = generateAllDiffs(tree)
1576
+ * for (const diff of diffs) {
1577
+ * console.log(formatUnifiedDiff(diff))
1578
+ * }
1579
+ * ```
1580
+ *
1581
+ * @param tree - Tree to generate diffs for
1582
+ * @param options - Diff options
1583
+ * @returns Array of FileDiff objects
1584
+ */
1585
+ function generateAllDiffs(tree, options = {}) {
1586
+ const changes = tree.listChanges();
1587
+ diffLogger.debug('generateAllDiffs', { changeCount: changes.length });
1588
+ return changes.map((change) => generateDiff(change, options));
1589
+ }
1590
+
1591
+ exports.Mode = Mode;
1592
+ exports.commitChanges = commitChanges;
1593
+ exports.createFsTree = createFsTree;
1594
+ exports.createTree = createTree;
1595
+ exports.createTreeFromDisk = createTreeFromDisk;
1596
+ exports.formatUnifiedDiff = formatUnifiedDiff;
1597
+ exports.generateAllDiffs = generateAllDiffs;
1598
+ exports.generateDiff = generateDiff;
1599
+ exports.rollbackChanges = rollbackChanges;
1600
+ //# sourceMappingURL=index.cjs.js.map