@mvkproject/nexus
Version:
Official Node.js wrapper for the MVKProject Nexus API and Free AI Services
248 lines (218 loc) • 7.34 kB
JavaScript
const axios = require("axios")
const { execSync } = require("child_process")
const fs = require("fs")
const path = require("path")
// Get package version
const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"), "utf8"))
const currentVersion = packageJson.version
const packageName = packageJson.name
// Function to check for updates and auto-update
async function checkForUpdates() {
try {
// Get the latest version from npm registry
const response = await axios.get(`https://registry.npmjs.org/${packageName}`)
const latestVersion = response.data["dist-tags"].latest
// Compare versions
if (latestVersion !== currentVersion) {
console.log(`[${packageName}] Updating from v${currentVersion} to v${latestVersion}...`)
// Execute npm update command
execSync(`npm install ${packageName}@latest --no-save`, { stdio: "ignore" })
console.log(`[${packageName}] Successfully updated to v${latestVersion}!`)
console.log(`[${packageName}] Please restart your application to use the new version.`)
}
} catch (error) {
// Silent fail - don't interrupt user's application if update check fails
}
}
// Run update check when module is loaded
checkForUpdates()
class NexusAPI {
constructor(apiKey) {
if (!apiKey) {
throw new Error("API key is required. Join Discord server to get one: https://discord.gg/9d8MP9gRbz")
}
this.apiKey = apiKey
this.baseURL = "https://nexus.adonis-except.xyz"
this.client = axios.create({
baseURL: this.baseURL,
headers: {
"x-api-key": this.apiKey,
"Content-Type": "application/json",
},
})
}
// Welcome Image Generation
async generateWelcomeImage(options) {
try {
const response = await this.client.post("/welcome/welcome-image", options)
return response.data
} catch (error) {
this._handleError(error)
}
}
// Rank/Level Card Generation
async generateRankCard(options) {
try {
const response = await this.client.post("/rank", options)
return response.data
} catch (error) {
this._handleError(error)
}
}
// Level Up Card Generation
async generateLevelUpCard(options) {
try {
const response = await this.client.post("/rank/level-up", options)
return response.data
} catch (error) {
this._handleError(error)
}
}
// ChatGPT Interaction
async chatGPT(options) {
try {
const mappedOptions = this._mapLengthParam(options)
const response = await this.client.post("/chatgpt", mappedOptions)
return response.data
} catch (error) {
this._handleError(error)
}
}
// Gemini Interaction
async gemini(options) {
try {
const mappedOptions = this._mapLengthParam(options)
const response = await this.client.post("/gemini", mappedOptions)
return response.data
} catch (error) {
this._handleError(error)
}
}
// DeepSeek Interaction
async deepSeek(options) {
try {
const mappedOptions = this._mapLengthParam(options)
const response = await this.client.post("/deep-ai", mappedOptions)
return response.data
} catch (error) {
this._handleError(error)
}
}
// Meta AI Interaction
async metaAI(options) {
try {
const mappedOptions = this._mapLengthParam(options)
const response = await this.client.post("/meta-ai", mappedOptions)
return response.data
} catch (error) {
this._handleError(error)
}
}
// AI Image Analysis (Vision)
async analyzeImage(options) {
try {
const response = await this.client.post("/vision", options)
return response.data
} catch (error) {
this._handleError(error)
}
}
// AI Image Generation
async generateImage(options) {
try {
const response = await this.client.post("/image-ai", options)
// If the response contains an image path, convert it to a complete URL
if (response.data && response.data.result) {
// Check if the response is already a complete URL or a relative path
if (!response.data.result.startsWith('http')) {
// Ensure there are no double slashes in the final URL
const path = response.data.result.startsWith('/')
? response.data.result
: `/${response.data.result}`
response.data.result = `${this.baseURL}${path}`
}
// Only download the image if autoDownload is true
if (options.autoDownload === true) {
try {
this._downloadImage(
response.data.result,
options.filename || `image-${Date.now()}.png`,
options.downloadDirectory
)
} catch (downloadError) {
console.warn("Could not start automatic download:", downloadError.message)
}
}
}
return response.data
} catch (error) {
this._handleError(error)
}
}
/**
* Downloads an image from a URL
* @param {string} url - URL of the image to download
* @param {string} filename - Filename to save the image
* @private
*/
async _downloadImage(url, filename, downloadDirectory) {
try {
// If we are in a browser
if (typeof window !== 'undefined') {
const link = document.createElement('a')
link.href = url
link.download = filename
link.style.display = 'none'
document.body.appendChild(link)
link.click()
setTimeout(() => {
document.body.removeChild(link)
}, 1000)
return
}
// If we are in Node.js
const fs = require('fs')
const path = require('path')
const { pipeline } = require('stream')
const { promisify } = require('util')
const streamPipeline = promisify(pipeline)
const response = await axios({
url,
method: 'GET',
responseType: 'stream'
})
// Determine download directory (use specified directory or fallback to 'downloads')
const downloadDir = downloadDirectory
? path.resolve(downloadDirectory)
: path.join(process.cwd(), 'downloads')
// Create download directory if it doesn't exist
if (!fs.existsSync(downloadDir)) {
fs.mkdirSync(downloadDir, { recursive: true })
}
const filePath = path.join(downloadDir, filename)
await streamPipeline(response.data, fs.createWriteStream(filePath))
console.log(`Image downloaded successfully: ${filePath}`)
} catch (error) {
throw new Error(`Error downloading the image: ${error.message}`)
}
}
_mapLengthParam(options) {
const mappedOptions = { ...options }
if (mappedOptions.length !== undefined) {
// Map "length" to "longitud" for the API
mappedOptions.longitud = mappedOptions.length
delete mappedOptions.length
}
return mappedOptions
}
_handleError(error) {
if (error.response) {
throw new Error(`API Error: ${error.response.status} - ${JSON.stringify(error.response.data)}`)
} else if (error.request) {
throw new Error("No response received from API")
} else {
throw new Error(`Error: ${error.message}`)
}
}
}
module.exports = NexusAPI