docs: adiciona setup completo e documentação end-to-end
- Cria .env com comentários detalhados (13 variáveis) - Atualiza READMEs com guia completo de instalação - Documenta setup Appwrite Cloud e schemas de collections - Adiciona troubleshooting e guias de deploy - Total: ~1.240 linhas de documentação em português
This commit is contained in:
parent
0737bc8831
commit
8380a470be
4 changed files with 1229 additions and 98 deletions
102
.env
Normal file
102
.env
Normal file
|
|
@ -0,0 +1,102 @@
|
||||||
|
# ==============================================================================
|
||||||
|
# APPWRITE CONFIGURATION - Backend as a Service (BaaS)
|
||||||
|
# ==============================================================================
|
||||||
|
# Appwrite Cloud provides authentication, database, storage, and serverless functions
|
||||||
|
# Documentation: https://appwrite.io/docs
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# SERVER-SIDE VARIABLES (for Node.js scripts and Appwrite Functions)
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# APPWRITE_ENDPOINT
|
||||||
|
# The API endpoint for your Appwrite instance
|
||||||
|
# For Appwrite Cloud: https://cloud.appwrite.io/v1
|
||||||
|
# For self-hosted: http://localhost/v1 or your custom domain
|
||||||
|
APPWRITE_ENDPOINT=https://cloud.appwrite.io/v1
|
||||||
|
|
||||||
|
# APPWRITE_PROJECT_ID
|
||||||
|
# Your Appwrite project identifier
|
||||||
|
# How to get: Go to https://cloud.appwrite.io → Select/Create Project → Copy Project ID
|
||||||
|
# Example: 6789abcdef123456
|
||||||
|
APPWRITE_PROJECT_ID=
|
||||||
|
|
||||||
|
# APPWRITE_API_KEY
|
||||||
|
# Secret API key with Admin permissions for server-side operations
|
||||||
|
# How to get: Project Settings → API Keys → Create API Key → Select all scopes
|
||||||
|
# WARNING: Keep this secret! Never commit to version control or expose client-side
|
||||||
|
# Example: a1b2c3d4e5f6...
|
||||||
|
APPWRITE_API_KEY=
|
||||||
|
|
||||||
|
# APPWRITE_FUNCTIONS_ENDPOINT (Optional)
|
||||||
|
# Custom endpoint for Appwrite Functions if using a dedicated domain
|
||||||
|
# Leave empty to use the same as APPWRITE_ENDPOINT
|
||||||
|
APPWRITE_FUNCTIONS_ENDPOINT=
|
||||||
|
|
||||||
|
# APPWRITE_FUNCTIONS_API_KEY (Optional)
|
||||||
|
# Separate API key for Functions if you want isolated permissions
|
||||||
|
# Leave empty to use the same as APPWRITE_API_KEY
|
||||||
|
APPWRITE_FUNCTIONS_API_KEY=
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# CLIENT-SIDE VARIABLES (for React Dashboard - Vite requires VITE_ prefix)
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# VITE_APPWRITE_ENDPOINT
|
||||||
|
# Same as APPWRITE_ENDPOINT, but accessible in browser via import.meta.env
|
||||||
|
# Must start with VITE_ to be exposed by Vite build system
|
||||||
|
VITE_APPWRITE_ENDPOINT=https://cloud.appwrite.io/v1
|
||||||
|
|
||||||
|
# VITE_APPWRITE_PROJECT_ID
|
||||||
|
# Your Appwrite project identifier (same value as APPWRITE_PROJECT_ID)
|
||||||
|
# Exposed to browser for client SDK initialization
|
||||||
|
VITE_APPWRITE_PROJECT_ID=
|
||||||
|
|
||||||
|
# VITE_APPWRITE_DATABASE_ID
|
||||||
|
# The database ID where all collections are stored
|
||||||
|
# How to get: Appwrite Console → Databases → Create/Select Database → Copy Database ID
|
||||||
|
# Suggested name: "DevOpsPlatform"
|
||||||
|
# Example: main_db_123
|
||||||
|
VITE_APPWRITE_DATABASE_ID=
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# COLLECTION IDs (created inside the database)
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# VITE_APPWRITE_COLLECTION_SERVERS_ID
|
||||||
|
# Collection for storing server information
|
||||||
|
# Schema: name (string), ip (string), status (enum: online/offline), region (string)
|
||||||
|
# Suggested ID: "servers"
|
||||||
|
VITE_APPWRITE_COLLECTION_SERVERS_ID=
|
||||||
|
|
||||||
|
# VITE_APPWRITE_COLLECTION_GITHUB_REPOS_ID
|
||||||
|
# Collection for GitHub repository data
|
||||||
|
# Schema: repo_name (string), url (url), last_commit (string), status (string)
|
||||||
|
# Suggested ID: "github_repos"
|
||||||
|
VITE_APPWRITE_COLLECTION_GITHUB_REPOS_ID=
|
||||||
|
|
||||||
|
# VITE_APPWRITE_COLLECTION_AUDIT_LOGS_ID
|
||||||
|
# Collection for audit log entries (used by Realtime terminal widget)
|
||||||
|
# Schema: event (string), user_id (string), timestamp (datetime)
|
||||||
|
# Suggested ID: "audit_logs"
|
||||||
|
VITE_APPWRITE_COLLECTION_AUDIT_LOGS_ID=
|
||||||
|
|
||||||
|
# VITE_APPWRITE_COLLECTION_CLOUDFLARE_ACCOUNTS_ID
|
||||||
|
# Collection for Cloudflare account integrations
|
||||||
|
# Schema: provider (string), apiKey (string), label (string)
|
||||||
|
# Suggested ID: "cloud_accounts" or "cloudflare_accounts"
|
||||||
|
VITE_APPWRITE_COLLECTION_CLOUDFLARE_ACCOUNTS_ID=
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# SETUP CHECKLIST
|
||||||
|
# ==============================================================================
|
||||||
|
# 1. Create Appwrite Cloud account at https://cloud.appwrite.io
|
||||||
|
# 2. Create a new project and copy the Project ID
|
||||||
|
# 3. Create API Key with all permissions (for server-side operations)
|
||||||
|
# 4. Create a Database named "DevOpsPlatform" and copy its ID
|
||||||
|
# 5. Create collections inside the database with the schemas described above
|
||||||
|
# 6. Enable Email/Password authentication provider
|
||||||
|
# 7. Create a test user in Authentication → Users
|
||||||
|
# 8. Deploy the three Appwrite Functions from appwrite-functions/ directory
|
||||||
|
# 9. Fill in all the IDs above
|
||||||
|
# 10. Run: npm install → npm run dev:web
|
||||||
|
# ==============================================================================
|
||||||
599
README.md
599
README.md
|
|
@ -1,85 +1,550 @@
|
||||||
# Core Platform Monorepo
|
# Core Platform Monorepo
|
||||||
|
|
||||||
Ambiente monorepo com três camadas principais: **Landing (Fresh + Deno)**, **Dashboard (React + Vite)** e **Appwrite Cloud** como backend. Este guia prioriza a configuração do Appwrite Cloud antes de rodar qualquer código local.
|
> **Plataforma DevOps completa** com Landing Page (Fresh + Deno), Dashboard (React + Vite) e Backend Appwrite Cloud. Sistema integrado com autenticação, banco de dados em tempo real, e funções serverless para gerenciamento de servidores, repositórios GitHub e contas Cloudflare.
|
||||||
|
|
||||||
## Passo a passo (Appwrite Cloud)
|
## 📋 Índice
|
||||||
1. Acesse https://cloud.appwrite.io e crie/abra um projeto.
|
|
||||||
2. No menu **API Keys**, gere uma chave com permissão de Admin para criar bancos, coleções e funções.
|
- [Visão Geral](#-visão-geral)
|
||||||
3. Registre os valores a seguir para preencher o `.env`:
|
- [Pré-requisitos](#-pré-requisitos)
|
||||||
- **API Endpoint** (ex.: `https://cloud.appwrite.io/v1`)
|
- [Instalação Rápida](#-instalação-rápida)
|
||||||
- **Project ID**
|
- [Configuração Detalhada](#-configuração-detalhada)
|
||||||
- **Database ID** (criado no passo seguinte)
|
- [Variáveis de Ambiente](#variáveis-de-ambiente)
|
||||||
- Opcional: endpoints/keys das Functions se você usar domínios dedicados.
|
- [Setup Appwrite Cloud](#setup-appwrite-cloud)
|
||||||
4. Crie um Database chamado **DevOpsPlatform** e anote seu ID.
|
- [Executando o Projeto](#-executando-o-projeto)
|
||||||
5. Dentro do banco, crie as coleções (IDs sugeridos entre parênteses):
|
- [Estrutura do Projeto](#-estrutura-do-projeto)
|
||||||
- **servers** (`servers`):
|
- [Scripts Disponíveis](#-scripts-disponíveis)
|
||||||
- `name` (string)
|
- [Verificação e Testes](#-verificação-e-testes)
|
||||||
- `ip` (string)
|
- [Troubleshooting](#-troubleshooting)
|
||||||
- `status` (enum: `online`, `offline`)
|
- [Deploy](#-deploy)
|
||||||
- `region` (string)
|
|
||||||
- **github_repos** (`github_repos`):
|
## 🎯 Visão Geral
|
||||||
- `repo_name` (string)
|
|
||||||
- `url` (url)
|
Este monorepo contém três componentes principais:
|
||||||
- `last_commit` (string)
|
|
||||||
- `status` (string)
|
- **Landing Page**: Interface pública desenvolvida com Fresh (framework Deno) e Tailwind CSS
|
||||||
- **audit_logs** (`audit_logs`):
|
- **Dashboard**: Painel administrativo em React + TypeScript + Vite com integração Appwrite
|
||||||
- `event` (string)
|
- **Appwrite Functions**: Três funções serverless (hello-world, sync-github, check-cloudflare-status)
|
||||||
- `user_id` (string)
|
|
||||||
- `timestamp` (datetime)
|
**Backend**: Appwrite Cloud - BaaS (Backend as a Service) com:
|
||||||
- **cloud_accounts** (`cloud_accounts`) para integrações:
|
- Autenticação (Email/Password)
|
||||||
- `provider` (string)
|
- Database com 4 coleções (servers, github_repos, audit_logs, cloud_accounts)
|
||||||
- `apiKey` (string)
|
- Realtime subscriptions para logs ao vivo
|
||||||
- `label` (string)
|
- Functions para automação
|
||||||
6. Ative o provedor **Email/Password** em *Authentication* e crie um usuário de teste.
|
|
||||||
7. Implante as Functions `hello-world`, `sync-github` e `check-cloudflare-status` (fontes em `appwrite-functions/`).
|
## 🛠 Pré-requisitos
|
||||||
|
|
||||||
|
Certifique-se de ter instalado:
|
||||||
|
|
||||||
|
| Software | Versão Mínima | Como Verificar | Download |
|
||||||
|
|----------|---------------|----------------|----------|
|
||||||
|
| **Node.js** | 18.x ou superior | `node --version` | [nodejs.org](https://nodejs.org) |
|
||||||
|
| **npm** | 9.x ou superior | `npm --version` | Vem com Node.js |
|
||||||
|
| **Deno** | 1.40+ | `deno --version` | [deno.land](https://deno.land/manual/getting_started/installation) |
|
||||||
|
| **Git** | 2.x | `git --version` | [git-scm.com](https://git-scm.com) |
|
||||||
|
|
||||||
|
### Conta Appwrite Cloud
|
||||||
|
|
||||||
|
Você também precisa de uma conta no **[Appwrite Cloud](https://cloud.appwrite.io)** (gratuito):
|
||||||
|
|
||||||
|
1. Acesse https://cloud.appwrite.io e crie uma conta
|
||||||
|
2. Crie um novo projeto
|
||||||
|
3. Anote o **Project ID** que será usado nas variáveis de ambiente
|
||||||
|
|
||||||
|
## 🚀 Instalação Rápida
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Clone o repositório
|
||||||
|
git clone <repository-url>
|
||||||
|
cd core
|
||||||
|
|
||||||
|
# 2. Instale as dependências raiz
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 3. Instale as dependências do dashboard
|
||||||
|
cd dashboard
|
||||||
|
npm install
|
||||||
|
cd ..
|
||||||
|
|
||||||
|
# 4. Verifique se o Deno está instalado
|
||||||
|
deno --version
|
||||||
|
# Se não estiver, instale: curl -fsSL https://deno.land/install.sh | sh
|
||||||
|
|
||||||
|
# 5. Configure as variáveis de ambiente
|
||||||
|
cp .env.example .env
|
||||||
|
# Edite o .env com suas credenciais Appwrite (veja seção abaixo)
|
||||||
|
|
||||||
|
# 6. Configure o Appwrite Cloud (veja seção "Setup Appwrite Cloud")
|
||||||
|
|
||||||
|
# 7. Execute o projeto
|
||||||
|
npm run dev:web
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⚙️ Configuração Detalhada
|
||||||
|
|
||||||
|
### Variáveis de Ambiente
|
||||||
|
|
||||||
|
O arquivo `.env` na raiz do projeto contém todas as configurações necessárias. Copie o `.env.example` e preencha os valores:
|
||||||
|
|
||||||
## Variáveis de ambiente
|
|
||||||
Copie o arquivo de exemplo e preencha com os IDs anotados:
|
|
||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
```
|
```
|
||||||
Campos principais:
|
|
||||||
- `VITE_APPWRITE_ENDPOINT`, `VITE_APPWRITE_PROJECT_ID`, `VITE_APPWRITE_DATABASE_ID`
|
|
||||||
- `VITE_APPWRITE_COLLECTION_SERVERS_ID`, `VITE_APPWRITE_COLLECTION_GITHUB_REPOS_ID`, `VITE_APPWRITE_COLLECTION_AUDIT_LOGS_ID`, `VITE_APPWRITE_COLLECTION_CLOUDFLARE_ACCOUNTS_ID`
|
|
||||||
- Para scripts server-side, use também `APPWRITE_ENDPOINT`, `APPWRITE_PROJECT_ID`, `APPWRITE_API_KEY`.
|
|
||||||
|
|
||||||
## Estrutura de pastas
|
#### Referência Completa de Variáveis
|
||||||
- `landing/`: app Fresh (Deno) para a landing page.
|
|
||||||
- `dashboard/`: painel React + Vite com integrações Appwrite (auth, Functions, Database, Realtime).
|
|
||||||
- `appwrite-functions/`: funções `hello-world`, `sync-github` e `check-cloudflare-status`.
|
|
||||||
|
|
||||||
## Rodando os ambientes
|
| Variável | Onde Obter | Obrigatória | Descrição |
|
||||||
1) **Appwrite local (opcional)**
|
|----------|------------|-------------|-----------|
|
||||||
```bash
|
| **Configuração Server-Side (Scripts Node.js e Functions)** | | | |
|
||||||
docker run -it --rm \
|
| `APPWRITE_ENDPOINT` | Fixo | ✅ | URL da API Appwrite. Use `https://cloud.appwrite.io/v1` |
|
||||||
-p 80:80 -p 443:443 \
|
| `APPWRITE_PROJECT_ID` | Console Appwrite | ✅ | ID do projeto. Obtido em: Dashboard → Seu Projeto → Settings |
|
||||||
-v "$(pwd)/appwrite:/var/lib/appwrite" \
|
| `APPWRITE_API_KEY` | Console Appwrite | ✅ | Chave API com permissões Admin. Criar em: Settings → API Keys → Create API Key → Selecione todos os scopes |
|
||||||
appwrite/appwrite:latest install
|
| `APPWRITE_FUNCTIONS_ENDPOINT` | Opcional | ❌ | Endpoint customizado para Functions. Deixe vazio para usar o mesmo do `APPWRITE_ENDPOINT` |
|
||||||
|
| `APPWRITE_FUNCTIONS_API_KEY` | Opcional | ❌ | API Key separada para Functions. Deixe vazio para usar `APPWRITE_API_KEY` |
|
||||||
|
| **Configuração Client-Side (React Dashboard - Vite)** | | | |
|
||||||
|
| `VITE_APPWRITE_ENDPOINT` | Fixo | ✅ | Mesmo que `APPWRITE_ENDPOINT`. Prefixo `VITE_` expõe no browser |
|
||||||
|
| `VITE_APPWRITE_PROJECT_ID` | Console Appwrite | ✅ | Mesmo que `APPWRITE_PROJECT_ID` |
|
||||||
|
| `VITE_APPWRITE_DATABASE_ID` | Console Appwrite | ✅ | ID do Database criado. Obtido em: Databases → Seu Database → Settings |
|
||||||
|
| `VITE_APPWRITE_COLLECTION_SERVERS_ID` | Console Appwrite | ✅ | ID da coleção `servers`. Obtido em: Databases → Collections → servers → Settings |
|
||||||
|
| `VITE_APPWRITE_COLLECTION_GITHUB_REPOS_ID` | Console Appwrite | ✅ | ID da coleção `github_repos` |
|
||||||
|
| `VITE_APPWRITE_COLLECTION_AUDIT_LOGS_ID` | Console Appwrite | ✅ | ID da coleção `audit_logs` (usado para Realtime no terminal) |
|
||||||
|
| `VITE_APPWRITE_COLLECTION_CLOUDFLARE_ACCOUNTS_ID` | Console Appwrite | ✅ | ID da coleção `cloud_accounts` ou `cloudflare_accounts` |
|
||||||
|
|
||||||
|
**⚠️ IMPORTANTE**: Variáveis com prefixo `VITE_` são expostas no JavaScript do browser. **NUNCA** coloque informações sensíveis (API Keys) nelas!
|
||||||
|
|
||||||
|
### Setup Appwrite Cloud
|
||||||
|
|
||||||
|
Siga este passo a passo para configurar o backend:
|
||||||
|
|
||||||
|
#### 1. Criar Projeto
|
||||||
|
|
||||||
|
1. Acesse https://cloud.appwrite.io
|
||||||
|
2. Clique em **Create Project**
|
||||||
|
3. Dê um nome (ex: "DevOps Platform")
|
||||||
|
4. **Copie o Project ID** e salve no `.env`:
|
||||||
|
```
|
||||||
|
APPWRITE_PROJECT_ID=seu_project_id_aqui
|
||||||
|
VITE_APPWRITE_PROJECT_ID=seu_project_id_aqui
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. Criar API Key
|
||||||
|
|
||||||
|
1. No menu lateral, vá em **Settings** → **API Keys**
|
||||||
|
2. Clique em **Create API Key**
|
||||||
|
3. Nome: "Admin Key" ou "Server Key"
|
||||||
|
4. **Scopes**: Marque **todos** (necessário para operações administrativas)
|
||||||
|
5. **Copie a API Key** (só aparece uma vez!) e salve no `.env`:
|
||||||
|
```
|
||||||
|
APPWRITE_API_KEY=sua_api_key_aqui
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. Criar Database
|
||||||
|
|
||||||
|
1. No menu lateral, clique em **Databases**
|
||||||
|
2. Clique em **Create Database**
|
||||||
|
3. Nome: **DevOpsPlatform** (ou outro de sua escolha)
|
||||||
|
4. **Copie o Database ID** e salve no `.env`:
|
||||||
|
```
|
||||||
|
VITE_APPWRITE_DATABASE_ID=seu_database_id_aqui
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4. Criar Collections
|
||||||
|
|
||||||
|
Dentro do Database criado, crie as 4 coleções com os seguintes schemas:
|
||||||
|
|
||||||
|
##### Collection 1: **servers**
|
||||||
|
|
||||||
|
| Campo | Tipo | Required | Array | Default |
|
||||||
|
|-------|------|----------|-------|---------|
|
||||||
|
| `name` | String | Sim | Não | - |
|
||||||
|
| `ip` | String | Sim | Não | - |
|
||||||
|
| `status` | Enum | Sim | Não | `online` |
|
||||||
|
| `region` | String | Não | Não | - |
|
||||||
|
|
||||||
|
**Enum `status`**: `online`, `offline`
|
||||||
|
|
||||||
|
ID sugerido: `servers`
|
||||||
|
|
||||||
|
Após criar, copie o ID:
|
||||||
```
|
```
|
||||||
Preencha o `.env` com os IDs gerados localmente e replique o schema acima no console.
|
VITE_APPWRITE_COLLECTION_SERVERS_ID=servers
|
||||||
|
|
||||||
2) **Landing (Fresh + Deno)**
|
|
||||||
```bash
|
|
||||||
npm run dev:landing
|
|
||||||
# ou: cd landing && deno task start
|
|
||||||
```
|
```
|
||||||
Roda em `http://localhost:8000`. O Deno carrega variáveis do `.env` automaticamente.
|
|
||||||
|
|
||||||
3) **Dashboard (React + Vite)**
|
##### Collection 2: **github_repos**
|
||||||
```bash
|
|
||||||
cd dashboard
|
| Campo | Tipo | Required | Array | Default |
|
||||||
npm install
|
|-------|------|----------|-------|---------|
|
||||||
npm run dev
|
| `repo_name` | String | Sim | Não | - |
|
||||||
|
| `url` | URL | Sim | Não | - |
|
||||||
|
| `last_commit` | String | Não | Não | - |
|
||||||
|
| `status` | String | Não | Não | `active` |
|
||||||
|
|
||||||
|
ID sugerido: `github_repos`
|
||||||
|
|
||||||
|
```
|
||||||
|
VITE_APPWRITE_COLLECTION_GITHUB_REPOS_ID=github_repos
|
||||||
```
|
```
|
||||||
Disponível em `http://localhost:5173`. O Vite lê apenas variáveis prefixadas com `VITE_`.
|
|
||||||
|
|
||||||
4) **Landing + Dashboard em paralelo**
|
##### Collection 3: **audit_logs**
|
||||||
|
|
||||||
|
| Campo | Tipo | Required | Array | Default |
|
||||||
|
|-------|------|----------|-------|---------|
|
||||||
|
| `event` | String | Sim | Não | - |
|
||||||
|
| `user_id` | String | Sim | Não | - |
|
||||||
|
| `timestamp` | DateTime | Sim | Não | - |
|
||||||
|
|
||||||
|
ID sugerido: `audit_logs`
|
||||||
|
|
||||||
|
**⚠️ Esta coleção é usada pelo Realtime Subscription no terminal do dashboard!**
|
||||||
|
|
||||||
|
```
|
||||||
|
VITE_APPWRITE_COLLECTION_AUDIT_LOGS_ID=audit_logs
|
||||||
|
```
|
||||||
|
|
||||||
|
##### Collection 4: **cloud_accounts**
|
||||||
|
|
||||||
|
| Campo | Tipo | Required | Array | Default |
|
||||||
|
|-------|------|----------|-------|---------|
|
||||||
|
| `provider` | String | Sim | Não | - |
|
||||||
|
| `apiKey` | String | Sim | Não | - |
|
||||||
|
| `label` | String | Não | Não | - |
|
||||||
|
|
||||||
|
ID sugerido: `cloud_accounts`
|
||||||
|
|
||||||
|
```
|
||||||
|
VITE_APPWRITE_COLLECTION_CLOUDFLARE_ACCOUNTS_ID=cloud_accounts
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 5. Configurar Autenticação
|
||||||
|
|
||||||
|
1. No menu lateral, clique em **Auth**
|
||||||
|
2. Vá em **Settings**
|
||||||
|
3. Ative o provedor **Email/Password**
|
||||||
|
4. (Opcional) Configure limites de taxa e outras opções de segurança
|
||||||
|
|
||||||
|
#### 6. Criar Usuário de Teste
|
||||||
|
|
||||||
|
1. Em **Auth** → **Users**
|
||||||
|
2. Clique em **Create User**
|
||||||
|
3. Preencha:
|
||||||
|
- Email: `admin@test.com`
|
||||||
|
- Password: `admin123` (altere para algo seguro!)
|
||||||
|
- Name: `Admin User`
|
||||||
|
4. Clique em **Create**
|
||||||
|
|
||||||
|
#### 7. Implantar Functions (Opcional)
|
||||||
|
|
||||||
|
As funções estão em `appwrite-functions/`. Para implantá-las:
|
||||||
|
|
||||||
|
1. Instale a [Appwrite CLI](https://appwrite.io/docs/command-line)
|
||||||
|
2. Execute:
|
||||||
|
```bash
|
||||||
|
appwrite login
|
||||||
|
appwrite deploy function
|
||||||
|
```
|
||||||
|
3. Ou crie manualmente via Console:
|
||||||
|
- **Functions** → **Create Function**
|
||||||
|
- Faça upload do código de cada pasta em `appwrite-functions/`
|
||||||
|
|
||||||
|
Funções disponíveis:
|
||||||
|
- `hello-world`: Função exemplo
|
||||||
|
- `sync-github`: Sincroniza dados de repositórios GitHub
|
||||||
|
- `check-cloudflare-status`: Verifica status de contas Cloudflare
|
||||||
|
|
||||||
|
## 🏃 Executando o Projeto
|
||||||
|
|
||||||
|
### Desenvolvimento
|
||||||
|
|
||||||
|
#### Executar Tudo Junto
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run dev:web
|
npm run dev:web
|
||||||
```
|
```
|
||||||
Usa `npm-run-all` para iniciar ambos os frontends.
|
|
||||||
|
|
||||||
## Notas rápidas
|
Isso inicia:
|
||||||
- Rotas do dashboard são protegidas pelo Appwrite (Email/Password) e usam `account.createEmailPasswordSession`.
|
- **Landing** em http://localhost:8000
|
||||||
- O widget de overview consulta as coleções de repositórios, servidores e audit logs para mostrar métricas reais.
|
- **Dashboard** em http://localhost:5173
|
||||||
- O terminal inferior assina o canal Realtime da coleção `audit_logs` usando o ID configurado no `.env`.
|
|
||||||
|
#### Executar Componentes Separadamente
|
||||||
|
|
||||||
|
**Landing (Fresh + Deno):**
|
||||||
|
```bash
|
||||||
|
npm run dev:landing
|
||||||
|
# Ou: cd landing && deno task start
|
||||||
|
```
|
||||||
|
Acesse: http://localhost:8000
|
||||||
|
|
||||||
|
**Dashboard (React + Vite):**
|
||||||
|
```bash
|
||||||
|
npm run dev:dashboard
|
||||||
|
# Ou: cd dashboard && npm run dev
|
||||||
|
```
|
||||||
|
Acesse: http://localhost:5173
|
||||||
|
|
||||||
|
Login no dashboard usa as credenciais criadas no Appwrite (ex: `admin@test.com` / `admin123`).
|
||||||
|
|
||||||
|
### Build para Produção
|
||||||
|
|
||||||
|
**Dashboard:**
|
||||||
|
```bash
|
||||||
|
cd dashboard
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
Saída em `dashboard/dist/`
|
||||||
|
|
||||||
|
**Landing:**
|
||||||
|
```bash
|
||||||
|
cd landing
|
||||||
|
deno task build
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📁 Estrutura do Projeto
|
||||||
|
|
||||||
|
```
|
||||||
|
core/
|
||||||
|
├── .env # Variáveis de ambiente (NÃO commitar!)
|
||||||
|
├── .env.example # Template de variáveis
|
||||||
|
├── package.json # Scripts raiz e npm-run-all
|
||||||
|
├── README.md # 📄 Este arquivo
|
||||||
|
├── SECURITY.md # Política de segurança
|
||||||
|
├── appwrite.json # Configuração Appwrite CLI
|
||||||
|
├── appwrite-databases-schema.md # Schema detalhado do banco
|
||||||
|
│
|
||||||
|
├── dashboard/ # 🎨 Painel React + Vite
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── components/ # Componentes reutilizáveis
|
||||||
|
│ │ ├── pages/ # Páginas/rotas
|
||||||
|
│ │ ├── lib/ # SDK Appwrite, utilitários
|
||||||
|
│ │ ├── App.tsx # Componente raiz
|
||||||
|
│ │ └── main.tsx # Entry point
|
||||||
|
│ ├── package.json # Dependências do dashboard
|
||||||
|
│ ├── vite.config.ts # Configuração Vite
|
||||||
|
│ ├── tailwind.config.js # Configuração Tailwind
|
||||||
|
│ └── README.md # Documentação específica
|
||||||
|
│
|
||||||
|
├── landing/ # 🚀 Landing Page (Fresh + Deno)
|
||||||
|
│ ├── routes/ # Rotas Fresh
|
||||||
|
│ ├── islands/ # Componentes interativos (ilhas)
|
||||||
|
│ ├── components/ # Componentes estáticos
|
||||||
|
│ ├── static/ # Arquivos estáticos
|
||||||
|
│ ├── deno.json # Configuração e tarefas Deno
|
||||||
|
│ ├── fresh.config.ts # Configuração Fresh
|
||||||
|
│ ├── main.ts # Entry point
|
||||||
|
│ └── README.md # Documentação específica
|
||||||
|
│
|
||||||
|
└── appwrite-functions/ # ⚡ Funções Serverless
|
||||||
|
├── hello-world/
|
||||||
|
├── sync-github/
|
||||||
|
└── check-cloudflare-status/
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📜 Scripts Disponíveis
|
||||||
|
|
||||||
|
### Raiz
|
||||||
|
|
||||||
|
| Script | Comando | Descrição |
|
||||||
|
|--------|---------|-----------|
|
||||||
|
| `dev:dashboard` | `npm run dev:dashboard` | Inicia somente o dashboard |
|
||||||
|
| `dev:landing` | `npm run dev:landing` | Inicia somente a landing |
|
||||||
|
| `dev:web` | `npm run dev:web` | Inicia dashboard + landing em paralelo |
|
||||||
|
| `lint:dashboard` | `npm run lint:dashboard` | Executa ESLint no dashboard |
|
||||||
|
|
||||||
|
### Dashboard (`cd dashboard`)
|
||||||
|
|
||||||
|
| Script | Comando | Descrição |
|
||||||
|
|--------|---------|-----------|
|
||||||
|
| `dev` | `npm run dev` | Inicia dev server Vite (porta 5173) |
|
||||||
|
| `build` | `npm run build` | Compila TypeScript + build otimizado |
|
||||||
|
| `preview` | `npm run preview` | Testa build de produção localmente |
|
||||||
|
| `lint` | `npm run lint` | Verifica código com ESLint |
|
||||||
|
|
||||||
|
### Landing (`cd landing`)
|
||||||
|
|
||||||
|
| Script | Comando | Descrição |
|
||||||
|
|--------|---------|-----------|
|
||||||
|
| `start` | `deno task start` | Inicia dev server Fresh (porta 8000) |
|
||||||
|
| `build` | `deno task build` | Gera build de produção |
|
||||||
|
| `preview` | `deno task preview` | Serve build de produção |
|
||||||
|
| `check` | `deno task check` | Formata, lint e type-check |
|
||||||
|
|
||||||
|
## ✅ Verificação e Testes
|
||||||
|
|
||||||
|
### Checklist de Instalação
|
||||||
|
|
||||||
|
Execute estes comandos para verificar se tudo está configurado corretamente:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Verificar versões
|
||||||
|
node --version # Deve ser >= 18
|
||||||
|
npm --version # Deve ser >= 9
|
||||||
|
deno --version # Deve ser >= 1.40
|
||||||
|
|
||||||
|
# 2. Verificar instalação de dependências
|
||||||
|
npm ls npm-run-all # Raiz
|
||||||
|
cd dashboard && npm ls appwrite # Dashboard
|
||||||
|
cd ../landing && deno info # Landing
|
||||||
|
|
||||||
|
# 3. Testar build do dashboard
|
||||||
|
cd dashboard
|
||||||
|
npm run build
|
||||||
|
# Deve gerar pasta dist/ sem erros
|
||||||
|
|
||||||
|
# 4. Testar lint
|
||||||
|
npm run lint
|
||||||
|
# Deve passar sem erros (warnings ok)
|
||||||
|
|
||||||
|
# 5. Testar landing page
|
||||||
|
cd ../landing
|
||||||
|
deno task check
|
||||||
|
# Deve passar formatting, linting e type-check
|
||||||
|
|
||||||
|
# 6. Verificar arquivo .env
|
||||||
|
cat ../.env
|
||||||
|
# Deve ter todos os IDs preenchidos (não vazios)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Testes Manuais
|
||||||
|
|
||||||
|
1. **Dashboard (http://localhost:5173)**:
|
||||||
|
- Login deve funcionar com usuário criado no Appwrite
|
||||||
|
- Overview deve mostrar widgets de servidores, repos e logs
|
||||||
|
- Terminal inferior deve conectar ao Realtime (audit_logs)
|
||||||
|
|
||||||
|
2. **Landing (http://localhost:8000)**:
|
||||||
|
- Página deve carregar sem erros
|
||||||
|
- Navegação deve funcionar
|
||||||
|
- Componentes interativos (Counter, ServerStatus) devem responder
|
||||||
|
|
||||||
|
## 🔧 Troubleshooting
|
||||||
|
|
||||||
|
### Erro: "Cannot find module 'appwrite'"
|
||||||
|
|
||||||
|
**Solução:**
|
||||||
|
```bash
|
||||||
|
cd dashboard
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### Erro: "deno: command not found"
|
||||||
|
|
||||||
|
**Solução:**
|
||||||
|
```bash
|
||||||
|
# Linux/Mac
|
||||||
|
curl -fsSL https://deno.land/install.sh | sh
|
||||||
|
|
||||||
|
# Windows (PowerShell)
|
||||||
|
irm https://deno.land/install.ps1 | iex
|
||||||
|
|
||||||
|
# Adicione ao PATH (Linux/Mac):
|
||||||
|
echo 'export PATH="$HOME/.deno/bin:$PATH"' >> ~/.bashrc
|
||||||
|
source ~/.bashrc
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dashboard não conecta ao Appwrite
|
||||||
|
|
||||||
|
**Checklist:**
|
||||||
|
1. Arquivo `.env` existe e tem variáveis `VITE_*` preenchidas?
|
||||||
|
2. Project ID está correto?
|
||||||
|
3. Database existe no Appwrite Cloud?
|
||||||
|
4. Collections foram criadas com os IDs corretos?
|
||||||
|
5. Usuário de autenticação foi criado?
|
||||||
|
|
||||||
|
**Debug:**
|
||||||
|
```javascript
|
||||||
|
// No console do browser (F12)
|
||||||
|
console.log(import.meta.env.VITE_APPWRITE_PROJECT_ID)
|
||||||
|
// Deve mostrar seu Project ID, não "undefined"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Erro: "Failed to fetch" no dashboard
|
||||||
|
|
||||||
|
**Possível causa**: CORS ou endpoint incorreto.
|
||||||
|
|
||||||
|
**Solução:**
|
||||||
|
1. Verifique se `VITE_APPWRITE_ENDPOINT` está correto: `https://cloud.appwrite.io/v1`
|
||||||
|
2. No Appwrite Console → Settings → Platforms, adicione:
|
||||||
|
- **Web Platform** com hostname `localhost`
|
||||||
|
|
||||||
|
### Landing page não carrega dependências
|
||||||
|
|
||||||
|
**Solução:**
|
||||||
|
```bash
|
||||||
|
cd landing
|
||||||
|
# Limpar cache do Deno
|
||||||
|
deno cache --reload dev.ts
|
||||||
|
# Tentar novamente
|
||||||
|
deno task start
|
||||||
|
```
|
||||||
|
|
||||||
|
### Build do dashboard falha
|
||||||
|
|
||||||
|
**Erro comum**: TypeScript errors
|
||||||
|
|
||||||
|
**Solução:**
|
||||||
|
```bash
|
||||||
|
cd dashboard
|
||||||
|
# Verificar erros de tipo
|
||||||
|
npx tsc --noEmit
|
||||||
|
# Se muitos erros, verifique versões:
|
||||||
|
npm ls typescript
|
||||||
|
npm ls @types/react
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚀 Deploy
|
||||||
|
|
||||||
|
### Dashboard (Vite App)
|
||||||
|
|
||||||
|
**Opções recomendadas**:
|
||||||
|
- [Vercel](https://vercel.com) (zero config)
|
||||||
|
- [Netlify](https://netlify.com)
|
||||||
|
- [Cloudflare Pages](https://pages.cloudflare.com)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd dashboard
|
||||||
|
npm run build
|
||||||
|
# Upload da pasta dist/ para seu provider
|
||||||
|
```
|
||||||
|
|
||||||
|
**Importante**: Configure as variáveis `VITE_*` no painel do provider!
|
||||||
|
|
||||||
|
### Landing (Deno Fresh)
|
||||||
|
|
||||||
|
**Opções recomendadas**:
|
||||||
|
- [Deno Deploy](https://deno.com/deploy) (nativo Fresh)
|
||||||
|
- [Fly.io](https://fly.io)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd landing
|
||||||
|
deno task build
|
||||||
|
# Ou deploy direto para Deno Deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
### Appwrite Functions
|
||||||
|
|
||||||
|
Via Appwrite CLI:
|
||||||
|
```bash
|
||||||
|
appwrite deploy function
|
||||||
|
```
|
||||||
|
|
||||||
|
Ou manualmente via Appwrite Console → Functions.
|
||||||
|
|
||||||
|
## 📚 Recursos Adicionais
|
||||||
|
|
||||||
|
- [Documentação Appwrite](https://appwrite.io/docs)
|
||||||
|
- [Documentação Fresh](https://fresh.deno.dev/docs)
|
||||||
|
- [Documentação Vite](https://vitejs.dev)
|
||||||
|
- [Documentação React](https://react.dev)
|
||||||
|
- [Deno Manual](https://deno.land/manual)
|
||||||
|
|
||||||
|
## 🔐 Segurança
|
||||||
|
|
||||||
|
- **NUNCA** commite o arquivo `.env`
|
||||||
|
- API Keys devem ter scopes mínimos necessários em produção
|
||||||
|
- Habilite MFA no Appwrite Console
|
||||||
|
- Revise `SECURITY.md` para reportar vulnerabilidades
|
||||||
|
|
||||||
|
## 📝 Licença
|
||||||
|
|
||||||
|
Este projeto está sob a licença [MIT](LICENSE) (ou especifique sua licença).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Desenvolvido com ❤️ usando Appwrite Cloud, Fresh, React e Deno**
|
||||||
|
|
|
||||||
|
|
@ -1,30 +1,263 @@
|
||||||
# React + TypeScript + Vite
|
# Dashboard - Core Platform
|
||||||
|
|
||||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
> Painel administrativo DevOps desenvolvido com **React + TypeScript + Vite** integrado ao **Appwrite Cloud** para autenticação, database e realtime.
|
||||||
|
|
||||||
Currently, two official plugins are available:
|
## 🎯 Visão Geral
|
||||||
|
|
||||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
|
Dashboard para gerenciamento de:
|
||||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
- **Servidores**: Monitoramento de status, IP e região
|
||||||
|
- **Repositórios GitHub**: Acompanhamento de commits e status
|
||||||
|
- **Audit Logs**: Logs de eventos em tempo real
|
||||||
|
- **Contas Cloudflare**: Gerenciamento de integrações
|
||||||
|
|
||||||
## Expanding the ESLint configuration
|
## 🛠 Stack Tecnológica
|
||||||
|
|
||||||
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
|
- **Framework**: [React 18](https://react.dev)
|
||||||
|
- **Build Tool**: [Vite 5](https://vitejs.dev)
|
||||||
|
- **Linguagem**: TypeScript 5
|
||||||
|
- **Roteamento**: React Router DOM 7
|
||||||
|
- **Estilização**: Tailwind CSS 3
|
||||||
|
- **Backend**: Appwrite Cloud SDK
|
||||||
|
- **Ícones**: Lucide React
|
||||||
|
- **Linting**: ESLint 8
|
||||||
|
|
||||||
- Configure the top-level `parserOptions` property like this:
|
## 📦 Instalação
|
||||||
|
|
||||||
```js
|
```bash
|
||||||
export default {
|
# Na raiz do projeto
|
||||||
// other rules...
|
cd dashboard
|
||||||
parserOptions: {
|
|
||||||
ecmaVersion: 'latest',
|
# Instalar dependências
|
||||||
sourceType: 'module',
|
npm install
|
||||||
project: ['./tsconfig.json', './tsconfig.node.json'],
|
|
||||||
tsconfigRootDir: __dirname,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked`
|
## ⚙️ Configuração
|
||||||
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
|
|
||||||
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list
|
### Variáveis de Ambiente
|
||||||
|
|
||||||
|
O dashboard lê variáveis do arquivo `.env` na **raíz do monorepo** (não nesta pasta).
|
||||||
|
|
||||||
|
Variáveis necessárias (todas com prefixo `VITE_`):
|
||||||
|
|
||||||
|
```env
|
||||||
|
VITE_APPWRITE_ENDPOINT=https://cloud.appwrite.io/v1
|
||||||
|
VITE_APPWRITE_PROJECT_ID=seu_project_id
|
||||||
|
VITE_APPWRITE_DATABASE_ID=seu_database_id
|
||||||
|
VITE_APPWRITE_COLLECTION_SERVERS_ID=servers
|
||||||
|
VITE_APPWRITE_COLLECTION_GITHUB_REPOS_ID=github_repos
|
||||||
|
VITE_APPWRITE_COLLECTION_AUDIT_LOGS_ID=audit_logs
|
||||||
|
VITE_APPWRITE_COLLECTION_CLOUDFLARE_ACCOUNTS_ID=cloud_accounts
|
||||||
|
```
|
||||||
|
|
||||||
|
**⚠️ Importante**: O Vite só expõe variáveis com prefixo `VITE_` para o browser.
|
||||||
|
|
||||||
|
### Configuração do Appwrite
|
||||||
|
|
||||||
|
Veja o [README principal](../README.md#setup-appwrite-cloud) para instruções completas de setup do Appwrite Cloud.
|
||||||
|
|
||||||
|
## 🏃 Scripts
|
||||||
|
|
||||||
|
| Comando | Descrição |
|
||||||
|
|---------|-----------|
|
||||||
|
| `npm run dev` | Inicia dev server (porta 5173) |
|
||||||
|
| `npm run build` | Gera build de produção em `dist/` |
|
||||||
|
| `npm run preview` | Testa build localmente |
|
||||||
|
| `npm run lint` | Executa ESLint |
|
||||||
|
|
||||||
|
### Executar em Desenvolvimento
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Acesse: http://localhost:5173
|
||||||
|
|
||||||
|
**Login**: Use credenciais criadas no Appwrite Auth (ex: `admin@test.com`)
|
||||||
|
|
||||||
|
## 📁 Estrutura de Pastas
|
||||||
|
|
||||||
|
```
|
||||||
|
dashboard/
|
||||||
|
├── public/ # Arquivos estáticos
|
||||||
|
│ └── vite.svg
|
||||||
|
├── src/
|
||||||
|
│ ├── components/ # Componentes reutilizáveis
|
||||||
|
│ │ ├── Header.tsx
|
||||||
|
│ │ ├── Overview.tsx
|
||||||
|
│ │ ├── ServerList.tsx
|
||||||
|
│ │ ├── GitHubRepos.tsx
|
||||||
|
│ │ ├── Terminal.tsx
|
||||||
|
│ │ └── ...
|
||||||
|
│ ├── pages/ # Páginas/rotas
|
||||||
|
│ │ ├── Login.tsx
|
||||||
|
│ │ ├── Dashboard.tsx
|
||||||
|
│ │ └── ...
|
||||||
|
│ ├── lib/ # Utilitários e SDK
|
||||||
|
│ │ └── appwrite.ts # Inicialização SDK Appwrite
|
||||||
|
│ ├── App.tsx # Componente raiz + rotas
|
||||||
|
│ ├── main.tsx # Entry point
|
||||||
|
│ └── index.css # Tailwind + estilos globais
|
||||||
|
├── index.html # Template HTML
|
||||||
|
├── vite.config.ts # Configuração Vite
|
||||||
|
├── tailwind.config.js # Configuração Tailwind
|
||||||
|
├── tsconfig.json # Configuração TypeScript
|
||||||
|
└── package.json # Dependências e scripts
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔑 Funcionalidades
|
||||||
|
|
||||||
|
### Autenticação
|
||||||
|
|
||||||
|
- Login com Email/Password via Appwrite Auth
|
||||||
|
- Session management com `account.createEmailPasswordSession`
|
||||||
|
- Logout com `account.deleteSession('current')`
|
||||||
|
- Proteção de rotas com verificação de sessão
|
||||||
|
|
||||||
|
### Database Queries
|
||||||
|
|
||||||
|
Consulta coleções Appwrite usando o SDK:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { databases } from './lib/appwrite';
|
||||||
|
|
||||||
|
// Listar servidores
|
||||||
|
const servers = await databases.listDocuments(
|
||||||
|
import.meta.env.VITE_APPWRITE_DATABASE_ID,
|
||||||
|
import.meta.env.VITE_APPWRITE_COLLECTION_SERVERS_ID
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Realtime Subscriptions
|
||||||
|
|
||||||
|
Terminal assina eventos da coleção `audit_logs`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { client } from './lib/appwrite';
|
||||||
|
|
||||||
|
client.subscribe(
|
||||||
|
`databases.${databaseId}.collections.${auditLogsId}.documents`,
|
||||||
|
(response) => {
|
||||||
|
console.log('Novo log:', response.payload);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎨 Componentes Principais
|
||||||
|
|
||||||
|
| Componente | Descrição |
|
||||||
|
|------------|-----------|
|
||||||
|
| `Header` | Barra superior com navegação e logout |
|
||||||
|
| `Overview` | Widgets com métricas de servidores, repos e logs |
|
||||||
|
| `ServerList` | Tabela de servidores com status online/offline |
|
||||||
|
| `GitHubRepos` | Lista de repositórios GitHub integrados |
|
||||||
|
| `Terminal` | Console com logs em tempo real (Realtime) |
|
||||||
|
|
||||||
|
## 🧪 Testes
|
||||||
|
|
||||||
|
### Linting
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run lint
|
||||||
|
```
|
||||||
|
|
||||||
|
Configuração ESLint em `.eslintrc.cjs`:
|
||||||
|
- Parser: `@typescript-eslint/parser`
|
||||||
|
- Plugins: React Hooks, React Refresh
|
||||||
|
- Regras: React 18.2+ (sem import React necessário)
|
||||||
|
|
||||||
|
### Build de Produção
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Saída:
|
||||||
|
- `dist/index.html`
|
||||||
|
- `dist/assets/index-[hash].js`
|
||||||
|
- `dist/assets/index-[hash].css`
|
||||||
|
|
||||||
|
Otimizações:
|
||||||
|
- Tree-shaking
|
||||||
|
- Minificação
|
||||||
|
- Code splitting
|
||||||
|
- Hashing de assets
|
||||||
|
|
||||||
|
## 🚀 Deploy
|
||||||
|
|
||||||
|
### Vercel (Recomendado)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
# Ou conecte o repo no painel Vercel
|
||||||
|
```
|
||||||
|
|
||||||
|
**Configuração Vercel**:
|
||||||
|
- Build Command: `npm run build`
|
||||||
|
- Output Directory: `dist`
|
||||||
|
- Environment Variables: Adicione todas as `VITE_*`
|
||||||
|
|
||||||
|
### Netlify
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
# Arraste a pasta dist/ no painel Netlify
|
||||||
|
```
|
||||||
|
|
||||||
|
**netlify.toml** (opcional):
|
||||||
|
```toml
|
||||||
|
[build]
|
||||||
|
command = "npm run build"
|
||||||
|
publish = "dist"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Cloudflare Pages
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
# Upload via Wrangler ou painel
|
||||||
|
```
|
||||||
|
|
||||||
|
**⚠️ Importante**: Configure as variáveis de ambiente `VITE_*` no painel do provider!
|
||||||
|
|
||||||
|
## 🔧 Troubleshooting
|
||||||
|
|
||||||
|
### "import.meta.env.VITE_APPWRITE_PROJECT_ID is undefined"
|
||||||
|
|
||||||
|
**Causa**: Arquivo `.env` não está na raiz do monorepo ou variável não tem prefixo `VITE_`
|
||||||
|
|
||||||
|
**Solução**:
|
||||||
|
```bash
|
||||||
|
# Verifique se o .env existe na raiz (não em dashboard/)
|
||||||
|
cat ../.env
|
||||||
|
|
||||||
|
# Certifique-se que as variáveis começam com VITE_
|
||||||
|
grep VITE_ ../.env
|
||||||
|
```
|
||||||
|
|
||||||
|
### Erro de CORS no Appwrite
|
||||||
|
|
||||||
|
**Solução**:
|
||||||
|
1. Appwrite Console → Settings → Platforms
|
||||||
|
2. Add Platform → **Web**
|
||||||
|
3. Hostname: `localhost` (dev) e seu domínio (produção)
|
||||||
|
|
||||||
|
### TypeScript errors no build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Verificar erros
|
||||||
|
npx tsc --noEmit
|
||||||
|
|
||||||
|
# Atualizar tipos se necessário
|
||||||
|
npm install --save-dev @types/react@latest @types/react-dom@latest
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📚 Recursos
|
||||||
|
|
||||||
|
- [Appwrite React SDK](https://appwrite.io/docs/sdks#client)
|
||||||
|
- [Vite Guide](https://vitejs.dev/guide/)
|
||||||
|
- [React Documentation](https://react.dev)
|
||||||
|
- [Tailwind CSS](https://tailwindcss.com/docs)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Para configuração completa e setup do Appwrite, veja o [README principal](../README.md).
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,351 @@
|
||||||
# Fresh project
|
# Landing Page - Core Platform
|
||||||
|
|
||||||
Your new Fresh project is ready to go. You can follow the Fresh "Getting
|
> Landing page desenvolvida com **Fresh** (framework Deno) e **Tailwind CSS**. Server-side rendering para performance máxima.
|
||||||
Started" guide here: https://fresh.deno.dev/docs/getting-started
|
|
||||||
|
|
||||||
### Usage
|
## 🎯 Visão Geral
|
||||||
|
|
||||||
Make sure to install Deno: https://deno.land/manual/getting_started/installation
|
Landing page pública da plataforma DevOps, com:
|
||||||
|
- Server-Side Rendering (SSR) nativo
|
||||||
|
- Componentes interativos (Islands Architecture)
|
||||||
|
- Páginas estáticas otimizadas
|
||||||
|
- Tailwind CSS integrado
|
||||||
|
|
||||||
Then start the project:
|
## 🛠 Stack Tecnológica
|
||||||
|
|
||||||
|
- **Framework**: [Fresh 1.7](https://fresh.deno.dev)
|
||||||
|
- **Runtime**: [Deno 2.x](https://deno.land)
|
||||||
|
- **JavaScript Library**: [Preact 10](https://preactjs.com)
|
||||||
|
- **Estilização**: Tailwind CSS 3
|
||||||
|
- **Signals**: @preact/signals
|
||||||
|
|
||||||
|
## 📦 Instalação
|
||||||
|
|
||||||
|
### Pré-requisito: Deno
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Linux/Mac
|
||||||
|
curl -fsSL https://deno.land/install.sh | sh
|
||||||
|
|
||||||
|
# Windows (PowerShell)
|
||||||
|
irm https://deno.land/install.ps1 | iex
|
||||||
|
|
||||||
|
# Verificar instalação
|
||||||
|
deno --version
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dependências
|
||||||
|
|
||||||
|
Fresh gerencia dependências automaticamente via `deno.json`. Não precisa `npm install`!
|
||||||
|
|
||||||
|
As dependências são baixadas na primeira execução:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd landing
|
||||||
|
deno task start
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🏃 Scripts
|
||||||
|
|
||||||
|
Todos os scripts estão definidos em `deno.json`:
|
||||||
|
|
||||||
|
| Comando | Descrição |
|
||||||
|
|---------|-----------|
|
||||||
|
| `deno task start` | Inicia dev server (porta 8000) com hot reload |
|
||||||
|
| `deno task build` | Gera build de produção |
|
||||||
|
| `deno task preview` | Serve build de produção |
|
||||||
|
| `deno task check` | Executa fmt + lint + type-check |
|
||||||
|
| `deno task manifest` | Regenera arquivo de rotas |
|
||||||
|
|
||||||
|
### Executar em Desenvolvimento
|
||||||
|
|
||||||
|
```bash
|
||||||
|
deno task start
|
||||||
|
```
|
||||||
|
|
||||||
|
Acesse: http://localhost:8000
|
||||||
|
|
||||||
|
**Hot Reload**: Alterações em `routes/` e `islands/` recarregam automaticamente.
|
||||||
|
|
||||||
|
## 📁 Estrutura de Pastas
|
||||||
|
|
||||||
```
|
```
|
||||||
|
landing/
|
||||||
|
├── routes/ # 🗺️ Rotas (SSR)
|
||||||
|
│ ├── index.tsx # Homepage (/)
|
||||||
|
│ ├── _app.tsx # Layout global
|
||||||
|
│ ├── _404.tsx # Página 404
|
||||||
|
│ ├── greet/
|
||||||
|
│ │ └── [name].tsx # Rota dinâmica (/greet/:name)
|
||||||
|
│ └── api/
|
||||||
|
│ └── joke.ts # API endpoint (/api/joke)
|
||||||
|
│
|
||||||
|
├── islands/ # 🏝️ Componentes interativos (client-side)
|
||||||
|
│ ├── Counter.tsx # Exemplo de contador
|
||||||
|
│ └── ServerStatus.tsx # Widget de status
|
||||||
|
│
|
||||||
|
├── components/ # 🧩 Componentes estáticos (SSR only)
|
||||||
|
│ ├── Button.tsx
|
||||||
|
│ └── Header.tsx
|
||||||
|
│
|
||||||
|
├── static/ # 📦 Arquivos estáticos
|
||||||
|
│ ├── logo.svg
|
||||||
|
│ ├── favicon.ico
|
||||||
|
│ └── styles.css
|
||||||
|
│
|
||||||
|
├── deno.json # Configuração Deno + tarefas
|
||||||
|
├── fresh.config.ts # Configuração Fresh
|
||||||
|
├── fresh.gen.ts # Auto-gerado (manifesto de rotas)
|
||||||
|
├── main.ts # Entry point produção
|
||||||
|
├── dev.ts # Entry point desenvolvimento
|
||||||
|
└── tailwind.config.ts # Configuração Tailwind
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🏗️ Arquitetura Fresh
|
||||||
|
|
||||||
|
### Routes (SSR)
|
||||||
|
|
||||||
|
Arquivos em `routes/` são renderizados no servidor:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// routes/index.tsx
|
||||||
|
export default function Home() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1>Homepage</h1>
|
||||||
|
<p>Renderizado no servidor!</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Rotas dinâmicas:
|
||||||
|
```tsx
|
||||||
|
// routes/greet/[name].tsx
|
||||||
|
export default function GreetPage(props) {
|
||||||
|
const { name } = props.params;
|
||||||
|
return <h1>Olá, {name}!</h1>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Islands (Client-Side)
|
||||||
|
|
||||||
|
Componentes em `islands/` são hidratados no cliente:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// islands/Counter.tsx
|
||||||
|
import { Signal, signal } from "@preact/signals";
|
||||||
|
|
||||||
|
export default function Counter() {
|
||||||
|
const count = signal(0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p>Contador: {count}</p>
|
||||||
|
<button onClick={() => count.value++}>+1</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Quando usar Islands**:
|
||||||
|
- Formulários interativos
|
||||||
|
- Widgets dinâmicos
|
||||||
|
- Animações client-side
|
||||||
|
|
||||||
|
**Quando usar Routes**:
|
||||||
|
- Conteúdo estático
|
||||||
|
- SEO crítico
|
||||||
|
- Performance máxima
|
||||||
|
|
||||||
|
### API Routes
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// routes/api/joke.ts
|
||||||
|
export const handler = {
|
||||||
|
GET() {
|
||||||
|
const joke = "Por que o JavaScript foi ao psicólogo? Porque tinha muitos callbacks!";
|
||||||
|
return new Response(JSON.stringify({ joke }), {
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Acesse: http://localhost:8000/api/joke
|
||||||
|
|
||||||
|
## 🎨 Tailwind CSS
|
||||||
|
|
||||||
|
Fresh integra Tailwind via plugin:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Usar classes normalmente
|
||||||
|
<div class="bg-blue-500 text-white p-4 rounded-lg">
|
||||||
|
Card estilizado
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Configuração**: `tailwind.config.ts`
|
||||||
|
|
||||||
|
## 🧪 Testes
|
||||||
|
|
||||||
|
### Type Checking
|
||||||
|
|
||||||
|
```bash
|
||||||
|
deno task check
|
||||||
|
```
|
||||||
|
|
||||||
|
Executa:
|
||||||
|
1. `deno fmt --check` (formatação)
|
||||||
|
2. `deno lint` (linting)
|
||||||
|
3. `deno check **/*.ts` (type-check)
|
||||||
|
|
||||||
|
### Corrigir Formatação
|
||||||
|
|
||||||
|
```bash
|
||||||
|
deno fmt
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚀 Deploy
|
||||||
|
|
||||||
|
### Deno Deploy (Recomendado)
|
||||||
|
|
||||||
|
**Via GitHub (automático)**:
|
||||||
|
1. Push para GitHub
|
||||||
|
2. Conecte repo em https://dash.deno.com
|
||||||
|
3. Fresh é detectado automaticamente
|
||||||
|
4. Deploy feito em cada push
|
||||||
|
|
||||||
|
**Via CLI**:
|
||||||
|
```bash
|
||||||
|
# Instalar CLI
|
||||||
|
deno install -Arf https://deno.land/x/deploy/deployctl.ts
|
||||||
|
|
||||||
|
# Deploy
|
||||||
|
deployctl deploy --project=seu-projeto dev.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker (Self-Hosted)
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM denoland/deno:alpine
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY . .
|
||||||
|
RUN deno cache dev.ts
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
CMD ["deno", "task", "start"]
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -t core-landing .
|
||||||
|
docker run -p 8000:8000 core-landing
|
||||||
|
```
|
||||||
|
|
||||||
|
### Fly.io
|
||||||
|
|
||||||
|
```bash
|
||||||
|
flyctl launch
|
||||||
|
flyctl deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⚙️ Configuração Avançada
|
||||||
|
|
||||||
|
### Variáveis de Ambiente
|
||||||
|
|
||||||
|
Fresh carrega `.env` automaticamente (se existir):
|
||||||
|
|
||||||
|
```env
|
||||||
|
# landing/.env
|
||||||
|
API_URL=https://api.example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
Acesso:
|
||||||
|
```typescript
|
||||||
|
const apiUrl = Deno.env.get("API_URL");
|
||||||
|
```
|
||||||
|
|
||||||
|
**⚠️ Segurança**: Não exponha secrets no client! Use apenas em API routes.
|
||||||
|
|
||||||
|
### Custom Middleware
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// routes/_middleware.ts
|
||||||
|
export async function handler(req, ctx) {
|
||||||
|
console.log("Request:", req.url);
|
||||||
|
const resp = await ctx.next();
|
||||||
|
resp.headers.set("X-Custom-Header", "Fresh");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### DENO_TLS_CA_STORE=system
|
||||||
|
|
||||||
|
Se sua rede usa certificados customizados:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# deno.json já inclui por padrão
|
||||||
DENO_TLS_CA_STORE=system deno task start
|
DENO_TLS_CA_STORE=system deno task start
|
||||||
```
|
```
|
||||||
|
|
||||||
This will watch the project directory and restart as necessary.
|
## 🔧 Troubleshooting
|
||||||
|
|
||||||
If your network uses a custom certificate authority, setting
|
### "Import map not found"
|
||||||
`DENO_TLS_CA_STORE=system` ensures Deno trusts the system certificate store
|
|
||||||
while downloading dependencies.
|
**Solução**: Regenerar manifesto
|
||||||
|
```bash
|
||||||
|
deno task manifest
|
||||||
|
```
|
||||||
|
|
||||||
|
### Erro ao baixar dependências
|
||||||
|
|
||||||
|
**Solução**: Limpar cache
|
||||||
|
```bash
|
||||||
|
deno cache --reload dev.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### Port 8000 já em uso
|
||||||
|
|
||||||
|
**Solução**: Alterar porta em `dev.ts`
|
||||||
|
```typescript
|
||||||
|
await start(manifest, { port: 3000 });
|
||||||
|
```
|
||||||
|
|
||||||
|
### Tailwind não funciona
|
||||||
|
|
||||||
|
**Solução**: Verificar plugin em `fresh.config.ts`
|
||||||
|
```typescript
|
||||||
|
import twindPlugin from "$fresh/plugins/twind.ts";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
plugins: [twindPlugin(twindConfig)],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📚 Recursos
|
||||||
|
|
||||||
|
- [Fresh Documentation](https://fresh.deno.dev/docs)
|
||||||
|
- [Deno Manual](https://deno.land/manual)
|
||||||
|
- [Preact Guide](https://preactjs.com/guide)
|
||||||
|
- [Islands Architecture](https://jasonformat.com/islands-architecture/)
|
||||||
|
|
||||||
|
## 🆚 Fresh vs Outros Frameworks
|
||||||
|
|
||||||
|
| Feature | Fresh | Next.js | SvelteKit |
|
||||||
|
|---------|-------|---------|-----------|
|
||||||
|
| Runtime | Deno | Node.js | Node.js |
|
||||||
|
| SSR | ✅ Nativo | ✅ | ✅ |
|
||||||
|
| Islands | ✅ Automático | ❌ | ❌ |
|
||||||
|
| Bundle size | 0 KB default | ~70 KB | ~20 KB |
|
||||||
|
| TypeScript | ✅ Nativo | Precisa config | Precisa config |
|
||||||
|
| Deploy | Deno Deploy | Vercel | Vercel/Netlify |
|
||||||
|
|
||||||
|
**Vantagens Fresh**:
|
||||||
|
- Zero JavaScript no cliente por padrão
|
||||||
|
- TypeScript sem configuração
|
||||||
|
- Deploy instantâneo (Deno Deploy)
|
||||||
|
- Deno = segurança e performance
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Para configuração completa do monorepo, veja o [README principal](../README.md).
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue