@doccov/sdk 0.18.0 → 0.20.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +397 -822
  2. package/dist/index.js +595 -1237
  3. package/package.json +6 -2
package/dist/index.d.ts CHANGED
@@ -1,3 +1,94 @@
1
+ /**
2
+ * Configuration types for DocCov.
3
+ * These types are shared between CLI and API.
4
+ */
5
+ /**
6
+ * Documentation configuration options.
7
+ */
8
+ interface DocsConfig {
9
+ /** Glob patterns for markdown docs to include */
10
+ include?: string[];
11
+ /** Glob patterns for markdown docs to exclude */
12
+ exclude?: string[];
13
+ }
14
+ /**
15
+ * Example validation modes.
16
+ */
17
+ type ExampleValidationMode = "presence" | "typecheck" | "run";
18
+ /**
19
+ * Schema extraction modes for validation libraries (Zod, Valibot, TypeBox, ArkType).
20
+ *
21
+ * - 'static': TypeScript Compiler API only (no runtime, always safe)
22
+ * - 'runtime': Standard Schema runtime extraction (requires built package)
23
+ * - 'hybrid': Try runtime first, fall back to static
24
+ */
25
+ type SchemaExtractionMode = "static" | "runtime" | "hybrid";
26
+ /**
27
+ * Check command configuration options.
28
+ */
29
+ interface CheckConfig {
30
+ /**
31
+ * Example validation modes to run.
32
+ * Can be a single mode, array of modes, or comma-separated string.
33
+ * - 'presence': Check that @example blocks exist on exports
34
+ * - 'typecheck': Compile examples with TypeScript
35
+ * - 'run': Execute examples and validate assertions
36
+ */
37
+ examples?: ExampleValidationMode | ExampleValidationMode[] | string;
38
+ /** Minimum coverage percentage required (0-100) */
39
+ minCoverage?: number;
40
+ /** Maximum drift percentage allowed (0-100) */
41
+ maxDrift?: number;
42
+ }
43
+ /**
44
+ * Normalized DocCov configuration.
45
+ * This is the parsed/normalized form used by commands.
46
+ */
47
+ interface DocCovConfig {
48
+ /** Export include patterns */
49
+ include?: string[];
50
+ /** Export exclude patterns */
51
+ exclude?: string[];
52
+ /** Plugins (future) */
53
+ plugins?: unknown[];
54
+ /** Documentation configuration */
55
+ docs?: DocsConfig;
56
+ /** Check command configuration */
57
+ check?: CheckConfig;
58
+ /**
59
+ * Schema extraction mode for validation libraries.
60
+ *
61
+ * - 'static' (default): Safe, uses TypeScript Compiler API
62
+ * - 'runtime': Uses Standard Schema (requires built package)
63
+ * - 'hybrid': Tries runtime first, falls back to static
64
+ *
65
+ * Runtime extraction provides richer JSON Schema output (formats, patterns)
66
+ * but requires the package to be built first.
67
+ */
68
+ schemaExtraction?: SchemaExtractionMode;
69
+ }
70
+ /**
71
+ * Define a DocCov configuration.
72
+ * Helper function for type-safe configuration in doccov.config.ts.
73
+ *
74
+ * @param config - Configuration object
75
+ * @returns The configuration object (for type inference)
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * // doccov.config.ts
80
+ * import { defineConfig } from '@doccov/sdk';
81
+ *
82
+ * defineConfig({
83
+ * include: ['MyClass', 'myFunction'],
84
+ * exclude: ['internal*'],
85
+ * check: {
86
+ * minCoverage: 80,
87
+ * },
88
+ * });
89
+ * ```
90
+ */
91
+ declare function defineConfig(config: DocCovConfig): DocCovConfig;
1
92
  interface DocCovOptions {
2
93
  includePrivate?: boolean;
3
94
  followImports?: boolean;
@@ -7,6 +98,14 @@ interface DocCovOptions {
7
98
  useCache?: boolean;
8
99
  /** Working directory for cache operations (default: process.cwd()) */
9
100
  cwd?: string;
101
+ /**
102
+ * Schema extraction mode for validation libraries (Zod, Valibot, etc.)
103
+ *
104
+ * - 'static' (default): TypeScript Compiler API only (no runtime)
105
+ * - 'runtime': Standard Schema runtime extraction (requires built package)
106
+ * - 'hybrid': Try runtime first, fall back to static
107
+ */
108
+ schemaExtraction?: SchemaExtractionMode;
10
109
  }
11
110
  /**
12
111
  * Pre-detected Standard Schema for a variable export.
@@ -15,177 +114,158 @@ interface DetectedSchemaEntry {
15
114
  schema: Record<string, unknown>;
16
115
  vendor: string;
17
116
  }
18
- /**
19
- * Standard JSON Schema Integration
20
- *
21
- * Provides runtime detection and extraction of Standard JSON Schema v1 compliant libraries.
22
- * This enables support for Zod v4.2+, ArkType, Valibot, and other Standard Schema compliant libraries.
23
- *
24
- * @see https://github.com/standard-schema/standard-schema
25
- */
26
- /**
27
- * Standard JSON Schema V1 interface (minimal subset for detection).
28
- * Full spec: https://github.com/standard-schema/standard-schema
29
- */
30
- interface StandardJSONSchemaV1 {
31
- readonly "~standard": {
32
- readonly version: 1;
33
- readonly vendor: string;
34
- readonly jsonSchema: {
35
- readonly output: (options?: StandardSchemaOutputOptions) => Record<string, unknown>;
36
- };
37
- };
117
+ interface SchemaDetectionContext {
118
+ baseDir: string;
119
+ entryFile: string;
120
+ }
121
+ interface DetectedSchema {
122
+ schema: Record<string, unknown>;
123
+ vendor: string;
38
124
  }
125
+ interface SchemaDetectionResult {
126
+ schemas: Map<string, DetectedSchema>;
127
+ errors: string[];
128
+ }
129
+ declare function detectRuntimeSchemas(context: SchemaDetectionContext): Promise<SchemaDetectionResult>;
130
+ declare function clearSchemaCache(): void;
131
+ import * as TS from "typescript";
39
132
  /**
40
- * Options for Standard Schema JSON output.
133
+ * A schema adapter can detect and extract output types from a specific
134
+ * schema validation library.
41
135
  */
42
- interface StandardSchemaOutputOptions {
136
+ interface SchemaAdapter {
137
+ /** Unique identifier for this adapter */
138
+ readonly id: string;
139
+ /** npm package name(s) this adapter handles */
140
+ readonly packages: readonly string[];
141
+ /**
142
+ * Check if a type matches this adapter's schema library.
143
+ * Should be fast - called for every export.
144
+ */
145
+ matches(type: TS.Type, checker: TS.TypeChecker): boolean;
43
146
  /**
44
- * Target JSON Schema dialect.
45
- * - 'draft-07': JSON Schema Draft 07 (widest compatibility)
46
- * - 'draft-2020-12': Latest JSON Schema (best features)
47
- * - 'openapi-3.0': OpenAPI 3.0 compatible schema
147
+ * Extract the output type from a schema type.
148
+ * Returns null if extraction fails.
48
149
  */
49
- target?: "draft-07" | "draft-2020-12" | "openapi-3.0";
150
+ extractOutputType(type: TS.Type, checker: TS.TypeChecker): TS.Type | null;
151
+ /**
152
+ * Extract the input type from a schema type (optional).
153
+ * Useful for transforms where input differs from output.
154
+ */
155
+ extractInputType?(type: TS.Type, checker: TS.TypeChecker): TS.Type | null;
50
156
  }
51
157
  /**
52
- * Result of Standard Schema extraction.
158
+ * Result of schema type extraction
53
159
  */
54
- interface StandardSchemaResult {
55
- /** The extracted JSON Schema */
56
- schema: Record<string, unknown>;
57
- /** The vendor library (e.g., 'zod', 'arktype', 'valibot') */
58
- vendor: string;
59
- /** Standard Schema version */
60
- version: number;
160
+ interface SchemaExtractionResult {
161
+ /** The adapter that matched */
162
+ adapter: SchemaAdapter;
163
+ /** The extracted output type */
164
+ outputType: TS.Type;
165
+ /** The extracted input type (if different from output) */
166
+ inputType?: TS.Type;
61
167
  }
168
+ import * as TS2 from "typescript";
62
169
  /**
63
- * Check if a value implements the Standard JSON Schema v1 interface.
64
- *
65
- * This enables runtime detection of schema libraries that implement the standard,
66
- * including Zod v4.2+, ArkType, Valibot, and others.
67
- *
68
- * @param value - Value to check
69
- * @returns True if the value implements StandardJSONSchemaV1
70
- *
71
- * @example
72
- * ```typescript
73
- * import { isStandardJSONSchema, extractViaStandardSchema } from '@doccov/sdk';
74
- * import { z } from 'zod';
75
- *
76
- * const UserSchema = z.object({
77
- * name: z.string(),
78
- * age: z.number().min(0),
79
- * });
80
- *
81
- * if (isStandardJSONSchema(UserSchema)) {
82
- * const jsonSchema = extractViaStandardSchema(UserSchema);
83
- * console.log(jsonSchema);
84
- * // { type: 'object', properties: { name: { type: 'string' }, age: { type: 'number', minimum: 0 } } }
85
- * }
86
- * ```
170
+ * Find an adapter that matches the given type.
171
+ * Returns null if no adapter matches.
87
172
  */
88
- declare function isStandardJSONSchema(value: unknown): value is StandardJSONSchemaV1;
173
+ declare function findAdapter(type: TS2.Type, checker: TS2.TypeChecker): SchemaAdapter | null;
89
174
  /**
90
- * Extract JSON Schema from a Standard Schema v1 compliant value.
91
- *
92
- * @param schema - A value implementing StandardJSONSchemaV1
93
- * @param options - Extraction options
94
- * @returns Extracted JSON Schema result with vendor info
95
- * @throws Error if the value doesn't implement Standard Schema
96
- *
97
- * @example
98
- * ```typescript
99
- * import { extractViaStandardSchema } from '@doccov/sdk';
100
- *
101
- * // Works with any Standard Schema v1 compliant library
102
- * const result = extractViaStandardSchema(mySchema, { target: 'draft-2020-12' });
103
- * console.log(result.vendor); // 'zod', 'arktype', 'valibot', etc.
104
- * console.log(result.schema); // The extracted JSON Schema
105
- * ```
175
+ * Check if a type is from a recognized schema library.
106
176
  */
107
- declare function extractViaStandardSchema(schema: StandardJSONSchemaV1, options?: StandardSchemaOutputOptions): StandardSchemaResult;
177
+ declare function isSchemaType(type: TS2.Type, checker: TS2.TypeChecker): boolean;
108
178
  /**
109
- * Try to extract JSON Schema from a value that may or may not implement Standard Schema.
110
- *
111
- * @param value - Any value that might be a Standard Schema
112
- * @param options - Extraction options
113
- * @returns Extraction result, or null if value doesn't implement Standard Schema
114
- *
115
- * @example
116
- * ```typescript
117
- * import { tryExtractStandardSchema } from '@doccov/sdk';
118
- *
119
- * const result = tryExtractStandardSchema(unknownSchema);
120
- * if (result) {
121
- * console.log(`Extracted ${result.vendor} schema:`, result.schema);
122
- * }
123
- * ```
179
+ * Extract the output type from a schema type.
180
+ * Returns null if:
181
+ * - The type is not from a recognized schema library
182
+ * - The adapter fails to extract the output type
124
183
  */
125
- declare function tryExtractStandardSchema(value: unknown, options?: StandardSchemaOutputOptions): StandardSchemaResult | null;
184
+ declare function extractSchemaOutputType(type: TS2.Type, checker: TS2.TypeChecker): TS2.Type | null;
126
185
  /**
127
- * Supported Standard Schema vendors and their minimum versions.
186
+ * Full extraction with adapter info.
187
+ * Useful when you need to know which library was detected.
128
188
  */
129
- declare const KNOWN_VENDORS: {
130
- readonly zod: {
131
- readonly minVersion: "4.2.0";
132
- readonly homepage: "https://zod.dev";
133
- };
134
- readonly arktype: {
135
- readonly minVersion: "2.0.0";
136
- readonly homepage: "https://arktype.io";
137
- };
138
- readonly valibot: {
139
- readonly minVersion: "1.0.0";
140
- readonly homepage: "https://valibot.dev";
189
+ declare function extractSchemaType(type: TS2.Type, checker: TS2.TypeChecker): SchemaExtractionResult | null;
190
+ /**
191
+ * Get all registered adapters.
192
+ * Useful for logging/debugging.
193
+ */
194
+ declare function getRegisteredAdapters(): readonly SchemaAdapter[];
195
+ /**
196
+ * Get supported library names.
197
+ * Useful for documentation/help output.
198
+ */
199
+ declare function getSupportedLibraries(): readonly string[];
200
+ /**
201
+ * Standard JSON Schema v1 interface (minimal for detection).
202
+ */
203
+ interface StandardJSONSchemaV1 {
204
+ "~standard": {
205
+ version: number;
206
+ vendor: string;
207
+ jsonSchema?: {
208
+ output: (target?: string) => Record<string, unknown>;
209
+ input?: (target?: string) => Record<string, unknown>;
210
+ };
141
211
  };
142
- };
143
- type KnownVendor = keyof typeof KNOWN_VENDORS;
212
+ }
144
213
  /**
145
- * Context for schema detection.
214
+ * Result of extracting Standard Schema from an export.
146
215
  */
147
- interface SchemaDetectionContext {
148
- /** Base directory for resolving modules */
149
- baseDir: string;
150
- /** Entry file being analyzed */
151
- entryFile: string;
216
+ interface StandardSchemaExtractionResult {
217
+ exportName: string;
218
+ vendor: string;
219
+ outputSchema: Record<string, unknown>;
220
+ inputSchema?: Record<string, unknown>;
152
221
  }
153
222
  /**
154
- * Result of runtime schema detection for a module.
223
+ * Options for runtime Standard Schema extraction.
155
224
  */
156
- interface SchemaDetectionResult {
157
- /** Map of name to detected Standard Schema */
158
- schemas: Map<string, StandardSchemaResult>;
159
- /** Errors encountered during detection (non-fatal) */
225
+ interface ExtractStandardSchemasOptions {
226
+ /** Timeout in milliseconds (default: 10000) */
227
+ timeout?: number;
228
+ /** JSON Schema target version (default: 'draft-2020-12') */
229
+ target?: "draft-2020-12" | "draft-07" | "openapi-3.0";
230
+ }
231
+ /**
232
+ * Result of Standard Schema extraction.
233
+ */
234
+ interface StandardSchemaExtractionOutput {
235
+ schemas: Map<string, StandardSchemaExtractionResult>;
160
236
  errors: string[];
161
237
  }
162
238
  /**
163
- * Detect Standard Schema exports from a compiled module.
164
- *
165
- * This function attempts to load the compiled/transpiled version of the entry file
166
- * and checks each for Standard Schema compliance.
239
+ * Check if an object implements StandardJSONSchemaV1.
240
+ * This is a static type guard - doesn't require runtime.
241
+ */
242
+ declare function isStandardJSONSchema(obj: unknown): obj is StandardJSONSchemaV1;
243
+ /**
244
+ * Resolve compiled JS path from TypeScript source.
245
+ * Tries common output locations: dist/, build/, lib/, same dir.
246
+ */
247
+ declare function resolveCompiledPath(tsPath: string, baseDir: string): string | null;
248
+ /**
249
+ * Extract Standard Schema JSON Schemas from a compiled JS module.
167
250
  *
168
- * @param context - Detection context with paths
169
- * @returns Detection result with found schemas and any errors
251
+ * **Security Note**: This executes the module in a subprocess.
252
+ * Only use with trusted code (user's own packages).
170
253
  *
171
- * @example
172
- * ```typescript
173
- * const result = await detectRuntimeSchemas({
174
- * baseDir: '/path/to/project',
175
- * entryFile: '/path/to/project/dist/index.js',
176
- * });
177
- *
178
- * for (const [name, schema] of result.schemas) {
179
- * console.log(`Found ${schema.vendor} schema: ${name}`);
180
- * }
181
- * ```
254
+ * @param compiledJsPath - Path to compiled .js file
255
+ * @param options - Extraction options
256
+ * @returns Extraction results with schemas and any errors
182
257
  */
183
- declare function detectRuntimeSchemas(context: SchemaDetectionContext): Promise<SchemaDetectionResult>;
258
+ declare function extractStandardSchemas(compiledJsPath: string, options?: ExtractStandardSchemasOptions): Promise<StandardSchemaExtractionOutput>;
184
259
  /**
185
- * Clear the module cache.
186
- * Useful for testing or when modules may have changed.
260
+ * Extract Standard Schema from a TypeScript project.
261
+ *
262
+ * Convenience function that resolves compiled JS and extracts schemas.
263
+ *
264
+ * @param entryFile - TypeScript entry file path
265
+ * @param baseDir - Project base directory
266
+ * @param options - Extraction options
187
267
  */
188
- declare function clearSchemaCache(): void;
268
+ declare function extractStandardSchemasFromProject(entryFile: string, baseDir: string, options?: ExtractStandardSchemasOptions): Promise<StandardSchemaExtractionOutput>;
189
269
  import { DriftCategory, SpecDocDrift, SpecExport } from "@openpkg-ts/spec";
190
270
  interface ExampleRunResult {
191
271
  success: boolean;
@@ -413,227 +493,18 @@ declare function ensureSpecCoverage(spec: OpenPkgSpec): OpenPkgSpec & {
413
493
  coverageScore: number;
414
494
  };
415
495
  };
416
- import { OpenPkg as OpenPkg3, SpecDocDrift as SpecDocDrift2, SpecDocsMetadata, SpecExport as SpecExport3 } from "@openpkg-ts/spec";
417
- import { SpecExport as SpecExport2, SpecExportKind } from "@openpkg-ts/spec";
418
- import * as TS from "typescript";
419
- /**
420
- * Represents a single parameter in a JSDoc patch
421
- */
422
- interface JSDocParam {
423
- name: string;
424
- type?: string;
425
- description?: string;
426
- optional?: boolean;
427
- }
428
- /**
429
- * Represents a return type in a JSDoc patch
430
- */
431
- interface JSDocReturn {
432
- type?: string;
433
- description?: string;
434
- }
435
- /**
436
- * Represents a generic tag in a JSDoc patch
437
- */
438
- interface JSDocTag {
439
- name: string;
440
- text: string;
441
- }
442
- /**
443
- * A patchable representation of a JSDoc comment
444
- */
445
- interface JSDocPatch {
446
- description?: string;
447
- params?: JSDocParam[];
448
- returns?: JSDocReturn;
449
- examples?: string[];
450
- deprecated?: string | false;
451
- async?: boolean;
452
- type?: string;
453
- typeParams?: Array<{
454
- name: string;
455
- constraint?: string;
456
- description?: string;
457
- }>;
458
- otherTags?: JSDocTag[];
459
- }
460
- /**
461
- * Represents an edit to be applied to a source file
462
- */
463
- interface JSDocEdit {
464
- filePath: string;
465
- symbolName: string;
466
- startLine: number;
467
- endLine: number;
468
- hasExisting: boolean;
469
- existingJSDoc?: string;
470
- newJSDoc: string;
471
- indent: string;
472
- }
473
- /**
474
- * Result of applying edits to source files
475
- */
476
- interface ApplyEditsResult {
477
- filesModified: number;
478
- editsApplied: number;
479
- errors: Array<{
480
- file: string;
481
- error: string;
482
- }>;
483
- }
484
- /**
485
- * Parse a JSDoc comment string into a patchable structure
486
- */
487
- declare function parseJSDocToPatch(jsDocText: string): JSDocPatch;
488
- /**
489
- * Apply a partial patch to an existing JSDoc patch, preserving unmodified content
490
- */
491
- declare function applyPatchToJSDoc(existing: JSDocPatch, updates: Partial<JSDocPatch>): JSDocPatch;
492
- /**
493
- * Serialize a JSDocPatch back to a formatted comment string
494
- */
495
- declare function serializeJSDoc(patch: JSDocPatch, indent?: string): string;
496
- /**
497
- * Find the JSDoc location for a declaration in a source file
498
- */
499
- declare function findJSDocLocation(sourceFile: TS.SourceFile, symbolName: string, approximateLine?: number): {
500
- startLine: number;
501
- endLine: number;
502
- declarationLine: number;
503
- hasExisting: boolean;
504
- existingJSDoc?: string;
505
- indent: string;
506
- } | null;
507
- /**
508
- * Apply a batch of edits to source files
509
- */
510
- declare function applyEdits(edits: JSDocEdit[]): Promise<ApplyEditsResult>;
511
- /**
512
- * Create a TypeScript source file from a file path
513
- */
514
- declare function createSourceFile(filePath: string): TS.SourceFile;
515
- /**
516
- * Quality rule severity levels.
517
- */
518
- type QualitySeverity = "error" | "warn" | "off";
519
- /**
520
- * Context passed to quality rule checks.
521
- */
522
- interface RuleContext {
523
- export: SpecExport2;
524
- rawJSDoc?: string;
525
- /**
526
- * Registry of all exported names/IDs for spec-level rules.
527
- * Used by rules like no-forgotten-to check if referenced types are exported.
528
- */
529
- exportRegistry?: Set<string>;
530
- }
531
- /**
532
- * A violation reported by a quality rule.
533
- */
534
- interface QualityViolation {
535
- ruleId: string;
536
- severity: "error" | "warn";
537
- message: string;
538
- line?: number;
539
- fixable: boolean;
540
- }
541
- /**
542
- * A quality rule checks one aspect of documentation quality.
543
- * Rules can contribute to coverage score, lint violations, or both.
544
- */
545
- interface QualityRule {
546
- /** Unique rule identifier */
547
- id: string;
548
- /** Human-readable name */
549
- name: string;
550
- /** What this rule checks */
551
- description: string;
552
- /**
553
- * Which kinds this rule applies to.
554
- * If undefined, applies to all kinds.
555
- */
556
- appliesTo?: SpecExportKind[];
557
- /**
558
- * Does this rule contribute to coverage score?
559
- * If true, the rule is counted as a "signal" for coverage calculation.
560
- */
561
- affectsCoverage: boolean;
562
- /**
563
- * Default lint severity. Set to 'off' if rule is coverage-only.
564
- */
565
- defaultSeverity: QualitySeverity;
566
- /**
567
- * Check if the satisfies this rule.
568
- * Returns true if satisfied, false if not.
569
- */
570
- check(ctx: RuleContext): boolean;
571
- /**
572
- * Get detailed violation info when check returns false.
573
- * Only called if check() returns false and severity !== 'off'.
574
- */
575
- getViolation?(ctx: RuleContext): QualityViolation;
576
- /**
577
- * Generate a fix for the violation.
578
- * Only called if check() returns false and fix is requested.
579
- */
580
- fix?(ctx: RuleContext): JSDocPatch | null;
581
- }
582
- /**
583
- * User configuration for quality rules.
584
- */
585
- interface QualityConfig {
586
- rules: Record<string, QualitySeverity>;
587
- }
588
- /**
589
- * Result of evaluating quality for a single export.
590
- */
591
- interface QualityResult {
592
- /** Coverage score (0-100) */
593
- coverageScore: number;
594
- /** Coverage details */
595
- coverage: {
596
- /** Rule IDs that passed */
597
- satisfied: string[];
598
- /** Rule IDs that failed */
599
- missing: string[];
600
- /** All applicable rule IDs */
601
- applicable: string[];
602
- };
603
- /** Lint violations (only for rules with severity !== 'off') */
604
- violations: QualityViolation[];
605
- /** Summary counts */
606
- summary: {
607
- errorCount: number;
608
- warningCount: number;
609
- fixableCount: number;
610
- };
611
- }
612
- /**
613
- * Aggregate result for multiple exports.
614
- */
615
- interface AggregateQualityResult {
616
- byExport: Map<string, QualityResult>;
617
- overall: {
618
- coverageScore: number;
619
- totalViolations: number;
620
- errorCount: number;
621
- warningCount: number;
622
- };
623
- }
496
+ import { OpenPkg as OpenPkg3, SpecDocDrift as SpecDocDrift2, SpecDocsMetadata, SpecExport as SpecExport2 } from "@openpkg-ts/spec";
624
497
  /**
625
498
  * An enriched with computed documentation metadata.
626
499
  * Extends SpecExport with the `docs` field for coverage analysis.
627
500
  */
628
- type EnrichedExport = SpecExport3 & {
501
+ type EnrichedExport = SpecExport2 & {
629
502
  docs?: EnrichedDocsMetadata;
630
503
  };
631
504
  /**
632
- * Extended docs metadata with quality violations.
505
+ * Extended docs metadata.
633
506
  */
634
- type EnrichedDocsMetadata = SpecDocsMetadata & {
635
- violations?: QualityViolation[];
636
- };
507
+ type EnrichedDocsMetadata = SpecDocsMetadata;
637
508
  /**
638
509
  * An enriched OpenPkg spec with computed documentation metadata.
639
510
  * Extends OpenPkg with per-and aggregate coverage data.
@@ -650,21 +521,11 @@ interface EnrichOptions {
650
521
  * Map from ID to drift issues.
651
522
  */
652
523
  driftByExport?: Map<string, SpecDocDrift2[]>;
653
- /**
654
- * Quality configuration with rule severities.
655
- */
656
- qualityConfig?: QualityConfig;
657
- /**
658
- * Per-raw JSDoc text for style rule checks.
659
- * Map from ID to raw JSDoc string.
660
- */
661
- rawJSDocByExport?: Map<string, string>;
662
524
  }
663
525
  /**
664
526
  * Enrich an OpenPkg spec with documentation coverage metadata.
665
527
  *
666
- * This function computes coverage scores using quality rules,
667
- * detects drift issues, and produces an EnrichedOpenPkg.
528
+ * Computes coverage scores and detects drift issues.
668
529
  *
669
530
  * @param spec - The pure OpenPkg spec to enrich
670
531
  * @param options - Optional enrichment configuration
@@ -677,10 +538,8 @@ interface EnrichOptions {
677
538
  * const doccov = new DocCov();
678
539
  * const { spec } = await doccov.analyzeFileWithDiagnostics('src/index.ts');
679
540
  *
680
- * // Enrich with coverage data
681
541
  * const enriched = enrichSpec(spec);
682
542
  * console.log(enriched.docs?.coverageScore); // e.g., 85
683
- * console.log(enriched.docs?.missing); // e.g., ['has-examples']
684
543
  * ```
685
544
  */
686
545
  declare function enrichSpec(spec: OpenPkg3, options?: EnrichOptions): EnrichedOpenPkg;
@@ -1178,350 +1037,89 @@ interface SpecCache {
1178
1037
  /** Hash validation data */
1179
1038
  hashes: {
1180
1039
  /** Hash of tsconfig.json content (null if not found) */
1181
- tsconfig: string | null;
1182
- /** Hash of package.json content */
1183
- packageJson: string;
1184
- /** Source file hashes: relative filepath → content hash */
1185
- sourceFiles: Record<string, string>;
1186
- };
1187
- /** Analysis configuration that affects output */
1188
- config: SpecCacheConfig;
1189
- /** The cached OpenPkg spec */
1190
- spec: OpenPkg6;
1191
- }
1192
- /**
1193
- * Result of cache validation.
1194
- */
1195
- interface CacheValidationResult {
1196
- /** Whether the cache is valid */
1197
- valid: boolean;
1198
- /** Reason for invalidation (if invalid) */
1199
- reason?: "cache-version-mismatch" | "entry-file-changed" | "config-changed" | "tsconfig-changed" | "package-json-changed" | "source-files-changed";
1200
- /** Files that changed (if reason is source-files-changed) */
1201
- changedFiles?: string[];
1202
- }
1203
- /**
1204
- * Context needed for cache operations.
1205
- */
1206
- interface CacheContext {
1207
- /** Entry file being analyzed (absolute path) */
1208
- entryFile: string;
1209
- /** Source files included in analysis (absolute paths) */
1210
- sourceFiles: string[];
1211
- /** Path to tsconfig.json (absolute, or null if not found) */
1212
- tsconfigPath: string | null;
1213
- /** Path to package.json (absolute) */
1214
- packageJsonPath: string;
1215
- /** Configuration that affects output */
1216
- config: SpecCacheConfig;
1217
- /** Working directory */
1218
- cwd: string;
1219
- }
1220
- /**
1221
- * Load cached spec from disk.
1222
- *
1223
- * @param cwd - Working directory
1224
- * @returns Cached spec, or null if not found or invalid JSON
1225
- */
1226
- declare function loadSpecCache(cwd: string): SpecCache | null;
1227
- /**
1228
- * Save spec to cache.
1229
- *
1230
- * @param spec - OpenPkg spec to cache
1231
- * @param context - Cache context with file paths and config
1232
- */
1233
- declare function saveSpecCache(spec: OpenPkg6, context: CacheContext): void;
1234
- /**
1235
- * Validate if cached spec is still valid.
1236
- *
1237
- * Checks:
1238
- * 1. Cache version matches
1239
- * 2. Entry file matches
1240
- * 3. Config matches
1241
- * 4. tsconfig.json hash matches
1242
- * 5. package.json hash matches
1243
- * 6. All source file hashes match
1244
- *
1245
- * @param cache - Cached spec to validate
1246
- * @param context - Current cache context
1247
- * @returns Validation result
1248
- */
1249
- declare function validateSpecCache(cache: SpecCache, context: CacheContext): CacheValidationResult;
1250
- /**
1251
- * Clear the spec cache.
1252
- *
1253
- * @param cwd - Working directory
1254
- * @returns True if cache was deleted, false if it didn't exist
1255
- */
1256
- declare function clearSpecCache(cwd: string): boolean;
1257
- /**
1258
- * Get cache file path for a given working directory.
1259
- *
1260
- * @param cwd - Working directory
1261
- * @returns Absolute path to cache file
1262
- */
1263
- declare function getSpecCachePath(cwd: string): string;
1264
- /**
1265
- * A single CODEOWNERS rule.
1266
- */
1267
- interface CodeOwnerRule {
1268
- /** Line number in the CODEOWNERS file (1-indexed) */
1269
- line: number;
1270
- /** The glob pattern for matching files */
1271
- pattern: string;
1272
- /** List of owners (e.g., @user, @org/team, email) */
1273
- owners: string[];
1274
- }
1275
- /**
1276
- * Parsed CODEOWNERS file.
1277
- */
1278
- interface CodeOwnersFile {
1279
- /** Path to the CODEOWNERS file */
1280
- filePath: string;
1281
- /** All parsed rules (in order, later rules take precedence) */
1282
- rules: CodeOwnerRule[];
1283
- }
1284
- /**
1285
- * Coverage stats for a single owner.
1286
- */
1287
- interface OwnerCoverageStats {
1288
- /** The owner identifier */
1289
- owner: string;
1290
- /** Total exports owned */
1291
- totalExports: number;
1292
- /** Documented exports (has description) */
1293
- documentedExports: number;
1294
- /** Coverage percentage */
1295
- coverageScore: number;
1296
- /** Exports with drift issues */
1297
- exportsWithDrift: number;
1298
- /** Drift percentage */
1299
- driftScore: number;
1300
- /** Exports missing @example */
1301
- missingExamples: number;
1302
- /** List of undocumented names */
1303
- undocumentedExports: string[];
1304
- }
1305
- /**
1306
- * Result of ownership analysis.
1307
- */
1308
- interface OwnershipAnalysisResult {
1309
- /** Path to the CODEOWNERS file used */
1310
- codeownersPath: string;
1311
- /** Stats per owner */
1312
- byOwner: Map<string, OwnerCoverageStats>;
1313
- /** Exports with no matching owner */
1314
- unowned: EnrichedExport[];
1315
- /** Total exports analyzed */
1316
- totalExports: number;
1317
- }
1318
- /**
1319
- * Parse a CODEOWNERS file content into rules.
1320
- */
1321
- declare function parseCodeOwners(content: string): CodeOwnerRule[];
1322
- /**
1323
- * Find and load CODEOWNERS file from a directory.
1324
- */
1325
- declare function loadCodeOwners(baseDir: string): CodeOwnersFile | null;
1326
- /**
1327
- * Find owners for a file path based on CODEOWNERS rules.
1328
- * Returns the owners from the last matching rule (CODEOWNERS precedence).
1329
- */
1330
- declare function findOwners(filePath: string, rules: CodeOwnerRule[]): string[];
1331
- /**
1332
- * Attribute owners to exports based on their source file paths.
1333
- */
1334
- declare function attributeOwners(exports: EnrichedExport[], rules: CodeOwnerRule[], baseDir: string): Map<EnrichedExport, string[]>;
1335
- /**
1336
- * Analyze ownership and coverage breakdown by owner.
1337
- */
1338
- declare function analyzeOwnership(spec: EnrichedOpenPkg, codeowners: CodeOwnersFile, baseDir: string): OwnershipAnalysisResult;
1339
- /**
1340
- * Options for ownership analysis.
1341
- */
1342
- interface AnalyzeOwnershipOptions {
1343
- /** Base directory for the project */
1344
- baseDir: string;
1345
- }
1346
- /**
1347
- * Load CODEOWNERS and analyze ownership for a spec.
1348
- * Returns null if no CODEOWNERS file is found.
1349
- */
1350
- declare function analyzeSpecOwnership(spec: EnrichedOpenPkg, options: AnalyzeOwnershipOptions): OwnershipAnalysisResult | null;
1351
- /**
1352
- * Git blame info for a single line.
1353
- */
1354
- interface BlameInfo {
1355
- /** Commit hash */
1356
- commit: string;
1357
- /** Author name */
1358
- author: string;
1359
- /** Author email */
1360
- email: string;
1361
- /** Line number (1-indexed) */
1362
- line: number;
1363
- /** Timestamp */
1364
- timestamp: number;
1365
- }
1366
- /**
1367
- * Stats for a single contributor.
1368
- */
1369
- interface ContributorStats {
1370
- /** Contributor name */
1371
- name: string;
1372
- /** Contributor email */
1373
- email: string;
1374
- /** Number of exports this contributor documented */
1375
- documentedExports: number;
1376
- /** Names of exports documented by this contributor */
1377
- exports: string[];
1378
- /** Number of JSDoc lines authored */
1379
- linesAuthored: number;
1380
- /** Most recent documentation contribution */
1381
- lastContribution: Date | null;
1382
- }
1383
- /**
1384
- * Result of contributor analysis.
1385
- */
1386
- interface ContributorAnalysisResult {
1387
- /** Stats per contributor */
1388
- byContributor: Map<string, ContributorStats>;
1389
- /** Total documented exports analyzed */
1390
- totalDocumented: number;
1391
- /** Exports that couldn't be attributed (no git history) */
1392
- unattributed: string[];
1393
- }
1394
- /**
1395
- * Get git blame for a file.
1396
- */
1397
- declare function getFileBlame(filePath: string, cwd: string): BlameInfo[] | null;
1398
- /**
1399
- * Get blame info for specific line range.
1400
- */
1401
- declare function getBlameForLines(filePath: string, startLine: number, endLine: number, cwd: string): BlameInfo[] | null;
1402
- /**
1403
- * Analyze contributors for documented exports.
1404
- */
1405
- declare function analyzeContributors(spec: EnrichedOpenPkg, baseDir: string): ContributorAnalysisResult;
1406
- /**
1407
- * Options for contributor analysis.
1408
- */
1409
- interface AnalyzeContributorsOptions {
1410
- /** Base directory for the project (must be a git repo) */
1411
- baseDir: string;
1412
- }
1413
- /**
1414
- * Analyze spec contributors.
1415
- * Returns null if not in a git repository.
1416
- */
1417
- declare function analyzeSpecContributors(spec: EnrichedOpenPkg, options: AnalyzeContributorsOptions): ContributorAnalysisResult | null;
1418
- /**
1419
- * Configuration types for DocCov.
1420
- * These types are shared between CLI and API.
1421
- */
1422
- /**
1423
- * Documentation configuration options.
1424
- */
1425
- interface DocsConfig {
1426
- /** Glob patterns for markdown docs to include */
1427
- include?: string[];
1428
- /** Glob patterns for markdown docs to exclude */
1429
- exclude?: string[];
1040
+ tsconfig: string | null;
1041
+ /** Hash of package.json content */
1042
+ packageJson: string;
1043
+ /** Source file hashes: relative filepath → content hash */
1044
+ sourceFiles: Record<string, string>;
1045
+ };
1046
+ /** Analysis configuration that affects output */
1047
+ config: SpecCacheConfig;
1048
+ /** The cached OpenPkg spec */
1049
+ spec: OpenPkg6;
1430
1050
  }
1431
1051
  /**
1432
- * Example validation modes.
1052
+ * Result of cache validation.
1433
1053
  */
1434
- type ExampleValidationMode = "presence" | "typecheck" | "run";
1054
+ interface CacheValidationResult {
1055
+ /** Whether the cache is valid */
1056
+ valid: boolean;
1057
+ /** Reason for invalidation (if invalid) */
1058
+ reason?: "cache-version-mismatch" | "entry-file-changed" | "config-changed" | "tsconfig-changed" | "package-json-changed" | "source-files-changed";
1059
+ /** Files that changed (if reason is source-files-changed) */
1060
+ changedFiles?: string[];
1061
+ }
1435
1062
  /**
1436
- * Check command configuration options.
1063
+ * Context needed for cache operations.
1437
1064
  */
1438
- interface CheckConfig {
1439
- /**
1440
- * Example validation modes to run.
1441
- * Can be a single mode, array of modes, or comma-separated string.
1442
- * - 'presence': Check that @example blocks exist on exports
1443
- * - 'typecheck': Compile examples with TypeScript
1444
- * - 'run': Execute examples and validate assertions
1445
- */
1446
- examples?: ExampleValidationMode | ExampleValidationMode[] | string;
1447
- /** Minimum coverage percentage required (0-100) */
1448
- minCoverage?: number;
1449
- /** Maximum drift percentage allowed (0-100) */
1450
- maxDrift?: number;
1065
+ interface CacheContext {
1066
+ /** Entry file being analyzed (absolute path) */
1067
+ entryFile: string;
1068
+ /** Source files included in analysis (absolute paths) */
1069
+ sourceFiles: string[];
1070
+ /** Path to tsconfig.json (absolute, or null if not found) */
1071
+ tsconfigPath: string | null;
1072
+ /** Path to package.json (absolute) */
1073
+ packageJsonPath: string;
1074
+ /** Configuration that affects output */
1075
+ config: SpecCacheConfig;
1076
+ /** Working directory */
1077
+ cwd: string;
1451
1078
  }
1452
1079
  /**
1453
- * Quality rule severity level.
1080
+ * Load cached spec from disk.
1081
+ *
1082
+ * @param cwd - Working directory
1083
+ * @returns Cached spec, or null if not found or invalid JSON
1454
1084
  */
1455
- type QualitySeverity2 = "error" | "warn" | "off";
1085
+ declare function loadSpecCache(cwd: string): SpecCache | null;
1456
1086
  /**
1457
- * Quality rules configuration.
1087
+ * Save spec to cache.
1088
+ *
1089
+ * @param spec - OpenPkg spec to cache
1090
+ * @param context - Cache context with file paths and config
1458
1091
  */
1459
- interface QualityRulesConfig {
1460
- /** Rule severity overrides */
1461
- rules?: Record<string, QualitySeverity2>;
1462
- }
1092
+ declare function saveSpecCache(spec: OpenPkg6, context: CacheContext): void;
1463
1093
  /**
1464
- * Per-path policy configuration.
1465
- * Allows setting different coverage requirements for different parts of the codebase.
1094
+ * Validate if cached spec is still valid.
1095
+ *
1096
+ * Checks:
1097
+ * 1. Cache version matches
1098
+ * 2. Entry file matches
1099
+ * 3. Config matches
1100
+ * 4. tsconfig.json hash matches
1101
+ * 5. package.json hash matches
1102
+ * 6. All source file hashes match
1103
+ *
1104
+ * @param cache - Cached spec to validate
1105
+ * @param context - Current cache context
1106
+ * @returns Validation result
1466
1107
  */
1467
- interface PolicyConfig {
1468
- /** Glob pattern to match file paths (e.g., "packages/public-api/**") */
1469
- path: string;
1470
- /** Minimum coverage percentage required for matched paths (0-100) */
1471
- minCoverage?: number;
1472
- /** Maximum drift percentage allowed for matched paths (0-100) */
1473
- maxDrift?: number;
1474
- /** Require @example blocks on all matched exports */
1475
- requireExamples?: boolean;
1476
- }
1108
+ declare function validateSpecCache(cache: SpecCache, context: CacheContext): CacheValidationResult;
1477
1109
  /**
1478
- * Normalized DocCov configuration.
1479
- * This is the parsed/normalized form used by commands.
1110
+ * Clear the spec cache.
1111
+ *
1112
+ * @param cwd - Working directory
1113
+ * @returns True if cache was deleted, false if it didn't exist
1480
1114
  */
1481
- interface DocCovConfig {
1482
- /** Export include patterns */
1483
- include?: string[];
1484
- /** Export exclude patterns */
1485
- exclude?: string[];
1486
- /** Plugins (future) */
1487
- plugins?: unknown[];
1488
- /** Documentation configuration */
1489
- docs?: DocsConfig;
1490
- /** Check command configuration */
1491
- check?: CheckConfig;
1492
- /** Quality rules configuration */
1493
- quality?: QualityRulesConfig;
1494
- /** Per-path coverage policies (Pro tier) */
1495
- policies?: PolicyConfig[];
1496
- }
1115
+ declare function clearSpecCache(cwd: string): boolean;
1497
1116
  /**
1498
- * Define a DocCov configuration.
1499
- * Helper function for type-safe configuration in doccov.config.ts.
1500
- *
1501
- * @param config - Configuration object
1502
- * @returns The configuration object (for type inference)
1503
- *
1504
- * @example
1505
- * ```typescript
1506
- * // doccov.config.ts
1507
- * import { defineConfig } from '@doccov/sdk';
1117
+ * Get cache file path for a given working directory.
1508
1118
  *
1509
- * defineConfig({
1510
- * include: ['MyClass', 'myFunction'],
1511
- * exclude: ['internal*'],
1512
- * docs: {
1513
- * include: ['docs/**\/*.md'],
1514
- * },
1515
- * quality: {
1516
- * rules: {
1517
- * 'has-description': 'error',
1518
- * 'has-examples': 'warn',
1519
- * },
1520
- * },
1521
- * });
1522
- * ```
1119
+ * @param cwd - Working directory
1120
+ * @returns Absolute path to cache file
1523
1121
  */
1524
- declare function defineConfig(config: DocCovConfig): DocCovConfig;
1122
+ declare function getSpecCachePath(cwd: string): string;
1525
1123
  /**
1526
1124
  * Project detection types for I/O-agnostic project analysis.
1527
1125
  * Used by both CLI (NodeFileSystem) and API (SandboxFileSystem).
@@ -1811,7 +1409,7 @@ declare function parseExamplesFlag(value: boolean | string | undefined): Example
1811
1409
  * Check if a specific validation is enabled.
1812
1410
  */
1813
1411
  declare function shouldValidate(validations: ExampleValidation[], check: ExampleValidation): boolean;
1814
- import { SpecExport as SpecExport4 } from "@openpkg-ts/spec";
1412
+ import { SpecExport as SpecExport3 } from "@openpkg-ts/spec";
1815
1413
  interface ExampleTypeError {
1816
1414
  /** Index of the example in the examples array */
1817
1415
  exampleIndex: number;
@@ -1934,7 +1532,7 @@ interface ExampleValidationResult {
1934
1532
  * - `typecheck`: type-checks examples (doesn't require presence or run)
1935
1533
  * - `run`: executes examples (doesn't require presence or typecheck)
1936
1534
  */
1937
- declare function validateExamples(exports: SpecExport4[], options: ExampleValidationOptions): Promise<ExampleValidationResult>;
1535
+ declare function validateExamples(exports: SpecExport3[], options: ExampleValidationOptions): Promise<ExampleValidationResult>;
1938
1536
  declare function extractPackageSpec(entryFile: string, packageDir?: string, content?: string, options?: DocCovOptions): Promise<OpenPkgSpec>;
1939
1537
  /**
1940
1538
  * Release stage/visibility tags that can be used for filtering.
@@ -2003,7 +1601,104 @@ declare function parseListFlag(value?: string | string[]): string[] | undefined;
2003
1601
  * ```
2004
1602
  */
2005
1603
  declare function mergeFilters(config: DocCovConfig | null, overrides: FilterOptions): ResolvedFilters;
2006
- import { SpecDocDrift as SpecDocDrift4, SpecExport as SpecExport5 } from "@openpkg-ts/spec";
1604
+ import { SpecDocDrift as SpecDocDrift4, SpecExport as SpecExport4 } from "@openpkg-ts/spec";
1605
+ import * as TS3 from "typescript";
1606
+ /**
1607
+ * Represents a single parameter in a JSDoc patch
1608
+ */
1609
+ interface JSDocParam {
1610
+ name: string;
1611
+ type?: string;
1612
+ description?: string;
1613
+ optional?: boolean;
1614
+ }
1615
+ /**
1616
+ * Represents a return type in a JSDoc patch
1617
+ */
1618
+ interface JSDocReturn {
1619
+ type?: string;
1620
+ description?: string;
1621
+ }
1622
+ /**
1623
+ * Represents a generic tag in a JSDoc patch
1624
+ */
1625
+ interface JSDocTag {
1626
+ name: string;
1627
+ text: string;
1628
+ }
1629
+ /**
1630
+ * A patchable representation of a JSDoc comment
1631
+ */
1632
+ interface JSDocPatch {
1633
+ description?: string;
1634
+ params?: JSDocParam[];
1635
+ returns?: JSDocReturn;
1636
+ examples?: string[];
1637
+ deprecated?: string | false;
1638
+ async?: boolean;
1639
+ type?: string;
1640
+ typeParams?: Array<{
1641
+ name: string;
1642
+ constraint?: string;
1643
+ description?: string;
1644
+ }>;
1645
+ otherTags?: JSDocTag[];
1646
+ }
1647
+ /**
1648
+ * Represents an edit to be applied to a source file
1649
+ */
1650
+ interface JSDocEdit {
1651
+ filePath: string;
1652
+ symbolName: string;
1653
+ startLine: number;
1654
+ endLine: number;
1655
+ hasExisting: boolean;
1656
+ existingJSDoc?: string;
1657
+ newJSDoc: string;
1658
+ indent: string;
1659
+ }
1660
+ /**
1661
+ * Result of applying edits to source files
1662
+ */
1663
+ interface ApplyEditsResult {
1664
+ filesModified: number;
1665
+ editsApplied: number;
1666
+ errors: Array<{
1667
+ file: string;
1668
+ error: string;
1669
+ }>;
1670
+ }
1671
+ /**
1672
+ * Parse a JSDoc comment string into a patchable structure
1673
+ */
1674
+ declare function parseJSDocToPatch(jsDocText: string): JSDocPatch;
1675
+ /**
1676
+ * Apply a partial patch to an existing JSDoc patch, preserving unmodified content
1677
+ */
1678
+ declare function applyPatchToJSDoc(existing: JSDocPatch, updates: Partial<JSDocPatch>): JSDocPatch;
1679
+ /**
1680
+ * Serialize a JSDocPatch back to a formatted comment string
1681
+ */
1682
+ declare function serializeJSDoc(patch: JSDocPatch, indent?: string): string;
1683
+ /**
1684
+ * Find the JSDoc location for a declaration in a source file
1685
+ */
1686
+ declare function findJSDocLocation(sourceFile: TS3.SourceFile, symbolName: string, approximateLine?: number): {
1687
+ startLine: number;
1688
+ endLine: number;
1689
+ declarationLine: number;
1690
+ hasExisting: boolean;
1691
+ existingJSDoc?: string;
1692
+ indent: string;
1693
+ } | null;
1694
+ /**
1695
+ * Apply a batch of edits to source files
1696
+ */
1697
+ declare function applyEdits(edits: JSDocEdit[]): Promise<ApplyEditsResult>;
1698
+ /**
1699
+ * Create a TypeScript source file from a file path
1700
+ */
1701
+ declare function createSourceFile(filePath: string): TS3.SourceFile;
2007
1702
  /**
2008
1703
  * Types of fixes that can be generated
2009
1704
  */
@@ -2025,11 +1720,11 @@ declare function isFixableDrift(drift: SpecDocDrift4): boolean;
2025
1720
  /**
2026
1721
  * Generate a fix for a single drift issue
2027
1722
  */
2028
- declare function generateFix(drift: SpecDocDrift4, exportEntry: SpecExport5, existingPatch?: JSDocPatch): FixSuggestion | null;
1723
+ declare function generateFix(drift: SpecDocDrift4, exportEntry: SpecExport4, existingPatch?: JSDocPatch): FixSuggestion | null;
2029
1724
  /**
2030
1725
  * Generate all fixes for an export's drift issues
2031
1726
  */
2032
- declare function generateFixesForExport(exportEntry: SpecExport5, existingPatch?: JSDocPatch): FixSuggestion[];
1727
+ declare function generateFixesForExport(exportEntry: SpecExport4, existingPatch?: JSDocPatch): FixSuggestion[];
2033
1728
  /**
2034
1729
  * Merge multiple fix patches into a single patch
2035
1730
  */
@@ -2601,8 +2296,9 @@ declare class DocCov {
2601
2296
  */
2602
2297
  private findPackageJson;
2603
2298
  /**
2604
- * Opportunistically detect Standard Schema exports from compiled modules.
2605
- * Returns undefined if detection fails or no schemas found (fallback to AST).
2299
+ * Detect Standard Schema exports from compiled modules.
2300
+ * Only runs when schemaExtraction is 'runtime' or 'hybrid'.
2301
+ * Returns undefined if detection is disabled, fails, or no schemas found.
2606
2302
  */
2607
2303
  private detectSchemas;
2608
2304
  private normalizeDiagnostic;
@@ -2613,127 +2309,6 @@ declare class DocCov {
2613
2309
  declare function analyze(code: string, options?: AnalyzeOptions): Promise<OpenPkgSpec>;
2614
2310
  declare function analyzeFile(filePath: string, options?: AnalyzeOptions): Promise<OpenPkgSpec>;
2615
2311
  /**
2616
- * Result of evaluating a single policy.
2617
- */
2618
- interface PolicyResult {
2619
- /** The policy that was evaluated */
2620
- policy: PolicyConfig;
2621
- /** Exports that matched this policy's path pattern */
2622
- matchedExports: EnrichedExport[];
2623
- /** Coverage score for matched exports (0-100) */
2624
- coverageScore: number;
2625
- /** Drift score for matched exports (0-100, percentage of exports with drift) */
2626
- driftScore: number;
2627
- /** Number of matched exports missing @example */
2628
- missingExamples: number;
2629
- /** Whether the policy passed all configured thresholds */
2630
- passed: boolean;
2631
- /** Specific failures for this policy */
2632
- failures: PolicyFailure[];
2633
- }
2634
- /**
2635
- * A specific policy failure.
2636
- */
2637
- interface PolicyFailure {
2638
- type: "coverage" | "drift" | "examples";
2639
- message: string;
2640
- actual: number;
2641
- threshold: number;
2642
- }
2643
- /**
2644
- * Result of evaluating all policies.
2645
- */
2646
- interface PolicyEvaluationResult {
2647
- /** Results for each policy */
2648
- results: PolicyResult[];
2649
- /** Whether all policies passed */
2650
- allPassed: boolean;
2651
- /** Total number of policies */
2652
- totalPolicies: number;
2653
- /** Number of policies that passed */
2654
- passedCount: number;
2655
- /** Number of policies that failed */
2656
- failedCount: number;
2657
- }
2658
- /**
2659
- * Evaluate a single policy against a set of exports.
2660
- */
2661
- declare function evaluatePolicy(policy: PolicyConfig, allExports: EnrichedExport[], baseDir?: string): PolicyResult;
2662
- /**
2663
- * Options for evaluating policies.
2664
- */
2665
- interface EvaluatePoliciesOptions {
2666
- /** Base directory for resolving relative paths in policies */
2667
- baseDir?: string;
2668
- }
2669
- /**
2670
- * Evaluate all policies against a spec's exports.
2671
- */
2672
- declare function evaluatePolicies(policies: PolicyConfig[], spec: EnrichedOpenPkg, options?: EvaluatePoliciesOptions): PolicyEvaluationResult;
2673
- import { SpecExport as SpecExport6 } from "@openpkg-ts/spec";
2674
- import { SpecExportKind as SpecExportKind2 } from "@openpkg-ts/spec";
2675
- /**
2676
- * Core quality rules - these affect coverage score.
2677
- */
2678
- declare const CORE_RULES: QualityRule[];
2679
- /**
2680
- * TSDoc Strictness rules - match API Extractor's TSDoc compliance.
2681
- * These help maintain consistent, high-quality documentation.
2682
- */
2683
- declare const TSDOC_RULES: QualityRule[];
2684
- /**
2685
- * Style rules - these don't affect coverage, only lint.
2686
- */
2687
- declare const STYLE_RULES: QualityRule[];
2688
- /**
2689
- * All built-in quality rules.
2690
- */
2691
- declare const BUILTIN_RULES: QualityRule[];
2692
- /**
2693
- * Get rules that affect coverage calculation.
2694
- */
2695
- declare function getCoverageRules(): QualityRule[];
2696
- /**
2697
- * Get rules applicable to a specific kind.
2698
- */
2699
- declare function getRulesForKind(kind: SpecExportKind2): QualityRule[];
2700
- /**
2701
- * Get a rule by ID.
2702
- */
2703
- declare function getRule(id: string): QualityRule | undefined;
2704
- /**
2705
- * Get default configuration with all rule defaults.
2706
- */
2707
- declare function getDefaultConfig(): Record<string, QualitySeverity>;
2708
- /**
2709
- * Evaluate quality for a single export.
2710
- *
2711
- * @param exp - The to evaluate
2712
- * @param rawJSDoc - Optional raw JSDoc text for regex-based checks
2713
- * @param config - Quality configuration with rule severities
2714
- * @param exportRegistry - Optional registry of all exported names for spec-level rules
2715
- * @returns Quality result with coverage score and violations
2716
- */
2717
- declare function evaluateExportQuality(exp: SpecExport6, rawJSDoc?: string, config?: QualityConfig, exportRegistry?: Set<string>): QualityResult;
2718
- /**
2719
- * Evaluate quality for multiple exports.
2720
- *
2721
- * @param exports - Array of exports with optional raw JSDoc
2722
- * @param config - Quality configuration with rule severities
2723
- * @returns Aggregate result with per-and overall scores
2724
- */
2725
- declare function evaluateQuality(exports: Array<{
2726
- export: SpecExport6;
2727
- rawJSDoc?: string;
2728
- }>, config?: QualityConfig): AggregateQualityResult;
2729
- /**
2730
- * Merge user configuration with defaults.
2731
- *
2732
- * @param userConfig - Partial user configuration
2733
- * @returns Complete configuration with defaults filled in
2734
- */
2735
- declare function mergeConfig(userConfig: Partial<QualityConfig>): QualityConfig;
2736
- /**
2737
2312
  * Options for resolving a target package/entry point.
2738
2313
  */
2739
2314
  interface ResolveTargetOptions {
@@ -3035,4 +2610,4 @@ declare function typecheckExample(example: string, packagePath: string, options?
3035
2610
  * Type-check multiple examples
3036
2611
  */
3037
2612
  declare function typecheckExamples(examples: string[], packagePath: string, options?: TypecheckOptions): TypecheckResult;
3038
- export { validateSpecCache, validateExamples, typecheckExamples, typecheckExample, tryExtractStandardSchema, shouldValidate, serializeJSDoc, saveSpecCache, saveSnapshot, saveReport, safeParseJson, runExamplesWithPackage, runExamples, runExample, resolveTarget, renderSparkline, renderApiSurface, readPackageJson, pruneHistory, pruneByTier, parseGitHubUrl2 as parseScanGitHubUrl, parseMarkdownFiles, parseMarkdownFile, parseListFlag, parseJSDocToPatch, parseGitHubUrl, parseExamplesFlag, parseCodeOwners, parseAssertions, mergeFixes, mergeFilters, mergeConfig, loadSpecCache, loadSnapshotsForDays, loadSnapshots, loadCodeOwners, loadCachedReport, listWorkspacePackages, isStandardJSONSchema, isFixableDrift, isExecutableLang, isCachedReportValid, installDependencies, hashString, hashFiles, hashFile, hasNonAssertionComments, hasDocsImpact, hasDocsForExport, groupDriftsByCategory, getUndocumentedExports, getTrend, getSpecCachePath, getRunCommand, getRulesForKind, getRule, getReportPath, getPrimaryBuildScript, getInstallCommand, getFileBlame, getExtendedTrend, getDriftSummary, getDocumentedExports, getDocsImpactSummary, getDiffReportPath, getDefaultConfig, getCoverageRules, getBlameForLines, generateWeeklySummaries, generateReportFromEnriched, generateReport, generateFixesForExport, generateFix, formatPackageList, formatDriftSummaryLine, formatDelta, findRemovedReferences, findPackageByName, findOwners, findJSDocLocation, findExportReferences, findDeprecatedReferences, fetchSpecFromGitHub, fetchSpec, fetchGitHubContext, extractViaStandardSchema, extractSpecSummary, extractPackageSpec, extractImports, extractFunctionCalls, evaluateQuality, evaluatePolicy, evaluatePolicies, evaluateExportQuality, ensureSpecCoverage, enrichSpec, diffSpecWithDocs, diffHashes, detectRuntimeSchemas, detectPackageManager, detectMonorepo, detectExampleRuntimeErrors, detectExampleAssertionFailures, detectEntryPoint, detectBuildInfo, defineConfig, createSourceFile, createNodeCommandRunner, computeSnapshot, computeExportDrift, computeDrift, clearSpecCache, clearSchemaCache, categorizeDrifts, categorizeDrift, calculateAggregateCoverage, buildRawUrl, buildExportRegistry, buildDisplayUrl, buildCloneUrl, blockReferencesExport, attributeOwners, applyPatchToJSDoc, applyEdits, analyzeSpecOwnership, analyzeSpecContributors, analyzeProject2 as analyzeProject, analyzeOwnership, analyzeFile, analyzeDocsImpact, analyzeContributors, analyze, WorkspacePackage, WorkspaceConfig, WeeklySummary, VALIDATION_INFO, TypecheckValidationResult, TypecheckResult, TypecheckOptions, TSDOC_RULES, SummaryDriftIssue, StandardSchemaResult, StandardSchemaOutputOptions, StandardJSONSchemaV1, SpecSummary, SpecDiffWithDocs, SpecCacheConfig, SpecCache, SchemaDetectionResult, SchemaDetectionContext, SandboxFileSystem, STYLE_RULES, SPEC_CACHE_FILE, RuntimeDrift, RunValidationResult, RunExamplesWithPackageResult, RunExamplesWithPackageOptions, RunExampleOptions, RuleContext, RetentionTier, ResolvedTarget, ResolvedFilters, ResolveTargetOptions, ReleaseTag, RETENTION_DAYS, REPORT_VERSION, REPORT_EXTENSIONS, QualityViolation, QualitySeverity2 as QualitySeverity, QualityRulesConfig, QualityRule, QualityResult, QualityConfig, ProjectInfo, PresenceResult, PolicyResult, PolicyFailure, PolicyEvaluationResult, PolicyConfig, ParsedGitHubUrl, PackageManagerInfo, PackageManager, PackageJson, PackageExports, OwnershipAnalysisResult, OwnerCoverageStats, OpenPkgSpec, NodeFileSystem, MonorepoType, MonorepoInfo, MemberChange, MarkdownDocFile, MarkdownCodeBlock, LLMAssertion, KnownVendor, KNOWN_VENDORS, JSDocTag, JSDocReturn, JSDocPatch, JSDocParam, JSDocEdit, InstallResult, InstallOptions, HISTORY_DIR, GitHubRepoMetadata, GitHubProjectContext, FixType, FixSuggestion, FilterSource, FilterOptions, FileSystem, FetchGitHubContextOptions, ExtendedTrendAnalysis, ExportReference, ExportDriftResult, ExportCoverageData, ExampleValidationTypeError, ExampleValidationResult, ExampleValidationOptions, ExampleValidationMode, ExampleValidation, ExampleTypeError, ExampleRunResult, EvaluatePoliciesOptions, EntryPointSource, EntryPointInfo, EnrichedOpenPkg, EnrichedExport, EnrichedDocsMetadata, EnrichOptions, DriftSummary, DriftResult, DriftReportSummary, DriftReport, DocsImpactResult, DocsImpactReference, DocsImpact, DocsConfig, DocsChangeType, DocCovReport, DocCovOptions, DocCovConfig, DocCov, DiffWithDocsOptions, Diagnostic2 as Diagnostic, DetectedSchemaEntry, DetectedPackageManager, DEFAULT_REPORT_PATH, DEFAULT_REPORT_DIR, CoverageTrend, CoverageSummary, CoverageSnapshot, ContributorStats, ContributorAnalysisResult, CommandRunner, CommandResult, CodeOwnersFile, CodeOwnerRule, CheckConfig, CategorizedDrift, CacheValidationResult, CacheContext, CORE_RULES, CACHE_VERSION, BuildPlanTarget, BuildPlanStepResult, BuildPlanStep, BuildPlanExecutionResult, BuildPlanEnvironment, BuildPlan, BuildInfo, BuildHints, BlameInfo, BUILTIN_RULES, ApplyEditsResult, AnalyzeProjectOptions, AnalyzeOwnershipOptions, AnalyzeOptions, AnalyzeContributorsOptions, AnalysisResult, AggregateQualityResult, ALL_VALIDATIONS };
2613
+ export { validateSpecCache, validateExamples, typecheckExamples, typecheckExample, shouldValidate, serializeJSDoc, saveSpecCache, saveSnapshot, saveReport, safeParseJson, runExamplesWithPackage, runExamples, runExample, resolveTarget, resolveCompiledPath, renderSparkline, renderApiSurface, readPackageJson, pruneHistory, pruneByTier, parseGitHubUrl2 as parseScanGitHubUrl, parseMarkdownFiles, parseMarkdownFile, parseListFlag, parseJSDocToPatch, parseGitHubUrl, parseExamplesFlag, parseAssertions, mergeFixes, mergeFilters, loadSpecCache, loadSnapshotsForDays, loadSnapshots, loadCachedReport, listWorkspacePackages, isStandardJSONSchema, isSchemaType, isFixableDrift, isExecutableLang, isCachedReportValid, installDependencies, hashString, hashFiles, hashFile, hasNonAssertionComments, hasDocsImpact, hasDocsForExport, groupDriftsByCategory, getUndocumentedExports, getTrend, getSupportedLibraries, getSpecCachePath, getRunCommand, getReportPath, getRegisteredAdapters, getPrimaryBuildScript, getInstallCommand, getExtendedTrend, getDriftSummary, getDocumentedExports, getDocsImpactSummary, getDiffReportPath, generateWeeklySummaries, generateReportFromEnriched, generateReport, generateFixesForExport, generateFix, formatPackageList, formatDriftSummaryLine, formatDelta, findRemovedReferences, findPackageByName, findJSDocLocation, findExportReferences, findDeprecatedReferences, findAdapter, fetchSpecFromGitHub, fetchSpec, fetchGitHubContext, extractStandardSchemasFromProject, extractStandardSchemas, extractSpecSummary, extractSchemaType, extractSchemaOutputType, extractPackageSpec, extractImports, extractFunctionCalls, ensureSpecCoverage, enrichSpec, diffSpecWithDocs, diffHashes, detectRuntimeSchemas, detectPackageManager, detectMonorepo, detectExampleRuntimeErrors, detectExampleAssertionFailures, detectEntryPoint, detectBuildInfo, defineConfig, createSourceFile, createNodeCommandRunner, computeSnapshot, computeExportDrift, computeDrift, clearSpecCache, clearSchemaCache, categorizeDrifts, categorizeDrift, calculateAggregateCoverage, buildRawUrl, buildExportRegistry, buildDisplayUrl, buildCloneUrl, blockReferencesExport, applyPatchToJSDoc, applyEdits, analyzeProject2 as analyzeProject, analyzeFile, analyzeDocsImpact, analyze, WorkspacePackage, WorkspaceConfig, WeeklySummary, VALIDATION_INFO, TypecheckValidationResult, TypecheckResult, TypecheckOptions, SummaryDriftIssue, StandardSchemaExtractionResult, StandardSchemaExtractionOutput, StandardJSONSchemaV1, SpecSummary, SpecDiffWithDocs, SpecCacheConfig, SpecCache, SchemaExtractionResult, SchemaExtractionMode, SchemaDetectionResult, SchemaDetectionContext, SchemaAdapter, SandboxFileSystem, SPEC_CACHE_FILE, RuntimeDrift, RunValidationResult, RunExamplesWithPackageResult, RunExamplesWithPackageOptions, RunExampleOptions, RetentionTier, ResolvedTarget, ResolvedFilters, ResolveTargetOptions, ReleaseTag, RETENTION_DAYS, REPORT_VERSION, REPORT_EXTENSIONS, ProjectInfo, PresenceResult, ParsedGitHubUrl, PackageManagerInfo, PackageManager, PackageJson, PackageExports, OpenPkgSpec, NodeFileSystem, MonorepoType, MonorepoInfo, MemberChange, MarkdownDocFile, MarkdownCodeBlock, LLMAssertion, JSDocTag, JSDocReturn, JSDocPatch, JSDocParam, JSDocEdit, InstallResult, InstallOptions, HISTORY_DIR, GitHubRepoMetadata, GitHubProjectContext, FixType, FixSuggestion, FilterSource, FilterOptions, FileSystem, FetchGitHubContextOptions, ExtractStandardSchemasOptions, ExtendedTrendAnalysis, ExportReference, ExportDriftResult, ExportCoverageData, ExampleValidationTypeError, ExampleValidationResult, ExampleValidationOptions, ExampleValidationMode, ExampleValidation, ExampleTypeError, ExampleRunResult, EntryPointSource, EntryPointInfo, EnrichedOpenPkg, EnrichedExport, EnrichedDocsMetadata, EnrichOptions, DriftSummary, DriftResult, DriftReportSummary, DriftReport, DocsImpactResult, DocsImpactReference, DocsImpact, DocsConfig, DocsChangeType, DocCovReport, DocCovOptions, DocCovConfig, DocCov, DiffWithDocsOptions, Diagnostic2 as Diagnostic, DetectedSchemaEntry, DetectedPackageManager, DEFAULT_REPORT_PATH, DEFAULT_REPORT_DIR, CoverageTrend, CoverageSummary, CoverageSnapshot, CommandRunner, CommandResult, CheckConfig, CategorizedDrift, CacheValidationResult, CacheContext, CACHE_VERSION, BuildPlanTarget, BuildPlanStepResult, BuildPlanStep, BuildPlanExecutionResult, BuildPlanEnvironment, BuildPlan, BuildInfo, BuildHints, ApplyEditsResult, AnalyzeProjectOptions, AnalyzeOptions, AnalysisResult, ALL_VALIDATIONS };