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