valzyysdk
Version:
CLI dan modul untuk mengakses data dari API JKT48Connect, termasuk data member, teater, event, pembayaran, dan lainnya.
183 lines (155 loc) • 6.11 kB
JavaScript
// version-checker.js
const https = require('https');
const semver = require('semver');
const path = require('path');
const fs = require('fs');
class RuntimeVersionChecker {
constructor(packageName) {
this.packageName = packageName;
this.currentVersion = this.getCurrentVersion();
this.cacheFile = path.join(__dirname, '.version-cache');
this.cacheDuration = 3600000; // 1 hour cache
}
getCurrentVersion() {
try {
const packagePath = path.join(__dirname, 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
return packageJson.version;
} catch (error) {
console.error('Error reading package.json:', error.message);
return '0.0.0';
}
}
async getLatestVersionFromRegistry() {
return new Promise((resolve, reject) => {
const url = `https://registry.npmjs.org/${this.packageName}/latest`;
const req = https.get(url, { timeout: 5000 }, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
try {
const packageInfo = JSON.parse(data);
resolve(packageInfo.version);
} catch (error) {
reject(new Error('Failed to parse npm registry response'));
}
});
});
req.on('timeout', () => {
req.destroy();
reject(new Error('Request timeout'));
});
req.on('error', (error) => {
reject(error);
});
});
}
getCachedVersion() {
try {
if (!fs.existsSync(this.cacheFile)) {
return null;
}
const cacheData = JSON.parse(fs.readFileSync(this.cacheFile, 'utf8'));
const now = Date.now();
// Check if cache is still valid
if ((now - cacheData.timestamp) < this.cacheDuration) {
return cacheData.latestVersion;
}
return null;
} catch (error) {
return null;
}
}
setCachedVersion(version) {
try {
const cacheData = {
latestVersion: version,
timestamp: Date.now()
};
fs.writeFileSync(this.cacheFile, JSON.stringify(cacheData));
} catch (error) {
// Silent fail for write permission issues
}
}
async getLatestVersion() {
// Try cache first
const cachedVersion = this.getCachedVersion();
if (cachedVersion) {
return cachedVersion;
}
// Fetch from registry
try {
const latestVersion = await this.getLatestVersionFromRegistry();
this.setCachedVersion(latestVersion);
return latestVersion;
} catch (error) {
// If network fails, return current version to allow usage
console.warn(`Warning: Could not check for updates (${error.message})`);
return this.currentVersion;
}
}
displayExpiredMessage(versionInfo) {
console.error(`
╔══════════════════════════════════════════════════════════════╗
║ 🚨 PACKAGE EXPIRED 🚨 ║
╠══════════════════════════════════════════════════════════════╣
║ Package: ${this.packageName.padEnd(48)} ║
║ Your Version: ${versionInfo.currentVersion.padEnd(37)} ║
║ Latest Version: ${versionInfo.latestVersion.padEnd(37)} ║
╠══════════════════════════════════════════════════════════════╣
║ ⚠️ Your version is outdated and no longer supported! ║
║ ║
║ 🔄 Please update to continue using this package: ║
║ ║
║ npm install ${this.packageName}${' '.repeat(Math.max(0, 25 - this.packageName.length))} ║
║ ║
║ 📖 Documentation: https://docs.jkt48connect.my.id ║
║ 🆕 New Features: /core (recommended) ║
║ ║
║ This script will not run until you update the package. ║
╚══════════════════════════════════════════════════════════════╝
`);
}
async checkVersionExpiry() {
try {
const latestVersion = await this.getLatestVersion();
// Compare versions
const isLatest = semver.gte(this.currentVersion, latestVersion);
const versionInfo = {
isLatest,
currentVersion: this.currentVersion,
latestVersion,
isExpired: !isLatest
};
if (!isLatest) {
this.displayExpiredMessage(versionInfo);
// Force exit - script cannot continue
console.error('\n❌ Script execution blocked due to outdated package version.\n');
process.exit(1);
}
return versionInfo;
} catch (error) {
// On network errors, allow execution but show warning
console.warn(`⚠️ Could not verify package version: ${error.message}`);
console.warn('⚠️ Continuing execution (offline mode)...\n');
return {
isLatest: true,
currentVersion: this.currentVersion,
latestVersion: this.currentVersion,
isExpired: false,
offline: true
};
}
}
async enforceLatestVersion() {
console.log('🔍 Checking package version...');
const versionInfo = await this.checkVersionExpiry();
if (!versionInfo.offline && versionInfo.isLatest) {
console.log('✅ Package version is up to date!');
}
return versionInfo;
}
}
module.exports = RuntimeVersionChecker;