feat: prisma schema, groups API, deploy workflow

This commit is contained in:
2026-04-23 21:41:11 +05:00
parent 4c50036172
commit 65cf8ca01f
285 changed files with 24602 additions and 25890 deletions
+18
View File
@@ -0,0 +1,18 @@
import { requireAuth } from '~/server/utils/auth'
import { getUserAchievements, achievements } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
// Calculate stats
const userAchievements = getUserAchievements(user.id)
const totalCompleted = userAchievements.filter((a: any) => a.id?.startsWith('completed-')).length
return {
achievements: userAchievements,
stats: {
total: userAchievements.length,
completedTasks: totalCompleted
}
}
})
+28
View File
@@ -0,0 +1,28 @@
import { requireAuth } from '~/server/utils/auth'
import { users, canvases, pushSubscriptions } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
if (user.role !== 'admin') {
throw createError({ statusCode: 403, message: 'Admin access required' })
}
const usersList = Array.from(users.values())
const canvasesList = Array.from(canvases.values()).map(c => ({
id: c.id,
name: c.name,
nodeCount: c.nodes.length,
updatedAt: c.updatedAt
}))
return {
users: usersList,
canvases: canvasesList,
stats: {
users: usersList.length,
canvases: canvasesList.length,
nodes: canvasesList.reduce((sum, c) => sum + c.nodeCount, 0),
pushes: pushSubscriptions.size
}
}
})
+85
View File
@@ -0,0 +1,85 @@
import { generateToken } from '~/server/utils/auth'
import { users } from '~/server/utils/db'
interface FirebaseUser {
localId: string
email: string
displayName?: string
photoUrl?: string
}
export default defineEventHandler(async (event) => {
const body = await readBody(event)
const { idToken } = body
if (!idToken) {
throw createError({ statusCode: 400, message: 'Firebase ID token required' })
}
const config = useRuntimeConfig()
const apiKey = config.firebaseApiKey || config.public.firebaseApiKey
if (!apiKey) {
throw createError({ statusCode: 500, message: 'Firebase API key not configured' })
}
// Verify token via Firebase Auth REST API
const verifyRes = await $fetch<any>(
`https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=${apiKey}`,
{
method: 'POST',
body: { idToken }
}
).catch(() => null)
if (!verifyRes?.users?.[0]) {
throw createError({ statusCode: 401, message: 'Invalid Firebase token' })
}
const fbUser: FirebaseUser = verifyRes.users[0]
const email = fbUser.email
const existing = users.get(email)
let role = 'user'
let userId = fbUser.localId
if (existing) {
// Update existing
users.set(email, {
...existing,
id: userId,
email,
username: fbUser.displayName || email.split('@')[0]
})
role = existing.role || 'user'
} else {
// Create new user
users.set(email, {
id: userId,
email,
username: fbUser.displayName || email.split('@')[0],
password: 'firebase-managed',
role: 'user'
})
}
const token = generateToken({
id: userId,
email,
username: fbUser.displayName || email.split('@')[0],
role
})
return {
message: 'Google sign-in successful',
token,
user: {
id: userId,
email,
username: fbUser.displayName || email.split('@')[0],
role,
photoUrl: fbUser.photoUrl
}
}
})
+17
View File
@@ -0,0 +1,17 @@
import { verifyToken } from '~/server/utils/auth'
export default defineEventHandler(async (event) => {
const authHeader = getHeader(event, 'authorization')
const token = authHeader?.split(' ')[1]
if (!token) {
return { valid: false, error: 'No token provided' }
}
try {
const decoded = verifyToken(token)
return { valid: true, user: decoded }
} catch {
return { valid: false, error: 'Invalid token' }
}
})
+15
View File
@@ -0,0 +1,15 @@
import { requireAuth } from '~/server/utils/auth'
import { canvases } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
requireAuth(event)
const id = getRouterParam(event, 'id')
if (!canvases.has(id || '')) {
throw createError({ statusCode: 404, message: 'Canvas not found' })
}
canvases.delete(id || '')
return { success: true, message: 'Canvas deleted' }
})
+62
View File
@@ -0,0 +1,62 @@
import { requireAuth } from '~/server/utils/auth'
import { canvases, userGroups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id')
if (!id) {
throw createError({ statusCode: 400, message: 'Canvas ID is required' })
}
const canvas = canvases.get(id)
if (!canvas) {
throw createError({ statusCode: 404, message: 'Canvas not found' })
}
// Check if canvas is public
if (canvas.isPublic) {
return {
id: canvas.id,
name: canvas.name,
nodes: canvas.nodes,
edges: canvas.edges,
isPublic: true,
ownerId: canvas.ownerId
}
}
// For private canvases, require authentication and check permissions
const user = requireAuth(event)
// Check if user owns the canvas
if (canvas.ownerId === user.id) {
return {
id: canvas.id,
name: canvas.name,
nodes: canvas.nodes,
edges: canvas.edges,
isPublic: false,
ownerId: canvas.ownerId
}
}
// Check if user has access through group membership
if (canvas.groupId) {
const membership = Array.from(userGroups.values()).find(
m => m.userId === user.id && m.groupId === canvas.groupId
)
if (membership) {
return {
id: canvas.id,
name: canvas.name,
nodes: canvas.nodes,
edges: canvas.edges,
isPublic: false,
ownerId: canvas.ownerId,
groupId: canvas.groupId
}
}
}
throw createError({ statusCode: 403, message: 'Access denied' })
})
+24
View File
@@ -0,0 +1,24 @@
import { requireAuth } from '~/server/utils/auth'
import { canvases } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
requireAuth(event)
const id = getRouterParam(event, 'id')
const body = await readBody(event)
const existing = canvases.get(id || '')
if (!existing) {
throw createError({ statusCode: 404, message: 'Canvas not found' })
}
const updated = {
...existing,
...body,
id: existing.id,
updatedAt: new Date().toISOString()
}
canvases.set(id || '', updated)
return { canvas: updated }
})
@@ -0,0 +1,46 @@
import { requireAuth } from '~/server/utils/auth'
import { canvases } from '~/server/utils/db'
import type { CanvasData } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const id = getRouterParam(event, 'id')
if (!id) {
throw createError({ statusCode: 400, message: 'Canvas ID is required' })
}
const original = canvases.get(id)
if (!original) {
throw createError({ statusCode: 404, message: 'Canvas not found' })
}
// Check permissions
if (original.ownerId !== user.id && !original.isPublic) {
throw createError({ statusCode: 403, message: 'Access denied' })
}
const newId = `canvas-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
const duplicate: CanvasData = {
...original,
id: newId,
name: `${original.name} (Copy)`,
ownerId: user.id,
groupId: undefined, // Duplicates are personal
isPublic: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
nodes: original.nodes.map(node => ({
...node,
id: `${node.id}-copy-${Date.now()}`
})),
edges: original.edges.map(edge => ({
...edge,
id: `${edge.id}-copy-${Date.now()}`
}))
}
canvases.set(newId, duplicate)
return { canvas: duplicate }
})
+34
View File
@@ -0,0 +1,34 @@
import { requireAuth } from '~/server/utils/auth'
import { canvases, userGroups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
// Get all canvases the user can access
const userGroupIds = Array.from(userGroups.values())
.filter(membership => membership.userId === user.id)
.map(membership => membership.groupId)
const accessibleCanvases = Array.from(canvases.values()).filter(canvas => {
// User can see their own canvases
if (canvas.ownerId === user.id) return true
// User can see public canvases
if (canvas.isPublic) return true
// User can see group canvases they're a member of
if (canvas.groupId && userGroupIds.includes(canvas.groupId)) return true
return false
})
const canvasList = accessibleCanvases.map(canvas => ({
id: canvas.id,
name: canvas.name,
ownerId: canvas.ownerId,
createdAt: canvas.createdAt,
updatedAt: canvas.updatedAt,
isPublic: canvas.isPublic,
groupId: canvas.groupId,
nodeCount: canvas.nodes.length
}))
return { canvases: canvasList }
})
+36
View File
@@ -0,0 +1,36 @@
import { requireAuth } from '~/server/utils/auth'
import { canvases, userGroups } from '~/server/utils/db'
import type { CanvasData } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const body = await readBody(event)
const { name = 'New Canvas', nodes = [], edges = [], isPublic = false, groupId } = body
// Check group permissions if groupId is provided
if (groupId) {
const membership = Array.from(userGroups.values()).find(
m => m.userId === user.id && m.groupId === groupId
)
if (!membership) {
throw createError({ statusCode: 403, message: 'Not a member of this group' })
}
}
const id = `canvas-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
const canvas: CanvasData = {
id,
name,
nodes,
edges,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
ownerId: user.id,
groupId,
isPublic
}
canvases.set(id, canvas)
return { canvas }
})
+36
View File
@@ -0,0 +1,36 @@
import { requireAuth } from '~/server/utils/auth'
import { saveCanvasToGitea } from '~/server/utils/giteaApi'
import { canvases } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const body = await readBody(event)
const { canvasId, autoSync = true } = body
if (!canvasId) {
throw createError({ statusCode: 400, message: 'Canvas ID is required' })
}
// Check if canvas exists and user has access
const canvas = canvases.get(canvasId)
if (!canvas) {
throw createError({ statusCode: 404, message: 'Canvas not found' })
}
// Check permissions
if (canvas.ownerId !== user.id && !canvas.isPublic) {
throw createError({ statusCode: 403, message: 'Access denied' })
}
try {
const ok = await saveCanvasToGitea(canvasId, canvas, `Auto-sync: ${canvas.name}`)
return {
success: ok,
message: ok ? 'Canvas synchronized with Gitea' : 'Gitea sync failed',
autoSyncEnabled: autoSync
}
} catch (error) {
console.error('Failed to sync canvas to Gitea:', error)
throw createError({ statusCode: 500, message: 'Failed to sync canvas to Gitea' })
}
})
+56
View File
@@ -0,0 +1,56 @@
import { requireAuth } from '~/server/utils/auth'
import { saveCanvasToGitea, loadCanvasFromGitea } from '~/server/utils/giteaApi'
import { canvases } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const body = await readBody(event)
const { canvasId, action, commitMessage } = body
if (!canvasId || !action) {
throw createError({ statusCode: 400, message: 'Canvas ID and action are required' })
}
try {
switch (action) {
case 'init':
case 'sync': {
const canvas = canvases.get(canvasId)
if (!canvas) {
throw createError({ statusCode: 404, message: 'Canvas not found' })
}
if (canvas.ownerId !== user.id && !canvas.isPublic) {
throw createError({ statusCode: 403, message: 'Access denied' })
}
const ok = await saveCanvasToGitea(canvasId, canvas, commitMessage)
return {
success: ok,
message: ok
? `Canvas ${canvasId} saved to Gitea`
: `Failed to save canvas ${canvasId} to Gitea`
}
}
case 'load': {
const gitCanvas = await loadCanvasFromGitea(canvasId)
if (!gitCanvas) {
return { success: false, message: 'Canvas not found in Gitea', needsInit: true }
}
const existing = canvases.get(canvasId)
if (existing) {
canvases.set(canvasId, { ...existing, nodes: gitCanvas.nodes || [], edges: gitCanvas.edges || [] })
}
return { success: true, canvas: gitCanvas, message: `Canvas ${canvasId} loaded from Gitea` }
}
default:
throw createError({ statusCode: 400, message: 'Invalid action' })
}
} catch (error: any) {
console.error('Gitea sync error:', error)
throw createError({ statusCode: 500, message: error?.message || 'Gitea operation failed' })
}
})
+47
View File
@@ -0,0 +1,47 @@
import { requireAuth } from '~/server/utils/auth'
import { saveCanvasToGitea } from '~/server/utils/giteaApi'
import { canvases, userGroups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const body = await readBody(event)
const { canvasId, type } = body
if (!canvasId || !type) {
throw createError({ statusCode: 400, message: 'Canvas ID and repository type are required' })
}
// Check if canvas exists and user has access
const canvas = canvases.get(canvasId)
if (!canvas) {
throw createError({ statusCode: 404, message: 'Canvas not found' })
}
if (canvas.ownerId !== user.id && !canvas.isPublic) {
// Check group access
if (canvas.groupId) {
const membership = Array.from(userGroups.values()).find(
m => m.userId === user.id && m.groupId === canvas.groupId
)
if (!membership) {
throw createError({ statusCode: 403, message: 'Access denied' })
}
} else {
throw createError({ statusCode: 403, message: 'Access denied' })
}
}
try {
// Initial save to Gitea creates the canvas file in the repo
const ok = await saveCanvasToGitea(canvasId, canvas, `Init canvas ${canvasId}`)
return {
success: ok,
message: ok
? `Canvas ${canvasId} initialized in Gitea`
: `Failed to initialize canvas ${canvasId} in Gitea`
}
} catch (error) {
console.error('Failed to initialize canvas in Gitea:', error)
throw createError({ statusCode: 500, message: 'Failed to initialize canvas in Gitea' })
}
})
+23
View File
@@ -0,0 +1,23 @@
import { requireAuth } from '~/server/utils/auth'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const body = await readBody(event)
const { canvasId, action, commitMessage } = body
if (!canvasId || !action) {
throw createError({ statusCode: 400, message: 'Canvas ID and action are required' })
}
try {
// Git sync logic will be implemented here
// For now, return success response
return {
success: true,
message: `Git ${action} completed for canvas ${canvasId}`,
commitMessage: commitMessage || `Auto-sync canvas ${canvasId}`
}
} catch (error) {
throw createError({ statusCode: 500, message: 'Git sync failed' })
}
})
+45
View File
@@ -0,0 +1,45 @@
// Test endpoint: GET /api/git/test
// Verifies Gitea connection and repo access
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const { giteaUrl, giteaToken, giteaOrg, giteaMindmapRepo } = config
if (!giteaUrl || !giteaToken) {
return { success: false, message: 'GITEA_URL or GITEA_TOKEN not set in .env' }
}
try {
// Test 1: check repo exists
const repo = await $fetch<any>(`${giteaUrl}/api/v1/repos/${giteaOrg}/${giteaMindmapRepo}`, {
headers: { 'Authorization': `token ${giteaToken}` }
})
// Test 2: check/create canvases folder by listing contents
let folderExists = false
try {
await $fetch(`${giteaUrl}/api/v1/repos/${giteaOrg}/${giteaMindmapRepo}/contents/canvases`, {
headers: { 'Authorization': `token ${giteaToken}` }
})
folderExists = true
} catch {
folderExists = false
}
return {
success: true,
repo: repo.full_name,
private: repo.private,
folderExists,
message: folderExists
? '✅ Gitea connected, canvases/ folder exists'
: '✅ Gitea connected, canvases/ folder will be created on first save'
}
} catch (e: any) {
return {
success: false,
message: `❌ Gitea connection failed: ${e?.message || e}`,
hint: 'Check GITEA_URL, GITEA_TOKEN, GITEA_ORG, GITEA_MINDMAP_REPO in .env'
}
}
})
+20
View File
@@ -0,0 +1,20 @@
import { requireAuth } from '~/server/utils/auth'
import { groups, userGroups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const groupId = getRouterParam(event, 'id')!
const group = groups.get(groupId)
if (!group) throw createError({ statusCode: 404, message: 'Group not found' })
if (group.ownerId !== user.id && user.role !== 'admin') {
throw createError({ statusCode: 403, message: 'Only owner can delete group' })
}
groups.delete(groupId)
for (const [key] of userGroups) {
if (key.endsWith(`-${groupId}`)) userGroups.delete(key)
}
return { success: true }
})
+17
View File
@@ -0,0 +1,17 @@
import { requireAuth } from '~/server/utils/auth'
import { groups, userGroups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const groupId = getRouterParam(event, 'id')!
const group = groups.get(groupId)
if (!group) throw createError({ statusCode: 404, message: 'Group not found' })
if (!group.isPublic) throw createError({ statusCode: 403, message: 'Group is private' })
const key = `${user.id}-${groupId}`
if (userGroups.has(key)) return { message: 'Already a member' }
userGroups.set(key, { userId: user.id, groupId, role: 'member', joinedAt: new Date().toISOString() })
return { success: true, message: `Joined group "${group.name}"` }
})
+17
View File
@@ -0,0 +1,17 @@
import { requireAuth } from '~/server/utils/auth'
import { groups, userGroups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const groupId = getRouterParam(event, 'id')!
const group = groups.get(groupId)
if (!group) throw createError({ statusCode: 404, message: 'Group not found' })
if (group.ownerId === user.id) throw createError({ statusCode: 400, message: 'Owner cannot leave group. Delete it instead.' })
const key = `${user.id}-${groupId}`
if (!userGroups.has(key)) throw createError({ statusCode: 400, message: 'Not a member' })
userGroups.delete(key)
return { success: true, message: `Left group "${group.name}"` }
})
+8
View File
@@ -0,0 +1,8 @@
import { requireAuth } from '~/server/utils/auth'
import { groups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
requireAuth(event)
const allGroups = Array.from(groups.values()).filter(g => g.isPublic)
return { groups: allGroups }
})
+27
View File
@@ -0,0 +1,27 @@
import { requireAuth } from '~/server/utils/auth'
import { groups, userGroups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const body = await readBody(event)
const { name, description = '', isPublic = true } = body
if (!name?.trim()) {
throw createError({ statusCode: 400, message: 'Group name is required' })
}
const id = `group-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`
const now = new Date().toISOString()
const group = { id, name: name.trim(), description, isPublic, createdAt: now, updatedAt: now, ownerId: user.id }
groups.set(id, group)
userGroups.set(`${user.id}-${id}`, {
userId: user.id,
groupId: id,
role: 'admin',
joinedAt: now
})
return { group }
})
+26
View File
@@ -0,0 +1,26 @@
import { requireAuth } from '~/server/utils/auth'
import { nodes, addAchievement } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const id = getRouterParam(event, 'id')
const body = await readBody(event)
const existing = nodes.get(id || '') || { id, state: 'pending', assigned_to: user.id }
// Update state
const updated = { ...existing, ...body, updatedAt: new Date().toISOString() }
nodes.set(id || '', updated)
// Gamification: achievement on completion
if (body.state === 'completed' && existing.state !== 'completed') {
addAchievement(user.id, {
id: `completed-${id}`,
title: 'Задача выполнена',
description: `Нода ${id} завершена`,
icon: '✅'
})
}
return { node: updated }
})
+14
View File
@@ -0,0 +1,14 @@
import { requireAuth } from '~/server/utils/auth'
import { nodes } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
// RBAC: filter nodes by assigned_to or role
const allNodes = Array.from(nodes.values())
const filtered = user.role === 'admin'
? allNodes
: allNodes.filter((n: any) => n.assigned_to === user.id || n.assigned_to === 'all')
return { nodes: filtered }
})
+21
View File
@@ -0,0 +1,21 @@
import { requireRole } from '~/server/utils/auth'
import { pushSubscriptions } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
requireRole(event, 'admin')
const body = await readBody(event)
const { title, message, userId } = body
const targets = userId
? [pushSubscriptions.get(userId)].filter(Boolean)
: Array.from(pushSubscriptions.values())
// In production, use web-push library with VAPID keys
const results = targets.map((sub: any) => ({
userId: sub.userId,
sent: true,
notification: { title, message, timestamp: new Date().toISOString() }
}))
return { sent: results.length, results }
})
+16
View File
@@ -0,0 +1,16 @@
import { requireAuth } from '~/server/utils/auth'
import { pushSubscriptions } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
const body = await readBody(event)
const { subscription } = body
if (!subscription?.endpoint) {
throw createError({ statusCode: 400, message: 'Invalid subscription' })
}
pushSubscriptions.set(user.id, { userId: user.id, subscription, createdAt: new Date().toISOString() })
return { success: true }
})
+18
View File
@@ -0,0 +1,18 @@
import { requireAuth } from '~/server/utils/auth'
import { userGroups, groups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const user = requireAuth(event)
// Get all groups the user is a member of
const userGroupMemberships = Array.from(userGroups.values()).filter(
membership => membership.userId === user.id
)
const userGroupsData = userGroupMemberships.map(membership => {
const group = groups.get(membership.groupId)
return group ? { ...group, membershipRole: membership.role } : null
}).filter(Boolean)
return { groups: userGroupsData }
})
+17
View File
@@ -0,0 +1,17 @@
import { activities } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const userId = getRouterParam(event, 'id')
if (!userId) {
throw createError({ statusCode: 400, message: 'User ID is required' })
}
// Get user's recent activities
const userActivities = Array.from(activities.values())
.filter(activity => activity.userId === userId)
.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
.slice(0, 50) // Limit to 50 most recent
return { activities: userActivities }
})
+36
View File
@@ -0,0 +1,36 @@
import { canvases, userGroups } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const userId = getRouterParam(event, 'id')
if (!userId) {
throw createError({ statusCode: 400, message: 'User ID is required' })
}
// Get user's group memberships
const userGroupIds = Array.from(userGroups.values())
.filter(membership => membership.userId === userId)
.map(membership => membership.groupId)
// Get canvases owned by user or shared with user's groups
const userCanvases = Array.from(canvases.values()).filter(canvas => {
// User's own canvases
if (canvas.ownerId === userId) return true
// Group canvases
if (canvas.groupId && userGroupIds.includes(canvas.groupId)) return true
return false
})
const canvasList = userCanvases.map(canvas => ({
id: canvas.id,
name: canvas.name,
ownerId: canvas.ownerId,
createdAt: canvas.createdAt,
updatedAt: canvas.updatedAt,
isPublic: canvas.isPublic,
groupId: canvas.groupId,
nodeCount: canvas.nodes.length
}))
return { canvases: canvasList }
})
+40
View File
@@ -0,0 +1,40 @@
import { profiles, canvases, follows } from '~/server/utils/db'
export default defineEventHandler(async (event) => {
const userId = getRouterParam(event, 'id')
if (!userId) {
throw createError({ statusCode: 400, message: 'User ID is required' })
}
const profile = profiles.get(userId)
if (!profile) {
throw createError({ statusCode: 404, message: 'Profile not found' })
}
// Count user's canvases
const userCanvases = Array.from(canvases.values()).filter(
canvas => canvas.ownerId === userId
)
// Count followers and following
const followers = Array.from(follows.values()).filter(
follow => follow.followingId === userId
).length
const following = Array.from(follows.values()).filter(
follow => follow.followerId === userId
).length
// Update profile with current stats
const updatedProfile = {
...profile,
canvasCount: userCanvases.length,
followerCount: followers,
followingCount: following
}
profiles.set(userId, updatedProfile)
return { profile: updatedProfile }
})
+50
View File
@@ -0,0 +1,50 @@
import jwt from 'jsonwebtoken'
import { H3Event, createError } from 'h3'
const JWT_SECRET = process.env.NUXT_JWT_SECRET || 'your-super-secret-jwt-key'
export interface AuthUser {
id: string
email: string
username: string
role?: string
}
export function generateToken(user: AuthUser): string {
return jwt.sign(
{ id: user.id, email: user.email, username: user.username, role: user.role || 'user' },
JWT_SECRET,
{ expiresIn: '7d' }
)
}
export function verifyToken(token: string): AuthUser {
return jwt.verify(token, JWT_SECRET) as AuthUser
}
export function getAuthUser(event: H3Event): AuthUser | null {
const authHeader = getHeader(event, 'authorization')
const token = authHeader?.split(' ')[1]
if (!token) return null
try {
return verifyToken(token)
} catch {
return null
}
}
export function requireAuth(event: H3Event): AuthUser {
const user = getAuthUser(event)
if (!user) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
return user
}
export function requireRole(event: H3Event, role: string): AuthUser {
const user = requireAuth(event)
if (user.role !== role) {
throw createError({ statusCode: 403, message: 'Forbidden' })
}
return user
}
+403
View File
@@ -0,0 +1,403 @@
import type { AuthUser } from './auth'
export interface CanvasNode {
id: string
type: string
x: number
y: number
width: number
height: number
text?: string
file?: string
frontmatter?: Record<string, any>
state?: 'pending' | 'in_progress' | 'completed'
label?: string
assigned_to?: string
alarm?: string
script_id?: string
prompt?: string
url?: string
method?: string
repo?: string
branch?: string
message?: string
style?: Record<string, string>
}
export interface CanvasEdge {
id: string
fromNode: string
fromSide: string
toNode: string
toSide: string
}
export interface CanvasData {
id: string
name: string
nodes: CanvasNode[]
edges: CanvasEdge[]
createdAt: string
updatedAt: string
ownerId: string
groupId?: string
isPublic?: boolean
}
export interface UserGroup {
userId: string
groupId: string
role: 'admin' | 'member' | 'viewer'
joinedAt: string
}
export interface Group {
id: string
name: string
description: string
isPublic: boolean
createdAt: string
updatedAt: string
ownerId: string
}
export interface Profile {
userId: string
displayName: string
bio: string
avatar: string
joinedAt: string
canvasCount: number
followerCount: number
followingCount: number
}
export interface Activity {
id: string
userId: string
action: string
targetId: string
targetType: string
timestamp: string
metadata?: Record<string, any>
}
// In-memory stores
export const users = new Map<string, { password: string } & AuthUser>()
export const nodes = new Map<string, any>()
export const achievements = new Map<string, any[]>()
export const pushSubscriptions = new Map<string, any>()
export const canvases = new Map<string, CanvasData>()
export const userGroups = new Map<string, UserGroup>()
export const groups = new Map<string, Group>()
export const profiles = new Map<string, Profile>()
export const activities = new Map<string, Activity>()
export const follows = new Map<string, { followerId: string, followingId: string, since: string }>()
// Seed admins
const seedAdmins = [
{ id: '1', email: 'admin@xflow.local', username: 'admin' },
{ id: '2', email: 'almalexyz@gmail.com', username: 'almalexyz' },
{ id: '3', email: 'ormix16@gmail.com', username: 'ormix16' }
]
for (const admin of seedAdmins) {
users.set(admin.email, {
...admin,
password: 'admin123',
role: 'admin'
})
// Create profiles for admins
profiles.set(admin.id, {
userId: admin.id,
displayName: admin.username,
bio: 'XFlow Administrator',
avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${admin.id}`,
joinedAt: new Date().toISOString(),
canvasCount: 0,
followerCount: 0,
followingCount: 0
})
}
// Create demo groups
const demoGroups: Group[] = [
{ id: 'group-1', name: 'XFlow Team', description: 'Core development team', isPublic: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ownerId: '1' },
{ id: 'group-2', name: 'Beta Testers', description: 'Early access users', isPublic: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ownerId: '1' },
{ id: 'group-3', name: 'AI Research', description: 'AI/LLM integration research', isPublic: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ownerId: '2' }
]
demoGroups.forEach(group => {
groups.set(group.id, group)
// Add admins to groups
seedAdmins.forEach(admin => {
userGroups.set(`${admin.id}-${group.id}`, {
userId: admin.id,
groupId: group.id,
role: admin.id === '1' ? 'admin' : 'member',
joinedAt: new Date().toISOString()
})
})
})
// Seed comprehensive XFlow project mind map
const xflowProjectCanvas: CanvasData = {
id: 'xflow-project',
name: 'Обзор Проекта XFlow',
nodes: [
// Core Architecture
{
id: 'arch-1',
type: 'text',
x: 100,
y: 100,
width: 320,
height: 180,
text: '# 🏗️ Основная Архитектура\n\n- **Nuxt 3** - Vue 3 фреймворк\n- **TailwindCSS** - Стилизация\n- **Vue Flow** - Движок канваса\n- **Firebase** - Аутентификация\n- **In-memory DB** - Хранение данных\n- **PWA** - Progressive Web App',
style: { background: '#1e293b', border: '#3b82f6' }
},
// Frontend Components
{
id: 'fe-1',
type: 'text',
x: 500,
y: 50,
width: 280,
height: 160,
text: '# 🎨 Фронтенд\n\n- **FlowEditor.vue** - Основной редактор\n- **FlowNodeRenderer.vue** - Отображение узлов\n- **CanvasViewer.vue** - Устаревший просмотр\n- **Админ Панель** - Управление интерфейсом\n- **Система Аутентификации** - Вход через Google',
style: { background: '#1e293b', border: '#10b981' }
},
// Backend APIs
{
id: 'be-1',
type: 'text',
x: 500,
y: 250,
width: 280,
height: 160,
text: '# ⚙️ Backend API\n\n- `/api/canvas/*` - CRUD операций с канвасами\n- `/api/nodes/*` - Управление узлами\n- `/api/auth/*` - Аутентификация\n- `/api/admin/*` - Административные операции\n- `/api/push/*` - Уведомления',
style: { background: '#1e293b', border: '#f59e0b' }
},
// Node Types
{
id: 'nodes-1',
type: 'text',
x: 100,
y: 320,
width: 320,
height: 200,
text: '# 📦 Типы Узлов\n\n- **Текстовая Заметка** - Markdown контент\n- **Ссылка на Файл** - Ссылки на файлы\n- **Узел Задачи** - Отслеживание состояния\n- **AI/LLM Узел** - AI обработка\n- **Webhook Узел** - HTTP триггеры\n- **Git Sync Узел** - Контроль версий',
style: { background: '#1e293b', border: '#8b5cf6' }
},
// Features
{
id: 'feat-1',
type: 'text',
x: 850,
y: 150,
width: 300,
height: 220,
text: '# ✨ Ключевые Функции\n\n- **Редактор в стиле Node-RED**\n - Палитра сбоку\n - Панель свойств\n - Drag & drop\n - Соединения проводами\n\n- **Совместимость с Obsidian**\n - Экспорт в .canvas формат\n - Импорт существующих карт\n - Поддержка Markdown\n\n- **Социальные Функции**\n - Группы пользователей\n - Общие канвасы\n - Лента активности',
style: { background: '#1e293b', border: '#ef4444' }
},
// Tech Stack
{
id: 'tech-1',
type: 'text',
x: 100,
y: 560,
width: 320,
height: 180,
text: '# 🛠️ Технологический Стек\n\n```json\n{\n "frontend": "Vue 3 + Nuxt 3",\n "styling": "TailwindCSS",\n "canvas": "Vue Flow",\n "auth": "Firebase Google",\n "storage": "In-memory",\n "pwa": "@vite-pwa/nuxt"\n}\n```',
style: { background: '#1e293b', border: '#06b6d4' }
},
// Future Plans
{
id: 'future-1',
type: 'text',
x: 500,
y: 450,
width: 280,
height: 180,
text: '# 🚀 Будущее Развитие\n\n- **Git Интеграция**\n - Commit/push/pull карт\n - История версий\n - Управление ветками\n\n- **AI Интеграция**\n - OpenClaw агенты\n - Автоматизация LLM узлов\n - Умные предложения\n\n- **Социальная Сеть**\n - Профили пользователей\n - Система подписок\n - Ленты активности',
style: { background: '#1e293b', border: '#ec4899' }
},
// Database Schema
{
id: 'db-1',
type: 'file',
x: 850,
y: 400,
width: 300,
height: 160,
file: 'app/server/utils/db.ts',
text: '## Схема Базы Данных\n\n- `users` - Пользовательские аккаунты\n- `canvases` - Ментальные карты\n- `nodes` - Отдельные узлы\n- `groups` - Группы пользователей\n- `profiles` - Профили пользователей\n- `activities` - Лента активности',
style: { background: '#1e293b', border: '#84cc16' }
},
// Deployment
{
id: 'deploy-1',
type: 'text',
x: 850,
y: 590,
width: 300,
height: 140,
text: '# 🚀 Развертывание\n\n- **Docker Compose**\n- **Nginx** - Обратный прокси\n- **Gitea** - Git сервер\n- **PostgreSQL** - База данных\n- **Certbot** - SSL сертификаты',
style: { background: '#1e293b', border: '#f97316' }
},
// Social Features
{
id: 'social-1',
type: 'text',
x: 100,
y: 780,
width: 320,
height: 160,
text: '# 👥 Social Network\n\n- **User Profiles**\n - Avatar & bio\n - Canvas statistics\n - Following/followers\n\n- **Groups System**\n - Public/private groups\n - Role-based permissions\n - Shared canvases',
style: { background: '#1e293b', border: '#a855f7' }
},
// File Structure
{
id: 'files-1',
type: 'file',
x: 500,
y: 660,
width: 280,
height: 140,
file: 'project-structure.md',
text: '## Project Structure\n\n```\napp/\n├── components/\n│ ├── FlowEditor.vue\n│ └── FlowNodeRenderer.vue\n├── pages/\n│ ├── canvas.vue\n│ └── admin.vue\n└── server/api/\n```',
style: { background: '#1e293b', border: '#0ea5e9' }
}
],
edges: [
{ id: 'e1', fromNode: 'arch-1', fromSide: 'right', toNode: 'fe-1', toSide: 'left' },
{ id: 'e2', fromNode: 'arch-1', fromSide: 'right', toNode: 'be-1', toSide: 'left' },
{ id: 'e3', fromNode: 'arch-1', fromSide: 'bottom', toNode: 'nodes-1', toSide: 'top' },
{ id: 'e4', fromNode: 'fe-1', fromSide: 'right', toNode: 'feat-1', toSide: 'left' },
{ id: 'e5', fromNode: 'be-1', fromSide: 'right', toNode: 'feat-1', toSide: 'left' },
{ id: 'e6', fromNode: 'nodes-1', fromSide: 'bottom', toNode: 'tech-1', toSide: 'top' },
{ id: 'e7', fromNode: 'be-1', fromSide: 'bottom', toNode: 'future-1', toSide: 'top' },
{ id: 'e8', fromNode: 'feat-1', fromSide: 'bottom', toNode: 'db-1', toSide: 'top' },
{ id: 'e9', fromNode: 'db-1', fromSide: 'bottom', toNode: 'deploy-1', toSide: 'top' },
{ id: 'e10', fromNode: 'tech-1', fromSide: 'right', toNode: 'future-1', toSide: 'left' },
{ id: 'e11', fromNode: 'tech-1', fromSide: 'bottom', toNode: 'social-1', toSide: 'top' },
{ id: 'e12', fromNode: 'future-1', fromSide: 'bottom', toNode: 'files-1', toSide: 'top' },
{ id: 'e13', fromNode: 'social-1', fromSide: 'right', toNode: 'files-1', toSide: 'left' }
],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
ownerId: '1',
isPublic: true
}
canvases.set('xflow-project', xflowProjectCanvas)
// Create shared canvases for groups
const sharedCanvases = [
{ id: 'team-roadmap', name: 'Team Roadmap 2025', groupId: 'group-1', ownerId: '1' },
{ id: 'beta-feedback', name: 'Beta Feedback Map', groupId: 'group-2', ownerId: '1' },
{ id: 'ai-research', name: 'AI Integration Ideas', groupId: 'group-3', ownerId: '2' }
]
sharedCanvases.forEach(canvas => {
const canvasData: CanvasData = {
id: canvas.id,
name: canvas.name,
nodes: [
{
id: `${canvas.id}-node-1`,
type: 'text',
x: 200,
y: 200,
width: 300,
height: 150,
text: `# ${canvas.name}\n\nThis is a shared canvas for the group.\n\nStart adding your ideas!`,
style: { background: '#1e293b', border: '#3b82f6' }
}
],
edges: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
ownerId: canvas.ownerId,
groupId: canvas.groupId,
isPublic: true
}
canvases.set(canvas.id, canvasData)
})
// Add demo activities
const demoActivities: Activity[] = [
{ id: 'activity-1', userId: '1', action: 'created_canvas', targetId: 'xflow-project', targetType: 'canvas', timestamp: new Date().toISOString() },
{ id: 'activity-2', userId: '2', action: 'joined_group', targetId: 'group-1', targetType: 'group', timestamp: new Date().toISOString() },
{ id: 'activity-3', userId: '3', action: 'created_canvas', targetId: 'ai-research', targetType: 'canvas', timestamp: new Date().toISOString() },
{ id: 'activity-4', userId: '1', action: 'followed_user', targetId: '2', targetType: 'user', timestamp: new Date().toISOString() }
]
demoActivities.forEach(activity => {
activities.set(activity.id, activity)
})
// Add demo follows
follows.set('1-2', { followerId: '1', followingId: '2', since: new Date().toISOString() })
follows.set('2-3', { followerId: '2', followingId: '3', since: new Date().toISOString() })
// Keep the old demo canvas for backward compatibility
canvases.set('demo', {
id: 'demo',
name: 'Demo Canvas',
nodes: [
{
id: 'node-1',
type: 'text',
x: 0,
y: 0,
width: 300,
height: 200,
text: '# Welcome\n\nЭто демо-нода с **Markdown** поддержкой.',
state: 'pending',
style: { background: '#1e293b', border: '#334155' }
},
{
id: 'node-2',
type: 'file',
x: 400,
y: 0,
width: 300,
height: 200,
file: 'tasks.md',
frontmatter: { alarm: '2025-04-24T09:00:00Z', script_id: 'notify', assigned_to: 'user' },
state: 'pending',
style: { background: '#1e293b', border: '#334155' }
},
{
id: 'node-3',
type: 'text',
x: 200,
y: 300,
width: 300,
height: 150,
text: '### Завершенная задача\n- [x] Настроить PWA',
state: 'completed',
style: { background: '#064e3b', border: '#059669' }
}
],
edges: [
{ id: 'edge-1', fromNode: 'node-1', fromSide: 'right', toNode: 'node-2', toSide: 'left' },
{ id: 'edge-2', fromNode: 'node-2', fromSide: 'bottom', toNode: 'node-3', toSide: 'top' }
],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
ownerId: '1'
})
export function getUserAchievements(userId: string) {
return achievements.get(userId) || []
}
export function addAchievement(userId: string, achievement: any) {
const list = achievements.get(userId) || []
list.push({ ...achievement, unlockedAt: new Date().toISOString() })
achievements.set(userId, list)
}
+2
View File
@@ -0,0 +1,2 @@
// Deprecated: replaced by giteaApi.ts
export { }
+101
View File
@@ -0,0 +1,101 @@
// Gitea API integration for XFlow canvas sync
// Uses Gitea REST API to store mind maps in MMAVTEX repo
interface GiteaFile {
content: string // base64
sha?: string
}
const getConfig = () => {
const config = useRuntimeConfig()
return {
url: config.giteaUrl,
token: config.giteaToken,
org: config.giteaOrg,
mindmapRepo: config.giteaMindmapRepo,
projectRepo: config.giteaProjectRepo,
}
}
const headers = (token: string) => ({
'Authorization': `token ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
})
// Get file from Gitea (returns null if not found)
export async function giteaGetFile(path: string, repo?: string): Promise<GiteaFile | null> {
const { url, token, org, mindmapRepo } = getConfig()
const repoName = repo || mindmapRepo
try {
const res = await $fetch<any>(`${url}/api/v1/repos/${org}/${repoName}/contents/${path}`, {
headers: headers(token)
})
return { content: res.content, sha: res.sha }
} catch {
return null
}
}
// Create or update file in Gitea
export async function giteaPutFile(path: string, content: string, message: string, sha?: string, repo?: string): Promise<boolean> {
const { url, token, org, mindmapRepo } = getConfig()
const repoName = repo || mindmapRepo
const encoded = Buffer.from(content).toString('base64')
try {
await $fetch(`${url}/api/v1/repos/${org}/${repoName}/contents/${path}`, {
method: sha ? 'PUT' : 'POST',
headers: headers(token),
body: {
message,
content: encoded,
...(sha ? { sha } : {})
}
})
return true
} catch (e) {
console.error('Gitea putFile error:', e)
return false
}
}
// Save canvas to Gitea MMAVTEX repo
export async function saveCanvasToGitea(canvasId: string, canvasData: any, commitMessage?: string): Promise<boolean> {
const path = `canvases/${canvasId}.canvas`
const content = JSON.stringify(canvasData, null, 2)
const message = commitMessage || `Update canvas ${canvasId} at ${new Date().toLocaleString('ru-RU')}`
// Get existing file SHA if exists (required for update)
const existing = await giteaGetFile(path)
return giteaPutFile(path, content, message, existing?.sha)
}
// Load canvas from Gitea
export async function loadCanvasFromGitea(canvasId: string): Promise<any | null> {
const path = `canvases/${canvasId}.canvas`
const file = await giteaGetFile(path)
if (!file) return null
try {
const decoded = Buffer.from(file.content, 'base64').toString('utf-8')
return JSON.parse(decoded)
} catch {
return null
}
}
// List all canvases in Gitea
export async function listCanvasesFromGitea(): Promise<string[]> {
const { url, token, org, mindmapRepo } = getConfig()
try {
const res = await $fetch<any[]>(`${url}/api/v1/repos/${org}/${mindmapRepo}/contents/canvases`, {
headers: headers(token)
})
return res
.filter((f: any) => f.name.endsWith('.canvas'))
.map((f: any) => f.name.replace('.canvas', ''))
} catch {
return []
}
}
+9
View File
@@ -0,0 +1,9 @@
import { PrismaClient } from '.prisma/client'
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }
export const prisma = globalForPrisma.prisma ?? new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error']
})
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
+264
View File
@@ -0,0 +1,264 @@
// Real Git integration utilities for XFlow with Gitea
// This handles actual Git operations, caching, and change tracking
import { execSync } from 'child_process'
import { writeFileSync, readFileSync, existsSync, mkdirSync } from 'fs'
import { join } from 'path'
export interface GitRepository {
id: string
name: string
owner: string
url: string
cloneUrl: string
isPrivate: boolean
type: 'personal' | 'group'
ownerId: string
localPath: string
createdAt: string
updatedAt: string
}
export interface GitCommit {
id: string
message: string
author: string
timestamp: string
canvasId: string
changes: {
added: string[]
modified: string[]
deleted: string[]
}
}
// Cache for Git repositories
const gitCache = new Map<string, GitRepository>()
const canvasCache = new Map<string, any>()
// Base path for local Git repositories
const GIT_BASE_PATH = process.env.GIT_BASE_PATH || '/tmp/xflow-git'
// Ensure base directory exists
if (!existsSync(GIT_BASE_PATH)) {
mkdirSync(GIT_BASE_PATH, { recursive: true })
}
// Create a new Git repository for a user
export async function createPersonalRepository(userId: string, canvasId: string): Promise<GitRepository> {
const repoId = `repo-${userId}-${canvasId}-${Date.now()}`
const repoName = `canvas-${canvasId}`
const localPath = join(GIT_BASE_PATH, userId, repoName)
// Create local directory
if (!existsSync(localPath)) {
mkdirSync(localPath, { recursive: true })
}
// Initialize Git repository
try {
execSync('git init', { cwd: localPath })
execSync('git config user.name "XFlow System"', { cwd: localPath })
execSync('git config user.email "xflow@system.local"', { cwd: localPath })
} catch (error) {
console.error('Failed to initialize Git repository:', error)
}
const repository: GitRepository = {
id: repoId,
name: repoName,
owner: userId,
url: `https://gitea.example.com/${userId}/${repoName}`,
cloneUrl: `https://gitea.example.com/${userId}/${repoName}.git`,
isPrivate: true,
type: 'personal',
ownerId: userId,
localPath,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
}
gitCache.set(repoId, repository)
// Initialize with initial commit
await initializeRepository(repository, canvasId)
return repository
}
// Initialize repository with initial canvas data
async function initializeRepository(repository: GitRepository, canvasId: string): Promise<void> {
const canvasFile = join(repository.localPath, `${canvasId}.canvas`)
// Create initial canvas file
const initialCanvas = {
nodes: [],
edges: []
}
writeFileSync(canvasFile, JSON.stringify(initialCanvas, null, 2))
// Create initial commit
try {
execSync('git add .', { cwd: repository.localPath })
execSync(`git commit -m "Initial commit for canvas ${canvasId}"`, { cwd: repository.localPath })
} catch (error) {
console.error('Failed to create initial commit:', error)
}
}
// Sync canvas changes to Git repository
export async function syncCanvasToGit(
canvasId: string,
canvasData: any,
commitMessage?: string
): Promise<GitCommit> {
// Find repository for this canvas
const repository = Array.from(gitCache.values())
.find(repo => repo.name.includes(canvasId))
if (!repository) {
throw new Error(`No Git repository found for canvas ${canvasId}`)
}
const canvasFile = join(repository.localPath, `${canvasId}.canvas`)
// Check if file has changed
const currentContent = JSON.stringify(canvasData, null, 2)
let hasChanges = true
if (existsSync(canvasFile)) {
const existingContent = readFileSync(canvasFile, 'utf-8')
hasChanges = existingContent !== currentContent
}
if (!hasChanges) {
// Return latest commit if no changes
const commits = getRepositoryHistory(repository)
return commits[0] || {
id: 'no-changes',
message: 'No changes detected',
author: 'system',
timestamp: new Date().toISOString(),
canvasId,
changes: { added: [], modified: [], deleted: [] }
}
}
// Write canvas data
writeFileSync(canvasFile, currentContent)
// Commit changes
const message = commitMessage || `Update canvas ${canvasId}`
try {
execSync('git add .', { cwd: repository.localPath })
execSync(`git commit -m "${message}"`, { cwd: repository.localPath })
} catch (error) {
console.error('Failed to commit changes:', error)
}
// Update cache
repository.updatedAt = new Date().toISOString()
canvasCache.set(canvasId, canvasData)
// Get commit hash
let commitHash = 'unknown'
try {
commitHash = execSync('git rev-parse HEAD', { cwd: repository.localPath, encoding: 'utf-8' }).trim()
} catch (error) {
console.error('Failed to get commit hash:', error)
}
const commit: GitCommit = {
id: commitHash,
message,
author: repository.owner,
timestamp: new Date().toISOString(),
canvasId,
changes: {
added: existsSync(canvasFile) ? [`${canvasId}.canvas`] : [],
modified: [`${canvasId}.canvas`],
deleted: []
}
}
return commit
}
// Load canvas from Git repository
export async function loadCanvasFromGit(canvasId: string): Promise<any> {
// Check cache first
if (canvasCache.has(canvasId)) {
return canvasCache.get(canvasId)
}
// Find repository for this canvas
const repository = Array.from(gitCache.values())
.find(repo => repo.name.includes(canvasId))
if (!repository) {
throw new Error(`No Git repository found for canvas ${canvasId}`)
}
const canvasFile = join(repository.localPath, `${canvasId}.canvas`)
if (!existsSync(canvasFile)) {
throw new Error(`Canvas file not found: ${canvasFile}`)
}
const canvasData = JSON.parse(readFileSync(canvasFile, 'utf-8'))
// Cache the data
canvasCache.set(canvasId, canvasData)
return canvasData
}
// Get repository for a canvas
export function getCanvasRepository(canvasId: string): GitRepository | null {
return Array.from(gitCache.values())
.find(repo => repo.name.includes(canvasId)) || null
}
// Get commit history for a repository
export function getRepositoryHistory(repository: GitRepository): GitCommit[] {
try {
const log = execSync('git log --pretty=format:"%H|%s|%an|%ad" --date=iso', {
cwd: repository.localPath,
encoding: 'utf-8'
})
return log.split('\n')
.filter(line => line.trim())
.map(line => {
const [id, message, author, timestamp] = line.split('|')
return {
id,
message,
author,
timestamp,
canvasId: repository.name.replace('canvas-', ''),
changes: { added: [], modified: [], deleted: [] }
}
})
} catch (error) {
console.error('Failed to get repository history:', error)
return []
}
}
// Check if canvas has unsaved changes
export function hasUnsavedChanges(canvasId: string, currentData: any): boolean {
if (!canvasCache.has(canvasId)) {
return true // No cached data, assume changes
}
const cachedData = canvasCache.get(canvasId)
return JSON.stringify(cachedData) !== JSON.stringify(currentData)
}
// Clear cache for a canvas
export function clearCanvasCache(canvasId: string): void {
canvasCache.delete(canvasId)
}