commit 693a10957c049ff5fc34ee70d5b45b2d02bc0eb1 Author: gibbyb Date: Tue Oct 28 10:57:53 2025 -0500 init commit diff --git a/.cursor/rules/convex_rules.mdc b/.cursor/rules/convex_rules.mdc new file mode 100644 index 0000000..1d98480 --- /dev/null +++ b/.cursor/rules/convex_rules.mdc @@ -0,0 +1,676 @@ +--- +description: Guidelines and best practices for building Convex projects, including database schema design, queries, mutations, and real-world examples +globs: **/*.ts,**/*.tsx,**/*.js,**/*.jsx +--- + +# Convex guidelines +## Function guidelines +### New function syntax +- ALWAYS use the new function syntax for Convex functions. For example: +```typescript +import { query } from "./_generated/server"; +import { v } from "convex/values"; +export const f = query({ + args: {}, + returns: v.null(), + handler: async (ctx, args) => { + // Function body + }, +}); +``` + +### Http endpoint syntax +- HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example: +```typescript +import { httpRouter } from "convex/server"; +import { httpAction } from "./_generated/server"; +const http = httpRouter(); +http.route({ + path: "/echo", + method: "POST", + handler: httpAction(async (ctx, req) => { + const body = await req.bytes(); + return new Response(body, { status: 200 }); + }), +}); +``` +- HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`. + +### Validators +- Below is an example of an array validator: +```typescript +import { mutation } from "./_generated/server"; +import { v } from "convex/values"; + +export default mutation({ +args: { + simpleArray: v.array(v.union(v.string(), v.number())), +}, +handler: async (ctx, args) => { + //... +}, +}); +``` +- Below is an example of a schema with validators that codify a discriminated union type: +```typescript +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + results: defineTable( + v.union( + v.object({ + kind: v.literal("error"), + errorMessage: v.string(), + }), + v.object({ + kind: v.literal("success"), + value: v.number(), + }), + ), + ) +}); +``` +- Always use the `v.null()` validator when returning a null value. Below is an example query that returns a null value: +```typescript +import { query } from "./_generated/server"; +import { v } from "convex/values"; + +export const exampleQuery = query({ + args: {}, + returns: v.null(), + handler: async (ctx, args) => { + console.log("This query returns a null value"); + return null; + }, +}); +``` +- Here are the valid Convex types along with their respective validators: +Convex Type | TS/JS type | Example Usage | Validator for argument validation and schemas | Notes | +| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Id | string | `doc._id` | `v.id(tableName)` | | +| Null | null | `null` | `v.null()` | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead. | +| Int64 | bigint | `3n` | `v.int64()` | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers. | +| Float64 | number | `3.1` | `v.number()` | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings. | +| Boolean | boolean | `true` | `v.boolean()` | +| String | string | `"abc"` | `v.string()` | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8. | +| Bytes | ArrayBuffer | `new ArrayBuffer(8)` | `v.bytes()` | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types. | +| Array | Array | `[1, 3.2, "abc"]` | `v.array(values)` | Arrays can have at most 8192 values. | +| Object | Object | `{a: "abc"}` | `v.object({property: value})` | Convex only supports "plain old JavaScript objects" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with "$" or "_". | +| Record | Record | `{"a": "1", "b": "2"}` | `v.record(keys, values)` | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with "$" or "_". | + +### Function registration +- Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`. +- Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private. +- You CANNOT register a function through the `api` or `internal` objects. +- ALWAYS include argument and return validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`. If a function doesn't return anything, include `returns: v.null()` as its output validator. +- If the JavaScript implementation of a Convex function doesn't have a return value, it implicitly returns `null`. + +### Function calling +- Use `ctx.runQuery` to call a query from a query, mutation, or action. +- Use `ctx.runMutation` to call a mutation from a mutation or action. +- Use `ctx.runAction` to call an action from an action. +- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead. +- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions. +- All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls. +- When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example, +``` +export const f = query({ + args: { name: v.string() }, + returns: v.string(), + handler: async (ctx, args) => { + return "Hello " + args.name; + }, +}); + +export const g = query({ + args: {}, + returns: v.null(), + handler: async (ctx, args) => { + const result: string = await ctx.runQuery(api.example.f, { name: "Bob" }); + return null; + }, +}); +``` + +### Function references +- Function references are pointers to registered Convex functions. +- Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`. +- Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`. +- Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`. +- A private function defined in `convex/example.ts` named `g` has a function reference of `internal.example.g`. +- Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`. + +### Api design +- Convex uses file-based routing, so thoughtfully organize files with public query, mutation, or action functions within the `convex/` directory. +- Use `query`, `mutation`, and `action` to define public functions. +- Use `internalQuery`, `internalMutation`, and `internalAction` to define private, internal functions. + +### Pagination +- Paginated queries are queries that return a list of results in incremental pages. +- You can define pagination using the following syntax: + +```ts +import { v } from "convex/values"; +import { query, mutation } from "./_generated/server"; +import { paginationOptsValidator } from "convex/server"; +export const listWithExtraArg = query({ + args: { paginationOpts: paginationOptsValidator, author: v.string() }, + handler: async (ctx, args) => { + return await ctx.db + .query("messages") + .filter((q) => q.eq(q.field("author"), args.author)) + .order("desc") + .paginate(args.paginationOpts); + }, +}); +``` +Note: `paginationOpts` is an object with the following properties: +- `numItems`: the maximum number of documents to return (the validator is `v.number()`) +- `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`) +- A query that ends in `.paginate()` returns an object that has the following properties: + - page (contains an array of documents that you fetches) + - isDone (a boolean that represents whether or not this is the last page of documents) + - continueCursor (a string that represents the cursor to use to fetch the next page of documents) + + +## Validator guidelines +- `v.bigint()` is deprecated for representing signed 64-bit integers. Use `v.int64()` instead. +- Use `v.record()` for defining a record type. `v.map()` and `v.set()` are not supported. + +## Schema guidelines +- Always define your schema in `convex/schema.ts`. +- Always import the schema definition functions from `convex/server`: +- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`. +- Always include all index fields in the index name. For example, if an index is defined as `["field1", "field2"]`, the index name should be "by_field1_and_field2". +- Index fields must be queried in the same order they are defined. If you want to be able to query by "field1" then "field2" and by "field2" then "field1", you must create separate indexes. + +## Typescript guidelines +- You can use the helper typescript type `Id` imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table. +- If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record, string>`. Below is an example of using `Record` with an `Id` type in a query: +```ts +import { query } from "./_generated/server"; +import { Doc, Id } from "./_generated/dataModel"; + +export const exampleQuery = query({ + args: { userIds: v.array(v.id("users")) }, + returns: v.record(v.id("users"), v.string()), + handler: async (ctx, args) => { + const idToUsername: Record, string> = {}; + for (const userId of args.userIds) { + const user = await ctx.db.get(userId); + if (user) { + idToUsername[user._id] = user.username; + } + } + + return idToUsername; + }, +}); +``` +- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`. +- Always use `as const` for string literals in discriminated union types. +- When using the `Array` type, make sure to always define your arrays as `const array: Array = [...];` +- When using the `Record` type, make sure to always define your records as `const record: Record = {...};` +- Always add `@types/node` to your `package.json` when using any Node.js built-in modules. + +## Full text search guidelines +- A query for "10 messages in channel '#general' that best match the query 'hello hi' in their body" would look like: + +const messages = await ctx.db + .query("messages") + .withSearchIndex("search_body", (q) => + q.search("body", "hello hi").eq("channel", "#general"), + ) + .take(10); + +## Query guidelines +- Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead. +- Convex queries do NOT support `.delete()`. Instead, `.collect()` the results, iterate over them, and call `ctx.db.delete(row._id)` on each result. +- Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query. +- When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax. +### Ordering +- By default Convex always returns documents in ascending `_creationTime` order. +- You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending. +- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans. + + +## Mutation guidelines +- Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist. +- Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist. + +## Action guidelines +- Always add `"use node";` to the top of files containing actions that use Node.js built-in modules. +- Never use `ctx.db` inside of an action. Actions don't have access to the database. +- Below is an example of the syntax for an action: +```ts +import { action } from "./_generated/server"; + +export const exampleAction = action({ + args: {}, + returns: v.null(), + handler: async (ctx, args) => { + console.log("This action does not return anything"); + return null; + }, +}); +``` + +## Scheduling guidelines +### Cron guidelines +- Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers. +- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods. +- Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example, +```ts +import { cronJobs } from "convex/server"; +import { internal } from "./_generated/api"; +import { internalAction } from "./_generated/server"; + +const empty = internalAction({ + args: {}, + returns: v.null(), + handler: async (ctx, args) => { + console.log("empty"); + }, +}); + +const crons = cronJobs(); + +// Run `internal.crons.empty` every two hours. +crons.interval("delete inactive users", { hours: 2 }, internal.crons.empty, {}); + +export default crons; +``` +- You can register Convex functions within `crons.ts` just like any other file. +- If a cron calls an internal function, always import the `internal` object from '_generated/api', even if the internal function is registered in the same file. + + +## File storage guidelines +- Convex includes file storage for large files like images, videos, and PDFs. +- The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist. +- Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata. + + Instead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<"_storage">`. +``` +import { query } from "./_generated/server"; +import { Id } from "./_generated/dataModel"; + +type FileMetadata = { + _id: Id<"_storage">; + _creationTime: number; + contentType?: string; + sha256: string; + size: number; +} + +export const exampleQuery = query({ + args: { fileId: v.id("_storage") }, + returns: v.null(), + handler: async (ctx, args) => { + const metadata: FileMetadata | null = await ctx.db.system.get(args.fileId); + console.log(metadata); + return null; + }, +}); +``` +- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage. + + +# Examples: +## Example: chat-app + +### Task +``` +Create a real-time chat application backend with AI responses. The app should: +- Allow creating users with names +- Support multiple chat channels +- Enable users to send messages to channels +- Automatically generate AI responses to user messages +- Show recent message history + +The backend should provide APIs for: +1. User management (creation) +2. Channel management (creation) +3. Message operations (sending, listing) +4. AI response generation using OpenAI's GPT-4 + +Messages should be stored with their channel, author, and content. The system should maintain message order +and limit history display to the 10 most recent messages per channel. + +``` + +### Analysis +1. Task Requirements Summary: +- Build a real-time chat backend with AI integration +- Support user creation +- Enable channel-based conversations +- Store and retrieve messages with proper ordering +- Generate AI responses automatically + +2. Main Components Needed: +- Database tables: users, channels, messages +- Public APIs for user/channel management +- Message handling functions +- Internal AI response generation system +- Context loading for AI responses + +3. Public API and Internal Functions Design: +Public Mutations: +- createUser: + - file path: convex/index.ts + - arguments: {name: v.string()} + - returns: v.object({userId: v.id("users")}) + - purpose: Create a new user with a given name +- createChannel: + - file path: convex/index.ts + - arguments: {name: v.string()} + - returns: v.object({channelId: v.id("channels")}) + - purpose: Create a new channel with a given name +- sendMessage: + - file path: convex/index.ts + - arguments: {channelId: v.id("channels"), authorId: v.id("users"), content: v.string()} + - returns: v.null() + - purpose: Send a message to a channel and schedule a response from the AI + +Public Queries: +- listMessages: + - file path: convex/index.ts + - arguments: {channelId: v.id("channels")} + - returns: v.array(v.object({ + _id: v.id("messages"), + _creationTime: v.number(), + channelId: v.id("channels"), + authorId: v.optional(v.id("users")), + content: v.string(), + })) + - purpose: List the 10 most recent messages from a channel in descending creation order + +Internal Functions: +- generateResponse: + - file path: convex/index.ts + - arguments: {channelId: v.id("channels")} + - returns: v.null() + - purpose: Generate a response from the AI for a given channel +- loadContext: + - file path: convex/index.ts + - arguments: {channelId: v.id("channels")} + - returns: v.array(v.object({ + _id: v.id("messages"), + _creationTime: v.number(), + channelId: v.id("channels"), + authorId: v.optional(v.id("users")), + content: v.string(), + })) +- writeAgentResponse: + - file path: convex/index.ts + - arguments: {channelId: v.id("channels"), content: v.string()} + - returns: v.null() + - purpose: Write an AI response to a given channel + +4. Schema Design: +- users + - validator: { name: v.string() } + - indexes: +- channels + - validator: { name: v.string() } + - indexes: +- messages + - validator: { channelId: v.id("channels"), authorId: v.optional(v.id("users")), content: v.string() } + - indexes + - by_channel: ["channelId"] + +5. Background Processing: +- AI response generation runs asynchronously after each user message +- Uses OpenAI's GPT-4 to generate contextual responses +- Maintains conversation context using recent message history + + +### Implementation + +#### package.json +```typescript +{ + "name": "chat-app", + "description": "This example shows how to build a chat app without authentication.", + "version": "1.0.0", + "dependencies": { + "convex": "^1.17.4", + "openai": "^4.79.0" + }, + "devDependencies": { + "typescript": "^5.7.3" + } +} +``` + +#### tsconfig.json +```typescript +{ + "compilerOptions": { + "target": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ESNext"], + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "jsx": "react-jsx" + }, + "exclude": ["convex"], + "include": ["**/src/**/*.tsx", "**/src/**/*.ts", "vite.config.ts"] +} +``` + +#### convex/index.ts +```typescript +import { + query, + mutation, + internalQuery, + internalMutation, + internalAction, +} from "./_generated/server"; +import { v } from "convex/values"; +import OpenAI from "openai"; +import { internal } from "./_generated/api"; + +/** + * Create a user with a given name. + */ +export const createUser = mutation({ + args: { + name: v.string(), + }, + returns: v.id("users"), + handler: async (ctx, args) => { + return await ctx.db.insert("users", { name: args.name }); + }, +}); + +/** + * Create a channel with a given name. + */ +export const createChannel = mutation({ + args: { + name: v.string(), + }, + returns: v.id("channels"), + handler: async (ctx, args) => { + return await ctx.db.insert("channels", { name: args.name }); + }, +}); + +/** + * List the 10 most recent messages from a channel in descending creation order. + */ +export const listMessages = query({ + args: { + channelId: v.id("channels"), + }, + returns: v.array( + v.object({ + _id: v.id("messages"), + _creationTime: v.number(), + channelId: v.id("channels"), + authorId: v.optional(v.id("users")), + content: v.string(), + }), + ), + handler: async (ctx, args) => { + const messages = await ctx.db + .query("messages") + .withIndex("by_channel", (q) => q.eq("channelId", args.channelId)) + .order("desc") + .take(10); + return messages; + }, +}); + +/** + * Send a message to a channel and schedule a response from the AI. + */ +export const sendMessage = mutation({ + args: { + channelId: v.id("channels"), + authorId: v.id("users"), + content: v.string(), + }, + returns: v.null(), + handler: async (ctx, args) => { + const channel = await ctx.db.get(args.channelId); + if (!channel) { + throw new Error("Channel not found"); + } + const user = await ctx.db.get(args.authorId); + if (!user) { + throw new Error("User not found"); + } + await ctx.db.insert("messages", { + channelId: args.channelId, + authorId: args.authorId, + content: args.content, + }); + await ctx.scheduler.runAfter(0, internal.index.generateResponse, { + channelId: args.channelId, + }); + return null; + }, +}); + +const openai = new OpenAI(); + +export const generateResponse = internalAction({ + args: { + channelId: v.id("channels"), + }, + returns: v.null(), + handler: async (ctx, args) => { + const context = await ctx.runQuery(internal.index.loadContext, { + channelId: args.channelId, + }); + const response = await openai.chat.completions.create({ + model: "gpt-4o", + messages: context, + }); + const content = response.choices[0].message.content; + if (!content) { + throw new Error("No content in response"); + } + await ctx.runMutation(internal.index.writeAgentResponse, { + channelId: args.channelId, + content, + }); + return null; + }, +}); + +export const loadContext = internalQuery({ + args: { + channelId: v.id("channels"), + }, + returns: v.array( + v.object({ + role: v.union(v.literal("user"), v.literal("assistant")), + content: v.string(), + }), + ), + handler: async (ctx, args) => { + const channel = await ctx.db.get(args.channelId); + if (!channel) { + throw new Error("Channel not found"); + } + const messages = await ctx.db + .query("messages") + .withIndex("by_channel", (q) => q.eq("channelId", args.channelId)) + .order("desc") + .take(10); + + const result = []; + for (const message of messages) { + if (message.authorId) { + const user = await ctx.db.get(message.authorId); + if (!user) { + throw new Error("User not found"); + } + result.push({ + role: "user" as const, + content: `${user.name}: ${message.content}`, + }); + } else { + result.push({ role: "assistant" as const, content: message.content }); + } + } + return result; + }, +}); + +export const writeAgentResponse = internalMutation({ + args: { + channelId: v.id("channels"), + content: v.string(), + }, + returns: v.null(), + handler: async (ctx, args) => { + await ctx.db.insert("messages", { + channelId: args.channelId, + content: args.content, + }); + return null; + }, +}); +``` + +#### convex/schema.ts +```typescript +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + channels: defineTable({ + name: v.string(), + }), + + users: defineTable({ + name: v.string(), + }), + + messages: defineTable({ + channelId: v.id("channels"), + authorId: v.optional(v.id("users")), + content: v.string(), + }).index("by_channel", ["channelId"]), +}); +``` + +#### src/App.tsx +```typescript +export default function App() { + return
Hello World
; +} +``` + diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..690faf4 --- /dev/null +++ b/.env.example @@ -0,0 +1,23 @@ +# 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. +NODE_ENV= +CI= +SKIP_ENV_VALIDATION= +CONVEX_SELF_HOSTED_URL= +CONVEX_SELF_HOSTED_ADMIN_KEY= +CONVEX_AUTH_URL= +SITE_URL= +USESEND_API_KEY= +AUTH_AUTHENTIK_ID= +AUTH_AUTHENTIK_SECRET= +AUTH_AUTHENTIK_ISSUER= +AUTH_MICROSOFT_ENTRA_ID_ID= +AUTH_MICROSOFT_ENTRA_ID_SECRET= +AUTH_MICROSOFT_ENTRA_ID_ISSUER= +AUTH_MICROSOFT_ENTRA_ID_AUTH_UR= +SENTRY_AUTH_TOKEN= +SENTRY_DSN= +SENTRY_ORG= +SENTRY_PROJECT_NAME= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8c8e366 --- /dev/null +++ b/.gitignore @@ -0,0 +1,53 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +node_modules +.pnp +.pnp.js + +# testing +coverage + +# next.js +.next/ +.swc/ +out/ +next-env.d.ts + +# production +build + +# nitro +.nitro/ +.output/ + +# expo +.expo/ +expo-env.d.ts +apps/expo/.gitignore +apps/expo/ios +apps/expo/android + +# misc +.DS_Store +*.pem +dist + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +.env.local +.env.development.local +.env.test.local +.env.production.local +.env + +# turbo +.turbo + +# tanstack +.tanstack diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..131fb14 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,3 @@ +{ + "arrowParens": "always" +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b615b0f --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Convex, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..65b1c38 --- /dev/null +++ b/README.md @@ -0,0 +1,190 @@ +# Fullstack monorepo template feat. Expo, Turbo, Next.js, Convex, Clerk + +This is a modern TypeScript monorepo template with AI web and native apps +featuring: + +- Turborepo: Monorepo management +- React 19: Latest React with concurrent features +- Next.js 15: Web app & marketing page with App Router +- Tailwind CSS v4: Modern CSS-first configuration +- React Native [Expo](https://expo.dev/): Mobile/native app with New Architecture +- [Convex](https://convex.dev): Backend, database, server functions +- [Clerk](https://clerk.dev): User authentication +- OpenAI: Text summarization (optional) + +The example app is a note taking app that can summarize notes using AI. Features +include: + +- Marketing page +- Dashboard page (web & native) +- Note taking page (web & native) +- Backend API that serves web & native with the same API +- Relational database +- End to end type safety (schema definition to frontend API clients) +- User authentication +- Asynchronous call to an OpenAI +- Everything is realtime by default + +## Using this example + +### 1. Install dependencies + +If you don't have `yarn` installed, run `npm install --global yarn`. + +Run `yarn`. + +### 2. Configure Convex + +> Note: The following command will print an error and ask you to add the +> appropriate environment variable to proceed. Continue reading on for how to do +> that. + +```sh +npm run setup --workspace packages/backend +``` + +The script will log you into Convex if you aren't already and prompt you to +create a project (free). It will then wait to deploy your code until you set the +environment variables in the dashboard. + +Configure Clerk with [this guide](https://docs.convex.dev/auth/clerk). Then add +the `CLERK_ISSUER_URL` found in the "convex" template +[here](https://dashboard.clerk.com/last-active?path=jwt-templates), to your +Convex environment variables +[here](https://dashboard.convex.dev/deployment/settings/environment-variables&var=CLERK_ISSUER_URL). + +Make sure to enable **Google and Apple** as possible Social Connection +providers, as these are used by the React Native login implementation. + +After that, optionally add the `OPENAI_API_KEY` env var from +[OpenAI](https://platform.openai.com/account/api-keys) to your Convex +environment variables to get AI summaries. + +The `setup` command should now finish successfully. + +### 3. Configure both apps + +In each app directory (`apps/web`, `apps/native`) create a `.env.local` file +using the `.example.env` as a template and fill out your Convex and Clerk +environment variables. + +- Use the `CONVEX_URL` from `packages/backend/.env.local` for + `{NEXT,EXPO}_PUBLIC_CONVEX_URL`. +- The Clerk publishable & secret keys can be found + [here](https://dashboard.clerk.com/last-active?path=api-keys). + +### 4. Run both apps + +Run the following command to run both the web and mobile apps: + +```sh +npm run dev +``` + +This will allow you to use the ⬆ and ⬇ keyboard keys to see logs for each +of the Convex backend, web app, and mobile app separately. +If you'd rather see all of the logs in one place, delete the +`"ui": "tui",` line in [turbo.json](./turbo.json). + +## Deploying + +In order to both deploy the frontend and Convex, run this as the build command from the apps/web directory: + +```sh +cd ../../packages/backend && npx convex deploy --cmd 'cd ../../apps/web && turbo run build' --cmd-url-env-var-name NEXT_PUBLIC_CONVEX_URL +``` + +There is a vercel.json file in the apps/web directory with this configuration for Vercel. + +## What's inside? + +This monorepo template includes the following packages/apps: + +### Apps and Packages + +- `web`: a [Next.js 15](https://nextjs.org/) app with Tailwind CSS and Clerk +- `native`: a [React Native](https://reactnative.dev/) app built with + [expo](https://docs.expo.dev/) +- `packages/backend`: a [Convex](https://www.convex.dev/) folder with the + database schema and shared functions + +Each package/app is 100% [TypeScript](https://www.typescriptlang.org/). + +To install a new package, `cd` into that directory, such as [packages/backend](./packages/backend/), and then run `yarn add mypackage@latest` + +### Utilities + +This Turborepo has some additional tools already setup for you: + +- [Expo](https://docs.expo.dev/) for native development +- [TypeScript](https://www.typescriptlang.org/) for static type checking +- [Prettier](https://prettier.io) for code formatting + +# What is Convex? + +[Convex](https://convex.dev) is a hosted backend platform with a built-in +reactive database that lets you write your +[database schema](https://docs.convex.dev/database/schemas) and +[server functions](https://docs.convex.dev/functions) in +[TypeScript](https://docs.convex.dev/typescript). Server-side database +[queries](https://docs.convex.dev/functions/query-functions) automatically +[cache](https://docs.convex.dev/functions/query-functions#caching--reactivity) +and [subscribe](https://docs.convex.dev/client/react#reactivity) to data, +powering a +[realtime `useQuery` hook](https://docs.convex.dev/client/react#fetching-data) +in our [React client](https://docs.convex.dev/client/react). There are also +clients for [Python](https://docs.convex.dev/client/python), +[Rust](https://docs.convex.dev/client/rust), +[ReactNative](https://docs.convex.dev/client/react-native), and +[Node](https://docs.convex.dev/client/javascript), as well as a straightforward +[HTTP API](https://github.com/get-convex/convex-js/blob/main/src/browser/http_client.ts#L40). + +The database supports +[NoSQL-style documents](https://docs.convex.dev/database/document-storage) with +[relationships](https://docs.convex.dev/database/document-ids) and +[custom indexes](https://docs.convex.dev/database/indexes/) (including on fields +in nested objects). + +The [`query`](https://docs.convex.dev/functions/query-functions) and +[`mutation`](https://docs.convex.dev/functions/mutation-functions) server +functions have transactional, low latency access to the database and leverage +our [`v8` runtime](https://docs.convex.dev/functions/runtimes) with +[determinism guardrails](https://docs.convex.dev/functions/runtimes#using-randomness-and-time-in-queries-and-mutations) +to provide the strongest ACID guarantees on the market: immediate consistency, +serializable isolation, and automatic conflict resolution via +[optimistic multi-version concurrency control](https://docs.convex.dev/database/advanced/occ) +(OCC / MVCC). + +The [`action` server functions](https://docs.convex.dev/functions/actions) have +access to external APIs and enable other side-effects and non-determinism in +either our [optimized `v8` runtime](https://docs.convex.dev/functions/runtimes) +or a more +[flexible `node` runtime](https://docs.convex.dev/functions/runtimes#nodejs-runtime). + +Functions can run in the background via +[scheduling](https://docs.convex.dev/scheduling/scheduled-functions) and +[cron jobs](https://docs.convex.dev/scheduling/cron-jobs). + +Development is cloud-first, with +[hot reloads for server function](https://docs.convex.dev/cli#run-the-convex-dev-server) +editing via the [CLI](https://docs.convex.dev/cli). There is a +[dashboard UI](https://docs.convex.dev/dashboard) to +[browse and edit data](https://docs.convex.dev/dashboard/deployments/data), +[edit environment variables](https://docs.convex.dev/production/environment-variables), +[view logs](https://docs.convex.dev/dashboard/deployments/logs), +[run server functions](https://docs.convex.dev/dashboard/deployments/functions), +and more. + +There are built-in features for +[reactive pagination](https://docs.convex.dev/database/pagination), +[file storage](https://docs.convex.dev/file-storage), +[reactive search](https://docs.convex.dev/text-search), +[https endpoints](https://docs.convex.dev/functions/http-actions) (for +webhooks), +[streaming import/export](https://docs.convex.dev/database/import-export/), and +[runtime data validation](https://docs.convex.dev/database/schemas#validators) +for [function arguments](https://docs.convex.dev/functions/args-validation) and +[database data](https://docs.convex.dev/database/schemas#schema-validation). + +Everything scales automatically, and it’s +[free to start](https://www.convex.dev/plans). diff --git a/apps/expo/.cache/.prettiercache b/apps/expo/.cache/.prettiercache new file mode 100644 index 0000000..f11a096 --- /dev/null +++ b/apps/expo/.cache/.prettiercache @@ -0,0 +1 @@ +[["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21"],{"key":"22","value":"23"},{"key":"24","value":"25"},{"key":"26","value":"27"},{"key":"28","value":"29"},{"key":"30","value":"31"},{"key":"32","value":"33"},{"key":"34","value":"35"},{"key":"36","value":"37"},{"key":"38","value":"39"},{"key":"40","value":"41"},{"key":"42","value":"43"},{"key":"44","value":"45"},{"key":"46","value":"47"},{"key":"48","value":"49"},{"key":"50","value":"51"},{"key":"52","value":"53"},{"key":"54","value":"55"},{"key":"56","value":"57"},{"key":"58","value":"59"},{"key":"60","value":"61"},{"key":"62","value":"63"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/eslint.config.mts",{"size":276,"mtime":1761443987000,"hash":"64","data":"65"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/src/app/index.tsx",{"size":5019,"mtime":1761443987000,"hash":"66","data":"67"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/app.config.ts",{"size":1333,"mtime":1761443987000,"hash":"68","data":"69"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/package.json",{"size":1736,"mtime":1761665033217,"hash":"70","data":"71"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/src/app/_layout.tsx",{"size":927,"mtime":1761443987000,"hash":"72","data":"73"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/metro.config.js",{"size":511,"mtime":1761443987000,"hash":"74","data":"75"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/src/utils/auth.ts",{"size":398,"mtime":1761443987000,"hash":"76","data":"77"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/index.ts",{"size":28,"mtime":1761443987000,"hash":"78","data":"79"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/src/utils/api.tsx",{"size":1327,"mtime":1761443987000,"hash":"80","data":"81"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/src/utils/session-store.ts",{"size":272,"mtime":1761443987000,"hash":"82","data":"83"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/turbo.json",{"size":163,"mtime":1761443987000,"hash":"84","data":"85"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/assets/icon-light.png",{"size":19133,"mtime":1761443987000,"hash":"86"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/eas.json",{"size":567,"mtime":1761443987000,"hash":"87","data":"88"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/postcss.config.js",{"size":66,"mtime":1761443987000,"hash":"89","data":"90"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/src/app/post/[id].tsx",{"size":757,"mtime":1761443987000,"hash":"91","data":"92"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/assets/icon-dark.png",{"size":19633,"mtime":1761443987000,"hash":"93"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/src/styles.css",{"size":90,"mtime":1761443987000,"hash":"94","data":"95"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/tsconfig.json",{"size":388,"mtime":1761663711587,"hash":"96","data":"97"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/src/utils/base-url.ts",{"size":880,"mtime":1761443987000,"hash":"98","data":"99"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/.expo-shared/assets.json",{"size":155,"mtime":1761443987000,"hash":"100","data":"101"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/expo/nativewind-env.d.ts",{"size":246,"mtime":1761443987000,"hash":"102","data":"103"},"3157b700ecbb4aa217059352507464a2",{"hashOfOptions":"104"},"2be11479779af34f59ec5003513b8e0b",{"hashOfOptions":"105"},"bd476a3950d078330d3e06a560e9f747",{"hashOfOptions":"106"},"f137cf230cf525ca8c2f0bdf233a6e3f",{"hashOfOptions":"107"},"518cd9c33ede87c649b01dd727bb00a0",{"hashOfOptions":"108"},"fbe52c661bc5cbe8d2f7c1058981b896",{"hashOfOptions":"109"},"9455acf80595f4373e11d98e5bc87d89",{"hashOfOptions":"110"},"cc3395d2be4587e21093428fdb6f69e6",{"hashOfOptions":"111"},"0adb5df94af971795b21eddb560c26b5",{"hashOfOptions":"112"},"691dcf997a384f03d1ba5c043c1a3405",{"hashOfOptions":"113"},"c7d4dcf839dfeaa02e0407adfd5e47a6",{"hashOfOptions":"114"},"863da15dbd856008b7c24077ca746d91","a3c1487f8318513ae7c156acc857fde2",{"hashOfOptions":"115"},"5080fb7f49a201ad809050ee57249d41",{"hashOfOptions":"116"},"28454ca5c544a35129bb829072b8dbc1",{"hashOfOptions":"117"},"1e8ac0d261e95efb19d290ffcf70ce36","5068090396cd9f4f9463f09f43c9e257",{"hashOfOptions":"118"},"74d22c2830502b877ac3b806a788bfa3",{"hashOfOptions":"119"},"29e520338914a80764ca0866a87fac3d",{"hashOfOptions":"120"},"0f7f54c7161b8403d3bc42d91f59cd91",{"hashOfOptions":"121"},"d4d589c153ac8b5e7bf0fb130a5b5a7d",{"hashOfOptions":"122"},"3529965326","1818025557","2842754191","1504153565","3815129580","3236408049","1664229517","2979851528","3930068749","2135093465","2923444549","366302476","4133218715","3075567833","3597942159","1044122342","1450990178","3667891651","3412980713"] \ No newline at end of file diff --git a/apps/expo/.expo-shared/assets.json b/apps/expo/.expo-shared/assets.json new file mode 100644 index 0000000..1e6decf --- /dev/null +++ b/apps/expo/.expo-shared/assets.json @@ -0,0 +1,4 @@ +{ + "12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true, + "40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true +} diff --git a/apps/expo/app.config.ts b/apps/expo/app.config.ts new file mode 100644 index 0000000..1f42aaa --- /dev/null +++ b/apps/expo/app.config.ts @@ -0,0 +1,60 @@ +import type { ConfigContext, ExpoConfig } from "expo/config"; + +export default ({ config }: ConfigContext): ExpoConfig => ({ + ...config, + name: "expo", + slug: "expo", + scheme: "expo", + version: "0.1.0", + orientation: "portrait", + icon: "./assets/icon-light.png", + userInterfaceStyle: "automatic", + updates: { + fallbackToCacheTimeout: 0, + }, + newArchEnabled: true, + assetBundlePatterns: ["**/*"], + ios: { + bundleIdentifier: "your.bundle.identifier", + supportsTablet: true, + icon: { + light: "./assets/icon-light.png", + dark: "./assets/icon-dark.png", + }, + }, + android: { + package: "your.bundle.identifier", + adaptiveIcon: { + foregroundImage: "./assets/icon-light.png", + backgroundColor: "#1F104A", + }, + edgeToEdgeEnabled: true, + }, + // extra: { + // eas: { + // projectId: "your-eas-project-id", + // }, + // }, + experiments: { + tsconfigPaths: true, + typedRoutes: true, + reactCanary: true, + reactCompiler: true, + }, + plugins: [ + "expo-router", + "expo-secure-store", + "expo-web-browser", + [ + "expo-splash-screen", + { + backgroundColor: "#E4E4E7", + image: "./assets/icon-light.png", + dark: { + backgroundColor: "#18181B", + image: "./assets/icon-dark.png", + }, + }, + ], + ], +}); diff --git a/apps/expo/assets/icon-dark.png b/apps/expo/assets/icon-dark.png new file mode 100644 index 0000000..e4f3cec Binary files /dev/null and b/apps/expo/assets/icon-dark.png differ diff --git a/apps/expo/assets/icon-light.png b/apps/expo/assets/icon-light.png new file mode 100644 index 0000000..5b15cab Binary files /dev/null and b/apps/expo/assets/icon-light.png differ diff --git a/apps/expo/eas.json b/apps/expo/eas.json new file mode 100644 index 0000000..6d3041f --- /dev/null +++ b/apps/expo/eas.json @@ -0,0 +1,33 @@ +{ + "cli": { + "version": ">= 4.1.2", + "appVersionSource": "remote" + }, + "build": { + "base": { + "node": "22.12.0", + "pnpm": "9.15.4", + "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/apps/expo/eslint.config.mts b/apps/expo/eslint.config.mts new file mode 100644 index 0000000..84c3e9d --- /dev/null +++ b/apps/expo/eslint.config.mts @@ -0,0 +1,12 @@ +import { defineConfig } from "eslint/config"; + +import { baseConfig } from "@acme/eslint-config/base"; +import { reactConfig } from "@acme/eslint-config/react"; + +export default defineConfig( + { + ignores: [".expo/**", "expo-plugins/**"], + }, + baseConfig, + reactConfig, +); diff --git a/apps/expo/index.ts b/apps/expo/index.ts new file mode 100644 index 0000000..80d3d99 --- /dev/null +++ b/apps/expo/index.ts @@ -0,0 +1 @@ +import "expo-router/entry"; diff --git a/apps/expo/metro.config.js b/apps/expo/metro.config.js new file mode 100644 index 0000000..bc118a0 --- /dev/null +++ b/apps/expo/metro.config.js @@ -0,0 +1,16 @@ +// Learn more: https://docs.expo.dev/guides/monorepos/ +const path = require("node:path"); +const { getDefaultConfig } = require("expo/metro-config"); +const { FileStore } = require("metro-cache"); +const { withNativewind } = require("nativewind/metro"); + +const config = getDefaultConfig(__dirname); + +config.cacheStores = [ + new FileStore({ + root: path.join(__dirname, "node_modules", ".cache", "metro"), + }), +]; + +/** @type {import('expo/metro-config').MetroConfig} */ +module.exports = withNativewind(config); diff --git a/apps/expo/nativewind-env.d.ts b/apps/expo/nativewind-env.d.ts new file mode 100644 index 0000000..82aac40 --- /dev/null +++ b/apps/expo/nativewind-env.d.ts @@ -0,0 +1,3 @@ +/// + +// NOTE: This file should not be edited and should be committed with your source code. It is generated by react-native-css. If you need to move or disable this file, please see the documentation. diff --git a/apps/expo/package.json b/apps/expo/package.json new file mode 100644 index 0000000..fa209fc --- /dev/null +++ b/apps/expo/package.json @@ -0,0 +1,55 @@ +{ + "name": "@acme/expo", + "private": true, + "main": "index.ts", + "scripts": { + "clean": "git clean -xdf .cache .expo .turbo android ios node_modules", + "dev": "expo start", + "dev:android": "expo start --android", + "dev:ios": "expo start --ios", + "android": "expo run:android", + "ios": "expo run:ios", + "format": "prettier --check . --ignore-path ../../.gitignore --ignore-path .prettierignore", + "lint": "eslint --flag unstable_native_nodejs_ts_config", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@acme/backend": "workspace:*", + "@convex-dev/auth": "workspace:*", + "@legendapp/list": "^2.0.14", + "convex": "workspace:*", + "expo": "~54.0.20", + "expo-constants": "~18.0.10", + "expo-dev-client": "~6.0.16", + "expo-linking": "~8.0.8", + "expo-router": "~6.0.13", + "expo-secure-store": "~15.0.7", + "expo-splash-screen": "~31.0.10", + "expo-status-bar": "~3.0.8", + "expo-system-ui": "~6.0.8", + "expo-web-browser": "~15.0.8", + "nativewind": "5.0.0-preview.2", + "react": "catalog:react19", + "react-dom": "catalog:react19", + "react-native": "~0.81.5", + "react-native-css": "3.0.1", + "react-native-gesture-handler": "~2.28.0", + "react-native-reanimated": "~4.1.3", + "react-native-safe-area-context": "~5.6.1", + "react-native-screens": "~4.16.0", + "react-native-worklets": "~0.5.1", + "superjson": "2.2.3" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tailwind-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "@types/react": "catalog:react19", + "eslint": "catalog:", + "prettier": "catalog:", + "tailwindcss": "catalog:", + "typescript": "catalog:" + }, + "prettier": "@acme/prettier-config" +} diff --git a/apps/expo/postcss.config.js b/apps/expo/postcss.config.js new file mode 100644 index 0000000..2e9905f --- /dev/null +++ b/apps/expo/postcss.config.js @@ -0,0 +1 @@ +module.exports = require("@acme/tailwind-config/postcss-config"); diff --git a/apps/expo/src/app/_layout.tsx b/apps/expo/src/app/_layout.tsx new file mode 100644 index 0000000..bfab22c --- /dev/null +++ b/apps/expo/src/app/_layout.tsx @@ -0,0 +1,33 @@ +import { useColorScheme } from "react-native"; +import { Stack } from "expo-router"; +import { StatusBar } from "expo-status-bar"; +import { QueryClientProvider } from "@tanstack/react-query"; + +import { queryClient } 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() { + const colorScheme = useColorScheme(); + return ( + + {/* + The Stack component displays the current page. + It also allows you to configure your screens + */} + + + + ); +} diff --git a/apps/expo/src/app/index.tsx b/apps/expo/src/app/index.tsx new file mode 100644 index 0000000..72fb1c3 --- /dev/null +++ b/apps/expo/src/app/index.tsx @@ -0,0 +1,172 @@ +import { useState } from "react"; +import { Pressable, Text, TextInput, View } from "react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { Link, Stack } from "expo-router"; +import { LegendList } from "@legendapp/list"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; + +import type { RouterOutputs } from "~/utils/api"; +import { trpc } from "~/utils/api"; +import { authClient } from "~/utils/auth"; + +function PostCard(props: { + post: RouterOutputs["post"]["all"][number]; + onDelete: () => void; +}) { + return ( + + + + + + {props.post.title} + + {props.post.content} + + + + + Delete + + + ); +} + +function CreatePost() { + const queryClient = useQueryClient(); + + const [title, setTitle] = useState(""); + const [content, setContent] = useState(""); + + const { mutate, error } = useMutation( + trpc.post.create.mutationOptions({ + async onSuccess() { + setTitle(""); + setContent(""); + await queryClient.invalidateQueries(trpc.post.all.queryFilter()); + }, + }), + ); + + return ( + + + {error?.data?.zodError?.fieldErrors.title && ( + + {error.data.zodError.fieldErrors.title} + + )} + + {error?.data?.zodError?.fieldErrors.content && ( + + {error.data.zodError.fieldErrors.content} + + )} + { + mutate({ + title, + content, + }); + }} + > + Create + + {error?.data?.code === "UNAUTHORIZED" && ( + + You need to be logged in to create a post + + )} + + ); +} + +function MobileAuth() { + const { data: session } = authClient.useSession(); + + return ( + <> + + {session?.user.name ? `Hello, ${session.user.name}` : "Not logged in"} + + + session + ? authClient.signOut() + : authClient.signIn.social({ + provider: "discord", + callbackURL: "/", + }) + } + className="bg-primary flex items-center rounded-sm p-2" + > + {session ? "Sign Out" : "Sign In With Discord"} + + + ); +} + +export default function Index() { + const queryClient = useQueryClient(); + + const postQuery = useQuery(trpc.post.all.queryOptions()); + + const deletePostMutation = useMutation( + trpc.post.delete.mutationOptions({ + onSettled: () => + queryClient.invalidateQueries(trpc.post.all.queryFilter()), + }), + ); + + return ( + + {/* Changes page title visible on the header */} + + + + Create T3 Turbo + + + + + + + Press on a post + + + + item.id} + ItemSeparatorComponent={() => } + renderItem={(p) => ( + deletePostMutation.mutate(p.item.id)} + /> + )} + /> + + + + + ); +} diff --git a/apps/expo/src/app/post/[id].tsx b/apps/expo/src/app/post/[id].tsx new file mode 100644 index 0000000..5470017 --- /dev/null +++ b/apps/expo/src/app/post/[id].tsx @@ -0,0 +1,24 @@ +import { SafeAreaView, Text, View } from "react-native"; +import { Stack, useGlobalSearchParams } from "expo-router"; +import { useQuery } from "@tanstack/react-query"; + +import { trpc } from "~/utils/api"; + +export default function Post() { + const { id } = useGlobalSearchParams<{ id: string }>(); + const { data } = useQuery(trpc.post.byId.queryOptions({ id })); + + if (!data) return null; + + return ( + + + + + {data.title} + + {data.content} + + + ); +} diff --git a/apps/expo/src/styles.css b/apps/expo/src/styles.css new file mode 100644 index 0000000..759cbd9 --- /dev/null +++ b/apps/expo/src/styles.css @@ -0,0 +1,3 @@ +@import "tailwindcss"; +@import "nativewind/theme"; +@import "@acme/tailwind-config/theme"; diff --git a/apps/expo/src/utils/api.tsx b/apps/expo/src/utils/api.tsx new file mode 100644 index 0000000..308e2ee --- /dev/null +++ b/apps/expo/src/utils/api.tsx @@ -0,0 +1,50 @@ +import { QueryClient } from "@tanstack/react-query"; +import { createTRPCClient, httpBatchLink, loggerLink } from "@trpc/client"; +import { createTRPCOptionsProxy } from "@trpc/tanstack-react-query"; +import superjson from "superjson"; + +import type { AppRouter } from "@acme/api"; + +import { authClient } from "./auth"; +import { getBaseUrl } from "./base-url"; + +export const queryClient = new QueryClient({ + defaultOptions: { + queries: { + // ... + }, + }, +}); + +/** + * A set of typesafe hooks for consuming your API. + */ +export const trpc = createTRPCOptionsProxy({ + client: createTRPCClient({ + links: [ + loggerLink({ + enabled: (opts) => + process.env.NODE_ENV === "development" || + (opts.direction === "down" && opts.result instanceof Error), + colorMode: "ansi", + }), + httpBatchLink({ + transformer: superjson, + url: `${getBaseUrl()}/api/trpc`, + headers() { + const headers = new Map(); + headers.set("x-trpc-source", "expo-react"); + + const cookies = authClient.getCookie(); + if (cookies) { + headers.set("Cookie", cookies); + } + return headers; + }, + }), + ], + }), + queryClient, +}); + +export type { RouterInputs, RouterOutputs } from "@acme/api"; diff --git a/apps/expo/src/utils/auth.ts b/apps/expo/src/utils/auth.ts new file mode 100644 index 0000000..7c64135 --- /dev/null +++ b/apps/expo/src/utils/auth.ts @@ -0,0 +1,16 @@ +import * as SecureStore from "expo-secure-store"; +import { expoClient } from "@better-auth/expo/client"; +import { createAuthClient } from "better-auth/react"; + +import { getBaseUrl } from "./base-url"; + +export const authClient = createAuthClient({ + baseURL: getBaseUrl(), + plugins: [ + expoClient({ + scheme: "expo", + storagePrefix: "expo", + storage: SecureStore, + }), + ], +}); diff --git a/apps/expo/src/utils/base-url.ts b/apps/expo/src/utils/base-url.ts new file mode 100644 index 0000000..94dfbbc --- /dev/null +++ b/apps/expo/src/utils/base-url.ts @@ -0,0 +1,26 @@ +import Constants from "expo-constants"; + +/** + * Extend this function when going to production by + * setting the baseUrl to your production API URL. + */ +export const getBaseUrl = () => { + /** + * Gets the IP address of your host-machine. If it cannot automatically find it, + * you'll have to manually set it. NOTE: Port 3000 should work for most but confirm + * you don't have anything else running on it, or you'd have to change it. + * + * **NOTE**: This is only for development. In production, you'll want to set the + * baseUrl to your production API URL. + */ + const debuggerHost = Constants.expoConfig?.hostUri; + const localhost = debuggerHost?.split(":")[0]; + + if (!localhost) { + // return "https://turbo.t3.gg"; + throw new Error( + "Failed to get localhost. Please point to your production server.", + ); + } + return `http://${localhost}:3000`; +}; diff --git a/apps/expo/src/utils/session-store.ts b/apps/expo/src/utils/session-store.ts new file mode 100644 index 0000000..8f55284 --- /dev/null +++ b/apps/expo/src/utils/session-store.ts @@ -0,0 +1,7 @@ +import * as SecureStore from "expo-secure-store"; + +const key = "session_token"; + +export const getToken = () => SecureStore.getItem(key); +export const deleteToken = () => SecureStore.deleteItemAsync(key); +export const setToken = (v: string) => SecureStore.setItem(key, v); diff --git a/apps/expo/tsconfig.json b/apps/expo/tsconfig.json new file mode 100644 index 0000000..60dde4f --- /dev/null +++ b/apps/expo/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": ["@acme/tsconfig/base.json"], + "compilerOptions": { + "jsx": "react-native", + "checkJs": false, + "moduleSuffixes": [".ios", ".android", ".native", ""], + "paths": { + "@/*": ["./src/*"] + } + }, + "include": [ + "src", + "*.ts", + "*.js", + ".expo/types/**/*.ts", + "expo-env.d.ts", + "nativewind-env.d.ts" + ], + "exclude": ["node_modules"] +} diff --git a/apps/expo/turbo.json b/apps/expo/turbo.json new file mode 100644 index 0000000..94d10b8 --- /dev/null +++ b/apps/expo/turbo.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://turborepo.com/schema.json", + "extends": ["//"], + "tasks": { + "dev": { + "persistent": true, + "interactive": true + } + } +} diff --git a/apps/nextjs/.cache/.prettiercache b/apps/nextjs/.cache/.prettiercache new file mode 100644 index 0000000..6a43dd2 --- /dev/null +++ b/apps/nextjs/.cache/.prettiercache @@ -0,0 +1 @@ +[["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21"],{"key":"22","value":"23"},{"key":"24","value":"25"},{"key":"26","value":"27"},{"key":"28","value":"29"},{"key":"30","value":"31"},{"key":"32","value":"33"},{"key":"34","value":"35"},{"key":"36","value":"37"},{"key":"38","value":"39"},{"key":"40","value":"41"},{"key":"42","value":"43"},{"key":"44","value":"45"},{"key":"46","value":"47"},{"key":"48","value":"49"},{"key":"50","value":"51"},{"key":"52","value":"53"},{"key":"54","value":"55"},{"key":"56","value":"57"},{"key":"58","value":"59"},{"key":"60","value":"61"},{"key":"62","value":"63"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/next.config.js",{"size":593,"mtime":1761443987000,"hash":"64","data":"65"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/package.json",{"size":1258,"mtime":1761665338729,"hash":"66","data":"67"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/env.ts",{"size":1095,"mtime":1761443987000,"hash":"68","data":"69"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/tsconfig.json",{"size":298,"mtime":1761663697154,"hash":"70","data":"71"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/app/api/auth/[...all]/route.ts",{"size":106,"mtime":1761443987000,"hash":"72","data":"73"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/app/_components/posts.tsx",{"size":5749,"mtime":1761443987000,"hash":"74","data":"75"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/app/styles.css",{"size":596,"mtime":1761443987000,"hash":"76","data":"77"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/turbo.json",{"size":255,"mtime":1761443987000,"hash":"78","data":"79"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/public/t3-icon.svg",{"size":923,"mtime":1761443987000,"hash":"80"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/eslint.config.ts",{"size":372,"mtime":1761443987000,"hash":"81","data":"82"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/auth/client.ts",{"size":101,"mtime":1761443987000,"hash":"83","data":"84"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/postcss.config.js",{"size":64,"mtime":1761443987000,"hash":"85","data":"86"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/trpc/react.tsx",{"size":2089,"mtime":1761443987000,"hash":"87","data":"88"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/app/layout.tsx",{"size":1886,"mtime":1761443987000,"hash":"89","data":"90"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/app/api/trpc/[trpc]/route.ts",{"size":1196,"mtime":1761443987000,"hash":"91","data":"92"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/trpc/server.tsx",{"size":1739,"mtime":1761443987000,"hash":"93","data":"94"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/app/_components/auth-showcase.tsx",{"size":1331,"mtime":1761443987000,"hash":"95","data":"96"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/app/page.tsx",{"size":1169,"mtime":1761443987000,"hash":"97","data":"98"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/trpc/query-client.ts",{"size":1002,"mtime":1761443987000,"hash":"99","data":"100"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/public/favicon.ico",{"size":103027,"mtime":1761443987000,"hash":"101"},"/home/gib/Documents/Code/monorepo/convex-monorepo/apps/nextjs/src/auth/server.ts",{"size":801,"mtime":1761443987000,"hash":"102","data":"103"},"c71c6d38b09f5b6d3d3b296f8d059be1",{"hashOfOptions":"104"},"17b075cb91d407b93cf2953f87c6f9a4",{"hashOfOptions":"105"},"d955c0845142285b98b385cfcf031209",{"hashOfOptions":"106"},"11c3c1f4e8823370fb28210a6afc9951",{"hashOfOptions":"107"},"669e07b8b58928400c63c6ed0e49a64e",{"hashOfOptions":"108"},"1ac9993352adbb74d13c9732ca6d533a",{"hashOfOptions":"109"},"c937699685ef9e811c900ebc5df5dbbf",{"hashOfOptions":"110"},"d9e20c7e10fd4cd098ff840dff46b4da",{"hashOfOptions":"111"},"44418c5550aee51cfdf0a321ad70ae47","7ec3983f3976b78e804a07f9c4fb6d97",{"hashOfOptions":"112"},"7e5ffd0852aee321277975c6e0ef14a2",{"hashOfOptions":"113"},"c665bf23f8df063f75de1b250d572cd2",{"hashOfOptions":"114"},"350ee0282e4eca8e9fda100a09710928",{"hashOfOptions":"115"},"f95bf95dd88062c4b8b3d18c68bc9e8c",{"hashOfOptions":"116"},"4c6cc67927d5070dc05bd2679763cf04",{"hashOfOptions":"117"},"c56363894a5bf471e89240bca1e515a0",{"hashOfOptions":"118"},"4df615c7a274b688db46c32500668ad5",{"hashOfOptions":"119"},"5a041655bd1d792d2d6fcbb5bc80f995",{"hashOfOptions":"120"},"9dc5bdce6cefdd08f481e08d9e6410fb",{"hashOfOptions":"121"},"36aa513994f9883f30ff408fe777cec6","fa176dc16feb16005a72ee19559c8030",{"hashOfOptions":"122"},"1344070621","3931217075","510666542","3840619408","3973314510","12400390","2874730995","1281675547","2976136881","3972850281","2547656773","3029720250","425961009","3256449973","4015957340","4189139749","3271685750","4052984653","2571191665"] \ No newline at end of file diff --git a/apps/nextjs/eslint.config.ts b/apps/nextjs/eslint.config.ts new file mode 100644 index 0000000..f0a54a4 --- /dev/null +++ b/apps/nextjs/eslint.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from "eslint/config"; + +import { baseConfig, restrictEnvAccess } from "@acme/eslint-config/base"; +import { nextjsConfig } from "@acme/eslint-config/nextjs"; +import { reactConfig } from "@acme/eslint-config/react"; + +export default defineConfig( + { + ignores: [".next/**"], + }, + baseConfig, + reactConfig, + nextjsConfig, + restrictEnvAccess, +); diff --git a/apps/nextjs/next.config.js b/apps/nextjs/next.config.js new file mode 100644 index 0000000..310babd --- /dev/null +++ b/apps/nextjs/next.config.js @@ -0,0 +1,23 @@ +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url); + +// Import env files to validate at build time. Use jiti so we can load .ts files in here. +await jiti.import("./src/env"); + +/** @type {import("next").NextConfig} */ +const config = { + /** Enables hot reloading for local packages without a build step */ + transpilePackages: [ + "@acme/api", + "@acme/auth", + "@acme/db", + "@acme/ui", + "@acme/validators", + ], + + /** We already do linting and typechecking as separate tasks in CI */ + typescript: { ignoreBuildErrors: true }, +}; + +export default config; diff --git a/apps/nextjs/package.json b/apps/nextjs/package.json new file mode 100644 index 0000000..397f8db --- /dev/null +++ b/apps/nextjs/package.json @@ -0,0 +1,43 @@ +{ + "name": "@acme/nextjs", + "private": true, + "type": "module", + "scripts": { + "build": "pnpm with-env next build", + "clean": "git clean -xdf .cache .next .turbo node_modules", + "dev": "pnpm with-env next dev", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint --flag unstable_native_nodejs_ts_config", + "start": "pnpm with-env next start", + "typecheck": "tsc --noEmit", + "with-env": "dotenv -e ../../.env --" + }, + "dependencies": { + "@acme/backend": "workspace:*", + "@acme/ui": "workspace:*", + "@convex-dev/auth": "workspace:*", + "@t3-oss/env-nextjs": "^0.13.8", + "convex": "workspace:*", + "next": "^16.0.0", + "react": "catalog:react19", + "react-dom": "catalog:react19", + "superjson": "2.2.3", + "zod": "catalog:" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tailwind-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "@types/node": "catalog:", + "@types/react": "catalog:react19", + "@types/react-dom": "catalog:react19", + "eslint": "catalog:", + "jiti": "^2.5.1", + "prettier": "catalog:", + "tailwindcss": "catalog:", + "tw-animate-css": "^1.4.0", + "typescript": "catalog:" + }, + "prettier": "@acme/prettier-config" +} diff --git a/apps/nextjs/postcss.config.js b/apps/nextjs/postcss.config.js new file mode 100644 index 0000000..cc57416 --- /dev/null +++ b/apps/nextjs/postcss.config.js @@ -0,0 +1 @@ +export { default } from "@acme/tailwind-config/postcss-config"; diff --git a/apps/nextjs/public/favicon.ico b/apps/nextjs/public/favicon.ico new file mode 100644 index 0000000..f0058b4 Binary files /dev/null and b/apps/nextjs/public/favicon.ico differ diff --git a/apps/nextjs/public/t3-icon.svg b/apps/nextjs/public/t3-icon.svg new file mode 100644 index 0000000..e377165 --- /dev/null +++ b/apps/nextjs/public/t3-icon.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/apps/nextjs/src/app/_components/auth-showcase.tsx b/apps/nextjs/src/app/_components/auth-showcase.tsx new file mode 100644 index 0000000..685a3f2 --- /dev/null +++ b/apps/nextjs/src/app/_components/auth-showcase.tsx @@ -0,0 +1,58 @@ +import { headers } from "next/headers"; +import { redirect } from "next/navigation"; + +import { Button } from "@acme/ui/button"; + +import { auth, getSession } from "~/auth/server"; + +export async function AuthShowcase() { + const session = await getSession(); + + if (!session) { + return ( +
+ +
+ ); + } + + return ( +
+

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

+ +
+ +
+
+ ); +} diff --git a/apps/nextjs/src/app/_components/posts.tsx b/apps/nextjs/src/app/_components/posts.tsx new file mode 100644 index 0000000..5a4bbeb --- /dev/null +++ b/apps/nextjs/src/app/_components/posts.tsx @@ -0,0 +1,210 @@ +"use client"; + +import { useForm } from "@tanstack/react-form"; +import { + useMutation, + useQueryClient, + useSuspenseQuery, +} from "@tanstack/react-query"; + +import type { RouterOutputs } from "@acme/api"; +import { CreatePostSchema } from "@acme/db/schema"; +import { cn } from "@acme/ui"; +import { Button } from "@acme/ui/button"; +import { + Field, + FieldContent, + FieldError, + FieldGroup, + FieldLabel, +} from "@acme/ui/field"; +import { Input } from "@acme/ui/input"; +import { toast } from "@acme/ui/toast"; + +import { useTRPC } from "~/trpc/react"; + +export function CreatePostForm() { + const trpc = useTRPC(); + + const queryClient = useQueryClient(); + const createPost = useMutation( + trpc.post.create.mutationOptions({ + onSuccess: async () => { + form.reset(); + await queryClient.invalidateQueries(trpc.post.pathFilter()); + }, + onError: (err) => { + toast.error( + err.data?.code === "UNAUTHORIZED" + ? "You must be logged in to post" + : "Failed to create post", + ); + }, + }), + ); + + const form = useForm({ + defaultValues: { + content: "", + title: "", + }, + validators: { + onSubmit: CreatePostSchema, + }, + onSubmit: (data) => createPost.mutate(data.value), + }); + + return ( +
{ + event.preventDefault(); + void form.handleSubmit(); + }} + > + + { + const isInvalid = + field.state.meta.isTouched && !field.state.meta.isValid; + return ( + + + Bug Title + + field.handleChange(e.target.value)} + aria-invalid={isInvalid} + placeholder="Title" + /> + {isInvalid && } + + ); + }} + /> + { + const isInvalid = + field.state.meta.isTouched && !field.state.meta.isValid; + return ( + + + Content + + field.handleChange(e.target.value)} + aria-invalid={isInvalid} + placeholder="Content" + /> + {isInvalid && } + + ); + }} + /> + + +
+ ); +} + +export function PostList() { + const trpc = useTRPC(); + const { data: posts } = useSuspenseQuery(trpc.post.all.queryOptions()); + + if (posts.length === 0) { + return ( +
+ + + + +
+

No posts yet

+
+
+ ); + } + + return ( +
+ {posts.map((p) => { + return ; + })} +
+ ); +} + +export function PostCard(props: { + post: RouterOutputs["post"]["all"][number]; +}) { + const trpc = useTRPC(); + const queryClient = useQueryClient(); + const deletePost = useMutation( + trpc.post.delete.mutationOptions({ + onSuccess: async () => { + await queryClient.invalidateQueries(trpc.post.pathFilter()); + }, + 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/apps/nextjs/src/app/api/auth/[...all]/route.ts b/apps/nextjs/src/app/api/auth/[...all]/route.ts new file mode 100644 index 0000000..71c7ff7 --- /dev/null +++ b/apps/nextjs/src/app/api/auth/[...all]/route.ts @@ -0,0 +1,4 @@ +import { auth } from "~/auth/server"; + +export const GET = auth.handler; +export const POST = auth.handler; diff --git a/apps/nextjs/src/app/api/trpc/[trpc]/route.ts b/apps/nextjs/src/app/api/trpc/[trpc]/route.ts new file mode 100644 index 0000000..c5548f9 --- /dev/null +++ b/apps/nextjs/src/app/api/trpc/[trpc]/route.ts @@ -0,0 +1,46 @@ +import type { NextRequest } from "next/server"; +import { fetchRequestHandler } from "@trpc/server/adapters/fetch"; + +import { appRouter, createTRPCContext } from "@acme/api"; + +import { auth } from "~/auth/server"; + +/** + * Configure basic CORS headers + * You should extend this to match your needs + */ +const 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 const OPTIONS = () => { + const response = new Response(null, { + status: 204, + }); + setCorsHeaders(response); + return response; +}; + +const handler = async (req: NextRequest) => { + const response = await fetchRequestHandler({ + endpoint: "/api/trpc", + router: appRouter, + req, + createContext: () => + createTRPCContext({ + auth: 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/apps/nextjs/src/app/layout.tsx b/apps/nextjs/src/app/layout.tsx new file mode 100644 index 0000000..8985f5d --- /dev/null +++ b/apps/nextjs/src/app/layout.tsx @@ -0,0 +1,70 @@ +import type { Metadata, Viewport } from "next"; +import { Geist, Geist_Mono } from "next/font/google"; + +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/styles.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 geistSans = Geist({ + subsets: ["latin"], + variable: "--font-geist-sans", +}); +const geistMono = Geist_Mono({ + subsets: ["latin"], + variable: "--font-geist-mono", +}); + +export default function RootLayout(props: { children: React.ReactNode }) { + return ( + + + + {props.children} +
+ +
+ +
+ + + ); +} diff --git a/apps/nextjs/src/app/page.tsx b/apps/nextjs/src/app/page.tsx new file mode 100644 index 0000000..28a5d24 --- /dev/null +++ b/apps/nextjs/src/app/page.tsx @@ -0,0 +1,41 @@ +import { Suspense } from "react"; + +import { HydrateClient, prefetch, trpc } from "~/trpc/server"; +import { AuthShowcase } from "./_components/auth-showcase"; +import { + CreatePostForm, + PostCardSkeleton, + PostList, +} from "./_components/posts"; + +export default function HomePage() { + prefetch(trpc.post.all.queryOptions()); + + return ( + +
+
+

+ Create T3 Turbo +

+ + + +
+ + + + +
+ } + > + + +
+ +
+
+ ); +} diff --git a/apps/nextjs/src/app/styles.css b/apps/nextjs/src/app/styles.css new file mode 100644 index 0000000..25d002f --- /dev/null +++ b/apps/nextjs/src/app/styles.css @@ -0,0 +1,29 @@ +@import "tailwindcss"; +@import "tw-animate-css"; +@import "@acme/tailwind-config/theme"; + +@source "../../../../packages/ui/src/*.{ts,tsx}"; + +@custom-variant dark (&:where(.dark, .dark *)); +@custom-variant light (&:where(.light, .light *)); +@custom-variant auto (&:where(.auto, .auto *)); + +@utility container { + margin-inline: auto; + padding-inline: 2rem; + @media (width >= --theme(--breakpoint-sm)) { + max-width: none; + } + @media (width >= 1400px) { + max-width: 1400px; + } +} + +@layer base { + * { + @apply border-border; + } + body { + letter-spacing: var(--tracking-normal); + } +} diff --git a/apps/nextjs/src/auth/client.ts b/apps/nextjs/src/auth/client.ts new file mode 100644 index 0000000..f1012dd --- /dev/null +++ b/apps/nextjs/src/auth/client.ts @@ -0,0 +1,3 @@ +import { createAuthClient } from "better-auth/react"; + +export const authClient = createAuthClient(); diff --git a/apps/nextjs/src/auth/server.ts b/apps/nextjs/src/auth/server.ts new file mode 100644 index 0000000..842b228 --- /dev/null +++ b/apps/nextjs/src/auth/server.ts @@ -0,0 +1,29 @@ +import "server-only"; + +import { cache } from "react"; +import { headers } from "next/headers"; +import { nextCookies } from "better-auth/next-js"; + +import { initAuth } from "@acme/auth"; + +import { env } from "~/env"; + +const baseUrl = + env.VERCEL_ENV === "production" + ? `https://${env.VERCEL_PROJECT_PRODUCTION_URL}` + : env.VERCEL_ENV === "preview" + ? `https://${env.VERCEL_URL}` + : "http://localhost:3000"; + +export const auth = initAuth({ + baseUrl, + productionUrl: `https://${env.VERCEL_PROJECT_PRODUCTION_URL ?? "turbo.t3.gg"}`, + secret: env.AUTH_SECRET, + discordClientId: env.AUTH_DISCORD_ID, + discordClientSecret: env.AUTH_DISCORD_SECRET, + extraPlugins: [nextCookies()], +}); + +export const getSession = cache(async () => + auth.api.getSession({ headers: await headers() }), +); diff --git a/apps/nextjs/src/env.ts b/apps/nextjs/src/env.ts new file mode 100644 index 0000000..6318524 --- /dev/null +++ b/apps/nextjs/src/env.ts @@ -0,0 +1,39 @@ +import { createEnv } from "@t3-oss/env-nextjs"; +import { vercel } from "@t3-oss/env-nextjs/presets-zod"; +import { z } from "zod/v4"; + +import { authEnv } from "@acme/auth/env"; + +export const env = createEnv({ + extends: [authEnv(), vercel()], + shared: { + NODE_ENV: z + .enum(["development", "production", "test"]) + .default("development"), + }, + /** + * Specify your server-side environment variables schema here. + * This way you can ensure the app isn't built with invalid env vars. + */ + server: { + POSTGRES_URL: z.url(), + }, + + /** + * 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. + */ + experimental__runtimeEnv: { + NODE_ENV: process.env.NODE_ENV, + + // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, + }, + skipValidation: + !!process.env.CI || process.env.npm_lifecycle_event === "lint", +}); diff --git a/apps/nextjs/src/trpc/query-client.ts b/apps/nextjs/src/trpc/query-client.ts new file mode 100644 index 0000000..7436c35 --- /dev/null +++ b/apps/nextjs/src/trpc/query-client.ts @@ -0,0 +1,33 @@ +import { + defaultShouldDehydrateQuery, + QueryClient, +} from "@tanstack/react-query"; +import SuperJSON from "superjson"; + +export const createQueryClient = () => + new QueryClient({ + defaultOptions: { + queries: { + // With SSR, we usually want to set some default staleTime + // above 0 to avoid refetching immediately on the client + staleTime: 30 * 1000, + }, + dehydrate: { + serializeData: SuperJSON.serialize, + shouldDehydrateQuery: (query) => + defaultShouldDehydrateQuery(query) || + query.state.status === "pending", + shouldRedactErrors: () => { + // We should not catch Next.js server errors + // as that's how Next.js detects dynamic pages + // so we cannot redact them. + // Next.js also automatically redacts errors for us + // with better digests. + return false; + }, + }, + hydrate: { + deserializeData: SuperJSON.deserialize, + }, + }, + }); diff --git a/apps/nextjs/src/trpc/react.tsx b/apps/nextjs/src/trpc/react.tsx new file mode 100644 index 0000000..e74fe31 --- /dev/null +++ b/apps/nextjs/src/trpc/react.tsx @@ -0,0 +1,70 @@ +"use client"; + +import type { QueryClient } from "@tanstack/react-query"; +import { useState } from "react"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + createTRPCClient, + httpBatchStreamLink, + loggerLink, +} from "@trpc/client"; +import { createTRPCContext } from "@trpc/tanstack-react-query"; +import SuperJSON from "superjson"; + +import type { AppRouter } from "@acme/api"; + +import { env } from "~/env"; +import { createQueryClient } from "./query-client"; + +let clientQueryClientSingleton: QueryClient | undefined = undefined; +const getQueryClient = () => { + if (typeof window === "undefined") { + // Server: always make a new query client + return createQueryClient(); + } else { + // Browser: use singleton pattern to keep the same query client + return (clientQueryClientSingleton ??= createQueryClient()); + } +}; + +export const { useTRPC, TRPCProvider } = createTRPCContext(); + +export function TRPCReactProvider(props: { children: React.ReactNode }) { + const queryClient = getQueryClient(); + + const [trpcClient] = useState(() => + createTRPCClient({ + links: [ + loggerLink({ + enabled: (op) => + env.NODE_ENV === "development" || + (op.direction === "down" && op.result instanceof Error), + }), + httpBatchStreamLink({ + transformer: SuperJSON, + url: getBaseUrl() + "/api/trpc", + headers() { + const headers = new Headers(); + headers.set("x-trpc-source", "nextjs-react"); + return headers; + }, + }), + ], + }), + ); + + return ( + + + {props.children} + + + ); +} + +const getBaseUrl = () => { + if (typeof window !== "undefined") return window.location.origin; + if (env.VERCEL_URL) return `https://${env.VERCEL_URL}`; + // eslint-disable-next-line no-restricted-properties + return `http://localhost:${process.env.PORT ?? 3000}`; +}; diff --git a/apps/nextjs/src/trpc/server.tsx b/apps/nextjs/src/trpc/server.tsx new file mode 100644 index 0000000..82ec5de --- /dev/null +++ b/apps/nextjs/src/trpc/server.tsx @@ -0,0 +1,54 @@ +import type { TRPCQueryOptions } from "@trpc/tanstack-react-query"; +import { cache } from "react"; +import { headers } from "next/headers"; +import { dehydrate, HydrationBoundary } from "@tanstack/react-query"; +import { createTRPCOptionsProxy } from "@trpc/tanstack-react-query"; + +import type { AppRouter } from "@acme/api"; +import { appRouter, createTRPCContext } from "@acme/api"; + +import { auth } from "~/auth/server"; +import { createQueryClient } from "./query-client"; + +/** + * 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(await headers()); + heads.set("x-trpc-source", "rsc"); + + return createTRPCContext({ + headers: heads, + auth, + }); +}); + +const getQueryClient = cache(createQueryClient); + +export const trpc = createTRPCOptionsProxy({ + router: appRouter, + ctx: createContext, + queryClient: getQueryClient, +}); + +export function HydrateClient(props: { children: React.ReactNode }) { + const queryClient = getQueryClient(); + return ( + + {props.children} + + ); +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function prefetch>>( + queryOptions: T, +) { + const queryClient = getQueryClient(); + if (queryOptions.queryKey[1]?.type === "infinite") { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any + void queryClient.prefetchInfiniteQuery(queryOptions as any); + } else { + void queryClient.prefetchQuery(queryOptions); + } +} diff --git a/apps/nextjs/tsconfig.json b/apps/nextjs/tsconfig.json new file mode 100644 index 0000000..e7816d1 --- /dev/null +++ b/apps/nextjs/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "@acme/tsconfig/base.json", + "compilerOptions": { + "lib": ["ES2022", "dom", "dom.iterable"], + "jsx": "preserve", + "paths": { + "@/*": ["./src/*"] + }, + "plugins": [{ "name": "next" }] + }, + "include": [".", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/apps/nextjs/turbo.json b/apps/nextjs/turbo.json new file mode 100644 index 0000000..16d06da --- /dev/null +++ b/apps/nextjs/turbo.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://turborepo.com/schema.json", + "extends": ["//"], + "tasks": { + "build": { + "dependsOn": ["^build"], + "outputs": [".next/**", "!.next/cache/**", "next-env.d.ts"] + }, + "dev": { + "persistent": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..490d8c5 --- /dev/null +++ b/package.json @@ -0,0 +1,37 @@ +{ + "name": "convex-monorepo", + "private": true, + "engines": { + "node": "^22.20.0", + "pnpm": "^10.19.0" + }, + "packageManager": "pnpm@10.19.0", + "scripts": { + "build": "turbo run build", + "clean": "git clean -xdf node_modules", + "clean:workspaces": "turbo run clean && rm -rf node_modules", + "convex:setup": "pnpm -F @acme/backend setup", + "dev": "turbo watch dev --continue", + "dev:tunnel": "turbo watch dev:tunnel --continue", + "dev:next": "turbo watch dev -F @acme/nextjs...", + "format": "turbo run format --continue -- --cache --cache-location .cache/.prettiercache", + "format:fix": "turbo run format --continue -- --write --cache --cache-location .cache/.prettiercache", + "lint": "turbo run lint --continue -- --cache --cache-location .cache/.eslintcache", + "lint:fix": "turbo run lint --continue -- --fix --cache --cache-location .cache/.eslintcache", + "lint:ws": "pnpm dlx sherif@latest", + "postinstall": "pnpm lint:ws", + "typecheck": "turbo run typecheck", + "ui-add": "turbo run ui-add", + "android": "expo run:android", + "ios": "expo run:ios" + }, + "devDependencies": { + "@acme/prettier-config": "workspace:*", + "@turbo/gen": "^2.5.8", + "dotenv-cli": "^10.0.0", + "prettier": "catalog:", + "turbo": "^2.5.8", + "typescript": "catalog:" + }, + "prettier": "@acme/prettier-config" +} diff --git a/packages/backend/.cache/.prettiercache b/packages/backend/.cache/.prettiercache new file mode 100644 index 0000000..2d424bf --- /dev/null +++ b/packages/backend/.cache/.prettiercache @@ -0,0 +1 @@ +[["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],{"key":"16","value":"17"},{"key":"18","value":"19"},{"key":"20","value":"21"},{"key":"22","value":"23"},{"key":"24","value":"25"},{"key":"26","value":"27"},{"key":"28","value":"29"},{"key":"30","value":"31"},{"key":"32","value":"33"},{"key":"34","value":"35"},{"key":"36","value":"37"},{"key":"38","value":"39"},{"key":"40","value":"41"},{"key":"42","value":"43"},{"key":"44","value":"45"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/.gitignore",{"size":16,"mtime":1753933693000,"hash":"46"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/_generated/server.d.ts",{"size":5540,"mtime":1761665487097,"hash":"47","data":"48"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/auth.config.js",{"size":128,"mtime":1753933693000,"hash":"49","data":"50"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/package.json",{"size":1135,"mtime":1761665487290,"hash":"51","data":"52"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/openai.ts",{"size":2036,"mtime":1761665487195,"hash":"53","data":"54"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/README.md",{"size":2525,"mtime":1761665487249,"hash":"55","data":"56"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/_generated/api.js",{"size":414,"mtime":1753933693000,"hash":"57","data":"58"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/tsconfig.json",{"size":732,"mtime":1753933693000,"hash":"59","data":"60"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/_generated/server.js",{"size":3453,"mtime":1761665487114,"hash":"61","data":"62"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/notes.ts",{"size":1632,"mtime":1761665487164,"hash":"63","data":"64"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/env.ts",{"size":219,"mtime":1761665487285,"hash":"65","data":"66"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/_generated/dataModel.d.ts",{"size":1726,"mtime":1761665487061,"hash":"67","data":"68"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/schema.ts",{"size":267,"mtime":1753933693000,"hash":"69","data":"70"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/utils.ts",{"size":635,"mtime":1753933693000,"hash":"71","data":"72"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/backend/convex/_generated/api.d.ts",{"size":845,"mtime":1761665486984,"hash":"73","data":"74"},"175b1a771387d8b7e26145c3d04e0475","da19b68e90524b894bbf1985bcec4d72",{"hashOfOptions":"75"},"a87d36cd21882ed8968ea6138f23acd9",{"hashOfOptions":"76"},"80903421dc266560a15314b96f727e40",{"hashOfOptions":"77"},"2cf34d0dd087d9749396d5f686419f4f",{"hashOfOptions":"78"},"7beaec3443b6db9c1a6b8c1668c98992",{"hashOfOptions":"79"},"c5dea56b7ddd47516cbd4038de020e53",{"hashOfOptions":"80"},"cfa98923457caed911ec68b626ef4234",{"hashOfOptions":"81"},"4a51b371d17b0a9dcc8d3a3d16790eec",{"hashOfOptions":"82"},"99403ed881c0f3caf6c13ad183e06049",{"hashOfOptions":"83"},"d78af64438f2e86a438ce045e0910a1d",{"hashOfOptions":"84"},"1a6eccbe2f9771c5b418adc40d8532c4",{"hashOfOptions":"85"},"9b1b5b82ff06ae9856df10ae91c15946",{"hashOfOptions":"86"},"0a1b4f144561ba1da064a40a2e089f10",{"hashOfOptions":"87"},"26351eae8dc2fa74ce0e3e6f6f0d4a49",{"hashOfOptions":"88"},"2545271053","1384390439","3159514942","514606721","3861339677","511151554","2611213275","1927515469","2174687556","3247610094","3411100989","2670794290","530123092","4075214594"] \ No newline at end of file diff --git a/packages/backend/.gitignore b/packages/backend/.gitignore new file mode 100644 index 0000000..5003a6f --- /dev/null +++ b/packages/backend/.gitignore @@ -0,0 +1,2 @@ +.env.local +.env diff --git a/packages/backend/convex/README.md b/packages/backend/convex/README.md new file mode 100644 index 0000000..97f0913 --- /dev/null +++ b/packages/backend/convex/README.md @@ -0,0 +1,92 @@ +# Welcome to your Convex functions directory! + +Write your Convex functions here. See +https://docs.convex.dev/using/writing-convex-functions for more. + +A query function that takes two arguments looks like: + +```ts +// functions.js +import { v } from "convex/values"; + +import { query } from "./_generated/server"; + +export const myQueryFunction = query({ + // Validators for arguments. + args: { + first: v.number(), + second: v.string(), + }, + + // Function implementation. + handler: async (ctx, args) => { + // Read the database as many times as you need here. + // See https://docs.convex.dev/database/reading-data. + const documents = await ctx.db.query("tablename").collect(); + + // Arguments passed from the client are properties of the args object. + console.log(args.first, args.second); + + // Write arbitrary JavaScript here: filter, aggregate, build derived data, + // remove non-public properties, or create new objects. + return documents; + }, +}); +``` + +Using this query function in a React component looks like: + +```ts +const data = useQuery(api.functions.myQueryFunction, { + first: 10, + second: "hello", +}); +``` + +A mutation function looks like: + +```ts +// functions.js +import { v } from "convex/values"; + +import { mutation } from "./_generated/server"; + +export const myMutationFunction = mutation({ + // Validators for arguments. + args: { + first: v.string(), + second: v.string(), + }, + + // Function implementation. + handler: async (ctx, args) => { + // Insert or modify documents in the database here. + // Mutations can also read from the database like queries. + // See https://docs.convex.dev/database/writing-data. + const message = { body: args.first, author: args.second }; + const id = await ctx.db.insert("messages", message); + + // Optionally, return a value from your mutation. + return await ctx.db.get(id); + }, +}); +``` + +Using this mutation function in a React component looks like: + +```ts +const mutation = useMutation(api.functions.myMutationFunction); +function handleButtonPress() { + // fire and forget, the most common way to use mutations + mutation({ first: "Hello!", second: "me" }); + // OR + // use the result once the mutation has completed + mutation({ first: "Hello!", second: "me" }).then((result) => + console.log(result), + ); +} +``` + +Use the Convex CLI to push your functions to a deployment. See everything +the Convex CLI can do by running `npx convex -h` in your project root +directory. To learn more, launch the docs with `npx convex docs`. diff --git a/packages/backend/convex/_generated/api.d.ts b/packages/backend/convex/_generated/api.d.ts new file mode 100644 index 0000000..a4c23d1 --- /dev/null +++ b/packages/backend/convex/_generated/api.d.ts @@ -0,0 +1,41 @@ +/* eslint-disable */ +/** + * Generated `api` utility. + * + * THIS CODE IS AUTOMATICALLY GENERATED. + * + * To regenerate, run `npx convex dev`. + * @module + */ + +import type { + ApiFromModules, + FilterApi, + FunctionReference, +} from "convex/server"; + +import type * as notes from "../notes.js"; +import type * as openai from "../openai.js"; +import type * as utils from "../utils.js"; + +/** + * A utility for referencing Convex functions in your app's API. + * + * Usage: + * ```js + * const myFunctionReference = api.myModule.myFunction; + * ``` + */ +declare const fullApi: ApiFromModules<{ + notes: typeof notes; + openai: typeof openai; + utils: typeof utils; +}>; +export declare const api: FilterApi< + typeof fullApi, + FunctionReference +>; +export declare const internal: FilterApi< + typeof fullApi, + FunctionReference +>; diff --git a/packages/backend/convex/_generated/api.js b/packages/backend/convex/_generated/api.js new file mode 100644 index 0000000..3f9c482 --- /dev/null +++ b/packages/backend/convex/_generated/api.js @@ -0,0 +1,22 @@ +/* eslint-disable */ +/** + * Generated `api` utility. + * + * THIS CODE IS AUTOMATICALLY GENERATED. + * + * To regenerate, run `npx convex dev`. + * @module + */ + +import { anyApi } from "convex/server"; + +/** + * A utility for referencing Convex functions in your app's API. + * + * Usage: + * ```js + * const myFunctionReference = api.myModule.myFunction; + * ``` + */ +export const api = anyApi; +export const internal = anyApi; diff --git a/packages/backend/convex/_generated/dataModel.d.ts b/packages/backend/convex/_generated/dataModel.d.ts new file mode 100644 index 0000000..376247c --- /dev/null +++ b/packages/backend/convex/_generated/dataModel.d.ts @@ -0,0 +1,61 @@ +/* eslint-disable */ +/** + * Generated data model types. + * + * THIS CODE IS AUTOMATICALLY GENERATED. + * + * To regenerate, run `npx convex dev`. + * @module + */ + +import type { + DataModelFromSchemaDefinition, + DocumentByName, + SystemTableNames, + TableNamesInDataModel, +} from "convex/server"; +import type { GenericId } from "convex/values"; + +import schema from "../schema.js"; + +/** + * The names of all of your Convex tables. + */ +export type TableNames = TableNamesInDataModel; + +/** + * The type of a document stored in Convex. + * + * @typeParam TableName - A string literal type of the table name (like "users"). + */ +export type Doc = DocumentByName< + DataModel, + TableName +>; + +/** + * An identifier for a document in Convex. + * + * Convex documents are uniquely identified by their `Id`, which is accessible + * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids). + * + * Documents can be loaded using `db.get(id)` in query and mutation functions. + * + * IDs are just strings at runtime, but this type can be used to distinguish them from other + * strings when type checking. + * + * @typeParam TableName - A string literal type of the table name (like "users"). + */ +export type Id = + GenericId; + +/** + * A type describing your Convex data model. + * + * This type includes information about what tables you have, the type of + * documents stored in those tables, and the indexes defined on them. + * + * This type is used to parameterize methods like `queryGeneric` and + * `mutationGeneric` to make them type-safe. + */ +export type DataModel = DataModelFromSchemaDefinition; diff --git a/packages/backend/convex/_generated/server.d.ts b/packages/backend/convex/_generated/server.d.ts new file mode 100644 index 0000000..90e3fd1 --- /dev/null +++ b/packages/backend/convex/_generated/server.d.ts @@ -0,0 +1,143 @@ +/* eslint-disable */ +/** + * Generated utilities for implementing server-side Convex query and mutation functions. + * + * THIS CODE IS AUTOMATICALLY GENERATED. + * + * To regenerate, run `npx convex dev`. + * @module + */ + +import { + ActionBuilder, + GenericActionCtx, + GenericDatabaseReader, + GenericDatabaseWriter, + GenericMutationCtx, + GenericQueryCtx, + HttpActionBuilder, + MutationBuilder, + QueryBuilder, +} from "convex/server"; + +import type { DataModel } from "./dataModel.js"; + +/** + * Define a query in this Convex app's public API. + * + * This function will be allowed to read your Convex database and will be accessible from the client. + * + * @param func - The query function. It receives a {@link QueryCtx} as its first argument. + * @returns The wrapped query. Include this as an `export` to name it and make it accessible. + */ +export declare const query: QueryBuilder; + +/** + * Define a query that is only accessible from other Convex functions (but not from the client). + * + * This function will be allowed to read from your Convex database. It will not be accessible from the client. + * + * @param func - The query function. It receives a {@link QueryCtx} as its first argument. + * @returns The wrapped query. Include this as an `export` to name it and make it accessible. + */ +export declare const internalQuery: QueryBuilder; + +/** + * Define a mutation in this Convex app's public API. + * + * This function will be allowed to modify your Convex database and will be accessible from the client. + * + * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. + * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. + */ +export declare const mutation: MutationBuilder; + +/** + * Define a mutation that is only accessible from other Convex functions (but not from the client). + * + * This function will be allowed to modify your Convex database. It will not be accessible from the client. + * + * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. + * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. + */ +export declare const internalMutation: MutationBuilder; + +/** + * Define an action in this Convex app's public API. + * + * An action is a function which can execute any JavaScript code, including non-deterministic + * code and code with side-effects, like calling third-party services. + * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. + * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. + * + * @param func - The action. It receives an {@link ActionCtx} as its first argument. + * @returns The wrapped action. Include this as an `export` to name it and make it accessible. + */ +export declare const action: ActionBuilder; + +/** + * Define an action that is only accessible from other Convex functions (but not from the client). + * + * @param func - The function. It receives an {@link ActionCtx} as its first argument. + * @returns The wrapped function. Include this as an `export` to name it and make it accessible. + */ +export declare const internalAction: ActionBuilder; + +/** + * Define an HTTP action. + * + * This function will be used to respond to HTTP requests received by a Convex + * deployment if the requests matches the path and method where this action + * is routed. Be sure to route your action in `convex/http.js`. + * + * @param func - The function. It receives an {@link ActionCtx} as its first argument. + * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up. + */ +export declare const httpAction: HttpActionBuilder; + +/** + * A set of services for use within Convex query functions. + * + * The query context is passed as the first argument to any Convex query + * function run on the server. + * + * This differs from the {@link MutationCtx} because all of the services are + * read-only. + */ +export type QueryCtx = GenericQueryCtx; + +/** + * A set of services for use within Convex mutation functions. + * + * The mutation context is passed as the first argument to any Convex mutation + * function run on the server. + */ +export type MutationCtx = GenericMutationCtx; + +/** + * A set of services for use within Convex action functions. + * + * The action context is passed as the first argument to any Convex action + * function run on the server. + */ +export type ActionCtx = GenericActionCtx; + +/** + * An interface to read from the database within Convex query functions. + * + * The two entry points are {@link DatabaseReader.get}, which fetches a single + * document by its {@link Id}, or {@link DatabaseReader.query}, which starts + * building a query. + */ +export type DatabaseReader = GenericDatabaseReader; + +/** + * An interface to read from and write to the database within Convex mutation + * functions. + * + * Convex guarantees that all writes within a single mutation are + * executed atomically, so you never have to worry about partial writes leaving + * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control) + * for the guarantees Convex provides your functions. + */ +export type DatabaseWriter = GenericDatabaseWriter; diff --git a/packages/backend/convex/_generated/server.js b/packages/backend/convex/_generated/server.js new file mode 100644 index 0000000..33c92f9 --- /dev/null +++ b/packages/backend/convex/_generated/server.js @@ -0,0 +1,89 @@ +/* eslint-disable */ +/** + * Generated utilities for implementing server-side Convex query and mutation functions. + * + * THIS CODE IS AUTOMATICALLY GENERATED. + * + * To regenerate, run `npx convex dev`. + * @module + */ + +import { + actionGeneric, + httpActionGeneric, + internalActionGeneric, + internalMutationGeneric, + internalQueryGeneric, + mutationGeneric, + queryGeneric, +} from "convex/server"; + +/** + * Define a query in this Convex app's public API. + * + * This function will be allowed to read your Convex database and will be accessible from the client. + * + * @param func - The query function. It receives a {@link QueryCtx} as its first argument. + * @returns The wrapped query. Include this as an `export` to name it and make it accessible. + */ +export const query = queryGeneric; + +/** + * Define a query that is only accessible from other Convex functions (but not from the client). + * + * This function will be allowed to read from your Convex database. It will not be accessible from the client. + * + * @param func - The query function. It receives a {@link QueryCtx} as its first argument. + * @returns The wrapped query. Include this as an `export` to name it and make it accessible. + */ +export const internalQuery = internalQueryGeneric; + +/** + * Define a mutation in this Convex app's public API. + * + * This function will be allowed to modify your Convex database and will be accessible from the client. + * + * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. + * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. + */ +export const mutation = mutationGeneric; + +/** + * Define a mutation that is only accessible from other Convex functions (but not from the client). + * + * This function will be allowed to modify your Convex database. It will not be accessible from the client. + * + * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. + * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. + */ +export const internalMutation = internalMutationGeneric; + +/** + * Define an action in this Convex app's public API. + * + * An action is a function which can execute any JavaScript code, including non-deterministic + * code and code with side-effects, like calling third-party services. + * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. + * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. + * + * @param func - The action. It receives an {@link ActionCtx} as its first argument. + * @returns The wrapped action. Include this as an `export` to name it and make it accessible. + */ +export const action = actionGeneric; + +/** + * Define an action that is only accessible from other Convex functions (but not from the client). + * + * @param func - The function. It receives an {@link ActionCtx} as its first argument. + * @returns The wrapped function. Include this as an `export` to name it and make it accessible. + */ +export const internalAction = internalActionGeneric; + +/** + * Define a Convex HTTP action. + * + * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object + * as its second. + * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`. + */ +export const httpAction = httpActionGeneric; diff --git a/packages/backend/convex/auth.config.js b/packages/backend/convex/auth.config.js new file mode 100644 index 0000000..99b495c --- /dev/null +++ b/packages/backend/convex/auth.config.js @@ -0,0 +1,8 @@ +export default { + providers: [ + { + domain: process.env.CLERK_ISSUER_URL, + applicationID: "convex", + }, + ], +}; diff --git a/packages/backend/convex/notes.ts b/packages/backend/convex/notes.ts new file mode 100644 index 0000000..aa51a7c --- /dev/null +++ b/packages/backend/convex/notes.ts @@ -0,0 +1,71 @@ +import { Auth } from "convex/server"; +import { v } from "convex/values"; + +import { internal } from "../convex/_generated/api"; +import { mutation, query } from "./_generated/server"; + +export const getUserId = async (ctx: { auth: Auth }) => { + return (await ctx.auth.getUserIdentity())?.subject; +}; + +// Get all notes for a specific user +export const getNotes = query({ + args: {}, + handler: async (ctx) => { + const userId = await getUserId(ctx); + if (!userId) return null; + + const notes = await ctx.db + .query("notes") + .filter((q) => q.eq(q.field("userId"), userId)) + .collect(); + + return notes; + }, +}); + +// Get note for a specific note +export const getNote = query({ + args: { + id: v.optional(v.id("notes")), + }, + handler: async (ctx, args) => { + const { id } = args; + if (!id) return null; + const note = await ctx.db.get(id); + return note; + }, +}); + +// Create a new note for a user +export const createNote = mutation({ + args: { + title: v.string(), + content: v.string(), + isSummary: v.boolean(), + }, + handler: async (ctx, { title, content, isSummary }) => { + const userId = await getUserId(ctx); + if (!userId) throw new Error("User not found"); + const noteId = await ctx.db.insert("notes", { userId, title, content }); + + if (isSummary) { + await ctx.scheduler.runAfter(0, internal.openai.summary, { + id: noteId, + title, + content, + }); + } + + return noteId; + }, +}); + +export const deleteNote = mutation({ + args: { + noteId: v.id("notes"), + }, + handler: async (ctx, args) => { + await ctx.db.delete(args.noteId); + }, +}); diff --git a/packages/backend/convex/openai.ts b/packages/backend/convex/openai.ts new file mode 100644 index 0000000..cefbe38 --- /dev/null +++ b/packages/backend/convex/openai.ts @@ -0,0 +1,76 @@ +import { v } from "convex/values"; +import OpenAI from "openai"; + +import { internal } from "./_generated/api"; +import { internalAction, internalMutation, query } from "./_generated/server"; +import { missingEnvVariableUrl } from "./utils"; + +export const openaiKeySet = query({ + args: {}, + handler: async () => { + return !!process.env.OPENAI_API_KEY; + }, +}); + +export const summary = internalAction({ + args: { + id: v.id("notes"), + title: v.string(), + content: v.string(), + }, + handler: async (ctx, { id, title, content }) => { + const prompt = `Take in the following note and return a summary: Title: ${title}, Note content: ${content}`; + + const apiKey = process.env.OPENAI_API_KEY; + if (!apiKey) { + const error = missingEnvVariableUrl( + "OPENAI_API_KEY", + "https://platform.openai.com/account/api-keys", + ); + console.error(error); + await ctx.runMutation(internal.openai.saveSummary, { + id: id, + summary: error, + }); + return; + } + const openai = new OpenAI({ apiKey }); + const output = await openai.chat.completions.create({ + messages: [ + { + role: "system", + content: + "You are a helpful assistant designed to output JSON in this format: {summary: string}", + }, + { role: "user", content: prompt }, + ], + model: "gpt-4-1106-preview", + response_format: { type: "json_object" }, + }); + + // Pull the message content out of the response + const messageContent = output.choices[0]?.message.content; + + console.log({ messageContent }); + + const parsedOutput = JSON.parse(messageContent!); + console.log({ parsedOutput }); + + await ctx.runMutation(internal.openai.saveSummary, { + id: id, + summary: parsedOutput.summary, + }); + }, +}); + +export const saveSummary = internalMutation({ + args: { + id: v.id("notes"), + summary: v.string(), + }, + handler: async (ctx, { id, summary }) => { + await ctx.db.patch(id, { + summary: summary, + }); + }, +}); diff --git a/packages/backend/convex/schema.ts b/packages/backend/convex/schema.ts new file mode 100644 index 0000000..669c26e --- /dev/null +++ b/packages/backend/convex/schema.ts @@ -0,0 +1,11 @@ +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + notes: defineTable({ + userId: v.string(), + title: v.string(), + content: v.string(), + summary: v.optional(v.string()), + }), +}); diff --git a/packages/backend/convex/tsconfig.json b/packages/backend/convex/tsconfig.json new file mode 100644 index 0000000..79995ae --- /dev/null +++ b/packages/backend/convex/tsconfig.json @@ -0,0 +1,24 @@ +{ + /* This TypeScript project config describes the environment that + * Convex functions run in and is used to typecheck them. + * You can modify it, but some settings required to use Convex. + */ + "compilerOptions": { + /* These settings are not required by Convex and can be modified. */ + "allowJs": true, + "strict": true, + + /* These compiler options are required by Convex */ + "target": "ESNext", + "lib": ["ES2021", "dom"], + "forceConsistentCasingInFileNames": true, + "allowSyntheticDefaultImports": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "isolatedModules": true, + "skipLibCheck": true, + "noEmit": true + }, + "include": ["./**/*"], + "exclude": ["./_generated"] +} diff --git a/packages/backend/convex/utils.ts b/packages/backend/convex/utils.ts new file mode 100644 index 0000000..24d17c2 --- /dev/null +++ b/packages/backend/convex/utils.ts @@ -0,0 +1,16 @@ +export function missingEnvVariableUrl(envVarName: string, whereToGet: string) { + const deployment = deploymentName(); + if (!deployment) return `Missing ${envVarName} in environment variables.`; + return ( + `\n Missing ${envVarName} in environment variables.\n\n` + + ` Get it from ${whereToGet} .\n Paste it on the Convex dashboard:\n` + + ` https://dashboard.convex.dev/d/${deployment}/settings?var=${envVarName}` + ); +} + +export function deploymentName() { + const url = process.env.CONVEX_CLOUD_URL; + if (!url) return undefined; + const regex = new RegExp("https://(.+).convex.cloud"); + return regex.exec(url)?.[1]; +} diff --git a/packages/backend/env.ts b/packages/backend/env.ts new file mode 100644 index 0000000..13151ec --- /dev/null +++ b/packages/backend/env.ts @@ -0,0 +1,10 @@ +import { createEnv } from "@t3-oss/env-core"; +import { z } from "zod/v4"; + +export const authEnv = () => { + return createEnv({ + server: {}, + runtimeEnv: process.env, + skipValidation: !!process.env.CI, + }); +}; diff --git a/packages/backend/package.json b/packages/backend/package.json new file mode 100644 index 0000000..694b0f7 --- /dev/null +++ b/packages/backend/package.json @@ -0,0 +1,40 @@ +{ + "name": "@acme/backend", + "private": true, + "type": "module", + "version": "1.0.0", + "description": "Convex Backend for Monorepo", + "author": "Gib", + "license": "MIT", + "exports": {}, + "scripts": { + "dev": "convex dev", + "dev:tunnel": "convex dev", + "setup": "convex dev --until-success", + "clean": "git clean -xdf .cache .turbo dist node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint --flag unstable_native_nodejs_ts_config", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@oslojs/crypto": "^1.0.1", + "@react-email/components": "0.5.4", + "@react-email/render": "^1.4.0", + "@t3-oss/env-core": "^0.13.8", + "convex": "^1.28.0", + "react": "19.1.1", + "react-dom": "19.1.1", + "usesend-js": "^1.5.6", + "zod": "catalog:" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "eslint": "catalog:", + "prettier": "catalog:", + "react-email": "4.2.11", + "typescript": "catalog:" + }, + "prettier": "@acme/prettier-config" +} diff --git a/packages/ui/.cache/.prettiercache b/packages/ui/.cache/.prettiercache new file mode 100644 index 0000000..be9b350 --- /dev/null +++ b/packages/ui/.cache/.prettiercache @@ -0,0 +1 @@ +[["1","2","3","4","5","6","7","8","9","10","11","12","13"],{"key":"14","value":"15"},{"key":"16","value":"17"},{"key":"18","value":"19"},{"key":"20","value":"21"},{"key":"22","value":"23"},{"key":"24","value":"25"},{"key":"26","value":"27"},{"key":"28","value":"29"},{"key":"30","value":"31"},{"key":"32","value":"33"},{"key":"34","value":"35"},{"key":"36","value":"37"},{"key":"38","value":"39"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/src/separator.tsx",{"size":650,"mtime":1761443987000,"hash":"40","data":"41"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/src/input.tsx",{"size":925,"mtime":1761443987000,"hash":"42","data":"43"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/src/label.tsx",{"size":566,"mtime":1761443987000,"hash":"44","data":"45"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/components.json",{"size":308,"mtime":1761443987000,"hash":"46","data":"47"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/src/index.ts",{"size":167,"mtime":1761443987000,"hash":"48","data":"49"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/eslint.config.ts",{"size":256,"mtime":1761443987000,"hash":"50","data":"51"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/src/button.tsx",{"size":2138,"mtime":1761443987000,"hash":"52","data":"53"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/src/dropdown-menu.tsx",{"size":8045,"mtime":1761443987000,"hash":"54","data":"55"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/src/theme.tsx",{"size":5136,"mtime":1761443987000,"hash":"56","data":"57"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/tsconfig.json",{"size":213,"mtime":1761443987000,"hash":"58","data":"59"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/src/toast.tsx",{"size":616,"mtime":1761443987000,"hash":"60","data":"61"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/src/field.tsx",{"size":6144,"mtime":1761443987000,"hash":"62","data":"63"},"/home/gib/Documents/Code/monorepo/convex-monorepo/packages/ui/package.json",{"size":1422,"mtime":1761443987000,"hash":"64","data":"65"},"83cdb634982bdcb0442886a9c1a2ac15",{"hashOfOptions":"66"},"03c1d36d1356b80e30445b4d9896cada",{"hashOfOptions":"67"},"4faf2b2914366f3672010fda69530e83",{"hashOfOptions":"68"},"9c7797b58e9124116b585c64e6c0b829",{"hashOfOptions":"69"},"b80c04716d3fd60c9de5da63578801f5",{"hashOfOptions":"70"},"420f5beb8cfa59be129b4697f434770b",{"hashOfOptions":"71"},"c015de3bdfc4d639054cbc88829ab284",{"hashOfOptions":"72"},"2ce4e76a857d234f206c0e651539636b",{"hashOfOptions":"73"},"b62cf6fa9377430923c4b0137ae2d414",{"hashOfOptions":"74"},"a6fc50dd2d117cd2ab5544870b6eb4fb",{"hashOfOptions":"75"},"3f99d212c8aceb0666e2a52d42f73af1",{"hashOfOptions":"76"},"a47a38dceeddc2f58e8f06c2a2c47a96",{"hashOfOptions":"77"},"62e4d8f2e00d6f44e7698889dce72c88",{"hashOfOptions":"78"},"2094140157","671104514","1777924684","3986582840","634744684","2132860788","4287561166","2299778291","1203426049","4138459277","3973557695","3103518834","3508854902"] \ No newline at end of file diff --git a/packages/ui/components.json b/packages/ui/components.json new file mode 100644 index 0000000..3f15f02 --- /dev/null +++ b/packages/ui/components.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "", + "css": "unused.css", + "baseColor": "zinc", + "cssVariables": true + }, + "aliases": { + "utils": "@acme/ui", + "components": "src/", + "ui": "src/" + } +} diff --git a/packages/ui/eslint.config.ts b/packages/ui/eslint.config.ts new file mode 100644 index 0000000..fb7ab01 --- /dev/null +++ b/packages/ui/eslint.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "eslint/config"; + +import { baseConfig } from "@acme/eslint-config/base"; +import { reactConfig } from "@acme/eslint-config/react"; + +export default defineConfig( + { + ignores: ["dist/**"], + }, + baseConfig, + reactConfig, +); diff --git a/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 0000000..ae4aba9 --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,47 @@ +{ + "name": "@acme/ui", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./button": "./src/button.tsx", + "./dropdown-menu": "./src/dropdown-menu.tsx", + "./field": "./src/field.tsx", + "./input": "./src/input.tsx", + "./label": "./src/label.tsx", + "./separator": "./src/separator.tsx", + "./theme": "./src/theme.tsx", + "./toast": "./src/toast.tsx" + }, + "license": "MIT", + "scripts": { + "clean": "git clean -xdf .cache .turbo dist node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint --flag unstable_native_nodejs_ts_config", + "typecheck": "tsc --noEmit --emitDeclarationOnly false", + "ui-add": "pnpm dlx shadcn@latest add && prettier src --write --list-different" + }, + "dependencies": { + "@radix-ui/react-icons": "^1.3.2", + "class-variance-authority": "^0.7.1", + "radix-ui": "^1.4.3", + "sonner": "^2.0.7", + "tailwind-merge": "^3.3.1" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "@types/react": "catalog:react19", + "eslint": "catalog:", + "prettier": "catalog:", + "react": "catalog:react19", + "typescript": "catalog:", + "zod": "catalog:" + }, + "peerDependencies": { + "react": "catalog:react19", + "zod": "catalog:" + }, + "prettier": "@acme/prettier-config" +} diff --git a/packages/ui/src/button.tsx b/packages/ui/src/button.tsx new file mode 100644 index 0000000..4f9c928 --- /dev/null +++ b/packages/ui/src/button.tsx @@ -0,0 +1,57 @@ +import type { VariantProps } from "class-variance-authority"; +import { cva } from "class-variance-authority"; +import { Slot as SlotPrimitive } from "radix-ui"; + +import { cn } from "@acme/ui"; + +export const buttonVariants = cva( + "focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: + "bg-primary text-primary-foreground hover:bg-primary/90 shadow-xs", + destructive: + "bg-destructive hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60 text-white shadow-xs", + outline: + "bg-background hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 border shadow-xs", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80 shadow-xs", + ghost: + "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2 has-[>svg]:px-3", + sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5", + lg: "h-10 rounded-md px-6 has-[>svg]:px-4", + icon: "size-9", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + }, +); + +export function Button({ + className, + variant, + size, + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean; + }) { + const Comp = asChild ? SlotPrimitive.Slot : "button"; + + return ( + + ); +} diff --git a/packages/ui/src/dropdown-menu.tsx b/packages/ui/src/dropdown-menu.tsx new file mode 100644 index 0000000..11ef322 --- /dev/null +++ b/packages/ui/src/dropdown-menu.tsx @@ -0,0 +1,242 @@ +"use client"; + +import { + CheckIcon, + ChevronRightIcon, + DotFilledIcon, +} from "@radix-ui/react-icons"; +import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"; + +import { cn } from "@acme/ui"; + +export function DropdownMenu({ + ...props +}: React.ComponentProps) { + return ; +} + +export function DropdownMenuPortal({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export function DropdownMenuTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export function DropdownMenuContent({ + className, + sideOffset = 4, + ...props +}: React.ComponentProps) { + return ( + + + + ); +} + +export function DropdownMenuGroup({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export function DropdownMenuItem({ + className, + inset, + variant = "default", + ...props +}: React.ComponentProps & { + inset?: boolean; + variant?: "default" | "destructive"; +}) { + return ( + + ); +} + +export function DropdownMenuCheckboxItem({ + className, + children, + checked, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ); +} + +export function DropdownMenuRadioGroup({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export function DropdownMenuRadioItem({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ); +} + +export function DropdownMenuLabel({ + className, + inset, + ...props +}: React.ComponentProps & { + inset?: boolean; +}) { + return ( + + ); +} + +export function DropdownMenuSeparator({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export function DropdownMenuShortcut({ + className, + ...props +}: React.ComponentProps<"span">) { + return ( + + ); +} + +export function DropdownMenuSub({ + ...props +}: React.ComponentProps) { + return ; +} + +export function DropdownMenuSubTrigger({ + className, + inset, + children, + ...props +}: React.ComponentProps & { + inset?: boolean; +}) { + return ( + + {children} + + + ); +} + +export function DropdownMenuSubContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} diff --git a/packages/ui/src/field.tsx b/packages/ui/src/field.tsx new file mode 100644 index 0000000..da1c2ea --- /dev/null +++ b/packages/ui/src/field.tsx @@ -0,0 +1,249 @@ +"use client"; + +import type { VariantProps } from "class-variance-authority"; +import { useMemo } from "react"; +import { cva } from "class-variance-authority"; + +import { cn } from "@acme/ui"; +import { Label } from "@acme/ui/label"; +import { Separator } from "@acme/ui/separator"; + +export function FieldSet({ + className, + ...props +}: React.ComponentProps<"fieldset">) { + return ( +
[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3", + className, + )} + {...props} + /> + ); +} + +export function FieldLegend({ + className, + variant = "legend", + ...props +}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) { + return ( + + ); +} + +export function FieldGroup({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
[data-slot=field-group]]:gap-4", + className, + )} + {...props} + /> + ); +} + +const fieldVariants = cva( + "group/field data-[invalid=true]:text-destructive flex w-full gap-3", + { + variants: { + orientation: { + vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"], + horizontal: [ + "flex-row items-center", + "[&>[data-slot=field-label]]:flex-auto", + "has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", + ], + responsive: [ + "flex-col @md/field-group:flex-row @md/field-group:items-center [&>*]:w-full @md/field-group:[&>*]:w-auto [&>.sr-only]:w-auto", + "@md/field-group:[&>[data-slot=field-label]]:flex-auto", + "@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", + ], + }, + }, + defaultVariants: { + orientation: "vertical", + }, + }, +); + +export function Field({ + className, + orientation = "vertical", + ...props +}: React.ComponentProps<"div"> & VariantProps) { + return ( +
+ ); +} + +export function FieldContent({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ); +} + +export function FieldLabel({ + className, + ...props +}: React.ComponentProps) { + return ( +