Skip to content

Latest commit

 

History

History
598 lines (457 loc) · 13.9 KB

File metadata and controls

598 lines (457 loc) · 13.9 KB

Library Management API Documentation

Overview

The DTMS Library Management API provides automatic update capabilities for frontend libraries (AlpineJS and HTMX). This system ensures DTMS always has access to the latest, secure, and performance-optimized versions of essential frontend frameworks.

API Base URL

http://dtms.localhost/core/api/libraries

Authentication

Currently, the Library Management API uses the same authentication mechanism as other DTMS core APIs. CSRF protection is implemented for state-changing operations.

Endpoints

Check for Updates

Get information about available library updates.

Endpoint: GET /libraries/check-updates

Response:

{
  "alpine": {
    "current_version": "3.13.3",
    "latest_version": "3.14.9",
    "has_update": true,
    "download_url": "https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/cdn.min.js"
  },
  "htmx": {
    "current_version": "1.9.8",
    "latest_version": "2.0.6",
    "has_update": true,
    "download_url": "https://unpkg.com/htmx.org@2.0.6/dist/htmx.min.js"
  }
}

Error Response:

{
  "alpine": {
    "error": "Failed to fetch Alpine.js releases from GitHub API"
  },
  "htmx": {
    "current_version": "1.9.8",
    "latest_version": "2.0.6",
    "has_update": true,
    "download_url": "https://unpkg.com/htmx.org@2.0.6/dist/htmx.min.js"
  }
}

Update Library

Update a specific library to the latest version or force update.

Endpoint: POST /libraries/update

Request Body:

{
  "library": "alpine", // Required: "alpine" or "htmx"
  "force": false // Optional: force update even if already latest
}

Success Response (Updated):

{
  "updated": true,
  "message": "Updated from 3.13.3 to 3.14.9",
  "previous_version": "3.13.3",
  "new_version": "3.14.9",
  "file_size": "43.7KB",
  "integrity": "sha384-9Ax3MmS9AClxJyd5/zafcXXjxmwFhZCdsT6HJoJjarvCaAkJlk5QDzjLJm+Wdx5F"
}

Success Response (Already Updated):

{
  "updated": false,
  "message": "Already on latest version 3.14.9",
  "current_version": "3.14.9",
  "latest_version": "3.14.9"
}

Error Response:

{
  "error": "Failed to download from https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/cdn.min.js"
}

HTTP Status Codes

Status Code Description
200 Success
400 Bad Request (invalid library name, malformed JSON)
405 Method Not Allowed (wrong HTTP method)
500 Internal Server Error (download failure, file system error)

Client Examples

JavaScript (Browser)

// Check for updates
async function checkLibraryUpdates() {
  try {
    const response = await fetch("/core/api/libraries/check-updates");
    const updates = await response.json();

    console.log("Available updates:", updates);
    return updates;
  } catch (error) {
    console.error("Failed to check updates:", error);
    throw error;
  }
}

// Update a library
async function updateLibrary(libraryName, force = false) {
  try {
    const response = await fetch("/core/api/libraries/update", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-Token": await getCSRFToken(), // Implement as needed
      },
      body: JSON.stringify({
        library: libraryName,
        force: force,
      }),
    });

    const result = await response.json();

    if (!response.ok) {
      throw new Error(result.error || "Update failed");
    }

    console.log("Update result:", result);
    return result;
  } catch (error) {
    console.error("Failed to update library:", error);
    throw error;
  }
}

// Example usage
async function updateAllLibraries() {
  const updates = await checkLibraryUpdates();

  for (const [lib, info] of Object.entries(updates)) {
    if (info.has_update) {
      console.log(`Updating ${lib}...`);
      const result = await updateLibrary(lib);
      if (result.updated) {
        console.log(`✅ ${lib} updated successfully!`);
      }
    }
  }
}

cURL Examples

# Check for updates
curl -s "http://dtms.localhost/core/api/libraries/check-updates" | jq '.'

# Update AlpineJS
curl -X POST "http://dtms.localhost/core/api/libraries/update" \
     -H "Content-Type: application/json" \
     -d '{"library":"alpine","force":false}' | jq '.'

# Force update HTMX
curl -X POST "http://dtms.localhost/core/api/libraries/update" \
     -H "Content-Type: application/json" \
     -d '{"library":"htmx","force":true}' | jq '.'

