@webpieces/nx-webpieces-rules 0.4.466 ā 0.4.468
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/package.json +6 -6
- package/src/executors/validate-architecture-unchanged/executor.js +6 -0
- package/src/executors/validate-architecture-unchanged/executor.js.map +1 -1
- package/src/executors/validate-eslint-sync/executor.js +5 -0
- package/src/executors/validate-eslint-sync/executor.js.map +1 -1
- package/src/executors/validate-no-architecture-cycles/executor.d.ts +1 -1
- package/src/executors/validate-no-architecture-cycles/executor.js +7 -1
- package/src/executors/validate-no-architecture-cycles/executor.js.map +1 -1
- package/src/executors/validate-packagejson/executor.js +49 -25
- package/src/executors/validate-packagejson/executor.js.map +1 -1
- package/src/executors/validate-versions-locked/executor.js +6 -1
- package/src/executors/validate-versions-locked/executor.js.map +1 -1
- package/src/lib/graph-loader.js +14 -0
- package/src/lib/graph-loader.js.map +1 -1
- package/src/lib/rule-gate.d.ts +33 -0
- package/src/lib/rule-gate.js +58 -0
- package/src/lib/rule-gate.js.map +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/nx-webpieces-rules",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.468",
|
|
4
4
|
"description": "Nx-specific webpieces validation rules and graph tooling. Bundles all @webpieces rule packages with Nx graph validators and an inference plugin.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -21,11 +21,11 @@
|
|
|
21
21
|
"README.md"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@webpieces/ai-hook-rules": "0.4.
|
|
25
|
-
"@webpieces/code-rules": "0.4.
|
|
26
|
-
"@webpieces/eslint-rules": "0.4.
|
|
27
|
-
"@webpieces/pr-gate": "0.4.
|
|
28
|
-
"@webpieces/rules-config": "0.4.
|
|
24
|
+
"@webpieces/ai-hook-rules": "0.4.468",
|
|
25
|
+
"@webpieces/code-rules": "0.4.468",
|
|
26
|
+
"@webpieces/eslint-rules": "0.4.468",
|
|
27
|
+
"@webpieces/pr-gate": "0.4.468",
|
|
28
|
+
"@webpieces/rules-config": "0.4.468",
|
|
29
29
|
"madge": "8.0.0"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
@@ -17,6 +17,7 @@ const graph_comparator_1 = require("../../lib/graph-comparator");
|
|
|
17
17
|
const graph_loader_1 = require("../../lib/graph-loader");
|
|
18
18
|
const graph_metadata_1 = require("../../lib/graph-metadata");
|
|
19
19
|
const api_scanner_1 = require("../../lib/api-usage/api-scanner");
|
|
20
|
+
const rule_gate_1 = require("../../lib/rule-gate");
|
|
20
21
|
const toError_1 = require("../../toError");
|
|
21
22
|
const TMP_MD_FILE = 'webpieces.dependencies.md';
|
|
22
23
|
/**
|
|
@@ -64,6 +65,11 @@ async function buildCurrentGraph(workspaceRoot) {
|
|
|
64
65
|
async function runExecutor(options, context) {
|
|
65
66
|
const graphPath = options.graphPath;
|
|
66
67
|
const workspaceRoot = context.root;
|
|
68
|
+
// Epoch-gateable: this rule diffs against the blessed architecture/dependencies.json, so
|
|
69
|
+
// "grandfather the current drift until <epoch>" is meaningful ā hence honorEpoch = true.
|
|
70
|
+
if (new rule_gate_1.RuleGate().isDisabled(workspaceRoot, 'validate-architecture-unchanged', true)) {
|
|
71
|
+
return { success: true };
|
|
72
|
+
}
|
|
67
73
|
console.log('\nš Validating Architecture Unchanged\n');
|
|
68
74
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
69
75
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-architecture-unchanged/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules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B,CAAC,CAAC;YAC7E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClB,OAAO,CAAC,KAAK,CAAC,mBAAmB,GAAG,MAAM,GAAG,qDAAqD,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Validate Architecture Unchanged Executor\n *\n * Validates that the current architecture graph matches the saved blessed graph.\n * This ensures no unapproved architecture changes have been made.\n *\n * Usage:\n * nx run architecture:validate-architecture-unchanged\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { writeTemplate } from '@webpieces/rules-config';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { compareGraphs } from '../../lib/graph-comparator';\nimport { loadBlessedGraph, graphFileExists } from '../../lib/graph-loader';\nimport { collectProjectInfo, enrichGraph, MetadataValidationError } from '../../lib/graph-metadata';\nimport { scanAndAttachApiRelations } from '../../lib/api-usage/api-scanner';\nimport { RuleGate } from '../../lib/rule-gate';\nimport type { EnhancedGraph } from '../../lib/graph-sorter';\nimport { toError } from '../../toError';\n\nexport interface ValidateArchitectureUnchangedOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\nconst TMP_MD_FILE = 'webpieces.dependencies.md';\n\n/**\n * Write the instructions documentation to .webpieces/instruct-ai/.\n * Sourced from @webpieces/rules-config.\n */\nfunction writeTmpInstructionsFile(workspaceRoot: string): string {\n const mdPath = writeTemplate(workspaceRoot, TMP_MD_FILE);\n\n return mdPath;\n}\n\n/**\n * Report a current-vs-saved graph mismatch and write the AI instructions file.\n */\nfunction reportMismatch(summary: string, workspaceRoot: string): void {\n const mdPath = writeTmpInstructionsFile(workspaceRoot);\n\n console.error('ā Architecture has changed since last update!');\n console.error('\\nDifferences:');\n console.error(summary);\n console.error('');\n console.error('ā ļø *** Refer to ' + mdPath + ' for instructions on how to fix *** ā ļø');\n console.error('');\n console.error('To fix:');\n console.error(' 1. Review the changes above');\n console.error(' 2. If intentional, ASK USER to run: nx run architecture:generate since this is a critical change');\n console.error(' 3. Commit the updated architecture/dependencies.json');\n}\n\n/**\n * Build the current dependency graph exactly as the generator does: reduce the nx\n * graph, sort into levels, enrich with metadata, and attach the derived\n * apiRelations ā so this validator compares like-for-like against the committed file.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches reportMismatch/writeTmpInstructionsFile in this file\nasync function buildCurrentGraph(workspaceRoot: string): Promise<EnhancedGraph> {\n console.log('š Generating current dependency graph...');\n const reducedGraph = await generateReducedGraph();\n console.log('š Computing topological layers...');\n const currentGraph = sortGraphTopologically(reducedGraph);\n console.log('š·ļø Enriching graph with framework + responsibilities metadata...');\n const projectInfos = await collectProjectInfo();\n enrichGraph(currentGraph, projectInfos, workspaceRoot);\n console.log('š Scanning source for implements/uses API relations...');\n scanAndAttachApiRelations(workspaceRoot, currentGraph, projectInfos);\n return currentGraph;\n}\n\nexport default async function runExecutor(\n options: ValidateArchitectureUnchangedOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n // Epoch-gateable: this rule diffs against the blessed architecture/dependencies.json, so\n // \"grandfather the current drift until <epoch>\" is meaningful ā hence honorEpoch = true.\n if (new RuleGate().isDisabled(workspaceRoot, 'validate-architecture-unchanged', true)) {\n return { success: true };\n }\n\n console.log('\\nš Validating Architecture Unchanged\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Check if saved graph exists\n if (!graphFileExists(workspaceRoot, graphPath)) {\n console.error('ā No saved graph found at architecture/dependencies.json');\n console.error('');\n console.error('To initialize:');\n console.error(' 1. Run: nx run architecture:generate');\n console.error(' 2. Run: nx run architecture:visualize');\n console.error(' 3. Manually inspect the generated graph to confirm it is the desired architecture');\n console.error(' 4. Commit architecture/dependencies.json');\n return { success: false };\n }\n\n // Steps 1-3: build + enrich + scan the current graph (same pipeline the\n // generator runs, so any drift is caught).\n const currentGraph = await buildCurrentGraph(workspaceRoot);\n\n // Step 4: Load saved graph\n console.log('š Loading saved graph...');\n const savedGraph = loadBlessedGraph(workspaceRoot, graphPath);\n\n if (!savedGraph) {\n console.error('ā Could not load saved graph');\n return { success: false };\n }\n\n // Step 5: Compare graphs\n console.log('š Comparing current graph to saved graph...');\n const comparison = compareGraphs(currentGraph, savedGraph.projects);\n\n if (comparison.identical) {\n console.log('ā
Architecture unchanged - current graph matches saved graph');\n return { success: true };\n }\n reportMismatch(comparison.summary, workspaceRoot);\n return { success: false };\n } catch (err: unknown) {\n const error = toError(err);\n console.error('ā Architecture validation failed:', error.message);\n if (error instanceof MetadataValidationError) {\n const mdPath = writeTemplate(workspaceRoot, 'webpieces.responsibilities.md');\n console.error('');\n console.error('ā ļø *** Refer to ' + mdPath + ' for how to author responsibilities.md files *** ā ļø');\n }\n return { success: false };\n }\n}\n"]}
|
|
@@ -4,6 +4,7 @@ exports.default = validateEslintSyncExecutor;
|
|
|
4
4
|
const fs_1 = require("fs");
|
|
5
5
|
const path_1 = require("path");
|
|
6
6
|
const crypto_1 = require("crypto");
|
|
7
|
+
const rule_gate_1 = require("../../lib/rule-gate");
|
|
7
8
|
function calculateHash(content) {
|
|
8
9
|
return (0, crypto_1.createHash)('sha256').update(content).digest('hex');
|
|
9
10
|
}
|
|
@@ -13,6 +14,10 @@ function normalizeContent(content) {
|
|
|
13
14
|
}
|
|
14
15
|
async function validateEslintSyncExecutor(options, context) {
|
|
15
16
|
const workspaceRoot = context.root;
|
|
17
|
+
// All-or-nothing (honorEpoch = false): the two files either match or they do not.
|
|
18
|
+
if (new rule_gate_1.RuleGate().isDisabled(workspaceRoot, 'validate-eslint-sync', false)) {
|
|
19
|
+
return { success: true };
|
|
20
|
+
}
|
|
16
21
|
const templatePath = (0, path_1.join)(workspaceRoot, 'packages/tooling/nx-webpieces-rules/templates/eslint.webpieces.config.mjs');
|
|
17
22
|
const workspacePath = (0, path_1.join)(workspaceRoot, 'eslint.webpieces.config.mjs');
|
|
18
23
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-eslint-sync/executor.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-eslint-sync/executor.ts"],"names":[],"mappings":";;AAqBA,6CAuCC;AA3DD,2BAAkC;AAClC,+BAA4B;AAC5B,mCAAoC;AACpC,mDAA+C;AAQ/C,SAAS,aAAa,CAAC,OAAe;IAClC,OAAO,IAAA,mBAAU,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,gBAAgB,CAAC,OAAe;IACrC,6CAA6C;IAC7C,OAAO,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AACjD,CAAC;AAEc,KAAK,UAAU,0BAA0B,CACpD,OAAkC,EAClC,OAAwB;IAExB,MAAM,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAEnC,kFAAkF;IAClF,IAAI,IAAI,oBAAQ,EAAE,CAAC,UAAU,CAAC,aAAa,EAAE,sBAAsB,EAAE,KAAK,CAAC,EAAE,CAAC;QAC1E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,MAAM,YAAY,GAAG,IAAA,WAAI,EAAC,aAAa,EAAE,2EAA2E,CAAC,CAAC;IACtH,MAAM,aAAa,GAAG,IAAA,WAAI,EAAC,aAAa,EAAE,6BAA6B,CAAC,CAAC;IAEzE,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,eAAe,GAAG,IAAA,iBAA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AAK,CAAC,EAAE,CAAC,CAAC;IAClB,OAAO,CAAC,KAAK,CAAC,yDAAyD,CAAC,CAAC;IACzE,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;IAC3E,OAAO,CAAC,KAAK,CAAC,yDAAyD,CAAC,CAAC;IACzE,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAClB,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IACzB,OAAO,CAAC,KAAK,CAAC,sFAAsF,CAAC,CAAC;IACtG,OAAO,CAAC,KAAK,CAAC,+CAA+C,CAAC,CAAC;IAC/D,OAAO,CAAC,KAAK,CAAC,8FAA8F,CAAC,CAAC;IAC9G,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAClB,OAAO,CAAC,KAAK,CAAC,kEAAkE,CAAC,CAAC;IAClF,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AACtB,CAAC;AAED,SAAS,mBAAmB,CAAC,OAAe;IACxC,mEAAmE;IACnE,wCAAwC;IACxC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC;IAC7D,IAAI,CAAC,KAAK,EAAE,CAAC;QACT,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC;IAClF,CAAC;IAED,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["import type { ExecutorContext } from '@nx/devkit';\nimport { readFileSync } from 'fs';\nimport { join } from 'path';\nimport { createHash } from 'crypto';\nimport { RuleGate } from '../../lib/rule-gate';\n\nexport interface ValidateEslintSyncOptions {}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\nfunction calculateHash(content: string): string {\n return createHash('sha256').update(content).digest('hex');\n}\n\nfunction normalizeContent(content: string): string {\n // Normalize line endings and trim whitespace\n return content.replace(/\\r\\n/g, '\\n').trim();\n}\n\nexport default async function validateEslintSyncExecutor(\n options: ValidateEslintSyncOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const workspaceRoot = context.root;\n\n // All-or-nothing (honorEpoch = false): the two files either match or they do not.\n if (new RuleGate().isDisabled(workspaceRoot, 'validate-eslint-sync', false)) {\n return { success: true };\n }\n\n const templatePath = join(workspaceRoot, 'packages/tooling/nx-webpieces-rules/templates/eslint.webpieces.config.mjs');\n const workspacePath = join(workspaceRoot, 'eslint.webpieces.config.mjs');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const templateContent = readFileSync(templatePath, 'utf-8');\n const workspaceContent = readFileSync(workspacePath, 'utf-8');\n\n const templateRules = extractRulesSection(templateContent);\n const workspaceRules = extractRulesSection(workspaceContent);\n\n const templateHash = calculateHash(normalizeContent(templateRules));\n const workspaceHash = calculateHash(normalizeContent(workspaceRules));\n\n if (templateHash !== workspaceHash) {\n printValidationError(templatePath, workspacePath);\n return { success: false };\n }\n\n console.log('ā
ESLint configuration sync validated - rules match!');\n return { success: true };\n\n } catch (err: unknown) {\n // Error occurred during validation - log and fail\n // eslint-disable-next-line @webpieces/catch-error-pattern\n console.error('ā Error validating ESLint sync:', err);\n return { success: false };\n }\n}\n\nfunction printValidationError(templatePath: string, workspacePath: string): void {\n console.error('');\n console.error('ā ESLint configuration sync validation FAILED');\n console.error('');\n console.error('The @webpieces ESLint rules must be identical in both files:');\n console.error(` 1. ${templatePath}`);\n console.error(` 2. ${workspacePath}`);\n console.error('');\n console.error('These files must have identical rules sections so that:');\n console.error(' - External clients get the same rules we use internally');\n console.error(' - We \"eat our own dog food\" - same rules for everyone');\n console.error('');\n console.error('To fix:');\n console.error(' 1. Modify the rules in ONE file (recommend: templates/eslint.webpieces.config.mjs)');\n console.error(' 2. Copy the rules section to the other file');\n console.error(' 3. Keep import statements different (template uses npm, workspace uses loadWorkspaceRules)');\n console.error('');\n console.error('Customization for webpieces workspace goes in: eslint.config.mjs');\n console.error('');\n}\n\nfunction extractRulesSection(content: string): string {\n // Extract everything between \"export default [\" and the final \"];\"\n // This includes the rules configuration\n const match = content.match(/export default \\[([\\s\\S]*)\\];/);\n if (!match) {\n throw new Error('Could not extract rules section - export default not found');\n }\n\n return match[1].trim();\n}\n"]}
|
|
@@ -13,4 +13,4 @@ export interface ValidateNoCyclesOptions {
|
|
|
13
13
|
export interface ExecutorResult {
|
|
14
14
|
success: boolean;
|
|
15
15
|
}
|
|
16
|
-
export default function runExecutor(_options: ValidateNoCyclesOptions,
|
|
16
|
+
export default function runExecutor(_options: ValidateNoCyclesOptions, context: ExecutorContext): Promise<ExecutorResult>;
|
|
@@ -12,8 +12,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
12
12
|
exports.default = runExecutor;
|
|
13
13
|
const graph_generator_1 = require("../../lib/graph-generator");
|
|
14
14
|
const graph_sorter_1 = require("../../lib/graph-sorter");
|
|
15
|
+
const rule_gate_1 = require("../../lib/rule-gate");
|
|
15
16
|
const toError_1 = require("../../toError");
|
|
16
|
-
async function runExecutor(_options,
|
|
17
|
+
async function runExecutor(_options, context) {
|
|
18
|
+
// Epoch-gateable: the existing cycle set can be grandfathered while a refactor lands, so this
|
|
19
|
+
// rule honors ignoreModifiedUntilEpoch / ignoreRuleWhileOnBranch in addition to mode: OFF.
|
|
20
|
+
if (new rule_gate_1.RuleGate().isDisabled(context.root, 'validate-no-architecture-cycles', true)) {
|
|
21
|
+
return { success: true };
|
|
22
|
+
}
|
|
17
23
|
console.log('\nš Validating No Circular Dependencies\n');
|
|
18
24
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
19
25
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-no-architecture-cycles/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/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O,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;YAC3B,OAAO,CAAC,KAAK,CAAC,6BAA6B,CAAC,CAAC;YAC7C,OAAO,CAAC,KAAK,CAAC,kDAAkD,CAAC,CAAC;YAClE,OAAO,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;YAC3C,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QAC9B,CAAC;IACL,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC3D,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Validate No Architecture Cycles Executor\n *\n * Validates that the architecture dependency graph has no circular dependencies.\n * This is a fast check that only validates acyclicity at the project level.\n *\n * Usage:\n * nx run architecture:validate-no-architecture-cycles\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { generateGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { RuleGate } from '../../lib/rule-gate';\nimport { toError } from '../../toError';\n\nexport interface ValidateNoCyclesOptions {\n // No options needed\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\nexport default async function runExecutor(\n _options: ValidateNoCyclesOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n // Epoch-gateable: the existing cycle set can be grandfathered while a refactor lands, so this\n // rule honors ignoreModifiedUntilEpoch / ignoreRuleWhileOnBranch in addition to mode: OFF.\n if (new RuleGate().isDisabled(context.root, 'validate-no-architecture-cycles', true)) {\n return { success: true };\n }\n\n console.log('\\nš Validating No Circular Dependencies\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Step 1: Generate current graph from project.json files\n console.log('š Generating dependency graph from project.json files...');\n const rawGraph = await generateGraph();\n\n // Step 2: Topological sort (validates acyclic)\n console.log('š Checking for cycles (topological sort)...');\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n sortGraphTopologically(rawGraph);\n console.log('ā
No circular dependencies detected!');\n\n // Print summary\n const projectCount = Object.keys(rawGraph).length;\n console.log(`\\nš Summary: ${projectCount} projects, all acyclic`);\n\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error('ā Circular dependency detected!');\n console.error(error.message);\n console.error('\\nTo fix:');\n console.error(' 1. Review the cycle above');\n console.error(' 2. Break the cycle by refactoring dependencies');\n console.error(' 3. Run this check again');\n return { success: false };\n }\n } catch (err: unknown) {\n const error = toError(err);\n console.error('ā Cycle validation failed:', error.message);\n return { success: false };\n }\n}\n"]}
|
|
@@ -13,9 +13,54 @@ exports.default = runExecutor;
|
|
|
13
13
|
const graph_generator_1 = require("../../lib/graph-generator");
|
|
14
14
|
const graph_sorter_1 = require("../../lib/graph-sorter");
|
|
15
15
|
const package_validator_1 = require("../../lib/package-validator");
|
|
16
|
+
const rule_gate_1 = require("../../lib/rule-gate");
|
|
16
17
|
const toError_1 = require("../../toError");
|
|
18
|
+
/**
|
|
19
|
+
* Console reporting for the validation result.
|
|
20
|
+
*
|
|
21
|
+
* Extracted from `runExecutor` purely to keep that method under the max-method-lines
|
|
22
|
+
* limit: it crossed 70 lines when the config gate (this branch) and the test-vs-prod
|
|
23
|
+
* dependency classification (main, #481) both landed in it.
|
|
24
|
+
*/
|
|
25
|
+
class ValidationReporter {
|
|
26
|
+
reportWarnings(warnings) {
|
|
27
|
+
// Warnings never fail the build (e.g. runtime-only / peer deps).
|
|
28
|
+
if (warnings.length === 0) {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
console.warn('\nā ļø Package.json notices (non-fatal):');
|
|
32
|
+
for (const warning of warnings) {
|
|
33
|
+
console.warn(` ${warning}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
reportErrors(errors) {
|
|
37
|
+
console.error('\nā Package.json validation failed!');
|
|
38
|
+
console.error('\nErrors:');
|
|
39
|
+
for (const error of errors) {
|
|
40
|
+
console.error(` ${error}`);
|
|
41
|
+
}
|
|
42
|
+
console.error('\nTo fix:');
|
|
43
|
+
console.error(' 1. Review each error above ā it names the SECTION the dependency belongs in');
|
|
44
|
+
console.error(' 2. Imported by production source ā package.json "dependencies"');
|
|
45
|
+
console.error(' 3. Imported only by *.spec.ts / __tests__ / test configs ā "devDependencies"');
|
|
46
|
+
console.error(' (devDependencies are excluded from `pnpm deploy --prod`, so test-only');
|
|
47
|
+
console.error(' packages never reach the production image)');
|
|
48
|
+
}
|
|
49
|
+
reportSummary(projectResults) {
|
|
50
|
+
const validProjects = projectResults.filter(r => r.valid).length;
|
|
51
|
+
const totalProjects = projectResults.length;
|
|
52
|
+
console.log(`\nš Validation Summary:`);
|
|
53
|
+
console.log(` Projects validated: ${totalProjects}`);
|
|
54
|
+
console.log(` Valid: ${validProjects}`);
|
|
55
|
+
console.log(` Invalid: ${totalProjects - validProjects}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
17
58
|
async function runExecutor(options, context) {
|
|
18
59
|
const workspaceRoot = context.root;
|
|
60
|
+
// All-or-nothing (honorEpoch = false): there is no blessed baseline to grandfather against.
|
|
61
|
+
if (new rule_gate_1.RuleGate().isDisabled(workspaceRoot, 'validate-packagejson', false)) {
|
|
62
|
+
return { success: true };
|
|
63
|
+
}
|
|
19
64
|
console.log('\nš¦ Validating Package.json Dependencies\n');
|
|
20
65
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
21
66
|
try {
|
|
@@ -29,35 +74,14 @@ async function runExecutor(options, context) {
|
|
|
29
74
|
console.log('š¦ Validating package.json dependencies match the architecture graph...');
|
|
30
75
|
const validatorOptions = new package_validator_1.PackageValidatorOptions(options.testOnlyDepMode ?? 'error');
|
|
31
76
|
const packageValidation = await (0, package_validator_1.validatePackageJsonDependencies)(enhancedGraph, workspaceRoot, validatorOptions);
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
console.warn('\nā ļø Package.json notices (non-fatal):');
|
|
35
|
-
for (const warning of packageValidation.warnings) {
|
|
36
|
-
console.warn(` ${warning}`);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
77
|
+
const reporter = new ValidationReporter();
|
|
78
|
+
reporter.reportWarnings(packageValidation.warnings);
|
|
39
79
|
if (!packageValidation.valid) {
|
|
40
|
-
|
|
41
|
-
console.error('\nErrors:');
|
|
42
|
-
for (const error of packageValidation.errors) {
|
|
43
|
-
console.error(` ${error}`);
|
|
44
|
-
}
|
|
45
|
-
console.error('\nTo fix:');
|
|
46
|
-
console.error(' 1. Review each error above ā it names the SECTION the dependency belongs in');
|
|
47
|
-
console.error(' 2. Imported by production source ā package.json "dependencies"');
|
|
48
|
-
console.error(' 3. Imported only by *.spec.ts / __tests__ / test configs ā "devDependencies"');
|
|
49
|
-
console.error(' (devDependencies are excluded from `pnpm deploy --prod`, so test-only');
|
|
50
|
-
console.error(' packages never reach the production image)');
|
|
80
|
+
reporter.reportErrors(packageValidation.errors);
|
|
51
81
|
return { success: false };
|
|
52
82
|
}
|
|
53
83
|
console.log('ā
Package.json dependencies cover the architecture graph');
|
|
54
|
-
|
|
55
|
-
const validProjects = packageValidation.projectResults.filter(r => r.valid).length;
|
|
56
|
-
const totalProjects = packageValidation.projectResults.length;
|
|
57
|
-
console.log(`\nš Validation Summary:`);
|
|
58
|
-
console.log(` Projects validated: ${totalProjects}`);
|
|
59
|
-
console.log(` Valid: ${validProjects}`);
|
|
60
|
-
console.log(` Invalid: ${totalProjects - validProjects}`);
|
|
84
|
+
reporter.reportSummary(packageValidation.projectResults);
|
|
61
85
|
return { success: true };
|
|
62
86
|
}
|
|
63
87
|
catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-packagejson/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-packagejson/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAsEH,8BAiDC;AApHD,+DAAiE;AACjE,yDAAgE;AAChE,mEAKqC;AACrC,mDAA+C;AAC/C,2CAAwC;AAexC;;;;;;GAMG;AACH,MAAM,kBAAkB;IACpB,cAAc,CAAC,QAAkB;QAC7B,iEAAiE;QACjE,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxB,OAAO;QACX,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,yCAAyC,CAAC,CAAC;QACxD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC7B,OAAO,CAAC,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC,CAAC;QACjC,CAAC;IACL,CAAC;IAED,YAAY,CAAC,MAAgB;QACzB,OAAO,CAAC,KAAK,CAAC,qCAAqC,CAAC,CAAC;QACrD,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAC3B,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YACzB,OAAO,CAAC,KAAK,CAAC,KAAK,KAAK,EAAE,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,+EAA+E,CAAC,CAAC;QAC/F,OAAO,CAAC,KAAK,CAAC,kEAAkE,CAAC,CAAC;QAClF,OAAO,CAAC,KAAK,CAAC,gFAAgF,CAAC,CAAC;QAChG,OAAO,CAAC,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAC5F,OAAO,CAAC,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACtE,CAAC;IAED,aAAa,CAAC,cAAyC;QACnD,MAAM,aAAa,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC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C;QAEF,MAAM,QAAQ,GAAG,IAAI,kBAAkB,EAAE,CAAC;QAC1C,QAAQ,CAAC,cAAc,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAC;QAEpD,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC;YAC3B,QAAQ,CAAC,YAAY,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;YAChD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QAC9B,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,0DAA0D,CAAC,CAAC;QACxE,QAAQ,CAAC,aAAa,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;QAEzD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAClE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Validate Package.json Executor\n *\n * Validates that package.json dependencies match project.json build dependencies.\n * This ensures the two sources of truth don't drift apart.\n *\n * Usage:\n * nx run architecture:validate-packagejson\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport {\n PackageValidatorOptions,\n ProjectValidationResult,\n TestOnlyDepMode,\n validatePackageJsonDependencies,\n} from '../../lib/package-validator';\nimport { RuleGate } from '../../lib/rule-gate';\nimport { toError } from '../../toError';\n\nexport interface ValidatePackageJsonOptions {\n /**\n * Strictness for \"a test-only package is listed in dependencies\" (i.e. it lands in\n * the `pnpm deploy --prod` closure and ships to production).\n * 'error' (default) | 'warn' (migration) | 'off'.\n */\n testOnlyDepMode?: TestOnlyDepMode;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n/**\n * Console reporting for the validation result.\n *\n * Extracted from `runExecutor` purely to keep that method under the max-method-lines\n * limit: it crossed 70 lines when the config gate (this branch) and the test-vs-prod\n * dependency classification (main, #481) both landed in it.\n */\nclass ValidationReporter {\n reportWarnings(warnings: string[]): void {\n // Warnings never fail the build (e.g. runtime-only / peer deps).\n if (warnings.length === 0) {\n return;\n }\n console.warn('\\nā ļø Package.json notices (non-fatal):');\n for (const warning of warnings) {\n console.warn(` ${warning}`);\n }\n }\n\n reportErrors(errors: string[]): void {\n console.error('\\nā Package.json validation failed!');\n console.error('\\nErrors:');\n for (const error of errors) {\n console.error(` ${error}`);\n }\n console.error('\\nTo fix:');\n console.error(' 1. Review each error above ā it names the SECTION the dependency belongs in');\n console.error(' 2. Imported by production source ā package.json \"dependencies\"');\n console.error(' 3. Imported only by *.spec.ts / __tests__ / test configs ā \"devDependencies\"');\n console.error(' (devDependencies are excluded from `pnpm deploy --prod`, so test-only');\n console.error(' packages never reach the production image)');\n }\n\n reportSummary(projectResults: ProjectValidationResult[]): void {\n const validProjects = projectResults.filter(r => r.valid).length;\n const totalProjects = projectResults.length;\n console.log(`\\nš Validation Summary:`);\n console.log(` Projects validated: ${totalProjects}`);\n console.log(` Valid: ${validProjects}`);\n console.log(` Invalid: ${totalProjects - validProjects}`);\n }\n}\n\nexport default async function runExecutor(\n options: ValidatePackageJsonOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const workspaceRoot = context.root;\n\n // All-or-nothing (honorEpoch = false): there is no blessed baseline to grandfather against.\n if (new RuleGate().isDisabled(workspaceRoot, 'validate-packagejson', false)) {\n return { success: true };\n }\n\n console.log('\\nš¦ Validating Package.json Dependencies\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Step 1: Build the full graph from nx, then transitively reduce it (the view)\n console.log(\"š Generating dependency graph from nx's project graph...\");\n const reducedGraph = await generateReducedGraph();\n\n // Step 2: Topological sort (to get enhanced graph with levels)\n console.log('š Computing topological layers...');\n const enhancedGraph = sortGraphTopologically(reducedGraph);\n\n // Step 3: Validate package.json dependencies match\n console.log('š¦ Validating package.json dependencies match the architecture graph...');\n const validatorOptions = new PackageValidatorOptions(options.testOnlyDepMode ?? 'error');\n const packageValidation = await validatePackageJsonDependencies(\n enhancedGraph,\n workspaceRoot,\n validatorOptions\n );\n\n const reporter = new ValidationReporter();\n reporter.reportWarnings(packageValidation.warnings);\n\n if (!packageValidation.valid) {\n reporter.reportErrors(packageValidation.errors);\n return { success: false };\n }\n\n console.log('ā
Package.json dependencies cover the architecture graph');\n reporter.reportSummary(packageValidation.projectResults);\n\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error('ā Package.json validation failed:', error.message);\n return { success: false };\n }\n}\n"]}
|
|
@@ -20,6 +20,7 @@ exports.default = runExecutor;
|
|
|
20
20
|
const tslib_1 = require("tslib");
|
|
21
21
|
const fs = tslib_1.__importStar(require("fs"));
|
|
22
22
|
const path = tslib_1.__importStar(require("path"));
|
|
23
|
+
const rule_gate_1 = require("../../lib/rule-gate");
|
|
23
24
|
const toError_1 = require("../../toError");
|
|
24
25
|
// webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file
|
|
25
26
|
// Find all package.json files except node_modules, dist, .nx, .angular
|
|
@@ -286,8 +287,12 @@ function checkSemverRanges(workspaceRoot) {
|
|
|
286
287
|
return { errors: semverErrors };
|
|
287
288
|
}
|
|
288
289
|
async function runExecutor(_options, context) {
|
|
289
|
-
console.log('\nš Validating Package Versions are LOCKED and CONSISTENT\n');
|
|
290
290
|
const workspaceRoot = context.root;
|
|
291
|
+
// All-or-nothing (honorEpoch = false): there is no blessed baseline to grandfather against.
|
|
292
|
+
if (new rule_gate_1.RuleGate().isDisabled(workspaceRoot, 'validate-versions-locked', false)) {
|
|
293
|
+
return { success: true };
|
|
294
|
+
}
|
|
295
|
+
console.log('\nš Validating Package Versions are LOCKED and CONSISTENT\n');
|
|
291
296
|
// Step 1: Check for semver ranges (FAILS if any found)
|
|
292
297
|
const semverResult = checkSemverRanges(workspaceRoot);
|
|
293
298
|
const semverErrors = semverResult.errors;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-versions-locked/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAiBH,oDA2CC;AA8QD,8BAsCC;;AA7WD,+CAAyB;AACzB,mDAA6B;AAC7B,2CAAwC;AAUxC,iGAAiG;AACjG,uEAAuE;AACvE,SAAgB,oBAAoB,CAAC,GAAW,EAAE,QAAQ,GAAG,EAAE;IAC3D,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IAElC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACtC,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAE/C,yBAAyB;QACzB,IACI,CAAC,cAAc,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,QAAQ,CAC/D,IAAI,CACP,EACH,CAAC;YACC,SAAS;QACb,CAAC;QAED,2FAA2F;QAC3F,IAAI,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE,CAAC;YACnC,SAAS;QACb,CAAC;QAED,gDAAgD;QAChD,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACvB,SAAS;QACb,CAAC;QAED,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACnC,IAAI,IAAI,CAAC,WAAW,EAAE,EAAE,CAA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AAC,CAAC;IACxD,OAAO,CAAC,GAAG,CAAC,yCAAyC,YAAY,EAAE,CAAC,CAAC;IACrE,OAAO,CAAC,GAAG,CAAC,yBAAyB,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC;IAEhE,iDAAiD;IACjD,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;QACnB,kCAAkC,CAAC,YAAY,CAAC,CAAC;QACjD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED,4BAA4B;IAC5B,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9B,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;QACtC,OAAO,CAAC,GAAG,CAAC,kGAAkG,CAAC,CAAC;QAChH,OAAO,CAAC,GAAG,CAAC,wGAAwG,CAAC,CAAC;QACtH,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,gEAAgE,CAAC,CAAC;IAC9E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["/**\n * Validate Versions Locked Executor\n *\n * Validates that package.json versions are:\n * 1. LOCKED (exact versions, no semver ranges like ^, ~, *)\n * 2. CONSISTENT across all package.json files (no version conflicts)\n *\n * Why locked versions matter:\n * - Micro bugs ARE introduced via patch versions (1.4.5 ā 1.4.6)\n * - git bisect fails when software changes OUTSIDE of git\n * - Library upgrades must be explicit via PR/commit, not implicit drift\n *\n * Usage:\n * nx run architecture:validate-versions-locked\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { toError } from '../../toError';\n\nexport interface ValidateVersionsLockedOptions {\n // No options needed\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n// webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file\n// Find all package.json files except node_modules, dist, .nx, .angular\nexport function findPackageJsonFiles(dir: string, basePath = ''): string[] {\n const files: string[] = [];\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const fullPath = path.join(dir, item);\n const relativePath = path.join(basePath, item);\n\n // Skip these directories\n if (\n ['node_modules', 'dist', '.nx', '.angular', 'tmp', '.git'].includes(\n item,\n )\n ) {\n continue;\n }\n\n // Skip platform-specific node_modules backups (node_modules_mac, node_modules_linux, etc.)\n if (item.startsWith('node_modules_')) {\n continue;\n }\n\n // Skip all hidden directories (starting with .)\n if (item.startsWith('.')) {\n continue;\n }\n\n const stat = fs.statSync(fullPath);\n if (stat.isDirectory()) {\n // Don't descend into a nested git repository (e.g. a clone under repositories/): it is a\n // separate project with its own version policy, NOT part of this monorepo's version lock.\n // The presence of a `.git` entry (dir for a real clone, file for a worktree/submodule)\n // marks a repo boundary ā the same signal the AI guards use to scope to the current repo.\n if (fs.existsSync(path.join(fullPath, '.git'))) {\n continue;\n }\n files.push(...findPackageJsonFiles(fullPath, relativePath));\n } else if (item === 'package.json') {\n files.push(fullPath);\n }\n }\n\n return files;\n}\n\n// Check if a version string uses semver ranges\nfunction hasSemverRange(version: string): boolean {\n // Allow workspace protocol\n if (version.startsWith('workspace:')) {\n return false;\n }\n\n // Allow file: protocol (for local packages)\n if (version.startsWith('file:')) {\n return false;\n }\n\n // Check for common semver range patterns\n const semverPatterns = [\n /^\\^/, // ^1.2.3\n /^~/, // ~1.2.3\n /^\\+/, // +1.2.3\n /^\\*/, // *\n /^>/, // >1.2.3\n /^</, // <1.2.3\n /^>=/, // >=1.2.3\n /^<=/, // <=1.2.3\n /\\|\\|/, // 1.2.3 || 2.x\n / - /, // 1.2.3 - 2.3.4\n /^\\d+\\.x/, // 1.x, 1.2.x\n /^latest$/, // latest\n /^next$/, // next\n ];\n\n return semverPatterns.some((pattern) => pattern.test(version));\n}\n\n// webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file\n// Validate a single package.json file for semver ranges\nfunction validatePackageJson(filePath: string): string[] {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n const pkg = JSON.parse(content);\n const errors: string[] = [];\n\n // Check dependencies\n if (pkg.dependencies) {\n for (const [name, version] of Object.entries(pkg.dependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) {\n continue;\n }\n\n if (hasSemverRange(version as string)) {\n errors.push(\n `dependencies.${name}: \"${version}\" uses semver range (must be locked to exact version)`,\n );\n }\n }\n }\n\n // Check devDependencies\n if (pkg.devDependencies) {\n for (const [name, version] of Object.entries(pkg.devDependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) {\n continue;\n }\n\n if (hasSemverRange(version as string)) {\n errors.push(\n `devDependencies.${name}: \"${version}\" uses semver range (must be locked to exact version)`,\n );\n }\n }\n }\n\n // Check peerDependencies (these can have ranges for compatibility)\n // We don't validate peerDependencies for semver ranges since they're meant to be flexible\n\n return errors;\n } catch (err: unknown) {\n const error = toError(err);\n return [`Failed to parse ${filePath}: ${error.message}`];\n }\n}\n\n// Track all dependency versions across the monorepo\ninterface DependencyUsage {\n version: string;\n file: string;\n type: 'dependencies' | 'devDependencies';\n}\n\n// webpieces-disable max-lines-new-methods -- Collecting dependencies from all package.json files\n// Collect all dependency versions from all package.json files\nfunction collectAllDependencies(workspaceRoot: string): Map<string, DependencyUsage[]> {\n const dependencyMap = new Map<string, DependencyUsage[]>();\n const packageFiles = findPackageJsonFiles(workspaceRoot);\n\n for (const filePath of packageFiles) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n const pkg = JSON.parse(content);\n const relativePath = path.relative(workspaceRoot, filePath);\n\n // Collect dependencies\n if (pkg.dependencies) {\n for (const [name, version] of Object.entries(pkg.dependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) continue;\n\n const usage: DependencyUsage = {\n version: version as string,\n file: relativePath,\n type: 'dependencies'\n };\n\n if (!dependencyMap.has(name)) {\n dependencyMap.set(name, []);\n }\n dependencyMap.get(name)!.push(usage);\n }\n }\n\n // Collect devDependencies\n if (pkg.devDependencies) {\n for (const [name, version] of Object.entries(pkg.devDependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) continue;\n\n const usage: DependencyUsage = {\n version: version as string,\n file: relativePath,\n type: 'devDependencies'\n };\n\n if (!dependencyMap.has(name)) {\n dependencyMap.set(name, []);\n }\n dependencyMap.get(name)!.push(usage);\n }\n }\n } catch (err: unknown) {\n // const error = toError(err);\n // Intentionally skip files that can't be parsed - this is expected for some package.json files\n }\n }\n\n return dependencyMap;\n}\n\n// webpieces-disable max-lines-new-methods -- Simple iteration logic, splitting would reduce clarity\n// Check for version conflicts across package.json files\nfunction checkVersionConflicts(workspaceRoot: string): string[] {\n console.log('\\nš Checking for version conflicts across package.json files:');\n\n const dependencyMap = collectAllDependencies(workspaceRoot);\n const conflicts: string[] = [];\n\n for (const [packageName, usages] of dependencyMap.entries()) {\n // Get unique versions (ignoring workspace: and file: protocols)\n const versions = new Set(\n usages\n .map(u => u.version)\n .filter(v => !v.startsWith('workspace:') && !v.startsWith('file:'))\n );\n\n if (versions.size > 1) {\n const conflictDetails = usages\n .filter(u => !u.version.startsWith('workspace:') && !u.version.startsWith('file:'))\n .map(u => ` ${u.file} (${u.type}): ${u.version}`)\n .join('\\n');\n\n conflicts.push(` ā ${packageName} has ${versions.size} different versions:\\n${conflictDetails}`);\n }\n }\n\n if (conflicts.length === 0) {\n console.log(' ā
No version conflicts found');\n } else {\n for (const conflict of conflicts) {\n console.log(conflict);\n }\n }\n\n return conflicts;\n}\n\n/**\n * Prints the educational message explaining why semver ranges are forbidden.\n * This helps developers understand the rationale behind locked versions.\n */\n// webpieces-disable max-lines-new-methods -- Educational message template, splitting reduces clarity\nfunction printSemverRangeEducationalMessage(semverErrors: number): void {\n console.log(`\nā SEMVER RANGES DETECTED - BUILD FAILED\n\nFound ${semverErrors} package(s) using semver ranges (^, ~, *, etc.) instead of locked versions.\n\nWHY THIS IS A HARD FAILURE:\nāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n\n1. MICRO BUGS ARE REAL\n Thinking that patch versions (1.4.5 ā 1.4.6) don't introduce bugs is wrong.\n They do. Sometimes what looks like an \"easy fix\" breaks things in subtle ways.\n\n2. GIT BISECT BECOMES USELESS\n When you run \"git bisect\" to find when a bug was introduced, it fails if\n software changed OUTSIDE of git. You checkout an old commit, but node_modules\n has different versions than when that commit was made. The bug persists even\n in \"known good\" commits because the library versions drifted.\n\n3. THE \"MAGIC BUG\" PROBLEM\n You checkout code from 6 months ago to debug an issue. The bug is still there!\n But it wasn't there 6 months ago... The culprit: a minor version upgrade that\n happened silently without any PR or git commit. Impossible to track down.\n\n4. CHANGES OUTSIDE GIT = BAD\n Every change to your software should be tracked in version control.\n Implicit library upgrades via semver ranges violate this principle.\n\nTHE SOLUTION:\nāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n\nUse LOCKED (exact) versions for all dependencies:\n ā \"lodash\": \"^4.17.21\" <- BAD: allows 4.17.22, 4.18.0, etc.\n ā \"lodash\": \"~4.17.21\" <- BAD: allows 4.17.22, 4.17.23, etc.\n ā
\"lodash\": \"4.17.21\" <- GOOD: locked to this exact version\n\nTo upgrade libraries, use an explicit process:\n 1. Run: npm update <package-name>\n 2. Test thoroughly\n 3. Commit the package.json AND package-lock.json changes\n 4. Create a PR so the upgrade is reviewed and tracked in git history\n\nThis way, every library change is:\n ⢠Intentional (not accidental)\n ⢠Reviewed (via PR)\n ⢠Tracked (in git history)\n ⢠Bisectable (git bisect works correctly)\n\n`);\n}\n\ntype SemverRangeResult = { errors: number };\n\n// Check semver ranges in all package.json files - FAILS if any found\nfunction checkSemverRanges(workspaceRoot: string): SemverRangeResult {\n console.log('\\nš Checking for unlocked versions (semver ranges):');\n const packageFiles = findPackageJsonFiles(workspaceRoot);\n let semverErrors = 0;\n\n for (const filePath of packageFiles) {\n const relativePath = path.relative(workspaceRoot, filePath);\n const errors = validatePackageJson(filePath);\n\n if (errors.length > 0) {\n console.log(` ā ${relativePath}:`);\n for (const error of errors) {\n console.log(` ${error}`);\n }\n semverErrors += errors.length;\n } else {\n console.log(` ā
${relativePath}`);\n }\n }\n\n return { errors: semverErrors };\n}\n\nexport default async function runExecutor(\n _options: ValidateVersionsLockedOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n console.log('\\nš Validating Package Versions are LOCKED and CONSISTENT\\n');\n\n const workspaceRoot = context.root;\n\n // Step 1: Check for semver ranges (FAILS if any found)\n const semverResult = checkSemverRanges(workspaceRoot);\n const semverErrors = semverResult.errors;\n const packageFiles = findPackageJsonFiles(workspaceRoot);\n\n // Step 2: Check for version conflicts across package.json files\n const versionConflicts = checkVersionConflicts(workspaceRoot);\n\n // Summary\n console.log(`\\nš Summary:`);\n console.log(` Files checked: ${packageFiles.length}`);\n console.log(` Unlocked versions (semver ranges): ${semverErrors}`);\n console.log(` Version conflicts: ${versionConflicts.length}`);\n\n // Fail on semver ranges with educational message\n if (semverErrors > 0) {\n printSemverRangeEducationalMessage(semverErrors);\n return { success: false };\n }\n\n // Fail on version conflicts\n if (versionConflicts.length > 0) {\n console.log('\\nā VALIDATION FAILED!');\n console.log(' Fix version conflicts - all package.json files must use the same version for each dependency.');\n console.log(' This prevents \"works on my machine\" bugs where different projects use different library versions.\\n');\n return { success: false };\n }\n\n console.log('\\nā
VALIDATION PASSED! All versions are locked and consistent.');\n return { success: true };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-versions-locked/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAkBH,oDA2CC;AA8QD,8BA2CC;;AAnXD,+CAAyB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,EAAE,CAAC,CAAC;IAEhE,iDAAiD;IACjD,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;QACnB,kCAAkC,CAAC,YAAY,CAAC,CAAC;QACjD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED,4BAA4B;IAC5B,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9B,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;QACtC,OAAO,CAAC,GAAG,CAAC,kGAAkG,CAAC,CAAC;QAChH,OAAO,CAAC,GAAG,CAAC,wGAAwG,CAAC,CAAC;QACtH,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,gEAAgE,CAAC,CAAC;IAC9E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["/**\n * Validate Versions Locked Executor\n *\n * Validates that package.json versions are:\n * 1. LOCKED (exact versions, no semver ranges like ^, ~, *)\n * 2. CONSISTENT across all package.json files (no version conflicts)\n *\n * Why locked versions matter:\n * - Micro bugs ARE introduced via patch versions (1.4.5 ā 1.4.6)\n * - git bisect fails when software changes OUTSIDE of git\n * - Library upgrades must be explicit via PR/commit, not implicit drift\n *\n * Usage:\n * nx run architecture:validate-versions-locked\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { RuleGate } from '../../lib/rule-gate';\nimport { toError } from '../../toError';\n\nexport interface ValidateVersionsLockedOptions {\n // No options needed\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n// webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file\n// Find all package.json files except node_modules, dist, .nx, .angular\nexport function findPackageJsonFiles(dir: string, basePath = ''): string[] {\n const files: string[] = [];\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const fullPath = path.join(dir, item);\n const relativePath = path.join(basePath, item);\n\n // Skip these directories\n if (\n ['node_modules', 'dist', '.nx', '.angular', 'tmp', '.git'].includes(\n item,\n )\n ) {\n continue;\n }\n\n // Skip platform-specific node_modules backups (node_modules_mac, node_modules_linux, etc.)\n if (item.startsWith('node_modules_')) {\n continue;\n }\n\n // Skip all hidden directories (starting with .)\n if (item.startsWith('.')) {\n continue;\n }\n\n const stat = fs.statSync(fullPath);\n if (stat.isDirectory()) {\n // Don't descend into a nested git repository (e.g. a clone under repositories/): it is a\n // separate project with its own version policy, NOT part of this monorepo's version lock.\n // The presence of a `.git` entry (dir for a real clone, file for a worktree/submodule)\n // marks a repo boundary ā the same signal the AI guards use to scope to the current repo.\n if (fs.existsSync(path.join(fullPath, '.git'))) {\n continue;\n }\n files.push(...findPackageJsonFiles(fullPath, relativePath));\n } else if (item === 'package.json') {\n files.push(fullPath);\n }\n }\n\n return files;\n}\n\n// Check if a version string uses semver ranges\nfunction hasSemverRange(version: string): boolean {\n // Allow workspace protocol\n if (version.startsWith('workspace:')) {\n return false;\n }\n\n // Allow file: protocol (for local packages)\n if (version.startsWith('file:')) {\n return false;\n }\n\n // Check for common semver range patterns\n const semverPatterns = [\n /^\\^/, // ^1.2.3\n /^~/, // ~1.2.3\n /^\\+/, // +1.2.3\n /^\\*/, // *\n /^>/, // >1.2.3\n /^</, // <1.2.3\n /^>=/, // >=1.2.3\n /^<=/, // <=1.2.3\n /\\|\\|/, // 1.2.3 || 2.x\n / - /, // 1.2.3 - 2.3.4\n /^\\d+\\.x/, // 1.x, 1.2.x\n /^latest$/, // latest\n /^next$/, // next\n ];\n\n return semverPatterns.some((pattern) => pattern.test(version));\n}\n\n// webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file\n// Validate a single package.json file for semver ranges\nfunction validatePackageJson(filePath: string): string[] {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n const pkg = JSON.parse(content);\n const errors: string[] = [];\n\n // Check dependencies\n if (pkg.dependencies) {\n for (const [name, version] of Object.entries(pkg.dependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) {\n continue;\n }\n\n if (hasSemverRange(version as string)) {\n errors.push(\n `dependencies.${name}: \"${version}\" uses semver range (must be locked to exact version)`,\n );\n }\n }\n }\n\n // Check devDependencies\n if (pkg.devDependencies) {\n for (const [name, version] of Object.entries(pkg.devDependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) {\n continue;\n }\n\n if (hasSemverRange(version as string)) {\n errors.push(\n `devDependencies.${name}: \"${version}\" uses semver range (must be locked to exact version)`,\n );\n }\n }\n }\n\n // Check peerDependencies (these can have ranges for compatibility)\n // We don't validate peerDependencies for semver ranges since they're meant to be flexible\n\n return errors;\n } catch (err: unknown) {\n const error = toError(err);\n return [`Failed to parse ${filePath}: ${error.message}`];\n }\n}\n\n// Track all dependency versions across the monorepo\ninterface DependencyUsage {\n version: string;\n file: string;\n type: 'dependencies' | 'devDependencies';\n}\n\n// webpieces-disable max-lines-new-methods -- Collecting dependencies from all package.json files\n// Collect all dependency versions from all package.json files\nfunction collectAllDependencies(workspaceRoot: string): Map<string, DependencyUsage[]> {\n const dependencyMap = new Map<string, DependencyUsage[]>();\n const packageFiles = findPackageJsonFiles(workspaceRoot);\n\n for (const filePath of packageFiles) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n const pkg = JSON.parse(content);\n const relativePath = path.relative(workspaceRoot, filePath);\n\n // Collect dependencies\n if (pkg.dependencies) {\n for (const [name, version] of Object.entries(pkg.dependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) continue;\n\n const usage: DependencyUsage = {\n version: version as string,\n file: relativePath,\n type: 'dependencies'\n };\n\n if (!dependencyMap.has(name)) {\n dependencyMap.set(name, []);\n }\n dependencyMap.get(name)!.push(usage);\n }\n }\n\n // Collect devDependencies\n if (pkg.devDependencies) {\n for (const [name, version] of Object.entries(pkg.devDependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) continue;\n\n const usage: DependencyUsage = {\n version: version as string,\n file: relativePath,\n type: 'devDependencies'\n };\n\n if (!dependencyMap.has(name)) {\n dependencyMap.set(name, []);\n }\n dependencyMap.get(name)!.push(usage);\n }\n }\n } catch (err: unknown) {\n // const error = toError(err);\n // Intentionally skip files that can't be parsed - this is expected for some package.json files\n }\n }\n\n return dependencyMap;\n}\n\n// webpieces-disable max-lines-new-methods -- Simple iteration logic, splitting would reduce clarity\n// Check for version conflicts across package.json files\nfunction checkVersionConflicts(workspaceRoot: string): string[] {\n console.log('\\nš Checking for version conflicts across package.json files:');\n\n const dependencyMap = collectAllDependencies(workspaceRoot);\n const conflicts: string[] = [];\n\n for (const [packageName, usages] of dependencyMap.entries()) {\n // Get unique versions (ignoring workspace: and file: protocols)\n const versions = new Set(\n usages\n .map(u => u.version)\n .filter(v => !v.startsWith('workspace:') && !v.startsWith('file:'))\n );\n\n if (versions.size > 1) {\n const conflictDetails = usages\n .filter(u => !u.version.startsWith('workspace:') && !u.version.startsWith('file:'))\n .map(u => ` ${u.file} (${u.type}): ${u.version}`)\n .join('\\n');\n\n conflicts.push(` ā ${packageName} has ${versions.size} different versions:\\n${conflictDetails}`);\n }\n }\n\n if (conflicts.length === 0) {\n console.log(' ā
No version conflicts found');\n } else {\n for (const conflict of conflicts) {\n console.log(conflict);\n }\n }\n\n return conflicts;\n}\n\n/**\n * Prints the educational message explaining why semver ranges are forbidden.\n * This helps developers understand the rationale behind locked versions.\n */\n// webpieces-disable max-lines-new-methods -- Educational message template, splitting reduces clarity\nfunction printSemverRangeEducationalMessage(semverErrors: number): void {\n console.log(`\nā SEMVER RANGES DETECTED - BUILD FAILED\n\nFound ${semverErrors} package(s) using semver ranges (^, ~, *, etc.) instead of locked versions.\n\nWHY THIS IS A HARD FAILURE:\nāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n\n1. MICRO BUGS ARE REAL\n Thinking that patch versions (1.4.5 ā 1.4.6) don't introduce bugs is wrong.\n They do. Sometimes what looks like an \"easy fix\" breaks things in subtle ways.\n\n2. GIT BISECT BECOMES USELESS\n When you run \"git bisect\" to find when a bug was introduced, it fails if\n software changed OUTSIDE of git. You checkout an old commit, but node_modules\n has different versions than when that commit was made. The bug persists even\n in \"known good\" commits because the library versions drifted.\n\n3. THE \"MAGIC BUG\" PROBLEM\n You checkout code from 6 months ago to debug an issue. The bug is still there!\n But it wasn't there 6 months ago... The culprit: a minor version upgrade that\n happened silently without any PR or git commit. Impossible to track down.\n\n4. CHANGES OUTSIDE GIT = BAD\n Every change to your software should be tracked in version control.\n Implicit library upgrades via semver ranges violate this principle.\n\nTHE SOLUTION:\nāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n\nUse LOCKED (exact) versions for all dependencies:\n ā \"lodash\": \"^4.17.21\" <- BAD: allows 4.17.22, 4.18.0, etc.\n ā \"lodash\": \"~4.17.21\" <- BAD: allows 4.17.22, 4.17.23, etc.\n ā
\"lodash\": \"4.17.21\" <- GOOD: locked to this exact version\n\nTo upgrade libraries, use an explicit process:\n 1. Run: npm update <package-name>\n 2. Test thoroughly\n 3. Commit the package.json AND package-lock.json changes\n 4. Create a PR so the upgrade is reviewed and tracked in git history\n\nThis way, every library change is:\n ⢠Intentional (not accidental)\n ⢠Reviewed (via PR)\n ⢠Tracked (in git history)\n ⢠Bisectable (git bisect works correctly)\n\n`);\n}\n\ntype SemverRangeResult = { errors: number };\n\n// Check semver ranges in all package.json files - FAILS if any found\nfunction checkSemverRanges(workspaceRoot: string): SemverRangeResult {\n console.log('\\nš Checking for unlocked versions (semver ranges):');\n const packageFiles = findPackageJsonFiles(workspaceRoot);\n let semverErrors = 0;\n\n for (const filePath of packageFiles) {\n const relativePath = path.relative(workspaceRoot, filePath);\n const errors = validatePackageJson(filePath);\n\n if (errors.length > 0) {\n console.log(` ā ${relativePath}:`);\n for (const error of errors) {\n console.log(` ${error}`);\n }\n semverErrors += errors.length;\n } else {\n console.log(` ā
${relativePath}`);\n }\n }\n\n return { errors: semverErrors };\n}\n\nexport default async function runExecutor(\n _options: ValidateVersionsLockedOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const workspaceRoot = context.root;\n\n // All-or-nothing (honorEpoch = false): there is no blessed baseline to grandfather against.\n if (new RuleGate().isDisabled(workspaceRoot, 'validate-versions-locked', false)) {\n return { success: true };\n }\n\n console.log('\\nš Validating Package Versions are LOCKED and CONSISTENT\\n');\n\n // Step 1: Check for semver ranges (FAILS if any found)\n const semverResult = checkSemverRanges(workspaceRoot);\n const semverErrors = semverResult.errors;\n const packageFiles = findPackageJsonFiles(workspaceRoot);\n\n // Step 2: Check for version conflicts across package.json files\n const versionConflicts = checkVersionConflicts(workspaceRoot);\n\n // Summary\n console.log(`\\nš Summary:`);\n console.log(` Files checked: ${packageFiles.length}`);\n console.log(` Unlocked versions (semver ranges): ${semverErrors}`);\n console.log(` Version conflicts: ${versionConflicts.length}`);\n\n // Fail on semver ranges with educational message\n if (semverErrors > 0) {\n printSemverRangeEducationalMessage(semverErrors);\n return { success: false };\n }\n\n // Fail on version conflicts\n if (versionConflicts.length > 0) {\n console.log('\\nā VALIDATION FAILED!');\n console.log(' Fix version conflicts - all package.json files must use the same version for each dependency.');\n console.log(' This prevents \"works on my machine\" bugs where different projects use different library versions.\\n');\n return { success: false };\n }\n\n console.log('\\nā
VALIDATION PASSED! All versions are locked and consistent.');\n return { success: true };\n}\n"]}
|
package/src/lib/graph-loader.js
CHANGED
|
@@ -144,6 +144,7 @@ function formatEntryLines(entry) {
|
|
|
144
144
|
pushOptionalArrayField(lines, 'framework', entry.framework);
|
|
145
145
|
pushOptionalField(lines, 'role', entry.role);
|
|
146
146
|
pushOptionalField(lines, 'serviceName', entry.serviceName);
|
|
147
|
+
pushOptionalCallsServiceField(lines, entry.callsService);
|
|
147
148
|
pushOptionalBooleanField(lines, 'drawOnGraph', entry.drawOnGraph);
|
|
148
149
|
pushOptionalField(lines, 'shortDescription', entry.shortDescription);
|
|
149
150
|
pushOptionalField(lines, 'responsibilitiesFile', entry.responsibilitiesFile);
|
|
@@ -170,6 +171,19 @@ function pushOptionalField(lines, field, value) {
|
|
|
170
171
|
lines.push(` ${JSON.stringify(field)}: ${JSON.stringify(value)},`);
|
|
171
172
|
}
|
|
172
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* Emit the optional `callsService` field (12-space indent). Unlike serviceName it may be EITHER a
|
|
176
|
+
* single service name (string) OR an { apiClassName: serviceName } map, so it is emitted with
|
|
177
|
+
* JSON.stringify to cover both inline. MUST be persisted here: the runtime graph's target resolution
|
|
178
|
+
* reads it back from the committed dependencies.json during validate ā dropping it would make
|
|
179
|
+
* generate (which enriches it in-memory) and validate (which loads this file) derive different graphs.
|
|
180
|
+
*/
|
|
181
|
+
// webpieces-disable no-function-outside-class -- module-scope formatter, matches the sibling push*Field helpers here
|
|
182
|
+
function pushOptionalCallsServiceField(lines, value) {
|
|
183
|
+
if (value !== undefined) {
|
|
184
|
+
lines.push(` "callsService": ${JSON.stringify(value)},`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
173
187
|
/**
|
|
174
188
|
* Emit one optional boolean field (12-space indent) as a raw JSON boolean
|
|
175
189
|
* (e.g. `"drawOnGraph": false,`), skipped when undefined.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-loader.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-loader.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;;;AA0EH,4CA2BC;AAqHD,8BAsBC;AAKD,0CAMC;;AAzPD,+CAAyB;AACzB,mDAA6B;AAG7B,wCAAqC;AAErC;;GAEG;AACU,QAAA,kBA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AC,CAAC;IACrD,OAAO,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Graph Loader\n *\n * Handles loading and saving the blessed dependency graph file.\n * The graph is stored at architecture/dependencies.json in the workspace root.\n *\n * File format (schema aimed at AI consumers):\n * {\n * \"aiInstructions\": \"...how AI should use the per-project fields...\",\n * \"projects\": {\n * \"<project>\": { level, framework, shortDescription,\n * responsibilitiesFile, designFile, dependsOn }\n * }\n * }\n *\n * `framework` is the project's libType ā the SET of runtime environments it is\n * validated to run in, drawn from browser | react | angular | node | express\n * (e.g. [\"browser\",\"node\"]). It comes from the project's `framework:` nx tags\n * and is enforced across edges by the `library-types-match-client` rule.\n *\n * The legacy format (flat { \"<project>\": { level, dependsOn } } map) is still\n * readable so validation against a pre-upgrade file produces a clean\n * \"re-run architecture:generate\" diff instead of a parse failure.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { EnhancedGraph, GraphEntry } from './graph-sorter';\nimport type { ProjectApiRelations } from './api-usage/api-relations';\nimport { toError } from '../toError';\n\n/**\n * Default path for the dependencies file (relative to workspace root)\n */\nexport const DEFAULT_GRAPH_PATH = 'architecture/dependencies.json';\n\n/**\n * Top-level instructions embedded in dependencies.json telling AI how to use\n * the per-project metadata fields.\n */\nexport const AI_INSTRUCTIONS =\n \"Each project's shortDescription is only a summary. BEFORE adding code to a project, \" +\n 'read its responsibilitiesFile for the full responsibilities (what belongs in that ' +\n 'project and what does not), and read its designFile to understand the DI design ' +\n 'before reading the code. Use the entries in `commands` to regenerate these files ' +\n 'or display any of the graphs in a browser. To hide a project (its box AND every ' +\n \"edge touching it) from BOTH rendered architecture graphs, add the nx tag \" +\n \"'drawOnGraph:false' to that project's project.json tags and regenerate; it stays \" +\n 'in this file (marked \"drawOnGraph\": false) but is omitted from the HTML.';\n\n/**\n * Named command ā \"command ā what it does\" map embedded in dependencies.json.\n */\nexport type CommandMap = Record<string, string>;\n\n/**\n * Commands embedded in dependencies.json so AI (and humans) know how to\n * regenerate and DISPLAY the architecture + design graphs. These work in any\n * repo consuming @webpieces/nx-webpieces-rules.\n */\nexport const GRAPH_COMMANDS: CommandMap = {\n regenerateArchitecture:\n 'pnpm nx run architecture:generate ā rewrites architecture/dependencies.json and ' +\n 'architecture/runtime-dependencies.json; run after adding/removing project dependencies',\n visualizeArchitecture:\n 'pnpm nx run architecture:visualize ā opens the monorepo dependency graph (this file) ' +\n 'as HTML in a browser',\n visualizeRuntimeArchitecture:\n 'pnpm nx run architecture:visualize-runtime ā opens the runtime microservice call graph ' +\n 'as HTML in a browser',\n regenerateDesigns:\n \"pnpm nx run-many --target=di-graph-generate ā rewrites every project's \" +\n 'design.json/design.md (also runs automatically on every build)',\n visualizeDesign:\n \"pnpm wp-design-visualize <project> ā opens a project's DI designs (its designFile) as \" +\n 'HTML, one graph per controller with the controller at the top; no args = interactive picker',\n};\n\n/**\n * The full contents of architecture/dependencies.json.\n */\nexport class DependenciesFile {\n constructor(\n public readonly aiInstructions: string,\n public readonly commands: CommandMap,\n public readonly projects: EnhancedGraph\n ) {}\n}\n\n/**\n * Load the blessed graph from disk. Understands both the current wrapper\n * format and the legacy flat map (which loads with empty aiInstructions).\n *\n * @param workspaceRoot - Absolute path to workspace root\n * @param graphPath - Relative path to graph file (default: architecture/dependencies.json)\n * @returns The blessed graph file, or null if it doesn't exist\n */\nexport function loadBlessedGraph(\n workspaceRoot: string,\n graphPath: string = DEFAULT_GRAPH_PATH\n): DependenciesFile | null {\n const fullPath = path.join(workspaceRoot, graphPath);\n\n if (!fs.existsSync(fullPath)) {\n return null;\n }\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const content = fs.readFileSync(fullPath, 'utf-8');\n const parsed = JSON.parse(content);\n if (parsed !== null && typeof parsed === 'object' && 'projects' in parsed) {\n return new DependenciesFile(\n typeof parsed.aiInstructions === 'string' ? parsed.aiInstructions : '',\n parsed.commands !== null && typeof parsed.commands === 'object' ? (parsed.commands as CommandMap) : {},\n parsed.projects as EnhancedGraph\n );\n }\n // Legacy flat format: the whole object is the project map\n return new DependenciesFile('', {}, parsed as EnhancedGraph);\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`Failed to load graph from ${fullPath}`, { cause: error });\n }\n}\n\n/**\n * Format the dependencies file as JSON with multi-line arrays for readability\n */\nfunction formatGraphJson(file: DependenciesFile): string {\n const lines: string[] = ['{'];\n lines.push(` \"aiInstructions\": ${JSON.stringify(file.aiInstructions)},`);\n lines.push(` \"commands\": {`);\n const commandNames = Object.keys(file.commands);\n commandNames.forEach((name: string, index: number) => {\n const comma = index === commandNames.length - 1 ? '' : ',';\n lines.push(` ${JSON.stringify(name)}: ${JSON.stringify(file.commands[name])}${comma}`);\n });\n lines.push(` },`);\n lines.push(` \"projects\": {`);\n\n const keys = Object.keys(file.projects).sort();\n keys.forEach((key: string, index: number) => {\n const entry = file.projects[key];\n const isLast = index === keys.length - 1;\n const comma = isLast ? '' : ',';\n\n lines.push(` ${JSON.stringify(key)}: {`);\n lines.push(...formatEntryLines(entry));\n lines.push(` }${comma}`);\n });\n\n lines.push(' }');\n lines.push('}');\n return lines.join('\\n') + '\\n';\n}\n\n/**\n * Format one project entry's fields (12-space indent). Optional metadata\n * fields are only emitted when present.\n */\nfunction formatEntryLines(entry: GraphEntry): string[] {\n const lines: string[] = [];\n lines.push(` \"level\": ${entry.level},`);\n\n pushOptionalArrayField(lines, 'framework', entry.framework);\n pushOptionalField(lines, 'role', entry.role);\n pushOptionalField(lines, 'serviceName', entry.serviceName);\n pushOptionalBooleanField(lines, 'drawOnGraph', entry.drawOnGraph);\n pushOptionalField(lines, 'shortDescription', entry.shortDescription);\n pushOptionalField(lines, 'responsibilitiesFile', entry.responsibilitiesFile);\n pushOptionalField(lines, 'designFile', entry.designFile);\n pushApiRelationsField(lines, entry.apiRelations);\n\n if (entry.dependsOn.length === 0) {\n lines.push(` \"dependsOn\": []`);\n } else {\n lines.push(` \"dependsOn\": [`);\n entry.dependsOn.forEach((dep: string, depIndex: number) => {\n const depComma = depIndex === entry.dependsOn.length - 1 ? '' : ',';\n lines.push(` ${JSON.stringify(dep)}${depComma}`);\n });\n lines.push(` ]`);\n }\n return lines;\n}\n\n/**\n * Emit one optional string field (12-space indent), skipped when undefined.\n */\nfunction pushOptionalField(lines: string[], field: string, value: string | undefined): void {\n if (value !== undefined) {\n lines.push(` ${JSON.stringify(field)}: ${JSON.stringify(value)},`);\n }\n}\n\n/**\n * Emit one optional boolean field (12-space indent) as a raw JSON boolean\n * (e.g. `\"drawOnGraph\": false,`), skipped when undefined.\n */\n// webpieces-disable no-function-outside-class -- module-scope formatter, matches the sibling push*Field helpers here\nfunction pushOptionalBooleanField(lines: string[], field: string, value: boolean | undefined): void {\n if (value !== undefined) {\n lines.push(` ${JSON.stringify(field)}: ${JSON.stringify(value)},`);\n }\n}\n\n/**\n * Emit one optional string-array field (12-space indent) as a compact inline\n * JSON array (e.g. `\"framework\": [\"browser\",\"node\"],`), skipped when undefined.\n */\nfunction pushOptionalArrayField(lines: string[], field: string, value: string[] | undefined): void {\n if (value !== undefined) {\n lines.push(` ${JSON.stringify(field)}: ${JSON.stringify(value)},`);\n }\n}\n\n/**\n * Emit the optional `apiRelations` object (pretty, multi-line, reindented under\n * the 12-space entry block) with a trailing comma, since `dependsOn` always\n * follows it. Skipped when absent/empty so plain-lib-only projects stay compact.\n * The scanner already sorts owners + refs, so the JSON is deterministic.\n */\n// webpieces-disable no-function-outside-class -- module-scope formatter, matches the sibling push*Field helpers here\nfunction pushApiRelationsField(lines: string[], value: ProjectApiRelations | undefined): void {\n if (value === undefined || Object.keys(value).length === 0) return;\n const pretty = JSON.stringify(value, null, 4).split('\\n');\n pretty.forEach((line: string, index: number) => {\n const prefix = index === 0 ? '\"apiRelations\": ' : '';\n const suffix = index === pretty.length - 1 ? ',' : '';\n lines.push(` ${prefix}${line}${suffix}`);\n });\n}\n\n/**\n * Save the graph to disk in the wrapper format with the standard aiInstructions.\n *\n * @param graph - The enriched project graph to save\n * @param workspaceRoot - Absolute path to workspace root\n * @param graphPath - Relative path to graph file (default: architecture/dependencies.json)\n */\nexport function saveGraph(\n graph: EnhancedGraph,\n workspaceRoot: string,\n graphPath: string = DEFAULT_GRAPH_PATH\n): void {\n const fullPath = path.join(workspaceRoot, graphPath);\n const dir = path.dirname(fullPath);\n\n // Ensure directory exists\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Sort keys for deterministic output\n const sortedGraph: EnhancedGraph = {};\n const sortedKeys = Object.keys(graph).sort();\n for (const key of sortedKeys) {\n sortedGraph[key] = graph[key];\n }\n\n const content = formatGraphJson(new DependenciesFile(AI_INSTRUCTIONS, GRAPH_COMMANDS, sortedGraph));\n fs.writeFileSync(fullPath, content, 'utf-8');\n}\n\n/**\n * Check if the graph file exists\n */\nexport function graphFileExists(\n workspaceRoot: string,\n graphPath: string = DEFAULT_GRAPH_PATH\n): boolean {\n const fullPath = path.join(workspaceRoot, graphPath);\n return fs.existsSync(fullPath);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"graph-loader.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-loader.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;;;AA0EH,4CA2BC;AAuID,8BAsBC;AAKD,0CAMC;;AA3QD,+CAAyB;AACzB,mDAA6B;AAG7B,wCAAqC;AAErC;;GAEG;AACU,QAAA,kBAAkB,GAAG,gCAAgC,CAAC;AAEnE;;;GAGG;AACU,QAAA,eAAe,GACxB,sFAAsF;IACtF,oFAAoF;IACpF,kFAAkF;IAClF,mFAAmF;IACnF,kFAAkF;IAClF,2EAA2E;IAC3E,mFAAmF;IACnF,0EAA0E,CAAC;AAO/E;;;;GAIG;AACU,QAAA,cAAc,GAAe;IACtC,sBAAsB,EAClB,kFAAkF;QAClF,wFAAwF;IAC5F,qBAAqB,EACjB,uFAAuF;QACvF,sBA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;IACrD,OAAO,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Graph Loader\n *\n * Handles loading and saving the blessed dependency graph file.\n * The graph is stored at architecture/dependencies.json in the workspace root.\n *\n * File format (schema aimed at AI consumers):\n * {\n * \"aiInstructions\": \"...how AI should use the per-project fields...\",\n * \"projects\": {\n * \"<project>\": { level, framework, shortDescription,\n * responsibilitiesFile, designFile, dependsOn }\n * }\n * }\n *\n * `framework` is the project's libType ā the SET of runtime environments it is\n * validated to run in, drawn from browser | react | angular | node | express\n * (e.g. [\"browser\",\"node\"]). It comes from the project's `framework:` nx tags\n * and is enforced across edges by the `library-types-match-client` rule.\n *\n * The legacy format (flat { \"<project>\": { level, dependsOn } } map) is still\n * readable so validation against a pre-upgrade file produces a clean\n * \"re-run architecture:generate\" diff instead of a parse failure.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { EnhancedGraph, GraphEntry } from './graph-sorter';\nimport type { ProjectApiRelations } from './api-usage/api-relations';\nimport { toError } from '../toError';\n\n/**\n * Default path for the dependencies file (relative to workspace root)\n */\nexport const DEFAULT_GRAPH_PATH = 'architecture/dependencies.json';\n\n/**\n * Top-level instructions embedded in dependencies.json telling AI how to use\n * the per-project metadata fields.\n */\nexport const AI_INSTRUCTIONS =\n \"Each project's shortDescription is only a summary. BEFORE adding code to a project, \" +\n 'read its responsibilitiesFile for the full responsibilities (what belongs in that ' +\n 'project and what does not), and read its designFile to understand the DI design ' +\n 'before reading the code. Use the entries in `commands` to regenerate these files ' +\n 'or display any of the graphs in a browser. To hide a project (its box AND every ' +\n \"edge touching it) from BOTH rendered architecture graphs, add the nx tag \" +\n \"'drawOnGraph:false' to that project's project.json tags and regenerate; it stays \" +\n 'in this file (marked \"drawOnGraph\": false) but is omitted from the HTML.';\n\n/**\n * Named command ā \"command ā what it does\" map embedded in dependencies.json.\n */\nexport type CommandMap = Record<string, string>;\n\n/**\n * Commands embedded in dependencies.json so AI (and humans) know how to\n * regenerate and DISPLAY the architecture + design graphs. These work in any\n * repo consuming @webpieces/nx-webpieces-rules.\n */\nexport const GRAPH_COMMANDS: CommandMap = {\n regenerateArchitecture:\n 'pnpm nx run architecture:generate ā rewrites architecture/dependencies.json and ' +\n 'architecture/runtime-dependencies.json; run after adding/removing project dependencies',\n visualizeArchitecture:\n 'pnpm nx run architecture:visualize ā opens the monorepo dependency graph (this file) ' +\n 'as HTML in a browser',\n visualizeRuntimeArchitecture:\n 'pnpm nx run architecture:visualize-runtime ā opens the runtime microservice call graph ' +\n 'as HTML in a browser',\n regenerateDesigns:\n \"pnpm nx run-many --target=di-graph-generate ā rewrites every project's \" +\n 'design.json/design.md (also runs automatically on every build)',\n visualizeDesign:\n \"pnpm wp-design-visualize <project> ā opens a project's DI designs (its designFile) as \" +\n 'HTML, one graph per controller with the controller at the top; no args = interactive picker',\n};\n\n/**\n * The full contents of architecture/dependencies.json.\n */\nexport class DependenciesFile {\n constructor(\n public readonly aiInstructions: string,\n public readonly commands: CommandMap,\n public readonly projects: EnhancedGraph\n ) {}\n}\n\n/**\n * Load the blessed graph from disk. Understands both the current wrapper\n * format and the legacy flat map (which loads with empty aiInstructions).\n *\n * @param workspaceRoot - Absolute path to workspace root\n * @param graphPath - Relative path to graph file (default: architecture/dependencies.json)\n * @returns The blessed graph file, or null if it doesn't exist\n */\nexport function loadBlessedGraph(\n workspaceRoot: string,\n graphPath: string = DEFAULT_GRAPH_PATH\n): DependenciesFile | null {\n const fullPath = path.join(workspaceRoot, graphPath);\n\n if (!fs.existsSync(fullPath)) {\n return null;\n }\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const content = fs.readFileSync(fullPath, 'utf-8');\n const parsed = JSON.parse(content);\n if (parsed !== null && typeof parsed === 'object' && 'projects' in parsed) {\n return new DependenciesFile(\n typeof parsed.aiInstructions === 'string' ? parsed.aiInstructions : '',\n parsed.commands !== null && typeof parsed.commands === 'object' ? (parsed.commands as CommandMap) : {},\n parsed.projects as EnhancedGraph\n );\n }\n // Legacy flat format: the whole object is the project map\n return new DependenciesFile('', {}, parsed as EnhancedGraph);\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`Failed to load graph from ${fullPath}`, { cause: error });\n }\n}\n\n/**\n * Format the dependencies file as JSON with multi-line arrays for readability\n */\nfunction formatGraphJson(file: DependenciesFile): string {\n const lines: string[] = ['{'];\n lines.push(` \"aiInstructions\": ${JSON.stringify(file.aiInstructions)},`);\n lines.push(` \"commands\": {`);\n const commandNames = Object.keys(file.commands);\n commandNames.forEach((name: string, index: number) => {\n const comma = index === commandNames.length - 1 ? '' : ',';\n lines.push(` ${JSON.stringify(name)}: ${JSON.stringify(file.commands[name])}${comma}`);\n });\n lines.push(` },`);\n lines.push(` \"projects\": {`);\n\n const keys = Object.keys(file.projects).sort();\n keys.forEach((key: string, index: number) => {\n const entry = file.projects[key];\n const isLast = index === keys.length - 1;\n const comma = isLast ? '' : ',';\n\n lines.push(` ${JSON.stringify(key)}: {`);\n lines.push(...formatEntryLines(entry));\n lines.push(` }${comma}`);\n });\n\n lines.push(' }');\n lines.push('}');\n return lines.join('\\n') + '\\n';\n}\n\n/**\n * Format one project entry's fields (12-space indent). Optional metadata\n * fields are only emitted when present.\n */\nfunction formatEntryLines(entry: GraphEntry): string[] {\n const lines: string[] = [];\n lines.push(` \"level\": ${entry.level},`);\n\n pushOptionalArrayField(lines, 'framework', entry.framework);\n pushOptionalField(lines, 'role', entry.role);\n pushOptionalField(lines, 'serviceName', entry.serviceName);\n pushOptionalCallsServiceField(lines, entry.callsService);\n pushOptionalBooleanField(lines, 'drawOnGraph', entry.drawOnGraph);\n pushOptionalField(lines, 'shortDescription', entry.shortDescription);\n pushOptionalField(lines, 'responsibilitiesFile', entry.responsibilitiesFile);\n pushOptionalField(lines, 'designFile', entry.designFile);\n pushApiRelationsField(lines, entry.apiRelations);\n\n if (entry.dependsOn.length === 0) {\n lines.push(` \"dependsOn\": []`);\n } else {\n lines.push(` \"dependsOn\": [`);\n entry.dependsOn.forEach((dep: string, depIndex: number) => {\n const depComma = depIndex === entry.dependsOn.length - 1 ? '' : ',';\n lines.push(` ${JSON.stringify(dep)}${depComma}`);\n });\n lines.push(` ]`);\n }\n return lines;\n}\n\n/**\n * Emit one optional string field (12-space indent), skipped when undefined.\n */\nfunction pushOptionalField(lines: string[], field: string, value: string | undefined): void {\n if (value !== undefined) {\n lines.push(` ${JSON.stringify(field)}: ${JSON.stringify(value)},`);\n }\n}\n\n/**\n * Emit the optional `callsService` field (12-space indent). Unlike serviceName it may be EITHER a\n * single service name (string) OR an { apiClassName: serviceName } map, so it is emitted with\n * JSON.stringify to cover both inline. MUST be persisted here: the runtime graph's target resolution\n * reads it back from the committed dependencies.json during validate ā dropping it would make\n * generate (which enriches it in-memory) and validate (which loads this file) derive different graphs.\n */\n// webpieces-disable no-function-outside-class -- module-scope formatter, matches the sibling push*Field helpers here\nfunction pushOptionalCallsServiceField(\n lines: string[],\n value: string | Record<string, string> | undefined,\n): void {\n if (value !== undefined) {\n lines.push(` \"callsService\": ${JSON.stringify(value)},`);\n }\n}\n\n/**\n * Emit one optional boolean field (12-space indent) as a raw JSON boolean\n * (e.g. `\"drawOnGraph\": false,`), skipped when undefined.\n */\n// webpieces-disable no-function-outside-class -- module-scope formatter, matches the sibling push*Field helpers here\nfunction pushOptionalBooleanField(lines: string[], field: string, value: boolean | undefined): void {\n if (value !== undefined) {\n lines.push(` ${JSON.stringify(field)}: ${JSON.stringify(value)},`);\n }\n}\n\n/**\n * Emit one optional string-array field (12-space indent) as a compact inline\n * JSON array (e.g. `\"framework\": [\"browser\",\"node\"],`), skipped when undefined.\n */\nfunction pushOptionalArrayField(lines: string[], field: string, value: string[] | undefined): void {\n if (value !== undefined) {\n lines.push(` ${JSON.stringify(field)}: ${JSON.stringify(value)},`);\n }\n}\n\n/**\n * Emit the optional `apiRelations` object (pretty, multi-line, reindented under\n * the 12-space entry block) with a trailing comma, since `dependsOn` always\n * follows it. Skipped when absent/empty so plain-lib-only projects stay compact.\n * The scanner already sorts owners + refs, so the JSON is deterministic.\n */\n// webpieces-disable no-function-outside-class -- module-scope formatter, matches the sibling push*Field helpers here\nfunction pushApiRelationsField(lines: string[], value: ProjectApiRelations | undefined): void {\n if (value === undefined || Object.keys(value).length === 0) return;\n const pretty = JSON.stringify(value, null, 4).split('\\n');\n pretty.forEach((line: string, index: number) => {\n const prefix = index === 0 ? '\"apiRelations\": ' : '';\n const suffix = index === pretty.length - 1 ? ',' : '';\n lines.push(` ${prefix}${line}${suffix}`);\n });\n}\n\n/**\n * Save the graph to disk in the wrapper format with the standard aiInstructions.\n *\n * @param graph - The enriched project graph to save\n * @param workspaceRoot - Absolute path to workspace root\n * @param graphPath - Relative path to graph file (default: architecture/dependencies.json)\n */\nexport function saveGraph(\n graph: EnhancedGraph,\n workspaceRoot: string,\n graphPath: string = DEFAULT_GRAPH_PATH\n): void {\n const fullPath = path.join(workspaceRoot, graphPath);\n const dir = path.dirname(fullPath);\n\n // Ensure directory exists\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Sort keys for deterministic output\n const sortedGraph: EnhancedGraph = {};\n const sortedKeys = Object.keys(graph).sort();\n for (const key of sortedKeys) {\n sortedGraph[key] = graph[key];\n }\n\n const content = formatGraphJson(new DependenciesFile(AI_INSTRUCTIONS, GRAPH_COMMANDS, sortedGraph));\n fs.writeFileSync(fullPath, content, 'utf-8');\n}\n\n/**\n * Check if the graph file exists\n */\nexport function graphFileExists(\n workspaceRoot: string,\n graphPath: string = DEFAULT_GRAPH_PATH\n): boolean {\n const fullPath = path.join(workspaceRoot, graphPath);\n return fs.existsSync(fullPath);\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config gate for the Nx infrastructure validators.
|
|
3
|
+
*
|
|
4
|
+
* Every other rule in the system (eslint rules, code-rules, ai-hook rules, validate-ts-in-src) can be
|
|
5
|
+
* turned off or time-boxed from webpieces.config.json. The five infrastructure executors
|
|
6
|
+
* (validate-architecture-unchanged, validate-no-architecture-cycles, validate-packagejson,
|
|
7
|
+
* validate-versions-locked, validate-eslint-sync) hardcoded their behavior instead, which made them
|
|
8
|
+
* the only checks a consuming repo could not adopt gradually. This gate gives them the same
|
|
9
|
+
* semantics, from the same source of truth (`loadAndValidate` ā webpieces.config.json).
|
|
10
|
+
*
|
|
11
|
+
* Semantics:
|
|
12
|
+
* - rule entry ABSENT (or no webpieces.config.json at all) ā RUN. Fail-safe: an older config, or a
|
|
13
|
+
* repo that has not adopted the keys yet, behaves exactly as it did before this gate existed.
|
|
14
|
+
* - `"mode": "OFF"` ā skip with a reason.
|
|
15
|
+
* - `ignoreModifiedUntilEpoch` / `ignoreRuleWhileOnBranch` ā honored ONLY when the caller passes
|
|
16
|
+
* `honorEpoch: true`, i.e. only for the two rules that compare against a blessed baseline and can
|
|
17
|
+
* therefore meaningfully grandfather today's state. The other three are all-or-nothing (see the
|
|
18
|
+
* comment block above ValidateArchitectureUnchangedConfig in rules-config/src/rule-configs.ts).
|
|
19
|
+
*/
|
|
20
|
+
export declare class RuleGate {
|
|
21
|
+
/**
|
|
22
|
+
* @param workspaceRoot the Nx `context.root` ā where webpieces.config.json is looked up from.
|
|
23
|
+
* @param ruleName the webpieces.config.json key, identical to the Nx target name.
|
|
24
|
+
* @param honorEpoch true only for the baseline-comparing rules (see class doc).
|
|
25
|
+
* @returns a human-readable reason when the executor must SKIP, or null when it must RUN.
|
|
26
|
+
*/
|
|
27
|
+
skipReason(workspaceRoot: string, ruleName: string, honorEpoch: boolean): string | null;
|
|
28
|
+
/**
|
|
29
|
+
* Convenience wrapper: prints the standard skip line and reports whether the caller should stop.
|
|
30
|
+
* Keeps the four-line preamble identical across all five executors.
|
|
31
|
+
*/
|
|
32
|
+
isDisabled(workspaceRoot: string, ruleName: string, honorEpoch: boolean): boolean;
|
|
33
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Config gate for the Nx infrastructure validators.
|
|
4
|
+
*
|
|
5
|
+
* Every other rule in the system (eslint rules, code-rules, ai-hook rules, validate-ts-in-src) can be
|
|
6
|
+
* turned off or time-boxed from webpieces.config.json. The five infrastructure executors
|
|
7
|
+
* (validate-architecture-unchanged, validate-no-architecture-cycles, validate-packagejson,
|
|
8
|
+
* validate-versions-locked, validate-eslint-sync) hardcoded their behavior instead, which made them
|
|
9
|
+
* the only checks a consuming repo could not adopt gradually. This gate gives them the same
|
|
10
|
+
* semantics, from the same source of truth (`loadAndValidate` ā webpieces.config.json).
|
|
11
|
+
*
|
|
12
|
+
* Semantics:
|
|
13
|
+
* - rule entry ABSENT (or no webpieces.config.json at all) ā RUN. Fail-safe: an older config, or a
|
|
14
|
+
* repo that has not adopted the keys yet, behaves exactly as it did before this gate existed.
|
|
15
|
+
* - `"mode": "OFF"` ā skip with a reason.
|
|
16
|
+
* - `ignoreModifiedUntilEpoch` / `ignoreRuleWhileOnBranch` ā honored ONLY when the caller passes
|
|
17
|
+
* `honorEpoch: true`, i.e. only for the two rules that compare against a blessed baseline and can
|
|
18
|
+
* therefore meaningfully grandfather today's state. The other three are all-or-nothing (see the
|
|
19
|
+
* comment block above ValidateArchitectureUnchangedConfig in rules-config/src/rule-configs.ts).
|
|
20
|
+
*/
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.RuleGate = void 0;
|
|
23
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
24
|
+
class RuleGate {
|
|
25
|
+
/**
|
|
26
|
+
* @param workspaceRoot the Nx `context.root` ā where webpieces.config.json is looked up from.
|
|
27
|
+
* @param ruleName the webpieces.config.json key, identical to the Nx target name.
|
|
28
|
+
* @param honorEpoch true only for the baseline-comparing rules (see class doc).
|
|
29
|
+
* @returns a human-readable reason when the executor must SKIP, or null when it must RUN.
|
|
30
|
+
*/
|
|
31
|
+
skipReason(workspaceRoot, ruleName, honorEpoch) {
|
|
32
|
+
const rule = (0, rules_config_1.loadAndValidate)(workspaceRoot).resolved.rules.get(ruleName);
|
|
33
|
+
// Absent ā run. Never invent a default that silently disables a check.
|
|
34
|
+
if (!rule)
|
|
35
|
+
return null;
|
|
36
|
+
if (rule.isOff)
|
|
37
|
+
return 'mode: OFF';
|
|
38
|
+
if (!honorEpoch)
|
|
39
|
+
return null;
|
|
40
|
+
const epoch = rule.options['ignoreModifiedUntilEpoch'];
|
|
41
|
+
const branch = rule.options['ignoreRuleWhileOnBranch'];
|
|
42
|
+
const skip = (0, rules_config_1.shouldSkipRule)(epoch, branch);
|
|
43
|
+
return skip.skip ? (skip.reason ?? 'temporarily disabled') : null;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Convenience wrapper: prints the standard skip line and reports whether the caller should stop.
|
|
47
|
+
* Keeps the four-line preamble identical across all five executors.
|
|
48
|
+
*/
|
|
49
|
+
isDisabled(workspaceRoot, ruleName, honorEpoch) {
|
|
50
|
+
const reason = this.skipReason(workspaceRoot, ruleName, honorEpoch);
|
|
51
|
+
if (reason === null)
|
|
52
|
+
return false;
|
|
53
|
+
console.log(`\nāļø Skipping ${ruleName} (${reason}) ā configured in webpieces.config.json\n`);
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
exports.RuleGate = RuleGate;
|
|
58
|
+
//# sourceMappingURL=rule-gate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rule-gate.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/rule-gate.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;GAkBG;;;AAEH,0DAA0E;AAE1E,MAAa,QAAQ;IACjB;;;;;OAKG;IACH,UAAU,CAAC,aAAqB,EAAE,QAAgB,EAAE,UAAmB;QACnE,MAAM,IAAI,GAAG,IAAA,8BAAe,EAAC,aAAa,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACzE,uEAAuE;QACvE,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,IAAI,IAAI,CAAC,KAAK;YAAE,OAAO,WAAW,CAAC;QACnC,IAAI,CAAC,UAAU;YAAE,OAAO,IAAI,CAAC;QAE7B,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,0BAA0B,CAAuB,CAAC;QAC7E,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAuB,CAAC;QAC7E,MAAM,IAAI,GAAG,IAAA,6BAAc,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC3C,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,sBAAsB,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACtE,CAAC;IAED;;;OAGG;IACH,UAAU,CAAC,aAAqB,EAAE,QAAgB,EAAE,UAAmB;QACnE,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,aAAa,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;QACpE,IAAI,MAAM,KAAK,IAAI;YAAE,OAAO,KAAK,CAAC;QAClC,OAAO,CAAC,GAAG,CAAC,kBAAkB,QAAQ,KAAK,MAAM,2CAA2C,CAAC,CAAC;QAC9F,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ;AA9BD,4BA8BC","sourcesContent":["/**\n * Config gate for the Nx infrastructure validators.\n *\n * Every other rule in the system (eslint rules, code-rules, ai-hook rules, validate-ts-in-src) can be\n * turned off or time-boxed from webpieces.config.json. The five infrastructure executors\n * (validate-architecture-unchanged, validate-no-architecture-cycles, validate-packagejson,\n * validate-versions-locked, validate-eslint-sync) hardcoded their behavior instead, which made them\n * the only checks a consuming repo could not adopt gradually. This gate gives them the same\n * semantics, from the same source of truth (`loadAndValidate` ā webpieces.config.json).\n *\n * Semantics:\n * - rule entry ABSENT (or no webpieces.config.json at all) ā RUN. Fail-safe: an older config, or a\n * repo that has not adopted the keys yet, behaves exactly as it did before this gate existed.\n * - `\"mode\": \"OFF\"` ā skip with a reason.\n * - `ignoreModifiedUntilEpoch` / `ignoreRuleWhileOnBranch` ā honored ONLY when the caller passes\n * `honorEpoch: true`, i.e. only for the two rules that compare against a blessed baseline and can\n * therefore meaningfully grandfather today's state. The other three are all-or-nothing (see the\n * comment block above ValidateArchitectureUnchangedConfig in rules-config/src/rule-configs.ts).\n */\n\nimport { loadAndValidate, shouldSkipRule } from '@webpieces/rules-config';\n\nexport class RuleGate {\n /**\n * @param workspaceRoot the Nx `context.root` ā where webpieces.config.json is looked up from.\n * @param ruleName the webpieces.config.json key, identical to the Nx target name.\n * @param honorEpoch true only for the baseline-comparing rules (see class doc).\n * @returns a human-readable reason when the executor must SKIP, or null when it must RUN.\n */\n skipReason(workspaceRoot: string, ruleName: string, honorEpoch: boolean): string | null {\n const rule = loadAndValidate(workspaceRoot).resolved.rules.get(ruleName);\n // Absent ā run. Never invent a default that silently disables a check.\n if (!rule) return null;\n if (rule.isOff) return 'mode: OFF';\n if (!honorEpoch) return null;\n\n const epoch = rule.options['ignoreModifiedUntilEpoch'] as number | undefined;\n const branch = rule.options['ignoreRuleWhileOnBranch'] as string | undefined;\n const skip = shouldSkipRule(epoch, branch);\n return skip.skip ? (skip.reason ?? 'temporarily disabled') : null;\n }\n\n /**\n * Convenience wrapper: prints the standard skip line and reports whether the caller should stop.\n * Keeps the four-line preamble identical across all five executors.\n */\n isDisabled(workspaceRoot: string, ruleName: string, honorEpoch: boolean): boolean {\n const reason = this.skipReason(workspaceRoot, ruleName, honorEpoch);\n if (reason === null) return false;\n console.log(`\\nāļø Skipping ${ruleName} (${reason}) ā configured in webpieces.config.json\\n`);\n return true;\n }\n}\n"]}
|