diff --git a/.env.example b/.env.example index 97094f3..8396519 100644 --- a/.env.example +++ b/.env.example @@ -13,7 +13,7 @@ HETZNER_API_TOKEN= HETZNER_SNAPSHOT_IMAGE_ID= # Optional builder defaults used by provider profile. -HETZNER_BUILDER_BASE_IMAGE=ubuntu-24.04 +HETZNER_BUILDER_BASE_IMAGE=docker-ce HETZNER_BUILDER_SERVER_TYPE=cx23 HETZNER_BUILDER_LOCATION=nbg1 diff --git a/.gitignore b/.gitignore index afd1a1c..7a4de30 100644 --- a/.gitignore +++ b/.gitignore @@ -54,3 +54,7 @@ generated/ tsconfig.tsbuildinfo .vercel .env*.local + +.vscode/ + +next-env.d.ts diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 59f219f..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "editor.defaultFormatter": "esbenp.prettier-vscode", - "editor.formatOnPaste": true, - "editor.formatOnSave": true, - "emmet.showExpandedAbbreviation": "never", - "js/ts.tsdk.path": "node_modules/typescript/lib", - "js/ts.tsdk.promptToUseWorkspaceVersion": true, - "[css]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[graphql]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[handlebars]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[html]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[javascript]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[javascriptreact]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[json]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[jsonc]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[less]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[markdown]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[scss]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[typescript]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[typescriptreact]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[vue-html]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[vue]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "[yaml]": { - "editor.defaultFormatter": "oxc.oxc-vscode" - }, - "editor.codeActionsOnSave": { - "source.fixAll.oxc": "explicit" - } -} diff --git a/agent b/agent index b8715dc..2f4d61a 160000 --- a/agent +++ b/agent @@ -1 +1 @@ -Subproject commit b8715dc29793f9eddcac88717ffb2ecf5b152efb +Subproject commit 2f4d61a1f0f7bada99b91cb471b76f65864ea401 diff --git a/app/admin/actions/create-server.ts b/app/admin/actions/create-server.ts index 1af1748..76d4a3d 100644 --- a/app/admin/actions/create-server.ts +++ b/app/admin/actions/create-server.ts @@ -6,17 +6,16 @@ import type { Prisma } from "@prisma/client"; import { humanId } from "human-id"; import { revalidatePath } from "next/cache"; import { ulid } from "ulid"; -import { start } from "workflow/api"; import { z } from "zod"; import { games, validateSettings } from "@/games"; import { logEvent } from "@/lib/audit"; import { prisma } from "@/lib/db"; import { SNAPSHOT_ENVIRONMENT } from "@/lib/env"; +import { sendServerProvisionInitiatedEmail } from "@/lib/mail"; import { getProviderForUserWithImage } from "@/lib/providers"; import type { Catalog } from "@/lib/providers/types"; import { requireSuperAdmin } from "@/lib/session"; -import { provisionServer } from "@/lib/workflows/provision-server"; const adminCreateServerSchema = z.object({ game: z.enum(games.map((g) => g.id) as [string, ...string[]]), @@ -112,7 +111,7 @@ export const adminCreateServer = async ( location: parsed.data.location, name: parsed.data.name, observedState: "pending", - phase: "queued", + phase: "pending", rconPassword, serverType: parsed.data.serverType, settings: settings as Prisma.InputJsonValue, @@ -197,7 +196,16 @@ export const adminCreateServer = async ( } } - await start(provisionServer, [{ serverId: server.id }]); + // Email user to approve and trigger provisioning + void sendServerProvisionInitiatedEmail({ + approveUrl: `${process.env.BETTER_AUTH_URL}/dashboard/${server.id}/approve-provision`, + game: game.name, + location: parsed.data.location, + serverName: parsed.data.name, + serverType: parsed.data.serverType, + toEmail: targetUser.email, + userName: targetUser.name ?? targetUser.email, + }); await logEvent({ action: "admin.server.create", diff --git a/app/admin/components/admin-sidebar-enhanced.tsx b/app/admin/components/admin-sidebar-enhanced.tsx index 83de6fb..9c34092 100644 --- a/app/admin/components/admin-sidebar-enhanced.tsx +++ b/app/admin/components/admin-sidebar-enhanced.tsx @@ -71,7 +71,7 @@ export const AdminSidebarEnhanced = ({ user={user} headerTitle="NodeByte" headerSubtitle="Admin Panel" - headerHref="/admin" + headerHref="/" showAdminLink={false} onSignOut={handleSignOut} > diff --git a/app/admin/components/admin-sidebar.tsx b/app/admin/components/admin-sidebar.tsx index 4fc2d3c..095503d 100644 --- a/app/admin/components/admin-sidebar.tsx +++ b/app/admin/components/admin-sidebar.tsx @@ -109,7 +109,7 @@ export const AdminSidebar = ({ user }: { user: AdminSidebarUser }) => { diff --git a/app/admin/servers/actions/delete.ts b/app/admin/servers/actions/delete.ts index 3cfc6d4..0dc8d8e 100644 --- a/app/admin/servers/actions/delete.ts +++ b/app/admin/servers/actions/delete.ts @@ -4,6 +4,7 @@ import { revalidatePath } from "next/cache"; import { z } from "zod"; import { prisma } from "@/lib/db"; +import { sendServerDeletedEmail } from "@/lib/mail"; import { getProviderForUser } from "@/lib/providers"; import { requireAdmin } from "@/lib/session"; @@ -31,7 +32,7 @@ export const adminDeleteServer = async ( } const server = await prisma.server.findFirst({ - include: { user: { select: { id: true } } }, + include: { user: { select: { email: true, id: true, name: true } } }, where: { id: parsed.data.serverId }, }); @@ -68,6 +69,13 @@ export const adminDeleteServer = async ( where: { serverId: parsed.data.serverId }, }); + // Notify the server owner (fire-and-forget) + void sendServerDeletedEmail({ + serverName: server.name, + toEmail: server.user.email, + userName: server.user.name, + }); + revalidatePath("/admin/servers"); return { ok: true }; } catch (error) { diff --git a/app/api/agent/heartbeat/route.ts b/app/api/agent/heartbeat/route.ts index 23e29be..8de04a4 100644 --- a/app/api/agent/heartbeat/route.ts +++ b/app/api/agent/heartbeat/route.ts @@ -28,8 +28,19 @@ export const POST = async (request: Request) => { await prisma.agent.update({ data: { + cpuPercent: parsed.data.cpuPercent ?? undefined, + diskTotalBytes: parsed.data.diskTotalBytes ?? undefined, + diskUsedBytes: parsed.data.diskUsedBytes ?? undefined, lastCommandId: parsed.data.lastCommandId ?? undefined, lastHeartbeatAt: new Date(), + maxPlayers: parsed.data.maxPlayers ?? undefined, + memTotalBytes: parsed.data.memTotalBytes ?? undefined, + memUsedBytes: parsed.data.memUsedBytes ?? undefined, + networkInBps: parsed.data.networkInBps ?? undefined, + networkOutBps: parsed.data.networkOutBps ?? undefined, + playerCount: parsed.data.playerCount ?? undefined, + tps: parsed.data.tps ?? undefined, + uptimeSeconds: parsed.data.uptimeSeconds, }, where: { id: verified.agentId }, }); diff --git a/app/api/servers/[id]/files/content/route.ts b/app/api/servers/[id]/files/content/route.ts new file mode 100644 index 0000000..85cf6e9 --- /dev/null +++ b/app/api/servers/[id]/files/content/route.ts @@ -0,0 +1,128 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; + +import { enqueueCommand, waitForCommand } from "@/lib/agent/commands"; +import { prisma } from "@/lib/db"; +import { requireUser } from "@/lib/session"; +import { filesReadResultSchema } from "@/protocol"; + +export const runtime = "nodejs"; +export const maxDuration = 120; + +const MAX_CONTENT_CHARS = 2_000_000; + +const writeBodySchema = z.object({ + content: z.string().max(MAX_CONTENT_CHARS), + encoding: z.enum(["utf-8", "base64"]).default("utf-8"), + path: z.string().min(1), +}); + +const requireOwnedServer = async (id: string) => { + const user = await requireUser(); + const server = await prisma.server.findFirst({ + where: { deletedAt: null, id, userId: user.id }, + }); + + if (!server) { + return { + error: NextResponse.json({ error: "Not Found" }, { status: 404 }), + } as const; + } + + return { server } as const; +}; + +export const GET = async ( + request: Request, + context: { params: Promise<{ id: string }> } +) => { + const { id } = await context.params; + const owned = await requireOwnedServer(id); + + if ("error" in owned) { + return owned.error; + } + + const url = new URL(request.url); + const path = url.searchParams.get("path"); + + if (!path) { + return NextResponse.json({ error: "Path Required" }, { status: 400 }); + } + + const command = await enqueueCommand({ + payload: { path }, + serverId: id, + type: "FILES_READ", + }); + + const outcome = await waitForCommand(command.id, 110_000); + + if (outcome.status === "timeout") { + return NextResponse.json( + { error: "Agent did not respond. Is the server online?" }, + { status: 504 } + ); + } + + if (outcome.status === "failed") { + return NextResponse.json( + { error: outcome.error ?? "Read Failed" }, + { status: 500 } + ); + } + + const parsed = filesReadResultSchema.safeParse(outcome.result); + + if (!parsed.success) { + return NextResponse.json({ error: "Invalid result" }, { status: 500 }); + } + + return NextResponse.json(parsed.data); +}; + +export const PUT = async ( + request: Request, + context: { params: Promise<{ id: string }> } +) => { + const { id } = await context.params; + const owned = await requireOwnedServer(id); + + if ("error" in owned) { + return owned.error; + } + + const json = await request.json().catch(() => null); + const parsedBody = writeBodySchema.safeParse(json); + + if (!parsedBody.success) { + return NextResponse.json( + { details: parsedBody.error.flatten(), error: "Invalid body" }, + { status: 400 } + ); + } + + const command = await enqueueCommand({ + payload: parsedBody.data, + serverId: id, + type: "FILES_WRITE", + }); + + const outcome = await waitForCommand(command.id, 110_000); + + if (outcome.status === "timeout") { + return NextResponse.json( + { error: "Agent did not respond. Is the server online?" }, + { status: 504 } + ); + } + + if (outcome.status === "failed") { + return NextResponse.json( + { error: outcome.error ?? "Write Failed" }, + { status: 500 } + ); + } + + return NextResponse.json({ ok: true }); +}; diff --git a/app/api/servers/[id]/members/route.ts b/app/api/servers/[id]/members/route.ts index 505e5e0..f212835 100644 --- a/app/api/servers/[id]/members/route.ts +++ b/app/api/servers/[id]/members/route.ts @@ -4,7 +4,7 @@ import { z } from "zod"; import { prisma } from "@/lib/db"; import { env } from "@/lib/env"; -import { sendServerInviteEmail } from "@/lib/mail"; +import { sendServerInviteEmail, sendServerMemberAddedEmail } from "@/lib/mail"; import { requireServerRole } from "@/lib/rbac"; import { requireUser } from "@/lib/session"; @@ -123,6 +123,27 @@ export const POST = async ( user: { select: { email: true, id: true, image: true, name: true } }, }, }); + + // Notify the added user by email (fire-and-forget) + const [serverInfo, inviter] = await Promise.all([ + prisma.server.findUnique({ + select: { name: true }, + where: { id: serverId }, + }), + prisma.user.findUnique({ + select: { email: true, name: true }, + where: { id: user.id }, + }), + ]); + const baseUrl = env.BETTER_AUTH_URL.replace(/\/$/u, ""); + void sendServerMemberAddedEmail({ + addedByName: inviter?.name ?? inviter?.email ?? "A NodeByte user", + role, + serverName: serverInfo?.name ?? "a server", + serverUrl: `${baseUrl}/dashboard/${serverId}`, + toEmail: member.user.email, + }); + return NextResponse.json({ member, type: "added" }, { status: 201 }); } diff --git a/app/api/servers/[id]/metrics/live/route.ts b/app/api/servers/[id]/metrics/live/route.ts index 0c66e89..fa44c37 100644 --- a/app/api/servers/[id]/metrics/live/route.ts +++ b/app/api/servers/[id]/metrics/live/route.ts @@ -5,19 +5,6 @@ import { requireUser } from "@/lib/session"; export const runtime = "nodejs"; -/** - * GET /api/servers/[id]/metrics/live - * - * Returns current live server metrics (CPU, Memory, Network, etc.) - * This endpoint would typically pull from an agent monitoring system - * or container monitoring service. - * - * In a production system, this would: - * - Query Prometheus/Grafana - * - Call the server agent API - * - Poll container stats (docker stats) - * - Get game-specific metrics from the server - */ export const GET = async ( _request: Request, context: { params: Promise<{ id: string }> } @@ -26,12 +13,29 @@ export const GET = async ( const { id } = await context.params; const server = await prisma.server.findFirst({ - select: { - id: true, - lastHeartbeatAt: true, - observedState: true, + include: { + agent: { + select: { + cpuPercent: true, + diskTotalBytes: true, + diskUsedBytes: true, + lastHeartbeatAt: true, + maxPlayers: true, + memTotalBytes: true, + memUsedBytes: true, + networkInBps: true, + networkOutBps: true, + playerCount: true, + tps: true, + uptimeSeconds: true, + }, + }, + }, + where: { + OR: [{ userId: user.id }, { members: { some: { userId: user.id } } }], + deletedAt: null, + id, }, - where: { deletedAt: null, id, userId: user.id }, }); if (!server) { @@ -45,32 +49,35 @@ export const GET = async ( ); } - // Integrate with monitoring system (Prometheus, agent API, container stats, etc.) - // For now, return mock data to demonstrate the API structure + const { agent } = server; + if (!agent || !agent.lastHeartbeatAt) { + return NextResponse.json({ metrics: null }); + } - const uptime = (server.lastHeartbeatAt as Date | null) - ? Math.floor( - (Date.now() - (server.lastHeartbeatAt as Date).getTime()) / 1000 - ) - : 0; + // Consider metrics stale if no heartbeat in the last 60 seconds + const staleSec = (Date.now() - agent.lastHeartbeatAt.getTime()) / 1000; + if (staleSec > 60) { + return NextResponse.json({ metrics: null }); + } + + const memTotal = agent.memTotalBytes ?? 0; + const memUsed = agent.memUsedBytes ?? 0; + const memPercent = memTotal > 0 ? (memUsed / memTotal) * 100 : 0; return NextResponse.json({ metrics: { - // System metrics (typically from container/host monitoring) - // cpu: value from container/host monitoring - // memory: value from container/host monitoring - // networkIn: bytes per second - // networkOut: bytes per second - cpu: Math.random() * 50 + 10, - memory: Math.random() * 40 + 20, - networkIn: Math.random() * 1_000_000, - networkOut: Math.random() * 500_000, - uptime: Math.max(uptime, 0), - - // Game-specific metrics (if available) - // playerCount: 0, - // maxPlayers: 32, - // tps: 20, + cpu: agent.cpuPercent ?? 0, + diskPercent: + agent.diskTotalBytes && agent.diskTotalBytes > 0 + ? ((agent.diskUsedBytes ?? 0) / agent.diskTotalBytes) * 100 + : undefined, + maxPlayers: agent.maxPlayers ?? undefined, + memory: memPercent, + networkIn: agent.networkInBps ?? 0, + networkOut: agent.networkOutBps ?? 0, + playerCount: agent.playerCount ?? undefined, + tps: agent.tps ?? undefined, + uptime: agent.uptimeSeconds ?? 0, }, }); }; diff --git a/app/api/webhooks/stripe/route.ts b/app/api/webhooks/stripe/route.ts index 9ef00a1..7137d8a 100644 --- a/app/api/webhooks/stripe/route.ts +++ b/app/api/webhooks/stripe/route.ts @@ -204,6 +204,7 @@ const buildSubscriptionUpsertData = ( subscription: Stripe.Subscription, firstItem: Stripe.SubscriptionItem | undefined, serverId: string, + internalBillingCustomerId: string, promoCode: string | null, couponAmountOff: number | null, periodStart: Date | null, @@ -220,7 +221,7 @@ const buildSubscriptionUpsertData = ( const status = toSubscriptionStatus(subscription.status); return { create: { - billingCustomerId: subscription.customer as string, + billingCustomerId: internalBillingCustomerId, canceledAt, currency: subscription.currency.toUpperCase(), currentPeriodEnd: periodEnd, @@ -260,6 +261,16 @@ const handleSubscriptionChanged = async ( return; } + // Resolve internal BillingCustomer.id from the Stripe customer ID + const stripeCustomerId = subscription.customer as string; + const billingCustomer = await prisma.billingCustomer.findUnique({ + select: { id: true }, + where: { stripeCustomerId }, + }); + if (!billingCustomer) { + return; + } + const { promoCode, couponAmountOff, couponPercentOff } = resolveSubscriptionDiscount(subscription); const { periodStart, periodEnd } = resolveSubscriptionPeriod(subscription); @@ -275,6 +286,7 @@ const handleSubscriptionChanged = async ( subscription, firstItem, serverId, + billingCustomer.id, promoCode, couponAmountOff, periodStart, @@ -409,9 +421,21 @@ const upsertCheckoutSubscriptionAndAddons = async ( ? firstItem.price.product : ((firstItem?.price.product as Stripe.Product)?.id ?? ""); + // Resolve the internal BillingCustomer.id from the Stripe customer ID — + // billingCustomerId is a FK to BillingCustomer.id (not stripeCustomerId) + const billingCustomer = await prisma.billingCustomer.findUnique({ + select: { id: true }, + where: { stripeCustomerId: customerId }, + }); + if (!billingCustomer) { + throw new Error( + `BillingCustomer not found for Stripe customer ${customerId}` + ); + } + await prisma.subscription.upsert({ create: { - billingCustomerId: customerId, + billingCustomerId: billingCustomer.id, currency: (subscription.currency ?? "gbp").toUpperCase(), id: subscriptionId, planName: subscription.metadata?.serverType ?? "unknown", diff --git a/app/dashboard/[id]/actions/approve-provision.ts b/app/dashboard/[id]/actions/approve-provision.ts new file mode 100644 index 0000000..0d399a9 --- /dev/null +++ b/app/dashboard/[id]/actions/approve-provision.ts @@ -0,0 +1,91 @@ +"use server"; + +import type { Prisma } from "@prisma/client"; +import { revalidatePath } from "next/cache"; +import { start } from "workflow/api"; +import { z } from "zod"; + +import { getGame, validateSettings } from "@/games"; +import { prisma } from "@/lib/db"; +import { env } from "@/lib/env"; +import { sendServerCreatedEmail } from "@/lib/mail"; +import { requireUser } from "@/lib/session"; +import { provisionServer } from "@/lib/workflows/provision-server"; + +const inputSchema = z.object({ + serverId: z.string().min(1), + settings: z.record(z.string(), z.unknown()).optional(), +}); + +export type ApproveProvisionInput = z.infer; + +export type ApproveProvisionResult = + | { ok: true } + | { error: string; ok: false }; + +export const approveProvision = async ( + input: ApproveProvisionInput +): Promise => { + const user = await requireUser(); + + const parsed = inputSchema.safeParse(input); + if (!parsed.success) { + return { error: "Invalid input", ok: false }; + } + + const server = await prisma.server.findFirst({ + include: { user: { select: { email: true, name: true } } }, + where: { deletedAt: null, id: parsed.data.serverId, userId: user.id }, + }); + if (!server) { + return { error: "Not found", ok: false }; + } + + if (server.phase !== "pending") { + return { error: "Server is not awaiting approval", ok: false }; + } + + // Save game-config settings the user reviewed on this page before launching + if (parsed.data.settings && Object.keys(parsed.data.settings).length > 0) { + const game = getGame(server.game); + if (game) { + const validation = validateSettings(game.settings, parsed.data.settings); + if (!validation.ok) { + return { error: validation.error, ok: false }; + } + await prisma.server.update({ + data: { + settings: { + ...(server.settings as Record | null), + ...validation.data, + } as Prisma.InputJsonValue, + }, + where: { id: parsed.data.serverId }, + }); + } + } + + // Transition to queued and kick off the provisioning workflow + await prisma.server.update({ + data: { phase: "queued" }, + where: { id: parsed.data.serverId }, + }); + + await start(provisionServer, [{ serverId: parsed.data.serverId }]); + + // Notify the user that provisioning has started (fire-and-forget) + if (server.user) { + void sendServerCreatedEmail({ + game: server.game, + region: server.location, + serverName: server.name, + serverUrl: `${env.BETTER_AUTH_URL}/dashboard/${parsed.data.serverId}`, + toEmail: server.user.email, + userName: server.user.name, + }); + } + + revalidatePath("/dashboard", "layout"); + + return { ok: true }; +}; diff --git a/app/dashboard/[id]/actions/power.ts b/app/dashboard/[id]/actions/power.ts new file mode 100644 index 0000000..84eef1e --- /dev/null +++ b/app/dashboard/[id]/actions/power.ts @@ -0,0 +1,138 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { z } from "zod"; + +import { prisma } from "@/lib/db"; +import { getProviderForUser } from "@/lib/providers"; +import { + MissingProviderCredentialsError, + ProviderApiError, +} from "@/lib/providers/errors"; +import { requireUser } from "@/lib/session"; + +const inputSchema = z.object({ serverId: z.string().min(1) }); + +export type PowerServerInput = z.infer; + +export type PowerServerResult = { ok: true } | { error: string; ok: false }; + +const getProvider = async (userId: string) => { + try { + return await getProviderForUser(userId); + } catch (error) { + if (error instanceof MissingProviderCredentialsError) { + throw new TypeError( + "Configure your Hetzner credentials in account settings.", + { cause: error } + ); + } + throw error; + } +}; + +export const powerOffServer = async ( + input: PowerServerInput +): Promise => { + const user = await requireUser(); + + const parsed = inputSchema.safeParse(input); + if (!parsed.success) { + return { error: "Invalid input", ok: false }; + } + + const server = await prisma.server.findFirst({ + where: { deletedAt: null, id: parsed.data.serverId, userId: user.id }, + }); + if (!server) { + return { error: "Not found", ok: false }; + } + + if (!server.providerServerId) { + return { error: "Server is not provisioned yet", ok: false }; + } + + if (server.poweredOff) { + return { error: "Server is already powered off", ok: false }; + } + + if (server.observedState !== "stopped") { + return { error: "Server must be stopped before powering off", ok: false }; + } + + let provider: Awaited>; + try { + provider = await getProvider(user.id); + } catch (error) { + return { error: (error as Error).message, ok: false }; + } + + try { + await provider.powerOffServer(server.providerServerId); + } catch (error) { + if (error instanceof ProviderApiError) { + return { error: error.message, ok: false }; + } + throw error; + } + + await prisma.server.update({ + data: { poweredOff: true }, + where: { id: parsed.data.serverId }, + }); + + revalidatePath("/dashboard", "layout"); + + return { ok: true }; +}; + +export const powerOnServer = async ( + input: PowerServerInput +): Promise => { + const user = await requireUser(); + + const parsed = inputSchema.safeParse(input); + if (!parsed.success) { + return { error: "Invalid input", ok: false }; + } + + const server = await prisma.server.findFirst({ + where: { deletedAt: null, id: parsed.data.serverId, userId: user.id }, + }); + if (!server) { + return { error: "Not found", ok: false }; + } + + if (!server.providerServerId) { + return { error: "Server is not provisioned yet", ok: false }; + } + + if (!server.poweredOff) { + return { error: "Server is not powered off", ok: false }; + } + + let provider: Awaited>; + try { + provider = await getProvider(user.id); + } catch (error) { + return { error: (error as Error).message, ok: false }; + } + + try { + await provider.powerOnServer(server.providerServerId); + } catch (error) { + if (error instanceof ProviderApiError) { + return { error: error.message, ok: false }; + } + throw error; + } + + await prisma.server.update({ + data: { poweredOff: false }, + where: { id: parsed.data.serverId }, + }); + + revalidatePath("/dashboard", "layout"); + + return { ok: true }; +}; diff --git a/app/dashboard/[id]/actions/rcon.ts b/app/dashboard/[id]/actions/rcon.ts index 7eee988..5f1c174 100644 --- a/app/dashboard/[id]/actions/rcon.ts +++ b/app/dashboard/[id]/actions/rcon.ts @@ -2,7 +2,6 @@ import { z } from "zod"; -import { checkSubscriptionForServer } from "@/lib/billing/subscription-check"; import { prisma } from "@/lib/db"; import { requireUser } from "@/lib/session"; @@ -47,19 +46,6 @@ export const sendRconCommand = async ( return { error: "Server is not running", ok: false }; } - // ⚠️ BILLING: Verify subscription is active - const subscriptionCheck = await checkSubscriptionForServer( - parsed.data.serverId - ); - if (!subscriptionCheck.isValid) { - return { - error: - subscriptionCheck.message ?? - "Subscription is not active for this server", - ok: false, - }; - } - try { // RCON is not yet fully implemented in the protocol // For now, return a not-implemented error diff --git a/app/dashboard/[id]/approve-provision/page.tsx b/app/dashboard/[id]/approve-provision/page.tsx new file mode 100644 index 0000000..6ad70ff --- /dev/null +++ b/app/dashboard/[id]/approve-provision/page.tsx @@ -0,0 +1,244 @@ +"use client"; +import { + AlertCircleIcon, + CheckCircleIcon, + CheckIcon, + CpuIcon, + Loader2Icon, + MapPinIcon, + RocketIcon, + ServerIcon, +} from "lucide-react"; +import Image from "next/image"; +import { useState } from "react"; +import { toast } from "sonner"; + +import { Panel, PanelCard } from "@/components/panel"; +import { Button } from "@/components/ui/button"; +import { getGame, missingRequiredFields, resolveSettings } from "@/games"; + +import { approveProvision } from "../actions/approve-provision"; +import type { + FieldValue, + SettingsValuesRecord, +} from "../components/game-settings-form"; +import { SettingsFields } from "../components/game-settings-form"; +import { useServer } from "../components/server-context"; + +const formatSpecs = ( + specs: { cores: number; disk: number; memory: number } | null | undefined, + serverType: string +): string => + specs + ? `${specs.cores} vCPU · ${specs.memory} GB RAM · ${specs.disk} GB disk` + : serverType; + +const InfoRow = ({ + icon: Icon, + label, + value, +}: { + icon: React.ElementType; + label: string; + value: React.ReactNode; +}) => ( +
+
+ +
+
+