PHP Client

<?php

class DTMSLibraryClient
{
    private $baseUrl;
    private $csrfToken;

    public function __construct($baseUrl = 'http://dtms.localhost/core/api/libraries')
    {
        $this->baseUrl = $baseUrl;
    }

    public function checkUpdates(): array
    {
        $response = file_get_contents($this->baseUrl . '/check-updates');

        if ($response === false) {
            throw new Exception('Failed to fetch update information');
        }

        return json_decode($response, true);
    }

    public function updateLibrary(string $library, bool $force = false): array
    {
        $data = [
            'library' => $library,
            'force' => $force
        ];

        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => [
                    'Content-Type: application/json',
                    // Add CSRF token if available
                    // 'X-CSRF-Token: ' . $this->csrfToken
                ],
                'content' => json_encode($data)
            ]
        ]);

        $response = file_get_contents($this->baseUrl . '/update', false, $context);

        if ($response === false) {
            throw new Exception('Failed to update library');
        }

        return json_decode($response, true);
    }

    public function updateAll(): array
    {
        $updates = $this->checkUpdates();
        $results = [];

        foreach ($updates as $library => $info) {
            if (isset($info['has_update']) && $info['has_update']) {
                try {
                    $result = $this->updateLibrary($library);
                    $results[$library] = $result;
                } catch (Exception $e) {
                    $results[$library] = ['error' => $e->getMessage()];
                }
            }
        }

        return $results;
    }
}

// Usage example
$client = new DTMSLibraryClient();

