From 0e87da18e2cde63bc7ab2700b580b29794050bf3 Mon Sep 17 00:00:00 2001 From: Turbobot Date: Sat, 30 Dec 2023 15:41:23 +0000 Subject: [PATCH 001/234] feat(create-turbo): apply pnpm-eslint transform --- .env | 15 + .eslintrc.json | 8 - .github/FUNDING.yml | 1 - .gitignore | 41 - my-turborepo/.env.example | 24 + my-turborepo/.github/FUNDING.yml | 3 + .../.github/ISSUE_TEMPLATE/bug_report.yml | 37 + .../ISSUE_TEMPLATE/feature_request.yml | 28 + my-turborepo/.github/renovate.json | 13 + my-turborepo/.github/workflows/ci.yml | 57 + my-turborepo/.gitignore | 50 + my-turborepo/.npmrc | 5 + my-turborepo/.nvmrc | 1 + my-turborepo/.vscode/extensions.json | 9 + my-turborepo/.vscode/launch.json | 13 + my-turborepo/.vscode/settings.json | 7 + my-turborepo/LICENSE | 21 + my-turborepo/README.md | 245 + my-turborepo/apps/auth-proxy/.env.example | 7 + my-turborepo/apps/auth-proxy/README.md | 16 + my-turborepo/apps/auth-proxy/package.json | 33 + .../apps/auth-proxy/routes/[...auth].ts | 17 + my-turborepo/apps/auth-proxy/tsconfig.json | 4 + .../apps/expo/.expo-shared/assets.json | 4 + my-turborepo/apps/expo/app.config.ts | 43 + my-turborepo/apps/expo/assets/icon.png | Bin 0 -> 10788 bytes my-turborepo/apps/expo/babel.config.js | 15 + my-turborepo/apps/expo/eas.json | 31 + .../expo/expo-plugins/with-modify-gradle.js | 44 + my-turborepo/apps/expo/metro.config.js | 29 + my-turborepo/apps/expo/package.json | 68 + my-turborepo/apps/expo/src/app/_layout.tsx | 27 + my-turborepo/apps/expo/src/app/index.tsx | 145 + my-turborepo/apps/expo/src/app/post/[id].tsx | 22 + my-turborepo/apps/expo/src/styles.css | 3 + .../apps/expo/src/types/nativewind-env.d.ts | 1 + my-turborepo/apps/expo/src/utils/api.tsx | 76 + my-turborepo/apps/expo/tailwind.config.ts | 10 + my-turborepo/apps/expo/tsconfig.json | 21 + my-turborepo/apps/nextjs/README.md | 28 + my-turborepo/apps/nextjs/next.config.js | 23 + my-turborepo/apps/nextjs/package.json | 60 + .../apps/nextjs/postcss.config.cjs | 2 +- my-turborepo/apps/nextjs/public/favicon.ico | Bin 0 -> 103027 bytes my-turborepo/apps/nextjs/public/t3-icon.svg | 13 + .../src/app/_components/auth-showcase.tsx | 42 + .../apps/nextjs/src/app/_components/posts.tsx | 168 + .../src/app/api/auth/[...nextauth]/route.ts | 3 + .../nextjs/src/app/api/trpc/[trpc]/route.ts | 46 + my-turborepo/apps/nextjs/src/app/globals.css | 50 + my-turborepo/apps/nextjs/src/app/layout.tsx | 68 + my-turborepo/apps/nextjs/src/app/page.tsx | 45 + my-turborepo/apps/nextjs/src/env.js | 50 + my-turborepo/apps/nextjs/src/trpc/react.tsx | 53 + my-turborepo/apps/nextjs/src/trpc/server.ts | 61 + my-turborepo/apps/nextjs/tailwind.config.ts | 19 + my-turborepo/apps/nextjs/tsconfig.json | 13 + my-turborepo/package.json | 31 + my-turborepo/packages/api/package.json | 40 + my-turborepo/packages/api/src/index.ts | 18 + my-turborepo/packages/api/src/root.ts | 11 + my-turborepo/packages/api/src/router/auth.ts | 11 + my-turborepo/packages/api/src/router/post.ts | 39 + my-turborepo/packages/api/src/trpc.ts | 101 + my-turborepo/packages/api/tsconfig.json | 8 + my-turborepo/packages/auth/env.js | 28 + my-turborepo/packages/auth/package.json | 42 + my-turborepo/packages/auth/src/index.ts | 35 + my-turborepo/packages/auth/tsconfig.json | 8 + my-turborepo/packages/db/drizzle.config.ts | 23 + my-turborepo/packages/db/package.json | 39 + my-turborepo/packages/db/src/index.ts | 19 + my-turborepo/packages/db/src/schema/_table.ts | 9 + my-turborepo/packages/db/src/schema/auth.ts | 83 + my-turborepo/packages/db/src/schema/post.ts | 14 + my-turborepo/packages/db/tsconfig.json | 8 + my-turborepo/packages/ui/package.json | 57 + my-turborepo/packages/ui/src/button.tsx | 58 + .../packages/ui/src/dropdown-menu.tsx | 200 + my-turborepo/packages/ui/src/form.tsx | 201 + my-turborepo/packages/ui/src/index.ts | 9 + my-turborepo/packages/ui/src/input.tsx | 24 + my-turborepo/packages/ui/src/label.tsx | 25 + my-turborepo/packages/ui/src/theme.tsx | 42 + my-turborepo/packages/ui/src/toast.tsx | 31 + my-turborepo/packages/ui/tailwind.config.ts | 12 + my-turborepo/packages/ui/tsconfig.json | 8 + my-turborepo/packages/validators/package.json | 33 + my-turborepo/packages/validators/src/index.ts | 6 + .../packages/validators/tsconfig.json | 8 + my-turborepo/pnpm-lock.yaml | 14686 ++++++++++++++++ my-turborepo/pnpm-workspace.yaml | 4 + my-turborepo/tooling/eslint/base.js | 44 + my-turborepo/tooling/eslint/nextjs.js | 10 + my-turborepo/tooling/eslint/package.json | 43 + my-turborepo/tooling/eslint/react.js | 24 + my-turborepo/tooling/eslint/tsconfig.json | 8 + my-turborepo/tooling/github/package.json | 3 + my-turborepo/tooling/github/setup/action.yml | 17 + my-turborepo/tooling/prettier/index.js | 36 + my-turborepo/tooling/prettier/package.json | 24 + my-turborepo/tooling/prettier/tsconfig.json | 8 + my-turborepo/tooling/tailwind/index.ts | 76 + my-turborepo/tooling/tailwind/package.json | 37 + my-turborepo/tooling/tailwind/tsconfig.json | 8 + my-turborepo/tooling/typescript/base.json | 21 + my-turborepo/tooling/typescript/package.json | 8 + my-turborepo/turbo.json | 50 + my-turborepo/turbo/generators/config.ts | 90 + .../generators/templates/package.json.hbs | 30 + .../generators/templates/tsconfig.json.hbs | 8 + my-turborepo/vercel.json | 5 + next-env.d.ts | 5 - next-seo.config.ts | 58 - next.config.mjs | 22 - package.json | 60 - prettier.config.cjs | 4 - prisma/schema.prisma | 66 - public/fonts/inter.woff2 | Bin 105924 -> 0 bytes public/img/apple-touch-icon-114x114.png | Bin 5948 -> 0 bytes public/img/apple-touch-icon-152x152.png | Bin 9948 -> 0 bytes public/img/apple-touch-icon-180x180.png | Bin 13737 -> 0 bytes public/img/banner.jpg | Bin 360034 -> 0 bytes public/img/banner_gh.jpg | Bin 34129 -> 0 bytes public/img/favicon.ico | Bin 21038 -> 0 bytes public/img/icon-192x192.png | Bin 14816 -> 0 bytes public/img/icon-256x256.png | Bin 24397 -> 0 bytes public/img/icon-384x384.png | Bin 53593 -> 0 bytes public/img/icon-512x512.png | Bin 103358 -> 0 bytes public/img/logo.png | Bin 125023 -> 0 bytes public/img/logo_flat.png | Bin 24099 -> 0 bytes public/manifest.json | 32 - src/components/auth/index.tsx | 81 - src/components/card/index.tsx | 113 - src/components/card/interface.ts | 7 - src/components/command/index.tsx | 110 - src/components/footer/index.tsx | 26 - src/components/functions/create/index.tsx | 141 - src/components/functions/delete/index.tsx | 105 - src/components/functions/edit/index.tsx | 116 - src/components/header/index.tsx | 33 - src/components/icons/logo.tsx | 21 - src/components/link/index.tsx | 17 - src/env/client.mjs | 38 - src/env/schema.mjs | 43 - src/env/server.mjs | 30 - src/layout/dashboard.tsx | 27 - src/layout/index.tsx | 18 - src/middleware.ts | 26 - src/motions/loader.tsx | 15 - src/motions/show.tsx | 28 - src/motions/up.tsx | 22 - src/pages/_app.tsx | 55 - src/pages/_document.tsx | 15 - src/pages/api/auth/[...nextauth].ts | 39 - src/pages/api/query/getLinks.ts | 41 - src/pages/api/query/index.ts | 44 - src/pages/api/trpc/[trpc].ts | 16 - src/pages/api/url/[slug].ts | 31 - src/pages/auth/index.tsx | 67 - src/pages/dash/create.tsx | 32 - src/pages/dash/index.tsx | 127 - src/pages/index.tsx | 41 - src/schema/link.schema.ts | 34 - src/server/common/get-server-auth-session.ts | 13 - src/server/db/client.ts | 18 - src/server/router/auth.ts | 10 - src/server/router/context.ts | 44 - src/server/router/index.ts | 11 - src/server/router/links.router.ts | 88 - src/server/router/trpc.ts | 39 - src/styles/globals.css | 11 - src/styles/toast.ts | 5 - src/types/next-auth.d.ts | 23 - src/ui/alert.tsx | 23 - src/ui/button.tsx | 46 - src/ui/dropdown.tsx | 56 - src/ui/iconButton.tsx | 20 - src/ui/index.ts | 3 - src/ui/input.tsx | 14 - src/ui/linkRoute.tsx | 22 - src/ui/modal.tsx | 58 - src/ui/textarea.tsx | 26 - src/utils/trpc.ts | 42 - tailwind.config.cjs | 20 - tsconfig.json | 25 - 186 files changed, 18408 insertions(+), 2474 deletions(-) create mode 100644 .env delete mode 100644 .eslintrc.json delete mode 100644 .github/FUNDING.yml delete mode 100644 .gitignore create mode 100644 my-turborepo/.env.example create mode 100644 my-turborepo/.github/FUNDING.yml create mode 100644 my-turborepo/.github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 my-turborepo/.github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 my-turborepo/.github/renovate.json create mode 100644 my-turborepo/.github/workflows/ci.yml create mode 100644 my-turborepo/.gitignore create mode 100644 my-turborepo/.npmrc create mode 100644 my-turborepo/.nvmrc create mode 100644 my-turborepo/.vscode/extensions.json create mode 100644 my-turborepo/.vscode/launch.json create mode 100644 my-turborepo/.vscode/settings.json create mode 100644 my-turborepo/LICENSE create mode 100644 my-turborepo/README.md create mode 100644 my-turborepo/apps/auth-proxy/.env.example create mode 100644 my-turborepo/apps/auth-proxy/README.md create mode 100644 my-turborepo/apps/auth-proxy/package.json create mode 100644 my-turborepo/apps/auth-proxy/routes/[...auth].ts create mode 100644 my-turborepo/apps/auth-proxy/tsconfig.json create mode 100644 my-turborepo/apps/expo/.expo-shared/assets.json create mode 100644 my-turborepo/apps/expo/app.config.ts create mode 100644 my-turborepo/apps/expo/assets/icon.png create mode 100644 my-turborepo/apps/expo/babel.config.js create mode 100644 my-turborepo/apps/expo/eas.json create mode 100644 my-turborepo/apps/expo/expo-plugins/with-modify-gradle.js create mode 100644 my-turborepo/apps/expo/metro.config.js create mode 100644 my-turborepo/apps/expo/package.json create mode 100644 my-turborepo/apps/expo/src/app/_layout.tsx create mode 100644 my-turborepo/apps/expo/src/app/index.tsx create mode 100644 my-turborepo/apps/expo/src/app/post/[id].tsx create mode 100644 my-turborepo/apps/expo/src/styles.css create mode 100644 my-turborepo/apps/expo/src/types/nativewind-env.d.ts create mode 100644 my-turborepo/apps/expo/src/utils/api.tsx create mode 100644 my-turborepo/apps/expo/tailwind.config.ts create mode 100644 my-turborepo/apps/expo/tsconfig.json create mode 100644 my-turborepo/apps/nextjs/README.md create mode 100644 my-turborepo/apps/nextjs/next.config.js create mode 100644 my-turborepo/apps/nextjs/package.json rename postcss.config.cjs => my-turborepo/apps/nextjs/postcss.config.cjs (96%) create mode 100644 my-turborepo/apps/nextjs/public/favicon.ico create mode 100644 my-turborepo/apps/nextjs/public/t3-icon.svg create mode 100644 my-turborepo/apps/nextjs/src/app/_components/auth-showcase.tsx create mode 100644 my-turborepo/apps/nextjs/src/app/_components/posts.tsx create mode 100644 my-turborepo/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts create mode 100644 my-turborepo/apps/nextjs/src/app/api/trpc/[trpc]/route.ts create mode 100644 my-turborepo/apps/nextjs/src/app/globals.css create mode 100644 my-turborepo/apps/nextjs/src/app/layout.tsx create mode 100644 my-turborepo/apps/nextjs/src/app/page.tsx create mode 100644 my-turborepo/apps/nextjs/src/env.js create mode 100644 my-turborepo/apps/nextjs/src/trpc/react.tsx create mode 100644 my-turborepo/apps/nextjs/src/trpc/server.ts create mode 100644 my-turborepo/apps/nextjs/tailwind.config.ts create mode 100644 my-turborepo/apps/nextjs/tsconfig.json create mode 100644 my-turborepo/package.json create mode 100644 my-turborepo/packages/api/package.json create mode 100644 my-turborepo/packages/api/src/index.ts create mode 100644 my-turborepo/packages/api/src/root.ts create mode 100644 my-turborepo/packages/api/src/router/auth.ts create mode 100644 my-turborepo/packages/api/src/router/post.ts create mode 100644 my-turborepo/packages/api/src/trpc.ts create mode 100644 my-turborepo/packages/api/tsconfig.json create mode 100644 my-turborepo/packages/auth/env.js create mode 100644 my-turborepo/packages/auth/package.json create mode 100644 my-turborepo/packages/auth/src/index.ts create mode 100644 my-turborepo/packages/auth/tsconfig.json create mode 100644 my-turborepo/packages/db/drizzle.config.ts create mode 100644 my-turborepo/packages/db/package.json create mode 100644 my-turborepo/packages/db/src/index.ts create mode 100644 my-turborepo/packages/db/src/schema/_table.ts create mode 100644 my-turborepo/packages/db/src/schema/auth.ts create mode 100644 my-turborepo/packages/db/src/schema/post.ts create mode 100644 my-turborepo/packages/db/tsconfig.json create mode 100644 my-turborepo/packages/ui/package.json create mode 100644 my-turborepo/packages/ui/src/button.tsx create mode 100644 my-turborepo/packages/ui/src/dropdown-menu.tsx create mode 100644 my-turborepo/packages/ui/src/form.tsx create mode 100644 my-turborepo/packages/ui/src/index.ts create mode 100644 my-turborepo/packages/ui/src/input.tsx create mode 100644 my-turborepo/packages/ui/src/label.tsx create mode 100644 my-turborepo/packages/ui/src/theme.tsx create mode 100644 my-turborepo/packages/ui/src/toast.tsx create mode 100644 my-turborepo/packages/ui/tailwind.config.ts create mode 100644 my-turborepo/packages/ui/tsconfig.json create mode 100644 my-turborepo/packages/validators/package.json create mode 100644 my-turborepo/packages/validators/src/index.ts create mode 100644 my-turborepo/packages/validators/tsconfig.json create mode 100644 my-turborepo/pnpm-lock.yaml create mode 100644 my-turborepo/pnpm-workspace.yaml create mode 100644 my-turborepo/tooling/eslint/base.js create mode 100644 my-turborepo/tooling/eslint/nextjs.js create mode 100644 my-turborepo/tooling/eslint/package.json create mode 100644 my-turborepo/tooling/eslint/react.js create mode 100644 my-turborepo/tooling/eslint/tsconfig.json create mode 100644 my-turborepo/tooling/github/package.json create mode 100644 my-turborepo/tooling/github/setup/action.yml create mode 100644 my-turborepo/tooling/prettier/index.js create mode 100644 my-turborepo/tooling/prettier/package.json create mode 100644 my-turborepo/tooling/prettier/tsconfig.json create mode 100644 my-turborepo/tooling/tailwind/index.ts create mode 100644 my-turborepo/tooling/tailwind/package.json create mode 100644 my-turborepo/tooling/tailwind/tsconfig.json create mode 100644 my-turborepo/tooling/typescript/base.json create mode 100644 my-turborepo/tooling/typescript/package.json create mode 100644 my-turborepo/turbo.json create mode 100644 my-turborepo/turbo/generators/config.ts create mode 100644 my-turborepo/turbo/generators/templates/package.json.hbs create mode 100644 my-turborepo/turbo/generators/templates/tsconfig.json.hbs create mode 100644 my-turborepo/vercel.json delete mode 100644 next-env.d.ts delete mode 100644 next-seo.config.ts delete mode 100644 next.config.mjs delete mode 100644 package.json delete mode 100644 prettier.config.cjs delete mode 100644 prisma/schema.prisma delete mode 100644 public/fonts/inter.woff2 delete mode 100644 public/img/apple-touch-icon-114x114.png delete mode 100644 public/img/apple-touch-icon-152x152.png delete mode 100644 public/img/apple-touch-icon-180x180.png delete mode 100644 public/img/banner.jpg delete mode 100644 public/img/banner_gh.jpg delete mode 100644 public/img/favicon.ico delete mode 100644 public/img/icon-192x192.png delete mode 100644 public/img/icon-256x256.png delete mode 100644 public/img/icon-384x384.png delete mode 100644 public/img/icon-512x512.png delete mode 100644 public/img/logo.png delete mode 100644 public/img/logo_flat.png delete mode 100644 public/manifest.json delete mode 100644 src/components/auth/index.tsx delete mode 100644 src/components/card/index.tsx delete mode 100644 src/components/card/interface.ts delete mode 100644 src/components/command/index.tsx delete mode 100644 src/components/footer/index.tsx delete mode 100644 src/components/functions/create/index.tsx delete mode 100644 src/components/functions/delete/index.tsx delete mode 100644 src/components/functions/edit/index.tsx delete mode 100644 src/components/header/index.tsx delete mode 100644 src/components/icons/logo.tsx delete mode 100644 src/components/link/index.tsx delete mode 100644 src/env/client.mjs delete mode 100644 src/env/schema.mjs delete mode 100644 src/env/server.mjs delete mode 100644 src/layout/dashboard.tsx delete mode 100644 src/layout/index.tsx delete mode 100644 src/middleware.ts delete mode 100644 src/motions/loader.tsx delete mode 100644 src/motions/show.tsx delete mode 100644 src/motions/up.tsx delete mode 100644 src/pages/_app.tsx delete mode 100644 src/pages/_document.tsx delete mode 100644 src/pages/api/auth/[...nextauth].ts delete mode 100644 src/pages/api/query/getLinks.ts delete mode 100644 src/pages/api/query/index.ts delete mode 100644 src/pages/api/trpc/[trpc].ts delete mode 100644 src/pages/api/url/[slug].ts delete mode 100644 src/pages/auth/index.tsx delete mode 100644 src/pages/dash/create.tsx delete mode 100644 src/pages/dash/index.tsx delete mode 100644 src/pages/index.tsx delete mode 100644 src/schema/link.schema.ts delete mode 100644 src/server/common/get-server-auth-session.ts delete mode 100644 src/server/db/client.ts delete mode 100644 src/server/router/auth.ts delete mode 100644 src/server/router/context.ts delete mode 100644 src/server/router/index.ts delete mode 100644 src/server/router/links.router.ts delete mode 100644 src/server/router/trpc.ts delete mode 100644 src/styles/globals.css delete mode 100644 src/styles/toast.ts delete mode 100644 src/types/next-auth.d.ts delete mode 100644 src/ui/alert.tsx delete mode 100644 src/ui/button.tsx delete mode 100644 src/ui/dropdown.tsx delete mode 100644 src/ui/iconButton.tsx delete mode 100644 src/ui/index.ts delete mode 100644 src/ui/input.tsx delete mode 100644 src/ui/linkRoute.tsx delete mode 100644 src/ui/modal.tsx delete mode 100644 src/ui/textarea.tsx delete mode 100644 src/utils/trpc.ts delete mode 100644 tailwind.config.cjs delete mode 100644 tsconfig.json diff --git a/.env b/.env new file mode 100644 index 0000000..ddc5451 --- /dev/null +++ b/.env @@ -0,0 +1,15 @@ +# Planetscale DB Url for Prisma => +DATABASE_URL='mysql://i0l1epmp0r1kpfmridc8:pscale_pw_VLQI4mDdN7sbLmzZglcoifYWIiP1xcaV0MsOSk76yxH@aws.connect.psdb.cloud/urll?sslaccept=strict' + +# Next Auth => +NEXTAUTH_SECRET=123nextauthsecret +NEXTAUTH_URL=http://localhost:3000 + +# Next Auth Github Provider => +GITHUB_ID=12343ba2db8cc5d42220 +GITHUB_CLIENT_SECRET=379b0432d5e4e60b9da7d697f0f5f9c0cab572b6 + +# ------------------- # +# Production -> DATABASE_URL='mysql://i0l1epmp0r1kpfmridc8:pscale_pw_VLQI4mDdN7sbLmzZglcoifYWIiP1xcaV0MsOSk76yxH@aws.connect.psdb.cloud/urll?sslaccept=strict' +# Devpreview -> DATABASE_URL='mysql://vqutbquv7btz92ncgfiv:pscale_pw_UdEUjE2om5Wusfx1DJYIirfh0qGjEUED9lNCR6GE0o2@aws.connect.psdb.cloud/urll?sslaccept=strict' +# ------------------- # \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 1cd4470..0000000 --- a/.eslintrc.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "parser": "@typescript-eslint/parser", - "parserOptions": { - "project": "./tsconfig.json" - }, - "plugins": ["@typescript-eslint"], - "extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"] -} diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index fa8557b..0000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1 +0,0 @@ -github: pheralb diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 48034dc..0000000 --- a/.gitignore +++ /dev/null @@ -1,41 +0,0 @@ -# Dependencies => -/node_modules -/.pnp -.pnp.js -package-lock.json -yarn.lock -pnpm-lock.json - -# Testing => -/coverage - -# Database => -/prisma/db.sqlite -/prisma/db.sqlite-journal - -# Next.js => -/.next/ -/out/ - -# Production => -/build - -# Misc => -.DS_Store -*.pem - -# Debug => -npm-debug.log* -yarn-debug.log* -yarn-error.log* -.pnpm-debug.log* - -# Local env files => -.env -.env*.local - -# Vercel => -.vercel - -# Typescript => -*.tsbuildinfo diff --git a/my-turborepo/.env.example b/my-turborepo/.env.example new file mode 100644 index 0000000..2ee83ee --- /dev/null +++ b/my-turborepo/.env.example @@ -0,0 +1,24 @@ +# Since .env is gitignored, you can use .env.example to build a new `.env` file when you clone the repo. +# Keep this file up-to-date when you add new variables to \`.env\`. + +# This file will be committed to version control, so make sure not to have any secrets in it. +# If you are cloning this repo, create a copy of this file named `.env` and populate it with your secrets. + +# The database URL is used to connect to your PlanetScale database. +DB_HOST='aws.connect.psdb.cloud' +DB_NAME='YOUR_DB_NAME' +DB_USERNAME='' +DB_PASSWORD='pscale_pw_' + +# @see https://next-auth.js.org/configuration/options#nextauth_url +AUTH_URL='http://localhost:3000' +AUTH_REDIRECT_PROXY_URL="http://localhost:3001/api" + +# You can generate the secret via 'openssl rand -base64 32' on Unix +# @see https://next-auth.js.org/configuration/options#secret +AUTH_SECRET='supersecret' + +# Preconfigured Discord OAuth provider, works out-of-the-box +# @see https://next-auth.js.org/providers/discord +AUTH_DISCORD_ID='' +AUTH_DISCORD_SECRET='' diff --git a/my-turborepo/.github/FUNDING.yml b/my-turborepo/.github/FUNDING.yml new file mode 100644 index 0000000..043f0f9 --- /dev/null +++ b/my-turborepo/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: juliusmarminge diff --git a/my-turborepo/.github/ISSUE_TEMPLATE/bug_report.yml b/my-turborepo/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..54199a8 --- /dev/null +++ b/my-turborepo/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,37 @@ +name: 🐞 Bug Report +description: Create a bug report to help us improve +title: "bug: " +labels: ["🐞❔ unconfirmed bug"] +body: + - type: textarea + attributes: + label: Provide environment information + description: | + Run this command in your project root and paste the results in a code block: + ```bash + npx envinfo --system --binaries + ``` + validations: + required: true + - type: textarea + attributes: + label: Describe the bug + description: A clear and concise description of the bug, as well as what you expected to happen when encountering it. + validations: + required: true + - type: input + attributes: + label: Link to reproduction + description: Please provide a link to a reproduction of the bug. Issues without a reproduction repo may be ignored. + validations: + required: true + - type: textarea + attributes: + label: To reproduce + description: Describe how to reproduce your bug. Steps, code snippets, reproduction repos etc. + validations: + required: true + - type: textarea + attributes: + label: Additional information + description: Add any other information related to the bug here, screenshots if applicable. diff --git a/my-turborepo/.github/ISSUE_TEMPLATE/feature_request.yml b/my-turborepo/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..44f8843 --- /dev/null +++ b/my-turborepo/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,28 @@ +# This template is heavily inspired by the Next.js's template: +# See here: https://github.com/vercel/next.js/tree/canary/.github/ISSUE_TEMPLATE + +name: 🛠 Feature Request +description: Create a feature request for the core packages +title: "feat: " +labels: ["✨ enhancement"] +body: + - type: markdown + attributes: + value: | + Thank you for taking the time to file a feature request. Please fill out this form as completely as possible. + - type: textarea + attributes: + label: Describe the feature you'd like to request + description: Please describe the feature as clear and concise as possible. Remember to add context as to why you believe this feature is needed. + validations: + required: true + - type: textarea + attributes: + label: Describe the solution you'd like to see + description: Please describe the solution you would like to see. Adding example usage is a good way to provide context. + validations: + required: true + - type: textarea + attributes: + label: Additional information + description: Add any other information related to the feature here. If your feature request is related to any issues or discussions, link them here. diff --git a/my-turborepo/.github/renovate.json b/my-turborepo/.github/renovate.json new file mode 100644 index 0000000..77555b1 --- /dev/null +++ b/my-turborepo/.github/renovate.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["config:base"], + "packageRules": [ + { + "matchPackagePatterns": ["^@acme/"], + "enabled": false + } + ], + "updateInternalDeps": true, + "rangeStrategy": "bump", + "automerge": true +} diff --git a/my-turborepo/.github/workflows/ci.yml b/my-turborepo/.github/workflows/ci.yml new file mode 100644 index 0000000..d0b20b7 --- /dev/null +++ b/my-turborepo/.github/workflows/ci.yml @@ -0,0 +1,57 @@ +name: CI + +on: + pull_request: + branches: ["*"] + push: + branches: ["main"] + merge_group: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/master' }} + +# You can leverage Vercel Remote Caching with Turbo to speed up your builds +# @link https://turborepo.org/docs/core-concepts/remote-caching#remote-caching-on-vercel-builds +env: + FORCE_COLOR: 3 + TURBO_TEAM: ${{ vars.TURBO_TEAM }} + TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup + uses: ./tooling/github/setup + + - name: Copy env + shell: bash + run: cp .env.example .env + + - name: Lint + run: pnpm lint && pnpm lint:ws + + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup + uses: ./tooling/github/setup + + - name: Format + run: pnpm format + + typecheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup + uses: ./tooling/github/setup + + - name: Typecheck + run: pnpm typecheck diff --git a/my-turborepo/.gitignore b/my-turborepo/.gitignore new file mode 100644 index 0000000..1e7a76d --- /dev/null +++ b/my-turborepo/.gitignore @@ -0,0 +1,50 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +node_modules +.pnp +.pnp.js + +# testing +coverage + +# next.js +.next/ +out/ +next-env.d.ts + +# nitro +.nitro/ +.output/ + +# expo +.expo/ +dist/ +expo-env.d.ts +apps/expo/.gitignore + +# production +build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +.env +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo + +# turbo +.turbo diff --git a/my-turborepo/.npmrc b/my-turborepo/.npmrc new file mode 100644 index 0000000..cfcb8e3 --- /dev/null +++ b/my-turborepo/.npmrc @@ -0,0 +1,5 @@ +# Expo doesn't play nice with pnpm by default. +# The symbolic links of pnpm break the rules of Expo monorepos. +# @link https://docs.expo.dev/guides/monorepos/#common-issues +node-linker=hoisted +strict-peer-dependencies=false diff --git a/my-turborepo/.nvmrc b/my-turborepo/.nvmrc new file mode 100644 index 0000000..89e0c3d --- /dev/null +++ b/my-turborepo/.nvmrc @@ -0,0 +1 @@ +20.10 \ No newline at end of file diff --git a/my-turborepo/.vscode/extensions.json b/my-turborepo/.vscode/extensions.json new file mode 100644 index 0000000..3606d87 --- /dev/null +++ b/my-turborepo/.vscode/extensions.json @@ -0,0 +1,9 @@ +{ + "recommendations": [ + "dbaeumer.vscode-eslint", + "expo.vscode-expo-tools", + "esbenp.prettier-vscode", + "yoavbls.pretty-ts-errors", + "bradlc.vscode-tailwindcss" + ] +} diff --git a/my-turborepo/.vscode/launch.json b/my-turborepo/.vscode/launch.json new file mode 100644 index 0000000..5fcd845 --- /dev/null +++ b/my-turborepo/.vscode/launch.json @@ -0,0 +1,13 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Next.js", + "type": "node-terminal", + "request": "launch", + "command": "pnpm dev", + "cwd": "${workspaceFolder}/apps/nextjs/", + "skipFiles": ["/**"] + } + ] +} diff --git a/my-turborepo/.vscode/settings.json b/my-turborepo/.vscode/settings.json new file mode 100644 index 0000000..44a73ec --- /dev/null +++ b/my-turborepo/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "eslint.workingDirectories": [ + { + "mode": "auto" + } + ] +} diff --git a/my-turborepo/LICENSE b/my-turborepo/LICENSE new file mode 100644 index 0000000..435503e --- /dev/null +++ b/my-turborepo/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Julius Marminge + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/my-turborepo/README.md b/my-turborepo/README.md new file mode 100644 index 0000000..46bac53 --- /dev/null +++ b/my-turborepo/README.md @@ -0,0 +1,245 @@ +# create-t3-turbo + +> **Note** +> Due to high demand, this repo now uses the `app` directory with some new experimental features. If you want to use the more traditional `pages` router, [check out the repo before the update](https://github.com/t3-oss/create-t3-turbo/tree/414aff131ca124573e721f3779df3edb64989fd4). + +> **Note** +> OAuth deployments are now working for preview deployments. Read [deployment guide](https://github.com/t3-oss/create-t3-turbo#auth-proxy) and [check out the source](./apps/auth-proxy) to learn more! + +## Installation + +There are two ways of initializing an app using the `create-t3-turbo` starter. You can either use this repository as a template: + +![use-as-template](https://github.com/t3-oss/create-t3-turbo/assets/51714798/bb6c2e5d-d8b6-416e-aeb3-b3e50e2ca994) + +or use Turbo's CLI to init your project (use PNPM as package manager): + +```bash +npx create-turbo@latest -e https://github.com/t3-oss/create-t3-turbo +``` + +## About + +Ever wondered how to migrate your T3 application into a monorepo? Stop right here! This is the perfect starter repo to get you running with the perfect stack! + +It uses [Turborepo](https://turborepo.org) and contains: + +```text +.github + └─ workflows + └─ CI with pnpm cache setup +.vscode + └─ Recommended extensions and settings for VSCode users +apps + ├─ auth-proxy + | ├─ Nitro server to proxy OAuth requests in preview deployments + | └─ Uses Auth.js Core + ├─ expo + | ├─ Expo SDK 49 + | ├─ React Native using React 18 + | ├─ Navigation using Expo Router + | ├─ Tailwind using Nativewind + | └─ Typesafe API calls using tRPC + └─ next.js + ├─ Next.js 14 + ├─ React 18 + ├─ Tailwind CSS + └─ E2E Typesafe API Server & Client +packages + ├─ api + | └─ tRPC v10 router definition + ├─ auth + | └─ Authentication using next-auth. **NOTE: Only for Next.js app, not Expo** + └─ db + └─ Typesafe db calls using Drizzle & Planetscale +tooling + ├─ eslint + | └─ shared, fine-grained, eslint presets + ├─ prettier + | └─ shared prettier configuration + ├─ tailwind + | └─ shared tailwind configuration + └─ typescript + └─ shared tsconfig you can extend from +``` + +> In this template, we use `@acme` as a placeholder for package names. As a user, you might want to replace it with your own organization or project name. You can use find-and-replace to change all the instances of `@acme` to something like `@my-company` or `@project-name`. + +## Quick Start + +> **Note** +> The [db](./packages/db) package is preconfigured to use PlanetScale and is **edge-bound** with the [database.js](https://github.com/planetscale/database-js) driver. If you're using something else, make the necesary modifications to the [schema](./packages/db/schema) as well as the [client](./packages/db/index.ts) and the [drizzle config](./packages/db/drizzle.config.ts). If you want to switch to non-edge database driver, remove `export const runtime = "edge";` [from all pages and api routes](https://github.com/t3-oss/create-t3-turbo/issues/634#issuecomment-1730240214). + +To get it running, follow the steps below: + +### 1. Setup dependencies + +```bash +# Install dependencies +pnpm i + +# Configure environment variables +# There is an `.env.example` in the root directory you can use for reference +cp .env.example .env + +# Push the Drizzle schema to the database +pnpm db:push +``` + +### 2. Configure Expo `dev`-script + +#### Use iOS Simulator + +1. Make sure you have XCode and XCommand Line Tools installed [as shown on expo docs](https://docs.expo.dev/workflow/ios-simulator). + + > **NOTE:** If you just installed XCode, or if you have updated it, you need to open the simulator manually once. Run `npx expo start` in the root dir, and then enter `I` to launch Expo Go. After the manual launch, you can run `pnpm dev` in the root directory. + + ```diff + + "dev": "expo start --ios", + ``` + +2. Run `pnpm dev` at the project root folder. + +#### Use Android Emulator + +1. Install Android Studio tools [as shown on expo docs](https://docs.expo.dev/workflow/android-studio-emulator). + +2. Change the `dev` script at `apps/expo/package.json` to open the Android emulator. + + ```diff + + "dev": "expo start --android", + ``` + +3. Run `pnpm dev` at the project root folder. + +> **TIP:** It might be easier to run each app in separate terminal windows so you get the logs from each app separately. This is also required if you want your terminals to be interactive, e.g. to access the Expo QR code. You can run `pnpm --filter expo dev` and `pnpm --filter nextjs dev` to run each app in a separate terminal window. + +### 3. When it's time to add a new package + +To add a new package, simply run `pnpm turbo gen init` in the monorepo root. This will prompt you for a package name as well as if you want to install any dependencies to the new package (of course you can also do this yourself later). + +The generator sets up the `package.json`, `tsconfig.json` and a `index.ts`, as well as configures all the necessary configurations for tooling around your package such as formatting, linting and typechecking. When the package is created, you're ready to go build out the package. + +## FAQ + +### Does the starter include Solito? + +No. Solito will not be included in this repo. It is a great tool if you want to share code between your Next.js and Expo app. However, the main purpose of this repo is not the integration between Next.js and Expo — it's the codesplitting of your T3 App into a monorepo. The Expo app is just a bonus example of how you can utilize the monorepo with multiple apps but can just as well be any app such as Vite, Electron, etc. + +Integrating Solito into this repo isn't hard, and there are a few [offical templates](https://github.com/nandorojo/solito/tree/master/example-monorepos) by the creators of Solito that you can use as a reference. + +### What auth solution should I use instead of Next-Auth.js for Expo? + +I've left this kind of open for you to decide. Some options are [Clerk](https://clerk.dev), [Supabase Auth](https://supabase.com/docs/guides/auth), [Firebase Auth](https://firebase.google.com/docs/auth/) or [Auth0](https://auth0.com/docs). Note that if you're dropping the Expo app for something more "browser-like", you can still use Next-Auth.js for those. [See an example in a Plasmo Chrome Extension here](https://github.com/t3-oss/create-t3-turbo/tree/chrome/apps/chrome). + +The Clerk.dev team even made an [official template repository](https://github.com/clerkinc/t3-turbo-and-clerk) integrating Clerk.dev with this repo. + +During Launch Week 7, Supabase [announced their fork](https://supabase.com/blog/launch-week-7-community-highlights#t3-turbo-x-supabase) of this repo integrating it with their newly announced auth improvements. You can check it out [here](https://github.com/supabase-community/create-t3-turbo). + +### Does this pattern leak backend code to my client applications? + +No, it does not. The `api` package should only be a production dependency in the Next.js application where it's served. The Expo app, and all other apps you may add in the future, should only add the `api` package as a dev dependency. This lets you have full typesafety in your client applications, while keeping your backend code safe. + +If you need to share runtime code between the client and server, such as input validation schemas, you can create a separate `shared` package for this and import it on both sides. + +## Deployment + +### Next.js + +#### Prerequisites + +> **Note** +> Please note that the Next.js application with tRPC must be deployed in order for the Expo app to communicate with the server in a production environment. + +#### Deploy to Vercel + +Let's deploy the Next.js application to [Vercel](https://vercel.com). If you've never deployed a Turborepo app there, don't worry, the steps are quite straightforward. You can also read the [official Turborepo guide](https://vercel.com/docs/concepts/monorepos/turborepo) on deploying to Vercel. + +1. Create a new project on Vercel, select the `apps/nextjs` folder as the root directory. Vercel's zero-config system should handle all configurations for you. + +2. Add your `DATABASE_URL` environment variable. + +3. Done! Your app should successfully deploy. Assign your domain and use that instead of `localhost` for the `url` in the Expo app so that your Expo app can communicate with your backend when you are not in development. + +### Auth Proxy + +The auth proxy is a Nitro server that proxies OAuth requests in preview deployments. This is required for the Next.js app to be able to authenticate users in preview deployments. The auth proxy is not used for OAuth requests in production deployments. To get it running, it's easiest to use Vercel Edge functions. See the [Nitro docs](https://nitro.unjs.io/deploy/providers/vercel#vercel-edge-functions) for how to deploy Nitro to Vercel. + +Then, there are some environment variables you need to set in order to get OAuth working: + +- For the Next.js app, set `AUTH_REDIRECT_PROXY_URL` to the URL of the auth proxy. +- For the auth proxy server, set `AUTH_REDIRECT_PROXY_URL` to the same as above, as well as `AUTH_DISCORD_ID`, `AUTH_DISCORD_SECRET` (or the equivalent for your OAuth provider(s)). Lastly, set `AUTH_SECRET` **to the same value as in the Next.js app** for preview environments. + +Read more about the setup in [the auth proxy README](./apps/auth-proxy/README.md). + +### Expo + +Deploying your Expo application works slightly differently compared to Next.js on the web. Instead of "deploying" your app online, you need to submit production builds of your app to app stores, like [Apple App Store](https://www.apple.com/app-store) and [Google Play](https://play.google.com/store/apps). You can read the full [guide to distributing your app](https://docs.expo.dev/distribution/introduction), including best practices, in the Expo docs. + +1. Make sure to modify the `getBaseUrl` function to point to your backend's production URL: + + + +2. Let's start by setting up [EAS Build](https://docs.expo.dev/build/introduction), which is short for Expo Application Services. The build service helps you create builds of your app, without requiring a full native development setup. The commands below are a summary of [Creating your first build](https://docs.expo.dev/build/setup). + + ```bash + # Install the EAS CLI + pnpm add -g eas-cli + + # Log in with your Expo account + eas login + + # Configure your Expo app + cd apps/expo + eas build:configure + ``` + +3. After the initial setup, you can create your first build. You can build for Android and iOS platforms and use different [`eas.json` build profiles](https://docs.expo.dev/build-reference/eas-json) to create production builds or development, or test builds. Let's make a production build for iOS. + + ```bash + eas build --platform ios --profile production + ``` + + > If you don't specify the `--profile` flag, EAS uses the `production` profile by default. + +4. Now that you have your first production build, you can submit this to the stores. [EAS Submit](https://docs.expo.dev/submit/introduction) can help you send the build to the stores. + + ```bash + eas submit --platform ios --latest + ``` + + > You can also combine build and submit in a single command, using `eas build ... --auto-submit`. + +5. Before you can get your app in the hands of your users, you'll have to provide additional information to the app stores. This includes screenshots, app information, privacy policies, etc. _While still in preview_, [EAS Metadata](https://docs.expo.dev/eas/metadata) can help you with most of this information. + +6. Once everything is approved, your users can finally enjoy your app. Let's say you spotted a small typo; you'll have to create a new build, submit it to the stores, and wait for approval before you can resolve this issue. In these cases, you can use EAS Update to quickly send a small bugfix to your users without going through this long process. Let's start by setting up EAS Update. + + The steps below summarize the [Getting started with EAS Update](https://docs.expo.dev/eas-update/getting-started/#configure-your-project) guide. + + ```bash + # Add the `expo-updates` library to your Expo app + cd apps/expo + pnpm expo install expo-updates + + # Configure EAS Update + eas update:configure + ``` + +7. Before we can send out updates to your app, you have to create a new build and submit it to the app stores. For every change that includes native APIs, you have to rebuild the app and submit the update to the app stores. See steps 2 and 3. + +8. Now that everything is ready for updates, let's create a new update for `production` builds. With the `--auto` flag, EAS Update uses your current git branch name and commit message for this update. See [How EAS Update works](https://docs.expo.dev/eas-update/how-eas-update-works/#publishing-an-update) for more information. + + ```bash + cd apps/expo + eas update --auto + ``` + + > Your OTA (Over The Air) updates must always follow the app store's rules. You can't change your app's primary functionality without getting app store approval. But this is a fast way to update your app for minor changes and bug fixes. + +9. Done! Now that you have created your production build, submitted it to the stores, and installed EAS Update, you are ready for anything! + +## References + +The stack originates from [create-t3-app](https://github.com/t3-oss/create-t3-app). + +A [blog post](https://jumr.dev/blog/t3-turbo) where I wrote how to migrate a T3 app into this. diff --git a/my-turborepo/apps/auth-proxy/.env.example b/my-turborepo/apps/auth-proxy/.env.example new file mode 100644 index 0000000..bdb4d55 --- /dev/null +++ b/my-turborepo/apps/auth-proxy/.env.example @@ -0,0 +1,7 @@ + +AUTH_SECRET="" +AUTH_DISCORD_ID="" +AUTH_DISCORD_SECRET="" +AUTH_REDIRECT_PROXY_URL="" + +NITRO_PRESET="vercel_edge" \ No newline at end of file diff --git a/my-turborepo/apps/auth-proxy/README.md b/my-turborepo/apps/auth-proxy/README.md new file mode 100644 index 0000000..1a9876e --- /dev/null +++ b/my-turborepo/apps/auth-proxy/README.md @@ -0,0 +1,16 @@ +# Auth Proxy + +This is a simple proxy server that enables OAuth authentication for preview environments. + +## Setup + +Deploy it somewhere (Vercel is a one-click, zero-config option) and set the following environment variables: + +- `AUTH_DISCORD_ID` - The Discord OAuth client ID +- `AUTH_DISCORD_SECRET` - The Discord OAuth client secret +- `AUTH_REDIRECT_PROXY_URL` - The URL of this proxy server +- `AUTH_SECRET` - Your secret + +Make sure the `AUTH_SECRET` and `AUTH_REDIRECT_PROXY_URL` match the values set for the main application's deployment for preview environments, and that you're using the same OAuth credentials for the proxy and the application's preview environment. The lines below shows what values should match eachother in both deployments. + +![Environment variables setup](https://github.com/t3-oss/create-t3-turbo/assets/51714798/5fadd3f5-f705-459a-82ab-559a3df881d0) diff --git a/my-turborepo/apps/auth-proxy/package.json b/my-turborepo/apps/auth-proxy/package.json new file mode 100644 index 0000000..82608ff --- /dev/null +++ b/my-turborepo/apps/auth-proxy/package.json @@ -0,0 +1,33 @@ +{ + "name": "@acme/auth-proxy", + "private": true, + "type": "module", + "scripts": { + "build": "nitro build", + "clean": "rm -rf .turbo node_modules", + "dev": "nitro dev --port 3001", + "lint": "eslint .", + "format": "prettier --check . --ignore-path ../../.gitignore", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@auth/core": "^0.19.0" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:^0.2.0", + "@acme/prettier-config": "workspace:^0.1.0", + "@acme/tailwind-config": "workspace:^0.1.0", + "@acme/tsconfig": "workspace:^0.1.0", + "eslint": "^8.56.0", + "nitropack": "^2.8.1", + "prettier": "^3.1.1", + "typescript": "^5.3.3" + }, + "eslintConfig": { + "root": true, + "extends": [ + "@acme/eslint-config/base" + ] + }, + "prettier": "@acme/prettier-config" +} diff --git a/my-turborepo/apps/auth-proxy/routes/[...auth].ts b/my-turborepo/apps/auth-proxy/routes/[...auth].ts new file mode 100644 index 0000000..f3f737b --- /dev/null +++ b/my-turborepo/apps/auth-proxy/routes/[...auth].ts @@ -0,0 +1,17 @@ +import { Auth } from "@auth/core"; +import Discord from "@auth/core/providers/discord"; +import { eventHandler, toWebRequest } from "h3"; + +export default eventHandler(async (event) => + Auth(toWebRequest(event), { + secret: process.env.AUTH_SECRET, + trustHost: !!process.env.VERCEL, + redirectProxyUrl: process.env.AUTH_REDIRECT_PROXY_URL, + providers: [ + Discord({ + clientId: process.env.AUTH_DISCORD_ID, + clientSecret: process.env.AUTH_DISCORD_SECRET, + }), + ], + }), +); diff --git a/my-turborepo/apps/auth-proxy/tsconfig.json b/my-turborepo/apps/auth-proxy/tsconfig.json new file mode 100644 index 0000000..a2aaadc --- /dev/null +++ b/my-turborepo/apps/auth-proxy/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "@acme/tsconfig/base.json", + "include": ["routes"] +} diff --git a/my-turborepo/apps/expo/.expo-shared/assets.json b/my-turborepo/apps/expo/.expo-shared/assets.json new file mode 100644 index 0000000..1e6decf --- /dev/null +++ b/my-turborepo/apps/expo/.expo-shared/assets.json @@ -0,0 +1,4 @@ +{ + "12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true, + "40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true +} diff --git a/my-turborepo/apps/expo/app.config.ts b/my-turborepo/apps/expo/app.config.ts new file mode 100644 index 0000000..f6c21c9 --- /dev/null +++ b/my-turborepo/apps/expo/app.config.ts @@ -0,0 +1,43 @@ +import type { ExpoConfig } from "@expo/config"; + +const defineConfig = (): ExpoConfig => ({ + name: "expo", + slug: "expo", + scheme: "expo", + version: "0.1.0", + orientation: "portrait", + icon: "./assets/icon.png", + userInterfaceStyle: "light", + splash: { + image: "./assets/icon.png", + resizeMode: "contain", + backgroundColor: "#1F104A", + }, + updates: { + fallbackToCacheTimeout: 0, + }, + assetBundlePatterns: ["**/*"], + ios: { + bundleIdentifier: "your.bundle.identifier", + supportsTablet: true, + }, + android: { + package: "your.bundle.identifier", + adaptiveIcon: { + foregroundImage: "./assets/icon.png", + backgroundColor: "#1F104A", + }, + }, + // extra: { + // eas: { + // projectId: "your-eas-project-id", + // }, + // }, + experiments: { + tsconfigPaths: true, + typedRoutes: true, + }, + plugins: ["expo-router", "./expo-plugins/with-modify-gradle.js"], +}); + +export default defineConfig; diff --git a/my-turborepo/apps/expo/assets/icon.png b/my-turborepo/apps/expo/assets/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..67917f52aec973e6248c22a58f4e36503c09a351 GIT binary patch literal 10788 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 literal 0 HcmV?d00001 diff --git a/my-turborepo/apps/expo/babel.config.js b/my-turborepo/apps/expo/babel.config.js new file mode 100644 index 0000000..143cb08 --- /dev/null +++ b/my-turborepo/apps/expo/babel.config.js @@ -0,0 +1,15 @@ +/** @type {import("@babel/core").ConfigFunction} */ +module.exports = function (api) { + api.cache.forever(); + + return { + presets: [ + ["babel-preset-expo", { jsxImportSource: "nativewind" }], + "nativewind/babel", + ], + plugins: [ + require.resolve("expo-router/babel"), + require.resolve("react-native-reanimated/plugin"), + ], + }; +}; diff --git a/my-turborepo/apps/expo/eas.json b/my-turborepo/apps/expo/eas.json new file mode 100644 index 0000000..607de32 --- /dev/null +++ b/my-turborepo/apps/expo/eas.json @@ -0,0 +1,31 @@ +{ + "cli": { + "version": ">= 4.1.2" + }, + "build": { + "base": { + "node": "18.16.1", + "ios": { + "resourceClass": "m-medium" + } + }, + "development": { + "extends": "base", + "developmentClient": true, + "distribution": "internal" + }, + "preview": { + "extends": "base", + "distribution": "internal", + "ios": { + "simulator": true + } + }, + "production": { + "extends": "base" + } + }, + "submit": { + "production": {} + } +} diff --git a/my-turborepo/apps/expo/expo-plugins/with-modify-gradle.js b/my-turborepo/apps/expo/expo-plugins/with-modify-gradle.js new file mode 100644 index 0000000..343c579 --- /dev/null +++ b/my-turborepo/apps/expo/expo-plugins/with-modify-gradle.js @@ -0,0 +1,44 @@ +// This plugin is required for fixing `.apk` build issue +// It appends Expo and RN versions into the `build.gradle` file +// References: +// https://github.com/t3-oss/create-t3-turbo/issues/120 +// https://github.com/expo/expo/issues/18129 + +/** @type {import("@expo/config-plugins").ConfigPlugin} */ +const defineConfig = (config) => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + return require("@expo/config-plugins").withProjectBuildGradle( + config, + (config) => { + if (!config.modResults.contents.includes("ext.getPackageJsonVersion =")) { + config.modResults.contents = config.modResults.contents.replace( + "buildscript {", + `buildscript { + ext.getPackageJsonVersion = { packageName -> + new File(['node', '--print', "JSON.parse(require('fs').readFileSync(require.resolve('\${packageName}/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim()) + }`, + ); + } + + if (!config.modResults.contents.includes("reactNativeVersion =")) { + config.modResults.contents = config.modResults.contents.replace( + "ext {", + `ext { + reactNativeVersion = "\${ext.getPackageJsonVersion('react-native')}"`, + ); + } + + if (!config.modResults.contents.includes("expoPackageVersion =")) { + config.modResults.contents = config.modResults.contents.replace( + "ext {", + `ext { + expoPackageVersion = "\${ext.getPackageJsonVersion('expo')}"`, + ); + } + + return config; + }, + ); +}; + +module.exports = defineConfig; diff --git a/my-turborepo/apps/expo/metro.config.js b/my-turborepo/apps/expo/metro.config.js new file mode 100644 index 0000000..3754383 --- /dev/null +++ b/my-turborepo/apps/expo/metro.config.js @@ -0,0 +1,29 @@ +// Learn more: https://docs.expo.dev/guides/monorepos/ +const { getDefaultConfig } = require("@expo/metro-config"); +const { withNativeWind } = require("nativewind/metro"); + +const path = require("path"); + +const projectRoot = __dirname; +const workspaceRoot = path.resolve(projectRoot, "../.."); + +// Create the default Metro config +const config = getDefaultConfig(projectRoot, { isCSSEnabled: true }); + +if (config.resolver) { + // 1. Watch all files within the monorepo + config.watchFolders = [workspaceRoot]; + // 2. Let Metro know where to resolve packages and in what order + config.resolver.nodeModulesPaths = [ + path.resolve(projectRoot, "node_modules"), + path.resolve(workspaceRoot, "node_modules"), + ]; + // 3. Force Metro to resolve (sub)dependencies only from the `nodeModulesPaths` + config.resolver.disableHierarchicalLookup = true; +} + +// @ts-expect-error - FIXME: type is mismatching? +module.exports = withNativeWind(config, { + input: "./src/styles.css", + configPath: "./tailwind.config.ts", +}); diff --git a/my-turborepo/apps/expo/package.json b/my-turborepo/apps/expo/package.json new file mode 100644 index 0000000..2c6eaf1 --- /dev/null +++ b/my-turborepo/apps/expo/package.json @@ -0,0 +1,68 @@ +{ + "name": "@acme/expo", + "version": "0.1.0", + "private": true, + "main": "expo-router/entry", + "scripts": { + "clean": "git clean -xdf .expo .turbo node_modules", + "dev": "expo start --ios", + "dev:android": "expo start --android", + "dev:ios": "expo start --ios", + "android": "expo run:android", + "ios": "expo run:ios", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint .", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@expo/metro-config": "^0.10.7", + "@shopify/flash-list": "1.4.3", + "@tanstack/react-query": "^5.8.7", + "@trpc/client": "next", + "@trpc/react-query": "next", + "@trpc/server": "next", + "expo": "^49.0.21", + "expo-constants": "~14.4.2", + "expo-linking": "~5.0.2", + "expo-router": "2.0.14", + "expo-splash-screen": "~0.22.0", + "expo-status-bar": "~1.7.1", + "nativewind": "^4.0.22", + "react": "18.2.0", + "react-dom": "18.2.0", + "react-native": "0.73.1", + "react-native-gesture-handler": "~2.12.0", + "react-native-reanimated": "~3.3.0", + "react-native-safe-area-context": "4.6.3", + "react-native-screens": "~3.22.1", + "superjson": "2.2.1" + }, + "devDependencies": { + "@acme/api": "workspace:^0.1.0", + "@acme/eslint-config": "workspace:^0.2.0", + "@acme/prettier-config": "workspace:^0.1.0", + "@acme/tailwind-config": "workspace:^0.1.0", + "@acme/tsconfig": "workspace:^0.1.0", + "@babel/core": "^7.23.7", + "@babel/preset-env": "^7.23.7", + "@babel/runtime": "^7.23.7", + "@expo/config-plugins": "^7.2.5", + "@types/babel__core": "^7.20.4", + "@types/react": "^18.2.46", + "eslint": "^8.56.0", + "prettier": "^3.1.1", + "tailwindcss": "^3.4.0", + "typescript": "^5.3.3" + }, + "eslintConfig": { + "root": true, + "extends": [ + "@acme/eslint-config/base", + "@acme/eslint-config/react" + ], + "ignorePatterns": [ + "expo-plugins/**" + ] + }, + "prettier": "@acme/prettier-config" +} diff --git a/my-turborepo/apps/expo/src/app/_layout.tsx b/my-turborepo/apps/expo/src/app/_layout.tsx new file mode 100644 index 0000000..23ff5a6 --- /dev/null +++ b/my-turborepo/apps/expo/src/app/_layout.tsx @@ -0,0 +1,27 @@ +import { Stack } from "expo-router"; +import { StatusBar } from "expo-status-bar"; + +import { TRPCProvider } from "~/utils/api"; + +import "../styles.css"; + +// This is the main layout of the app +// It wraps your pages with the providers they need +export default function RootLayout() { + return ( + + {/* + The Stack component displays the current page. + It also allows you to configure your screens + */} + + + + ); +} diff --git a/my-turborepo/apps/expo/src/app/index.tsx b/my-turborepo/apps/expo/src/app/index.tsx new file mode 100644 index 0000000..f53e766 --- /dev/null +++ b/my-turborepo/apps/expo/src/app/index.tsx @@ -0,0 +1,145 @@ +import { useState } from "react"; +import { Button, Pressable, Text, TextInput, View } from "react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { Link, Stack } from "expo-router"; +import { FlashList } from "@shopify/flash-list"; + +import type { RouterOutputs } from "~/utils/api"; +import { api } from "~/utils/api"; + +function PostCard(props: { + post: RouterOutputs["post"]["all"][number]; + onDelete: () => void; +}) { + return ( + + + + + + {props.post.title} + + {props.post.content} + + + + + Delete + + + ); +} + +function CreatePost() { + const utils = api.useUtils(); + + const [title, setTitle] = useState(""); + const [content, setContent] = useState(""); + + const { mutate, error } = api.post.create.useMutation({ + async onSuccess() { + setTitle(""); + setContent(""); + await utils.post.all.invalidate(); + }, + }); + + return ( + + + {error?.data?.zodError?.fieldErrors.title && ( + + {error.data.zodError.fieldErrors.title} + + )} + + {error?.data?.zodError?.fieldErrors.content && ( + + {error.data.zodError.fieldErrors.content} + + )} + { + mutate({ + title, + content, + }); + }} + > + Publish post + + {error?.data?.code === "UNAUTHORIZED" && ( + + You need to be logged in to create a post + + )} + + ); +} + +export default function Index() { + const utils = api.useUtils(); + + const postQuery = api.post.all.useQuery(); + + const deletePostMutation = api.post.delete.useMutation({ + onSettled: () => utils.post.all.invalidate(), + }); + + return ( + + {/* Changes page title visible on the header */} + + + + Create T3 Turbo + + + + + ); + } + + return ( +
+

