@webpieces/code-rules 0.4.814 → 0.4.815
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 +2 -2
- package/src/cli.js +6 -14
- package/src/cli.js.map +1 -1
- package/src/code-rules-bootstrap.d.ts +13 -0
- package/src/code-rules-bootstrap.js +38 -0
- package/src/code-rules-bootstrap.js.map +1 -0
- package/src/code-rules-engine.d.ts +13 -1
- package/src/code-rules-engine.js +32 -5
- package/src/code-rules-engine.js.map +1 -1
- package/src/code-rules-run-request.d.ts +41 -0
- package/src/code-rules-run-request.js +103 -0
- package/src/code-rules-run-request.js.map +1 -0
- package/src/debug-run-report.d.ts +22 -0
- package/src/debug-run-report.js +127 -0
- package/src/debug-run-report.js.map +1 -0
- package/src/index.d.ts +1 -0
- package/src/index.js +4 -1
- package/src/index.js.map +1 -1
- package/src/rule-scope-plan.d.ts +72 -0
- package/src/rule-scope-plan.js +132 -0
- package/src/rule-scope-plan.js.map +1 -0
- package/src/validate-code.d.ts +7 -7
- package/src/validate-code.js +11 -20
- package/src/validate-code.js.map +1 -1
- package/src/validate-no-custom-css.d.ts +2 -1
- package/src/validate-no-custom-css.js +2 -1
- package/src/validate-no-custom-css.js.map +1 -1
- package/src/validate-no-state-paths-in-templates.d.ts +2 -1
- package/src/validate-no-state-paths-in-templates.js +2 -1
- package/src/validate-no-state-paths-in-templates.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-no-custom-css.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-custom-css.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAUiC;AACjC,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAEhD,gEAAgE;AAChE,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE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QACtC,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,mFAAmF,CAAC,CAAC;QACnG,OAAO,CAAC,KAAK,CAAC,0EAA0E,CAAC,CAAC;QAC1F,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAC5F,OAAO,CAAC,KAAK,CAAC,qFAAqF,CAAC,CAAC;QACrG,OAAO,CAAC,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC5D,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,mEAAmE,CAAC,CAAC;QACnF,OAAO,CAAC,KAAK,CAAC,yDAAyD,CAAC,CAAC;QACzE,OAAO,CAAC,KAAK,CAAC,+DAA+D,CAAC,CAAC;QAC/E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAC;QAC1C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtB,CAAC;CACJ,CAAA;AArNY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMjB,gCAAiB;GAL5B,oBAAoB,CAqNhC","sourcesContent":["/**\n * Validate No Custom CSS Executor\n *\n * Enforces Tailwind-first styling in Angular sources by banning hand-written CSS on CHANGED code:\n * - `.ts` — `styles:` / `styleUrls:` / `styleUrl:` inside an `@Component({...})` decorator\n * (detected via the TypeScript AST, so only the real decorator triggers it).\n * - `.html` — a static `style=\"…\"` attribute, a `[style]` / `[style.x]` binding, or `[ngStyle]`\n * (line/regex scan — Angular templates have no TS AST).\n *\n * Unlike an ESLint rule (which lints whole files), this is diff-scoped: NEW_AND_MODIFIED_CODE only\n * flags violations on changed lines, so a legacy Angular app is never retroactively flooded — the\n * rule bites when a file is next edited.\n *\n * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines) | NEW_AND_MODIFIED_FILES (all in changed files).\n *\n * ESCAPE HATCH (a genuinely dynamic runtime value):\n * .ts: // webpieces-disable no-custom-css -- <reason>\n * .html: <!-- webpieces-disable no-custom-css -- <reason> -->\n *\n * PATH EXEMPTION: `allowGlobs` in the rule's webpieces.config.json entry (a vendored kit copied verbatim\n * with its own CSS, a generated artifact). It is applied by the shared `NoCustomCssScope`, the SAME class\n * the edit-time hook rule consults — so the editor and CI agree on which paths the rule looks at.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport {\n hasDisable,\n RULE_NAMES,\n NoCustomCssConfig,\n NoCustomCssScope,\n ModifiedCodeMode,\n detectBase,\n getChangedFiles,\n getFileDiff,\n getChangedLineNumbers,\n} from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\n// @Component decorator properties that inject hand-written CSS.\nconst STYLE_PROPS = new Set(['styles', 'styleUrls', 'styleUrl']);\n\n// Template patterns. `[style.width]=\"x\"` is preceded by `[`, so the inline-style regex's\n// `(^|\\s)style=` boundary keeps it apart from the binding forms.\nconst RE_INLINE_STYLE = /(^|\\s)style\\s*=\\s*[\"']/;\nconst RE_NG_STYLE = /\\[?ngStyle\\]?\\s*=/;\nconst RE_STYLE_BINDING = /\\[style(?:\\.[\\w.-]+)?\\]/;\n\nexport class CssViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n ) {}\n}\n\nexport class CssHit {\n constructor(\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n readonly hasDisableComment: boolean,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoCustomCssValidator extends CodeValidator<NoCustomCssConfig> {\n // The SAME exemption the edit-time hook rule applies per file — one class in @webpieces/rules-config,\n // so `allowGlobs` cannot be honoured by the editor and ignored here (which is what it used to do).\n private readonly pathScope: NoCustomCssScope;\n\n constructor(config: NoCustomCssConfig) {\n super(config, 'no-custom-css', 'no-custom-css');\n this.pathScope = new NoCustomCssScope(config);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const opts = this.config;\n const mode = this.resolveMode(opts.mode ?? 'OFF', opts.turnOffRuleUntilEpoch, opts.turnOffRuleWhileOnBranch ?? undefined);\n const disableAllowed = opts.disableAllowed ?? true;\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-custom-css validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Custom CSS (Tailwind-first)\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log('\\n⏭️ Skipping no-custom-css validation (could not detect base branch)\\n');\n return { success: true };\n }\n }\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n // tsOnly:false so changed .html templates are included; then filter to relevant files.\n const changedFiles = getChangedFiles(workspaceRoot, base, head, { tsOnly: false }).filter((f: string) => this.isRelevantFile(f));\n if (changedFiles.length === 0) {\n console.log('✅ No Angular .ts/.html files changed');\n return { success: true };\n }\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n const violations =\n mode === 'NEW_AND_MODIFIED_CODE'\n ? this.findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed)\n : this.findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n\n if (violations.length === 0) {\n console.log('✅ No custom CSS found');\n return { success: true };\n }\n this.reportViolations(violations, mode);\n return { success: false };\n }\n\n /**\n * A changed file this rule cares about: an Angular .ts/.tsx or .html that the shared\n * {@link NoCustomCssScope} does not exempt (a test source, or a configured `allowGlobs` match).\n *\n * This is the ONE place the changed-file set is narrowed, which is what makes the exemption\n * impossible to apply in one mode and forget in the other — both `NEW_AND_MODIFIED_CODE` and\n * `NEW_AND_MODIFIED_FILES` run over the list this predicate produced.\n */\n isRelevantFile(file: string): boolean {\n if (this.pathScope.isExempt(file)) return false;\n return file.endsWith('.html') || file.endsWith('.ts') || file.endsWith('.tsx');\n }\n\n /** All banned-CSS hits in a single file (dispatches to the .ts AST or the .html line scan). */\n findHitsForFile(file: string, workspaceRoot: string): CssHit[] {\n if (file.endsWith('.html')) return this.findCustomCssInHtmlFile(file, workspaceRoot);\n if (file.endsWith('.ts') || file.endsWith('.tsx')) return this.findCustomCssInTsFile(file, workspaceRoot);\n return [];\n }\n\n /** NEW_AND_MODIFIED_CODE: only hits whose line is in the diff hunks. */\n private findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n ): CssViolation[] {\n const violations: CssViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const h of this.findHitsForFile(file, workspaceRoot)) {\n if (disableAllowed && h.hasDisableComment) continue;\n if (!changedLines.has(h.line)) continue;\n violations.push(new CssViolation(file, h.line, h.column, h.detail));\n }\n }\n return violations;\n }\n\n /** NEW_AND_MODIFIED_FILES: all hits in any changed file. */\n private findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): CssViolation[] {\n const violations: CssViolation[] = [];\n for (const file of changedFiles) {\n for (const h of this.findHitsForFile(file, workspaceRoot)) {\n if (disableAllowed && h.hasDisableComment) continue;\n violations.push(new CssViolation(file, h.line, h.column, h.detail));\n }\n }\n return violations;\n }\n\n /** Flag styles:/styleUrls:/styleUrl: properties inside an `@Component({...})` decorator. */\n private findCustomCssInTsFile(filePath: string, workspaceRoot: string): CssHit[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const hits: CssHit[] = [];\n this.collectTsHits(sourceFile, sourceFile, fileLines, hits);\n return hits;\n }\n\n /** Recurse the AST; every `@Component(...)` decorator contributes its banned style props. */\n private collectTsHits(node: ts.Node, sourceFile: ts.SourceFile, fileLines: string[], hits: CssHit[]): void {\n if (ts.isDecorator(node)) this.collectComponentStyleProps(node, sourceFile, fileLines, hits);\n ts.forEachChild(node, (child: ts.Node) => this.collectTsHits(child, sourceFile, fileLines, hits));\n }\n\n /** Pull the banned style props out of a single `@Component(...)` decorator node. */\n private collectComponentStyleProps(node: ts.Decorator, sourceFile: ts.SourceFile, fileLines: string[], hits: CssHit[]): void {\n const expr = node.expression;\n if (!ts.isCallExpression(expr) || !ts.isIdentifier(expr.expression) || expr.expression.text !== 'Component') return;\n const arg = expr.arguments[0];\n if (!arg || !ts.isObjectLiteralExpression(arg)) return;\n for (const prop of arg.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n const name = prop.name.text;\n if (!STYLE_PROPS.has(name)) continue;\n const pos = sourceFile.getLineAndCharacterOfPosition(prop.getStart(sourceFile));\n const line = pos.line + 1;\n hits.push(new CssHit(line, pos.character + 1, `\\`${name}\\` block in @Component`, this.hasDisableComment(fileLines, line)));\n }\n }\n\n /** Flag inline style=, [style.x]/[style], and [ngStyle] in an Angular template via a line scan. */\n private findCustomCssInHtmlFile(filePath: string, workspaceRoot: string): CssHit[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n const fileLines = fs.readFileSync(fullPath, 'utf-8').split('\\n');\n const hits: CssHit[] = [];\n for (let i = 0; i < fileLines.length; i++) {\n const detail = this.detailForTemplateLine(fileLines[i] ?? '');\n if (!detail) continue;\n const line = i + 1;\n hits.push(new CssHit(line, 1, detail, this.hasDisableComment(fileLines, line)));\n }\n return hits;\n }\n\n /** The banned-pattern label for a template line, or '' when the line is clean. */\n private detailForTemplateLine(raw: string): string {\n if (RE_NG_STYLE.test(raw)) return 'inline `[ngStyle]`';\n if (RE_STYLE_BINDING.test(raw)) return 'inline `[style.x]` binding';\n if (RE_INLINE_STYLE.test(raw)) return 'inline `style=` attribute';\n return '';\n }\n\n /** True if a `webpieces-disable no-custom-css` marker sits on this line or up to 3 lines above. */\n private hasDisableComment(lines: string[], lineNumber: number): boolean {\n const start = Math.max(0, lineNumber - 4);\n for (let i = lineNumber - 1; i >= start; i--) {\n if (hasDisable(lines[i] ?? '', RULE_NAMES.NO_CUSTOM_CSS)) return true;\n }\n return false;\n }\n\n private resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-custom-css validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n\n private reportViolations(violations: CssViolation[], mode: ModifiedCodeMode): void {\n console.error('');\n console.error('❌ Custom CSS found in Angular source! Style with Tailwind utility classes instead.');\n console.error('');\n console.error('📚 Tailwind-first keeps styling in the template, greppable and consistent:');\n console.error(' BAD: styles: [\".card { display: flex; gap: 1rem; }\"]');\n console.error(' GOOD: class=\"flex gap-4\"');\n console.error(' BAD: <div style=\"width: 240px\"> | [style.width] | [ngStyle]');\n console.error(' GOOD: <div class=\"w-[240px]\"> | [class.x] toggles');\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}:${v.column}`);\n console.error(` ${v.detail}`);\n }\n console.error('');\n console.error(' To fix: delete the CSS and use Tailwind utility classes (arbitrary values like');\n console.error(' `bg-[#fffde7]` / `grid-cols-[2fr_2fr_2fr_48px]` cover the long tail).');\n console.error('');\n console.error(' Whole tree not yours to restyle (a vendored kit, a generated artifact)?');\n console.error(' Add a glob to no-custom-css.allowGlobs in webpieces.config.json — it exempts the');\n console.error(' path here and in the editor hook alike.');\n console.error('');\n console.error(' Escape hatch (genuinely dynamic runtime value, use sparingly):');\n console.error(' .ts // webpieces-disable no-custom-css -- <reason>');\n console.error(' .html <!-- webpieces-disable no-custom-css -- <reason> -->');\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validate-no-custom-css.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-custom-css.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAUiC;AACjC,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAEhD,gEAAgE;AAChE,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC;AAEjE,yFAAyF;AACzF,iEAAiE;AACjE,MAAM,eAAe,GAAG,wBAAwB,CAAC;AACjD,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,gBAAgB,GAAG,yBAAyB,CAAC;AAEnD,MAAa,YAAY;IAER;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,IAAY,EACZ,MAAc,EACd,MAAc;QAHd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QACZ,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAQ;IACxB,CAAC;CACP;AAPD,oCAOC;AAED,MAAa,MAAM;IAEF;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,MAAc,EACd,MAAc,EACd,iBAA0B;QAH1B,SAAI,GAAJ,IAAI,CAAQ;QACZ,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAQ;QACd,sBAAiB,GAAjB,iBAAiB,CAAS;IACpC,CAAC;CACP;AAPD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;QAC1C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtB,CAAC;CACJ,CAAA;AArNY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMjB,gCAAiB;GAL5B,oBAAoB,CAqNhC","sourcesContent":["/**\n * Validate No Custom CSS Executor\n *\n * Enforces Tailwind-first styling in Angular sources by banning hand-written CSS on CHANGED code:\n * - `.ts` — `styles:` / `styleUrls:` / `styleUrl:` inside an `@Component({...})` decorator\n * (detected via the TypeScript AST, so only the real decorator triggers it).\n * - `.html` — a static `style=\"…\"` attribute, a `[style]` / `[style.x]` binding, or `[ngStyle]`\n * (line/regex scan — Angular templates have no TS AST).\n *\n * Unlike an ESLint rule (which lints whole files), this is diff-scoped: NEW_AND_MODIFIED_CODE only\n * flags violations on changed lines, so a legacy Angular app is never retroactively flooded — the\n * rule bites when a file is next edited.\n *\n * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines) | NEW_AND_MODIFIED_FILES (all in changed files)\n * | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole-scope, #1027 — widened centrally by DiffScope).\n *\n * ESCAPE HATCH (a genuinely dynamic runtime value):\n * .ts: // webpieces-disable no-custom-css -- <reason>\n * .html: <!-- webpieces-disable no-custom-css -- <reason> -->\n *\n * PATH EXEMPTION: `allowGlobs` in the rule's webpieces.config.json entry (a vendored kit copied verbatim\n * with its own CSS, a generated artifact). It is applied by the shared `NoCustomCssScope`, the SAME class\n * the edit-time hook rule consults — so the editor and CI agree on which paths the rule looks at.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport {\n hasDisable,\n RULE_NAMES,\n NoCustomCssConfig,\n NoCustomCssScope,\n ModifiedCodeMode,\n detectBase,\n getChangedFiles,\n getFileDiff,\n getChangedLineNumbers,\n} from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\n// @Component decorator properties that inject hand-written CSS.\nconst STYLE_PROPS = new Set(['styles', 'styleUrls', 'styleUrl']);\n\n// Template patterns. `[style.width]=\"x\"` is preceded by `[`, so the inline-style regex's\n// `(^|\\s)style=` boundary keeps it apart from the binding forms.\nconst RE_INLINE_STYLE = /(^|\\s)style\\s*=\\s*[\"']/;\nconst RE_NG_STYLE = /\\[?ngStyle\\]?\\s*=/;\nconst RE_STYLE_BINDING = /\\[style(?:\\.[\\w.-]+)?\\]/;\n\nexport class CssViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n ) {}\n}\n\nexport class CssHit {\n constructor(\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n readonly hasDisableComment: boolean,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoCustomCssValidator extends CodeValidator<NoCustomCssConfig> {\n // The SAME exemption the edit-time hook rule applies per file — one class in @webpieces/rules-config,\n // so `allowGlobs` cannot be honoured by the editor and ignored here (which is what it used to do).\n private readonly pathScope: NoCustomCssScope;\n\n constructor(config: NoCustomCssConfig) {\n super(config, 'no-custom-css', 'no-custom-css');\n this.pathScope = new NoCustomCssScope(config);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const opts = this.config;\n const mode = this.resolveMode(opts.mode ?? 'OFF', opts.turnOffRuleUntilEpoch, opts.turnOffRuleWhileOnBranch ?? undefined);\n const disableAllowed = opts.disableAllowed ?? true;\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-custom-css validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Custom CSS (Tailwind-first)\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log('\\n⏭️ Skipping no-custom-css validation (could not detect base branch)\\n');\n return { success: true };\n }\n }\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n // tsOnly:false so changed .html templates are included; then filter to relevant files.\n const changedFiles = getChangedFiles(workspaceRoot, base, head, { tsOnly: false }).filter((f: string) => this.isRelevantFile(f));\n if (changedFiles.length === 0) {\n console.log('✅ No Angular .ts/.html files changed');\n return { success: true };\n }\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n const violations =\n mode === 'NEW_AND_MODIFIED_CODE'\n ? this.findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed)\n : this.findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n\n if (violations.length === 0) {\n console.log('✅ No custom CSS found');\n return { success: true };\n }\n this.reportViolations(violations, mode);\n return { success: false };\n }\n\n /**\n * A changed file this rule cares about: an Angular .ts/.tsx or .html that the shared\n * {@link NoCustomCssScope} does not exempt (a test source, or a configured `allowGlobs` match).\n *\n * This is the ONE place the changed-file set is narrowed, which is what makes the exemption\n * impossible to apply in one mode and forget in the other — both `NEW_AND_MODIFIED_CODE` and\n * `NEW_AND_MODIFIED_FILES` run over the list this predicate produced.\n */\n isRelevantFile(file: string): boolean {\n if (this.pathScope.isExempt(file)) return false;\n return file.endsWith('.html') || file.endsWith('.ts') || file.endsWith('.tsx');\n }\n\n /** All banned-CSS hits in a single file (dispatches to the .ts AST or the .html line scan). */\n findHitsForFile(file: string, workspaceRoot: string): CssHit[] {\n if (file.endsWith('.html')) return this.findCustomCssInHtmlFile(file, workspaceRoot);\n if (file.endsWith('.ts') || file.endsWith('.tsx')) return this.findCustomCssInTsFile(file, workspaceRoot);\n return [];\n }\n\n /** NEW_AND_MODIFIED_CODE: only hits whose line is in the diff hunks. */\n private findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n ): CssViolation[] {\n const violations: CssViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const h of this.findHitsForFile(file, workspaceRoot)) {\n if (disableAllowed && h.hasDisableComment) continue;\n if (!changedLines.has(h.line)) continue;\n violations.push(new CssViolation(file, h.line, h.column, h.detail));\n }\n }\n return violations;\n }\n\n /** NEW_AND_MODIFIED_FILES: all hits in any changed file. */\n private findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): CssViolation[] {\n const violations: CssViolation[] = [];\n for (const file of changedFiles) {\n for (const h of this.findHitsForFile(file, workspaceRoot)) {\n if (disableAllowed && h.hasDisableComment) continue;\n violations.push(new CssViolation(file, h.line, h.column, h.detail));\n }\n }\n return violations;\n }\n\n /** Flag styles:/styleUrls:/styleUrl: properties inside an `@Component({...})` decorator. */\n private findCustomCssInTsFile(filePath: string, workspaceRoot: string): CssHit[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const hits: CssHit[] = [];\n this.collectTsHits(sourceFile, sourceFile, fileLines, hits);\n return hits;\n }\n\n /** Recurse the AST; every `@Component(...)` decorator contributes its banned style props. */\n private collectTsHits(node: ts.Node, sourceFile: ts.SourceFile, fileLines: string[], hits: CssHit[]): void {\n if (ts.isDecorator(node)) this.collectComponentStyleProps(node, sourceFile, fileLines, hits);\n ts.forEachChild(node, (child: ts.Node) => this.collectTsHits(child, sourceFile, fileLines, hits));\n }\n\n /** Pull the banned style props out of a single `@Component(...)` decorator node. */\n private collectComponentStyleProps(node: ts.Decorator, sourceFile: ts.SourceFile, fileLines: string[], hits: CssHit[]): void {\n const expr = node.expression;\n if (!ts.isCallExpression(expr) || !ts.isIdentifier(expr.expression) || expr.expression.text !== 'Component') return;\n const arg = expr.arguments[0];\n if (!arg || !ts.isObjectLiteralExpression(arg)) return;\n for (const prop of arg.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n const name = prop.name.text;\n if (!STYLE_PROPS.has(name)) continue;\n const pos = sourceFile.getLineAndCharacterOfPosition(prop.getStart(sourceFile));\n const line = pos.line + 1;\n hits.push(new CssHit(line, pos.character + 1, `\\`${name}\\` block in @Component`, this.hasDisableComment(fileLines, line)));\n }\n }\n\n /** Flag inline style=, [style.x]/[style], and [ngStyle] in an Angular template via a line scan. */\n private findCustomCssInHtmlFile(filePath: string, workspaceRoot: string): CssHit[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n const fileLines = fs.readFileSync(fullPath, 'utf-8').split('\\n');\n const hits: CssHit[] = [];\n for (let i = 0; i < fileLines.length; i++) {\n const detail = this.detailForTemplateLine(fileLines[i] ?? '');\n if (!detail) continue;\n const line = i + 1;\n hits.push(new CssHit(line, 1, detail, this.hasDisableComment(fileLines, line)));\n }\n return hits;\n }\n\n /** The banned-pattern label for a template line, or '' when the line is clean. */\n private detailForTemplateLine(raw: string): string {\n if (RE_NG_STYLE.test(raw)) return 'inline `[ngStyle]`';\n if (RE_STYLE_BINDING.test(raw)) return 'inline `[style.x]` binding';\n if (RE_INLINE_STYLE.test(raw)) return 'inline `style=` attribute';\n return '';\n }\n\n /** True if a `webpieces-disable no-custom-css` marker sits on this line or up to 3 lines above. */\n private hasDisableComment(lines: string[], lineNumber: number): boolean {\n const start = Math.max(0, lineNumber - 4);\n for (let i = lineNumber - 1; i >= start; i--) {\n if (hasDisable(lines[i] ?? '', RULE_NAMES.NO_CUSTOM_CSS)) return true;\n }\n return false;\n }\n\n private resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-custom-css validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n\n private reportViolations(violations: CssViolation[], mode: ModifiedCodeMode): void {\n console.error('');\n console.error('❌ Custom CSS found in Angular source! Style with Tailwind utility classes instead.');\n console.error('');\n console.error('📚 Tailwind-first keeps styling in the template, greppable and consistent:');\n console.error(' BAD: styles: [\".card { display: flex; gap: 1rem; }\"]');\n console.error(' GOOD: class=\"flex gap-4\"');\n console.error(' BAD: <div style=\"width: 240px\"> | [style.width] | [ngStyle]');\n console.error(' GOOD: <div class=\"w-[240px]\"> | [class.x] toggles');\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}:${v.column}`);\n console.error(` ${v.detail}`);\n }\n console.error('');\n console.error(' To fix: delete the CSS and use Tailwind utility classes (arbitrary values like');\n console.error(' `bg-[#fffde7]` / `grid-cols-[2fr_2fr_2fr_48px]` cover the long tail).');\n console.error('');\n console.error(' Whole tree not yours to restyle (a vendored kit, a generated artifact)?');\n console.error(' Add a glob to no-custom-css.allowGlobs in webpieces.config.json — it exempts the');\n console.error(' path here and in the editor hook alike.');\n console.error('');\n console.error(' Escape hatch (genuinely dynamic runtime value, use sparingly):');\n console.error(' .ts // webpieces-disable no-custom-css -- <reason>');\n console.error(' .html <!-- webpieces-disable no-custom-css -- <reason> -->');\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n }\n}\n"]}
|
|
@@ -29,7 +29,8 @@
|
|
|
29
29
|
* rule is a no-op. Deliberately NOT widened to `backlog/**` (frozen records of past requests — editing
|
|
30
30
|
* them falsifies the record) or to hand-written docs that name a FILE rather than a path.
|
|
31
31
|
*
|
|
32
|
-
* MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)
|
|
32
|
+
* MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)
|
|
33
|
+
* | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole-scope, #1027 — widened centrally by DiffScope).
|
|
33
34
|
* Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)
|
|
34
35
|
* are not retroactively flooded — the rule bites when a template is next edited.
|
|
35
36
|
*
|
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
* rule is a no-op. Deliberately NOT widened to `backlog/**` (frozen records of past requests — editing
|
|
31
31
|
* them falsifies the record) or to hand-written docs that name a FILE rather than a path.
|
|
32
32
|
*
|
|
33
|
-
* MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)
|
|
33
|
+
* MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)
|
|
34
|
+
* | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole-scope, #1027 — widened centrally by DiffScope).
|
|
34
35
|
* Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)
|
|
35
36
|
* are not retroactively flooded — the rule bites when a template is next edited.
|
|
36
37
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-no-state-paths-in-templates.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-state-paths-in-templates.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAaiC;AACjC,yCAA2D;AAE3D,qDAAiE;AACjE,iDAAgD;AAEhD,sDAAsD;AACtD,MAAa,kBAAkB;IAEd;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,IAAY,EACZ,MAAc,EACd,MAAc;QAHd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QACZ,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAQ;IACxB,CAAC;CACP;AAPD,gDAOC;AAED,6FAA6F;AAC7F,MAAa,YAAY;IAER;IACA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AAc,EAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QAClD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;YACxF,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,UAAU,CAAC;IACtB,CAAC;CACJ,CAAA;AA5MY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,4CAA6B;GADxC,gCAAgC,CA4M5C","sourcesContent":["/**\n * Validate No State Paths In Templates\n *\n * FAILS when a GENERATED-doc template restates a webpieces state path (`.webpieces/…`) as a literal\n * instead of rendering it from the resolver that already computes it.\n *\n * ## The incident this exists for\n *\n * `webpieces.git-workflow.md` — an AI-instruction doc regenerated into `.webpieces/instruct-ai/` of\n * every governed repo on every `wp-*` command — carried the literal\n * `.webpieces/logs/branch-mutations.log`. That log is deliberately PER-WORKTREE (one appender each):\n *\n * primary clone → `<primary>/.webpieces/logs/branch-mutations.log`\n * linked worktree → `<primary>/.webpieces/worktrees/<name>/logs/branch-mutations.log`\n *\n * So in a linked worktree the doc named a file that DOES NOT EXIST. The reader greps nothing, and the\n * silence reads as \"no deletions were logged\" — the opposite of the truth, from the one file whose\n * entire job is to prove every deletion is recoverable.\n *\n * The cure is not \"fix that line\". Every one of these paths already has a resolver, and the template\n * engine already substitutes (`{{MERGE_DIR}}`, `{{RUN_STATE}}`, `{{BRANCH_MUTATION_LOG}}` …). This\n * rule makes RESTATING the thing that fails and RENDERING the thing that passes, so the next one\n * cannot land.\n *\n * ## Scope\n *\n * `templateDirs` (workspace-relative dirs, recursive, `.md` only) — default\n * `packages/tooling/rules-config/templates`. A repo that generates no AI docs matches no files and the\n * rule is a no-op. Deliberately NOT widened to `backlog/**` (frozen records of past requests — editing\n * them falsifies the record) or to hand-written docs that name a FILE rather than a path.\n *\n * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file).\n * Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)\n * are not retroactively flooded — the rule bites when a template is next edited.\n *\n * ESCAPE HATCH (this table IS the layout, and printing it is the point):\n * <!-- webpieces-disable no-state-paths-in-templates -- <reason> -->\n *\n * `~/.webpieces/…` is NOT a violation: the machine-local tier has no per-tree resolver and no\n * per-tree answer, so the literal is the correct and only spelling of it.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n hasDisable,\n RULE_NAMES,\n NoStatePathsInTemplatesConfig,\n Option,\n RuleFailError,\n DEFAULT_TEMPLATE_DIRS,\n DEFAULT_BANNED_STATE_PATH_PREFIXES,\n ModifiedCodeMode,\n detectBase,\n getChangedFiles,\n getFileDiff,\n getChangedLineNumbers,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { shouldSkipRule } from './resolve-mode';\n\n/** One restated state path, located in a template. */\nexport class StatePathViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n ) {}\n}\n\n/** One restated state path within a single file, plus whether its line carries a disable. */\nexport class StatePathHit {\n constructor(\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n readonly hasDisableComment: boolean,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoStatePathsInTemplatesValidator extends CodeValidator<NoStatePathsInTemplatesConfig> {\n constructor(config: NoStatePathsInTemplatesConfig) {\n super(config, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const opts = this.config;\n const mode = this.resolveMode(\n opts.mode ?? 'NEW_AND_MODIFIED_CODE', opts.turnOffRuleUntilEpoch, opts.turnOffRuleWhileOnBranch ?? undefined);\n const disableAllowed = opts.disableAllowed ?? true;\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No State Paths In Templates\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (base === undefined || base === '') {\n base = detectBase(workspaceRoot) ?? undefined;\n if (base === undefined || base === '') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (could not detect base branch)\\n');\n return { success: true };\n }\n }\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = getChangedFiles(workspaceRoot, base, head, { tsOnly: false })\n .filter((file: string): boolean => this.isRelevantFile(file));\n if (changedFiles.length === 0) {\n console.log('✅ No generated-doc templates changed');\n return { success: true };\n }\n console.log(`📂 Checking ${String(changedFiles.length)} changed template(s)...`);\n\n const violations = mode === 'NEW_AND_MODIFIED_CODE'\n ? this.violationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed)\n : this.violationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n\n if (violations.length === 0) {\n console.log('✅ No hard-coded state paths in generated-doc templates');\n return { success: true };\n }\n throw this.failure(violations, mode);\n }\n\n /**\n * The ONE spelling of \"this validator failed\": a thrown {@link RuleFailError} carrying its cures as\n * `Option[]`, which {@link RuleReporter} catches and renders.\n *\n * NOT `console.error` + `{ success: false }`. That pair is a second spelling of the same fact (see\n * RuleReporter.runValidators, which calls it a back-compat shim scheduled for deletion), and\n * hand-written \"To fix: … / Escape hatch: …\" prose is a second spelling of `Option[]` — the\n * framework owns the `Fix Option N:` numbering and the `(preferred)` tag, so a rule never writes them.\n */\n private failure(violations: StatePathViolation[], mode: ModifiedCodeMode): RuleFailError {\n const detail = violations.map((violation: StatePathViolation): string =>\n ` ${violation.file}:${String(violation.line)}:${String(violation.column)} restates \\`${violation.detail}…\\``)\n .join('\\n');\n const first = violations[0];\n return new RuleFailError(\n RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES,\n 'A generated-doc template RESTATES a webpieces state path instead of computing it. These docs are '\n + 'regenerated into every governed repo and handed to an agent by absolute path AS INSTRUCTION, and '\n + 'every .webpieces/ path is per-tree — a linked worktree keeps its state under '\n + `<primary>/.webpieces/worktrees/<name>/ — so the relative spelling names a file that DOES NOT EXIST `\n + `in half the trees that read it. Current mode: ${mode}.\\n${detail}`,\n first?.line,\n first?.detail,\n [\n new Option(\n 'Put a {{PLACEHOLDER}} in the template and render it from the resolver that already computes '\n + 'that path, the way {{BRANCH_MUTATION_LOG}} is rendered from '\n + 'BranchMutationLog.branchMutationLogPath(root) in GitWorkflowDoc.render',\n true),\n new Option(\n 'If the doc\\'s SUBJECT is the layout and printing the literal is the point, say so out loud:\\n'\n + '<!-- webpieces-disable no-state-paths-in-templates -- <reason> -->'),\n ],\n );\n }\n\n /**\n * A changed file this rule looks at: a `.md` under one of the configured template dirs.\n *\n * The ONE place the file set is narrowed, so both modes run over the same list and a scope change\n * cannot be applied in one and forgotten in the other.\n */\n isRelevantFile(file: string): boolean {\n const norm = file.replace(/\\\\/g, '/');\n if (!norm.endsWith('.md')) return false;\n return this.templateDirs().some((dir: string): boolean => norm.startsWith(`${dir}/`));\n }\n\n /** Every restated state path in `text`, one hit per line (the first match on that line). */\n findHits(text: string): StatePathHit[] {\n const lines = text.split('\\n');\n const hits: StatePathHit[] = [];\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i] ?? '';\n for (const prefix of this.bannedPrefixes()) {\n const column = this.columnOf(raw, prefix);\n if (column < 0) continue;\n hits.push(new StatePathHit(i + 1, column + 1, prefix, this.hasDisableComment(lines, i + 1)));\n break;\n }\n }\n return hits;\n }\n\n /**\n * Where `prefix` is restated in `raw`, or -1.\n *\n * `~/.webpieces/…` is skipped: the machine-local tier is the same absolute path from every tree, so\n * there is no resolver to call and the literal is the only spelling there is. Everything else —\n * including the bare relative form that started this — is a restatement of a per-tree path.\n */\n private columnOf(raw: string, prefix: string): number {\n let from = 0;\n for (;;) {\n const at = raw.indexOf(prefix, from);\n if (at < 0) return -1;\n if (raw.slice(Math.max(0, at - 2), at) !== '~/') return at;\n from = at + 1;\n }\n }\n\n /** NEW_AND_MODIFIED_CODE: only hits whose line is in the diff hunks. */\n private violationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n if (!changedLines.has(hit.line)) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n /** NEW_AND_MODIFIED_FILES: every hit in any changed template. */\n private violationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n private hitsForFile(file: string, workspaceRoot: string): StatePathHit[] {\n const fullPath = path.join(workspaceRoot, file);\n if (!fs.existsSync(fullPath)) return [];\n return this.findHits(fs.readFileSync(fullPath, 'utf-8'));\n }\n\n private templateDirs(): readonly string[] {\n const dirs = this.config.templateDirs ?? DEFAULT_TEMPLATE_DIRS;\n return dirs.map((dir: string): string => dir.replace(/\\\\/g, '/').replace(/\\/+$/, ''));\n }\n\n private bannedPrefixes(): readonly string[] {\n return this.config.bannedPathPrefixes ?? DEFAULT_BANNED_STATE_PATH_PREFIXES;\n }\n\n /** True if a `webpieces-disable no-state-paths-in-templates` sits on this line or up to 3 above. */\n private hasDisableComment(lines: string[], lineNumber: number): boolean {\n const start = Math.max(0, lineNumber - 4);\n for (let i = lineNumber - 1; i >= start; i--) {\n if (hasDisable(lines[i] ?? '', RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES)) return true;\n }\n return false;\n }\n\n private resolveMode(\n normalMode: ModifiedCodeMode,\n epoch: number | undefined,\n branchPattern: string | undefined,\n ): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-state-paths-in-templates validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validate-no-state-paths-in-templates.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-state-paths-in-templates.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAaiC;AACjC,yCAA2D;AAE3D,qDAAiE;AACjE,iDAAgD;AAEhD,sDAAsD;AACtD,MAAa,kBAAkB;IAEd;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,IAAY,EACZ,MAAc,EACd,MAAc;QAHd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QACZ,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAQ;IACxB,CAAC;CACP;AAPD,gDAOC;AAED,6FAA6F;AAC7F,MAAa,YAAY;IAER;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,MAAc,EACd,MAAc,EACd,iBAA0B;QAH1B,SAAI,GAAJ,IAAI,CAAQ;QACZ,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAQ;QACd,sBAAiB,GAAjB,iBAAiB,CAAS;IACpC,CAAC;CACP;AAPD,oCAOC;AAGM,IAAM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CAAA;AA5MY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,4CAA6B;GADxC,gCAAgC,CA4M5C","sourcesContent":["/**\n * Validate No State Paths In Templates\n *\n * FAILS when a GENERATED-doc template restates a webpieces state path (`.webpieces/…`) as a literal\n * instead of rendering it from the resolver that already computes it.\n *\n * ## The incident this exists for\n *\n * `webpieces.git-workflow.md` — an AI-instruction doc regenerated into `.webpieces/instruct-ai/` of\n * every governed repo on every `wp-*` command — carried the literal\n * `.webpieces/logs/branch-mutations.log`. That log is deliberately PER-WORKTREE (one appender each):\n *\n * primary clone → `<primary>/.webpieces/logs/branch-mutations.log`\n * linked worktree → `<primary>/.webpieces/worktrees/<name>/logs/branch-mutations.log`\n *\n * So in a linked worktree the doc named a file that DOES NOT EXIST. The reader greps nothing, and the\n * silence reads as \"no deletions were logged\" — the opposite of the truth, from the one file whose\n * entire job is to prove every deletion is recoverable.\n *\n * The cure is not \"fix that line\". Every one of these paths already has a resolver, and the template\n * engine already substitutes (`{{MERGE_DIR}}`, `{{RUN_STATE}}`, `{{BRANCH_MUTATION_LOG}}` …). This\n * rule makes RESTATING the thing that fails and RENDERING the thing that passes, so the next one\n * cannot land.\n *\n * ## Scope\n *\n * `templateDirs` (workspace-relative dirs, recursive, `.md` only) — default\n * `packages/tooling/rules-config/templates`. A repo that generates no AI docs matches no files and the\n * rule is a no-op. Deliberately NOT widened to `backlog/**` (frozen records of past requests — editing\n * them falsifies the record) or to hand-written docs that name a FILE rather than a path.\n *\n * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)\n * | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole-scope, #1027 — widened centrally by DiffScope).\n * Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)\n * are not retroactively flooded — the rule bites when a template is next edited.\n *\n * ESCAPE HATCH (this table IS the layout, and printing it is the point):\n * <!-- webpieces-disable no-state-paths-in-templates -- <reason> -->\n *\n * `~/.webpieces/…` is NOT a violation: the machine-local tier has no per-tree resolver and no\n * per-tree answer, so the literal is the correct and only spelling of it.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n hasDisable,\n RULE_NAMES,\n NoStatePathsInTemplatesConfig,\n Option,\n RuleFailError,\n DEFAULT_TEMPLATE_DIRS,\n DEFAULT_BANNED_STATE_PATH_PREFIXES,\n ModifiedCodeMode,\n detectBase,\n getChangedFiles,\n getFileDiff,\n getChangedLineNumbers,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { shouldSkipRule } from './resolve-mode';\n\n/** One restated state path, located in a template. */\nexport class StatePathViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n ) {}\n}\n\n/** One restated state path within a single file, plus whether its line carries a disable. */\nexport class StatePathHit {\n constructor(\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n readonly hasDisableComment: boolean,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoStatePathsInTemplatesValidator extends CodeValidator<NoStatePathsInTemplatesConfig> {\n constructor(config: NoStatePathsInTemplatesConfig) {\n super(config, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const opts = this.config;\n const mode = this.resolveMode(\n opts.mode ?? 'NEW_AND_MODIFIED_CODE', opts.turnOffRuleUntilEpoch, opts.turnOffRuleWhileOnBranch ?? undefined);\n const disableAllowed = opts.disableAllowed ?? true;\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No State Paths In Templates\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (base === undefined || base === '') {\n base = detectBase(workspaceRoot) ?? undefined;\n if (base === undefined || base === '') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (could not detect base branch)\\n');\n return { success: true };\n }\n }\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = getChangedFiles(workspaceRoot, base, head, { tsOnly: false })\n .filter((file: string): boolean => this.isRelevantFile(file));\n if (changedFiles.length === 0) {\n console.log('✅ No generated-doc templates changed');\n return { success: true };\n }\n console.log(`📂 Checking ${String(changedFiles.length)} changed template(s)...`);\n\n const violations = mode === 'NEW_AND_MODIFIED_CODE'\n ? this.violationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed)\n : this.violationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n\n if (violations.length === 0) {\n console.log('✅ No hard-coded state paths in generated-doc templates');\n return { success: true };\n }\n throw this.failure(violations, mode);\n }\n\n /**\n * The ONE spelling of \"this validator failed\": a thrown {@link RuleFailError} carrying its cures as\n * `Option[]`, which {@link RuleReporter} catches and renders.\n *\n * NOT `console.error` + `{ success: false }`. That pair is a second spelling of the same fact (see\n * RuleReporter.runValidators, which calls it a back-compat shim scheduled for deletion), and\n * hand-written \"To fix: … / Escape hatch: …\" prose is a second spelling of `Option[]` — the\n * framework owns the `Fix Option N:` numbering and the `(preferred)` tag, so a rule never writes them.\n */\n private failure(violations: StatePathViolation[], mode: ModifiedCodeMode): RuleFailError {\n const detail = violations.map((violation: StatePathViolation): string =>\n ` ${violation.file}:${String(violation.line)}:${String(violation.column)} restates \\`${violation.detail}…\\``)\n .join('\\n');\n const first = violations[0];\n return new RuleFailError(\n RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES,\n 'A generated-doc template RESTATES a webpieces state path instead of computing it. These docs are '\n + 'regenerated into every governed repo and handed to an agent by absolute path AS INSTRUCTION, and '\n + 'every .webpieces/ path is per-tree — a linked worktree keeps its state under '\n + `<primary>/.webpieces/worktrees/<name>/ — so the relative spelling names a file that DOES NOT EXIST `\n + `in half the trees that read it. Current mode: ${mode}.\\n${detail}`,\n first?.line,\n first?.detail,\n [\n new Option(\n 'Put a {{PLACEHOLDER}} in the template and render it from the resolver that already computes '\n + 'that path, the way {{BRANCH_MUTATION_LOG}} is rendered from '\n + 'BranchMutationLog.branchMutationLogPath(root) in GitWorkflowDoc.render',\n true),\n new Option(\n 'If the doc\\'s SUBJECT is the layout and printing the literal is the point, say so out loud:\\n'\n + '<!-- webpieces-disable no-state-paths-in-templates -- <reason> -->'),\n ],\n );\n }\n\n /**\n * A changed file this rule looks at: a `.md` under one of the configured template dirs.\n *\n * The ONE place the file set is narrowed, so both modes run over the same list and a scope change\n * cannot be applied in one and forgotten in the other.\n */\n isRelevantFile(file: string): boolean {\n const norm = file.replace(/\\\\/g, '/');\n if (!norm.endsWith('.md')) return false;\n return this.templateDirs().some((dir: string): boolean => norm.startsWith(`${dir}/`));\n }\n\n /** Every restated state path in `text`, one hit per line (the first match on that line). */\n findHits(text: string): StatePathHit[] {\n const lines = text.split('\\n');\n const hits: StatePathHit[] = [];\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i] ?? '';\n for (const prefix of this.bannedPrefixes()) {\n const column = this.columnOf(raw, prefix);\n if (column < 0) continue;\n hits.push(new StatePathHit(i + 1, column + 1, prefix, this.hasDisableComment(lines, i + 1)));\n break;\n }\n }\n return hits;\n }\n\n /**\n * Where `prefix` is restated in `raw`, or -1.\n *\n * `~/.webpieces/…` is skipped: the machine-local tier is the same absolute path from every tree, so\n * there is no resolver to call and the literal is the only spelling there is. Everything else —\n * including the bare relative form that started this — is a restatement of a per-tree path.\n */\n private columnOf(raw: string, prefix: string): number {\n let from = 0;\n for (;;) {\n const at = raw.indexOf(prefix, from);\n if (at < 0) return -1;\n if (raw.slice(Math.max(0, at - 2), at) !== '~/') return at;\n from = at + 1;\n }\n }\n\n /** NEW_AND_MODIFIED_CODE: only hits whose line is in the diff hunks. */\n private violationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n if (!changedLines.has(hit.line)) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n /** NEW_AND_MODIFIED_FILES: every hit in any changed template. */\n private violationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n private hitsForFile(file: string, workspaceRoot: string): StatePathHit[] {\n const fullPath = path.join(workspaceRoot, file);\n if (!fs.existsSync(fullPath)) return [];\n return this.findHits(fs.readFileSync(fullPath, 'utf-8'));\n }\n\n private templateDirs(): readonly string[] {\n const dirs = this.config.templateDirs ?? DEFAULT_TEMPLATE_DIRS;\n return dirs.map((dir: string): string => dir.replace(/\\\\/g, '/').replace(/\\/+$/, ''));\n }\n\n private bannedPrefixes(): readonly string[] {\n return this.config.bannedPathPrefixes ?? DEFAULT_BANNED_STATE_PATH_PREFIXES;\n }\n\n /** True if a `webpieces-disable no-state-paths-in-templates` sits on this line or up to 3 above. */\n private hasDisableComment(lines: string[], lineNumber: number): boolean {\n const start = Math.max(0, lineNumber - 4);\n for (let i = lineNumber - 1; i >= start; i--) {\n if (hasDisable(lines[i] ?? '', RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES)) return true;\n }\n return false;\n }\n\n private resolveMode(\n normalMode: ModifiedCodeMode,\n epoch: number | undefined,\n branchPattern: string | undefined,\n ): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-state-paths-in-templates validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n}\n"]}
|