@boringparts/verule 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tssae
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,13 @@
1
+ import { type AdditionalInputEntry, type AdditionalInputRegistrar, type AdditionalInputRegistry, type AdditionalInputSource, type ScopedAdditionalInputRegistrar } from "tssae";
2
+ export type { AdditionalInputEntry, AdditionalInputRegistrar, AdditionalInputRegistry, AdditionalInputSource, ScopedAdditionalInputRegistrar, };
3
+ /** Validates config-level `additionalInputs` paths without performing filesystem I/O. */
4
+ export declare function validateAdditionalInputPaths(paths: readonly string[] | undefined): readonly string[];
5
+ /**
6
+ * Wraps `tssae`'s `createAdditionalInputRegistry` so registry validation and read
7
+ * errors surface as `VeruleExecutionError` matching Verule's error contract.
8
+ */
9
+ export declare function createAdditionalInputRegistry(options: {
10
+ readonly cwd: string;
11
+ }): AdditionalInputRegistry;
12
+ /** Binds an `AdditionalInputRegistrar` to a fixed rule or adapter source tag. */
13
+ export declare function createScopedAdditionalInputRegistrar(registrar: AdditionalInputRegistrar, source: AdditionalInputSource): ScopedAdditionalInputRegistrar;
@@ -0,0 +1,68 @@
1
+ import { createAdditionalInputRegistry as createTssaeAdditionalInputRegistry, createScopedAdditionalInputRegistrar as createTssaeScopedAdditionalInputRegistrar, } from "tssae";
2
+ import { VeruleExecutionError, toVeruleError } from "./types.js";
3
+ /** Validates config-level `additionalInputs` paths without performing filesystem I/O. */
4
+ export function validateAdditionalInputPaths(paths) {
5
+ if (paths === undefined) {
6
+ return [];
7
+ }
8
+ const validated = [];
9
+ for (const rawPath of paths) {
10
+ if (typeof rawPath !== "string" || rawPath.trim() === "") {
11
+ throw new VeruleExecutionError("INVALID_CONFIG", "Additional input path must be a non-empty string.");
12
+ }
13
+ validated.push(rawPath);
14
+ }
15
+ return validated;
16
+ }
17
+ /**
18
+ * Wraps `tssae`'s `createAdditionalInputRegistry` so registry validation and read
19
+ * errors surface as `VeruleExecutionError` matching Verule's error contract.
20
+ */
21
+ export function createAdditionalInputRegistry(options) {
22
+ const inner = createTssaeAdditionalInputRegistry(options);
23
+ return {
24
+ cwd: inner.cwd,
25
+ registerAdditionalInput(filePath, source) {
26
+ try {
27
+ return inner.registerAdditionalInput(filePath, source);
28
+ }
29
+ catch (err) {
30
+ throw toVeruleError(err, "INVALID_CONFIG");
31
+ }
32
+ },
33
+ readAdditionalInput(filePath, source) {
34
+ try {
35
+ return inner.readAdditionalInput(filePath, source);
36
+ }
37
+ catch (err) {
38
+ const mapped = toVeruleError(err, "RULE_EXECUTION_ERROR");
39
+ if (mapped.message.startsWith("Failed to read additional input ")) {
40
+ throw new VeruleExecutionError("RULE_EXECUTION_ERROR", mapped.message, {
41
+ cause: err,
42
+ });
43
+ }
44
+ throw mapped;
45
+ }
46
+ },
47
+ listAdditionalInputs: () => inner.listAdditionalInputs(),
48
+ getTrackedAbsolutePaths: () => inner.getTrackedAbsolutePaths(),
49
+ refresh: () => inner.refresh(),
50
+ resolveAbsolutePath(filePath) {
51
+ try {
52
+ return inner.resolveAbsolutePath(filePath);
53
+ }
54
+ catch (err) {
55
+ throw toVeruleError(err, "INVALID_CONFIG");
56
+ }
57
+ },
58
+ };
59
+ }
60
+ /** Binds an `AdditionalInputRegistrar` to a fixed rule or adapter source tag. */
61
+ export function createScopedAdditionalInputRegistrar(registrar, source) {
62
+ try {
63
+ return createTssaeScopedAdditionalInputRegistrar(registrar, source);
64
+ }
65
+ catch (err) {
66
+ throw toVeruleError(err, "INVALID_CONFIG");
67
+ }
68
+ }
@@ -0,0 +1,13 @@
1
+ export type CliCommandIdentity = {
2
+ readonly commandName: string;
3
+ readonly version: string;
4
+ };
5
+ /**
6
+ * Resolves the single executable command name and display version from a CLI package manifest.
7
+ *
8
+ * Throws if `bin` does not declare exactly one command; defaults missing `version` to `"unpublished"`.
9
+ */
10
+ export declare function cliCommandIdentity(manifest: {
11
+ readonly bin: Readonly<Record<string, string>>;
12
+ readonly version?: string;
13
+ }): CliCommandIdentity;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Resolves the single executable command name and display version from a CLI package manifest.
3
+ *
4
+ * Throws if `bin` does not declare exactly one command; defaults missing `version` to `"unpublished"`.
5
+ */
6
+ export function cliCommandIdentity(manifest) {
7
+ const names = Object.keys(manifest.bin);
8
+ if (names.length !== 1) {
9
+ throw new Error("CLI package must declare exactly one command in bin.");
10
+ }
11
+ return {
12
+ commandName: names[0],
13
+ version: manifest.version ?? "unpublished",
14
+ };
15
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ import { fstatSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { nodeCliOutput } from "@ykdz/cli-contract/node";
5
+ import { cliCommandIdentity } from "./cli-command-identity.js";
6
+ import { runCli } from "./main.js";
7
+ const require = createRequire(import.meta.url);
8
+ const shutdownController = new AbortController();
9
+ const abortShutdown = () => shutdownController.abort();
10
+ process.on("SIGINT", abortShutdown);
11
+ process.on("SIGTERM", abortShutdown);
12
+ let watchStdin = false;
13
+ try {
14
+ const stdinStat = fstatSync(0);
15
+ watchStdin = stdinStat.isFIFO() || stdinStat.isSocket();
16
+ }
17
+ catch {
18
+ watchStdin = false;
19
+ }
20
+ if (watchStdin) {
21
+ process.stdin.once("end", abortShutdown);
22
+ process.stdin.resume();
23
+ }
24
+ try {
25
+ process.exitCode = await runCli({
26
+ argv: process.argv,
27
+ signal: shutdownController.signal,
28
+ write: nodeCliOutput({ stdout: process.stdout, stderr: process.stderr }),
29
+ // Keep manifest reading and identity validation inside runCli's unexpected-failure boundary.
30
+ get identity() {
31
+ return cliCommandIdentity(require("../package.json"));
32
+ },
33
+ });
34
+ }
35
+ finally {
36
+ process.off("SIGINT", abortShutdown);
37
+ process.off("SIGTERM", abortShutdown);
38
+ if (watchStdin) {
39
+ process.stdin.off("end", abortShutdown);
40
+ process.stdin.pause();
41
+ }
42
+ }
@@ -0,0 +1,14 @@
1
+ import { type NormalizedVeruleConfig } from "./index.ts";
2
+ export type LoadedProjectConfig = {
3
+ readonly configPath: string;
4
+ readonly config: NormalizedVeruleConfig;
5
+ readonly watchFiles: readonly string[];
6
+ };
7
+ export declare function resolveConfigPath(cwd: string, explicitConfig?: string): string;
8
+ /**
9
+ * Dynamically imports a Verule configuration file with ESM cache-busting for the config
10
+ * and its local relative module graph, returning the validated config and dependency paths.
11
+ */
12
+ export declare function loadProjectConfigWithDependencies(cwd: string, explicitConfig?: string): Promise<LoadedProjectConfig>;
13
+ /** Dynamically imports and validates a project configuration file. */
14
+ export declare function loadProjectConfig(cwd: string, explicitConfig?: string): Promise<NormalizedVeruleConfig>;
@@ -0,0 +1,105 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { existsSync } from "node:fs";
10
+ import { registerHooks } from "node:module";
11
+ import { resolve } from "node:path";
12
+ import { fileURLToPath, pathToFileURL } from "node:url";
13
+ import { VeruleExecutionError, defineConfig, } from "./index.js";
14
+ const DEFAULT_CONFIG_CANDIDATES = [
15
+ "verule.config.ts",
16
+ "verule.config.mts",
17
+ "verule.config.mjs",
18
+ "verule.config.js",
19
+ ];
20
+ let nextReloadGeneration = 1;
21
+ export function resolveConfigPath(cwd, explicitConfig) {
22
+ if (explicitConfig !== undefined) {
23
+ const resolved = resolve(cwd, explicitConfig);
24
+ if (!existsSync(resolved)) {
25
+ throw new VeruleExecutionError("INVALID_CONFIG", `Configuration file not found: ${resolved}`);
26
+ }
27
+ return resolved;
28
+ }
29
+ for (const candidate of DEFAULT_CONFIG_CANDIDATES) {
30
+ const resolved = resolve(cwd, candidate);
31
+ if (existsSync(resolved)) {
32
+ return resolved;
33
+ }
34
+ }
35
+ throw new VeruleExecutionError("INVALID_CONFIG", `No Verule configuration file found in ${cwd}.`);
36
+ }
37
+ function isLocalImportSpecifier(specifier) {
38
+ return (specifier.startsWith("./") ||
39
+ specifier.startsWith("../") ||
40
+ specifier.startsWith("/") ||
41
+ specifier.startsWith("file://"));
42
+ }
43
+ /**
44
+ * Dynamically imports a Verule configuration file with ESM cache-busting for the config
45
+ * and its local relative module graph, returning the validated config and dependency paths.
46
+ */
47
+ export async function loadProjectConfigWithDependencies(cwd, explicitConfig) {
48
+ const configPath = resolveConfigPath(cwd, explicitConfig);
49
+ const configUrl = pathToFileURL(configPath).href;
50
+ const reloadToken = String(nextReloadGeneration++);
51
+ const reloadMarker = `verule-reload=${reloadToken}`;
52
+ const trackedFiles = new Set([configPath]);
53
+ const hook = registerHooks({
54
+ resolve(specifier, context, nextResolve) {
55
+ const resolved = nextResolve(specifier, context);
56
+ const fromReloadedGraph = typeof context.parentURL === "string" &&
57
+ context.parentURL.includes(reloadMarker);
58
+ if (fromReloadedGraph &&
59
+ isLocalImportSpecifier(specifier) &&
60
+ resolved.url.startsWith("file://") &&
61
+ !resolved.url.includes("/node_modules/")) {
62
+ const cleanUrl = resolved.url.split("?")[0];
63
+ try {
64
+ trackedFiles.add(fileURLToPath(cleanUrl));
65
+ }
66
+ catch {
67
+ // Ignore non-file paths.
68
+ }
69
+ return {
70
+ ...resolved,
71
+ url: `${cleanUrl}?${reloadMarker}`,
72
+ };
73
+ }
74
+ return resolved;
75
+ },
76
+ });
77
+ let loaded;
78
+ try {
79
+ loaded = await import(__rewriteRelativeImportExtension(`${configUrl}?${reloadMarker}`));
80
+ }
81
+ catch (err) {
82
+ const message = err instanceof Error ? err.message : String(err);
83
+ throw new VeruleExecutionError("INVALID_CONFIG", `Failed to load Verule configuration "${configPath}": ${message}`, { cause: err });
84
+ }
85
+ finally {
86
+ hook.deregister();
87
+ }
88
+ if (typeof loaded !== "object" || loaded === null || !("default" in loaded)) {
89
+ throw new VeruleExecutionError("INVALID_CONFIG", `Verule configuration "${configPath}" must export a default configuration object.`);
90
+ }
91
+ const rawDefault = loaded.default;
92
+ if (typeof rawDefault !== "object" || rawDefault === null) {
93
+ throw new VeruleExecutionError("INVALID_CONFIG", `Default export of "${configPath}" must be a configuration object.`);
94
+ }
95
+ return {
96
+ configPath,
97
+ config: defineConfig(rawDefault),
98
+ watchFiles: [...trackedFiles],
99
+ };
100
+ }
101
+ /** Dynamically imports and validates a project configuration file. */
102
+ export async function loadProjectConfig(cwd, explicitConfig) {
103
+ const loaded = await loadProjectConfigWithDependencies(cwd, explicitConfig);
104
+ return loaded.config;
105
+ }
@@ -0,0 +1,8 @@
1
+ export { createAdditionalInputRegistry, createScopedAdditionalInputRegistrar, type AdditionalInputEntry, type AdditionalInputRegistrar, type AdditionalInputRegistry, type AdditionalInputSource, type ScopedAdditionalInputRegistrar, } from "./additional-inputs.ts";
2
+ export { INLINE_IGNORE_RULE_ID } from "./inline-ignore.ts";
3
+ export { parseObserveLimit, parseTargetSpec } from "./observation.ts";
4
+ export { defineConfig, defineModel, defineRule, openSession, runCheck, } from "./session.ts";
5
+ export { requestSharedReport, startSharedSession } from "./shared-session.ts";
6
+ export { watchProject } from "./watch.ts";
7
+ export { defineAdapter, defineFactProvider, defineFactType, getEngineVersion, isSameInstance, resolveRetainedObjectFields, type AdapterContext, type AssignabilityPair, type AssignabilityResult, type BranchCoverageItem, type BranchCoverageOptions, type BranchCoverageStatus, type BranchDirection, type BranchEdgeInfo, type BranchKind, type BranchRef, type CallEffectsOptions, type CallEffectsResult, type CallEffectsTargetRef, type CallbackInvocationInfo, type CallProjectionSelection, type CallRef, type CallSiteParameterBinding, type CallTargetInfo, type CallTargetsResult, type CleanupCoverageStatus, type CleanupModelOperation, type CleanupModelOperationKind, type CleanupModelTarget, type CleanupScopeRef, type CleanupSiteInfo, type CompilerOptionsSummary, type ConfiguredAdapter, type DeclarationCallersResult, type DeclarationProjectionSelection, type DeclarationRef, type DiagnosticBasis, type DiagnosticLocation, type DirectCallInfo, type EngineFactExtractionOptions, type EngineProviderExtractionStats, type Evidence, type ExplainCleanupPath, type ExplainGapResolution, type ExplainGapResolutionStatus, type ExplainLocalGap, type ExplainProviderEvaluation, type ExplainProviderEvaluationStatus, type FactConflictDetails, type FactConflictParty, type FactContribution, type FactExplainTrace, type FactExtractionRequest, type FactMergeOutcome, type FactProvider, type FactProviderContribution, type FactQueryOptions, type FactResult, type FactType, type FactTypeSpec, type FieldEffect, type FieldEffectKind, type FieldWriteOperator, type FindSyntaxOptions, type FullCallProjectionFields, type FullDeclarationProjectionFields, type FullInstanceProjectionFields, type FullSignatureProjectionFields, type FullSyntaxLookupFields, type FullTypeProjectionFields, type FunctionBranchesResult, type Gap, type GuardConditionInfo, type ImplementationResolutionResult, type ImplementationStatus, type ImplementationTargetRef, type InstanceCleanupOptions, type InstanceCleanupScopeResult, type InstanceModelBehavior, type InstanceModelMatch, type InstanceOriginKind, type InstanceProjectionSelection, type InstanceRef, type InstanceResolutionResult, type InstanceTargetRef, type InstantiatedParameterType, type LibraryAdapter, type LifecycleEventBehavior, type LookupFilesOptions, type MemoryStats, type Model, type NativeAdapterObservation, type ObjectFieldShape, type ObserveLimit, type ObserveLimitInput, type ObserveMode, type ObserveOptions, type PackageResolutionMode, type ProgramObjectKind, type ProgramRef, type ProjectedCallResolutionRow, type ProjectedCallRow, type ProjectedDeclarationRow, type ProjectedInstanceRow, type ProjectedSignatureRow, type ProjectedSyntaxLookupRow, type ProjectedTypeRow, type ProjectSummary, type RecomputationScope, type ResolvedImplementationTarget, type ResolvedInstanceInfo, type RetainedObjectFields, type SelectableQueryResult, type SelectedKeys, type SignatureParameterInfo, type SignatureProjectionSelection, type SignatureRef, type SourceFileOrigin, type SourceFileProjectOrigin, type SourceRange, type SourceTarget, type SyntaxKind, type SyntaxLookupSelection, type SyntaxNodeResult, type SyntaxRef, type TargetInstanceCleanupResult, type TypeAtResult, type TypeProjectionSelection, type TypePropertyInfo, type TypeRef, type TypeSummary, type ValueEndpoint, type ValuePropagationMode, type ValuePropagationOptions, type ValuePropagationPath, type ValuePropagationResult, type ValuePropagationStep, type ValuePropagationStepKind, type ValuePropagationTargetResult, } from "tssae";
8
+ export { REPORT_SCHEMA_VERSION, VeruleExecutionError, type AnalysisSession, type CheckReport, type CheckpointOutcome, type CheckpointTarget, type Diagnostic, type DiagnosticInput, type ExplainCheckpointTrace, type ExplainQueryStep, type ExplainReport, type ExplainResult, type ExplainStatus, type InlineIgnoreEntry, type InlineIgnoreStatus, type ModelIdentitySummary, type NormalizedVeruleConfig, type ObservationDetailEntry, type ObservationOverhead, type ObservationPhases, type ObservationReport, type ObservationRpcMetrics, type OpenSessionOptions, type ReportIdentity, type RequestSharedReportOptions, type Rule, type RuleContext, type RuleIdentitySummary, type RunCheckOptions, type SessionCheckOptions, type SessionUpdateOptions, type SessionUpdateResult, type SharedSession, type SharedSessionOptions, type VeruleConfig, type VeruleErrorCode, type WatchConfigLoadResult, type WatchEvent, type WatchFailureEvent, type WatchProjectOptions, type WatchReportEvent, type WatchTrigger, } from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { createAdditionalInputRegistry, createScopedAdditionalInputRegistrar, } from "./additional-inputs.js";
2
+ export { INLINE_IGNORE_RULE_ID } from "./inline-ignore.js";
3
+ export { parseObserveLimit, parseTargetSpec } from "./observation.js";
4
+ export { defineConfig, defineModel, defineRule, openSession, runCheck, } from "./session.js";
5
+ export { requestSharedReport, startSharedSession } from "./shared-session.js";
6
+ export { watchProject } from "./watch.js";
7
+ export { defineAdapter, defineFactProvider, defineFactType, getEngineVersion, isSameInstance, resolveRetainedObjectFields, } from "tssae";
8
+ export { REPORT_SCHEMA_VERSION, VeruleExecutionError, } from "./types.js";
@@ -0,0 +1,44 @@
1
+ import { type DiagnosticLocation, type ProjectSummary, type ScannedComment } from "tssae";
2
+ import type { CollectedDiagnostic } from "./projects.ts";
3
+ import type { InlineIgnoreEntry } from "./types.ts";
4
+ export declare const INLINE_IGNORE_RULE_ID: "verule/inline-ignore";
5
+ export type ParsedDirectiveItem = {
6
+ readonly kind: "valid";
7
+ readonly ruleId: string;
8
+ readonly reason: string;
9
+ readonly at: DiagnosticLocation;
10
+ readonly targetLine: number | null;
11
+ } | {
12
+ readonly kind: "malformed";
13
+ readonly message: string;
14
+ readonly at: DiagnosticLocation;
15
+ };
16
+ /** Parses one `verule-ignore-next-code-line` directive from a TSSAE standalone comment. */
17
+ export declare function parseDirectiveFromComment(comment: ScannedComment): ParsedDirectiveItem | undefined;
18
+ /** Filters and parses all Verule inline ignore directives from scanned snapshot comments. */
19
+ export declare function parseInlineIgnoreDirectives(comments: readonly ScannedComment[]): readonly ParsedDirectiveItem[];
20
+ export type InlineIgnoreSuppression = {
21
+ readonly ruleId: string;
22
+ readonly at: DiagnosticLocation;
23
+ readonly directiveAt: DiagnosticLocation;
24
+ readonly reason: string;
25
+ };
26
+ export type InlineIgnoreSettlement = {
27
+ readonly diagnostics: readonly CollectedDiagnostic[];
28
+ readonly suppressions: readonly InlineIgnoreSuppression[];
29
+ readonly entries: readonly InlineIgnoreEntry[];
30
+ };
31
+ /**
32
+ * Resolves `verule-ignore-next-code-line` directives against collected rule diagnostics.
33
+ *
34
+ * Rules run normally and keep all gaps and evidence; suppression only hides diagnostics whose
35
+ * `(ruleId, file, start, end)` primary location uniquely matches the target code line.
36
+ */
37
+ export declare function resolveInlineIgnores(params: {
38
+ readonly directives: readonly ParsedDirectiveItem[];
39
+ readonly collected: readonly CollectedDiagnostic[];
40
+ readonly projects: readonly ProjectSummary[];
41
+ readonly configuredRuleIds: ReadonlySet<string>;
42
+ readonly executedRuleIds: ReadonlySet<string>;
43
+ readonly isPartialRuleSelection: boolean;
44
+ }): InlineIgnoreSettlement;
@@ -0,0 +1,297 @@
1
+ import { normalizeLocation, } from "tssae";
2
+ export const INLINE_IGNORE_RULE_ID = "verule/inline-ignore";
3
+ const DIRECTIVE_PREFIX = "verule-ignore-next-code-line";
4
+ function isWhitespaceChar(ch) {
5
+ return /\s/u.test(ch);
6
+ }
7
+ function splitReasonSeparator(rest) {
8
+ if (rest.startsWith("--")) {
9
+ const after = rest.slice(2);
10
+ if (after === "" || isWhitespaceChar(after[0])) {
11
+ return ["", after];
12
+ }
13
+ return undefined;
14
+ }
15
+ let searchFrom = 0;
16
+ while (true) {
17
+ const idx = rest.indexOf("--", searchFrom);
18
+ if (idx === -1) {
19
+ return undefined;
20
+ }
21
+ const before = rest.slice(0, idx);
22
+ const after = rest.slice(idx + 2);
23
+ const leftOk = before.length > 0 && isWhitespaceChar(before.at(-1));
24
+ const rightOk = after === "" || isWhitespaceChar(after[0]);
25
+ if (leftOk && rightOk) {
26
+ return [before, after];
27
+ }
28
+ searchFrom = idx + 1;
29
+ }
30
+ }
31
+ /** Parses one `verule-ignore-next-code-line` directive from a TSSAE standalone comment. */
32
+ export function parseDirectiveFromComment(comment) {
33
+ const trimmed = comment.text.trim();
34
+ if (!trimmed.startsWith(DIRECTIVE_PREFIX)) {
35
+ return undefined;
36
+ }
37
+ const afterPrefix = trimmed.slice(DIRECTIVE_PREFIX.length);
38
+ if (afterPrefix.length > 0 && !isWhitespaceChar(afterPrefix[0])) {
39
+ return undefined;
40
+ }
41
+ const rest = afterPrefix.trim();
42
+ if (rest === "") {
43
+ return {
44
+ kind: "malformed",
45
+ message: 'Missing rule ID and reason; expected "verule-ignore-next-code-line <ruleId> -- <reason>".',
46
+ at: comment.at,
47
+ };
48
+ }
49
+ const separated = splitReasonSeparator(rest);
50
+ if (!separated) {
51
+ return {
52
+ kind: "malformed",
53
+ message: 'Missing "-- <reason>" separator; expected "verule-ignore-next-code-line <ruleId> -- <reason>".',
54
+ at: comment.at,
55
+ };
56
+ }
57
+ const [rawIdPart, rawReasonPart] = separated;
58
+ const idTokens = rawIdPart.trim().split(/\s+/u).filter(Boolean);
59
+ if (idTokens.length === 0) {
60
+ return {
61
+ kind: "malformed",
62
+ message: 'Missing rule ID before "--"; expected "verule-ignore-next-code-line <ruleId> -- <reason>".',
63
+ at: comment.at,
64
+ };
65
+ }
66
+ if (idTokens.length > 1 || idTokens[0].includes(",")) {
67
+ return {
68
+ kind: "malformed",
69
+ message: 'Expected a single rule ID before "--".',
70
+ at: comment.at,
71
+ };
72
+ }
73
+ const reason = rawReasonPart.trim();
74
+ if (reason === "") {
75
+ return {
76
+ kind: "malformed",
77
+ message: 'Missing non-empty reason after "--".',
78
+ at: comment.at,
79
+ };
80
+ }
81
+ return {
82
+ kind: "valid",
83
+ ruleId: idTokens[0],
84
+ reason,
85
+ at: comment.at,
86
+ targetLine: comment.nextCodeLine,
87
+ };
88
+ }
89
+ /** Filters and parses all Verule inline ignore directives from scanned snapshot comments. */
90
+ export function parseInlineIgnoreDirectives(comments) {
91
+ const directives = [];
92
+ for (const comment of comments) {
93
+ const parsed = parseDirectiveFromComment(comment);
94
+ if (parsed !== undefined) {
95
+ directives.push(parsed);
96
+ }
97
+ }
98
+ return directives;
99
+ }
100
+ function normalizeFilePath(file) {
101
+ return file.replaceAll("\\", "/");
102
+ }
103
+ function primaryRangeKey(loc) {
104
+ return `${normalizeFilePath(loc.file)}\0${loc.start}\0${loc.end}`;
105
+ }
106
+ function compareLocations(a, b) {
107
+ if (a.file < b.file)
108
+ return -1;
109
+ if (a.file > b.file)
110
+ return 1;
111
+ if (a.start !== b.start)
112
+ return a.start - b.start;
113
+ if (a.end !== b.end)
114
+ return a.end - b.end;
115
+ if (a.line !== b.line)
116
+ return a.line - b.line;
117
+ return a.column - b.column;
118
+ }
119
+ /**
120
+ * Resolves `verule-ignore-next-code-line` directives against collected rule diagnostics.
121
+ *
122
+ * Rules run normally and keep all gaps and evidence; suppression only hides diagnostics whose
123
+ * `(ruleId, file, start, end)` primary location uniquely matches the target code line.
124
+ */
125
+ export function resolveInlineIgnores(params) {
126
+ if (params.directives.length === 0) {
127
+ return {
128
+ diagnostics: params.collected,
129
+ suppressions: [],
130
+ entries: [],
131
+ };
132
+ }
133
+ const fileProjects = new Map();
134
+ for (const project of params.projects) {
135
+ for (const file of project.sourceFiles) {
136
+ const normalized = normalizeFilePath(file);
137
+ const list = fileProjects.get(normalized);
138
+ if (list) {
139
+ if (!list.includes(project.projectId)) {
140
+ list.push(project.projectId);
141
+ }
142
+ }
143
+ else {
144
+ fileProjects.set(normalized, [project.projectId]);
145
+ }
146
+ }
147
+ }
148
+ const byRuleFileLine = new Map();
149
+ for (const diag of params.collected) {
150
+ const file = normalizeFilePath(diag.at.file);
151
+ const key = `${diag.ruleId}\0${file}\0${diag.at.line}`;
152
+ const bucket = byRuleFileLine.get(key);
153
+ if (bucket) {
154
+ bucket.push(diag);
155
+ }
156
+ else {
157
+ byRuleFileLine.set(key, [diag]);
158
+ }
159
+ }
160
+ const suppressedKeys = new Set();
161
+ const suppressions = [];
162
+ const directiveDiagnostics = [];
163
+ const entries = [];
164
+ const emitDirectiveDiagnostic = (directiveAt, findingKey, message, evidence = []) => {
165
+ const projectIds = fileProjects.get(directiveAt.file) ?? [
166
+ params.projects[0]?.projectId ?? "default",
167
+ ];
168
+ for (const projectId of projectIds) {
169
+ directiveDiagnostics.push({
170
+ ruleId: INLINE_IGNORE_RULE_ID,
171
+ projectId,
172
+ at: directiveAt,
173
+ message,
174
+ findingKey,
175
+ evidence,
176
+ });
177
+ }
178
+ };
179
+ for (const rawDirective of params.directives) {
180
+ const directiveAt = normalizeLocation(rawDirective.at);
181
+ if (rawDirective.kind === "malformed") {
182
+ const message = `Malformed inline ignore directive: ${rawDirective.message}`;
183
+ emitDirectiveDiagnostic(directiveAt, "inline-ignore-malformed", message);
184
+ entries.push({
185
+ status: "malformed",
186
+ at: directiveAt,
187
+ message,
188
+ });
189
+ continue;
190
+ }
191
+ if (!params.isPartialRuleSelection &&
192
+ !params.configuredRuleIds.has(rawDirective.ruleId)) {
193
+ const message = `Unknown rule ID "${rawDirective.ruleId}" in inline ignore directive.`;
194
+ emitDirectiveDiagnostic(directiveAt, "inline-ignore-unknown-rule", message);
195
+ entries.push({
196
+ status: "unknown_rule",
197
+ at: directiveAt,
198
+ ...(rawDirective.targetLine !== null
199
+ ? { targetLine: rawDirective.targetLine }
200
+ : {}),
201
+ ruleId: rawDirective.ruleId,
202
+ reason: rawDirective.reason,
203
+ message,
204
+ });
205
+ continue;
206
+ }
207
+ const matches = rawDirective.targetLine !== null
208
+ ? (byRuleFileLine.get(`${rawDirective.ruleId}\0${directiveAt.file}\0${rawDirective.targetLine}`) ?? [])
209
+ : [];
210
+ const uniqueByRange = new Map();
211
+ for (const match of matches) {
212
+ const key = primaryRangeKey(match.at);
213
+ if (!uniqueByRange.has(key)) {
214
+ uniqueByRange.set(key, normalizeLocation(match.at));
215
+ }
216
+ }
217
+ const uniqueLocations = [...uniqueByRange.values()].toSorted(compareLocations);
218
+ const isRuleComplete = params.executedRuleIds.has(rawDirective.ruleId);
219
+ if (uniqueLocations.length >= 2) {
220
+ const locLabels = uniqueLocations
221
+ .map((loc) => `${loc.file}:${loc.line}:${loc.column}`)
222
+ .join(", ");
223
+ const message = `Ambiguous inline ignore directive for rule "${rawDirective.ruleId}": matched ${uniqueLocations.length} distinct primary locations on line ${rawDirective.targetLine} (${locLabels}); all original diagnostics are retained.`;
224
+ const evidence = uniqueLocations.map((loc) => ({
225
+ kind: "source",
226
+ message: `Matched primary location ${loc.file}:${loc.line}:${loc.column} (${loc.start}..${loc.end})`,
227
+ at: loc,
228
+ }));
229
+ emitDirectiveDiagnostic(directiveAt, "inline-ignore-ambiguous", message, evidence);
230
+ entries.push({
231
+ status: "ambiguous",
232
+ at: directiveAt,
233
+ ...(rawDirective.targetLine !== null
234
+ ? { targetLine: rawDirective.targetLine }
235
+ : {}),
236
+ ruleId: rawDirective.ruleId,
237
+ reason: rawDirective.reason,
238
+ matchedLocations: uniqueLocations,
239
+ message,
240
+ });
241
+ continue;
242
+ }
243
+ if (!isRuleComplete) {
244
+ entries.push({
245
+ status: "undetermined",
246
+ at: directiveAt,
247
+ ...(rawDirective.targetLine !== null
248
+ ? { targetLine: rawDirective.targetLine }
249
+ : {}),
250
+ ruleId: rawDirective.ruleId,
251
+ reason: rawDirective.reason,
252
+ });
253
+ continue;
254
+ }
255
+ if (uniqueLocations.length === 0) {
256
+ const message = rawDirective.targetLine === null
257
+ ? `Unused inline ignore directive for rule "${rawDirective.ruleId}": no code line immediately follows the comment (blank line or end of file).`
258
+ : `Unused inline ignore directive for rule "${rawDirective.ruleId}": no matching diagnostic on line ${rawDirective.targetLine}.`;
259
+ emitDirectiveDiagnostic(directiveAt, "inline-ignore-unused", message);
260
+ entries.push({
261
+ status: "unused",
262
+ at: directiveAt,
263
+ ...(rawDirective.targetLine !== null
264
+ ? { targetLine: rawDirective.targetLine }
265
+ : {}),
266
+ ruleId: rawDirective.ruleId,
267
+ reason: rawDirective.reason,
268
+ message,
269
+ });
270
+ continue;
271
+ }
272
+ const matchedLoc = uniqueLocations[0];
273
+ suppressedKeys.add(`${rawDirective.ruleId}\0${primaryRangeKey(matchedLoc)}`);
274
+ suppressions.push({
275
+ ruleId: rawDirective.ruleId,
276
+ at: matchedLoc,
277
+ directiveAt,
278
+ reason: rawDirective.reason,
279
+ });
280
+ entries.push({
281
+ status: "suppressed",
282
+ at: directiveAt,
283
+ ...(rawDirective.targetLine !== null
284
+ ? { targetLine: rawDirective.targetLine }
285
+ : {}),
286
+ ruleId: rawDirective.ruleId,
287
+ reason: rawDirective.reason,
288
+ matchedLocations: [matchedLoc],
289
+ });
290
+ }
291
+ const surviving = params.collected.filter((diag) => !suppressedKeys.has(`${diag.ruleId}\0${primaryRangeKey(diag.at)}`));
292
+ return {
293
+ diagnostics: [...surviving, ...directiveDiagnostics],
294
+ suppressions,
295
+ entries,
296
+ };
297
+ }