@hyperfrontend/versioning 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 (353) hide show
  1. package/ARCHITECTURE.md +593 -0
  2. package/CHANGELOG.md +35 -0
  3. package/FUNDING.md +141 -0
  4. package/LICENSE.md +21 -0
  5. package/README.md +195 -0
  6. package/SECURITY.md +82 -0
  7. package/changelog/compare/diff.d.ts +128 -0
  8. package/changelog/compare/diff.d.ts.map +1 -0
  9. package/changelog/compare/index.cjs.js +628 -0
  10. package/changelog/compare/index.cjs.js.map +1 -0
  11. package/changelog/compare/index.d.ts +4 -0
  12. package/changelog/compare/index.d.ts.map +1 -0
  13. package/changelog/compare/index.esm.js +612 -0
  14. package/changelog/compare/index.esm.js.map +1 -0
  15. package/changelog/compare/is-equal.d.ts +114 -0
  16. package/changelog/compare/is-equal.d.ts.map +1 -0
  17. package/changelog/index.cjs.js +6448 -0
  18. package/changelog/index.cjs.js.map +1 -0
  19. package/changelog/index.d.ts +6 -0
  20. package/changelog/index.d.ts.map +1 -0
  21. package/changelog/index.esm.js +6358 -0
  22. package/changelog/index.esm.js.map +1 -0
  23. package/changelog/models/changelog.d.ts +86 -0
  24. package/changelog/models/changelog.d.ts.map +1 -0
  25. package/changelog/models/commit-ref.d.ts +51 -0
  26. package/changelog/models/commit-ref.d.ts.map +1 -0
  27. package/changelog/models/entry.d.ts +84 -0
  28. package/changelog/models/entry.d.ts.map +1 -0
  29. package/changelog/models/index.cjs.js +2043 -0
  30. package/changelog/models/index.cjs.js.map +1 -0
  31. package/changelog/models/index.d.ts +11 -0
  32. package/changelog/models/index.d.ts.map +1 -0
  33. package/changelog/models/index.esm.js +2026 -0
  34. package/changelog/models/index.esm.js.map +1 -0
  35. package/changelog/models/schema.d.ts +68 -0
  36. package/changelog/models/schema.d.ts.map +1 -0
  37. package/changelog/models/section.d.ts +25 -0
  38. package/changelog/models/section.d.ts.map +1 -0
  39. package/changelog/operations/add-entry.d.ts +56 -0
  40. package/changelog/operations/add-entry.d.ts.map +1 -0
  41. package/changelog/operations/add-item.d.ts +18 -0
  42. package/changelog/operations/add-item.d.ts.map +1 -0
  43. package/changelog/operations/filter-by-predicate.d.ts +81 -0
  44. package/changelog/operations/filter-by-predicate.d.ts.map +1 -0
  45. package/changelog/operations/filter-by-range.d.ts +63 -0
  46. package/changelog/operations/filter-by-range.d.ts.map +1 -0
  47. package/changelog/operations/filter-entries.d.ts +9 -0
  48. package/changelog/operations/filter-entries.d.ts.map +1 -0
  49. package/changelog/operations/index.cjs.js +2455 -0
  50. package/changelog/operations/index.cjs.js.map +1 -0
  51. package/changelog/operations/index.d.ts +15 -0
  52. package/changelog/operations/index.d.ts.map +1 -0
  53. package/changelog/operations/index.esm.js +2411 -0
  54. package/changelog/operations/index.esm.js.map +1 -0
  55. package/changelog/operations/merge.d.ts +88 -0
  56. package/changelog/operations/merge.d.ts.map +1 -0
  57. package/changelog/operations/remove-entry.d.ts +45 -0
  58. package/changelog/operations/remove-entry.d.ts.map +1 -0
  59. package/changelog/operations/remove-section.d.ts +50 -0
  60. package/changelog/operations/remove-section.d.ts.map +1 -0
  61. package/changelog/operations/transform.d.ts +143 -0
  62. package/changelog/operations/transform.d.ts.map +1 -0
  63. package/changelog/parse/index.cjs.js +1282 -0
  64. package/changelog/parse/index.cjs.js.map +1 -0
  65. package/changelog/parse/index.d.ts +5 -0
  66. package/changelog/parse/index.d.ts.map +1 -0
  67. package/changelog/parse/index.esm.js +1275 -0
  68. package/changelog/parse/index.esm.js.map +1 -0
  69. package/changelog/parse/line.d.ts +48 -0
  70. package/changelog/parse/line.d.ts.map +1 -0
  71. package/changelog/parse/parser.d.ts +16 -0
  72. package/changelog/parse/parser.d.ts.map +1 -0
  73. package/changelog/parse/tokenizer.d.ts +49 -0
  74. package/changelog/parse/tokenizer.d.ts.map +1 -0
  75. package/changelog/serialize/index.cjs.js +574 -0
  76. package/changelog/serialize/index.cjs.js.map +1 -0
  77. package/changelog/serialize/index.d.ts +6 -0
  78. package/changelog/serialize/index.d.ts.map +1 -0
  79. package/changelog/serialize/index.esm.js +564 -0
  80. package/changelog/serialize/index.esm.js.map +1 -0
  81. package/changelog/serialize/templates.d.ts +81 -0
  82. package/changelog/serialize/templates.d.ts.map +1 -0
  83. package/changelog/serialize/to-json.d.ts +57 -0
  84. package/changelog/serialize/to-json.d.ts.map +1 -0
  85. package/changelog/serialize/to-string.d.ts +30 -0
  86. package/changelog/serialize/to-string.d.ts.map +1 -0
  87. package/commits/index.cjs.js +648 -0
  88. package/commits/index.cjs.js.map +1 -0
  89. package/commits/index.d.ts +3 -0
  90. package/commits/index.d.ts.map +1 -0
  91. package/commits/index.esm.js +629 -0
  92. package/commits/index.esm.js.map +1 -0
  93. package/commits/models/breaking.d.ts +39 -0
  94. package/commits/models/breaking.d.ts.map +1 -0
  95. package/commits/models/commit-type.d.ts +32 -0
  96. package/commits/models/commit-type.d.ts.map +1 -0
  97. package/commits/models/conventional.d.ts +49 -0
  98. package/commits/models/conventional.d.ts.map +1 -0
  99. package/commits/models/index.cjs.js +207 -0
  100. package/commits/models/index.cjs.js.map +1 -0
  101. package/commits/models/index.d.ts +7 -0
  102. package/commits/models/index.d.ts.map +1 -0
  103. package/commits/models/index.esm.js +193 -0
  104. package/commits/models/index.esm.js.map +1 -0
  105. package/commits/parse/body.d.ts +18 -0
  106. package/commits/parse/body.d.ts.map +1 -0
  107. package/commits/parse/footer.d.ts +16 -0
  108. package/commits/parse/footer.d.ts.map +1 -0
  109. package/commits/parse/header.d.ts +15 -0
  110. package/commits/parse/header.d.ts.map +1 -0
  111. package/commits/parse/index.cjs.js +505 -0
  112. package/commits/parse/index.cjs.js.map +1 -0
  113. package/commits/parse/index.d.ts +5 -0
  114. package/commits/parse/index.d.ts.map +1 -0
  115. package/commits/parse/index.esm.js +499 -0
  116. package/commits/parse/index.esm.js.map +1 -0
  117. package/commits/parse/message.d.ts +17 -0
  118. package/commits/parse/message.d.ts.map +1 -0
  119. package/commits/utils/replace-char.d.ts +19 -0
  120. package/commits/utils/replace-char.d.ts.map +1 -0
  121. package/flow/executor/execute.d.ts +72 -0
  122. package/flow/executor/execute.d.ts.map +1 -0
  123. package/flow/executor/index.cjs.js +4402 -0
  124. package/flow/executor/index.cjs.js.map +1 -0
  125. package/flow/executor/index.d.ts +3 -0
  126. package/flow/executor/index.d.ts.map +1 -0
  127. package/flow/executor/index.esm.js +4398 -0
  128. package/flow/executor/index.esm.js.map +1 -0
  129. package/flow/factory.d.ts +58 -0
  130. package/flow/factory.d.ts.map +1 -0
  131. package/flow/index.cjs.js +8506 -0
  132. package/flow/index.cjs.js.map +1 -0
  133. package/flow/index.d.ts +7 -0
  134. package/flow/index.d.ts.map +1 -0
  135. package/flow/index.esm.js +8451 -0
  136. package/flow/index.esm.js.map +1 -0
  137. package/flow/models/flow.d.ts +130 -0
  138. package/flow/models/flow.d.ts.map +1 -0
  139. package/flow/models/index.cjs.js +285 -0
  140. package/flow/models/index.cjs.js.map +1 -0
  141. package/flow/models/index.d.ts +7 -0
  142. package/flow/models/index.d.ts.map +1 -0
  143. package/flow/models/index.esm.js +268 -0
  144. package/flow/models/index.esm.js.map +1 -0
  145. package/flow/models/step.d.ts +108 -0
  146. package/flow/models/step.d.ts.map +1 -0
  147. package/flow/models/types.d.ts +150 -0
  148. package/flow/models/types.d.ts.map +1 -0
  149. package/flow/presets/conventional.d.ts +59 -0
  150. package/flow/presets/conventional.d.ts.map +1 -0
  151. package/flow/presets/independent.d.ts +61 -0
  152. package/flow/presets/independent.d.ts.map +1 -0
  153. package/flow/presets/index.cjs.js +3903 -0
  154. package/flow/presets/index.cjs.js.map +1 -0
  155. package/flow/presets/index.d.ts +4 -0
  156. package/flow/presets/index.d.ts.map +1 -0
  157. package/flow/presets/index.esm.js +3889 -0
  158. package/flow/presets/index.esm.js.map +1 -0
  159. package/flow/presets/synced.d.ts +65 -0
  160. package/flow/presets/synced.d.ts.map +1 -0
  161. package/flow/steps/analyze-commits.d.ts +19 -0
  162. package/flow/steps/analyze-commits.d.ts.map +1 -0
  163. package/flow/steps/calculate-bump.d.ts +27 -0
  164. package/flow/steps/calculate-bump.d.ts.map +1 -0
  165. package/flow/steps/create-commit.d.ts +16 -0
  166. package/flow/steps/create-commit.d.ts.map +1 -0
  167. package/flow/steps/create-tag.d.ts +22 -0
  168. package/flow/steps/create-tag.d.ts.map +1 -0
  169. package/flow/steps/fetch-registry.d.ts +19 -0
  170. package/flow/steps/fetch-registry.d.ts.map +1 -0
  171. package/flow/steps/generate-changelog.d.ts +25 -0
  172. package/flow/steps/generate-changelog.d.ts.map +1 -0
  173. package/flow/steps/index.cjs.js +3523 -0
  174. package/flow/steps/index.cjs.js.map +1 -0
  175. package/flow/steps/index.d.ts +8 -0
  176. package/flow/steps/index.d.ts.map +1 -0
  177. package/flow/steps/index.esm.js +3504 -0
  178. package/flow/steps/index.esm.js.map +1 -0
  179. package/flow/steps/update-packages.d.ts +25 -0
  180. package/flow/steps/update-packages.d.ts.map +1 -0
  181. package/flow/utils/interpolate.d.ts +11 -0
  182. package/flow/utils/interpolate.d.ts.map +1 -0
  183. package/git/factory.d.ts +233 -0
  184. package/git/factory.d.ts.map +1 -0
  185. package/git/index.cjs.js +2863 -0
  186. package/git/index.cjs.js.map +1 -0
  187. package/git/index.d.ts +5 -0
  188. package/git/index.d.ts.map +1 -0
  189. package/git/index.esm.js +2785 -0
  190. package/git/index.esm.js.map +1 -0
  191. package/git/models/commit.d.ts +129 -0
  192. package/git/models/commit.d.ts.map +1 -0
  193. package/git/models/index.cjs.js +755 -0
  194. package/git/models/index.cjs.js.map +1 -0
  195. package/git/models/index.d.ts +7 -0
  196. package/git/models/index.d.ts.map +1 -0
  197. package/git/models/index.esm.js +729 -0
  198. package/git/models/index.esm.js.map +1 -0
  199. package/git/models/ref.d.ts +120 -0
  200. package/git/models/ref.d.ts.map +1 -0
  201. package/git/models/tag.d.ts +141 -0
  202. package/git/models/tag.d.ts.map +1 -0
  203. package/git/operations/commit.d.ts +97 -0
  204. package/git/operations/commit.d.ts.map +1 -0
  205. package/git/operations/head-info.d.ts +29 -0
  206. package/git/operations/head-info.d.ts.map +1 -0
  207. package/git/operations/index.cjs.js +1954 -0
  208. package/git/operations/index.cjs.js.map +1 -0
  209. package/git/operations/index.d.ts +14 -0
  210. package/git/operations/index.d.ts.map +1 -0
  211. package/git/operations/index.esm.js +1903 -0
  212. package/git/operations/index.esm.js.map +1 -0
  213. package/git/operations/log.d.ts +104 -0
  214. package/git/operations/log.d.ts.map +1 -0
  215. package/git/operations/manage-tags.d.ts +60 -0
  216. package/git/operations/manage-tags.d.ts.map +1 -0
  217. package/git/operations/query-tags.d.ts +88 -0
  218. package/git/operations/query-tags.d.ts.map +1 -0
  219. package/git/operations/stage.d.ts +66 -0
  220. package/git/operations/stage.d.ts.map +1 -0
  221. package/git/operations/status.d.ts +173 -0
  222. package/git/operations/status.d.ts.map +1 -0
  223. package/index.cjs.js +16761 -0
  224. package/index.cjs.js.map +1 -0
  225. package/index.d.ts +102 -0
  226. package/index.d.ts.map +1 -0
  227. package/index.esm.js +16427 -0
  228. package/index.esm.js.map +1 -0
  229. package/package.json +200 -0
  230. package/registry/factory.d.ts +18 -0
  231. package/registry/factory.d.ts.map +1 -0
  232. package/registry/index.cjs.js +543 -0
  233. package/registry/index.cjs.js.map +1 -0
  234. package/registry/index.d.ts +5 -0
  235. package/registry/index.d.ts.map +1 -0
  236. package/registry/index.esm.js +535 -0
  237. package/registry/index.esm.js.map +1 -0
  238. package/registry/models/index.cjs.js +69 -0
  239. package/registry/models/index.cjs.js.map +1 -0
  240. package/registry/models/index.d.ts +6 -0
  241. package/registry/models/index.d.ts.map +1 -0
  242. package/registry/models/index.esm.js +66 -0
  243. package/registry/models/index.esm.js.map +1 -0
  244. package/registry/models/package-info.d.ts +55 -0
  245. package/registry/models/package-info.d.ts.map +1 -0
  246. package/registry/models/registry.d.ts +62 -0
  247. package/registry/models/registry.d.ts.map +1 -0
  248. package/registry/models/version-info.d.ts +67 -0
  249. package/registry/models/version-info.d.ts.map +1 -0
  250. package/registry/npm/cache.d.ts +50 -0
  251. package/registry/npm/cache.d.ts.map +1 -0
  252. package/registry/npm/client.d.ts +30 -0
  253. package/registry/npm/client.d.ts.map +1 -0
  254. package/registry/npm/index.cjs.js +456 -0
  255. package/registry/npm/index.cjs.js.map +1 -0
  256. package/registry/npm/index.d.ts +4 -0
  257. package/registry/npm/index.d.ts.map +1 -0
  258. package/registry/npm/index.esm.js +451 -0
  259. package/registry/npm/index.esm.js.map +1 -0
  260. package/semver/compare/compare.d.ts +100 -0
  261. package/semver/compare/compare.d.ts.map +1 -0
  262. package/semver/compare/index.cjs.js +386 -0
  263. package/semver/compare/index.cjs.js.map +1 -0
  264. package/semver/compare/index.d.ts +3 -0
  265. package/semver/compare/index.d.ts.map +1 -0
  266. package/semver/compare/index.esm.js +370 -0
  267. package/semver/compare/index.esm.js.map +1 -0
  268. package/semver/compare/sort.d.ts +36 -0
  269. package/semver/compare/sort.d.ts.map +1 -0
  270. package/semver/format/index.cjs.js +58 -0
  271. package/semver/format/index.cjs.js.map +1 -0
  272. package/semver/format/index.d.ts +2 -0
  273. package/semver/format/index.d.ts.map +1 -0
  274. package/semver/format/index.esm.js +53 -0
  275. package/semver/format/index.esm.js.map +1 -0
  276. package/semver/format/to-string.d.ts +31 -0
  277. package/semver/format/to-string.d.ts.map +1 -0
  278. package/semver/increment/bump.d.ts +37 -0
  279. package/semver/increment/bump.d.ts.map +1 -0
  280. package/semver/increment/index.cjs.js +223 -0
  281. package/semver/increment/index.cjs.js.map +1 -0
  282. package/semver/increment/index.d.ts +2 -0
  283. package/semver/increment/index.d.ts.map +1 -0
  284. package/semver/increment/index.esm.js +219 -0
  285. package/semver/increment/index.esm.js.map +1 -0
  286. package/semver/index.cjs.js +1499 -0
  287. package/semver/index.cjs.js.map +1 -0
  288. package/semver/index.d.ts +6 -0
  289. package/semver/index.d.ts.map +1 -0
  290. package/semver/index.esm.js +1458 -0
  291. package/semver/index.esm.js.map +1 -0
  292. package/semver/models/index.cjs.js +153 -0
  293. package/semver/models/index.cjs.js.map +1 -0
  294. package/semver/models/index.d.ts +5 -0
  295. package/semver/models/index.d.ts.map +1 -0
  296. package/semver/models/index.esm.js +139 -0
  297. package/semver/models/index.esm.js.map +1 -0
  298. package/semver/models/range.d.ts +83 -0
  299. package/semver/models/range.d.ts.map +1 -0
  300. package/semver/models/version.d.ts +78 -0
  301. package/semver/models/version.d.ts.map +1 -0
  302. package/semver/parse/index.cjs.js +799 -0
  303. package/semver/parse/index.cjs.js.map +1 -0
  304. package/semver/parse/index.d.ts +5 -0
  305. package/semver/parse/index.d.ts.map +1 -0
  306. package/semver/parse/index.esm.js +793 -0
  307. package/semver/parse/index.esm.js.map +1 -0
  308. package/semver/parse/range.d.ts +38 -0
  309. package/semver/parse/range.d.ts.map +1 -0
  310. package/semver/parse/version.d.ts +49 -0
  311. package/semver/parse/version.d.ts.map +1 -0
  312. package/workspace/discovery/changelog-path.d.ts +21 -0
  313. package/workspace/discovery/changelog-path.d.ts.map +1 -0
  314. package/workspace/discovery/dependencies.d.ts +145 -0
  315. package/workspace/discovery/dependencies.d.ts.map +1 -0
  316. package/workspace/discovery/discover-changelogs.d.ts +76 -0
  317. package/workspace/discovery/discover-changelogs.d.ts.map +1 -0
  318. package/workspace/discovery/index.cjs.js +2300 -0
  319. package/workspace/discovery/index.cjs.js.map +1 -0
  320. package/workspace/discovery/index.d.ts +13 -0
  321. package/workspace/discovery/index.d.ts.map +1 -0
  322. package/workspace/discovery/index.esm.js +2283 -0
  323. package/workspace/discovery/index.esm.js.map +1 -0
  324. package/workspace/discovery/packages.d.ts +83 -0
  325. package/workspace/discovery/packages.d.ts.map +1 -0
  326. package/workspace/index.cjs.js +4445 -0
  327. package/workspace/index.cjs.js.map +1 -0
  328. package/workspace/index.d.ts +52 -0
  329. package/workspace/index.d.ts.map +1 -0
  330. package/workspace/index.esm.js +4394 -0
  331. package/workspace/index.esm.js.map +1 -0
  332. package/workspace/models/index.cjs.js +284 -0
  333. package/workspace/models/index.cjs.js.map +1 -0
  334. package/workspace/models/index.d.ts +10 -0
  335. package/workspace/models/index.d.ts.map +1 -0
  336. package/workspace/models/index.esm.js +261 -0
  337. package/workspace/models/index.esm.js.map +1 -0
  338. package/workspace/models/project.d.ts +118 -0
  339. package/workspace/models/project.d.ts.map +1 -0
  340. package/workspace/models/workspace.d.ts +139 -0
  341. package/workspace/models/workspace.d.ts.map +1 -0
  342. package/workspace/operations/batch-update.d.ts +99 -0
  343. package/workspace/operations/batch-update.d.ts.map +1 -0
  344. package/workspace/operations/cascade-bump.d.ts +125 -0
  345. package/workspace/operations/cascade-bump.d.ts.map +1 -0
  346. package/workspace/operations/index.cjs.js +2675 -0
  347. package/workspace/operations/index.cjs.js.map +1 -0
  348. package/workspace/operations/index.d.ts +12 -0
  349. package/workspace/operations/index.d.ts.map +1 -0
  350. package/workspace/operations/index.esm.js +2663 -0
  351. package/workspace/operations/index.esm.js.map +1 -0
  352. package/workspace/operations/validate.d.ts +85 -0
  353. package/workspace/operations/validate.d.ts.map +1 -0
