API Overview
Visual Diff Merge provides several API endpoints for processing diffs and handling various tasks.
These endpoints are PHP scripts in the api/
directory, and they handle operations like:
- Processing differences between content
- Retrieving file content securely
- Fetching content from URLs
- Performing merge operations
- Providing configuration information
For details on the underlying architecture of these API endpoints, see the System Components section of the Architecture documentation.
Base URL
API endpoints are normally accessed relative to the Visual Diff Merge installation. For example:
https://your-server.com/visual-diff-merge/api/diff-processor.php
Authentication
By default, Visual Diff Merge endpoints do not require authentication. For production environments, you should implement your own authentication layer if needed.
Endpoints
diff-processor.php
The main endpoint for processing diff operations. It accepts content from various sources and returns structured diff data.
Request
- Method: POST
- Content-Type: application/json
Request Body
{
"old": {
"type": "file|url|text",
"content": "Content if type is text",
"url": "URL if type is url",
"server_path": "Server path if type is file",
"filename": "Optional filename"
},
"new": {
"type": "file|url|text",
"content": "Content if type is text",
"url": "URL if type is url",
"server_path": "Server path if type is file",
"filename": "Optional filename"
},
"filepath": "Optional filepath for language detection",
"debug": true|false,
"translations": { /* Optional translations */ }
}
Response
{
"success": true,
"config": {
"diffData": {
"old": [ /* Array of line objects for old content */ ],
"new": [ /* Array of line objects for new content */ ],
"chunks": [ /* Array of chunk objects describing differences */ ]
},
"serverSaveEnabled": true|false,
"fileRefId": "Reference ID for new file if applicable",
"oldFileRefId": "Reference ID for old file if applicable",
"newFileName": "New file name",
"oldFileName": "Old file name",
"filepath": "Filepath",
"translations": { /* Translations object */ },
/* Other configuration properties */
}
}
If the content is identical, the response will indicate this:
{
"success": true,
"identical": true,
"message": "The files are identical.",
"config": {
"translations": { /* Translations object */ }
}
}
Error Response
{
"error": "Error message",
"success": false
}
Example Usage
// Example JavaScript fetch
fetch('api/diff-processor.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
old: {
type: 'text',
content: 'function hello() {\n console.log("Hello");\n}',
filename: 'old.js'
},
new: {
type: 'text',
content: 'function hello() {\n console.log("Hello World");\n}',
filename: 'new.js'
},
filepath: 'example.js'
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Process diff data
console.log(data.config.diffData);
} else {
console.error(data.error);
}
});
ajax-diff-merge.php
Handles merge operations, allowing users to save the merged content.
Request
- Method: POST
- Content-Type: application/json
Request Body
{
"mergedContent": "The merged content as text",
"fileRefId": "Reference ID for the file to save",
"oldFileRefId": "Reference ID for the old file",
"newFileName": "New file name",
"oldFileName": "Old file name",
"saveMode": "original|new-suffix|old|old-suffix|both|both-suffix"
}
Response
{
"success": true,
"message": "Success message",
"files": [
{
"path": "Saved file path",
"filename": "Saved file name"
}
]
}
Error Response
{
"error": "Error message",
"success": false
}
get-file-content.php
Securely retrieves file content based on a path or reference ID.
Request
- Method: GET
- Parameters:
path
- Path to the file (if no refId)refId
- Reference ID for the file (preferred for security)
Response
{
"success": true,
"content": "File content",
"filename": "File name",
"language": "Detected language"
}
Error Response
{
"success": false,
"error": "Error message"
}
Example Usage
// Example JavaScript fetch
fetch('api/get-file-content.php?refId=abcdef123456')
.then(response => response.json())
.then(data => {
if (data.success) {
console.log(data.content);
} else {
console.error(data.error);
}
});
get-url-content.php
Fetches content from external URLs, helping to overcome CORS limitations.
Request
- Method: GET
- Parameters:
url
- URL to fetch content from
Response
{
"success": true,
"content": "Content from URL",
"url": "Original URL"
}
Error Response
{
"success": false,
"error": "Error message"
}
Example Usage
// Example JavaScript fetch
fetch('api/get-url-content.php?url=' + encodeURIComponent('https://example.com/file.js'))
.then(response => response.json())
.then(data => {
if (data.success) {
console.log(data.content);
} else {
console.error(data.error);
}
});
endpoints-config.php
Provides information about API endpoints to the JavaScript client.
Request
- Method: GET
- Parameters:
absolute
- Set to "1" to get absolute URLs
Response
{
"diffProcessor": "path/to/diff-processor.php",
"ajaxDiffMerge": "path/to/ajax-diff-merge.php",
"endpoints": "path/to/endpoints-config.php"
}
Example Usage
// Example JavaScript fetch
fetch('api/endpoints-config.php?absolute=1')
.then(response => response.json())
.then(endpoints => {
console.log(endpoints.diffProcessor); // Use this URL for diff processing
});
Diff Data Format
The diff-processor.php endpoint returns a structured data object that describes the differences between the old and new content. This section explains the format of this data.
Top-Level Structure
{
"success": true,
"config": {
"diffData": {
"old": [ /* Line objects for old content */ ],
"new": [ /* Line objects for new content */ ],
"chunks": [ /* Chunk objects describing differences */ ]
},
/* Other configuration properties */
}
}
Line Objects
The old
and new
arrays contain line objects:
{
"number": 1, // 1-based line number
"content": "Line content",
"code": "Line content (for syntax highlighting)",
"type": "context|added|removed|unchanged",
"chunks": [0, 1] // Indices of chunks that include this line
}
Chunk Objects
The chunks
array contains objects describing each difference:
{
"id": 0, // Chunk ID (index)
"old": {
"start": 1, // 1-based line number of the start of the chunk in old content
"end": 3, // 1-based line number of the end of the chunk in old content
"lines": [0, 1, 2] // Indices in the old lines array
},
"new": {
"start": 1, // 1-based line number of the start of the chunk in new content
"end": 4, // 1-based line number of the end of the chunk in new content
"lines": [0, 1, 2, 3] // Indices in the new lines array
},
"type": "modified|added|removed|unchanged", // Type of change
"selected": "old|new" // Selected version for merge
}
Security Considerations
When working with the Visual Diff Merge API, consider these security practices:
File Access Security
- Use Reference IDs: When working with server files, always use reference IDs instead of direct paths. Reference IDs are secure tokens that map to file paths without exposing the actual paths to the client.
-
Configure Allowed Directories: In
api/config.php
, specify which directories are allowed to be accessed using thephp.security.allowedDirectories
setting. See Configuration for details.
CORS Considerations
If you're accessing the API from a different domain:
- Server Configuration: Configure your web server to allow cross-origin requests to the API endpoints if needed. See Server-Specific Configuration for diff-viewer.
-
URL Content Fetching: Use the
get-url-content.php
endpoint to fetch content from external URLs to avoid CORS issues.
Authorization
By default, Visual Diff Merge does not include an authorization system. For production use:
- Implement Authentication: Add your own authentication layer to protect the API endpoints.
- API Keys: Consider implementing API keys or tokens for programmatic access.
Advanced Usage
Custom API Endpoints
You can create custom API endpoints to extend Visual Diff Merge's functionality:
- Create a new PHP file in the
api/
directory - Include the necessary classes from the
VisualDiffMerge
namespace - Implement your custom logic
- Return a JSON response
Example Custom Endpoint
<?php
// custom-endpoint.php
require_once __DIR__ . '/../vendor/autoload.php';
use VisualDiffMerge\Config;
use VisualDiffMerge\DiffViewer;
// Initialize config
Config::init();
// Set JSON response headers
header('Content-Type: application/json');
// Handle the request
try {
// Your custom logic here
$result = [
'success' => true,
'data' => 'Your custom response'
];
echo json_encode($result);
} catch (Exception $e) {
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}
Programmatic API Usage
You can use the Visual Diff Merge API programmatically from your applications:
PHP Example
<?php
// PHP example using curl
$data = [
'old' => [
'type' => 'text',
'content' => 'Old content here',
'filename' => 'old.txt'
],
'new' => [
'type' => 'text',
'content' => 'New content here',
'filename' => 'new.txt'
]
];
$ch = curl_init('https://your-server.com/visual-diff-merge/api/diff-processor.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);
$result = json_decode($response, true);
if ($result['success']) {
// Process the diff data
$diffData = $result['config']['diffData'];
} else {
// Handle error
echo $result['error'];
}
curl_close($ch);
JavaScript Example
// JavaScript example using fetch API
const processsDiff = async (oldContent, newContent) => {
const data = {
old: {
type: 'text',
content: oldContent,
filename: 'old.txt'
},
new: {
type: 'text',
content: newContent,
filename: 'new.txt'
}
};
try {
const response = await fetch('https://your-server.com/visual-diff-merge/api/diff-processor.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
if (result.success) {
// Process the diff data
return result.config.diffData;
} else {
throw new Error(result.error);
}
} catch (error) {
console.error('Error processing diff:', error);
throw error;
}
};