Sveltia Git CMS
Admin Super Admin
' + '' + '' + '' + '
' + '' + '
⚡
' + '' + siteName + '' + '
' + '
' + '← All Articles' + 'Studio Admin' + '
' + '
' + '
' + '
' + '
' + '' + (cat.name || 'General') + '' + '' + new Date(post.publishedAt || post.createdAt || Date.now()).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) + '' + '
' + '

' + safeTitle + '

' + (post.subtitle ? '

' + post.subtitle + '

' : '') + '
' + (post.featuredImage ? '
' + safeTitle + '
' : '') + '
' + contentHtml + '
' + '
' + '' + '' + ''; } function buildClientHomepageHtml(appData) { var settings = appData.settings || {}; var siteName = (settings.siteName || 'Astro Blog').replace(/' + '
' + '' + '' + (p.title || '').replace(/' + '' + '
' + '' + (cat.name || 'General') + '' + '

' + '' + (p.title || '').replace(/' + '

' + '

' + (p.excerpt || '').replace(/' + '

' + '
' + '
' + '' + new Date(p.publishedAt || p.createdAt || Date.now()).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) + '' + 'Read Article →' + '
' + ''; }).join(''); return '' + '' + '' + '' + '' + '' + siteName + ' – ' + siteTagline + '' + '' + '' + '' + '' + '' + '' + '' + '' + '
' + '' + '
⚡
' + '' + siteName + '' + '
' + '
' + 'Studio Admin' + '
' + '
' + '
' + (heroPost ? ( '
' + '
' + '' + (heroPost.featuredImage ? '
' + (heroPost.title || '').replace(/
' : '') + '
' + '
' ) : '') + '
' + '

📰Latest Publications

