@boringparts/verule 0.0.0-stage → 0.2.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.
@@ -0,0 +1,333 @@
1
+ import { mkdirSync, rmSync } from "node:fs";
2
+ import { createConnection, createServer, } from "node:net";
3
+ import { dirname, resolve } from "node:path";
4
+ import { VeruleExecutionError, } from "./types.js";
5
+ import { createWorkspaceController, toExecutionErrorInfo, } from "./watch.js";
6
+ function isNamedPipeEndpoint(endpoint) {
7
+ return process.platform === "win32" && endpoint.startsWith("\\\\.\\pipe\\");
8
+ }
9
+ function resolveEndpointPath(cwd, endpoint) {
10
+ if (isNamedPipeEndpoint(endpoint)) {
11
+ return endpoint;
12
+ }
13
+ return resolve(cwd, endpoint);
14
+ }
15
+ function probeSocketActive(endpoint) {
16
+ return new Promise((resolveProbe) => {
17
+ const socket = createConnection(endpoint);
18
+ const finish = (active) => {
19
+ socket.removeAllListeners();
20
+ socket.destroy();
21
+ resolveProbe(active);
22
+ };
23
+ socket.setTimeout(250, () => finish(false));
24
+ socket.once("connect", () => finish(true));
25
+ socket.once("error", () => finish(false));
26
+ });
27
+ }
28
+ function bindServerOnce(server, endpoint) {
29
+ return new Promise((resolveBind, rejectBind) => {
30
+ const onError = (err) => {
31
+ server.off("listening", onListening);
32
+ rejectBind(err);
33
+ };
34
+ const onListening = () => {
35
+ server.off("error", onError);
36
+ resolveBind();
37
+ };
38
+ server.once("error", onError);
39
+ server.once("listening", onListening);
40
+ server.listen(endpoint);
41
+ });
42
+ }
43
+ async function listenEndpoint(server, endpoint) {
44
+ if (!isNamedPipeEndpoint(endpoint)) {
45
+ mkdirSync(dirname(endpoint), { recursive: true });
46
+ }
47
+ try {
48
+ await bindServerOnce(server, endpoint);
49
+ }
50
+ catch (err) {
51
+ const nodeErr = err;
52
+ if (nodeErr.code !== "EADDRINUSE" || isNamedPipeEndpoint(endpoint)) {
53
+ throw new VeruleExecutionError("ENGINE_ERROR", `Failed to listen on shared session endpoint "${endpoint}": ${nodeErr.message}`, { cause: err });
54
+ }
55
+ const active = await probeSocketActive(endpoint);
56
+ if (active) {
57
+ throw new VeruleExecutionError("INVALID_CONFIG", `Shared session endpoint "${endpoint}" is already in use by an active session.`);
58
+ }
59
+ rmSync(endpoint, { force: true });
60
+ try {
61
+ await bindServerOnce(server, endpoint);
62
+ }
63
+ catch (retryErr) {
64
+ const msg = retryErr instanceof Error ? retryErr.message : String(retryErr);
65
+ throw new VeruleExecutionError("ENGINE_ERROR", `Failed to listen on shared session endpoint "${endpoint}": ${msg}`, { cause: retryErr });
66
+ }
67
+ }
68
+ }
69
+ function parseSharedRequest(rawLine) {
70
+ let parsed;
71
+ try {
72
+ parsed = JSON.parse(rawLine);
73
+ }
74
+ catch (err) {
75
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid shared session request JSON: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
76
+ }
77
+ if (typeof parsed !== "object" ||
78
+ parsed === null ||
79
+ typeof parsed.id !== "string" ||
80
+ parsed.method !== "check") {
81
+ throw new VeruleExecutionError("INVALID_CONFIG", 'Shared session request must include string "id" and method "check".');
82
+ }
83
+ return parsed;
84
+ }
85
+ function toCheckParams(params) {
86
+ if (!params)
87
+ return undefined;
88
+ return {
89
+ ...(params.ruleIds !== undefined ? { ruleIds: params.ruleIds } : {}),
90
+ ...(params.at !== undefined ? { at: params.at } : {}),
91
+ ...(params.observe !== undefined ? { observe: params.observe } : {}),
92
+ ...(params.observeLimit !== undefined
93
+ ? { observeLimit: params.observeLimit }
94
+ : {}),
95
+ };
96
+ }
97
+ /**
98
+ * Starts an explicit long-lived shared analysis session bound to a single configuration and
99
+ * local socket/pipe endpoint. Reuses the same incremental update and rule execution pipeline
100
+ * as `watchProject`, and verifies disk state synchronously on every client query to avoid
101
+ * watcher debounce races.
102
+ */
103
+ export async function startSharedSession(options) {
104
+ if (options.signal?.aborted) {
105
+ throw new VeruleExecutionError("SESSION_CLOSED", "Shared session startup was aborted.");
106
+ }
107
+ const absCwd = resolve(options.cwd);
108
+ const endpoint = resolveEndpointPath(absCwd, options.endpoint);
109
+ const controller = createWorkspaceController({
110
+ cwd: absCwd,
111
+ ...(options.config !== undefined ? { config: options.config } : {}),
112
+ ...(options.loadConfig !== undefined
113
+ ? { loadConfig: options.loadConfig }
114
+ : {}),
115
+ ...(options.watchFiles !== undefined
116
+ ? { watchFiles: options.watchFiles }
117
+ : {}),
118
+ ...(options.observe !== undefined ? { observe: options.observe } : {}),
119
+ ...(options.observeLimit !== undefined
120
+ ? { observeLimit: options.observeLimit }
121
+ : {}),
122
+ ...(options.debounceMs !== undefined
123
+ ? { debounceMs: options.debounceMs }
124
+ : {}),
125
+ onBatchReady: () => {
126
+ // Keep the engine snapshot warm in the background; errors are captured for client queries.
127
+ void controller.applyPendingBatch().catch(() => { });
128
+ },
129
+ });
130
+ try {
131
+ await controller.openInitial();
132
+ }
133
+ catch (err) {
134
+ await controller.close();
135
+ throw err;
136
+ }
137
+ const activeSockets = new Set();
138
+ let isClosed = false;
139
+ let closePromise;
140
+ let resolveClosed;
141
+ const closedDone = new Promise((resolveDone) => {
142
+ resolveClosed = resolveDone;
143
+ });
144
+ const server = createServer((socket) => {
145
+ if (isClosed) {
146
+ socket.destroy();
147
+ return;
148
+ }
149
+ activeSockets.add(socket);
150
+ socket.setEncoding("utf8");
151
+ let buffer = "";
152
+ let handled = false;
153
+ const writeResponse = (response) => {
154
+ if (!socket.destroyed) {
155
+ socket.end(`${JSON.stringify(response)}\n`);
156
+ }
157
+ };
158
+ const handleLine = async (line) => {
159
+ if (handled)
160
+ return;
161
+ handled = true;
162
+ let requestId = "";
163
+ try {
164
+ const request = parseSharedRequest(line);
165
+ requestId = request.id;
166
+ const report = await controller.checkLatest(toCheckParams(request.params));
167
+ writeResponse({
168
+ id: requestId,
169
+ ok: true,
170
+ report,
171
+ });
172
+ }
173
+ catch (err) {
174
+ const info = toExecutionErrorInfo(err);
175
+ writeResponse({
176
+ id: requestId,
177
+ ok: false,
178
+ error: info,
179
+ });
180
+ }
181
+ };
182
+ socket.on("data", (chunk) => {
183
+ if (handled)
184
+ return;
185
+ buffer += chunk;
186
+ const newlineIndex = buffer.indexOf("\n");
187
+ if (newlineIndex === -1)
188
+ return;
189
+ const line = buffer.slice(0, newlineIndex).trim();
190
+ buffer = buffer.slice(newlineIndex + 1);
191
+ if (line.length > 0) {
192
+ void handleLine(line);
193
+ }
194
+ });
195
+ socket.on("error", () => {
196
+ activeSockets.delete(socket);
197
+ socket.destroy();
198
+ });
199
+ socket.on("close", () => {
200
+ activeSockets.delete(socket);
201
+ });
202
+ });
203
+ try {
204
+ await listenEndpoint(server, endpoint);
205
+ }
206
+ catch (err) {
207
+ await controller.close();
208
+ throw err;
209
+ }
210
+ const close = async () => {
211
+ if (closePromise) {
212
+ return closePromise;
213
+ }
214
+ closePromise = (async () => {
215
+ isClosed = true;
216
+ options.signal?.removeEventListener("abort", onAbort);
217
+ for (const socket of activeSockets) {
218
+ socket.destroy();
219
+ }
220
+ activeSockets.clear();
221
+ await new Promise((resolveServerClose) => {
222
+ server.close(() => resolveServerClose());
223
+ });
224
+ if (!isNamedPipeEndpoint(endpoint)) {
225
+ rmSync(endpoint, { force: true });
226
+ }
227
+ await controller.close();
228
+ resolveClosed();
229
+ })();
230
+ return closePromise;
231
+ };
232
+ const onAbort = () => {
233
+ void close();
234
+ };
235
+ options.signal?.addEventListener("abort", onAbort, { once: true });
236
+ return {
237
+ endpoint,
238
+ get snapshotId() {
239
+ return controller.session?.snapshotId ?? 0;
240
+ },
241
+ get projects() {
242
+ return controller.session?.projects ?? [];
243
+ },
244
+ get closed() {
245
+ return isClosed;
246
+ },
247
+ waitUntilClosed: () => closedDone,
248
+ close,
249
+ };
250
+ }
251
+ /**
252
+ * Queries a running shared analysis session over its local socket/pipe endpoint
253
+ * and returns the latest complete `CheckReport`.
254
+ */
255
+ export async function requestSharedReport(options) {
256
+ const endpoint = resolveEndpointPath(options.cwd ?? process.cwd(), options.endpoint);
257
+ return new Promise((resolveReport, rejectReport) => {
258
+ const socket = createConnection(endpoint);
259
+ socket.setEncoding("utf8");
260
+ let buffer = "";
261
+ let settled = false;
262
+ const finishError = (err) => {
263
+ if (settled)
264
+ return;
265
+ settled = true;
266
+ socket.destroy();
267
+ rejectReport(err);
268
+ };
269
+ const finishSuccess = (report) => {
270
+ if (settled)
271
+ return;
272
+ settled = true;
273
+ socket.destroy();
274
+ resolveReport(report);
275
+ };
276
+ if (options.timeoutMs !== undefined) {
277
+ socket.setTimeout(options.timeoutMs, () => {
278
+ finishError(new VeruleExecutionError("ENGINE_ERROR", `Timed out waiting for shared session response from "${endpoint}".`));
279
+ });
280
+ }
281
+ socket.once("connect", () => {
282
+ const request = {
283
+ id: "1",
284
+ method: "check",
285
+ params: {
286
+ ...(options.ruleIds !== undefined
287
+ ? { ruleIds: options.ruleIds }
288
+ : {}),
289
+ ...(options.at !== undefined ? { at: options.at } : {}),
290
+ ...(options.observe !== undefined
291
+ ? { observe: options.observe }
292
+ : {}),
293
+ ...(options.observeLimit !== undefined
294
+ ? { observeLimit: options.observeLimit }
295
+ : {}),
296
+ },
297
+ };
298
+ socket.write(`${JSON.stringify(request)}\n`);
299
+ });
300
+ socket.on("data", (chunk) => {
301
+ if (settled)
302
+ return;
303
+ buffer += chunk;
304
+ const newlineIndex = buffer.indexOf("\n");
305
+ if (newlineIndex === -1)
306
+ return;
307
+ const line = buffer.slice(0, newlineIndex).trim();
308
+ if (line.length === 0)
309
+ return;
310
+ let parsed;
311
+ try {
312
+ parsed = JSON.parse(line);
313
+ }
314
+ catch (err) {
315
+ finishError(new VeruleExecutionError("ENGINE_ERROR", `Malformed response from shared session "${endpoint}": ${err instanceof Error ? err.message : String(err)}`, { cause: err }));
316
+ return;
317
+ }
318
+ if (!parsed.ok) {
319
+ finishError(new VeruleExecutionError(parsed.error.code, parsed.error.message));
320
+ return;
321
+ }
322
+ finishSuccess(parsed.report);
323
+ });
324
+ socket.once("end", () => {
325
+ if (!settled) {
326
+ finishError(new VeruleExecutionError("ENGINE_ERROR", `Shared session at "${endpoint}" closed the connection before sending a report.`));
327
+ }
328
+ });
329
+ socket.once("error", (err) => {
330
+ finishError(new VeruleExecutionError("ENGINE_ERROR", `Failed to connect to shared session at "${endpoint}": ${err.message}`, { cause: err }));
331
+ });
332
+ });
333
+ }
@@ -0,0 +1,307 @@
1
+ import { type AdditionalInputEntry, type AdditionalInputSource, type DiagnosticBasis, type DiagnosticLocation, type EngineIrCacheMetrics, type EngineLoweringMetrics, type EngineSummaryLookupMetrics, type Evidence, type ExplainCleanupPath, type Gap, type MemoryStats, type ObserveLimit, type ObserveLimitInput, type ObserveMode, type ObserveOptions, type ProjectContext, type ProjectSummary, type RecomputationScope, type SourceFileOrigin, type SourceTarget, type SummaryConflictDetails, type SyntaxRef, type TssaeErrorCode } from "tssae";
2
+ export type { AdditionalInputEntry, AdditionalInputSource, DiagnosticLocation, EngineIrCacheMetrics, EngineLoweringMetrics, EngineSummaryLookupMetrics, Evidence, ExplainCleanupPath, Gap, MemoryStats, ObserveLimit, ObserveLimitInput, ObserveMode, ObserveOptions, ProjectContext, ProjectSummary, RecomputationScope, SourceFileOrigin, SourceTarget, SummaryConflictDetails, SyntaxRef, TssaeErrorCode, } from "tssae";
3
+ export declare const REPORT_SCHEMA_VERSION: "1";
4
+ export type VeruleErrorCode = TssaeErrorCode | "RULE_EXECUTION_ERROR";
5
+ /** Execution failure raised when analysis configuration, loading, queries, or rules fail. */
6
+ export declare class VeruleExecutionError extends Error {
7
+ readonly code: VeruleErrorCode;
8
+ readonly summaryConflict?: SummaryConflictDetails;
9
+ constructor(code: VeruleErrorCode, message: string, options?: ErrorOptions & {
10
+ readonly summaryConflict?: SummaryConflictDetails;
11
+ });
12
+ }
13
+ /** Maps upstream `TssaeError` or unknown exceptions into `VeruleExecutionError`. */
14
+ export declare function toVeruleError(error: unknown, fallbackCode?: VeruleErrorCode): VeruleExecutionError;
15
+ export type CheckpointOutcome = "pass" | "exclude" | "info";
16
+ export type CheckpointTarget = DiagnosticLocation | SyntaxRef | {
17
+ readonly location: DiagnosticLocation;
18
+ };
19
+ export type DiagnosticInput = {
20
+ readonly at: DiagnosticLocation;
21
+ readonly message: string;
22
+ readonly findingKey?: string;
23
+ /** Selected query results and explicit evidence, in diagnostic display order. */
24
+ readonly basis?: readonly DiagnosticBasis[];
25
+ };
26
+ export type Diagnostic = {
27
+ readonly id: string;
28
+ readonly ruleId: string;
29
+ readonly at: DiagnosticLocation;
30
+ readonly message: string;
31
+ readonly evidence: readonly Evidence[];
32
+ readonly projects: readonly string[];
33
+ };
34
+ export type RuleIdentitySummary = {
35
+ readonly id: string;
36
+ readonly digest: string;
37
+ };
38
+ export type ReportIdentity = {
39
+ readonly snapshotDigest: string;
40
+ readonly configDigest: string;
41
+ readonly rules: readonly RuleIdentitySummary[];
42
+ };
43
+ export type ObservationPhases = {
44
+ readonly configAndOpenMs: number;
45
+ readonly engineQueryMs: number;
46
+ readonly ruleExecutionMs: number;
47
+ readonly totalMs: number;
48
+ };
49
+ export type ObservationRpcMetrics = {
50
+ readonly batches: number;
51
+ readonly queryBatches: number;
52
+ readonly bytesSent: number;
53
+ readonly bytesReceived: number;
54
+ };
55
+ export type ObservationOverhead = {
56
+ readonly checkpointMs: number;
57
+ readonly encodeMs: number;
58
+ readonly writeMs: number;
59
+ };
60
+ export type ObservationDetailEntry = {
61
+ readonly kind: "query" | "checkpoint" | "engineStep";
62
+ readonly ruleId?: string;
63
+ readonly projectId?: string;
64
+ readonly provider?: string;
65
+ readonly name?: string;
66
+ readonly outcome?: CheckpointOutcome;
67
+ readonly cacheStatus?: "computed" | "reused";
68
+ readonly candidateCount?: number;
69
+ readonly durationMs?: number;
70
+ readonly at?: DiagnosticLocation;
71
+ readonly summary: string;
72
+ readonly detail?: unknown;
73
+ };
74
+ export type ObservationReport = {
75
+ readonly mode: Exclude<ObserveMode, "off">;
76
+ readonly phases: ObservationPhases;
77
+ readonly rpc: ObservationRpcMetrics;
78
+ readonly overhead: ObservationOverhead;
79
+ readonly queryCount: number;
80
+ readonly computedQueryCount: number;
81
+ readonly reusedQueryCount: number;
82
+ readonly candidateCount: number;
83
+ readonly checkpointCount: number;
84
+ readonly providers: readonly string[];
85
+ readonly lowering: EngineLoweringMetrics;
86
+ readonly irCache: EngineIrCacheMetrics;
87
+ readonly summaryLookup: EngineSummaryLookupMetrics;
88
+ readonly limit?: ObserveLimit;
89
+ readonly truncated: boolean;
90
+ readonly droppedCount: number;
91
+ readonly details?: readonly ObservationDetailEntry[];
92
+ };
93
+ export type ExplainStatus = "reported" | "excluded_by_checkpoint" | "excluded_by_query" | "not_in_candidates" | "target_not_in_project" | "suppressed_by_ignore" | "blocked_by_gap" | "covered_by_cleanup" | "rule_filtered";
94
+ export type ExplainQueryStep = {
95
+ readonly queryIndex: number;
96
+ readonly op: string;
97
+ readonly projectId: string;
98
+ readonly provider: string;
99
+ readonly cacheStatus: "computed" | "reused";
100
+ readonly candidateCount: number;
101
+ readonly matchedTarget: boolean;
102
+ readonly durationMs: number;
103
+ readonly summary?: string;
104
+ readonly detail?: unknown;
105
+ };
106
+ export type ExplainCheckpointTrace = {
107
+ readonly name: string;
108
+ readonly ruleId: string;
109
+ readonly projectId: string;
110
+ readonly outcome: CheckpointOutcome;
111
+ readonly at?: DiagnosticLocation;
112
+ readonly detail?: unknown;
113
+ };
114
+ export type ExplainResult = {
115
+ readonly ruleId: string;
116
+ readonly target: SourceTarget;
117
+ readonly status: ExplainStatus;
118
+ readonly inCandidates: boolean;
119
+ readonly summary: string;
120
+ readonly projectsChecked: readonly string[];
121
+ readonly matchingCandidates: readonly DiagnosticLocation[];
122
+ readonly excludedByQuery?: ExplainQueryStep;
123
+ readonly excludedByCheckpoint?: ExplainCheckpointTrace;
124
+ readonly queries: readonly ExplainQueryStep[];
125
+ readonly checkpoints: readonly ExplainCheckpointTrace[];
126
+ readonly gaps: readonly Gap[];
127
+ readonly providers: readonly string[];
128
+ readonly cleanupPaths: readonly ExplainCleanupPath[];
129
+ readonly inlineIgnore?: {
130
+ readonly matched: boolean;
131
+ readonly ruleId?: string;
132
+ readonly reason?: string;
133
+ readonly commentAt?: DiagnosticLocation;
134
+ };
135
+ };
136
+ export type InlineIgnoreStatus = "suppressed" | "unused" | "ambiguous" | "malformed" | "unknown_rule" | "undetermined";
137
+ export type InlineIgnoreEntry = {
138
+ readonly status: InlineIgnoreStatus;
139
+ readonly at: DiagnosticLocation;
140
+ readonly targetLine?: number;
141
+ readonly ruleId?: string;
142
+ readonly reason?: string;
143
+ readonly matchedLocations?: readonly DiagnosticLocation[];
144
+ readonly message?: string;
145
+ };
146
+ export type CheckReport = {
147
+ readonly reportVersion: typeof REPORT_SCHEMA_VERSION;
148
+ readonly status: "clean" | "findings";
149
+ readonly projects: readonly ProjectSummary[];
150
+ readonly fileOrigins: readonly SourceFileOrigin[];
151
+ readonly additionalInputs: readonly AdditionalInputEntry[];
152
+ readonly diagnostics: readonly Diagnostic[];
153
+ readonly gaps: readonly Gap[];
154
+ readonly identity: ReportIdentity;
155
+ readonly inlineIgnores?: readonly InlineIgnoreEntry[];
156
+ readonly observation?: ObservationReport;
157
+ readonly explanation?: ExplainResult;
158
+ readonly explanations?: readonly ExplainResult[];
159
+ };
160
+ export type ExplainReport = CheckReport & {
161
+ readonly explanation: ExplainResult;
162
+ };
163
+ /** Execution context exposed to Verule rules, backed by TSSAE `ProjectContext` queries. */
164
+ export type RuleContext = ProjectContext & {
165
+ report: (diagnostic: DiagnosticInput) => void;
166
+ /**
167
+ * Records a named TS judgment checkpoint for explainability and detail observation.
168
+ * When observation and explanation are disabled, `detail` is never invoked.
169
+ */
170
+ checkpoint: (name: string, target: CheckpointTarget, outcome: CheckpointOutcome, detail?: () => unknown) => void;
171
+ recordGaps: (gaps: readonly Gap[], options?: {
172
+ readonly relatedLocation?: DiagnosticLocation;
173
+ }) => void;
174
+ };
175
+ export type Rule = {
176
+ readonly id: string;
177
+ readonly description?: string;
178
+ readonly run: (ctx: RuleContext) => void | Promise<void>;
179
+ };
180
+ export type VeruleConfig = {
181
+ readonly tsconfig?: string;
182
+ readonly projects?: readonly string[];
183
+ readonly rules?: readonly Rule[];
184
+ readonly additionalInputs?: readonly string[];
185
+ };
186
+ export type NormalizedVeruleConfig = {
187
+ readonly tsconfig?: string;
188
+ readonly projects?: readonly string[];
189
+ readonly rules: readonly Rule[];
190
+ readonly additionalInputs: readonly string[];
191
+ };
192
+ export type SessionCheckOptions = {
193
+ readonly rulesOverride?: readonly Rule[];
194
+ readonly ruleIds?: readonly string[];
195
+ readonly at?: string | SourceTarget;
196
+ readonly observe?: ObserveMode | ObserveOptions;
197
+ readonly observeLimit?: ObserveLimitInput;
198
+ readonly configLoadMs?: number;
199
+ };
200
+ export type ExplainOptions = {
201
+ readonly ruleId?: string;
202
+ readonly at: string | SourceTarget;
203
+ readonly observe?: ObserveMode | ObserveOptions;
204
+ readonly observeLimit?: ObserveLimitInput;
205
+ readonly rulesOverride?: readonly Rule[];
206
+ };
207
+ export type OpenSessionOptions = {
208
+ readonly cwd: string;
209
+ readonly config?: VeruleConfig | NormalizedVeruleConfig;
210
+ readonly observe?: ObserveMode | ObserveOptions;
211
+ readonly observeLimit?: ObserveLimitInput;
212
+ readonly configLoadMs?: number;
213
+ };
214
+ export type RunCheckOptions = OpenSessionOptions & {
215
+ readonly ruleIds?: readonly string[];
216
+ readonly at?: string | SourceTarget;
217
+ };
218
+ export type SessionUpdateOptions = {
219
+ readonly changed?: readonly string[];
220
+ readonly created?: readonly string[];
221
+ readonly deleted?: readonly string[];
222
+ readonly config?: VeruleConfig | NormalizedVeruleConfig;
223
+ readonly rules?: readonly Rule[];
224
+ readonly entries?: readonly string[];
225
+ readonly additionalInputs?: readonly string[];
226
+ };
227
+ export type SessionUpdateResult = {
228
+ readonly previousSnapshotId: number;
229
+ readonly snapshotId: number;
230
+ readonly projects: readonly ProjectSummary[];
231
+ readonly fileOrigins: readonly SourceFileOrigin[];
232
+ readonly additionalInputs: readonly AdditionalInputEntry[];
233
+ readonly recomputation: RecomputationScope;
234
+ readonly memory: MemoryStats;
235
+ };
236
+ export type AnalysisSession = {
237
+ readonly snapshotId: number;
238
+ readonly projects: readonly ProjectSummary[];
239
+ readonly fileOrigins: readonly SourceFileOrigin[];
240
+ readonly additionalInputs: readonly AdditionalInputEntry[];
241
+ readonly memory: MemoryStats;
242
+ registerAdditionalInput: (filePath: string, source: AdditionalInputSource) => AdditionalInputEntry;
243
+ check: (optionsOrRules?: readonly Rule[] | SessionCheckOptions) => Promise<CheckReport>;
244
+ update: (options?: SessionUpdateOptions) => Promise<SessionUpdateResult>;
245
+ explain: (options: ExplainOptions) => Promise<ExplainReport>;
246
+ close: () => Promise<void>;
247
+ };
248
+ export type WatchTrigger = "initial" | "change";
249
+ export type WatchConfigLoadResult = {
250
+ readonly config: VeruleConfig | NormalizedVeruleConfig;
251
+ readonly watchFiles?: readonly string[];
252
+ };
253
+ export type WatchProjectOptions = {
254
+ readonly cwd: string;
255
+ readonly config?: VeruleConfig | NormalizedVeruleConfig;
256
+ readonly loadConfig?: () => Promise<WatchConfigLoadResult>;
257
+ readonly watchFiles?: readonly string[];
258
+ readonly observe?: ObserveMode;
259
+ readonly observeLimit?: ObserveLimitInput;
260
+ readonly debounceMs?: number;
261
+ readonly signal?: AbortSignal;
262
+ };
263
+ export type WatchReportEvent = {
264
+ readonly kind: "report";
265
+ readonly sequence: number;
266
+ readonly trigger: WatchTrigger;
267
+ readonly snapshotId: number;
268
+ readonly recomputation: RecomputationScope;
269
+ readonly memory: MemoryStats;
270
+ readonly report: CheckReport;
271
+ };
272
+ export type WatchFailureEvent = {
273
+ readonly kind: "failed";
274
+ readonly sequence: number;
275
+ readonly trigger: WatchTrigger;
276
+ readonly code: VeruleErrorCode;
277
+ readonly message: string;
278
+ };
279
+ export type WatchEvent = WatchReportEvent | WatchFailureEvent;
280
+ export type SharedSessionOptions = {
281
+ readonly cwd: string;
282
+ readonly endpoint: string;
283
+ readonly config?: VeruleConfig | NormalizedVeruleConfig;
284
+ readonly loadConfig?: () => Promise<WatchConfigLoadResult>;
285
+ readonly watchFiles?: readonly string[];
286
+ readonly observe?: ObserveMode;
287
+ readonly observeLimit?: ObserveLimitInput;
288
+ readonly debounceMs?: number;
289
+ readonly signal?: AbortSignal;
290
+ };
291
+ export type SharedSession = {
292
+ readonly endpoint: string;
293
+ readonly snapshotId: number;
294
+ readonly projects: readonly ProjectSummary[];
295
+ readonly closed: boolean;
296
+ waitUntilClosed: () => Promise<void>;
297
+ close: () => Promise<void>;
298
+ };
299
+ export type RequestSharedReportOptions = {
300
+ readonly endpoint: string;
301
+ readonly cwd?: string;
302
+ readonly ruleIds?: readonly string[];
303
+ readonly at?: string | SourceTarget;
304
+ readonly observe?: ObserveMode | ObserveOptions;
305
+ readonly observeLimit?: ObserveLimitInput;
306
+ readonly timeoutMs?: number;
307
+ };
package/dist/types.js ADDED
@@ -0,0 +1,43 @@
1
+ import { TssaeError, } from "tssae";
2
+ export const REPORT_SCHEMA_VERSION = "1";
3
+ /** Execution failure raised when analysis configuration, loading, queries, or rules fail. */
4
+ export class VeruleExecutionError extends Error {
5
+ code;
6
+ summaryConflict;
7
+ constructor(code, message, options) {
8
+ super(message, options);
9
+ this.name = "VeruleExecutionError";
10
+ this.code = code;
11
+ if (options?.summaryConflict !== undefined) {
12
+ this.summaryConflict = options.summaryConflict;
13
+ }
14
+ }
15
+ }
16
+ /** Maps upstream `TssaeError` or unknown exceptions into `VeruleExecutionError`. */
17
+ export function toVeruleError(error, fallbackCode = "ENGINE_ERROR") {
18
+ if (error instanceof VeruleExecutionError) {
19
+ return error;
20
+ }
21
+ if (error instanceof TssaeError) {
22
+ return new VeruleExecutionError(error.code, error.message, {
23
+ cause: error,
24
+ ...(error.summaryConflict !== undefined
25
+ ? { summaryConflict: error.summaryConflict }
26
+ : {}),
27
+ });
28
+ }
29
+ if (error instanceof Error &&
30
+ error.name === "TssaeError" &&
31
+ "code" in error &&
32
+ typeof error.code === "string") {
33
+ const summaryConflict = "summaryConflict" in error && error.summaryConflict !== undefined
34
+ ? error.summaryConflict
35
+ : undefined;
36
+ return new VeruleExecutionError(error.code, error.message, {
37
+ cause: error,
38
+ ...(summaryConflict !== undefined ? { summaryConflict } : {}),
39
+ });
40
+ }
41
+ const message = error instanceof Error ? error.message : String(error);
42
+ return new VeruleExecutionError(fallbackCode, message, { cause: error });
43
+ }