/** * Carbon Canvas - Aesthetic Code Card & Snippet Image Generator * Author: Vamz Spectre (VamxAPI) * * Fitur: * - Mengubah potongan source code menjadi gambar kartu kode estetis ala Carbon (carbon.now.sh) * - macOS Window Frame: Tombol kontrol jendela (Merah, Kuning, Hijau) & judul file * - Syntax Highlighting Otomatis: Keyword, String, Number, Boolean, Comment, Function, Operator * - 6 Pilihan Tema Populer: one-dark, dracula, monokai, night-owl, catppuccin, nord * - 6 Pilihan Background Gradient: candy, sunset, ocean, aurora, midnight, transparent * - High-Resolution Rendering menggunakan skia-canvas (anti-aliased & drop shadow realistis) * - Auto-Upload ke Vamx Media CDN (https://cdn.vamxapi.my.id/m/...) untuk WhatsApp & Telegram bot * * Penggunaan CLI: * curl -sL "https://code.vamxapi.my.id/snippet/raw/carbon-canvas" -o carbon-canvas.js * node carbon-canvas.js "const greeting = 'Hello World!'; console.log(greeting);" * node carbon-canvas.js --file ./carbon-canvas.js --theme dracula --bg ocean */ const fs = require("fs"); const path = require("path"); const { Canvas } = require("skia-canvas"); const VAMX_CDN_UPLOAD_ENDPOINT = "https://cdn.vamxapi.my.id/api/v1/media/upload"; // Palet Warna Tema Editor const THEMES = { "one-dark": { bg: "#282c34", text: "#abb2bf", lineNum: "rgba(171, 178, 191, 0.35)", keyword: "#e06c75", string: "#98c379", number: "#d19a66", boolean: "#d19a66", comment: "#5c6370", function: "#61afef", operator: "#56b6c2", identifier: "#abb2bf", }, dracula: { bg: "#282a36", text: "#f8f8f2", lineNum: "rgba(248, 248, 242, 0.35)", keyword: "#ff79c6", string: "#f1fa8c", number: "#bd93f9", boolean: "#bd93f9", comment: "#6272a4", function: "#50fa7b", operator: "#ff79c6", identifier: "#f8f8f2", }, monokai: { bg: "#272822", text: "#f8f8f2", lineNum: "rgba(248, 248, 242, 0.35)", keyword: "#f92672", string: "#e6db74", number: "#ae81ff", boolean: "#ae81ff", comment: "#75715e", function: "#a6e22e", operator: "#f92672", identifier: "#f8f8f2", }, "night-owl": { bg: "#011627", text: "#d6deeb", lineNum: "rgba(214, 222, 235, 0.35)", keyword: "#c792ea", string: "#ecc48d", number: "#f78c6c", boolean: "#ff5874", comment: "#637777", function: "#82aaff", operator: "#7fdbca", identifier: "#d6deeb", }, catppuccin: { bg: "#1e1e2e", text: "#cdd6f4", lineNum: "rgba(205, 214, 244, 0.35)", keyword: "#cba6f7", string: "#a6e3a1", number: "#fab387", boolean: "#f38ba8", comment: "#6c7086", function: "#89b4fa", operator: "#94e2d5", identifier: "#cdd6f4", }, nord: { bg: "#2e3440", text: "#d8dee9", lineNum: "rgba(216, 222, 233, 0.35)", keyword: "#81a1c1", string: "#a3be8c", number: "#b48ead", boolean: "#b48ead", comment: "#4c566a", function: "#88c0d0", operator: "#81a1c1", identifier: "#d8dee9", }, }; // Palet Background Gradient const GRADIENTS = { candy: ["#4158D0", "#C850C0", "#FFCC70"], sunset: ["#FA709A", "#FEE140"], ocean: ["#2E3192", "#1BFFFF"], aurora: ["#00c6ff", "#0072ff"], midnight: ["#0f2027", "#203a43", "#2c5364"], transparent: null, }; /** * Tokenizer sintaks kode sederhana untuk JavaScript, Python & bahasa pemrograman umum * @param {string} line * @returns {Array<{ text: string, type: string }>} */ function tokenizeLine(line) { const tokens = []; let i = 0; while (i < line.length) { // Comment baris tunggal if (line.slice(i, i + 2) === "//" || line[i] === "#") { tokens.push({ text: line.slice(i), type: "comment" }); break; } // String (double quote) if (line[i] === '"') { let j = i + 1; while (j < line.length && (line[j] !== '"' || line[j - 1] === "\\")) j++; tokens.push({ text: line.slice(i, j + 1), type: "string" }); i = j + 1; continue; } // String (single quote) if (line[i] === "'") { let j = i + 1; while (j < line.length && (line[j] !== "'" || line[j - 1] === "\\")) j++; tokens.push({ text: line.slice(i, j + 1), type: "string" }); i = j + 1; continue; } // String template literal if (line[i] === "`") { let j = i + 1; while (j < line.length && (line[j] !== "`" || line[j - 1] === "\\")) j++; tokens.push({ text: line.slice(i, j + 1), type: "string" }); i = j + 1; continue; } // Angka (Number) if (/\d/.test(line[i]) && (i === 0 || !/[a-zA-Z0-9_$]/.test(line[i - 1]))) { let j = i; while (j < line.length && /[0-9.xXbBoOa-fA-F]/.test(line[j])) j++; tokens.push({ text: line.slice(i, j), type: "number" }); i = j; continue; } // Kata / Identifier if (/[a-zA-Z_$]/.test(line[i])) { let j = i; while (j < line.length && /[a-zA-Z0-9_$]/.test(line[j])) j++; const word = line.slice(i, j); const keywords = new Set([ "const", "let", "var", "function", "return", "if", "else", "for", "while", "do", "switch", "case", "break", "continue", "new", "this", "class", "extends", "import", "export", "from", "default", "async", "await", "try", "catch", "finally", "throw", "typeof", "instanceof", "in", "of", "def", "elif", "print", "self", "None", "True", "False", "public", "private", "protected", "static", "interface", "type", "enum" ]); const booleans = new Set(["true", "false", "null", "undefined", "NaN"]); if (keywords.has(word)) { tokens.push({ text: word, type: "keyword" }); } else if (booleans.has(word)) { tokens.push({ text: word, type: "boolean" }); } else if (line[j] === "(") { tokens.push({ text: word, type: "function" }); } else { tokens.push({ text: word, type: "identifier" }); } i = j; continue; } // Simbol, operator & spasi tokens.push({ text: line[i], type: "operator" }); i++; } return tokens; } /** * Upload gambar hasil render ke Vamx Media CDN * @param {Buffer} buffer * @param {string} filename * @returns {Promise} */ async function uploadToVamxCdn(buffer, filename = "carbon.png") { try { const blob = new Blob([buffer], { type: "image/png" }); const form = new FormData(); form.append("file", blob, filename); const res = await fetch(VAMX_CDN_UPLOAD_ENDPOINT, { method: "POST", headers: { "x-client-mode": "vamx-cdn" }, body: form, }); const json = await res.json(); if (json.status && json.result?.media?.url) { return json.result.media.url; } throw new Error(json.message || "Gagal mengunggah gambar ke CDN"); } catch (err) { throw new Error(`[Upload Error] ${err.message}`); } } /** * Main Carbon Canvas Generator * @param {string} codeContent - String teks kode sumber * @param {object} [options] - Opsi konfigurasi * @returns {Promise<{ buffer: Buffer, url?: string, width: number, height: number, lines: number }>} */ async function generateCarbon(codeContent, options = {}) { const code = String(codeContent || "").trim() || '// Carbon Canvas Code Card\nconsole.log("Hello, World!");'; const themeName = (options.theme || "one-dark").toLowerCase(); const theme = THEMES[themeName] || THEMES["one-dark"]; const bgName = (options.bg || "candy").toLowerCase(); const gradient = GRADIENTS[bgName] !== undefined ? GRADIENTS[bgName] : GRADIENTS["candy"]; const showLineNumbers = options.lineNumbers !== false; const title = options.title || "snippet.js"; const lines = code.split("\n"); const fontSize = 16; const lineHeight = 28; const charWidth = 9.8; const maxLineLength = Math.max(...lines.map((l) => l.length)); // Hitung dimensi jendela kode const lineNumWidth = showLineNumbers ? Math.max(String(lines.length).length * 10 + 25, 45) : 10; const codeWidth = Math.max(Math.round(maxLineLength * charWidth + lineNumWidth + 60), 480); const codeHeight = lines.length * lineHeight + 65; // Dimensi total canvas const pad = options.padding !== undefined ? Number(options.padding) : 56; const W = Math.round(codeWidth + pad * 2); const H = Math.round(codeHeight + pad * 2); const canvas = new Canvas(W, H); const ctx = canvas.getContext("2d"); // 1. Gambar Background Gradient if (gradient && gradient.length > 0) { const grad = ctx.createLinearGradient(0, 0, W, H); if (gradient.length === 2) { grad.addColorStop(0, gradient[0]); grad.addColorStop(1, gradient[1]); } else { grad.addColorStop(0, gradient[0]); grad.addColorStop(0.5, gradient[1]); grad.addColorStop(1, gradient[2]); } ctx.fillStyle = grad; ctx.fillRect(0, 0, W, H); } // 2. Gambar Jendela macOS (Drop Shadow) ctx.save(); ctx.shadowColor = "rgba(0, 0, 0, 0.45)"; ctx.shadowBlur = 35; ctx.shadowOffsetY = 18; const winX = pad; const winY = pad; const winW = codeWidth; const winH = codeHeight; const cornerRadius = 14; ctx.fillStyle = theme.bg; ctx.beginPath(); ctx.roundRect(winX, winY, winW, winH, cornerRadius); ctx.fill(); ctx.restore(); // 3. Header Window macOS (Traffic Light Dots) const dots = [ { x: winX + 22, color: "#ff5f56" }, // Red { x: winX + 42, color: "#ffbd2e" }, // Yellow { x: winX + 62, color: "#27c93f" }, // Green ]; dots.forEach((d) => { ctx.beginPath(); ctx.arc(d.x, winY + 22, 6, 0, Math.PI * 2); ctx.fillStyle = d.color; ctx.fill(); }); // Judul Window if (title) { ctx.fillStyle = "rgba(255, 255, 255, 0.35)"; ctx.font = '13px "DejaVu Sans Mono", "Liberation Mono", sans-serif'; ctx.textAlign = "center"; ctx.fillText(title, winX + winW / 2, winY + 26); } // 4. Render Garis Kode & Syntax Highlighting ctx.font = '16px "DejaVu Sans Mono", "Liberation Mono", monospace'; ctx.textAlign = "left"; const startX = winX + (showLineNumbers ? lineNumWidth + 20 : 30); const startY = winY + 62; lines.forEach((line, lineIdx) => { const y = startY + lineIdx * lineHeight; // Nomor Baris if (showLineNumbers) { ctx.fillStyle = theme.lineNum; ctx.textAlign = "right"; ctx.fillText(String(lineIdx + 1), winX + lineNumWidth, y); ctx.textAlign = "left"; } // Token Warna const tokens = tokenizeLine(line); let currentX = startX; tokens.forEach((t) => { ctx.fillStyle = theme[t.type] || theme.text; ctx.fillText(t.text, currentX, y); currentX += ctx.measureText(t.text).width; }); }); const buffer = await canvas.toBuffer("png"); let cdnUrl = null; if (options.uploadCdn !== false) { try { cdnUrl = await uploadToVamxCdn(buffer, `carbon_${Date.now()}.png`); } catch {} } return { buffer, url: cdnUrl, width: W, height: H, lines: lines.length, theme: themeName, bg: bgName, }; } module.exports = { generateCarbon, THEMES, GRADIENTS }; // CLI Execution if (require.main === module) { const args = process.argv.slice(2); let codeInput = ""; let themeInput = "one-dark"; let bgInput = "candy"; let titleInput = "index.js"; for (let i = 0; i < args.length; i++) { if (args[i] === "--file" && args[i + 1]) { codeInput = fs.readFileSync(path.resolve(args[i + 1]), "utf-8"); titleInput = path.basename(args[i + 1]); i++; } else if (args[i] === "--theme" && args[i + 1]) { themeInput = args[i + 1]; i++; } else if (args[i] === "--bg" && args[i + 1]) { bgInput = args[i + 1]; i++; } else if (args[i] === "--title" && args[i + 1]) { titleInput = args[i + 1]; i++; } else if (!codeInput && !args[i].startsWith("--")) { codeInput = args[i]; } } if (!codeInput) { codeInput = `// Welcome to Carbon Canvas function calculateFactorial(number) { if (number <= 1) return 1; return number * calculateFactorial(number - 1); } const result = calculateFactorial(5); console.log("Factorial(5) =", result);`; } generateCarbon(codeInput, { theme: themeInput, bg: bgInput, title: titleInput, uploadCdn: true, }) .then((res) => { console.log( JSON.stringify( { status: true, creator: "Vamz Spectre", data: { title: titleInput, url: res.url, theme: res.theme, background: res.bg, dimensions: `${res.width}x${res.height}`, lines: res.lines, buffer_size: `${(res.buffer.length / 1024).toFixed(2)} KB`, }, }, null, 2 ) ); }) .catch((err) => { console.error( JSON.stringify( { status: false, creator: "Vamz Spectre", message: err.message || "Gagal membuat gambar carbon canvas.", }, null, 2 ) ); process.exit(1); }); }