' + '
' + cardsHtml + '
' + '
' + '
' + '' + '' + ''; } async function pushBatchCommitDirect(owner, repo, token, branch, files, commitMessage, onProgress) { var rawToken = (token || '').trim(); var authHeader = rawToken.startsWith('Bearer ') || rawToken.startsWith('token ') ? rawToken : (rawToken.startsWith('github_pat_') ? ('Bearer ' + rawToken) : ('token ' + rawToken)); var headers = { Authorization: authHeader, Accept: 'application/vnd.github.v3+json', 'Content-Type': 'application/json' }; // 1. Fetch current branch HEAD if (onProgress) onProgress('Checking branch "' + branch + '"...'); var branchRes = await fetch('https://api.github.com/repos/' + owner + '/' + repo + '/branches/' + encodeURIComponent(branch), { headers: headers }); var baseCommitSha = null; var baseTreeSha = null; if (branchRes.ok) { var branchData = await branchRes.json(); baseCommitSha = branchData.commit ? branchData.commit.sha : null; baseTreeSha = (branchData.commit && branchData.commit.commit && branchData.commit.commit.tree) ? branchData.commit.commit.tree.sha : null; } // 2. Create Blobs in controlled batches of 5 var treeEntries = []; var BATCH_SIZE = 5; for (var i = 0; i < files.length; i += BATCH_SIZE) { var batch = files.slice(i, i + BATCH_SIZE); var promises = batch.map(async function(f) { var base64 = btoa(unescape(encodeURIComponent(f.content))); var blobRes = await fetch('https://api.github.com/repos/' + owner + '/' + repo + '/git/blobs', { method: 'POST', headers: headers, body: JSON.stringify({ content: base64, encoding: 'base64' }) }); if (!blobRes.ok) { var err = await blobRes.json().catch(function() { return {}; }); throw new Error('Blob creation failed for ' + f.path + ': ' + (err.message || blobRes.statusText)); } var blobData = await blobRes.json(); return { path: f.path, mode: '100644', type: 'blob', sha: blobData.sha }; }); var results = await Promise.all(promises); treeEntries.push.apply(treeEntries, results); var completed = Math.min(i + BATCH_SIZE, files.length); if (onProgress) onProgress('Processed ' + completed + '/' + files.length + ' files...'); if (i + BATCH_SIZE < files.length) await new Promise(function(r) { setTimeout(r, 40); }); } // 3. Create Git Tree if (onProgress) onProgress('Building Git tree (' + treeEntries.length + ' items)...'); var treePayload = { tree: treeEntries }; if (baseTreeSha) treePayload.base_tree = baseTreeSha; var treeRes = await fetch('https://api.github.com/repos/' + owner + '/' + repo + '/git/trees', { method: 'POST', headers: headers, body: JSON.stringify(treePayload) }); if (!treeRes.ok) { var errT = await treeRes.json().catch(function() { return {}; }); throw new Error('Failed to create Git tree: ' + (errT.message || treeRes.statusText)); } var newTree = await treeRes.json(); // 4. Create 1 Single Atomic Commit if (onProgress) onProgress('Creating 1 single atomic commit...'); var commitPayload = { message: commitMessage, tree: newTree.sha, parents: baseCommitSha ? [baseCommitSha] : [] }; var commitRes = await fetch('https://api.github.com/repos/' + owner + '/' + repo + '/git/commits', { method: 'POST', headers: headers, body: JSON.stringify(commitPayload) }); if (!commitRes.ok) { var errC = await commitRes.json().catch(function() { return {}; }); throw new Error('Failed to create commit: ' + (errC.message || commitRes.statusText)); } var newCommit = await commitRes.json(); // 5. Update branch ref if (onProgress) onProgress('Updating branch ref in 1 build...'); var updateRefRes = await fetch('https://api.github.com/repos/' + owner + '/' + repo + '/git/refs/heads/' + encodeURIComponent(branch), { method: 'PATCH', headers: headers, body: JSON.stringify({ sha: newCommit.sha, force: true }) }); if (!updateRefRes.ok) { var createRefRes = await fetch('https://api.github.com/repos/' + owner + '/' + repo + '/git/refs', { method: 'POST', headers: headers, body: JSON.stringify({ ref: 'refs/heads/' + branch, sha: newCommit.sha }) }); if (!createRefRes.ok) { await fetch('https://api.github.com/repos/' + owner + '/' + repo + '/git/refs/heads/' + encodeURIComponent(branch), { method: 'PATCH', headers: headers, body: JSON.stringify({ sha: newCommit.sha, force: true }) }); } } return newCommit; } async function commitAllToGitHub(customMessage) { if (isLivePushRunning) { showToast('Push already in progress. Please wait...'); return; } var token = localStorage.getItem('astro_sveltia_gh_token') || ''; var owner = localStorage.getItem('astro_sveltia_gh_user') || APP_DATA.githubUser; var repo = localStorage.getItem('astro_sveltia_gh_repo') || APP_DATA.githubRepo; var branch = localStorage.getItem('astro_sveltia_gh_branch') || 'main'; if (!token) { promptEditGithubToken(); token = localStorage.getItem('astro_sveltia_gh_token') || ''; if (!token) return; } isLivePushRunning = true; var syncBtn = document.getElementById('btnSyncGh'); var syncLabel = document.getElementById('syncGhLabel'); if (syncBtn) syncBtn.disabled = true; function updateStatus(msg) { if (syncLabel) syncLabel.innerText = msg; showToast(msg); } updateStatus('Preparing atomic package...'); try { // 1. Sort posts chronologically descending var postsList = (APP_DATA.posts || []).slice().sort(function(a, b) { var tA = new Date(a.publishedAt || a.createdAt || 0).getTime(); var tB = new Date(b.publishedAt || b.createdAt || 0).getTime(); return tB - tA; }); var files = []; // 2. Data manifests var postsJson = JSON.stringify(postsList, null, 2); var settingsJson = JSON.stringify(APP_DATA.settings || {}, null, 2); var categoriesJson = JSON.stringify(APP_DATA.categories || [], null, 2); var menusJson = JSON.stringify({ items: APP_DATA.menus || [] }, null, 2); var redirectsJson = JSON.stringify({ rules: APP_DATA.redirects || [] }, null, 2); files.push({ path: 'src/data/posts.json', content: postsJson }); files.push({ path: 'dist/data/posts.json', content: postsJson }); files.push({ path: 'public/data/posts.json', content: postsJson }); files.push({ path: 'src/data/settings.json', content: settingsJson }); files.push({ path: 'dist/data/settings.json', content: settingsJson }); files.push({ path: 'public/data/settings.json', content: settingsJson }); files.push({ path: 'src/content/categories/categories.json', content: categoriesJson }); files.push({ path: 'src/data/menus.json', content: menusJson }); files.push({ path: 'src/data/redirects.json', content: redirectsJson }); // Edge cache control header var headersContent = '/*\n Cache-Control: public, max-age=0, must-revalidate\n/assets/*\n Cache-Control: public, max-age=31536000, immutable\n'; files.push({ path: '_headers', content: headersContent }); files.push({ path: 'dist/_headers', content: headersContent }); files.push({ path: 'public/_headers', content: headersContent }); // 3. Homepage HTML var homepageHtml = buildClientHomepageHtml(APP_DATA); files.push({ path: 'index.html', content: homepageHtml }); files.push({ path: 'dist/index.html', content: homepageHtml }); files.push({ path: 'public/index.html', content: homepageHtml }); files.push({ path: '404.html', content: homepageHtml }); files.push({ path: 'dist/404.html', content: homepageHtml }); // 4. Articles for (var i = 0; i < postsList.length; i++) { var p = postsList[i]; var catObj = (APP_DATA.categories || []).find(function(c) { return c.id === p.categoryId; }) || { name: 'General' }; var frontmatter = '---\n' + 'title: "' + (p.title || '').replace(/"/g, '\\"') + '"\n' + 'subtitle: "' + (p.subtitle || '').replace(/"/g, '\\"') + '"\n' + 'slug: "' + p.slug + '"\n' + 'publishedAt: "' + (p.publishedAt || new Date().toISOString()) + '"\n' + 'status: "' + (p.status || 'published') + '"\n' + 'category: "' + (catObj.name || 'General') + '"\n' + 'tags: ' + JSON.stringify(p.tags || []) + '\n' + 'author: "' + (p.authorId || 'Admin') + '"\n' + 'featuredImage: "' + (p.featuredImage || '') + '"\n' + 'featuredImageAlt: "' + (p.featuredImageAlt || '').replace(/"/g, '\\"') + '"\n' + 'featuredImageCaption: "' + (p.featuredImageCaption || '').replace(/"/g, '\\"') + '"\n' + 'featuredImageCredit: "' + (p.featuredImageCredit || '').replace(/"/g, '\\"') + '"\n' + 'showFeaturedImageInPost: ' + (p.showFeaturedImageInPost !== false) + '\n' + 'isFeatured: ' + (!!p.isFeatured) + '\n' + 'isTrending: ' + (!!p.isTrending) + '\n' + 'allowComments: ' + (p.allowComments !== false) + '\n' + 'excerpt: "' + (p.excerpt || '').replace(/"/g, '\\"') + '"\n' + 'seoTitle: "' + (p.seoTitle || '').replace(/"/g, '\\"') + '"\n' + 'metaDescription: "' + (p.metaDescription || '').replace(/"/g, '\\"') + '"\n' + '---\n\n' + (p.content || ''); files.push({ path: 'src/content/blog/' + p.slug + '.md', content: frontmatter }); if (p.status === 'published') { var postHtml = buildClientArticleHtml(p, APP_DATA); files.push({ path: p.slug + '/index.html', content: postHtml }); files.push({ path: 'dist/' + p.slug + '/index.html', content: postHtml }); files.push({ path: 'public/' + p.slug + '/index.html', content: postHtml }); } } // 5. Commit all atomically var commitMsg = customMessage || ('feat(blog): update site and articles in 1 single build (' + new Date().toLocaleTimeString() + ')'); var commit = await pushBatchCommitDirect(owner, repo, token, branch, files, commitMsg, function(stepMsg) { updateStatus(stepMsg); }); if (syncLabel) syncLabel.innerText = 'Live in 1 Build (#' + (commit.sha ? commit.sha.slice(0, 7) : 'ok') + ')'; showToast('✨ Published live in 1 single build! Cloudflare build running once.'); } catch (err) { console.error(err); if (syncLabel) syncLabel.innerText = 'Push Failed'; showToast('Push failed: ' + (err.message || 'Check GitHub token'), false); } finally { isLivePushRunning = false; if (syncBtn) syncBtn.disabled = false; } } function promptEditGithubToken() { var current = localStorage.getItem('astro_sveltia_gh_token') || ''; var input = prompt('Enter your GitHub Personal Access Token (classic token with "repo" scope):', current); if (input !== null && input.trim()) { localStorage.setItem('astro_sveltia_gh_token', input.trim()); showToast('GitHub token saved in your browser!'); } } // Direct Instant Initialization with DOM safeguard function initStudio() { try { renderNavbars(); switchTab('dashboard'); } catch (e) { console.error('Studio init error:', e); } } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initStudio); } else { initStudio(); }