UNPKG

create-sps-project

Version:

CLI tool to create SPS Digital Tech template projects

101 lines (85 loc) 3.23 kB
const http = require('http'); const https = require('https'); const path = require('path'); const FileSystem = require('../utils/file-system'); const Logger = require('../utils/logger'); class Downloader { constructor(config) { this.config = config; this.baseUrl = config.isDev ? 'http://localhost:3000/api' : 'https://sps-home.netlify.app/api'; this.requester = config.isDev ? http : https; } async downloadTemplate() { const { token, projectName, projectDir, isSingleComponent } = this.config; const endpoint = isSingleComponent ? `${this.baseUrl}/download-component` : `${this.baseUrl}/setup-template`; const data = JSON.stringify({ token, projectName: isSingleComponent ? undefined : projectName }); const options = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': data.length } }; return new Promise((resolve, reject) => { const req = this.requester.request(endpoint, options, (res) => { if (res.statusCode === 404) { reject(new Error(`Server endpoint not found: ${endpoint}`)); return; } if (res.statusCode === 200) { // Create project directory if not in single component mode if (!isSingleComponent) { FileSystem.createDirectory(projectDir); } // Download zip file const zipFileName = isSingleComponent ? 'sps-component.zip' : `${projectName}.zip`; const zipPath = path.join(projectDir, zipFileName); const fileStream = FileSystem.createWriteStream(zipPath); Logger.info(isSingleComponent ? 'Downloading component...' : 'Downloading template...'); Logger.info(`Downloading to: ${zipPath}`); res.pipe(fileStream); let downloadedBytes = 0; res.on('data', (chunk) => { downloadedBytes += chunk.length; Logger.progressUpdate(`Downloaded: ${Math.round(downloadedBytes / 1024)}KB`); }); fileStream.on('finish', () => { fileStream.close(() => { Logger.info('\nDownload completed, extracting files...'); resolve(zipPath); }); }); fileStream.on('error', (error) => { reject(new Error(`File write error: ${error.message}`)); }); } else { let errorData = ''; res.on('data', chunk => { errorData += chunk; }); res.on('end', () => { try { const response = JSON.parse(errorData); reject(new Error(response.error || `Server returned status code ${res.statusCode}`)); } catch { reject(new Error(`Server returned status code ${res.statusCode}: ${errorData}`)); } }); } }); req.on('error', (error) => { reject(new Error(`Connection error: ${error.message}`)); }); req.write(data); req.end(); }); } } module.exports = Downloader;