Compare commits
5 Commits
nico/26-fe
...
stg
| Author | SHA1 | Date | |
|---|---|---|---|
| 9e6734d1a5 | |||
|
|
1b9ddf0f4b | ||
| a0f440f6b3 | |||
| 1f56dd7660 | |||
| 1a2a213d0a |
19
.env.example
Normal file
19
.env.example
Normal file
@@ -0,0 +1,19 @@
|
||||
# Database
|
||||
DATABASE_URL="postgresql://user:password@localhost:5432/dashboard_desa?schema=public"
|
||||
|
||||
# Authentication
|
||||
BETTER_AUTH_SECRET="your-secret-key-here-min-32-characters"
|
||||
ADMIN_EMAIL="admin@example.com"
|
||||
ADMIN_PASSWORD="admin123"
|
||||
|
||||
# GitHub OAuth (Optional)
|
||||
GITHUB_CLIENT_ID=""
|
||||
GITHUB_CLIENT_SECRET=""
|
||||
|
||||
# Application
|
||||
PORT=3000
|
||||
NODE_ENV=development
|
||||
LOG_LEVEL=info
|
||||
|
||||
# Public URL
|
||||
VITE_PUBLIC_URL="http://localhost:3000"
|
||||
106
.github/workflows/publish.yml
vendored
Normal file
106
.github/workflows/publish.yml
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
name: Publish Docker to GHCR
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
stack_env:
|
||||
description: "stack env"
|
||||
required: true
|
||||
type: choice
|
||||
default: "dev"
|
||||
options:
|
||||
- dev
|
||||
- prod
|
||||
- stg
|
||||
tag:
|
||||
description: "Image tag (e.g. 1.0.0)"
|
||||
required: true
|
||||
default: "1.0.0"
|
||||
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Build & Push to GHCR ${{ github.repository }}:${{ github.event.inputs.stack_env }}-${{ github.event.inputs.tag }}
|
||||
runs-on: ubuntu-latest
|
||||
environment: ${{ vars.PORTAINER_ENV || 'portainer' }}
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Free disk space
|
||||
run: |
|
||||
sudo rm -rf /usr/share/dotnet
|
||||
sudo rm -rf /usr/local/lib/android
|
||||
sudo rm -rf /opt/ghc
|
||||
sudo rm -rf /opt/hostedtoolcache/CodeQL
|
||||
sudo docker image prune --all --force
|
||||
df -h
|
||||
|
||||
- name: Checkout branch ${{ github.event.inputs.stack_env }}
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.inputs.stack_env }}
|
||||
|
||||
- name: Checkout scripts from main
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
path: .ci
|
||||
sparse-checkout: .github/workflows/script
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Generate image metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
type=raw,value=${{ github.event.inputs.stack_env }}-${{ github.event.inputs.tag }}
|
||||
type=raw,value=${{ github.event.inputs.stack_env }}-latest
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: true
|
||||
platforms: linux/amd64
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
no-cache: true
|
||||
|
||||
- name: Notify success
|
||||
if: success()
|
||||
run: bash ./.ci/.github/workflows/script/notify.sh
|
||||
env:
|
||||
TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
NOTIFY_STATUS: success
|
||||
NOTIFY_WORKFLOW: "Publish Docker"
|
||||
NOTIFY_DETAIL: "Image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.event.inputs.stack_env }}-${{ github.event.inputs.tag }}"
|
||||
|
||||
- name: Notify failure
|
||||
if: failure()
|
||||
run: bash ./.ci/.github/workflows/script/notify.sh
|
||||
env:
|
||||
TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
NOTIFY_STATUS: failure
|
||||
NOTIFY_WORKFLOW: "Publish Docker"
|
||||
NOTIFY_DETAIL: "Image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.event.inputs.stack_env }}-${{ github.event.inputs.tag }}"
|
||||
60
.github/workflows/re-pull.yml
vendored
Normal file
60
.github/workflows/re-pull.yml
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
name: Re-Pull Docker
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
stack_name:
|
||||
description: "stack name"
|
||||
required: true
|
||||
type: string
|
||||
stack_env:
|
||||
description: "stack env"
|
||||
required: true
|
||||
type: choice
|
||||
default: "dev"
|
||||
options:
|
||||
- dev
|
||||
- stg
|
||||
- prod
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Re-Pull Docker ${{ github.event.inputs.stack_name }}
|
||||
runs-on: ubuntu-latest
|
||||
environment: ${{ vars.PORTAINER_ENV || 'portainer' }}
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout scripts from main
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
sparse-checkout: .github/workflows/script
|
||||
|
||||
- name: Deploy ke Portainer
|
||||
run: bash ./.github/workflows/script/re-pull.sh
|
||||
env:
|
||||
PORTAINER_USERNAME: ${{ secrets.PORTAINER_USERNAME }}
|
||||
PORTAINER_PASSWORD: ${{ secrets.PORTAINER_PASSWORD }}
|
||||
PORTAINER_URL: ${{ secrets.PORTAINER_URL }}
|
||||
STACK_NAME: ${{ github.event.inputs.stack_name }}-${{ github.event.inputs.stack_env }}
|
||||
|
||||
- name: Notify success
|
||||
if: success()
|
||||
run: bash ./.github/workflows/script/notify.sh
|
||||
env:
|
||||
TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
NOTIFY_STATUS: success
|
||||
NOTIFY_WORKFLOW: "Re-Pull Docker"
|
||||
NOTIFY_DETAIL: "Stack: ${{ github.event.inputs.stack_name }}-${{ github.event.inputs.stack_env }}"
|
||||
|
||||
- name: Notify failure
|
||||
if: failure()
|
||||
run: bash ./.github/workflows/script/notify.sh
|
||||
env:
|
||||
TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
NOTIFY_STATUS: failure
|
||||
NOTIFY_WORKFLOW: "Re-Pull Docker"
|
||||
NOTIFY_DETAIL: "Stack: ${{ github.event.inputs.stack_name }}-${{ github.event.inputs.stack_env }}"
|
||||
26
.github/workflows/script/notify.sh
vendored
Normal file
26
.github/workflows/script/notify.sh
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
|
||||
: "${TELEGRAM_TOKEN:?TELEGRAM_TOKEN tidak di-set}"
|
||||
: "${TELEGRAM_CHAT_ID:?TELEGRAM_CHAT_ID tidak di-set}"
|
||||
: "${NOTIFY_STATUS:?NOTIFY_STATUS tidak di-set}"
|
||||
: "${NOTIFY_WORKFLOW:?NOTIFY_WORKFLOW tidak di-set}"
|
||||
|
||||
if [ "$NOTIFY_STATUS" = "success" ]; then
|
||||
ICON="✅"
|
||||
TEXT="${ICON} *${NOTIFY_WORKFLOW}* berhasil!"
|
||||
else
|
||||
ICON="❌"
|
||||
TEXT="${ICON} *${NOTIFY_WORKFLOW}* gagal!"
|
||||
fi
|
||||
|
||||
if [ -n "$NOTIFY_DETAIL" ]; then
|
||||
TEXT="${TEXT}
|
||||
${NOTIFY_DETAIL}"
|
||||
fi
|
||||
|
||||
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(jq -n \
|
||||
--arg chat_id "$TELEGRAM_CHAT_ID" \
|
||||
--arg text "$TEXT" \
|
||||
'{chat_id: $chat_id, text: $text, parse_mode: "Markdown"}')"
|
||||
93
.github/workflows/script/re-pull.sh
vendored
Normal file
93
.github/workflows/script/re-pull.sh
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
#!/bin/bash
|
||||
|
||||
: "${PORTAINER_URL:?PORTAINER_URL tidak di-set}"
|
||||
: "${PORTAINER_USERNAME:?PORTAINER_USERNAME tidak di-set}"
|
||||
: "${PORTAINER_PASSWORD:?PORTAINER_PASSWORD tidak di-set}"
|
||||
: "${STACK_NAME:?STACK_NAME tidak di-set}"
|
||||
|
||||
echo "🔐 Autentikasi ke Portainer..."
|
||||
TOKEN=$(curl -s -X POST https://${PORTAINER_URL}/api/auth \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"username\": \"${PORTAINER_USERNAME}\", \"password\": \"${PORTAINER_PASSWORD}\"}" \
|
||||
| jq -r .jwt)
|
||||
|
||||
if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
|
||||
echo "❌ Autentikasi gagal! Cek PORTAINER_URL, USERNAME, dan PASSWORD."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🔍 Mencari stack: $STACK_NAME..."
|
||||
STACK=$(curl -s -X GET https://${PORTAINER_URL}/api/stacks \
|
||||
-H "Authorization: Bearer ${TOKEN}" \
|
||||
| jq ".[] | select(.Name == \"$STACK_NAME\")")
|
||||
|
||||
if [ -z "$STACK" ]; then
|
||||
echo "❌ Stack '$STACK_NAME' tidak ditemukan di Portainer!"
|
||||
echo " Pastikan nama stack sudah benar."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
STACK_ID=$(echo "$STACK" | jq -r .Id)
|
||||
ENDPOINT_ID=$(echo "$STACK" | jq -r .EndpointId)
|
||||
ENV=$(echo "$STACK" | jq '.Env // []')
|
||||
|
||||
echo "📄 Mengambil compose file..."
|
||||
STACK_FILE=$(curl -s -X GET "https://${PORTAINER_URL}/api/stacks/${STACK_ID}/file" \
|
||||
-H "Authorization: Bearer ${TOKEN}" \
|
||||
| jq -r .StackFileContent)
|
||||
|
||||
PAYLOAD=$(jq -n \
|
||||
--arg content "$STACK_FILE" \
|
||||
--argjson env "$ENV" \
|
||||
'{stackFileContent: $content, env: $env, pullImage: true}')
|
||||
|
||||
echo "🚀 Redeploying $STACK_NAME (pull latest image)..."
|
||||
HTTP_STATUS=$(curl -s -o /tmp/portainer_response.json -w "%{http_code}" \
|
||||
-X PUT "https://${PORTAINER_URL}/api/stacks/${STACK_ID}?endpointId=${ENDPOINT_ID}" \
|
||||
-H "Authorization: Bearer ${TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$PAYLOAD")
|
||||
|
||||
if [ "$HTTP_STATUS" != "200" ]; then
|
||||
echo "❌ Redeploy gagal! HTTP Status: $HTTP_STATUS"
|
||||
cat /tmp/portainer_response.json | jq .
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "⏳ Menunggu container running..."
|
||||
|
||||
MAX_RETRY=15
|
||||
COUNT=0
|
||||
|
||||
while [ $COUNT -lt $MAX_RETRY ]; do
|
||||
sleep 5
|
||||
COUNT=$((COUNT + 1))
|
||||
|
||||
CONTAINERS=$(curl -s -X GET \
|
||||
"https://${PORTAINER_URL}/api/endpoints/${ENDPOINT_ID}/docker/containers/json?all=true&filters=%7B%22label%22%3A%5B%22com.docker.compose.project%3D${STACK_NAME}%22%5D%7D" \
|
||||
-H "Authorization: Bearer ${TOKEN}")
|
||||
|
||||
TOTAL=$(echo "$CONTAINERS" | jq 'length')
|
||||
RUNNING=$(echo "$CONTAINERS" | jq '[.[] | select(.State == "running")] | length')
|
||||
FAILED=$(echo "$CONTAINERS" | jq '[.[] | select(.State == "exited" and (.Status | test("Exited \\(0\\)") | not))] | length')
|
||||
|
||||
echo "🔄 [${COUNT}/${MAX_RETRY}] Running: ${RUNNING} | Failed: ${FAILED} | Total: ${TOTAL}"
|
||||
echo "$CONTAINERS" | jq -r '.[] | " → \(.Names[0]) | \(.State) | \(.Status)"'
|
||||
|
||||
if [ "$FAILED" -gt "0" ]; then
|
||||
echo ""
|
||||
echo "❌ Ada container yang crash!"
|
||||
echo "$CONTAINERS" | jq -r '.[] | select(.State == "exited" and (.Status | test("Exited \\(0\\)") | not)) | " → \(.Names[0]) | \(.Status)"'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$RUNNING" -gt "0" ]; then
|
||||
echo ""
|
||||
echo "✅ Stack $STACK_NAME berhasil di-redeploy dan running!"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "❌ Timeout! Stack tidak kunjung running setelah $((MAX_RETRY * 5)) detik."
|
||||
exit 1
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -16,6 +16,7 @@ _.log
|
||||
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# dotenv environment variable files
|
||||
# Only .env.example is allowed to be committed
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
@@ -33,6 +34,9 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
|
||||
# Dashboard-MD
|
||||
Dashboard-MD
|
||||
|
||||
# Playwright artifacts
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
62
Dockerfile
Normal file
62
Dockerfile
Normal file
@@ -0,0 +1,62 @@
|
||||
# Stage 1: Build
|
||||
FROM oven/bun:1.3 AS build
|
||||
|
||||
# Install build dependencies for native modules
|
||||
RUN apt-get update && apt-get install -y \
|
||||
python3 \
|
||||
make \
|
||||
g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set the working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package.json bun.lock* ./
|
||||
|
||||
# Install dependencies
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
# Copy the rest of the application code
|
||||
COPY . .
|
||||
|
||||
# Use .env.example as default env for build
|
||||
RUN cp .env.example .env
|
||||
|
||||
# Generate Prisma client
|
||||
RUN bun x prisma generate
|
||||
|
||||
# Generate API types
|
||||
RUN bun run gen:api
|
||||
|
||||
# Build the application frontend
|
||||
RUN bun run build
|
||||
|
||||
# Stage 2: Runtime
|
||||
FROM oven/bun:1.3-slim AS runtime
|
||||
|
||||
# Set environment variables
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Install runtime dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
postgresql-client \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set the working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy necessary files from build stage
|
||||
COPY --from=build /app/package.json ./
|
||||
COPY --from=build /app/tsconfig.json ./
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY --from=build /app/generated ./generated
|
||||
COPY --from=build /app/src ./src
|
||||
COPY --from=build /app/node_modules ./node_modules
|
||||
COPY --from=build /app/prisma ./prisma
|
||||
|
||||
# Expose the port
|
||||
EXPOSE 3000
|
||||
|
||||
# Start the application
|
||||
CMD ["bun", "start"]
|
||||
@@ -184,5 +184,6 @@ export function Sidebar({ className }: SidebarProps) {
|
||||
</Box>
|
||||
</Stack>
|
||||
</Box>
|
||||
|
||||
);
|
||||
}
|
||||
|
||||
BIN
src/components/ui/logo-desa-plus.png
Normal file
BIN
src/components/ui/logo-desa-plus.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
413
src/index.ts
413
src/index.ts
@@ -12,240 +12,243 @@ const isProduction = process.env.NODE_ENV === "production";
|
||||
|
||||
// Auto-seed database in production (ensure admin user exists)
|
||||
if (isProduction && process.env.ADMIN_EMAIL) {
|
||||
try {
|
||||
console.log("🌱 Running database seed in production...");
|
||||
const { runSeed } = await import("../prisma/seed.ts");
|
||||
await runSeed();
|
||||
} catch (error) {
|
||||
console.error("⚠️ Production seed failed:", error);
|
||||
// Don't crash the server if seed fails
|
||||
}
|
||||
try {
|
||||
console.log("🌱 Running database seed in production...");
|
||||
const { runSeed } = await import("../prisma/seed.ts");
|
||||
await runSeed();
|
||||
} catch (error) {
|
||||
console.error("⚠️ Production seed failed:", error);
|
||||
// Don't crash the server if seed fails
|
||||
}
|
||||
}
|
||||
|
||||
const app = new Elysia().use(api);
|
||||
|
||||
if (!isProduction) {
|
||||
// Development: Use Vite middleware
|
||||
const { createVite } = await import("./vite");
|
||||
const vite = await createVite();
|
||||
// Development: Use Vite middleware
|
||||
const { createVite } = await import("./vite");
|
||||
const vite = await createVite();
|
||||
|
||||
// Serve PWA/TWA assets in dev (root and nested path support)
|
||||
const _servePwaAsset = (srcPath: string) => () => Bun.file(srcPath);
|
||||
// Serve PWA/TWA assets in dev (root and nested path support)
|
||||
const _servePwaAsset = (srcPath: string) => () => Bun.file(srcPath);
|
||||
|
||||
app.post("/__open-in-editor", ({ body }) => {
|
||||
const { relativePath, lineNumber, columnNumber } = body as {
|
||||
relativePath: string;
|
||||
lineNumber: number;
|
||||
columnNumber: number;
|
||||
};
|
||||
app.post("/__open-in-editor", ({ body }) => {
|
||||
const { relativePath, lineNumber, columnNumber } = body as {
|
||||
relativePath: string;
|
||||
lineNumber: number;
|
||||
columnNumber: number;
|
||||
};
|
||||
|
||||
openInEditor(relativePath, {
|
||||
line: lineNumber,
|
||||
column: columnNumber,
|
||||
editor: "antigravity",
|
||||
});
|
||||
openInEditor(relativePath, {
|
||||
line: lineNumber,
|
||||
column: columnNumber,
|
||||
editor: "antigravity",
|
||||
});
|
||||
|
||||
return { ok: true };
|
||||
});
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
// Vite middleware for other requests
|
||||
app.all("*", async ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const pathname = url.pathname;
|
||||
// Vite middleware for other requests
|
||||
app.all("*", async ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const pathname = url.pathname;
|
||||
|
||||
// Serve transformed index.html for root or any path that should be handled by the SPA
|
||||
if (
|
||||
pathname === "/" ||
|
||||
(!pathname.includes(".") &&
|
||||
!pathname.startsWith("/@") &&
|
||||
!pathname.startsWith("/inspector") &&
|
||||
!pathname.startsWith("/__open-stack-frame-in-editor") &&
|
||||
!pathname.startsWith("/api"))
|
||||
) {
|
||||
try {
|
||||
const htmlPath = path.resolve("src/index.html");
|
||||
let html = fs.readFileSync(htmlPath, "utf-8");
|
||||
html = await vite.transformIndexHtml(pathname, html);
|
||||
// Serve transformed index.html for root or any path that should be handled by the SPA
|
||||
if (
|
||||
pathname === "/" ||
|
||||
(!pathname.includes(".") &&
|
||||
!pathname.startsWith("/@") &&
|
||||
!pathname.startsWith("/inspector") &&
|
||||
!pathname.startsWith("/__open-stack-frame-in-editor") &&
|
||||
!pathname.startsWith("/api"))
|
||||
) {
|
||||
try {
|
||||
const htmlPath = path.resolve("src/index.html");
|
||||
let html = fs.readFileSync(htmlPath, "utf-8");
|
||||
html = await vite.transformIndexHtml(pathname, html);
|
||||
|
||||
return new Response(html, {
|
||||
headers: { "Content-Type": "text/html" },
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
return new Response(html, {
|
||||
headers: { "Content-Type": "text/html" },
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
return new Promise<Response>((resolve) => {
|
||||
// Use a Proxy to mock Node.js req because Bun's Request is read-only
|
||||
const req = new Proxy(request, {
|
||||
get(target, prop) {
|
||||
if (prop === "url") return pathname + url.search;
|
||||
if (prop === "method") return request.method;
|
||||
if (prop === "headers")
|
||||
return Object.fromEntries(request.headers as any);
|
||||
return (target as any)[prop];
|
||||
},
|
||||
}) as any;
|
||||
return new Promise<Response>((resolve) => {
|
||||
// Use a Proxy to mock Node.js req because Bun's Request is read-only
|
||||
const req = new Proxy(request, {
|
||||
get(target, prop) {
|
||||
if (prop === "url") return pathname + url.search;
|
||||
if (prop === "method") return request.method;
|
||||
if (prop === "headers")
|
||||
return Object.fromEntries(request.headers as any);
|
||||
return (target as any)[prop];
|
||||
},
|
||||
}) as any;
|
||||
|
||||
const res = {
|
||||
statusCode: 200,
|
||||
setHeader(name: string, value: string) {
|
||||
this.headers[name.toLowerCase()] = value;
|
||||
},
|
||||
getHeader(name: string) {
|
||||
return this.headers[name.toLowerCase()];
|
||||
},
|
||||
writeHead(code: number, headers: Record<string, string>) {
|
||||
this.statusCode = code;
|
||||
Object.assign(this.headers, headers);
|
||||
},
|
||||
write(chunk: any, callback?: () => void) {
|
||||
// Collect chunks for streaming responses
|
||||
if (!this._chunks) this._chunks = [];
|
||||
this._chunks.push(chunk);
|
||||
if (callback) callback();
|
||||
return true; // Indicate we can accept more data
|
||||
},
|
||||
headers: {} as Record<string, string>,
|
||||
end(data: any) {
|
||||
// Handle potential Buffer or string data from Vite
|
||||
let body = data;
|
||||
// If we have collected chunks from write() calls, combine them
|
||||
if (this._chunks && this._chunks.length > 0) {
|
||||
body = Buffer.concat(this._chunks);
|
||||
}
|
||||
if (data instanceof Uint8Array) {
|
||||
body = data;
|
||||
} else if (typeof data === "string") {
|
||||
body = data;
|
||||
} else if (data) {
|
||||
body = String(data);
|
||||
}
|
||||
const res = {
|
||||
statusCode: 200,
|
||||
setHeader(name: string, value: string) {
|
||||
this.headers[name.toLowerCase()] = value;
|
||||
},
|
||||
getHeader(name: string) {
|
||||
return this.headers[name.toLowerCase()];
|
||||
},
|
||||
writeHead(code: number, headers: Record<string, string>) {
|
||||
this.statusCode = code;
|
||||
Object.assign(this.headers, headers);
|
||||
},
|
||||
write(chunk: any, callback?: () => void) {
|
||||
// Collect chunks for streaming responses
|
||||
if (!this._chunks) this._chunks = [];
|
||||
this._chunks.push(chunk);
|
||||
if (callback) callback();
|
||||
return true; // Indicate we can accept more data
|
||||
},
|
||||
headers: {} as Record<string, string>,
|
||||
end(data: any) {
|
||||
// Handle potential Buffer or string data from Vite
|
||||
let body = data;
|
||||
|
||||
// If we have collected chunks from write() calls, combine them
|
||||
if (this._chunks && this._chunks.length > 0) {
|
||||
body = Buffer.concat(this._chunks);
|
||||
}
|
||||
|
||||
if (data instanceof Uint8Array) {
|
||||
body = data;
|
||||
} else if (typeof data === "string") {
|
||||
body = data;
|
||||
} else if (data) {
|
||||
body = String(data);
|
||||
}
|
||||
|
||||
resolve(
|
||||
new Response(body || "", {
|
||||
status: this.statusCode,
|
||||
headers: this.headers,
|
||||
}),
|
||||
);
|
||||
},
|
||||
// Minimal event emitter mock
|
||||
once() {
|
||||
return this;
|
||||
},
|
||||
on() {
|
||||
return this;
|
||||
},
|
||||
emit() {
|
||||
return this;
|
||||
},
|
||||
removeListener() {
|
||||
return this;
|
||||
},
|
||||
} as any;
|
||||
resolve(
|
||||
new Response(body || "", {
|
||||
status: this.statusCode,
|
||||
headers: this.headers,
|
||||
}),
|
||||
);
|
||||
},
|
||||
// Minimal event emitter mock
|
||||
once() {
|
||||
return this;
|
||||
},
|
||||
on() {
|
||||
return this;
|
||||
},
|
||||
emit() {
|
||||
return this;
|
||||
},
|
||||
removeListener() {
|
||||
return this;
|
||||
},
|
||||
} as any;
|
||||
|
||||
vite.middlewares(req, res, (err: any) => {
|
||||
if (err) {
|
||||
console.error("Vite middleware error:", err);
|
||||
resolve(new Response(err.stack || err.toString(), { status: 500 }));
|
||||
return;
|
||||
}
|
||||
// If Vite doesn't handle it, return 404
|
||||
resolve(new Response("Not Found", { status: 404 }));
|
||||
});
|
||||
});
|
||||
});
|
||||
vite.middlewares(req, res, (err: any) => {
|
||||
if (err) {
|
||||
console.error("Vite middleware error:", err);
|
||||
resolve(new Response(err.stack || err.toString(), { status: 500 }));
|
||||
return;
|
||||
}
|
||||
// If Vite doesn't handle it, return 404
|
||||
resolve(new Response("Not Found", { status: 404 }));
|
||||
});
|
||||
});
|
||||
});
|
||||
} else {
|
||||
// Production: Final catch-all for static files and SPA fallback
|
||||
app.all("*", async ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const pathname = url.pathname;
|
||||
// Production: Final catch-all for static files and SPA fallback
|
||||
app.all("*", async ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const pathname = url.pathname;
|
||||
|
||||
// 1. Try exact match in dist
|
||||
let filePath = path.join(
|
||||
"dist",
|
||||
pathname === "/" ? "index.html" : pathname,
|
||||
);
|
||||
// 1. Try exact match in dist
|
||||
let filePath = path.join(
|
||||
"dist",
|
||||
pathname === "/" ? "index.html" : pathname,
|
||||
);
|
||||
|
||||
// 1.1 Special handling for PWA/TWA assets that might not be in dist (since we use custom bun build)
|
||||
if (isProduction) {
|
||||
const srcPath = path.join("src", pathname);
|
||||
if (fs.existsSync(srcPath)) {
|
||||
filePath = srcPath;
|
||||
}
|
||||
// Check public folder for static assets
|
||||
const publicPath = path.join("public", pathname);
|
||||
if (fs.existsSync(publicPath)) {
|
||||
filePath = publicPath;
|
||||
}
|
||||
}
|
||||
// 1.1 Special handling for PWA/TWA assets that might not be in dist (since we use custom bun build)
|
||||
if (isProduction) {
|
||||
const srcPath = path.join("src", pathname);
|
||||
if (fs.existsSync(srcPath)) {
|
||||
filePath = srcPath;
|
||||
}
|
||||
// Check public folder for static assets
|
||||
const publicPath = path.join("public", pathname);
|
||||
if (fs.existsSync(publicPath)) {
|
||||
filePath = publicPath;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. If not found and looks like an asset (has extension), try root of dist or src
|
||||
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
|
||||
if (pathname.includes(".") && !pathname.endsWith("/")) {
|
||||
const filename = path.basename(pathname);
|
||||
// 2. If not found and looks like an asset (has extension), try root of dist or src
|
||||
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
|
||||
if (pathname.includes(".") && !pathname.endsWith("/")) {
|
||||
const filename = path.basename(pathname);
|
||||
|
||||
// Try root of dist
|
||||
const fallbackDistPath = path.join("dist", filename);
|
||||
if (
|
||||
fs.existsSync(fallbackDistPath) &&
|
||||
fs.statSync(fallbackDistPath).isFile()
|
||||
) {
|
||||
filePath = fallbackDistPath;
|
||||
}
|
||||
// Try public folder
|
||||
else {
|
||||
const fallbackPublicPath = path.join("public", filename);
|
||||
if (
|
||||
fs.existsSync(fallbackPublicPath) &&
|
||||
fs.statSync(fallbackPublicPath).isFile()
|
||||
) {
|
||||
filePath = fallbackPublicPath;
|
||||
}
|
||||
}
|
||||
// Special handling for PWA files in src
|
||||
if (pathname.includes("assetlinks.json")) {
|
||||
const srcFilename = pathname.includes("assetlinks.json")
|
||||
? ".well-known/assetlinks.json"
|
||||
: filename;
|
||||
const fallbackSrcPath = path.join("src", srcFilename);
|
||||
if (
|
||||
fs.existsSync(fallbackSrcPath) &&
|
||||
fs.statSync(fallbackSrcPath).isFile()
|
||||
) {
|
||||
filePath = fallbackSrcPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Try root of dist
|
||||
const fallbackDistPath = path.join("dist", filename);
|
||||
if (
|
||||
fs.existsSync(fallbackDistPath) &&
|
||||
fs.statSync(fallbackDistPath).isFile()
|
||||
) {
|
||||
filePath = fallbackDistPath;
|
||||
}
|
||||
// Try public folder
|
||||
else {
|
||||
const fallbackPublicPath = path.join("public", filename);
|
||||
if (
|
||||
fs.existsSync(fallbackPublicPath) &&
|
||||
fs.statSync(fallbackPublicPath).isFile()
|
||||
) {
|
||||
filePath = fallbackPublicPath;
|
||||
}
|
||||
}
|
||||
// Special handling for PWA files in src
|
||||
if (pathname.includes("assetlinks.json")) {
|
||||
const srcFilename = pathname.includes("assetlinks.json")
|
||||
? ".well-known/assetlinks.json"
|
||||
: filename;
|
||||
const fallbackSrcPath = path.join("src", srcFilename);
|
||||
if (
|
||||
fs.existsSync(fallbackSrcPath) &&
|
||||
fs.statSync(fallbackSrcPath).isFile()
|
||||
) {
|
||||
filePath = fallbackSrcPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
||||
const file = Bun.file(filePath);
|
||||
return new Response(file, {
|
||||
headers: {
|
||||
Vary: "Accept-Encoding",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
||||
const file = Bun.file(filePath);
|
||||
return new Response(file, {
|
||||
headers: {
|
||||
Vary: "Accept-Encoding",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 3. SPA Fallback: Serve index.html
|
||||
const indexHtml = path.join("dist", "index.html");
|
||||
if (fs.existsSync(indexHtml)) {
|
||||
return new Response(Bun.file(indexHtml), {
|
||||
headers: {
|
||||
Vary: "Accept-Encoding",
|
||||
},
|
||||
});
|
||||
}
|
||||
// 3. SPA Fallback: Serve index.html
|
||||
const indexHtml = path.join("dist", "index.html");
|
||||
if (fs.existsSync(indexHtml)) {
|
||||
return new Response(Bun.file(indexHtml), {
|
||||
headers: {
|
||||
Vary: "Accept-Encoding",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return new Response("Not Found", { status: 404 });
|
||||
});
|
||||
return new Response("Not Found", { status: 404 });
|
||||
});
|
||||
}
|
||||
|
||||
app.listen(PORT);
|
||||
|
||||
console.log(
|
||||
`🚀 Server running at http://localhost:${PORT} in ${isProduction ? "production" : "development"} mode`,
|
||||
`🚀 Server running at http://localhost:${PORT} in ${isProduction ? "production" : "development"} mode`,
|
||||
);
|
||||
|
||||
export type ApiApp = typeof app;
|
||||
|
||||
|
||||
@@ -68,18 +68,8 @@ const routeRules: RouteRule[] = [
|
||||
{
|
||||
match: (p) => p === "/dashboard" || p.startsWith("/dashboard/"),
|
||||
requireAuth: true,
|
||||
redirectTo: "/signin",
|
||||
},
|
||||
{
|
||||
match: (p) => p === "/admin" || p.startsWith("/admin/"),
|
||||
requireAuth: true,
|
||||
requiredRole: "admin",
|
||||
redirectTo: "/dashboard",
|
||||
},
|
||||
{
|
||||
match: (p) => p === "/" || p === "",
|
||||
requireAuth: false,
|
||||
redirectTo: "/dashboard",
|
||||
redirectTo: "/profile",
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -32,29 +32,11 @@ import {
|
||||
IconStack2,
|
||||
IconSun,
|
||||
} from "@tabler/icons-react";
|
||||
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
|
||||
import { createFileRoute, Link } from "@tanstack/react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSnapshot } from "valtio";
|
||||
import { authStore } from "@/store/auth";
|
||||
|
||||
export const Route = createFileRoute("/")({
|
||||
component: HomePage,
|
||||
beforeLoad: async () => {
|
||||
// Check if user is already logged in
|
||||
const session = await fetch("/api/session", {
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
}).then((res) => (res.ok ? res.json() : null));
|
||||
|
||||
// If user is logged in, redirect to dashboard
|
||||
if (session?.data?.user) {
|
||||
throw {
|
||||
redirect: {
|
||||
to: "/dashboard",
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Navigation items
|
||||
|
||||
Reference in New Issue
Block a user