@webpieces/code-rules 0.4.837 → 0.4.839

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/code-rules",
3
- "version": "0.4.837",
3
+ "version": "0.4.839",
4
4
  "description": "Standalone code validation rules extracted from architecture-validators, no Nx dependency required",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -16,10 +16,12 @@
16
16
  "directory": "packages/tooling/code-rules"
17
17
  },
18
18
  "dependencies": {
19
- "@webpieces/rules-config": "0.4.837",
19
+ "@webpieces/rules-config": "0.4.839",
20
20
  "@inversifyjs/binding-decorators": "1.1.5",
21
21
  "inversify": "7.10.4",
22
- "reflect-metadata": "0.2.2"
22
+ "reflect-metadata": "0.2.2",
23
+ "@webpieces/tooling-common": "0.4.839",
24
+ "@webpieces/repo-workflow-core": "0.4.839"
23
25
  },
24
26
  "publishConfig": {
25
27
  "access": "public"
package/src/cli.js CHANGED
@@ -3,6 +3,8 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  require("reflect-metadata");
5
5
  const rules_config_1 = require("@webpieces/rules-config");
6
+ const tooling_common_1 = require("@webpieces/tooling-common");
7
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
6
8
  const code_rules_bootstrap_1 = require("./code-rules-bootstrap");
7
9
  const code_rules_run_request_1 = require("./code-rules-run-request");
8
10
  const USAGE = new rules_config_1.CliUsage('wp-validate-code', 'run the code rules against the diff, exactly as the gate does — or, with --rule, a DEBUG run of one rule', [
@@ -22,7 +24,7 @@ async function main() {
22
24
  process.exit(result.success ? 0 : 1);
23
25
  }
24
26
  catch (err) {
25
- const error = (0, rules_config_1.toError)(err);
27
+ const error = (0, to_error_1.toError)(err);
26
28
  if (error instanceof rules_config_1.CliExitError) {
27
29
  console.error(error.message);
28
30
  process.exit(error.exitCode);
@@ -30,7 +32,7 @@ async function main() {
30
32
  else if (error instanceof rules_config_1.RuleFailError) {
31
33
  console.error((0, rules_config_1.renderRuleFailForHuman)(error));
32
34
  }
33
- else if (err instanceof rules_config_1.InformAiError) {
35
+ else if (err instanceof tooling_common_1.InformAiError) {
34
36
  console.error(error.message);
35
37
  }
36
38
  else {
package/src/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/cli.ts"],"names":[],"mappings":";;;AACA,4BAA0B;AAC1B,0DAUiC;AAEjC,iEAA4D;AAC5D,qEAA4D;AAE5D,MAAM,KAAK,GAAG,IAAI,uBAAQ,CACtB,kBAAkB,EAClB,0GAA0G,EAC1G;IACI,IAAI,sBAAO,CAAC,QAAQ,EAAE,4GAA4G,EAAE,IAAI,CAAC;IACzI,IAAI,sBAAO,CAAC,QAAQ,EAAE,uGAAuG,EAAE,IAAI,CAAC;IACpI,IAAI,sBAAO,CAAC,YAAY,EAAE,qGAAqG,EAAE,IAAI,CAAC;CACzI,CACJ,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,qFAAqF;IACrF,IAAI,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,sBAAO,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACxC,MAAM,OAAO,GAAG,IAAI,yCAAgB,EAAE,CAAC,KAAK,CACxC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,EACrD,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,EACrD,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,SAAS,CAChE,CAAC;QACF,8FAA8F;QAC9F,6CAA6C;QAC7C,MAAM,aAAa,GAAG,IAAI,6BAAc,EAAE,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;QAC1E,MAAM,MAAM,GAAG,MAAM,IAAI,yCAAkB,EAAE,CAAC,GAAG,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;QAC1E,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACzC,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,IAAI,KAAK,YAAY,2BAAY,EAAE,CAAC;YAChC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAC7B,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QACjC,CAAC;aAAM,IAAI,KAAK,YAAY,4BAAa,EAAE,CAAC;YACxC,OAAO,CAAC,KAAK,CAAC,IAAA,qCAAsB,EAAC,KAAK,CAAC,CAAC,CAAC;QACjD,CAAC;aAAM,IAAI,GAAG,YAAY,4BAAa,EAAE,CAAC;YACtC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACjC,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,KAAK,CAAC,kCAAkC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACrE,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC;AAED,IAAI,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\nimport 'reflect-metadata';\nimport {\n CliArgs,\n CliExitError,\n CliFlag,\n CliUsage,\n InformAiError,\n RuleFailError,\n renderRuleFailForHuman,\n toError,\n RepoRootFinder,\n} from '@webpieces/rules-config';\n\nimport { CodeRulesBootstrap } from './code-rules-bootstrap';\nimport { RunRequestParser } from './code-rules-run-request';\n\nconst USAGE = new CliUsage(\n 'wp-validate-code',\n 'run the code rules against the diff, exactly as the gate does — or, with --rule, a DEBUG run of one rule',\n [\n new CliFlag('--rule', 'DEBUG: run only this rule (e.g. one-enum-spelling-in-api-lib). Nothing is written; the gate is unaffected.', true),\n new CliFlag('--mode', 'DEBUG: run --rule at this mode instead of its committed one (e.g. RUN_EVERY_TIME, MODIFIED_PROJECTS).', true),\n new CliFlag('--projects', 'DEBUG: judge only files owned by these nx projects, comma-separated (e.g. lang-apis,lang-fsdb-api).', true),\n ],\n);\n\nasync function main(): Promise<void> {\n // webpieces-disable no-unmanaged-exceptions -- global entry point for code-rules CLI\n try {\n const args = new CliArgs().parse(USAGE);\n const request = new RunRequestParser().parse(\n args.has('--rule') ? args.value('--rule') : undefined,\n args.has('--mode') ? args.value('--mode') : undefined,\n args.has('--projects') ? args.value('--projects') : undefined,\n );\n // Anchor at the repo root so `.webpieces/instruct-ai` docs land there, not in whatever subdir\n // this CLI ran from; load config from there.\n const workspaceRoot = new RepoRootFinder().resolveRepoRoot(process.cwd());\n const result = await new CodeRulesBootstrap().run(workspaceRoot, request);\n process.exit(result.success ? 0 : 1);\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof CliExitError) {\n console.error(error.message);\n process.exit(error.exitCode);\n } else if (error instanceof RuleFailError) {\n console.error(renderRuleFailForHuman(error));\n } else if (err instanceof InformAiError) {\n console.error(error.message);\n } else {\n console.error(`[code-rules] unexpected error: ${error.message}`);\n }\n process.exit(1);\n }\n}\n\nmain();\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/cli.ts"],"names":[],"mappings":";;;AACA,4BAA0B;AAC1B,0DAA0I;AAC1I,8DAA0D;AAC1D,iEAA6D;AAE7D,iEAA4D;AAC5D,qEAA4D;AAE5D,MAAM,KAAK,GAAG,IAAI,uBAAQ,CACtB,kBAAkB,EAClB,0GAA0G,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,IAAI,KAAK,YAAY,2BAAY,EAAE,CAAC;YAChC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAC7B,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QACjC,CAAC;aAAM,IAAI,KAAK,YAAY,4BAAa,EAAE,CAAC;YACxC,OAAO,CAAC,KAAK,CAAC,IAAA,qCAAsB,EAAC,KAAK,CAAC,CAAC,CAAC;QACjD,CAAC;aAAM,IAAI,GAAG,YAAY,8BAAa,EAAE,CAAC;YACtC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACjC,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,KAAK,CAAC,kCAAkC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACrE,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC;AAED,IAAI,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\nimport 'reflect-metadata';\nimport { CliArgs, CliExitError, CliFlag, CliUsage, RuleFailError, renderRuleFailForHuman, RepoRootFinder } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\nimport { CodeRulesBootstrap } from './code-rules-bootstrap';\nimport { RunRequestParser } from './code-rules-run-request';\n\nconst USAGE = new CliUsage(\n 'wp-validate-code',\n 'run the code rules against the diff, exactly as the gate does — or, with --rule, a DEBUG run of one rule',\n [\n new CliFlag('--rule', 'DEBUG: run only this rule (e.g. one-enum-spelling-in-api-lib). Nothing is written; the gate is unaffected.', true),\n new CliFlag('--mode', 'DEBUG: run --rule at this mode instead of its committed one (e.g. RUN_EVERY_TIME, MODIFIED_PROJECTS).', true),\n new CliFlag('--projects', 'DEBUG: judge only files owned by these nx projects, comma-separated (e.g. lang-apis,lang-fsdb-api).', true),\n ],\n);\n\nasync function main(): Promise<void> {\n // webpieces-disable no-unmanaged-exceptions -- global entry point for code-rules CLI\n try {\n const args = new CliArgs().parse(USAGE);\n const request = new RunRequestParser().parse(\n args.has('--rule') ? args.value('--rule') : undefined,\n args.has('--mode') ? args.value('--mode') : undefined,\n args.has('--projects') ? args.value('--projects') : undefined,\n );\n // Anchor at the repo root so `.webpieces/instruct-ai` docs land there, not in whatever subdir\n // this CLI ran from; load config from there.\n const workspaceRoot = new RepoRootFinder().resolveRepoRoot(process.cwd());\n const result = await new CodeRulesBootstrap().run(workspaceRoot, request);\n process.exit(result.success ? 0 : 1);\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof CliExitError) {\n console.error(error.message);\n process.exit(error.exitCode);\n } else if (error instanceof RuleFailError) {\n console.error(renderRuleFailForHuman(error));\n } else if (err instanceof InformAiError) {\n console.error(error.message);\n } else {\n console.error(`[code-rules] unexpected error: ${error.message}`);\n }\n process.exit(1);\n }\n}\n\nmain();\n"]}
@@ -4,6 +4,7 @@ exports.CodeRulesBootstrap = void 0;
4
4
  require("reflect-metadata");
5
5
  const inversify_1 = require("inversify");
6
6
  const rules_config_1 = require("@webpieces/rules-config");
7
+ const tooling_common_1 = require("@webpieces/tooling-common");
7
8
  const code_rules_app_1 = require("./code-rules-app");
8
9
  const code_rules_context_1 = require("./code-rules-context");
9
10
  const code_rules_config_table_1 = require("./code-rules-config-table");
@@ -41,7 +42,7 @@ class CodeRulesBootstrap {
41
42
  async run(workspaceRoot, request) {
42
43
  const loaded = (0, rules_config_1.loadAndValidate)(workspaceRoot);
43
44
  if (loaded.configPath === null) {
44
- throw new rules_config_1.InformAiError('No webpieces.config.json found at workspace root (or any ancestor).');
45
+ throw new tooling_common_1.InformAiError('No webpieces.config.json found at workspace root (or any ancestor).');
45
46
  }
46
47
  console.log(`\n📄 Loaded config: ${loaded.configPath}`);
47
48
  const plan = request.isDebug() ? this.plan(workspaceRoot, loaded, request) : undefined;
@@ -91,7 +92,7 @@ class CodeRulesBootstrap {
91
92
  return new DebugPlan(rule, mode, committedMode, request.projects);
92
93
  }
93
94
  refusal(reason) {
94
- return new rules_config_1.InformAiError(`[debug run] ${reason}`);
95
+ return new tooling_common_1.InformAiError(`[debug run] ${reason}`);
95
96
  }
96
97
  /** The mode set of a rule that reads its files through ScanScope, or undefined for any other rule. */
97
98
  wholeScopeModesOf(rule, loaded) {
@@ -1 +1 @@
1
- {"version":3,"file":"code-rules-bootstrap.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-bootstrap.ts"],"names":[],"mappings":";;;AAAA,4BAA0B;AAC1B,yCAAsC;AACtC,0DASiC;AAGjC,qDAAgD;AAChD,6DAAuE;AACvE,uEAA2E;AAC3E,qEAA8E;AAC9E,6CAAwF;AAExF,0GAA0G;AAC1G,MAAM,SAAS;IAEE;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,IAAY,EACZ,aAAqB,EACrB,QAAuC;QAHvC,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QACZ,kBAAa,GAAb,aAAa,CAAQ;QACrB,aAAQ,GAAR,QAAQ,CAA+B;IACjD,CAAC;CACP;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAa,kBAAkB;IAC3B,KAAK,CAAC,GAAG,CAAC,aAAqB,EAAE,OAA4B;QACzD,MAAM,MAAM,GAAG,IAAA,8BAAe,EAAC,aAAa,CAAC,CAAC;QAC9C,IAAI,MAAM,CAAC,UAAU,KAAK,IAAI,EAAE,CAAC;YAC7B,MAAM,IAAI,4BAAa,CAAC,qEAAqE,CAAC,CAAC;QACnG,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,uBAAuB,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;QAExD,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACvF,IAAI,IAAI,K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AM,KAAK,GAAG,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;QAChE,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,GAAW,EAAE,CAAS,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;QACzF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,KAAK,eAAe,CAAC,CAAC;QACtE,KAAK,MAAM,IAAI,IAAI,KAAK;YAAE,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,KAAK,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC9E,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;YACjC,OAAO,CAAC,GAAG,CAAC,sEAAsE,CAAC,CAAC;QACxF,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAChB,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ;AAxHD,gDAwHC","sourcesContent":["import 'reflect-metadata';\nimport { Container } from 'inversify';\nimport {\n BaseRuleConfig,\n DiffScope,\n InformAiError,\n LoadedConfig,\n MatchRuleConfig,\n MODIFIED_CODE_MODES,\n RULE_SCHEMAS,\n loadAndValidate,\n} from '@webpieces/rules-config';\n\nimport { ExecutorResult } from './code-validator';\nimport { CodeRulesApp } from './code-rules-app';\nimport { WorkspaceRoot, MatchRulesHolder } from './code-rules-context';\nimport { CONFIG_BINDINGS, ConfigBinding } from './code-rules-config-table';\nimport { CodeRulesRunRequest, RuleSelection } from './code-rules-run-request';\nimport { ProjectCatalog, ProjectEntry, ScanRestriction, ScanScope } from './scan-scope';\n\n/** A validated debug run (#1027): the one rule, the mode it runs at, and the projects it is scoped to. */\nclass DebugPlan {\n constructor(\n readonly rule: string,\n readonly mode: string,\n readonly committedMode: string,\n readonly projects: readonly string[] | undefined,\n ) {}\n}\n\n/**\n * The ONE composition root of a code-rules run, shared by the `validate-code` nx executor and the\n * `wp-validate-code` bin so the two cannot drift. It binds the workspace root and every rule's config,\n * then resolves {@link CodeRulesApp} so inversify builds the whole validator DAG.\n *\n * A DEBUG run (#1027 — any of `--rule` / `--mode` / `--projects`) differs from the gate in exactly four\n * ways, all in memory: only the named rule runs; its mode is replaced when `--mode` is given; its two\n * escape hatches are cleared (the question asked is \"what is left?\", which a time-boxed OFF must not\n * hide); and every rule reads its files through a {@link ScanRestriction} naming the projects. Nothing\n * is written — webpieces.config.json is untouched, so the gate keeps honouring the committed mode. It\n * prints the rule's own failure text, then one count per project, and fails when any site exists.\n *\n * A request it cannot run (no config, an unknown rule or project, --mode without --rule) THROWS an\n * {@link InformAiError} naming the cure; the bin's and the executor's top-level handlers print it.\n */\nexport class CodeRulesBootstrap {\n async run(workspaceRoot: string, request: CodeRulesRunRequest): Promise<ExecutorResult> {\n const loaded = loadAndValidate(workspaceRoot);\n if (loaded.configPath === null) {\n throw new InformAiError('No webpieces.config.json found at workspace root (or any ancestor).');\n }\n console.log(`\\n📄 Loaded config: ${loaded.configPath}`);\n\n const plan = request.isDebug() ? this.plan(workspaceRoot, loaded, request) : undefined;\n if (plan !== undefined) this.printBanner(plan);\n\n // autobind self-binds every @injectable(Singleton) tooling class (replaces the buildProviderModule registry scan)\n const container = new Container({ autobind: true });\n container.bind(WorkspaceRoot).toConstantValue(new WorkspaceRoot(workspaceRoot));\n container.bind(MatchRulesHolder).toConstantValue(new MatchRulesHolder(this.matchRules(loaded, plan)));\n container.bind(RuleSelection).toConstantValue(new RuleSelection(plan?.rule));\n container.bind(ScanRestriction).toConstantValue(new ScanRestriction(plan?.projects));\n for (const binding of CONFIG_BINDINGS) {\n const ConfigClass = binding[0];\n const configured = loaded.rulesConfig[binding[1]] as BaseRuleConfig | undefined;\n const config = configured ?? new ConfigClass();\n container.bind(ConfigClass).toConstantValue(plan?.rule === binding[1] ? this.overridden(config, plan) : config);\n }\n\n const result = await container.get(CodeRulesApp).run();\n if (plan === undefined) return result;\n // A debug run FAILS whenever a site exists — including a rule that only warns at the gate\n // (no-client-creation-outside-server-or-client at severity \"warn\") — so it can gate a loop.\n const sites = this.printCounts(workspaceRoot, plan, container.get(ScanScope), result);\n return { success: result.success && sites === 0 };\n }\n\n /** Validate a debug request against the loaded config and the repo's projects; throws on a refusal. */\n private plan(workspaceRoot: string, loaded: LoadedConfig, request: CodeRulesRunRequest): DebugPlan {\n const rule = request.rule;\n if (rule === undefined) throw this.refusal('--mode and --projects need --rule=<name>: a debug run judges exactly one rule.');\n const modes = this.wholeScopeModesOf(rule, loaded);\n if (modes === undefined) {\n throw this.refusal(`--rule=${rule} is not a code rule that supports a debug run. Rules that do (they offer ` +\n `MODIFIED_PROJECTS and RUN_EVERY_TIME): ${this.debuggableRules(loaded).join(', ')}.`);\n }\n const committedMode = this.committedModeOf(rule, loaded) ?? 'OFF';\n const mode = request.mode ?? committedMode;\n if (!modes.includes(mode) || mode === 'OFF') {\n const why = request.mode === undefined ? `its committed mode is ${committedMode}` : `--mode=${mode} is not one of its modes`;\n throw this.refusal(`${rule} cannot run: ${why}. Pass --mode=<one of ${modes.filter((m: string) => m !== 'OFF').join(', ')}>.`);\n }\n const unknown = (request.projects ?? []).filter((name: string) => !this.projectNames(workspaceRoot).includes(name));\n if (unknown.length > 0) {\n throw this.refusal(`--projects names no such nx project: ${unknown.join(', ')}. Known projects: ` +\n `${this.projectNames(workspaceRoot).join(', ')}.`);\n }\n return new DebugPlan(rule, mode, committedMode, request.projects);\n }\n\n private refusal(reason: string): InformAiError {\n return new InformAiError(`[debug run] ${reason}`);\n }\n\n /** The mode set of a rule that reads its files through ScanScope, or undefined for any other rule. */\n private wholeScopeModesOf(rule: string, loaded: LoadedConfig): readonly string[] | undefined {\n if (loaded.matchRules.some((mr: MatchRuleConfig) => mr.name === rule)) return MODIFIED_CODE_MODES;\n if (!CONFIG_BINDINGS.some((binding: ConfigBinding) => binding[1] === rule)) return undefined;\n const modes = RULE_SCHEMAS[rule]?.['mode']?.enumValues ?? [];\n return modes.includes('MODIFIED_PROJECTS') && modes.includes('RUN_EVERY_TIME') ? modes : undefined;\n }\n\n private debuggableRules(loaded: LoadedConfig): string[] {\n const builtIns = CONFIG_BINDINGS.map((binding: ConfigBinding) => binding[1] as string);\n const names = [...builtIns, ...loaded.matchRules.map((mr: MatchRuleConfig) => mr.name)];\n return names.filter((name: string) => this.wholeScopeModesOf(name, loaded) !== undefined);\n }\n\n private committedModeOf(rule: string, loaded: LoadedConfig): string | undefined {\n const match = loaded.matchRules.find((mr: MatchRuleConfig) => mr.name === rule);\n if (match !== undefined) return match.mode;\n const configured = loaded.rulesConfig[rule as keyof typeof loaded.rulesConfig] as BaseRuleConfig | undefined;\n return configured?.mode;\n }\n\n private projectNames(workspaceRoot: string): string[] {\n return new ProjectCatalog(new DiffScope()).all(workspaceRoot).map((p: ProjectEntry) => p.name).sort();\n }\n\n /** The match-rules, with the debugged one (if it is a match rule) overridden. */\n private matchRules(loaded: LoadedConfig, plan: DebugPlan | undefined): MatchRuleConfig[] {\n return loaded.matchRules.map((mr: MatchRuleConfig) => (plan?.rule === mr.name ? this.overridden(mr, plan) : mr));\n }\n\n /** A copy of `config` at the plan's mode with both escape hatches cleared. The original is untouched. */\n private overridden<C extends BaseRuleConfig>(config: C, plan: DebugPlan): C {\n const copy = Object.assign(Object.create(Object.getPrototypeOf(config) as object) as C, config);\n copy.mode = plan.mode;\n copy.turnOffRuleUntilEpoch = 0;\n copy.turnOffRuleWhileOnBranch = null;\n return copy;\n }\n\n private printBanner(plan: DebugPlan): void {\n console.log('');\n console.log(`🔍 DEBUG RUN of ${plan.rule} — NOT the gate. webpieces.config.json is unchanged and nothing is written.`);\n console.log(` Mode: ${plan.mode} (committed: ${plan.committedMode})` +\n ` · Projects: ${plan.projects === undefined ? 'every project' : plan.projects.join(', ')}` +\n ' · escape hatches (turnOffRuleUntilEpoch / turnOffRuleWhileOnBranch) ignored for this run');\n }\n\n /** Print one count per project and return the total. */\n private printCounts(workspaceRoot: string, plan: DebugPlan, scan: ScanScope, result: ExecutorResult): number {\n const counts = scan.countsByProject(workspaceRoot);\n const names = plan.projects ?? Array.from(counts.keys()).sort();\n const total = Array.from(counts.values()).reduce((sum: number, n: number) => sum + n, 0);\n console.log('');\n console.log(`🔍 ${plan.rule} at ${plan.mode}: ${total} site(s) left`);\n for (const name of names) console.log(` ${name}: ${counts.get(name) ?? 0}`);\n if (!result.success && total === 0) {\n console.log(' (the rule failed without reporting sites — read its output above)');\n }\n console.log('');\n return total;\n }\n}\n"]}
1
+ {"version":3,"file":"code-rules-bootstrap.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-bootstrap.ts"],"names":[],"mappings":";;;AAAA,4BAA0B;AAC1B,yCAAsC;AACtC,0DAAuJ;AACvJ,8DAA0D;AAG1D,qDAAgD;AAChD,6DAAuE;AACvE,uEAA2E;AAC3E,qEAA8E;AAC9E,6CAAwF;AAExF,0GAA0G;AAC1G,MAAM,SAAS;IAEE;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,IAAY,EACZ,aAAqB,EACrB,QAAuC;QAHvC,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QACZ,kBAAa,GAAb,aAAa,CAAQ;QACrB,aAAQ,GAAR,QAAQ,CAA+B;IACjD,CAAC;CACP;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAa,kBAAkB;IAC3B,KAAK,CAAC,GAAG,CAAC,aAAqB,EAAE,OAA4B;QACzD,MAAM,MAAM,GAAG,IAAA,8BAAe,EAAC,aAAa,CAAC,CAAC;QAC9C,IAAI,MAAM,CAAC,UAAU,KAAK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uleConfig, DiffScope, LoadedConfig, MatchRuleConfig, MODIFIED_CODE_MODES, RULE_SCHEMAS, loadAndValidate } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\n\nimport { ExecutorResult } from './code-validator';\nimport { CodeRulesApp } from './code-rules-app';\nimport { WorkspaceRoot, MatchRulesHolder } from './code-rules-context';\nimport { CONFIG_BINDINGS, ConfigBinding } from './code-rules-config-table';\nimport { CodeRulesRunRequest, RuleSelection } from './code-rules-run-request';\nimport { ProjectCatalog, ProjectEntry, ScanRestriction, ScanScope } from './scan-scope';\n\n/** A validated debug run (#1027): the one rule, the mode it runs at, and the projects it is scoped to. */\nclass DebugPlan {\n constructor(\n readonly rule: string,\n readonly mode: string,\n readonly committedMode: string,\n readonly projects: readonly string[] | undefined,\n ) {}\n}\n\n/**\n * The ONE composition root of a code-rules run, shared by the `validate-code` nx executor and the\n * `wp-validate-code` bin so the two cannot drift. It binds the workspace root and every rule's config,\n * then resolves {@link CodeRulesApp} so inversify builds the whole validator DAG.\n *\n * A DEBUG run (#1027 — any of `--rule` / `--mode` / `--projects`) differs from the gate in exactly four\n * ways, all in memory: only the named rule runs; its mode is replaced when `--mode` is given; its two\n * escape hatches are cleared (the question asked is \"what is left?\", which a time-boxed OFF must not\n * hide); and every rule reads its files through a {@link ScanRestriction} naming the projects. Nothing\n * is written — webpieces.config.json is untouched, so the gate keeps honouring the committed mode. It\n * prints the rule's own failure text, then one count per project, and fails when any site exists.\n *\n * A request it cannot run (no config, an unknown rule or project, --mode without --rule) THROWS an\n * {@link InformAiError} naming the cure; the bin's and the executor's top-level handlers print it.\n */\nexport class CodeRulesBootstrap {\n async run(workspaceRoot: string, request: CodeRulesRunRequest): Promise<ExecutorResult> {\n const loaded = loadAndValidate(workspaceRoot);\n if (loaded.configPath === null) {\n throw new InformAiError('No webpieces.config.json found at workspace root (or any ancestor).');\n }\n console.log(`\\n📄 Loaded config: ${loaded.configPath}`);\n\n const plan = request.isDebug() ? this.plan(workspaceRoot, loaded, request) : undefined;\n if (plan !== undefined) this.printBanner(plan);\n\n // autobind self-binds every @injectable(Singleton) tooling class (replaces the buildProviderModule registry scan)\n const container = new Container({ autobind: true });\n container.bind(WorkspaceRoot).toConstantValue(new WorkspaceRoot(workspaceRoot));\n container.bind(MatchRulesHolder).toConstantValue(new MatchRulesHolder(this.matchRules(loaded, plan)));\n container.bind(RuleSelection).toConstantValue(new RuleSelection(plan?.rule));\n container.bind(ScanRestriction).toConstantValue(new ScanRestriction(plan?.projects));\n for (const binding of CONFIG_BINDINGS) {\n const ConfigClass = binding[0];\n const configured = loaded.rulesConfig[binding[1]] as BaseRuleConfig | undefined;\n const config = configured ?? new ConfigClass();\n container.bind(ConfigClass).toConstantValue(plan?.rule === binding[1] ? this.overridden(config, plan) : config);\n }\n\n const result = await container.get(CodeRulesApp).run();\n if (plan === undefined) return result;\n // A debug run FAILS whenever a site exists — including a rule that only warns at the gate\n // (no-client-creation-outside-server-or-client at severity \"warn\") — so it can gate a loop.\n const sites = this.printCounts(workspaceRoot, plan, container.get(ScanScope), result);\n return { success: result.success && sites === 0 };\n }\n\n /** Validate a debug request against the loaded config and the repo's projects; throws on a refusal. */\n private plan(workspaceRoot: string, loaded: LoadedConfig, request: CodeRulesRunRequest): DebugPlan {\n const rule = request.rule;\n if (rule === undefined) throw this.refusal('--mode and --projects need --rule=<name>: a debug run judges exactly one rule.');\n const modes = this.wholeScopeModesOf(rule, loaded);\n if (modes === undefined) {\n throw this.refusal(`--rule=${rule} is not a code rule that supports a debug run. Rules that do (they offer ` +\n `MODIFIED_PROJECTS and RUN_EVERY_TIME): ${this.debuggableRules(loaded).join(', ')}.`);\n }\n const committedMode = this.committedModeOf(rule, loaded) ?? 'OFF';\n const mode = request.mode ?? committedMode;\n if (!modes.includes(mode) || mode === 'OFF') {\n const why = request.mode === undefined ? `its committed mode is ${committedMode}` : `--mode=${mode} is not one of its modes`;\n throw this.refusal(`${rule} cannot run: ${why}. Pass --mode=<one of ${modes.filter((m: string) => m !== 'OFF').join(', ')}>.`);\n }\n const unknown = (request.projects ?? []).filter((name: string) => !this.projectNames(workspaceRoot).includes(name));\n if (unknown.length > 0) {\n throw this.refusal(`--projects names no such nx project: ${unknown.join(', ')}. Known projects: ` +\n `${this.projectNames(workspaceRoot).join(', ')}.`);\n }\n return new DebugPlan(rule, mode, committedMode, request.projects);\n }\n\n private refusal(reason: string): InformAiError {\n return new InformAiError(`[debug run] ${reason}`);\n }\n\n /** The mode set of a rule that reads its files through ScanScope, or undefined for any other rule. */\n private wholeScopeModesOf(rule: string, loaded: LoadedConfig): readonly string[] | undefined {\n if (loaded.matchRules.some((mr: MatchRuleConfig) => mr.name === rule)) return MODIFIED_CODE_MODES;\n if (!CONFIG_BINDINGS.some((binding: ConfigBinding) => binding[1] === rule)) return undefined;\n const modes = RULE_SCHEMAS[rule]?.['mode']?.enumValues ?? [];\n return modes.includes('MODIFIED_PROJECTS') && modes.includes('RUN_EVERY_TIME') ? modes : undefined;\n }\n\n private debuggableRules(loaded: LoadedConfig): string[] {\n const builtIns = CONFIG_BINDINGS.map((binding: ConfigBinding) => binding[1] as string);\n const names = [...builtIns, ...loaded.matchRules.map((mr: MatchRuleConfig) => mr.name)];\n return names.filter((name: string) => this.wholeScopeModesOf(name, loaded) !== undefined);\n }\n\n private committedModeOf(rule: string, loaded: LoadedConfig): string | undefined {\n const match = loaded.matchRules.find((mr: MatchRuleConfig) => mr.name === rule);\n if (match !== undefined) return match.mode;\n const configured = loaded.rulesConfig[rule as keyof typeof loaded.rulesConfig] as BaseRuleConfig | undefined;\n return configured?.mode;\n }\n\n private projectNames(workspaceRoot: string): string[] {\n return new ProjectCatalog(new DiffScope()).all(workspaceRoot).map((p: ProjectEntry) => p.name).sort();\n }\n\n /** The match-rules, with the debugged one (if it is a match rule) overridden. */\n private matchRules(loaded: LoadedConfig, plan: DebugPlan | undefined): MatchRuleConfig[] {\n return loaded.matchRules.map((mr: MatchRuleConfig) => (plan?.rule === mr.name ? this.overridden(mr, plan) : mr));\n }\n\n /** A copy of `config` at the plan's mode with both escape hatches cleared. The original is untouched. */\n private overridden<C extends BaseRuleConfig>(config: C, plan: DebugPlan): C {\n const copy = Object.assign(Object.create(Object.getPrototypeOf(config) as object) as C, config);\n copy.mode = plan.mode;\n copy.turnOffRuleUntilEpoch = 0;\n copy.turnOffRuleWhileOnBranch = null;\n return copy;\n }\n\n private printBanner(plan: DebugPlan): void {\n console.log('');\n console.log(`🔍 DEBUG RUN of ${plan.rule} — NOT the gate. webpieces.config.json is unchanged and nothing is written.`);\n console.log(` Mode: ${plan.mode} (committed: ${plan.committedMode})` +\n ` · Projects: ${plan.projects === undefined ? 'every project' : plan.projects.join(', ')}` +\n ' · escape hatches (turnOffRuleUntilEpoch / turnOffRuleWhileOnBranch) ignored for this run');\n }\n\n /** Print one count per project and return the total. */\n private printCounts(workspaceRoot: string, plan: DebugPlan, scan: ScanScope, result: ExecutorResult): number {\n const counts = scan.countsByProject(workspaceRoot);\n const names = plan.projects ?? Array.from(counts.keys()).sort();\n const total = Array.from(counts.values()).reduce((sum: number, n: number) => sum + n, 0);\n console.log('');\n console.log(`🔍 ${plan.rule} at ${plan.mode}: ${total} site(s) left`);\n for (const name of names) console.log(` ${name}: ${counts.get(name) ?? 0}`);\n if (!result.success && total === 0) {\n console.log(' (the rule failed without reporting sites — read its output above)');\n }\n console.log('');\n return total;\n }\n}\n"]}
@@ -15,7 +15,7 @@ exports.ProjectRoleResolver = void 0;
15
15
  const tslib_1 = require("tslib");
16
16
  const fs = tslib_1.__importStar(require("fs"));
17
17
  const path = tslib_1.__importStar(require("path"));
18
- const rules_config_1 = require("@webpieces/rules-config");
18
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
19
19
  const inversify_1 = require("inversify");
20
20
  const ROLE_TAG_PREFIX = 'role:';
21
21
  let ProjectRoleResolver = class ProjectRoleResolver {
@@ -58,7 +58,7 @@ let ProjectRoleResolver = class ProjectRoleResolver {
58
58
  return null;
59
59
  }
60
60
  catch (err) {
61
- const error = (0, rules_config_1.toError)(err);
61
+ const error = (0, to_error_1.toError)(err);
62
62
  void error; // swallow — malformed project.json is not this resolver's concern
63
63
  return null;
64
64
  }
@@ -1 +1 @@
1
- {"version":3,"file":"project-role-resolver.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/project-role-resolver.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAkD;AAClD,yCAA2D;AAE3D,MAAM,eAAe,GAAG,OAAO,CAAC;AAMzB,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAC5B,wFAAwF;IACxF,MAAM,CAAC,aAAqB,EAAE,OAAe;QACzC,MAAM,eAAe,GAAG,IAAI,CAAC,qBAAqB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;QAC3E,IAAI,eAAe,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QAC1C,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,eAAe,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,kGAAkG;IAC1F,qBAAqB,CAAC,aAAqB,EAAE,OAAe;QAChE,IAAI,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAChC,OAAO,IAAI,EAAE,CAAC;YACV,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;YACjD,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC,EAAE,CAAC;gBACrD,OAAO,SAAS,CAAC;YACrB,CAAC;YACD,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACjC,IAAI,MAAM,KAAK,GAAG,IAAI,GAAG,KAAK,GAAG,IAAI,GAAG,KAAK,EAAE,EAAE,CAAC;gBAC9C,OAAO,IAAI,CAAC;YAChB,CAAC;YACD,GAAG,GAAG,MAAM,CAAC;QACjB,CAAC;IACL,CAAC;IAED;4EACwE;IAChE,QAAQ,CAAC,QAAgB;QAC7B,8DAA8D;QAC9D,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAmB,CAAC;YAChF,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3D,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;gBACrB,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,eAAe,CAAC;oBAAE,SAAS;gBAC1E,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;gBACvD,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;oBAAE,OAAO,KAAK,CAAC;YACvC,CAAC;YACD,OAAO,IAAI,CAAC;QAChB,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,kEAAkE;YAC9E,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ,CAAA;AA3CY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,mBAAmB,CA2C/B","sourcesContent":["/**\n * Resolves the `role:` nx tag VALUE of the project owning a given source file.\n *\n * The role-tag rule ({@link ../tag-rule}) only checks a `role:` tag is PRESENT; a few rules\n * (e.g. no-client-creation-outside-server-or-client) additionally need the tag's VALUE to decide\n * whether a construct is allowed in that kind of project. This is the single home for that lookup:\n * walk up from the file to its nearest `project.json`, read its `tags`, and return the first\n * `role:<value>` value (or null when the file belongs to no project, or its project carries no role).\n *\n * Injectable so it composes into the code-rules DI DAG and can be shared by any validator.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { toError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nconst ROLE_TAG_PREFIX = 'role:';\n\n/** The only field of a project.json this resolver reads. */\ntype RawProjectJson = { tags?: string[] };\n\n@injectable(bindingScopeValues.Singleton)\nexport class ProjectRoleResolver {\n /** The `role:` value of the project owning `relFile`, or null when unknown/untagged. */\n roleOf(workspaceRoot: string, relFile: string): string | null {\n const projectJsonPath = this.findOwningProjectJson(workspaceRoot, relFile);\n if (projectJsonPath === null) return null;\n return this.readRole(path.join(workspaceRoot, projectJsonPath));\n }\n\n /** Nearest ancestor directory of `relFile` that holds a project.json (repo-relative), or null. */\n private findOwningProjectJson(workspaceRoot: string, relFile: string): string | null {\n let dir = path.dirname(relFile);\n while (true) {\n const candidate = path.join(dir, 'project.json');\n if (fs.existsSync(path.join(workspaceRoot, candidate))) {\n return candidate;\n }\n const parent = path.dirname(dir);\n if (parent === dir || dir === '.' || dir === '') {\n return null;\n }\n dir = parent;\n }\n }\n\n /** First `role:<value>` tag value in a project.json, or null. Never throws — a malformed\n * project.json is the role-tag rule's concern, not this resolver's. */\n private readRole(fullPath: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RawProjectJson;\n const tags = Array.isArray(parsed.tags) ? parsed.tags : [];\n for (const tag of tags) {\n if (typeof tag !== 'string' || !tag.startsWith(ROLE_TAG_PREFIX)) continue;\n const value = tag.slice(ROLE_TAG_PREFIX.length).trim();\n if (value.length > 0) return value;\n }\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — malformed project.json is not this resolver's concern\n return null;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"project-role-resolver.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/project-role-resolver.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,iEAA6D;AAC7D,yCAA2D;AAE3D,MAAM,eAAe,GAAG,OAAO,CAAC;AAMzB,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAC5B,wFAAwF;IACxF,MAAM,CAAC,aAAqB,EAAE,OAAe;QACzC,MAAM,eAAe,GAAG,IAAI,CAAC,qBAAqB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;QAC3E,IAAI,eAAe,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QAC1C,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,eAAe,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,kGAAkG;IAC1F,qBAAqB,CAAC,aAAqB,EAAE,OAAe;QAChE,IAAI,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAChC,OAAO,IAAI,EAAE,CAAC;YACV,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;YACjD,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC,EAAE,CAAC;gBACrD,OAAO,SAAS,CAAC;YACrB,CAAC;YACD,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACjC,IAAI,MAAM,KAAK,GAAG,IAAI,GAAG,KAAK,GAAG,IAAI,GAAG,KAAK,EAAE,EAAE,CAAC;gBAC9C,OAAO,IAAI,CAAC;YAChB,CAAC;YACD,GAAG,GAAG,MAAM,CAAC;QACjB,CAAC;IACL,CAAC;IAED;4EACwE;IAChE,QAAQ,CAAC,QAAgB;QAC7B,8DAA8D;QAC9D,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAmB,CAAC;YAChF,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3D,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;gBACrB,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,eAAe,CAAC;oBAAE,SAAS;gBAC1E,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;gBACvD,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;oBAAE,OAAO,KAAK,CAAC;YACvC,CAAC;YACD,OAAO,IAAI,CAAC;QAChB,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,kEAAkE;YAC9E,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ,CAAA;AA3CY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,mBAAmB,CA2C/B","sourcesContent":["/**\n * Resolves the `role:` nx tag VALUE of the project owning a given source file.\n *\n * The role-tag rule ({@link ../tag-rule}) only checks a `role:` tag is PRESENT; a few rules\n * (e.g. no-client-creation-outside-server-or-client) additionally need the tag's VALUE to decide\n * whether a construct is allowed in that kind of project. This is the single home for that lookup:\n * walk up from the file to its nearest `project.json`, read its `tags`, and return the first\n * `role:<value>` value (or null when the file belongs to no project, or its project carries no role).\n *\n * Injectable so it composes into the code-rules DI DAG and can be shared by any validator.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nconst ROLE_TAG_PREFIX = 'role:';\n\n/** The only field of a project.json this resolver reads. */\ntype RawProjectJson = { tags?: string[] };\n\n@injectable(bindingScopeValues.Singleton)\nexport class ProjectRoleResolver {\n /** The `role:` value of the project owning `relFile`, or null when unknown/untagged. */\n roleOf(workspaceRoot: string, relFile: string): string | null {\n const projectJsonPath = this.findOwningProjectJson(workspaceRoot, relFile);\n if (projectJsonPath === null) return null;\n return this.readRole(path.join(workspaceRoot, projectJsonPath));\n }\n\n /** Nearest ancestor directory of `relFile` that holds a project.json (repo-relative), or null. */\n private findOwningProjectJson(workspaceRoot: string, relFile: string): string | null {\n let dir = path.dirname(relFile);\n while (true) {\n const candidate = path.join(dir, 'project.json');\n if (fs.existsSync(path.join(workspaceRoot, candidate))) {\n return candidate;\n }\n const parent = path.dirname(dir);\n if (parent === dir || dir === '.' || dir === '') {\n return null;\n }\n dir = parent;\n }\n }\n\n /** First `role:<value>` tag value in a project.json, or null. Never throws — a malformed\n * project.json is the role-tag rule's concern, not this resolver's. */\n private readRole(fullPath: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RawProjectJson;\n const tags = Array.isArray(parsed.tags) ? parsed.tags : [];\n for (const tag of tags) {\n if (typeof tag !== 'string' || !tag.startsWith(ROLE_TAG_PREFIX)) continue;\n const value = tag.slice(ROLE_TAG_PREFIX.length).trim();\n if (value.length > 0) return value;\n }\n return null;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — malformed project.json is not this resolver's concern\n return null;\n }\n }\n}\n"]}
@@ -15,6 +15,8 @@ const tslib_1 = require("tslib");
15
15
  const fs = tslib_1.__importStar(require("fs"));
16
16
  const path = tslib_1.__importStar(require("path"));
17
17
  const rules_config_1 = require("@webpieces/rules-config");
18
+ const tooling_common_1 = require("@webpieces/tooling-common");
19
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
18
20
  const inversify_1 = require("inversify");
19
21
  const scan_scope_1 = require("./scan-scope");
20
22
  const FRAMEWORK_TAG_PREFIX = 'framework:';
@@ -56,7 +58,7 @@ let ProjectScanTargets = class ProjectScanTargets {
56
58
  touched(workspaceRoot, all, ruleName) {
57
59
  const range = this.diffScope.resolveBase(workspaceRoot);
58
60
  if (range.base === undefined) {
59
- throw new rules_config_1.InformAiError(`${ruleName} could not determine the comparison base for MODIFIED_PROJECTS. Set NX_BASE to the ` +
61
+ throw new tooling_common_1.InformAiError(`${ruleName} could not determine the comparison base for MODIFIED_PROJECTS. Set NX_BASE to the ` +
60
62
  'base branch or commit and retry.');
61
63
  }
62
64
  const dirs = new Set();
@@ -82,8 +84,8 @@ let ProjectScanTargets = class ProjectScanTargets {
82
84
  return Array.from(new Set(values));
83
85
  }
84
86
  catch (err) {
85
- const error = (0, rules_config_1.toError)(err);
86
- throw new rules_config_1.InformAiError(`Cannot read framework tags from ${file} — fix project.json and retry.`, {
87
+ const error = (0, to_error_1.toError)(err);
88
+ throw new tooling_common_1.InformAiError(`Cannot read framework tags from ${file} — fix project.json and retry.`, {
87
89
  cause: error,
88
90
  });
89
91
  }
@@ -1 +1 @@
1
- {"version":3,"file":"project-scan-targets.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/project-scan-targets.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA6F;AAC7F,yCAA2D;AAC3D,6CAA6E;AAE7E,MAAM,oBAAoB,GAAG,YAAY,CAAC;AAK1C,iEAAiE;AACjE,MAAa,cAAc;IAEV;IAEA;IAEA;IALb,YACa,IAAY;IACrB,uDAAuD;IAC9C,GAAW;IACpB,6FAA6F;IACpF,UAA6B;QAJ7B,SAAI,GAAJ,IAAI,CAAQ;QAEZ,QAAG,GAAH,GAAG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AAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3D,MAAM,MAAM,GAAG,IAAI;iBACd,MAAM,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,UAAU,CAAC,oBAAoB,CAAC,CAAC;iBACxF,GAAG,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;iBACnE,MAAM,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACjD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,MAAM,IAAI,4BAAa,CAAC,mCAAmC,IAAI,gCAAgC,EAAE;gBAC7F,KAAK,EAAE,KAAK;aACf,CAAC,CAAC;QACP,CAAC;IACL,CAAC;CACJ,CAAA;AAtDY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGL,wBAAS;QACX,2BAAc;QACV,4BAAe;GAJxC,kBAAkB,CAsD9B","sourcesContent":["/**\n * Which PROJECTS a project-scoped rule judges — the two tag-truth code rules (#1064),\n * `framework-tsconfig` and `framework-packages` — and the `framework:` tags each carries.\n *\n * MODIFIED_PROJECTS — every project owning a changed file (any file, not only .ts: a project.json or\n * tsconfig edit is exactly what these rules judge)\n * RUN_EVERY_TIME — every project in the repo, every run (the migration sweep)\n *\n * The per-run `--projects` restriction of the debug run (#1027) narrows both.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { DiffScope, InformAiError, ProjectScanMode, toError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ProjectCatalog, ProjectEntry, ScanRestriction } from './scan-scope';\n\nconst FRAMEWORK_TAG_PREFIX = 'framework:';\n\n/** The only field of a project.json this reads. */\ntype RawProjectTags = { tags?: string[] };\n\n/** One project to judge and its framework env set. Data-only. */\nexport class ScannedProject {\n constructor(\n readonly name: string,\n /** Repo-relative, '/'-separated, no trailing slash. */\n readonly dir: string,\n /** The `framework:` tag values, in declaration order, de-duplicated. Empty when untagged. */\n readonly frameworks: readonly string[],\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ProjectScanTargets {\n constructor(\n private readonly diffScope: DiffScope,\n private readonly catalog: ProjectCatalog,\n private readonly restriction: ScanRestriction,\n ) {}\n\n /** The projects `mode` judges, root project excluded. `mode` must not be OFF. */\n projects(workspaceRoot: string, mode: ProjectScanMode, ruleName: string): ScannedProject[] {\n const all = this.catalog.all(workspaceRoot).filter((p: ProjectEntry) => p.dir !== '');\n const chosen = mode === 'RUN_EVERY_TIME' ? all : this.touched(workspaceRoot, all, ruleName);\n const names = this.restriction.projectNames;\n const restricted = names === undefined ? chosen : chosen.filter((p: ProjectEntry) => names.includes(p.name));\n return restricted\n .map((p: ProjectEntry) => new ScannedProject(p.name, p.dir, this.frameworksOf(workspaceRoot, p.dir)))\n .sort((a: ScannedProject, b: ScannedProject) => a.dir.localeCompare(b.dir));\n }\n\n private touched(workspaceRoot: string, all: ProjectEntry[], ruleName: string): ProjectEntry[] {\n const range = this.diffScope.resolveBase(workspaceRoot);\n if (range.base === undefined) {\n throw new InformAiError(\n `${ruleName} could not determine the comparison base for MODIFIED_PROJECTS. Set NX_BASE to the ` +\n 'base branch or commit and retry.',\n );\n }\n const dirs = new Set<string>();\n for (const file of this.diffScope.getChangedFiles(workspaceRoot, range.base, range.head, { tsOnly: false })) {\n const owner = this.catalog.ownerOf(workspaceRoot, file);\n if (owner !== undefined) dirs.add(owner.dir);\n }\n return all.filter((p: ProjectEntry) => dirs.has(p.dir));\n }\n\n /** The `framework:` values of a project.json. Unreadable JSON is the plumbing error it is. */\n private frameworksOf(workspaceRoot: string, dir: string): string[] {\n const file = path.join(workspaceRoot, dir, 'project.json');\n // webpieces-disable no-unmanaged-exceptions -- add the exact project.json path while preserving the parse/read failure as cause\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf-8')) as RawProjectTags;\n const tags = Array.isArray(parsed.tags) ? parsed.tags : [];\n const values = tags\n .filter((tag: string) => typeof tag === 'string' && tag.startsWith(FRAMEWORK_TAG_PREFIX))\n .map((tag: string) => tag.slice(FRAMEWORK_TAG_PREFIX.length).trim())\n .filter((value: string) => value.length > 0);\n return Array.from(new Set(values));\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot read framework tags from ${file} — fix project.json and retry.`, {\n cause: error,\n });\n }\n }\n}\n"]}
1
+ {"version":3,"file":"project-scan-targets.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/project-scan-targets.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAqE;AACrE,8DAA0D;AAC1D,iEAA6D;AAC7D,yCAA2D;AAC3D,6CAA6E;AAE7E,MAAM,oBAAoB,GAAG,YAAY,CAAC;AAK1C,iEAAiE;AACjE,MAAa,cAAc;IAEV;IAEA;IAEA;IALb,YACa,IAAY;IACrB,uDAAuD;IAC9C,GAAW;IACpB,6FAA6F;IACpF,UAA6B;QAJ7B,SAAI,GAAJ,IAAI,CAAQ;QAEZ,QAAG,GAAH,GAAG,CAAQ;QAEX,eAAU,GAAV,UAAU,CAAmB;IACvC,CAAC;CACP;AARD,wCAQC;AAGM,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAEN;IACA;IACA;IAHrB,YACqB,SAAoB,EACpB,OAAuB,EACvB,WAA4B;Q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GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,UAAU,CAAC,oBAAoB,CAAC,CAAC;iBACxF,GAAG,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;iBACnE,MAAM,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACjD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,MAAM,IAAI,8BAAa,CAAC,mCAAmC,IAAI,gCAAgC,EAAE;gBAC7F,KAAK,EAAE,KAAK;aACf,CAAC,CAAC;QACP,CAAC;IACL,CAAC;CACJ,CAAA;AAtDY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGL,wBAAS;QACX,2BAAc;QACV,4BAAe;GAJxC,kBAAkB,CAsD9B","sourcesContent":["/**\n * Which PROJECTS a project-scoped rule judges — the two tag-truth code rules (#1064),\n * `framework-tsconfig` and `framework-packages` — and the `framework:` tags each carries.\n *\n * MODIFIED_PROJECTS — every project owning a changed file (any file, not only .ts: a project.json or\n * tsconfig edit is exactly what these rules judge)\n * RUN_EVERY_TIME — every project in the repo, every run (the migration sweep)\n *\n * The per-run `--projects` restriction of the debug run (#1027) narrows both.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { DiffScope, ProjectScanMode } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ProjectCatalog, ProjectEntry, ScanRestriction } from './scan-scope';\n\nconst FRAMEWORK_TAG_PREFIX = 'framework:';\n\n/** The only field of a project.json this reads. */\ntype RawProjectTags = { tags?: string[] };\n\n/** One project to judge and its framework env set. Data-only. */\nexport class ScannedProject {\n constructor(\n readonly name: string,\n /** Repo-relative, '/'-separated, no trailing slash. */\n readonly dir: string,\n /** The `framework:` tag values, in declaration order, de-duplicated. Empty when untagged. */\n readonly frameworks: readonly string[],\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ProjectScanTargets {\n constructor(\n private readonly diffScope: DiffScope,\n private readonly catalog: ProjectCatalog,\n private readonly restriction: ScanRestriction,\n ) {}\n\n /** The projects `mode` judges, root project excluded. `mode` must not be OFF. */\n projects(workspaceRoot: string, mode: ProjectScanMode, ruleName: string): ScannedProject[] {\n const all = this.catalog.all(workspaceRoot).filter((p: ProjectEntry) => p.dir !== '');\n const chosen = mode === 'RUN_EVERY_TIME' ? all : this.touched(workspaceRoot, all, ruleName);\n const names = this.restriction.projectNames;\n const restricted = names === undefined ? chosen : chosen.filter((p: ProjectEntry) => names.includes(p.name));\n return restricted\n .map((p: ProjectEntry) => new ScannedProject(p.name, p.dir, this.frameworksOf(workspaceRoot, p.dir)))\n .sort((a: ScannedProject, b: ScannedProject) => a.dir.localeCompare(b.dir));\n }\n\n private touched(workspaceRoot: string, all: ProjectEntry[], ruleName: string): ProjectEntry[] {\n const range = this.diffScope.resolveBase(workspaceRoot);\n if (range.base === undefined) {\n throw new InformAiError(\n `${ruleName} could not determine the comparison base for MODIFIED_PROJECTS. Set NX_BASE to the ` +\n 'base branch or commit and retry.',\n );\n }\n const dirs = new Set<string>();\n for (const file of this.diffScope.getChangedFiles(workspaceRoot, range.base, range.head, { tsOnly: false })) {\n const owner = this.catalog.ownerOf(workspaceRoot, file);\n if (owner !== undefined) dirs.add(owner.dir);\n }\n return all.filter((p: ProjectEntry) => dirs.has(p.dir));\n }\n\n /** The `framework:` values of a project.json. Unreadable JSON is the plumbing error it is. */\n private frameworksOf(workspaceRoot: string, dir: string): string[] {\n const file = path.join(workspaceRoot, dir, 'project.json');\n // webpieces-disable no-unmanaged-exceptions -- add the exact project.json path while preserving the parse/read failure as cause\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf-8')) as RawProjectTags;\n const tags = Array.isArray(parsed.tags) ? parsed.tags : [];\n const values = tags\n .filter((tag: string) => typeof tag === 'string' && tag.startsWith(FRAMEWORK_TAG_PREFIX))\n .map((tag: string) => tag.slice(FRAMEWORK_TAG_PREFIX.length).trim())\n .filter((value: string) => value.length > 0);\n return Array.from(new Set(values));\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot read framework tags from ${file} — fix project.json and retry.`, {\n cause: error,\n });\n }\n }\n}\n"]}
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RuleReporter = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const rules_config_1 = require("@webpieces/rules-config");
6
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
6
7
  const inversify_1 = require("inversify");
7
8
  /**
8
9
  * Runs the active validators with per-validator isolation and prints failures for humans/CI.
@@ -31,7 +32,7 @@ let RuleReporter = class RuleReporter {
31
32
  anyFailed = true;
32
33
  }
33
34
  catch (err) {
34
- const error = (0, rules_config_1.toError)(err);
35
+ const error = (0, to_error_1.toError)(err);
35
36
  if (error instanceof rules_config_1.RuleFailError) {
36
37
  this.reportRuleFail(error);
37
38
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rule-reporter.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/rule-reporter.ts"],"names":[],"mappings":";;;;AAAA,0DAAmF;AACnF,yCAA2D;AAI3D;;GAEG;AAEI,IAAM,YAAY,GAAlB,MAAM,YAAY;IACrB;;;;;;;;;;;;OAYG;IACH,KAAK,CAAC,aAAa,CAAC,IAAwB;QACxC,IAAI,SAAS,GAAG,KAAK,CAAC;QACtB,KAAK,MAAM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C,EAAE,CAAC,CAAC;IACtB,CAAC;IAED,kGAAkG;IAClG,+DAA+D;IACvD,WAAW,CAAC,IAAY,EAAE,KAAY;QAC1C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,gBAAgB,IAAI,cAAc,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACjE,OAAO,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAC;QAC9E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtB,CAAC;CACJ,CAAA;AA1DY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,YAAY,CA0DxB","sourcesContent":["import { RuleFailError, toError, formatFixOptions } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { RuleRun, ExecutorResult } from './code-validator';\n\n/**\n * Runs the active validators with per-validator isolation and prints failures for humans/CI.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class RuleReporter {\n /**\n * Run every {@link RuleRun} with per-run isolation: a run that throws — a `RuleFailError` (an\n * expected failure) OR a plain `Error` (a bug) — is caught, reported, and marks the whole run\n * failed, but the remaining runs STILL execute. One validator can no longer abort the CI run.\n *\n * LEGACY, and still a back-compat shim: a run that reports its own failure by returning\n * `{ success: false }` (usually after `console.error`-ing its own banner) still flips the\n * aggregate. That is a SECOND spelling of \"this validator failed\" and it is scheduled for\n * deletion, not blessed — the one spelling is to THROW a `RuleFailError` carrying `Option[]`\n * cures, so this reporter renders it for the build-time audience. Removing the shim means\n * `RuleRun.run` returning `Promise<void>` and `ExecutorResult` deleted (`code-validator.ts`);\n * it waits only on the ~22 validators under `src/validate-*.ts` still returning the boolean.\n */\n async runValidators(runs: readonly RuleRun[]): Promise<ExecutorResult> {\n let anyFailed = false;\n for (const item of runs) {\n // webpieces-disable no-unmanaged-exceptions -- per-run isolation chokepoint: one validator must never abort the rest\n try {\n const result = await item.run();\n if (!result.success) anyFailed = true;\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof RuleFailError) {\n this.reportRuleFail(error);\n } else {\n this.reportCrash(item.name, error);\n }\n anyFailed = true;\n }\n }\n return { success: !anyFailed };\n }\n\n // Human/CI console block for a validator that threw a RuleFailError. code-rules is developer-\n // facing, so it prints humanMessage (falls back to aiMessage inside RuleFailError when not set).\n private reportRuleFail(err: RuleFailError): void {\n console.error('');\n console.error(`❌ [${err.ruleName}] ${err.humanMessage}`);\n if (err.line !== undefined) {\n console.error(` L${String(err.line)}: ${err.snippet ?? ''}`);\n }\n // The \"Fix Option N:\"/\"(preferred)\" labels are framework-owned — same renderer the edit-time\n // report uses — so a validator never hand-numbers its cures inside its message string.\n for (const line of formatFixOptions(err.fixOptions, ' ')) {\n console.error(line);\n }\n console.error('');\n }\n\n // A validator that threw a plain Error is a BUG in the validator — surface it (don't swallow) and\n // keep going so it doesn't hide the other validators' results.\n private reportCrash(name: string, error: Error): void {\n console.error('');\n console.error(`❌ Validator '${name}' crashed: ${error.message}`);\n console.error(' (a bug in the validator — the other validators still ran)');\n console.error('');\n }\n}\n"]}
1
+ {"version":3,"file":"rule-reporter.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/rule-reporter.ts"],"names":[],"mappings":";;;;AAAA,0DAA0E;AAC1E,iEAA6D;AAC7D,yCAA2D;AAI3D;;GAEG;AAEI,IAAM,YAAY,GAAlB,MAAM,YAAY;IACrB;;;;;;;;;;;;OAYG;IACH,KAAK,CAAC,aAAa,CAAC,IAAwB;QACxC,IAAI,SAAS,GAAG,KAAK,CAAC;QACtB,KAAK,MAAM,IAAI,IAAI,IAAI,EAAE,CAAC;YACtB,qHAAqH;YACrH,IAAI,CAAC;gBACD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,GAAG,EAAE,CAAC;gBAChC,IAAI,CAAC,MAAM,CAAC,OAAO;oBAAE,SAAS,GAAG,IAAI,CAAC;YAC1C,CAAC;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C,OAAO,EAAE,CAAC,CAAC;QACjE,OAAO,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAC;QAC9E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtB,CAAC;CACJ,CAAA;AA1DY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,YAAY,CA0DxB","sourcesContent":["import { RuleFailError, formatFixOptions } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { RuleRun, ExecutorResult } from './code-validator';\n\n/**\n * Runs the active validators with per-validator isolation and prints failures for humans/CI.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class RuleReporter {\n /**\n * Run every {@link RuleRun} with per-run isolation: a run that throws — a `RuleFailError` (an\n * expected failure) OR a plain `Error` (a bug) — is caught, reported, and marks the whole run\n * failed, but the remaining runs STILL execute. One validator can no longer abort the CI run.\n *\n * LEGACY, and still a back-compat shim: a run that reports its own failure by returning\n * `{ success: false }` (usually after `console.error`-ing its own banner) still flips the\n * aggregate. That is a SECOND spelling of \"this validator failed\" and it is scheduled for\n * deletion, not blessed — the one spelling is to THROW a `RuleFailError` carrying `Option[]`\n * cures, so this reporter renders it for the build-time audience. Removing the shim means\n * `RuleRun.run` returning `Promise<void>` and `ExecutorResult` deleted (`code-validator.ts`);\n * it waits only on the ~22 validators under `src/validate-*.ts` still returning the boolean.\n */\n async runValidators(runs: readonly RuleRun[]): Promise<ExecutorResult> {\n let anyFailed = false;\n for (const item of runs) {\n // webpieces-disable no-unmanaged-exceptions -- per-run isolation chokepoint: one validator must never abort the rest\n try {\n const result = await item.run();\n if (!result.success) anyFailed = true;\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof RuleFailError) {\n this.reportRuleFail(error);\n } else {\n this.reportCrash(item.name, error);\n }\n anyFailed = true;\n }\n }\n return { success: !anyFailed };\n }\n\n // Human/CI console block for a validator that threw a RuleFailError. code-rules is developer-\n // facing, so it prints humanMessage (falls back to aiMessage inside RuleFailError when not set).\n private reportRuleFail(err: RuleFailError): void {\n console.error('');\n console.error(`❌ [${err.ruleName}] ${err.humanMessage}`);\n if (err.line !== undefined) {\n console.error(` L${String(err.line)}: ${err.snippet ?? ''}`);\n }\n // The \"Fix Option N:\"/\"(preferred)\" labels are framework-owned — same renderer the edit-time\n // report uses — so a validator never hand-numbers its cures inside its message string.\n for (const line of formatFixOptions(err.fixOptions, ' ')) {\n console.error(line);\n }\n console.error('');\n }\n\n // A validator that threw a plain Error is a BUG in the validator — surface it (don't swallow) and\n // keep going so it doesn't hide the other validators' results.\n private reportCrash(name: string, error: Error): void {\n console.error('');\n console.error(`❌ Validator '${name}' crashed: ${error.message}`);\n console.error(' (a bug in the validator — the other validators still ran)');\n console.error('');\n }\n}\n"]}
package/src/scan-scope.js CHANGED
@@ -23,6 +23,8 @@ const tslib_1 = require("tslib");
23
23
  const fs = tslib_1.__importStar(require("fs"));
24
24
  const path = tslib_1.__importStar(require("path"));
25
25
  const rules_config_1 = require("@webpieces/rules-config");
26
+ const tooling_common_1 = require("@webpieces/tooling-common");
27
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
26
28
  const inversify_1 = require("inversify");
27
29
  /** One nx project: its name and its directory (repo-relative, '/'-separated, no trailing slash). */
28
30
  class ProjectEntry {
@@ -80,8 +82,8 @@ let ProjectCatalog = class ProjectCatalog {
80
82
  return typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : undefined;
81
83
  }
82
84
  catch (err) {
83
- const error = (0, rules_config_1.toError)(err);
84
- throw new rules_config_1.InformAiError(`Cannot read nx project identity from ${fullPath} — fix project.json and retry.`, {
85
+ const error = (0, to_error_1.toError)(err);
86
+ throw new tooling_common_1.InformAiError(`Cannot read nx project identity from ${fullPath} — fix project.json and retry.`, {
85
87
  cause: error,
86
88
  });
87
89
  }
@@ -1 +1 @@
1
- {"version":3,"file":"scan-scope.js","s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,CAgErB;AAED;;;GAGG;AACH,MAAa,aAAc,SAAQ,SAAS;IACxC;QACI,MAAM,SAAS,GAAG,IAAI,wBAAS,EAAE,CAAC;QAClC,KAAK,CAAC,SAAS,EAAE,IAAI,cAAc,CAAC,SAAS,CAAC,EAAE,IAAI,eAAe,CAAC,SAAS,CAAC,CAAC,CAAC;IACpF,CAAC;CACJ;AALD,sCAKC","sourcesContent":["/**\n * Which FILES a diff-scoped code rule judges, for every mode it offers — and the one place the per-run\n * `--projects` restriction of the debug run (#1027) is applied.\n *\n * NEW_AND_MODIFIED_CODE — the changed files (the rule then keeps only sites on changed lines)\n * NEW_AND_MODIFIED_FILES — the changed files, whole\n * MODIFIED_PROJECTS — every in-scope file of every project the diff touches, whole, plus the\n * changed files themselves (so it is never narrower than NEW_AND_MODIFIED_FILES)\n * RUN_EVERY_TIME — every in-scope file in the repo, whole, every run\n *\n * The two whole-scope modes are NEW_AND_MODIFIED_FILES over a bigger file set — the rule's own detection,\n * disable handling and failure text are untouched, which is what lets a debug run print exactly what the\n * gate would print. A rule asks {@link ScanScope.files} instead of `getChangedFiles`, and asks\n * {@link ScanScope.isLineScoped} instead of comparing its mode to NEW_AND_MODIFIED_CODE.\n *\n * Every rule that reads its files here also reports its sites through {@link ScanScope.recordSites}, so\n * the debug run can print a count per project without parsing any rule's output.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { ChangedFilesOptions, DiffScope, InformAiError, ModifiedCodeMode, toError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/** One nx project: its name and its directory (repo-relative, '/'-separated, no trailing slash). */\nexport class ProjectEntry {\n constructor(\n readonly name: string,\n readonly dir: string,\n ) {}\n}\n\n/** The only field of a project.json this catalog reads. */\ntype RawProjectName = { name?: string };\n\n/**\n * The repo's nx projects, found from the `project.json` files git knows about (tracked or untracked,\n * never ignored), and the owner lookup every whole-scope mode and `--projects` filter uses: a file\n * belongs to the DEEPEST project directory containing it.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProjectCatalog {\n private cachedRoot: string | undefined;\n private cached: ProjectEntry[] = [];\n\n constructor(private readonly diffScope: DiffScope) {}\n\n all(workspaceRoot: string): ProjectEntry[] {\n if (this.cachedRoot !== workspaceRoot) {\n this.cached = this.load(workspaceRoot);\n this.cachedRoot = workspaceRoot;\n }\n return this.cached;\n }\n\n /** The project owning `relFile`, or undefined when no project directory contains it. */\n ownerOf(workspaceRoot: string, relFile: string): ProjectEntry | undefined {\n const file = relFile.split(path.sep).join('/');\n let best: ProjectEntry | undefined;\n for (const project of this.all(workspaceRoot)) {\n const inside = project.dir === '' || file.startsWith(`${project.dir}/`);\n if (inside && (best === undefined || project.dir.length > best.dir.length)) best = project;\n }\n return best;\n }\n\n private load(workspaceRoot: string): ProjectEntry[] {\n const jsons = this.diffScope.getAllFiles(workspaceRoot, { tsOnly: false })\n .filter((f: string) => f === 'project.json' || f.endsWith('/project.json'));\n return jsons.map((rel: string) => {\n const dir = path.posix.dirname(rel) === '.' ? '' : path.posix.dirname(rel);\n return new ProjectEntry(this.readName(path.join(workspaceRoot, rel)) ?? path.posix.basename(dir), dir);\n });\n }\n\n private readName(fullPath: string): string | undefined {\n // webpieces-disable no-unmanaged-exceptions -- add the exact project.json path while preserving the parse/read failure as cause\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RawProjectName;\n return typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : undefined;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot read nx project identity from ${fullPath} — fix project.json and retry.`, {\n cause: error,\n });\n }\n }\n}\n\n/**\n * The per-run project restriction. Bound at the composition root: `undefined` for every normal run (the\n * gate), the `--projects` names for a debug run. Data-only.\n */\nexport class ScanRestriction {\n constructor(readonly projectNames: readonly string[] | undefined) {}\n}\n\n/** One recorded violating site: which rule, which file. Data-only. */\nexport class RecordedSite {\n constructor(\n readonly ruleName: string,\n readonly relFile: string,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ScanScope {\n private readonly sites: RecordedSite[] = [];\n\n constructor(\n private readonly diffScope: DiffScope,\n private readonly catalog: ProjectCatalog,\n private readonly restriction: ScanRestriction,\n ) {}\n\n /** True when the rule keeps only sites on changed lines; every other active mode judges whole files. */\n isLineScoped(mode: ModifiedCodeMode): boolean {\n return mode === 'NEW_AND_MODIFIED_CODE';\n }\n\n /**\n * The files a rule in `mode` judges, restricted to the debug run's `--projects` when there is one.\n * `opts` is passed through to the git listing (`tsOnly: false` for a rule that reads templates/CSS).\n */\n files(workspaceRoot: string, mode: ModifiedCodeMode, base: string, head: string | undefined, opts?: ChangedFilesOptions): string[] {\n return this.restrict(workspaceRoot, this.unrestricted(workspaceRoot, mode, base, head, opts));\n }\n\n /** Record every violating site a rule found, for the debug run's per-project count. */\n recordSites(ruleName: string, relFiles: readonly string[]): void {\n for (const relFile of relFiles) this.sites.push(new RecordedSite(ruleName, relFile));\n }\n\n /** Sites recorded so far, counted per owning project name (`(no project)` for a file outside one). */\n countsByProject(workspaceRoot: string): Map<string, number> {\n const counts = new Map<string, number>();\n for (const site of this.sites) {\n const name = this.catalog.ownerOf(workspaceRoot, site.relFile)?.name ?? '(no project)';\n counts.set(name, (counts.get(name) ?? 0) + 1);\n }\n return counts;\n }\n\n private unrestricted(workspaceRoot: string, mode: ModifiedCodeMode, base: string, head: string | undefined, opts?: ChangedFilesOptions): string[] {\n if (mode === 'RUN_EVERY_TIME') return this.diffScope.getAllFiles(workspaceRoot, opts);\n const changed = this.diffScope.getChangedFiles(workspaceRoot, base, head, opts);\n if (mode !== 'MODIFIED_PROJECTS') return changed;\n // A project is TOUCHED by any changed file it owns — not only the files this rule reads — so a\n // project.json or README edit counts, exactly as nx affected would see it.\n const touched = new Set<string>();\n for (const f of this.diffScope.getChangedFiles(workspaceRoot, base, head, { tsOnly: false })) {\n const owner = this.catalog.ownerOf(workspaceRoot, f);\n if (owner !== undefined) touched.add(owner.dir);\n }\n const inTouched = this.diffScope.getAllFiles(workspaceRoot, opts).filter((f: string) => {\n const owner = this.catalog.ownerOf(workspaceRoot, f);\n return owner !== undefined && touched.has(owner.dir);\n });\n return Array.from(new Set([...changed, ...inTouched]));\n }\n\n private restrict(workspaceRoot: string, files: string[]): string[] {\n const names = this.restriction.projectNames;\n if (names === undefined) return files;\n const wanted = new Set(names);\n return files.filter((f: string) => {\n const owner = this.catalog.ownerOf(workspaceRoot, f);\n return owner !== undefined && wanted.has(owner.name);\n });\n }\n}\n\n/**\n * The gate's {@link ScanScope} — the diff, no project restriction — for a caller that builds a validator\n * outside the DI container: the single-rule nx executors (`validate-no-any-unknown` and friends) and specs.\n */\nexport class GateScanScope extends ScanScope {\n constructor() {\n const diffScope = new DiffScope();\n super(diffScope, new ProjectCatalog(diffScope), new ScanRestriction(undefined));\n }\n}\n"]}
1
+ {"version":3,"file":"scan-scope.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/scan-scope.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA2F;AAC3F,8DAA0D;AAC1D,iEAA6D;AAC7D,yCAA2D;AAE3D,oGAAoG;AACpG,MAAa,YAAY;IAER;IACA;IAFb,YACa,IAAY,EACZ,GAAW;QADX,SAAI,GAAJ,IAAI,CAAQ;QACZ,QAAG,GAAH,GAAG,CAAQ;IACrB,CAAC;CACP;AALD,oCAKC;AAKD;;;;GAIG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAIM;IAHrB,UAAU,CAAqB;IAC/B,MAAM,GAAmB,EAAE,CAAC;IAEpC,YAA6B,SAAoB;QAApB,cAAS,GAAT,SAAS,CAAW;IAAG,CAAC;IAErD,GAAG,CAAC,aAAqB;QACrB,IAAI,IAAI,CAAC,UAAU,KAAK,aAAa,EAAE,CAAC;YACpC,IAAI,CAAC,MAAM,GAAG,I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,QAAQ,CAAC,aAAqB,EAAE,KAAe;QACnD,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC;QAC5C,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QACtC,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;QAC9B,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAS,EAAE,EAAE;YAC9B,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;YACrD,OAAO,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACzD,CAAC,CAAC,CAAC;IACP,CAAC;CACJ,CAAA;AAhEY,8BAAS;oBAAT,SAAS;IADrB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAKL,wBAAS;QACX,cAAc;QACV,eAAe;GANxC,SAAS,CAgErB;AAED;;;GAGG;AACH,MAAa,aAAc,SAAQ,SAAS;IACxC;QACI,MAAM,SAAS,GAAG,IAAI,wBAAS,EAAE,CAAC;QAClC,KAAK,CAAC,SAAS,EAAE,IAAI,cAAc,CAAC,SAAS,CAAC,EAAE,IAAI,eAAe,CAAC,SAAS,CAAC,CAAC,CAAC;IACpF,CAAC;CACJ;AALD,sCAKC","sourcesContent":["/**\n * Which FILES a diff-scoped code rule judges, for every mode it offers — and the one place the per-run\n * `--projects` restriction of the debug run (#1027) is applied.\n *\n * NEW_AND_MODIFIED_CODE — the changed files (the rule then keeps only sites on changed lines)\n * NEW_AND_MODIFIED_FILES — the changed files, whole\n * MODIFIED_PROJECTS — every in-scope file of every project the diff touches, whole, plus the\n * changed files themselves (so it is never narrower than NEW_AND_MODIFIED_FILES)\n * RUN_EVERY_TIME — every in-scope file in the repo, whole, every run\n *\n * The two whole-scope modes are NEW_AND_MODIFIED_FILES over a bigger file set — the rule's own detection,\n * disable handling and failure text are untouched, which is what lets a debug run print exactly what the\n * gate would print. A rule asks {@link ScanScope.files} instead of `getChangedFiles`, and asks\n * {@link ScanScope.isLineScoped} instead of comparing its mode to NEW_AND_MODIFIED_CODE.\n *\n * Every rule that reads its files here also reports its sites through {@link ScanScope.recordSites}, so\n * the debug run can print a count per project without parsing any rule's output.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { ChangedFilesOptions, DiffScope, ModifiedCodeMode } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/** One nx project: its name and its directory (repo-relative, '/'-separated, no trailing slash). */\nexport class ProjectEntry {\n constructor(\n readonly name: string,\n readonly dir: string,\n ) {}\n}\n\n/** The only field of a project.json this catalog reads. */\ntype RawProjectName = { name?: string };\n\n/**\n * The repo's nx projects, found from the `project.json` files git knows about (tracked or untracked,\n * never ignored), and the owner lookup every whole-scope mode and `--projects` filter uses: a file\n * belongs to the DEEPEST project directory containing it.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProjectCatalog {\n private cachedRoot: string | undefined;\n private cached: ProjectEntry[] = [];\n\n constructor(private readonly diffScope: DiffScope) {}\n\n all(workspaceRoot: string): ProjectEntry[] {\n if (this.cachedRoot !== workspaceRoot) {\n this.cached = this.load(workspaceRoot);\n this.cachedRoot = workspaceRoot;\n }\n return this.cached;\n }\n\n /** The project owning `relFile`, or undefined when no project directory contains it. */\n ownerOf(workspaceRoot: string, relFile: string): ProjectEntry | undefined {\n const file = relFile.split(path.sep).join('/');\n let best: ProjectEntry | undefined;\n for (const project of this.all(workspaceRoot)) {\n const inside = project.dir === '' || file.startsWith(`${project.dir}/`);\n if (inside && (best === undefined || project.dir.length > best.dir.length)) best = project;\n }\n return best;\n }\n\n private load(workspaceRoot: string): ProjectEntry[] {\n const jsons = this.diffScope.getAllFiles(workspaceRoot, { tsOnly: false })\n .filter((f: string) => f === 'project.json' || f.endsWith('/project.json'));\n return jsons.map((rel: string) => {\n const dir = path.posix.dirname(rel) === '.' ? '' : path.posix.dirname(rel);\n return new ProjectEntry(this.readName(path.join(workspaceRoot, rel)) ?? path.posix.basename(dir), dir);\n });\n }\n\n private readName(fullPath: string): string | undefined {\n // webpieces-disable no-unmanaged-exceptions -- add the exact project.json path while preserving the parse/read failure as cause\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RawProjectName;\n return typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : undefined;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot read nx project identity from ${fullPath} — fix project.json and retry.`, {\n cause: error,\n });\n }\n }\n}\n\n/**\n * The per-run project restriction. Bound at the composition root: `undefined` for every normal run (the\n * gate), the `--projects` names for a debug run. Data-only.\n */\nexport class ScanRestriction {\n constructor(readonly projectNames: readonly string[] | undefined) {}\n}\n\n/** One recorded violating site: which rule, which file. Data-only. */\nexport class RecordedSite {\n constructor(\n readonly ruleName: string,\n readonly relFile: string,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ScanScope {\n private readonly sites: RecordedSite[] = [];\n\n constructor(\n private readonly diffScope: DiffScope,\n private readonly catalog: ProjectCatalog,\n private readonly restriction: ScanRestriction,\n ) {}\n\n /** True when the rule keeps only sites on changed lines; every other active mode judges whole files. */\n isLineScoped(mode: ModifiedCodeMode): boolean {\n return mode === 'NEW_AND_MODIFIED_CODE';\n }\n\n /**\n * The files a rule in `mode` judges, restricted to the debug run's `--projects` when there is one.\n * `opts` is passed through to the git listing (`tsOnly: false` for a rule that reads templates/CSS).\n */\n files(workspaceRoot: string, mode: ModifiedCodeMode, base: string, head: string | undefined, opts?: ChangedFilesOptions): string[] {\n return this.restrict(workspaceRoot, this.unrestricted(workspaceRoot, mode, base, head, opts));\n }\n\n /** Record every violating site a rule found, for the debug run's per-project count. */\n recordSites(ruleName: string, relFiles: readonly string[]): void {\n for (const relFile of relFiles) this.sites.push(new RecordedSite(ruleName, relFile));\n }\n\n /** Sites recorded so far, counted per owning project name (`(no project)` for a file outside one). */\n countsByProject(workspaceRoot: string): Map<string, number> {\n const counts = new Map<string, number>();\n for (const site of this.sites) {\n const name = this.catalog.ownerOf(workspaceRoot, site.relFile)?.name ?? '(no project)';\n counts.set(name, (counts.get(name) ?? 0) + 1);\n }\n return counts;\n }\n\n private unrestricted(workspaceRoot: string, mode: ModifiedCodeMode, base: string, head: string | undefined, opts?: ChangedFilesOptions): string[] {\n if (mode === 'RUN_EVERY_TIME') return this.diffScope.getAllFiles(workspaceRoot, opts);\n const changed = this.diffScope.getChangedFiles(workspaceRoot, base, head, opts);\n if (mode !== 'MODIFIED_PROJECTS') return changed;\n // A project is TOUCHED by any changed file it owns — not only the files this rule reads — so a\n // project.json or README edit counts, exactly as nx affected would see it.\n const touched = new Set<string>();\n for (const f of this.diffScope.getChangedFiles(workspaceRoot, base, head, { tsOnly: false })) {\n const owner = this.catalog.ownerOf(workspaceRoot, f);\n if (owner !== undefined) touched.add(owner.dir);\n }\n const inTouched = this.diffScope.getAllFiles(workspaceRoot, opts).filter((f: string) => {\n const owner = this.catalog.ownerOf(workspaceRoot, f);\n return owner !== undefined && touched.has(owner.dir);\n });\n return Array.from(new Set([...changed, ...inTouched]));\n }\n\n private restrict(workspaceRoot: string, files: string[]): string[] {\n const names = this.restriction.projectNames;\n if (names === undefined) return files;\n const wanted = new Set(names);\n return files.filter((f: string) => {\n const owner = this.catalog.ownerOf(workspaceRoot, f);\n return owner !== undefined && wanted.has(owner.name);\n });\n }\n}\n\n/**\n * The gate's {@link ScanScope} — the diff, no project restriction — for a caller that builds a validator\n * outside the DI container: the single-rule nx executors (`validate-no-any-unknown` and friends) and specs.\n */\nexport class GateScanScope extends ScanScope {\n constructor() {\n const diffScope = new DiffScope();\n super(diffScope, new ProjectCatalog(diffScope), new ScanRestriction(undefined));\n }\n}\n"]}
package/src/tag-rule.js CHANGED
@@ -16,6 +16,7 @@ const tslib_1 = require("tslib");
16
16
  const fs = tslib_1.__importStar(require("fs"));
17
17
  const path = tslib_1.__importStar(require("path"));
18
18
  const rules_config_1 = require("@webpieces/rules-config");
19
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
19
20
  const resolve_mode_1 = require("./resolve-mode");
20
21
  /** A project (identified by its project.json) missing the required tag. */
21
22
  class MissingTagProject {
@@ -104,7 +105,7 @@ function readProjectJson(projectJsonPath, workspaceRoot) {
104
105
  return new ProjectJson(name, tags);
105
106
  }
106
107
  catch (err) {
107
- const error = (0, rules_config_1.toError)(err);
108
+ const error = (0, to_error_1.toError)(err);
108
109
  void error; // swallow — malformed project.json is not this rule's concern
109
110
  return new ProjectJson(null, []);
110
111
  }
@@ -1 +1 @@
1
- {"version":3,"file":"tag-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/tag-rule.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AA8IH,wDAcC;AASD,4EAiBC;AAqBD,0CAgEC;;AAzQD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4F;AAE5F,iDAAgD;AAEhD,2EAA2E;AAC3E,MAAa,iBAAiB;IAEN;IACA;IAFpB,YACoB,IAAY,EACZ,eAAuB;QADvB,SAAI,GAAJ,IAAI,CAAQ;QACZ,oBAAe,GAAf,eAAe,CAAQ;IACxC,CAAC;CACP;AALD,8CAKC;AAED;;;;GAIG;AACH,MAAa,iBAAiB;IAEN;IACA;IACA;IAHpB,YACoB,IAAY,EACZ,eAAuB,EACvB,SAAmB;QAFnB,SAAI,GAAJ,IAAI,CAAQ;QACZ,oBAAe,GAAf,eAAe,CAAQ;QACvB,cAAS,GAAT,SAAS,CAAU;IACpC,CAAC;CACP;AAND,8CAMC;AASD,qFAAqF;AACrF,MAAa,WAAW;IAGA;IAEA;IAEA;IAEA;IAEA;IAMA;IAEA;IAlBpB;IACI,gDAAgD;IAChC,SAA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M,CAAC,CAAC;QACjG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;QAC1D,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Shared \"every modified project must carry a `<prefix>` nx tag\" rule engine.\n *\n * Both `framework-tag` (prefix `framework:`) and `role-tag` (prefix `role:`) are\n * the same rule with different prefix/known-values/messages, so the\n * project-walking + diff-scoping + mode logic lives here once and each concrete\n * rule supplies only a {@link TagRuleSpec}.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { ProjectMode, detectBase, getChangedFiles, toError } from '@webpieces/rules-config';\nimport { ExecutorResult } from './code-validator';\nimport { shouldSkipRule } from './resolve-mode';\n\n/** A project (identified by its project.json) missing the required tag. */\nexport class MissingTagProject {\n constructor(\n public readonly name: string,\n public readonly projectJsonPath: string\n ) {}\n}\n\n/**\n * A project carrying one or more `<prefix>` tag VALUES outside the known set\n * (e.g. `framework:all`). `role-tag` never uses this — only rules that opt into\n * value validation via {@link TagRuleSpec.validateValues}.\n */\nexport class InvalidTagProject {\n constructor(\n public readonly name: string,\n public readonly projectJsonPath: string,\n public readonly badValues: string[]\n ) {}\n}\n\n/** Print the invalid-value report for projects carrying out-of-set tag values. */\nexport type ReportInvalidValues = (\n invalid: InvalidTagProject[],\n knownTypes: string[],\n mode: ProjectMode\n) => void;\n\n/** The knobs and messages that make a concrete tag rule out of the shared engine. */\nexport class TagRuleSpec {\n constructor(\n /** Tag prefix, e.g. `framework:` or `role:`. */\n public readonly tagPrefix: string,\n /** Rule id, e.g. `framework-tag` / `role-tag` (used in skip/validating logs). */\n public readonly ruleName: string,\n /** Human label for the \"Validating X\" banner, e.g. `Framework Tag`. */\n public readonly ruleLabel: string,\n /** Default allowed values when config.knownTypes is empty. */\n public readonly defaultKnownTypes: string[],\n /** Print the violation report for the missing-tag projects. */\n public readonly report: (untagged: MissingTagProject[], knownTypes: string[], mode: ProjectMode) => void,\n /**\n * When true, ALSO validate that every `<prefix>` tag value is in the\n * known set (framework-tag opts in to reject `framework:all` and typos;\n * role-tag leaves this false so its single-value behavior is unchanged).\n */\n public readonly validateValues: boolean = false,\n /** Report for out-of-set values; required when {@link validateValues} is true. */\n public readonly reportInvalidValues: ReportInvalidValues | null = null\n ) {}\n}\n\n/** The config fields the shared engine reads (shared by every tag rule config). */\nexport interface TagRuleConfig {\n mode?: ProjectMode;\n knownTypes?: string[];\n turnOffRuleUntilEpoch?: number;\n turnOffRuleWhileOnBranch?: string | null;\n}\n\ntype RawProjectJson = { name?: string; tags?: string[] };\n\nclass ProjectJson {\n constructor(\n public readonly name: string | null,\n public readonly tags: string[]\n ) {}\n}\n\n/**\n * Parse `name` + `tags` from a project.json. Returns an empty ProjectJson when\n * unreadable/unparseable — config validation owns malformed-json reporting; this\n * rule just nudges for a tag and must never crash the build.\n */\nfunction readProjectJson(projectJsonPath: string, workspaceRoot: string): ProjectJson {\n const fullPath = path.join(workspaceRoot, projectJsonPath);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed: RawProjectJson = JSON.parse(fs.readFileSync(fullPath, 'utf-8'));\n const name = typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : null;\n const tags = Array.isArray(parsed.tags) ? parsed.tags.filter((tag: string) => typeof tag === 'string') : [];\n return new ProjectJson(name, tags);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — malformed project.json is not this rule's concern\n return new ProjectJson(null, []);\n }\n}\n\n/**\n * Walk up from a changed file to the nearest ancestor directory containing a\n * project.json (the file's owning nx project). Returns the repo-relative\n * project.json path, or null when the file belongs to no project.\n */\nfunction findOwningProjectJson(changedFile: string, workspaceRoot: string): string | null {\n let dir = path.dirname(changedFile);\n while (true) {\n const candidate = path.join(dir, 'project.json');\n if (fs.existsSync(path.join(workspaceRoot, candidate))) {\n return candidate;\n }\n const parent = path.dirname(dir);\n if (parent === dir || dir === '.' || dir === '') {\n return null;\n }\n dir = parent;\n }\n}\n\nfunction hasTag(tags: string[], tagPrefix: string): boolean {\n return tags.some((tag: string) => tag.startsWith(tagPrefix) && tag.slice(tagPrefix.length).trim().length > 0);\n}\n\n/** The non-empty values of every `<tagPrefix>` tag on a project (the env/role set). */\nfunction tagValues(tags: string[], tagPrefix: string): string[] {\n return tags\n .filter((tag: string) => tag.startsWith(tagPrefix))\n .map((tag: string) => tag.slice(tagPrefix.length).trim())\n .filter((value: string) => value.length > 0);\n}\n\n/** The distinct owning project.json paths of a set of changed files. */\nfunction collectOwningProjectJsons(workspaceRoot: string, changedFiles: string[]): string[] {\n const projectJsonPaths = new Set<string>();\n for (const file of changedFiles) {\n const owning = findOwningProjectJson(file, workspaceRoot);\n if (owning !== null) {\n projectJsonPaths.add(owning);\n }\n }\n return Array.from(projectJsonPaths).sort();\n}\n\n/** Every owning project of a changed file that is missing a `<tagPrefix>` tag. */\nexport function findProjectsMissingTag(\n workspaceRoot: string,\n changedFiles: string[],\n tagPrefix: string\n): MissingTagProject[] {\n const missing: MissingTagProject[] = [];\n for (const projectJsonPath of collectOwningProjectJsons(workspaceRoot, changedFiles)) {\n const projectJson = readProjectJson(projectJsonPath, workspaceRoot);\n if (!hasTag(projectJson.tags, tagPrefix)) {\n const name = projectJson.name ?? path.dirname(projectJsonPath);\n missing.push(new MissingTagProject(name, projectJsonPath));\n }\n }\n return missing;\n}\n\n/**\n * Every owning project of a changed file that carries one or more `<tagPrefix>`\n * tag VALUES outside `knownTypes`. Multiple values per project are allowed (an\n * env set) — this only flags values not in the known set (e.g. `framework:all`\n * or a typo). Projects with no `<tagPrefix>` tag are skipped here (the\n * missing-tag scan owns that case).\n */\nexport function findProjectsWithInvalidTagValues(\n workspaceRoot: string,\n changedFiles: string[],\n tagPrefix: string,\n knownTypes: string[]\n): InvalidTagProject[] {\n const known = new Set(knownTypes);\n const invalid: InvalidTagProject[] = [];\n for (const projectJsonPath of collectOwningProjectJsons(workspaceRoot, changedFiles)) {\n const projectJson = readProjectJson(projectJsonPath, workspaceRoot);\n const badValues = tagValues(projectJson.tags, tagPrefix).filter((value: string) => !known.has(value));\n if (badValues.length > 0) {\n const name = projectJson.name ?? path.dirname(projectJsonPath);\n invalid.push(new InvalidTagProject(name, projectJsonPath, badValues));\n }\n }\n return invalid;\n}\n\nfunction resolveMode(\n normalMode: ProjectMode,\n epoch: number | undefined,\n branchPattern: string | undefined,\n ruleName: string\n): ProjectMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping ${ruleName} validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\n/** Run a concrete tag rule (framework-tag / role-tag) against the git diff. */\nexport async function runTagValidator(\n options: TagRuleConfig,\n workspaceRoot: string,\n spec: TagRuleSpec\n): Promise<ExecutorResult> {\n const mode: ProjectMode = resolveMode(\n options.mode ?? 'OFF',\n options.turnOffRuleUntilEpoch,\n (options.turnOffRuleWhileOnBranch ?? undefined),\n spec.ruleName\n );\n const knownTypes = options.knownTypes && options.knownTypes.length > 0 ? options.knownTypes : spec.defaultKnownTypes;\n\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${spec.ruleName} validation (mode: OFF)`);\n console.log('');\n return { success: true };\n }\n\n console.log(`\\n📏 Validating ${spec.ruleLabel}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${spec.ruleName} validation (could not detect base branch)`);\n console.log('');\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n // Project-level rule: ANY changed file (not just .ts) makes its owning\n // project require a tag, so include non-code files too.\n const changedFiles = getChangedFiles(workspaceRoot, base, head, { tsOnly: false });\n if (changedFiles.length === 0) {\n console.log('✅ No changed files in any project');\n return { success: true };\n }\n\n const missing = findProjectsMissingTag(workspaceRoot, changedFiles, spec.tagPrefix);\n const invalid =\n spec.validateValues && spec.reportInvalidValues !== null\n ? findProjectsWithInvalidTagValues(workspaceRoot, changedFiles, spec.tagPrefix, knownTypes)\n : [];\n\n if (missing.length === 0 && invalid.length === 0) {\n console.log(`✅ Every modified project declares a valid ${spec.tagPrefix.replace(/:$/, '')} tag`);\n return { success: true };\n }\n\n if (missing.length > 0) {\n spec.report(missing, knownTypes, mode);\n }\n if (invalid.length > 0 && spec.reportInvalidValues !== null) {\n spec.reportInvalidValues(invalid, knownTypes, mode);\n }\n return { success: false };\n}\n"]}
1
+ {"version":3,"file":"tag-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/tag-rule.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AA+IH,wDAcC;AASD,4EAiBC;AAqBD,0CAgEC;;AA1QD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAmF;AACnF,iEAA6D;AAE7D,iDAAgD;AAEhD,2EAA2E;AAC3E,MAAa,iBAAiB;IAEN;IACA;IAFpB,YACoB,IAAY,EACZ,eAAuB;QADvB,SAAI,GAAJ,IAAI,CAAQ;QACZ,oBAAe,GAAf,eAAe,CAAQ;IACxC,CAAC;CACP;AALD,8CAKC;AAED;;;;GAIG;AACH,MAAa,iBAAiB;IAEN;IACA;IACA;IAHpB,YACoB,IAAY,EACZ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C,SAAS,EAAE,UAAU,CAAC;QAC3F,CAAC,CAAC,EAAE,CAAC;IAEb,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/C,OAAO,CAAC,GAAG,CAAC,6CAA6C,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;QACjG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;QAC1D,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Shared \"every modified project must carry a `<prefix>` nx tag\" rule engine.\n *\n * Both `framework-tag` (prefix `framework:`) and `role-tag` (prefix `role:`) are\n * the same rule with different prefix/known-values/messages, so the\n * project-walking + diff-scoping + mode logic lives here once and each concrete\n * rule supplies only a {@link TagRuleSpec}.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { ProjectMode, detectBase, getChangedFiles } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { ExecutorResult } from './code-validator';\nimport { shouldSkipRule } from './resolve-mode';\n\n/** A project (identified by its project.json) missing the required tag. */\nexport class MissingTagProject {\n constructor(\n public readonly name: string,\n public readonly projectJsonPath: string\n ) {}\n}\n\n/**\n * A project carrying one or more `<prefix>` tag VALUES outside the known set\n * (e.g. `framework:all`). `role-tag` never uses this — only rules that opt into\n * value validation via {@link TagRuleSpec.validateValues}.\n */\nexport class InvalidTagProject {\n constructor(\n public readonly name: string,\n public readonly projectJsonPath: string,\n public readonly badValues: string[]\n ) {}\n}\n\n/** Print the invalid-value report for projects carrying out-of-set tag values. */\nexport type ReportInvalidValues = (\n invalid: InvalidTagProject[],\n knownTypes: string[],\n mode: ProjectMode\n) => void;\n\n/** The knobs and messages that make a concrete tag rule out of the shared engine. */\nexport class TagRuleSpec {\n constructor(\n /** Tag prefix, e.g. `framework:` or `role:`. */\n public readonly tagPrefix: string,\n /** Rule id, e.g. `framework-tag` / `role-tag` (used in skip/validating logs). */\n public readonly ruleName: string,\n /** Human label for the \"Validating X\" banner, e.g. `Framework Tag`. */\n public readonly ruleLabel: string,\n /** Default allowed values when config.knownTypes is empty. */\n public readonly defaultKnownTypes: string[],\n /** Print the violation report for the missing-tag projects. */\n public readonly report: (untagged: MissingTagProject[], knownTypes: string[], mode: ProjectMode) => void,\n /**\n * When true, ALSO validate that every `<prefix>` tag value is in the\n * known set (framework-tag opts in to reject `framework:all` and typos;\n * role-tag leaves this false so its single-value behavior is unchanged).\n */\n public readonly validateValues: boolean = false,\n /** Report for out-of-set values; required when {@link validateValues} is true. */\n public readonly reportInvalidValues: ReportInvalidValues | null = null\n ) {}\n}\n\n/** The config fields the shared engine reads (shared by every tag rule config). */\nexport interface TagRuleConfig {\n mode?: ProjectMode;\n knownTypes?: string[];\n turnOffRuleUntilEpoch?: number;\n turnOffRuleWhileOnBranch?: string | null;\n}\n\ntype RawProjectJson = { name?: string; tags?: string[] };\n\nclass ProjectJson {\n constructor(\n public readonly name: string | null,\n public readonly tags: string[]\n ) {}\n}\n\n/**\n * Parse `name` + `tags` from a project.json. Returns an empty ProjectJson when\n * unreadable/unparseable — config validation owns malformed-json reporting; this\n * rule just nudges for a tag and must never crash the build.\n */\nfunction readProjectJson(projectJsonPath: string, workspaceRoot: string): ProjectJson {\n const fullPath = path.join(workspaceRoot, projectJsonPath);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed: RawProjectJson = JSON.parse(fs.readFileSync(fullPath, 'utf-8'));\n const name = typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : null;\n const tags = Array.isArray(parsed.tags) ? parsed.tags.filter((tag: string) => typeof tag === 'string') : [];\n return new ProjectJson(name, tags);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — malformed project.json is not this rule's concern\n return new ProjectJson(null, []);\n }\n}\n\n/**\n * Walk up from a changed file to the nearest ancestor directory containing a\n * project.json (the file's owning nx project). Returns the repo-relative\n * project.json path, or null when the file belongs to no project.\n */\nfunction findOwningProjectJson(changedFile: string, workspaceRoot: string): string | null {\n let dir = path.dirname(changedFile);\n while (true) {\n const candidate = path.join(dir, 'project.json');\n if (fs.existsSync(path.join(workspaceRoot, candidate))) {\n return candidate;\n }\n const parent = path.dirname(dir);\n if (parent === dir || dir === '.' || dir === '') {\n return null;\n }\n dir = parent;\n }\n}\n\nfunction hasTag(tags: string[], tagPrefix: string): boolean {\n return tags.some((tag: string) => tag.startsWith(tagPrefix) && tag.slice(tagPrefix.length).trim().length > 0);\n}\n\n/** The non-empty values of every `<tagPrefix>` tag on a project (the env/role set). */\nfunction tagValues(tags: string[], tagPrefix: string): string[] {\n return tags\n .filter((tag: string) => tag.startsWith(tagPrefix))\n .map((tag: string) => tag.slice(tagPrefix.length).trim())\n .filter((value: string) => value.length > 0);\n}\n\n/** The distinct owning project.json paths of a set of changed files. */\nfunction collectOwningProjectJsons(workspaceRoot: string, changedFiles: string[]): string[] {\n const projectJsonPaths = new Set<string>();\n for (const file of changedFiles) {\n const owning = findOwningProjectJson(file, workspaceRoot);\n if (owning !== null) {\n projectJsonPaths.add(owning);\n }\n }\n return Array.from(projectJsonPaths).sort();\n}\n\n/** Every owning project of a changed file that is missing a `<tagPrefix>` tag. */\nexport function findProjectsMissingTag(\n workspaceRoot: string,\n changedFiles: string[],\n tagPrefix: string\n): MissingTagProject[] {\n const missing: MissingTagProject[] = [];\n for (const projectJsonPath of collectOwningProjectJsons(workspaceRoot, changedFiles)) {\n const projectJson = readProjectJson(projectJsonPath, workspaceRoot);\n if (!hasTag(projectJson.tags, tagPrefix)) {\n const name = projectJson.name ?? path.dirname(projectJsonPath);\n missing.push(new MissingTagProject(name, projectJsonPath));\n }\n }\n return missing;\n}\n\n/**\n * Every owning project of a changed file that carries one or more `<tagPrefix>`\n * tag VALUES outside `knownTypes`. Multiple values per project are allowed (an\n * env set) — this only flags values not in the known set (e.g. `framework:all`\n * or a typo). Projects with no `<tagPrefix>` tag are skipped here (the\n * missing-tag scan owns that case).\n */\nexport function findProjectsWithInvalidTagValues(\n workspaceRoot: string,\n changedFiles: string[],\n tagPrefix: string,\n knownTypes: string[]\n): InvalidTagProject[] {\n const known = new Set(knownTypes);\n const invalid: InvalidTagProject[] = [];\n for (const projectJsonPath of collectOwningProjectJsons(workspaceRoot, changedFiles)) {\n const projectJson = readProjectJson(projectJsonPath, workspaceRoot);\n const badValues = tagValues(projectJson.tags, tagPrefix).filter((value: string) => !known.has(value));\n if (badValues.length > 0) {\n const name = projectJson.name ?? path.dirname(projectJsonPath);\n invalid.push(new InvalidTagProject(name, projectJsonPath, badValues));\n }\n }\n return invalid;\n}\n\nfunction resolveMode(\n normalMode: ProjectMode,\n epoch: number | undefined,\n branchPattern: string | undefined,\n ruleName: string\n): ProjectMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping ${ruleName} validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\n/** Run a concrete tag rule (framework-tag / role-tag) against the git diff. */\nexport async function runTagValidator(\n options: TagRuleConfig,\n workspaceRoot: string,\n spec: TagRuleSpec\n): Promise<ExecutorResult> {\n const mode: ProjectMode = resolveMode(\n options.mode ?? 'OFF',\n options.turnOffRuleUntilEpoch,\n (options.turnOffRuleWhileOnBranch ?? undefined),\n spec.ruleName\n );\n const knownTypes = options.knownTypes && options.knownTypes.length > 0 ? options.knownTypes : spec.defaultKnownTypes;\n\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${spec.ruleName} validation (mode: OFF)`);\n console.log('');\n return { success: true };\n }\n\n console.log(`\\n📏 Validating ${spec.ruleLabel}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${spec.ruleName} validation (could not detect base branch)`);\n console.log('');\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n // Project-level rule: ANY changed file (not just .ts) makes its owning\n // project require a tag, so include non-code files too.\n const changedFiles = getChangedFiles(workspaceRoot, base, head, { tsOnly: false });\n if (changedFiles.length === 0) {\n console.log('✅ No changed files in any project');\n return { success: true };\n }\n\n const missing = findProjectsMissingTag(workspaceRoot, changedFiles, spec.tagPrefix);\n const invalid =\n spec.validateValues && spec.reportInvalidValues !== null\n ? findProjectsWithInvalidTagValues(workspaceRoot, changedFiles, spec.tagPrefix, knownTypes)\n : [];\n\n if (missing.length === 0 && invalid.length === 0) {\n console.log(`✅ Every modified project declares a valid ${spec.tagPrefix.replace(/:$/, '')} tag`);\n return { success: true };\n }\n\n if (missing.length > 0) {\n spec.report(missing, knownTypes, mode);\n }\n if (invalid.length > 0 && spec.reportInvalidValues !== null) {\n spec.reportInvalidValues(invalid, knownTypes, mode);\n }\n return { success: false };\n}\n"]}
@@ -1,4 +1,5 @@
1
- import { EnsureWeAreSecureConfig, InformAiError, RuleFailError } from '@webpieces/rules-config';
1
+ import { EnsureWeAreSecureConfig, RuleFailError } from '@webpieces/rules-config';
2
+ import { InformAiError } from '@webpieces/tooling-common';
2
3
  import { CodeValidator, ExecutorResult } from './code-validator';
3
4
  export declare class SecurityContractViolation {
4
5
  readonly file: string;
@@ -11,6 +11,7 @@ const fs = tslib_1.__importStar(require("fs"));
11
11
  const path = tslib_1.__importStar(require("path"));
12
12
  const ts = tslib_1.__importStar(require("typescript"));
13
13
  const rules_config_1 = require("@webpieces/rules-config");
14
+ const tooling_common_1 = require("@webpieces/tooling-common");
14
15
  const inversify_1 = require("inversify");
15
16
  const code_validator_1 = require("./code-validator");
16
17
  const HTTP_AUTH = new Set([
@@ -364,7 +365,7 @@ function securityContractsError(violations) {
364
365
  }
365
366
  // webpieces-disable no-function-outside-class -- one plumbing failure shared by tests and runner
366
367
  function missingSecurityBaseError() {
367
- return new rules_config_1.InformAiError('ensure-we-are-secure could not determine the comparison base. Set NX_BASE to the base branch or commit and retry.');
368
+ return new tooling_common_1.InformAiError('ensure-we-are-secure could not determine the comparison base. Set NX_BASE to the base branch or commit and retry.');
368
369
  }
369
370
  let EnsureWeAreSecureValidator = class EnsureWeAreSecureValidator extends code_validator_1.CodeValidator {
370
371
  constructor(config) {
@@ -1 +1 @@
1
- {"version":3,"file":"validate-ensure-we-are-secure.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-ensure-we-are-secure.ts"],"names":[],"mappings":";;;AAieA,0EAUC;AA+BD,wDA8BC;AAGD,wDA2BC;AAGD,4DAIC;;AA7kBD,+FAA+F;AAC/F,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAQiC;AACjC,yCAA2D;AAC3D,qDAAiE;AAEjE,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC;IACtB,WAAW;IACX,YAAY;IACZ,eAAe;IACf,oBAAoB;IACpB,cAAc;IACd,iBAAiB;IACjB,cAAc;CACjB,CAAC,CAAC;AACH,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAChC,GAAG,SAAS;IACZ,SAAS;IACT,UAAU;IACV,YAAY;IACZ,eAAe;CAClB,CAAC,CAAC;AAEH,MAAa,yBAAyB;IAErB;IACA;IAC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AK,CAAC,MAAM,EAAE,sBAAsB,EAAE,sBAAsB,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC,KAAK,KAAK;YAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QACpE,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,IAAA,yBAAU,EAAC,aAAa,CAAC,CAAC;QACjE,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACtC,MAAM,wBAAwB,EAAE,CAAC;QACrC,CAAC;QACD,MAAM,OAAO,GAAG,IAAA,8BAAe,EAAC,aAAa,EAAE,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;YACzE,MAAM,EAAE,KAAK;SAChB,CAAC,CAAC;QACH,MAAM,KAAK,GAAG,+BAA+B,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;QACtE,MAAM,UAAU,GAAG,sBAAsB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;QAChE,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QACtD,MAAM,sBAAsB,CAAC,UAAU,CAAC,CAAC;IAC7C,CAAC;CACJ,CAAA;AAnBY,gEAA0B;qCAA1B,0BAA0B;IADtC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,sCAAuB;GADlC,0BAA0B,CAmBtC","sourcesContent":["/** Audits explicit HTTP authentication and IPC-only contracts in directly changed projects. */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport {\n EnsureWeAreSecureConfig,\n getChangedFiles,\n detectBase,\n InformAiError,\n Option,\n RuleFailError,\n RULE_NAMES,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { CodeValidator, ExecutorResult } from './code-validator';\n\nconst HTTP_AUTH = new Set([\n 'WpAuthJwt',\n 'WpAuthOidc',\n 'WpAuthWebhook',\n 'WpAuthSharedSecret',\n 'WpAuthApiKey',\n 'WpAuthLocalOnly',\n 'WpAuthPublic',\n]);\nconst CONTRACT_DECORATORS = new Set([\n ...HTTP_AUTH,\n 'ApiPath',\n 'Endpoint',\n 'WpInternal',\n 'WpIpcEndpoint',\n]);\n\nexport class SecurityContractViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly code: string,\n readonly message: string,\n ) {}\n}\n\nclass DecoratorUse {\n constructor(\n readonly name: string,\n readonly decorator: ts.Decorator,\n readonly call: ts.CallExpression | null,\n ) {}\n}\n\nclass CanonicalImports {\n readonly named = new Map<string, string>();\n readonly namespaces = new Set<string>();\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction isCanonicalModule(moduleName: string): boolean {\n return (\n moduleName === '@webpieces/core-util' ||\n moduleName === '@webpieces/core-util/ipc' ||\n moduleName.endsWith('/core-util/src/http/decorators') ||\n moduleName.includes('/core-util/src/ipc/')\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction importsOf(source: ts.SourceFile): CanonicalImports {\n const result = new CanonicalImports();\n for (const statement of source.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))\n continue;\n if (!isCanonicalModule(statement.moduleSpecifier.text)) continue;\n const bindings = statement.importClause?.namedBindings;\n if (bindings && ts.isNamedImports(bindings)) {\n for (const item of bindings.elements) {\n const exported = item.propertyName?.text ?? item.name.text;\n if (CONTRACT_DECORATORS.has(exported)) result.named.set(item.name.text, exported);\n }\n } else if (bindings && ts.isNamespaceImport(bindings)) {\n result.namespaces.add(bindings.name.text);\n }\n }\n return result;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction decoratorUse(decorator: ts.Decorator, imports: CanonicalImports): DecoratorUse | null {\n const expr = decorator.expression;\n const call = ts.isCallExpression(expr) ? expr : null;\n const callee = call?.expression ?? expr;\n if (ts.isIdentifier(callee)) {\n const canonical = imports.named.get(callee.text);\n return canonical ? new DecoratorUse(canonical, decorator, call) : null;\n }\n if (\n ts.isPropertyAccessExpression(callee) &&\n ts.isIdentifier(callee.expression) &&\n imports.namespaces.has(callee.expression.text)\n ) {\n return CONTRACT_DECORATORS.has(callee.name.text)\n ? new DecoratorUse(callee.name.text, decorator, call)\n : null;\n }\n return null;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction decoratorsOf(node: ts.Node, imports: CanonicalImports): DecoratorUse[] {\n if (!ts.canHaveDecorators(node)) return [];\n return (ts.getDecorators(node) ?? [])\n .map((decorator: ts.Decorator) => decoratorUse(decorator, imports))\n .filter((use): use is DecoratorUse => use !== null);\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction lineOf(source: ts.SourceFile, node: ts.Node): number {\n return source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction literalId(use: DecoratorUse): string | null {\n const arg = use.call?.arguments[0];\n if (!arg || (!ts.isStringLiteral(arg) && !ts.isNoSubstitutionTemplateLiteral(arg))) return null;\n const value = arg.text.trim();\n return value.length > 0 ? value : null;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction methodName(method: ts.MethodDeclaration): string {\n return ts.isIdentifier(method.name) || ts.isStringLiteral(method.name)\n ? method.name.text\n : method.name.getText();\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction hasPromiseReturn(method: ts.MethodDeclaration): boolean {\n const type = method.type;\n return (\n type !== undefined &&\n ts.isTypeReferenceNode(type) &&\n ts.isIdentifier(type.typeName) &&\n type.typeName.text === 'Promise'\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction add(\n out: SecurityContractViolation[],\n file: string,\n source: ts.SourceFile,\n node: ts.Node,\n code: string,\n message: string,\n): void {\n out.push(new SecurityContractViolation(file, lineOf(source, node), code, message));\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction checkHttpMethod(\n file: string,\n source: ts.SourceFile,\n method: ts.MethodDeclaration,\n uses: DecoratorUse[],\n out: SecurityContractViolation[],\n): void {\n const endpoints = uses.filter((use: DecoratorUse) => use.name === 'Endpoint');\n const auth = uses.filter((use: DecoratorUse) => HTTP_AUTH.has(use.name));\n const ipc = uses.filter((use: DecoratorUse) => use.name === 'WpIpcEndpoint');\n const label = methodName(method);\n if (endpoints.length > 1)\n add(\n out,\n file,\n source,\n method,\n 'HTTP_MULTIPLE_ENDPOINTS',\n `${label} has multiple @Endpoint decorators.`,\n );\n if (endpoints.length > 0 && auth.length !== 1) {\n add(\n out,\n file,\n source,\n method,\n 'HTTP_AUTH_COUNT',\n `${label} must have exactly one method-level @WpAuth* decorator; found ${auth.length}. Prefer an authenticated mode; use @WpAuthPublic('reason') only for deliberate anonymous access.`,\n );\n }\n if (endpoints.length === 0 && auth.length > 0)\n add(\n out,\n file,\n source,\n auth[0]!.decorator,\n 'HTTP_ORPHAN_AUTH',\n `${label} has @WpAuth* but no @Endpoint.`,\n );\n for (const publicUse of auth.filter((use: DecoratorUse) => use.name === 'WpAuthPublic')) {\n if (literalId(publicUse) === null)\n add(\n out,\n file,\n source,\n publicUse.decorator,\n 'HTTP_PUBLIC_REASON',\n `${label} must use @WpAuthPublic('non-empty reason').`,\n );\n }\n if (ipc.length > 0)\n add(\n out,\n file,\n source,\n ipc[0]!.decorator,\n 'HTTP_IPC_MIX',\n `${label} mixes HTTP and IPC endpoint metadata.`,\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction checkInternalMethod(\n file: string,\n source: ts.SourceFile,\n method: ts.MethodDeclaration,\n uses: DecoratorUse[],\n out: SecurityContractViolation[],\n ids: Set<string>,\n): void {\n const ipc = uses.filter((use: DecoratorUse) => use.name === 'WpIpcEndpoint');\n const endpoint = uses.some((use: DecoratorUse) => use.name === 'Endpoint');\n const auth = uses.some((use: DecoratorUse) => HTTP_AUTH.has(use.name));\n const label = methodName(method);\n if (ipc.length !== 1)\n add(\n out,\n file,\n source,\n method,\n 'IPC_ENDPOINT_COUNT',\n `${label} must have exactly one @WpIpcEndpoint('stable-method-id'); found ${ipc.length}.`,\n );\n if (endpoint || auth)\n add(\n out,\n file,\n source,\n method,\n 'IPC_HTTP_MIX',\n `${label} is internal and cannot use @Endpoint or @WpAuth*.`,\n );\n if (method.parameters.length !== 1)\n add(\n out,\n file,\n source,\n method,\n 'IPC_DTO_COUNT',\n `${label} must accept exactly one DTO argument; found ${method.parameters.length}.`,\n );\n if (!hasPromiseReturn(method))\n add(\n out,\n file,\n source,\n method,\n 'IPC_PROMISE_RETURN',\n `${label} must declare a Promise return type.`,\n );\n for (const use of ipc) {\n const id = literalId(use);\n if (id === null)\n add(\n out,\n file,\n source,\n use.decorator,\n 'IPC_METHOD_ID',\n `${label} requires a non-empty inline stable method id.`,\n );\n else if (ids.has(id))\n add(\n out,\n file,\n source,\n use.decorator,\n 'IPC_DUPLICATE_METHOD_ID',\n `${label} duplicates IPC method id '${id}'.`,\n );\n else ids.add(id);\n }\n}\n\nclass InternalApiId {\n constructor(\n readonly id: string,\n readonly file: string,\n readonly source: ts.SourceFile,\n readonly node: ts.Node,\n ) {}\n}\n\nclass ApiClassAudit {\n readonly classUses: DecoratorUse[];\n readonly methods: ts.MethodDeclaration[];\n readonly methodUses: DecoratorUse[][];\n readonly apiPaths: DecoratorUse[];\n readonly internals: DecoratorUse[];\n readonly classAuth: DecoratorUse[];\n readonly hasHttpMethod: boolean;\n readonly hasIpcMethod: boolean;\n readonly className: string;\n\n constructor(\n readonly statement: ts.ClassDeclaration,\n imports: CanonicalImports,\n ) {\n this.classUses = decoratorsOf(statement, imports);\n this.methods = statement.members.filter(ts.isMethodDeclaration);\n this.methodUses = this.methods.map((method: ts.MethodDeclaration) =>\n decoratorsOf(method, imports),\n );\n this.apiPaths = this.classUses.filter((use: DecoratorUse) => use.name === 'ApiPath');\n this.internals = this.classUses.filter((use: DecoratorUse) => use.name === 'WpInternal');\n this.classAuth = this.classUses.filter((use: DecoratorUse) => HTTP_AUTH.has(use.name));\n this.hasHttpMethod = this.methodUses.some((uses: DecoratorUse[]) =>\n uses.some((use: DecoratorUse) => use.name === 'Endpoint'),\n );\n this.hasIpcMethod = this.methodUses.some((uses: DecoratorUse[]) =>\n uses.some((use: DecoratorUse) => use.name === 'WpIpcEndpoint'),\n );\n this.className = statement.name?.text ?? '<anonymous class>';\n }\n\n get isHttp(): boolean {\n return this.apiPaths.length > 0 || this.hasHttpMethod;\n }\n\n get isInternal(): boolean {\n return this.internals.length > 0 || this.hasIpcMethod;\n }\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction checkClassShape(\n file: string,\n source: ts.SourceFile,\n audit: ApiClassAudit,\n out: SecurityContractViolation[],\n): void {\n if (audit.hasHttpMethod && audit.apiPaths.length === 0)\n add(\n out,\n file,\n source,\n audit.statement,\n 'HTTP_MISSING_API_PATH',\n `${audit.className} has @Endpoint methods but no @ApiPath.`,\n );\n if (audit.hasIpcMethod && audit.internals.length === 0)\n add(\n out,\n file,\n source,\n audit.statement,\n 'IPC_MISSING_INTERNAL',\n `${audit.className} has @WpIpcEndpoint methods but no @WpInternal('stable-api-id').`,\n );\n if (audit.apiPaths.length > 1)\n add(\n out,\n file,\n source,\n audit.statement,\n 'HTTP_API_PATH_COUNT',\n `${audit.className} has multiple @ApiPath decorators.`,\n );\n if (audit.internals.length > 1)\n add(\n out,\n file,\n source,\n audit.statement,\n 'IPC_INTERNAL_COUNT',\n `${audit.className} has multiple @WpInternal decorators.`,\n );\n if (audit.classAuth.length > 0)\n add(\n out,\n file,\n source,\n audit.classAuth[0]!.decorator,\n 'HTTP_CLASS_AUTH',\n `${audit.className} cannot declare class-level @WpAuth*; annotate every @Endpoint method.`,\n );\n if (audit.isHttp && audit.isInternal)\n add(\n out,\n file,\n source,\n audit.statement,\n 'HTTP_IPC_CLASS_MIX',\n `${audit.className} mixes HTTP and internal IPC contract metadata.`,\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction checkClassMethods(\n file: string,\n source: ts.SourceFile,\n audit: ApiClassAudit,\n out: SecurityContractViolation[],\n apiIds: InternalApiId[],\n): void {\n if (audit.internals.length === 0) {\n if (audit.isHttp)\n audit.methods.forEach((method: ts.MethodDeclaration, index: number) =>\n checkHttpMethod(file, source, method, audit.methodUses[index]!, out),\n );\n return;\n }\n const internal = audit.internals[0]!;\n const id = literalId(internal);\n if (id === null)\n add(\n out,\n file,\n source,\n internal.decorator,\n 'IPC_API_ID',\n `${audit.className} requires @WpInternal('non-empty-stable-api-id').`,\n );\n else apiIds.push(new InternalApiId(id, file, source, internal.decorator));\n if (audit.apiPaths.length > 0)\n add(\n out,\n file,\n source,\n audit.apiPaths[0]!.decorator,\n 'IPC_API_PATH',\n `${audit.className} is internal and cannot use @ApiPath.`,\n );\n const ids = new Set<string>();\n audit.methods.forEach((method: ts.MethodDeclaration, index: number) =>\n checkInternalMethod(file, source, method, audit.methodUses[index]!, out, ids),\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction auditFile(\n file: string,\n workspaceRoot: string,\n apiIds: InternalApiId[],\n): SecurityContractViolation[] {\n const content = fs.readFileSync(path.join(workspaceRoot, file), 'utf-8');\n const source = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true);\n const imports = importsOf(source);\n const out: SecurityContractViolation[] = [];\n for (const statement of source.statements) {\n if (!ts.isClassDeclaration(statement)) continue;\n const audit = new ApiClassAudit(statement, imports);\n if (!audit.isHttp && !audit.isInternal && audit.classAuth.length === 0) continue;\n checkClassShape(file, source, audit, out);\n checkClassMethods(file, source, audit, out, apiIds);\n }\n return out;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction owningProjectJson(workspaceRoot: string, relativeFile: string): string | null {\n let dir = path.dirname(relativeFile);\n while (dir !== '.' && dir !== '') {\n const candidate = path.join(dir, 'project.json');\n if (fs.existsSync(path.join(workspaceRoot, candidate))) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return fs.existsSync(path.join(workspaceRoot, 'project.json')) ? 'project.json' : null;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nexport function findDirectlyChangedProjectRoots(\n workspaceRoot: string,\n changedFiles: string[],\n): string[] {\n const roots = new Set<string>();\n for (const file of changedFiles) {\n const projectJson = owningProjectJson(workspaceRoot, file);\n if (projectJson !== null) roots.add(path.dirname(projectJson));\n }\n return [...roots].sort();\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction projectFiles(workspaceRoot: string, projectRoot: string): string[] {\n const files: string[] = [];\n const fullRoot = path.join(workspaceRoot, projectRoot);\n const walk = (dir: string): void => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === '.git')\n continue;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (\n /\\.tsx?$/.test(entry.name) &&\n !entry.name.endsWith('.d.ts') &&\n !entry.name.endsWith('.spec.ts') &&\n !entry.name.endsWith('.test.ts') &&\n !entry.name.endsWith('.spec.tsx') &&\n !entry.name.endsWith('.test.tsx')\n ) {\n const rel = path.relative(workspaceRoot, full);\n const owner = owningProjectJson(workspaceRoot, rel);\n if (owner !== null && path.dirname(owner) === projectRoot) files.push(rel);\n }\n }\n };\n if (fs.existsSync(fullRoot)) walk(fullRoot);\n return files.sort();\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nexport function auditSecurityContracts(\n workspaceRoot: string,\n projectRoots: string[],\n): SecurityContractViolation[] {\n const apiIds: InternalApiId[] = [];\n const files = projectRoots.flatMap((root: string) => projectFiles(workspaceRoot, root));\n const out = files.flatMap((file: string) => auditFile(file, workspaceRoot, apiIds));\n const byId = new Map<string, InternalApiId[]>();\n for (const api of apiIds) byId.set(api.id, [...(byId.get(api.id) ?? []), api]);\n for (const entry of byId.entries()) {\n const id = entry[0];\n const duplicates = entry[1];\n if (duplicates.length < 2) continue;\n for (const duplicate of duplicates)\n add(\n out,\n duplicate.file,\n duplicate.source,\n duplicate.node,\n 'IPC_DUPLICATE_API_ID',\n `Duplicate internal API id '${id}'.`,\n );\n }\n return out.sort(\n (a: SecurityContractViolation, b: SecurityContractViolation) =>\n a.file.localeCompare(b.file) ||\n a.line - b.line ||\n a.code.localeCompare(b.code) ||\n a.message.localeCompare(b.message),\n );\n}\n\n// webpieces-disable no-function-outside-class -- one structured rule failure shared by tests and runner\nexport function securityContractsError(\n violations: readonly SecurityContractViolation[],\n): RuleFailError {\n const details = violations\n .map(\n (violation: SecurityContractViolation): string =>\n ` ${violation.file}:${String(violation.line)} [${violation.code}] ${violation.message}`,\n )\n .join('\\n');\n const first = violations[0];\n const message =\n 'API contracts in directly changed projects are not explicit and secure.\\n' + details;\n return new RuleFailError(\n RULE_NAMES.ENSURE_WE_ARE_SECURE,\n message,\n first?.line,\n first === undefined ? undefined : `[${first.code}] ${first.message}`,\n [\n new Option(\n \"Put exactly one authenticated method-level @WpAuth* decorator on every @Endpoint. Use @WpAuthPublic('non-empty reason') only when anonymous access is deliberate.\",\n true,\n ),\n new Option(\n \"For IPC-only contracts, replace HTTP metadata with class-level @WpInternal('stable-api-id') and exactly one @WpIpcEndpoint('stable-method-id') per method.\",\n ),\n ],\n );\n}\n\n// webpieces-disable no-function-outside-class -- one plumbing failure shared by tests and runner\nexport function missingSecurityBaseError(): InformAiError {\n return new InformAiError(\n 'ensure-we-are-secure could not determine the comparison base. Set NX_BASE to the base branch or commit and retry.',\n );\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class EnsureWeAreSecureValidator extends CodeValidator<EnsureWeAreSecureConfig> {\n constructor(config: EnsureWeAreSecureConfig) {\n super(config, 'ensure-we-are-secure', 'ensure-we-are-secure');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n if ((this.config.mode ?? 'OFF') === 'OFF') return { success: true };\n const base = process.env['NX_BASE'] ?? detectBase(workspaceRoot);\n if (base === null || base === undefined) {\n throw missingSecurityBaseError();\n }\n const changed = getChangedFiles(workspaceRoot, base, process.env['NX_HEAD'], {\n tsOnly: false,\n });\n const roots = findDirectlyChangedProjectRoots(workspaceRoot, changed);\n const violations = auditSecurityContracts(workspaceRoot, roots);\n if (violations.length === 0) return { success: true };\n throw securityContractsError(violations);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-ensure-we-are-secure.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-ensure-we-are-secure.ts"],"names":[],"mappings":";;;AA0dA,0EAUC;AA+BD,wDA8BC;AAGD,wDA2BC;AAGD,4DAIC;;AAtkBD,+FAA+F;AAC/F,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAkI;AAClI,8DAA0D;AAC1D,yCAA2D;AAC3D,qDAAiE;AAEjE,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC;IACtB,WAAW;IACX,YAAY;IACZ,eAAe;IACf,oBAAoB;IACpB,cAAc;IACd,iBAAiB;IACjB,cAAc;CACjB,CAAC,CAAC;AACH,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAChC,GAAG,SAAS;IACZ,SAAS;IACT,UAAU;IACV,YAAY;IACZ,eAAe;CAClB,CAAC,CAAC;AAEH,MAAa,yBAAyB;IAErB;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,IAAY,EACZ,IAAY,EACZ,OAAe;QAHf,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ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IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC,KAAK,KAAK;YAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QACpE,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,IAAA,yBAAU,EAAC,aAAa,CAAC,CAAC;QACjE,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACtC,MAAM,wBAAwB,EAAE,CAAC;QACrC,CAAC;QACD,MAAM,OAAO,GAAG,IAAA,8BAAe,EAAC,aAAa,EAAE,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;YACzE,MAAM,EAAE,KAAK;SAChB,CAAC,CAAC;QACH,MAAM,KAAK,GAAG,+BAA+B,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;QACtE,MAAM,UAAU,GAAG,sBAAsB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;QAChE,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QACtD,MAAM,sBAAsB,CAAC,UAAU,CAAC,CAAC;IAC7C,CAAC;CACJ,CAAA;AAnBY,gEAA0B;qCAA1B,0BAA0B;IADtC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,sCAAuB;GADlC,0BAA0B,CAmBtC","sourcesContent":["/** Audits explicit HTTP authentication and IPC-only contracts in directly changed projects. */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { EnsureWeAreSecureConfig, getChangedFiles, detectBase, Option, RuleFailError, RULE_NAMES } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { CodeValidator, ExecutorResult } from './code-validator';\n\nconst HTTP_AUTH = new Set([\n 'WpAuthJwt',\n 'WpAuthOidc',\n 'WpAuthWebhook',\n 'WpAuthSharedSecret',\n 'WpAuthApiKey',\n 'WpAuthLocalOnly',\n 'WpAuthPublic',\n]);\nconst CONTRACT_DECORATORS = new Set([\n ...HTTP_AUTH,\n 'ApiPath',\n 'Endpoint',\n 'WpInternal',\n 'WpIpcEndpoint',\n]);\n\nexport class SecurityContractViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly code: string,\n readonly message: string,\n ) {}\n}\n\nclass DecoratorUse {\n constructor(\n readonly name: string,\n readonly decorator: ts.Decorator,\n readonly call: ts.CallExpression | null,\n ) {}\n}\n\nclass CanonicalImports {\n readonly named = new Map<string, string>();\n readonly namespaces = new Set<string>();\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction isCanonicalModule(moduleName: string): boolean {\n return (\n moduleName === '@webpieces/core-util' ||\n moduleName === '@webpieces/core-util/ipc' ||\n moduleName.endsWith('/core-util/src/http/decorators') ||\n moduleName.includes('/core-util/src/ipc/')\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction importsOf(source: ts.SourceFile): CanonicalImports {\n const result = new CanonicalImports();\n for (const statement of source.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))\n continue;\n if (!isCanonicalModule(statement.moduleSpecifier.text)) continue;\n const bindings = statement.importClause?.namedBindings;\n if (bindings && ts.isNamedImports(bindings)) {\n for (const item of bindings.elements) {\n const exported = item.propertyName?.text ?? item.name.text;\n if (CONTRACT_DECORATORS.has(exported)) result.named.set(item.name.text, exported);\n }\n } else if (bindings && ts.isNamespaceImport(bindings)) {\n result.namespaces.add(bindings.name.text);\n }\n }\n return result;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction decoratorUse(decorator: ts.Decorator, imports: CanonicalImports): DecoratorUse | null {\n const expr = decorator.expression;\n const call = ts.isCallExpression(expr) ? expr : null;\n const callee = call?.expression ?? expr;\n if (ts.isIdentifier(callee)) {\n const canonical = imports.named.get(callee.text);\n return canonical ? new DecoratorUse(canonical, decorator, call) : null;\n }\n if (\n ts.isPropertyAccessExpression(callee) &&\n ts.isIdentifier(callee.expression) &&\n imports.namespaces.has(callee.expression.text)\n ) {\n return CONTRACT_DECORATORS.has(callee.name.text)\n ? new DecoratorUse(callee.name.text, decorator, call)\n : null;\n }\n return null;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction decoratorsOf(node: ts.Node, imports: CanonicalImports): DecoratorUse[] {\n if (!ts.canHaveDecorators(node)) return [];\n return (ts.getDecorators(node) ?? [])\n .map((decorator: ts.Decorator) => decoratorUse(decorator, imports))\n .filter((use): use is DecoratorUse => use !== null);\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction lineOf(source: ts.SourceFile, node: ts.Node): number {\n return source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction literalId(use: DecoratorUse): string | null {\n const arg = use.call?.arguments[0];\n if (!arg || (!ts.isStringLiteral(arg) && !ts.isNoSubstitutionTemplateLiteral(arg))) return null;\n const value = arg.text.trim();\n return value.length > 0 ? value : null;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction methodName(method: ts.MethodDeclaration): string {\n return ts.isIdentifier(method.name) || ts.isStringLiteral(method.name)\n ? method.name.text\n : method.name.getText();\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction hasPromiseReturn(method: ts.MethodDeclaration): boolean {\n const type = method.type;\n return (\n type !== undefined &&\n ts.isTypeReferenceNode(type) &&\n ts.isIdentifier(type.typeName) &&\n type.typeName.text === 'Promise'\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction add(\n out: SecurityContractViolation[],\n file: string,\n source: ts.SourceFile,\n node: ts.Node,\n code: string,\n message: string,\n): void {\n out.push(new SecurityContractViolation(file, lineOf(source, node), code, message));\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction checkHttpMethod(\n file: string,\n source: ts.SourceFile,\n method: ts.MethodDeclaration,\n uses: DecoratorUse[],\n out: SecurityContractViolation[],\n): void {\n const endpoints = uses.filter((use: DecoratorUse) => use.name === 'Endpoint');\n const auth = uses.filter((use: DecoratorUse) => HTTP_AUTH.has(use.name));\n const ipc = uses.filter((use: DecoratorUse) => use.name === 'WpIpcEndpoint');\n const label = methodName(method);\n if (endpoints.length > 1)\n add(\n out,\n file,\n source,\n method,\n 'HTTP_MULTIPLE_ENDPOINTS',\n `${label} has multiple @Endpoint decorators.`,\n );\n if (endpoints.length > 0 && auth.length !== 1) {\n add(\n out,\n file,\n source,\n method,\n 'HTTP_AUTH_COUNT',\n `${label} must have exactly one method-level @WpAuth* decorator; found ${auth.length}. Prefer an authenticated mode; use @WpAuthPublic('reason') only for deliberate anonymous access.`,\n );\n }\n if (endpoints.length === 0 && auth.length > 0)\n add(\n out,\n file,\n source,\n auth[0]!.decorator,\n 'HTTP_ORPHAN_AUTH',\n `${label} has @WpAuth* but no @Endpoint.`,\n );\n for (const publicUse of auth.filter((use: DecoratorUse) => use.name === 'WpAuthPublic')) {\n if (literalId(publicUse) === null)\n add(\n out,\n file,\n source,\n publicUse.decorator,\n 'HTTP_PUBLIC_REASON',\n `${label} must use @WpAuthPublic('non-empty reason').`,\n );\n }\n if (ipc.length > 0)\n add(\n out,\n file,\n source,\n ipc[0]!.decorator,\n 'HTTP_IPC_MIX',\n `${label} mixes HTTP and IPC endpoint metadata.`,\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction checkInternalMethod(\n file: string,\n source: ts.SourceFile,\n method: ts.MethodDeclaration,\n uses: DecoratorUse[],\n out: SecurityContractViolation[],\n ids: Set<string>,\n): void {\n const ipc = uses.filter((use: DecoratorUse) => use.name === 'WpIpcEndpoint');\n const endpoint = uses.some((use: DecoratorUse) => use.name === 'Endpoint');\n const auth = uses.some((use: DecoratorUse) => HTTP_AUTH.has(use.name));\n const label = methodName(method);\n if (ipc.length !== 1)\n add(\n out,\n file,\n source,\n method,\n 'IPC_ENDPOINT_COUNT',\n `${label} must have exactly one @WpIpcEndpoint('stable-method-id'); found ${ipc.length}.`,\n );\n if (endpoint || auth)\n add(\n out,\n file,\n source,\n method,\n 'IPC_HTTP_MIX',\n `${label} is internal and cannot use @Endpoint or @WpAuth*.`,\n );\n if (method.parameters.length !== 1)\n add(\n out,\n file,\n source,\n method,\n 'IPC_DTO_COUNT',\n `${label} must accept exactly one DTO argument; found ${method.parameters.length}.`,\n );\n if (!hasPromiseReturn(method))\n add(\n out,\n file,\n source,\n method,\n 'IPC_PROMISE_RETURN',\n `${label} must declare a Promise return type.`,\n );\n for (const use of ipc) {\n const id = literalId(use);\n if (id === null)\n add(\n out,\n file,\n source,\n use.decorator,\n 'IPC_METHOD_ID',\n `${label} requires a non-empty inline stable method id.`,\n );\n else if (ids.has(id))\n add(\n out,\n file,\n source,\n use.decorator,\n 'IPC_DUPLICATE_METHOD_ID',\n `${label} duplicates IPC method id '${id}'.`,\n );\n else ids.add(id);\n }\n}\n\nclass InternalApiId {\n constructor(\n readonly id: string,\n readonly file: string,\n readonly source: ts.SourceFile,\n readonly node: ts.Node,\n ) {}\n}\n\nclass ApiClassAudit {\n readonly classUses: DecoratorUse[];\n readonly methods: ts.MethodDeclaration[];\n readonly methodUses: DecoratorUse[][];\n readonly apiPaths: DecoratorUse[];\n readonly internals: DecoratorUse[];\n readonly classAuth: DecoratorUse[];\n readonly hasHttpMethod: boolean;\n readonly hasIpcMethod: boolean;\n readonly className: string;\n\n constructor(\n readonly statement: ts.ClassDeclaration,\n imports: CanonicalImports,\n ) {\n this.classUses = decoratorsOf(statement, imports);\n this.methods = statement.members.filter(ts.isMethodDeclaration);\n this.methodUses = this.methods.map((method: ts.MethodDeclaration) =>\n decoratorsOf(method, imports),\n );\n this.apiPaths = this.classUses.filter((use: DecoratorUse) => use.name === 'ApiPath');\n this.internals = this.classUses.filter((use: DecoratorUse) => use.name === 'WpInternal');\n this.classAuth = this.classUses.filter((use: DecoratorUse) => HTTP_AUTH.has(use.name));\n this.hasHttpMethod = this.methodUses.some((uses: DecoratorUse[]) =>\n uses.some((use: DecoratorUse) => use.name === 'Endpoint'),\n );\n this.hasIpcMethod = this.methodUses.some((uses: DecoratorUse[]) =>\n uses.some((use: DecoratorUse) => use.name === 'WpIpcEndpoint'),\n );\n this.className = statement.name?.text ?? '<anonymous class>';\n }\n\n get isHttp(): boolean {\n return this.apiPaths.length > 0 || this.hasHttpMethod;\n }\n\n get isInternal(): boolean {\n return this.internals.length > 0 || this.hasIpcMethod;\n }\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction checkClassShape(\n file: string,\n source: ts.SourceFile,\n audit: ApiClassAudit,\n out: SecurityContractViolation[],\n): void {\n if (audit.hasHttpMethod && audit.apiPaths.length === 0)\n add(\n out,\n file,\n source,\n audit.statement,\n 'HTTP_MISSING_API_PATH',\n `${audit.className} has @Endpoint methods but no @ApiPath.`,\n );\n if (audit.hasIpcMethod && audit.internals.length === 0)\n add(\n out,\n file,\n source,\n audit.statement,\n 'IPC_MISSING_INTERNAL',\n `${audit.className} has @WpIpcEndpoint methods but no @WpInternal('stable-api-id').`,\n );\n if (audit.apiPaths.length > 1)\n add(\n out,\n file,\n source,\n audit.statement,\n 'HTTP_API_PATH_COUNT',\n `${audit.className} has multiple @ApiPath decorators.`,\n );\n if (audit.internals.length > 1)\n add(\n out,\n file,\n source,\n audit.statement,\n 'IPC_INTERNAL_COUNT',\n `${audit.className} has multiple @WpInternal decorators.`,\n );\n if (audit.classAuth.length > 0)\n add(\n out,\n file,\n source,\n audit.classAuth[0]!.decorator,\n 'HTTP_CLASS_AUTH',\n `${audit.className} cannot declare class-level @WpAuth*; annotate every @Endpoint method.`,\n );\n if (audit.isHttp && audit.isInternal)\n add(\n out,\n file,\n source,\n audit.statement,\n 'HTTP_IPC_CLASS_MIX',\n `${audit.className} mixes HTTP and internal IPC contract metadata.`,\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction checkClassMethods(\n file: string,\n source: ts.SourceFile,\n audit: ApiClassAudit,\n out: SecurityContractViolation[],\n apiIds: InternalApiId[],\n): void {\n if (audit.internals.length === 0) {\n if (audit.isHttp)\n audit.methods.forEach((method: ts.MethodDeclaration, index: number) =>\n checkHttpMethod(file, source, method, audit.methodUses[index]!, out),\n );\n return;\n }\n const internal = audit.internals[0]!;\n const id = literalId(internal);\n if (id === null)\n add(\n out,\n file,\n source,\n internal.decorator,\n 'IPC_API_ID',\n `${audit.className} requires @WpInternal('non-empty-stable-api-id').`,\n );\n else apiIds.push(new InternalApiId(id, file, source, internal.decorator));\n if (audit.apiPaths.length > 0)\n add(\n out,\n file,\n source,\n audit.apiPaths[0]!.decorator,\n 'IPC_API_PATH',\n `${audit.className} is internal and cannot use @ApiPath.`,\n );\n const ids = new Set<string>();\n audit.methods.forEach((method: ts.MethodDeclaration, index: number) =>\n checkInternalMethod(file, source, method, audit.methodUses[index]!, out, ids),\n );\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction auditFile(\n file: string,\n workspaceRoot: string,\n apiIds: InternalApiId[],\n): SecurityContractViolation[] {\n const content = fs.readFileSync(path.join(workspaceRoot, file), 'utf-8');\n const source = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true);\n const imports = importsOf(source);\n const out: SecurityContractViolation[] = [];\n for (const statement of source.statements) {\n if (!ts.isClassDeclaration(statement)) continue;\n const audit = new ApiClassAudit(statement, imports);\n if (!audit.isHttp && !audit.isInternal && audit.classAuth.length === 0) continue;\n checkClassShape(file, source, audit, out);\n checkClassMethods(file, source, audit, out, apiIds);\n }\n return out;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction owningProjectJson(workspaceRoot: string, relativeFile: string): string | null {\n let dir = path.dirname(relativeFile);\n while (dir !== '.' && dir !== '') {\n const candidate = path.join(dir, 'project.json');\n if (fs.existsSync(path.join(workspaceRoot, candidate))) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return fs.existsSync(path.join(workspaceRoot, 'project.json')) ? 'project.json' : null;\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nexport function findDirectlyChangedProjectRoots(\n workspaceRoot: string,\n changedFiles: string[],\n): string[] {\n const roots = new Set<string>();\n for (const file of changedFiles) {\n const projectJson = owningProjectJson(workspaceRoot, file);\n if (projectJson !== null) roots.add(path.dirname(projectJson));\n }\n return [...roots].sort();\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nfunction projectFiles(workspaceRoot: string, projectRoot: string): string[] {\n const files: string[] = [];\n const fullRoot = path.join(workspaceRoot, projectRoot);\n const walk = (dir: string): void => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === '.git')\n continue;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (\n /\\.tsx?$/.test(entry.name) &&\n !entry.name.endsWith('.d.ts') &&\n !entry.name.endsWith('.spec.ts') &&\n !entry.name.endsWith('.test.ts') &&\n !entry.name.endsWith('.spec.tsx') &&\n !entry.name.endsWith('.test.tsx')\n ) {\n const rel = path.relative(workspaceRoot, full);\n const owner = owningProjectJson(workspaceRoot, rel);\n if (owner !== null && path.dirname(owner) === projectRoot) files.push(rel);\n }\n }\n };\n if (fs.existsSync(fullRoot)) walk(fullRoot);\n return files.sort();\n}\n\n// webpieces-disable no-function-outside-class -- stateless TypeScript AST security validator helper\nexport function auditSecurityContracts(\n workspaceRoot: string,\n projectRoots: string[],\n): SecurityContractViolation[] {\n const apiIds: InternalApiId[] = [];\n const files = projectRoots.flatMap((root: string) => projectFiles(workspaceRoot, root));\n const out = files.flatMap((file: string) => auditFile(file, workspaceRoot, apiIds));\n const byId = new Map<string, InternalApiId[]>();\n for (const api of apiIds) byId.set(api.id, [...(byId.get(api.id) ?? []), api]);\n for (const entry of byId.entries()) {\n const id = entry[0];\n const duplicates = entry[1];\n if (duplicates.length < 2) continue;\n for (const duplicate of duplicates)\n add(\n out,\n duplicate.file,\n duplicate.source,\n duplicate.node,\n 'IPC_DUPLICATE_API_ID',\n `Duplicate internal API id '${id}'.`,\n );\n }\n return out.sort(\n (a: SecurityContractViolation, b: SecurityContractViolation) =>\n a.file.localeCompare(b.file) ||\n a.line - b.line ||\n a.code.localeCompare(b.code) ||\n a.message.localeCompare(b.message),\n );\n}\n\n// webpieces-disable no-function-outside-class -- one structured rule failure shared by tests and runner\nexport function securityContractsError(\n violations: readonly SecurityContractViolation[],\n): RuleFailError {\n const details = violations\n .map(\n (violation: SecurityContractViolation): string =>\n ` ${violation.file}:${String(violation.line)} [${violation.code}] ${violation.message}`,\n )\n .join('\\n');\n const first = violations[0];\n const message =\n 'API contracts in directly changed projects are not explicit and secure.\\n' + details;\n return new RuleFailError(\n RULE_NAMES.ENSURE_WE_ARE_SECURE,\n message,\n first?.line,\n first === undefined ? undefined : `[${first.code}] ${first.message}`,\n [\n new Option(\n \"Put exactly one authenticated method-level @WpAuth* decorator on every @Endpoint. Use @WpAuthPublic('non-empty reason') only when anonymous access is deliberate.\",\n true,\n ),\n new Option(\n \"For IPC-only contracts, replace HTTP metadata with class-level @WpInternal('stable-api-id') and exactly one @WpIpcEndpoint('stable-method-id') per method.\",\n ),\n ],\n );\n}\n\n// webpieces-disable no-function-outside-class -- one plumbing failure shared by tests and runner\nexport function missingSecurityBaseError(): InformAiError {\n return new InformAiError(\n 'ensure-we-are-secure could not determine the comparison base. Set NX_BASE to the base branch or commit and retry.',\n );\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class EnsureWeAreSecureValidator extends CodeValidator<EnsureWeAreSecureConfig> {\n constructor(config: EnsureWeAreSecureConfig) {\n super(config, 'ensure-we-are-secure', 'ensure-we-are-secure');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n if ((this.config.mode ?? 'OFF') === 'OFF') return { success: true };\n const base = process.env['NX_BASE'] ?? detectBase(workspaceRoot);\n if (base === null || base === undefined) {\n throw missingSecurityBaseError();\n }\n const changed = getChangedFiles(workspaceRoot, base, process.env['NX_HEAD'], {\n tsOnly: false,\n });\n const roots = findDirectlyChangedProjectRoots(workspaceRoot, changed);\n const violations = auditSecurityContracts(workspaceRoot, roots);\n if (violations.length === 0) return { success: true };\n throw securityContractsError(violations);\n }\n}\n"]}
@@ -14,7 +14,7 @@ const tslib_1 = require("tslib");
14
14
  const child_process_1 = require("child_process");
15
15
  const fs = tslib_1.__importStar(require("fs"));
16
16
  const path = tslib_1.__importStar(require("path"));
17
- const rules_config_1 = require("@webpieces/rules-config");
17
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
18
18
  class NxStepRunner {
19
19
  /**
20
20
  * Distinct from 1 so a survivor abort is greppable in CI history and cannot be confused with an
@@ -68,7 +68,7 @@ class NxStepRunner {
68
68
  awaitExit(child) {
69
69
  return new Promise((resolve) => {
70
70
  child.on('error', (err) => {
71
- console.error(`[wp-ci] could not run nx: ${(0, rules_config_1.toError)(err).message}`);
71
+ console.error(`[wp-ci] could not run nx: ${(0, to_error_1.toError)(err).message}`);
72
72
  resolve(1);
73
73
  });
74
74
  child.on('close', (code) => {
@@ -1 +1 @@
1
- {"version":3,"file":"wp-ci-nx-runner.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/wp-ci-nx-runner.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;AAEH,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAE7B,0DAAkD;AAGlD,MAAa,YAAY;IACrB;;;OAGG;IACH,MAAM,CAAU,0BAA0B,GAAG,EAAE,CAAC;IAE/B,IAAI,CAAS;IACb,WAAW,CAAc;IACzB,QAAQ,CAAmB;IA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step for wp-ci and refuses to leave survivors behind.\n *\n * The step is spawned DETACHED, which on POSIX makes the child a process-group leader (pgid == pid).\n * That group id is the handle everything else needs: it is what `ps` is filtered on to enumerate\n * workers that outlived nx, and it is what gets SIGKILLed so the step's stdout can reach EOF.\n * Without the group there is no way to tell an orphaned nx worker from an unrelated process, because\n * orphans are re-parented away from the tree that spawned them.\n */\n\nimport { ChildProcess, spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { toError } from '@webpieces/rules-config';\nimport { GracePeriod, ProcessGroupKiller, SurvivorReporter, SurvivorWatchdog } from './wp-ci-survivors';\n\nexport class NxStepRunner {\n /**\n * Distinct from 1 so a survivor abort is greppable in CI history and cannot be confused with an\n * ordinary red build.\n */\n static readonly SURVIVOR_TIMEOUT_EXIT_CODE = 75;\n\n private readonly root: string;\n private readonly gracePeriod: GracePeriod;\n private readonly watchdog: SurvivorWatchdog;\n private readonly reporter: SurvivorReporter;\n private readonly killer: ProcessGroupKiller;\n /**\n * ONE budget for the whole wp-ci process, fixed at construction (i.e. at wp-ci start) rather\n * than per step. A per-step grace period would multiply by the number of steps and could still\n * overrun the outer CI timeout the number was chosen against.\n */\n private readonly deadlineEpochMillis: number;\n\n constructor(\n root: string,\n gracePeriod: GracePeriod,\n watchdog: SurvivorWatchdog,\n reporter: SurvivorReporter,\n killer: ProcessGroupKiller,\n ) {\n this.root = root;\n this.gracePeriod = gracePeriod;\n this.watchdog = watchdog;\n this.reporter = reporter;\n this.killer = killer;\n this.deadlineEpochMillis = Date.now() + gracePeriod.millis;\n }\n\n async run(args: string[], stepLabel: string): Promise<number> {\n const child = spawn(this.nxBin(), args, { stdio: 'inherit', cwd: this.root, detached: true });\n const exitCode = await this.awaitExit(child);\n\n const processGroupId = child.pid;\n if (processGroupId === undefined) return exitCode;\n return this.settleStep(processGroupId, stepLabel, exitCode);\n }\n\n /**\n * The whole point of the fix: a step is not finished when its child exits, it is finished when\n * nothing it spawned is left holding the step's stdout. Split out from `run` so it is unit\n * testable without spawning nx.\n */\n async settleStep(processGroupId: number, stepLabel: string, exitCode: number): Promise<number> {\n const scan = await this.watchdog.waitForGroupToDrain(processGroupId, this.deadlineEpochMillis);\n if (scan.scanError !== null) {\n this.reporter.reportScanUnavailable(stepLabel, scan.scanError);\n return exitCode;\n }\n if (scan.survivors.length === 0) return exitCode;\n\n this.reporter.reportSurvivors(stepLabel, this.gracePeriod, scan.survivors);\n this.killer.kill(processGroupId);\n return NxStepRunner.SURVIVOR_TIMEOUT_EXIT_CODE;\n }\n\n private awaitExit(child: ChildProcess): Promise<number> {\n return new Promise<number>((resolve: (code: number) => void) => {\n child.on('error', (err: Error) => {\n console.error(`[wp-ci] could not run nx: ${toError(err).message}`);\n resolve(1);\n });\n child.on('close', (code: number | null) => {\n resolve(code === null ? 1 : code);\n });\n });\n }\n\n private nxBin(): string {\n const local = path.join(this.root, 'node_modules', '.bin', 'nx');\n return fs.existsSync(local) ? local : 'nx';\n }\n}\n"]}
1
+ {"version":3,"file":"wp-ci-nx-runner.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/wp-ci-nx-runner.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;AAEH,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAE7B,iEAA6D;AAG7D,MAAa,YAAY;IACrB;;;OAGG;IACH,MAAM,CAAU,0BAA0B,GAAG,EAAE,CAAC;IAE/B,IAAI,CAAS;IACb,WAAW,CAAc;IACzB,QAAQ,CAAmB;IAC3B,QAAQ,CAAmB;IAC3B,MAAM,CAAqB;IAC5C;;;;OAIG;IACc,mBAAmB,CAAS;IAE7C,YACI,IAAY,EACZ,WAAwB,EACxB,QAA0B,EAC1B,QAA0B,EAC1B,MAA0B;QAE1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAA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AC,CAAC;QAC3E,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACjC,OAAO,YAAY,CAAC,0BAA0B,CAAC;IACnD,CAAC;IAEO,SAAS,CAAC,KAAmB;QACjC,OAAO,IAAI,OAAO,CAAS,CAAC,OAA+B,EAAE,EAAE;YAC3D,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,GAAU,EAAE,EAAE;gBAC7B,OAAO,CAAC,KAAK,CAAC,6BAA6B,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;gBACnE,OAAO,CAAC,CAAC,CAAC,CAAC;YACf,CAAC,CAAC,CAAC;YACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,IAAmB,EAAE,EAAE;gBACtC,OAAO,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YACtC,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAEO,KAAK;QACT,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,cAAc,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QACjE,OAAO,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;IAC/C,CAAC;;AA5EL,oCA6EC","sourcesContent":["/**\n * Runs one `nx` step for wp-ci and refuses to leave survivors behind.\n *\n * The step is spawned DETACHED, which on POSIX makes the child a process-group leader (pgid == pid).\n * That group id is the handle everything else needs: it is what `ps` is filtered on to enumerate\n * workers that outlived nx, and it is what gets SIGKILLed so the step's stdout can reach EOF.\n * Without the group there is no way to tell an orphaned nx worker from an unrelated process, because\n * orphans are re-parented away from the tree that spawned them.\n */\n\nimport { ChildProcess, spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { GracePeriod, ProcessGroupKiller, SurvivorReporter, SurvivorWatchdog } from './wp-ci-survivors';\n\nexport class NxStepRunner {\n /**\n * Distinct from 1 so a survivor abort is greppable in CI history and cannot be confused with an\n * ordinary red build.\n */\n static readonly SURVIVOR_TIMEOUT_EXIT_CODE = 75;\n\n private readonly root: string;\n private readonly gracePeriod: GracePeriod;\n private readonly watchdog: SurvivorWatchdog;\n private readonly reporter: SurvivorReporter;\n private readonly killer: ProcessGroupKiller;\n /**\n * ONE budget for the whole wp-ci process, fixed at construction (i.e. at wp-ci start) rather\n * than per step. A per-step grace period would multiply by the number of steps and could still\n * overrun the outer CI timeout the number was chosen against.\n */\n private readonly deadlineEpochMillis: number;\n\n constructor(\n root: string,\n gracePeriod: GracePeriod,\n watchdog: SurvivorWatchdog,\n reporter: SurvivorReporter,\n killer: ProcessGroupKiller,\n ) {\n this.root = root;\n this.gracePeriod = gracePeriod;\n this.watchdog = watchdog;\n this.reporter = reporter;\n this.killer = killer;\n this.deadlineEpochMillis = Date.now() + gracePeriod.millis;\n }\n\n async run(args: string[], stepLabel: string): Promise<number> {\n const child = spawn(this.nxBin(), args, { stdio: 'inherit', cwd: this.root, detached: true });\n const exitCode = await this.awaitExit(child);\n\n const processGroupId = child.pid;\n if (processGroupId === undefined) return exitCode;\n return this.settleStep(processGroupId, stepLabel, exitCode);\n }\n\n /**\n * The whole point of the fix: a step is not finished when its child exits, it is finished when\n * nothing it spawned is left holding the step's stdout. Split out from `run` so it is unit\n * testable without spawning nx.\n */\n async settleStep(processGroupId: number, stepLabel: string, exitCode: number): Promise<number> {\n const scan = await this.watchdog.waitForGroupToDrain(processGroupId, this.deadlineEpochMillis);\n if (scan.scanError !== null) {\n this.reporter.reportScanUnavailable(stepLabel, scan.scanError);\n return exitCode;\n }\n if (scan.survivors.length === 0) return exitCode;\n\n this.reporter.reportSurvivors(stepLabel, this.gracePeriod, scan.survivors);\n this.killer.kill(processGroupId);\n return NxStepRunner.SURVIVOR_TIMEOUT_EXIT_CODE;\n }\n\n private awaitExit(child: ChildProcess): Promise<number> {\n return new Promise<number>((resolve: (code: number) => void) => {\n child.on('error', (err: Error) => {\n console.error(`[wp-ci] could not run nx: ${toError(err).message}`);\n resolve(1);\n });\n child.on('close', (code: number | null) => {\n resolve(code === null ? 1 : code);\n });\n });\n }\n\n private nxBin(): string {\n const local = path.join(this.root, 'node_modules', '.bin', 'nx');\n return fs.existsSync(local) ? local : 'nx';\n }\n}\n"]}
@@ -20,7 +20,7 @@ exports.ProcessGroupKiller = exports.SurvivorReporter = exports.SurvivorWatchdog
20
20
  const tslib_1 = require("tslib");
21
21
  const child_process_1 = require("child_process");
22
22
  const fs = tslib_1.__importStar(require("fs"));
23
- const rules_config_1 = require("@webpieces/rules-config");
23
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
24
24
  /** One process that is still alive after the step that spawned it has already finished. */
25
25
  class SurvivingProcess {
26
26
  pid;
@@ -70,7 +70,7 @@ class ProcessGroupScanner {
70
70
  maxBuffer: ProcessGroupScanner.PS_MAX_BUFFER_BYTES,
71
71
  });
72
72
  if (result.error) {
73
- return new SurvivorScan([], `ps could not be run: ${(0, rules_config_1.toError)(result.error).message}`);
73
+ return new SurvivorScan([], `ps could not be run: ${(0, to_error_1.toError)(result.error).message}`);
74
74
  }
75
75
  if (result.status !== 0) {
76
76
  const stderr = (result.stderr ?? '').trim();
@@ -192,7 +192,7 @@ class SurvivorReporter {
192
192
  fs.writeSync(this.fd, `${text}\n`);
193
193
  }
194
194
  catch (err) {
195
- const error = (0, rules_config_1.toError)(err);
195
+ const error = (0, to_error_1.toError)(err);
196
196
  console.error(`[wp-ci] could not write survivor diagnostic: ${error.message}`);
197
197
  }
198
198
  }
@@ -206,7 +206,7 @@ class ProcessGroupKiller {
206
206
  process.kill(-processGroupId, 'SIGKILL');
207
207
  }
208
208
  catch (err) {
209
- const error = (0, rules_config_1.toError)(err);
209
+ const error = (0, to_error_1.toError)(err);
210
210
  console.error(`[wp-ci] could not kill process group ${processGroupId}: ${error.message}`);
211
211
  }
212
212
  }
@@ -1 +1 @@
1
- {"version":3,"file":"wp-ci-survivors.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/wp-ci-survivors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;AAEH,iDAA0C;AAC1C,+CAAyB;AAEzB,0DAAkD;AAElD,2FAA2F;AAC3F,MAAa,gBAAgB;IAChB,GAAG,CAAS;IACZ,WAAW,CAAS;IAE7B,YAAY,GAAW,EAAE,WAAmB;QACxC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACnC,CAAC;CACJ;AARD,4CAQC;AAED;;;;GAIG;AACH,MAAa,YAAY;IACZ,SAAS,CAAqB;IAC9B,SAAS,CAAgB;IAElC,YAAY,SAA6B,EAAE,SAAwB;QAC/D,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;CACJ;AARD,oCAQC;AAED,sGAAsG;AACtG,MAAa,WAAW;IACX,MAAM,CAAS;IACf,MAAM,CAAS;IAExB,YAAY,MAAc,EAAE,MAAc;QACtC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AARD,kCAQC;AAED;;;;;GAKG;AACH,MAAa,mBAAmB;IACpB,MAAM,CAAU,mBAAmB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;IACvD,MAAM,CAAU,YAAY,GAAG,6BAA6B,CAAC;IAErE,IAAI,CAAC,cAAsB;QACvB,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,kBAAkB,CAAC,EAAE;YAC7D,QAAQ,EAAE,MAAM;YAChB,SAAS,EAA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AC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,CAAC,KAAK,CAAC,gDAAgD,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACnF,CAAC;IACL,CAAC;;AA7CL,4CA8CC;AAED,wGAAwG;AACxG,MAAa,kBAAkB;IAC3B,IAAI,CAAC,cAAsB;QACvB,0HAA0H;QAC1H,IAAI,CAAC;YACD,OAAO,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE,SAAS,CAAC,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,CAAC,KAAK,CAAC,wCAAwC,cAAc,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC9F,CAAC;IACL,CAAC;CACJ;AAVD,gDAUC","sourcesContent":["/**\n * wp-ci survivor watchdog.\n *\n * WHY this exists (see backlog/bug-wp-ci-hangs-forever-after-success-...md):\n * a CI step that runs `wp-ci` can hang FOREVER *after* every task has succeeded. GitHub Actions\n * ends a step when the step's stdout reaches EOF, not when the shell exits. Because the nx child\n * was handed the step's real stdout fd, any nx worker that outlives nx keeps that fd open, so the\n * step never ends — no output, no error, the whole job timeout burned with a zero exit code\n * already in hand. Three hours and eleven CI runs went into diagnosing that once.\n *\n * The cure is to make the failure SAY SO. Every nx step is spawned into its own process group, and\n * once the step has finished we wait for that group to drain. If anything is still alive when the\n * grace period expires we print every surviving pid with its full command line, kill the group so\n * the step's stdout can finally reach EOF, and exit non-zero. One log line replaces the whole\n * investigation.\n */\n\nimport { spawnSync } from 'child_process';\nimport * as fs from 'fs';\n\nimport { toError } from '@webpieces/rules-config';\n\n/** One process that is still alive after the step that spawned it has already finished. */\nexport class SurvivingProcess {\n readonly pid: number;\n readonly commandLine: string;\n\n constructor(pid: number, commandLine: string) {\n this.pid = pid;\n this.commandLine = commandLine;\n }\n}\n\n/**\n * Outcome of one `ps` sweep. `scanError` is non-null when `ps` itself could not be consulted\n * (not every container ships it) — that must never mask the real build result, so a failed scan\n * degrades to \"assume drained\" rather than throwing.\n */\nexport class SurvivorScan {\n readonly survivors: SurvivingProcess[];\n readonly scanError: string | null;\n\n constructor(survivors: SurvivingProcess[], scanError: string | null) {\n this.survivors = survivors;\n this.scanError = scanError;\n }\n}\n\n/** How long wp-ci may wait for survivors, and where that number came from (printed in the banner). */\nexport class GracePeriod {\n readonly millis: number;\n readonly source: string;\n\n constructor(millis: number, source: string) {\n this.millis = millis;\n this.source = source;\n }\n}\n\n/**\n * Enumerates the processes still running in a given process group, with full argv.\n * `ps -A -o pid=,pgid=,args=` is the one spelling that behaves the same on macOS (BSD ps) and Linux\n * (procps), which is why the fields are requested with trailing `=` (header suppression) instead of\n * `-eo`.\n */\nexport class ProcessGroupScanner {\n private static readonly PS_MAX_BUFFER_BYTES = 16 * 1024 * 1024;\n private static readonly LINE_PATTERN = /^\\s*(\\d+)\\s+(\\d+)\\s+(\\S.*)$/;\n\n scan(processGroupId: number): SurvivorScan {\n const result = spawnSync('ps', ['-A', '-o', 'pid=,pgid=,args='], {\n encoding: 'utf8',\n maxBuffer: ProcessGroupScanner.PS_MAX_BUFFER_BYTES,\n });\n if (result.error) {\n return new SurvivorScan([], `ps could not be run: ${toError(result.error).message}`);\n }\n if (result.status !== 0) {\n const stderr = (result.stderr ?? '').trim();\n return new SurvivorScan([], `ps exited with status ${result.status}: ${stderr}`);\n }\n return new SurvivorScan(this.parse(result.stdout ?? '', processGroupId), null);\n }\n\n /** Exposed so the parsing can be unit-tested against real macOS/Linux `ps` output. */\n parse(psOutput: string, processGroupId: number): SurvivingProcess[] {\n const found: SurvivingProcess[] = [];\n const lines = psOutput.split('\\n');\n for (const line of lines) {\n const match = ProcessGroupScanner.LINE_PATTERN.exec(line);\n if (match === null) continue;\n const pid = Number(match[1]);\n const pgid = Number(match[2]);\n if (pgid !== processGroupId) continue;\n if (pid === process.pid) continue;\n found.push(new SurvivingProcess(pid, (match[3] ?? '').trim()));\n }\n return found;\n }\n}\n\n/**\n * Resolves the grace period. The default is 25 minutes: the client repo whose CI this incident came\n * from uses a 30-minute step timeout, so firing at 25 leaves headroom for the diagnostic to be\n * printed and flushed before the outer timeout kills everything (a diagnostic that races the job\n * timeout is no diagnostic at all).\n *\n * Overridable by ENV VAR rather than by a webpieces.config.json key on purpose: the config\n * validator that runs against this repo is one release behind the source, so a brand-new config key\n * is rejected as unknown and deadlocks the session. An env var ships in the same PR as its reader.\n */\nexport class GracePeriodResolver {\n static readonly DEFAULT_MINUTES = 25;\n static readonly ENV_VAR = 'WP_CI_SURVIVOR_GRACE_MINUTES';\n\n resolve(env: NodeJS.ProcessEnv): GracePeriod {\n const defaultMillis = GracePeriodResolver.DEFAULT_MINUTES * 60 * 1000;\n const raw = env[GracePeriodResolver.ENV_VAR];\n if (raw === undefined || raw.trim() === '') {\n return new GracePeriod(defaultMillis, `default ${GracePeriodResolver.DEFAULT_MINUTES} minutes`);\n }\n const minutes = Number(raw.trim());\n if (!Number.isFinite(minutes) || minutes < 0) {\n return new GracePeriod(\n defaultMillis,\n `default ${GracePeriodResolver.DEFAULT_MINUTES} minutes (ignored unparseable ${GracePeriodResolver.ENV_VAR}=${raw})`,\n );\n }\n return new GracePeriod(minutes * 60 * 1000, `${GracePeriodResolver.ENV_VAR}=${raw.trim()}`);\n }\n}\n\n/** Polls the process group until it drains, the deadline passes, or `ps` turns out to be unusable. */\nexport class SurvivorWatchdog {\n private readonly scanner: ProcessGroupScanner;\n private readonly pollIntervalMillis: number;\n\n constructor(scanner: ProcessGroupScanner, pollIntervalMillis: number) {\n this.scanner = scanner;\n this.pollIntervalMillis = pollIntervalMillis;\n }\n\n async waitForGroupToDrain(processGroupId: number, deadlineEpochMillis: number): Promise<SurvivorScan> {\n let scan = this.scanner.scan(processGroupId);\n while (scan.scanError === null && scan.survivors.length > 0 && Date.now() < deadlineEpochMillis) {\n await this.sleep(this.pollIntervalMillis);\n scan = this.scanner.scan(processGroupId);\n }\n return scan;\n }\n\n private sleep(millis: number): Promise<void> {\n return new Promise<void>((resolve: () => void) => {\n setTimeout(resolve, millis);\n });\n }\n}\n\n/**\n * Prints the banner with `fs.writeSync(2, …)` rather than `console.error`. The entire failure mode\n * being diagnosed is entangled stdio, and node's console is asynchronous on a pipe — a buffered\n * message can be lost when the process exits or is killed moments later. A synchronous write to fd 2\n * is on the wire before the next line of code runs.\n */\nexport class SurvivorReporter {\n private static readonly RULE = '='.repeat(78);\n private static readonly STDERR_FD = 2;\n\n /** The fd to write to; only tests ever pass anything other than stderr. */\n private readonly fd: number;\n\n constructor(fd: number = SurvivorReporter.STDERR_FD) {\n this.fd = fd;\n }\n\n reportSurvivors(stepLabel: string, gracePeriod: GracePeriod, survivors: SurvivingProcess[]): void {\n const lines: string[] = [];\n lines.push('');\n lines.push(SurvivorReporter.RULE);\n lines.push('❌ wp-ci ABORTED — processes SURVIVED a step that already finished');\n lines.push(SurvivorReporter.RULE);\n lines.push(`Step: ${stepLabel}`);\n lines.push(`Grace period: ${gracePeriod.source} (${gracePeriod.millis} ms) — expired.`);\n lines.push('');\n lines.push('These processes still hold this step\\'s stdout open, so CI would hang forever');\n lines.push('with all work already done. They are listed with full command lines:');\n lines.push('');\n for (const survivor of survivors) {\n lines.push(` pid ${survivor.pid} ${survivor.commandLine}`);\n }\n lines.push('');\n lines.push(`Killing process group and failing. Raise/lower the wait with ${GracePeriodResolver.ENV_VAR}=<minutes>.`);\n lines.push(SurvivorReporter.RULE);\n lines.push('');\n this.writeStderr(lines.join('\\n'));\n }\n\n reportScanUnavailable(stepLabel: string, scanError: string): void {\n this.writeStderr(`\\n⚠️ wp-ci could not check for surviving processes after ${stepLabel}: ${scanError}\\n`);\n }\n\n private writeStderr(text: string): void {\n // webpieces-disable no-unmanaged-exceptions -- a diagnostic must never replace the real failure\n try {\n fs.writeSync(this.fd, `${text}\\n`);\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`[wp-ci] could not write survivor diagnostic: ${error.message}`);\n }\n }\n}\n\n/** SIGKILLs a whole process group, so the leaked stdout fd is finally released and the step can end. */\nexport class ProcessGroupKiller {\n kill(processGroupId: number): void {\n // webpieces-disable no-unmanaged-exceptions -- the group may drain between scan and kill; that is a success, not an error\n try {\n process.kill(-processGroupId, 'SIGKILL');\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`[wp-ci] could not kill process group ${processGroupId}: ${error.message}`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"wp-ci-survivors.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/wp-ci-survivors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;AAEH,iDAA0C;AAC1C,+CAAyB;AAEzB,iEAA6D;AAE7D,2FAA2F;AAC3F,MAAa,gBAAgB;IAChB,GAAG,CAAS;IACZ,WAAW,CAAS;IAE7B,YAAY,GAAW,EAAE,WAAmB;QACxC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACnC,CAAC;CACJ;AARD,4CAQC;AAED;;;;GAIG;AACH,MAAa,YAAY;IACZ,SAAS,CAAqB;IAC9B,SAAS,CAAgB;IAElC,YAAY,SAA6B,EAAE,SAAwB;QAC/D,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;CACJ;AARD,oCAQC;AAED,sGAAsG;AACtG,MAAa,WAAW;IACX,MAAM,CAAS;IACf,MAAM,CAAS;IAExB,YAAY,MAAc,EAAE,MAAc;QACtC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AARD,kCAQC;AAED;;;;;GAKG;AACH,MAAa,mBAAmB;IACpB,MAAM,CAAU,mBAAmB,GA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,EAAE,SAAiB;QACtD,IAAI,CAAC,WAAW,CAAC,6DAA6D,SAAS,KAAK,SAAS,IAAI,CAAC,CAAC;IAC/G,CAAC;IAEO,WAAW,CAAC,IAAY;QAC5B,gGAAgG;QAChG,IAAI,CAAC;YACD,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,GAAG,IAAI,IAAI,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,CAAC,KAAK,CAAC,gDAAgD,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACnF,CAAC;IACL,CAAC;;AA7CL,4CA8CC;AAED,wGAAwG;AACxG,MAAa,kBAAkB;IAC3B,IAAI,CAAC,cAAsB;QACvB,0HAA0H;QAC1H,IAAI,CAAC;YACD,OAAO,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE,SAAS,CAAC,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,CAAC,KAAK,CAAC,wCAAwC,cAAc,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC9F,CAAC;IACL,CAAC;CACJ;AAVD,gDAUC","sourcesContent":["/**\n * wp-ci survivor watchdog.\n *\n * WHY this exists (see backlog/bug-wp-ci-hangs-forever-after-success-...md):\n * a CI step that runs `wp-ci` can hang FOREVER *after* every task has succeeded. GitHub Actions\n * ends a step when the step's stdout reaches EOF, not when the shell exits. Because the nx child\n * was handed the step's real stdout fd, any nx worker that outlives nx keeps that fd open, so the\n * step never ends — no output, no error, the whole job timeout burned with a zero exit code\n * already in hand. Three hours and eleven CI runs went into diagnosing that once.\n *\n * The cure is to make the failure SAY SO. Every nx step is spawned into its own process group, and\n * once the step has finished we wait for that group to drain. If anything is still alive when the\n * grace period expires we print every surviving pid with its full command line, kill the group so\n * the step's stdout can finally reach EOF, and exit non-zero. One log line replaces the whole\n * investigation.\n */\n\nimport { spawnSync } from 'child_process';\nimport * as fs from 'fs';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/** One process that is still alive after the step that spawned it has already finished. */\nexport class SurvivingProcess {\n readonly pid: number;\n readonly commandLine: string;\n\n constructor(pid: number, commandLine: string) {\n this.pid = pid;\n this.commandLine = commandLine;\n }\n}\n\n/**\n * Outcome of one `ps` sweep. `scanError` is non-null when `ps` itself could not be consulted\n * (not every container ships it) — that must never mask the real build result, so a failed scan\n * degrades to \"assume drained\" rather than throwing.\n */\nexport class SurvivorScan {\n readonly survivors: SurvivingProcess[];\n readonly scanError: string | null;\n\n constructor(survivors: SurvivingProcess[], scanError: string | null) {\n this.survivors = survivors;\n this.scanError = scanError;\n }\n}\n\n/** How long wp-ci may wait for survivors, and where that number came from (printed in the banner). */\nexport class GracePeriod {\n readonly millis: number;\n readonly source: string;\n\n constructor(millis: number, source: string) {\n this.millis = millis;\n this.source = source;\n }\n}\n\n/**\n * Enumerates the processes still running in a given process group, with full argv.\n * `ps -A -o pid=,pgid=,args=` is the one spelling that behaves the same on macOS (BSD ps) and Linux\n * (procps), which is why the fields are requested with trailing `=` (header suppression) instead of\n * `-eo`.\n */\nexport class ProcessGroupScanner {\n private static readonly PS_MAX_BUFFER_BYTES = 16 * 1024 * 1024;\n private static readonly LINE_PATTERN = /^\\s*(\\d+)\\s+(\\d+)\\s+(\\S.*)$/;\n\n scan(processGroupId: number): SurvivorScan {\n const result = spawnSync('ps', ['-A', '-o', 'pid=,pgid=,args='], {\n encoding: 'utf8',\n maxBuffer: ProcessGroupScanner.PS_MAX_BUFFER_BYTES,\n });\n if (result.error) {\n return new SurvivorScan([], `ps could not be run: ${toError(result.error).message}`);\n }\n if (result.status !== 0) {\n const stderr = (result.stderr ?? '').trim();\n return new SurvivorScan([], `ps exited with status ${result.status}: ${stderr}`);\n }\n return new SurvivorScan(this.parse(result.stdout ?? '', processGroupId), null);\n }\n\n /** Exposed so the parsing can be unit-tested against real macOS/Linux `ps` output. */\n parse(psOutput: string, processGroupId: number): SurvivingProcess[] {\n const found: SurvivingProcess[] = [];\n const lines = psOutput.split('\\n');\n for (const line of lines) {\n const match = ProcessGroupScanner.LINE_PATTERN.exec(line);\n if (match === null) continue;\n const pid = Number(match[1]);\n const pgid = Number(match[2]);\n if (pgid !== processGroupId) continue;\n if (pid === process.pid) continue;\n found.push(new SurvivingProcess(pid, (match[3] ?? '').trim()));\n }\n return found;\n }\n}\n\n/**\n * Resolves the grace period. The default is 25 minutes: the client repo whose CI this incident came\n * from uses a 30-minute step timeout, so firing at 25 leaves headroom for the diagnostic to be\n * printed and flushed before the outer timeout kills everything (a diagnostic that races the job\n * timeout is no diagnostic at all).\n *\n * Overridable by ENV VAR rather than by a webpieces.config.json key on purpose: the config\n * validator that runs against this repo is one release behind the source, so a brand-new config key\n * is rejected as unknown and deadlocks the session. An env var ships in the same PR as its reader.\n */\nexport class GracePeriodResolver {\n static readonly DEFAULT_MINUTES = 25;\n static readonly ENV_VAR = 'WP_CI_SURVIVOR_GRACE_MINUTES';\n\n resolve(env: NodeJS.ProcessEnv): GracePeriod {\n const defaultMillis = GracePeriodResolver.DEFAULT_MINUTES * 60 * 1000;\n const raw = env[GracePeriodResolver.ENV_VAR];\n if (raw === undefined || raw.trim() === '') {\n return new GracePeriod(defaultMillis, `default ${GracePeriodResolver.DEFAULT_MINUTES} minutes`);\n }\n const minutes = Number(raw.trim());\n if (!Number.isFinite(minutes) || minutes < 0) {\n return new GracePeriod(\n defaultMillis,\n `default ${GracePeriodResolver.DEFAULT_MINUTES} minutes (ignored unparseable ${GracePeriodResolver.ENV_VAR}=${raw})`,\n );\n }\n return new GracePeriod(minutes * 60 * 1000, `${GracePeriodResolver.ENV_VAR}=${raw.trim()}`);\n }\n}\n\n/** Polls the process group until it drains, the deadline passes, or `ps` turns out to be unusable. */\nexport class SurvivorWatchdog {\n private readonly scanner: ProcessGroupScanner;\n private readonly pollIntervalMillis: number;\n\n constructor(scanner: ProcessGroupScanner, pollIntervalMillis: number) {\n this.scanner = scanner;\n this.pollIntervalMillis = pollIntervalMillis;\n }\n\n async waitForGroupToDrain(processGroupId: number, deadlineEpochMillis: number): Promise<SurvivorScan> {\n let scan = this.scanner.scan(processGroupId);\n while (scan.scanError === null && scan.survivors.length > 0 && Date.now() < deadlineEpochMillis) {\n await this.sleep(this.pollIntervalMillis);\n scan = this.scanner.scan(processGroupId);\n }\n return scan;\n }\n\n private sleep(millis: number): Promise<void> {\n return new Promise<void>((resolve: () => void) => {\n setTimeout(resolve, millis);\n });\n }\n}\n\n/**\n * Prints the banner with `fs.writeSync(2, …)` rather than `console.error`. The entire failure mode\n * being diagnosed is entangled stdio, and node's console is asynchronous on a pipe — a buffered\n * message can be lost when the process exits or is killed moments later. A synchronous write to fd 2\n * is on the wire before the next line of code runs.\n */\nexport class SurvivorReporter {\n private static readonly RULE = '='.repeat(78);\n private static readonly STDERR_FD = 2;\n\n /** The fd to write to; only tests ever pass anything other than stderr. */\n private readonly fd: number;\n\n constructor(fd: number = SurvivorReporter.STDERR_FD) {\n this.fd = fd;\n }\n\n reportSurvivors(stepLabel: string, gracePeriod: GracePeriod, survivors: SurvivingProcess[]): void {\n const lines: string[] = [];\n lines.push('');\n lines.push(SurvivorReporter.RULE);\n lines.push('❌ wp-ci ABORTED — processes SURVIVED a step that already finished');\n lines.push(SurvivorReporter.RULE);\n lines.push(`Step: ${stepLabel}`);\n lines.push(`Grace period: ${gracePeriod.source} (${gracePeriod.millis} ms) — expired.`);\n lines.push('');\n lines.push('These processes still hold this step\\'s stdout open, so CI would hang forever');\n lines.push('with all work already done. They are listed with full command lines:');\n lines.push('');\n for (const survivor of survivors) {\n lines.push(` pid ${survivor.pid} ${survivor.commandLine}`);\n }\n lines.push('');\n lines.push(`Killing process group and failing. Raise/lower the wait with ${GracePeriodResolver.ENV_VAR}=<minutes>.`);\n lines.push(SurvivorReporter.RULE);\n lines.push('');\n this.writeStderr(lines.join('\\n'));\n }\n\n reportScanUnavailable(stepLabel: string, scanError: string): void {\n this.writeStderr(`\\n⚠️ wp-ci could not check for surviving processes after ${stepLabel}: ${scanError}\\n`);\n }\n\n private writeStderr(text: string): void {\n // webpieces-disable no-unmanaged-exceptions -- a diagnostic must never replace the real failure\n try {\n fs.writeSync(this.fd, `${text}\\n`);\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`[wp-ci] could not write survivor diagnostic: ${error.message}`);\n }\n }\n}\n\n/** SIGKILLs a whole process group, so the leaked stdout fd is finally released and the step can end. */\nexport class ProcessGroupKiller {\n kill(processGroupId: number): void {\n // webpieces-disable no-unmanaged-exceptions -- the group may drain between scan and kill; that is a success, not an error\n try {\n process.kill(-processGroupId, 'SIGKILL');\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`[wp-ci] could not kill process group ${processGroupId}: ${error.message}`);\n }\n }\n}\n"]}
package/src/wp-ci.js CHANGED
@@ -26,6 +26,9 @@ const path = tslib_1.__importStar(require("path"));
26
26
  require("reflect-metadata");
27
27
  const inversify_1 = require("inversify");
28
28
  const rules_config_1 = require("@webpieces/rules-config");
29
+ const tooling_common_1 = require("@webpieces/tooling-common");
30
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
31
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
29
32
  const code_rules_app_1 = require("./code-rules-app");
30
33
  const code_rules_context_1 = require("./code-rules-context");
31
34
  const code_rules_config_table_1 = require("./code-rules-config-table");
@@ -60,8 +63,8 @@ function isPluginRegistered(nxJsonPath) {
60
63
  return plugins.some((entry) => pluginEntryMatches(entry));
61
64
  }
62
65
  catch (err) {
63
- const error = (0, rules_config_1.toError)(err);
64
- throw new rules_config_1.InformAiError(`nx.json has invalid JSON — fix the file, then retry.\nParse error: ${error.message}\nFile: ${nxJsonPath}`);
66
+ const error = (0, to_error_1.toError)(err);
67
+ throw new tooling_common_1.InformAiError(`nx.json has invalid JSON — fix the file, then retry.\nParse error: ${error.message}\nFile: ${nxJsonPath}`);
65
68
  }
66
69
  }
67
70
  async function runStandalone(cwd) {
@@ -109,7 +112,7 @@ async function main() {
109
112
  }
110
113
  const gracePeriod = new wp_ci_survivors_1.GracePeriodResolver().resolve(process.env);
111
114
  const runner = new wp_ci_nx_runner_1.NxStepRunner(root, gracePeriod, new wp_ci_survivors_1.SurvivorWatchdog(new wp_ci_survivors_1.ProcessGroupScanner(), SURVIVOR_POLL_INTERVAL_MILLIS), new wp_ci_survivors_1.SurvivorReporter(), new wp_ci_survivors_1.ProcessGroupKiller());
112
- const hotfix = new rules_config_1.BranchIdentity().isHotfix();
115
+ const hotfix = new repo_workflow_core_1.BranchIdentity().isHotfix();
113
116
  // Validate the root policy exactly once. webpieces.config.json is deliberately NOT a
114
117
  // sharedGlobal Nx input: making every project hash depend on it turned a policy-only edit into
115
118
  // a workspace-wide compile/lint/test. The scoped rules project preserves the gate without that
@@ -134,11 +137,11 @@ async function main() {
134
137
  process.exit(ciCode);
135
138
  }
136
139
  catch (err) {
137
- const error = (0, rules_config_1.toError)(err);
140
+ const error = (0, to_error_1.toError)(err);
138
141
  if (error instanceof rules_config_1.RuleFailError) {
139
142
  console.error((0, rules_config_1.renderRuleFailForHuman)(error));
140
143
  }
141
- else if (err instanceof rules_config_1.InformAiError) {
144
+ else if (err instanceof tooling_common_1.InformAiError) {
142
145
  console.error(error.message);
143
146
  }
144
147
  else {
package/src/wp-ci.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"wp-ci.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/wp-ci.ts"],"names":[],"mappings":";;AACA;;;;;;;;;;;;;;;;;;GAkBG;;;AAEH,+CAAyB;AACzB,mDAA6B;AAE7B,4BAA0B;AAC1B,yCAAsC;AACtC,0DAAyK;AACzK,qDAAgD;AAChD,6DAAuE;AACvE,uEAA4D;AAC5D,uDAAiD;AACjD,uDAAqI;AAErI,sGAAsG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AC;aAAM,IAAI,GAAG,YAAY,4BAAa,EAAE,CAAC;YACtC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACjC,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,KAAK,CAAC,6BAA6B,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAChE,CAAC;QACD,iGAAiG;QACjG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC;AAED,KAAK,IAAI,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * wp-ci — the universal webpieces CI entrypoint.\n *\n * Works in BOTH an Nx monorepo and a plain (non-Nx) repo, because the detection of\n * \"are we even in Nx?\" cannot live inside an Nx executor (by the time an executor runs,\n * Nx is already running). Dispatch:\n *\n * - no nx.json (non-Nx repo) -> run the standalone code validators, succeed.\n * - nx.json present, plugin NOT in it -> fail with the exact install command.\n * - nx.json present, plugin registered -> normal branch: validators + affected `ci`;\n * `/hotfix/` branch: affected `hotfix-ci` (build + test only).\n *\n * Repos reference this as a bin (`\"webpieces:ci\": \"wp-ci\"`) so the logic is versioned in\n * the npm package instead of copy-pasted into each repo's package.json (which drifts).\n *\n * Every nx step goes through NxStepRunner, which spawns it into its own process group and refuses\n * to return until that group has drained — a step whose workers outlive it holds the CI step's\n * stdout open and hangs the job forever with all work already green. See wp-ci-survivors.ts.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport 'reflect-metadata';\nimport { Container } from 'inversify';\nimport { loadAndValidate, InformAiError, RuleFailError, renderRuleFailForHuman, toError, RepoRootFinder, BaseRuleConfig, BranchIdentity } from '@webpieces/rules-config';\nimport { CodeRulesApp } from './code-rules-app';\nimport { WorkspaceRoot, MatchRulesHolder } from './code-rules-context';\nimport { CONFIG_BINDINGS } from './code-rules-config-table';\nimport { NxStepRunner } from './wp-ci-nx-runner';\nimport { GracePeriodResolver, ProcessGroupKiller, ProcessGroupScanner, SurvivorReporter, SurvivorWatchdog } from './wp-ci-survivors';\n\n/** How often the watchdog re-runs `ps` while waiting for a finished step's process group to drain. */\nconst SURVIVOR_POLL_INTERVAL_MILLIS = 1000;\n\nconst NX_PLUGIN_NAME = '@webpieces/nx-webpieces-rules';\n\ninterface NxPluginObject {\n plugin?: string;\n}\n\ntype NxPluginEntry = string | NxPluginObject;\n\ninterface RawNxJson {\n plugins?: NxPluginEntry[];\n}\n\nfunction findUp(filename: string, startDir: string): string | null {\n let dir = startDir;\n while (true) {\n const candidate = path.join(dir, filename);\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nfunction pluginEntryMatches(entry: NxPluginEntry): boolean {\n if (typeof entry === 'string') return entry === NX_PLUGIN_NAME;\n return entry.plugin === NX_PLUGIN_NAME;\n}\n\nfunction isPluginRegistered(nxJsonPath: string): boolean {\n const raw = fs.readFileSync(nxJsonPath, 'utf8');\n // webpieces-disable no-unmanaged-exceptions -- rethrow as InformAiError so global catch surfaces readable message to AI\n try {\n const parsed = JSON.parse(raw) as RawNxJson;\n const plugins = parsed.plugins ?? [];\n return plugins.some((entry: NxPluginEntry) => pluginEntryMatches(entry));\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`nx.json has invalid JSON — fix the file, then retry.\\nParse error: ${error.message}\\nFile: ${nxJsonPath}`);\n }\n}\n\nasync function runStandalone(cwd: string): Promise<number> {\n const workspaceRoot = new RepoRootFinder().resolveRepoRoot(cwd);\n const loaded = loadAndValidate(workspaceRoot);\n if (loaded.configPath === null) {\n console.log('ℹ️ Not an Nx repo and no webpieces.config.json found — nothing to validate.');\n return 0;\n }\n console.log('ℹ️ Not an Nx repo — running standalone webpieces code validators.\\n');\n\n // Composition root: bind runtime values, then resolve the app so inversify builds the whole DAG.\n // autobind self-binds every @injectable(Singleton) tooling class (replaces the buildProviderModule registry scan)\n const container = new Container({ autobind: true });\n container.bind(WorkspaceRoot).toConstantValue(new WorkspaceRoot(workspaceRoot));\n container.bind(MatchRulesHolder).toConstantValue(new MatchRulesHolder(loaded.matchRules));\n for (const binding of CONFIG_BINDINGS) {\n const ConfigClass = binding[0];\n const configured = loaded.rulesConfig[binding[1]] as BaseRuleConfig | undefined;\n container.bind(ConfigClass).toConstantValue(configured ?? new ConfigClass());\n }\n\n const app = container.get(CodeRulesApp);\n const result = await app.run();\n return result.success ? 0 : 1;\n}\n\nfunction reportPluginMissing(): void {\n console.error('\\n❌ This is an Nx monorepo but the webpieces Nx plugin is not installed.\\n');\n console.error(' Install it so the validators run during CI:\\n');\n console.error(` nx add ${NX_PLUGIN_NAME}\\n`);\n console.error(' (or add it manually to the \"plugins\" array in nx.json).\\n');\n}\n\n// webpieces-disable no-unmanaged-exceptions -- global entry point for wp-ci CLI\nasync function main(): Promise<void> {\n try {\n const cwd = process.cwd();\n const passthrough = process.argv.slice(2);\n\n const nxJsonPath = findUp('nx.json', cwd);\n if (!nxJsonPath) {\n const code = await runStandalone(cwd);\n process.exit(code);\n }\n\n const root = path.dirname(nxJsonPath);\n if (!isPluginRegistered(nxJsonPath)) {\n reportPluginMissing();\n process.exit(1);\n }\n\n const gracePeriod = new GracePeriodResolver().resolve(process.env);\n const runner = new NxStepRunner(root, gracePeriod, new SurvivorWatchdog(new ProcessGroupScanner(), SURVIVOR_POLL_INTERVAL_MILLIS), new SurvivorReporter(), new ProcessGroupKiller());\n const hotfix = new BranchIdentity().isHotfix();\n\n // Validate the root policy exactly once. webpieces.config.json is deliberately NOT a\n // sharedGlobal Nx input: making every project hash depend on it turned a policy-only edit into\n // a workspace-wide compile/lint/test. The scoped rules project preserves the gate without that\n // fan-out.\n const rules = await runner.run(['run', 'rules:check'], 'rules:check');\n // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary\n if (rules !== 0) process.exit(rules);\n\n // Run the architecture + code validators next (this also runs the wiring guard,\n // which fails loudly if nx.json no longer wires validators into the build).\n if (!hotfix && fs.existsSync(path.join(root, 'architecture'))) {\n const validateCode = await runner.run(['run', 'architecture:validate-complete'], 'architecture:validate-complete');\n // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary\n if (validateCode !== 0) process.exit(validateCode);\n }\n\n // Hotfix deliberately schedules only compile/typecheck + tests. The shared branch resolver makes\n // this the same decision the local PR gate makes, including detached GitHub checkouts.\n const target = hotfix ? 'hotfix-ci' : 'ci';\n const ciCode = await runner.run(['affected', `--target=${target}`, ...passthrough], `nx affected --target=${target}`);\n // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary\n process.exit(ciCode);\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof RuleFailError) {\n console.error(renderRuleFailForHuman(error));\n } else if (err instanceof InformAiError) {\n console.error(error.message);\n } else {\n console.error(`[wp-ci] unexpected error: ${error.message}`);\n }\n // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary\n process.exit(1);\n }\n}\n\nvoid main();\n"]}
1
+ {"version":3,"file":"wp-ci.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/wp-ci.ts"],"names":[],"mappings":";;AACA;;;;;;;;;;;;;;;;;;GAkBG;;;AAEH,+CAAyB;AACzB,mDAA6B;AAE7B,4BAA0B;AAC1B,yCAAsC;AACtC,0DAAiI;AACjI,8DAA0D;AAC1D,iEAA6D;AAC7D,sEAA+D;AAC/D,qDAAgD;AAChD,6DAAuE;AACvE,uEAA4D;AAC5D,uDAAiD;AACjD,uDAAqI;AAErI,sGAAsG;AACtG,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAE3C,MAAM,cAAc,GAAG,+BAA+B,CAAC;AAYvD,SAAS,MAAM,CAAC,QAAgB,EAAE,QAAgB;IAC9C,IAAI,GAAG,GAAG,QAAQ,CAAC;IACnB,OAAO,IAAI,EAAE,CAAC;QACV,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;QAC3C,IAAI,EAAE,C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ACL,CAAC;AAED,KAAK,IAAI,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * wp-ci — the universal webpieces CI entrypoint.\n *\n * Works in BOTH an Nx monorepo and a plain (non-Nx) repo, because the detection of\n * \"are we even in Nx?\" cannot live inside an Nx executor (by the time an executor runs,\n * Nx is already running). Dispatch:\n *\n * - no nx.json (non-Nx repo) -> run the standalone code validators, succeed.\n * - nx.json present, plugin NOT in it -> fail with the exact install command.\n * - nx.json present, plugin registered -> normal branch: validators + affected `ci`;\n * `/hotfix/` branch: affected `hotfix-ci` (build + test only).\n *\n * Repos reference this as a bin (`\"webpieces:ci\": \"wp-ci\"`) so the logic is versioned in\n * the npm package instead of copy-pasted into each repo's package.json (which drifts).\n *\n * Every nx step goes through NxStepRunner, which spawns it into its own process group and refuses\n * to return until that group has drained — a step whose workers outlive it holds the CI step's\n * stdout open and hangs the job forever with all work already green. See wp-ci-survivors.ts.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport 'reflect-metadata';\nimport { Container } from 'inversify';\nimport { loadAndValidate, RuleFailError, renderRuleFailForHuman, RepoRootFinder, BaseRuleConfig } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { BranchIdentity } from '@webpieces/repo-workflow-core';\nimport { CodeRulesApp } from './code-rules-app';\nimport { WorkspaceRoot, MatchRulesHolder } from './code-rules-context';\nimport { CONFIG_BINDINGS } from './code-rules-config-table';\nimport { NxStepRunner } from './wp-ci-nx-runner';\nimport { GracePeriodResolver, ProcessGroupKiller, ProcessGroupScanner, SurvivorReporter, SurvivorWatchdog } from './wp-ci-survivors';\n\n/** How often the watchdog re-runs `ps` while waiting for a finished step's process group to drain. */\nconst SURVIVOR_POLL_INTERVAL_MILLIS = 1000;\n\nconst NX_PLUGIN_NAME = '@webpieces/nx-webpieces-rules';\n\ninterface NxPluginObject {\n plugin?: string;\n}\n\ntype NxPluginEntry = string | NxPluginObject;\n\ninterface RawNxJson {\n plugins?: NxPluginEntry[];\n}\n\nfunction findUp(filename: string, startDir: string): string | null {\n let dir = startDir;\n while (true) {\n const candidate = path.join(dir, filename);\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nfunction pluginEntryMatches(entry: NxPluginEntry): boolean {\n if (typeof entry === 'string') return entry === NX_PLUGIN_NAME;\n return entry.plugin === NX_PLUGIN_NAME;\n}\n\nfunction isPluginRegistered(nxJsonPath: string): boolean {\n const raw = fs.readFileSync(nxJsonPath, 'utf8');\n // webpieces-disable no-unmanaged-exceptions -- rethrow as InformAiError so global catch surfaces readable message to AI\n try {\n const parsed = JSON.parse(raw) as RawNxJson;\n const plugins = parsed.plugins ?? [];\n return plugins.some((entry: NxPluginEntry) => pluginEntryMatches(entry));\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`nx.json has invalid JSON — fix the file, then retry.\\nParse error: ${error.message}\\nFile: ${nxJsonPath}`);\n }\n}\n\nasync function runStandalone(cwd: string): Promise<number> {\n const workspaceRoot = new RepoRootFinder().resolveRepoRoot(cwd);\n const loaded = loadAndValidate(workspaceRoot);\n if (loaded.configPath === null) {\n console.log('ℹ️ Not an Nx repo and no webpieces.config.json found — nothing to validate.');\n return 0;\n }\n console.log('ℹ️ Not an Nx repo — running standalone webpieces code validators.\\n');\n\n // Composition root: bind runtime values, then resolve the app so inversify builds the whole DAG.\n // autobind self-binds every @injectable(Singleton) tooling class (replaces the buildProviderModule registry scan)\n const container = new Container({ autobind: true });\n container.bind(WorkspaceRoot).toConstantValue(new WorkspaceRoot(workspaceRoot));\n container.bind(MatchRulesHolder).toConstantValue(new MatchRulesHolder(loaded.matchRules));\n for (const binding of CONFIG_BINDINGS) {\n const ConfigClass = binding[0];\n const configured = loaded.rulesConfig[binding[1]] as BaseRuleConfig | undefined;\n container.bind(ConfigClass).toConstantValue(configured ?? new ConfigClass());\n }\n\n const app = container.get(CodeRulesApp);\n const result = await app.run();\n return result.success ? 0 : 1;\n}\n\nfunction reportPluginMissing(): void {\n console.error('\\n❌ This is an Nx monorepo but the webpieces Nx plugin is not installed.\\n');\n console.error(' Install it so the validators run during CI:\\n');\n console.error(` nx add ${NX_PLUGIN_NAME}\\n`);\n console.error(' (or add it manually to the \"plugins\" array in nx.json).\\n');\n}\n\n// webpieces-disable no-unmanaged-exceptions -- global entry point for wp-ci CLI\nasync function main(): Promise<void> {\n try {\n const cwd = process.cwd();\n const passthrough = process.argv.slice(2);\n\n const nxJsonPath = findUp('nx.json', cwd);\n if (!nxJsonPath) {\n const code = await runStandalone(cwd);\n process.exit(code);\n }\n\n const root = path.dirname(nxJsonPath);\n if (!isPluginRegistered(nxJsonPath)) {\n reportPluginMissing();\n process.exit(1);\n }\n\n const gracePeriod = new GracePeriodResolver().resolve(process.env);\n const runner = new NxStepRunner(root, gracePeriod, new SurvivorWatchdog(new ProcessGroupScanner(), SURVIVOR_POLL_INTERVAL_MILLIS), new SurvivorReporter(), new ProcessGroupKiller());\n const hotfix = new BranchIdentity().isHotfix();\n\n // Validate the root policy exactly once. webpieces.config.json is deliberately NOT a\n // sharedGlobal Nx input: making every project hash depend on it turned a policy-only edit into\n // a workspace-wide compile/lint/test. The scoped rules project preserves the gate without that\n // fan-out.\n const rules = await runner.run(['run', 'rules:check'], 'rules:check');\n // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary\n if (rules !== 0) process.exit(rules);\n\n // Run the architecture + code validators next (this also runs the wiring guard,\n // which fails loudly if nx.json no longer wires validators into the build).\n if (!hotfix && fs.existsSync(path.join(root, 'architecture'))) {\n const validateCode = await runner.run(['run', 'architecture:validate-complete'], 'architecture:validate-complete');\n // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary\n if (validateCode !== 0) process.exit(validateCode);\n }\n\n // Hotfix deliberately schedules only compile/typecheck + tests. The shared branch resolver makes\n // this the same decision the local PR gate makes, including detached GitHub checkouts.\n const target = hotfix ? 'hotfix-ci' : 'ci';\n const ciCode = await runner.run(['affected', `--target=${target}`, ...passthrough], `nx affected --target=${target}`);\n // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary\n process.exit(ciCode);\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof RuleFailError) {\n console.error(renderRuleFailForHuman(error));\n } else if (err instanceof InformAiError) {\n console.error(error.message);\n } else {\n console.error(`[wp-ci] unexpected error: ${error.message}`);\n }\n // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary\n process.exit(1);\n }\n}\n\nvoid main();\n"]}