pkg-scaffold 2.4.0 → 3.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/docs/guide.md ADDED
@@ -0,0 +1,102 @@
1
+ # Getting Started with pkg-scaffold
2
+
3
+ This guide will walk you through the installation and basic usage of `pkg-scaffold`. Learn how to quickly clean and optimize your project.
4
+
5
+ ## Installation
6
+
7
+ `pkg-scaffold` is an npm package and can be easily installed in your project. It is recommended to install it as a `devDependency`.
8
+
9
+ ```bash
10
+ npm install --save-dev pkg-scaffold
11
+ # or
12
+ yarn add --dev pkg-scaffold
13
+ # or
14
+ pnpm add --save-dev pkg-scaffold
15
+ ```
16
+
17
+ After installation, you can run `pkg-scaffold` via `npx` or by adding a script to your `package.json`.
18
+
19
+ ## Basic Usage
20
+
21
+ ### Dry-Run Mode (Recommended)
22
+
23
+ Before making any changes to your project, it is always advisable to use the dry-run mode. This mode analyzes your project and shows you which changes *would be made* without actually applying them.
24
+
25
+ ```bash
26
+ npx pkg-scaffold --no-fix
27
+ ```
28
+
29
+ This command will output a summary of identified issues, such as orphaned files or potential refactoring opportunities.
30
+
31
+ ### Applying Changes
32
+
33
+ If you are satisfied with the proposed changes, you can run `pkg-scaffold` with the `--fix` option to apply the changes to your project. The `--yes` option skips the confirmation prompt.
34
+
35
+ ```bash
36
+ npx pkg-scaffold --fix --yes
37
+ ```
38
+
39
+ **Caution:** Ensure you have backed up your changes or are in a version control system before using this option.
40
+
41
+ ### Monorepo Support
42
+
43
+ For projects organized in a monorepo, `pkg-scaffold` can be run with the `--workspace` option to analyze and optimize all packages within the workspace.
44
+
45
+ ```bash
46
+ npx pkg-scaffold --workspace --fix --yes
47
+ ```
48
+
49
+ ## Next Steps
50
+
51
+ * Learn more about all available options in the [Reference](/reference).
52
+ * Visit the [GitHub Repository](https://github.com/DreamLongYT/pkg-scaffold) for the latest updates and to report issues.
53
+
54
+ ## Plugin Development
55
+
56
+ Building a plugin for pkg-scaffold is straightforward. You need to export a class that extends the `BasePlugin` (or follows its structure).
57
+
58
+ ### Basic Plugin Structure
59
+
60
+ ```javascript
61
+ export default class MyCustomPlugin {
62
+ constructor(context) {
63
+ this.context = context;
64
+ }
65
+
66
+ // Unique identifier for the plugin
67
+ get name() {
68
+ return 'my-plugin';
69
+ }
70
+
71
+ // Files that indicate this ecosystem is active
72
+ getConfigFiles() {
73
+ return ['my-config.json'];
74
+ }
75
+
76
+ // Regex patterns for entry point files
77
+ getRoutePatterns() {
78
+ return [
79
+ /\/src\/routes\/.*\.js$/
80
+ ];
81
+ }
82
+
83
+ // Symbols that should never be flagged as unused in entry points
84
+ getRequiredSystemContracts() {
85
+ return ['default', 'handler', 'config'];
86
+ }
87
+
88
+ // Logic to determine if the plugin should run
89
+ async isActive(baseDir) {
90
+ // Return true if your framework is detected
91
+ return true;
92
+ }
93
+ }
94
+ ```
95
+
96
+ ### Advanced: Interfacing with the Engine
97
+
98
+ Plugins have access to the `context`, allowing them to trigger specific engine behaviors like `fastMode` or `selfHealing` for certain file types.
99
+
100
+ ### Knip Compatibility
101
+
102
+ If you are porting a Knip plugin, ensure the export mappings align with the `getRoutePatterns()` and `getRequiredSystemContracts()` methods to ensure full compatibility with the pkg-scaffold resolution graph.
package/docs/index.md ADDED
@@ -0,0 +1,64 @@
1
+ ---
2
+ layout: home
3
+
4
+ hero:
5
+ name: "pkg-scaffold"
6
+ text: "AST-driven Refactoring & Self-Healing Engine"
7
+ tagline: "Optimize your codebase with precise AST analysis and automated cleanup."
8
+ actions:
9
+ - theme: brand
10
+ text: Get Started
11
+ link: /guide
12
+ - theme: alt
13
+ text: View on GitHub
14
+ link: https://github.com/DreamLongYT/pkg-scaffold
15
+
16
+ features:
17
+ - title: AST-Driven Analysis
18
+ details: pkg-scaffold leverages Abstract Syntax Trees (ASTs) for deep and precise analysis of your codebase, identifying unused structures and optimization potentials.
19
+ - title: Intelligent Refactoring
20
+ details: Automatic detection and pruning of orphaned files and dead code to improve the maintainability and performance of your project.
21
+ - title: Dry-Run Mode
22
+ details: Preview all proposed structural changes before they are actually applied, ensuring maximum control and safety.
23
+ - title: Monorepo Support
24
+ details: Optimized for complex project structures and monorepos, ensuring consistent code quality across multiple packages.
25
+ - title: Integrated Test Validation
26
+ details: Executes integrated tests after each modification to verify workspace integrity and prevent regressions.
27
+ - title: Seamless Integration
28
+ details: As a CLI tool, pkg-scaffold integrates effortlessly into existing CI/CD workflows and development environments.
29
+ ---
30
+
31
+
32
+ # Welcome to pkg-scaffold
33
+
34
+ pkg-scaffold is a powerful command-line tool designed to enhance the health and efficiency of your JavaScript and TypeScript projects. By utilizing an advanced AST engine, it identifies and fixes structural issues, optimizes dependencies, and ensures a clean and maintainable codebase.
35
+
36
+ Whether you are working on a small project or a large monorepo, pkg-scaffold helps streamline your development experience and secure the quality of your code.
37
+
38
+ ## pkg-scaffold vs. Knip.dev vs. ts-prune
39
+
40
+ While tools like Knip.dev and ts-prune are excellent for specific tasks, pkg-scaffold offers a unique approach with its AST-driven refactoring and self-healing capabilities. Here's how it compares:
41
+
42
+ | Feature / Tool | pkg-scaffold | Knip.dev | ts-prune |
43
+ | :------------------- | :--------------------------------------------- | :------------------------------------------- | :----------------------------------------- |
44
+ | **Primary Focus** | Structural Refactoring, Self-Healing, Orphaned Files | Unused Dependencies, Exports, Files | Unused Exports |
45
+ | **Analysis Method** | AST-driven, Deep Structural Analysis | Deep Analysis with fine-grained entry points | TypeScript Compiler API |
46
+ | **Unused Dependencies** | Limited (focus on structural usage) | Yes (very detailed) | No |
47
+ | **Unused Exports** | No (currently) | Yes | Yes |
48
+ | **Orphaned Files** | Yes (core feature) | Yes | No |
49
+ | **Automated Fixes** | Yes (`--fix` option) | Yes | No (reporting only) |
50
+ | **Monorepo Support** | Yes | Yes | Limited |
51
+ | **Integrated Test Validation** | Yes (post-fix) | No | No |
52
+ | **Key Advantage** | **Proactive structural integrity, self-healing, prevents file bloat.** | **Comprehensive dependency/export cleanup, excellent for bundle size.** | **Simple, fast unused export detection for TS.** |
53
+
54
+ ### Where pkg-scaffold excels:
55
+
56
+ pkg-scaffold shines in maintaining the **structural integrity** of your project. Unlike Knip.dev, which focuses heavily on unused dependencies and exports (often for bundle size optimization), pkg-scaffold's core strength lies in:
57
+
58
+ * **Orphaned File Detection & Pruning:** It actively identifies and removes files that are no longer referenced anywhere in your codebase, preventing file system bloat and confusion.
59
+ * **AST-driven Self-Healing:** Its deep AST analysis allows for more intelligent structural refactoring, ensuring that your project's architecture remains sound over time.
60
+ * **Integrated Safety:** By running tests post-fix, it provides an additional layer of confidence that automated changes haven't introduced regressions.
61
+
62
+ While Knip.dev is superior for finding unused `package.json` dependencies and exports, pkg-scaffold complements it by focusing on the physical file structure and overall project health. ts-prune is a simpler tool specifically for TypeScript unused exports.
63
+
64
+ Start optimizing your projects today! Head over to the [Getting Started Guide](/guide) to learn more.
@@ -0,0 +1,52 @@
1
+ # CLI Reference
2
+
3
+ This page lists all available command-line options for `pkg-scaffold`.
4
+
5
+ ```text
6
+ Usage: pkg-scaffold [options]
7
+ Enterprise-Grade AST Syntax Refactoring & Self-Healing Engine
8
+
9
+ Options:
10
+ -V, --version output the version number
11
+ -c, --cwd <path> Specify the execution context root directory (default: "/home/ubuntu/test-project")
12
+ --fix Enable atomic code updates, structural file pruning, and active type sanitization (default: true)
13
+ --no-fix Disable direct file manipulation modifications (dry-run reporting mode)
14
+ --tsconfig <filename> Specify path to custom layout configurations (default: "tsconfig.json")
15
+ --test-command <command> Integrated continuous safety test validation script execution path (default: "npm test")
16
+ --workspace Enable high-density workspace workspace/monorepo cluster mesh evaluation parsing (default: false)
17
+ --verbose Toggle expanded trace telemetry for debug operational diagnostics (default: false)
18
+ -y, --yes Skip confirmation prompts and execute planned structural modifications automatically (default: false)
19
+ -h, --help display help for command
20
+ ```
21
+
22
+ ## Options in Detail
23
+
24
+ ### `-V`, `--version`
25
+ Displays the current version of `pkg-scaffold`.
26
+
27
+ ### `-c`, `--cwd <path>`
28
+ Defines the root directory where `pkg-scaffold` should be executed. By default, this is the current working directory.
29
+
30
+ ### `--fix`
31
+ Activates the mode for atomic code updates, structural file pruning, and active type sanitization. This is the mode in which `pkg-scaffold` makes actual changes to your code.
32
+
33
+ ### `--no-fix`
34
+ Disables direct file manipulation modifications. `pkg-scaffold` performs an analysis and reports on potential changes without applying them (dry-run mode).
35
+
36
+ ### `--tsconfig <filename>`
37
+ Specifies the path to a custom `tsconfig.json` file. By default, `pkg-scaffold` looks for `tsconfig.json` in the current working directory.
38
+
39
+ ### `--test-command <command>`
40
+ Defines the command to be executed for integrated continuous safety test validation after changes. By default, `npm test` is used.
41
+
42
+ ### `--workspace`
43
+ Enables evaluation of workspaces/monorepo clusters. When this option is enabled, `pkg-scaffold` analyzes and optimizes all packages within a monorepo.
44
+
45
+ ### `--verbose`
46
+ Enables expanded trace telemetry for debug operational diagnostics, providing more detailed output during execution.
47
+
48
+ ### `-y`, `--yes`
49
+ Skips all confirmation prompts and automatically executes planned structural modifications. **Use with caution in production environments without prior review.**
50
+
51
+ ### `-h`, `--help`
52
+ Displays help information for `pkg-scaffold`.
package/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  /**
4
4
  * ============================================================================
5
- * 📦 pkg-scaffold v2.3.0: Enterprise Dependency Intelligence & Scaffolding Engine
5
+ * 📦 pkg-scaffold v3.1.0: Ultimate Enterprise Codebase Janitor & Self-Healing Engine
6
6
  * ============================================================================
7
7
  * * Eine hochgradig integrierte Code-Analyse- und Projektbootstrapping-Engine.
8
8
  * Kombiniert rekursive Erreichbarkeitsanalysen (Reachability Graphs) auf
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pkg-scaffold",
3
- "version": "2.4.0",
4
- "description": "An advanced, AST-driven dependency resolution, refactoring, and self-healing engine.",
3
+ "version": "3.1.0",
4
+ "description": "The ultimate enterprise-grade codebase janitor. Faster than Knip v6 with OXC integration, type-aware analysis, and self-healing capabilities.",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "bin": {
@@ -9,8 +9,12 @@
9
9
  },
10
10
  "scripts": {
11
11
  "start": "node bin/cli.js",
12
+ "pkg-scaffold:run": "node bin/cli.js",
12
13
  "test": "echo \"Error: no test specified\" && exit 0",
13
- "test:stability": "npm run test"
14
+ "test:stability": "npm run test",
15
+ "docs:dev": "vitepress dev docs",
16
+ "docs:build": "vitepress build docs",
17
+ "docs:preview": "vitepress preview docs"
14
18
  },
15
19
  "keywords": [
16
20
  "scaffold",
@@ -44,11 +48,24 @@
44
48
  "commander": "^12.0.0",
45
49
  "enhanced-resolve": "^5.16.0",
46
50
  "execa": "^8.0.1",
51
+ "oxc-parser": "^0.135.0",
52
+ "oxc-resolver": "^11.20.0",
47
53
  "ramda": "^0.29.1",
48
- "typescript": "^5.4.5",
49
54
  "yocto-spinner": "^0.1.0"
50
55
  },
56
+ "devDepencies": {
57
+ "vitepress": "^1.0.0",
58
+ "vue": ">=3.5.0"
59
+ },
51
60
  "engines": {
52
61
  "node": ">=18.0.0"
62
+ },
63
+ "devDependencies": {
64
+ "@types/node": "^25.9.3",
65
+ "express": "^5.2.1",
66
+ "knip": "^6.16.1",
67
+ "lodash": "^4.18.1",
68
+ "typescript": "^6.0.3",
69
+ "vitepress": "^1.6.4"
53
70
  }
54
71
  }
@@ -0,0 +1,25 @@
1
+ {
2
+ // Interface mode: "CLI" for terminal usage, "GUI" for web interface
3
+ "interface": "CLI",
4
+
5
+ // Plugin activation toggles
6
+ "useBuiltinPlugins": true,
7
+ "useCustomPlugins": true,
8
+ "supportKnipPlugins": true,
9
+
10
+ // Engine performance and behavior options
11
+ "options": {
12
+ "verbose": false,
13
+ "fastMode": true, // Uses OXC parser for 4x speed boost
14
+ "selfHealing": true // Automatically fixes and validates code
15
+ },
16
+
17
+ // List of core plugins to load (if useBuiltinPlugins is true)
18
+ "enabledPlugins": [
19
+ "nextjs",
20
+ "nuxt",
21
+ "remix",
22
+ "sveltekit",
23
+ "astro"
24
+ ]
25
+ }
@@ -0,0 +1,19 @@
1
+ # pkg-scaffold Plugins
2
+
3
+ This directory is for your custom plugins. pkg-scaffold will automatically load any `.js` or `.mjs` files placed here if `useCustomPlugins` is set to `true` in your `config.json`.
4
+
5
+ ## Supported Ecosystems (Built-in)
6
+
7
+ - **Next.js**: Handles pages, API routes, and App Router conventions.
8
+ - **Nuxt**: Supports auto-imports and server routes.
9
+ - **Remix**: Maps loaders, actions, and root exports.
10
+ - **SvelteKit**: Tracks `+page`, `+layout`, and server-side scripts.
11
+ - **Astro**: Analyzes `.astro` files and static paths.
12
+
13
+ ## Knip Compatibility
14
+
15
+ pkg-scaffold supports Knip-style plugins. You can drop Knip plugins into this folder, and the engine will attempt to wrap them for use within the pkg-scaffold ecosystem.
16
+
17
+ ## Documentation
18
+
19
+ For a detailed guide on how to build your own plugins, please refer to the [Plugin Development Guide](../../docs/guide.md#plugin-development).
@@ -11,6 +11,7 @@ import fs from 'fs/promises';
11
11
 
12
12
  /**
13
13
  * High-Fidelity Graph Element Node representing a single file asset boundary.
14
+ * @scaffold-suppress GraphNode
14
15
  */
15
16
  export class GraphNode {
16
17
  constructor(filePath) {
@@ -42,6 +43,7 @@ export class GraphNode {
42
43
  this.securityThreats = [];
43
44
  this.calculatedDynamicImports = [];
44
45
  this.localSuppressedRules = new Set();
46
+ this.externalPackageUsage = new Set(); // Tracked third-party package names
45
47
 
46
48
  // Detailed AST Location Diagnostics (Symbol -> Structural Location Mapping)
47
49
  this.symbolSourceLocations = new Map(); // Symbol -> { line: number, column: number, length: number }
@@ -58,7 +60,22 @@ export class GraphNode {
58
60
  const parentNode = projectGraph.get(parentPath);
59
61
  if (!parentNode) continue;
60
62
 
61
- // Direct identity reference check
63
+ // Check if the symbol is explicitly imported by the parent
64
+ const importKey = `${path.relative(path.dirname(parentPath), this.filePath).replace(/\\/g, '/')}:${symbolName}`;
65
+ const importKeyAlt = `${path.relative(path.dirname(parentPath), this.filePath).replace(/\\/g, '/').replace(/\.(js|ts|tsx|jsx)$/, '')}:${symbolName}`;
66
+
67
+ if (parentNode.importedSymbols.has(importKey) || parentNode.importedSymbols.has(importKeyAlt)) {
68
+ return true;
69
+ }
70
+
71
+ // Check for star imports or namespace imports
72
+ const starKey = `${path.relative(path.dirname(parentPath), this.filePath).replace(/\\/g, '/')}:*`;
73
+ const starKeyAlt = `${path.relative(path.dirname(parentPath), this.filePath).replace(/\\/g, '/').replace(/\.(js|ts|tsx|jsx)$/, '')}:*`;
74
+ if (parentNode.importedSymbols.has(starKey) || parentNode.importedSymbols.has(starKeyAlt)) {
75
+ return true;
76
+ }
77
+
78
+ // Direct identity reference check (for cases where it's used but not explicitly imported in a traceable way, or global)
62
79
  if (parentNode.instantiatedIdentifiers.has(symbolName)) return true;
63
80
 
64
81
  // Property lookup reference checks (e.g., config.databaseUrl)
@@ -105,6 +122,7 @@ export class EngineContext {
105
122
  this.allowAutoFix = options.autoFix ?? true;
106
123
  this.isWorkspaceEnabled = options.workspace ?? false;
107
124
  this.verbose = options.verbose ?? false;
125
+ this.skipConfirm = options.skipConfirm ?? false;
108
126
 
109
127
  // Core Memory Repositories
110
128
  this.graph = new Map(); // Absolute File Path -> GraphNode
@@ -123,8 +141,11 @@ export class EngineContext {
123
141
  prunedFilesCount: 0,
124
142
  prunedExportsCount: 0,
125
143
  totalSymbolsAnalyzed: 0,
126
- securityVulnerabilitiesMitigated: 0
144
+ securityVulnerabilitiesMitigated: 0,
145
+ unusedDependenciesCount: 0
127
146
  };
147
+ this.usedExternalPackages = new Set(); // Global set of used npm packages
148
+ this.manifestDependencies = new Map(); // Package.json path -> { dependencies, devDependencies }
128
149
  }
129
150
 
130
151
  /**
@@ -219,7 +240,8 @@ export class EngineContext {
219
240
  structuralIssuesDetected: {
220
241
  deadFiles: [],
221
242
  deadExports: [],
222
- securityThreats: []
243
+ securityThreats: [],
244
+ unusedDependencies: []
223
245
  },
224
246
  modificationsExecuted: {
225
247
  filesUnlinked: this.metrics.prunedFilesCount,
@@ -235,7 +257,10 @@ export class EngineContext {
235
257
  const relativePath = path.relative(this.cwd, filePath);
236
258
 
237
259
  // Category A: Completely orphaned components (no references, not library/framework entries)
238
- if (node.incomingEdges.size === 0 && !node.isLibraryEntry && !node.isFrameworkContract) {
260
+ // A file with ANY @scaffold-suppress directive is considered intentionally retained and must
261
+ // never be flagged as orphaned, even if no other file imports it directly.
262
+ const fileHasSuppressDirective = node.localSuppressedRules.size > 0;
263
+ if (node.incomingEdges.size === 0 && !node.isLibraryEntry && !node.isFrameworkContract && !fileHasSuppressDirective) {
239
264
  summary.structuralIssuesDetected.deadFiles.push(relativePath);
240
265
  continue; // An orphaned file implies all internal sub-exports are dead; skip sub-checks
241
266
  }
@@ -277,6 +302,23 @@ export class EngineContext {
277
302
  }
278
303
  }
279
304
 
305
+ // Category D: Unused Dependencies Audit
306
+ for (const [manifestPath, manifestData] of this.manifestDependencies.entries()) {
307
+ const relativeManifest = path.relative(this.cwd, manifestPath);
308
+
309
+ // We only audit 'dependencies' for now as devDependencies are harder to track (test files, tools, etc.)
310
+ for (const dep of manifestData.dependencies) {
311
+ if (!this.usedExternalPackages.has(dep)) {
312
+ summary.structuralIssuesDetected.unusedDependencies.push({
313
+ manifest: relativeManifest,
314
+ package: dep,
315
+ type: 'dependency'
316
+ });
317
+ this.metrics.unusedDependenciesCount++;
318
+ }
319
+ }
320
+ }
321
+
280
322
  return summary;
281
323
  }
282
324
  }