@@ -0,0 +1,2283 @@
1
+ import { join as join$1, resolve, parse as parse$1, dirname } from 'node:path';
2
+ import 'node:util';
3
+ import { existsSync, readFileSync, statSync, lstatSync, readdirSync } from 'node:fs';
4
+ import 'node:os';
5
+
6
+ /**
7
+ * Safe copies of Error built-ins via factory functions.
8
+ *
9
+ * Since constructors cannot be safely captured via Object.assign, this module
10
+ * provides factory functions that use Reflect.construct internally.
11
+ *
12
+ * These references are captured at module initialization time to protect against
13
+ * prototype pollution attacks. Import only what you need for tree-shaking.
14
+ *
15
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/error
16
+ */
17
+ // Capture references at module initialization time
18
+ const _Error = globalThis.Error;
19
+ const _Reflect$2 = globalThis.Reflect;
20
+ /**
21
+ * (Safe copy) Creates a new Error using the captured Error constructor.
22
+ * Use this instead of `new Error()`.
23
+ *
24
+ * @param message - Optional error message.
25
+ * @param options - Optional error options.
26
+ * @returns A new Error instance.
27
+ */
28
+ const createError = (message, options) => _Reflect$2.construct(_Error, [message, options]);
29
+
30
+ /**
31
+ * Safe copies of Map built-in via factory function.
32
+ *
33
+ * Since constructors cannot be safely captured via Object.assign, this module
34
+ * provides a factory function that uses Reflect.construct internally.
35
+ *
36
+ * These references are captured at module initialization time to protect against
37
+ * prototype pollution attacks. Import only what you need for tree-shaking.
38
+ *
39
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/map
40
+ */
41
+ // Capture references at module initialization time
42
+ const _Map = globalThis.Map;
43
+ const _Reflect$1 = globalThis.Reflect;
44
+ /**
45
+ * (Safe copy) Creates a new Map using the captured Map constructor.
46
+ * Use this instead of `new Map()`.
47
+ *
48
+ * @param iterable - Optional iterable of key-value pairs.
49
+ * @returns A new Map instance.
50
+ */
51
+ const createMap = (iterable) => _Reflect$1.construct(_Map, iterable ? [iterable] : []);
52
+
53
+ /**
54
+ * Safe copies of Set built-in via factory function.
55
+ *
56
+ * Since constructors cannot be safely captured via Object.assign, this module
57
+ * provides a factory function that uses Reflect.construct internally.
58
+ *
59
+ * These references are captured at module initialization time to protect against
60
+ * prototype pollution attacks. Import only what you need for tree-shaking.
61
+ *
62
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/set
63
+ */
64
+ // Capture references at module initialization time
65
+ const _Set = globalThis.Set;
66
+ const _Reflect = globalThis.Reflect;
67
+ /**
68
+ * (Safe copy) Creates a new Set using the captured Set constructor.
69
+ * Use this instead of `new Set()`.
70
+ *
71
+ * @param iterable - Optional iterable of values.
72
+ * @returns A new Set instance.
73
+ */
74
+ const createSet = (iterable) => _Reflect.construct(_Set, iterable ? [iterable] : []);
75
+
76
+ /**
77
+ * Safe copies of Console built-in methods.
78
+ *
79
+ * These references are captured at module initialization time to protect against
80
+ * prototype pollution attacks. Import only what you need for tree-shaking.
81
+ *
82
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/console
83
+ */
84
+ // Capture references at module initialization time
85
+ const _console = globalThis.console;
86
+ /**
87
+ * (Safe copy) Outputs a message to the console.
88
+ */
89
+ const log = _console.log.bind(_console);
90
+ /**
91
+ * (Safe copy) Outputs a warning message to the console.
92
+ */
93
+ const warn = _console.warn.bind(_console);
94
+ /**
95
+ * (Safe copy) Outputs an error message to the console.
96
+ */
97
+ const error = _console.error.bind(_console);
98
+ /**
99
+ * (Safe copy) Outputs an informational message to the console.
100
+ */
101
+ const info = _console.info.bind(_console);
102
+ /**
103
+ * (Safe copy) Outputs a debug message to the console.
104
+ */
105
+ const debug = _console.debug.bind(_console);
106
+ /**
107
+ * (Safe copy) Outputs a stack trace to the console.
108
+ */
109
+ _console.trace.bind(_console);
110
+ /**
111
+ * (Safe copy) Displays an interactive listing of the properties of a specified object.
112
+ */
113
+ _console.dir.bind(_console);
114
+ /**
115
+ * (Safe copy) Displays tabular data as a table.
116
+ */
117
+ _console.table.bind(_console);
118
+ /**
119
+ * (Safe copy) Writes an error message to the console if the assertion is false.
120
+ */
121
+ _console.assert.bind(_console);
122
+ /**
123
+ * (Safe copy) Clears the console.
124
+ */
125
+ _console.clear.bind(_console);
126
+ /**
127
+ * (Safe copy) Logs the number of times that this particular call to count() has been called.
128
+ */
129
+ _console.count.bind(_console);
130
+ /**
131
+ * (Safe copy) Resets the counter used with console.count().
132
+ */
133
+ _console.countReset.bind(_console);
134
+ /**
135
+ * (Safe copy) Creates a new inline group in the console.
136
+ */
137
+ _console.group.bind(_console);
138
+ /**
139
+ * (Safe copy) Creates a new inline group in the console that is initially collapsed.
140
+ */
141
+ _console.groupCollapsed.bind(_console);
142
+ /**
143
+ * (Safe copy) Exits the current inline group.
144
+ */
145
+ _console.groupEnd.bind(_console);
146
+ /**
147
+ * (Safe copy) Starts a timer with a name specified as an input parameter.
148
+ */
149
+ _console.time.bind(_console);
150
+ /**
151
+ * (Safe copy) Stops a timer that was previously started.
152
+ */
153
+ _console.timeEnd.bind(_console);
154
+ /**
155
+ * (Safe copy) Logs the current value of a timer that was previously started.
156
+ */
157
+ _console.timeLog.bind(_console);
158
+
159
+ /**
160
+ * Safe copies of Array built-in static methods.
161
+ *
162
+ * These references are captured at module initialization time to protect against
163
+ * prototype pollution attacks. Import only what you need for tree-shaking.
164
+ *
165
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/array
166
+ */
167
+ // Capture references at module initialization time
168
+ const _Array = globalThis.Array;
169
+ /**
170
+ * (Safe copy) Determines whether the passed value is an Array.
171
+ */
172
+ const isArray = _Array.isArray;
173
+
174
+ /**
175
+ * Safe copies of JSON built-in methods.
176
+ *
177
+ * These references are captured at module initialization time to protect against
178
+ * prototype pollution attacks. Import only what you need for tree-shaking.
179
+ *
180
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/json
181
+ */
182
+ // Capture references at module initialization time
183
+ const _JSON = globalThis.JSON;
184
+ /**
185
+ * (Safe copy) Converts a JavaScript Object Notation (JSON) string into an object.
186
+ */
187
+ const parse = _JSON.parse;
188
+ /**
189
+ * (Safe copy) Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
190
+ */
191
+ const stringify = _JSON.stringify;
192
+
193
+ /**
194
+ * Safe copies of Object built-in methods.
195
+ *
196
+ * These references are captured at module initialization time to protect against
197
+ * prototype pollution attacks. Import only what you need for tree-shaking.
198
+ *
199
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/object
200
+ */
201
+ // Capture references at module initialization time
202
+ const _Object = globalThis.Object;
203
+ /**
204
+ * (Safe copy) Prevents modification of existing property attributes and values,
205
+ * and prevents the addition of new properties.
206
+ */
207
+ const freeze = _Object.freeze;
208
+ /**
209
+ * (Safe copy) Returns the names of the enumerable string properties and methods of an object.
210
+ */
211
+ const keys = _Object.keys;
212
+ /**
213
+ * (Safe copy) Returns an array of key/values of the enumerable own properties of an object.
214
+ */
215
+ const entries = _Object.entries;
216
+ /**
217
+ * (Safe copy) Returns an array of values of the enumerable own properties of an object.
218
+ */
219
+ const values = _Object.values;
220
+ /**
221
+ * (Safe copy) Adds one or more properties to an object, and/or modifies attributes of existing properties.
222
+ */
223
+ const defineProperties = _Object.defineProperties;
224
+
225
+ const registeredClasses = [];
226
+
227
+ /**
228
+ * Returns the data type of the target.
229
+ * Uses native `typeof` operator, however, makes distinction between `null`, `array`, and `object`.
230
+ * Also, when classes are registered via `registerClass`, it checks if objects are instance of any known registered class.
231
+ *
232
+ * @param target - The target to get the data type of.
233
+ * @returns The data type of the target.
234
+ */
235
+ const getType = (target) => {
236
+ if (target === null)
237
+ return 'null';
238
+ const nativeDataType = typeof target;
239
+ if (nativeDataType === 'object') {
240
+ if (isArray(target))
241
+ return 'array';
242
+ for (const registeredClass of registeredClasses) {
243
+ if (target instanceof registeredClass)
244
+ return registeredClass.name;
245
+ }
246
+ }
247
+ return nativeDataType;
248
+ };
249
+
250
+ /* eslint-disable @typescript-eslint/no-explicit-any */
251
+ /**
252
+ * Creates a wrapper function that only executes the wrapped function if the condition function returns true.
253
+ *
254
+ * @param func - The function to be conditionally executed.
255
+ * @param conditionFunc - A function that returns a boolean, determining if `func` should be executed.
256
+ * @returns A wrapped version of `func` that executes conditionally.
257
+ */
258
+ function createConditionalExecutionFunction(func, conditionFunc) {
259
+ return function (...args) {
260
+ if (conditionFunc()) {
261
+ return func(...args);
262
+ }
263
+ };
264
+ }
265
+
266
+ /* eslint-disable @typescript-eslint/no-explicit-any */
267
+ /**
268
+ * Creates a wrapper function that silently ignores any errors thrown by the wrapped void function.
269
+ * This function is specifically for wrapping functions that do not return a value (void functions).
270
+ * Exceptions are swallowed without any logging or handling.
271
+ *
272
+ * @param func - The void function to be wrapped.
273
+ * @returns A wrapped version of the input function that ignores errors.
274
+ */
275
+ function createErrorIgnoringFunction(func) {
276
+ return function (...args) {
277
+ try {
278
+ func(...args);
279
+ }
280
+ catch {
281
+ // Deliberately swallowing/ignoring the exception
282
+ }
283
+ };
284
+ }
285
+
286
+ /* eslint-disable @typescript-eslint/no-unused-vars */
287
+ /**
288
+ * A no-operation function (noop) that does nothing regardless of the arguments passed.
289
+ * It is designed to be as permissive as possible in its typing without using the `Function` keyword.
290
+ *
291
+ * @param args - Any arguments passed to the function (ignored)
292
+ */
293
+ const noop = (...args) => {
294
+ // Intentionally does nothing
295
+ };
296
+
297
+ const logLevels = ['none', 'error', 'warn', 'log', 'info', 'debug'];
298
+ const priority = {
299
+ error: 4,
300
+ warn: 3,
301
+ log: 2,
302
+ info: 1,
303
+ debug: 0,
304
+ };
305
+ /**
306
+ * Validates whether a given string is a valid log level.
307
+ *
308
+ * @param level - The log level to validate
309
+ * @returns True if the level is valid, false otherwise
310
+ */
311
+ function isValidLogLevel(level) {
312
+ return logLevels.includes(level);
313
+ }
314
+ /**
315
+ * Creates a log level configuration manager for controlling logging behavior.
316
+ * Provides methods to get, set, and evaluate log levels based on priority.
317
+ *
318
+ * @param level - The initial log level (defaults to 'error')
319
+ * @returns A configuration object with log level management methods
320
+ * @throws {Error} When the provided level is not a valid log level
321
+ */
322
+ function createLogLevelConfig(level = 'error') {
323
+ if (!isValidLogLevel(level)) {
324
+ throw createError('Cannot create log level configuration with a valid default log level');
325
+ }
326
+ const state = { level };
327
+ const getLogLevel = () => state.level;
328
+ const setLogLevel = (level) => {
329
+ if (!isValidLogLevel(level)) {
330
+ throw createError(`Cannot set value '${level}' level. Expected levels are ${logLevels}.`);
331
+ }
332
+ state.level = level;
333
+ };
334
+ const shouldLog = (level) => {
335
+ if (state.level === 'none' || level === 'none' || !isValidLogLevel(level)) {
336
+ return false;
337
+ }
338
+ return priority[level] >= priority[state.level];
339
+ };
340
+ return freeze({
341
+ getLogLevel,
342
+ setLogLevel,
343
+ shouldLog,
344
+ });
345
+ }
346
+
347
+ /**
348
+ * Creates a logger instance with configurable log level filtering.
349
+ * Each log function is wrapped to respect the current log level setting.
350
+ *
351
+ * @param error - Function to handle error-level logs (required)
352
+ * @param warn - Function to handle warning-level logs (optional, defaults to noop)
353
+ * @param log - Function to handle standard logs (optional, defaults to noop)
354
+ * @param info - Function to handle info-level logs (optional, defaults to noop)
355
+ * @param debug - Function to handle debug-level logs (optional, defaults to noop)
356
+ * @returns A frozen logger object with log methods and level control
357
+ * @throws {ErrorLevelFn} When any provided log function is invalid
358
+ */
359
+ function createLogger(error, warn = noop, log = noop, info = noop, debug = noop) {
360
+ if (notValidLogFn(error)) {
361
+ throw createError(notFnMsg('error'));
362
+ }
363
+ if (notValidLogFn(warn)) {
364
+ throw createError(notFnMsg('warn'));
365
+ }
366
+ if (notValidLogFn(log)) {
367
+ throw createError(notFnMsg('log'));
368
+ }
369
+ if (notValidLogFn(info)) {
370
+ throw createError(notFnMsg('info'));
371
+ }
372
+ if (notValidLogFn(debug)) {
373
+ throw createError(notFnMsg('debug'));
374
+ }
375
+ const { setLogLevel, getLogLevel, shouldLog } = createLogLevelConfig();
376
+ const wrapLogFn = (fn, level) => {
377
+ if (fn === noop)
378
+ return fn;
379
+ const condition = () => shouldLog(level);
380
+ return createConditionalExecutionFunction(createErrorIgnoringFunction(fn), condition);
381
+ };
382
+ return freeze({
383
+ error: wrapLogFn(error, 'error'),
384
+ warn: wrapLogFn(warn, 'warn'),
385
+ log: wrapLogFn(log, 'log'),
386
+ info: wrapLogFn(info, 'info'),
387
+ debug: wrapLogFn(debug, 'debug'),
388
+ setLogLevel,
389
+ getLogLevel,
390
+ });
391
+ }
392
+ /**
393
+ * Validates whether a given value is a valid log function.
394
+ *
395
+ * @param fn - The value to validate
396
+ * @returns True if the value is not a function (invalid), false if it is valid
397
+ */
398
+ function notValidLogFn(fn) {
399
+ return getType(fn) !== 'function' && fn !== noop;
400
+ }
401
+ /**
402
+ * Generates an error message for invalid log function parameters.
403
+ *
404
+ * @param label - The name of the log function that failed validation
405
+ * @returns A formatted error message string
406
+ */
407
+ function notFnMsg(label) {
408
+ return `Cannot create a logger when ${label} is not a function`;
409
+ }
410
+
411
+ createLogger(error, warn, log, info, debug);
412
+
413
+ /**
414
+ * Global log level registry.
415
+ * Tracks all created scoped loggers to allow global log level changes.
416
+ */
417
+ const loggerRegistry = createSet();
418
+ /** Redacted placeholder for sensitive values */
419
+ const REDACTED = '[REDACTED]';
420
+ /**
421
+ * Patterns that indicate a sensitive key name.
422
+ * Keys containing these patterns will have their values sanitized.
423
+ */
424
+ const SENSITIVE_KEY_PATTERNS = [
425
+ /token/i,
426
+ /key/i,
427
+ /password/i,
428
+ /secret/i,
429
+ /credential/i,
430
+ /auth/i,
431
+ /bearer/i,
432
+ /api[_-]?key/i,
433
+ /private/i,
434
+ /passphrase/i,
435
+ ];
436
+ /**
437
+ * Checks if a key name indicates sensitive data.
438
+ *
439
+ * @param key - Key name to check
440
+ * @returns True if the key indicates sensitive data
441
+ */
442
+ function isSensitiveKey(key) {
443
+ return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
444
+ }
445
+ /**
446
+ * Sanitizes an object by replacing sensitive values with REDACTED.
447
+ * This function recursively processes nested objects and arrays.
448
+ *
449
+ * @param obj - Object to sanitize
450
+ * @returns New object with sensitive values redacted
451
+ */
452
+ function sanitize(obj) {
453
+ if (obj === null || obj === undefined) {
454
+ return obj;
455
+ }
456
+ if (isArray(obj)) {
457
+ return obj.map((item) => sanitize(item));
458
+ }
459
+ if (typeof obj === 'object') {
460
+ const result = {};
461
+ for (const [key, value] of entries(obj)) {
462
+ if (isSensitiveKey(key)) {
463
+ result[key] = REDACTED;
464
+ }
465
+ else if (typeof value === 'object' && value !== null) {
466
+ result[key] = sanitize(value);
467
+ }
468
+ else {
469
+ result[key] = value;
470
+ }
471
+ }
472
+ return result;
473
+ }
474
+ return obj;
475
+ }
476
+ /**
477
+ * Formats a log message with optional metadata.
478
+ *
479
+ * @param namespace - Logger namespace prefix
480
+ * @param message - Log message
481
+ * @param meta - Optional metadata object
482
+ * @returns Formatted log string
483
+ */
484
+ function formatMessage(namespace, message, meta) {
485
+ const prefix = `[${namespace}]`;
486
+ if (meta && keys(meta).length > 0) {
487
+ const sanitizedMeta = sanitize(meta);
488
+ return `${prefix} ${message} ${stringify(sanitizedMeta)}`;
489
+ }
490
+ return `${prefix} ${message}`;
491
+ }
492
+ /**
493
+ * Creates a scoped logger with namespace prefix and optional secret sanitization.
494
+ * All log messages will be prefixed with [namespace] and sensitive metadata
495
+ * values will be automatically redacted.
496
+ *
497
+ * @param namespace - Logger namespace (e.g., 'project-scope', 'analyze')
498
+ * @param options - Logger configuration options
499
+ * @returns A configured scoped logger instance
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * const logger = createScopedLogger('project-scope')
504
+ * logger.setLogLevel('debug')
505
+ *
506
+ * // Basic logging
507
+ * logger.info('Starting analysis', { path: './project' })
508
+ *
509
+ * // Sensitive data is automatically redacted
510
+ * logger.debug('Config loaded', { apiKey: 'secret123' })
511
+ * // Output: [project-scope] Config loaded {"apiKey":"[REDACTED]"}
512
+ * ```
513
+ */
514
+ function createScopedLogger(namespace, options = {}) {
515
+ const { level = 'error', sanitizeSecrets = true } = options;
516
+ // Create wrapper functions that add namespace prefix and sanitization
517
+ const createLogFn = (baseFn) => (message, meta) => {
518
+ const processedMeta = sanitizeSecrets && meta ? sanitize(meta) : meta;
519
+ baseFn(formatMessage(namespace, message, processedMeta));
520
+ };
521
+ // Create base logger with wrapped functions
522
+ const baseLogger = createLogger(createLogFn(error), createLogFn(warn), createLogFn(log), createLogFn(info), createLogFn(debug));
523
+ // Set initial log level (use global override if set)
524
+ baseLogger.setLogLevel(level);
525
+ const scopedLogger = freeze({
526
+ error: (message, meta) => baseLogger.error(message, meta),
527
+ warn: (message, meta) => baseLogger.warn(message, meta),
528
+ log: (message, meta) => baseLogger.log(message, meta),
529
+ info: (message, meta) => baseLogger.info(message, meta),
530
+ debug: (message, meta) => baseLogger.debug(message, meta),
531
+ setLogLevel: baseLogger.setLogLevel,
532
+ getLogLevel: baseLogger.getLogLevel,
533
+ });
534
+ // Register logger for global level management
535
+ loggerRegistry.add(scopedLogger);
536
+ return scopedLogger;
537
+ }
538
+ /**
539
+ * Default logger instance for the project-scope library.
540
+ * Use this for general logging within the library.
541
+ *
542
+ * @example
543
+ * ```typescript
544
+ * import { logger } from '@hyperfrontend/project-scope/core'
545
+ *
546
+ * logger.setLogLevel('debug')
547
+ * logger.debug('Analyzing project', { path: './src' })
548
+ * ```
549
+ */
550
+ createScopedLogger('project-scope');
551
+
552
+ const fsLogger = createScopedLogger('project-scope:fs');
553
+ /**
554
+ * Create a file system error with code and context.
555
+ *
556
+ * @param message - The error message describing what went wrong
557
+ * @param code - The category code for this type of filesystem failure
558
+ * @param context - Additional context including path, operation, and cause
559
+ * @returns A configured Error object with code and context properties
560
+ */
561
+ function createFileSystemError(message, code, context) {
562
+ const error = createError(message);
563
+ defineProperties(error, {
564
+ code: { value: code, enumerable: true },
565
+ context: { value: context, enumerable: true },
566
+ });
567
+ return error;
568
+ }
569
+ /**
570
+ * Read file contents as string.
571
+ *
572
+ * @param filePath - Path to file
573
+ * @param encoding - File encoding (default: utf-8)
574
+ * @returns File contents as string
575
+ * @throws {Error} If file doesn't exist or can't be read
576
+ *
577
+ * @example
578
+ * ```typescript
579
+ * import { readFileContent } from '@hyperfrontend/project-scope'
580
+ *
581
+ * const content = readFileContent('./package.json')
582
+ * console.log(content) // JSON string
583
+ * ```
584
+ */
585
+ function readFileContent(filePath, encoding = 'utf-8') {
586
+ if (!existsSync(filePath)) {
587
+ fsLogger.debug('File not found', { path: filePath });
588
+ throw createFileSystemError(`File not found: ${filePath}`, 'FS_NOT_FOUND', { path: filePath, operation: 'read' });
589
+ }
590
+ try {
591
+ return readFileSync(filePath, { encoding });
592
+ }
593
+ catch (error) {
594
+ fsLogger.warn('Failed to read file', { path: filePath });
595
+ throw createFileSystemError(`Failed to read file: ${filePath}`, 'FS_READ_ERROR', { path: filePath, operation: 'read', cause: error });
596
+ }
597
+ }
598
+ /**
599
+ * Read file if exists, return null otherwise.
600
+ *
601
+ * @param filePath - Path to file
602
+ * @param encoding - File encoding (default: utf-8)
603
+ * @returns File contents or null if file doesn't exist
604
+ */
605
+ function readFileIfExists(filePath, encoding = 'utf-8') {
606
+ if (!existsSync(filePath)) {
607
+ return null;
608
+ }
609
+ try {
610
+ return readFileSync(filePath, { encoding });
611
+ }
612
+ catch {
613
+ return null;
614
+ }
615
+ }
616
+
617
+ createScopedLogger('project-scope:fs:write');
618
+
619
+ /**
620
+ * Get file stats with error handling.
621
+ *
622
+ * @param filePath - Path to file
623
+ * @param followSymlinks - Whether to follow symlinks (default: true)
624
+ * @returns File stats or null if path doesn't exist
625
+ */
626
+ function getFileStat(filePath, followSymlinks = true) {
627
+ if (!existsSync(filePath)) {
628
+ return null;
629
+ }
630
+ try {
631
+ const stat = followSymlinks ? statSync(filePath) : lstatSync(filePath);
632
+ return {
633
+ isFile: stat.isFile(),
634
+ isDirectory: stat.isDirectory(),
635
+ isSymlink: stat.isSymbolicLink(),
636
+ size: stat.size,
637
+ created: stat.birthtime,
638
+ modified: stat.mtime,
639
+ accessed: stat.atime,
640
+ mode: stat.mode,
641
+ };
642
+ }
643
+ catch {
644
+ return null;
645
+ }
646
+ }
647
+ /**
648
+ * Check if path is a directory.
649
+ *
650
+ * @param dirPath - Path to check
651
+ * @returns True if path is a directory
652
+ */
653
+ function isDirectory(dirPath) {
654
+ const stats = getFileStat(dirPath);
655
+ return stats?.isDirectory ?? false;
656
+ }
657
+ /**
658
+ * Check if path exists.
659
+ *
660
+ * @param filePath - Path to check
661
+ * @returns True if path exists
662
+ */
663
+ function exists(filePath) {
664
+ return existsSync(filePath);
665
+ }
666
+
667
+ const fsDirLogger = createScopedLogger('project-scope:fs:dir');
668
+ /**
669
+ * List immediate contents of a directory.
670
+ *
671
+ * @param dirPath - Absolute or relative path to the directory
672
+ * @returns Array of entries with metadata for each file/directory
673
+ * @throws {Error} If directory doesn't exist or isn't a directory
674
+ *
675
+ * @example
676
+ * ```typescript
677
+ * import { readDirectory } from '@hyperfrontend/project-scope'
678
+ *
679
+ * const entries = readDirectory('./src')
680
+ * for (const entry of entries) {
681
+ * console.log(entry.name, entry.isFile ? 'file' : 'directory')
682
+ * }
683
+ * ```
684
+ */
685
+ function readDirectory(dirPath) {
686
+ fsDirLogger.debug('Reading directory', { path: dirPath });
687
+ if (!existsSync(dirPath)) {
688
+ fsDirLogger.debug('Directory not found', { path: dirPath });
689
+ throw createFileSystemError(`Directory not found: ${dirPath}`, 'FS_NOT_FOUND', { path: dirPath, operation: 'readdir' });
690
+ }
691
+ if (!isDirectory(dirPath)) {
692
+ fsDirLogger.debug('Path is not a directory', { path: dirPath });
693
+ throw createFileSystemError(`Not a directory: ${dirPath}`, 'FS_NOT_A_DIRECTORY', { path: dirPath, operation: 'readdir' });
694
+ }
695
+ try {
696
+ const entries = readdirSync(dirPath, { withFileTypes: true });
697
+ fsDirLogger.debug('Directory read complete', { path: dirPath, entryCount: entries.length });
698
+ return entries.map((entry) => ({
699
+ name: entry.name,
700
+ path: join$1(dirPath, entry.name),
701
+ isFile: entry.isFile(),
702
+ isDirectory: entry.isDirectory(),
703
+ isSymlink: entry.isSymbolicLink(),
704
+ }));
705
+ }
706
+ catch (error) {
707
+ fsDirLogger.warn('Failed to read directory', { path: dirPath, error: error instanceof Error ? error.message : String(error) });
708
+ throw createFileSystemError(`Failed to read directory: ${dirPath}`, 'FS_READ_ERROR', {
709
+ path: dirPath,
710
+ operation: 'readdir',
711
+ cause: error,
712
+ });
713
+ }
714
+ }
715
+
716
+ /**
717
+ * Join path segments.
718
+ * Uses platform-specific separators (e.g., / or \).
719
+ *
720
+ * @param paths - Path segments to join
721
+ * @returns Joined path
722
+ */
723
+ function join(...paths) {
724
+ return join$1(...paths);
725
+ }
726
+
727
+ const fsTraversalLogger = createScopedLogger('project-scope:fs:traversal');
728
+ /**
729
+ * Generic upward directory traversal.
730
+ * Name avoids similarity to fs.readdir/fs.readdirSync.
731
+ *
732
+ * @param startPath - Starting directory
733
+ * @param predicate - Function to test each directory
734
+ * @returns First matching directory or null
735
+ */
736
+ function traverseUpward(startPath, predicate) {
737
+ fsTraversalLogger.debug('Starting upward traversal', { startPath });
738
+ let currentPath = resolve(startPath);
739
+ const rootPath = parse$1(currentPath).root;
740
+ while (currentPath !== rootPath) {
741
+ if (predicate(currentPath)) {
742
+ fsTraversalLogger.debug('Upward traversal found match', { startPath, foundPath: currentPath });
743
+ return currentPath;
744
+ }
745
+ currentPath = dirname(currentPath);
746
+ }
747
+ // Check root directory
748
+ if (predicate(rootPath)) {
749
+ fsTraversalLogger.debug('Upward traversal found match at root', { startPath, foundPath: rootPath });
750
+ return rootPath;
751
+ }
752
+ fsTraversalLogger.debug('Upward traversal found no match', { startPath });
753
+ return null;
754
+ }
755
+ /**
756
+ * Find directory containing any of the specified marker files.
757
+ *
758
+ * @param startPath - Starting directory
759
+ * @param markers - Array of marker file names to search for
760
+ * @returns First directory containing any marker, or null
761
+ */
762
+ function locateByMarkers(startPath, markers) {
763
+ fsTraversalLogger.debug('Locating by markers', { startPath, markers });
764
+ const result = traverseUpward(startPath, (dir) => markers.some((marker) => exists(join(dir, marker))));
765
+ if (result) {
766
+ fsTraversalLogger.debug('Found directory with marker', { startPath, foundPath: result });
767
+ }
768
+ return result;
769
+ }
770
+ /**
771
+ * Find directory where predicate returns true, starting from given path.
772
+ *
773
+ * @param startPath - Starting directory
774
+ * @param test - Function to test if directory matches criteria
775
+ * @returns Matching directory path or null
776
+ */
777
+ function findUpwardWhere(startPath, test) {
778
+ fsTraversalLogger.debug('Finding upward where condition met', { startPath });
779
+ return traverseUpward(startPath, test);
780
+ }
781
+
782
+ /**
783
+ * Create a structured error with code and optional context.
784
+ *
785
+ * @param message - The human-readable error message
786
+ * @param code - The machine-readable error code for programmatic handling
787
+ * @param context - Additional contextual information about the error
788
+ * @returns Structured error instance with code and context properties
789
+ *
790
+ * @example
791
+ * ```typescript
792
+ * import { createStructuredError } from '@hyperfrontend/project-scope'
793
+ *
794
+ * throw createStructuredError(
795
+ * 'Configuration file not found',
796
+ * 'CONFIG_NOT_FOUND',
797
+ * { path: './config.json', searched: ['./config.json', './settings.json'] }
798
+ * )
799
+ * ```
800
+ */
801
+ function createStructuredError(message, code, context) {
802
+ const error = createError(message);
803
+ error.code = code;
804
+ error.context = context ?? {};
805
+ return error;
806
+ }
807
+ /**
808
+ * Create a configuration-related error.
809
+ *
810
+ * @param message - The human-readable error message
811
+ * @param code - The machine-readable error code for programmatic handling
812
+ * @param context - Additional contextual information (e.g., file path, config key)
813
+ * @returns Structured error instance tagged with type 'config'
814
+ */
815
+ function createConfigError(message, code, context) {
816
+ return createStructuredError(message, code, { ...context, type: 'config' });
817
+ }
818
+
819
+ const packageLogger = createScopedLogger('project-scope:project:package');
820
+ /**
821
+ * Verifies that a value is an object with only string values,
822
+ * used for validating dependency maps and script definitions.
823
+ *
824
+ * @param value - Value to check
825
+ * @returns True if value is a record of strings
826
+ */
827
+ function isStringRecord(value) {
828
+ if (typeof value !== 'object' || value === null)
829
+ return false;
830
+ return values(value).every((v) => typeof v === 'string');
831
+ }
832
+ /**
833
+ * Extracts and normalizes the workspaces field from package.json,
834
+ * supporting both array format and object with packages array.
835
+ *
836
+ * @param value - Raw workspaces value from package.json
837
+ * @returns Normalized workspace patterns or undefined if invalid
838
+ */
839
+ function parseWorkspaces(value) {
840
+ if (isArray(value) && value.every((v) => typeof v === 'string')) {
841
+ return value;
842
+ }
843
+ if (typeof value === 'object' && value !== null) {
844
+ const obj = value;
845
+ if (isArray(obj['packages'])) {
846
+ return { packages: obj['packages'] };
847
+ }
848
+ }
849
+ return undefined;
850
+ }
851
+ /**
852
+ * Validate and normalize package.json data.
853
+ *
854
+ * @param data - Raw parsed data
855
+ * @returns Validated package.json
856
+ */
857
+ function validatePackageJson(data) {
858
+ if (typeof data !== 'object' || data === null) {
859
+ throw createError('package.json must be an object');
860
+ }
861
+ const pkg = data;
862
+ return {
863
+ name: typeof pkg['name'] === 'string' ? pkg['name'] : undefined,
864
+ version: typeof pkg['version'] === 'string' ? pkg['version'] : undefined,
865
+ description: typeof pkg['description'] === 'string' ? pkg['description'] : undefined,
866
+ main: typeof pkg['main'] === 'string' ? pkg['main'] : undefined,
867
+ module: typeof pkg['module'] === 'string' ? pkg['module'] : undefined,
868
+ browser: typeof pkg['browser'] === 'string' ? pkg['browser'] : undefined,
869
+ types: typeof pkg['types'] === 'string' ? pkg['types'] : undefined,
870
+ bin: typeof pkg['bin'] === 'string' || isStringRecord(pkg['bin']) ? pkg['bin'] : undefined,
871
+ scripts: isStringRecord(pkg['scripts']) ? pkg['scripts'] : undefined,
872
+ dependencies: isStringRecord(pkg['dependencies']) ? pkg['dependencies'] : undefined,
873
+ devDependencies: isStringRecord(pkg['devDependencies']) ? pkg['devDependencies'] : undefined,
874
+ peerDependencies: isStringRecord(pkg['peerDependencies']) ? pkg['peerDependencies'] : undefined,
875
+ optionalDependencies: isStringRecord(pkg['optionalDependencies']) ? pkg['optionalDependencies'] : undefined,
876
+ workspaces: parseWorkspaces(pkg['workspaces']),
877
+ exports: typeof pkg['exports'] === 'object' ? pkg['exports'] : undefined,
878
+ engines: isStringRecord(pkg['engines']) ? pkg['engines'] : undefined,
879
+ ...pkg,
880
+ };
881
+ }
882
+ /**
883
+ * Reads and parses package.json from a directory, validating
884
+ * the structure and normalizing fields to the PackageJson interface.
885
+ *
886
+ * @param projectPath - Project directory path or path to package.json
887
+ * @returns Parsed package.json
888
+ * @throws {Error} Error if file doesn't exist or is invalid
889
+ */
890
+ function readPackageJson(projectPath) {
891
+ const packageJsonPath = projectPath.endsWith('package.json') ? projectPath : join$1(projectPath, 'package.json');
892
+ packageLogger.debug('Reading package.json', { path: packageJsonPath });
893
+ const content = readFileContent(packageJsonPath);
894
+ try {
895
+ const data = parse(content);
896
+ const validated = validatePackageJson(data);
897
+ packageLogger.debug('Package.json read successfully', { path: packageJsonPath, name: validated.name });
898
+ return validated;
899
+ }
900
+ catch (error) {
901
+ packageLogger.warn('Failed to parse package.json', {
902
+ path: packageJsonPath,
903
+ error: error instanceof Error ? error.message : String(error),
904
+ });
905
+ throw createConfigError(`Failed to parse package.json: ${packageJsonPath}`, 'CONFIG_PARSE_ERROR', {
906
+ filePath: packageJsonPath,
907
+ cause: error,
908
+ });
909
+ }
910
+ }
911
+ /**
912
+ * Attempts to read and parse package.json if it exists,
913
+ * returning null on missing file or parse failure.
914
+ *
915
+ * @param projectPath - Project directory path or path to package.json
916
+ * @returns Parsed package.json or null if not found
917
+ */
918
+ function readPackageJsonIfExists(projectPath) {
919
+ const packageJsonPath = projectPath.endsWith('package.json') ? projectPath : join$1(projectPath, 'package.json');
920
+ const content = readFileIfExists(packageJsonPath);
921
+ if (!content) {
922
+ packageLogger.debug('Package.json not found', { path: packageJsonPath });
923
+ return null;
924
+ }
925
+ try {
926
+ const validated = validatePackageJson(parse(content));
927
+ packageLogger.debug('Package.json loaded', { path: packageJsonPath, name: validated.name });
928
+ return validated;
929
+ }
930
+ catch {
931
+ packageLogger.debug('Failed to parse package.json, returning null', { path: packageJsonPath });
932
+ return null;
933
+ }
934
+ }
935
+ /**
936
+ * Find nearest package.json by walking up the directory tree.
937
+ *
938
+ * @param startPath - Starting path
939
+ * @returns Path to directory containing package.json, or null if not found
940
+ */
941
+ function findNearestPackageJson(startPath) {
942
+ return locateByMarkers(startPath, ['package.json']);
943
+ }
944
+
945
+ createScopedLogger('project-scope:heuristics:deps');
946
+
947
+ /**
948
+ * Global registry of all caches for bulk operations.
949
+ */
950
+ const cacheRegistry = createSet();
951
+ /**
952
+ * Create a cache with optional TTL and size limits.
953
+ *
954
+ * The cache provides a simple key-value store with:
955
+ * - Optional TTL (time-to-live) for automatic expiration
956
+ * - Optional maxSize for limiting cache size with FIFO eviction
957
+ * - Lazy expiration (entries are checked on access)
958
+ *
959
+ * @param options - Cache configuration options
960
+ * @returns Cache instance
961
+ *
962
+ * @example
963
+ * ```typescript
964
+ * // Basic cache
965
+ * const cache = createCache<string, number>()
966
+ * cache.set('answer', 42)
967
+ * cache.get('answer') // 42
968
+ *
969
+ * // Cache with TTL (expires after 60 seconds)
970
+ * const ttlCache = createCache<string, object>({ ttl: 60000 })
971
+ *
972
+ * // Cache with max size (evicts oldest when full)
973
+ * const lruCache = createCache<string, object>({ maxSize: 100 })
974
+ *
975
+ * // Combined options
976
+ * const configCache = createCache<string, object>({
977
+ * ttl: 30000,
978
+ * maxSize: 50
979
+ * })
980
+ * ```
981
+ */
982
+ function createCache(options) {
983
+ const { ttl, maxSize } = options ?? {};
984
+ const store = createMap();
985
+ // Track insertion order for FIFO eviction
986
+ const insertionOrder = [];
987
+ /**
988
+ * Check if an entry is expired.
989
+ *
990
+ * @param entry - Cache entry to check
991
+ * @returns True if entry is expired
992
+ */
993
+ function isExpired(entry) {
994
+ if (ttl === undefined)
995
+ return false;
996
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
997
+ return Date.now() - entry.timestamp > ttl;
998
+ }
999
+ /**
1000
+ * Evict oldest entries to make room for new ones.
1001
+ */
1002
+ function evictIfNeeded() {
1003
+ if (maxSize === undefined)
1004
+ return;
1005
+ while (store.size >= maxSize && insertionOrder.length > 0) {
1006
+ const oldestKey = insertionOrder.shift();
1007
+ if (oldestKey !== undefined) {
1008
+ store.delete(oldestKey);
1009
+ }
1010
+ }
1011
+ }
1012
+ /**
1013
+ * Remove key from insertion order tracking.
1014
+ *
1015
+ * @param key - Key to remove from order tracking
1016
+ */
1017
+ function removeFromOrder(key) {
1018
+ const index = insertionOrder.indexOf(key);
1019
+ if (index !== -1) {
1020
+ insertionOrder.splice(index, 1);
1021
+ }
1022
+ }
1023
+ const cache = {
1024
+ get(key) {
1025
+ const entry = store.get(key);
1026
+ if (!entry)
1027
+ return undefined;
1028
+ if (isExpired(entry)) {
1029
+ store.delete(key);
1030
+ removeFromOrder(key);
1031
+ return undefined;
1032
+ }
1033
+ return entry.value;
1034
+ },
1035
+ set(key, value) {
1036
+ // If key exists, remove from order first
1037
+ if (store.has(key)) {
1038
+ removeFromOrder(key);
1039
+ }
1040
+ else {
1041
+ // Evict if needed before adding new entry
1042
+ evictIfNeeded();
1043
+ }
1044
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
1045
+ store.set(key, { value, timestamp: Date.now() });
1046
+ insertionOrder.push(key);
1047
+ },
1048
+ has(key) {
1049
+ const entry = store.get(key);
1050
+ if (!entry)
1051
+ return false;
1052
+ if (isExpired(entry)) {
1053
+ store.delete(key);
1054
+ removeFromOrder(key);
1055
+ return false;
1056
+ }
1057
+ return true;
1058
+ },
1059
+ delete(key) {
1060
+ removeFromOrder(key);
1061
+ return store.delete(key);
1062
+ },
1063
+ clear() {
1064
+ store.clear();
1065
+ insertionOrder.length = 0;
1066
+ },
1067
+ size() {
1068
+ return store.size;
1069
+ },
1070
+ keys() {
1071
+ return [...insertionOrder];
1072
+ },
1073
+ };
1074
+ // Register cache for global operations
1075
+ cacheRegistry.add(cache);
1076
+ return freeze(cache);
1077
+ }
1078
+
1079
+ /**
1080
+ * Pattern matching utilities with ReDoS protection.
1081
+ * Uses character-by-character matching instead of regex where possible.
1082
+ */
1083
+ /**
1084
+ * Match path against glob pattern using safe character iteration.
1085
+ * Avoids regex to prevent ReDoS attacks.
1086
+ *
1087
+ * Supported patterns:
1088
+ * - * matches any characters except /
1089
+ * - ** matches any characters including /
1090
+ * - ? matches exactly one character except /
1091
+ * - {a,b,c} matches any of the alternatives
1092
+ *
1093
+ * @param path - The filesystem path to test against the pattern
1094
+ * @param pattern - The glob pattern to match against
1095
+ * @returns True if path matches pattern
1096
+ *
1097
+ * @example
1098
+ * ```typescript
1099
+ * import { matchGlobPattern } from '@hyperfrontend/project-scope'
1100
+ *
1101
+ * matchGlobPattern('src/utils/helper.ts', '\*\*\/*.ts') // true
1102
+ * matchGlobPattern('test.spec.ts', '\*.spec.ts') // true
1103
+ * matchGlobPattern('config.json', '\*.{json,yaml}') // true
1104
+ * matchGlobPattern('src/index.ts', 'src/\*.ts') // true
1105
+ * ```
1106
+ */
1107
+ function matchGlobPattern(path, pattern) {
1108
+ return matchSegments(path.split('/'), pattern.split('/'), 0, 0);
1109
+ }
1110
+ /**
1111
+ * Internal recursive function to match path segments against pattern segments.
1112
+ *
1113
+ * @param pathParts - Array of path segments split by '/'
1114
+ * @param patternParts - Array of pattern segments split by '/'
1115
+ * @param pathIdx - Current index in pathParts being examined
1116
+ * @param patternIdx - Current index in patternParts being examined
1117
+ * @returns True if remaining segments match
1118
+ */
1119
+ function matchSegments(pathParts, patternParts, pathIdx, patternIdx) {
1120
+ // Base cases
1121
+ if (pathIdx === pathParts.length && patternIdx === patternParts.length) {
1122
+ return true; // Both exhausted = match
1123
+ }
1124
+ if (patternIdx >= patternParts.length) {
1125
+ return false; // Pattern exhausted but path remains
1126
+ }
1127
+ const patternPart = patternParts[patternIdx];
1128
+ // Handle ** (globstar) - matches zero or more directories
1129
+ if (patternPart === '**') {
1130
+ // Try matching rest of pattern against current position and all future positions
1131
+ for (let i = pathIdx; i <= pathParts.length; i++) {
1132
+ if (matchSegments(pathParts, patternParts, i, patternIdx + 1)) {
1133
+ return true;
1134
+ }
1135
+ }
1136
+ return false;
1137
+ }
1138
+ if (pathIdx >= pathParts.length) {
1139
+ return false; // Path exhausted but pattern remains (and it's not **)
1140
+ }
1141
+ const pathPart = pathParts[pathIdx];
1142
+ // Match current segment
1143
+ if (matchSegment(pathPart, patternPart)) {
1144
+ return matchSegments(pathParts, patternParts, pathIdx + 1, patternIdx + 1);
1145
+ }
1146
+ return false;
1147
+ }
1148
+ /**
1149
+ * Match a single path segment against a pattern segment.
1150
+ * Handles *, ?, and {a,b,c} patterns.
1151
+ *
1152
+ * @param text - The path segment text to match
1153
+ * @param pattern - The pattern segment to match against
1154
+ * @returns True if the text matches the pattern
1155
+ */
1156
+ function matchSegment(text, pattern) {
1157
+ let textIdx = 0;
1158
+ let patternIdx = 0;
1159
+ while (patternIdx < pattern.length) {
1160
+ const char = pattern[patternIdx];
1161
+ if (char === '*') {
1162
+ // * matches zero or more characters
1163
+ patternIdx++;
1164
+ if (patternIdx === pattern.length) {
1165
+ return true; // * at end matches rest of string
1166
+ }
1167
+ // Try matching rest of pattern at each position in text
1168
+ for (let i = textIdx; i <= text.length; i++) {
1169
+ if (matchSegmentFrom(text, i, pattern, patternIdx)) {
1170
+ return true;
1171
+ }
1172
+ }
1173
+ return false;
1174
+ }
1175
+ else if (char === '?') {
1176
+ // ? matches exactly one character
1177
+ if (textIdx >= text.length) {
1178
+ return false;
1179
+ }
1180
+ textIdx++;
1181
+ patternIdx++;
1182
+ }
1183
+ else if (char === '{') {
1184
+ // {a,b,c} matches any alternative
1185
+ const closeIdx = findClosingBrace(pattern, patternIdx);
1186
+ if (closeIdx === -1) {
1187
+ // Unmatched brace, treat as literal
1188
+ if (textIdx >= text.length || text[textIdx] !== char) {
1189
+ return false;
1190
+ }
1191
+ textIdx++;
1192
+ patternIdx++;
1193
+ }
1194
+ else {
1195
+ const alternatives = extractAlternatives(pattern.slice(patternIdx + 1, closeIdx));
1196
+ for (const alt of alternatives) {
1197
+ if (matchSegmentFrom(text, textIdx, text.slice(0, textIdx) + alt + pattern.slice(closeIdx + 1), textIdx)) {
1198
+ return true;
1199
+ }
1200
+ }
1201
+ return false;
1202
+ }
1203
+ }
1204
+ else {
1205
+ // Literal character
1206
+ if (textIdx >= text.length || text[textIdx] !== char) {
1207
+ return false;
1208
+ }
1209
+ textIdx++;
1210
+ patternIdx++;
1211
+ }
1212
+ }
1213
+ return textIdx === text.length;
1214
+ }
1215
+ /**
1216
+ * Helper to match from a specific position.
1217
+ *
1218
+ * @param text - The full text being matched
1219
+ * @param textIdx - The starting index in text to match from
1220
+ * @param pattern - The full pattern being matched
1221
+ * @param patternIdx - The starting index in pattern to match from
1222
+ * @returns True if the text matches the pattern from the given positions
1223
+ */
1224
+ function matchSegmentFrom(text, textIdx, pattern, patternIdx) {
1225
+ const remainingText = text.slice(textIdx);
1226
+ const remainingPattern = pattern.slice(patternIdx);
1227
+ return matchSegment(remainingText, remainingPattern);
1228
+ }
1229
+ /**
1230
+ * Find closing brace for {a,b,c} pattern.
1231
+ *
1232
+ * @param pattern - The pattern string to search within
1233
+ * @param startIdx - The index of the opening brace
1234
+ * @returns The index of the matching closing brace, or -1 if not found
1235
+ */
1236
+ function findClosingBrace(pattern, startIdx) {
1237
+ let depth = 0;
1238
+ for (let i = startIdx; i < pattern.length; i++) {
1239
+ if (pattern[i] === '{') {
1240
+ depth++;
1241
+ }
1242
+ else if (pattern[i] === '}') {
1243
+ depth--;
1244
+ if (depth === 0) {
1245
+ return i;
1246
+ }
1247
+ }
1248
+ }
1249
+ return -1;
1250
+ }
1251
+ /**
1252
+ * Extract alternatives from {a,b,c} pattern content.
1253
+ *
1254
+ * @param content - The content between braces (without the braces themselves)
1255
+ * @returns Array of alternative strings split by commas at depth 0
1256
+ */
1257
+ function extractAlternatives(content) {
1258
+ const alternatives = [];
1259
+ let current = '';
1260
+ let depth = 0;
1261
+ for (let i = 0; i < content.length; i++) {
1262
+ const char = content[i];
1263
+ if (char === '{') {
1264
+ depth++;
1265
+ current += char;
1266
+ }
1267
+ else if (char === '}') {
1268
+ depth--;
1269
+ current += char;
1270
+ }
1271
+ else if (char === ',' && depth === 0) {
1272
+ alternatives.push(current);
1273
+ current = '';
1274
+ }
1275
+ else {
1276
+ current += char;
1277
+ }
1278
+ }
1279
+ if (current) {
1280
+ alternatives.push(current);
1281
+ }
1282
+ return alternatives;
1283
+ }
1284
+
1285
+ const walkLogger = createScopedLogger('project-scope:project:walk');
1286
+ /**
1287
+ * Reads .gitignore file from the given directory and extracts
1288
+ * non-comment patterns for use in file traversal filtering.
1289
+ *
1290
+ * @param startPath - Directory containing the .gitignore file
1291
+ * @returns Array of gitignore patterns
1292
+ */
1293
+ function loadGitignorePatterns(startPath) {
1294
+ const patterns = [];
1295
+ const gitignorePath = join$1(startPath, '.gitignore');
1296
+ const content = readFileIfExists(gitignorePath);
1297
+ if (content) {
1298
+ const lines = content.split('\n');
1299
+ for (const line of lines) {
1300
+ const trimmed = line.trim();
1301
+ if (trimmed && !trimmed.startsWith('#')) {
1302
+ patterns.push(trimmed);
1303
+ }
1304
+ }
1305
+ }
1306
+ return patterns;
1307
+ }
1308
+ /**
1309
+ * Evaluates whether a relative path should be ignored based on
1310
+ * a list of gitignore-style patterns.
1311
+ *
1312
+ * @param relativePath - Path relative to the root directory
1313
+ * @param patterns - Array of gitignore-style patterns to test
1314
+ * @returns True if the path matches any ignore pattern
1315
+ */
1316
+ function matchesIgnorePattern(relativePath, patterns) {
1317
+ for (const pattern of patterns) {
1318
+ if (matchPattern(relativePath, pattern)) {
1319
+ return true;
1320
+ }
1321
+ }
1322
+ return false;
1323
+ }
1324
+ /**
1325
+ * Tests if the given path matches a gitignore-style pattern,
1326
+ * supporting negation patterns with '!' prefix.
1327
+ * Uses safe character-by-character matching to prevent ReDoS attacks.
1328
+ *
1329
+ * @param path - File or directory path to test
1330
+ * @param pattern - Gitignore-style pattern (may include wildcards)
1331
+ * @returns True if the path matches the pattern (or doesn't match if negated)
1332
+ */
1333
+ function matchPattern(path, pattern) {
1334
+ const normalizedPattern = pattern.startsWith('/') ? pattern.slice(1) : pattern;
1335
+ const isNegation = normalizedPattern.startsWith('!');
1336
+ const actualPattern = isNegation ? normalizedPattern.slice(1) : normalizedPattern;
1337
+ const matchesFullPath = matchGlobPattern(path, actualPattern) || matchGlobPattern(path, `**/${actualPattern}`);
1338
+ const matchesSegment = path.split('/').some((segment) => matchGlobPattern(segment, actualPattern));
1339
+ const matches = matchesFullPath || matchesSegment;
1340
+ return isNegation ? !matches : matches;
1341
+ }
1342
+ /**
1343
+ * Traverses a directory tree synchronously, calling a visitor function
1344
+ * for each file and directory encountered. Supports depth limiting,
1345
+ * hidden file filtering, and gitignore pattern matching.
1346
+ *
1347
+ * @param startPath - Root directory to begin traversal
1348
+ * @param visitor - Callback function invoked for each file system entry
1349
+ * @param options - Configuration for traversal behavior
1350
+ */
1351
+ function walkDirectory(startPath, visitor, options) {
1352
+ walkLogger.debug('Starting directory walk', {
1353
+ startPath,
1354
+ maxDepth: options?.maxDepth ?? -1,
1355
+ includeHidden: options?.includeHidden ?? false,
1356
+ respectGitignore: options?.respectGitignore ?? true,
1357
+ ignorePatterns: options?.ignorePatterns?.length ?? 0,
1358
+ });
1359
+ const maxDepth = options?.maxDepth ?? -1;
1360
+ const includeHidden = options?.includeHidden ?? false;
1361
+ const ignorePatterns = options?.ignorePatterns ?? [];
1362
+ const respectGitignore = options?.respectGitignore ?? true;
1363
+ const gitignorePatterns = respectGitignore ? loadGitignorePatterns(startPath) : [];
1364
+ const allIgnorePatterns = [...ignorePatterns, ...gitignorePatterns];
1365
+ if (gitignorePatterns.length > 0) {
1366
+ walkLogger.debug('Loaded gitignore patterns', { count: gitignorePatterns.length });
1367
+ }
1368
+ /**
1369
+ * Recursively walks directory entries, applying visitor to each.
1370
+ *
1371
+ * @param currentPath - Absolute path to current directory
1372
+ * @param relativePath - Path relative to the starting directory
1373
+ * @param depth - Current recursion depth
1374
+ * @returns False to stop walking, true to continue
1375
+ */
1376
+ function walk(currentPath, relativePath, depth) {
1377
+ if (maxDepth !== -1 && depth > maxDepth) {
1378
+ return true;
1379
+ }
1380
+ let entries;
1381
+ try {
1382
+ entries = readDirectory(currentPath);
1383
+ }
1384
+ catch {
1385
+ return true;
1386
+ }
1387
+ for (const entry of entries) {
1388
+ if (!includeHidden && entry.name.startsWith('.')) {
1389
+ continue;
1390
+ }
1391
+ const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
1392
+ if (matchesIgnorePattern(entryRelativePath, allIgnorePatterns)) {
1393
+ continue;
1394
+ }
1395
+ const walkEntry = {
1396
+ name: entry.name,
1397
+ path: entry.path,
1398
+ relativePath: entryRelativePath,
1399
+ isFile: entry.isFile,
1400
+ isDirectory: entry.isDirectory,
1401
+ isSymlink: entry.isSymlink,
1402
+ depth,
1403
+ };
1404
+ const result = visitor(walkEntry);
1405
+ if (result === 'stop') {
1406
+ return false;
1407
+ }
1408
+ if (result === 'skip') {
1409
+ continue;
1410
+ }
1411
+ if (entry.isDirectory) {
1412
+ const shouldContinue = walk(entry.path, entryRelativePath, depth + 1);
1413
+ if (!shouldContinue) {
1414
+ return false;
1415
+ }
1416
+ }
1417
+ }
1418
+ return true;
1419
+ }
1420
+ walk(startPath, '', 0);
1421
+ walkLogger.debug('Directory walk complete', { startPath });
1422
+ }
1423
+
1424
+ const searchLogger = createScopedLogger('project-scope:project:search');
1425
+ /**
1426
+ * Tests if a path matches at least one pattern from an array of globs,
1427
+ * enabling flexible multi-pattern file filtering.
1428
+ * Uses safe character-by-character matching to prevent ReDoS attacks.
1429
+ *
1430
+ * @param path - File path to test
1431
+ * @param patterns - Array of glob patterns
1432
+ * @returns True if path matches any pattern
1433
+ */
1434
+ function matchesPatterns(path, patterns) {
1435
+ return patterns.some((pattern) => matchGlobPattern(path, pattern));
1436
+ }
1437
+ /**
1438
+ * Searches a directory tree for files matching one or more glob patterns,
1439
+ * returning relative or absolute paths based on options.
1440
+ *
1441
+ * @param startPath - Root directory to begin the search
1442
+ * @param patterns - Glob patterns (e.g., '*.ts', '**\/*.json') to filter files
1443
+ * @param options - Configuration for search behavior
1444
+ * @returns List of relative file paths that match the patterns
1445
+ *
1446
+ * @example
1447
+ * ```typescript
1448
+ * import { findFiles } from '@hyperfrontend/project-scope'
1449
+ *
1450
+ * // Find all TypeScript files
1451
+ * const tsFiles = findFiles('./src', '\*\*\/*.ts')
1452
+ *
1453
+ * // Find multiple file types
1454
+ * const configFiles = findFiles('./', ['\*.json', '\*.yaml', '\*.yml'])
1455
+ *
1456
+ * // Limit results and get absolute paths
1457
+ * const first10 = findFiles('./src', '\*\*\/*.ts', {
1458
+ * maxResults: 10,
1459
+ * absolutePaths: true
1460
+ * })
1461
+ * ```
1462
+ */
1463
+ function findFiles(startPath, patterns, options) {
1464
+ const normalizedPatterns = isArray(patterns) ? patterns : [patterns];
1465
+ searchLogger.debug('Finding files', { startPath, patterns: normalizedPatterns, maxResults: options?.maxResults });
1466
+ const results = [];
1467
+ const maxResults = options?.maxResults ?? Infinity;
1468
+ walkDirectory(startPath, (entry) => {
1469
+ if (results.length >= maxResults) {
1470
+ return 'stop';
1471
+ }
1472
+ if (!entry.isFile) {
1473
+ return undefined;
1474
+ }
1475
+ if (matchesPatterns(entry.relativePath, normalizedPatterns)) {
1476
+ results.push(options?.absolutePaths ? entry.path : entry.relativePath);
1477
+ }
1478
+ return undefined;
1479
+ }, options);
1480
+ searchLogger.debug('File search complete', { startPath, matchCount: results.length });
1481
+ return results;
1482
+ }
1483
+
1484
+ createScopedLogger('project-scope:heuristics:entry-points');
1485
+ /**
1486
+ * Cache for entry point discovery results.
1487
+ * TTL: 60 seconds (entry points are relatively stable)
1488
+ */
1489
+ createCache({ ttl: 60000, maxSize: 50 });
1490
+
1491
+ createScopedLogger('project-scope:tech');
1492
+ /**
1493
+ * Cache for tech detection results.
1494
+ * TTL: 60 seconds (tech stack can change during active development)
1495
+ */
1496
+ createCache({ ttl: 60000, maxSize: 50 });
1497
+
1498
+ createScopedLogger('project-scope:heuristics:project-type');
1499
+
1500
+ const rootLogger = createScopedLogger('project-scope:root');
1501
+ /**
1502
+ * Files indicating workspace/monorepo root.
1503
+ */
1504
+ const WORKSPACE_MARKERS = ['nx.json', 'turbo.json', 'lerna.json', 'pnpm-workspace.yaml', 'rush.json'];
1505
+ /**
1506
+ * Find workspace root (monorepo root).
1507
+ * Searches up for workspace markers like nx.json, turbo.json, etc.
1508
+ *
1509
+ * @param startPath - Starting path
1510
+ * @returns Workspace root path or null
1511
+ *
1512
+ * @example
1513
+ * ```typescript
1514
+ * import { findWorkspaceRoot } from '@hyperfrontend/project-scope'
1515
+ *
1516
+ * const root = findWorkspaceRoot('./libs/my-lib')
1517
+ * if (root) {
1518
+ * console.log('Monorepo root:', root) // e.g., '/home/user/my-monorepo'
1519
+ * }
1520
+ * ```
1521
+ */
1522
+ function findWorkspaceRoot(startPath) {
1523
+ rootLogger.debug('Finding workspace root', { startPath });
1524
+ const byMarker = locateByMarkers(startPath, WORKSPACE_MARKERS);
1525
+ if (byMarker) {
1526
+ rootLogger.debug('Found workspace root by marker', { root: byMarker });
1527
+ return byMarker;
1528
+ }
1529
+ const byWorkspaces = findUpwardWhere(startPath, (dir) => {
1530
+ const pkg = readPackageJsonIfExists(dir);
1531
+ return pkg?.workspaces !== undefined;
1532
+ });
1533
+ if (byWorkspaces) {
1534
+ rootLogger.debug('Found workspace root by workspaces field', { root: byWorkspaces });
1535
+ return byWorkspaces;
1536
+ }
1537
+ const byPackage = findNearestPackageJson(startPath);
1538
+ if (byPackage) {
1539
+ rootLogger.debug('Found workspace root by package.json', { root: byPackage });
1540
+ }
1541
+ else {
1542
+ rootLogger.debug('Workspace root not found');
1543
+ }
1544
+ return byPackage;
1545
+ }
1546
+
1547
+ createScopedLogger('project-scope:nx');
1548
+
1549
+ createScopedLogger('project-scope:nx:devkit');
1550
+
1551
+ createScopedLogger('project-scope:nx:config');
1552
+
1553
+ createScopedLogger('project-scope:config');
1554
+ /**
1555
+ * Cache for config detection results.
1556
+ * TTL: 30 seconds (configs can change frequently during setup)
1557
+ */
1558
+ createCache({ ttl: 30000, maxSize: 50 });
1559
+
1560
+ /** Logger for analysis operations */
1561
+ createScopedLogger('project-scope:analyze');
1562
+
1563
+ /** Logger for CLI operations */
1564
+ createScopedLogger('project-scope:cli');
1565
+
1566
+ createScopedLogger('project-scope:encoding');
1567
+
1568
+ createScopedLogger('project-scope:encoding:convert');
1569
+
1570
+ createScopedLogger('project-scope:heuristics:framework');
1571
+ /**
1572
+ * Cache for framework identification results.
1573
+ * TTL: 60 seconds (frameworks are stable but can change during development)
1574
+ */
1575
+ createCache({ ttl: 60000, maxSize: 50 });
1576
+
1577
+ createScopedLogger('project-scope:vfs:tree');
1578
+
1579
+ createScopedLogger('project-scope:vfs:factory');
1580
+
1581
+ createScopedLogger('project-scope:vfs');
1582
+
1583
+ createScopedLogger('project-scope:vfs:diff');
1584
+
1585
+ /**
1586
+ * Project Model
1587
+ *
1588
+ * Represents a single project/package within a workspace.
1589
+ * Contains package.json data, paths, and dependency information.
1590
+ */
1591
+ /**
1592
+ * Creates a new Project object.
1593
+ *
1594
+ * @param options - Project properties
1595
+ * @returns A new Project object
1596
+ */
1597
+ function createProject(options) {
1598
+ const isPrivate = options.packageJson['private'] === true;
1599
+ const publishable = !isPrivate && options.name !== undefined && options.version !== undefined;
1600
+ return {
1601
+ name: options.name,
1602
+ version: options.version,
1603
+ path: options.path,
1604
+ packageJsonPath: options.packageJsonPath,
1605
+ packageJson: options.packageJson,
1606
+ changelogPath: options.changelogPath ?? null,
1607
+ internalDependencies: options.internalDependencies ?? [],
1608
+ internalDependents: options.internalDependents ?? [],
1609
+ publishable,
1610
+ private: isPrivate,
1611
+ };
1612
+ }
1613
+
1614
+ /**
1615
+ * Workspace Model
1616
+ *
1617
+ * Represents a monorepo workspace with multiple projects.
1618
+ * Used for package discovery, dependency tracking, and coordinated versioning.
1619
+ */
1620
+ /**
1621
+ * Default workspace discovery patterns.
1622
+ */
1623
+ const DEFAULT_PATTERNS = [
1624
+ 'libs/*/package.json',
1625
+ 'apps/*/package.json',
1626
+ 'packages/*/package.json',
1627
+ 'tools/*/package.json',
1628
+ 'plugins/*/package.json',
1629
+ ];
1630
+ /**
1631
+ * Default exclusion patterns.
1632
+ */
1633
+ const DEFAULT_EXCLUDE = ['**/node_modules/**', '**/dist/**', '**/coverage/**', '**/.git/**'];
1634
+ /**
1635
+ * Default workspace configuration.
1636
+ */
1637
+ const DEFAULT_WORKSPACE_CONFIG = {
1638
+ patterns: DEFAULT_PATTERNS,
1639
+ exclude: DEFAULT_EXCLUDE,
1640
+ includeChangelogs: true,
1641
+ trackDependencies: true,
1642
+ };
1643
+
1644
+ /**
1645
+ * Dependency Graph
1646
+ *
1647
+ * Builds and analyzes dependency relationships between workspace projects.
1648
+ * Provides functions for traversing the dependency graph and determining
1649
+ * build/release order.
1650
+ */
1651
+ /**
1652
+ * Finds internal dependencies in a package.json.
1653
+ * Returns names of workspace packages that this package depends on.
1654
+ *
1655
+ * @param packageJson - Parsed package.json content
1656
+ * @param workspacePackageNames - Set of all package names in the workspace
1657
+ * @returns Array of internal dependency names
1658
+ *
1659
+ * @example
1660
+ * ```typescript
1661
+ * const internalDeps = findInternalDependencies(packageJson, allPackageNames)
1662
+ * // ['@scope/lib-a', '@scope/lib-b']
1663
+ * ```
1664
+ */
1665
+ function findInternalDependencies(packageJson, workspacePackageNames) {
1666
+ const internal = [];
1667
+ const allDeps = {
1668
+ ...packageJson.dependencies,
1669
+ ...packageJson.devDependencies,
1670
+ ...packageJson.peerDependencies,
1671
+ ...packageJson.optionalDependencies,
1672
+ };
1673
+ for (const depName of keys(allDeps)) {
1674
+ if (workspacePackageNames.has(depName)) {
1675
+ internal.push(depName);
1676
+ }
1677
+ }
1678
+ return internal;
1679
+ }
1680
+ /**
1681
+ * Finds internal dependencies with type information.
1682
+ *
1683
+ * @param packageName - Name of the package being analyzed
1684
+ * @param packageJson - Parsed package.json content
1685
+ * @param workspacePackageNames - Set of all package names in the workspace
1686
+ * @returns Array of dependency edges with type information
1687
+ */
1688
+ function findInternalDependenciesWithTypes(packageName, packageJson, workspacePackageNames) {
1689
+ const edges = [];
1690
+ const depTypes = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
1691
+ for (const depType of depTypes) {
1692
+ const deps = packageJson[depType];
1693
+ if (deps) {
1694
+ for (const [depName, versionRange] of entries(deps)) {
1695
+ if (workspacePackageNames.has(depName)) {
1696
+ edges.push({
1697
+ from: packageName,
1698
+ to: depName,
1699
+ type: depType,
1700
+ versionRange,
1701
+ });
1702
+ }
1703
+ }
1704
+ }
1705
+ }
1706
+ return edges;
1707
+ }
1708
+ /**
1709
+ * Builds a complete dependency graph from a list of projects.
1710
+ *
1711
+ * @param projects - List of projects to analyze
1712
+ * @returns Dependency graph analysis result
1713
+ *
1714
+ * @example
1715
+ * ```typescript
1716
+ * import { buildDependencyGraph, discoverPackages } from '@hyperfrontend/versioning'
1717
+ *
1718
+ * const { projects } = discoverPackages()
1719
+ * const analysis = buildDependencyGraph(projects)
1720
+ *
1721
+ * // Get packages that depend on 'lib-utils'
1722
+ * const dependents = analysis.dependencyGraph.get('lib-utils') ?? []
1723
+ *
1724
+ * // Get packages in topological order for building
1725
+ * const buildOrder = getTopologicalOrder(analysis)
1726
+ * ```
1727
+ */
1728
+ function buildDependencyGraph(projects) {
1729
+ const packageNames = createSet(projects.map((p) => p.name));
1730
+ const edges = [];
1731
+ // Collect all edges
1732
+ for (const project of projects) {
1733
+ const projectEdges = findInternalDependenciesWithTypes(project.name, project.packageJson, packageNames);
1734
+ edges.push(...projectEdges);
1735
+ }
1736
+ // Build forward graph (dependency -> dependents)
1737
+ const dependencyGraph = createMap();
1738
+ for (const name of packageNames) {
1739
+ dependencyGraph.set(name, []);
1740
+ }
1741
+ for (const edge of edges) {
1742
+ const dependents = dependencyGraph.get(edge.to);
1743
+ if (dependents) {
1744
+ dependents.push(edge.from);
1745
+ }
1746
+ }
1747
+ // Build reverse graph (package -> dependencies)
1748
+ const reverseDependencyGraph = createMap();
1749
+ for (const name of packageNames) {
1750
+ reverseDependencyGraph.set(name, []);
1751
+ }
1752
+ for (const edge of edges) {
1753
+ const deps = reverseDependencyGraph.get(edge.from);
1754
+ if (deps) {
1755
+ deps.push(edge.to);
1756
+ }
1757
+ }
1758
+ // Find leaf packages (no dependents)
1759
+ const leafPackages = [];
1760
+ for (const [name, dependents] of dependencyGraph) {
1761
+ if (dependents.length === 0) {
1762
+ leafPackages.push(name);
1763
+ }
1764
+ }
1765
+ // Find root packages (no dependencies)
1766
+ const rootPackages = [];
1767
+ for (const [name, deps] of reverseDependencyGraph) {
1768
+ if (deps.length === 0) {
1769
+ rootPackages.push(name);
1770
+ }
1771
+ }
1772
+ // Detect circular dependencies
1773
+ const { hasCircular, cycles } = detectCircularDependencies(reverseDependencyGraph);
1774
+ // Convert to readonly maps
1775
+ const readonlyDependencyGraph = createMap();
1776
+ for (const [key, value] of dependencyGraph) {
1777
+ readonlyDependencyGraph.set(key, [...value]);
1778
+ }
1779
+ const readonlyReverseDependencyGraph = createMap();
1780
+ for (const [key, value] of reverseDependencyGraph) {
1781
+ readonlyReverseDependencyGraph.set(key, [...value]);
1782
+ }
1783
+ return {
1784
+ dependencyGraph: readonlyDependencyGraph,
1785
+ reverseDependencyGraph: readonlyReverseDependencyGraph,
1786
+ edges,
1787
+ leafPackages,
1788
+ rootPackages,
1789
+ hasCircularDependencies: hasCircular,
1790
+ circularDependencies: cycles,
1791
+ };
1792
+ }
1793
+ /**
1794
+ * Detects circular dependencies in the graph using DFS.
1795
+ *
1796
+ * @param reverseDependencyGraph - Map of package to its dependencies
1797
+ * @returns Detection result with cycle information
1798
+ */
1799
+ function detectCircularDependencies(reverseDependencyGraph) {
1800
+ const cycles = [];
1801
+ const visited = createSet();
1802
+ const recursionStack = createSet();
1803
+ const path = [];
1804
+ /**
1805
+ * Depth-first search to detect cycles.
1806
+ *
1807
+ * @param node - Current node being visited
1808
+ * @returns True if a cycle was found
1809
+ */
1810
+ function dfs(node) {
1811
+ visited.add(node);
1812
+ recursionStack.add(node);
1813
+ path.push(node);
1814
+ const deps = reverseDependencyGraph.get(node) ?? [];
1815
+ for (const dep of deps) {
1816
+ if (!visited.has(dep)) {
1817
+ if (dfs(dep)) {
1818
+ return true;
1819
+ }
1820
+ }
1821
+ else if (recursionStack.has(dep)) {
1822
+ // Found a cycle
1823
+ const cycleStart = path.indexOf(dep);
1824
+ const cycle = path.slice(cycleStart);
1825
+ cycle.push(dep); // Close the cycle
1826
+ cycles.push(cycle);
1827
+ }
1828
+ }
1829
+ path.pop();
1830
+ recursionStack.delete(node);
1831
+ return false;
1832
+ }
1833
+ for (const node of reverseDependencyGraph.keys()) {
1834
+ if (!visited.has(node)) {
1835
+ dfs(node);
1836
+ }
1837
+ }
1838
+ return {
1839
+ hasCircular: cycles.length > 0,
1840
+ cycles,
1841
+ };
1842
+ }
1843
+ /**
1844
+ * Gets a topological ordering of packages for building.
1845
+ * Packages with no dependencies come first.
1846
+ *
1847
+ * @param analysis - Dependency graph analysis result
1848
+ * @returns Array of package names in build order
1849
+ * @throws {Error} If circular dependencies exist
1850
+ *
1851
+ * @example
1852
+ * ```typescript
1853
+ * const buildOrder = getTopologicalOrder(analysis)
1854
+ * for (const pkg of buildOrder) {
1855
+ * await build(pkg)
1856
+ * }
1857
+ * ```
1858
+ */
1859
+ function getTopologicalOrder(analysis) {
1860
+ if (analysis.hasCircularDependencies) {
1861
+ throw createError(`Circular dependencies detected: ${analysis.circularDependencies.map((c) => c.join(' -> ')).join(', ')}`);
1862
+ }
1863
+ const result = [];
1864
+ const inDegree = createMap();
1865
+ const adjacency = createMap();
1866
+ // Initialize
1867
+ for (const [name, deps] of analysis.reverseDependencyGraph) {
1868
+ inDegree.set(name, deps.length);
1869
+ adjacency.set(name, []);
1870
+ }
1871
+ // Build adjacency list (dependency -> dependents)
1872
+ for (const [name, deps] of analysis.reverseDependencyGraph) {
1873
+ for (const dep of deps) {
1874
+ const adj = adjacency.get(dep);
1875
+ if (adj) {
1876
+ adj.push(name);
1877
+ }
1878
+ }
1879
+ }
1880
+ // Kahn's algorithm
1881
+ const queue = [...analysis.rootPackages];
1882
+ while (queue.length > 0) {
1883
+ const node = queue.shift();
1884
+ if (node === undefined) {
1885
+ break;
1886
+ }
1887
+ result.push(node);
1888
+ const dependents = adjacency.get(node) ?? [];
1889
+ for (const dependent of dependents) {
1890
+ const degree = inDegree.get(dependent) ?? 0;
1891
+ inDegree.set(dependent, degree - 1);
1892
+ if (degree - 1 === 0) {
1893
+ queue.push(dependent);
1894
+ }
1895
+ }
1896
+ }
1897
+ return result;
1898
+ }
1899
+ /**
1900
+ * Gets all transitive dependents of a package (direct and indirect).
1901
+ *
1902
+ * @param workspace - The workspace containing projects
1903
+ * @param packageName - Name of the package to analyze
1904
+ * @returns Set of all packages that depend on this package
1905
+ *
1906
+ * @example
1907
+ * ```typescript
1908
+ * // If lib-a depends on lib-utils and app-main depends on lib-a
1909
+ * // Then getTransitiveDependents('lib-utils') returns ['lib-a', 'app-main']
1910
+ * ```
1911
+ */
1912
+ function getTransitiveDependents(workspace, packageName) {
1913
+ const dependents = createSet();
1914
+ const queue = [packageName];
1915
+ while (queue.length > 0) {
1916
+ const current = queue.shift();
1917
+ if (current === undefined) {
1918
+ break;
1919
+ }
1920
+ const directDependents = workspace.dependencyGraph.get(current) ?? [];
1921
+ for (const dep of directDependents) {
1922
+ if (!dependents.has(dep)) {
1923
+ dependents.add(dep);
1924
+ queue.push(dep);
1925
+ }
1926
+ }
1927
+ }
1928
+ return dependents;
1929
+ }
1930
+ /**
1931
+ * Gets all transitive dependencies of a package (direct and indirect).
1932
+ *
1933
+ * @param workspace - The workspace containing projects
1934
+ * @param packageName - Name of the package to analyze
1935
+ * @returns Set of all packages this package depends on
1936
+ */
1937
+ function getTransitiveDependencies(workspace, packageName) {
1938
+ const dependencies = createSet();
1939
+ const queue = [packageName];
1940
+ while (queue.length > 0) {
1941
+ const current = queue.shift();
1942
+ if (current === undefined) {
1943
+ break;
1944
+ }
1945
+ const directDeps = workspace.reverseDependencyGraph.get(current) ?? [];
1946
+ for (const dep of directDeps) {
1947
+ if (!dependencies.has(dep)) {
1948
+ dependencies.add(dep);
1949
+ queue.push(dep);
1950
+ }
1951
+ }
1952
+ }
1953
+ return dependencies;
1954
+ }
1955
+ /**
1956
+ * Checks if package A transitively depends on package B.
1957
+ *
1958
+ * @param workspace - The workspace containing projects
1959
+ * @param packageA - Name of the potentially dependent package
1960
+ * @param packageB - Name of the potential dependency
1961
+ * @returns True if packageA transitively depends on packageB
1962
+ */
1963
+ function transitivelyDependsOn(workspace, packageA, packageB) {
1964
+ const deps = getTransitiveDependencies(workspace, packageA);
1965
+ return deps.has(packageB);
1966
+ }
1967
+
1968
+ /**
1969
+ * Changelog Discovery
1970
+ *
1971
+ * Discovers CHANGELOG.md files within workspace projects.
1972
+ */
1973
+ /**
1974
+ * Common changelog file names in priority order.
1975
+ */
1976
+ const CHANGELOG_NAMES = ['CHANGELOG.md', 'Changelog.md', 'changelog.md', 'HISTORY.md', 'CHANGES.md'];
1977
+ /**
1978
+ * Finds changelog files for a list of packages.
1979
+ * Returns a map of project path to changelog absolute path.
1980
+ *
1981
+ * @param workspaceRoot - Workspace root path
1982
+ * @param packages - List of packages to find changelogs for
1983
+ * @returns Map of project path to changelog path
1984
+ */
1985
+ function findChangelogs(workspaceRoot, packages) {
1986
+ const result = createMap();
1987
+ for (const pkg of packages) {
1988
+ const changelogPath = findProjectChangelog(pkg.path);
1989
+ if (changelogPath) {
1990
+ result.set(pkg.path, changelogPath);
1991
+ }
1992
+ }
1993
+ return result;
1994
+ }
1995
+ /**
1996
+ * Finds the changelog file for a single project.
1997
+ * Checks for common changelog names in order of priority.
1998
+ *
1999
+ * @param projectPath - Path to project directory
2000
+ * @returns Absolute path to changelog or null if not found
2001
+ *
2002
+ * @example
2003
+ * ```typescript
2004
+ * import { findProjectChangelog } from '@hyperfrontend/versioning'
2005
+ *
2006
+ * const changelogPath = findProjectChangelog('./libs/my-lib')
2007
+ * if (changelogPath) {
2008
+ * console.log('Found changelog:', changelogPath)
2009
+ * }
2010
+ * ```
2011
+ */
2012
+ function findProjectChangelog(projectPath) {
2013
+ for (const name of CHANGELOG_NAMES) {
2014
+ const changelogPath = join$1(projectPath, name);
2015
+ if (exists(changelogPath)) {
2016
+ return changelogPath;
2017
+ }
2018
+ }
2019
+ return null;
2020
+ }
2021
+ /**
2022
+ * Discovers all changelog files within a workspace.
2023
+ *
2024
+ * @param workspaceRoot - Workspace root path
2025
+ * @param patterns - Glob patterns for finding changelogs (default: all CHANGELOGs)
2026
+ * @returns Array of discovered changelog information
2027
+ *
2028
+ * @example
2029
+ * ```typescript
2030
+ * import { discoverAllChangelogs } from '@hyperfrontend/versioning'
2031
+ *
2032
+ * const changelogs = discoverAllChangelogs('/path/to/workspace')
2033
+ * for (const changelog of changelogs) {
2034
+ * console.log(`${changelog.projectPath} -> ${changelog.path}`)
2035
+ * }
2036
+ * ```
2037
+ */
2038
+ function discoverAllChangelogs(workspaceRoot, patterns = ['**/CHANGELOG.md', '**/Changelog.md', '**/changelog.md']) {
2039
+ const results = [];
2040
+ const files = findFiles(workspaceRoot, [...patterns], {
2041
+ ignorePatterns: ['**/node_modules/**', '**/dist/**'],
2042
+ absolutePaths: false,
2043
+ });
2044
+ for (const relativePath of files) {
2045
+ const absolutePath = join$1(workspaceRoot, relativePath);
2046
+ const projectPath = dirname(absolutePath);
2047
+ const filename = relativePath.split('/').pop() ?? 'CHANGELOG.md';
2048
+ results.push({
2049
+ path: absolutePath,
2050
+ relativePath,
2051
+ projectPath,
2052
+ filename,
2053
+ });
2054
+ }
2055
+ return results;
2056
+ }
2057
+
2058
+ /**
2059
+ * Package Discovery
2060
+ *
2061
+ * Discovers packages within a workspace by finding package.json files
2062
+ * and extracting relevant metadata. Uses project-scope for file operations.
2063
+ */
2064
+ /**
2065
+ * Discovers all packages within a workspace.
2066
+ * Finds package.json files, parses them, and optionally discovers
2067
+ * changelogs and internal dependencies.
2068
+ *
2069
+ * @param options - Discovery options
2070
+ * @returns Discovery result with all found packages
2071
+ * @throws {Error} If workspace root cannot be found
2072
+ *
2073
+ * @example
2074
+ * ```typescript
2075
+ * import { discoverPackages } from '@hyperfrontend/versioning'
2076
+ *
2077
+ * // Discover all packages in current workspace
2078
+ * const result = discoverPackages()
2079
+ *
2080
+ * // Discover with custom patterns
2081
+ * const result = discoverPackages({
2082
+ * patterns: ['packages/*\/package.json'],
2083
+ * includeChangelogs: true
2084
+ * })
2085
+ *
2086
+ * // Access discovered projects
2087
+ * for (const project of result.projects) {
2088
+ * console.log(`${project.name}@${project.version}`)
2089
+ * }
2090
+ * ```
2091
+ */
2092
+ function discoverPackages(options = {}) {
2093
+ // Resolve workspace root
2094
+ const workspaceRoot = options.workspaceRoot ?? findWorkspaceRoot(process.cwd());
2095
+ if (!workspaceRoot) {
2096
+ throw createError('Could not find workspace root. Ensure you are in a monorepo with nx.json, turbo.json, or workspaces field.');
2097
+ }
2098
+ // Build configuration
2099
+ const config = {
2100
+ patterns: options.patterns ?? DEFAULT_WORKSPACE_CONFIG.patterns,
2101
+ exclude: options.exclude ?? DEFAULT_WORKSPACE_CONFIG.exclude,
2102
+ includeChangelogs: options.includeChangelogs ?? DEFAULT_WORKSPACE_CONFIG.includeChangelogs,
2103
+ trackDependencies: options.trackDependencies ?? DEFAULT_WORKSPACE_CONFIG.trackDependencies,
2104
+ };
2105
+ // Find all package.json files
2106
+ const packageJsonPaths = findPackageJsonFiles(workspaceRoot, config);
2107
+ // Parse package.json files
2108
+ const rawPackages = parsePackageJsonFiles(workspaceRoot, packageJsonPaths);
2109
+ // Collect all package names for internal dependency detection
2110
+ const packageNames = createSet(rawPackages.map((p) => p.name));
2111
+ // Find changelogs if requested
2112
+ const changelogMap = config.includeChangelogs ? findChangelogs(workspaceRoot, rawPackages) : createMap();
2113
+ // Build projects with changelog paths
2114
+ const rawWithChangelogs = rawPackages.map((pkg) => ({
2115
+ ...pkg,
2116
+ changelogPath: changelogMap.get(pkg.path) ?? null,
2117
+ }));
2118
+ // Calculate internal dependencies
2119
+ const projects = config.trackDependencies
2120
+ ? buildProjectsWithDependencies(rawWithChangelogs, packageNames)
2121
+ : rawWithChangelogs.map((pkg) => createProject(pkg));
2122
+ // Build project map
2123
+ const projectMap = createMap();
2124
+ for (const project of projects) {
2125
+ projectMap.set(project.name, project);
2126
+ }
2127
+ return {
2128
+ projects,
2129
+ projectMap,
2130
+ packageNames,
2131
+ workspaceRoot,
2132
+ config,
2133
+ };
2134
+ }
2135
+ /**
2136
+ * Finds all package.json files matching the configured patterns.
2137
+ *
2138
+ * @param workspaceRoot - Root directory to search from
2139
+ * @param config - Workspace configuration
2140
+ * @returns Array of relative paths to package.json files
2141
+ */
2142
+ function findPackageJsonFiles(workspaceRoot, config) {
2143
+ const patterns = [...config.patterns];
2144
+ const excludePatterns = [...config.exclude];
2145
+ return findFiles(workspaceRoot, patterns, {
2146
+ ignorePatterns: excludePatterns,
2147
+ });
2148
+ }
2149
+ /**
2150
+ * Parses package.json files and extracts metadata.
2151
+ *
2152
+ * @param workspaceRoot - Workspace root path
2153
+ * @param packageJsonPaths - Relative paths to package.json files
2154
+ * @returns Array of raw package info objects
2155
+ */
2156
+ function parsePackageJsonFiles(workspaceRoot, packageJsonPaths) {
2157
+ const packages = [];
2158
+ for (const relativePath of packageJsonPaths) {
2159
+ const absolutePath = join$1(workspaceRoot, relativePath);
2160
+ const projectPath = dirname(absolutePath);
2161
+ try {
2162
+ const packageJson = readPackageJson(absolutePath);
2163
+ // Skip packages without a name
2164
+ if (!packageJson.name) {
2165
+ continue;
2166
+ }
2167
+ packages.push({
2168
+ name: packageJson.name,
2169
+ version: packageJson.version ?? '0.0.0',
2170
+ path: projectPath,
2171
+ packageJsonPath: absolutePath,
2172
+ packageJson,
2173
+ changelogPath: null,
2174
+ });
2175
+ }
2176
+ catch {
2177
+ // Skip packages that can't be parsed
2178
+ continue;
2179
+ }
2180
+ }
2181
+ return packages;
2182
+ }
2183
+ /**
2184
+ * Builds projects with internal dependency information.
2185
+ *
2186
+ * @param rawPackages - Raw package info objects
2187
+ * @param packageNames - Set of all package names
2188
+ * @returns Array of Project objects with dependencies populated
2189
+ */
2190
+ function buildProjectsWithDependencies(rawPackages, packageNames) {
2191
+ // First pass: create projects with dependencies
2192
+ const projectsWithDeps = [];
2193
+ for (const pkg of rawPackages) {
2194
+ const internalDeps = findInternalDependencies(pkg.packageJson, packageNames);
2195
+ projectsWithDeps.push({
2196
+ ...pkg,
2197
+ internalDependencies: internalDeps,
2198
+ });
2199
+ }
2200
+ // Build dependency -> dependents map
2201
+ const dependentsMap = createMap();
2202
+ for (const pkg of projectsWithDeps) {
2203
+ for (const dep of pkg.internalDependencies) {
2204
+ const existing = dependentsMap.get(dep) ?? [];
2205
+ existing.push(pkg.name);
2206
+ dependentsMap.set(dep, existing);
2207
+ }
2208
+ }
2209
+ // Second pass: add dependents to each project
2210
+ return projectsWithDeps.map((pkg) => {
2211
+ const dependents = dependentsMap.get(pkg.name) ?? [];
2212
+ return createProject({
2213
+ ...pkg,
2214
+ internalDependents: dependents,
2215
+ });
2216
+ });
2217
+ }
2218
+ /**
2219
+ * Discovers a single project by path.
2220
+ *
2221
+ * @param projectPath - Path to project directory or package.json
2222
+ * @returns The discovered project or null if not found
2223
+ */
2224
+ function discoverProject(projectPath) {
2225
+ const packageJsonPath = projectPath.endsWith('package.json') ? projectPath : join$1(projectPath, 'package.json');
2226
+ const projectDir = projectPath.endsWith('package.json') ? dirname(projectPath) : projectPath;
2227
+ try {
2228
+ const packageJson = readPackageJson(packageJsonPath);
2229
+ if (!packageJson.name) {
2230
+ return null;
2231
+ }
2232
+ return createProject({
2233
+ name: packageJson.name,
2234
+ version: packageJson.version ?? '0.0.0',
2235
+ path: projectDir,
2236
+ packageJsonPath,
2237
+ packageJson,
2238
+ changelogPath: null,
2239
+ });
2240
+ }
2241
+ catch {
2242
+ return null;
2243
+ }
2244
+ }
2245
+ /**
2246
+ * Discovers a project by name within a workspace.
2247
+ *
2248
+ * @param projectName - Name of the project to find
2249
+ * @param options - Discovery options
2250
+ * @returns The project or null if not found
2251
+ */
2252
+ function discoverProjectByName(projectName, options = {}) {
2253
+ const result = discoverPackages(options);
2254
+ return result.projectMap.get(projectName) ?? null;
2255
+ }
2256
+
2257
+ /**
2258
+ * Changelog Path Utilities
2259
+ *
2260
+ * Functions for checking changelog existence and resolving expected paths.
2261
+ */
2262
+ /**
2263
+ * Checks if a project has a changelog file.
2264
+ *
2265
+ * @param projectPath - Directory containing the project to check
2266
+ * @returns True if changelog exists
2267
+ */
2268
+ function hasChangelog(projectPath) {
2269
+ return findProjectChangelog(projectPath) !== null;
2270
+ }
2271
+ /**
2272
+ * Gets the expected changelog path for a project.
2273
+ * Returns the standard CHANGELOG.md path regardless of whether it exists.
2274
+ *
2275
+ * @param projectPath - Directory containing the project files
2276
+ * @returns Absolute path to CHANGELOG.md in the project directory
2277
+ */
2278
+ function getExpectedChangelogPath(projectPath) {
2279
+ return join$1(projectPath, 'CHANGELOG.md');
2280
+ }
2281
+
2282
+ export { CHANGELOG_NAMES, buildDependencyGraph, discoverAllChangelogs, discoverPackages, discoverProject, discoverProjectByName, findChangelogs, findInternalDependencies, findInternalDependenciesWithTypes, findProjectChangelog, getExpectedChangelogPath, getTopologicalOrder, getTransitiveDependencies, getTransitiveDependents, hasChangelog, transitivelyDependsOn };
2283
+ //# sourceMappingURL=index.esm.js.map