Compare commits

...
5 Commits
Author SHA1 Message Date
Gabriel Brown 2356383da1 CI: run on the VPS runner (plain shell instead of checkout/setup-bun actions)
Build and Push Next App / quality (push) Successful in 2m5s
Build and Push Next App / build-next (push) Canceled after 10s
Rootless podman on cirunner-vps cannot copy cached actions into job
containers (symlinks: "path escapes from parent"), so any job that
landed there failed. Checkout is now plain git and Bun comes from its
install script; both are verified on cirunner-vps.
2026-10-02 04:36:50 -04:00
Gabriel Brown 55929d8c7f Fix avatar crash when users.image is an IdP URL
Build and Push Next App / quality (push) Successful in 1m19s
Build and Push Next App / build-next (push) Successful in 2m35s
Authentik sign-ins write the picture claim URL to users.image, and both avatar components cast that value to a storage ID and passed it to files:getImageUrl, which failed argument validation and took the layout down after sign-in. getUser now returns imageUrl resolved from either a storage ID or a URL, and updateUser only deletes the previous avatar when it was an uploaded file. getImageUrl stays until the new Next image is live.
2026-10-01 15:01:51 -04:00
Gabriel Brown 8f09a423d4 Read CI env from Infisical and give the local stack its own ports
Build and Push Next App / quality (push) Successful in 1m12s
Build and Push Next App / build-next (push) Successful in 2m20s
CI reads Infisical staging as the read-only convexmonorepo-base-ci machine identity, runs the quality gate, and builds and pushes the image. The template is not deployed, so there is no Convex or VPS deploy step. The local stack moves to its own Compose name and ports so it runs beside the Payload template's, and it syncs the Convex runtime env. The scripts pick up Infisical account switching, dev-kill and a cache-safe CI install.
2026-10-01 14:55:35 -04:00
Gabriel Brown 55b253257b Add PostHog, move Plausible to v4, and drop Sentry session replay
PostHog loads after the page is idle through a same-origin /ingest proxy and follows the signed-in Convex user. Plausible uses the per-site script through a /pa proxy. Sentry keeps errors and traces only. Pages load only the @gib/ui modules they import, and client code reads public env from publicEnv.ts so zod stays out of the browser.
2026-10-01 14:55:11 -04:00
Gabriel Brown 818b41fb21 Update dependencies and fix what the new lint rules caught
Every package moves to its newest in-major version, plus React 19.3, @convex-dev/auth 0.0.96 and next-plausible 4. The backend declares @auth/core and generates sign-in codes without oslo, which @convex-dev/auth no longer pulls in. The UseSend patch now actually removes the crypto import Convex refuses to bundle. The stricter react-hooks and typescript-eslint rules flagged the carousel, chart, image crop and mobile hook, which now pass.
2026-10-01 14:54:53 -04:00
52 changed files with 1460 additions and 1424 deletions

No files matched your search