try {
    // Check what updates are available
    $updates = $client->checkUpdates();
    echo "Available updates:\n";
    print_r($updates);

    // Update all libraries
    $results = $client->updateAll();
    echo "Update results:\n";
    print_r($results);

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

Batch Operations Script

DTMS includes a command-line script for batch operations:

Script Usage

# Check for updates
./scripts/update-libraries.sh check

# Update all libraries
./scripts/update-libraries.sh update-all

# Force update all libraries
./scripts/update-libraries.sh force-update-all

Script Output Examples

Check Updates:

🔍 Vérification des mises à jour disponibles...
{
  "alpine": {
    "current_version": "3.14.9",
    "latest_version": "3.14.9",
    "has_update": false,
    "download_url": "https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/cdn.min.js"
  },
  "htmx": {
    "current_version": "2.0.6",
    "latest_version": "2.0.6",
    "has_update": false,
    "download_url": "https://unpkg.com/htmx.org@2.0.6/dist/htmx.min.js"
  }
}

Update All:

🚀 Mise à jour de toutes les bibliothèques...

📦 Mise à jour de alpine...
{
  "updated": false,
  "message": "Already on latest version 3.14.9",
  "current_version": "3.14.9",
  "latest_version": "3.14.9"
}
ℹ️ alpine: Already on latest version 3.14.9

📦 Mise à jour de htmx...
{
  "updated": false,
  "message": "Already on latest version 2.0.6",
  "current_version": "2.0.6",
  "latest_version": "2.0.6"
}
ℹ️ htmx: Already on latest version 2.0.6

✨ Mise à jour terminée. Vérification finale...
# ... final status check

File System Structure

The library management system maintains the following structure:

public/assets/js/lib/
├── dtms-lib-manager.js     # Intelligent library loader
├── alpine.min.js           # AlpineJS library file
├── htmx.min.js            # HTMX library file
└── versions.json          # Version tracking and metadata

versions.json Structure

{
  "alpine": {
    "current_version": "3.14.9",
    "local_file": "alpine.min.js",
    "cdn_url": "https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/cdn.min.js",
    "last_updated": "2025-08-23T13:37:55+08:00",
    "file_size": "43.7KB",
    "integrity": "sha384-9Ax3MmS9AClxJyd5/zafcXXjxmwFhZCdsT6HJoJjarvCaAkJlk5QDzjLJm+Wdx5F"
  },
  "htmx": {
    "current_version": "2.0.6",
    "local_file": "htmx.min.js",
    "cdn_url": "https://unpkg.com/htmx.org@2.0.6/dist/htmx.min.js",
    "last_updated": "2025-08-23T13:38:56+08:00",
    "file_size": "49.8KB",
    "integrity": "sha384-Akqfrbj/HpNVo8k11SXBb6TlBWmXXlYQrCSqEWmyKJe+hDm3Z/B2WVG4smwBkRVm"
  },
  "update_strategy": "cdn-with-fallback",
  "last_check": "2025-08-23T13:38:56+08:00",
  "admin_notes": "Installed via DTMS lib manager"
}

Version Detection Strategy

The system uses a hybrid approach for version detection:

1. Primary: GitHub API

  • AlpineJS: https://api.github.com/repos/alpinejs/alpine/releases/latest
  • HTMX: https://api.github.com/repos/bigskysoftware/htmx/releases/latest

2. Fallback: Known Latest Versions

If GitHub API is unavailable, the system falls back to hardcoded latest known versions:

  • AlpineJS: v3.14.9
  • HTMX: v2.0.6

This ensures the update system remains functional even in environments with restricted internet access.

Security Features

1. Integrity Verification

All downloaded libraries are verified using SHA384 checksums:

// Generate and verify integrity
$content = file_get_contents($downloadUrl);
$integrity = 'sha384-' . base64_encode(hash('sha384', $content, true));

// Store in versions.json for future verification
$versions[$library]['integrity'] = $integrity;

2. Backup and Rollback

Before updating, the system creates automatic backups:

// Backup current file
if (file_exists($targetFile)) {
    copy($targetFile, $targetFile . '.backup');
}

// Rollback on failure
if ($updateFailed && file_exists($backupFile)) {
    copy($backupFile, $targetFile);
}

3. Content Validation

Basic validation prevents corrupted downloads:

// Verify minimum file size
if (strlen($newContent) < 1000) {
    throw new Exception("Downloaded file too small, possible error");
}

Error Handling

The API provides comprehensive error handling:

Common Error Scenarios

  1. Network Issues

    • GitHub API unavailable
    • CDN download failures
    • Timeout errors
  2. File System Issues

    • Permission errors
    • Disk space problems
    • Write failures
  3. Validation Errors

    • Corrupted downloads
    • Invalid JSON responses
    • Missing version information

Error Response Format

{
  "error": "Descriptive error message",
  "error_code": "DOWNLOAD_FAILED", // Optional error code
  "details": {
    // Optional additional details
    "url": "https://...",
    "http_status": 404
  }
}

Performance Considerations

1. Caching

  • Version information is cached in versions.json
  • Update checks use conditional requests when possible
  • Local files serve as fallback for performance

2. Rate Limiting

  • GitHub API calls are rate-limited (60 requests/hour for unauthenticated)
  • Fallback versions prevent API exhaustion
  • Update checks are typically manual or scheduled

3. Download Optimization

  • Files are streamed directly to disk
  • Progress tracking for large downloads
  • Resume capability for interrupted downloads (future feature)

Monitoring and Logging

Logging

Library operations are logged through DTMS's standard logging system:

error_log("DTMS Library Manager: Updated {$library} from {$oldVersion} to {$newVersion}");

Admin Interface

Web-based monitoring available at /admin/libraries.html:

  • Real-time update status
  • Version history
  • Manual update triggers
  • System health indicators

Automation

Scheduled Updates

For production environments, consider scheduling regular update checks:

#!/bin/bash
# Add to crontab: 0 2 * * 0 /path/to/update-libraries.sh update-all
cd /path/to/dtms
./scripts/update-libraries.sh update-all >> /var/log/dtms-library-updates.log 2>&1

CI/CD Integration

# GitHub Actions example
name: Update DTMS Libraries
on:
  schedule:
    - cron: "0 2 * * 1" # Weekly on Monday 2 AM
  workflow_dispatch:

jobs:
  update-libraries:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Update Libraries
        run: |
          ./scripts/update-libraries.sh update-all
          git add public/assets/js/lib/
          git commit -m "Auto-update frontend libraries" || echo "No updates"
          git push

Future Enhancements

Planned Features

  1. Additional Libraries

    • Vue.js support
    • React integration
    • Custom library definitions
  2. Advanced Update Strategies

    • Staged rollouts
    • A/B testing support
    • Automatic rollback on errors
  3. Enhanced Security

    • GPG signature verification
    • Subresource Integrity (SRI) enforcement
    • Vulnerability scanning
  4. Better Monitoring

    • Usage analytics
    • Performance metrics
    • Update success rates

Related Documentation