diff --git a/README.md b/README.md index 4e62a20..3641c21 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,80 @@ # nl-postgres -[Vercel's Natural Language Postgres](https://github.com/vercel-labs/natural-language-postgres) on -**Cloudflare Workers**, deployed by [Orun](https://github.com/sourceplane/orun) to stage -and prod on every merge, and then packaged as an Orun baseline. - -This commit is the repository's frame: `intent.yaml` (with the placeholder -workspace `ws_CHANGE_ME`, so CI plans nothing until it is linked), the Orun -CI workflow, the shared TypeScript and ESLint configuration, and the spec -index. The work is tracked as an epic under [`specs/epics`](specs/epics/README.md). +Vercel's [Natural Language Postgres](https://github.com/vercel-labs/natural-language-postgres) +— a question about a table of unicorn companies asked in plain English, the +SQL a model writes for it, the rows, a chart of them and an explanation of +the query: one page and four server actions — running on **Cloudflare +Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), +its SQL written by **Workers AI** through the Worker's `AI` binding and run +as a **read-only database role**, its table a **Supabase** project's +database reached through **Cloudflare Hyperdrive**, both provisioned by +Terraform through [Orun](https://github.com/sourceplane/orun) and the schema +applied by Orun's `db-migrate`, the way the +[rag-chatbot baseline](https://github.com/sourceplane/rag-chatbot) does it, deployed by +[Orun](https://github.com/sourceplane/orun) to stage and prod on every merge. +Packaging it as an Orun baseline is the next milestone (NL2). + +The template's code is the code. What the port changes is what the Workers +runtime, a fresh unattended deployment and SQL written by a model force: the +database client is built per call over the Hyperdrive binding (`lib/db.ts`); +the model is Workers AI's (`lib/ai/models.ts`) — the platform brokers no AI +vendor, and the Cloudflare account the app deploys into already is one — +with upstream's OpenAI model behind an optional key; and the model's SQL runs +only as `query_reader`, a role that can read the one table and nothing else, +through a function it cannot step out of (migration `040_read_only_queries`), +with the template's own string check kept in front. The template's data is +CB Insights' list, which each owner downloads; a fresh product starts with +sixty fictional companies in its shape, and a tool turns the owner's CSV into +a migration. See [`specs/epics/nl-postgres`](specs/epics/nl-postgres/README.md) +for the design, the milestones and the as-built status, including every +departure. + +## What is here (the product) + +| Surface | Where | +|---|---| +| The product's name and source link | `apps/web/lib/site.ts` | +| The page and its four server actions, `/api/health` | `apps/web/app` | +| The model: Workers AI, or OpenAI behind an optional key | `apps/web/lib/ai/models.ts` | +| The per-call client and the read-only query path | `apps/web/lib/db.ts` | +| Workers build and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc` (committed), `component.yaml` | +| The table, the sample data, row-level security and the read-only role as migrations, and Lumen's runner | `packages/db` (`@saas/db`) | +| CB Insights' CSV as a migration; the local apply | `tooling/migrations` | +| The Supabase project, the Hyperdrive config, the migration step | `infra/terraform/supabase`, `infra/terraform/cloudflare-hyperdrive`, `infra/db-migrate` | +| Tests | `tests/web`, `tests/db` (vitest) | + +## Getting started + +```bash +pnpm install +pnpm run wire:fixture # re-render apps/web/wrangler.jsonc from its template (committed; this changes nothing) +pnpm typecheck +pnpm lint +pnpm test +pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next +pnpm --filter @saas/db run manifest:check +``` + +The build needs no database, no model and no Cloudflare credential. Running +it locally — a Postgres on `localhost:5432`, `pnpm --filter @app/web +db:migrate:local`, `wrangler login` for Workers AI, `next dev` or `wrangler +dev` — is in the product's README (`.baseline/product/README.md`), which is +what a product built from here carries. + +## How it maps to Vercel + +| Vercel | Here | +|---|---| +| Next.js 15.5 hosting, four server actions | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets on Next.js 16.3.8 (the adapter refuses 15.5); the actions run as they did | +| `"openai/gpt-5.4-mini"` through Vercel's AI Gateway | Workers AI through the `AI` binding: `@cf/meta/llama-4-scout-17b-16e-instruct`, in JSON mode for the three structured outputs, no key. `OPENAI_API_KEY`, if set, switches to upstream's `gpt-5.4-mini` straight from OpenAI | +| `sql.query(query)` from `@vercel/postgres`, on the owner's connection | `runReadOnlyQuery()`: the query through `app_private.run_read_only` as `query_reader`, in a read-only transaction with a 5 s timeout, behind the template's own check | +| Vercel Postgres | The Supabase project's Postgres through a Hyperdrive config; `getSql()` builds the `postgres` client per call from the `HYPERDRIVE` binding's connection string | +| `pnpm run seed` (lib/seed.ts: the table, and CB Insights' CSV) | `packages/db` + `infra/db-migrate`: the same CREATE TABLE, sixty fictional sample companies, row-level security and the read-only role, applied through Supabase's Management API before the Worker deploys; `tooling/migrations/csv-to-sql.mjs` turns the CSV into a migration | +| A Postgres database created in the dashboard | `infra/terraform/supabase` (one project per environment) + `infra/terraform/cloudflare-hyperdrive` (one config per environment), ids and credentials as orun secrets | +| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, provisioned, deployed; the header links to its own source | + +## CI + +| Workflow | What it runs | Ships to a product | +|---|---|---| +| `ci.yml` | the Orun pipeline, and the only workflow a product carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the app built and dry-deployed per environment, both Terraform roots checked and planned, the migrations planned); no lane runs the `typecheck`, `lint` or `test` scripts — `baseline.yml`'s e2e tier runs them on the bootstrapped product before every tag, and a product's developers run them before they push. The bootstrap's own landings (`orun/BASE-*`) run `plan` alone and nothing waits for it — the landing was checked in the build box; a merge applies, migrates and deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes | diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example new file mode 100644 index 0000000..5bd138a --- /dev/null +++ b/apps/web/.dev.vars.example @@ -0,0 +1,11 @@ +# Local Worker secrets for `wrangler dev` / `opennextjs-cloudflare preview`. +# Copy to .dev.vars (git-ignored). Every key is optional: the database is not +# here (the Worker reaches it through the HYPERDRIVE binding, wrangler.jsonc), +# and neither is the model — Workers AI answers through the AI binding. +# +# OpenAI instead of Workers AI: set, the SQL is written, explained and charted +# by upstream's own model, gpt-5.4-mini, straight from OpenAI. In stage/prod +# this is a Worker secret the owner sets once per environment: +# `wrangler secret put OPENAI_API_KEY --name nl-postgres-web-` +# (README, "Use OpenAI instead"). +# OPENAI_API_KEY= diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 0000000..44c95b3 --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1,17 @@ +# Local development. Copy to .env.local (git-ignored); never commit a value. +# +# DATABASE_URL is read by `pnpm --filter @app/web db:migrate:local` (which +# applies packages/db's migrations to a local Postgres) and by the app only +# when no Cloudflare context is available. Under `next dev` and `wrangler dev` +# the app reads the HYPERDRIVE binding from wrangler.jsonc instead (its +# localConnectionString — point both at the same database). +DATABASE_URL=postgres://postgres:postgres@localhost:5432/unicorns +# Optional. Unset, the SQL is written by Workers AI, through the AI binding +# (`next dev` reaches it after `wrangler login`). Set, it is written by +# upstream's own model, OpenAI's gpt-5.4-mini, straight from OpenAI; `next +# dev` reads it from here, `wrangler dev` from .dev.vars. +# OPENAI_API_KEY= +# Optional: the site's public origin, which the page's Open Graph image link +# is resolved against. The Orun build sets it per environment +# (component.yaml); unset, it is http://localhost:3000. +NEXT_PUBLIC_SITE_URL=http://localhost:3000 diff --git a/apps/web/.vscode/settings.json b/apps/web/.vscode/settings.json new file mode 100644 index 0000000..33b3971 --- /dev/null +++ b/apps/web/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "typescript.tsdk": "node_modules/.pnpm/typescript@5.0.4/node_modules/typescript/lib", + "typescript.enablePromptUseWorkspaceTsdk": true +} diff --git a/apps/web/LICENSE b/apps/web/LICENSE new file mode 100644 index 0000000..695ee2d --- /dev/null +++ b/apps/web/LICENSE @@ -0,0 +1,13 @@ +Copyright 2024 Vercel, 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. \ No newline at end of file diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100644 index 0000000..620ad2f --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,115 @@ +# Natural Language PostgreSQL + + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fnatural-language-postgres&env=OPENAI_API_KEY&envDescription=Learn%20more%20about%20how%20to%20get%20the%20API%20Keys%20for%20the%20application&envLink=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fnatural-language-postgres%2Fblob%2Fmain%2F.env.example&demo-title=Natural%20Language%20Postgres&demo-description=Query%20PostgreSQL%20database%20using%20natural%20language%20and%20visualize%20results%20with%20Next.js%20and%20AI%20SDK.&demo-url=https%3A%2F%2Fnatural-language-postgres.vercel.app&stores=%5B%7B%22type%22%3A%22postgres%22%7D%5D) + +This project is a Next.js application that allows users to query a PostgreSQL database using natural language and visualize the results. It's powered by the AI SDK by Vercel and uses OpenAI's GPT-4o model to translate natural language queries into SQL. + +## Features + +- Natural Language to SQL: Users can input queries in plain English, which are then converted to SQL using AI. +- Data Visualization: Results are displayed in both table and chart formats, with the chart type automatically selected based on the data. +- Query Explanation: Users can view the full SQL query and get an AI-generated explanation of each part of the query. + +## Technology Stack + +- Next.js for the frontend and API routes +- AI SDK by Vercel for AI integration +- OpenAI's GPT-4o for natural language processing +- PostgreSQL for data storage +- Vercel Postgres for database hosting +- Framer Motion for animations +- ShadowUI for UI components +- Tailwind CSS for styling +- Recharts for data visualization + +## How It Works + +1. The user enters a natural language query about unicorn companies. +2. The application uses GPT-4 to generate an appropriate SQL query. +3. The SQL query is executed against the PostgreSQL database. +4. Results are displayed in a table format. +5. An AI-generated chart configuration is created based on the data. +6. The results are visualized using the generated chart configuration. +7. Users can toggle between table and chart views. +8. Users can request an explanation of the SQL query, which is also generated by AI. + +## Data + +The database contains information about unicorn companies, including: + +- Company name +- Valuation +- Date joined (unicorn status) +- Country +- City +- Industry +- Select investors + +This data is based on CB Insights' list of unicorn companies. + +## Getting Started + +To get the project up and running, follow these steps: + +1. Install dependencies: + + ```bash + pnpm install + ``` + +2. Copy the example environment file: + + ```bash + cp .env.example .env + ``` + +3. Add your OpenAI API key and PostgreSQL connection string to the `.env` file: + + ``` + OPENAI_API_KEY=your_api_key_here + POSTGRES_URL="..." + POSTGRES_PRISMA_URL="..." + POSTGRES_URL_NO_SSL="..." + POSTGRES_URL_NON_POOLING="..." + POSTGRES_USER="..." + POSTGRES_HOST="..." + POSTGRES_PASSWORD="..." + POSTGRES_DATABASE="..." + ``` +4. Download the dataset: + - Go to https://www.cbinsights.com/research-unicorn-companies + - Download the unicorn companies dataset + - Save the file as `unicorns.csv` in the root of your project + +5. Seed the database: + ```bash + pnpm run seed + ``` + +6. Start the development server: + ```bash + pnpm run dev + ``` + +Your project should now be running on [http://localhost:3000](http://localhost:3000). + +## Deployment + +The project is set up for easy deployment on Vercel. Use the "Deploy with Vercel" button in the repository to create your own instance of the application. + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fnatural-language-postgres&env=OPENAI_API_KEY&envDescription=Learn%20more%20about%20how%20to%20get%20the%20API%20Keys%20for%20the%20application&envLink=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fnatural-language-postgres%2Fblob%2Fmain%2F.env.example&demo-title=Natural%20Language%20Postgres&demo-description=Query%20PostgreSQL%20database%20using%20natural%20language%20and%20visualize%20results%20with%20Next.js%20and%20AI%20SDK.&demo-url=https%3A%2F%2Fnatural-language-postgres.vercel.app&stores=%5B%7B%22type%22%3A%22postgres%22%7D%5D) + + +## Learn More + +To learn more about the technologies used in this project, check out the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) +- [AI SDK](https://sdk.vercel.ai/docs) +- [OpenAI](https://openai.com/) +- [Vercel Postgres powered by Neon](https://vercel.com/docs/storage/vercel-postgres) +- [Framer Motion](https://www.framer.com/motion/) +- [ShadcnUI](https://ui.shadcn.com/) +- [Tailwind CSS](https://tailwindcss.com/docs) +- [Recharts](https://recharts.org/en-US/) \ No newline at end of file diff --git a/apps/web/app/actions.ts b/apps/web/app/actions.ts new file mode 100644 index 0000000..669093c --- /dev/null +++ b/apps/web/app/actions.ts @@ -0,0 +1,200 @@ +"use server"; + +import { Config, configSchema, explanationsSchema, Result } from "@/lib/types"; +import { runReadOnlyQuery } from "@/lib/db"; +import { model } from "@/lib/ai/models"; +import { generateText, Output } from "ai"; +import { z } from "zod"; + +export const generateQuery = async (input: string) => { + "use server"; + try { + const { output } = await generateText({ + model: await model(), + system: `You are a SQL (postgres) and data visualization expert. Your job is to help the user write a SQL query to retrieve the data they need. The table schema is as follows: + + unicorns ( + id SERIAL PRIMARY KEY, + company VARCHAR(255) NOT NULL UNIQUE, + valuation DECIMAL(10, 2) NOT NULL, + date_joined DATE, + country VARCHAR(255) NOT NULL, + city VARCHAR(255) NOT NULL, + industry VARCHAR(255) NOT NULL, + select_investors TEXT NOT NULL + ); + + Only retrieval queries are allowed. + + For things like industry, company names and other string fields, use the ILIKE operator and convert both the search term and the field to lowercase using LOWER() function. For example: LOWER(industry) ILIKE LOWER('%search_term%'). + + Note: select_investors is a comma-separated list of investors. Trim whitespace to ensure you're grouping properly. Note, some fields may be null or have only one value. + When answering questions about a specific field, ensure you are selecting the identifying column (ie. what is Vercel's valuation would select company and valuation'). + + The industries available are: + - healthcare & life sciences + - consumer & retail + - financial services + - enterprise tech + - insurance + - media & entertainment + - industrials + - health + + If the user asks for a category that is not in the list, infer based on the list above. + + Note: valuation is in billions of dollars so 10b would be 10.0. + Note: if the user asks for a rate, return it as a decimal. For example, 0.1 would be 10%. + + If the user asks for 'over time' data, return by year. + + When searching for UK or USA, write out United Kingdom or United States respectively. + + EVERY QUERY SHOULD RETURN QUANTITATIVE DATA THAT CAN BE PLOTTED ON A CHART! There should always be at least two columns. If the user asks for a single column, return the column and the count of the column. If the user asks for a rate, return the rate as a decimal. For example, 0.1 would be 10%. + `, + prompt: `Generate the query necessary to retrieve the data the user wants: ${input}`, + output: Output.object({ + schema: z.object({ + query: z.string(), + }), + }), + }); + return output.query; + } catch (e) { + console.error(e); + throw new Error("Failed to generate query"); + } +}; + +export const runGenerateSQLQuery = async (query: string) => { + "use server"; + // Check if the query is a SELECT statement + if ( + !query.trim().toLowerCase().startsWith("select") || + query.trim().toLowerCase().includes("drop") || + query.trim().toLowerCase().includes("delete") || + query.trim().toLowerCase().includes("insert") || + query.trim().toLowerCase().includes("update") || + query.trim().toLowerCase().includes("alter") || + query.trim().toLowerCase().includes("truncate") || + query.trim().toLowerCase().includes("create") || + query.trim().toLowerCase().includes("grant") || + query.trim().toLowerCase().includes("revoke") + ) { + throw new Error("Only SELECT queries are allowed"); + } + + // Not upstream's: the query runs as query_reader, not as this connection + // (lib/db.ts, migration 040) — the check above is the template's, and the + // database's privileges are the boundary. + let rows: Result[]; + try { + rows = await runReadOnlyQuery(query); + } catch (e: any) { + if ( + e.message.includes('relation "unicorns" does not exist') || + e.message.includes("app_private.run_read_only") + ) { + // Upstream seeded the table here once; here the migrations create and + // seed it (db-migrate), so an unmigrated database is an error. + console.log("The database is not migrated: apply packages/db's migrations"); + throw Error("Table does not exist"); + } else { + throw e; + } + } + + return rows; +}; + +export const explainQuery = async (input: string, sqlQuery: string) => { + "use server"; + try { + const { output } = await generateText({ + model: await model(), + output: Output.object({ + schema: z.object({ + explanations: explanationsSchema, + }), + }), + system: `You are a SQL (postgres) expert. Your job is to explain to the user write a SQL query you wrote to retrieve the data they asked for. The table schema is as follows: + unicorns ( + id SERIAL PRIMARY KEY, + company VARCHAR(255) NOT NULL UNIQUE, + valuation DECIMAL(10, 2) NOT NULL, + date_joined DATE, + country VARCHAR(255) NOT NULL, + city VARCHAR(255) NOT NULL, + industry VARCHAR(255) NOT NULL, + select_investors TEXT NOT NULL + ); + + When you explain you must take a section of the query, and then explain it. Each "section" should be unique. So in a query like: "SELECT * FROM unicorns limit 20", the sections could be "SELECT *", "FROM UNICORNS", "LIMIT 20". + If a section doesnt have any explanation, include it, but leave the explanation empty. + + `, + prompt: `Explain the SQL query you generated to retrieve the data the user wanted. Assume the user is not an expert in SQL. Break down the query into steps. Be concise. + + User Query: + ${input} + + Generated SQL Query: + ${sqlQuery}`, + }); + return output; + } catch (e) { + console.error(e); + throw new Error("Failed to generate query"); + } +}; + +export const generateChartConfig = async ( + results: Result[], + userQuery: string, +) => { + "use server"; + const system = `You are a data visualization expert. `; + + try { + const { output: config } = await generateText({ + model: await model(), + system, + prompt: `Given the following data from a SQL query result, generate the chart config that best visualises the data and answers the users query. + For multiple groups use multi-lines. + + Here is an example complete config: + export const chartConfig = { + type: "pie", + xKey: "month", + yKeys: ["sales", "profit", "expenses"], + colors: { + sales: "#4CAF50", // Green for sales + profit: "#2196F3", // Blue for profit + expenses: "#F44336" // Red for expenses + }, + legend: true + } + + User Query: + ${userQuery} + + Data: + ${JSON.stringify(results, null, 2)}`, + output: Output.object({ + schema: configSchema, + }), + }); + + const colors: Record = {}; + config.yKeys.forEach((key, index) => { + colors[key] = `hsl(var(--chart-${index + 1}))`; + }); + + const updatedConfig: Config = { ...config, colors }; + return { config: updatedConfig }; + } catch (e) { + // @ts-expect-errore + console.error(e.message); + throw new Error("Failed to generate chart suggestion"); + } +}; diff --git a/apps/web/app/api/health/route.ts b/apps/web/app/api/health/route.ts new file mode 100644 index 0000000..e756487 --- /dev/null +++ b/apps/web/app/api/health/route.ts @@ -0,0 +1,38 @@ +import { getSql } from "@/lib/db"; +import { modelProvider } from "@/lib/ai/models"; + +// Not upstream's: the deploy's smoke check and the bootstrap's probe read +// this. A page that renders proves the Worker deployed; this proves what the +// page never touches until somebody asks a question — the HYPERDRIVE binding +// names a real config, Hyperdrive reaches the Supabase database, and +// db-migrate applied the schema: the table, the role the model's SQL runs as +// and the function it runs through (migration 040). It calls no model and +// runs no generated SQL. `model` says which provider would write the SQL +// (lib/ai/models.ts). +export const dynamic = "force-dynamic"; + +export async function GET() { + try { + const sql = await getSql(); + try { + const [row] = await sql< + { unicorns: string | null; reader: boolean; runner: string | null }[] + >`select to_regclass('public.unicorns')::text as unicorns, + exists (select 1 from pg_roles where rolname = 'query_reader') as reader, + to_regprocedure('app_private.run_read_only(text)')::text as runner`; + const ok = Boolean(row?.unicorns && row?.reader && row?.runner); + return Response.json( + { ok, database: "reachable", schema: ok ? "migrated" : "missing", model: modelProvider() }, + { status: ok ? 200 : 503, headers: { "cache-control": "no-store" } }, + ); + } finally { + await sql.end({ timeout: 5 }); + } + } catch (error) { + console.error("health: database check failed", error); + return Response.json( + { ok: false, database: "unreachable" }, + { status: 503, headers: { "cache-control": "no-store" } }, + ); + } +} diff --git a/apps/web/app/favicon.ico b/apps/web/app/favicon.ico new file mode 100644 index 0000000..718d6fe Binary files /dev/null and b/apps/web/app/favicon.ico differ diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css new file mode 100644 index 0000000..6c7fb71 --- /dev/null +++ b/apps/web/app/globals.css @@ -0,0 +1,72 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +:root { + --foreground-rgb: 0, 0, 0; + --background-start-rgb: 214, 219, 220; + --background-end-rgb: 255, 255, 255; +} + + + +@layer base { + :root { + --background: 0 0% 100%; + --foreground: 0 0% 3.9%; + --card: 0 0% 100%; + --card-foreground: 0 0% 3.9%; + --popover: 0 0% 100%; + --popover-foreground: 0 0% 3.9%; + --primary: 0 0% 9%; + --primary-foreground: 0 0% 98%; + --secondary: 0 0% 96.1%; + --secondary-foreground: 0 0% 9%; + --muted: 0 0% 96.1%; + --muted-foreground: 0 0% 45.1%; + --accent: 0 0% 96.1%; + --accent-foreground: 0 0% 9%; + --destructive: 0 84.2% 60.2%; + --destructive-foreground: 0 0% 98%; + --border: 0 0% 89.8%; + --input: 0 0% 89.8%; + --ring: 0 0% 3.9%; + --radius: 0.5rem; + --chart-1: 240 2% 26%; + --chart-2: 240 1% 42%; + --chart-3: 240 1% 58%; + --chart-4: 240 1% 74%; + --chart-5: 359 2% 90%; + } + + .dark { + --background: 0 0% 3.9%; + --foreground: 0 0% 98%; + --card: 0 0% 3.9%; + --card-foreground: 0 0% 98%; + --popover: 0 0% 3.9%; + --popover-foreground: 0 0% 98%; + --primary: 0 0% 98%; + --primary-foreground: 0 0% 9%; + --secondary: 0 0% 14.9%; + --secondary-foreground: 0 0% 98%; + --muted: 0 0% 14.9%; + --muted-foreground: 0 0% 63.9%; + --accent: 0 0% 14.9%; + --accent-foreground: 0 0% 98%; + --destructive: 0 62.8% 30.6%; + --destructive-foreground: 0 0% 98%; + --border: 0 0% 14.9%; + --input: 0 0% 14.9%; + --ring: 0 0% 83.1%; + --chart-1: 359 2% 90%; + --chart-2: 240 1% 74%; + --chart-3: 240 1% 58%; + --chart-4: 240 1% 42%; + --chart-5: 240 2% 26%; + } +} + +body { + @apply bg-neutral-50 dark:bg-neutral-900; +} \ No newline at end of file diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx new file mode 100644 index 0000000..4b3564f --- /dev/null +++ b/apps/web/app/layout.tsx @@ -0,0 +1,28 @@ +import "./globals.css"; +import { GeistMono } from "geist/font/mono"; +import { GeistSans } from "geist/font/sans"; +import { ThemeProvider } from "next-themes"; +import { SITE_NAME, siteUrl } from "@/lib/site"; + +export const metadata = { + metadataBase: siteUrl(), + title: SITE_NAME, + description: + "Chat with a Postgres database using natural language powered by the AI SDK by Vercel.", +}; + +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + + + + {children} + + + + ); +} diff --git a/apps/web/app/opengraph-image.png b/apps/web/app/opengraph-image.png new file mode 100644 index 0000000..500564c Binary files /dev/null and b/apps/web/app/opengraph-image.png differ diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx new file mode 100644 index 0000000..a68ce27 --- /dev/null +++ b/apps/web/app/page.tsx @@ -0,0 +1,160 @@ +"use client"; + +import { useState } from "react"; +import { motion, AnimatePresence } from "framer-motion"; +import { + generateChartConfig, + generateQuery, + runGenerateSQLQuery, +} from "./actions"; +import { Config, Result } from "@/lib/types"; +import { Loader2 } from "lucide-react"; +import { toast } from "sonner"; +import { ProjectInfo } from "@/components/project-info"; +import { Results } from "@/components/results"; +import { SuggestedQueries } from "@/components/suggested-queries"; +import { QueryViewer } from "@/components/query-viewer"; +import { Search } from "@/components/search"; +import { Header } from "@/components/header"; + +export default function Page() { + const [inputValue, setInputValue] = useState(""); + const [submitted, setSubmitted] = useState(false); + const [results, setResults] = useState([]); + const [columns, setColumns] = useState([]); + const [activeQuery, setActiveQuery] = useState(""); + const [loading, setLoading] = useState(false); + const [loadingStep, setLoadingStep] = useState(1); + const [chartConfig, setChartConfig] = useState(null); + + const handleSubmit = async (suggestion?: string) => { + const question = suggestion ?? inputValue; + if (inputValue.length === 0 && !suggestion) return; + clearExistingData(); + if (question.trim()) { + setSubmitted(true); + } + setLoading(true); + setLoadingStep(1); + setActiveQuery(""); + try { + const query = await generateQuery(question); + if (query === undefined) { + toast.error("An error occurred. Please try again."); + setLoading(false); + return; + } + setActiveQuery(query); + setLoadingStep(2); + const companies = await runGenerateSQLQuery(query); + const columns = companies.length > 0 ? Object.keys(companies[0]) : []; + setResults(companies); + setColumns(columns); + setLoading(false); + const generation = await generateChartConfig(companies, question); + setChartConfig(generation.config); + } catch (e) { + toast.error("An error occurred. Please try again."); + setLoading(false); + } + }; + + const handleSuggestionClick = async (suggestion: string) => { + setInputValue(suggestion); + try { + await handleSubmit(suggestion); + } catch (e) { + toast.error("An error occurred. Please try again."); + } + }; + + const clearExistingData = () => { + setActiveQuery(""); + setResults([]); + setColumns([]); + setChartConfig(null); + }; + + const handleClear = () => { + setSubmitted(false); + setInputValue(""); + clearExistingData(); + }; + + return ( +
+
+ +
+
+ +
+
+ + {!submitted ? ( + + ) : ( + + {activeQuery.length > 0 && ( + + )} + {loading ? ( +
+ +

+ {loadingStep === 1 + ? "Generating SQL query..." + : "Running SQL query..."} +

+
+ ) : results.length === 0 ? ( +
+

+ No results found. +

+
+ ) : ( + + )} +
+ )} +
+
+
+
+ +
+
+
+ ); +} diff --git a/apps/web/cloudflare-env.d.ts b/apps/web/cloudflare-env.d.ts new file mode 100644 index 0000000..ae65789 --- /dev/null +++ b/apps/web/cloudflare-env.d.ts @@ -0,0 +1,13 @@ +// The bindings wrangler.template.jsonc gives the Worker, as seen through +// `getCloudflareContext().env` from @opennextjs/cloudflare (which types `env` +// as the global `CloudflareEnv` interface for the app to augment). Regenerate +// with `wrangler types --env-interface CloudflareEnv` after changing the +// bindings. +/// +interface CloudflareEnv { + HYPERDRIVE: Hyperdrive; + AI: Ai; + ASSETS: Fetcher; + // Optional Worker secret (lib/ai/models.ts): upstream's model, from OpenAI. + OPENAI_API_KEY?: string; +} diff --git a/apps/web/component.yaml b/apps/web/component.yaml new file mode 100644 index 0000000..8e6e940 --- /dev/null +++ b/apps/web/component.yaml @@ -0,0 +1,122 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: web + description: Vercel's Natural Language Postgres (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, Workers AI writing the SQL, the model's SQL run as a read-only role, per environment) +spec: + type: cloudflare-workers-assets-turbo + lifecycle: production + owner: platform + # Its pages, attached to it in the workspace's catalog: what the Docs + # library shows for it, and what the catalog's docs and runbook checks read. + # Generated from what this manifest and its sources declare. + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + # `app`, not `web`: a domain and a component share one name space in the + # catalog, and a domain called `web` hid this component from it. + domain: app + path: apps/web + # Its own lane per environment: the Next.js build is the longest job in the + # plan, and a shared lane would wait on it. + lane: isolated + # INFRA BEFORE APP, ENFORCED ON MAIN. A merge to main converges the whole + # product in one run: the Supabase project, then the Hyperdrive config over + # its database, then the migrations — the unicorns table, its sample rows, + # row-level security, the read-only role the model's SQL runs as — then + # this Worker. Its deploy reads the Hyperdrive id + # (WIRING_CLOUDFLARE_HYPERDRIVE_, rendered into the HYPERDRIVE binding) + # and needs the schema applied, and a job resolves its secrets when it + # STARTS — so it waits on both, `mode: enforced`, and the ids the applies + # lease-published are there. A pull request deploys nothing, so nothing on + # one waits: every edge is advisory there. + dependsOn: + - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: db-migrate + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + # The wiring documents the cloudflare-hyperdrive root lease-publishes, one + # per deployed environment; tooling/wire/live.mjs picks this job's. Workers + # AI needs nothing here: the AI binding is the account the deploy targets. + # OPENAI_API_KEY, if an owner wants upstream's OpenAI model, is a Worker + # secret they set once per environment (README); the lane never sets it. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://nl-postgres/nl-postgres/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://nl-postgres/nl-postgres/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + subscribe: + environments: + - name: dev + profile: verify + - name: stage + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + - name: prod + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + + workspaceDir: ../.. + appDir: . + + turboFilter: "@app/web" + wranglerConfig: wrangler.jsonc + + # @opennextjs/cloudflare emits a Worker entrypoint plus a static-assets + # directory bound via ASSETS — both deploy in one `wrangler deploy`. + workerEntrypoint: .open-next/worker.js + assetsDir: .open-next/assets + + # Per-env worker name: nl-postgres-web-{dev,stage,prod}. + workerName: nl-postgres-web + environmentAwareWorkerName: true + + # The account's workers.dev subdomain; exported to the smoke step as + # ${WORKERS_DEV_SUBDOMAIN} and used to build ${DEPLOYED_URL}. + workersDevSubdomain: your-workers-subdomain + + installCommand: pnpm install --frozen-lockfile + # wrangler.jsonc is COMMITTED — the fixture render, so the composition's + # structure check (`test -f wrangler.jsonc`, before the build, in a fresh + # checkout) passes. Stage and prod re-render it here, in their own job + # tree, from this environment's wiring document, so the Worker binds the + # real Hyperdrive config; dev verifies with the fixture and has no wiring. + # + # The site's public origin (the Open Graph image link is absolute, and the + # page is pre-rendered, so the build bakes it in): the environment's + # SITE_URL when intent.yaml sets one (a custom domain), else its + # workers.dev URL. The subdomain is written out rather than read from + # ${WORKERS_DEV_SUBDOMAIN}: the composition exports that to the smoke step + # only, so the build would see it empty and bake + # `https://-..workers.dev` into the link. ${ORUN_ENVIRONMENT} + # the runner sets for every step. + buildCommand: if [ "${ORUN_ENVIRONMENT}" != dev ]; then node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-hyperdrive --env "${ORUN_ENVIRONMENT}"; fi && NEXT_PUBLIC_SITE_URL="${SITE_URL:-https://nl-postgres-web-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" pnpm exec turbo run build --filter=@app/web + + # Smoke: the page renders (its question box is in the pre-rendered + # shell), and /api/health answers ok — the database behind the HYPERDRIVE + # binding reachable and migrated: the table, the read-only role and the + # function the model's SQL runs through. Neither calls a model. Each + # response is buffered before grep so an early match cannot SIGPIPE curl. + smokeCommand: "html=$(curl -sfL \"${DEPLOYED_URL}/\") && echo \"${html}\" | grep -q 'placeholder=\"Ask about startup unicorns...\"' && health=$(curl -sf \"${DEPLOYED_URL}/api/health\") && echo \"${health}\" | grep -q '\"ok\":true'" + labels: + team: platform + layer: delivery + surface: web + runtime: cloudflare diff --git a/apps/web/components.json b/apps/web/components.json new file mode 100644 index 0000000..5896c1a --- /dev/null +++ b/apps/web/components.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "default", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "tailwind.config.js", + "css": "app/globals.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + } +} \ No newline at end of file diff --git a/apps/web/components/dynamic-chart.tsx b/apps/web/components/dynamic-chart.tsx new file mode 100644 index 0000000..ef23796 --- /dev/null +++ b/apps/web/components/dynamic-chart.tsx @@ -0,0 +1,234 @@ +"use client"; + +import { useState } from "react"; +import { + Bar, + BarChart, + Line, + LineChart, + Area, + AreaChart, + Pie, + PieChart, + Cell, + XAxis, + YAxis, + CartesianGrid, + Legend, +} from "recharts"; +import { + ChartContainer, + ChartTooltip, + ChartTooltipContent, +} from "@/components/ui/chart"; +import { Config, Result } from "@/lib/types"; +import { Label } from "recharts"; +import { transformDataForMultiLineChart } from "@/lib/rechart-format"; + +function toTitleCase(str: string): string { + return str + .split("_") + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(" "); +} +const colors = [ + "hsl(var(--chart-1))", + "hsl(var(--chart-2))", + "hsl(var(--chart-3))", + "hsl(var(--chart-4))", + "hsl(var(--chart-5))", + "hsl(var(--chart-6))", + "hsl(var(--chart-7))", + "hsl(var(--chart-8))", +]; + +export function DynamicChart({ + chartData, + chartConfig, +}: { + chartData: Result[]; + chartConfig: Config; +}) { + const renderChart = () => { + if (!chartData || !chartConfig) return
No chart data
; + const parsedChartData = chartData.map((item) => { + const parsedItem: { [key: string]: any } = {}; + for (const [key, value] of Object.entries(item)) { + parsedItem[key] = isNaN(Number(value)) ? value : Number(value); + } + return parsedItem; + }); + + chartData = parsedChartData; + + const processChartData = (data: Result[], chartType: string) => { + if (chartType === "bar" || chartType === "pie") { + if (data.length <= 8) { + return data; + } + + const subset = data.slice(0, 20); + return subset; + } + return data; + }; + + chartData = processChartData(chartData, chartConfig.type); + // console.log({ chartData, chartConfig }); + + switch (chartConfig.type) { + case "bar": + return ( + + + + + + + } /> + {chartConfig.legend && } + {chartConfig.yKeys.map((key, index) => ( + + ))} + + ); + case "line": + const { data, xAxisField, lineFields } = transformDataForMultiLineChart( + chartData, + chartConfig, + ); + const useTransformedData = + chartConfig.multipleLines && + chartConfig.measurementColumn && + chartConfig.yKeys.includes(chartConfig.measurementColumn); + // console.log(useTransformedData, "useTransformedData"); + // const useTransformedData = false; + return ( + + + + + + + } /> + {chartConfig.legend && } + {useTransformedData + ? lineFields.map((key, index) => ( + + )) + : chartConfig.yKeys.map((key, index) => ( + + ))} + + ); + case "area": + return ( + + + + + } /> + {chartConfig.legend && } + {chartConfig.yKeys.map((key, index) => ( + + ))} + + ); + case "pie": + return ( + + + {chartData.map((_, index) => ( + + ))} + + } /> + {chartConfig.legend && } + + ); + default: + return
Unsupported chart type: {chartConfig.type}
; + } + }; + + return ( +
+

{chartConfig.title}

+ {chartConfig && chartData.length > 0 && ( + { + acc[key] = { + label: key, + color: colors[index % colors.length], + }; + return acc; + }, + {} as Record, + )} + className="h-[320px] w-full" + > + {renderChart()} + + )} +
+

