@hyperfrontend/project-scope 0.2.0 → 0.2.2

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