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