{chartConfig.description}

+

{chartConfig.takeaway}

+
+
+ ); +} diff --git a/apps/web/components/header.tsx b/apps/web/components/header.tsx new file mode 100644 index 0000000..89d38d2 --- /dev/null +++ b/apps/web/components/header.tsx @@ -0,0 +1,37 @@ +import { Moon, Sun } from "lucide-react"; +import { SourceLink } from "./source-link"; +import { SITE_NAME } from "@/lib/site"; +import { Button } from "./ui/button"; +import { useTheme } from "next-themes"; + +export const Header = ({ handleClear }: { handleClear: () => void }) => { + const { theme, setTheme } = useTheme(); + + return ( +
+

handleClear()} + > + {SITE_NAME} +

+
+ +
+ +
+
+
+ ); +}; diff --git a/apps/web/components/project-info.tsx b/apps/web/components/project-info.tsx new file mode 100644 index 0000000..764b0d9 --- /dev/null +++ b/apps/web/components/project-info.tsx @@ -0,0 +1,39 @@ +import { Info } from "lucide-react"; +import { SourceLink } from "./source-link"; +import { Alert, AlertDescription } from "./ui/alert"; +import Link from "next/link"; + +export const ProjectInfo = () => { + return ( +
+ + + + This application uses the{" "} + + AI SDK + {" "} + to allow you to query a PostgreSQL database with natural language. It + starts with sample data — sixty fictional companies — in + the shape of CB Insights' list of all unicorn companies, which + its README says how to load. Learn more at{" "} + + CB Insights + + . +
+ +
+
+
+
+ ); +}; diff --git a/apps/web/components/query-viewer.tsx b/apps/web/components/query-viewer.tsx new file mode 100644 index 0000000..8963f2f --- /dev/null +++ b/apps/web/components/query-viewer.tsx @@ -0,0 +1,90 @@ +import { useState } from "react"; +import { Button } from "./ui/button"; +import { QueryWithTooltips } from "./ui/query-with-tooltips"; +import { explainQuery } from "@/app/actions"; +import { QueryExplanation } from "@/lib/types"; +import { CircleHelp, Loader2 } from "lucide-react"; + +export const QueryViewer = ({ + activeQuery, + inputValue, +}: { + activeQuery: string; + inputValue: string; +}) => { + const activeQueryCutoff = 100; + + const [queryExplanations, setQueryExplanations] = useState< + QueryExplanation[] | null + >(); + const [loadingExplanation, setLoadingExplanation] = useState(false); + const [queryExpanded, setQueryExpanded] = useState(activeQuery.length > activeQueryCutoff); + + const handleExplainQuery = async () => { + setQueryExpanded(true); + setLoadingExplanation(true); + const { explanations } = await explainQuery(inputValue, activeQuery); + setQueryExplanations(explanations); + setLoadingExplanation(false); + }; + + if (activeQuery.length === 0) return null; + + return ( +
+
+
+ {queryExpanded ? ( + queryExplanations && queryExplanations.length > 0 ? ( + <> + +

+ Generated explanation! Hover over different parts of the SQL + query to see explanations. +

+ + ) : ( +
+ {activeQuery} + +
+ ) + ) : ( + + {activeQuery.slice(0, activeQueryCutoff)} + {activeQuery.length > activeQueryCutoff ? "..." : ""} + + )} +
+
+ {!queryExpanded && ( + + )} +
+ ); +}; diff --git a/apps/web/components/results.tsx b/apps/web/components/results.tsx new file mode 100644 index 0000000..f791f65 --- /dev/null +++ b/apps/web/components/results.tsx @@ -0,0 +1,117 @@ +import { Config, Result, Unicorn } from "@/lib/types"; +import { DynamicChart } from "./dynamic-chart"; +import { SkeletonCard } from "./skeleton-card"; +import { + TableHeader, + TableRow, + TableHead, + TableBody, + TableCell, + Table, +} from "./ui/table"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs"; + +export const Results = ({ + results, + columns, + chartConfig, +}: { + results: Result[]; + columns: string[]; + chartConfig: Config | null; +}) => { + const formatColumnTitle = (title: string) => { + return title + .split("_") + .map((word, index) => + index === 0 ? word.charAt(0).toUpperCase() + word.slice(1) : word, + ) + .join(" "); + }; + + const formatCellValue = (column: string, value: any) => { + if (column.toLowerCase().includes("valuation")) { + const parsedValue = parseFloat(value); + if (isNaN(parsedValue)) { + return ""; + } + const formattedValue = parsedValue.toFixed(2); + const trimmedValue = formattedValue.replace(/\.?0+$/, ""); + return `$${trimmedValue}B`; + } + if (column.toLowerCase().includes("rate")) { + const parsedValue = parseFloat(value); + if (isNaN(parsedValue)) { + return ""; + } + const percentage = (parsedValue * 100).toFixed(2); + return `${percentage}%`; + } + if (value instanceof Date) { + return value.toLocaleDateString(); + } + return String(value); + }; + + return ( +
+ + + Table + + Chart + + + +
+ + + + {columns.map((column, index) => ( + + {formatColumnTitle(column)} + + ))} + + + + {results.map((company, index) => ( + + {columns.map((column, cellIndex) => ( + + {formatCellValue( + column, + company[column as keyof Unicorn], + )} + + ))} + + ))} + +
+
+
+ +
+ {chartConfig && results.length > 0 ? ( + + ) : ( + + )} +
+
+
+
+ ); +}; diff --git a/apps/web/components/search.tsx b/apps/web/components/search.tsx new file mode 100644 index 0000000..1b446d6 --- /dev/null +++ b/apps/web/components/search.tsx @@ -0,0 +1,56 @@ +import { Search as SearchIcon } from "lucide-react"; +import { Button } from "./ui/button"; +import { Input } from "./ui/input"; + +export const Search = ({ + handleSubmit, + inputValue, + setInputValue, + submitted, + handleClear, +}: { + handleSubmit: () => Promise; + inputValue: string; + setInputValue: React.Dispatch>; + submitted: boolean; + handleClear: () => void; +}) => { + return ( +
{ + e.preventDefault(); + await handleSubmit(); + }} + className="mb-6" + > +
+
+ setInputValue(e.target.value)} + className="pr-10 text-base" + /> + +
+
+ {submitted ? ( + + ) : ( + + )} +
+
+
+ ); +}; diff --git a/apps/web/components/skeleton-card.tsx b/apps/web/components/skeleton-card.tsx new file mode 100644 index 0000000..bb6531d --- /dev/null +++ b/apps/web/components/skeleton-card.tsx @@ -0,0 +1,23 @@ +import { Skeleton } from "@/components/ui/skeleton"; + +export function SkeletonCard() { + return ( +
+
+ +
+ +
+ +
+
+ + +
+
+ + +
+
+ ); +} diff --git a/apps/web/components/source-link.tsx b/apps/web/components/source-link.tsx new file mode 100644 index 0000000..af7cb54 --- /dev/null +++ b/apps/web/components/source-link.tsx @@ -0,0 +1,16 @@ +import { SOURCE_URL } from "@/lib/site"; + +// Where upstream had its "Deploy with Vercel" button (components/deploy-button.tsx): +// this product's own source repository. +export const SourceLink = () => ( + + {/* eslint-disable-next-line @next/next/no-img-element */} + + Source + +); diff --git a/apps/web/components/suggested-queries.tsx b/apps/web/components/suggested-queries.tsx new file mode 100644 index 0000000..5ad4f9d --- /dev/null +++ b/apps/web/components/suggested-queries.tsx @@ -0,0 +1,88 @@ +import { motion } from "framer-motion"; +import { Button } from "./ui/button"; + +export const SuggestedQueries = ({ + handleSuggestionClick, +}: { + handleSuggestionClick: (suggestion: string) => void; +}) => { + const suggestionQueries = [ + { + desktop: "Compare count of unicorns in SF and NY over time", + mobile: "SF vs NY", + }, + { + desktop: "Compare unicorn valuations in the US vs China over time", + mobile: "US vs China", + }, + { + desktop: "Countries with highest unicorn density", + mobile: "Top countries", + }, + { + desktop: + "Show the number of unicorns founded each year over the past two decades", + mobile: "Yearly count", + }, + { + desktop: "Display the cumulative total valuation of unicorns over time", + mobile: "Total value", + }, + { + desktop: + "Compare the yearly funding amounts for fintech vs healthtech unicorns", + mobile: "Fintech vs health", + }, + { + desktop: "Which cities have with most SaaS unicorns", + mobile: "SaaS cities", + }, + { + desktop: "Show the countries with highest unicorn density", + mobile: "Dense nations", + }, + { + desktop: + "Show the number of unicorns (grouped by year) over the past decade", + mobile: "Decade trend", + }, + { + desktop: + "Compare the average valuation of AI companies vs. biotech companies", + mobile: "AI vs biotech", + }, + { + desktop: "Investors with the most unicorns", + mobile: "Top investors", + }, + ]; + + return ( + +

+ Try these queries: +

+
+ {suggestionQueries.map((suggestion, index) => ( + + ))} +
+
+ ); +}; diff --git a/apps/web/components/ui/alert.tsx b/apps/web/components/ui/alert.tsx new file mode 100644 index 0000000..41fa7e0 --- /dev/null +++ b/apps/web/components/ui/alert.tsx @@ -0,0 +1,59 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const alertVariants = cva( + "relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground", + { + variants: { + variant: { + default: "bg-background text-foreground", + destructive: + "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +const Alert = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes & VariantProps +>(({ className, variant, ...props }, ref) => ( +
+)) +Alert.displayName = "Alert" + +const AlertTitle = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +AlertTitle.displayName = "AlertTitle" + +const AlertDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +AlertDescription.displayName = "AlertDescription" + +export { Alert, AlertTitle, AlertDescription } diff --git a/apps/web/components/ui/button.tsx b/apps/web/components/ui/button.tsx new file mode 100644 index 0000000..0ba4277 --- /dev/null +++ b/apps/web/components/ui/button.tsx @@ -0,0 +1,56 @@ +import * as React from "react" +import { Slot } from "@radix-ui/react-slot" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const buttonVariants = cva( + "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/90", + destructive: + "bg-destructive text-destructive-foreground hover:bg-destructive/90", + outline: + "border border-input bg-background hover:bg-accent hover:text-accent-foreground", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-10 px-4 py-2", + sm: "h-9 rounded-md px-3", + lg: "h-11 rounded-md px-8", + icon: "h-10 w-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button" + return ( + + ) + } +) +Button.displayName = "Button" + +export { Button, buttonVariants } diff --git a/apps/web/components/ui/card.tsx b/apps/web/components/ui/card.tsx new file mode 100644 index 0000000..afa13ec --- /dev/null +++ b/apps/web/components/ui/card.tsx @@ -0,0 +1,79 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Card = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +Card.displayName = "Card" + +const CardHeader = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardHeader.displayName = "CardHeader" + +const CardTitle = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

+)) +CardTitle.displayName = "CardTitle" + +const CardDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

+)) +CardDescription.displayName = "CardDescription" + +const CardContent = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

