### Install api-diff-viewer using npm Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md This command installs the api-diff-viewer package from npm. It is a prerequisite for using the library in your project. ```sh npm install api-diff-viewer ``` -------------------------------- ### Integrating CodeMirror Extensions Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Provides an example of how to integrate custom CodeMirror extensions, such as search and highlighting functionalities, into the diff viewer. Note that `@codemirror/search` needs to be installed separately. ```typescript import { createDiffViewer } from 'api-diff-viewer' import { search, searchKeymap, highlightSelectionMatches } from '@codemirror/search' import { highlightActiveLine, keymap } from '@codemirror/view' const viewer = createDiffViewer(container, before, after, { extensions: [ search(), keymap.of(searchKeymap), highlightActiveLine(), highlightSelectionMatches(), ], }) // Ctrl+F / Cmd+F opens search in each panel ``` -------------------------------- ### Initialize API Diff Viewer with Vanilla JS Source: https://github.com/udamir/api-diff-viewer/blob/master/examples/vanilla/index.html Initializes the API Diff Viewer component using vanilla JavaScript. It takes a container element, 'before' and 'after' OpenAPI specifications, and an options object. The viewer displays differences between the two API specifications. Dependencies include the 'createDiffViewer' function and 'styles.css'. ```javascript import { createDiffViewer } from '../../src/index.ts' import '../../src/styles.css' // Sample OpenAPI specs const before = { openapi: '3.0.1', info: { title: 'Pet Store', version: '1.0.0', description: 'A sample pet store API' }, paths: { '/pets': { get: { summary: 'List all pets', operationId: 'listPets', parameters: [ { name: 'limit', in: 'query', required: false, schema: { type: 'integer', format: 'int32' } } ], responses: { '200': { description: 'A list of pets' }, '500': { description: 'Server error' } } }, post: { summary: 'Create a pet', operationId: 'createPet', responses: { '201': { description: 'Pet created' } } } }, '/pets/{petId}': { get: { summary: 'Get a pet by ID', operationId: 'getPet', parameters: [ { name: 'petId', in: 'path', required: true, schema: { type: 'string' } } ], responses: { '200': { description: 'A pet' }, '404': { description: 'Pet not found' } } } } } } const after = { openapi: '3.0.1', info: { title: 'Pet Store API', version: '2.0.0', description: 'An improved pet store API with enhanced features' }, paths: { '/pets': { get: { summary: 'List all pets', operationId: 'listPets', parameters: [ { name: 'limit', in: 'query', required: false, schema: { type: 'integer', format: 'int32' } }, { name: 'offset', in: 'query', required: false, schema: { type: 'integer', format: 'int32' } } ], responses: { '200': { description: 'A paginated list of pets' }, '500': { description: 'Internal server error' } } }, post: { summary: 'Create a new pet', operationId: 'createPet', requestBody: { required: true, content: { 'application/json': { schema: { type: 'object' } } } }, responses: { '201': { description: 'Pet created successfully' }, '400': { description: 'Invalid input' } } } }, '/pets/{petId}': { get: { summary: 'Get a pet by ID', operationId: 'getPet', parameters: [ { name: 'petId', in: 'path', required: true, schema: { type: 'integer' } } ], responses: { '200': { description: 'A pet' }, '404': { description: 'Pet not found' } } }, delete: { summary: 'Delete a pet', operationId: 'deletePet', parameters: [ { name: 'petId', in: 'path', required: true, schema: { type: 'integer' } } ], responses: { '204': { description: 'Pet deleted' }, '404': { description: 'Pet not found' } } } } } } const container = document.getElementById('diff-container') const statusEl = document.getElementById('status') const viewer = createDiffViewer(container, before, after, { format: 'yaml', mode: 'side-by-side', useWorker: false, wordDiffMode: 'word', }) viewer.on('ready', ({ summary }) => { statusEl.textContent = `Ready — ${summary.total} changes (${summary.breaking} breaking, ${summary.nonBreaking} non-breaking, ${summary.annotation} annotation)` }) viewer.on('error', ({ message }) => { statusEl.textContent = `Error: ${message}` }) ``` -------------------------------- ### Create a diff viewer instance with TypeScript Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md This TypeScript code snippet demonstrates how to create a diff viewer instance. It takes a container element, the 'before' and 'after' API specifications (as objects or strings), and optional configuration options. The example also shows how to listen for the 'ready' event and how to destroy the viewer when done. ```typescript import { createDiffViewer } from 'api-diff-viewer' const viewer = createDiffViewer( document.getElementById('diff')!, beforeSpec, // object or JSON/YAML string afterSpec, { format: 'yaml', mode: 'side-by-side' } ) viewer.on('ready', ({ summary }) => { console.log(`${summary.total} changes (${summary.breaking} breaking)`) }) // Cleanup when done viewer.destroy() ``` -------------------------------- ### Development Commands (Shell) Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Provides essential commands for developing the API Diff Viewer project using pnpm. These commands cover dependency installation, building the library, running Storybook for UI development, executing tests, and linting the codebase. ```shell pnpm install # Install dependencies pnpm run build # Type-check + build library pnpm run storybook # Run Storybook on port 6006 pnpm run test # Run tests pnpm run lint # Lint with Biome ``` -------------------------------- ### Control API Diff Viewer Toolbar Actions with Vanilla JS Source: https://github.com/udamir/api-diff-viewer/blob/master/examples/vanilla/index.html Handles user interactions with the toolbar buttons and select elements to control the API Diff Viewer's behavior. This includes toggling between side-by-side and inline modes, changing the display format (YAML/JSON), toggling dark mode, and destroying the viewer instance. These actions modify the viewer's state and appearance dynamically. ```javascript // Toolbar actions document.getElementById('toggle-mode').onclick = () => { viewer.setMode(viewer.getMode() === 'side-by-side' ? 'inline' : 'side-by-side') } document.getElementById('format-select').onchange = (e) => { viewer.setFormat(e.target.value) } document.getElementById('toggle-dark').onclick = () => { viewer.setTheme({ dark: !viewer.isDark() }) document.body.style.background = viewer.isDark() ? '#0d1117' : '#f6f8fa' document.body.style.color = viewer.isDark() ? '#c9d1d9' : '#1f2328' } document.getElementById('destroy-btn').onclick = () => { viewer.destroy() statusEl.textContent = 'Destroyed' } ``` -------------------------------- ### Filtering Changes by Classification Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Shows how to filter the displayed diff to only include specific change classifications, such as 'breaking' changes. This example also enables folding and classification display. ```typescript const viewer = createDiffViewer(container, before, after, { filters: ['breaking'], enableFolding: true, showClassification: true, }) ``` -------------------------------- ### Get Change Summary from DiffViewer Source: https://context7.com/udamir/api-diff-viewer/llms.txt Retrieves a summary of changes in a diff, categorized by type (total, breaking, non-breaking, annotation, unclassified). This method is available after the 'ready' event has fired. ```typescript import { createDiffViewer } from 'api-diff-viewer' const viewer = createDiffViewer(container, beforeSpec, afterSpec) viewer.on('ready', ({ summary }) => { // Same data available via method const changeSummary = viewer.getChangeSummary() console.log(`Total changes: ${changeSummary.total}`) console.log(`Breaking: ${changeSummary.breaking}`) console.log(`Non-breaking: ${changeSummary.nonBreaking}`) console.log(`Annotation: ${changeSummary.annotation}`) console.log(`Unclassified: ${changeSummary.unclassified}`) // Changes organized by path changeSummary.byPath.forEach((counts, path) => { counts.forEach(({ type, count }) => { console.log(`${path}: ${count} ${type} change(s)`) }) }) }) ``` -------------------------------- ### Basic Side-by-Side Diff Viewer Initialization Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Shows the most basic usage of the `createDiffViewer` function to initialize a side-by-side diff view. It requires a container element and two API specification objects (before and after). ```typescript import { createDiffViewer } from 'api-diff-viewer' const viewer = createDiffViewer( document.getElementById('diff')!, openApiV1, openApiV2, ) ``` -------------------------------- ### createDiffViewer - Basic Usage Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Initializes the diff viewer with a container element and two API specifications (e.g., OpenAPI v1 and v2). ```APIDOC ## POST /api/diff ### Description Initializes the diff viewer with a container element and two API specifications (e.g., OpenAPI v1 and v2). ### Method POST ### Endpoint /api/diff ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **container** (HTMLElement) - Required - The DOM element where the viewer will be rendered. - **before** (object) - Required - The first API specification object. - **after** (object) - Required - The second API specification object. - **options** (object) - Optional - Configuration options for the diff viewer. ### Request Example ```json { "container": "document.getElementById('diff')!", "before": "openApiV1", "after": "openApiV2" } ``` ### Response #### Success Response (200) - **viewer** (object) - An instance of the diff viewer. #### Response Example ```json { "viewer": "{...}" } ``` ``` -------------------------------- ### Create Diff Viewer with Merge Options Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Demonstrates how to create a diff viewer and pass custom options to the underlying api-smart-diff engine. This includes configuring custom comparison rules, annotation hooks, and external sources for resolving references. ```typescript createDiffViewer(container, before, after, { mergeOptions: { // Custom comparison rules rules: { ... }, // Custom annotation hook annotateHook: (before, after, ctx) => { ... }, // Resolved external $ref sources externalSources: { before: { 'common.yaml': { ... } }, after: { 'common.yaml': { ... } }, }, }, }) ``` -------------------------------- ### Create API Diff Viewer Instance Source: https://context7.com/udamir/api-diff-viewer/llms.txt Initializes and renders the API Diff Viewer component within a specified DOM container. It accepts API specifications as objects or strings (JSON/YAML) and configures various display options. The viewer emits lifecycle events for loading, readiness, and errors. ```typescript import { createDiffViewer } from 'api-diff-viewer' // OpenAPI spec versions to compare const openApiV1 = { openapi: '3.0.0', info: { title: 'Pet Store API', version: '1.0.0' }, paths: { '/pets': { get: { summary: 'List all pets', parameters: [ { name: 'limit', in: 'query', schema: { type: 'integer' } } ], responses: { '200': { description: 'A list of pets' } } } } } } const openApiV2 = { openapi: '3.0.0', info: { title: 'Pet Store API', version: '2.0.0' }, paths: { '/pets': { get: { summary: 'List all pets with pagination', parameters: [ { name: 'limit', in: 'query', required: true, schema: { type: 'integer' } }, { name: 'offset', in: 'query', schema: { type: 'integer' } } ], responses: { '200': { description: 'A paginated list of pets' } } } } } } // Create the diff viewer const viewer = createDiffViewer( document.getElementById('diff-container'), openApiV1, openApiV2, { mode: 'side-by-side', // or 'inline' format: 'yaml', // or 'json' dark: false, enableFolding: true, showClassification: true, wordDiffMode: 'word', // 'word', 'char', or 'none' wordWrap: true, useWorker: true // non-blocking merge computation } ) // Handle lifecycle events viewer.on('loading', () => { console.log('Computing diff...') }) viewer.on('ready', ({ summary }) => { console.log(`Total changes: ${summary.total}`) console.log(`Breaking: ${summary.breaking}`) console.log(`Non-breaking: ${summary.nonBreaking}`) console.log(`Annotation: ${summary.annotation}`) console.log(`Unclassified: ${summary.unclassified}`) }) viewer.on('error', ({ message, cause }) => { console.error('Diff computation failed:', message) }) // Cleanup when done viewer.destroy() ``` -------------------------------- ### Customizing Colors and Theme Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Demonstrates how to enable dark mode and customize the colors used for 'breaking' and 'non-breaking' changes in the diff viewer. ```typescript const viewer = createDiffViewer(container, before, after, { dark: true, colors: { breakingColor: '#ff6b6b', nonBreakingColor: '#51cf66', }, }) ``` -------------------------------- ### Update API Diff Viewer Specifications (TypeScript) Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Shows how to initialize the API Diff Viewer with initial specifications and subsequently update them with new versions using TypeScript. This is useful for comparing different states of an API specification over time. ```typescript const viewer = createDiffViewer(container, specV1, specV2) // Later, compare different versions viewer.update(specV2, specV3) ``` -------------------------------- ### Inline Mode Diff Viewer Configuration Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Illustrates how to configure the diff viewer to operate in 'inline' mode. Additional options like enabling folding and showing change classifications are also demonstrated. ```typescript const viewer = createDiffViewer(container, before, after, { mode: 'inline', enableFolding: true, showClassification: true, }) ``` -------------------------------- ### Diff Engine Options - mergeOptions Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Allows passing options directly to the underlying api-smart-diff engine for custom comparison rules and external source resolution. ```APIDOC ## POST /api/diff/merge-options ### Description Allows passing options directly to the underlying api-smart-diff engine for custom comparison rules and external source resolution. ### Method POST ### Endpoint /api/diff/merge-options ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **container** (HTMLElement) - Required - The DOM element where the viewer will be rendered. - **before** (object) - Required - The first API specification object. - **after** (object) - Required - The second API specification object. - **options** (object) - Optional - Configuration options for the diff viewer. - **mergeOptions** (object) - Optional - Options passed to `api-smart-diff`. - **rules** (CompareRules) - Optional - Custom comparison rules. - **annotateHook** (AnnotateHook) - Optional - Custom hook for change annotations. - **externalSources** (object) - Optional - Resolved external `$ref` sources. - **before** (Record) - Optional - External sources for the 'before' spec. - **after** (Record) - Optional - External sources for the 'after' spec. ### Request Example ```json { "container": "container", "before": "before", "after": "after", "options": { "mergeOptions": { "rules": {" ... "}, "annotateHook": "(before, after, ctx) => { ... }", "externalSources": { "before": {"common.yaml": {" ... "}}, "after": {"common.yaml": {" ... "}} } } } } ``` ### Response #### Success Response (200) - **viewer** (object) - An instance of the diff viewer. #### Response Example ```json { "viewer": "{...}" } ``` ``` -------------------------------- ### Control API Diff Viewer Runtime Options (TypeScript) Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Demonstrates how to control the API Diff Viewer's display mode (side-by-side vs. inline), format (yaml vs. json), and theme (dark mode) using TypeScript. This requires the `createDiffViewer` function and assumes the viewer instance is already created. ```typescript const viewer = createDiffViewer(container, before, after) // Toggle mode document.getElementById('toggle-mode')!.onclick = () => { viewer.setMode(viewer.getMode() === 'side-by-side' ? 'inline' : 'side-by-side') } // Toggle format document.getElementById('toggle-format')!.onclick = () => { viewer.setFormat(viewer.getFormat() === 'yaml' ? 'json' : 'yaml') } // Toggle dark mode document.getElementById('toggle-dark')!.onclick = () => { viewer.setTheme({ dark: !viewer.isDark() }) } ``` -------------------------------- ### Create and Use CodeMirror Diff Theme Source: https://context7.com/udamir/api-diff-viewer/llms.txt Generates a CodeMirror theme extension for diff-specific styling, allowing for optional color overrides. It can be used in custom editor configurations or managed at runtime for theme switching. ```typescript import { diffTheme, lightColors, darkColors, DiffThemeManager } from 'api-diff-viewer' import { EditorView } from '@codemirror/view' import { EditorState } from '@codemirror/state' // Create theme extension const theme = diffTheme({ dark: true, colors: { breakingColor: '#ff6b6b', nonBreakingColor: '#51cf66', addedBg: 'rgba(46, 160, 67, 0.25)' } }) // Use in custom editor const editor = new EditorView({ parent: document.getElementById('editor'), state: EditorState.create({ doc: 'content here', extensions: [theme] }) }) // Use DiffThemeManager for runtime switching const themeManager = new DiffThemeManager() const view = new EditorView({ parent: container, state: EditorState.create({ extensions: themeManager.getExtensions(undefined, {}, false) }) }) // Switch to dark mode at runtime themeManager.setDiffTheme(view, { dark: true }) // Access default color palettes console.log('Light colors:', lightColors) console.log('Dark colors:', darkColors) ``` -------------------------------- ### createDiffViewer - CodeMirror Extensions Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Integrates custom CodeMirror extensions, such as search and highlighting, into the diff viewer. ```APIDOC ## POST /api/diff/codemirror ### Description Integrates custom CodeMirror extensions, such as search and highlighting, into the diff viewer. ### Method POST ### Endpoint /api/diff/codemirror ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **container** (HTMLElement) - Required - The DOM element where the viewer will be rendered. - **before** (object) - Required - The first API specification object. - **after** (object) - Required - The second API specification object. - **options** (object) - Optional - Configuration options for the diff viewer. - **extensions** (array) - Optional - An array of CodeMirror extensions to apply. ### Request Example ```json { "container": "container", "before": "before", "after": "after", "options": { "extensions": [ "search()", "keymap.of(searchKeymap)", "highlightActiveLine()", "highlightSelectionMatches()" ] } } ``` ### Response #### Success Response (200) - **viewer** (object) - An instance of the diff viewer. #### Response Example ```json { "viewer": "{...}" } ``` ``` -------------------------------- ### Handle Viewer Events Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Event listeners for various viewer states, including loading, readiness, errors, and changes in mode, format, theme, and word wrap. These events allow for dynamic updates and responses to viewer actions. ```typescript viewer.on('loading', () => { /* merge started */ }) viewer.on('ready', ({ summary }) => { console.log(`${summary.total} changes`) console.log(`${summary.breaking} breaking`) console.log(`${summary.nonBreaking} non-breaking`) console.log(`${summary.annotation} annotation`) console.log(`${summary.unclassified} unclassified`) }) viewer.on('error', ({ message, cause }) => { console.error('Merge failed:', message) }) viewer.on('modeChange', ({ mode }) => { /* 'side-by-side' | 'inline' */ }) viewer.on('formatChange', ({ format }) => { /* 'json' | 'yaml' */ }) viewer.on('themeChange', ({ dark }) => { /* boolean */ }) viewer.on('wordWrapChange', ({ wordWrap }) => { /* boolean */ }) ``` -------------------------------- ### Control Viewer Display and Format Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Methods to control the viewer's display mode, format, filters, theme, and word diff settings. These functions allow users to customize the visual presentation and filtering of differences. ```typescript viewer.setMode('inline') // Switch between 'side-by-side' and 'inline' viewer.getMode() // Returns current mode viewer.setFormat('json') // Switch between 'json' and 'yaml' viewer.getFormat() // Returns current format viewer.setFilters(['breaking']) // Filter visible changes by classification viewer.getFilters() // Returns active filters viewer.setTheme({ dark: true }) // Toggle dark mode viewer.setTheme({ colors: { ... }}) // Override diff colors viewer.isDark() // Returns dark mode state viewer.setWordDiffMode('char') // Change word diff granularity viewer.setWordWrap(false) // Disable word wrap (enables synced horizontal scroll) viewer.getWordWrap() // Returns word wrap state viewer.setFoldingEnabled(true) // Toggle code folding viewer.setClassificationEnabled(true) // Toggle classification indicators ``` -------------------------------- ### Programmatic Navigation Through Diff Changes Source: https://context7.com/udamir/api-diff-viewer/llms.txt Provides methods for programmatic navigation through changes in the diff viewer. This includes iterating through changes, jumping to specific paths, searching content, and inspecting the document tree structure. It's useful for building custom diff navigation UIs or automated analysis. ```typescript import { createDiffViewer } from 'api-diff-viewer' const viewer = createDiffViewer(container, beforeSpec, afterSpec) viewer.on('ready', () => { const nav = viewer.navigation // Navigate to next/previous change document.getElementById('next-btn').addEventListener('click', () => { const path = nav.goToNextChange() console.log(`Navigated to: ${path}`) }) document.getElementById('prev-btn').addEventListener('click', () => { const path = nav.goToPrevChange() console.log(`Navigated to: ${path}`) }) // Navigate to next breaking change only const breakingPath = nav.goToNextChange('breaking') // Navigate to any breaking or annotation change const changePath = nav.goToNextChange('breaking', 'annotation') // Jump to specific path nav.goToPath('paths./pets.get.parameters', { behavior: 'smooth', align: 'center', highlight: true }) // Search for paths containing text const results = nav.findPaths('pet', { caseSensitive: false, searchIn: 'both', // 'keys', 'values', or 'both' limit: 10 }) results.forEach(r => { console.log(`Found "${r.matchedText}" at ${r.path} (${r.matchLocation})`) }) // Get child keys at a path const children = nav.getChildKeys('paths./pets') children.forEach(child => { console.log(`${child.key}: hasChange=${child.hasDirectChange}, diffType=${child.diffType}`) }) // Get change summary const summary = nav.getChangeSummary() console.log(`Total: ${summary.total}, Breaking: ${summary.breaking}`) // Subscribe to navigation events const unsubscribe = nav.onNavigate((path) => { console.log(`Current path: ${path}`) }) // Later: unsubscribe() }) ``` -------------------------------- ### Configure DiffViewer with Merge Options Source: https://context7.com/udamir/api-diff-viewer/llms.txt Configures the DiffViewer with custom merge options for the underlying api-smart-diff engine. Supports custom comparison rules, annotation hooks, and external $ref source resolution. ```typescript import { createDiffViewer } from 'api-diff-viewer' const viewer = createDiffViewer(container, beforeSpec, afterSpec, { mergeOptions: { // Custom comparison rules for specific paths rules: { '/info/version': { breaking: true } }, // Custom annotation hook for change classification annotateHook: (before, after, ctx) => { // Return custom diff type based on context if (ctx.path.includes('x-internal')) { return 'annotation' } return undefined // use default classification }, // Resolved external $ref sources for both specs externalSources: { before: { 'common.yaml': { components: { schemas: { Error: { type: 'object', properties: { message: { type: 'string' } } } } } } }, after: { 'common.yaml': { components: { schemas: { Error: { type: 'object', properties: { message: { type: 'string' }, code: { type: 'integer' } } } } } } } } } }) ``` -------------------------------- ### createDiffViewer - Inline Mode with Folding Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Configures the diff viewer to use inline mode with collapsible sections for better readability. ```APIDOC ## POST /api/diff/inline ### Description Configures the diff viewer to use inline mode with collapsible sections for better readability. ### Method POST ### Endpoint /api/diff/inline ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **container** (HTMLElement) - Required - The DOM element where the viewer will be rendered. - **before** (object) - Required - The first API specification object. - **after** (object) - Required - The second API specification object. - **options** (object) - Optional - Configuration options for the diff viewer. - **mode** (string) - Optional - Set to 'inline' for inline diff view. - **enableFolding** (boolean) - Optional - Enables collapsible sections. - **showClassification** (boolean) - Optional - Displays change classification. ### Request Example ```json { "container": "container", "before": "before", "after": "after", "options": { "mode": "inline", "enableFolding": true, "showClassification": true } } ``` ### Response #### Success Response (200) - **viewer** (object) - An instance of the diff viewer. #### Response Example ```json { "viewer": "{...}" } ``` ``` -------------------------------- ### Configure Visual Theme for DiffViewer Source: https://context7.com/udamir/api-diff-viewer/llms.txt Configures the visual theme including dark mode toggle and custom diff colors. Colors are applied via CSS variables allowing fine-grained control over the diff highlighting appearance. This method allows customization of the viewer's look and feel. ```typescript import { createDiffViewer } from 'api-diff-viewer' const viewer = createDiffViewer(container, beforeSpec, afterSpec) // Enable dark mode viewer.setTheme({ dark: true }) // Customize diff colors viewer.setTheme({ dark: true, colors: { addedBg: 'rgba(46, 160, 67, 0.2)', removedBg: 'rgba(248, 81, 73, 0.2)', modifiedBg: 'rgba(227, 179, 65, 0.2)', breakingColor: '#f85149', nonBreakingColor: '#3fb950', annotationColor: '#a371f7', unclassifiedColor: '#768390', addedTextBg: 'rgba(46, 160, 67, 0.5)', removedTextBg: 'rgba(248, 81, 73, 0.5)', spacerBg: '#161b22', spacerStripe: '#30363d' } }) // Check dark mode state console.log(`Dark mode: ${viewer.isDark()}`) // Listen for theme changes viewer.on('themeChange', ({ dark }) => { document.body.classList.toggle('dark-theme', dark) }) ``` -------------------------------- ### Access Advanced Editor Views and Cleanup Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Provides access to the underlying CodeMirror editor instances for both side-by-side and inline modes, allows retrieval of change summaries without navigation, and includes a method for destroying the viewer instance. ```typescript // Access underlying CodeMirror editors const { before, after } = viewer.getEditorViews() // side-by-side const { unified } = viewer.getEditorViews() // inline // Get change summary without navigation viewer.getChangeSummary() // Cleanup viewer.destroy() ``` -------------------------------- ### diffTheme - CodeMirror Theme Extension Source: https://context7.com/udamir/api-diff-viewer/llms.txt Creates a CodeMirror theme extension for diff-specific styling. It allows for optional color overrides and can be used in custom editor configurations or with DiffThemeManager for runtime switching. ```APIDOC ## diffTheme ### Description Creates a CodeMirror theme extension with diff-specific styling and optional color overrides. Used internally by DiffViewer but can be applied to custom editor configurations. ### Method `diffTheme(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `options` (object) - Configuration options for the theme. - `dark` (boolean) - Whether to use dark theme colors. Defaults to `false`. - `colors` (object) - Optional overrides for default colors. - `breakingColor` (string) - Color for breaking changes. - `nonBreakingColor` (string) - Color for non-breaking changes. - `addedBg` (string) - Background color for added elements. ### Request Example ```javascript import { diffTheme, lightColors, darkColors, DiffThemeManager } from 'api-diff-viewer' import { EditorView } from '@codemirror/view' import { EditorState } from '@codemirror/state' // Create theme extension const theme = diffTheme({ dark: true, colors: { breakingColor: '#ff6b6b', nonBreakingColor: '#51cf66', addedBg: 'rgba(46, 160, 67, 0.25)' } }) // Use in custom editor const editor = new EditorView({ parent: document.getElementById('editor'), state: EditorState.create({ doc: 'content here', extensions: [theme] }) }) // Use DiffThemeManager for runtime switching const themeManager = new DiffThemeManager() const view = new EditorView({ parent: container, state: EditorState.create({ extensions: themeManager.getExtensions(undefined, {}, false) }) }) // Switch to dark mode at runtime themeManager.setDiffTheme(view, { dark: true }) // Access default color palettes console.log('Light colors:', lightColors) console.log('Dark colors:', darkColors) ``` ### Response Returns a CodeMirror extension. #### Success Response (200) CodeMirror extension object. #### Response Example (CodeMirror extension object) ``` -------------------------------- ### Path Utilities Source: https://context7.com/udamir/api-diff-viewer/llms.txt A collection of utility functions for navigating and manipulating document paths within the diff tree. These utilities help in identifying and accessing specific nodes in the merged document structure. ```APIDOC ## Path Utilities ### Description Utility functions for working with document paths in the diff tree. Paths are JSON Pointer-like strings or arrays of segments used to identify nodes in the merged document. ### Methods - `formatPath(pathArray)`: Formats an array path into a string. - `parsePath(pathString)`: Parses a string path into an array. - `resolvePathToBlock(path, blocks)`: Resolves a path to a specific block within the diff data. - `getAncestorBlockIds(path, blocks)`: Retrieves the IDs of all ancestor blocks for a given path. - `encodeSegment(segment)`: Encodes a path segment to handle special characters. - `decodeSegment(encodedSegment)`: Decodes an encoded path segment. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `pathArray` (array) - An array representing a document path. - `pathString` (string) - A string representation of a document path. - `path` (string) - The path to resolve. - `blocks` (object) - The diff data blocks. - `segment` (string) - A path segment to encode. - `encodedSegment` (string) - An encoded path segment to decode. ### Request Example ```javascript import { formatPath, parsePath, resolvePathToBlock, getAncestorBlockIds, encodeSegment, decodeSegment } from 'api-diff-viewer' // Format array path to string const pathString = formatPath(['paths', '/pets', 'get', 'parameters', '0']) console.log(pathString) // 'paths./pets.get.parameters.0' // Parse string path to array const pathArray = parsePath('paths./pets.get.parameters.0') console.log(pathArray) // ['paths', '/pets', 'get', 'parameters', '0'] // Encode/decode special characters in segments const encoded = encodeSegment('paths/pets') // handles slashes const decoded = decodeSegment(encoded) // Resolve path to block in diff data const block = resolvePathToBlock('paths./pets.get', diffData.blocks) if (block) { console.log('Found block:', block.id) console.log('Has diff:', !!block.diff) } // Get ancestor block IDs (for expanding collapsed parents) const ancestors = getAncestorBlockIds('paths./pets.get.parameters.0', diffData.blocks) console.log('Ancestors:', ancestors) // ['paths', 'paths./pets', 'paths./pets.get', ...] ``` ### Response Returns the result of the respective path utility operation. #### Success Response (200) - `formatPath`: string - `parsePath`: array - `resolvePathToBlock`: object (block data) or null - `getAncestorBlockIds`: array - `encodeSegment`: string - `decodeSegment`: string #### Response Example (Varies based on the utility function called. See Request Example for specific outputs.) ``` -------------------------------- ### createDiffViewer - Dark Mode with Custom Colors Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Applies dark mode and custom color schemes for breaking and non-breaking changes. ```APIDOC ## POST /api/diff/dark-mode ### Description Applies dark mode and custom color schemes for breaking and non-breaking changes. ### Method POST ### Endpoint /api/diff/dark-mode ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **container** (HTMLElement) - Required - The DOM element where the viewer will be rendered. - **before** (object) - Required - The first API specification object. - **after** (object) - Required - The second API specification object. - **options** (object) - Optional - Configuration options for the diff viewer. - **dark** (boolean) - Optional - Enables dark mode. - **colors** (object) - Optional - Custom color definitions. - **breakingColor** (string) - Optional - Color for breaking changes. - **nonBreakingColor** (string) - Optional - Color for non-breaking changes. ### Request Example ```json { "container": "container", "before": "before", "after": "after", "options": { "dark": true, "colors": { "breakingColor": "#ff6b6b", "nonBreakingColor": "#51cf66" } } } ``` ### Response #### Success Response (200) - **viewer** (object) - An instance of the diff viewer. #### Response Example ```json { "viewer": "{...}" } ``` ``` -------------------------------- ### DiffViewer.expandAll / collapseAll Source: https://context7.com/udamir/api-diff-viewer/llms.txt Controls the fold state of all collapsible blocks in the diff view. Useful for providing "Expand All" / "Collapse All" toolbar buttons in the UI. ```APIDOC ## DiffViewer.expandAll / collapseAll ### Description Controls the fold state of all collapsible blocks in the diff view. Useful for providing "Expand All" / "Collapse All" toolbar buttons in the UI. ### Method `expandAll()` `collapseAll()` ### Parameters None ### Request Example ```javascript // Expand all folded sections viewer.expandAll() // Collapse all sections to top-level viewer.collapseAll() ``` ### Response #### Success Response (200) These methods do not return a value. #### Response Example None ``` -------------------------------- ### DiffViewer.update Source: https://context7.com/udamir/api-diff-viewer/llms.txt Replaces the before and after specifications and re-computes the diff. Useful for implementing live editing scenarios or comparing different version pairs without recreating the viewer instance. ```APIDOC ## DiffViewer.update ### Description Replaces the before and after specifications and re-computes the diff. Useful for implementing live editing scenarios or comparing different version pairs without recreating the viewer instance. ### Method `update` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **beforeSpec** (object | string) - Required - The initial specification (e.g., OpenAPI document) or a string representation. - **afterSpec** (object | string) - Required - The updated specification (e.g., OpenAPI document) or a string representation. ### Request Example ```javascript // Compare different versions viewer.update(specVersions[version].before, specVersions[version].after) // Also accepts YAML/JSON strings const yamlBefore = ` openapi: "3.0.0" info: title: My API version: "1.0" ` const yamlAfter = ` openapi: "3.0.0" info: title: My API version: "2.0" ` viewer.update(yamlBefore, yamlAfter) ``` ### Response #### Success Response (200) This method does not return a value. #### Response Example None ``` -------------------------------- ### Control Folding and Toggling Paths Source: https://github.com/udamir/api-diff-viewer/blob/master/README.md Functions to manage the folding state of diff blocks and toggle specific paths within the diff view. This allows for granular control over what parts of the diff are visible. ```typescript viewer.expandAll() // Expand all folded blocks viewer.collapseAll() // Collapse all foldable blocks viewer.togglePath('info') // Toggle a specific path viewer.togglePath(['paths', '/pets', 'get']) // Array form also works ``` -------------------------------- ### DiffViewer.togglePath Source: https://context7.com/udamir/api-diff-viewer/llms.txt Toggles the fold state of a specific path in the document tree. Accepts either a string path (e.g., "paths./pets.get") or an array of path segments. ```APIDOC ## DiffViewer.togglePath ### Description Toggles the fold state of a specific path in the document tree. Accepts either a string path (e.g., "paths./pets.get") or an array of path segments. ### Method `togglePath` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **path** (string | string[]) - Required - The path to toggle. Can be a dot-separated string or an array of path segments. ### Request Example ```javascript // Toggle using string path viewer.togglePath('paths./pets.get') // Toggle using array path viewer.togglePath(['paths', '/pets', 'get', 'parameters']) // Toggle info section viewer.togglePath('info') ``` ### Response #### Success Response (200) This method does not return a value. #### Response Example None ``` -------------------------------- ### Build Diff Block Data Structures Source: https://context7.com/udamir/api-diff-viewer/llms.txt Provides a low-level API to construct diff block data structures from a merged document, suitable for custom diff rendering. It takes merged API specifications and formats them into a hierarchical block structure. ```typescript import { buildDiffBlock } from 'api-diff-viewer' import { apiMerge } from 'api-smart-diff' const before = { info: { title: 'API v1' } } const after = { info: { title: 'API v2' } } // Merge specs using api-smart-diff const merged = apiMerge(before, after, { metaKey: '$diff', arrayMeta: true }) // Build diff blocks for YAML format const diffBlock = buildDiffBlock(merged, 'yaml', { skipWordDiff: false // set true for large documents }) // Inspect block structure console.log('Block ID:', diffBlock.id) console.log('Children:', diffBlock.children.length) console.log('Diff counts [breaking, non-breaking, annotation, unclassified]:', diffBlock.diffs) // Iterate through children diffBlock.children.forEach(child => { if (child.diff) { console.log(`${child.id}: ${child.diff.action} (${child.diff.type})`) } }) ``` -------------------------------- ### DiffViewer.setTheme Source: https://context7.com/udamir/api-diff-viewer/llms.txt Configures the visual theme including dark mode toggle and custom diff colors. Colors are applied via CSS variables allowing fine-grained control over the diff highlighting appearance. ```APIDOC ## DiffViewer.setTheme ### Description Configures the visual theme including dark mode toggle and custom diff colors. Colors are applied via CSS variables allowing fine-grained control over the diff highlighting appearance. ### Method `setTheme` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **themeOptions** (object) - Required - An object containing theme configuration. - **dark** (boolean) - Optional - Enables or disables dark mode. - **colors** (object) - Optional - An object to customize diff highlighting colors. - **addedBg** (string) - Background color for added sections. - **removedBg** (string) - Background color for removed sections. - **modifiedBg** (string) - Background color for modified sections. - **breakingColor** (string) - Color for breaking changes. - **nonBreakingColor** (string) - Color for non-breaking changes. - **annotationColor** (string) - Color for annotation changes. - **unclassifiedColor** (string) - Color for unclassified changes. - **addedTextBg** (string) - Background color for added text. - **removedTextBg** (string) - Background color for removed text. - **spacerBg** (string) - Background color for spacer elements. - **spacerStripe** (string) - Color for spacer stripes. ### Request Example ```javascript // Enable dark mode viewer.setTheme({ dark: true }) // Customize diff colors viewer.setTheme({ dark: true, colors: { addedBg: 'rgba(46, 160, 67, 0.2)', removedBg: 'rgba(248, 81, 73, 0.2)', modifiedBg: 'rgba(227, 179, 65, 0.2)', breakingColor: '#f85149', nonBreakingColor: '#3fb950', annotationColor: '#a371f7', unclassifiedColor: '#768390', addedTextBg: 'rgba(46, 160, 67, 0.5)', removedTextBg: 'rgba(248, 81, 73, 0.5)', spacerBg: '#161b22', spacerStripe: '#30363d' } }) ``` ### Response #### Success Response (200) This method does not return a value. #### Response Example None ``` -------------------------------- ### Change Diff Viewer Output Format Source: https://context7.com/udamir/api-diff-viewer/llms.txt Enables switching the output serialization format of the diff content between YAML and JSON. This action re-renders the viewer's display while retaining the previously computed diff data. It's useful for adapting to user preferences or downstream processing needs. ```typescript import { createDiffViewer } from 'api-diff-viewer' const viewer = createDiffViewer(container, beforeSpec, afterSpec, { format: 'yaml' }) // Switch to JSON format viewer.setFormat('json') console.log(`Current format: ${viewer.getFormat()}`) // 'json' // Listen for format changes viewer.on('formatChange', ({ format }) => { document.getElementById('format-label').textContent = format.toUpperCase() }) ```