### Custom Instrumenter Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Complete example of setting up the plugin with a custom instrumenter in vite.config.js. ```javascript import istanbul from 'vite-plugin-istanbul'; import { createOxcInstrumenter } from 'oxc-coverage-instrument/vitest'; export default { plugins: [ istanbul({ instrumenter: createOxcInstrumenter(), }), ], }; ``` -------------------------------- ### Advanced Configuration Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Example demonstrating all available configuration options. ```javascript istanbul({ include: 'src/**', exclude: ['**/*.test.ts'], extension: ['.ts', '.tsx', '.vue'], requireEnv: true, cypress: false, checkProd: true, forceBuildInstrument: false, cwd: process.cwd(), nycrcPath: undefined, generatorOpts: { compact: false }, onCover: (file, coverage) => console.log(`Instrumented: ${file}`), instrumenter: undefined, // Uses default }) ``` -------------------------------- ### Installation Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Commands for installing vite-plugin-istanbul using npm, yarn, or pnpm. ```bash npm install -D vite-plugin-istanbul # or yarn add -D vite-plugin-istanbul # or pnpm add -D vite-plugin-istanbul ``` -------------------------------- ### Minimal Setup Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Basic configuration for vite-plugin-istanbul in vite.config.js. ```javascript // vite.config.js import istanbul from 'vite-plugin-istanbul'; export default { plugins: [istanbul()], }; ``` -------------------------------- ### Testing Library / Jest-like Testing Setup Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/endpoints.md Example setup script for integrating coverage collection with Testing Library or Jest-like environments. ```javascript // setup-coverage.js afterAll(async () => { if (typeof fetch === 'undefined') { // Polyfill for Node environment if needed const http = require('http'); return new Promise((resolve) => { http.get('http://localhost:5173/__coverage__', (res) => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => { global.__coverage__ = JSON.parse(data); resolve(); }); }); }); } const response = await fetch('/__coverage__'); global.__coverage__ = await response.json(); }); ``` -------------------------------- ### Setup Commands Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/AGENTS.md Commands for installing dependencies, preparing git hooks, and verifying the Node version. ```bash pnpm install --frozen-lockfile ``` ```bash pnpm run prepare ``` ```bash node -v ``` -------------------------------- ### Use with .nycrc Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Example of configuring vite-plugin-istanbul to automatically load settings from a .nycrc file. ```javascript istanbul({ // Settings loaded from .nycrc automatically // Can override individual options here if needed }) ``` -------------------------------- ### Troubleshooting Wrong Environment Variable Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Examples of setting environment variables for different scenarios like requireEnv and cypress, highlighting case sensitivity. ```bash # If using requireEnv: true VITE_COVERAGE=true npm run dev # If using cypress: true CYPRESS_COVERAGE=true npx cypress run # Note: Case sensitive for value (use lowercase) VITE_COVERAGE=true # ✓ Works VITE_COVERAGE=True # ✗ Won't work ``` -------------------------------- ### Basic Setup Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/istanbul-plugin.md Basic setup for vite-plugin-istanbul in vite.config.js. ```javascript // vite.config.js import istanbul from 'vite-plugin-istanbul'; export default { plugins: [ istanbul({ include: 'src/*', exclude: ['node_modules', 'test/'], extension: ['.js', '.ts', '.vue'], }), ], }; ``` -------------------------------- ### Include Patterns Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Examples of glob patterns for the 'include' option. ```javascript istanbul({ include: 'src/*' // All files directly in src/ include: 'src/**' // All files recursively in src/ include: 'src/**/*.ts' // Only .ts files include: ['src/**', '!node_modules'] // Multiple patterns }) ``` -------------------------------- ### GET /__coverage__ Request Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/endpoints.md Example HTTP request to retrieve code coverage data. ```http GET /__coverage__ HTTP/1.1 Host: localhost:5173 Accept: application/json ``` -------------------------------- ### Two-Phase Enable Check Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md Example illustrating the two-phase check for enabling the plugin. ```typescript let enabled = true; // Lazy check apply(_, env) { return forceBuildInstrument ? true : env.command == 'serve'; } configResolved(config) { if (checkProd && isProduction) { enabled = false; } // ... check env vars ... } ``` -------------------------------- ### Configuration Resolution Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md An example of how plugin options are merged with configuration files like .nycrc, with plugin options having the highest priority. ```javascript istanbul({ include: 'src/**', // exclude not specified, will load from .nycrc if exists }) ``` -------------------------------- ### Basic Development Setup Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md A basic configuration for development setup, including include and exclude patterns. ```javascript // vite.config.js import istanbul from 'vite-plugin-istanbul'; export default { plugins: [ istanbul({ include: 'src/**', exclude: ['**/*.spec.ts', 'node_modules/**'], }), ], }; ``` -------------------------------- ### Example Vitest Commands (Future Use) Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/AGENTS.md Example patterns for running Vitest tests by file or by test name, to be added if a test framework is configured. ```bash pnpm vitest run path/to/file.test.ts ``` ```bash pnpm vitest run -t "name" ``` -------------------------------- ### With Custom Instrumenter Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Configuration using a custom instrumenter, demonstrated with Oxc. ```javascript import { createOxcInstrumenter } from 'oxc-coverage-instrument/vitest'; istanbul({ instrumenter: createOxcInstrumenter(), }) ``` -------------------------------- ### File Structure Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Overview of the vite-plugin-istanbul project file structure. ```text vite-plugin-istanbul/ ├── src/index.ts ← Main plugin function ├── src/types.d.ts ← Type declarations ├── src/source-map.ts ← Source map utilities ├── src/vue-sfc.ts ← Vue SFC handling └── dist/ ├── index.mjs ← Compiled plugin └── index.d.mts ← Exported types ``` -------------------------------- ### Installation with yarn Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/README.md Installs the vite-plugin-istanbul package as a development dependency using yarn. ```bash yarn add -D vite-plugin-istanbul ``` -------------------------------- ### Custom Configuration Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/exports-index.md Example of configuring the plugin with a custom nycrcPath. ```javascript istanbul({ nycrcPath: '/path/to/.nycrc', }) ``` -------------------------------- ### Vitest Integration Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/endpoints.md Example configuration for integrating vite-plugin-istanbul with Vitest. ```javascript // vitest.config.js import { defineConfig } from 'vitest/config'; import istanbul from 'vite-plugin-istanbul'; export default defineConfig({ plugins: [istanbul({ include: 'src/*' })], test: { coverage: { provider: 'istanbul', }, }, }); ``` ```javascript // In test setup: import { afterAll } from 'vitest'; afterAll(async () => { const coverage = await fetch('/__coverage__').then(r => r.json()); // Process coverage data }); ``` -------------------------------- ### Installation with npm Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/README.md Installs the vite-plugin-istanbul package as a development dependency using npm. ```bash npm i -D vite-plugin-istanbul ``` -------------------------------- ### Cypress Integration Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/endpoints.md Example support file for integrating coverage collection with Cypress. ```javascript // cypress/support/coverage.js Cypress.on('window:before:load', (win) => { cy.visit('/').then(() => { cy.window().then((win) => { if (win.__coverage__) { cy.log('Coverage data found in window'); } }); }); }); afterEach(() => { cy.window().then((win) => { const coverage = win.__coverage__; if (coverage) { // Save coverage data for later analysis cy.writeFile('cypress/coverage.json', JSON.stringify(coverage)); } }); }); ``` -------------------------------- ### vite.config.js Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/README.md Example of how to define the vite-plugin-istanbul in your vite.config.js file. ```javascript // vite.config.js import istanbul from 'vite-plugin-istanbul'; export default { open: true, port: 3000, plugins: [ istanbul({ include: 'src/*', exclude: ['node_modules', 'test/'], extension: ['.js', '.ts', '.vue'], requireEnv: true, }), ], }; ``` -------------------------------- ### Usage Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/types.md Example of how to use the istanbul plugin in Vite configuration. ```typescript import istanbul from 'vite-plugin-istanbul'; const config = { plugins: [ istanbul({ include: ['src/**/*.{js,ts}'], exclude: ['**/*.spec.ts', 'node_modules/**'], extension: ['.js', '.ts'], requireEnv: true, cwd: process.cwd(), onCover: (filename, coverage) => { console.log(`Instrumented: ${filename}`); }, }), ], }; ``` -------------------------------- ### Commit Message Header Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/CONTRIBUTING.md An example of a commit message header. ```git docs(changelog): update changelog to beta.5 ``` -------------------------------- ### Coverage Callback Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Demonstrates how to use the `onCover` callback to execute code when files are instrumented. ```javascript export default { plugins: [ istanbul({ include: 'src/*', onCover: (fileName, fileCoverage) => { console.log(`Instrumented: ${fileName}`); // fileCoverage is the Istanbul file coverage object // Can be used to track instrumentation progress }, }), ], }; ``` -------------------------------- ### Handling Production Builds Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Configuration options for handling production builds, including disabling instrumentation and forcing instrumentation. ```javascript // Don't instrument in production istanbul({ checkProd: true, // Default: skip in production }) // Force instrumentation (not recommended) istanbul({ checkProd: false, forceBuildInstrument: true, }) ``` -------------------------------- ### Configuration Options Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/exports-index.md Illustrates the structure of configuration options that can be passed to the istanbul plugin. ```typescript istanbul({ include?: string | string[]; exclude?: string | string[]; extension?: string | string[]; requireEnv?: boolean; cypress?: boolean; checkProd?: boolean; forceBuildInstrument?: boolean; cwd?: string; nycrcPath?: string; generatorOpts?: GeneratorOptions; onCover?: (fileName: string, fileCoverage: object) => void; instrumenter?: CustomInstrumenter; }) ``` -------------------------------- ### createCompleteSourceMap Usage Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/source-map-utilities.md Example of creating a complete source map for Vue SFCs. ```typescript // Creating a complete source map for Vue SFC import { createCompleteSourceMap } from './source-map'; const vueCompiledCode = `/* generated from template */\nfunction render() { ... }`; const originalVueFile = `\n`; const sourceMap = createCompleteSourceMap( 'src/App.vue', vueCompiledCode, originalVueFile, { file: 'App.vue' } ); ``` -------------------------------- ### JavaScript/Fetch Usage Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/endpoints.md Example of fetching coverage data using the Fetch API in JavaScript. ```javascript // Basic fetch const response = await fetch('/__coverage__'); const coverage = await response.json(); console.log(coverage); // With error handling async function getCoverage() { try { const response = await fetch('/__coverage__'); if (!response.ok) { throw new Error(`Coverage endpoint returned ${response.status}`); } const coverage = await response.json(); return coverage; } catch (error) { console.error('Failed to fetch coverage:', error); return null; } } ``` -------------------------------- ### Using .nycrc Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Example .nycrc configuration file. ```json { "include": ["src/**"], "exclude": ["**/*.spec.ts", "node_modules/**"], "extension": [".js", ".ts"], "report-dir": "./coverage", "reporter": ["text", "html"] } ``` -------------------------------- ### Commit Message Body Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/CONTRIBUTING.md An example of a commit message with a body. ```git fix(release): need to depend on latest rxjs and zone.js The version in our package.json gets copied to the one we publish, and users need the latest of these. ``` -------------------------------- ### Lazy Initialization Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md Example demonstrating lazy initialization of the testExclude object. ```typescript let testExclude: TestExclude; // Declared globally async config() { testExclude = await createTestExclude(opts); } ``` -------------------------------- ### Exclude Patterns Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Examples of glob patterns for the 'exclude' option. ```javascript istanbul({ exclude: 'node_modules' // Exclude node_modules exclude: '**/*.spec.ts' // Exclude test files exclude: ['dist/**', 'build/**'] // Multiple patterns }) ``` -------------------------------- ### Using package.json for NYC Configuration Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Example NYC configuration within package.json. ```json { "name": "my-project", "nyc": { "include": ["src/**"], "exclude": ["**/*.spec.ts", "node_modules/**"], "extension": [".js", ".ts"] } } ``` -------------------------------- ### Type Exports Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Importing type definitions for configuration and custom instrumenters. ```typescript import type { IstanbulPluginOptions, CustomInstrumenter } from 'vite-plugin-istanbul'; ``` -------------------------------- ### Vue Project Configuration Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Configuration tailored for Vue projects, specifying additional file extensions. ```javascript istanbul({ include: 'src/**', extension: ['.ts', '.tsx', '.vue'], }) ``` -------------------------------- ### Development Configuration Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Configuration pattern for development environments, including include and exclude patterns. ```javascript istanbul({ include: 'src/**', exclude: ['**/*.test.ts'], }) ``` -------------------------------- ### Environment Variable Case Sensitivity Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/errors.md Bash examples demonstrating the case sensitivity of environment variable keys versus values for the VITE_COVERAGE setting. ```bash # These work (lowercase true/false): VITE_COVERAGE=true # ✅ Enables instrumentation VITE_COVERAGE=false # ✅ Disables instrumentation VITE_COVERAGE=True # ❌ Not recognized, treated as string VITE_COVERAGE=FALSE # ❌ Not recognized, treated as string ``` -------------------------------- ### Options API SFC Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/vue-sfc-handling.md An example of a Vue file using the Options API and its compilation output. ```vue ``` ```javascript // Chunk 1: id = /path/to/App.vue // Contains: compiled template + user code const _sfc_main = { data() { return { count: 0 } }, methods: { increment() { this.count++ } } } export default _sfc_main; // Chunk 2: id = /path/to/App.vue?vue&type=style&index=0 // Contains: CSS (not instrumented) ``` -------------------------------- ### Valid Pattern Syntax Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/errors.md JavaScript configuration examples demonstrating valid glob syntax for include/exclude patterns. ```javascript istanbul({ include: ['src/**/*.ts', 'src/**/*.js'], exclude: ['**/*.spec.ts', '**/*.test.ts', 'node_modules/**'], }) ``` -------------------------------- ### With Coverage Callback Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/istanbul-plugin.md Setup for vite-plugin-istanbul with a coverage callback. ```javascript // vite.config.js import istanbul from 'vite-plugin-istanbul'; export default { plugins: [ istanbul({ include: 'src/*', onCover: (fileName, fileCoverage) => { console.log(`Instrumented: ${fileName}`); }, }), ], }; ``` -------------------------------- ### createIdentitySourceMap Usage Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/source-map-utilities.md Example of how to use the createIdentitySourceMap function within the plugin. ```typescript // Internal usage within the plugin import { createIdentitySourceMap } from './source-map'; const sourceMap = createIdentitySourceMap( 'src/app.ts', sourceCode, { file: 'app.ts' } ); ``` -------------------------------- ### Composition API SFC Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/vue-sfc-handling.md An example of a Vue file using the Composition API and its compilation output. ```vue ``` ```javascript // Chunk 1: id = /path/to/App.vue // Contains: ONLY imports and exports, no user code import _sfc_main from '/path/to/App.vue?vue&type=script&setup=true&lang.ts' export default _sfc_main; // Chunk 2: id = /path/to/App.vue?vue&type=style&index=0 // Contains: CSS (not instrumented) const _sfc_main = (await import('vue')).defineComponent({ __name: 'App', setup() { /* user code here */ } }) // Chunk 3: id = /path/to/App.vue?vue&type=script&setup=true&lang.ts // Contains: ALL USER CODE (this is what needs instrumentation) import { ref } from 'vue'; const count = ref(0); const increment = () => count.value++; ``` -------------------------------- ### Babel Generator Options Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Example of configuring Babel generator options within vite-plugin-istanbul. ```typescript import istanbul from 'vite-plugin-istanbul'; export default { plugins: [ istanbul({ generatorOpts: { compact: false, // Pretty-print output comments: true, // Preserve comments retainLines: true, // Keep original line numbers }, }), ], }; ``` -------------------------------- ### With Cypress Integration Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/istanbul-plugin.md Setup for vite-plugin-istanbul with Cypress integration. ```javascript // vite.config.js import istanbul from 'vite-plugin-istanbul'; export default { plugins: [ istanbul({ include: 'src/*', cypress: true, // Uses CYPRESS_COVERAGE env var }), ], }; ``` -------------------------------- ### Development Server Startup Data Flow Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md The data flow when the development server starts up. ```text Vite resolves config ↓ Plugin.apply() called ← Decides if plugin is active ↓ Plugin.config() hook ← Enable sourcemap if needed ↓ Plugin.configResolved() hook ← Check env vars, enable/disable ↓ Plugin.configureServer() hook ← Add /__coverage__ endpoint ↓ Dev server ready ``` -------------------------------- ### Force Build Instrumentation Configuration Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/errors.md JavaScript configuration example to enable instrumentation during build mode. ```javascript istanbul({ forceBuildInstrument: true, }) ``` -------------------------------- ### Global Coverage Object Access Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/endpoints.md Examples of accessing coverage data directly from the global scope. ```javascript // In browser console during dev console.log(window.__coverage__); // In Node.js test environment if (global.__coverage__) { const coverage = global.__coverage__; } ``` -------------------------------- ### Default Export Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Importing the main plugin factory function. ```typescript import istanbulPlugin from 'vite-plugin-istanbul'; // or import istanbul from 'vite-plugin-istanbul'; ``` -------------------------------- ### With Custom Instrumenter Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/istanbul-plugin.md Setup for vite-plugin-istanbul with a custom instrumenter. ```javascript // vite.config.js import istanbul from 'vite-plugin-istanbul'; import { createOxcInstrumenter } from 'oxc-coverage-instrument/vitest'; export default { plugins: [ istanbul({ include: 'src/*', exclude: ['node_modules', 'test/'], instrumenter: createOxcInstrumenter(), }), ], }; ``` -------------------------------- ### Fetching Coverage Data Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/istanbul-plugin.md Example of fetching coverage data from the /__coverage__ endpoint. ```javascript // In your test setup or after tests run async function getCoverage() { const response = await fetch('/__coverage__'); const coverage = await response.json(); return coverage; } ``` -------------------------------- ### Error Response Body Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/endpoints.md Example JSON response body for an error when coverage data cannot be serialized. ```json { "error": "Failed to serialize coverage data" } ``` -------------------------------- ### Invalid Pattern Syntax Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/errors.md JavaScript configuration examples demonstrating invalid glob syntax for include/exclude patterns. ```javascript istanbul({ include: 'src/{*.ts,*.js', exclude: '**/*.spec.{ts', }) ``` -------------------------------- ### Real-World Example: OXC Instrumenter Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/types.md Shows how to use the OXC instrumenter with vite-plugin-istanbul. ```typescript import istanbul from 'vite-plugin-istanbul'; import { createOxcInstrumenter } from 'oxc-coverage-instrument/vitest'; export default { plugins: [ istanbul({ include: 'src/*', instrumenter: createOxcInstrumenter(), }), ], }; ``` -------------------------------- ### Fetch Coverage Programmatically Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Asynchronously fetching coverage data from the API endpoint. ```javascript async function getCoverage() { const res = await fetch('/__coverage__'); return res.json(); } ``` -------------------------------- ### Coverage Data Endpoint Fetch Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/README.md Example of fetching coverage data from the /__coverage__ endpoint in code. ```javascript const response = await fetch('/__coverage__'); const coverage = await response.json(); console.log(coverage); ``` -------------------------------- ### Enable for One Command Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Enabling coverage for a single command execution using an environment variable. ```bash VITE_COVERAGE=true npm run dev ``` -------------------------------- ### Testing (CI/Strict) Configuration Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Configuration for CI environments, requiring an environment variable to enable coverage. ```javascript istanbul({ include: 'src/**', exclude: ['**/*.test.ts'], requireEnv: true, }) ``` -------------------------------- ### Example: Implementing a Custom Instrumenter Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/types.md Demonstrates how to implement a custom instrumenter by extending the CustomInstrumenter interface. ```typescript class MyCustomInstrumenter implements CustomInstrumenter { private lastSourceMapValue: RawSourceMap | null = null; fileCoverage: object = {}; instrumentSync( code: string, filename: string, inputSourceMap?: RawSourceMap ): string { // Perform instrumentation const instrumented = instrumentMyWay(code, filename); // Generate source map this.lastSourceMapValue = generateSourceMap(code, instrumented); // Populate coverage data this.fileCoverage = { /* coverage data */ }; return instrumented; } lastSourceMap(): RawSourceMap | null { return this.lastSourceMapValue; } } ``` -------------------------------- ### Troubleshooting "Sourcemaps" Warning Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Configuration fix for the "Sourcemaps" warning by setting the sourcemap option in vite.config.js. ```javascript // Fix by setting in vite.config.js export default { build: { sourcemap: true, // or 'inline' or 'hidden' }, plugins: [istanbul()], }; ``` -------------------------------- ### Vite Config with .nycrc Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Example vite.config.js when using a .nycrc file. ```javascript import istanbul from 'vite-plugin-istanbul'; export default { plugins: [ istanbul({ // Settings are loaded from .nycrc automatically // Can still override individual options here }), ], }; ``` -------------------------------- ### GeneratorOptions Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/types.md Illustrates how to configure Babel generator options for vite-plugin-istanbul. ```typescript import istanbul from 'vite-plugin-istanbul'; export default { plugins: [ istanbul({ include: 'src/*', generatorOpts: { compact: false, comments: true, retainLines: true, }, }), ], }; ``` -------------------------------- ### With Strict Environment Variable Requirement Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/istanbul-plugin.md Setup for vite-plugin-istanbul requiring a strict environment variable. ```javascript // vite.config.js import istanbul from 'vite-plugin-istanbul'; export default { plugins: [ istanbul({ include: 'src/*', exclude: ['node_modules', 'test/'], requireEnv: true, // Only run when VITE_COVERAGE=true }), ], }; ``` ```bash VITE_COVERAGE=true npm run dev ``` -------------------------------- ### Debug Instrumentation Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Using the onCover callback to log files being instrumented for debugging purposes. ```javascript istanbul({ // Check what's being instrumented onCover: (file, coverage) => { console.log(`✓ ${file}`); }, }) ``` -------------------------------- ### Cypress Configuration Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Configuration for use with Cypress, enabling coverage via a specific environment variable. ```javascript istanbul({ cypress: true, requireEnv: true, }) ``` -------------------------------- ### Forcing Build-Mode Instrumentation Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Example of forcing instrumentation during production builds by setting `forceBuildInstrument` to true and `checkProd` to false. ```javascript export default { plugins: [ istanbul({ include: 'src/*', forceBuildInstrument: true, // Enable in build mode checkProd: false, // Allow in production }), ], }; ``` -------------------------------- ### Troubleshooting Coverage Not Collected Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Commands to troubleshoot coverage collection issues, including checking environment variables, dev server status, file patterns, and plugin configuration. ```bash # 1. Check env var echo $VITE_COVERAGE # 2. Check dev server is running curl http://localhost:5173/__coverage__ # 3. Check files match patterns find src -name "*.ts" -type f | head -5 # 4. Check plugin is in vite.config.js cat vite.config.js | grep istanbul ``` -------------------------------- ### Custom Instrumenter (OXC) Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Example of using a custom instrumenter, specifically OXC, with vite-plugin-istanbul. ```javascript import istanbul from 'vite-plugin-istanbul'; import { createOxcInstrumenter } from 'oxc-coverage-instrument/vitest'; export default { plugins: [ istanbul({ include: 'src/**', instrumenter: createOxcInstrumenter(), generatorOpts: { compact: true, // OXC output is already compact }, }), ], }; ``` -------------------------------- ### Troubleshooting Files Not Instrumented Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Debugging patterns for files not being instrumented by adjusting include, exclude, and extension options. ```javascript // Debug patterns istanbul({ include: 'src/**', exclude: '**/*.test.ts', extension: ['.ts'], onCover: (f) => console.log(`✓ ${f}`), }) ``` -------------------------------- ### Implicit Re-exports (from dependencies) Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Importing types re-exported from dependencies, like @babel/generator. ```typescript import type { GeneratorOptions // from @babel/generator } from 'vite-plugin-istanbul'; ``` -------------------------------- ### Environment Variable Check Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/errors.md Bash commands to check and set the VITE_COVERAGE environment variable for enabling instrumentation. ```bash # Required behavior VITE_COVERAGE=true npm run dev # Check current value echo $VITE_COVERAGE ``` -------------------------------- ### Custom envPrefix in Vite config Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/errors.md Example of how to set a custom environment prefix in the Vite configuration file. ```javascript // vite.config.js export default { envPrefix: 'MY_APP_', // Custom prefix plugins: [istanbul()], }; ``` -------------------------------- ### Sourcemaps Warning Fix Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/errors.md Configuration example to fix the 'Sourcemaps was automatically enabled' warning by setting build.sourcemap. ```javascript // vite.config.js export default { build: { sourcemap: true, // or 'inline' or 'hidden' }, plugins: [istanbul()], }; ``` -------------------------------- ### Standard Mode Environment Variables Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Environment variables for enabling/disabling instrumentation in standard mode. ```bash VITE_COVERAGE=true # Enable instrumentation (default unless requireEnv: true) VITE_COVERAGE=false # Disable instrumentation ``` -------------------------------- ### Manual Testing - Fetch coverage via endpoint Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md Command to fetch coverage data from the __coverage__ endpoint. ```bash curl http://localhost:5173/__coverage__ | jq '.' ``` -------------------------------- ### Use custom fast instrumenter Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md Configuration to use a custom, faster instrumenter. ```javascript instrumenter: createOxcInstrumenter() ``` -------------------------------- ### Debugging Output Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/vue-sfc-handling.md Example console output when debugging instrumentation decisions for a Composition API Vue component. ```text /src/App.vue: SKIP /src/App.vue?vue&type=style&index=0: SKIP /src/App.vue?vue&type=script&setup=true&lang.ts: INSTRUMENT ``` -------------------------------- ### Troubleshooting: Some Files Not Instrumented Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Verifying exclude patterns and extension settings to ensure files are not unintentionally filtered. ```javascript istanbul({ include: 'src/**', exclude: ['**/*.test.ts'], // Excludes test files only extension: ['.ts'], // Only .ts files }) ``` -------------------------------- ### Coverage Data Response Body Example Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/endpoints.md Example JSON response body containing code coverage data in Istanbul format. ```json { "src/App.ts": { "path": "src/App.ts", "statementMap": { "0": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 20 } }, "1": { "start": { "line": 2, "column": 0 }, "end": { "line": 2, "column": 30 } } }, "fnMap": { "0": { "name": "getData", "decl": { "start": { "line": 5, "column": 0 }, "end": { "line": 5, "column": 20 } }, "loc": { "start": { "line": 5, "column": 0 }, "end": { "line": 8, "column": 1 } } } }, "branchMap": {}, "s": { "0": 1, "1": 2 }, "f": { "0": 1 }, "b": {} } } ``` -------------------------------- ### Build Commands Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/AGENTS.md Commands for performing standard builds, watch/dev builds, and prepublish builds. ```bash pnpm run build ``` ```bash pnpm run dev ``` ```bash pnpm run prepublishOnly ``` -------------------------------- ### Project Structure Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md The directory structure of the vite-plugin-istanbul project. ```bash vite-plugin-istanbul/ ├── src/ │ ├── index.ts # Main plugin implementation │ ├── types.d.ts # Type declarations for dependencies │ ├── source-map.ts # Source map utility functions │ ├── vue-sfc.ts # Vue SFC detection and handling │ └── ... ├── dist/ # Compiled output │ ├── index.mjs # ES module export │ └── index.d.mts # TypeScript declarations ├── package.json # Project metadata and dependencies ├── tsconfig.json # TypeScript configuration └── README.md ``` -------------------------------- ### Environment Variables: Default behavior Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/README.md Demonstrates how to enable and disable instrumentation using environment variables. ```bash # Instrumentation enabled by default, disable with: VITE_COVERAGE=false npm run dev # With requireEnv: true, must explicitly enable: VITE_COVERAGE=true npm run test ``` -------------------------------- ### Troubleshooting: Sourcemaps Warning Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Fixing the 'Sourcemaps was automatically enabled' warning by configuring build.sourcemap. ```javascript export default { build: { sourcemap: true, }, plugins: [istanbul({})], }; ``` -------------------------------- ### Troubleshooting: Coverage Not Collected (Include Patterns) Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Ensuring the 'include' pattern in the istanbul plugin configuration matches the files. ```javascript istanbul({ include: 'src/**', // Make sure this matches your files }) ``` -------------------------------- ### Check if Instrumented Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/quick-reference.md Checking if the global coverage object exists to determine if instrumentation is active. ```javascript const isInstrumented = !!global.__coverage__; console.log(`Instrumented files: ${Object.keys(global.__coverage__ || {}).length}`); ``` -------------------------------- ### Cypress Mode Environment Variables Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Environment variables for enabling/disabling instrumentation in Cypress mode. ```bash CYPRESS_COVERAGE=true # Enable instrumentation CYPRESS_COVERAGE=false # Disable instrumentation ``` -------------------------------- ### Strict Mode (Testing) Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/README.md Example of configuring the plugin for strict mode, typically used for testing. ```javascript istanbul({ include: 'src/**', requireEnv: true, // Must set VITE_COVERAGE=true }) Run: VITE_COVERAGE=true npm test ``` -------------------------------- ### Cypress Run Command Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/README.md Command to run Cypress tests with coverage enabled. ```bash CYPRESS_COVERAGE=true npx cypress run ``` -------------------------------- ### Two-Pass Instrumentation (Non-Vue Files) Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md Illustrates the two-pass instrumentation process for non-Vue files to ensure proper source map chaining. ```text Pass 1: Instrument with combined source map ↓ Get result source map ↓ Pass 2: Instrument again with identity map ↓ Get final source map ↓ Return result ``` -------------------------------- ### RequireEnv Environment Variable Usage Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/README.md Examples of correct and incorrect usage of the VITE_COVERAGE environment variable when requireEnv is true. ```bash VITE_COVERAGE=true npm run dev # ✓ Correct VITE_COVERAGE=false npm run dev # ✗ Disabled echo $VITE_COVERAGE # Check the value ``` -------------------------------- ### Manual Testing - Strict mode Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md Command to run tests in strict mode, requiring environment variables. ```bash VITE_COVERAGE=true npm run test # requireEnv: true ``` -------------------------------- ### Lint / Formatting Commands Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/AGENTS.md Commands for lint checking, lint autofixing, formatting the repository, and checking format. ```bash pnpm run lint ``` ```bash pnpm run lint:fix ``` ```bash pnpm run format ``` ```bash pnpm run format:check ``` -------------------------------- ### Plugin State Encapsulation Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md Example of how the plugin state is encapsulated within the plugin function scope using closure variables. ```typescript export default function istanbulPlugin(opts?) { const logger = createLogger(...); let testExclude: TestExclude; const instrumenter: CustomInstrumenter = ...; let enabled = true; return { name: PLUGIN_NAME, // ... hooks using closure variables ... }; } ``` -------------------------------- ### Debugging Source Maps - Logging Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/source-map-utilities.md Example code snippet to log the generated source map for debugging purposes. ```javascript const sourceMap = createIdentitySourceMap(file, source, opts); console.log(JSON.stringify(sourceMap, null, 2)); ``` -------------------------------- ### Module Graph Dependencies Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md The dependency graph of vite-plugin-istanbul, showing its relationship with other libraries. ```text istanbul-lib-instrument ↓ vite-plugin-istanbul ├── @istanbuljs/load-nyc-config (Load NYC config files) ├── test-exclude (Pattern matching for files) ├── espree (Tokenization for source maps) ├── source-map (Source map generation) ├── picocolors (Console output coloring) └── vite (Plugin interface & dev server) ``` -------------------------------- ### Middleware Pattern for Coverage Endpoint Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/architecture.md Example of integrating a coverage endpoint into Vite's dev server middleware chain using a `use` method. ```typescript middlewares.use((req, res, next) => { if (req.url !== COVERAGE_PUBLIC_PATH) { return next(); // Pass to next middleware } // Handle coverage request res.end(data); }); ``` -------------------------------- ### Importing the plugin Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/README.md Imports the IstanbulPlugin from the vite-plugin-istanbul package. ```javascript import IstanbulPlugin from 'vite-plugin-istanbul'; ``` -------------------------------- ### Integration with Main Plugin Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/api-reference/vue-sfc-handling.md Example of the `canInstrumentChunk` function being called in the main plugin's `transform()` hook to skip instrumentation. ```typescript // In src/index.ts, line 242 if (!canInstrumentChunk(id, srcCode)) { return; // Skip instrumentation for this chunk } ``` -------------------------------- ### Troubleshooting: Coverage Not Collected (Environment Variable) Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Checking if the VITE_COVERAGE environment variable is set correctly. ```bash echo $VITE_COVERAGE # Should print 'true' ``` -------------------------------- ### Cypress Integration Configuration Source: https://github.com/ifaxity/vite-plugin-istanbul/blob/next/_autodocs/configuration.md Configuration for integrating with Cypress, enabling the plugin via an environment variable. ```javascript import istanbul from 'vite-plugin-istanbul'; export default { plugins: [ istanbul({ include: 'src/**', exclude: ['node_modules/**'], cypress: true, // Uses CYPRESS_COVERAGE env var requireEnv: true, }), ], }; // In cypress.config.js: const { defineConfig } = require('cypress'); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { require('@cypress/code-coverage/task')(on, config); return config; }, }, }); ```