+70 -18
View File
@@ -2,55 +2,107 @@ name: Build and Push Next App
on: on:
push: push:
branches: [main] branches:
- main
paths: paths:
- 'apps/**' - 'apps/next/**'
- 'packages/**' - 'packages/**'
- 'tools/**' - 'tools/**'
- 'scripts/**' - 'scripts/**'
- 'docker/**' - 'docker/**'
- '.gitea/workflows/build-next.yml' - '.gitea/workflows/build-next.yml'
- '.infisical.json'
- 'package.json' - 'package.json'
- 'bun.lock' - 'bun.lock'
- 'turbo.json' - 'turbo.json'
# One image build at a time; a newer push waits rather than racing.
concurrency:
group: build-next
cancel-in-progress: false
# This template is not deployed. CI runs the quality gate and builds and pushes
# the image so the template stays known-good. Env comes from the Infisical
# `staging` environment: each job logs in as the read-only
# `convexmonorepo-base-ci` machine identity and writes it to a temp file
# (scripts/ci-export-env.mjs), so no values live in Gitea.
jobs: jobs:
# Quality gate: workspace lint (sherif), eslint, typecheck and the unit,
# integration and component suites must pass before anything touches
# production. The local-stack e2e smoke check is skipped in CI.
quality: quality:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - name: Checkout repository
- uses: oven-sh/setup-bun@v2 # Plain git instead of actions/checkout: rootless podman on cirunner-vps
with: # rejects symlinks inside cached actions ("path escapes from parent").
bun-version: 1.3.10
- run: bun install --frozen-lockfile
- name: Lint, typecheck, and test
env: env:
DOTENV_PROD: ${{ secrets.DOTENV_PROD }} GITEA_TOKEN: ${{ gitea.token }}
run: |
git init -q .
git remote add origin "${{ gitea.server_url }}/${{ gitea.repository }}.git"
auth="$(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)"
git -c http.extraHeader="Authorization: basic $auth" \
fetch -q --depth 1 origin "${{ gitea.sha }}"
git checkout -q FETCH_HEAD
- name: Set up Bun
# Install script instead of oven-sh/setup-bun (same podman symlink issue).
run: |
curl -fsSL https://bun.sh/install | bash -s "bun-v1.3.14" >/dev/null
echo "$HOME/.bun/bin" >> "$GITHUB_PATH"
- name: Install dependencies
run: ./scripts/ci-install
- name: Lint and typecheck
env:
INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_CLIENT_ID }}
INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_CLIENT_SECRET }}
run: | run: |
env_file="$(mktemp)" env_file="$(mktemp)"
trap 'rm -f "$env_file"' EXIT trap 'rm -f "$env_file"' EXIT
printf '%s\n' "$DOTENV_PROD" > "$env_file" node scripts/ci-export-env.mjs staging > "$env_file"
bunx dotenv -e "$env_file" -- env NODE_ENV=test SKIP_E2E=1 bun run ci:check bunx dotenv -e "$env_file" -- env NODE_ENV=test SKIP_E2E=1 bun run ci:check
build-next: build-next:
needs: [quality] needs: [quality]
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - name: Checkout repository
- name: Log in to container registry # Plain git instead of actions/checkout: rootless podman on cirunner-vps
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.gbrown.org -u "${{ secrets.REGISTRY_USER }}" --password-stdin # rejects symlinks inside cached actions ("path escapes from parent").
- name: Build image
env: env:
DOTENV_PROD: ${{ secrets.DOTENV_PROD }} GITEA_TOKEN: ${{ gitea.token }}
run: |
git init -q .
git remote add origin "${{ gitea.server_url }}/${{ gitea.repository }}.git"
auth="$(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)"
git -c http.extraHeader="Authorization: basic $auth" \
fetch -q --depth 1 origin "${{ gitea.sha }}"
git checkout -q FETCH_HEAD
- name: Log in to container registry
run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.gbrown.org -u "${{ secrets.REGISTRY_USER }}" --password-stdin
- name: Build app using project script
env:
INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_CLIENT_ID }}
INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_CLIENT_SECRET }}
run: | run: |
env_file="$(mktemp)" env_file="$(mktemp)"
trap 'rm -f "$env_file"' EXIT trap 'rm -f "$env_file"' EXIT
printf '%s\n' "$DOTENV_PROD" > "$env_file" node scripts/ci-export-env.mjs staging > "$env_file"
CI_ENV_FILE="$env_file" ./scripts/build-next-app staging CI_ENV_FILE="$env_file" ./scripts/build-next-app staging
- name: Tag and push image
- name: Tag built image
run: | run: |
docker tag convexmonorepo-no-payload-next:latest git.gbrown.org/gib/convexmonorepo-no-payload-next:${{ gitea.sha }} docker tag convexmonorepo-no-payload-next:latest git.gbrown.org/gib/convexmonorepo-no-payload-next:${{ gitea.sha }}
docker tag convexmonorepo-no-payload-next:latest git.gbrown.org/gib/convexmonorepo-no-payload-next:latest docker tag convexmonorepo-no-payload-next:latest git.gbrown.org/gib/convexmonorepo-no-payload-next:latest
- name: Push image tags
run: |
docker push git.gbrown.org/gib/convexmonorepo-no-payload-next:${{ gitea.sha }} docker push git.gbrown.org/gib/convexmonorepo-no-payload-next:${{ gitea.sha }}
docker push git.gbrown.org/gib/convexmonorepo-no-payload-next:latest docker push git.gbrown.org/gib/convexmonorepo-no-payload-next:latest
+3
View File
@@ -66,3 +66,6 @@ apps/next/playwright-report/
# tanstack # tanstack
.tanstack .tanstack
# local command flags (machine-specific, e.g. which Infisical account to use)
scripts/flags/
+3 -2
View File
@@ -1,5 +1,6 @@
{ {
"workspaceId": "b2760150-c581-4e0d-acb5-b4da51cee58d", "workspaceId": "93d78472-e1a0-4faf-8874-e57aa030a06f",
"defaultEnvironment": "", "defaultEnvironment": "",
"gitBranchToEnvironmentMapping": null "gitBranchToEnvironmentMapping": null,
"domain": "https://infisical.gbrown.org/api"
} }
+30 -5
View File
@@ -7,7 +7,7 @@
- `packages/backend/convex`: self-hosted Convex functions, schema, and auth. - `packages/backend/convex`: self-hosted Convex functions, schema, and auth.
- `packages/ui`: shared shadcn-based UI components. - `packages/ui`: shared shadcn-based UI components.
- `tools`: shared ESLint, Prettier, Tailwind, TypeScript, and Vitest config. - `tools`: shared ESLint, Prettier, Tailwind, TypeScript, and Vitest config.
- Local development uses host-run apps, local Convex on ports 3210/3211, and - Local development uses host-run apps, local Convex on ports 3250/3251, and
its own data volume. Convex does not use Postgres unless a cloned project its own data volume. Convex does not use Postgres unless a cloned project
explicitly enables the commented optional `POSTGRES_URL` example. explicitly enables the commented optional `POSTGRES_URL` example.
@@ -27,8 +27,18 @@
- Run `infisical login` and `infisical init` before local development. - Run `infisical login` and `infisical init` before local development.
- Machine-generated values belong in `.local/<env>.generated.env`; never put - Machine-generated values belong in `.local/<env>.generated.env`; never put
the generated Convex admin key in shared Infisical. the generated Convex admin key in shared Infisical.
- CI uses Gitea-injected secrets or `CI_ENV_FILE` and must not call Infisical. - CI reads `staging` through `scripts/ci-export-env.mjs`, logged in as the
- App code imports validated variables from `@/env`, never `process.env`. read-only `convexmonorepo-base-ci` machine identity (Gitea secrets
`INFISICAL_CLIENT_ID` and `INFISICAL_CLIENT_SECRET`). `scripts/export-env`
refuses to run in CI.
- This template's `staging` has no Convex admin key, so nothing here can deploy
to a real backend. A cloned app gets its own Infisical project.
- If you are logged in to more than one Infisical account, put
`INFISICAL_EMAIL=...` in `scripts/flags/infisical.env` (gitignored) and the
scripts switch the CLI to that account before exporting.
- Server code imports validated variables from `@/env`. Client components and
`instrumentation-client.ts` import from `@/publicEnv`, which keeps zod out of
the browser bundle. Never read `process.env` elsewhere.
- Add cache-relevant variables to `turbo.json` `globalEnv`. - Add cache-relevant variables to `turbo.json` `globalEnv`.
## Code and dependency rules ## Code and dependency rules
@@ -50,13 +60,28 @@ bun db:up # start Convex and dashboard
bun dev:next # host Next + deploy/watch local Convex functions bun dev:next # host Next + deploy/watch local Convex functions
bun db:down # stop and preserve Convex data bun db:down # stop and preserve Convex data
bun db:down:wipe # remove Convex volume and generated admin key bun db:down:wipe # remove Convex volume and generated admin key
bun db:sync-env # re-push Infisical dev values into the local Convex env
bun dev:kill # stop dev servers that survived a Ctrl-C
``` ```
Local URLs: app `http://localhost:3000`, Convex `http://localhost:3210`, Local URLs: app `http://localhost:3000`, Convex `http://localhost:3250`,
dashboard `http://localhost:6791`. dashboard `http://localhost:6795`. The Compose project and containers are named
`convexmonorepo-base-local*` so this stack can run beside the Payload template's.
Use `INFISICAL_ENV=staging bun dev:next` for staging services. Normal `db:up` Use `INFISICAL_ENV=staging bun dev:next` for staging services. Normal `db:up`
never connects to staging and does not start Postgres. never connects to staging and does not start Postgres.
## Analytics and bundle size
- Plausible (`NEXT_PUBLIC_PLAUSIBLE_SRC`, the per-site script URL) loads through
a same-origin proxy under `/pa`. PostHog (`NEXT_PUBLIC_POSTHOG_KEY`,
`NEXT_PUBLIC_POSTHOG_HOST`) loads after the page is idle through `/ingest`.
Both stay off when their env is unset.
- Session replay comes from PostHog. Sentry carries errors and traces only.
- `packages/ui/src/index.tsx` holds re-exports only (`cn` and `ccn` live in
`utils.ts`). With `optimizePackageImports` in `next.config.js`, each page
loads only the UI modules it imports. Declaring anything in the index breaks
that.
## Validation ## Validation
Use `bun typecheck`, never a production build for routine validation. The full Use `bun typecheck`, never a production build for routine validation. The full
+14 -6
View File
@@ -5,7 +5,8 @@ shared UI/config packages, Vitest, and Docker deployment.
## Local setup ## Local setup
Requirements: Bun 1.3.10, Docker or Podman, Node 22, and the Infisical CLI. Requirements: Bun 1.3.14, Docker or Podman, Node 22, the Infisical CLI, `jq`, and
`flock`.
```sh ```sh
bun install --frozen-lockfile bun install --frozen-lockfile
@@ -22,8 +23,8 @@ files. Select staging with `INFISICAL_ENV=staging bun dev:next`.
Local services: Local services:
- Next.js: `http://localhost:3000` - Next.js: `http://localhost:3000`
- Convex API: `http://localhost:3210` - Convex API: `http://localhost:3250`
- Convex dashboard: `http://localhost:6791` - Convex dashboard: `http://localhost:6795`
Next and Expo run on the host. Convex uses a self-hosted data volume and does Next and Expo run on the host. Convex uses a self-hosted data volume and does
not use Postgres by default. The commented `POSTGRES_URL` in Compose is an not use Postgres by default. The commented `POSTGRES_URL` in Compose is an
@@ -46,7 +47,8 @@ Convex URL with the development host's LAN address when testing Expo on-device.
- Local `dev` and `staging`: Infisical. - Local `dev` and `staging`: Infisical.
- Generated local state: `.local/<environment>.generated.env`. - Generated local state: `.local/<environment>.generated.env`.
- CI/CD: Gitea `DOTENV_PROD`, materialized only as a temporary runner file. - CI/CD: Infisical `staging`, read by the read-only `convexmonorepo-base-ci`
machine identity and materialized only as a temporary runner file.
- Docker compilation: explicit Compose build args; `.env*` stays outside the - Docker compilation: explicit Compose build args; `.env*` stays outside the
image context. image context.
@@ -81,5 +83,11 @@ Shared dependency versions belong in root catalogs. Edit the root catalog, run
Production Compose retains the self-hosted Convex backend/dashboard and has no Production Compose retains the self-hosted Convex backend/dashboard and has no
Postgres service by default. A commented `POSTGRES_URL` remains only as an Postgres service by default. A commented `POSTGRES_URL` remains only as an
optional Convex-on-Postgres example for cloned projects. Gitea runs the quality optional Convex-on-Postgres example for cloned projects. Gitea runs the quality
gate first, builds the Next image from a temporary Gitea-secret env file, then gate first, then builds the Next image and pushes SHA and `latest` tags. Each
pushes SHA and `latest` tags. CI never installs or invokes Infisical. job reads Infisical `staging` through `scripts/ci-export-env.mjs` as the
`convexmonorepo-base-ci` machine identity (Gitea secrets `INFISICAL_CLIENT_ID`
and `INFISICAL_CLIENT_SECRET`).
The template itself is not deployed. A cloned app that is adds a `convex-deploy`
job and the VPS deploy step from an app that already has them (StPeteIT,
LashAddict, bill-tracker), plus its own Infisical project and machine identity.
+11 -11
View File
@@ -20,26 +20,26 @@
"@expo/vector-icons": "^15.1.1", "@expo/vector-icons": "^15.1.1",
"@gib/backend": "workspace:*", "@gib/backend": "workspace:*",
"@legendapp/list": "^2.0.19", "@legendapp/list": "^2.0.19",
"@react-navigation/bottom-tabs": "^7.15.8", "@react-navigation/bottom-tabs": "^7.20.0",
"@react-navigation/elements": "^2.9.13", "@react-navigation/elements": "^2.9.44",
"@react-navigation/native": "^7.2.1", "@react-navigation/native": "^7.5.0",
"@sentry/react-native": "^7.13.0", "@sentry/react-native": "^7.13.0",
"convex": "catalog:convex", "convex": "catalog:convex",
"expo": "~54.0.33", "expo": "~54.0.37",
"expo-apple-authentication": "~8.0.8", "expo-apple-authentication": "~8.0.8",
"expo-constants": "~18.0.13", "expo-constants": "~18.0.14",
"expo-dev-client": "~6.0.20", "expo-dev-client": "~6.0.21",
"expo-font": "~14.0.11", "expo-font": "~14.0.12",
"expo-haptics": "~15.0.8", "expo-haptics": "~15.0.8",
"expo-image": "~3.0.11", "expo-image": "~3.0.11",
"expo-linking": "~8.0.11", "expo-linking": "~8.0.12",
"expo-router": "~6.0.23", "expo-router": "~6.0.24",
"expo-secure-store": "~15.0.8", "expo-secure-store": "~15.0.8",
"expo-splash-screen": "~31.0.13", "expo-splash-screen": "~31.0.13",
"expo-status-bar": "~3.0.9", "expo-status-bar": "~3.0.9",
"expo-symbols": "~1.0.8", "expo-symbols": "~1.0.8",
"expo-system-ui": "~6.0.9", "expo-system-ui": "~6.0.9",
"expo-web-browser": "~15.0.10", "expo-web-browser": "~15.0.11",
"nativewind": "5.0.0-preview.2", "nativewind": "5.0.0-preview.2",
"react": "catalog:react19", "react": "catalog:react19",
"react-dom": "catalog:react19", "react-dom": "catalog:react19",
@@ -49,7 +49,7 @@
"react-native-reanimated": "~4.1.7", "react-native-reanimated": "~4.1.7",
"react-native-safe-area-context": "~5.6.2", "react-native-safe-area-context": "~5.6.2",
"react-native-screens": "~4.16.0", "react-native-screens": "~4.16.0",
"react-native-web": "~0.21.2", "react-native-web": "~0.21.3",
"react-native-worklets": "~0.5.2" "react-native-worklets": "~0.5.2"
}, },
"devDependencies": { "devDependencies": {
+1
View File
@@ -3,6 +3,7 @@
"compilerOptions": { "compilerOptions": {
"jsx": "react-native", "jsx": "react-native",
"checkJs": false, "checkJs": false,
"types": ["node"],
"moduleSuffixes": [".ios", ".android", ".native", ""], "moduleSuffixes": [".ios", ".android", ".native", ""],
"paths": { "paths": {
"~/*": ["./src/*"] "~/*": ["./src/*"]
+52 -5
View File
@@ -3,12 +3,16 @@ import { createJiti } from 'jiti';
import { withPlausibleProxy } from 'next-plausible'; import { withPlausibleProxy } from 'next-plausible';
const jiti = createJiti(import.meta.url); const jiti = createJiti(import.meta.url);
await jiti.import('./src/env'); const { env } = /** @type {typeof import('./src/env')} */ (
await jiti.import('./src/env')
);
const { posthogScriptAliases } =
/** @type {typeof import('./src/lib/posthog-scripts')} */ (
await jiti.import('./src/lib/posthog-scripts')
);
/** @type {import("next").NextConfig} */ /** @type {import("next").NextConfig} */
const config = withPlausibleProxy({ const baseConfig = {
customDomain: process.env.NEXT_PUBLIC_PLAUSIBLE_URL,
})({
output: 'standalone', output: 'standalone',
images: { images: {
remotePatterns: [ remotePatterns: [
@@ -23,11 +27,54 @@ const config = withPlausibleProxy({
serverActions: { serverActions: {
bodySizeLimit: '10mb', bodySizeLimit: '10mb',
}, },
// Resolves `import { Button } from '@gib/ui'` to the button module alone,
// so marketing pages never pull in admin-only Radix widgets or Recharts.
// radix-ui is the umbrella package the shadcn components import from.
// lucide-react, date-fns and @tabler/icons-react are on Next's default list.
optimizePackageImports: ['@gib/ui', 'radix-ui'],
}, },
/** Enables hot reloading for local packages without a build step */ /** Enables hot reloading for local packages without a build step */
transpilePackages: ['@gib/backend', '@gib/ui'], transpilePackages: ['@gib/backend', '@gib/ui'],
typescript: { ignoreBuildErrors: true }, typescript: { ignoreBuildErrors: true },
}); // PostHog's capture paths end in a slash (/e/, /i/v0/e/), and Next's
// built-in trailing-slash redirect would answer those proxied POSTs with a
// redirect. It is turned off here and replaced by the redirect below, which
// strips trailing slashes everywhere except /ingest.
skipTrailingSlashRedirect: true,
redirects: async () => [
{
source: '/:path((?!ingest(?:/|$)).+)/',
destination: '/:path',
permanent: true,
},
],
// Same-origin proxy for PostHog, so blocklists that match the PostHog host
// never see the request. The aliased extension scripts (blocked by file
// name, see src/lib/posthog-scripts.ts) map back to their real files first.
rewrites: async () => {
const host = env.NEXT_PUBLIC_POSTHOG_HOST;
if (!host) return [];
return [
...Object.entries(posthogScriptAliases).map(([name, alias]) => ({
source: `/ingest/static/${alias}.js`,
destination: `${host}/static/${name}.js`,
})),
{ source: '/ingest/:path*', destination: `${host}/:path*` },
];
},
};
// Serves Plausible's per-site script from this origin so ad blockers see a
// first-party request. next-plausible 4 takes the full script URL. Its default
// event path is /api/event, which sits inside Payload's /api routes, so both
// paths move under /pa.
const config = env.NEXT_PUBLIC_PLAUSIBLE_SRC
? withPlausibleProxy({
src: env.NEXT_PUBLIC_PLAUSIBLE_SRC,
scriptPath: '/pa/script.js',
apiPath: '/pa/event',
})(baseConfig)
: baseConfig;
const sentryConfig = { const sentryConfig = {
// For all available options, see: // For all available options, see:
+6 -5
View File
@@ -23,15 +23,16 @@
"@convex-dev/auth": "catalog:convex", "@convex-dev/auth": "catalog:convex",
"@gib/backend": "workspace:*", "@gib/backend": "workspace:*",
"@gib/ui": "workspace:*", "@gib/ui": "workspace:*",
"@sentry/nextjs": "^10.46.0", "@sentry/nextjs": "^10.75.3",
"@t3-oss/env-nextjs": "^0.13.11", "@t3-oss/env-nextjs": "^0.13.11",
"convex": "catalog:convex", "convex": "catalog:convex",
"next": "^16.2.1", "next": "^16.3.8",
"next-plausible": "^3.12.5", "next-plausible": "^4.0.0",
"posthog-js": "^1.435.6",
"react": "catalog:react19", "react": "catalog:react19",
"react-dom": "catalog:react19", "react-dom": "catalog:react19",
"require-in-the-middle": "^7.5.2", "require-in-the-middle": "^7.5.2",
"superjson": "2.2.3", "superjson": "2.2.6",
"zod": "catalog:" "zod": "catalog:"
}, },
"devDependencies": { "devDependencies": {
@@ -44,7 +45,7 @@
"@types/node": "catalog:", "@types/node": "catalog:",
"@types/react": "catalog:react19", "@types/react": "catalog:react19",
"@types/react-dom": "catalog:react19", "@types/react-dom": "catalog:react19",
"baseline-browser-mapping": "^2.10.11", "baseline-browser-mapping": "^2.11.26",
"eslint": "catalog:", "eslint": "catalog:",
"jsdom": "catalog:test", "jsdom": "catalog:test",
"prettier": "catalog:", "prettier": "catalog:",
+35 -33
View File
@@ -10,8 +10,8 @@ import { useEffect } from 'react';
import Footer from '@/components/layout/footer'; import Footer from '@/components/layout/footer';
import Header from '@/components/layout/header'; import Header from '@/components/layout/header';
import { ConvexClientProvider } from '@/components/providers'; import { ConvexClientProvider } from '@/components/providers';
import { env } from '@/env';
import { generateMetadata } from '@/lib/metadata'; import { generateMetadata } from '@/lib/metadata';
import { publicEnv } from '@/publicEnv';
import * as Sentry from '@sentry/nextjs'; import * as Sentry from '@sentry/nextjs';
import PlausibleProvider from 'next-plausible'; import PlausibleProvider from 'next-plausible';
@@ -44,39 +44,41 @@ const GlobalError = ({ error, reset = undefined }: GlobalErrorProps) => {
useEffect(() => { useEffect(() => {
Sentry.captureException(error); Sentry.captureException(error);
}, [error]); }, [error]);
return ( const page = (
<PlausibleProvider <ThemeProvider
domain={env.NEXT_PUBLIC_SITE_URL.trim().replace(/^https?:\/\//, '')} attribute='class'
customDomain={env.NEXT_PUBLIC_PLAUSIBLE_URL} defaultTheme='system'
enableSystem
disableTransitionOnChange
> >
<html lang='en' suppressHydrationWarning> <ConvexClientProvider>
<body <main className='flex min-h-screen flex-col items-center'>
className={`${geistSans.variable} ${geistMono.variable} antialiased`} <Header />
> <NextError statusCode={0} />
<ThemeProvider {reset !== undefined && (
attribute='class' <Button onClick={() => reset()}>Try Again</Button>
defaultTheme='system' )}
enableSystem <Toaster />
disableTransitionOnChange <Footer />
> </main>
<ConvexClientProvider> <main className='flex min-h-[90vh] flex-col items-center'>
<main className='flex min-h-screen flex-col items-center'> <Toaster />
<Header /> </main>
<NextError statusCode={0} /> </ConvexClientProvider>
{reset !== undefined && ( </ThemeProvider>
<Button onClick={() => reset()}>Try Again</Button> );
)} return (
<Toaster /> <html lang='en' suppressHydrationWarning>
<Footer /> <body
</main> className={`${geistSans.variable} ${geistMono.variable} antialiased`}
<main className='flex min-h-[90vh] flex-col items-center'> >
<Toaster /> {publicEnv.NEXT_PUBLIC_PLAUSIBLE_SRC ? (
</main> <PlausibleProvider>{page}</PlausibleProvider>
</ConvexClientProvider> ) : (
</ThemeProvider> page
</body> )}
</html> </body>
</PlausibleProvider> </html>
); );
}; };
export default GlobalError; export default GlobalError;
+30 -26
View File
@@ -36,34 +36,38 @@ const RootLayout = ({
}: Readonly<{ }: Readonly<{
children: React.ReactNode; children: React.ReactNode;
}>) => { }>) => {
const app = (
<ThemeProvider
attribute='class'
defaultTheme='system'
enableSystem
disableTransitionOnChange
>
<ConvexClientProvider>
<div className='flex min-h-screen flex-col'>
<Header />
{children}
<Footer />
</div>
<Toaster />
</ConvexClientProvider>
</ThemeProvider>
);
return ( return (
<ConvexAuthNextjsServerProvider> <ConvexAuthNextjsServerProvider>
<PlausibleProvider <html lang='en' suppressHydrationWarning>
domain={env.NEXT_PUBLIC_SITE_URL.trim().replace(/^https?:\/\//, '')} <body
customDomain={env.NEXT_PUBLIC_PLAUSIBLE_URL} className={`${geistSans.variable} ${geistMono.variable} antialiased`}
> >
<html lang='en' suppressHydrationWarning> {/* Plausible loads its per-site script through the same-origin
<body proxy in next.config.js; without that config it stays off. */}
className={`${geistSans.variable} ${geistMono.variable} antialiased`} {env.NEXT_PUBLIC_PLAUSIBLE_SRC ? (
> <PlausibleProvider>{app}</PlausibleProvider>
<ThemeProvider ) : (
attribute='class' app
defaultTheme='system' )}
enableSystem </body>
disableTransitionOnChange </html>
>
<ConvexClientProvider>
<div className='flex min-h-screen flex-col'>
<Header />
{children}
<Footer />
</div>
<Toaster />
</ConvexClientProvider>
</ThemeProvider>
</body>
</html>
</PlausibleProvider>
</ConvexAuthNextjsServerProvider> </ConvexAuthNextjsServerProvider>
); );
}; };
@@ -3,7 +3,7 @@
import type { Preloaded } from 'convex/react'; import type { Preloaded } from 'convex/react';
import type { ChangeEvent } from 'react'; import type { ChangeEvent } from 'react';
import { useRef, useState } from 'react'; import { useRef, useState } from 'react';
import { useMutation, usePreloadedQuery, useQuery } from 'convex/react'; import { useMutation, usePreloadedQuery } from 'convex/react';
import { Loader2, Pencil, Upload, XIcon } from 'lucide-react'; import { Loader2, Pencil, Upload, XIcon } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
@@ -48,11 +48,6 @@ export const AvatarUpload = ({ preloadedUser }: AvatarUploadProps) => {
const generateUploadUrl = useMutation(api.files.generateUploadUrl); const generateUploadUrl = useMutation(api.files.generateUploadUrl);
const updateUser = useMutation(api.auth.updateUser); const updateUser = useMutation(api.auth.updateUser);
const currentImageUrl = useQuery(
api.files.getImageUrl,
user?.image ? { storageId: user.image as Id<'_storage'> } : 'skip',
);
const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => { const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0] ?? null; const file = event.target.files?.[0] ?? null;
if (!file) return; if (!file) return;
@@ -117,7 +112,7 @@ export const AvatarUpload = ({ preloadedUser }: AvatarUploadProps) => {
onClick={() => inputRef.current?.click()} onClick={() => inputRef.current?.click()}
> >
<BasedAvatar <BasedAvatar
src={currentImageUrl ?? undefined} src={user?.imageUrl}
fullName={user?.name} fullName={user?.name}
className='h-42 w-42 text-6xl font-semibold' className='h-42 w-42 text-6xl font-semibold'
userIconProps={{ size: 100 }} userIconProps={{ size: 100 }}
@@ -2,6 +2,7 @@
import { useState } from 'react'; import { useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { resetAnalyticsIdentity } from '@/lib/analytics';
import { useAuthActions } from '@convex-dev/auth/react'; import { useAuthActions } from '@convex-dev/auth/react';
import { LogOut } from 'lucide-react'; import { LogOut } from 'lucide-react';
@@ -22,6 +23,7 @@ export const SignOutForm = () => {
setIsSigningOut(true); setIsSigningOut(true);
try { try {
await signOut(); await signOut();
resetAnalyticsIdentity();
router.push('/'); router.push('/');
} catch (error) { } catch (error) {
console.error('Sign out error:', error); console.error('Sign out error:', error);
@@ -2,10 +2,10 @@
import Link from 'next/link'; import Link from 'next/link';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { resetAnalyticsIdentity, useAnalyticsIdentity } from '@/lib/analytics';
import { useAuthActions } from '@convex-dev/auth/react'; import { useAuthActions } from '@convex-dev/auth/react';
import { useConvexAuth, useQuery } from 'convex/react'; import { useConvexAuth, useQuery } from 'convex/react';
import type { Id } from '@gib/backend/convex/_generated/dataModel.js';
import { api } from '@gib/backend/convex/_generated/api.js'; import { api } from '@gib/backend/convex/_generated/api.js';
import { import {
BasedAvatar, BasedAvatar,
@@ -23,10 +23,7 @@ export const AvatarDropdown = () => {
const { isLoading, isAuthenticated } = useConvexAuth(); const { isLoading, isAuthenticated } = useConvexAuth();
const { signOut } = useAuthActions(); const { signOut } = useAuthActions();
const user = useQuery(api.auth.getUser, {}); const user = useQuery(api.auth.getUser, {});
const currentImageUrl = useQuery( useAnalyticsIdentity(user?._id);
api.files.getImageUrl,
user?.image ? { storageId: user.image as Id<'_storage'> } : 'skip',
);
if (isLoading) { if (isLoading) {
return ( return (
@@ -51,7 +48,7 @@ export const AvatarDropdown = () => {
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger> <DropdownMenuTrigger>
<BasedAvatar <BasedAvatar
src={currentImageUrl} src={user?.imageUrl}
fullName={user?.name} fullName={user?.name}
className='h-9 w-9' className='h-9 w-9'
fallbackProps={{ className: 'text-sm font-semibold' }} fallbackProps={{ className: 'text-sm font-semibold' }}
@@ -77,6 +74,7 @@ export const AvatarDropdown = () => {
<button <button
onClick={() => onClick={() =>
void signOut().then(() => { void signOut().then(() => {
resetAnalyticsIdentity();
router.push('/'); router.push('/');
}) })
} }
@@ -1,11 +1,11 @@
'use client'; 'use client';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import { env } from '@/env'; import { publicEnv } from '@/publicEnv';
import { ConvexAuthNextjsProvider } from '@convex-dev/auth/nextjs'; import { ConvexAuthNextjsProvider } from '@convex-dev/auth/nextjs';
import { ConvexReactClient } from 'convex/react'; import { ConvexReactClient } from 'convex/react';
const convex = new ConvexReactClient(env.NEXT_PUBLIC_CONVEX_URL); const convex = new ConvexReactClient(publicEnv.NEXT_PUBLIC_CONVEX_URL);
export const ConvexClientProvider = ({ children }: { children: ReactNode }) => ( export const ConvexClientProvider = ({ children }: { children: ReactNode }) => (
<ConvexAuthNextjsProvider client={convex}> <ConvexAuthNextjsProvider client={convex}>
+7 -2
View File
@@ -18,7 +18,10 @@ export const env = createEnv({
client: { client: {
NEXT_PUBLIC_SITE_URL: z.url(), NEXT_PUBLIC_SITE_URL: z.url(),
NEXT_PUBLIC_CONVEX_URL: z.url(), NEXT_PUBLIC_CONVEX_URL: z.url(),
NEXT_PUBLIC_PLAUSIBLE_URL: z.url(), // Analytics are optional: absent values leave the integration off.
NEXT_PUBLIC_PLAUSIBLE_SRC: z.url().optional(),
NEXT_PUBLIC_POSTHOG_KEY: z.string().optional(),
NEXT_PUBLIC_POSTHOG_HOST: z.url().optional(),
NEXT_PUBLIC_SENTRY_DSN: z.string(), NEXT_PUBLIC_SENTRY_DSN: z.string(),
NEXT_PUBLIC_SENTRY_URL: z.string(), NEXT_PUBLIC_SENTRY_URL: z.string(),
NEXT_PUBLIC_SENTRY_ORG: z.string(), NEXT_PUBLIC_SENTRY_ORG: z.string(),
@@ -34,7 +37,9 @@ export const env = createEnv({
CI: process.env.CI, CI: process.env.CI,
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
NEXT_PUBLIC_CONVEX_URL: process.env.NEXT_PUBLIC_CONVEX_URL, NEXT_PUBLIC_CONVEX_URL: process.env.NEXT_PUBLIC_CONVEX_URL,
NEXT_PUBLIC_PLAUSIBLE_URL: process.env.NEXT_PUBLIC_PLAUSIBLE_URL, NEXT_PUBLIC_PLAUSIBLE_SRC: process.env.NEXT_PUBLIC_PLAUSIBLE_SRC,
NEXT_PUBLIC_POSTHOG_KEY: process.env.NEXT_PUBLIC_POSTHOG_KEY,
NEXT_PUBLIC_POSTHOG_HOST: process.env.NEXT_PUBLIC_POSTHOG_HOST,
NEXT_PUBLIC_SENTRY_DSN: process.env.NEXT_PUBLIC_SENTRY_DSN, NEXT_PUBLIC_SENTRY_DSN: process.env.NEXT_PUBLIC_SENTRY_DSN,
NEXT_PUBLIC_SENTRY_URL: process.env.NEXT_PUBLIC_SENTRY_URL, NEXT_PUBLIC_SENTRY_URL: process.env.NEXT_PUBLIC_SENTRY_URL,
NEXT_PUBLIC_SENTRY_ORG: process.env.NEXT_PUBLIC_SENTRY_ORG, NEXT_PUBLIC_SENTRY_ORG: process.env.NEXT_PUBLIC_SENTRY_ORG,
+24 -16
View File
@@ -1,27 +1,35 @@
// https://docs.sentry.io/platforms/javascript/guides/nextjs/ // https://docs.sentry.io/platforms/javascript/guides/nextjs/
import { env } from '@/env'; import { startAnalytics } from '@/lib/analytics';
import { publicEnv } from '@/publicEnv';
import * as Sentry from '@sentry/nextjs'; import * as Sentry from '@sentry/nextjs';
// Session replay is left to PostHog, so Sentry carries no replay integration.
Sentry.init({ Sentry.init({
dsn: env.NEXT_PUBLIC_SENTRY_DSN, dsn: publicEnv.NEXT_PUBLIC_SENTRY_DSN,
integrations: [
Sentry.replayIntegration({
maskAllText: false,
blockAllMedia: false,
}),
Sentry.feedbackIntegration({
colorScheme: 'system',
}),
],
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#sendDefaultPii // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#sendDefaultPii
sendDefaultPii: true, sendDefaultPii: false,
// https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate
tracesSampleRate: 1, // A tenth of page loads is plenty for performance trends and keeps the
// self-hosted Sentry light.
tracesSampleRate: 0.1,
enableLogs: true, enableLogs: true,
// https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration
replaysSessionSampleRate: 0.5,
replaysOnErrorSampleRate: 1.0,
debug: false, debug: false,
}); });
// The feedback widget is a floating button nobody needs during the first
// paint, so its code is split into its own chunk and added once the page has
// loaded.
const addFeedbackWidget = async () => {
const { feedbackIntegration } = await import('@sentry/nextjs');
Sentry.addIntegration(feedbackIntegration({ colorScheme: 'system' }));
};
if (document.readyState === 'complete') void addFeedbackWidget();
else
window.addEventListener('load', () => void addFeedbackWidget(), {
once: true,
});
startAnalytics();
// `captureRouterTransitionStart` is available from SDK version 9.12.0 onwards // `captureRouterTransitionStart` is available from SDK version 9.12.0 onwards
export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;
+86
View File
@@ -0,0 +1,86 @@
import type { PostHog } from 'posthog-js';
import { useEffect } from 'react';
import { aliasPosthogScript } from '@/lib/posthog-scripts';
import { publicEnv } from '@/publicEnv';
// PostHog stays off until a project key and host are configured. Calling
// posthog-js before init logs an error on every call, so every use goes
// through this flag.
export const analyticsEnabled = Boolean(
publicEnv.NEXT_PUBLIC_POSTHOG_KEY && publicEnv.NEXT_PUBLIC_POSTHOG_HOST,
);
let client: PostHog | undefined;
// Identity calls made before PostHog has loaded, replayed in order once it has.
const pending: ((posthog: PostHog) => void)[] = [];
const withPosthog = (call: (posthog: PostHog) => void) => {
if (client) call(client);
else pending.push(call);
};
// Runs once the page has loaded and the main thread is idle, so analytics
// never competes with the first paint or hydration.
const afterPageIsIdle = (run: () => void) => {
const schedule = () => {
if ('requestIdleCallback' in window)
window.requestIdleCallback(run, { timeout: 4_000 });
else setTimeout(run, 0);
};
if (document.readyState === 'complete') schedule();
else window.addEventListener('load', schedule, { once: true });
};
const initPosthog = async (key: string) => {
const { default: posthog } = await import('posthog-js');
posthog.init(key, {
// Events go through the same-origin /ingest rewrite in next.config.js
// rather than straight to the PostHog host, whose name and paths ad
// blockers match on. ui_host keeps toolbar links on the real host.
api_host: '/ingest',
ui_host: publicEnv.NEXT_PUBLIC_POSTHOG_HOST,
// Makes pageviews follow App Router client-side navigation.
defaults: '2026-08-30',
// Autocapture, session replay (typed input masked), heatmaps and web
// vitals come from these defaults plus the project settings in PostHog.
capture_exceptions: true,
// Two extension script names are ad-blocked by name; see
// lib/posthog-scripts.ts for the aliasing.
strict_script_versioning: false,
prepare_external_dependency_script: (script) => {
script.src = aliasPosthogScript(script.src);
return script;
},
});
// Keeps local runs separate from production in the same project.
posthog.register({
environment: new URL(publicEnv.NEXT_PUBLIC_SITE_URL).hostname,
});
client = posthog;
for (const call of pending.splice(0)) call(posthog);
};
// Called once from instrumentation-client. posthog-js is downloaded and
// initialised only after the page is idle, which keeps it out of the first
// load; identity calls made in the meantime are queued above.
export const startAnalytics = () => {
const key = publicEnv.NEXT_PUBLIC_POSTHOG_KEY;
if (!analyticsEnabled || !key) return;
afterPageIsIdle(() => void initPosthog(key));
};
// Ties this browser's PostHog person to the signed-in Convex user. The id is
// opaque, so no name or email leaves the app. Mounted by the header avatar,
// which renders on every page while someone is signed in.
export const useAnalyticsIdentity = (userId: string | undefined) => {
useEffect(() => {
if (!analyticsEnabled || !userId) return;
withPosthog((posthog) => posthog.identify(userId));
}, [userId]);
};
// Starts a fresh anonymous id on sign-out so the next person on this browser
// is never merged into the last one.
export const resetAnalyticsIdentity = () => {
if (analyticsEnabled) withPosthog((posthog) => posthog.reset());
};
+24
View File
@@ -0,0 +1,24 @@
// posthog-js loads optional features (session replay, dead clicks) as extra
// scripts from <api_host>/static/<name>.js. Two of those file names sit on the
// default ad-blocker lists by name alone (EasyPrivacy carries the literal
// substrings /posthog-recorder.js and /dead-clicks-autocapture.js), so the
// same-origin proxy does not save them: the browser refuses the request before
// it leaves. The client asks for the alias instead, and next.config.js rewrites
// the alias back to the real file on the way out. Nothing here changes what is
// loaded, only what it is called on the wire. The aliases are deliberately
// meaningless so a broader rule added later has nothing to match.
export const posthogScriptAliases: Record<string, string> = {
'posthog-recorder': 'ext-a',
'dead-clicks-autocapture': 'ext-b',
};
const staticScript = /\/static\/([a-z0-9-]+)\.js(?=\?|$)/;
// Rewrites a PostHog extension script URL to its alias, or returns it
// unchanged when the file is not on the list.
export const aliasPosthogScript = (src: string) =>
src.replace(staticScript, (match, name: string) =>
name in posthogScriptAliases
? `/static/${posthogScriptAliases[name]}.js`
: match,
);
+30
View File
@@ -0,0 +1,30 @@
import type { env } from '@/env';
type PublicEnv = Pick<
typeof env,
| 'NEXT_PUBLIC_SITE_URL'
| 'NEXT_PUBLIC_CONVEX_URL'
| 'NEXT_PUBLIC_PLAUSIBLE_SRC'
| 'NEXT_PUBLIC_POSTHOG_KEY'
| 'NEXT_PUBLIC_POSTHOG_HOST'
| 'NEXT_PUBLIC_SENTRY_DSN'
>;
// Empty strings count as unset, matching `emptyStringAsUndefined` in env.ts.
const read = (value: string | undefined) => (value === '' ? undefined : value);
// The browser-side NEXT_PUBLIC_* values for client components and
// instrumentation-client. Next inlines each literal `process.env.X` at build
// time, and env.ts has already validated them by then (next.config.js imports
// it), so reading them here keeps zod and the env schema out of every
// visitor's first download. Server code keeps importing `@/env`.
/* eslint-disable no-restricted-properties -- the one sanctioned client-side reader, see AGENTS.md */
export const publicEnv = {
NEXT_PUBLIC_SITE_URL: read(process.env.NEXT_PUBLIC_SITE_URL),
NEXT_PUBLIC_CONVEX_URL: read(process.env.NEXT_PUBLIC_CONVEX_URL),
NEXT_PUBLIC_PLAUSIBLE_SRC: read(process.env.NEXT_PUBLIC_PLAUSIBLE_SRC),
NEXT_PUBLIC_POSTHOG_KEY: read(process.env.NEXT_PUBLIC_POSTHOG_KEY),
NEXT_PUBLIC_POSTHOG_HOST: read(process.env.NEXT_PUBLIC_POSTHOG_HOST),
NEXT_PUBLIC_SENTRY_DSN: read(process.env.NEXT_PUBLIC_SENTRY_DSN),
} as PublicEnv;
/* eslint-enable no-restricted-properties */
+2 -1
View File
@@ -3,7 +3,8 @@ import * as Sentry from '@sentry/nextjs';
Sentry.init({ Sentry.init({
dsn: env.NEXT_PUBLIC_SENTRY_DSN, dsn: env.NEXT_PUBLIC_SENTRY_DSN,
tracesSampleRate: 1, // One in ten requests keeps traces useful without loading the home server.
tracesSampleRate: 0.1,
enableLogs: true, enableLogs: true,
debug: false, debug: false,
}); });
+516 -1156
View File
File diff suppressed because it is too large. Load diff
+9 -5
View File
@@ -1,16 +1,18 @@
# syntax=docker/dockerfile:1 # syntax=docker/dockerfile:1
FROM docker.io/oven/bun:1.3.10-alpine AS base FROM docker.io/oven/bun:1.3.14-alpine AS base
# Builder stage # Builder stage
FROM base AS builder FROM base AS builder
RUN apk add --no-cache libc6-compat RUN apk add --no-cache curl libc6-compat
WORKDIR /app WORKDIR /app
ARG SENTRY_AUTH_TOKEN ARG SENTRY_AUTH_TOKEN
ARG SENTRY_DISABLE_AUTO_UPLOAD=false ARG SENTRY_DISABLE_AUTO_UPLOAD=false
ARG NEXT_PUBLIC_SITE_URL ARG NEXT_PUBLIC_SITE_URL
ARG NEXT_PUBLIC_CONVEX_URL ARG NEXT_PUBLIC_CONVEX_URL
ARG NEXT_PUBLIC_PLAUSIBLE_URL ARG NEXT_PUBLIC_PLAUSIBLE_SRC
ARG NEXT_PUBLIC_POSTHOG_KEY
ARG NEXT_PUBLIC_POSTHOG_HOST
ARG NEXT_PUBLIC_SENTRY_DSN ARG NEXT_PUBLIC_SENTRY_DSN
ARG NEXT_PUBLIC_SENTRY_URL ARG NEXT_PUBLIC_SENTRY_URL
ARG NEXT_PUBLIC_SENTRY_ORG ARG NEXT_PUBLIC_SENTRY_ORG
@@ -20,7 +22,9 @@ ENV SENTRY_AUTH_TOKEN=$SENTRY_AUTH_TOKEN
ENV SENTRY_DISABLE_AUTO_UPLOAD=$SENTRY_DISABLE_AUTO_UPLOAD ENV SENTRY_DISABLE_AUTO_UPLOAD=$SENTRY_DISABLE_AUTO_UPLOAD
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL
ENV NEXT_PUBLIC_CONVEX_URL=$NEXT_PUBLIC_CONVEX_URL ENV NEXT_PUBLIC_CONVEX_URL=$NEXT_PUBLIC_CONVEX_URL
ENV NEXT_PUBLIC_PLAUSIBLE_URL=$NEXT_PUBLIC_PLAUSIBLE_URL ENV NEXT_PUBLIC_PLAUSIBLE_SRC=$NEXT_PUBLIC_PLAUSIBLE_SRC
ENV NEXT_PUBLIC_POSTHOG_KEY=$NEXT_PUBLIC_POSTHOG_KEY
ENV NEXT_PUBLIC_POSTHOG_HOST=$NEXT_PUBLIC_POSTHOG_HOST
ENV NEXT_PUBLIC_SENTRY_DSN=$NEXT_PUBLIC_SENTRY_DSN ENV NEXT_PUBLIC_SENTRY_DSN=$NEXT_PUBLIC_SENTRY_DSN
ENV NEXT_PUBLIC_SENTRY_URL=$NEXT_PUBLIC_SENTRY_URL ENV NEXT_PUBLIC_SENTRY_URL=$NEXT_PUBLIC_SENTRY_URL
ENV NEXT_PUBLIC_SENTRY_ORG=$NEXT_PUBLIC_SENTRY_ORG ENV NEXT_PUBLIC_SENTRY_ORG=$NEXT_PUBLIC_SENTRY_ORG
@@ -36,7 +40,7 @@ RUN bun install --frozen-lockfile
# Build with proper environment # Build with proper environment
ENV NEXT_TELEMETRY_DISABLED=1 ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production ENV NODE_ENV=production
RUN cd apps/next && bun run build:docker RUN sh scripts/build-next-bundle
# Runner stage # Runner stage
FROM docker.io/library/node:22-alpine AS runner FROM docker.io/library/node:22-alpine AS runner
+10 -10
View File
@@ -1,17 +1,17 @@
name: convexmonorepo-local name: convexmonorepo-base-local
services: services:
convex-backend: convex-backend:
image: ghcr.io/get-convex/convex-backend:${BACKEND_TAG:-latest} image: ghcr.io/get-convex/convex-backend:${BACKEND_TAG:-latest}
container_name: convexmonorepo-local-convex container_name: convexmonorepo-base-local-convex
ports: ports:
- '${BACKEND_PORT:-3210}:3210' - '${BACKEND_PORT:-3250}:3210'
- '${SITE_PROXY_PORT:-3211}:3211' - '${SITE_PROXY_PORT:-3251}:3211'
environment: environment:
- INSTANCE_NAME=${LOCAL_INSTANCE_NAME:-convexmonorepo_local} - INSTANCE_NAME=${LOCAL_INSTANCE_NAME:-convexmonorepo_base_local}
- INSTANCE_SECRET=${LOCAL_INSTANCE_SECRET:-0000000000000000000000000000000000000000000000000000000000000000} - INSTANCE_SECRET=${LOCAL_INSTANCE_SECRET:-0000000000000000000000000000000000000000000000000000000000000000}
- CONVEX_CLOUD_ORIGIN=http://localhost:${BACKEND_PORT:-3210} - CONVEX_CLOUD_ORIGIN=http://localhost:${BACKEND_PORT:-3250}
- CONVEX_SITE_ORIGIN=http://localhost:${SITE_PROXY_PORT:-3211} - CONVEX_SITE_ORIGIN=http://localhost:${SITE_PROXY_PORT:-3251}
- DISABLE_BEACON=true - DISABLE_BEACON=true
- REDACT_LOGS_TO_CLIENT=false - REDACT_LOGS_TO_CLIENT=false
- DO_NOT_REQUIRE_SSL=true - DO_NOT_REQUIRE_SSL=true
@@ -31,10 +31,10 @@ services:
convex-dashboard: convex-dashboard:
image: ghcr.io/get-convex/convex-dashboard:${DASHBOARD_TAG:-latest} image: ghcr.io/get-convex/convex-dashboard:${DASHBOARD_TAG:-latest}
container_name: convexmonorepo-local-convex-dashboard container_name: convexmonorepo-base-local-convex-dashboard
ports: ['${DASHBOARD_PORT:-6791}:6791'] ports: ['${DASHBOARD_PORT:-6795}:6791']
environment: environment:
- NEXT_PUBLIC_DEPLOYMENT_URL=http://localhost:${BACKEND_PORT:-3210} - NEXT_PUBLIC_DEPLOYMENT_URL=http://localhost:${BACKEND_PORT:-3250}
depends_on: depends_on:
convex-backend: convex-backend:
condition: service_healthy condition: service_healthy
+6 -2
View File
@@ -12,7 +12,9 @@ services:
SENTRY_DISABLE_AUTO_UPLOAD: ${SENTRY_DISABLE_AUTO_UPLOAD:-false} SENTRY_DISABLE_AUTO_UPLOAD: ${SENTRY_DISABLE_AUTO_UPLOAD:-false}
NEXT_PUBLIC_SITE_URL: ${NEXT_PUBLIC_SITE_URL} NEXT_PUBLIC_SITE_URL: ${NEXT_PUBLIC_SITE_URL}
NEXT_PUBLIC_CONVEX_URL: ${NEXT_PUBLIC_CONVEX_URL} NEXT_PUBLIC_CONVEX_URL: ${NEXT_PUBLIC_CONVEX_URL}
NEXT_PUBLIC_PLAUSIBLE_URL: ${NEXT_PUBLIC_PLAUSIBLE_URL} NEXT_PUBLIC_PLAUSIBLE_SRC: ${NEXT_PUBLIC_PLAUSIBLE_SRC:-}
NEXT_PUBLIC_POSTHOG_KEY: ${NEXT_PUBLIC_POSTHOG_KEY:-}
NEXT_PUBLIC_POSTHOG_HOST: ${NEXT_PUBLIC_POSTHOG_HOST:-}
NEXT_PUBLIC_SENTRY_DSN: ${NEXT_PUBLIC_SENTRY_DSN} NEXT_PUBLIC_SENTRY_DSN: ${NEXT_PUBLIC_SENTRY_DSN}
NEXT_PUBLIC_SENTRY_URL: ${NEXT_PUBLIC_SENTRY_URL} NEXT_PUBLIC_SENTRY_URL: ${NEXT_PUBLIC_SENTRY_URL}
NEXT_PUBLIC_SENTRY_ORG: ${NEXT_PUBLIC_SENTRY_ORG} NEXT_PUBLIC_SENTRY_ORG: ${NEXT_PUBLIC_SENTRY_ORG}
@@ -25,7 +27,9 @@ services:
- SENTRY_AUTH_TOKEN=${SENTRY_AUTH_TOKEN} - SENTRY_AUTH_TOKEN=${SENTRY_AUTH_TOKEN}
- NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL:-http://localhost:${NEXT_PORT:-3000}} - NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL:-http://localhost:${NEXT_PORT:-3000}}
- NEXT_PUBLIC_CONVEX_URL=${NEXT_PUBLIC_CONVEX_URL:-http://${BACKEND_CONTAINER_NAME:-convex-backend}:${BACKEND_PORT:-3210}} - NEXT_PUBLIC_CONVEX_URL=${NEXT_PUBLIC_CONVEX_URL:-http://${BACKEND_CONTAINER_NAME:-convex-backend}:${BACKEND_PORT:-3210}}
- NEXT_PUBLIC_PLAUSIBLE_URL=${NEXT_PUBLIC_PLAUSIBLE_URL:-https://plausible.gbrown.org} - NEXT_PUBLIC_PLAUSIBLE_SRC=${NEXT_PUBLIC_PLAUSIBLE_SRC:-}
- NEXT_PUBLIC_POSTHOG_KEY=${NEXT_PUBLIC_POSTHOG_KEY:-}
- NEXT_PUBLIC_POSTHOG_HOST=${NEXT_PUBLIC_POSTHOG_HOST:-}
- NEXT_PUBLIC_SENTRY_DSN=${NEXT_PUBLIC_SENTRY_DSN} - NEXT_PUBLIC_SENTRY_DSN=${NEXT_PUBLIC_SENTRY_DSN}
- NEXT_PUBLIC_SENTRY_URL=${NEXT_PUBLIC_SENTRY_URL} - NEXT_PUBLIC_SENTRY_URL=${NEXT_PUBLIC_SENTRY_URL}
- NEXT_PUBLIC_SENTRY_ORG=${NEXT_PUBLIC_SENTRY_ORG:-sentry} - NEXT_PUBLIC_SENTRY_ORG=${NEXT_PUBLIC_SENTRY_ORG:-sentry}
+16 -14
View File
@@ -4,7 +4,7 @@
"engines": { "engines": {
"node": "^22.20.0" "node": "^22.20.0"
}, },
"packageManager": "[email protected]0", "packageManager": "[email protected]4",
"workspaces": [ "workspaces": [
"apps/*", "apps/*",
"packages/*", "packages/*",
@@ -25,24 +25,24 @@
"test": { "test": {
"@edge-runtime/vm": "^5.0.0", "@edge-runtime/vm": "^5.0.0",
"@playwright/test": "^1.60.0", "@playwright/test": "^1.60.0",
"@testing-library/jest-dom": "^6.9.1", "@testing-library/jest-dom": "^6.10.0",
"@testing-library/react": "^16.3.2", "@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.1", "@testing-library/user-event": "^14.6.1",
"@vitejs/plugin-react": "^6.0.2", "@vitejs/plugin-react": "^6.1.1",
"@vitest/coverage-v8": "^4.1.8", "@vitest/coverage-v8": "^4.1.8",
"convex-test": "^0.0.53", "convex-test": "^0.0.53",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"vitest": "^4.1.8" "vitest": "^4.1.11"
}, },
"convex": { "convex": {
"@convex-dev/auth": "^0.0.87", "@convex-dev/auth": "^0.0.96",
"convex": "^1.34.1" "convex": "^1.46.0"
}, },
"react19": { "react19": {
"@types/react": "~19.2.14", "@types/react": "~19.3.0",
"@types/react-dom": "~19.2.3", "@types/react-dom": "~19.3.0",
"react": "19.2.4", "react": "19.3.0",
"react-dom": "19.2.4" "react-dom": "19.3.0"
} }
}, },
"scripts": { "scripts": {
@@ -55,11 +55,13 @@
"dev:next:web": "turbo run dev:web -F @gib/next -F @gib/backend", "dev:next:web": "turbo run dev:web -F @gib/next -F @gib/backend",
"dev:expo": "turbo run dev -F @gib/expo -F @gib/backend", "dev:expo": "turbo run dev -F @gib/expo -F @gib/backend",
"dev:backend": "turbo run dev -F @gib/backend", "dev:backend": "turbo run dev -F @gib/backend",
"dev:kill": "bash scripts/dev-kill",
"dev:staging": "INFISICAL_ENV=staging turbo run dev -F @gib/next -F @gib/backend", "dev:staging": "INFISICAL_ENV=staging turbo run dev -F @gib/next -F @gib/backend",
"dev:expo:tunnel": "turbo run dev:tunnel -F @gib/expo -F @gib/backend", "dev:expo:tunnel": "turbo run dev:tunnel -F @gib/expo -F @gib/backend",
"db:up": "bash scripts/db/up", "db:up": "bash scripts/db/up",
"db:down": "bash scripts/db/down", "db:down": "bash scripts/db/down",
"db:down:wipe": "bash scripts/db/down --wipe", "db:down:wipe": "bash scripts/db/down --wipe",
"db:sync-env": "bash scripts/with-env dev -- bash scripts/sync-local-convex-env",
"format": "turbo run format --continue -- --cache --cache-location .cache/.prettiercache", "format": "turbo run format --continue -- --cache --cache-location .cache/.prettiercache",
"format:fix": "turbo run format --continue -- --write --cache --cache-location .cache/.prettiercache", "format:fix": "turbo run format --continue -- --write --cache --cache-location .cache/.prettiercache",
"lint": "turbo run lint --continue -- --cache --cache-location .cache/.eslintcache", "lint": "turbo run lint --continue -- --cache --cache-location .cache/.eslintcache",
@@ -82,12 +84,12 @@
}, },
"devDependencies": { "devDependencies": {
"@gib/prettier-config": "workspace:", "@gib/prettier-config": "workspace:",
"@turbo/gen": "^2.9.18", "@turbo/gen": "^2.11.6",
"dotenv-cli": "11.0.0", "dotenv-cli": "11.0.0",
"husky": "^9.1.7", "husky": "^9.1.7",
"lint-staged": "^17.0.7", "lint-staged": "^17.6.0",
"prettier": "catalog:", "prettier": "catalog:",
"turbo": "^2.9.18", "turbo": "^2.11.6",
"typescript": "catalog:" "typescript": "catalog:"
}, },
"prettier": "@gib/prettier-config", "prettier": "@gib/prettier-config",
+19
View File
@@ -21,6 +21,17 @@ import {
} from "convex/server"; } from "convex/server";
import type { DataModel } from "./dataModel.js"; import type { DataModel } from "./dataModel.js";
/**
* Typesafe environment variables.
*
* This includes platform-provided env vars and any variables declared in
* `convex.config.ts`.
*/
type Env = {
readonly CONVEX_CLOUD_URL: string;
readonly CONVEX_SITE_URL: string;
};
/** /**
* Define a query in this Convex app's public API. * Define a query in this Convex app's public API.
* *
@@ -95,6 +106,14 @@ export declare const internalAction: ActionBuilder<DataModel, "internal">;
*/ */
export declare const httpAction: HttpActionBuilder; export declare const httpAction: HttpActionBuilder;
/**
* Typesafe environment variables.
*
* This includes platform-provided env vars and any variables declared in
* `convex.config.ts`.
*/
export declare const env: Env;
/** /**
* A set of services for use within Convex query functions. * A set of services for use within Convex query functions.
* *
@@ -91,3 +91,11 @@ export const internalAction = internalActionGeneric;
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up. * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/ */
export const httpAction = httpActionGeneric; export const httpAction = httpActionGeneric;
/**
* Typesafe environment variables.
*
* This includes platform-provided env vars and any variables declared in
* `convex.config.ts`.
*/
export const env = process.env;
+17 -2
View File
@@ -45,12 +45,24 @@ export const getUserProvider = query({
}, },
}); });
/**
* `users.image` holds either a Convex storage ID (avatar uploaded in-app) or a
* plain URL (the `picture` claim Authentik writes on every OAuth sign-in).
* Resolves either form to a URL the client can render directly.
*/
const resolveImageUrl = async (ctx: QueryCtx, image: string | undefined) => {
if (!image) return null;
const storageId = ctx.db.system.normalizeId('_storage', image);
return storageId ? await ctx.storage.getUrl(storageId) : image;
};
export const getUser = query({ export const getUser = query({
args: { userId: v.optional(v.id('users')) }, args: { userId: v.optional(v.id('users')) },
handler: async (ctx, args) => { handler: async (ctx, args) => {
const userId = args.userId ?? (await getAuthUserId(ctx)); const userId = args.userId ?? (await getAuthUserId(ctx));
if (!userId) return null; if (!userId) return null;
return getUserById(ctx, userId); const user = await getUserById(ctx, userId);
return { ...user, imageUrl: await resolveImageUrl(ctx, user.image) };
}, },
}); });
@@ -73,7 +85,10 @@ export const updateUser = mutation({
if (args.name !== undefined) patch.name = args.name; if (args.name !== undefined) patch.name = args.name;
if (args.email !== undefined) patch.email = args.email; if (args.email !== undefined) patch.email = args.email;
if (args.image !== undefined) { if (args.image !== undefined) {
const oldImage = user.image as Id<'_storage'> | undefined; // Only delete the previous avatar when it was an uploaded file, not an IdP URL.
const oldImage = user.image
? ctx.db.system.normalizeId('_storage', user.image)
: null;
patch.image = args.image; patch.image = args.image;
if (oldImage && oldImage !== args.image) { if (oldImage && oldImage !== args.image) {
await ctx.storage.delete(oldImage); await ctx.storage.delete(oldImage);
@@ -1,6 +1,5 @@
import type { EmailConfig, EmailUserConfig } from '@auth/core/providers/email'; import type { EmailConfig, EmailUserConfig } from '@auth/core/providers/email';
import { generateRandomString, RandomReader } from '@oslojs/crypto/random'; import { generateRandomString, RandomReader } from '@oslojs/crypto/random';
import { alphabet } from 'oslo/crypto';
import { UseSend } from 'usesend-js'; import { UseSend } from 'usesend-js';
export default function UseSendProvider(config: EmailUserConfig): EmailConfig { export default function UseSendProvider(config: EmailUserConfig): EmailConfig {
@@ -17,7 +16,7 @@ export default function UseSendProvider(config: EmailUserConfig): EmailConfig {
crypto.getRandomValues(bytes as Uint8Array<ArrayBuffer>); crypto.getRandomValues(bytes as Uint8Array<ArrayBuffer>);
}, },
}; };
return generateRandomString(random, alphabet('0-9'), 6); return generateRandomString(random, '0123456789', 6);
}, },
sendVerificationRequest: async (params) => { sendVerificationRequest: async (params) => {
+3 -2
View File
@@ -26,9 +26,10 @@
"with-env": "sh ../../scripts/with-env ${INFISICAL_ENV:-dev} --" "with-env": "sh ../../scripts/with-env ${INFISICAL_ENV:-dev} --"
}, },
"dependencies": { "dependencies": {
"@auth/core": "^0.41.3",
"@oslojs/crypto": "^1.0.1", "@oslojs/crypto": "^1.0.1",
"@react-email/components": "1.0.10", "@react-email/components": "1.0.12",
"@react-email/render": "^2.0.4", "@react-email/render": "^2.1.0",
"convex": "catalog:convex", "convex": "catalog:convex",
"react": "catalog:react19", "react": "catalog:react19",
"react-dom": "catalog:react19", "react-dom": "catalog:react19",
+24 -24
View File
@@ -18,38 +18,38 @@
"ui-add": "bunx --bun shadcn@latest add && prettier src --write --list-different" "ui-add": "bunx --bun shadcn@latest add && prettier src --write --list-different"
}, },
"dependencies": { "dependencies": {
"@base-ui/react": "^1.3.0", "@base-ui/react": "^1.8.0",
"@hookform/resolvers": "^5.2.2", "@hookform/resolvers": "^5.9.1",
"@radix-ui/react-avatar": "^1.1.11", "@radix-ui/react-avatar": "^1.2.6",
"@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-checkbox": "^1.3.11",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.23",
"@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-dropdown-menu": "^2.1.24",
"@radix-ui/react-icons": "^1.3.2", "@radix-ui/react-icons": "^1.3.2",
"@radix-ui/react-label": "^2.1.8", "@radix-ui/react-label": "^2.1.15",
"@radix-ui/react-progress": "^1.1.8", "@radix-ui/react-progress": "^1.1.16",
"@radix-ui/react-scroll-area": "^1.2.10", "@radix-ui/react-scroll-area": "^1.2.18",
"@radix-ui/react-separator": "^1.1.8", "@radix-ui/react-separator": "^1.1.15",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.3.3",
"@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-switch": "^1.3.7",
"@radix-ui/react-tabs": "^1.1.13", "@radix-ui/react-tabs": "^1.1.21",
"@tabler/icons-react": "^3.41.0", "@tabler/icons-react": "^3.48.0",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"date-fns": "^4.1.0", "date-fns": "^4.4.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"input-otp": "^1.4.2", "input-otp": "^1.5.0",
"lucide-react": "^0.577.0", "lucide-react": "^0.577.0",
"motion": "^12.38.0", "motion": "^12.43.0",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"radix-ui": "^1.4.3", "radix-ui": "^1.6.7",
"react-day-picker": "^9.14.0", "react-day-picker": "^9.14.0",
"react-hook-form": "^7.72.0", "react-hook-form": "^7.89.0",
"react-image-crop": "^11.0.10", "react-image-crop": "^11.1.2",
"react-resizable-panels": "^4.7.6", "react-resizable-panels": "^4.14.1",
"recharts": "^3.8.1", "recharts": "^3.10.1",
"sonner": "^2.0.7", "sonner": "^2.0.8",
"tailwind-merge": "^3.5.0", "tailwind-merge": "^3.7.0",
"vaul": "^1.1.2" "vaul": "^1.1.2"
}, },
"devDependencies": { "devDependencies": {
+3
View File
@@ -93,6 +93,9 @@ const Carousel = ({
React.useEffect(() => { React.useEffect(() => {
if (!api) return; if (!api) return;
// Embla is the source of truth for scroll state; read it once on mount,
// then follow its events.
// eslint-disable-next-line react-hooks/set-state-in-effect
onSelect(api); onSelect(api);
api.on('reInit', onSelect); api.on('reInit', onSelect);
api.on('select', onSelect); api.on('select', onSelect);
+6 -4
View File
@@ -105,6 +105,10 @@ ${colorConfig
const ChartTooltip = RechartsPrimitive.Tooltip; const ChartTooltip = RechartsPrimitive.Tooltip;
// Recharts injects `payload`/`label`/`active` into tooltip and legend content
// at render time, but (as of recharts v3) does not expose them on the public
// prop types, and the payload items are loosely typed. Model the fields we use
// explicitly so the component is type-safe.
type ChartPayloadItem = { type ChartPayloadItem = {
name?: string | number; name?: string | number;
value?: number | string; value?: number | string;
@@ -356,15 +360,13 @@ const getPayloadConfigFromPayload = (
key in payload && key in payload &&
typeof payload[key as keyof typeof payload] === 'string' typeof payload[key as keyof typeof payload] === 'string'
) { ) {
configLabelKey = payload[key as keyof typeof payload] as string; configLabelKey = payload[key as keyof typeof payload];
} else if ( } else if (
payloadPayload && payloadPayload &&
key in payloadPayload && key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === 'string' typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
) { ) {
configLabelKey = payloadPayload[ configLabelKey = payloadPayload[key as keyof typeof payloadPayload];
key as keyof typeof payloadPayload
] as string;
} }
return configLabelKey in config ? config[configLabelKey] : config[key]; return configLabelKey in config ? config[configLabelKey] : config[key];
+14 -16
View File
@@ -1,21 +1,19 @@
import * as React from 'react'; import * as React from 'react';
const MOBILE_BREAKPOINT = 768; const MOBILE_BREAKPOINT = 768;
const MOBILE_QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`;
export const useIsMobile = () => { const subscribe = (onChange: () => void) => {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>( const mql = window.matchMedia(MOBILE_QUERY);
undefined, mql.addEventListener('change', onChange);
); return () => mql.removeEventListener('change', onChange);
React.useEffect(() => {
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);
}, []);
return !!isMobile;
}; };
// True below the mobile breakpoint. Server renders and hydration assume
// desktop, then the browser's media query takes over.
export const useIsMobile = () =>
React.useSyncExternalStore(
subscribe,
() => window.matchMedia(MOBILE_QUERY).matches,
() => false,
);
+2 -8
View File
@@ -294,10 +294,7 @@ export const ImageCropApply = ({
if (asChild) { if (asChild) {
return ( return (
<Slot.Root <Slot.Root onClick={handleClick} {...props}>
onClick={handleClick}
{...(props as ComponentProps<typeof Slot.Root>)}
>
{children} {children}
</Slot.Root> </Slot.Root>
); );
@@ -329,10 +326,7 @@ export const ImageCropReset = ({
if (asChild) { if (asChild) {
return ( return (
<Slot.Root <Slot.Root onClick={handleClick} {...props}>
onClick={handleClick}
{...(props as ComponentProps<typeof Slot.Root>)}
>
{children} {children}
</Slot.Root> </Slot.Root>
); );
+5 -17
View File
@@ -1,20 +1,8 @@
import { cx } from 'class-variance-authority'; // Re-exports only. The Next app lists @gib/ui in `optimizePackageImports`,
import { twMerge } from 'tailwind-merge'; // which resolves each named import straight to its own module so a page that
// uses Button never loads Chart (and Recharts). That only works while nothing
export const cn = (...inputs: Parameters<typeof cx>) => twMerge(cx(inputs)); // is declared in this file.
export { cn, ccn } from './utils';
export const ccn = ({
context,
className,
on = '',
off = '',
}: {
context: boolean;
className: string;
on: string;
off: string;
}) => twMerge(className, context ? on : off);
export { export {
Accordion, Accordion,
AccordionItem, AccordionItem,
+16
View File
@@ -0,0 +1,16 @@
import { cx } from 'class-variance-authority';
import { twMerge } from 'tailwind-merge';
export const cn = (...inputs: Parameters<typeof cx>) => twMerge(cx(inputs));
export const ccn = ({
context,
className,
on = '',
off = '',
}: {
context: boolean;
className: string;
on: string;
off: string;
}) => twMerge(className, context ? on : off);
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env sh
set -eu
ROOT_DIR="$(cd -- "$(dirname -- "$0")/.." && pwd)"
if [ -n "${SENTRY_AUTH_TOKEN:-}" ] &&
[ -n "${NEXT_PUBLIC_SENTRY_URL:-}" ] &&
! curl \
--connect-timeout 3 \
--max-time 10 \
--silent \
--show-error \
--output /dev/null \
"${NEXT_PUBLIC_SENTRY_URL%/}/api/0/"; then
echo "Sentry is unreachable; continuing without source-map upload." >&2
SENTRY_AUTH_TOKEN=""
SKIP_ENV_VALIDATION=true
NEXT_PUBLIC_SENTRY_URL="http://127.0.0.1:9"
export NEXT_PUBLIC_SENTRY_URL SENTRY_AUTH_TOKEN SKIP_ENV_VALIDATION
fi
cd "$ROOT_DIR/apps/next"
exec bun run build:docker
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env node
// ci-export-env.mjs [environment]
//
// CI's counterpart to scripts/export-env: prints an Infisical environment
// (default `staging`) as dotenv on stdout, in the same quoting export-env uses.
// It logs in as the `convexmonorepo-base-ci` machine identity through Universal Auth, using
// INFISICAL_CLIENT_ID and INFISICAL_CLIENT_SECRET from the job's Gitea secrets,
// and reads the project and host from .infisical.json. Plain Node, no CLI to
// install, so it runs in every job whether or not Bun is set up.
import { readFile } from 'node:fs/promises';
const environment = process.argv[2] ?? 'staging';
const { INFISICAL_CLIENT_ID: clientId, INFISICAL_CLIENT_SECRET: clientSecret } =
process.env;
const fail = (message) => {
console.error(`ci-export-env: ${message}`);
process.exit(1);
};
if (!clientId || !clientSecret)
fail('INFISICAL_CLIENT_ID and INFISICAL_CLIENT_SECRET must be set.');
const { workspaceId, domain } = JSON.parse(
await readFile(new URL('../.infisical.json', import.meta.url), 'utf8'),
);
const request = async (path, init) => {
const response = await fetch(`${domain}${path}`, init);
if (!response.ok)
fail(`${init?.method ?? 'GET'} ${path} returned ${response.status}.`);
return response.json();
};
const { accessToken } = await request('/v1/auth/universal-auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId, clientSecret }),
});
const query = new URLSearchParams({
workspaceId,
environment,
secretPath: '/',
expandSecretReferences: 'true',
include_imports: 'true',
});
const { secrets, imports = [] } = await request(`/v3/secrets/raw?${query}`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
// Imported secrets first so the environment's own values win.
const values = new Map();
for (const { secretKey, secretValue } of [
...imports.flatMap((folder) => folder.secrets),
...secrets,
])
values.set(secretKey, secretValue);
const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
for (const [key, value] of [...values].sort(([a], [b]) => a.localeCompare(b)))
process.stdout.write(`${key}=${quote(value)}\n`);
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Install on a runner, and survive a half-written cache entry.
#
# Runners have failed twice with "Fail extracting tarball" on a different
# package each time, on different machines, and passed on a re-run. The cache
# is shared between jobs on a host, so a job that dies mid-write leaves an
# entry the next job cannot read. Clearing it and installing again costs a
# couple of minutes; a human re-running the job costs however long it takes
# someone to notice.
set -euo pipefail
if bun install --frozen-lockfile; then exit 0; fi
echo "Install failed. Clearing the bun cache and trying once more." >&2
rm -rf "${BUN_INSTALL_CACHE_DIR:-$HOME/.bun/install/cache}"
bun install --frozen-lockfile
+8 -3
View File
@@ -44,9 +44,9 @@ refresh_env
info "Starting local Convex and dashboard" info "Starting local Convex and dashboard"
dc up -d dc up -d
info "Waiting for Convex at http://localhost:${BACKEND_PORT:-3210}" info "Waiting for Convex at http://localhost:${BACKEND_PORT:-3250}"
for i in $(seq 1 60); do for i in $(seq 1 60); do
curl -fs "http://localhost:${BACKEND_PORT:-3210}/version" >/dev/null 2>&1 && break curl -fs "http://localhost:${BACKEND_PORT:-3250}/version" >/dev/null 2>&1 && break
[ "$i" -lt 60 ] || die "Convex did not become ready." [ "$i" -lt 60 ] || die "Convex did not become ready."
sleep 2 sleep 2
done done
@@ -62,6 +62,11 @@ fi
info "Deploying Convex schema and functions" info "Deploying Convex schema and functions"
(cd "$ROOT_DIR/packages/backend" && bun run setup) (cd "$ROOT_DIR/packages/backend" && bun run setup)
# Env sync runs after the deploy: changing deployment env re-analyzes the
# deployed modules, which fails on a fresh volume before the first deploy.
info "Synchronizing the Convex function runtime environment"
sh "$ROOT_DIR/scripts/with-env" dev -- bash "$ROOT_DIR/scripts/sync-local-convex-env"
convex_env_names="$( convex_env_names="$(
sh "$ROOT_DIR/scripts/with-env" dev -- bash -c \ sh "$ROOT_DIR/scripts/with-env" dev -- bash -c \
'cd packages/backend && bunx convex env list' 2>/dev/null \ 'cd packages/backend && bunx convex env list' 2>/dev/null \
@@ -82,4 +87,4 @@ if ! printf '%s\n' "$convex_env_names" | grep -qx 'JWT_PRIVATE_KEY' \
' '
fi fi
printf '\nLocal stack ready:\n App: http://localhost:3000\n Convex: http://localhost:%s\n Dashboard: http://localhost:%s\n' "${BACKEND_PORT:-3210}" "${DASHBOARD_PORT:-6791}" printf '\nLocal stack ready:\n App: http://localhost:3000\n Convex: http://localhost:%s\n Dashboard: http://localhost:%s\n' "${BACKEND_PORT:-3250}" "${DASHBOARD_PORT:-6795}"
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
#
# Kill any lingering host-level dev servers (Next.js, Expo Metro, Convex CLI
# watchers, turbo orchestrators) that survived a Ctrl-C. Does not touch the
# dockerized Convex/Postgres stack — use `bun db:down` for that.
#
# Usage: scripts/dev-kill (wired as `bun dev:kill`)
set -euo pipefail
info() { printf '\033[36m▶ %s\033[0m\n' "$*"; }
ok() { printf '\033[32m✓ %s\033[0m\n' "$*"; }
PORTS=(3000 3001 8081 19000 19001 19002)
PATTERNS=('next-server' 'next dev' 'expo start' 'turbo run dev' 'convex dev')
killed=false
for port in "${PORTS[@]}"; do
pids="$(lsof -ti "tcp:$port" -sTCP:LISTEN 2>/dev/null || true)"
[ -z "$pids" ] && continue
for pid in $pids; do
cmd="$(ps -p "$pid" -o comm= 2>/dev/null || true)"
info "Killing $cmd (pid $pid) on port $port"
kill "$pid" 2>/dev/null || true
killed=true
done
done
for pattern in "${PATTERNS[@]}"; do
pids="$(pgrep -f "$pattern" 2>/dev/null || true)"
[ -z "$pids" ] && continue
for pid in $pids; do
info "Killing '$pattern' (pid $pid)"
kill "$pid" 2>/dev/null || true
killed=true
done
done
if [ "$killed" = true ]; then
sleep 1
ok "Dev servers stopped."
else
ok "No dev servers were running."
fi
+4 -4
View File
@@ -15,8 +15,8 @@ container_running() {
"$RUNTIME" ps --format '{{.Names}}' | grep -qx "$1" "$RUNTIME" ps --format '{{.Names}}' | grep -qx "$1"
} }
if container_running convexmonorepo-local-convex \ if container_running convexmonorepo-base-local-convex \
&& container_running convexmonorepo-local-convex-dashboard; then && container_running convexmonorepo-base-local-convex-dashboard; then
SHOULD_STOP_STACK=false SHOULD_STOP_STACK=false
else else
SHOULD_STOP_STACK=true SHOULD_STOP_STACK=true
@@ -25,8 +25,8 @@ fi
cleanup() { cleanup() {
if [ "$SHOULD_STOP_STACK" = true ]; then if [ "$SHOULD_STOP_STACK" = true ]; then
"$RUNTIME" rm -f \ "$RUNTIME" rm -f \
convexmonorepo-local-convex-dashboard \ convexmonorepo-base-local-convex-dashboard \
convexmonorepo-local-convex \ convexmonorepo-base-local-convex \
>/dev/null 2>&1 || true >/dev/null 2>&1 || true
fi fi
} }
+6
View File
@@ -16,6 +16,12 @@ fi
[ -f "$ROOT_DIR/.infisical.json" ] || { echo "export-env: run 'infisical init' in this repository." >&2; exit 1; } [ -f "$ROOT_DIR/.infisical.json" ] || { echo "export-env: run 'infisical init' in this repository." >&2; exit 1; }
command -v infisical >/dev/null 2>&1 || { echo "export-env: Infisical CLI is required." >&2; exit 1; } command -v infisical >/dev/null 2>&1 || { echo "export-env: Infisical CLI is required." >&2; exit 1; }
if [ -f "$ROOT_DIR/scripts/infisical-profile" ]; then
# shellcheck source=/dev/null
. "$ROOT_DIR/scripts/infisical-profile"
ensure_infisical_profile "$ROOT_DIR/scripts/flags/infisical.env"
fi
(cd "$ROOT_DIR" && infisical export --env="$ENVIRONMENT" --format=dotenv --silent) || { (cd "$ROOT_DIR" && infisical export --env="$ENVIRONMENT" --format=dotenv --silent) || {
echo "export-env: failed to export '$ENVIRONMENT'; check login and project access." >&2 echo "export-env: failed to export '$ENVIRONMENT'; check login and project access." >&2
exit 1 exit 1
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env sh
#
# ensure_infisical_profile <profile_env_file>
#
# Infisical's CLI keeps a single active login (~/.infisical/infisical-config.json)
# shared across every project on the machine. If you juggle multiple Infisical
# accounts (e.g. a client org vs. a personal org), running with-env in one repo
# can silently pull secrets while logged in as the wrong user.
#
# This switches the active `loggedInUserEmail` to the email configured in
# scripts/flags/infisical.env (INFISICAL_EMAIL=...) before infisical runs,
# provided that email is already logged in locally (`infisical login`).
# It is a no-op if the flag file is absent, only one user is logged in, or the
# expected user isn't logged in yet.
#
# POSIX sh, no bashisms: matches the rest of scripts/ which must stay
# busybox-compatible.
warn_infisical_profile() {
echo "Warning: infisical-profile: $*" >&2
}
ensure_infisical_profile() {
profile_env_file="${1:-}"
if [ -z "$profile_env_file" ] || [ ! -f "$profile_env_file" ]; then
return 0
fi
set -a
# shellcheck source=/dev/null
if ! . "$profile_env_file"; then
set +a
warn_infisical_profile "could not read $profile_env_file. Continuing with current Infisical profile."
return 0
fi
set +a
expected_email="${INFISICAL_EMAIL:-}"
if [ -z "$expected_email" ]; then
return 0
fi
config="${INFISICAL_CONFIG_PATH:-$HOME/.infisical/infisical-config.json}"
lock="${INFISICAL_LOCK_PATH:-$HOME/.infisical/.switch.lock}"
if [ ! -f "$config" ]; then
warn_infisical_profile "Infisical config not found at $config. Continuing with current Infisical profile."
return 0
fi
if ! command -v jq >/dev/null 2>&1; then
warn_infisical_profile "jq is required to select Infisical profile. Continuing with current Infisical profile."
return 0
fi
if ! command -v flock >/dev/null 2>&1; then
warn_infisical_profile "flock is required to safely select Infisical profile. Continuing with current Infisical profile."
return 0
fi
if ! mkdir -p "$(dirname "$lock")"; then
warn_infisical_profile "could not create Infisical lock directory. Continuing with current Infisical profile."
return 0
fi
(
if ! flock 9; then
warn_infisical_profile "could not lock Infisical profile config. Continuing with current Infisical profile."
return 0
fi
user_count="$(jq -r '(.loggedInUsers // []) | length' "$config" 2>/dev/null)" || {
warn_infisical_profile "could not parse Infisical config. Continuing with current Infisical profile."
return 0
}
if [ "$user_count" -lt 2 ]; then
return 0
fi
current_email="$(jq -r '.loggedInUserEmail // ""' "$config" 2>/dev/null)" || {
warn_infisical_profile "could not read current Infisical profile. Continuing with current Infisical profile."
return 0
}
if [ "$current_email" = "$expected_email" ]; then
return 0
fi
domain="$(
jq -er --arg email "$expected_email" \
'.loggedInUsers[] | select(.email == $email) | .domain' \
"$config" 2>/dev/null
)" || {
warn_infisical_profile "Infisical profile $expected_email is not logged in locally. Continuing with current Infisical profile."
return 0
}
tmp="$(mktemp)" || {
warn_infisical_profile "could not create temp file for Infisical profile switch. Continuing with current Infisical profile."
return 0
}
if jq --arg email "$expected_email" --arg domain "$domain" \
'.loggedInUserEmail = $email | .LoggedInUserDomain = $domain' \
"$config" > "$tmp"; then
chmod 600 "$tmp"
mv "$tmp" "$config"
else
rm -f "$tmp"
warn_infisical_profile "failed to update Infisical profile. Continuing with current Infisical profile."
fi
) 9>"$lock"
return 0
}
+9
View File
@@ -7,6 +7,15 @@ const __dirname = path.dirname(__filename);
const usesendDir = path.join(__dirname, '..', 'node_modules', 'usesend-js'); const usesendDir = path.join(__dirname, '..', 'node_modules', 'usesend-js');
const ensureReplacement = (content, searchValue, replaceValue, filePath) => { const ensureReplacement = (content, searchValue, replaceValue, filePath) => {
// Removal step (empty replacement): it's already applied once the search
// snippet is gone. Guard on searchValue, not replaceValue — every string
// "includes" the empty string, which would make this a silent no-op.
if (replaceValue === '') {
return content.includes(searchValue)
? content.replace(searchValue, replaceValue)
: content;
}
if (content.includes(replaceValue)) { if (content.includes(replaceValue)) {
return content; return content;
} }
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd)"
VALUE_FILE=""
readonly RUNTIME_ENV_NAMES=(
AUTH_AUTHENTIK_ID
AUTH_AUTHENTIK_SECRET
AUTH_AUTHENTIK_ISSUER
USESEND_API_KEY
USESEND_URL
USESEND_FROM_EMAIL
)
readonly DEPLOYMENT_ENV_NAMES=(
CONVEX_SELF_HOSTED_URL
CONVEX_SELF_HOSTED_ADMIN_KEY
)
die() { printf 'sync-local-convex-env: %s\n' "$*" >&2; exit 1; }
cleanup() {
if [ -n "$VALUE_FILE" ] && [ -f "$VALUE_FILE" ]; then
rm -f "$VALUE_FILE"
fi
}
trap cleanup EXIT INT TERM HUP
for name in "${DEPLOYMENT_ENV_NAMES[@]}" "${RUNTIME_ENV_NAMES[@]}"; do
[ -n "${!name:-}" ] || die "Missing required environment variable: $name"
done
VALUE_FILE="$(mktemp "${TMPDIR:-/tmp}/convex-monorepo-convex-env.value.XXXXXX")"
chmod 600 "$VALUE_FILE"
for name in "${RUNTIME_ENV_NAMES[@]}"; do
printf '%s' "${!name}" > "$VALUE_FILE"
(
cd "$ROOT_DIR/packages/backend"
env -u CONVEX_DEPLOY_KEY -u CONVEX_DEPLOYMENT \
CONVEX_SELF_HOSTED_URL="$CONVEX_SELF_HOSTED_URL" \
CONVEX_SELF_HOSTED_ADMIN_KEY="$CONVEX_SELF_HOSTED_ADMIN_KEY" \
bunx convex env set "$name" --from-file "$VALUE_FILE" >/dev/null
)
done
printf 'Local Convex runtime environment synchronized.\n'
+6 -6
View File
@@ -13,16 +13,16 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@eslint/compat": "^2.0.3", "@eslint/compat": "^2.1.1",
"@eslint/js": "catalog:", "@eslint/js": "catalog:",
"@next/eslint-plugin-next": "^16.2.1", "@next/eslint-plugin-next": "^16.3.8",
"eslint-plugin-import": "^2.32.0", "eslint-plugin-import": "^2.32.0",
"eslint-plugin-jsx-a11y": "^6.10.2", "eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-prefer-arrow-functions": "^3.9.1", "eslint-plugin-prefer-arrow-functions": "^3.10.2",
"eslint-plugin-react": "^7.37.5", "eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-turbo": "^2.8.20", "eslint-plugin-turbo": "^2.11.6",
"typescript-eslint": "^8.57.2" "typescript-eslint": "^8.71.0"
}, },
"devDependencies": { "devDependencies": {
"@gib/prettier-config": "workspace:*", "@gib/prettier-config": "workspace:*",
+1 -1
View File
@@ -13,7 +13,7 @@
"dependencies": { "dependencies": {
"@ianvs/prettier-plugin-sort-imports": "^4.7.1", "@ianvs/prettier-plugin-sort-imports": "^4.7.1",
"prettier": "catalog:", "prettier": "catalog:",
"prettier-plugin-tailwindcss": "^0.7.2" "prettier-plugin-tailwindcss": "^0.7.4"
}, },
"devDependencies": { "devDependencies": {
"@gib/tsconfig": "workspace:*", "@gib/tsconfig": "workspace:*",
+1 -1
View File
@@ -15,7 +15,7 @@
}, },
"dependencies": { "dependencies": {
"@tailwindcss/postcss": "catalog:", "@tailwindcss/postcss": "catalog:",
"postcss": "^8.5.8", "postcss": "^8.5.28",
"tailwindcss": "catalog:" "tailwindcss": "catalog:"
}, },
"devDependencies": { "devDependencies": {
+5 -2
View File
@@ -1,5 +1,5 @@
{ {
"$schema": "https://v2-9-18.turborepo.dev/schema.json", "$schema": "https://v2-11-6.turborepo.dev/schema.json",
"globalDependencies": [".infisical.json", ".local/*.env"], "globalDependencies": [".infisical.json", ".local/*.env"],
"globalEnv": [ "globalEnv": [
"NODE_ENV", "NODE_ENV",
@@ -8,7 +8,9 @@
"SENTRY_DISABLE_AUTO_UPLOAD", "SENTRY_DISABLE_AUTO_UPLOAD",
"NEXT_PUBLIC_SITE_URL", "NEXT_PUBLIC_SITE_URL",
"NEXT_PUBLIC_CONVEX_URL", "NEXT_PUBLIC_CONVEX_URL",
"NEXT_PUBLIC_PLAUSIBLE_URL", "NEXT_PUBLIC_PLAUSIBLE_SRC",
"NEXT_PUBLIC_POSTHOG_KEY",
"NEXT_PUBLIC_POSTHOG_HOST",
"NEXT_PUBLIC_SENTRY_DSN", "NEXT_PUBLIC_SENTRY_DSN",
"NEXT_PUBLIC_SENTRY_URL", "NEXT_PUBLIC_SENTRY_URL",
"NEXT_PUBLIC_SENTRY_ORG", "NEXT_PUBLIC_SENTRY_ORG",
@@ -47,6 +49,7 @@
], ],
"globalPassThroughEnv": ["NODE_ENV"], "globalPassThroughEnv": ["NODE_ENV"],
"ui": "tui", "ui": "tui",
"agentGuidance": false,
"tasks": { "tasks": {
"topo": { "topo": {
"dependsOn": ["^topo"] "dependsOn": ["^topo"]