+ {session && Logged in as {session.user.name}} +

+ +
+ +
+
+ ); +} diff --git a/my-turborepo/apps/nextjs/src/app/_components/posts.tsx b/my-turborepo/apps/nextjs/src/app/_components/posts.tsx new file mode 100644 index 0000000..4e06acc --- /dev/null +++ b/my-turborepo/apps/nextjs/src/app/_components/posts.tsx @@ -0,0 +1,168 @@ +"use client"; + +import type { RouterOutputs } from "@acme/api"; +import { cn } from "@acme/ui"; +import { Button } from "@acme/ui/button"; +import { + Form, + FormControl, + FormField, + FormItem, + FormMessage, + useForm, +} from "@acme/ui/form"; +import { Input } from "@acme/ui/input"; +import { toast } from "@acme/ui/toast"; +import { CreatePostSchema } from "@acme/validators"; + +import { api } from "~/trpc/react"; + +export function CreatePostForm() { + const form = useForm({ + schema: CreatePostSchema, + defaultValues: { + content: "", + title: "", + }, + }); + + const utils = api.useUtils(); + const createPost = api.post.create.useMutation({ + onSuccess: async () => { + form.reset(); + await utils.post.invalidate(); + }, + onError: (err) => { + toast.error( + err?.data?.code === "UNAUTHORIZED" + ? "You must be logged in to post" + : "Failed to create post", + ); + }, + }); + + return ( +
+ { + createPost.mutate(data); + })} + > + ( + + + + + + + )} + /> + ( + + + + + + + )} + /> + + + + ); +} + +export function PostList() { + const [posts] = api.post.all.useSuspenseQuery(); + + if (posts.length === 0) { + return ( +
+ + + + +
+

No posts yet

+
+
+ ); + } + + return ( +
+ {posts.map((p) => { + return ; + })} +
+ ); +} + +export function PostCard(props: { + post: RouterOutputs["post"]["all"][number]; +}) { + const utils = api.useUtils(); + const deletePost = api.post.delete.useMutation({ + onSuccess: async () => { + await utils.post.invalidate(); + }, + onError: (err) => { + toast.error( + err?.data?.code === "UNAUTHORIZED" + ? "You must be logged in to delete a post" + : "Failed to delete post", + ); + }, + }); + + return ( +
+
+

{props.post.title}

+

{props.post.content}

+
+
+ +
+
+ ); +} + +export function PostCardSkeleton(props: { pulse?: boolean }) { + const { pulse = true } = props; + return ( +
+
+

+   +

+

+   +

+
+
+ ); +} diff --git a/my-turborepo/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts b/my-turborepo/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts new file mode 100644 index 0000000..16c8300 --- /dev/null +++ b/my-turborepo/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts @@ -0,0 +1,3 @@ +export { GET, POST } from "@acme/auth"; + +export const runtime = "edge"; diff --git a/my-turborepo/apps/nextjs/src/app/api/trpc/[trpc]/route.ts b/my-turborepo/apps/nextjs/src/app/api/trpc/[trpc]/route.ts new file mode 100644 index 0000000..c9a4269 --- /dev/null +++ b/my-turborepo/apps/nextjs/src/app/api/trpc/[trpc]/route.ts @@ -0,0 +1,46 @@ +import { fetchRequestHandler } from "@trpc/server/adapters/fetch"; + +import { appRouter, createTRPCContext } from "@acme/api"; +import { auth } from "@acme/auth"; + +export const runtime = "edge"; + +/** + * Configure basic CORS headers + * You should extend this to match your needs + */ +function setCorsHeaders(res: Response) { + res.headers.set("Access-Control-Allow-Origin", "*"); + res.headers.set("Access-Control-Request-Method", "*"); + res.headers.set("Access-Control-Allow-Methods", "OPTIONS, GET, POST"); + res.headers.set("Access-Control-Allow-Headers", "*"); +} + +export function OPTIONS() { + const response = new Response(null, { + status: 204, + }); + setCorsHeaders(response); + return response; +} + +const handler = auth(async (req) => { + const response = await fetchRequestHandler({ + endpoint: "/api/trpc", + router: appRouter, + req, + createContext: () => + createTRPCContext({ + session: req.auth, + headers: req.headers, + }), + onError({ error, path }) { + console.error(`>>> tRPC Error on '${path}'`, error); + }, + }); + + setCorsHeaders(response); + return response; +}); + +export { handler as GET, handler as POST }; diff --git a/my-turborepo/apps/nextjs/src/app/globals.css b/my-turborepo/apps/nextjs/src/app/globals.css new file mode 100644 index 0000000..b9d992f --- /dev/null +++ b/my-turborepo/apps/nextjs/src/app/globals.css @@ -0,0 +1,50 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +@layer base { + :root { + --background: 0 0% 100%; + --foreground: 240 10% 3.9%; + --card: 0 0% 100%; + --card-foreground: 240 10% 3.9%; + --popover: 0 0% 100%; + --popover-foreground: 240 10% 3.9%; + --primary: 327 66% 69%; + --primary-foreground: 337 65.5% 17.1%; + --secondary: 240 4.8% 95.9%; + --secondary-foreground: 240 5.9% 10%; + --muted: 240 4.8% 95.9%; + --muted-foreground: 240 3.8% 46.1%; + --accent: 240 4.8% 95.9%; + --accent-foreground: 240 5.9% 10%; + --destructive: 0 72.22% 50.59%; + --destructive-foreground: 0 0% 98%; + --border: 240 5.9% 90%; + --input: 240 5.9% 90%; + --ring: 240 5% 64.9%; + --radius: 0.5rem; + } + + .dark { + --background: 240 10% 3.9%; + --foreground: 0 0% 98%; + --card: 240 10% 3.9%; + --card-foreground: 0 0% 98%; + --popover: 240 10% 3.9%; + --popover-foreground: 0 0% 98%; + --primary: 327 66% 69%; + --primary-foreground: 337 65.5% 17.1%; + --secondary: 240 3.7% 15.9%; + --secondary-foreground: 0 0% 98%; + --muted: 240 3.7% 15.9%; + --muted-foreground: 240 5% 64.9%; + --accent: 240 3.7% 15.9%; + --accent-foreground: 0 0% 98%; + --destructive: 0 62.8% 30.6%; + --destructive-foreground: 0 85.7% 97.3%; + --border: 240 3.7% 15.9%; + --input: 240 3.7% 15.9%; + --ring: 240 4.9% 83.9%; + } +} diff --git a/my-turborepo/apps/nextjs/src/app/layout.tsx b/my-turborepo/apps/nextjs/src/app/layout.tsx new file mode 100644 index 0000000..0d5fbaf --- /dev/null +++ b/my-turborepo/apps/nextjs/src/app/layout.tsx @@ -0,0 +1,68 @@ +import type { Metadata, Viewport } from "next"; +import { cache } from "react"; +import { headers } from "next/headers"; +import { GeistMono } from "geist/font/mono"; +import { GeistSans } from "geist/font/sans"; + +import { cn } from "@acme/ui"; +import { ThemeProvider, ThemeToggle } from "@acme/ui/theme"; +import { Toaster } from "@acme/ui/toast"; + +import { env } from "~/env"; +import { TRPCReactProvider } from "~/trpc/react"; + +import "~/app/globals.css"; + +export const metadata: Metadata = { + metadataBase: new URL( + env.VERCEL_ENV === "production" + ? "https://turbo.t3.gg" + : "http://localhost:3000", + ), + title: "Create T3 Turbo", + description: "Simple monorepo with shared backend for web & mobile apps", + openGraph: { + title: "Create T3 Turbo", + description: "Simple monorepo with shared backend for web & mobile apps", + url: "https://create-t3-turbo.vercel.app", + siteName: "Create T3 Turbo", + }, + twitter: { + card: "summary_large_image", + site: "@jullerino", + creator: "@jullerino", + }, +}; + +export const viewport: Viewport = { + themeColor: [ + { media: "(prefers-color-scheme: light)", color: "white" }, + { media: "(prefers-color-scheme: dark)", color: "black" }, + ], +}; + +const getHeaders = cache(async () => headers()); + +export default function RootLayout(props: { children: React.ReactNode }) { + return ( + + + + + {props.children} + +
+ +
+ +
+ + + ); +} diff --git a/my-turborepo/apps/nextjs/src/app/page.tsx b/my-turborepo/apps/nextjs/src/app/page.tsx new file mode 100644 index 0000000..b9bcdc0 --- /dev/null +++ b/my-turborepo/apps/nextjs/src/app/page.tsx @@ -0,0 +1,45 @@ +import { Suspense } from "react"; + +import { api } from "~/trpc/server"; +import { AuthShowcase } from "./_components/auth-showcase"; +import { + CreatePostForm, + PostCardSkeleton, + PostList, +} from "./_components/posts"; + +export const runtime = "edge"; + +export default async function HomePage() { + // You don't need to fetch these here, just showing different usages + // If you don't want the Suspense loading state, you could pass these + // posts as props as use as initialData in the query. + const posts = await api.post.all.query(); + console.log("RSC Posts:", posts); + + return ( +
+
+

+ Create T3 Turbo +

+ + + +
+ + + + +
+ } + > + + +
+ +
+ ); +} diff --git a/my-turborepo/apps/nextjs/src/env.js b/my-turborepo/apps/nextjs/src/env.js new file mode 100644 index 0000000..eb5cd8c --- /dev/null +++ b/my-turborepo/apps/nextjs/src/env.js @@ -0,0 +1,50 @@ +import { createEnv } from "@t3-oss/env-nextjs"; +import { z } from "zod"; + +export const env = createEnv({ + shared: { + NODE_ENV: z + .enum(["development", "production", "test"]) + .default("development"), + VERCEL_ENV: z.enum(["development", "preview", "production"]).optional(), + VERCEL_URL: z + .string() + .optional() + .transform((v) => (v ? `https://${v}` : undefined)), + PORT: z.coerce.number().default(3000), + }, + /** + * Specify your server-side environment variables schema here. + * This way you can ensure the app isn't built with invalid env vars. + */ + server: { + DB_HOST: z.string(), + DB_NAME: z.string(), + DB_PASSWORD: z.string(), + DB_USERNAME: z.string(), + }, + /** + * Specify your client-side environment variables schema here. + * For them to be exposed to the client, prefix them with `NEXT_PUBLIC_`. + */ + client: { + // NEXT_PUBLIC_CLIENTVAR: z.string(), + }, + /** + * Destructure all variables from `process.env` to make sure they aren't tree-shaken away. + */ + runtimeEnv: { + DB_HOST: process.env.DB_HOST, + DB_NAME: process.env.DB_NAME, + DB_PASSWORD: process.env.DB_PASSWORD, + DB_USERNAME: process.env.DB_USERNAME, + PORT: process.env.PORT, + VERCEL_URL: process.env.VERCEL_URL, + + // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, + }, + skipValidation: + !!process.env.CI || + !!process.env.SKIP_ENV_VALIDATION || + process.env.npm_lifecycle_event === "lint", +}); diff --git a/my-turborepo/apps/nextjs/src/trpc/react.tsx b/my-turborepo/apps/nextjs/src/trpc/react.tsx new file mode 100644 index 0000000..2bb842c --- /dev/null +++ b/my-turborepo/apps/nextjs/src/trpc/react.tsx @@ -0,0 +1,53 @@ +"use client"; + +import { useState } from "react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { loggerLink, unstable_httpBatchStreamLink } from "@trpc/client"; +import { createTRPCReact } from "@trpc/react-query"; +import SuperJSON from "superjson"; + +import type { AppRouter } from "@acme/api"; + +export const api = createTRPCReact(); + +export function TRPCReactProvider(props: { + children: React.ReactNode; + headersPromise: Promise; +}) { + const [queryClient] = useState(() => new QueryClient()); + + const [trpcClient] = useState(() => + api.createClient({ + transformer: SuperJSON, + links: [ + loggerLink({ + enabled: (op) => + process.env.NODE_ENV === "development" || + (op.direction === "down" && op.result instanceof Error), + }), + unstable_httpBatchStreamLink({ + url: getBaseUrl() + "/api/trpc", + async headers() { + const headers = new Map(await props.headersPromise); + headers.set("x-trpc-source", "nextjs-react"); + return Object.fromEntries(headers); + }, + }), + ], + }), + ); + + return ( + + + {props.children} + + + ); +} + +function getBaseUrl() { + if (typeof window !== "undefined") return window.location.origin; + if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; + return `http://localhost:${process.env.PORT ?? 3000}`; +} diff --git a/my-turborepo/apps/nextjs/src/trpc/server.ts b/my-turborepo/apps/nextjs/src/trpc/server.ts new file mode 100644 index 0000000..1e14dd5 --- /dev/null +++ b/my-turborepo/apps/nextjs/src/trpc/server.ts @@ -0,0 +1,61 @@ +import type { TRPCErrorResponse } from "@trpc/server/rpc"; +import { cache } from "react"; +import { headers } from "next/headers"; +import { createTRPCClient, loggerLink, TRPCClientError } from "@trpc/client"; +import { callProcedure } from "@trpc/server"; +import { observable } from "@trpc/server/observable"; +import SuperJSON from "superjson"; + +import { appRouter, createTRPCContext } from "@acme/api"; +import { auth } from "@acme/auth"; + +/** + * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when + * handling a tRPC call from a React Server Component. + */ +const createContext = cache(async () => { + const heads = new Headers(headers()); + heads.set("x-trpc-source", "rsc"); + + return createTRPCContext({ + session: await auth(), + headers: heads, + }); +}); + +export const api = createTRPCClient({ + transformer: SuperJSON, + links: [ + loggerLink({ + enabled: (op) => + process.env.NODE_ENV === "development" || + (op.direction === "down" && op.result instanceof Error), + }), + /** + * Custom RSC link that invokes procedures directly in the server component Don't be too afraid + * about the complexity here, it's just wrapping `callProcedure` with an observable to make it a + * valid ending link for tRPC. + */ + () => + ({ op }) => + observable((observer) => { + createContext() + .then((ctx) => { + return callProcedure({ + procedures: appRouter._def.procedures, + path: op.path, + getRawInput: () => Promise.resolve(op.input), + ctx, + type: op.type, + }); + }) + .then((data) => { + observer.next({ result: { data } }); + observer.complete(); + }) + .catch((cause: TRPCErrorResponse) => { + observer.error(TRPCClientError.from(cause)); + }); + }), + ], +}); diff --git a/my-turborepo/apps/nextjs/tailwind.config.ts b/my-turborepo/apps/nextjs/tailwind.config.ts new file mode 100644 index 0000000..bfe6abb --- /dev/null +++ b/my-turborepo/apps/nextjs/tailwind.config.ts @@ -0,0 +1,19 @@ +import type { Config } from "tailwindcss"; +import { fontFamily } from "tailwindcss/defaultTheme"; + +import baseConfig from "@acme/tailwind-config"; + +export default { + // We need to append the path to the UI package to the content array so that + // those classes are included correctly. + content: [...baseConfig.content, "../../packages/ui/**/*.{ts,tsx}"], + presets: [baseConfig], + theme: { + extend: { + fontFamily: { + sans: ["var(--font-geist-sans)", ...fontFamily.sans], + mono: ["var(--font-geist-mono)", ...fontFamily.mono], + }, + }, + }, +} satisfies Config; diff --git a/my-turborepo/apps/nextjs/tsconfig.json b/my-turborepo/apps/nextjs/tsconfig.json new file mode 100644 index 0000000..c73f60c --- /dev/null +++ b/my-turborepo/apps/nextjs/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "@acme/tsconfig/base.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "~/*": ["./src/*"] + }, + "plugins": [{ "name": "next" }], + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json" + }, + "include": [".", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/my-turborepo/package.json b/my-turborepo/package.json new file mode 100644 index 0000000..e36f33e --- /dev/null +++ b/my-turborepo/package.json @@ -0,0 +1,31 @@ +{ + "name": "create-t3-turbo", + "private": true, + "engines": { + "node": ">=20.10" + }, + "packageManager": "pnpm@8.12.1", + "scripts": { + "build": "turbo build", + "clean": "git clean -xdf node_modules", + "clean:workspaces": "turbo clean", + "db:push": "pnpm -F db push", + "db:studio": "pnpm -F db studio", + "dev": "turbo dev --parallel", + "format": "turbo format --continue -- --cache --cache-location node_modules/.cache/.prettiercache", + "format:fix": "turbo format --continue -- --write --cache --cache-location node_modules/.cache/.prettiercache", + "lint": "turbo lint --continue -- --cache --cache-location node_modules/.cache/.eslintcache", + "lint:fix": "turbo lint --continue -- --fix --cache --cache-location node_modules/.cache/.eslintcache", + "lint:ws": "pnpm dlx sherif@latest", + "postinstall": "pnpm lint:ws", + "typecheck": "turbo typecheck" + }, + "devDependencies": { + "@acme/prettier-config": "workspace:^0.1.0", + "@turbo/gen": "^1.11.2", + "prettier": "^3.1.1", + "turbo": "^1.11.2", + "typescript": "^5.3.3" + }, + "prettier": "@acme/prettier-config" +} diff --git a/my-turborepo/packages/api/package.json b/my-turborepo/packages/api/package.json new file mode 100644 index 0000000..72b5c39 --- /dev/null +++ b/my-turborepo/packages/api/package.json @@ -0,0 +1,40 @@ +{ + "name": "@acme/api", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "license": "MIT", + "scripts": { + "clean": "rm -rf .turbo node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint .", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@acme/auth": "workspace:^0.1.0", + "@acme/db": "workspace:^0.1.0", + "@acme/validators": "workspace:^0.1.0", + "@trpc/client": "next", + "@trpc/server": "next", + "superjson": "2.2.1", + "zod": "^3.22.4" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:^0.2.0", + "@acme/prettier-config": "workspace:^0.1.0", + "@acme/tsconfig": "workspace:^0.1.0", + "eslint": "^8.56.0", + "prettier": "^3.1.1", + "typescript": "^5.3.3" + }, + "eslintConfig": { + "root": true, + "extends": [ + "@acme/eslint-config/base" + ] + }, + "prettier": "@acme/prettier-config" +} diff --git a/my-turborepo/packages/api/src/index.ts b/my-turborepo/packages/api/src/index.ts new file mode 100644 index 0000000..8fe0a9b --- /dev/null +++ b/my-turborepo/packages/api/src/index.ts @@ -0,0 +1,18 @@ +import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server"; + +import type { AppRouter } from "./root"; + +export { appRouter, type AppRouter } from "./root"; +export { createTRPCContext } from "./trpc"; + +/** + * Inference helpers for input types + * @example type HelloInput = RouterInputs['example']['hello'] + **/ +export type RouterInputs = inferRouterInputs; + +/** + * Inference helpers for output types + * @example type HelloOutput = RouterOutputs['example']['hello'] + **/ +export type RouterOutputs = inferRouterOutputs; diff --git a/my-turborepo/packages/api/src/root.ts b/my-turborepo/packages/api/src/root.ts new file mode 100644 index 0000000..730251c --- /dev/null +++ b/my-turborepo/packages/api/src/root.ts @@ -0,0 +1,11 @@ +import { authRouter } from "./router/auth"; +import { postRouter } from "./router/post"; +import { createTRPCRouter } from "./trpc"; + +export const appRouter = createTRPCRouter({ + auth: authRouter, + post: postRouter, +}); + +// export type definition of API +export type AppRouter = typeof appRouter; diff --git a/my-turborepo/packages/api/src/router/auth.ts b/my-turborepo/packages/api/src/router/auth.ts new file mode 100644 index 0000000..105b4ea --- /dev/null +++ b/my-turborepo/packages/api/src/router/auth.ts @@ -0,0 +1,11 @@ +import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc"; + +export const authRouter = createTRPCRouter({ + getSession: publicProcedure.query(({ ctx }) => { + return ctx.session; + }), + getSecretMessage: protectedProcedure.query(() => { + // testing type validation of overridden next-auth Session in @acme/auth package + return "you can see this secret message!"; + }), +}); diff --git a/my-turborepo/packages/api/src/router/post.ts b/my-turborepo/packages/api/src/router/post.ts new file mode 100644 index 0000000..ad9b3aa --- /dev/null +++ b/my-turborepo/packages/api/src/router/post.ts @@ -0,0 +1,39 @@ +import { z } from "zod"; + +import { desc, eq, schema } from "@acme/db"; +import { CreatePostSchema } from "@acme/validators"; + +import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc"; + +export const postRouter = createTRPCRouter({ + all: publicProcedure.query(({ ctx }) => { + // return ctx.db.select().from(schema.post).orderBy(desc(schema.post.id)); + return ctx.db.query.post.findMany({ + orderBy: desc(schema.post.id), + limit: 10, + }); + }), + + byId: publicProcedure + .input(z.object({ id: z.number() })) + .query(({ ctx, input }) => { + // return ctx.db + // .select() + // .from(schema.post) + // .where(eq(schema.post.id, input.id)); + + return ctx.db.query.post.findFirst({ + where: eq(schema.post.id, input.id), + }); + }), + + create: protectedProcedure + .input(CreatePostSchema) + .mutation(({ ctx, input }) => { + return ctx.db.insert(schema.post).values(input); + }), + + delete: protectedProcedure.input(z.number()).mutation(({ ctx, input }) => { + return ctx.db.delete(schema.post).where(eq(schema.post.id, input)); + }), +}); diff --git a/my-turborepo/packages/api/src/trpc.ts b/my-turborepo/packages/api/src/trpc.ts new file mode 100644 index 0000000..69f663b --- /dev/null +++ b/my-turborepo/packages/api/src/trpc.ts @@ -0,0 +1,101 @@ +/** + * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS: + * 1. You want to modify request context (see Part 1) + * 2. You want to create a new middleware or type of procedure (see Part 3) + * + * tl;dr - this is where all the tRPC server stuff is created and plugged in. + * The pieces you will need to use are documented accordingly near the end + */ +import { initTRPC, TRPCError } from "@trpc/server"; +import superjson from "superjson"; +import { ZodError } from "zod"; + +import type { Session } from "@acme/auth"; +import { auth } from "@acme/auth"; +import { db } from "@acme/db"; + +/** + * 1. CONTEXT + * + * This section defines the "contexts" that are available in the backend API. + * + * These allow you to access things when processing a request, like the database, the session, etc. + * + * This helper generates the "internals" for a tRPC context. The API handler and RSC clients each + * wrap this and provides the required context. + * + * @see https://trpc.io/docs/server/context + */ +export const createTRPCContext = async (opts: { + headers: Headers; + session: Session | null; +}) => { + const session = opts.session ?? (await auth()); + const source = opts.headers.get("x-trpc-source") ?? "unknown"; + + console.log(">>> tRPC Request from", source, "by", session?.user); + + return { + session, + db, + }; +}; + +/** + * 2. INITIALIZATION + * + * This is where the trpc api is initialized, connecting the context and + * transformer + */ +const t = initTRPC.context().create({ + transformer: superjson, + errorFormatter: ({ shape, error }) => ({ + ...shape, + data: { + ...shape.data, + zodError: error.cause instanceof ZodError ? error.cause.flatten() : null, + }, + }), +}); + +/** + * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) + * + * These are the pieces you use to build your tRPC API. You should import these + * a lot in the /src/server/api/routers folder + */ + +/** + * This is how you create new routers and subrouters in your tRPC API + * @see https://trpc.io/docs/router + */ +export const createTRPCRouter = t.router; + +/** + * Public (unauthed) procedure + * + * This is the base piece you use to build new queries and mutations on your + * tRPC API. It does not guarantee that a user querying is authorized, but you + * can still access user session data if they are logged in + */ +export const publicProcedure = t.procedure; + +/** + * Protected (authenticated) procedure + * + * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies + * the session is valid and guarantees `ctx.session.user` is not null. + * + * @see https://trpc.io/docs/procedures + */ +export const protectedProcedure = t.procedure.use(({ ctx, next }) => { + if (!ctx.session?.user) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } + return next({ + ctx: { + // infers the `session` as non-nullable + session: { ...ctx.session, user: ctx.session.user }, + }, + }); +}); diff --git a/my-turborepo/packages/api/tsconfig.json b/my-turborepo/packages/api/tsconfig.json new file mode 100644 index 0000000..ba556ec --- /dev/null +++ b/my-turborepo/packages/api/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@acme/tsconfig/base.json", + "compilerOptions": { + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json" + }, + "include": ["src"], + "exclude": ["node_modules"] +} diff --git a/my-turborepo/packages/auth/env.js b/my-turborepo/packages/auth/env.js new file mode 100644 index 0000000..2551b6f --- /dev/null +++ b/my-turborepo/packages/auth/env.js @@ -0,0 +1,28 @@ +import { createEnv } from "@t3-oss/env-nextjs"; +import { z } from "zod"; + +export const env = createEnv({ + server: { + AUTH_DISCORD_ID: z.string().min(1), + AUTH_DISCORD_SECRET: z.string().min(1), + AUTH_SECRET: + process.env.NODE_ENV === "production" + ? z.string().min(1) + : z.string().min(1).optional(), + AUTH_URL: z.preprocess( + // This makes Vercel deployments not fail if you don't set NEXTAUTH_URL + // Since NextAuth.js automatically uses the VERCEL_URL if present. + (str) => process.env.VERCEL_URL ?? str, + // VERCEL_URL doesn't include `https` so it cant be validated as a URL + process.env.VERCEL ? z.string() : z.string().url(), + ), + }, + client: {}, + runtimeEnv: { + AUTH_DISCORD_ID: process.env.AUTH_DISCORD_ID, + AUTH_DISCORD_SECRET: process.env.AUTH_DISCORD_SECRET, + AUTH_SECRET: process.env.AUTH_SECRET, + AUTH_URL: process.env.AUTH_URL, + }, + skipValidation: !!process.env.CI || !!process.env.SKIP_ENV_VALIDATION, +}); diff --git a/my-turborepo/packages/auth/package.json b/my-turborepo/packages/auth/package.json new file mode 100644 index 0000000..fe71b56 --- /dev/null +++ b/my-turborepo/packages/auth/package.json @@ -0,0 +1,42 @@ +{ + "name": "@acme/auth", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./env": "./env.js" + }, + "license": "MIT", + "scripts": { + "clean": "rm -rf .turbo node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint .", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@acme/db": "workspace:^0.1.0", + "@auth/drizzle-adapter": "^0.3.12", + "@t3-oss/env-nextjs": "^0.7.1", + "next": "^14.0.4", + "next-auth": "5.0.0-beta.4", + "react": "18.2.0", + "react-dom": "18.2.0", + "zod": "^3.22.4" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:^0.2.0", + "@acme/prettier-config": "workspace:^0.1.0", + "@acme/tsconfig": "workspace:^0.1.0", + "eslint": "^8.56.0", + "prettier": "^3.1.1", + "typescript": "^5.3.3" + }, + "eslintConfig": { + "root": true, + "extends": [ + "@acme/eslint-config/base" + ] + }, + "prettier": "@acme/prettier-config" +} diff --git a/my-turborepo/packages/auth/src/index.ts b/my-turborepo/packages/auth/src/index.ts new file mode 100644 index 0000000..d80454c --- /dev/null +++ b/my-turborepo/packages/auth/src/index.ts @@ -0,0 +1,35 @@ +import type { DefaultSession } from "next-auth"; +import { DrizzleAdapter } from "@auth/drizzle-adapter"; +import NextAuth from "next-auth"; +import Discord from "next-auth/providers/discord"; + +import { db, tableCreator } from "@acme/db"; + +export type { Session } from "next-auth"; + +declare module "next-auth" { + interface Session { + user: { + id: string; + } & DefaultSession["user"]; + } +} + +export const { + handlers: { GET, POST }, + auth, + signIn, + signOut, +} = NextAuth({ + adapter: DrizzleAdapter(db, tableCreator), + providers: [Discord], + callbacks: { + session: ({ session, user }) => ({ + ...session, + user: { + ...session.user, + id: user.id, + }, + }), + }, +}); diff --git a/my-turborepo/packages/auth/tsconfig.json b/my-turborepo/packages/auth/tsconfig.json new file mode 100644 index 0000000..a2db6e3 --- /dev/null +++ b/my-turborepo/packages/auth/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@acme/tsconfig/base.json", + "compilerOptions": { + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json" + }, + "include": ["src", "env.js"], + "exclude": ["node_modules"] +} diff --git a/my-turborepo/packages/db/drizzle.config.ts b/my-turborepo/packages/db/drizzle.config.ts new file mode 100644 index 0000000..331a94a --- /dev/null +++ b/my-turborepo/packages/db/drizzle.config.ts @@ -0,0 +1,23 @@ +import type { Config } from "drizzle-kit"; +import * as dotenv from "dotenv"; + +dotenv.config({ path: "../../.env" }); + +const uri = [ + "mysql://", + process.env.DB_USERNAME, + ":", + process.env.DB_PASSWORD, + "@", + process.env.DB_HOST, + ":3306/", + process.env.DB_NAME, + '?ssl={"rejectUnauthorized":true}', +].join(""); + +export default { + schema: "./src/schema", + driver: "mysql2", + dbCredentials: { uri }, + tablesFilter: ["t3turbo_*"], +} satisfies Config; diff --git a/my-turborepo/packages/db/package.json b/my-turborepo/packages/db/package.json new file mode 100644 index 0000000..a9d41be --- /dev/null +++ b/my-turborepo/packages/db/package.json @@ -0,0 +1,39 @@ +{ + "name": "@acme/db", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "license": "MIT", + "scripts": { + "clean": "rm -rf .turbo node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint .", + "push": "drizzle-kit push:mysql", + "studio": "drizzle-kit studio", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@planetscale/database": "^1.13.0", + "drizzle-orm": "^0.29.2" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:^0.2.0", + "@acme/prettier-config": "workspace:^0.1.0", + "@acme/tsconfig": "workspace:^0.1.0", + "dotenv-cli": "^7.3.0", + "drizzle-kit": "^0.20.9", + "eslint": "^8.56.0", + "prettier": "^3.1.1", + "typescript": "^5.3.3" + }, + "eslintConfig": { + "root": true, + "extends": [ + "@acme/eslint-config/base" + ] + }, + "prettier": "@acme/prettier-config" +} diff --git a/my-turborepo/packages/db/src/index.ts b/my-turborepo/packages/db/src/index.ts new file mode 100644 index 0000000..f1f7e67 --- /dev/null +++ b/my-turborepo/packages/db/src/index.ts @@ -0,0 +1,19 @@ +import { connect } from "@planetscale/database"; +import { drizzle } from "drizzle-orm/planetscale-serverless"; + +import * as auth from "./schema/auth"; +import * as post from "./schema/post"; + +export const schema = { ...auth, ...post }; + +export { mySqlTable as tableCreator } from "./schema/_table"; + +export * from "drizzle-orm"; + +const connection = connect({ + host: process.env.DB_HOST!, + username: process.env.DB_USERNAME!, + password: process.env.DB_PASSWORD!, +}); + +export const db = drizzle(connection, { schema }); diff --git a/my-turborepo/packages/db/src/schema/_table.ts b/my-turborepo/packages/db/src/schema/_table.ts new file mode 100644 index 0000000..122c188 --- /dev/null +++ b/my-turborepo/packages/db/src/schema/_table.ts @@ -0,0 +1,9 @@ +import { mysqlTableCreator } from "drizzle-orm/mysql-core"; + +/** + * This is an example of how to use the multi-project schema feature of Drizzle ORM. + * Use the same database instance for multiple projects. + * + * @see https://orm.drizzle.team/docs/goodies#multi-project-schema + */ +export const mySqlTable = mysqlTableCreator((name) => `t3turbo_${name}`); diff --git a/my-turborepo/packages/db/src/schema/auth.ts b/my-turborepo/packages/db/src/schema/auth.ts new file mode 100644 index 0000000..be2c3d8 --- /dev/null +++ b/my-turborepo/packages/db/src/schema/auth.ts @@ -0,0 +1,83 @@ +import { relations, sql } from "drizzle-orm"; +import { + index, + int, + primaryKey, + text, + timestamp, + varchar, +} from "drizzle-orm/mysql-core"; + +import { mySqlTable } from "./_table"; + +export const users = mySqlTable("user", { + id: varchar("id", { length: 255 }).notNull().primaryKey(), + name: varchar("name", { length: 255 }), + email: varchar("email", { length: 255 }).notNull(), + emailVerified: timestamp("emailVerified", { + mode: "date", + fsp: 3, + }).default(sql`CURRENT_TIMESTAMP(3)`), + image: varchar("image", { length: 255 }), +}); + +export const usersRelations = relations(users, ({ many }) => ({ + accounts: many(accounts), +})); + +export const accounts = mySqlTable( + "account", + { + userId: varchar("userId", { length: 255 }).notNull(), + type: varchar("type", { length: 255 }) + .$type<"oauth" | "oidc" | "email">() + .notNull(), + provider: varchar("provider", { length: 255 }).notNull(), + providerAccountId: varchar("providerAccountId", { length: 255 }).notNull(), + refresh_token: varchar("refresh_token", { length: 255 }), + access_token: varchar("access_token", { length: 255 }), + expires_at: int("expires_at"), + token_type: varchar("token_type", { length: 255 }), + scope: varchar("scope", { length: 255 }), + id_token: text("id_token"), + session_state: varchar("session_state", { length: 255 }), + }, + (account) => ({ + compoundKey: primaryKey(account.provider, account.providerAccountId), + userIdIdx: index("userId_idx").on(account.userId), + }), +); + +export const accountsRelations = relations(accounts, ({ one }) => ({ + user: one(users, { fields: [accounts.userId], references: [users.id] }), +})); + +export const sessions = mySqlTable( + "session", + { + sessionToken: varchar("sessionToken", { length: 255 }) + .notNull() + .primaryKey(), + userId: varchar("userId", { length: 255 }).notNull(), + expires: timestamp("expires", { mode: "date" }).notNull(), + }, + (session) => ({ + userIdIdx: index("userId_idx").on(session.userId), + }), +); + +export const sessionsRelations = relations(sessions, ({ one }) => ({ + user: one(users, { fields: [sessions.userId], references: [users.id] }), +})); + +export const verificationTokens = mySqlTable( + "verificationToken", + { + identifier: varchar("identifier", { length: 255 }).notNull(), + token: varchar("token", { length: 255 }).notNull(), + expires: timestamp("expires", { mode: "date" }).notNull(), + }, + (vt) => ({ + compoundKey: primaryKey(vt.identifier, vt.token), + }), +); diff --git a/my-turborepo/packages/db/src/schema/post.ts b/my-turborepo/packages/db/src/schema/post.ts new file mode 100644 index 0000000..3b26be3 --- /dev/null +++ b/my-turborepo/packages/db/src/schema/post.ts @@ -0,0 +1,14 @@ +import { sql } from "drizzle-orm"; +import { serial, timestamp, varchar } from "drizzle-orm/mysql-core"; + +import { mySqlTable } from "./_table"; + +export const post = mySqlTable("post", { + id: serial("id").primaryKey(), + title: varchar("name", { length: 256 }).notNull(), + content: varchar("content", { length: 256 }).notNull(), + createdAt: timestamp("created_at") + .default(sql`CURRENT_TIMESTAMP`) + .notNull(), + updatedAt: timestamp("updatedAt").onUpdateNow(), +}); diff --git a/my-turborepo/packages/db/tsconfig.json b/my-turborepo/packages/db/tsconfig.json new file mode 100644 index 0000000..5b3b782 --- /dev/null +++ b/my-turborepo/packages/db/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@acme/tsconfig/base.json", + "compilerOptions": { + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json" + }, + "include": ["src", "drizzle.config.ts"], + "exclude": ["node_modules"] +} diff --git a/my-turborepo/packages/ui/package.json b/my-turborepo/packages/ui/package.json new file mode 100644 index 0000000..4b5bf73 --- /dev/null +++ b/my-turborepo/packages/ui/package.json @@ -0,0 +1,57 @@ +{ + "name": "@acme/ui", + "private": true, + "version": "0.1.0", + "type": "module", + "exports": { + ".": "./src/index.ts", + "./button": "./src/button.tsx", + "./form": "./src/form.tsx", + "./input": "./src/input.tsx", + "./label": "./src/label.tsx", + "./theme": "./src/theme.tsx", + "./toast": "./src/toast.tsx" + }, + "license": "MIT", + "scripts": { + "add": "pnpm dlx shadcn-ui add", + "clean": "rm -rf .turbo node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint .", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@hookform/resolvers": "^3.3.3", + "@radix-ui/react-dropdown-menu": "^2.0.6", + "@radix-ui/react-icons": "^1.3.0", + "@radix-ui/react-label": "^2.0.2", + "@radix-ui/react-slot": "^1.0.2", + "class-variance-authority": "^0.7.0", + "next-themes": "^0.2.1", + "react-hook-form": "^7.49.2", + "sonner": "^1.3.1", + "tailwind-merge": "^2.2.0", + "tailwindcss-animate": "^1.0.7" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:^0.2.0", + "@acme/prettier-config": "workspace:^0.1.0", + "@acme/tailwind-config": "workspace:^0.1.0", + "@acme/tsconfig": "workspace:^0.1.0", + "eslint": "^8.56.0", + "prettier": "^3.1.1", + "tailwindcss": "^3.4.0", + "typescript": "^5.3.3", + "zod": "^3.22.4" + }, + "peerDependencies": { + "zod": "^3.22.4" + }, + "eslintConfig": { + "extends": [ + "@acme/eslint-config/base", + "@acme/eslint-config/react" + ] + }, + "prettier": "@acme/prettier-config" +} diff --git a/my-turborepo/packages/ui/src/button.tsx b/my-turborepo/packages/ui/src/button.tsx new file mode 100644 index 0000000..19fa944 --- /dev/null +++ b/my-turborepo/packages/ui/src/button.tsx @@ -0,0 +1,58 @@ +import type { VariantProps } from "class-variance-authority"; +import * as React from "react"; +import { Slot } from "@radix-ui/react-slot"; +import { cva } from "class-variance-authority"; + +import { cn } from "."; + +const buttonVariants = cva( + "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", + { + variants: { + variant: { + primary: + "bg-primary text-primary-foreground shadow hover:bg-primary/90", + destructive: + "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", + outline: + "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", + secondary: + "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + sm: "h-8 rounded-md px-3 text-xs", + md: "h-9 px-4 py-2", + lg: "h-10 rounded-md px-8", + icon: "size-9", + }, + }, + defaultVariants: { + variant: "primary", + size: "md", + }, + }, +); + +interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean; +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button"; + return ( + + ); + }, +); +Button.displayName = "Button"; + +export { Button, buttonVariants }; diff --git a/my-turborepo/packages/ui/src/dropdown-menu.tsx b/my-turborepo/packages/ui/src/dropdown-menu.tsx new file mode 100644 index 0000000..5ea9f27 --- /dev/null +++ b/my-turborepo/packages/ui/src/dropdown-menu.tsx @@ -0,0 +1,200 @@ +"use client"; + +import * as React from "react"; +import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; +import { + CheckIcon, + ChevronRightIcon, + DotFilledIcon, +} from "@radix-ui/react-icons"; + +import { cn } from "."; + +const DropdownMenu = DropdownMenuPrimitive.Root; +const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger; +const DropdownMenuGroup = DropdownMenuPrimitive.Group; +const DropdownMenuPortal = DropdownMenuPrimitive.Portal; +const DropdownMenuSub = DropdownMenuPrimitive.Sub; +const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup; + +const DropdownMenuSubTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, children, ...props }, ref) => ( + + {children} + + +)); +DropdownMenuSubTrigger.displayName = + DropdownMenuPrimitive.SubTrigger.displayName; + +const DropdownMenuSubContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DropdownMenuSubContent.displayName = + DropdownMenuPrimitive.SubContent.displayName; + +const DropdownMenuContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, sideOffset = 4, ...props }, ref) => ( + + + +)); +DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName; + +const DropdownMenuItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + +)); +DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName; + +const DropdownMenuCheckboxItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, checked, ...props }, ref) => ( + + + + + + + {children} + +)); +DropdownMenuCheckboxItem.displayName = + DropdownMenuPrimitive.CheckboxItem.displayName; + +const DropdownMenuRadioItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + + + + {children} + +)); +DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName; + +const DropdownMenuLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + +)); +DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName; + +const DropdownMenuSeparator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName; + +const DropdownMenuShortcut = ({ + className, + ...props +}: React.HTMLAttributes) => { + return ( + + ); +}; +DropdownMenuShortcut.displayName = "DropdownMenuShortcut"; + +export { + DropdownMenu, + DropdownMenuTrigger, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuCheckboxItem, + DropdownMenuRadioItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuGroup, + DropdownMenuPortal, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuRadioGroup, +}; diff --git a/my-turborepo/packages/ui/src/form.tsx b/my-turborepo/packages/ui/src/form.tsx new file mode 100644 index 0000000..30de18d --- /dev/null +++ b/my-turborepo/packages/ui/src/form.tsx @@ -0,0 +1,201 @@ +"use client"; + +import type * as LabelPrimitive from "@radix-ui/react-label"; +import type { + ControllerProps, + FieldPath, + FieldValues, + UseFormProps, +} from "react-hook-form"; +import type { ZodType } from "zod"; +import * as React from "react"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { Slot } from "@radix-ui/react-slot"; +import { + useForm as __useForm, + Controller, + FormProvider, + useFormContext, +} from "react-hook-form"; + +import { cn } from "."; +import { Label } from "./label"; + +function useForm( + props: Omit, "resolver"> & { + schema: TSchema; + }, +) { + const form = __useForm({ + ...props, + resolver: zodResolver(props.schema, undefined), + }); + + return form; +} + +const Form = FormProvider; + +interface FormFieldContextValue< + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath = FieldPath, +> { + name: TName; +} + +const FormFieldContext = React.createContext( + {} as FormFieldContextValue, +); + +const FormField = < + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath = FieldPath, +>({ + ...props +}: ControllerProps) => { + return ( + + + + ); +}; + +const useFormField = () => { + const fieldContext = React.useContext(FormFieldContext); + const itemContext = React.useContext(FormItemContext); + const { getFieldState, formState } = useFormContext(); + + const fieldState = getFieldState(fieldContext.name, formState); + + if (!fieldContext) { + throw new Error("useFormField should be used within "); + } + + const { id } = itemContext; + + return { + id, + name: fieldContext.name, + formItemId: `${id}-form-item`, + formDescriptionId: `${id}-form-item-description`, + formMessageId: `${id}-form-item-message`, + ...fieldState, + }; +}; + +interface FormItemContextValue { + id: string; +} + +const FormItemContext = React.createContext( + {} as FormItemContextValue, +); + +const FormItem = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => { + const id = React.useId(); + + return ( + +
+ + ); +}); +FormItem.displayName = "FormItem"; + +const FormLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => { + const { error, formItemId } = useFormField(); + + return ( +
- {errors.slug && {errors.slug.message}} - -
- -