{label}

+

{value}

+
+
+); + +export default function ApprovePage() { + const { server } = useServer(); + const game = getGame(server.game); + const hasSettings = Boolean(game && Object.keys(game.settings).length > 0); + + const initial = game + ? (resolveSettings(game.settings, server.settings) as SettingsValuesRecord) + : ({} as SettingsValuesRecord); + + const [values, setValues] = useState(initial); + const [isApproving, setIsApproving] = useState(false); + + const setField = (key: string, value: FieldValue) => + setValues((prev) => ({ ...prev, [key]: value })); + + const missingRequired = game + ? missingRequiredFields(game.settings, values) + : []; + const canApprove = missingRequired.length === 0; + + if (server.phase !== "pending") { + return ( +
+
+ +
+

Already in progress

+

+ This server has already been approved and is{" "} + {server.phase === "healthy" || server.observedState === "running" + ? "running" + : "provisioning"} + . +

+
+
+
+ ); + } + + const handleApprove = async () => { + setIsApproving(true); + try { + const result = await approveProvision({ + serverId: server.id, + settings: hasSettings ? values : undefined, + }); + if (result.ok) { + toast.success( + "Provisioning started — you'll get an email when it's ready." + ); + } else { + toast.error(result.error); + } + } catch { + toast.error("Failed to start provisioning"); + } finally { + setIsApproving(false); + } + }; + + const locationLabel = server.location + ? [server.location.city, server.location.country] + .filter(Boolean) + .join(", ") || server.location.name + : "—"; + + const specsLabel = formatSpecs(server.specs, server.serverType); + + return ( +
+ {/* Page header */} +
+
+ +

Review & provision

+
+

+ An admin has created this server for you. Review the configuration + below and launch it when you're ready. +

+
+ + {/* Server summary */} + + +
+ {/* Game + name identity row */} +
+ {game && ( + {game.name} + )} +
+

{server.name}

+

+ {game?.name ?? server.game} +

+
+
+ +
+ + {/* Info grid */} +
+ + + +
+
+ + + + {/* Game configuration */} + {hasSettings && game && ( + + + + + {missingRequired.length > 0 && ( +

+ Fill in required fields before launching:{" "} + {missingRequired + .map( + (k) => + (game.settings as Record)[k] + ?.label ?? k + ) + .join(", ")} +

+ )} +
+ )} + + {/* What happens next */} + + +
    + {[ + "A VM will be booted in your chosen region", + "The NodeByte agent connects and installs the game", + "Your server starts up and health checks run (~60 seconds total)", + "You'll receive an email and can connect immediately", + ].map((step) => ( +
  • + + {step} +
  • + ))} +
+
+
+ + {/* CTA */} +
+ + {!canApprove && !isApproving && ( +

+ Fill in all required fields above +

+ )} +
+
+ ); +} diff --git a/app/dashboard/[id]/components/backups-panel.tsx b/app/dashboard/[id]/components/backups-panel.tsx index 7c34166..8ad8da9 100644 --- a/app/dashboard/[id]/components/backups-panel.tsx +++ b/app/dashboard/[id]/components/backups-panel.tsx @@ -331,7 +331,7 @@ export const BackupsPanel = ({ } > - Daily snapshots taken by Hetzner, retained for 7 days. + Daily snapshots, retained for 7 days.
diff --git a/app/dashboard/[id]/components/files-panel.tsx b/app/dashboard/[id]/components/files-panel.tsx index 4d48033..dab909d 100644 --- a/app/dashboard/[id]/components/files-panel.tsx +++ b/app/dashboard/[id]/components/files-panel.tsx @@ -8,7 +8,8 @@ import { Trash2Icon, UploadIcon, } from "lucide-react"; -import { useCallback, useEffect, useRef, useState } from "react"; +import dynamic from "next/dynamic"; +import { useCallback, useEffect, useRef, useState, useMemo } from "react"; import { toast } from "sonner"; import { Panel, PanelCard } from "@/components/panel"; @@ -48,6 +49,10 @@ import { import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +const MonacoEditor = dynamic(() => import("@monaco-editor/react"), { + ssr: false, +}); + interface FileEntry { name: string; type: "file" | "dir"; @@ -55,10 +60,23 @@ interface FileEntry { mtime: string; } +interface FileReadResponse { + path: string; + content: string; + encoding: "utf-8" | "utf-8" | "base64"; + size: number; + truncated: boolean; +} + interface Props { serverId: string; } +interface pathbreadcrumbProps { + path: string; + onNavigate: (nextPath: string) => void; +} + const DEFAULT_PATH = ""; const formatSize = (bytes: number): string => { @@ -124,21 +142,22 @@ const waitForCommand = async ( interface EntryRowProps { entry: FileEntry; onOpenDir: (name: string) => void; + onOpenFile: (name: string) => void; onDelete: (entry: FileEntry) => void; } -const EntryRow = ({ entry, onOpenDir, onDelete }: EntryRowProps) => { +const EntryRow = ({ + entry, + onOpenDir, + onOpenFile, + onDelete, +}: EntryRowProps) => { const isDir = entry.type === "dir"; return (
+ + )} + + {crumbs.map((segment, index) => { + const isLast = index === crumbs.length - 1; + const target = crumbs.slice(0, index + 1).join("/"); + return ( + + + + {isLast ? ( + {segment} + ) : ( + + + + )} + + + ); + })} + + + ); +}; + +const getDeletedDescription = (type: FileEntry["type"] | undefined) => { + if (type === "dir") { + return "This folder and everything inside it will be permanently removed."; + } + return "This file will be permanently removed."; +}; + export const FilesPanel = ({ serverId }: Props) => { const [path, setPath] = useState(DEFAULT_PATH); const [entries, setEntries] = useState(null); @@ -226,6 +348,24 @@ export const FilesPanel = ({ serverId }: Props) => { const [uploading, setUploading] = useState(false); const fileInputRef = useRef(null); + const [selectedFilePath, setSelectedFilePath] = useState(null); + const [editorContent, setEditorContent] = useState(""); + const [savedContent, setSavedContent] = useState(""); + const [editorEncoding, setEditorEncoding] = useState<"utf-8" | "base64">( + "utf-8" + ); + const [editorSize, setEditorSize] = useState(null); + const [editorTruncated, setEditorTruncated] = useState(false); + const [editorLoading, setEditorLoading] = useState(false); + const [editorSaving, setEditorSaving] = useState(false); + const [editorError, setEditorError] = useState(null); + const editorLanguage = useMemo( + () => languageFromPath(selectedFilePath), + [selectedFilePath] + ); + const isEditorDirty = + selectedFilePath !== null && editorContent !== savedContent; + const load = useCallback( async (target: string) => { setLoadError(null); @@ -336,47 +476,147 @@ export const FilesPanel = ({ serverId }: Props) => { } }; - const crumbs = path ? path.split("/").filter(Boolean) : []; + const openFile = useCallback( + async (name: string) => { + const fullPath = joinPath(path, name); + setSelectedFilePath(fullPath); + setEditorError(null); + setEditorLoading(true); + + try { + const res = await fetch( + `/api/servers/${serverId}/files/content?path=${encodeURIComponent(fullPath)}`, + { cache: "no-store" } + ); + + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + error?: string; + }; + throw new Error(body.error ?? "Could not read File"); + } + + const file = (await res.json()) as FileReadResponse; + setEditorContent(file.content); + setSavedContent(file.content); + setEditorEncoding(file.encoding === "base64" ? "base64" : "utf-8"); + setEditorSize(file.size); + setEditorTruncated(file.truncated); + } catch (error) { + setEditorContent(""); + setSavedContent(""); + setEditorEncoding("utf-8"); + setEditorSize(null); + setEditorTruncated(false); + setEditorError( + error instanceof Error ? error.message : "Could not read File" + ); + toast.error( + error instanceof Error ? error.message : "Could not read File" + ); + } finally { + setEditorLoading(false); + } + }, + [path, serverId] + ); + + const closeEditorOverlay = () => { + setSelectedFilePath(null); + setEditorError(null); + setEditorLoading(false); + setEditorSaving(false); + }; + + const saveFile = useCallback(async () => { + if (!selectedFilePath) { + return; + } + + setEditorSaving(true); + setEditorError(null); + + try { + const res = await fetch(`/api/servers/${serverId}/files/content`, { + body: JSON.stringify({ + content: editorContent, + encoding: editorEncoding === "base64" ? "base64" : "utf-8", + path: selectedFilePath, + }), + headers: { "Content-Type": "application/json" }, + method: "PUT", + }); + + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { error?: string }; + throw new Error(body.error ?? "Could not save file"); + } + + setSavedContent(editorContent); + setEditorSize( + editorEncoding === "utf-8" + ? new TextEncoder().encode(editorContent).length + : Math.floor((editorContent.length * 3) / 4) + ); + toast.success( + `Saved ${selectedFilePath.split("/").pop() ?? selectedFilePath}` + ); + } catch (error) { + setEditorError( + error instanceof Error ? error.message : "Could not save file" + ); + toast.error( + error instanceof Error ? error.message : "Could not save file" + ); + } finally { + setEditorSaving(false); + } + }, [editorContent, editorEncoding, selectedFilePath, serverId]); + + let editorBody; + + if (editorLoading) { + editorBody = ( +
Loading...
+ ); + } else if (editorEncoding === "base64") { + editorBody = ( +
+ Bianary File Not supported. Editing disabled. +
+ ); + } else { + editorBody = ( + setEditorContent(value ?? "")} + /> + ); + } + + const getSaveButtonLabel = () => { + if (editorSaving) { + return "Saving"; + } + if (isEditorDirty) { + return "Save"; + } + return "Saved"; + }; return (
- - - - {path === "" ? ( - data - ) : ( - - - - )} - - {crumbs.map((segment, index) => { - const isLast = index === crumbs.length - 1; - const target = crumbs.slice(0, index + 1).join("/"); - return ( - - - - {isLast ? ( - {segment} - ) : ( - - - - )} - - - ); - })} - - +
{
- {renderEntryList({ entries, loadError, onDelete: setDeleteTarget, onOpenDir: (name) => setPath(joinPath(path, name)), + onOpenFile: openFile, })} @@ -455,6 +695,57 @@ export const FilesPanel = ({ serverId }: Props) => { + { + if (!open) { + closeEditorOverlay(); + } + }} + open={selectedFilePath !== null} + > + + + + {selectedFilePath ?? "Editor"} + + + {editorSize === null ? `${editorSize} bytes` : "-"} .{" "} + {editorEncoding} + {editorTruncated ? " . truncated" : ""} + + + + {editorError ? ( +
+ {editorError} +
+ ) : null} + +
+ {editorBody} +
+ + + + + +
+
+ !open && setDeleteTarget(null)} open={deleteTarget !== null} @@ -463,9 +754,7 @@ export const FilesPanel = ({ serverId }: Props) => { Delete {deleteTarget?.name}? - {deleteTarget?.type === "dir" - ? "This folder and everything inside it will be permanently removed." - : "This file will be permanently removed."} + {getDeletedDescription(deleteTarget?.type)} diff --git a/app/dashboard/[id]/components/live-metrics-panel.tsx b/app/dashboard/[id]/components/live-metrics-panel.tsx index 0f06ce9..ae48354 100644 --- a/app/dashboard/[id]/components/live-metrics-panel.tsx +++ b/app/dashboard/[id]/components/live-metrics-panel.tsx @@ -7,6 +7,7 @@ import { ArrowUpIcon, ClockIcon, CpuIcon, + HardDriveIcon, MemoryStickIcon, UsersIcon, } from "lucide-react"; @@ -67,13 +68,13 @@ const MetricItem = ({ pct?: number; mono?: boolean; }) => ( -
-
+
+
{icon} - {label} + {label}
{value} @@ -121,7 +122,7 @@ export const LiveMetricsPanel = ({ } return ( -
+
} label="CPU" @@ -151,8 +152,8 @@ export const LiveMetricsPanel = ({ icon={} label="Players" value={ - maxPlayers - ? `${metrics.playerCount}/${maxPlayers}` + (metrics.maxPlayers ?? maxPlayers) + ? `${metrics.playerCount}/${metrics.maxPlayers ?? maxPlayers}` : String(metrics.playerCount) } /> @@ -161,9 +162,18 @@ export const LiveMetricsPanel = ({ } label="TPS" + pct={(metrics.tps / 20) * 100} value={metrics.tps.toFixed(1)} /> )} + {metrics.diskPercent !== undefined && ( + } + label="Disk" + pct={metrics.diskPercent} + value={`${metrics.diskPercent.toFixed(1)}%`} + /> + )} } label="Uptime" diff --git a/app/dashboard/[id]/components/logs-stream.tsx b/app/dashboard/[id]/components/logs-stream.tsx index 0f1588f..f0da82b 100644 --- a/app/dashboard/[id]/components/logs-stream.tsx +++ b/app/dashboard/[id]/components/logs-stream.tsx @@ -3,6 +3,8 @@ import Anser from "anser"; import { useEffect, useMemo, useRef, useState } from "react"; import { StickToBottom } from "use-stick-to-bottom"; +import { cn } from "@/lib/utils"; + interface LogItem { id: string; seq: number; @@ -39,6 +41,26 @@ const AnsiPart = ({ part }: { part: Anser.AnserJsonEntry }) => { return {part.content}; }; +const getLineClass = (text: string) => { + if (text.includes("ERROR") || text.includes("FATAL")) { + return "text-red-400"; + } + if (text.includes("WARN")) { + return "text-yellow-400"; + } + if (text.includes("INFO")) { + return "text-sky-400"; + } + if (text.includes("DEBUG")) { + return "text-purple-400"; + } + if (text.includes("SUCCESS") || text.includes("OK")) { + return "text-emerald-400"; + } + + return "text-zinc-300"; +}; + const AnsiLine = ({ text }: { text: string }) => { const parts = useMemo( () => @@ -48,8 +70,16 @@ const AnsiLine = ({ text }: { text: string }) => { }), [text] ); + + const hasAnsiColors = parts.some((p) => p.fg || p.bg); + return ( - + {parts.map((part, i) => ( ))} @@ -98,11 +128,11 @@ export const LogsStream = ({ serverId }: { serverId: string }) => { return ( - + {lines.length === 0 && ( Waiting for logs… diff --git a/app/dashboard/[id]/components/provisioning-status.tsx b/app/dashboard/[id]/components/provisioning-status.tsx index 6aa3d02..a42beba 100644 --- a/app/dashboard/[id]/components/provisioning-status.tsx +++ b/app/dashboard/[id]/components/provisioning-status.tsx @@ -1,23 +1,58 @@ "use client"; -import { CheckIcon, CircleXIcon } from "lucide-react"; +import { + AlertTriangleIcon, + CheckIcon, + CircleXIcon, + Loader2Icon, + RocketIcon, +} from "lucide-react"; -import { Spinner } from "@/components/ui/spinner"; import { cn } from "@/lib/utils"; const STEPS = [ - { key: "create", label: "Create server", phases: ["queued", "provisioning"] }, - { key: "boot", label: "Boot VM", phases: ["booting"] }, - { key: "agent", label: "Connect agent", phases: ["agent_connected"] }, - { key: "install", label: "Install game", phases: ["installing"] }, - { key: "start", label: "Start server", phases: ["starting"] }, - { key: "health", label: "Run health checks", phases: ["healthy"] }, + { + description: "Reserving a virtual machine in your chosen region", + key: "create", + label: "Create server", + phases: ["queued", "provisioning"], + }, + { + description: "Operating system booting and network interfaces coming up", + key: "boot", + label: "Boot VM", + phases: ["booting"], + }, + { + description: "NodeByte agent connecting and enrolling with the panel", + key: "agent", + label: "Connect agent", + phases: ["agent_connected"], + }, + { + description: "Downloading and configuring game server files", + key: "install", + label: "Install game", + phases: ["installing"], + }, + { + description: "Game server process initialising", + key: "start", + label: "Start server", + phases: ["starting"], + }, + { + description: "Verifying server health and network connectivity", + key: "health", + label: "Run health checks", + phases: ["healthy"], + }, ] as const; const PHASE_ORDER: string[] = STEPS.flatMap((s) => [...s.phases]); type StepStatus = "done" | "active" | "pending" | "error"; -const stepStatus = ( +const resolveStepStatus = ( currentIndex: number, stepStart: number, stepEnd: number, @@ -35,17 +70,57 @@ const stepStatus = ( return "pending"; }; -const StepIcon = ({ status }: { status: StepStatus }) => { +const StepCircle = ({ status }: { status: StepStatus }) => { if (status === "done") { - return ; + return ( +
+ +
+ ); } if (status === "active") { - return ; + return ( +
+ + {/* Outer pulse ring */} + +
+ ); } if (status === "error") { - return ; + return ( +
+ +
+ ); } - return
; + return ( +
+
+
+ ); +}; + +const ConnectorLine = ({ status }: { status: StepStatus }) => ( +
+); + +const PHASE_LABEL: Record = { + agent_connected: "Connecting agent", + booting: "Booting VM", + errored: "Provisioning failed", + healthy: "Checking health", + installing: "Installing game", + provisioning: "Creating VM", + queued: "Queued", + starting: "Starting server", }; export const ProvisioningStatus = ({ @@ -58,44 +133,115 @@ export const ProvisioningStatus = ({ errorReason: string | null; }) => { const currentIndex = PHASE_ORDER.indexOf(phase); - // Legacy fallback: older records stored phase='errored' (now we preserve - // the in-flight phase), which returns -1 — pin the error to the first step. const errorIndex = errored && currentIndex === -1 ? 0 : currentIndex; + const phaseLabel = PHASE_LABEL[phase] ?? "In progress"; + return ( -
- {STEPS.map((step) => { - const stepStart = PHASE_ORDER.indexOf(step.phases[0]); - const stepEnd = stepStart + step.phases.length - 1; - const isErrorStep = - errored && errorIndex >= stepStart && errorIndex <= stepEnd; - const status = stepStatus( - currentIndex, - stepStart, - stepEnd, - isErrorStep - ); +
+ {/* Status banner */} + {errored ? ( +
+ +
+

+ Provisioning failed +

+

+ {errorReason ?? + "An error occurred during provisioning. Our team has been notified."} +

+
+
+ ) : ( +
+ +
+

{phaseLabel}…

+

+ Your server will be ready in approximately 60 seconds. +

+
+
+ )} + + {/* Step timeline */} +
+ {STEPS.map((step, i) => { + const stepStart = PHASE_ORDER.indexOf(step.phases[0]); + const stepEnd = stepStart + step.phases.length - 1; + const isErrorStep = + errored && errorIndex >= stepStart && errorIndex <= stepEnd; + const status = resolveStepStatus( + currentIndex, + stepStart, + stepEnd, + isErrorStep + ); + const isLast = i === STEPS.length - 1; + + return ( +
+ {/* Left: circle + connector */} +
+ + {!isLast && } +
+ + {/* Right: content */} +
+

+ {step.label} +

+

+ {step.description} +

+ {isErrorStep && errorReason && ( +

+ {errorReason} +

+ )} +
- return ( -
-
- - + {status === "done" && ( + + Done + + )} + {status === "active" && ( + + In progress + )} - > - {step.label} - + {status === "error" && ( + + Failed + + )} +
- {isErrorStep && errorReason && ( -

{errorReason}

- )} -
- ); - })} + ); + })} +
); }; diff --git a/app/dashboard/[id]/components/server-context.tsx b/app/dashboard/[id]/components/server-context.tsx index 793225b..8381355 100644 --- a/app/dashboard/[id]/components/server-context.tsx +++ b/app/dashboard/[id]/components/server-context.tsx @@ -33,6 +33,7 @@ export interface ServerView { lastHeartbeatAt: string | null; serverType: string; backupsEnabled: boolean; + poweredOff: boolean; specs: Specs | null; location: ServerLocation | null; settings: Record; diff --git a/app/dashboard/[id]/components/shell.tsx b/app/dashboard/[id]/components/shell.tsx index 8674fc5..17da3b7 100644 --- a/app/dashboard/[id]/components/shell.tsx +++ b/app/dashboard/[id]/components/shell.tsx @@ -1,9 +1,19 @@ "use client"; import { + ActivityIcon, + ArchiveIcon, + BarChart2Icon, + FolderIcon, + InfoIcon, + LayoutDashboardIcon, MoreHorizontalIcon, PlayIcon, + PowerIcon, + PowerOffIcon, RotateCcwIcon, + Settings2Icon, SquareIcon, + TerminalIcon, Trash2Icon, Users2Icon, } from "lucide-react"; @@ -42,6 +52,7 @@ import { cn } from "@/lib/utils"; import { PageBody, PageHeader } from "../../components/page-header"; import { runServerCommand } from "../actions/commands"; import { deleteServer } from "../actions/delete"; +import { powerOnServer, powerOffServer } from "../actions/power"; import { ProvisioningStatus } from "./provisioning-status"; import { ServerProvider } from "./server-context"; import type { ServerView } from "./server-context"; @@ -63,6 +74,8 @@ const STATE_BADGE: Record = { failed: "border-red-500/40 bg-red-500/10 text-red-600 dark:bg-red-500/15 dark:text-red-400", lost: "border-red-500/40 bg-red-500/10 text-red-600 dark:bg-red-500/15 dark:text-red-400", + "powered-off": + "border-zinc-500/40 bg-zinc-500/10 text-zinc-500 dark:bg-zinc-500/15 dark:text-zinc-400", running: "border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:bg-emerald-500/15 dark:text-emerald-400", stopped: @@ -72,15 +85,60 @@ const STATE_BADGE: Record = { }; const ALL_TABS = [ - { label: "Overview", minRole: "viewer" as ServerRole, value: "connect" }, - { label: "Activity", minRole: "viewer" as ServerRole, value: "activity" }, - { label: "Console", minRole: "viewer" as ServerRole, value: "console" }, - { label: "Graphs", minRole: "viewer" as ServerRole, value: "graphs" }, - { label: "Backups", minRole: "admin" as ServerRole, value: "backups" }, - { label: "Files", minRole: "admin" as ServerRole, value: "files" }, - { label: "Details", minRole: "member" as ServerRole, value: "details" }, - { label: "Settings", minRole: "admin" as ServerRole, value: "settings" }, - { label: "Team", minRole: "owner" as ServerRole, value: "team" }, + { + icon: LayoutDashboardIcon, + label: "Overview", + minRole: "viewer" as ServerRole, + value: "connect", + }, + { + icon: ActivityIcon, + label: "Activity", + minRole: "viewer" as ServerRole, + value: "activity", + }, + { + icon: TerminalIcon, + label: "Console", + minRole: "viewer" as ServerRole, + value: "console", + }, + { + icon: BarChart2Icon, + label: "Graphs", + minRole: "viewer" as ServerRole, + value: "graphs", + }, + { + icon: ArchiveIcon, + label: "Backups", + minRole: "admin" as ServerRole, + value: "backups", + }, + { + icon: FolderIcon, + label: "Files", + minRole: "admin" as ServerRole, + value: "files", + }, + { + icon: InfoIcon, + label: "Details", + minRole: "member" as ServerRole, + value: "details", + }, + { + icon: Settings2Icon, + label: "Settings", + minRole: "admin" as ServerRole, + value: "settings", + }, + { + icon: Users2Icon, + label: "Team", + minRole: "owner" as ServerRole, + value: "team", + }, ] as const; const ROLE_ORDER: Record = { @@ -114,6 +172,122 @@ const getStatusDotColor = (key: string) => { return "bg-zinc-400"; }; +interface ServerActionsProps { + canControl: boolean; + canDelete: boolean; + deleting: boolean; + pending: string | null; + poweredOff: boolean; + observedState: string; + onDelete: () => void; + onPowerOff: () => void; + onPowerOn: () => void; + onCommand: (type: "START" | "STOP" | "RESTART") => void; +} + +const ServerActions = ({ + canControl, + canDelete, + deleting, + pending, + poweredOff, + observedState, + onDelete, + onPowerOff, + onPowerOn, + onCommand, +}: ServerActionsProps) => ( +
+ {canControl && poweredOff && ( + + )} + {canControl && !poweredOff && observedState === "stopped" && ( + <> + + + + )} + {canControl && observedState === "running" && ( + <> + + + + )} + {pending && ( + + {pending.toLowerCase().replace("_", " ")}… + + )} + {canDelete && ( + + + + + + + + Delete server + + + + )} +
+); + export const ServerShell = ({ server: initial, eligibleTypes, @@ -135,6 +309,9 @@ export const ServerShell = ({ const [deleteOpen, setDeleteOpen] = useState(false); const [deleteConfirmName, setDeleteConfirmName] = useState(""); + const updateServer = (patch: Partial) => + setServer((prev) => ({ ...prev, ...patch })); + useEffect(() => { const t = setInterval(async () => { const res = await fetch(`/api/servers/${initial.id}`); @@ -155,6 +332,7 @@ export const ServerShell = ({ name: fresh.name, observedState: fresh.observedState, phase: fresh.phase, + poweredOff: fresh.poweredOff ?? prev.poweredOff, serverType: fresh.serverType ?? prev.serverType, })); } @@ -173,6 +351,30 @@ export const ServerShell = ({ } }; + const runPowerOff = async () => { + setPending("POWER_OFF"); + const result = await powerOffServer({ serverId: server.id }); + setPending(null); + if (result.ok) { + updateServer({ poweredOff: true }); + toast.success("Server Powering Off"); + } else { + toast.error(result.error); + } + }; + + const runPowerOn = async () => { + setPending("POWER_ON"); + const result = await powerOnServer({ serverId: server.id }); + setPending(null); + if (result.ok) { + updateServer({ poweredOff: false }); + toast.success("Server powering on"); + } else { + toast.error(result.error); + } + }; + const runDelete = async () => { setPending("DELETE"); const result = await deleteServer({ serverId: server.id }); @@ -184,9 +386,6 @@ export const ServerShell = ({ } }; - const updateServer = (patch: Partial) => - setServer((prev) => ({ ...prev, ...patch })); - const handleDeleteOpenChange = (open: boolean) => { setDeleteOpen(open); if (!open) { @@ -202,8 +401,13 @@ export const ServerShell = ({ } const deleting = server.desiredState === "deleted"; - const statusKey = deleting ? "deleting" : server.observedState; - const statusLabel = statusKey.charAt(0).toUpperCase() + statusKey.slice(1); + const statusKey = + (deleting ? "deleting" : null) ?? + (server.poweredOff ? "powered-off" : server.observedState); + const statusLabel = + statusKey === "powered-off" + ? "Powered off" + : statusKey.charAt(0).toUpperCase() + statusKey.slice(1); const meta = ( - {canControl && server.observedState === "stopped" && ( - - )} - {canControl && server.observedState === "running" && ( - <> - - - - )} - {pending && ( - - {pending.toLowerCase()}… - - )} - {canDelete && ( - - - - - - setDeleteOpen(true)} - variant="destructive" - > - - Delete server - - - - )} -
+ setDeleteOpen(true)} + onPowerOff={runPowerOff} + onPowerOn={runPowerOn} + /> ); const deleteDialog = ( @@ -389,14 +539,10 @@ export const ServerShell = ({ : `/dashboard/${server.id}/${tab.value}` } > - {tab.value === "team" ? ( - - - Team - - ) : ( - tab.label - )} + + + {tab.label} + ))} diff --git a/app/dashboard/[id]/components/use-live-metrics.ts b/app/dashboard/[id]/components/use-live-metrics.ts index 33f72b8..d60c931 100644 --- a/app/dashboard/[id]/components/use-live-metrics.ts +++ b/app/dashboard/[id]/components/use-live-metrics.ts @@ -16,6 +16,8 @@ export interface LiveMetrics { networkOut: number; // Seconds uptime: number; + // Disk usage percentage (if available) + diskPercent?: number; // Current players playerCount?: number; // Max players diff --git a/app/dashboard/[id]/console/page.tsx b/app/dashboard/[id]/console/page.tsx index bc31426..6a67429 100644 --- a/app/dashboard/[id]/console/page.tsx +++ b/app/dashboard/[id]/console/page.tsx @@ -1,8 +1,9 @@ "use client"; -import { HistoryIcon, SendIcon, TerminalIcon } from "lucide-react"; +import { CopyIcon, HistoryIcon, SendIcon, TerminalIcon } from "lucide-react"; import { useState } from "react"; import { toast } from "sonner"; +import { Panel, PanelCard } from "@/components/panel"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { cn } from "@/lib/utils"; @@ -16,8 +17,9 @@ const ConsoleTab = () => { const { server } = useServer(); const [commandInput, setCommandInput] = useState(""); const [commandHistory, setCommandHistory] = useState([]); - const [, setHistoryIndex] = useState(-1); + const [_historyIndex, setHistoryIndex] = useState(-1); const [isSending, setIsSending] = useState(false); + const [showHistory, setShowHistory] = useState(false); const handleSendCommand = async () => { if (!commandInput.trim() || server.observedState !== "running") { @@ -52,6 +54,7 @@ const ConsoleTab = () => { void handleSendCommand(); } else if (e.key === "ArrowUp") { e.preventDefault(); + setShowHistory(true); setHistoryIndex((prev) => { const next = prev + 1; if (next < commandHistory.length) { @@ -69,6 +72,7 @@ const ConsoleTab = () => { return next; } else if (prev === 0) { setCommandInput(""); + setShowHistory(false); return -1; } return prev; @@ -79,84 +83,128 @@ const ConsoleTab = () => { const isRunning = server.observedState === "running"; return ( -
- {/* Live metrics — compact bar when running */} +
+ {/* Live metrics */} {isRunning && ( -
- -
+ + + + + )} - {/* Terminal window */} -
- {/* Terminal title bar */} -
- - {server.name} -
-
- - {isRunning ? "live" : server.observedState} - - {commandHistory.length > 0 && ( - - - {commandHistory.length} + {/* Terminal */} + + + {/* Title bar */} +
+
+ + + {server.name} - )} +
+
+
+ + {isRunning ? "live" : server.observedState} + +
-
- - {/* Log output — fills remaining space */} -
- -
- {/* Command input */} - {isRunning ? ( -
- - $ - - { - setCommandInput(e.target.value); - setHistoryIndex(-1); - }} - onKeyDown={handleKeyDown} - /> - + {/* Log output — fills remaining height */} +
+
- ) : ( -
-

- Server is {server.observedState}. Start the server to send - commands. -

-
- )} -
+ + {/* History dropdown */} + {showHistory && commandHistory.length > 0 && ( +
+
+ + Recent Commands +
+
    + {commandHistory.slice(0, 10).map((cmd, idx) => ( +
  • + +
  • + ))} +
+
+ )} + + {/* Command input */} + {isRunning ? ( +
+ + $ + + { + setCommandInput(e.target.value); + setHistoryIndex(-1); + }} + onKeyDown={handleKeyDown} + /> +
+ {commandInput && ( + + )} + +
+
+ ) : ( +
+

+ Server is {server.observedState}. Start the server to send + commands. +

+
+ )} +
+
); }; diff --git a/app/dashboard/[id]/layout.tsx b/app/dashboard/[id]/layout.tsx index 61a394b..afb04a1 100644 --- a/app/dashboard/[id]/layout.tsx +++ b/app/dashboard/[id]/layout.tsx @@ -59,7 +59,16 @@ const ServerLayout = async ({ user.id, SNAPSHOT_ENVIRONMENT ); - const catalog = await provider.getCatalog(imageId); + + // Fetch catalog with fallback for missing images + let catalog; + try { + catalog = await provider.getCatalog(imageId); + } catch { + // Image not found or catalog unavailable — use empty fallback + catalog = { currency: "gbp", serverTypes: [] }; + } + const serverType = catalog.serverTypes.find( (t) => t.name === server.serverType ); @@ -111,6 +120,7 @@ const ServerLayout = async ({ name: server.name, observedState: server.observedState, phase: server.phase, + poweredOff: server.poweredOff, serverType: server.serverType, settings: (server.settings ?? {}) as Record, specs, diff --git a/app/dashboard/account/backend/page.tsx b/app/dashboard/account/backend/page.tsx index 991afde..9fb4c26 100644 --- a/app/dashboard/account/backend/page.tsx +++ b/app/dashboard/account/backend/page.tsx @@ -1,7 +1,5 @@ import { redirect } from "next/navigation"; -// The "Backend" page (user Hetzner token management) has been removed now that -// NodeByte manages infrastructure centrally. Redirect users to the new billing page. const BackendPage = () => { redirect("/dashboard/account/billing"); }; diff --git a/app/dashboard/components/app-sidebar.tsx b/app/dashboard/components/app-sidebar.tsx index 3c10f4f..d0cd7f8 100644 --- a/app/dashboard/components/app-sidebar.tsx +++ b/app/dashboard/components/app-sidebar.tsx @@ -123,7 +123,7 @@ export const AppSidebar = ({ {/* Header */} diff --git a/app/dashboard/components/server-card.tsx b/app/dashboard/components/server-card.tsx index ef190db..0699aef 100644 --- a/app/dashboard/components/server-card.tsx +++ b/app/dashboard/components/server-card.tsx @@ -94,53 +94,23 @@ const statusConfig = { }, }; -const metricsCache = new Map(); - -const fetchMetrics = async (serverId: string): Promise => { - const cached = metricsCache.get(serverId); - if (cached && Date.now() - cached.timestamp < 5000) { - return cached.data; - } - +const fetchLiveMetrics = async (serverId: string): Promise => { try { - const now = new Date(); - const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000); - - const response = await fetch( - `/api/servers/${serverId}/metrics?type=cpu&start=${fiveMinutesAgo.toISOString()}&end=${now.toISOString()}` - ); - + const response = await fetch(`/api/servers/${serverId}/metrics/live`, { + cache: "no-store", + }); if (!response.ok) { return {}; } - const data = await response.json(); - const timeSeries = data.metrics?.time_series || {}; - const cpuValues = timeSeries["node_cpu_seconds_total"]?.values || []; - const memoryValues = - timeSeries["node_memory_MemAvailable_bytes"]?.values || []; - - let cpu = 0; - if (cpuValues.length > 0) { - cpu = Math.min( - Math.round(Number.parseFloat(cpuValues.at(-1)[1]) * 100) / 100, - 100 - ); - } - - let memory = 0; - if (memoryValues.length > 0) { - memory = Math.min( - Math.round( - Number.parseFloat(memoryValues.at(-1)[1]) / 1024 / 1024 / 10 - ), - 100 - ); + const m = data.metrics; + if (!m) { + return {}; } - - const metrics = { cpu: cpu || undefined, memory: memory || undefined }; - metricsCache.set(serverId, { data: metrics, timestamp: Date.now() }); - return metrics; + return { + cpu: typeof m.cpu === "number" ? m.cpu : undefined, + memory: typeof m.memory === "number" ? m.memory : undefined, + }; } catch { return {}; } @@ -192,20 +162,38 @@ export const ServerCard = ({ server, game }: Props) => { statusConfig.stopped; useEffect(() => { - if (server.observedState === "running") { - setMetricsLoading(true); - const load = async () => { - try { - const m = await fetchMetrics(server.id); - setMetrics(m); - } finally { - setMetricsLoading(false); - } - }; - void load(); - } else { + if (server.observedState !== "running") { setMetrics({}); + setMetricsLoading(false); + return; } + + setMetricsLoading(true); + let cancelled = false; + + const load = async () => { + const m = await fetchLiveMetrics(server.id); + if (!cancelled) { + setMetrics(m); + setMetricsLoading(false); + } + }; + void load(); + + // Poll every 10s while running + const interval = setInterval(() => { + void (async () => { + const m = await fetchLiveMetrics(server.id); + if (!cancelled) { + setMetrics(m); + } + })(); + }, 10_000); + + return () => { + cancelled = true; + clearInterval(interval); + }; }, [server.id, server.observedState]); const handleCommand = useCallback( diff --git a/app/dashboard/new/actions/create-server.ts b/app/dashboard/new/actions/create-server.ts index 9ad365b..bf0103d 100644 --- a/app/dashboard/new/actions/create-server.ts +++ b/app/dashboard/new/actions/create-server.ts @@ -10,7 +10,7 @@ import { z } from "zod"; import { games, validateSettings } from "@/games"; import { prisma } from "@/lib/db"; -import { API_URL, SNAPSHOT_ENVIRONMENT } from "@/lib/env"; +import { API_URL, env, SNAPSHOT_ENVIRONMENT } from "@/lib/env"; import { getProviderForUserWithImage } from "@/lib/providers"; import { requireUser } from "@/lib/session"; @@ -39,30 +39,52 @@ export type CreateServerResult = * Get or create a Stripe Price for a given server type and monthly GBP pence amount. * Uses a stable lookup_key so repeated calls are idempotent. */ -const getOrCreateStripePrice = async ( +const getOrCreateStripePrices = async ( stripe: Stripe, serverTypeName: string, pricePerMonthCents: number -): Promise => { - const lookupKey = `nodebyte-${serverTypeName.toLowerCase()}-monthly`; - const existing = await stripe.prices.list({ lookup_keys: [lookupKey] }); - if (existing.data.length > 0) { - return existing.data[0].id; +): Promise<{ + introductoryPriceId: string; + usageSubscriptionPriceId: string; +}> => { + const priceKey = `nodebyte-${serverTypeName.toLowerCase()}-${pricePerMonthCents}`; + const [introductoryPrices, usagePrices] = await Promise.all([ + stripe.prices.list({ lookup_keys: [`${priceKey}-first-month`] }), + stripe.prices.list({ lookup_keys: [`${priceKey}-usage-base`] }), + ]); + if (introductoryPrices.data[0] && usagePrices.data[0]) { + return { + introductoryPriceId: introductoryPrices.data[0].id, + usageSubscriptionPriceId: usagePrices.data[0].id, + }; } - // Create a recurring product + price for this server type const product = await stripe.products.create({ metadata: { serverType: serverTypeName }, name: `NodeByte — ${serverTypeName} Game Server`, }); - const price = await stripe.prices.create({ - currency: "gbp", - lookup_key: lookupKey, - product: product.id, - recurring: { interval: "month" }, - transfer_lookup_key: true, - unit_amount: pricePerMonthCents, - }); - return price.id; + const [introductoryPrice, usageSubscriptionPrice] = await Promise.all([ + introductoryPrices.data[0] ?? + stripe.prices.create({ + currency: "gbp", + lookup_key: `${priceKey}-first-month`, + product: product.id, + transfer_lookup_key: true, + unit_amount: pricePerMonthCents, + }), + usagePrices.data[0] ?? + stripe.prices.create({ + currency: "gbp", + lookup_key: `${priceKey}-usage-base`, + product: product.id, + recurring: { interval: "month" }, + transfer_lookup_key: true, + unit_amount: 0, + }), + ]); + return { + introductoryPriceId: introductoryPrice.id, + usageSubscriptionPriceId: usageSubscriptionPrice.id, + }; }; export const createServer = async ( @@ -151,29 +173,46 @@ export const createServer = async ( ); const pricePerMonthCents = Math.round(type.pricePerMonth * 100); - const priceId = await getOrCreateStripePrice( + const prices = await getOrCreateStripePrices( stripe, type.name, pricePerMonthCents ); + const stripeReturnUrl = env.NODEBYTE_PUBLIC_URL || API_URL; + + // On preview deployments, Vercel Deployment Protection intercepts the + // Stripe redirect before the app runs (browser has no Vercel auth cookie + // after returning from checkout). Append the bypass secret as a query param + // so Vercel lets the redirect through automatically. + const bypassParam = env.VERCEL_AUTOMATION_BYPASS_SECRET + ? `&x-vercel-protection-bypass=${env.VERCEL_AUTOMATION_BYPASS_SECRET}` + : ""; + const session = await stripe.checkout.sessions.create({ - cancel_url: `${API_URL}/dashboard/new`, + cancel_url: `${stripeReturnUrl}/dashboard/new${bypassParam ? `?${bypassParam.slice(1)}` : ""}`, customer: stripeCustomerId, - line_items: [{ price: priceId, quantity: 1 }], + line_items: [ + { price: prices.introductoryPriceId, quantity: 1 }, + { price: prices.usageSubscriptionPriceId, quantity: 1 }, + ], metadata: { + hourlyRateMilliCents: String(location.hourlyPriceMilliCents), nodebyteServerId: server.id, nodebyteUserId: user.id, + pricePerMonthCents: String(pricePerMonthCents), }, mode: "subscription", subscription_data: { metadata: { + hourlyRateMilliCents: String(location.hourlyPriceMilliCents), nodebyteServerId: server.id, nodebyteUserId: user.id, + pricePerMonthCents: String(pricePerMonthCents), serverType: type.name, }, }, - success_url: `${API_URL}/dashboard/new/success?session_id={CHECKOUT_SESSION_ID}`, + success_url: `${stripeReturnUrl}/dashboard/new/success?session_id={CHECKOUT_SESSION_ID}${bypassParam}`, }); if (!session.url) { diff --git a/app/dashboard/new/components/form.tsx b/app/dashboard/new/components/form.tsx index f117701..7290abe 100644 --- a/app/dashboard/new/components/form.tsx +++ b/app/dashboard/new/components/form.tsx @@ -380,7 +380,7 @@ const GameStep = ({ games, gameId, setGameId }: GameStepProps) => ( Select the game you want to run on your server.

-
+
{games.map((game) => (
- ) + ); }, ...components, }} {...props} /> - ) + ); } function CalendarDayButton({ @@ -187,12 +194,12 @@ function CalendarDayButton({ locale, ...props }: React.ComponentProps & { locale?: Partial }) { - const defaultClassNames = getDefaultClassNames() + const defaultClassNames = getDefaultClassNames(); - const ref = React.useRef(null) + const ref = React.useRef(null); React.useEffect(() => { - if (modifiers.focused) ref.current?.focus() - }, [modifiers.focused]) + if (modifiers.focused) ref.current?.focus(); + }, [modifiers.focused]); return ( - ) + ); } function CarouselNext({ @@ -207,7 +207,7 @@ function CarouselNext({ size = "icon-sm", ...props }: React.ComponentProps) { - const { orientation, scrollNext, canScrollNext } = useCarousel() + const { orientation, scrollNext, canScrollNext } = useCarousel(); return ( - ) + ); } export { @@ -239,4 +239,4 @@ export { CarouselPrevious, CarouselNext, useCarousel, -} +}; diff --git a/components/ui/chart.tsx b/components/ui/chart.tsx index 7c2dc84..b59312a 100644 --- a/components/ui/chart.tsx +++ b/components/ui/chart.tsx @@ -1,42 +1,42 @@ -"use client" +"use client"; -import * as React from "react" -import * as RechartsPrimitive from "recharts" -import type { TooltipValueType } from "recharts" +import * as React from "react"; +import * as RechartsPrimitive from "recharts"; +import type { TooltipValueType } from "recharts"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; // Format: { THEME_NAME: CSS_SELECTOR } -const THEMES = { light: "", dark: ".dark" } as const +const THEMES = { light: "", dark: ".dark" } as const; -const INITIAL_DIMENSION = { width: 320, height: 200 } as const -type TooltipNameType = number | string +const INITIAL_DIMENSION = { width: 320, height: 200 } as const; +type TooltipNameType = number | string; export type ChartConfig = Record< string, { - label?: React.ReactNode - icon?: React.ComponentType + label?: React.ReactNode; + icon?: React.ComponentType; } & ( | { color?: string; theme?: never } | { color?: never; theme: Record } ) -> +>; type ChartContextProps = { - config: ChartConfig -} + config: ChartConfig; +}; -const ChartContext = React.createContext(null) +const ChartContext = React.createContext(null); function useChart() { - const context = React.useContext(ChartContext) + const context = React.useContext(ChartContext); if (!context) { - throw new Error("useChart must be used within a ") + throw new Error("useChart must be used within a "); } - return context + return context; } function ChartContainer({ @@ -47,17 +47,17 @@ function ChartContainer({ initialDimension = INITIAL_DIMENSION, ...props }: React.ComponentProps<"div"> & { - config: ChartConfig + config: ChartConfig; children: React.ComponentProps< typeof RechartsPrimitive.ResponsiveContainer - >["children"] + >["children"]; initialDimension?: { - width: number - height: number - } + width: number; + height: number; + }; }) { - const uniqueId = React.useId() - const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}` + const uniqueId = React.useId(); + const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`; return ( @@ -66,7 +66,7 @@ function ChartContainer({ data-chart={chartId} className={cn( "flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden", - className + className, )} {...props} > @@ -78,16 +78,16 @@ function ChartContainer({
- ) + ); } const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => { const colorConfig = Object.entries(config).filter( - ([, config]) => config.theme ?? config.color - ) + ([, config]) => config.theme ?? config.color, + ); if (!colorConfig.length) { - return null + return null; } return ( @@ -101,20 +101,20 @@ ${colorConfig .map(([key, itemConfig]) => { const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ?? - itemConfig.color - return color ? ` --color-${key}: ${color};` : null + itemConfig.color; + return color ? ` --color-${key}: ${color};` : null; }) .join("\n")} } -` +`, ) .join("\n"), }} /> - ) -} + ); +}; -const ChartTooltip = RechartsPrimitive.Tooltip +const ChartTooltip = RechartsPrimitive.Tooltip; function ChartTooltipContent({ active, @@ -132,11 +132,11 @@ function ChartTooltipContent({ labelKey, }: React.ComponentProps & React.ComponentProps<"div"> & { - hideLabel?: boolean - hideIndicator?: boolean - indicator?: "line" | "dot" | "dashed" - nameKey?: string - labelKey?: string + hideLabel?: boolean; + hideIndicator?: boolean; + indicator?: "line" | "dot" | "dashed"; + nameKey?: string; + labelKey?: string; } & Omit< RechartsPrimitive.DefaultTooltipContentProps< TooltipValueType, @@ -144,34 +144,34 @@ function ChartTooltipContent({ >, "accessibilityLayer" >) { - const { config } = useChart() + const { config } = useChart(); const tooltipLabel = React.useMemo(() => { if (hideLabel || !payload?.length) { - return null + return null; } - const [item] = payload - const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}` - const itemConfig = getPayloadConfigFromPayload(config, item, key) + const [item] = payload; + const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`; + const itemConfig = getPayloadConfigFromPayload(config, item, key); const value = !labelKey && typeof label === "string" ? (config[label]?.label ?? label) - : itemConfig?.label + : itemConfig?.label; if (labelFormatter) { return (
{labelFormatter(value, payload)}
- ) + ); } if (!value) { - return null + return null; } - return
{value}
+ return
{value}
; }, [ label, labelFormatter, @@ -180,19 +180,19 @@ function ChartTooltipContent({ labelClassName, config, labelKey, - ]) + ]); if (!active || !payload?.length) { - return null + return null; } - const nestLabel = payload.length === 1 && indicator !== "dot" + const nestLabel = payload.length === 1 && indicator !== "dot"; return (
{!nestLabel ? tooltipLabel : null} @@ -200,16 +200,16 @@ function ChartTooltipContent({ {payload .filter((item) => item.type !== "none") .map((item, index) => { - const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}` - const itemConfig = getPayloadConfigFromPayload(config, item, key) - const indicatorColor = color ?? item.payload?.fill ?? item.color + const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`; + const itemConfig = getPayloadConfigFromPayload(config, item, key); + const indicatorColor = color ?? item.payload?.fill ?? item.color; return (
svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground", - indicator === "dot" && "items-center" + indicator === "dot" && "items-center", )} > {formatter && item?.value !== undefined && item.name ? ( @@ -229,7 +229,7 @@ function ChartTooltipContent({ "w-0 border-[1.5px] border-dashed bg-transparent": indicator === "dashed", "my-0.5": nestLabel && indicator === "dashed", - } + }, )} style={ { @@ -243,7 +243,7 @@ function ChartTooltipContent({
@@ -263,14 +263,14 @@ function ChartTooltipContent({ )}
- ) + ); })}
- ) + ); } -const ChartLegend = RechartsPrimitive.Legend +const ChartLegend = RechartsPrimitive.Legend; function ChartLegendContent({ className, @@ -279,13 +279,13 @@ function ChartLegendContent({ verticalAlign = "bottom", nameKey, }: React.ComponentProps<"div"> & { - hideIcon?: boolean - nameKey?: string + hideIcon?: boolean; + nameKey?: string; } & RechartsPrimitive.DefaultLegendContentProps) { - const { config } = useChart() + const { config } = useChart(); if (!payload?.length) { - return null + return null; } return ( @@ -293,20 +293,20 @@ function ChartLegendContent({ className={cn( "flex items-center justify-center gap-4", verticalAlign === "top" ? "pb-3" : "pt-3", - className + className, )} > {payload .filter((item) => item.type !== "none") .map((item, index) => { - const key = `${nameKey ?? item.dataKey ?? "value"}` - const itemConfig = getPayloadConfigFromPayload(config, item, key) + const key = `${nameKey ?? item.dataKey ?? "value"}`; + const itemConfig = getPayloadConfigFromPayload(config, item, key); return (
svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground" + "flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground", )} > {itemConfig?.icon && !hideIcon ? ( @@ -321,19 +321,19 @@ function ChartLegendContent({ )} {itemConfig?.label}
- ) + ); })}
- ) + ); } function getPayloadConfigFromPayload( config: ChartConfig, payload: unknown, - key: string + key: string, ) { if (typeof payload !== "object" || payload === null) { - return undefined + return undefined; } const payloadPayload = @@ -341,15 +341,15 @@ function getPayloadConfigFromPayload( typeof payload.payload === "object" && payload.payload !== null ? payload.payload - : undefined + : undefined; - let configLabelKey: string = key + let configLabelKey: string = key; if ( key in payload && typeof payload[key as keyof typeof payload] === "string" ) { - configLabelKey = payload[key as keyof typeof payload] as string + configLabelKey = payload[key as keyof typeof payload] as string; } else if ( payloadPayload && key in payloadPayload && @@ -357,10 +357,10 @@ function getPayloadConfigFromPayload( ) { configLabelKey = payloadPayload[ key as keyof typeof payloadPayload - ] as string + ] as string; } - return configLabelKey in config ? config[configLabelKey] : config[key] + return configLabelKey in config ? config[configLabelKey] : config[key]; } export { @@ -370,4 +370,4 @@ export { ChartLegend, ChartLegendContent, ChartStyle, -} +}; diff --git a/components/ui/checkbox.tsx b/components/ui/checkbox.tsx index 9e22145..f94b930 100644 --- a/components/ui/checkbox.tsx +++ b/components/ui/checkbox.tsx @@ -1,10 +1,10 @@ -"use client" +"use client"; -import * as React from "react" -import { Checkbox as CheckboxPrimitive } from "radix-ui" +import * as React from "react"; +import { Checkbox as CheckboxPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" -import { CheckIcon } from "lucide-react" +import { cn } from "@/lib/utils"; +import { CheckIcon } from "lucide-react"; function Checkbox({ className, @@ -15,7 +15,7 @@ function Checkbox({ data-slot="checkbox" className={cn( "peer relative flex size-4 shrink-0 items-center justify-center rounded-[6px] border border-input transition-shadow outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-[3px] aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary", - className + className, )} {...props} > @@ -23,11 +23,10 @@ function Checkbox({ data-slot="checkbox-indicator" className="grid place-content-center text-current transition-none [&>svg]:size-3.5" > - + - ) + ); } -export { Checkbox } +export { Checkbox }; diff --git a/components/ui/collapsible.tsx b/components/ui/collapsible.tsx index 2f7a4e7..a8bf893 100644 --- a/components/ui/collapsible.tsx +++ b/components/ui/collapsible.tsx @@ -1,11 +1,11 @@ -"use client" +"use client"; -import { Collapsible as CollapsiblePrimitive } from "radix-ui" +import { Collapsible as CollapsiblePrimitive } from "radix-ui"; function Collapsible({ ...props }: React.ComponentProps) { - return + return ; } function CollapsibleTrigger({ @@ -16,7 +16,7 @@ function CollapsibleTrigger({ data-slot="collapsible-trigger" {...props} /> - ) + ); } function CollapsibleContent({ @@ -27,7 +27,7 @@ function CollapsibleContent({ data-slot="collapsible-content" {...props} /> - ) + ); } -export { Collapsible, CollapsibleTrigger, CollapsibleContent } +export { Collapsible, CollapsibleTrigger, CollapsibleContent }; diff --git a/components/ui/command.tsx b/components/ui/command.tsx index d6375b3..d240bc8 100644 --- a/components/ui/command.tsx +++ b/components/ui/command.tsx @@ -1,21 +1,18 @@ -"use client" +"use client"; -import * as React from "react" -import { Command as CommandPrimitive } from "cmdk" +import * as React from "react"; +import { Command as CommandPrimitive } from "cmdk"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, -} from "@/components/ui/dialog" -import { - InputGroup, - InputGroupAddon, -} from "@/components/ui/input-group" -import { SearchIcon, CheckIcon } from "lucide-react" +} from "@/components/ui/dialog"; +import { InputGroup, InputGroupAddon } from "@/components/ui/input-group"; +import { SearchIcon, CheckIcon } from "lucide-react"; function Command({ className, @@ -26,11 +23,11 @@ function Command({ data-slot="command" className={cn( "flex size-full flex-col overflow-hidden rounded-4xl bg-popover p-1 text-popover-foreground", - className + className, )} {...props} /> - ) + ); } function CommandDialog({ @@ -41,10 +38,10 @@ function CommandDialog({ showCloseButton = false, ...props }: React.ComponentProps & { - title?: string - description?: string - className?: string - showCloseButton?: boolean + title?: string; + description?: string; + className?: string; + showCloseButton?: boolean; }) { return ( @@ -55,14 +52,14 @@ function CommandDialog({ {children} - ) + ); } function CommandInput({ @@ -76,7 +73,7 @@ function CommandInput({ data-slot="command-input" className={cn( "w-full text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50", - className + className, )} {...props} /> @@ -85,7 +82,7 @@ function CommandInput({
- ) + ); } function CommandList({ @@ -97,11 +94,11 @@ function CommandList({ data-slot="command-list" className={cn( "no-scrollbar max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto outline-none", - className + className, )} {...props} /> - ) + ); } function CommandEmpty({ @@ -114,7 +111,7 @@ function CommandEmpty({ className={cn("py-6 text-center text-sm", className)} {...props} /> - ) + ); } function CommandGroup({ @@ -126,11 +123,11 @@ function CommandGroup({ data-slot="command-group" className={cn( "overflow-hidden p-1 text-foreground **:[[cmdk-group-heading]]:px-3 **:[[cmdk-group-heading]]:py-2 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-muted-foreground", - className + className, )} {...props} /> - ) + ); } function CommandSeparator({ @@ -143,7 +140,7 @@ function CommandSeparator({ className={cn("my-1 h-px bg-border/50", className)} {...props} /> - ) + ); } function CommandItem({ @@ -156,14 +153,14 @@ function CommandItem({ data-slot="command-item" className={cn( "group/command-item relative flex cursor-default items-center gap-2 rounded-lg px-3 py-2 text-sm outline-hidden select-none in-data-[slot=dialog-content]:rounded-2xl data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:*:[svg]:text-foreground", - className + className, )} {...props} > {children} - ) + ); } function CommandShortcut({ @@ -175,11 +172,11 @@ function CommandShortcut({ data-slot="command-shortcut" className={cn( "ml-auto text-xs tracking-widest text-muted-foreground group-data-selected/command-item:text-foreground", - className + className, )} {...props} /> - ) + ); } export { @@ -192,4 +189,4 @@ export { CommandItem, CommandShortcut, CommandSeparator, -} +}; diff --git a/components/ui/context-menu.tsx b/components/ui/context-menu.tsx index ef28518..df8cafa 100644 --- a/components/ui/context-menu.tsx +++ b/components/ui/context-menu.tsx @@ -1,15 +1,15 @@ -"use client" +"use client"; -import * as React from "react" -import { ContextMenu as ContextMenuPrimitive } from "radix-ui" +import * as React from "react"; +import { ContextMenu as ContextMenuPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" -import { ChevronRightIcon, CheckIcon } from "lucide-react" +import { cn } from "@/lib/utils"; +import { ChevronRightIcon, CheckIcon } from "lucide-react"; function ContextMenu({ ...props }: React.ComponentProps) { - return + return ; } function ContextMenuTrigger({ @@ -22,7 +22,7 @@ function ContextMenuTrigger({ className={cn("select-none", className)} {...props} /> - ) + ); } function ContextMenuGroup({ @@ -30,7 +30,7 @@ function ContextMenuGroup({ }: React.ComponentProps) { return ( - ) + ); } function ContextMenuPortal({ @@ -38,13 +38,13 @@ function ContextMenuPortal({ }: React.ComponentProps) { return ( - ) + ); } function ContextMenuSub({ ...props }: React.ComponentProps) { - return + return ; } function ContextMenuRadioGroup({ @@ -55,24 +55,27 @@ function ContextMenuRadioGroup({ data-slot="context-menu-radio-group" {...props} /> - ) + ); } function ContextMenuContent({ className, ...props }: React.ComponentProps & { - side?: "top" | "right" | "bottom" | "left" + side?: "top" | "right" | "bottom" | "left"; }) { return ( - ) + ); } function ContextMenuItem({ @@ -81,8 +84,8 @@ function ContextMenuItem({ variant = "default", ...props }: React.ComponentProps & { - inset?: boolean - variant?: "default" | "destructive" + inset?: boolean; + variant?: "default" | "destructive"; }) { return ( - ) + ); } function ContextMenuSubTrigger({ @@ -104,7 +107,7 @@ function ContextMenuSubTrigger({ children, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( {children} - ) + ); } function ContextMenuSubContent({ @@ -129,10 +132,13 @@ function ContextMenuSubContent({ return ( - ) + ); } function ContextMenuCheckboxItem({ @@ -142,7 +148,7 @@ function ContextMenuCheckboxItem({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - + {children} - ) + ); } function ContextMenuRadioItem({ @@ -172,7 +177,7 @@ function ContextMenuRadioItem({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - + {children} - ) + ); } function ContextMenuLabel({ @@ -200,7 +204,7 @@ function ContextMenuLabel({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - ) + ); } function ContextMenuSeparator({ @@ -225,7 +229,7 @@ function ContextMenuSeparator({ className={cn("-mx-1 my-1 h-px bg-border/50", className)} {...props} /> - ) + ); } function ContextMenuShortcut({ @@ -237,11 +241,11 @@ function ContextMenuShortcut({ data-slot="context-menu-shortcut" className={cn( "ml-auto text-xs tracking-widest text-muted-foreground group-focus/context-menu-item:text-accent-foreground", - className + className, )} {...props} /> - ) + ); } export { @@ -260,4 +264,4 @@ export { ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuRadioGroup, -} +}; diff --git a/components/ui/dialog.tsx b/components/ui/dialog.tsx index 7c17b89..5bbf68e 100644 --- a/components/ui/dialog.tsx +++ b/components/ui/dialog.tsx @@ -1,34 +1,34 @@ -"use client" +"use client"; -import * as React from "react" -import { Dialog as DialogPrimitive } from "radix-ui" +import * as React from "react"; +import { Dialog as DialogPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" -import { Button } from "@/components/ui/button" -import { XIcon } from "lucide-react" +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { XIcon } from "lucide-react"; function Dialog({ ...props }: React.ComponentProps) { - return + return ; } function DialogTrigger({ ...props }: React.ComponentProps) { - return + return ; } function DialogPortal({ ...props }: React.ComponentProps) { - return + return ; } function DialogClose({ ...props }: React.ComponentProps) { - return + return ; } function DialogOverlay({ @@ -40,11 +40,11 @@ function DialogOverlay({ data-slot="dialog-overlay" className={cn( "fixed inset-0 isolate z-50 bg-black/80 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0", - className + className, )} {...props} /> - ) + ); } function DialogContent({ @@ -53,7 +53,7 @@ function DialogContent({ showCloseButton = true, ...props }: React.ComponentProps & { - showCloseButton?: boolean + showCloseButton?: boolean; }) { return ( @@ -62,7 +62,7 @@ function DialogContent({ data-slot="dialog-content" className={cn( "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-6 rounded-4xl bg-popover p-6 text-sm text-popover-foreground ring-1 ring-foreground/5 duration-100 outline-none sm:max-w-md data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", - className + className, )} {...props} > @@ -74,15 +74,14 @@ function DialogContent({ className="absolute top-4 right-4" size="icon-sm" > - + Close )} - ) + ); } function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { @@ -92,7 +91,7 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { className={cn("flex flex-col gap-2", className)} {...props} /> - ) + ); } function DialogFooter({ @@ -101,14 +100,14 @@ function DialogFooter({ children, ...props }: React.ComponentProps<"div"> & { - showCloseButton?: boolean + showCloseButton?: boolean; }) { return (
@@ -119,7 +118,7 @@ function DialogFooter({ )}
- ) + ); } function DialogTitle({ @@ -129,13 +128,10 @@ function DialogTitle({ return ( - ) + ); } function DialogDescription({ @@ -147,11 +143,11 @@ function DialogDescription({ data-slot="dialog-description" className={cn( "text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground", - className + className, )} {...props} /> - ) + ); } export { @@ -165,4 +161,4 @@ export { DialogPortal, DialogTitle, DialogTrigger, -} +}; diff --git a/components/ui/direction.tsx b/components/ui/direction.tsx index 22e1657..ed312b3 100644 --- a/components/ui/direction.tsx +++ b/components/ui/direction.tsx @@ -1,22 +1,22 @@ -"use client" +"use client"; -import * as React from "react" -import { Direction } from "radix-ui" +import * as React from "react"; +import { Direction } from "radix-ui"; function DirectionProvider({ dir, direction, children, }: React.ComponentProps & { - direction?: React.ComponentProps["dir"] + direction?: React.ComponentProps["dir"]; }) { return ( {children} - ) + ); } -const useDirection = Direction.useDirection +const useDirection = Direction.useDirection; -export { DirectionProvider, useDirection } +export { DirectionProvider, useDirection }; diff --git a/components/ui/drawer.tsx b/components/ui/drawer.tsx index ea5b6d3..ede913e 100644 --- a/components/ui/drawer.tsx +++ b/components/ui/drawer.tsx @@ -1,32 +1,32 @@ -"use client" +"use client"; -import * as React from "react" -import { Drawer as DrawerPrimitive } from "vaul" +import * as React from "react"; +import { Drawer as DrawerPrimitive } from "vaul"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Drawer({ ...props }: React.ComponentProps) { - return + return ; } function DrawerTrigger({ ...props }: React.ComponentProps) { - return + return ; } function DrawerPortal({ ...props }: React.ComponentProps) { - return + return ; } function DrawerClose({ ...props }: React.ComponentProps) { - return + return ; } function DrawerOverlay({ @@ -38,11 +38,11 @@ function DrawerOverlay({ data-slot="drawer-overlay" className={cn( "fixed inset-0 z-50 bg-black/80 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0", - className + className, )} {...props} /> - ) + ); } function DrawerContent({ @@ -57,7 +57,7 @@ function DrawerContent({ data-slot="drawer-content" className={cn( "group/drawer-content fixed z-50 flex h-auto flex-col bg-transparent p-4 text-sm text-popover-foreground before:absolute before:inset-2 before:-z-10 before:rounded-4xl before:border before:border-border before:bg-popover data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=left]:sm:max-w-sm data-[vaul-drawer-direction=right]:sm:max-w-sm", - className + className, )} {...props} > @@ -65,7 +65,7 @@ function DrawerContent({ {children} - ) + ); } function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) { @@ -74,11 +74,11 @@ function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) { data-slot="drawer-header" className={cn( "flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left", - className + className, )} {...props} /> - ) + ); } function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) { @@ -88,7 +88,7 @@ function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) { className={cn("mt-auto flex flex-col gap-2 p-4", className)} {...props} /> - ) + ); } function DrawerTitle({ @@ -98,13 +98,10 @@ function DrawerTitle({ return ( - ) + ); } function DrawerDescription({ @@ -117,7 +114,7 @@ function DrawerDescription({ className={cn("text-sm text-muted-foreground", className)} {...props} /> - ) + ); } export { @@ -131,4 +128,4 @@ export { DrawerFooter, DrawerTitle, DrawerDescription, -} +}; diff --git a/components/ui/dropdown-menu.tsx b/components/ui/dropdown-menu.tsx index 172cc15..8027fc2 100644 --- a/components/ui/dropdown-menu.tsx +++ b/components/ui/dropdown-menu.tsx @@ -1,15 +1,15 @@ -"use client" +"use client"; -import * as React from "react" -import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui" +import * as React from "react"; +import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" -import { CheckIcon, ChevronRightIcon } from "lucide-react" +import { cn } from "@/lib/utils"; +import { CheckIcon, ChevronRightIcon } from "lucide-react"; function DropdownMenu({ ...props }: React.ComponentProps) { - return + return ; } function DropdownMenuPortal({ @@ -17,7 +17,7 @@ function DropdownMenuPortal({ }: React.ComponentProps) { return ( - ) + ); } function DropdownMenuTrigger({ @@ -28,7 +28,7 @@ function DropdownMenuTrigger({ data-slot="dropdown-menu-trigger" {...props} /> - ) + ); } function DropdownMenuContent({ @@ -43,11 +43,14 @@ function DropdownMenuContent({ data-slot="dropdown-menu-content" sideOffset={sideOffset} align={align} - className={cn("z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-48 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-2xl bg-popover p-1 text-popover-foreground shadow-2xl ring-1 ring-foreground/5 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden dark:ring-foreground/10 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )} + className={cn( + "z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-48 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-2xl bg-popover p-1 text-popover-foreground shadow-2xl ring-1 ring-foreground/5 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden dark:ring-foreground/10 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", + className, + )} {...props} /> - ) + ); } function DropdownMenuGroup({ @@ -55,7 +58,7 @@ function DropdownMenuGroup({ }: React.ComponentProps) { return ( - ) + ); } function DropdownMenuItem({ @@ -64,8 +67,8 @@ function DropdownMenuItem({ variant = "default", ...props }: React.ComponentProps & { - inset?: boolean - variant?: "default" | "destructive" + inset?: boolean; + variant?: "default" | "destructive"; }) { return ( - ) + ); } function DropdownMenuCheckboxItem({ @@ -88,7 +91,7 @@ function DropdownMenuCheckboxItem({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - + {children} - ) + ); } function DropdownMenuRadioGroup({ @@ -123,7 +125,7 @@ function DropdownMenuRadioGroup({ data-slot="dropdown-menu-radio-group" {...props} /> - ) + ); } function DropdownMenuRadioItem({ @@ -132,7 +134,7 @@ function DropdownMenuRadioItem({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( @@ -149,13 +151,12 @@ function DropdownMenuRadioItem({ data-slot="dropdown-menu-radio-item-indicator" > - + {children} - ) + ); } function DropdownMenuLabel({ @@ -163,7 +164,7 @@ function DropdownMenuLabel({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - ) + ); } function DropdownMenuSeparator({ @@ -188,7 +189,7 @@ function DropdownMenuSeparator({ className={cn("-mx-1 my-1 h-px bg-border/50", className)} {...props} /> - ) + ); } function DropdownMenuShortcut({ @@ -200,17 +201,17 @@ function DropdownMenuShortcut({ data-slot="dropdown-menu-shortcut" className={cn( "ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground", - className + className, )} {...props} /> - ) + ); } function DropdownMenuSub({ ...props }: React.ComponentProps) { - return + return ; } function DropdownMenuSubTrigger({ @@ -219,7 +220,7 @@ function DropdownMenuSubTrigger({ children, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( {children} - ) + ); } function DropdownMenuSubContent({ @@ -244,10 +245,13 @@ function DropdownMenuSubContent({ return ( - ) + ); } export { @@ -266,4 +270,4 @@ export { DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent, -} +}; diff --git a/components/ui/empty.tsx b/components/ui/empty.tsx index f96c914..ee9b00d 100644 --- a/components/ui/empty.tsx +++ b/components/ui/empty.tsx @@ -1,6 +1,6 @@ -import { cva, type VariantProps } from "class-variance-authority" +import { cva, type VariantProps } from "class-variance-authority"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Empty({ className, ...props }: React.ComponentProps<"div">) { return ( @@ -8,11 +8,11 @@ function Empty({ className, ...props }: React.ComponentProps<"div">) { data-slot="empty" className={cn( "flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-lg border-dashed p-12 text-center text-balance", - className + className, )} {...props} /> - ) + ); } function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) { @@ -22,7 +22,7 @@ function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) { className={cn("flex max-w-sm flex-col items-center gap-2", className)} {...props} /> - ) + ); } const emptyMediaVariants = cva( @@ -37,8 +37,8 @@ const emptyMediaVariants = cva( defaultVariants: { variant: "default", }, - } -) + }, +); function EmptyMedia({ className, @@ -52,20 +52,17 @@ function EmptyMedia({ className={cn(emptyMediaVariants({ variant, className }))} {...props} /> - ) + ); } function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) { return (
- ) + ); } function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) { @@ -74,11 +71,11 @@ function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) { data-slot="empty-description" className={cn( "text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary", - className + className, )} {...props} /> - ) + ); } function EmptyContent({ className, ...props }: React.ComponentProps<"div">) { @@ -87,11 +84,11 @@ function EmptyContent({ className, ...props }: React.ComponentProps<"div">) { data-slot="empty-content" className={cn( "flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance", - className + className, )} {...props} /> - ) + ); } export { @@ -101,4 +98,4 @@ export { EmptyDescription, EmptyContent, EmptyMedia, -} +}; diff --git a/components/ui/field.tsx b/components/ui/field.tsx index 0c3dde6..ec2409a 100644 --- a/components/ui/field.tsx +++ b/components/ui/field.tsx @@ -1,11 +1,11 @@ -"use client" +"use client"; -import { useMemo } from "react" -import { cva, type VariantProps } from "class-variance-authority" +import { useMemo } from "react"; +import { cva, type VariantProps } from "class-variance-authority"; -import { cn } from "@/lib/utils" -import { Label } from "@/components/ui/label" -import { Separator } from "@/components/ui/separator" +import { cn } from "@/lib/utils"; +import { Label } from "@/components/ui/label"; +import { Separator } from "@/components/ui/separator"; function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) { return ( @@ -13,11 +13,11 @@ function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) { data-slot="field-set" className={cn( "flex flex-col gap-6 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3", - className + className, )} {...props} /> - ) + ); } function FieldLegend({ @@ -31,11 +31,11 @@ function FieldLegend({ data-variant={variant} className={cn( "mb-3 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base", - className + className, )} {...props} /> - ) + ); } function FieldGroup({ className, ...props }: React.ComponentProps<"div">) { @@ -44,11 +44,11 @@ function FieldGroup({ className, ...props }: React.ComponentProps<"div">) { data-slot="field-group" className={cn( "group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4", - className + className, )} {...props} /> - ) + ); } const fieldVariants = cva( @@ -66,8 +66,8 @@ const fieldVariants = cva( defaultVariants: { orientation: "vertical", }, - } -) + }, +); function Field({ className, @@ -82,7 +82,7 @@ function Field({ className={cn(fieldVariants({ orientation }), className)} {...props} /> - ) + ); } function FieldContent({ className, ...props }: React.ComponentProps<"div">) { @@ -91,11 +91,11 @@ function FieldContent({ className, ...props }: React.ComponentProps<"div">) { data-slot="field-content" className={cn( "group/field-content flex flex-1 flex-col gap-1 leading-snug", - className + className, )} {...props} /> - ) + ); } function FieldLabel({ @@ -108,11 +108,11 @@ function FieldLabel({ className={cn( "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-xl has-[>[data-slot=field]]:border *:data-[slot=field]:p-4 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10", "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col", - className + className, )} {...props} /> - ) + ); } function FieldTitle({ className, ...props }: React.ComponentProps<"div">) { @@ -121,11 +121,11 @@ function FieldTitle({ className, ...props }: React.ComponentProps<"div">) { data-slot="field-label" className={cn( "flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50", - className + className, )} {...props} /> - ) + ); } function FieldDescription({ className, ...props }: React.ComponentProps<"p">) { @@ -136,11 +136,11 @@ function FieldDescription({ className, ...props }: React.ComponentProps<"p">) { "text-left text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5", "last:mt-0 nth-last-2:-mt-1", "[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary", - className + className, )} {...props} /> - ) + ); } function FieldSeparator({ @@ -148,7 +148,7 @@ function FieldSeparator({ className, ...props }: React.ComponentProps<"div"> & { - children?: React.ReactNode + children?: React.ReactNode; }) { return (
@@ -170,7 +170,7 @@ function FieldSeparator({ )}
- ) + ); } function FieldError({ @@ -179,37 +179,37 @@ function FieldError({ errors, ...props }: React.ComponentProps<"div"> & { - errors?: Array<{ message?: string } | undefined> + errors?: Array<{ message?: string } | undefined>; }) { const content = useMemo(() => { if (children) { - return children + return children; } if (!errors?.length) { - return null + return null; } const uniqueErrors = [ ...new Map(errors.map((error) => [error?.message, error])).values(), - ] + ]; if (uniqueErrors?.length == 1) { - return uniqueErrors[0]?.message + return uniqueErrors[0]?.message; } return (
    {uniqueErrors.map( (error, index) => - error?.message &&
  • {error.message}
  • + error?.message &&
  • {error.message}
  • , )}
- ) - }, [children, errors]) + ); + }, [children, errors]); if (!content) { - return null + return null; } return ( @@ -221,7 +221,7 @@ function FieldError({ > {content}
- ) + ); } export { @@ -235,4 +235,4 @@ export { FieldSet, FieldContent, FieldTitle, -} +}; diff --git a/components/ui/form.tsx b/components/ui/form.tsx index 524b986..bf4214d 100644 --- a/components/ui/form.tsx +++ b/components/ui/form.tsx @@ -1,8 +1,8 @@ -"use client" +"use client"; -import * as React from "react" -import * as LabelPrimitive from "@radix-ui/react-label" -import { Slot } from "@radix-ui/react-slot" +import * as React from "react"; +import * as LabelPrimitive from "@radix-ui/react-label"; +import { Slot } from "@radix-ui/react-slot"; import { Controller, FormProvider, @@ -11,23 +11,23 @@ import { type ControllerProps, type FieldPath, type FieldValues, -} from "react-hook-form" +} from "react-hook-form"; -import { cn } from "@/lib/utils" -import { Label } from "@/components/ui/label" +import { cn } from "@/lib/utils"; +import { Label } from "@/components/ui/label"; -const Form = FormProvider +const Form = FormProvider; type FormFieldContextValue< TFieldValues extends FieldValues = FieldValues, TName extends FieldPath = FieldPath, > = { - name: TName -} + name: TName; +}; const FormFieldContext = React.createContext( - {} as FormFieldContextValue -) + {} as FormFieldContextValue, +); const FormField = < TFieldValues extends FieldValues = FieldValues, @@ -39,21 +39,21 @@ const FormField = < - ) -} + ); +}; const useFormField = () => { - const fieldContext = React.useContext(FormFieldContext) - const itemContext = React.useContext(FormItemContext) - const { getFieldState } = useFormContext() - const formState = useFormState({ name: fieldContext.name }) - const fieldState = getFieldState(fieldContext.name, formState) + const fieldContext = React.useContext(FormFieldContext); + const itemContext = React.useContext(FormItemContext); + const { getFieldState } = useFormContext(); + const formState = useFormState({ name: fieldContext.name }); + const fieldState = getFieldState(fieldContext.name, formState); if (!fieldContext) { - throw new Error("useFormField should be used within ") + throw new Error("useFormField should be used within "); } - const { id } = itemContext + const { id } = itemContext; return { id, @@ -62,19 +62,19 @@ const useFormField = () => { formDescriptionId: `${id}-form-item-description`, formMessageId: `${id}-form-item-message`, ...fieldState, - } -} + }; +}; type FormItemContextValue = { - id: string -} + id: string; +}; const FormItemContext = React.createContext( - {} as FormItemContextValue -) + {} as FormItemContextValue, +); function FormItem({ className, ...props }: React.ComponentProps<"div">) { - const id = React.useId() + const id = React.useId(); return ( @@ -84,14 +84,14 @@ function FormItem({ className, ...props }: React.ComponentProps<"div">) { {...props} /> - ) + ); } function FormLabel({ className, ...props }: React.ComponentProps) { - const { error, formItemId } = useFormField() + const { error, formItemId } = useFormField(); return (
- ) + ); } function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) { @@ -78,10 +78,9 @@ function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) { role="separator" {...props} > - +
- ) + ); } -export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator } +export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }; diff --git a/components/ui/input.tsx b/components/ui/input.tsx index e49996f..4acc3ed 100644 --- a/components/ui/input.tsx +++ b/components/ui/input.tsx @@ -1,6 +1,6 @@ -import * as React from "react" +import * as React from "react"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Input({ className, type, ...props }: React.ComponentProps<"input">) { return ( @@ -9,11 +9,11 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) { data-slot="input" className={cn( "h-9 w-full min-w-0 rounded-4xl border border-input bg-input/30 px-3 py-1 text-base transition-colors outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-[3px] aria-invalid:ring-destructive/20 md:text-sm dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40", - className + className, )} {...props} /> - ) + ); } -export { Input } +export { Input }; diff --git a/components/ui/item.tsx b/components/ui/item.tsx index 2d49219..ee9a96f 100644 --- a/components/ui/item.tsx +++ b/components/ui/item.tsx @@ -1,9 +1,9 @@ -import * as React from "react" -import { cva, type VariantProps } from "class-variance-authority" -import { Slot } from "radix-ui" +import * as React from "react"; +import { cva, type VariantProps } from "class-variance-authority"; +import { Slot } from "radix-ui"; -import { cn } from "@/lib/utils" -import { Separator } from "@/components/ui/separator" +import { cn } from "@/lib/utils"; +import { Separator } from "@/components/ui/separator"; function ItemGroup({ className, ...props }: React.ComponentProps<"div">) { return ( @@ -12,11 +12,11 @@ function ItemGroup({ className, ...props }: React.ComponentProps<"div">) { data-slot="item-group" className={cn( "group/item-group flex w-full flex-col gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2", - className + className, )} {...props} /> - ) + ); } function ItemSeparator({ @@ -30,7 +30,7 @@ function ItemSeparator({ className={cn("my-2", className)} {...props} /> - ) + ); } const itemVariants = cva( @@ -52,8 +52,8 @@ const itemVariants = cva( variant: "default", size: "default", }, - } -) + }, +); function Item({ className, @@ -63,7 +63,7 @@ function Item({ ...props }: React.ComponentProps<"div"> & VariantProps & { asChild?: boolean }) { - const Comp = asChild ? Slot.Root : "div" + const Comp = asChild ? Slot.Root : "div"; return ( - ) + ); } const itemMediaVariants = cva( @@ -89,8 +89,8 @@ const itemMediaVariants = cva( defaultVariants: { variant: "default", }, - } -) + }, +); function ItemMedia({ className, @@ -104,7 +104,7 @@ function ItemMedia({ className={cn(itemMediaVariants({ variant, className }))} {...props} /> - ) + ); } function ItemContent({ className, ...props }: React.ComponentProps<"div">) { @@ -113,11 +113,11 @@ function ItemContent({ className, ...props }: React.ComponentProps<"div">) { data-slot="item-content" className={cn( "flex flex-1 flex-col gap-1 group-data-[size=xs]/item:gap-0.5 [&+[data-slot=item-content]]:flex-none", - className + className, )} {...props} /> - ) + ); } function ItemTitle({ className, ...props }: React.ComponentProps<"div">) { @@ -126,11 +126,11 @@ function ItemTitle({ className, ...props }: React.ComponentProps<"div">) { data-slot="item-title" className={cn( "line-clamp-1 flex w-fit items-center gap-2 text-sm leading-snug font-medium underline-offset-4", - className + className, )} {...props} /> - ) + ); } function ItemDescription({ className, ...props }: React.ComponentProps<"p">) { @@ -139,11 +139,11 @@ function ItemDescription({ className, ...props }: React.ComponentProps<"p">) { data-slot="item-description" className={cn( "line-clamp-2 text-left text-sm font-normal text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary", - className + className, )} {...props} /> - ) + ); } function ItemActions({ className, ...props }: React.ComponentProps<"div">) { @@ -153,7 +153,7 @@ function ItemActions({ className, ...props }: React.ComponentProps<"div">) { className={cn("flex items-center gap-2", className)} {...props} /> - ) + ); } function ItemHeader({ className, ...props }: React.ComponentProps<"div">) { @@ -162,11 +162,11 @@ function ItemHeader({ className, ...props }: React.ComponentProps<"div">) { data-slot="item-header" className={cn( "flex basis-full items-center justify-between gap-2", - className + className, )} {...props} /> - ) + ); } function ItemFooter({ className, ...props }: React.ComponentProps<"div">) { @@ -175,11 +175,11 @@ function ItemFooter({ className, ...props }: React.ComponentProps<"div">) { data-slot="item-footer" className={cn( "flex basis-full items-center justify-between gap-2", - className + className, )} {...props} /> - ) + ); } export { @@ -193,4 +193,4 @@ export { ItemDescription, ItemHeader, ItemFooter, -} +}; diff --git a/components/ui/kbd.tsx b/components/ui/kbd.tsx index ff93b53..44df653 100644 --- a/components/ui/kbd.tsx +++ b/components/ui/kbd.tsx @@ -1,4 +1,4 @@ -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Kbd({ className, ...props }: React.ComponentProps<"kbd">) { return ( @@ -6,11 +6,11 @@ function Kbd({ className, ...props }: React.ComponentProps<"kbd">) { data-slot="kbd" className={cn( "pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm bg-muted px-1 font-sans text-xs font-medium text-muted-foreground select-none in-data-[slot=tooltip-content]:bg-background/20 in-data-[slot=tooltip-content]:text-background dark:in-data-[slot=tooltip-content]:bg-background/10 [&_svg:not([class*='size-'])]:size-3", - className + className, )} {...props} /> - ) + ); } function KbdGroup({ className, ...props }: React.ComponentProps<"div">) { @@ -20,7 +20,7 @@ function KbdGroup({ className, ...props }: React.ComponentProps<"div">) { className={cn("inline-flex items-center gap-1", className)} {...props} /> - ) + ); } -export { Kbd, KbdGroup } +export { Kbd, KbdGroup }; diff --git a/components/ui/label.tsx b/components/ui/label.tsx index 1ac80f7..573d586 100644 --- a/components/ui/label.tsx +++ b/components/ui/label.tsx @@ -1,9 +1,9 @@ -"use client" +"use client"; -import * as React from "react" -import { Label as LabelPrimitive } from "radix-ui" +import * as React from "react"; +import { Label as LabelPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Label({ className, @@ -14,11 +14,11 @@ function Label({ data-slot="label" className={cn( "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50", - className + className, )} {...props} /> - ) + ); } -export { Label } +export { Label }; diff --git a/components/ui/menubar.tsx b/components/ui/menubar.tsx index bc46223..4014daf 100644 --- a/components/ui/menubar.tsx +++ b/components/ui/menubar.tsx @@ -1,10 +1,10 @@ -"use client" +"use client"; -import * as React from "react" -import { Menubar as MenubarPrimitive } from "radix-ui" +import * as React from "react"; +import { Menubar as MenubarPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" -import { CheckIcon, ChevronRightIcon } from "lucide-react" +import { cn } from "@/lib/utils"; +import { CheckIcon, ChevronRightIcon } from "lucide-react"; function Menubar({ className, @@ -16,25 +16,25 @@ function Menubar({ className={cn("flex h-9 items-center rounded-4xl border p-1", className)} {...props} /> - ) + ); } function MenubarMenu({ ...props }: React.ComponentProps) { - return + return ; } function MenubarGroup({ ...props }: React.ComponentProps) { - return + return ; } function MenubarPortal({ ...props }: React.ComponentProps) { - return + return ; } function MenubarRadioGroup({ @@ -42,7 +42,7 @@ function MenubarRadioGroup({ }: React.ComponentProps) { return ( - ) + ); } function MenubarTrigger({ @@ -54,11 +54,11 @@ function MenubarTrigger({ data-slot="menubar-trigger" className={cn( "flex items-center rounded-xl px-2 py-0.75 text-sm font-medium outline-hidden select-none hover:bg-muted aria-expanded:bg-muted", - className + className, )} {...props} /> - ) + ); } function MenubarContent({ @@ -75,11 +75,14 @@ function MenubarContent({ align={align} alignOffset={alignOffset} sideOffset={sideOffset} - className={cn("z-50 min-w-48 origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-2xl bg-popover p-1 text-popover-foreground shadow-2xl ring-1 ring-foreground/5 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95", className )} + className={cn( + "z-50 min-w-48 origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-2xl bg-popover p-1 text-popover-foreground shadow-2xl ring-1 ring-foreground/5 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95", + className, + )} {...props} /> - ) + ); } function MenubarItem({ @@ -88,8 +91,8 @@ function MenubarItem({ variant = "default", ...props }: React.ComponentProps & { - inset?: boolean - variant?: "default" | "destructive" + inset?: boolean; + variant?: "default" | "destructive"; }) { return ( - ) + ); } function MenubarCheckboxItem({ @@ -112,7 +115,7 @@ function MenubarCheckboxItem({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - + {children} - ) + ); } function MenubarRadioItem({ @@ -142,7 +144,7 @@ function MenubarRadioItem({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - + {children} - ) + ); } function MenubarLabel({ @@ -170,7 +171,7 @@ function MenubarLabel({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - ) + ); } function MenubarSeparator({ @@ -195,7 +196,7 @@ function MenubarSeparator({ className={cn("-mx-1 my-1 h-px bg-border/50", className)} {...props} /> - ) + ); } function MenubarShortcut({ @@ -207,17 +208,17 @@ function MenubarShortcut({ data-slot="menubar-shortcut" className={cn( "ml-auto text-xs tracking-widest text-muted-foreground group-focus/menubar-item:text-accent-foreground", - className + className, )} {...props} /> - ) + ); } function MenubarSub({ ...props }: React.ComponentProps) { - return + return ; } function MenubarSubTrigger({ @@ -226,7 +227,7 @@ function MenubarSubTrigger({ children, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( {children} - ) + ); } function MenubarSubContent({ @@ -251,10 +252,13 @@ function MenubarSubContent({ return ( - ) + ); } export { @@ -274,4 +278,4 @@ export { MenubarSub, MenubarSubTrigger, MenubarSubContent, -} +}; diff --git a/components/ui/native-select.tsx b/components/ui/native-select.tsx index b579bda..639482a 100644 --- a/components/ui/native-select.tsx +++ b/components/ui/native-select.tsx @@ -1,11 +1,11 @@ -import * as React from "react" +import * as React from "react"; -import { cn } from "@/lib/utils" -import { ChevronDownIcon } from "lucide-react" +import { cn } from "@/lib/utils"; +import { ChevronDownIcon } from "lucide-react"; type NativeSelectProps = Omit, "size"> & { - size?: "sm" | "default" -} + size?: "sm" | "default"; +}; function NativeSelect({ className, @@ -16,7 +16,7 @@ function NativeSelect({
-
- ) + ); } function NativeSelectOption({ @@ -42,7 +46,7 @@ function NativeSelectOption({ className={cn("bg-[Canvas] text-[CanvasText]", className)} {...props} /> - ) + ); } function NativeSelectOptGroup({ @@ -55,7 +59,7 @@ function NativeSelectOptGroup({ className={cn("bg-[Canvas] text-[CanvasText]", className)} {...props} /> - ) + ); } -export { NativeSelect, NativeSelectOptGroup, NativeSelectOption } +export { NativeSelect, NativeSelectOptGroup, NativeSelectOption }; diff --git a/components/ui/navigation-menu.tsx b/components/ui/navigation-menu.tsx index 9cda5a3..70d9086 100644 --- a/components/ui/navigation-menu.tsx +++ b/components/ui/navigation-menu.tsx @@ -1,9 +1,9 @@ -import * as React from "react" -import { cva } from "class-variance-authority" -import { NavigationMenu as NavigationMenuPrimitive } from "radix-ui" +import * as React from "react"; +import { cva } from "class-variance-authority"; +import { NavigationMenu as NavigationMenuPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" -import { ChevronDownIcon } from "lucide-react" +import { cn } from "@/lib/utils"; +import { ChevronDownIcon } from "lucide-react"; function NavigationMenu({ className, @@ -11,7 +11,7 @@ function NavigationMenu({ viewport = true, ...props }: React.ComponentProps & { - viewport?: boolean + viewport?: boolean; }) { return ( {children} {viewport && } - ) + ); } function NavigationMenuList({ @@ -38,11 +38,11 @@ function NavigationMenuList({ data-slot="navigation-menu-list" className={cn( "group flex flex-1 list-none items-center justify-center gap-0", - className + className, )} {...props} /> - ) + ); } function NavigationMenuItem({ @@ -55,12 +55,12 @@ function NavigationMenuItem({ className={cn("relative", className)} {...props} /> - ) + ); } const navigationMenuTriggerStyle = cva( - "group/navigation-menu-trigger inline-flex h-9 w-max items-center justify-center rounded-2xl px-4.5 py-2.5 text-sm font-medium transition-all outline-none hover:bg-muted focus:bg-muted focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-popup-open:bg-muted/50 data-popup-open:hover:bg-muted data-open:bg-muted/50 data-open:hover:bg-muted data-open:focus:bg-muted" -) + "group/navigation-menu-trigger inline-flex h-9 w-max items-center justify-center rounded-2xl px-4.5 py-2.5 text-sm font-medium transition-all outline-none hover:bg-muted focus:bg-muted focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-popup-open:bg-muted/50 data-popup-open:hover:bg-muted data-open:bg-muted/50 data-open:hover:bg-muted data-open:focus:bg-muted", +); function NavigationMenuTrigger({ className, @@ -74,9 +74,12 @@ function NavigationMenuTrigger({ {...props} > {children}{" "} -
- ) + ); } function SidebarTrigger({ @@ -258,7 +258,7 @@ function SidebarTrigger({ onClick, ...props }: React.ComponentProps) { - const { toggleSidebar } = useSidebar() + const { toggleSidebar } = useSidebar(); return ( - ) + ); } function SidebarRail({ className, ...props }: React.ComponentProps<"button">) { - const { toggleSidebar } = useSidebar() + const { toggleSidebar } = useSidebar(); return (
- ) + ); } function TableHeader({ className, ...props }: React.ComponentProps<"thead">) { @@ -26,7 +26,7 @@ function TableHeader({ className, ...props }: React.ComponentProps<"thead">) { className={cn("[&_tr]:border-b", className)} {...props} /> - ) + ); } function TableBody({ className, ...props }: React.ComponentProps<"tbody">) { @@ -36,7 +36,7 @@ function TableBody({ className, ...props }: React.ComponentProps<"tbody">) { className={cn("[&_tr:last-child]:border-0", className)} {...props} /> - ) + ); } function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) { @@ -45,11 +45,11 @@ function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) { data-slot="table-footer" className={cn( "border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", - className + className, )} {...props} /> - ) + ); } function TableRow({ className, ...props }: React.ComponentProps<"tr">) { @@ -58,11 +58,11 @@ function TableRow({ className, ...props }: React.ComponentProps<"tr">) { data-slot="table-row" className={cn( "border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted", - className + className, )} {...props} /> - ) + ); } function TableHead({ className, ...props }: React.ComponentProps<"th">) { @@ -71,11 +71,11 @@ function TableHead({ className, ...props }: React.ComponentProps<"th">) { data-slot="table-head" className={cn( "h-12 px-3 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0", - className + className, )} {...props} /> - ) + ); } function TableCell({ className, ...props }: React.ComponentProps<"td">) { @@ -84,11 +84,11 @@ function TableCell({ className, ...props }: React.ComponentProps<"td">) { data-slot="table-cell" className={cn( "p-3 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0", - className + className, )} {...props} /> - ) + ); } function TableCaption({ @@ -101,7 +101,7 @@ function TableCaption({ className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} /> - ) + ); } export { @@ -113,4 +113,4 @@ export { TableRow, TableCell, TableCaption, -} +}; diff --git a/components/ui/tabs.tsx b/components/ui/tabs.tsx index b641f89..f58fee9 100644 --- a/components/ui/tabs.tsx +++ b/components/ui/tabs.tsx @@ -1,10 +1,10 @@ -"use client" +"use client"; -import * as React from "react" -import { cva, type VariantProps } from "class-variance-authority" -import { Tabs as TabsPrimitive } from "radix-ui" +import * as React from "react"; +import { cva, type VariantProps } from "class-variance-authority"; +import { Tabs as TabsPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Tabs({ className, @@ -17,11 +17,11 @@ function Tabs({ data-orientation={orientation} className={cn( "group/tabs flex gap-2 data-horizontal:flex-col", - className + className, )} {...props} /> - ) + ); } const tabsListVariants = cva( @@ -36,8 +36,8 @@ const tabsListVariants = cva( defaultVariants: { variant: "default", }, - } -) + }, +); function TabsList({ className, @@ -52,7 +52,7 @@ function TabsList({ className={cn(tabsListVariants({ variant }), className)} {...props} /> - ) + ); } function TabsTrigger({ @@ -67,11 +67,11 @@ function TabsTrigger({ "group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent", "data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground", "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100", - className + className, )} {...props} /> - ) + ); } function TabsContent({ @@ -84,7 +84,7 @@ function TabsContent({ className={cn("flex-1 text-sm outline-none", className)} {...props} /> - ) + ); } -export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants } +export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }; diff --git a/components/ui/textarea.tsx b/components/ui/textarea.tsx index e62bf7d..c643606 100644 --- a/components/ui/textarea.tsx +++ b/components/ui/textarea.tsx @@ -1,6 +1,6 @@ -import * as React from "react" +import * as React from "react"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Textarea({ className, ...props }: React.ComponentProps<"textarea">) { return ( @@ -8,11 +8,11 @@ function Textarea({ className, ...props }: React.ComponentProps<"textarea">) { data-slot="textarea" className={cn( "flex field-sizing-content min-h-16 w-full resize-none rounded-xl border border-input bg-input/30 px-3 py-3 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-[3px] aria-invalid:ring-destructive/20 md:text-sm dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40", - className + className, )} {...props} /> - ) + ); } -export { Textarea } +export { Textarea }; diff --git a/components/ui/toggle-group.tsx b/components/ui/toggle-group.tsx index f62c08c..7f25a15 100644 --- a/components/ui/toggle-group.tsx +++ b/components/ui/toggle-group.tsx @@ -1,23 +1,23 @@ -"use client" +"use client"; -import * as React from "react" -import { type VariantProps } from "class-variance-authority" -import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui" +import * as React from "react"; +import { type VariantProps } from "class-variance-authority"; +import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" -import { toggleVariants } from "@/components/ui/toggle" +import { cn } from "@/lib/utils"; +import { toggleVariants } from "@/components/ui/toggle"; const ToggleGroupContext = React.createContext< VariantProps & { - spacing?: number - orientation?: "horizontal" | "vertical" + spacing?: number; + orientation?: "horizontal" | "vertical"; } >({ size: "default", variant: "default", spacing: 0, orientation: "horizontal", -}) +}); function ToggleGroup({ className, @@ -29,8 +29,8 @@ function ToggleGroup({ ...props }: React.ComponentProps & VariantProps & { - spacing?: number - orientation?: "horizontal" | "vertical" + spacing?: number; + orientation?: "horizontal" | "vertical"; }) { return ( @@ -52,7 +52,7 @@ function ToggleGroup({ {children} - ) + ); } function ToggleGroupItem({ @@ -63,7 +63,7 @@ function ToggleGroupItem({ ...props }: React.ComponentProps & VariantProps) { - const context = React.useContext(ToggleGroupContext) + const context = React.useContext(ToggleGroupContext); return ( {children} - ) + ); } -export { ToggleGroup, ToggleGroupItem } +export { ToggleGroup, ToggleGroupItem }; diff --git a/components/ui/toggle.tsx b/components/ui/toggle.tsx index a08fc57..588c12c 100644 --- a/components/ui/toggle.tsx +++ b/components/ui/toggle.tsx @@ -1,10 +1,10 @@ -"use client" +"use client"; -import * as React from "react" -import { cva, type VariantProps } from "class-variance-authority" -import { Toggle as TogglePrimitive } from "radix-ui" +import * as React from "react"; +import { cva, type VariantProps } from "class-variance-authority"; +import { Toggle as TogglePrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; const toggleVariants = cva( "group/toggle inline-flex items-center justify-center gap-1 rounded-4xl text-sm font-medium whitespace-nowrap transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", @@ -25,8 +25,8 @@ const toggleVariants = cva( variant: "default", size: "default", }, - } -) + }, +); function Toggle({ className, @@ -41,7 +41,7 @@ function Toggle({ className={cn(toggleVariants({ variant, size, className }))} {...props} /> - ) + ); } -export { Toggle, toggleVariants } +export { Toggle, toggleVariants }; diff --git a/components/ui/tooltip.tsx b/components/ui/tooltip.tsx index 1f61e3d..cb4ebda 100644 --- a/components/ui/tooltip.tsx +++ b/components/ui/tooltip.tsx @@ -1,9 +1,9 @@ -"use client" +"use client"; -import * as React from "react" -import { Tooltip as TooltipPrimitive } from "radix-ui" +import * as React from "react"; +import { Tooltip as TooltipPrimitive } from "radix-ui"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function TooltipProvider({ delayDuration = 0, @@ -15,19 +15,19 @@ function TooltipProvider({ delayDuration={delayDuration} {...props} /> - ) + ); } function Tooltip({ ...props }: React.ComponentProps) { - return + return ; } function TooltipTrigger({ ...props }: React.ComponentProps) { - return + return ; } function TooltipContent({ @@ -43,7 +43,7 @@ function TooltipContent({ sideOffset={sideOffset} className={cn( "z-50 inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-1.5 rounded-2xl bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-4xl data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", - className + className, )} {...props} > @@ -51,7 +51,7 @@ function TooltipContent({ - ) + ); } -export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } +export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger }; diff --git a/games b/games index cd0b48b..4635a9a 160000 --- a/games +++ b/games @@ -1 +1 @@ -Subproject commit cd0b48b8457407d588544cda22c3e0cdfd39101e +Subproject commit 4635a9aafd0dee2e0ba75b8026183a24956c75a0 diff --git a/hooks/use-mobile.ts b/hooks/use-mobile.ts index 2b0fe1d..a93d583 100644 --- a/hooks/use-mobile.ts +++ b/hooks/use-mobile.ts @@ -1,19 +1,21 @@ -import * as React from "react" +import * as React from "react"; -const MOBILE_BREAKPOINT = 768 +const MOBILE_BREAKPOINT = 768; export function useIsMobile() { - const [isMobile, setIsMobile] = React.useState(undefined) + const [isMobile, setIsMobile] = React.useState( + undefined, + ); React.useEffect(() => { - const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`) + const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); const onChange = () => { - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) - } - mql.addEventListener("change", onChange) - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) - return () => mql.removeEventListener("change", onChange) - }, []) + setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); + }; + mql.addEventListener("change", onChange); + setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); + return () => mql.removeEventListener("change", onChange); + }, []); - return !!isMobile + return !!isMobile; } diff --git a/lib/mail.ts b/lib/mail.ts index c6d9049..d034023 100644 --- a/lib/mail.ts +++ b/lib/mail.ts @@ -797,3 +797,221 @@ export const sendSuspensionWarningEmail = ( to: toEmail, }); }; + +// --------------------------------------------------------------------------- +// Server ready email +// --------------------------------------------------------------------------- + +interface ServerReadyParams { + toEmail: string; + userName: string | null | undefined; + serverName: string; + game: string; + region: string; + serverUrl: string; +} + +export const sendServerReadyEmail = ( + params: ServerReadyParams +): Promise => { + const { toEmail, userName, serverName, game, region, serverUrl } = params; + const displayName = userName ?? "there"; + const gameLabel = + game.charAt(0).toUpperCase() + game.slice(1).replaceAll("-", " "); + + const html = baseTemplate(` +

Your server is ready! 🎮

+

Hi ${displayName}, your game server has finished provisioning and is ready to use.

+
+
Server name
${serverName}
+
Game
${gameLabel}
+
Region
${region}
+
+ Go to server +

+ You'll find the connection details and server controls on your server page. +

+ `); + + const text = [ + `Your NodeByte server "${serverName}" is ready!`, + ``, + `Game: ${gameLabel}`, + `Region: ${region}`, + ``, + `Go to your server: ${serverUrl}`, + ].join("\n"); + + return sendMail({ + html, + subject: `Your server "${serverName}" is ready to play`, + text, + to: toEmail, + }); +}; + +// --------------------------------------------------------------------------- +// Server provision failed email +// --------------------------------------------------------------------------- + +interface ServerProvisionFailedParams { + toEmail: string; + userName: string | null | undefined; + serverName: string; + reason: string; + supportUrl: string; +} + +export const sendServerProvisionFailedEmail = ( + params: ServerProvisionFailedParams +): Promise => { + const { toEmail, userName, serverName, reason, supportUrl } = params; + const displayName = userName ?? "there"; + + const html = baseTemplate(` +

Server provisioning failed

+

Hi ${displayName}, we were unable to provision your server ${serverName}.

+
+
Reason
${reason}
+
+

Our team has been notified. Please contact support and we'll get this resolved for you.

+ Contact support +

+ Your subscription will not be charged for a server that failed to provision. +

+ `); + + const text = [ + `Server provisioning failed — NodeByte`, + ``, + `Hi ${displayName}, we were unable to provision "${serverName}".`, + ``, + `Reason: ${reason}`, + ``, + `Please contact support: ${supportUrl}`, + `Your subscription will not be charged for a server that failed to provision.`, + ].join("\n"); + + return sendMail({ + html, + subject: `Server "${serverName}" failed to provision`, + text, + to: toEmail, + }); +}; + +// --------------------------------------------------------------------------- +// Server provision initiated email (admin creates server, user approves) +// --------------------------------------------------------------------------- + +interface ServerProvisionInitiatedParams { + toEmail: string; + userName: string; + serverName: string; + serverType: string; + location: string; + game: string; + approveUrl: string; +} + +export const sendServerProvisionInitiatedEmail = ( + params: ServerProvisionInitiatedParams +): Promise => { + const { + toEmail, + userName, + serverName, + serverType, + location, + game, + approveUrl, + } = params; + const displayName = userName ?? "there"; + const gameLabel = + game.charAt(0).toUpperCase() + game.slice(1).replaceAll("-", " "); + + const html = baseTemplate(` +

Admin created a server for you

+

Hi ${displayName}, an admin has created a new game server for your account. Review the settings and approve to start provisioning.

+
+
Server name
${serverName}
+
Game
${gameLabel}
+
Server type
${serverType}
+
Region
${location}
+
+ Review and approve +

+ You can adjust any settings after reviewing. Once approved, provisioning will begin and the server will be ready in about 60 seconds. +

+ `); + + const text = [ + `Admin created a server for you — NodeByte`, + ``, + `Hi ${displayName}, an admin has set up a new game server on your account.`, + ``, + `Server name: ${serverName}`, + `Game: ${gameLabel}`, + `Server type: ${serverType}`, + `Region: ${location}`, + ``, + `Review and approve: ${approveUrl}`, + ``, + `Once approved, provisioning will begin and your server will be ready in about 60 seconds.`, + ].join("\n"); + + return sendMail({ + html, + subject: `Admin created server "${serverName}" for you`, + text, + to: toEmail, + }); +}; + +// --------------------------------------------------------------------------- +// Server member added (direct-add, no invite link) +// --------------------------------------------------------------------------- + +interface ServerMemberAddedParams { + toEmail: string; + serverName: string; + addedByName: string; + role: string; + serverUrl: string; +} + +export const sendServerMemberAddedEmail = ( + params: ServerMemberAddedParams +): Promise => { + const { toEmail, serverName, addedByName, role, serverUrl } = params; + const roleLabel = role.charAt(0).toUpperCase() + role.slice(1); + + const html = baseTemplate(` +

You've been added to a server

+

+ ${addedByName} has added you to the server + ${serverName} on NodeByte Panel. +

+

You have been granted the ${roleLabel} role.

+ View server +

+ You can manage your server access from within the panel. + If you believe this was a mistake, contact the server owner. +

+ `); + + const text = [ + `You've been added to ${serverName} on NodeByte Panel by ${addedByName}.`, + ``, + `Role: ${roleLabel}`, + ``, + `View the server: ${serverUrl}`, + ].join("\n"); + + return sendMail({ + html, + subject: `You've been added to ${serverName} on NodeByte`, + text, + to: toEmail, + }); +}; diff --git a/lib/pricing.ts b/lib/pricing.ts index 9f44e88..7a2c979 100644 --- a/lib/pricing.ts +++ b/lib/pricing.ts @@ -43,6 +43,14 @@ export const applyMarkup = ( return Math.max(rounded, MIN_PRICE_CENTS); }; +export const applyHourlyMarkupMilliCents = ( + hetznerHourlyPriceEur: number, + cpuType: "shared" | "dedicated" +): number => { + const gbp = hetznerHourlyPriceEur * EUR_TO_GBP_RATE; + return Math.max(0, Math.round(gbp * (1 + MARKUP[cpuType]) * 100_000)); +}; + /** * Format a price in pence to a GBP display string. */ diff --git a/lib/providers b/lib/providers index 173fb99..1d587d4 160000 --- a/lib/providers +++ b/lib/providers @@ -1 +1 @@ -Subproject commit 173fb999c9e44cc130be88432b04cf43928db73d +Subproject commit 1d587d43ab9b6aa4273c2acba2be8fd6e99c8d68 diff --git a/lib/rbac.ts b/lib/rbac.ts index 31dd502..3db0ba3 100644 --- a/lib/rbac.ts +++ b/lib/rbac.ts @@ -35,11 +35,6 @@ export const getServerRole = async ( userSystemRole: string, userSuperAdmin: boolean ): Promise => { - // System admins can read/manage every server - if (userSuperAdmin || userSystemRole === "admin") { - return "admin"; - } - const server = await prisma.server.findFirst({ select: { userId: true }, where: { deletedAt: null, id: serverId }, @@ -48,10 +43,17 @@ export const getServerRole = async ( if (!server) { return null; } + + // Ownership always wins — even for system admins who own the server if (server.userId === userId) { return "owner"; } + // System admins get "admin" on every server they don't own + if (userSuperAdmin || userSystemRole === "admin") { + return "admin"; + } + const membership = await prisma.serverMember.findUnique({ select: { role: true }, where: { serverId_userId: { serverId, userId } }, diff --git a/lib/sandbox/compile-agent.ts b/lib/sandbox/compile-agent.ts index 4e559db..3b14e6e 100644 --- a/lib/sandbox/compile-agent.ts +++ b/lib/sandbox/compile-agent.ts @@ -26,21 +26,136 @@ interface GitSource { password?: string; } +interface GitHubRepo { + owner: string; + repo: string; +} + const sha256 = (buf: Buffer): string => crypto.createHash("sha256").update(buf).digest("hex"); -const resolveGitSource = (): GitSource => { - const explicitUrl = process.env.NBP_GIT_REPO_URL; - const owner = process.env.VERCEL_GIT_REPO_OWNER; - const slug = process.env.VERCEL_GIT_REPO_SLUG; - const sha = process.env.VERCEL_GIT_COMMIT_SHA ?? process.env.NBP_GIT_REVISION; +const parseGitHubRepoFromUrl = (url: string): GitHubRepo | null => { + try { + const normalized = url.replace(/\.git$/iu, ""); + const parsed = new URL(normalized); + if (parsed.hostname !== "github.com") { + return null; + } + + const [owner, repo] = parsed.pathname + .replace(/^\//u, "") + .split("/") + .filter(Boolean); + if (!owner || !repo) { + return null; + } + + return { owner, repo }; + } catch { + return null; + } +}; + +const resolveLatestCommitSha = async (input: { + owner: string; + repo: string; + ref: string; + token?: string; +}): Promise => { + const headers: Record = { + Accept: "application/vnd.github+json", + }; + if (input.token) { + headers.Authorization = `Bearer ${input.token}`; + } - if (!sha) { + const response = await fetch( + `https://api.github.com/repos/${input.owner}/${input.repo}/commits/${encodeURIComponent(input.ref)}`, + { headers } + ); + if (!response.ok) { throw new Error( - "No git revision available. Set VERCEL_GIT_COMMIT_SHA (Vercel injects this) or NBP_GIT_REVISION for local dev." + `GitHub commit lookup failed for ${input.owner}/${input.repo}@${input.ref} (HTTP ${response.status})` ); } + const payload: unknown = await response.json(); + const sha = + payload && typeof payload === "object" && "sha" in payload + ? (payload.sha as unknown) + : undefined; + if (typeof sha !== "string" || sha.length === 0) { + throw new Error( + `GitHub commit lookup for ${input.owner}/${input.repo}@${input.ref} returned no sha` + ); + } + return sha; +}; + +const resolveRevisionFromRef = async (input: { + ref: string; + repoInfo: GitHubRepo | null; + token?: string; +}): Promise => { + if (!input.repoInfo) { + return input.ref; + } + return await resolveLatestCommitSha({ + owner: input.repoInfo.owner, + ref: input.ref, + repo: input.repoInfo.repo, + token: input.token, + }); +}; + +const resolveRequestedRevision = async (input: { + devBranchRef: string; + isDev: boolean; + isProd: boolean; + prodFallbackRef: string; + repoInfo: GitHubRepo | null; + sha?: string; + token?: string; +}): Promise => { + if (input.isDev) { + return await resolveRevisionFromRef({ + ref: input.devBranchRef, + repoInfo: input.repoInfo, + token: input.token, + }); + } + + if (input.sha) { + return input.sha; + } + + if (input.isProd) { + return await resolveRevisionFromRef({ + ref: input.prodFallbackRef, + repoInfo: input.repoInfo, + token: input.token, + }); + } + + throw new Error( + "No git revision available. Set VERCEL_GIT_COMMIT_SHA or NBP_GIT_REVISION." + ); +}; + +const resolveGitSource = async (): Promise => { + const explicitUrl = process.env.NBP_GIT_REPO_URL; + const owner = process.env.VERCEL_GIT_REPO_OWNER; + const slug = process.env.VERCEL_GIT_REPO_SLUG; + const isDev = + process.env.NODE_ENV === "development" || + process.env.VERCEL_ENV === "development" || + !process.env.VERCEL_ENV; + const isProd = process.env.VERCEL_ENV === "production"; + const sha = process.env.VERCEL_GIT_COMMIT_SHA ?? process.env.NBP_GIT_REVISION; + const devBranchRef = + process.env.VERCEL_GIT_COMMIT_REF ?? process.env.NBP_GIT_REF ?? "develop"; + const prodFallbackRef = process.env.NBP_GIT_PROD_REF ?? "main"; + const url = explicitUrl ?? (owner && slug ? `https://github.com/${owner}/${slug}` : null); @@ -55,21 +170,48 @@ const resolveGitSource = (): GitSource => { process.env.GIT_AUTH_TOKEN ?? process.env.VERCEL_SANDBOX_GIT_TOKEN ?? process.env.GITHUB_TOKEN; + + const repoInfo = + owner && slug ? { owner, repo: slug } : parseGitHubRepoFromUrl(url); + + const revision = await resolveRequestedRevision({ + devBranchRef, + isDev, + isProd, + prodFallbackRef, + repoInfo, + sha: sha ?? undefined, + token, + }); + + if (!revision) { + throw new Error( + isProd + ? "No git revision available. Set VERCEL_GIT_COMMIT_SHA (preferred) or ensure NBP_GIT_PROD_REF can be resolved (default: main)." + : "No git revision available. Set NBP_GIT_REF for local dev (default: develop)." + ); + } if (token) { - return { password: token, revision: sha, url, username: "x-access-token" }; + return { + password: token, + revision, + url, + username: "x-access-token", + }; } - return { revision: sha, url }; + return { revision, url }; }; export const compileAgentBinary = async (): Promise<{ bytes: Buffer; sha: string; }> => { - const git = resolveGitSource(); + const git = await resolveGitSource(); let sandbox: Awaited>; try { sandbox = await Sandbox.create({ + projectId: process.env.VERCEL_PROJECT_ID, resources: { vcpus: 4 }, runtime: "node22", source: { @@ -80,7 +222,9 @@ export const compileAgentBinary = async (): Promise<{ ? { password: git.password, username: git.username } : {}), }, + teamId: process.env.VERCEL_TEAM_ID, timeout: 10 * 60 * 1000, + token: process.env.VERCEL_TOKEN, }); } catch (error) { const msg = error instanceof Error ? error.message : String(error); diff --git a/lib/utils.ts b/lib/utils.ts index bd0c391..a5ef193 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -1,6 +1,6 @@ -import { clsx, type ClassValue } from "clsx" -import { twMerge } from "tailwind-merge" +import { clsx, type ClassValue } from "clsx"; +import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { - return twMerge(clsx(inputs)) + return twMerge(clsx(inputs)); } diff --git a/lib/workflows/build-snapshot-cloud-init.ts b/lib/workflows/build-snapshot-cloud-init.ts index 4c5d642..4d90c8b 100644 --- a/lib/workflows/build-snapshot-cloud-init.ts +++ b/lib/workflows/build-snapshot-cloud-init.ts @@ -96,9 +96,9 @@ ufw allow 22/tcp ufw --force enable mkdir -p /etc/nodebyte /var/lib/nodebyte/game -chmod 700 /etc/nodebyte /var/lib/nodebyte +chmod 777 /etc/nodebyte /var/lib/nodebyte -retry_cmd 5 curl --retry 5 --retry-delay 5 --retry-connrefused -fsSL "${agentBinaryUrl}" -o /usr/local/bin/nodebyte-agent +retry_cmd 5 curl --retry 5 --retry-delay 5 --retry-connrefused -A "Mozilla/5.0" -fsSL "${agentBinaryUrl}" -o /usr/local/bin/nodebyte-agent # Verify the download is a Linux ELF — guards against silently baking an HTML # auth-wall or sign-in redirect into the snapshot. Aborts the script (set -e) @@ -129,12 +129,12 @@ shutdown -h now write_files: - path: /etc/systemd/system/nodebyte-agent.service owner: root:root - permissions: '0644' + permissions: '0777' content: | ${indent(SYSTEMD_UNIT, 6)} - path: /root/build-image.sh owner: root:root - permissions: '0755' + permissions: '0777' content: | ${indent(buildScript, 6)} runcmd: diff --git a/lib/workflows/provision-server.ts b/lib/workflows/provision-server.ts index 45c1190..7c0ec3a 100644 --- a/lib/workflows/provision-server.ts +++ b/lib/workflows/provision-server.ts @@ -67,19 +67,19 @@ const waitForEnrollment = async ( type InstallOutcome = | { type: "healthy" } - | { type: "errored" } + | { type: "errored"; errorMessage?: string } | { type: "cancelled" } | { type: "timeout" }; const waitForInstall = async (serverId: string): Promise => { const deadline = Date.now() + MAX_INSTALL_WAIT_SECONDS * 1000; while (Date.now() < deadline) { - const phase = await stepReadAgentPhase(serverId); + const { phase, message } = await stepReadAgentPhase(serverId); if (phase === "healthy" || phase === "ready") { return { type: "healthy" }; } if (phase === "errored") { - return { type: "errored" }; + return { errorMessage: message, type: "errored" }; } if (await isCancelled(serverId)) { return { type: "cancelled" }; @@ -139,7 +139,8 @@ export const provisionServer = async (input: { serverId: string }) => { return; } if (installOutcome.type === "errored") { - await stepMarkFailed({ reason: "Agent reported error", serverId }); + const errorMsg = installOutcome.errorMessage ?? "Agent reported error"; + await stepMarkFailed({ reason: errorMsg, serverId }); return; } if (installOutcome.type === "timeout") { diff --git a/lib/workflows/steps.ts b/lib/workflows/steps.ts index 908004b..c7ba509 100644 --- a/lib/workflows/steps.ts +++ b/lib/workflows/steps.ts @@ -7,6 +7,11 @@ import { enqueueCommand } from "@/lib/agent/commands"; import { prisma } from "@/lib/db"; import { API_URL, env, SNAPSHOT_ENVIRONMENT } from "@/lib/env"; import { emitActivity } from "@/lib/events/emit"; +import { + sendServerDeletedEmail, + sendServerProvisionFailedEmail, + sendServerReadyEmail, +} from "@/lib/mail"; import { getProviderForUser, getProviderForUserWithImage, @@ -285,6 +290,25 @@ export const stepMarkReady = async (serverId: string) => { phase: "ready", serverId, }); + const server = await prisma.server.findUnique({ + select: { + game: true, + location: true, + name: true, + user: { select: { email: true, name: true } }, + }, + where: { id: serverId }, + }); + if (server?.user) { + void sendServerReadyEmail({ + game: server.game, + region: server.location, + serverName: server.name, + serverUrl: `${API_URL}/dashboard/${serverId}`, + toEmail: server.user.email, + userName: server.user.name, + }); + } }; export const stepMarkFailed = async (input: { @@ -305,6 +329,19 @@ export const stepMarkFailed = async (input: { phase: "errored", serverId: input.serverId, }); + const server = await prisma.server.findUnique({ + select: { name: true, user: { select: { email: true, name: true } } }, + where: { id: input.serverId }, + }); + if (server?.user) { + void sendServerProvisionFailedEmail({ + reason: input.reason, + serverName: server.name, + supportUrl: "https://nodebyte.host/contact", + toEmail: server.user.email, + userName: server.user.name, + }); + } }; const AGENT_LIVENESS_WINDOW_MS = 60_000; @@ -353,6 +390,10 @@ export const stepDeleteProviderServer = async (serverId: string) => { export const stepMarkDeleted = async (serverId: string) => { "use step"; + const server = await prisma.server.findUnique({ + select: { name: true, user: { select: { email: true, name: true } } }, + where: { id: serverId }, + }); const { count } = await prisma.server.updateMany({ data: { deletedAt: new Date(), @@ -369,6 +410,13 @@ export const stepMarkDeleted = async (serverId: string) => { phase: "deleted", serverId, }); + if (server?.user) { + void sendServerDeletedEmail({ + serverName: server.name, + toEmail: server.user.email, + userName: server.user.name, + }); + } }; export const stepReadPhase = async ( @@ -384,14 +432,17 @@ export const stepReadPhase = async ( export const stepReadAgentPhase = async ( serverId: string -): Promise => { +): Promise<{ phase: Phase | null; message?: string }> => { "use step"; const event = await prisma.activityEvent.findFirst({ orderBy: { seq: "desc" }, - select: { phase: true }, + select: { message: true, phase: true }, where: { serverId, source: "agent" }, }); - return (event?.phase as Phase | undefined) ?? null; + return { + message: event?.message ?? undefined, + phase: (event?.phase as Phase | undefined) ?? null, + }; }; export const stepReadDesiredState = async (serverId: string) => { diff --git a/next-env.d.ts b/next-env.d.ts deleted file mode 100644 index 9edff1c..0000000 --- a/next-env.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/// -/// -import "./.next/types/routes.d.ts"; - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/package.json b/package.json index cd76f08..51e52af 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@nodebyte/gsm", "version": "0.1.0", - "description": "NodeByte GSM is a game server management platform built with Next.js, Prisma, and Tailwind CSS. It provides an intuitive interface for managing game servers, including features like server provisioning, monitoring, and billing.", + "description": "NodeByte GSM is our custom game server management platform.", "license": "AGPL-3.0-only", "type": "module", "scripts": { @@ -34,10 +34,13 @@ "submodules:status": "node scripts/submodules.mjs status", "submodules:update": "node scripts/submodules.mjs update", "submodules:push": "node scripts/submodules.mjs push", - "bump-deps": "npx npm-check-updates -u -x zod && bun install" + "bump-deps": "npx npm-check-updates -u -x zod && bun install", + "prettier:check": "bunx prettier . --check", + "prettier:run": "bunx prettier . --write" }, "dependencies": { "@better-auth/passkey": "^1.6.9", + "@monaco-editor/react": "^4.7.0", "@noble/ed25519": "^3.1.0", "@nosecone/next": "1.4.0", "@prisma/adapter-pg": "^7.8.0", @@ -49,6 +52,7 @@ "@vercel/analytics": "^2.0.1", "@vercel/blob": "^2.3.3", "@vercel/sandbox": "^1.10.1", + "@vercel/speed-insights": "^2.0.0", "anser": "^2.3.5", "better-auth": "^1.6.9", "class-variance-authority": "^0.7.1", @@ -109,6 +113,7 @@ "oxfmt": "^0.48.0", "oxlint": "^1.63.0", "postcss": "^8.5.14", + "prettier": "3.9.6", "prisma": "^7.8.0", "tailwindcss": "^4.2.4", "tailwindcss-animate": "^1.0.7", diff --git a/prisma/migrations/20260519050228_add_agent_metrics/migration.sql b/prisma/migrations/20260519050228_add_agent_metrics/migration.sql new file mode 100644 index 0000000..688add1 --- /dev/null +++ b/prisma/migrations/20260519050228_add_agent_metrics/migration.sql @@ -0,0 +1,12 @@ +-- AlterTable +ALTER TABLE "agents" ADD COLUMN "cpuPercent" DOUBLE PRECISION, +ADD COLUMN "diskTotalBytes" DOUBLE PRECISION, +ADD COLUMN "diskUsedBytes" DOUBLE PRECISION, +ADD COLUMN "maxPlayers" INTEGER, +ADD COLUMN "memTotalBytes" DOUBLE PRECISION, +ADD COLUMN "memUsedBytes" DOUBLE PRECISION, +ADD COLUMN "networkInBps" DOUBLE PRECISION, +ADD COLUMN "networkOutBps" DOUBLE PRECISION, +ADD COLUMN "playerCount" INTEGER, +ADD COLUMN "tps" DOUBLE PRECISION, +ADD COLUMN "uptimeSeconds" INTEGER; diff --git a/prisma/migrations/20260816120000_add_server_powered_off/migration.sql b/prisma/migrations/20260816120000_add_server_powered_off/migration.sql new file mode 100644 index 0000000..843546b --- /dev/null +++ b/prisma/migrations/20260816120000_add_server_powered_off/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "servers" ADD COLUMN "poweredOff" BOOLEAN NOT NULL DEFAULT false; diff --git a/prisma/migrations/20260820120000_usage_billing/migration.sql b/prisma/migrations/20260820120000_usage_billing/migration.sql new file mode 100644 index 0000000..dc2fe03 --- /dev/null +++ b/prisma/migrations/20260820120000_usage_billing/migration.sql @@ -0,0 +1,24 @@ +ALTER TABLE "subscriptions" + ADD COLUMN "hourlyRateMilliCents" INTEGER, + ADD COLUMN "usageBillingStartedAt" TIMESTAMP(3), + ADD COLUMN "usageLastBilledAt" TIMESTAMP(3); + +CREATE TABLE "usage_invoices" ( + "id" TEXT NOT NULL, + "subscriptionId" TEXT NOT NULL, + "periodStart" TIMESTAMP(3) NOT NULL, + "periodEnd" TIMESTAMP(3) NOT NULL, + "amountCents" INTEGER NOT NULL, + "stripeInvoiceId" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "usage_invoices_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "usage_invoices_stripeInvoiceId_key" ON "usage_invoices"("stripeInvoiceId"); +CREATE UNIQUE INDEX "usage_invoices_subscriptionId_periodStart_key" ON "usage_invoices"("subscriptionId", "periodStart"); +CREATE INDEX "usage_invoices_subscriptionId_idx" ON "usage_invoices"("subscriptionId"); + +ALTER TABLE "usage_invoices" + ADD CONSTRAINT "usage_invoices_subscriptionId_fkey" + FOREIGN KEY ("subscriptionId") REFERENCES "subscriptions"("id") + ON DELETE CASCADE ON UPDATE CASCADE; \ No newline at end of file diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 0b00208..345d022 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -157,6 +157,7 @@ model Server { joinPassword String? settings Json @default("{}") backupsEnabled Boolean @default(false) + poweredOff Boolean @default(false) lastSuspendedAt DateTime? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -222,6 +223,18 @@ model Agent { sessionVersion Int @default(0) lastHeartbeatAt DateTime? lastCommandId String? + // Live metrics — updated on each heartbeat + cpuPercent Float? + memTotalBytes Float? + memUsedBytes Float? + diskTotalBytes Float? + diskUsedBytes Float? + networkInBps Float? + networkOutBps Float? + uptimeSeconds Int? + playerCount Int? + maxPlayers Int? + tps Float? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt server Server @relation(fields: [serverId], references: [id], onDelete: Cascade) @@ -366,37 +379,57 @@ enum SubscriptionStatus { } model Subscription { - id String @id - serverId String @unique - billingCustomerId String - stripeSubscriptionId String @unique - stripePriceId String - stripeProductId String - status SubscriptionStatus @default(incomplete) + id String @id + serverId String @unique + billingCustomerId String + stripeSubscriptionId String @unique + stripePriceId String + stripeProductId String + status SubscriptionStatus @default(incomplete) // NodeByte-facing plan metadata - planName String // e.g. "CX21", "CPX31" - pricePerMonthCents Int // NodeByte price (not Hetzner base) - currency String @default("GBP") - currentPeriodStart DateTime? - currentPeriodEnd DateTime? - canceledAt DateTime? - suspendedAt DateTime? // set when server is suspended due to non-payment + planName String // e.g. "CX21", "CPX31" + pricePerMonthCents Int // NodeByte price (not Hetzner base) + // First-month fixed fee and subsequent Hetzner hourly cost-plus rate. + hourlyRateMilliCents Int? // GBP thousandths of a penny per provider hour + usageBillingStartedAt DateTime? + usageLastBilledAt DateTime? + currency String @default("GBP") + currentPeriodStart DateTime? + currentPeriodEnd DateTime? + canceledAt DateTime? + suspendedAt DateTime? // set when server is suspended due to non-payment // Promo / discount - promoCode String? // human-readable promo code applied - discountAmountCents Int? // flat GBP pence discount (if any) - trialEnd DateTime? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - server Server @relation(fields: [serverId], references: [id], onDelete: Cascade) - billingCustomer BillingCustomer @relation(fields: [billingCustomerId], references: [id]) - invoices Invoice[] - addons ServerAddon[] + promoCode String? // human-readable promo code applied + discountAmountCents Int? // flat GBP pence discount (if any) + trialEnd DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + server Server @relation(fields: [serverId], references: [id], onDelete: Cascade) + billingCustomer BillingCustomer @relation(fields: [billingCustomerId], references: [id]) + invoices Invoice[] + addons ServerAddon[] + usageInvoices UsageInvoice[] @@index([billingCustomerId]) @@index([status]) @@map("subscriptions") } +model UsageInvoice { + id String @id @default(cuid()) + subscriptionId String + periodStart DateTime + periodEnd DateTime + amountCents Int + stripeInvoiceId String? @unique + createdAt DateTime @default(now()) + subscription Subscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade) + + @@unique([subscriptionId, periodStart]) + @@index([subscriptionId]) + @@map("usage_invoices") +} + enum InvoiceStatus { draft open diff --git a/protocol/constants.ts b/protocol/constants.ts index 73cae65..7f67950 100644 --- a/protocol/constants.ts +++ b/protocol/constants.ts @@ -39,6 +39,8 @@ export const COMMAND_TYPES = [ "UPLOAD_BACKUP", "FETCH_LOGS", "FILES_LIST", + "FILES_READ", + "FILES_WRITE", "FILES_DELETE", "FILES_INSTALL_FROM_URL", ] as const; diff --git a/protocol/schemas.ts b/protocol/schemas.ts index c958b30..5a52cc7 100644 --- a/protocol/schemas.ts +++ b/protocol/schemas.ts @@ -26,8 +26,13 @@ export const heartbeatSchema = z.object({ diskUsedBytes: z.number().int().nonnegative().optional(), dockerState: z.enum(["running", "stopped", "missing", "error"]), lastCommandId: z.string().nullable().optional(), + maxPlayers: z.number().int().positive().optional(), memTotalBytes: z.number().int().positive().optional(), memUsedBytes: z.number().int().nonnegative().optional(), + networkInBps: z.number().nonnegative().optional(), + networkOutBps: z.number().nonnegative().optional(), + playerCount: z.number().int().nonnegative().optional(), + tps: z.number().min(0).optional(), uptimeSeconds: z.number().int().nonnegative(), }); export type Heartbeat = z.infer; @@ -107,6 +112,22 @@ const filesListCommand = z.object({ payload: z.object({ path: z.string() }), type: z.literal("FILES_LIST"), }); +const filesReadCommand = z.object({ + id: z.string().min(1), + issuedAt: z.string().datetime(), + payload: z.object({ path: z.string().min(1) }), + type: z.literal("FILES_READ"), +}); +const filesWriteCommand = z.object({ + id: z.string().min(1), + issuedAt: z.string().datetime(), + payload: z.object({ + content: z.string(), + encoding: z.enum(["utf-8", "base64"]).default("utf-8"), + path: z.string().min(1), + }), + type: z.literal("FILES_WRITE"), +}); const filesDeleteCommand = z.object({ id: z.string().min(1), issuedAt: z.string().datetime(), @@ -136,6 +157,8 @@ export const commandSchema = z.discriminatedUnion("type", [ uploadBackupCommand, fetchLogsCommand, filesListCommand, + filesReadCommand, + filesWriteCommand, filesDeleteCommand, filesInstallFromUrlCommand, ]); @@ -153,6 +176,16 @@ export const filesListResultSchema = z.object({ path: z.string(), }); export type FilesListResult = z.infer; + +export const filesReadResultSchema = z.object({ + content: z.string(), + encoding: z.enum(["utf-8", "base64"]), + path: z.string(), + size: z.number().int().nonnegative(), + truncated: z.boolean(), +}); +export type FilesReadResult = z.infer; + export type Command = z.infer; export const commandEnvelopeSchema = z.object({ diff --git a/test/hetzner-catalog.test.ts b/test/hetzner-catalog.test.ts index ff228d5..ce2fc7b 100644 --- a/test/hetzner-catalog.test.ts +++ b/test/hetzner-catalog.test.ts @@ -55,8 +55,16 @@ const baseServerType = (overrides: Record = {}) => ({ memory: 4, name: "cx22", prices: [ - { location: "fsn1", price_monthly: { gross: "5.00" } }, - { location: "nbg1", price_monthly: { gross: "6.00" } }, + { + location: "fsn1", + price_hourly: { gross: "0.01" }, + price_monthly: { gross: "5.00" }, + }, + { + location: "nbg1", + price_hourly: { gross: "0.01" }, + price_monthly: { gross: "6.00" }, + }, ], ...overrides, }); @@ -102,9 +110,12 @@ describe("getHetznerCatalog", () => { expect(type.name).toBe("cx22"); expect(type.cpuType).toBe("shared"); expect(type.architecture).toBe("x86"); + expect(type.pricePerMonth).toBe(6.5); + expect(type.hourlyPriceMilliCents).toBe(1204); expect(type.locations.map((l) => l.name)).toEqual(["fsn1", "nbg1"]); expect(type.locations[0]).toMatchObject({ available: true, name: "fsn1" }); expect(type.locations[1]).toMatchObject({ available: false, name: "nbg1" }); + expect(type.locations[0].hourlyPriceMilliCents).toBe(1204); }); test("falls back to alphabetical name sort when locations share availability", async () => { diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..2720d9b --- /dev/null +++ b/vercel.json @@ -0,0 +1,8 @@ +{ + "crons": [ + { + "path": "/api/cron/billing", + "schedule": "15 * * * *" + } + ] +}