+)) +CardContent.displayName = "CardContent" + +const CardFooter = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardFooter.displayName = "CardFooter" + +export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } diff --git a/apps/web/components/ui/chart.tsx b/apps/web/components/ui/chart.tsx new file mode 100644 index 0000000..8620baa --- /dev/null +++ b/apps/web/components/ui/chart.tsx @@ -0,0 +1,365 @@ +"use client" + +import * as React from "react" +import * as RechartsPrimitive from "recharts" + +import { cn } from "@/lib/utils" + +// Format: { THEME_NAME: CSS_SELECTOR } +const THEMES = { light: "", dark: ".dark" } as const + +export type ChartConfig = { + [k in string]: { + label?: React.ReactNode + icon?: React.ComponentType + } & ( + | { color?: string; theme?: never } + | { color?: never; theme: Record } + ) +} + +type ChartContextProps = { + config: ChartConfig +} + +const ChartContext = React.createContext(null) + +function useChart() { + const context = React.useContext(ChartContext) + + if (!context) { + throw new Error("useChart must be used within a ") + } + + return context +} + +const ChartContainer = React.forwardRef< + HTMLDivElement, + React.ComponentProps<"div"> & { + config: ChartConfig + children: React.ComponentProps< + typeof RechartsPrimitive.ResponsiveContainer + >["children"] + } +>(({ id, className, children, config, ...props }, ref) => { + const uniqueId = React.useId() + const chartId = `chart-${id || uniqueId.replace(/:/g, "")}` + + return ( + +
+ + + {children} + +
+
+ ) +}) +ChartContainer.displayName = "Chart" + +const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => { + const colorConfig = Object.entries(config).filter( + ([_, config]) => config.theme || config.color + ) + + if (!colorConfig.length) { + return null + } + + return ( +