@hyperfrontend/project-scope 0.1.0

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