diff --git a/apps/docs/components/Extensions.tsx b/apps/docs/components/Extensions.tsx index a3ab9bff99e..b7b7260cd64 100644 --- a/apps/docs/components/Extensions.tsx +++ b/apps/docs/components/Extensions.tsx @@ -94,8 +94,15 @@ export default function Extensions() { filters.length === 0 ? x : x.tags.some((item) => filters.includes(item)) ) .map((extension) => ( - - + +

{extension.comment.charAt(0).toUpperCase() + extension.comment.slice(1)} diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts index 7385afd2d3d..2dcd089bbc1 100644 --- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts +++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts @@ -553,8 +553,10 @@ export const functions = { url: '/guides/functions/examples/connect-to-postgres', items: [], }, + { name: 'Discord Bot', url: '/guides/functions/examples/discord-bot', items: [] }, { name: 'GitHub Actions', url: '/guides/functions/examples/github-actions', items: [] }, { name: 'OG Image', url: '/guides/functions/examples/og-image', items: [] }, + { name: 'OpenAI', url: '/guides/functions/examples/openai', items: [] }, { name: 'Storage Caching', url: '/guides/functions/examples/storage-caching', items: [] }, { name: 'Stripe Webhooks', url: '/guides/functions/examples/stripe-webhooks', items: [] }, { name: 'Telegram Bot', url: '/guides/functions/examples/telegram-bot', items: [] }, @@ -635,7 +637,7 @@ export const platform = { url: undefined, items: [ { name: 'Access Control', url: '/guides/platform/access-control', items: [] }, - { name: 'Database Usage', url: '/guides/platform/database-usage', items: [] }, + { name: 'Database Size', url: '/guides/platform/database-size', items: [] }, { name: 'HTTP Status Codes', url: '/guides/platform/http-status-codes', items: [] }, { name: 'Logging', url: '/guides/platform/logs', items: [] }, { name: 'Metrics', url: '/guides/platform/metrics', items: [] }, @@ -821,6 +823,7 @@ export const integrations = { url: undefined, items: [ { name: 'Estuary', url: '/guides/integrations/estuary', items: [] }, + { name: 'OpenAI', url: '/guides/functions/examples/openai', items: [] }, { name: 'pgMustard', url: '/guides/integrations/pgmustard', items: [] }, { name: 'Prisma', url: '/guides/integrations/prisma', items: [] }, { name: 'Sequin', url: '/guides/integrations/sequin', items: [] }, diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideList.tsx b/apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideList.tsx index 7e52d424832..c55ec3b6f0d 100644 --- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideList.tsx +++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenuGuideList.tsx @@ -38,7 +38,7 @@ const NavigationMenuGuideList: React.FC = ({ id, active }) => { // disabled // level !== 'home' && level !== id ? '-ml-8' : '', - !active ? 'opacity-0 invisible absolute' : '', + !active ? 'opacity-0 invisible absolute h-0 overflow-hidden' : '', ].join(' ')} > diff --git a/apps/docs/layouts/DefaultLayout.tsx b/apps/docs/layouts/DefaultLayout.tsx index 3e610896b8b..0a6b48c5547 100644 --- a/apps/docs/layouts/DefaultLayout.tsx +++ b/apps/docs/layouts/DefaultLayout.tsx @@ -21,7 +21,7 @@ const Layout: FC = (props: Props) => { {props.meta?.title} | Supabase Docs - + diff --git a/apps/docs/layouts/tutorials/TutorialLayout.tsx b/apps/docs/layouts/tutorials/TutorialLayout.tsx index fc1a2fa8ea9..2f58a612cca 100644 --- a/apps/docs/layouts/tutorials/TutorialLayout.tsx +++ b/apps/docs/layouts/tutorials/TutorialLayout.tsx @@ -50,7 +50,7 @@ const Layout: FC = (props: Props) => { {props.meta?.title} | Supabase - + diff --git a/apps/docs/pages/_document.tsx b/apps/docs/pages/_document.tsx index 98acbb79912..ed9a8a70c10 100644 --- a/apps/docs/pages/_document.tsx +++ b/apps/docs/pages/_document.tsx @@ -3,7 +3,9 @@ import { Html, Head, Main, NextScript } from 'next/document' export default function Document() { return ( - + + +

diff --git a/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx b/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx index 7598037b2d8..8d73f79e224 100644 --- a/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx +++ b/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx @@ -137,7 +137,8 @@ In order to get the most out of TypeScript and it´s intellisense, you should im // and what to do when importing types declare namespace App { interface Supabase { - Database: import('./DatabaseDefinitions').Database + // Use the path to where you generated the types using the Supbase CLI. + Database: import('../types/supabase').Database; SchemaName: 'public' } diff --git a/apps/docs/pages/guides/auth/server-side-rendering.mdx b/apps/docs/pages/guides/auth/server-side-rendering.mdx index 635407cd986..346984a63fb 100644 --- a/apps/docs/pages/guides/auth/server-side-rendering.mdx +++ b/apps/docs/pages/guides/auth/server-side-rendering.mdx @@ -160,6 +160,12 @@ use this potentially stale information to render a page. ## Frequently Asked Questions +### No session on the server side with Next.js route prefetching? + +When you use route prefetching in Next.js using `` components or the `Router.push()` APIs can send server-side requests before the browser processes the access and refresh tokens. This means that those requests may not have any cookies set and your server code will render unauthenticated content. + +To improve experience for your users, we recommend redirecting users to one specific page after sign-in that does not include any route prefetching from Next.js. Once the Supabase client library running in the browser has obtained the access and refresh tokens from the URL fragment, you can send users to any pages that use prefetching. + ### How do I make the cookies `HttpOnly`? This is not necessary. Both the access token and refresh token are designed to diff --git a/apps/docs/pages/guides/functions.mdx b/apps/docs/pages/guides/functions.mdx index a382f7ccde1..b19ddb81872 100644 --- a/apps/docs/pages/guides/functions.mdx +++ b/apps/docs/pages/guides/functions.mdx @@ -43,12 +43,12 @@ export const examples = [ { name: 'With supabase-js', description: 'Use the Supabase client inside your Edge Function.', - href: 'https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts', + href: '/guides/functions/auth', }, { name: 'With CORS headers', description: 'Send CORS headers for invoking from the browser.', - href: 'https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/browser-with-cors/index.ts', + href: '/guides/functions/cors', }, { name: 'React Native with Stripe', @@ -86,6 +86,71 @@ export const examples = [ description: `Get user location data from user's IP address.`, href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/location', }, + { + name: 'Cloudflare Turnstile', + description: `Protecting Forms with Cloudflare Turnstile.`, + href: '/guides/functions/examples/cloudflare-turnstile', + }, + { + name: 'Connect to Postgres', + description: `Connecting to Postgres from Edge Functions.`, + href: '/guides/functions/examples/connect-to-postgres', + }, + { + name: 'Github Actions', + description: `Deploying Edge Functions with GitHub Actions.`, + href: '/guides/functions/examples/github-actions', + }, + { + name: 'Oak Server Middleware', + description: `Request Routing with Oak server middleware.`, + href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/oak-server', + }, + { + name: 'OpenAI', + description: `Using OpenAI in Edge Functions.`, + href: '/guides/functions/examples/openai', + }, + { + name: 'Stripe Webhooks', + description: `Handling signed Stripe Webhooks with Edge Functions.`, + href: '/guides/functions/examples/stripe-webhooks', + }, + { + name: 'Send emails', + description: `Send emails in Edge Functions.`, + href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/send-email-smtp', + }, + { + name: 'Web Stream', + description: `Server-Sent Events in Edge Functions.`, + href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/streams', + }, + { + name: 'Puppeteer', + description: `Generate screenshots with Puppeteer.`, + href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/puppeteer', + }, + { + name: 'Discord Bot', + description: `Building a Slash Command Discord Bot with Edge Functions.`, + href: '/guides/functions/examples/discord-bot', + }, + { + name: 'Telegram Bot', + description: `Building a Telegram Bot with Edge Functions.`, + href: '/guides/functions/examples/telegram-bot', + }, + { + name: 'Upload File', + description: `Process multipart/form-data.`, + href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/file-upload-storage', + }, + { + name: 'Upstash Redis', + description: `Build an Edge Functions Counter with Upstash Redis.`, + href: '/guides/functions/examples/upstash-redis', + }, ] export const Page = ({ children }) => diff --git a/apps/docs/pages/guides/functions/auth.mdx b/apps/docs/pages/guides/functions/auth.mdx index 871c16bd6f2..29ad1505034 100644 --- a/apps/docs/pages/guides/functions/auth.mdx +++ b/apps/docs/pages/guides/functions/auth.mdx @@ -20,7 +20,7 @@ By creating a supabase client with the auth context from the function, you can d 2. Run queries in the context of the user with [Row Level Security (RLS)](/docs/guides/auth/row-level-security) policies enforced. ```js lines=14,17-19,22-23 title=supabase/functions/select-from-table-with-auth-rls/index.ts -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' +import { serve } from 'https://deno.land/std@0.177.0/http/server.ts' import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' serve(async (req: Request) => { diff --git a/apps/docs/pages/guides/functions/cors.mdx b/apps/docs/pages/guides/functions/cors.mdx index 766da74ae86..7274d810b02 100644 --- a/apps/docs/pages/guides/functions/cors.mdx +++ b/apps/docs/pages/guides/functions/cors.mdx @@ -24,7 +24,7 @@ export const corsHeaders = { You can then import and use the CORS headers within your functions: ```ts index.ts -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' +import { serve } from 'https://deno.land/std@0.177.0/http/server.ts' import { corsHeaders } from '../_shared/cors.ts' console.log(`Function "browser-with-cors" up and running!`) diff --git a/apps/docs/pages/guides/functions/examples/cloudflare-turnstile.mdx b/apps/docs/pages/guides/functions/examples/cloudflare-turnstile.mdx index ef38552855f..830e91723c8 100644 --- a/apps/docs/pages/guides/functions/examples/cloudflare-turnstile.mdx +++ b/apps/docs/pages/guides/functions/examples/cloudflare-turnstile.mdx @@ -34,7 +34,7 @@ supabase functions new cloudflare-turnstile And add the code to the `index.ts` file: ```ts index.ts -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' +import { serve } from 'https://deno.land/std@0.177.0/http/server.ts' import { corsHeaders } from '../_shared/cors.ts' console.log('Hello from Cloudflare Trunstile!') diff --git a/apps/docs/pages/guides/functions/examples/connect-to-postgres.mdx b/apps/docs/pages/guides/functions/examples/connect-to-postgres.mdx index 3b66a4affd9..d99931b58e8 100644 --- a/apps/docs/pages/guides/functions/examples/connect-to-postgres.mdx +++ b/apps/docs/pages/guides/functions/examples/connect-to-postgres.mdx @@ -4,6 +4,7 @@ export const meta = { id: 'examples-postgres-on-the-edge', title: 'Connect to Postgres', description: 'Connecting to Postgres from Edge Functions.', + video: 'https://www.youtube.com/v/cl7EuF1-RsY', }
@@ -19,7 +20,7 @@ Supabase Edge Functions allow you to go beyond HTTP and can connect to your Post ```ts index.ts import * as postgres from 'https://deno.land/x/postgres@v0.14.2/mod.ts' -import { serve } from 'https://deno.land/std@0.168.0/http/server.ts' +import { serve } from 'https://deno.land/std@0.177.0/http/server.ts' // Get the connection string from the environment variable "DATABASE_URL" const databaseUrl = Deno.env.get('DATABASE_URL')! diff --git a/apps/docs/pages/guides/functions/examples/discord-bot.mdx b/apps/docs/pages/guides/functions/examples/discord-bot.mdx new file mode 100644 index 00000000000..281a2ac0e3e --- /dev/null +++ b/apps/docs/pages/guides/functions/examples/discord-bot.mdx @@ -0,0 +1,178 @@ +import Layout from '~/layouts/DefaultGuideLayout' + +export const meta = { + id: 'examples-discord-bot', + title: 'Discord Bot', + description: 'Building a Slash Command Discord Bot with Edge Functions.', + video: 'https://www.youtube.com/v/J24Bvo_m7DM', +} + +
+ +
+ +## Create an application on Discord Developer Portal + +1. Go to [https://discord.com/developers/applications](https://discord.com/developers/applications) (login using your discord account if required). +2. Click on **New Application** button available at left side of your profile picture. +3. Name your application and click on **Create**. +4. Go to **Bot** section, click on **Add Bot**, and finally on **Yes, do it!** to confirm. + +That's it. A new application is created which will hold our Slash Command. Don't close the tab as we need information from this application page throughout our development. + +Before we can write some code, we need to curl a discord endpoint to register a Slash Command in our app. + +Fill `DISCORD_BOT_TOKEN` with the token available in the **Bot** section and `CLIENT_ID` with the ID available on the **General Information** section of the page and run the command on your terminal. + +```bash +BOT_TOKEN='replace_me_with_bot_token' +CLIENT_ID='replace_me_with_client_id' +curl -X POST \ +-H 'Content-Type: application/json' \ +-H "Authorization: Bot $BOT_TOKEN" \ +-d '{"name":"hello","description":"Greet a person","options":[{"name":"name","description":"The name of the person","type":3,"required":true}]}' \ +"https://discord.com/api/v8/applications/$CLIENT_ID/commands" +``` + +This will register a Slash Command named `hello` that accepts a parameter named `name` of type string. + +## Code + +```ts index.ts +// Sift is a small routing library that abstracts away details like starting a +// listener on a port, and provides a simple function (serve) that has an API +// to invoke a function for a specific path. +import { json, serve, validateRequest } from 'sift' +// TweetNaCl is a cryptography library that we use to verify requests +// from Discord. +import nacl from 'nacl' + +enum DiscordCommandType { + Ping = 1, + ApplicationCommand = 2, +} + +// For all requests to "/" endpoint, we want to invoke home() handler. +serve({ + '/discord-bot': home, +}) + +// The main logic of the Discord Slash Command is defined in this function. +async function home(request: Request) { + // validateRequest() ensures that a request is of POST method and + // has the following headers. + const { error } = await validateRequest(request, { + POST: { + headers: ['X-Signature-Ed25519', 'X-Signature-Timestamp'], + }, + }) + if (error) { + return json({ error: error.message }, { status: error.status }) + } + + // verifySignature() verifies if the request is coming from Discord. + // When the request's signature is not valid, we return a 401 and this is + // important as Discord sends invalid requests to test our verification. + const { valid, body } = await verifySignature(request) + if (!valid) { + return json( + { error: 'Invalid request' }, + { + status: 401, + } + ) + } + + const { type = 0, data = { options: [] } } = JSON.parse(body) + // Discord performs Ping interactions to test our application. + // Type 1 in a request implies a Ping interaction. + if (type === DiscordCommandType.Ping) { + return json({ + type: 1, // Type 1 in a response is a Pong interaction response type. + }) + } + + // Type 2 in a request is an ApplicationCommand interaction. + // It implies that a user has issued a command. + if (type === DiscordCommandType.ApplicationCommand) { + const { value } = data.options.find( + (option: { name: string; value: string }) => option.name === 'name' + ) + return json({ + // Type 4 responds with the below message retaining the user's + // input at the top. + type: 4, + data: { + content: `Hello, ${value}!`, + }, + }) + } + + // We will return a bad request error as a valid Discord request + // shouldn't reach here. + return json({ error: 'bad request' }, { status: 400 }) +} + +/** Verify whether the request is coming from Discord. */ +async function verifySignature(request: Request): Promise<{ valid: boolean; body: string }> { + const PUBLIC_KEY = Deno.env.get('DISCORD_PUBLIC_KEY')! + // Discord sends these headers with every request. + const signature = request.headers.get('X-Signature-Ed25519')! + const timestamp = request.headers.get('X-Signature-Timestamp')! + const body = await request.text() + const valid = nacl.sign.detached.verify( + new TextEncoder().encode(timestamp + body), + hexToUint8Array(signature), + hexToUint8Array(PUBLIC_KEY) + ) + + return { valid, body } +} + +/** Converts a hexadecimal string to Uint8Array. */ +function hexToUint8Array(hex: string) { + return new Uint8Array(hex.match(/.{1,2}/g)!.map((val) => parseInt(val, 16))) +} +``` + +## Deploy the Slash Command Handler + +```bash +supabase functions deploy discord-bot --no-verify-jwt +supabase secrets set DISCORD_PUBLIC_KEY=your_public_key +``` + +Navigate to your Function details in the Supabase Dashboard to get your Endpoint URL. + +### Configure Discord application to use our URL as interactions endpoint URL + +1. Go back to your application (Greeter) page on Discord Developer Portal +2. Fill **INTERACTIONS ENDPOINT URL** field with the URL and click on **Save Changes**. + +The application is now ready. Let's proceed to the next section to install it. + +## Install the Slash Command on your Discord server + +So to use the `hello` Slash Command, we need to install our Greeter application on our Discord server. Here are the steps: + +1. Go to **OAuth2** section of the Discord application page on Discord Developer Portal +2. Select `applications.commands` scope and click on the **Copy** button below. +3. Now paste and visit the URL on your browser. Select your server and click on **Authorize**. + +Open Discord, type `/Promise` and press **Enter**. + +## Run locally + +```bash +supabase functions serve discord-bot --no-verify-jwt --env-file ./supabase/.env.local +ngrok http 54321 +``` + +export const Page = ({ children }) => + +export default Page diff --git a/apps/docs/pages/guides/functions/examples/og-image.mdx b/apps/docs/pages/guides/functions/examples/og-image.mdx index efa8eb99e59..be4f4dc46d2 100644 --- a/apps/docs/pages/guides/functions/examples/og-image.mdx +++ b/apps/docs/pages/guides/functions/examples/og-image.mdx @@ -50,7 +50,7 @@ export default function handler(req: Request) { Create an `index.ts` file to execute the handler on incoming requests: ```ts index.ts -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' +import { serve } from 'https://deno.land/std@0.177.0/http/server.ts' import handler from './handler.tsx' console.log('Hello from og-image Function!') diff --git a/apps/docs/pages/guides/functions/examples/openai.mdx b/apps/docs/pages/guides/functions/examples/openai.mdx new file mode 100644 index 00000000000..bc24d6a151a --- /dev/null +++ b/apps/docs/pages/guides/functions/examples/openai.mdx @@ -0,0 +1,84 @@ +import Layout from '~/layouts/DefaultGuideLayout' + +export const meta = { + id: 'examples-openai', + title: 'OpenAI', + description: 'Using OpenAI in Edge Functions.', + video: 'https://www.youtube.com/v/29p8kIqyU_Y', +} + +
+ +
+ +Use the [OpenAI completions API](https://platform.openai.com/docs/api-reference/completions) in Supabase Edge Functions. + +```ts index.ts +import 'xhr_polyfill' +import { serve } from 'std/server' +import { CreateCompletionRequest } from 'openai' + +serve(async (req) => { + const { query } = await req.json() + + const completionConfig: CreateCompletionRequest = { + model: 'text-davinci-003', + prompt: query, + max_tokens: 256, + temperature: 0, + stream: true, + } + + return fetch('https://api.openai.com/v1/completions', { + method: 'POST', + headers: { + Authorization: `Bearer ${Deno.env.get('OPENAI_API_KEY')}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(completionConfig), + }) +}) +``` + +## Run locally + +```bash +supabase functions serve --env-file ./supabase/.env.local --no-verify-jwt +``` + +Use cURL or Postman to make a POST request to http://localhost:54321/functions/v1/openai. + +```bash +curl -i --location --request POST http://localhost:54321/functions/v1/openai \ + --header 'Content-Type: application/json' \ + --data '{"query":"What is Supabase?"}' +``` + +## Deploy + +```bash +supabase functions deploy --no-verify-jwt openai +supabase secrets set --env-file ./supabase/.env.local +``` + +## Go deeper + +If you're interesting in learning how to use this to build your own ChatGPT, read [the blog post](/blog/chatgpt-supabase-docs) and check out the video: + +
+ +
+ +export const Page = ({ children }) => + +export default Page diff --git a/apps/docs/pages/guides/functions/examples/upstash-redis.mdx b/apps/docs/pages/guides/functions/examples/upstash-redis.mdx index bbe58dd4dd1..77411c5b1d8 100644 --- a/apps/docs/pages/guides/functions/examples/upstash-redis.mdx +++ b/apps/docs/pages/guides/functions/examples/upstash-redis.mdx @@ -73,7 +73,7 @@ serve(async (_req) => { ```bash supabase start -supabase functions serve upstash-redis-counter --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env +supabase functions serve --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env ``` Navigate to http://localhost:54321/functions/v1/upstash-redis-counter. diff --git a/apps/docs/pages/guides/functions/local-development.mdx b/apps/docs/pages/guides/functions/local-development.mdx index e342abe9b14..254cad70044 100644 --- a/apps/docs/pages/guides/functions/local-development.mdx +++ b/apps/docs/pages/guides/functions/local-development.mdx @@ -10,7 +10,7 @@ You can run your Edge Function locally using [`supabase functions serve`](/docs/ ```bash supabase start # start the supabase stack -supabase functions serve hello-world # start the Function watcher +supabase functions serve # start the Functions watcher ``` The `functions serve` command has hot-reloading capabilities. It will watch for any changes to your files and restart the Deno server. @@ -20,7 +20,7 @@ The `functions serve` command has hot-reloading capabilities. It will watch for While serving your local Edge Function, you can invoke it using curl: ```bash -curl --request POST 'http://localhost:54321/functions/v1/hello-world' \ +curl --request POST 'http://localhost:54321/functions/v1/function-name' \ --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs' \ --header 'Content-Type: application/json' \ --data '{ "name":"Functions" }' @@ -37,7 +37,7 @@ const supabase = createClient( 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0' ) -const { data, error } = await supabase.functions.invoke('hello-world', { +const { data, error } = await supabase.functions.invoke('function-name', { body: { name: 'Functions' }, }) ``` diff --git a/apps/docs/pages/guides/functions/secrets.mdx b/apps/docs/pages/guides/functions/secrets.mdx index 3d60a239a8b..3487fc94d79 100644 --- a/apps/docs/pages/guides/functions/secrets.mdx +++ b/apps/docs/pages/guides/functions/secrets.mdx @@ -46,7 +46,7 @@ console.log(Deno.env.get('MY_NAME')) Now we can invoke our function locally, by serving it with our new `.env.local` file: ```bash -supabase functions serve hello-world --env-file ./supabase/.env.local +supabase functions serve --env-file ./supabase/.env.local ``` When the function starts you should see the name “Yoda” output to the terminal. diff --git a/apps/docs/pages/guides/getting-started/quickstarts/flutter.mdx b/apps/docs/pages/guides/getting-started/quickstarts/flutter.mdx index 339eb20dd2f..476c5813490 100644 --- a/apps/docs/pages/guides/getting-started/quickstarts/flutter.mdx +++ b/apps/docs/pages/guides/getting-started/quickstarts/flutter.mdx @@ -176,6 +176,7 @@ export const meta = { Run your app on a platform of your choosing! By default an app should launch in your web browser. Note that `supabase_flutter` is compatible with web, iOS, Android, macOS, and Windows apps. + Running the app on MacOS requires additional configuration to [set the entitlements](https://docs.flutter.dev/development/platform-integration/macos/building#setting-up-entitlements). diff --git a/apps/docs/pages/guides/getting-started/quickstarts/nuxtjs.mdx b/apps/docs/pages/guides/getting-started/quickstarts/nuxtjs.mdx index 366120f35e9..f9259185926 100644 --- a/apps/docs/pages/guides/getting-started/quickstarts/nuxtjs.mdx +++ b/apps/docs/pages/guides/getting-started/quickstarts/nuxtjs.mdx @@ -126,7 +126,7 @@ The fastest way to get started with supabase and Nuxt.js is to use the supabase- - Next, in your Next.js app, create a file called supabase-client.js and add the following code to initialize the Supabase client and set your project's credentials: + Next, in your Nuxt.js app, create a file called supabase-client.js and add the following code to initialize the Supabase client and set your project's credentials: diff --git a/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx b/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx index 3be4542731a..1daf9a881ec 100644 --- a/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx +++ b/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx @@ -50,9 +50,9 @@ These variables will be exposed on the browser, and that's completely fine since ```js title=src/lib/supabaseClient.ts import { createClient } from '@supabase/auth-helpers-sveltekit' -import { env } from '$env/dynamic/public' +import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public' -export const supabase = createClient(env.PUBLIC_SUPABASE_URL, env.PUBLIC_SUPABASE_ANON_KEY) +export const supabase = createClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY) ``` Optionally, update `src/routes/styles.css` with the [CSS from the example](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/svelte-user-management/src/app.css). diff --git a/apps/docs/pages/guides/getting-started/tutorials/with-vue-3.mdx b/apps/docs/pages/guides/getting-started/tutorials/with-vue-3.mdx index 5480df2d4aa..0cbdd921ca2 100644 --- a/apps/docs/pages/guides/getting-started/tutorials/with-vue-3.mdx +++ b/apps/docs/pages/guides/getting-started/tutorials/with-vue-3.mdx @@ -99,7 +99,7 @@ const handleLogin = async () => {

Supabase + Vue 3

Sign in via magic link with your email below

- +
{ const [user, setUser] = useState(null) - const [oneSignalInitialized, setOneSignalInitialized] = - useState(false) + const [oneSignalInitialized, setOneSignalInitialized] = useState(false) /** * Initializes OneSignal SDK for a given Supabase User ID @@ -123,9 +121,7 @@ const Home: NextPage = () => { const { price } = Object.fromEntries(new FormData(event.currentTarget)) if (typeof price !== 'string') return - const { error } = await supabase - .from('orders') - .insert({ price: Number(price) }) + const { error } = await supabase.from('orders').insert({ price: Number(price) }) if (error) { alert(error.message) } @@ -142,15 +138,13 @@ const Home: NextPage = () => { initialize() - const authListener = supabase.auth.onAuthStateChange( - async (event, session) => { - const user = session?.user ?? null - setUser(user) - if (user) { - initializeOneSignal(user.id) - } + const authListener = supabase.auth.onAuthStateChange(async (event, session) => { + const user = session?.user ?? null + setUser(user) + if (user) { + initializeOneSignal(user.id) } - ) + }) return () => { authListener.data.subscription.unsubscribe() @@ -175,10 +169,7 @@ const Home: NextPage = () => { - @@ -190,10 +181,7 @@ const Home: NextPage = () => { name="email" placeholder="Email" /> - @@ -211,7 +199,7 @@ There is quite a bit of stuff going on here, but basically, it’s creating a si Notice that inside the `initializeOneSignal()` function, we are setting the Supabase user ID as an [external user ID of OneSignal](https://documentation.onesignal.com/docs/external-user-ids). This allows us to later send push notifications to the user using their Supabase user ID from the backend, which is very handy. ```tsx -await OneSignal.setExternalUserId(uid); +await OneSignal.setExternalUserId(uid) ``` The front-end side of things is done here. Let’s get into the backend. @@ -237,7 +225,7 @@ supabase functions new notify Replace the contents of `supabase/functions/notify/index.ts` with the following ```tsx -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' +import { serve } from 'https://deno.land/std@0.177.0/http/server.ts' import * as OneSignal from 'https://esm.sh/@onesignal/node-onesignal@1.0.0-beta7' const _OnesignalAppId_ = Deno.env.get('ONESIGNAL_APP_ID')! @@ -263,12 +251,9 @@ serve(async (req) => { } const onesignalApiRes = await onesignal.createNotification(notification) - return new Response( - JSON.stringify({ onesignalResponse: onesignalApiRes }), - { - headers: { 'Content-Type': 'application/json' }, - } - ) + return new Response(JSON.stringify({ onesignalResponse: onesignalApiRes }), { + headers: { 'Content-Type': 'application/json' }, + }) } catch (err) { console.error('Failed to create OneSignal notification', err) return new Response('Server error.', { @@ -295,7 +280,6 @@ ONESIGNAL_REST_API_KEY=YOUR_ONESIGNAL_REST_API_KEY ![Where to find OneSignal User Auth Key](/docs/img/guides/integrations/onesignal/onesignal-api-key.png) - Once your environment variables are filled in, you can run the following command to set the environment variable. ```bash @@ -313,35 +297,35 @@ supabase functions deploy notify --no-verify-jwt Finally, we get to set up the database! Run the following SQL to set up the `orders` table. ```sql -create table if not exists public.orders ( - id uuid not null primary key default uuid_generate_v4(), - created_at timestamptz not null default now(), - user_id uuid not null default auth.uid(), +create table + if not exists public.orders ( + id uuid not null primary key default uuid_generate_v4 (), + created_at timestamptz not null default now (), + user_id uuid not null default auth.uid (), price int8 not null -); + ); ``` As you can see, the `orders` table has 4 columns and 3 of them have default values. That means all we need to send from the front-end app is the price. That is why our insert statement looked very simple. ```tsx const { error } = await supabase.from('orders').insert({ - price: 100, - }) + price: 100, +}) ``` Let’s also set up the webhook so that whenever a new row is inserted in the `orders` table, it calls the edge function. Go to `Database > Webhooks` and create a new Database Webhook. The table should be set to `orders` and Events should be inserted. The type should be HTTP Request, the HTTP method should be POST, and the URL should be the URL of your edge function. Hit confirm to save the webhook configuration. ![Supabase Webhooks configuration](/docs/img/guides/integrations/onesignal/webhook.png) -At this point, the app should be complete! Run your app locally with `npm run dev`, or deploy your app to a hosting service and see how you receive a push notification when you place an order! +At this point, the app should be complete! Run your app locally with `npm run dev`, or deploy your app to a hosting service and see how you receive a push notification when you place an order! Remember that if you decide to deploy your app to a hosting service, you would need to create another OneSignal app configured for your local address. ![Ordering app UI](/docs/img/guides/integrations/onesignal/app-ui.png) - ## Resources -This particular example was using Next.js, but you can apply the same principles to implement send push notification, SMS, Emails, and in-app-notifications on other platforms as well. +This particular example was using Next.js, but you can apply the same principles to implement send push notification, SMS, Emails, and in-app-notifications on other platforms as well. - [OneSignal + Flutter + Supabase example](https://github.com/OneSignalDevelopers/onesignal-supabase-sample-integration-supabase) - [OneSignal Mobile Quickstart](https://documentation.onesignal.com/docs/mobile-sdk-setup) diff --git a/apps/docs/pages/guides/integrations/prisma.mdx b/apps/docs/pages/guides/integrations/prisma.mdx index c2f0d5a8f14..2951c44b9d6 100644 --- a/apps/docs/pages/guides/integrations/prisma.mdx +++ b/apps/docs/pages/guides/integrations/prisma.mdx @@ -29,22 +29,17 @@ In case you don’t have a Prisma project or this is your first time working wit ### Cloning the starter project -Navigate into a directory of your choice and run the following command in your terminal if you’re on a Windows machine: +Navigate into a directory of your choice and run the following command in your terminal: ```bash -curl https://pris.ly/quickstart -L -o quickstart-main.tar.gz && tar -zxvf quickstart-main.tar.gz quickstart-main/typescript/starter && move quickstart-main\typescript\starter starter && rmdir /S /Q quickstart-main && del /Q quickstart-main.tar.gz -``` - -And if you’re using Mac OS or Linux, run the following command: - -```bash -curl -L https://pris.ly/quickstart | tar -xz --strip=2 quickstart-main/typescript/starter +curl https://codeload.github.com/prisma/prisma-examples/tar.gz/latest | tar -xz --strip=2 prisma-examples-latest/databases/postgresql-supabase ``` You can now navigate into the directory and install the project’s dependencies: ```bash -cd starter && npm install +cd postgresql-supabase +npm install ``` ### A look at the project’s structure @@ -52,16 +47,17 @@ cd starter && npm install This project comes with TypeScript configured and has the following structure. - A `prisma` directory which contains: - - A `dev.db` file: This is a SQLite database. - - A `schema.prisma` file: Where we define the different database models and relations between them. -- A `.env` file: Contains the `DATABASE_URL` variable, which Prisma will use. -- A `script.ts` file: where we will run some queries using Prisma Client. - This starter also comes with the following packages installed: + - A `seed.ts` file: This is the data used to seed your database. + - A `schema.prisma` file: Where you define the different database models and relations between them. +- A `script.ts` file: where you will run some queries using Prisma Client. + +This starter also comes with the following packages installed: - [`@prisma/client`](https://www.npmjs.com/package/@prisma/client): An auto-generated and type-safe query builder that’s _tailored_ to your data. - [`prisma`](https://www.npmjs.com/package/prisma): Prisma’s command-line interface (CLI). It allows you to initialize new project assets, generate Prisma Client, and analyze existing database structures through introspection to automatically create your application models. - > Note: Prisma works with both JavaScript and TypeScript. However, to get the best possible development experience, using TypeScript is highly recommended. -### Configuring the project to use PostgreSQL +> Note: Prisma works with both JavaScript and TypeScript. However, to get the best possible development experience, using TypeScript is highly recommended. + +### Configuring the project By default, Prisma migrations will try to drop the `postgres` database, which can lead to conflicts with Supabase databases. For this scenario, use [Prisma Shadow Databases](https://www.prisma.io/docs/concepts/components/prisma-migrate/shadow-database#cloud-hosted-shadow-databases-must-be-created-manually). @@ -78,7 +74,6 @@ postgres=> CREATE DATABASE postgres_shadow; postgres=> exit ``` -Go ahead and delete the `prisma/dev.db` file because we will be switching to PostgreSQL. In the `.env` file, update `DATABASE_URL` and `SHADOW_DATABASE_URL` to the connection string from **step 1**. The `.env` file should look like: ```env @@ -87,18 +82,19 @@ DATABASE_URL="postgres://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT-REF].supabase SHADOW_DATABASE_URL="postgres://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT-REF].supabase.co:5432/postgres_shadow" ``` -In the `schema.prisma` file, change the `provider` from "sqlite" to `"postgresql"` and add the `shadowDatabaseUrl` property. This is what your `schema.prisma` file should look like: ```go datasource db { - provider = "postgresql" - url = env("DATABASE_URL") + provider = "postgresql" + url = env("DATABASE_URL") shadowDatabaseUrl = env("SHADOW_DATABASE_URL") } + generator client { provider = "prisma-client-js" } + model Post { id Int @id @default(autoincrement()) title String @@ -107,6 +103,7 @@ model Post { author User? @relation(fields: [authorId], references: [id]) authorId Int? } + model User { id Int @id @default(autoincrement()) email String @unique @@ -115,53 +112,83 @@ model User { } ``` + To test that everything works correctly, run the following command to create a migration: ```bash -prisma migrate dev --name init +npx prisma migrate dev --name init ``` -You can optionally give your migration a name, depending on the changes you made. Since this is the project’s first migration, you’re setting the `--name` flag to “init”. -If everything works correctly, you should get the following message in your terminal: +You can optionally give your migration a name, depending on the changes you made. Since this is the project’s first migration, you’re setting the `--name` flag to “init”. If everything works correctly, you should get the following message in your terminal: ```text Your database is now in sync with your schema. -:heavy_check_mark: Generated Prisma Client (2.x.x) to ./node_modules/@prisma/client in 111ms +:heavy_check_mark: Generated Prisma Client (4.x.x) to ./node_modules/@prisma/client in 111ms ``` This will create a `prisma/migrations` folder inside your `prisma` directory and synchronize your Prisma schema with your database schema. -> Note: if you want to skip the process of creating a migration history, you can use the [`db push`](https://www.prisma.io/docs/concepts/components/prisma-migrate/db-push) command instead of `migrate dev`. -> If you go to your Supabase project, in the table editor, you should see that two tables have been created, a `Post` and a `User` table. -> ![tables created in the UI](/docs/img/guides/integrations/prisma/7y4qq4wwvfrheti6r09u.png) -> That’s it! You have now successfully connected a Prisma project to a PostgreSQL database hosted on Supabase and ran your first migration. +> **Note**: If you want to skip the process of creating a migration history, you can use the [`prisma db push`](https://www.prisma.io/docs/concepts/components/prisma-migrate/db-push) command instead of `prisma migrate dev`. However, we recommend using `prisma migrate dev` to evolve your database schema in development. +> If you would like to get a conceptual overview of how Prisma Migrate works and which commands to use in what environment, refer to [this page in the Prisma documentation](https://www.prisma.io/docs/concepts/components/prisma-migrate/mental-model). + +If you go to your Supabase project, in the table editor, you should see that two tables have been created, a `Post`, `User`, and `_prisma_migrations` tables. The `_prisma_migrations` table is used to keep + +![tables created in the UI](/docs/img/guides/integrations/prisma/7y4qq4wwvfrheti6r09u.png) + +That’s it! You have now successfully connected a Prisma project to a PostgreSQL database hosted on Supabase and ran your first migration. ## Connection pooling with Supabase -If you’re working in a serverless environment (for example Node.js functions hosted on AWS Lambda, Vercel or Netlify Functions), you need to set up [connection pooling](https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#serverless-environments-faas) using a tool like [PgBouncer](https://www.pgbouncer.org/). That’s because every function invocation may result in a [new connection to the database](https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#the-serverless-challenge). Supabase [supports connection management using PgBouncer](https://supabase.io/blog/2021/04/02/supabase-pgbouncer#what-is-connection-pooling) and are enabled by default. -Go to the **Database** page from the sidebar in the Supabase dashboard and navigate to **connection pool** settings +If you’re working in a serverless environment (for example Node.js functions hosted on AWS Lambda, Vercel or Netlify Functions), you need to set up [connection pooling](https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#serverless-environments-faas) using a tool like [PgBouncer](https://www.pgbouncer.org/). That’s because every function invocation may result in a [new connection to the database](https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#the-serverless-challenge). + +Supabase [supports connection management using PgBouncer](/docs/guides/database/connecting-to-postgres#connection-pool). + +Go to the **Database** page from the sidebar in the Supabase dashboard and navigate to **Connection pool** settings: + ![Connection pool settings](/docs/img/guides/integrations/prisma/w0oowg8vq435ob5c3gf0.png) -When migrating, you need to use the non-pooled connection URL (like the one used in **step 1**). However, when deploying your app, use the pooled connection URL and add the `?pgbouncer=true` flag to the PostgreSQL connection URL. It's also recommended to minimize the number of concurrent connections by setting the `connection_limit` to `1`. The `.env` file should look like: + +When updating your database schema, you need to use the non-pooled connection URL (like the one used in **step 1**). You can configure the non-pooled connection string by using the `directUrl` property in the datasource block. + +Update your `.env` file with the following changes: +1. Rename the `DATABASE_URL` environment variable to `DIRECT_URL` +1. Create a `DATABASE_URL` environment variable and paste in the new connection string from the dashboard as its value + +It is recommended to minimize the number of concurrent connections by setting the `connection_limit` to `1`. You can set connection limit by appending `?connection_limit=1` to your connection string + +Your `.env` file should resemble the following: ```env # .env -DATABASE_URL="postgres://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT-REF].supabase.co:6543/postgres?pgbouncer=true&connection_limit=1" +# PostgreSQL connection string used for migrations +DIRECT_URL="postgres://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT-REF].supabase.co:6543/postgres" +# PostgreSQL connection string with pgBouncer config — used by Prisma Client +DATABASE_URL="postgres://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT-REF].supabase.co:6543/postgres?connection_limit=1" + SHADOW_DATABASE_URL="postgres://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT-REF].supabase.co:5432/postgres_shadow" ``` -Prisma Migrate uses database transactions to check out the current state of the database and the migrations table. However, the Migration Engine is designed to use a single connection to the database, and does not support connection pooling with PgBouncer. If you attempt to run Prisma Migrate commands in any environment that uses PgBouncer for connection pooling, you might see the following error: +Update your Prisma schema by setting the `directUrl` in the datasource block: -```bash -Error: undefined: Database error -Error querying the database: db error: ERROR: prepared statement “s0” already exists +```go +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + directURL = env("DIRECT_URL") + shadowDatabaseUrl = env("SHADOW_DATABASE_URL") +} ``` -This is a known issue and it is being worked on, you can follow the progress on this [GitHub issue](https://github.com/prisma/prisma/issues/6485). -If you want to learn more about Prisma, check out the [docs](https://www.prisma.io/docs). Also in case you have any questions or run into any issue, feel free to start a discussion in the repo’s [discussions section](https://github.com/prisma/prisma/discussions). +> **Note**: This feature is available from Prisma version [4.10.0](https://github.com/prisma/prisma/releases/tag/4.10.0) and higher. + +If you want to learn more about Prisma, check out the [docs](https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#fields). Also in case you have any questions or run into any issue, feel free to start a discussion in the repo’s [discussions section](https://github.com/prisma/prisma/discussions). ## Troubleshooting -If you run `prisma migrate dev --name init` multiple times, it sometimes asks if you want to recreate the whole schema. If you chose yes, it will delete the public schema and recreate it. The default grants are missing after this. If you run into this problem, add a helper SQL for fixing the grants: +### 1. Missing grants + +If you run `prisma migrate dev --name init` multiple times, it sometimes asks if you want to recreate the whole schema. If you chose yes, it will delete the public schema and recreate it. The default grants are missing after this. + + If you run into this problem, create a draft migration using `prisma migrate dev --create-only`, and add the following helper SQL: ```sql grant usage on schema public to postgres, anon, authenticated, service_role; @@ -175,6 +202,93 @@ alter default privileges in schema public grant all on functions to postgres, an alter default privileges in schema public grant all on sequences to postgres, anon, authenticated, service_role; ``` +Run `prisma migrate dev` to apply the draft migration to the database. + +### 2. Using Prisma with multiple PostgreSQL schemas + +If you're using multiple database schemas, enable the `multiSchema` Preview feature flag in the `generator` block of your Prisma schema: + +```go +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + directURL = env("DIRECT_URL") + shadowDatabaseUrl = env("SHADOW_DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" + previewFeatures = ["multiSchema"] +} +``` + +Next, specify the database schemas you would like to include in your Prisma schema: + +```go +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + directURL = env("DIRECT_URL") + shadowDatabaseUrl = env("SHADOW_DATABASE_URL") + schemas = ["public", "auth"] +} + +generator client { + provider = "prisma-client-js" + previewFeatures = ["multiSchema"] +} +``` + +You can then specify what schema a model or enum belongs to using the `@@schema` attribute: + +```go +model User { + id Int @id + // ... + + @@schema("auth") // or @@schema("public") +} +``` + +To learn more about using Prisma with multiple database schemas, refer to [this page in the Prisma docs](https://www.prisma.io/docs/guides/database/multi-schema#learn-more-about-the-multischema-preview-feature). + +### 3. Enabling PosgreSQL extensions + +If you would like to use a PostgreSQL extension with Prisma, enable the `postgresqlExtensions` Preview feature flag in the `generator` block of your Prisma schema: + +```go +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + directURL = env("DIRECT_URL") + shadowDatabaseUrl = env("SHADOW_DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" + previewFeatures = ["postgresqlExtensions"] +} +``` + +Next, specify the extensions you need in the `datasource` block: + +```go +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + directURL = env("DIRECT_URL") + shadowDatabaseUrl = env("SHADOW_DATABASE_URL") + extensions = [hstore(schema: "myHstoreSchema"), pg_trgm, postgis(version: "2.1")] +} + +generator client { + provider = "prisma-client-js" + previewFeatures = ["postgresqlExtensions"] +} +``` + +To learn more about using Prisma with PostgreSQL extensions, refer to [this page in the Prisma docs](https://www.prisma.io/docs/concepts/components/prisma-schema/postgresql-extensions). + ## Resources - [Prisma](https://prisma.io) official website. diff --git a/apps/docs/pages/guides/platform/custom-domains.mdx b/apps/docs/pages/guides/platform/custom-domains.mdx index 558496506d1..441ebef2f87 100644 --- a/apps/docs/pages/guides/platform/custom-domains.mdx +++ b/apps/docs/pages/guides/platform/custom-domains.mdx @@ -155,6 +155,7 @@ As with the final activation stage of the process for setting up a vanity subdom - Edge functions do not honor the custom domain or the vanity subdomain setting and they still have to be invoked via the `foobarbaz.supabase.co` domain. - A Supabase project can—at this time—use either a Custom Domain or a Vanity Subdomain, but not both. +- Some authentication flows like Sign-in with Twitter set cookies to track the progress of the flow. Make sure you use only one domain in your frontend application for this reason. Mixing calls to the Supabase domain `foobarbaz.supabase.co` and your custom domain could cause those flows to stop working due to the [Same Origin Policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) enforced on cookies by the browser. export const Page = ({ children }) => diff --git a/apps/docs/pages/guides/platform/database-size.mdx b/apps/docs/pages/guides/platform/database-size.mdx new file mode 100644 index 00000000000..b827b926832 --- /dev/null +++ b/apps/docs/pages/guides/platform/database-size.mdx @@ -0,0 +1,101 @@ +import Layout from '~/layouts/DefaultGuideLayout' + +export const meta = { + id: 'database-size', + title: 'Database size', + description: 'Understanding how database size applies to your subscription.', +} + +Database size refers to the _monthly average storage usage_, as reported by Postgres. This metric is reported in your project's [billing usage](https://app.supabase.com/project/_/settings/billing/usage) and is updated daily. As you read this document we will refer to "database size" and "disk size": + +- "Database size" is the total size of used storage from your database. +- "Disk size" describes the size of the underlying available storage. + +## Database space management + +### Database size + +This SQL query will show the current size of your Postgres database: + +```sql +select + sum(pg_database_size (pg_database.datname)) / (1024 * 1024) as db_size_mb +from + pg_database; +``` + +This value is reported in the [database settings page](https://app.supabase.com/project/_/settings/database). + +Database Space is consumed primarily by your data, indexes, and materialized views. You can reduce your disk size by removing any of these and running a Vacuum operation. + + + +Depending on your billing tier, your database can go into read-only mode which can prevent you inserting and deleting data. There are instructions for managing read-only mode in the [Disk Management](#disk-management) section. + + + +### Vacuum operations + +Postgres does not immediately reclaim the physical space used by dead tuples (i.e., deleted rows) in the DB. They are marked as "removed" until a [vacuum operation](https://www.postgresql.org/docs/current/routine-vacuuming.html) is executed. As a result, deleting data from your database may not immediately reduce the reported disk usage. + + + +Vacuum operations can temporarily increase resource utilization, which may adversely impact the observed performance of your project until the maintenance is completed. + + + +Supabase projects have automatic vacuuming enabled, which ensures that these operations are performed regularly to keep the database healthy and performant. +It is possible to [fine-tune](https://www.percona.com/blog/2018/08/10/tuning-autovacuum-in-postgresql-and-autovacuum-internals/) +the [autovacuum parameters](https://www.enterprisedb.com/blog/postgresql-vacuum-and-analyze-best-practice-tips), +or [manually initiate](https://www.postgresql.org/docs/current/sql-vacuum.html) vacuum operations. +Running a manual vacuum after deleting large amounts of data from your DB could help reduce the database size reported by Postgres. + +### Preoccupied Space + +New Supabase projects have a database size of ~40-60mb. This space includes pre-installed extensions, schemas, and default Postgres data. Additional database size is used when installing extensions, even if those extensions are inactive. + +## Disk management + +Supabase uses network-attached storage to balance performance with scalability. The behavior of your disk depends on your billing tier. + +### Paid Tier Behavior + +Pro and Enterprise projects have auto-scaling Disk Storage. + +Disk storage expands automatically when the database reaches 90% of the disk size. The disk is expanded to be 50% larger (e.g., 8GB -> 12GB). Auto-scaling can only take place once every 6 hours. If within those 6 hours you reach 95% of the disk space, your project will enter read-only mode. + + + +If you intend to import a lot of data into your database which requires multiple disk expansions then [reach out to our team](https://app.supabase.com/support/new). For example, uploading more than 1.5x the current size of your database storage will put your database into [read-only mode](#read-only-mode). + + + +The maximum Disk Size for Pro Tier is 1024TB. If you need more than this, [contact us](https://app.supabase.com/support/new) to learn more about the Enterprise plan. + +### Free Tier Behavior + +Free Tier projects enter [read-only](#read-only-mode) mode when you exceed the 500mb limit. Once in read-only mode, you have several options: + +- [Upgrade to the Pro or Enterprise tier](https://app.supabase.com/project/_/settings/billing/subscription) to enable auto-scaling and expand beyond the 500mb database size limit. +- [Disable read-only mode](#disabling-read-only-mode) and reduce your database size. + +### Read-only mode + +In some cases Supabase may put your database into read-only mode to prevent your database from exceeding the billing or disk limitations. + +In read-only mode, clients will encounter errors such as `cannot execute INSERT in a read-only transaction`. Regular operation (read-write mode) is automatically re-enabled once usage is below 95% of the disk size, + +### Disabling read-only mode + +You can manually override read-only mode to reduce disk size. To do this, run the following in the [SQL Editor](https://app.supabase.com/project/_/sql): + +```sql +SET + default_transaction_read_only = 'off'; +``` + +This allows you to delete data from within the session. After deleting data, you should run a vacuum to reclaim as much space as possible. + +export const Page = ({ children }) => + +export default Page diff --git a/apps/docs/pages/guides/platform/database-usage.mdx b/apps/docs/pages/guides/platform/database-usage.mdx deleted file mode 100644 index 6ce6385770d..00000000000 --- a/apps/docs/pages/guides/platform/database-usage.mdx +++ /dev/null @@ -1,74 +0,0 @@ -import Layout from '~/layouts/DefaultGuideLayout' - -export const meta = { - id: 'database-usage', - title: 'Database usage', - description: 'Understanding how database usage applies to your subscription.', -} - -Database size refers to the _monthly average storage usage_, as reported by Postgres. This metric is reported in your project's [billing usage](https://app.supabase.com/project/_/settings/billing/usage) and is updated daily. -Database size is the total size of used storage from your database, whereas disk size describes the size of the underlying available storage. - -For an instantaneous live view of the DB size, you can execute in Postgres: - -```sql -select - sum(pg_database_size (pg_database.datname)) / (1024 * 1024) as db_size_mb -from - pg_database; -``` - -This value is also reported in the [database settings page](https://app.supabase.com/project/_/settings/database). - -## Database storage management - -Supabase uses network-attached storage to balance performance with scalability. -For Pro and Enterprise projects, disk size expands ~1.5x automatically (e.g., 8GB -> 12GB) when you reach 90% of the disk size. -Disk size expansion can only occur once every six hours. -Pro projects can store up to 1024TB. - -All projects enter read-only mode when you reach 95% of the disk size. In read-only mode, clients will encounter errors such as `cannot execute INSERT in a read-only transaction`. -Regular operation (read-write mode) is automatically re-enabled once usage is below 95% of the disk size. - -If you need more than 1024TB of disk size or require multiple storage expansions in a short period of time, [contact us](https://app.supabase.com/support/new) to learn more about the Enterprise plan. - -### Increasing available disk size - -1. [Upgrade to the Pro or Enterprise plan](https://app.supabase.com/project/_/settings/billing/subscription) to increase your quota and expand your disk size automatically. - -2. Delete data from your project's database to lower its disk usage. If your database is already in read-only mode, run the following command to change the transaction mode to read-write for your session: - - ```sql - SET - default_transaction_read_only = 'off'; - ``` - - This allows you to delete data from within the session. - -### Preoccupied Space - -When launching a new project, your database size will be roughly ~40-60mb. -The space is used up by preinstalled extensions, schema/data used by our services that are offered with each project and default Postgres data. - -When installing additional extensions, even if you don't actively use them, additional database size is used. - -## Vacuum operations - -Postgres does not immediately reclaim the physical space used by dead tuples (i.e., deleted rows) in the DB. Instead, they are internally marked as removed until a [vacuum operation](https://www.postgresql.org/docs/current/routine-vacuuming.html) is executed. -As a result, deleting data from your database may not immediately reduce the reported disk usage. - - - -Vacuum operations can temporarily increase resource utilization, which may adversely impact the observed performance of your project until the maintenance is completed. - - - -Supabase projects have automatic vacuuming enabled, which ensures that these operations are performed regularly to keep the database healthy and performant. -However, it can be necessary to either [fine-tune](https://www.percona.com/blog/2018/08/10/tuning-autovacuum-in-postgresql-and-autovacuum-internals/) -the [autovacuum parameters](https://www.enterprisedb.com/blog/postgresql-vacuum-and-analyze-best-practice-tips), -or [manually initiate](https://www.postgresql.org/docs/current/sql-vacuum.html) vacuum operations. -For example, running a manual vacuum after deleting large amounts of data from your DB could help reduce the reported disk usage by Postgres. - -export const Page = ({ children }) => - -export default Page diff --git a/apps/docs/pages/guides/platform/migrating-and-upgrading-projects.mdx b/apps/docs/pages/guides/platform/migrating-and-upgrading-projects.mdx index 1b657450546..9b035e1264b 100644 --- a/apps/docs/pages/guides/platform/migrating-and-upgrading-projects.mdx +++ b/apps/docs/pages/guides/platform/migrating-and-upgrading-projects.mdx @@ -66,7 +66,7 @@ Replication for Realtime is disabled for all tables in your new project. On the ### Migrate Storage objects -The new project has the old project's Storage buckets, but the Storage objects need to be migrated manually. Use this script to move storage objects from one project to another. If you have more than 10k objects, we can move the objects for you. Just contact us at [support@supabase.com](mailto:support@supabase.com). +The new project has the old project's Storage buckets, but the Storage objects need to be migrated manually. Use this script to move storage objects from one project to another. ```js // npm install @supabase/supabase-js@1 diff --git a/apps/docs/pages/guides/platform/performance.mdx b/apps/docs/pages/guides/platform/performance.mdx index 8d7ae48e422..a00b509dbb3 100644 --- a/apps/docs/pages/guides/platform/performance.mdx +++ b/apps/docs/pages/guides/platform/performance.mdx @@ -8,6 +8,159 @@ export const meta = { The Supabase platform automatically optimizes your Postgres database to take advantage of the compute resources of the tier your project is on. However, these optimizations are based on assumptions about the type of workflow the project is being utilized for, and it is likely that better results can be obtained by tuning the database for your particular workflow. +## Examining Query Performance + +Unoptimized queries are a major cause of poor database performance. The techniques on this page can help you identify and understand queries that take the most time and resources from your database. + +Database performance is a large topic and many factors can contribute. Some of the most common causes of poor performance include: + +* An inefficiently designed schema +* Inefficiently designed queries +* A lack of indexes causing slower than required queries over large tables +* Unused indexes causing slow `INSERT`, `UPDATE` and `DELETE` operations +* Not enough compute resources, such as memory, causing your database to go to disk for results too often +* Lock contention from multiple queries operating on highly utilized tables +* Large amount of bloat on your tables causing poor query planning + +Thankfully there are solutions to all these issues, which we will cover in the following sections. + +### Postgres Cumulative Statistics system + +Postgres collects data about its own operations using the [cumulative statistics system](https://www.postgresql.org/docs/current/monitoring-stats.html). In addition to this, every Supabase project has the [pg_stat_statements extension](/docs/guides/database/extensions/pg_stat_statements) enabled by default. This extension records query execution performance details and is the best way to find inefficient queries. This information can be combined with the Postgres query plan analyzer to develop more efficient queries. + +Here are some example queries to get you started. + +#### Most frequently called queries: + +```sql +select + auth.rolname, + statements.query, + statements.calls, + -- -- Postgres 13, 14, 15 + statements.total_exec_time + statements.total_plan_time as total_time, + statements.min_exec_time + statements.min_plan_time as min_time, + statements.max_exec_time + statements.max_plan_time as max_time, + statements.mean_exec_time + statements.mean_plan_time as mean_time, + -- -- Postgres <= 12 + -- total_time, + -- min_time, + -- max_time, + -- mean_time, + statements.rows / statements.calls as avg_rows + +from pg_stat_statements as statements + inner join pg_authid as auth on statements.userid = auth.oid +order by + statements.calls desc +limit + 100; +``` + +This query shows: + +- query statistics, ordered by the number of times each query has been executed +- the role that ran the query +- the number of times it has been called +- the average number of rows returned +- the cumulative total time the query has spent running +- the min, max and mean query times. + +This provides useful information about the queries you run most frequently. Queries that have high `max_time` or `mean_time` times and are being called often can be good candidates for optimization. + +#### Slowest queries by execution time: + +```sql +select + auth.rolname, + statements.query, + statements.calls, + -- -- Postgres 13, 14, 15 + statements.total_exec_time + statements.total_plan_time as total_time, + statements.min_exec_time + statements.min_plan_time as min_time, + statements.max_exec_time + statements.max_plan_time as max_time, + statements.mean_exec_time + statements.mean_plan_time as mean_time, + -- -- Postgres <= 12 + -- total_time, + -- min_time, + -- max_time, + -- mean_time, + statements.rows / statements.calls as avg_rows +from pg_stat_statements as statements + inner join pg_authid as auth on statements.userid = auth.oid + order by + max_time desc + limit + 100; +``` + +This query will show you statistics about queries ordered by the maximum execution time. It is similar to the query above ordered by calls, but this one highlights outliers that may have high executions times. Queries which have high or mean execution times are good candidates for optimisation. + +#### Most time consuming queries: + +```sql +select + auth.rolname, + statements.query, + statements.calls, + statements.total_exec_time + statements.total_plan_time as total_time, + to_char(((statements.total_exec_time + statements.total_plan_time)/sum(statements.total_exec_time + statements.total_plan_time) over()) * 100, 'FM90D0') || '%' as prop_total_time +from pg_stat_statements as statements + inner join pg_authid as auth on statements.userid = auth.oid +order by + total_time desc +limit + 100; +``` + +This query will show you statistics about queries ordered by the cumulative total execution time. It shows the total time the query has spent running as well as the proportion of total execution time the query has taken up. + +Queries which are the most time consuming are not necessarily bad, you may have a very effiecient and frequently ran queries that end up taking a large total % time, but it can be useful to help spot queries that are taking up more time than they should. + +### Hit rate + +Generally for most applications a small percentage of data is accessed more regularly than the rest. To make sure that your regularly accessed data is available, Postgres tracks your data access patterns and keeps this in its [shared_buffers](https://www.postgresql.org/docs/15/runtime-config-resource.html#RUNTIME-CONFIG-RESOURCE-MEMORY) cache. + +Applications with lower cache hit rates generally perform more poorly since they have to hit the disk to get results rather than serving them from memory. Very poor hit rates can also cause you to burst past your [Disk I/O limits](https://supabase.com/docs/guides/platform/compute-add-ons#disk-io-bandwidth) causing significant performance issues. + +You can view your cache and index hit rate by executing the following query: + +```sql +select + 'index hit rate' as name, + (sum(idx_blks_hit)) / nullif(sum(idx_blks_hit + idx_blks_read),0) * 100 as ratio +from pg_statio_user_indexes +union all +select + 'table hit rate' as name, + sum(heap_blks_hit) / nullif(sum(heap_blks_hit) + sum(heap_blks_read),0) * 100 as ratio +from pg_statio_user_tables; +``` + +This shows the ratio of data blocks fetched from the Postgres [shared_buffers](https://www.postgresql.org/docs/15/runtime-config-resource.html#RUNTIME-CONFIG-RESOURCE-MEMORY) cache against the data blocks that were read from disk/OS cache. + +If either of your index or table hit rate are < 99% then this can indicate your compute plan is too small for your current workload and you would benefit from more memory. [Upgrading your compute](https://supabase.com/docs/guides/platform/compute-add-ons) is easy and can be done from your [project dashboard](https://app.supabase.com/project/_/settings/billing/subscription). + + +### Optimizing poor performing queries + +Postgres has built in tooling to help you optimize poorly performing queries. You can use the [query plan analyzer](https://www.postgresql.org/docs/current/sql-explain.html) on any expensive queries that you have identified: + +```sql +explain analyze ; +``` + +Be careful using `explain analyze` with `insert`/`update`/`delete` queries, because the query will actually run, and could have unintended side-effects. + +Using the query plan analyzer to optimize your queries is a large topic, with a number of online resources available: + +- [Official docs.](https://www.postgresql.org/docs/current/using-explain.html) +- [The Art of PostgreSQL.](https://theartofpostgresql.com/explain-plan-visualizer/) +- [Postgres Wiki.](https://wiki.postgresql.org/wiki/Using_EXPLAIN) +- [Enterprise DB.](https://www.enterprisedb.com/blog/postgresql-query-optimization-performance-tuning-with-explain-analyze) + +You can pair the information available from `pg_stat_statements` with the detailed system metrics available [via your metrics endpoint](../platform/metrics) to better understand the behavior of your DB and the queries you're executing against it. + ## Optimizing the number of connections By default, the number of connections allowed to Postgres and PgBouncer is configured based on the resources available to the database. @@ -64,33 +217,6 @@ alter system reset ; Configuring the number of PgBouncer connections is not supported at this time. -## Examining Query Performance - -Every Supabase project has [the pg_stat_statements extension](https://www.postgresql.org/docs/14/pgstatstatements.html) enabled by default. This extension records query execution performance details and is the best way to find queries that take the most time to execute. This information can be combined with the Postgres query plan analyzer to develop more efficient queries. - -Obtaining information from pg_stat_statements: - -```sql -select mean_exec_time + stddev_exec_time, * from pg_stat_statements order by 1 desc; -``` - -Using the query plan analyzer on your expensive queries: - -```sql -explain analyze ; -``` - -Be careful using `explain analyze` with `insert`/`update`/`delete` queries, because the query will actually run, and could have unintended side-effects. - -Using the query plan analyzer to optimize your queries is a large topic, with a number of online resources available: - -- [Official docs.](https://www.postgresql.org/docs/current/using-explain.html) -- [The Art of PostgreSQL.](https://theartofpostgresql.com/explain-plan-visualizer/) -- [Postgres Wiki.](https://wiki.postgresql.org/wiki/Using_EXPLAIN) -- [Enterprise DB.](https://www.enterprisedb.com/blog/postgresql-query-optimization-performance-tuning-with-explain-analyze) - -You can pair the information available from `pg_stat_statements` with the detailed system metrics available [via your metrics endpoint](../platform/metrics) to better understand the behavior of your DB and the queries you're executing against it. - export const Page = ({ children }) => export default Page diff --git a/apps/docs/public/img/guides/integrations/prisma/w0oowg8vq435ob5c3gf0.png b/apps/docs/public/img/guides/integrations/prisma/w0oowg8vq435ob5c3gf0.png index 9bfb34db474..05db2d109b6 100644 Binary files a/apps/docs/public/img/guides/integrations/prisma/w0oowg8vq435ob5c3gf0.png and b/apps/docs/public/img/guides/integrations/prisma/w0oowg8vq435ob5c3gf0.png differ diff --git a/apps/docs/public/img/integrations/logos/openai_logo.png b/apps/docs/public/img/integrations/logos/openai_logo.png new file mode 100644 index 00000000000..c5596878b0b Binary files /dev/null and b/apps/docs/public/img/integrations/logos/openai_logo.png differ diff --git a/apps/www/_blog/2023-02-07-chatgpt-supabase-docs.mdx b/apps/www/_blog/2023-02-07-chatgpt-supabase-docs.mdx index 0773f7c9713..85b061947c7 100644 --- a/apps/www/_blog/2023-02-07-chatgpt-supabase-docs.mdx +++ b/apps/www/_blog/2023-02-07-chatgpt-supabase-docs.mdx @@ -11,7 +11,7 @@ date: '2023-02-07' toc_depth: 3 --- -We all know that Microsoft's real agenda for pouring billions into OpenAI to revive their favorite friend Clippy. +We all know that Microsoft's real agenda for pouring billions into OpenAI is to revive their favorite friend Clippy. Today, we're doing our part to support the momentum by releasing “Supabase Clippy” for our docs (and we don't expect this name to last long before the lawyers catch on). ![Clippy](/images/blog/docsgpt/clippy.png) @@ -30,7 +30,7 @@ Our product suite has grown in the past 2 years and our docs have grown as a res ### The “ask” interface -Developers have recently gained an the ability to trust a bot. Where Clippy failed, ChatGPT succeeded. +Developers have recently gained the ability to trust a bot. Where Clippy failed, ChatGPT succeeded. This is convenient timing for us, since our documentation content is more than the average developer wants to consume in one go. Today we're providing a similar interface to ChatGPT which is trained on our own docs. diff --git a/apps/www/lib/redirects.js b/apps/www/lib/redirects.js index e73aa509b57..00b9b15e5c5 100644 --- a/apps/www/lib/redirects.js +++ b/apps/www/lib/redirects.js @@ -1857,4 +1857,9 @@ module.exports = [ source: '/docs/reference/javascript/v0/rpc', destination: '/docs/reference/javascript/rpc', }, + { + permanent: true, + source: '/docs/guides/platform/database-usage', + destination: '/docs/guides/platform/database-size', + }, ] diff --git a/apps/www/pages/_app.tsx b/apps/www/pages/_app.tsx index b4fb7a031ce..9698060202f 100644 --- a/apps/www/pages/_app.tsx +++ b/apps/www/pages/_app.tsx @@ -38,7 +38,7 @@ export default function MyApp({ Component, pageProps }: AppProps) { return ( <> - + { {site_title} + diff --git a/apps/www/pages/pricing/index.tsx b/apps/www/pages/pricing/index.tsx index 9b209dc901e..bb359df65a1 100644 --- a/apps/www/pages/pricing/index.tsx +++ b/apps/www/pages/pricing/index.tsx @@ -83,34 +83,6 @@ export default function IndexPage() { additional: '', cta: 'Get Started', }, - // { - // name: 'Team', - // nameBadge: 'New', - // costUnit: 'per month per org', - // href: 'https://app.supabase.com/new/new-project', - // from: true, - // priceLabel: 'Starting from', - // priceMonthly: 599, - // description: 'For scaling teams with permissions & access controls', - // warning: '+ any additional usage', - // features: [ - // 'Usage-based pricing', - // 'Organization member roles (ABAC)', - // 'SOC2', - // 'Priority email support & SLAs', - // '14 day backups', - // '100,000 monthly active users included', - // 'Standardized Security Questionnaire', - // 'SSO for Supabase Dashboard', - // '1 XS compute instance', - // '28 day log retention', - // ], - // scale: '', - // shutdown: '', - // preface: 'The following features will apply to all projects within the organization:', - // additional: '', - // cta: 'Get Started', - // }, { name: 'Enterprise', href: 'https://forms.supabase.com/enterprise', @@ -127,8 +99,8 @@ export default function IndexPage() { `Private Slack channel`, `Uptime SLA`, ], - priceLabel: 'Custom quotas', - priceMonthly: 'Exclusive pricing', + priceLabel: '', + priceMonthly: 'Contact us', preface: 'These apply to all projects within the organization:', scale: '', shutdown: '', @@ -164,7 +136,7 @@ export default function IndexPage() { name: 'Point in Time Recovery', heroImg: 'addons-pitr-hero', icon: 'pitr-upgrade', - price: 'Starts from $5', + price: 'Starts from $100', description: 'Roll back to any specific point in time and ensure that data is not lost.', leftCtaText: 'Documentation', leftCtaLink: 'https://supabase.com/docs/guides/platform/backups', @@ -319,7 +291,7 @@ export default function IndexPage() {

{tier.name !== 'Enterprise' && '$'} @@ -750,13 +722,15 @@ export default function IndexPage() { <> {tier.name !== 'Enterprise' && '$'} {tier.priceMonthly} -

per project per month

+ {tier.name !== 'Enterprise' && ( +

per project per month

+ )} {tier.warning && ( @@ -861,66 +835,12 @@ export default function IndexPage() {

Frequently asked questions

-

- Can't find the answer to your question, ask someone in the community either on - our Discord or GitHub. -

-
-
- {/* @ts-ignore */} +
@@ -940,6 +860,28 @@ export default function IndexPage() { })}
+

+ Can't find the answer to your question, you can{' '} + + open a support ticket + {' '} + and our team of experts will be able to help. +

+

+ For enterprise enquries,{' '} + + you can contact the team here + + . +

diff --git a/examples/edge-functions/README.md b/examples/edge-functions/README.md index f32e56e2357..47e624783a9 100644 --- a/examples/edge-functions/README.md +++ b/examples/edge-functions/README.md @@ -6,23 +6,17 @@ ## Example Functions -The function examples are located in [`./supabase/functions`](./supabase/functions): - -- [`browser-with-cors`](./supabase/functions/browser-with-cors/index.ts): Handle CORS headers for function invocations from browser environments. -- [`select-from-table-with-auth-rls`](./supabase/functions/select-from-table-with-auth-rls/index.ts): Retrieve data from an authenticated user via RLS. -- [`send-email-smtp`](./supabase/functions/send-email-smtp/index.ts): Send an email using SMTP credentials. -- [`stripe-webhooks`](./supabase/functions/stripe-webhooks/index.ts): Handle Stripe Webhooks. -- [`telegram-bot`](./supabase/functions/telegram-bot/index.ts): Webhook handler for Telegram bots using [grammY](https://grammy.dev/). +We're constantly adding new Function Examples, [check our docs](https://supabase.com/docs/guides/functions#examples) for a complete list! ## Develop locally - Run `supabase start` (make sure your Docker daemon is running.) -- Run `mv ./supabase/.env.local.example ./supabase/.env.local` to rename the local `.env` file. -- Set the required variables to run the desired edge functions in the `.env.local` file. -- Run `supabase functions serve your-function-name --env-file ./supabase/.env.local` +- Run `cp ./supabase/.env.local.example ./supabase/.env.local` to create your local `.env` file. +- Set the required variables for the corresponding edge functions in the `.env.local` file. +- Run `supabase functions serve --env-file ./supabase/.env.local --no-verify-jwt` - Run the CURL command in the example function, or use the [invoke method](https://supabase.com/docs/reference/javascript/invoke) on the Supabase client or use the test client [app](./app/). -## Test +## Test Client This example includes a create-react-app in the [`./app/`](./app/) directory which you can use as a sort of postman to make test requests both locally and to your deployed functions. @@ -45,10 +39,13 @@ Note: when testing locally, the select dropdown doesn't have any effect, and inv - Link your project - Within your project root run `supabase link --project-ref your-project-ref` - Set up your secrets + - Run `supabase secrets set --env-file ./supabase/.env.local` to set the environment variables. - + (This is assuming your local and production secrets are the same. The recommended way is to create a separate `.env` file for storing production secrets, and then use it to set the environment variables while deploying.) + - You can run `supabase secrets list` to check that it worked and also to see what other env vars are set by default. + - Deploy the function - Within your project root run `supabase functions deploy your-function-name` - In your [`./app/.env`](./app/.env) file remove the `SUPA_FUNCTION_LOCALHOST` variable and restart your Expo app. diff --git a/examples/edge-functions/edge-functions.code-workspace b/examples/edge-functions/edge-functions.code-workspace index 80054980ded..d3e694fd61c 100644 --- a/examples/edge-functions/edge-functions.code-workspace +++ b/examples/edge-functions/edge-functions.code-workspace @@ -18,6 +18,7 @@ "node_modules/": true, "app/": true, "supabase/functions/": true - } + }, + "deno.importMap": "./supabase/functions/import_map.json" } } diff --git a/examples/edge-functions/supabase/.env.local.example b/examples/edge-functions/supabase/.env.local.example index 4456221dc6c..0031244f9f3 100644 --- a/examples/edge-functions/supabase/.env.local.example +++ b/examples/edge-functions/supabase/.env.local.example @@ -1,3 +1,21 @@ +# cloudflare-turnstile +CLOUDFLARE_TURNSTILE_SECRET_KEY=your_secret_key + +# discord-bot +DISCORD_PUBLIC_KEY= + +# location +IPINFO_TOKEN="your https://ipinfo.io token" + +# openai +OPENAI_API_KEY="" + +# postgres-on-the-edge +DATABASE_URL= + +# puppeteer +PUPPETEER_BROWSERLESS_IO_TOKEN= + # send-email-smtp SMTP_HOSTNAME="your.hostname.com" SMTP_PORT="2587" @@ -5,13 +23,14 @@ SMTP_USERNAME="your_username" SMTP_PASSWORD="your_password" SMTP_FROM="no-reply@example.com" -# telegram-bot -TELEGRAM_BOT_TOKEN="get it from https://t.me/BotFather" -FUNCTION_SECRET="random secret" - # stripe-webhooks STRIPE_API_KEY="" STRIPE_WEBHOOK_SIGNING_SECRET="" -# openai -OPENAI_API_KEY="" +# telegram-bot +TELEGRAM_BOT_TOKEN="get it from https://t.me/BotFather" +FUNCTION_SECRET="random secret" + +# upstash-redis-counter +UPSTASH_REDIS_REST_URL= +UPSTASH_REDIS_REST_TOKEN= diff --git a/examples/edge-functions/supabase/functions/.vscode/settings.json b/examples/edge-functions/supabase/functions/.vscode/settings.json index e40716fdd7e..1d800e858b2 100644 --- a/examples/edge-functions/supabase/functions/.vscode/settings.json +++ b/examples/edge-functions/supabase/functions/.vscode/settings.json @@ -1,5 +1,5 @@ { "deno.enable": true, - "deno.lint": true, - "deno.unstable": true + "deno.unstable": true, + "deno.importMap": "./import_map.json" } diff --git a/examples/edge-functions/supabase/functions/browser-with-cors/index.ts b/examples/edge-functions/supabase/functions/browser-with-cors/index.ts index 1ab04de4e1f..d022ef6035f 100644 --- a/examples/edge-functions/supabase/functions/browser-with-cors/index.ts +++ b/examples/edge-functions/supabase/functions/browser-with-cors/index.ts @@ -2,7 +2,7 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' +import { serve } from 'std/server' import { corsHeaders } from '../_shared/cors.ts' console.log(`Function "browser-with-cors" up and running!`) diff --git a/examples/edge-functions/supabase/functions/cloudflare-turnstile/README.md b/examples/edge-functions/supabase/functions/cloudflare-turnstile/README.md index 4d8bc5008cd..3ec3bf986bc 100644 --- a/examples/edge-functions/supabase/functions/cloudflare-turnstile/README.md +++ b/examples/edge-functions/supabase/functions/cloudflare-turnstile/README.md @@ -2,6 +2,10 @@ Turnstile is Cloudflare's CAPTCHA alternative: https://developers.cloudflare.com/turnstile/get-started/ +## Watch the Video Tutorial + +[![video tutorial](https://img.youtube.com/vi/OwW0znboh60/0.jpg)](https://www.youtube.com/watch?v=OwW0znboh60) + ## Setup - Follow these steps to set up a new site: https://developers.cloudflare.com/turnstile/get-started/ diff --git a/examples/edge-functions/supabase/functions/cloudflare-turnstile/index.ts b/examples/edge-functions/supabase/functions/cloudflare-turnstile/index.ts index 5d831d18ab7..02e440f3460 100644 --- a/examples/edge-functions/supabase/functions/cloudflare-turnstile/index.ts +++ b/examples/edge-functions/supabase/functions/cloudflare-turnstile/index.ts @@ -2,7 +2,7 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' +import { serve } from 'std/server' import { corsHeaders } from '../_shared/cors.ts' console.log(`Function "cloudflare-turnstile" up and running!`) @@ -55,7 +55,7 @@ serve(async (req) => { }) // To invoke: -// curl -i --location --request POST 'http://localhost:54321/functions/v1/' \ +// curl -i --location --request POST 'http://localhost:54321/functions/v1/cloudflare-turnstile' \ // --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0' \ // --header 'Content-Type: application/json' \ // --data '{"token":"cf-turnstile-response"}' diff --git a/examples/edge-functions/supabase/functions/discord-bot/README.md b/examples/edge-functions/supabase/functions/discord-bot/README.md index 5e9ad79f29b..7d66deb798c 100644 --- a/examples/edge-functions/supabase/functions/discord-bot/README.md +++ b/examples/edge-functions/supabase/functions/discord-bot/README.md @@ -5,6 +5,10 @@ - https://deno.com/deploy/docs/tutorial-discord-slash - https://discord.com/developers/docs/interactions/application-commands#slash-commands +## Watch the Video Tutorial + +[![video tutorial](https://img.youtube.com/vi/J24Bvo_m7DM/0.jpg)](https://www.youtube.com/watch?v=J24Bvo_m7DM) + ## Create an application on Discord Developer Portal 1. Go to [https://discord.com/developers/applications](https://discord.com/developers/applications) (login using your discord account if required). @@ -59,6 +63,6 @@ Open Discord, type `/Promise` and press **Enter**. ## Run locally ```bash -supabase functions serve discord-bot --no-verify-jwt --env-file ./supabase/functions/discord-bot/.env +supabase functions serve discord-bot --no-verify-jwt --env-file ./supabase/.env.local ngrok http 54321 ``` diff --git a/examples/edge-functions/supabase/functions/discord-bot/index.ts b/examples/edge-functions/supabase/functions/discord-bot/index.ts index 140bb30b767..abbf5985f2d 100644 --- a/examples/edge-functions/supabase/functions/discord-bot/index.ts +++ b/examples/edge-functions/supabase/functions/discord-bot/index.ts @@ -5,10 +5,10 @@ // Sift is a small routing library that abstracts away details like starting a // listener on a port, and provides a simple function (serve) that has an API // to invoke a function for a specific path. -import { json, serve, validateRequest } from 'https://deno.land/x/sift@0.6.0/mod.ts' +import { json, serve, validateRequest } from 'sift' // TweetNaCl is a cryptography library that we use to verify requests // from Discord. -import nacl from 'https://cdn.skypack.dev/tweetnacl@v1.0.3?dts' +import nacl from 'nacl' enum DiscordCommandType { Ping = 1, diff --git a/examples/edge-functions/supabase/functions/file-upload-storage/index.ts b/examples/edge-functions/supabase/functions/file-upload-storage/index.ts index 5593c0b6581..208619a7b49 100644 --- a/examples/edge-functions/supabase/functions/file-upload-storage/index.ts +++ b/examples/edge-functions/supabase/functions/file-upload-storage/index.ts @@ -1,8 +1,8 @@ // This example shows how to use Edge Functions to read incoming multipart/form-data request, // and write files to Supabase Storage and other fields to a database table. -import { Application, Router } from 'https://deno.land/x/oak/mod.ts' -import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' +import { Application } from 'oak' +import { createClient } from '@supabase/supabase-js' const MB = 1024 * 1024 @@ -25,9 +25,9 @@ app.use(async (ctx) => { const supabaseClient = createClient( // Supabase API URL - env var exported by default. - Deno.env.get('SUPABASE_URL') ?? '', + Deno.env.get('SUPABASE_URL')!, // Supabase API ANON KEY - env var exported by default. - Deno.env.get('SUPABASE_ANON_KEY') ?? '' + Deno.env.get('SUPABASE_ANON_KEY')! ) //upload image to Storage diff --git a/examples/edge-functions/supabase/functions/get-tshirt-competition/README.md b/examples/edge-functions/supabase/functions/get-tshirt-competition/README.md index 8d0bcb0dd72..b83a049526c 100644 --- a/examples/edge-functions/supabase/functions/get-tshirt-competition/README.md +++ b/examples/edge-functions/supabase/functions/get-tshirt-competition/README.md @@ -15,9 +15,11 @@ Good luck trying to GET a T-Shirt! ### Serve this function locally ```bash -supabase functions serve --no-verify-jwt get-tshirt-competition +supabase functions serve --no-verify-jwt ``` +Navigate to http://localhost:54321/functions/v1/get-tshirt-competition?email=testr@test.de&twitter=thorwebdev&size=2XL&answer=20 + ### Deploy this function ```bash diff --git a/examples/edge-functions/supabase/functions/get-tshirt-competition/index.ts b/examples/edge-functions/supabase/functions/get-tshirt-competition/index.ts index 01e03605441..76b09b974c9 100644 --- a/examples/edge-functions/supabase/functions/get-tshirt-competition/index.ts +++ b/examples/edge-functions/supabase/functions/get-tshirt-competition/index.ts @@ -2,8 +2,8 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' -import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' +import { serve } from 'std/server' +import { createClient } from '@supabase/supabase-js' import { corsHeaders } from '../_shared/cors.ts' console.log(`Function "get-tshirt-competition" up and running!`) diff --git a/examples/edge-functions/supabase/functions/github-action-deploy/index.ts b/examples/edge-functions/supabase/functions/github-action-deploy/index.ts index 2dc629d0cf8..423445b1608 100644 --- a/examples/edge-functions/supabase/functions/github-action-deploy/index.ts +++ b/examples/edge-functions/supabase/functions/github-action-deploy/index.ts @@ -2,23 +2,18 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from "https://deno.land/std@0.131.0/http/server.ts"; +import { serve } from 'std/server' -console.log("Hello from Functions!"); +console.log('Hello from Functions!') -serve(async (req) => { - const { name } = await req.json(); +serve((_req) => { const data = { message: `I was deployed via GitHub Actions!`, - }; + } return new Response(JSON.stringify(data), { - headers: { "Content-Type": "application/json" }, - }); -}); + headers: { 'Content-Type': 'application/json' }, + }) +}) -// To invoke: -// curl -i --location --request POST 'http://localhost:54321/functions/v1/' \ -// --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs' \ -// --header 'Content-Type: application/json' \ -// --data '{"name":"Functions"}' +// To invoke: http://localhost:54321/functions/v1/github-action-deploy diff --git a/examples/edge-functions/supabase/functions/import_map.json b/examples/edge-functions/supabase/functions/import_map.json new file mode 100644 index 00000000000..be4b4d84118 --- /dev/null +++ b/examples/edge-functions/supabase/functions/import_map.json @@ -0,0 +1,20 @@ +{ + "imports": { + "denomailer": "https://deno.land/x/denomailer@0.12.0/mod.ts", + "nacl": "https://cdn.skypack.dev/tweetnacl@v1.0.3?dts", + "oak": "https://deno.land/x/oak@v11.1.0/mod.ts", + "og_edge": "https://deno.land/x/og_edge@0.0.4/mod.ts", + "openai": "https://esm.sh/openai@3.1.0", + "grammy": "https://deno.land/x/grammy@v1.8.3/mod.ts", + "react": "https://esm.sh/react@18.2.0", + "std/server": "https://deno.land/std@0.177.0/http/server.ts", + "stripe": "https://esm.sh/stripe@11.1.0?target=deno", + "sift": "https://deno.land/x/sift@0.6.0/mod.ts", + "@supabase/supabase-js": "https://esm.sh/@supabase/supabase-js@2.7.1", + "postgres": "https://deno.land/x/postgres@v0.14.2/mod.ts", + "puppeteer": "https://deno.land/x/puppeteer@16.2.0/mod.ts", + "React": "https://esm.sh/react@18.2.0?deno-std=0.177.0", + "upstash_redis": "https://deno.land/x/upstash_redis@v1.19.3/mod.ts", + "xhr_polyfill": "https://deno.land/x/xhr@0.3.0/mod.ts" + } +} diff --git a/examples/edge-functions/supabase/functions/location/README.md b/examples/edge-functions/supabase/functions/location/README.md index b2c0bacceb7..de3010f4440 100644 --- a/examples/edge-functions/supabase/functions/location/README.md +++ b/examples/edge-functions/supabase/functions/location/README.md @@ -4,6 +4,14 @@ This example shows how you can get user location based on the IP provided in X-F You will need to signup for an account in https://ipinfo.io and provide it as `IPINFO_TOKEN` environment variable ([learn how to set environment variables to your functions](https://supabase.com/docs/guides/functions#secrets-and-environment-variables)). +## Develop locally + +```bash +supabase functions serve --env-file ./supabase/.env.local --no-verify-jwt +``` + +Navigate to http://localhost:54321/functions/v1/location + ## Deploy ```bash diff --git a/examples/edge-functions/supabase/functions/location/index.ts b/examples/edge-functions/supabase/functions/location/index.ts index c9df62475af..cda85ab7837 100644 --- a/examples/edge-functions/supabase/functions/location/index.ts +++ b/examples/edge-functions/supabase/functions/location/index.ts @@ -2,20 +2,29 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from "https://deno.land/std@0.131.0/http/server.ts" +import { serve } from 'std/server' function ips(req: Request) { - return req.headers.get("x-forwarded-for")?.split(/\s*,\s*/); + return req.headers.get('x-forwarded-for')?.split(/\s*,\s*/) } serve(async (req) => { - const clientIps = ips(req) || ['']; - const res = await fetch(`https://ipinfo.io/${clientIps[0]}?token=${Deno.env.get('IPINFO_TOKEN')}`, { - headers: { 'Content-Type': 'application/json'}}); - const { city, country } = await res.json(); - - return new Response( - JSON.stringify(`You're accessing from ${city}, ${country}`), - { headers: { "Content-Type": "application/json" } }, + const clientIps = ips(req) || [''] + const res = await fetch( + `https://ipinfo.io/${clientIps[0]}?token=${Deno.env.get('IPINFO_TOKEN')}`, + { + headers: { 'Content-Type': 'application/json' }, + } ) + if (res.ok) { + const { city, country } = await res.json() + + return new Response(JSON.stringify(`You're accessing from ${city}, ${country}`), { + headers: { 'Content-Type': 'application/json' }, + }) + } else { + return new Response(await res.text(), { + status: 400, + }) + } }) diff --git a/examples/edge-functions/supabase/functions/oak-server/README.md b/examples/edge-functions/supabase/functions/oak-server/README.md index b1db6166231..ed2795cfc71 100644 --- a/examples/edge-functions/supabase/functions/oak-server/README.md +++ b/examples/edge-functions/supabase/functions/oak-server/README.md @@ -5,7 +5,7 @@ This example shows how you can write functions using Oak server middleware (http ## Run locally ```bash -supabase functions serve oak-server +supabase functions serve --no-verify-jwt ``` Use cURL or Postman to make a POST request to http://localhost:54321/functions/v1/oak-server. @@ -20,5 +20,5 @@ Use cURL or Postman to make a POST request to http://localhost:54321/functions/v ## Deploy ```bash -supabase functions deploy oak-server +supabase functions deploy oak-server --no-verify-jwt ``` diff --git a/examples/edge-functions/supabase/functions/oak-server/index.ts b/examples/edge-functions/supabase/functions/oak-server/index.ts index 9be189be65a..965da32e4a0 100644 --- a/examples/edge-functions/supabase/functions/oak-server/index.ts +++ b/examples/edge-functions/supabase/functions/oak-server/index.ts @@ -1,4 +1,4 @@ -import { Application, Router } from 'https://deno.land/x/oak/mod.ts' +import { Application, Router } from 'oak' const router = new Router() router diff --git a/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/README.md b/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/README.md index 2adb83328c7..05158fd957e 100644 --- a/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/README.md +++ b/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/README.md @@ -9,7 +9,7 @@ Generate Open Graph images with Deno and Supabase Edge Functions and cache the g ## Run locally ```bash -supabase functions serve og-image-with-storage-cdn --no-verify-jwt +supabase functions serve --no-verify-jwt ``` Navigate to http://localhost:54321/functions/v1/og-image-with-storage-cdn?ticketNumber=3524&username=thorwebdev&name=Thor%20%E9%9B%B7%E7%A5%9E%20Schaeff diff --git a/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/handler.tsx b/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/handler.tsx index 80ef24e2ccd..202684370ea 100644 --- a/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/handler.tsx +++ b/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/handler.tsx @@ -1,6 +1,6 @@ -import React from 'https://esm.sh/react@18.2.0?deno-std=0.140.0' -import { ImageResponse } from 'https://deno.land/x/og_edge@0.0.4/mod.ts' -import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' +import React from 'React' +import { ImageResponse } from 'og_edge' +import { createClient } from '@supabase/supabase-js' import { corsHeaders } from '../_shared/cors.ts' const STORAGE_URL = 'https://obuldanrptloktxcffvn.supabase.co/storage/v1/object/public/images/lw6' @@ -213,7 +213,7 @@ export async function handler(req: Request) { }) if (error) throw error - return generatedImage + return await fetch(`${STORAGE_URL}/tickets/${username}.png?v=3`) } catch (error) { return new Response(JSON.stringify({ error: error.message }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, diff --git a/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/index.ts b/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/index.ts index 5b2cf3da0b9..0cf64b6e552 100644 --- a/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/index.ts +++ b/examples/edge-functions/supabase/functions/og-image-with-storage-cdn/index.ts @@ -2,7 +2,7 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.140.0/http/server.ts' +import { serve } from 'std/server' import { handler } from './handler.tsx' diff --git a/examples/edge-functions/supabase/functions/openai/README.md b/examples/edge-functions/supabase/functions/openai/README.md index 4433aa6abb1..33894bacb4f 100644 --- a/examples/edge-functions/supabase/functions/openai/README.md +++ b/examples/edge-functions/supabase/functions/openai/README.md @@ -9,7 +9,7 @@ cp supabase/.env.local.example supabase/.env.local ## Run locally ```bash -supabase functions serve --no-verify-jwt --env-file ./supabase/.env.local openai +supabase functions serve --env-file ./supabase/.env.local --no-verify-jwt ``` Use cURL or Postman to make a POST request to http://localhost:54321/functions/v1/openai. diff --git a/examples/edge-functions/supabase/functions/openai/index.ts b/examples/edge-functions/supabase/functions/openai/index.ts index 5bab2eafbb2..a7418d73e19 100644 --- a/examples/edge-functions/supabase/functions/openai/index.ts +++ b/examples/edge-functions/supabase/functions/openai/index.ts @@ -1,6 +1,6 @@ -import 'https://deno.land/x/xhr@0.3.0/mod.ts' -import { serve } from 'https://deno.land/std@0.168.0/http/server.ts' -import { CreateCompletionRequest } from 'https://esm.sh/openai@3.1.0' +import 'xhr_polyfill' +import { serve } from 'std/server' +import { CreateCompletionRequest } from 'openai' serve(async (req) => { const { query } = await req.json() diff --git a/examples/edge-functions/supabase/functions/opengraph/README.md b/examples/edge-functions/supabase/functions/opengraph/README.md index 9242524394e..866f222465a 100644 --- a/examples/edge-functions/supabase/functions/opengraph/README.md +++ b/examples/edge-functions/supabase/functions/opengraph/README.md @@ -8,7 +8,7 @@ Generate Open Graph images with Deno and Supabase Edge Functions, no framework n ## Run locally ```bash -supabase functions serve opengraph --no-verify-jwt +supabase functions serve --no-verify-jwt ``` Navigate to http://localhost:54321/functions/v1/opengraph diff --git a/examples/edge-functions/supabase/functions/opengraph/handler.tsx b/examples/edge-functions/supabase/functions/opengraph/handler.tsx index ef64dc4b8e9..d1bbcd5b2c2 100644 --- a/examples/edge-functions/supabase/functions/opengraph/handler.tsx +++ b/examples/edge-functions/supabase/functions/opengraph/handler.tsx @@ -1,5 +1,5 @@ -import React from 'https://esm.sh/react@18.2.0?deno-std=0.140.0' -import { ImageResponse } from 'https://deno.land/x/og_edge@0.0.4/mod.ts' +import React from 'React' +import { ImageResponse } from 'og_edge' export function handler(req: Request) { return new ImageResponse( diff --git a/examples/edge-functions/supabase/functions/opengraph/index.ts b/examples/edge-functions/supabase/functions/opengraph/index.ts index 5a7c90237cf..0a928de50a7 100644 --- a/examples/edge-functions/supabase/functions/opengraph/index.ts +++ b/examples/edge-functions/supabase/functions/opengraph/index.ts @@ -2,7 +2,7 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.140.0/http/server.ts' +import { serve } from 'std/server' import { handler } from './handler.tsx' diff --git a/examples/edge-functions/supabase/functions/postgres-on-the-edge/index.ts b/examples/edge-functions/supabase/functions/postgres-on-the-edge/index.ts index 6ce14f6990d..871d24679fe 100644 --- a/examples/edge-functions/supabase/functions/postgres-on-the-edge/index.ts +++ b/examples/edge-functions/supabase/functions/postgres-on-the-edge/index.ts @@ -1,5 +1,5 @@ -import * as postgres from 'https://deno.land/x/postgres@v0.14.2/mod.ts' -import { serve } from 'https://deno.land/std@0.168.0/http/server.ts' +import * as postgres from 'postgres' +import { serve } from 'std/server' // Get the connection string from the environment variable "DATABASE_URL" const databaseUrl = Deno.env.get('DATABASE_URL')! diff --git a/examples/edge-functions/supabase/functions/puppeteer/README.md b/examples/edge-functions/supabase/functions/puppeteer/README.md index 353df27fd05..57e99a74781 100644 --- a/examples/edge-functions/supabase/functions/puppeteer/README.md +++ b/examples/edge-functions/supabase/functions/puppeteer/README.md @@ -4,6 +4,14 @@ This example shows how you can use Puppeteer and a headless-browser to generate Since Edge Functions cannot run a Headless Browser instance due to resource constraints, you will need to use a hosted browser service like https://browserless.io. +## Develop locally + +```bash +supabase functions serve --env-file ./supabase/.env.local --no-verify-jwt +``` + +Navigate to http://localhost:54321/functions/v1/puppeteer + ## Deploy ```bash diff --git a/examples/edge-functions/supabase/functions/puppeteer/index.ts b/examples/edge-functions/supabase/functions/puppeteer/index.ts index 7eac140f29f..72efb56a723 100644 --- a/examples/edge-functions/supabase/functions/puppeteer/index.ts +++ b/examples/edge-functions/supabase/functions/puppeteer/index.ts @@ -1,11 +1,14 @@ -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' -import puppeteer from 'https://deno.land/x/puppeteer@16.2.0/mod.ts' +import { serve } from 'std/server' +import puppeteer from 'puppeteer' serve(async (req) => { try { + console.log(`wss://chrome.browserless.io?token=${Deno.env.get('PUPPETEER_BROWSERLESS_IO_KEY')}`) // Visit browserless.io to get your free API token const browser = await puppeteer.connect({ - browserWSEndpoint: 'wss://chrome.browserless.io?token=YOUR_API_TOKEN', + browserWSEndpoint: `wss://chrome.browserless.io?token=${Deno.env.get( + 'PUPPETEER_BROWSERLESS_IO_KEY' + )}`, }) const page = await browser.newPage() @@ -17,7 +20,7 @@ serve(async (req) => { return new Response(screenshot, { headers: { 'Content-Type': 'image/png' } }) } catch (e) { console.error(e) - return new Response(JSON.stringify(`Error occurred when generating the screenshot`), { + return new Response(JSON.stringify({ error: e.message }), { headers: { 'Content-Type': 'application/json' }, status: 500, }) diff --git a/examples/edge-functions/supabase/functions/read-storage/index.ts b/examples/edge-functions/supabase/functions/read-storage/index.ts index d7247b800dc..c32ccfd91bc 100644 --- a/examples/edge-functions/supabase/functions/read-storage/index.ts +++ b/examples/edge-functions/supabase/functions/read-storage/index.ts @@ -2,8 +2,8 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' -import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' +import { serve } from 'std/server' +import { createClient } from '@supabase/supabase-js' const corsHeaders = { 'Access-Control-Allow-Origin': '*', diff --git a/examples/edge-functions/supabase/functions/restful-tasks/index.ts b/examples/edge-functions/supabase/functions/restful-tasks/index.ts index 67c36ed0a98..eea5219a074 100644 --- a/examples/edge-functions/supabase/functions/restful-tasks/index.ts +++ b/examples/edge-functions/supabase/functions/restful-tasks/index.ts @@ -2,8 +2,8 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' -import { createClient, SupabaseClient } from 'https://esm.sh/@supabase/supabase-js@2' +import { serve } from 'std/server' +import { createClient, SupabaseClient } from '@supabase/supabase-js' const corsHeaders = { 'Access-Control-Allow-Origin': '*', diff --git a/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts b/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts index f9dedb16a7d..72b95575cb9 100644 --- a/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts +++ b/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts @@ -2,8 +2,8 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' -import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' +import { serve } from 'std/server' +import { createClient } from '@supabase/supabase-js' import { corsHeaders } from '../_shared/cors.ts' console.log(`Function "select-from-table-with-auth-rls" up and running!`) diff --git a/examples/edge-functions/supabase/functions/send-email-smtp/README.md b/examples/edge-functions/supabase/functions/send-email-smtp/README.md index 02e6d5a6b08..68b7dbad82b 100644 --- a/examples/edge-functions/supabase/functions/send-email-smtp/README.md +++ b/examples/edge-functions/supabase/functions/send-email-smtp/README.md @@ -13,4 +13,4 @@ Note: `SMTP_PORT` must be a port other than `25`, `465`, and `587` as Deno Deplo ## Test locally - `cp ./supabase/.env.local.example ./supabase/.env.local` -- `supabase functions serve send-email-smtp --env-file ./supabase/.env.local` \ No newline at end of file +- `supabase functions serve --env-file ./supabase/.env.local` diff --git a/examples/edge-functions/supabase/functions/send-email-smtp/index.ts b/examples/edge-functions/supabase/functions/send-email-smtp/index.ts index 4958b8fa153..d0abf117129 100644 --- a/examples/edge-functions/supabase/functions/send-email-smtp/index.ts +++ b/examples/edge-functions/supabase/functions/send-email-smtp/index.ts @@ -2,14 +2,14 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.131.0/http/server.ts' -import { SmtpClient } from 'https://deno.land/x/denomailer@0.12.0/mod.ts' +import { serve } from 'std/server' +import { SmtpClient } from 'denomailer' const smtp = new SmtpClient() console.log(`Function "send-email-smtp" up and running!`) -serve(async (req) => { +serve(async (_req) => { await smtp.connect({ hostname: Deno.env.get('SMTP_HOSTNAME')!, port: Number(Deno.env.get('SMTP_PORT')!), @@ -24,7 +24,7 @@ serve(async (req) => { subject: `Hello from Supabase Edge Functions`, content: `Hello Functions \o/`, }) - } catch (error: any) { + } catch (error) { return new Response(error.message, { status: 500 }) } @@ -41,7 +41,7 @@ serve(async (req) => { }) // To invoke: -// curl -i --location --request POST 'http://localhost:54321/functions/v1/' \ +// curl -i --location --request POST 'http://localhost:54321/functions/v1/send-email-smtp' \ // --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs' \ // --header 'Content-Type: application/json' \ // --data '{"name":"Functions"}' diff --git a/examples/edge-functions/supabase/functions/streams/README.md b/examples/edge-functions/supabase/functions/streams/README.md index 52cd230a364..1be0ec27b24 100644 --- a/examples/edge-functions/supabase/functions/streams/README.md +++ b/examples/edge-functions/supabase/functions/streams/README.md @@ -3,7 +3,7 @@ ## Run locally ```bash -supabase functions serve --no-verify-jwt streams +supabase functions serve --no-verify-jwt ``` Use cURL or Postman to make a GET request to http://localhost:54321/functions/v1/streams. diff --git a/examples/edge-functions/supabase/functions/streams/index.ts b/examples/edge-functions/supabase/functions/streams/index.ts index 15d3c2ace8e..dafbf83c7d7 100644 --- a/examples/edge-functions/supabase/functions/streams/index.ts +++ b/examples/edge-functions/supabase/functions/streams/index.ts @@ -1,4 +1,4 @@ -import { serve } from 'https://deno.land/std@0.168.0/http/server.ts' +import { serve } from 'std/server' const msg = new TextEncoder().encode('data: hello\r\n\r\n') diff --git a/examples/edge-functions/supabase/functions/stripe-webhooks/README.md b/examples/edge-functions/supabase/functions/stripe-webhooks/README.md index 2d5a7a24d5d..337352277fb 100644 --- a/examples/edge-functions/supabase/functions/stripe-webhooks/README.md +++ b/examples/edge-functions/supabase/functions/stripe-webhooks/README.md @@ -9,7 +9,7 @@ Also check out our full Stripe Payments examples for [React Native (Expo)](https ## Test locally - Terminal 1: - - `supabase functions serve --no-verify-jwt stripe-webhooks --env-file ./supabase/.env.local` + - `supabase functions serve --no-verify-jwt --env-file ./supabase/.env.local` - Terminal 2: - `stripe listen --forward-to localhost:54321/functions/v1/` - Terminal 3 (optional): diff --git a/examples/edge-functions/supabase/functions/stripe-webhooks/index.ts b/examples/edge-functions/supabase/functions/stripe-webhooks/index.ts index 6b159a2a5b4..a0bbb7dc958 100644 --- a/examples/edge-functions/supabase/functions/stripe-webhooks/index.ts +++ b/examples/edge-functions/supabase/functions/stripe-webhooks/index.ts @@ -2,20 +2,21 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.132.0/http/server.ts' +import { serve } from 'std/server' -// esm.sh is used to compile stripe-node to be compatible with ES modules. -import Stripe from 'https://esm.sh/stripe@10.13.0?target=deno&no-check&deno-std=0.132.0' +// Import via bare specifier thanks to the import_map.json file. +import Stripe from 'stripe' -const stripe = Stripe(Deno.env.get('STRIPE_API_KEY'), { +const stripe = new Stripe(Deno.env.get('STRIPE_API_KEY') as string, { // This is needed to use the Fetch API rather than relying on the Node http // package. + apiVersion: '2022-11-15', httpClient: Stripe.createFetchHttpClient(), }) // This is needed in order to use the Web Crypto API in Deno. const cryptoProvider = Stripe.createSubtleCryptoProvider() -console.log(`Function "stripe-webhooks" up and running!`) +console.log('Hello from Stripe Webhook!') serve(async (request) => { const signature = request.headers.get('Stripe-Signature') @@ -27,8 +28,8 @@ serve(async (request) => { try { receivedEvent = await stripe.webhooks.constructEventAsync( body, - signature, - Deno.env.get('STRIPE_WEBHOOK_SIGNING_SECRET'), + signature!, + Deno.env.get('STRIPE_WEBHOOK_SIGNING_SECRET')!, undefined, cryptoProvider ) @@ -36,25 +37,5 @@ serve(async (request) => { return new Response(err.message, { status: 400 }) } console.log(`🔔 Event received: ${receivedEvent.id}`) - - // Secondly, we use this event to query the Stripe API in order to avoid - // handling any forged event. If available, we use the idempotency key. - const requestOptions = - receivedEvent.request && receivedEvent.request.idempotency_key - ? { - idempotencyKey: receivedEvent.request.idempotency_key, - } - : {} - - let retrievedEvent - try { - retrievedEvent = await stripe.events.retrieve(receivedEvent.id, requestOptions) - } catch (err) { - return new Response(err.message, { status: 400 }) - } - - return new Response(JSON.stringify({ id: retrievedEvent.id, status: 'ok' }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }) + return new Response(JSON.stringify({ ok: true }), { status: 200 }) }) diff --git a/examples/edge-functions/supabase/functions/telegram-bot/index.ts b/examples/edge-functions/supabase/functions/telegram-bot/index.ts index eab5aed9fd6..ecaa9916327 100644 --- a/examples/edge-functions/supabase/functions/telegram-bot/index.ts +++ b/examples/edge-functions/supabase/functions/telegram-bot/index.ts @@ -2,34 +2,28 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from "https://deno.land/std@0.131.0/http/server.ts" +import { serve } from 'std/server' console.log(`Function "telegram-bot" up and running!`) -import { Bot, webhookCallback } from "https://deno.land/x/grammy@v1.8.3/mod.ts"; +import { Bot, webhookCallback } from 'grammy' -const bot = new Bot(Deno.env.get('TELEGRAM_BOT_TOKEN') || ''); +const bot = new Bot(Deno.env.get('TELEGRAM_BOT_TOKEN') || '') -bot.command("start", (ctx) => ctx.reply("Welcome! Up and running.")); +bot.command('start', (ctx) => ctx.reply('Welcome! Up and running.')) bot.command('ping', (ctx) => ctx.reply(`Pong! ${new Date()} ${Date.now()}`)) -const handleUpdate = webhookCallback(bot, "std/http"); +const handleUpdate = webhookCallback(bot, 'std/http') serve(async (req) => { try { - const url = new URL(req.url); - if (url.searchParams.get('secret') !== Deno.env.get('FUNCTION_SECRET')) + const url = new URL(req.url) + if (url.searchParams.get('secret') !== Deno.env.get('FUNCTION_SECRET')) return new Response('not allowed', { status: 405 }) - return await handleUpdate(req); + return await handleUpdate(req) } catch (err) { - console.error(err); + console.error(err) } }) - -// To invoke: -// curl -i --location --request POST 'http://localhost:54321/functions/v1/' \ -// --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs' \ -// --header 'Content-Type: application/json' \ -// --data '{"name":"Functions"}' diff --git a/examples/edge-functions/supabase/functions/upstash-redis-counter/.env.example b/examples/edge-functions/supabase/functions/upstash-redis-counter/.env.example deleted file mode 100644 index d0785c19978..00000000000 --- a/examples/edge-functions/supabase/functions/upstash-redis-counter/.env.example +++ /dev/null @@ -1,2 +0,0 @@ -UPSTASH_REDIS_REST_URL= -UPSTASH_REDIS_REST_TOKEN= \ No newline at end of file diff --git a/examples/edge-functions/supabase/functions/upstash-redis-counter/README.md b/examples/edge-functions/supabase/functions/upstash-redis-counter/README.md index 3d33a9e7dd7..dd854b5a07b 100644 --- a/examples/edge-functions/supabase/functions/upstash-redis-counter/README.md +++ b/examples/edge-functions/supabase/functions/upstash-redis-counter/README.md @@ -9,7 +9,7 @@ Create a Redis database using the [Upstash Console](https://console.upstash.com/ Select the `Global` type to minimize the latency from all edge locations. Copy the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` to your .env file. You'll find them under **Details > REST API > .env**. ```bash -cp supabase/functions/upstash-redis-counter/.env.example supabase/functions/upstash-redis-counter/.env +cp supabase/.env.local.example supabase/.env.local ``` ## Run locally @@ -18,7 +18,7 @@ Make sure you have the latest version of the [Supabase CLI installed](https://su ```bash supabase start -supabase functions serve upstash-redis-counter --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env +supabase functions serve --no-verify-jwt --env-file supabase/.env.local ``` Navigate to http://localhost:54321/functions/v1/upstash-redis-counter. @@ -27,5 +27,5 @@ Navigate to http://localhost:54321/functions/v1/upstash-redis-counter. ```bash supabase functions deploy upstash-redis-counter --no-verify-jwt -supabase secrets set --env-file supabase/functions/upstash-redis-counter/.env +supabase secrets set --env-file supabase/.env.local ``` diff --git a/examples/edge-functions/supabase/functions/upstash-redis-counter/index.ts b/examples/edge-functions/supabase/functions/upstash-redis-counter/index.ts index 911424209c9..bf630d0287f 100644 --- a/examples/edge-functions/supabase/functions/upstash-redis-counter/index.ts +++ b/examples/edge-functions/supabase/functions/upstash-redis-counter/index.ts @@ -2,8 +2,8 @@ // https://deno.land/manual/getting_started/setup_your_environment // This enables autocomplete, go to definition, etc. -import { serve } from 'https://deno.land/std@0.177.0/http/server.ts' -import { Redis } from 'https://deno.land/x/upstash_redis@v1.19.3/mod.ts' +import { serve } from 'std/server' +import { Redis } from 'upstash_redis' console.log(`Function "upstash-redis-counter" up and running!`) diff --git a/examples/user-management/sveltekit-user-management/src/app.html b/examples/user-management/sveltekit-user-management/src/app.html index b555f2469a3..8ce87909fb7 100644 --- a/examples/user-management/sveltekit-user-management/src/app.html +++ b/examples/user-management/sveltekit-user-management/src/app.html @@ -3,7 +3,7 @@ - + %sveltekit.head% diff --git a/package-lock.json b/package-lock.json index ad7da916061..d2bc8fa6836 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,6 +5,7 @@ "requires": true, "packages": { "": { + "name": "supabase", "version": "0.0.0", "license": "Apache-2.0", "workspaces": [ @@ -3171,6 +3172,37 @@ "react": "^16.8.3 || ^17 || ^18" } }, + "node_modules/@codemirror/language": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.0.0.tgz", + "integrity": "sha512-rtjk5ifyMzOna1c7PBu7J1VCt0PvA5wy3o8eMVnxMKb7z8KA7JFecvD04dSn14vj/bBaAbqRsGed5OjtofEnLA==", + "peer": true, + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/common": "^1.0.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0", + "style-mod": "^4.0.0" + } + }, + "node_modules/@codemirror/state": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.2.0.tgz", + "integrity": "sha512-69QXtcrsc3RYtOtd+GsvczJ319udtBf1PTrr2KbLWM/e2CXUPnh0Nz9AUo8WfhSQ7GeL8dPVNUmhQVgpmuaNGA==", + "peer": true + }, + "node_modules/@codemirror/view": { + "version": "6.9.0", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.9.0.tgz", + "integrity": "sha512-uFaqE6fBOp0Dj/tmWoe/TFlSSIPdpAzhvATgbq1eAKRkgq3hY79FioZ7nfdiT+24kz68AIWuSZ9hi3psKe36WQ==", + "peer": true, + "dependencies": { + "@codemirror/state": "^6.1.4", + "style-mod": "^4.0.0", + "w3c-keyname": "^2.2.4" + } + }, "node_modules/@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -3501,6 +3533,66 @@ "integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==", "dev": true }, + "node_modules/@graphiql/react": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@graphiql/react/-/react-0.15.0.tgz", + "integrity": "sha512-kJqkdf6d4Cck05Wt5yCDZXWfs7HZgcpuoWq/v8nOa698qVaNMM3qdG4CpRsZEexku0DSSJzWWuanxd5x+sRcFg==", + "dependencies": { + "@graphiql/toolkit": "^0.8.0", + "@reach/combobox": "^0.17.0", + "@reach/dialog": "^0.17.0", + "@reach/listbox": "^0.17.0", + "@reach/menu-button": "^0.17.0", + "@reach/tooltip": "^0.17.0", + "@reach/visually-hidden": "^0.17.0", + "codemirror": "^5.65.3", + "codemirror-graphql": "^2.0.2", + "copy-to-clipboard": "^3.2.0", + "graphql-language-service": "^5.1.0", + "markdown-it": "^12.2.0", + "set-value": "^4.1.0" + }, + "peerDependencies": { + "graphql": "^15.5.0 || ^16.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/@graphiql/react/node_modules/set-value": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-4.1.0.tgz", + "integrity": "sha512-zTEg4HL0RwVrqcWs3ztF+x1vkxfm0lP+MQQFPiMJTKVceBwEV0A569Ou8l9IYQG8jOZdMVI1hGsc0tmeD2o/Lw==", + "funding": [ + "https://github.com/sponsors/jonschlinkert", + "https://paypal.me/jonathanschlinkert", + "https://jonschlinkert.dev/sponsor" + ], + "dependencies": { + "is-plain-object": "^2.0.4", + "is-primitive": "^3.0.1" + }, + "engines": { + "node": ">=11.0" + } + }, + "node_modules/@graphiql/toolkit": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@graphiql/toolkit/-/toolkit-0.8.0.tgz", + "integrity": "sha512-DbMFhEKejpPzB6k8W3Mj+Rl8geXiw49USDF9Wdi06EEk1XLVh1iebDqveYY+4lViITsV4+BeGikxlqi8umfP4g==", + "dependencies": { + "@n1ru4l/push-pull-async-iterable-iterator": "^3.1.0", + "meros": "^1.1.4" + }, + "peerDependencies": { + "graphql": "^15.5.0 || ^16.0.0", + "graphql-ws": ">= 4.5.0" + }, + "peerDependenciesMeta": { + "graphql-ws": { + "optional": true + } + } + }, "node_modules/@hcaptcha/react-hcaptcha": { "version": "1.4.4", "resolved": "https://registry.npmjs.org/@hcaptcha/react-hcaptcha/-/react-hcaptcha-1.4.4.tgz", @@ -4500,6 +4592,30 @@ "@jridgewell/sourcemap-codec": "1.4.14" } }, + "node_modules/@lezer/common": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.0.2.tgz", + "integrity": "sha512-SVgiGtMnMnW3ActR8SXgsDhw7a0w0ChHSYAyAUxxrOiJ1OqYWEKk/xJd84tTSPo1mo6DXLObAJALNnd0Hrv7Ng==", + "peer": true + }, + "node_modules/@lezer/highlight": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.1.3.tgz", + "integrity": "sha512-3vLKLPThO4td43lYRBygmMY18JN3CPh9w+XS2j8WC30vR4yZeFG4z1iFe4jXE43NtGqe//zHW5q8ENLlHvz9gw==", + "peer": true, + "dependencies": { + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@lezer/lr": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.3.3.tgz", + "integrity": "sha512-JPQe3mwJlzEVqy67iQiiGozhcngbO8QBgpqZM6oL1Wj/dXckrEexpBLeFkq0edtW5IqnPRFxA24BHJni8Js69w==", + "peer": true, + "dependencies": { + "@lezer/common": "^1.0.0" + } + }, "node_modules/@mapbox/node-pre-gyp": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.10.tgz", @@ -4980,6 +5096,14 @@ "integrity": "sha512-Iozmtbqv0noj0uDDqoL0zNq0VBEfK2YFoMAZoxJe4cwphvLR+JskfF30QhXHOR4m3KrE6NLRYw+U9MRXvifyig==", "dev": true }, + "node_modules/@n1ru4l/push-pull-async-iterable-iterator": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@n1ru4l/push-pull-async-iterable-iterator/-/push-pull-async-iterable-iterator-3.2.0.tgz", + "integrity": "sha512-3fkKj25kEjsfObL6IlKPAlHYPq/oYwUkkQ03zsTTiDjD7vg/RxjdiLeCydqtxHZP0JgsXL3D/X5oAkMGzuUp/Q==", + "engines": { + "node": ">=12" + } + }, "node_modules/@next/bundle-analyzer": { "version": "13.0.5", "resolved": "https://registry.npmjs.org/@next/bundle-analyzer/-/bundle-analyzer-13.0.5.tgz", @@ -7196,6 +7320,229 @@ "@babel/runtime": "^7.13.10" } }, + "node_modules/@reach/auto-id": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/auto-id/-/auto-id-0.17.0.tgz", + "integrity": "sha512-ud8iPwF52RVzEmkHq1twuqGuPA+moreumUHdtgvU3sr3/15BNhwp3KyDLrKKSz0LP1r3V4pSdyF9MbYM8BoSjA==", + "dependencies": { + "@reach/utils": "0.17.0", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/combobox": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/combobox/-/combobox-0.17.0.tgz", + "integrity": "sha512-2mYvU5agOBCQBMdlM4cri+P1BbNwp05P1OuDyc33xJSNiBG7BMy4+ZSHJ0X4fyle6rHwSgCAOCLOeWV1XUYjoQ==", + "dependencies": { + "@reach/auto-id": "0.17.0", + "@reach/descendants": "0.17.0", + "@reach/popover": "0.17.0", + "@reach/portal": "0.17.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/descendants": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/descendants/-/descendants-0.17.0.tgz", + "integrity": "sha512-c7lUaBfjgcmKFZiAWqhG+VnXDMEhPkI4kAav/82XKZD6NVvFjsQOTH+v3tUkskrAPV44Yuch0mFW/u5Ntifr7Q==", + "dependencies": { + "@reach/utils": "0.17.0", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/dialog": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/dialog/-/dialog-0.17.0.tgz", + "integrity": "sha512-AnfKXugqDTGbeG3c8xDcrQDE4h9b/vnc27Sa118oQSquz52fneUeX9MeFb5ZEiBJK8T5NJpv7QUTBIKnFCAH5A==", + "dependencies": { + "@reach/portal": "0.17.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2", + "react-focus-lock": "^2.5.2", + "react-remove-scroll": "^2.4.3", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/dropdown": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/dropdown/-/dropdown-0.17.0.tgz", + "integrity": "sha512-qBTIGInhxtPHtdj4Pl2XZgZMz3e37liydh0xR3qc48syu7g71sL4nqyKjOzThykyfhA3Pb3/wFgsFJKGTSdaig==", + "dependencies": { + "@reach/auto-id": "0.17.0", + "@reach/descendants": "0.17.0", + "@reach/popover": "0.17.0", + "@reach/utils": "0.17.0", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/listbox": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/listbox/-/listbox-0.17.0.tgz", + "integrity": "sha512-AMnH1P6/3VKy2V/nPb4Es441arYR+t4YRdh9jdcFVrCOD6y7CQrlmxsYjeg9Ocdz08XpdoEBHM3PKLJqNAUr7A==", + "dependencies": { + "@reach/auto-id": "0.17.0", + "@reach/descendants": "0.17.0", + "@reach/machine": "0.17.0", + "@reach/popover": "0.17.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/machine": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/machine/-/machine-0.17.0.tgz", + "integrity": "sha512-9EHnuPgXzkbRENvRUzJvVvYt+C2jp7PGN0xon7ffmKoK8rTO6eA/bb7P0xgloyDDQtu88TBUXKzW0uASqhTXGA==", + "dependencies": { + "@reach/utils": "0.17.0", + "@xstate/fsm": "1.4.0", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/menu-button": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/menu-button/-/menu-button-0.17.0.tgz", + "integrity": "sha512-YyuYVyMZKamPtivoEI6D0UEILYH3qZtg4kJzEAuzPmoR/aHN66NZO75Fx0gtjG1S6fZfbiARaCOZJC0VEiDOtQ==", + "dependencies": { + "@reach/dropdown": "0.17.0", + "@reach/popover": "0.17.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x", + "react-is": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/observe-rect": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@reach/observe-rect/-/observe-rect-1.2.0.tgz", + "integrity": "sha512-Ba7HmkFgfQxZqqaeIWWkNK0rEhpxVQHIoVyW1YDSkGsGIXzcaW4deC8B0pZrNSSyLTdIk7y+5olKt5+g0GmFIQ==" + }, + "node_modules/@reach/popover": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/popover/-/popover-0.17.0.tgz", + "integrity": "sha512-yYbBF4fMz4Ml4LB3agobZjcZ/oPtPsNv70ZAd7lEC2h7cvhF453pA+zOBGYTPGupKaeBvgAnrMjj7RnxDU5hoQ==", + "dependencies": { + "@reach/portal": "0.17.0", + "@reach/rect": "0.17.0", + "@reach/utils": "0.17.0", + "tabbable": "^4.0.0", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/portal": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/portal/-/portal-0.17.0.tgz", + "integrity": "sha512-+IxsgVycOj+WOeNPL2NdgooUdHPSY285wCtj/iWID6akyr4FgGUK7sMhRM9aGFyrGpx2vzr+eggbUmAVZwOz+A==", + "dependencies": { + "@reach/utils": "0.17.0", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/rect": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/rect/-/rect-0.17.0.tgz", + "integrity": "sha512-3YB7KA5cLjbLc20bmPkJ06DIfXSK06Cb5BbD2dHgKXjUkT9WjZaLYIbYCO8dVjwcyO3GCNfOmPxy62VsPmZwYA==", + "dependencies": { + "@reach/observe-rect": "1.2.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/tooltip": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/tooltip/-/tooltip-0.17.0.tgz", + "integrity": "sha512-HP8Blordzqb/Cxg+jnhGmWQfKgypamcYLBPlcx6jconyV5iLJ5m93qipr1giK7MqKT2wlsKWy44ZcOrJ+Wrf8w==", + "dependencies": { + "@reach/auto-id": "0.17.0", + "@reach/portal": "0.17.0", + "@reach/rect": "0.17.0", + "@reach/utils": "0.17.0", + "@reach/visually-hidden": "0.17.0", + "prop-types": "^15.7.2", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/utils": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/utils/-/utils-0.17.0.tgz", + "integrity": "sha512-M5y8fCBbrWeIsxedgcSw6oDlAMQDkl5uv3VnMVJ7guwpf4E48Xlh1v66z/1BgN/WYe2y8mB/ilFD2nysEfdGeA==", + "dependencies": { + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, + "node_modules/@reach/visually-hidden": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/visually-hidden/-/visually-hidden-0.17.0.tgz", + "integrity": "sha512-T6xF3Nv8vVnjVkGU6cm0+kWtvliLqPAo8PcZ+WxkKacZsaHTjaZb4v1PaCcyQHmuTNT/vtTVNOJLG0SjQOIb7g==", + "dependencies": { + "prop-types": "^15.7.2", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "react": "^16.8.0 || 17.x", + "react-dom": "^16.8.0 || 17.x" + } + }, "node_modules/@react-dnd/asap": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@react-dnd/asap/-/asap-4.0.1.tgz", @@ -11362,6 +11709,11 @@ "@xtuc/long": "4.2.2" } }, + "node_modules/@xstate/fsm": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@xstate/fsm/-/fsm-1.4.0.tgz", + "integrity": "sha512-uTHDeu2xI5E1IFwf37JFQM31RrH7mY7877RqPBS4ZqSNUwoLDuct8AhBWaXGnVizBAYyimVwgCyGa9z/NiRhXA==" + }, "node_modules/@xtuc/ieee754": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", @@ -13905,6 +14257,24 @@ "node": ">=0.10.0" } }, + "node_modules/codemirror": { + "version": "5.65.11", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.65.11.tgz", + "integrity": "sha512-Gp62g2eKSCHYt10axmGhKq3WoJSvVpvhXmowNq7pZdRVowwtvBR/hi2LSP5srtctKkRT33T6/n8Kv1UGp7JW4A==" + }, + "node_modules/codemirror-graphql": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/codemirror-graphql/-/codemirror-graphql-2.0.3.tgz", + "integrity": "sha512-T58f+XQVKE6/6goAADJfu56wPRcdF2RUZMHITUol6h6Uo1KKUmknV4muKNFOl6GM15BjBraysF6HATp4oY6kyA==", + "dependencies": { + "graphql-language-service": "5.1.1" + }, + "peerDependencies": { + "@codemirror/language": "6.0.0", + "codemirror": "^5.65.3", + "graphql": "^15.5.0 || ^16.0.0" + } + }, "node_modules/coffee-script": { "version": "1.12.7", "resolved": "https://registry.npmjs.org/coffee-script/-/coffee-script-1.12.7.tgz", @@ -16586,7 +16956,6 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", - "dev": true, "funding": { "url": "https://github.com/fb55/entities?sponsor=1" } @@ -19489,6 +19858,23 @@ "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", "dev": true }, + "node_modules/graphiql": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/graphiql/-/graphiql-2.2.0.tgz", + "integrity": "sha512-w1ujpCKMlkwkoUjeg0HpRiBBTm1WHAjHNkFv1TbMu6trjzz63mQ48GLZlmyQY1yhwmc+diCcvmmAt+AyvKLWWA==", + "dependencies": { + "@graphiql/react": "^0.15.0", + "@graphiql/toolkit": "^0.8.0", + "entities": "^2.0.0", + "graphql-language-service": "^5.1.0", + "markdown-it": "^12.2.0" + }, + "peerDependencies": { + "graphql": "^15.5.0 || ^16.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, "node_modules/graphlib": { "version": "2.1.8", "resolved": "https://registry.npmjs.org/graphlib/-/graphlib-2.1.8.tgz", @@ -19497,6 +19883,40 @@ "lodash": "^4.17.15" } }, + "node_modules/graphql": { + "version": "16.6.0", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.6.0.tgz", + "integrity": "sha512-KPIBPDlW7NxrbT/eh4qPXz5FiFdL5UbaA0XUNz2Rp3Z3hqBSkbj0GVjwFDztsWVauZUWsbKHgMg++sk8UX0bkw==", + "engines": { + "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" + } + }, + "node_modules/graphql-language-service": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/graphql-language-service/-/graphql-language-service-5.1.1.tgz", + "integrity": "sha512-gpaDT9E3+3eWhoqO4C81CGhkzr7Vp2jH/eq+ykoUbgfvMEpqhGTfCeNmrf+S4K/+4WTkAAJBsYT0/ZPZkqe/Hg==", + "dependencies": { + "nullthrows": "^1.0.0", + "vscode-languageserver-types": "^3.17.1" + }, + "bin": { + "graphql": "dist/temp-bin.js" + }, + "peerDependencies": { + "graphql": "^15.5.0 || ^16.0.0" + } + }, + "node_modules/graphql-ws": { + "version": "5.11.3", + "resolved": "https://registry.npmjs.org/graphql-ws/-/graphql-ws-5.11.3.tgz", + "integrity": "sha512-fU8zwSgAX2noXAsuFiCZ8BtXeXZOzXyK5u1LloCdacsVth4skdBMPO74EG51lBoWSIZ8beUocdpV8+cQHBODnQ==", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "graphql": ">=0.11 <=16" + } + }, "node_modules/gray-matter": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz", @@ -21183,6 +21603,14 @@ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", "dev": true }, + "node_modules/is-primitive": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-3.0.1.tgz", + "integrity": "sha512-GljRxhWvlCNRfZyORiH77FwdFwGcMO620o37EOYC0ORWdq+WYNVqW0w2Juzew4M+L81l6/QS3t5gkkihyRqv9w==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/is-reference": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.0.tgz", @@ -23771,6 +24199,14 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "devOptional": true }, + "node_modules/linkify-it": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.3.tgz", + "integrity": "sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==", + "dependencies": { + "uc.micro": "^1.0.1" + } + }, "node_modules/list-item": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/list-item/-/list-item-1.1.1.tgz", @@ -24166,6 +24602,29 @@ "node": ">=0.10.0" } }, + "node_modules/markdown-it": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.3.2.tgz", + "integrity": "sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg==", + "dependencies": { + "argparse": "^2.0.1", + "entities": "~2.1.0", + "linkify-it": "^3.0.1", + "mdurl": "^1.0.1", + "uc.micro": "^1.0.5" + }, + "bin": { + "markdown-it": "bin/markdown-it.js" + } + }, + "node_modules/markdown-it/node_modules/entities": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.1.0.tgz", + "integrity": "sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w==", + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/markdown-link": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/markdown-link/-/markdown-link-0.1.1.tgz", @@ -25125,6 +25584,22 @@ "uuid": "dist/bin/uuid" } }, + "node_modules/meros": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/meros/-/meros-1.2.1.tgz", + "integrity": "sha512-R2f/jxYqCAGI19KhAvaxSOxALBMkaXWH2a7rOyqQw+ZmizX5bKkEYWLzdhC+U82ZVVPVp6MCXe3EkVligh+12g==", + "engines": { + "node": ">=13" + }, + "peerDependencies": { + "@types/node": ">=13" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, "node_modules/methods": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", @@ -27361,6 +27836,11 @@ "url": "https://github.com/fb55/nth-check?sponsor=1" } }, + "node_modules/nullthrows": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/nullthrows/-/nullthrows-1.1.1.tgz", + "integrity": "sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw==" + }, "node_modules/num2fraction": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/num2fraction/-/num2fraction-1.2.2.tgz", @@ -30848,6 +31328,17 @@ "react-dom": "^16.8.5 || ^17.0.0 || ^18.0.0" } }, + "node_modules/react-clientside-effect": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/react-clientside-effect/-/react-clientside-effect-1.2.6.tgz", + "integrity": "sha512-XGGGRQAKY+q25Lz9a/4EPqom7WRjz3z9R2k4jhVKA/puQFH/5Nt27vFZYql4m4NVNdUvX8PS3O7r/Zzm7cjUlg==", + "dependencies": { + "@babel/runtime": "^7.12.13" + }, + "peerDependencies": { + "react": "^15.3.0 || ^16.0.0 || ^17.0.0 || ^18.0.0" + } + }, "node_modules/react-contexify": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/react-contexify/-/react-contexify-5.0.0.tgz", @@ -31089,6 +31580,39 @@ "react": ">=16.8.6" } }, + "node_modules/react-focus-lock": { + "version": "2.9.3", + "resolved": "https://registry.npmjs.org/react-focus-lock/-/react-focus-lock-2.9.3.tgz", + "integrity": "sha512-cGNkz9p5Fpqio6hBHlkKxzRYrBYtcPosFOL6Q3N/LSbHjwP/PTBqHpvbgaOYoE7rWfzw8qXPKTB3Tk/VPgw4NQ==", + "dependencies": { + "@babel/runtime": "^7.0.0", + "focus-lock": "^0.11.5", + "prop-types": "^15.6.2", + "react-clientside-effect": "^1.2.6", + "use-callback-ref": "^1.3.0", + "use-sidecar": "^1.1.2" + }, + "peerDependencies": { + "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-focus-lock/node_modules/focus-lock": { + "version": "0.11.5", + "resolved": "https://registry.npmjs.org/focus-lock/-/focus-lock-0.11.5.tgz", + "integrity": "sha512-1mTr6pl9HBpJ8CqY7hRc38MCrcuTZIeYAkBD1gBTzbx5/to+bRBaBYtJ68iDq7ryTzAAbKrG3dVKjkrWTaaEaw==", + "dependencies": { + "tslib": "^2.0.3" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/react-from-dom": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/react-from-dom/-/react-from-dom-0.6.2.tgz", @@ -34964,6 +35488,12 @@ "url": "https://opencollective.com/webpack" } }, + "node_modules/style-mod": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.0.0.tgz", + "integrity": "sha512-OPhtyEjyyN9x3nhPsu76f52yUGXiZcgvsrFVtvTkyGRQJ0XK+GPc6ov1z+lRpbeabka+MYEQxOYRnt5nF30aMw==", + "peer": true + }, "node_modules/style-to-object": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-0.3.0.tgz", @@ -35110,6 +35640,11 @@ "integrity": "sha512-qImOD23aDfnIDNqlG1NOehdB9IYsn1V9oByPjKY1nakv2MQYCEMyX033/q+aEtYCpmYK1cv2+NTmlH+ra6GA5A==", "dev": true }, + "node_modules/tabbable": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-4.0.0.tgz", + "integrity": "sha512-H1XoH1URcBOa/rZZWxLxHCtOdVUEev+9vo5YdYhC9tCY4wnybX+VQrCYuy9ubkg69fCBxCONJOSLGfw0DWMffQ==" + }, "node_modules/table": { "version": "6.8.1", "resolved": "https://registry.npmjs.org/table/-/table-6.8.1.tgz", @@ -36169,6 +36704,11 @@ "node": ">=4.2.0" } }, + "node_modules/uc.micro": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", + "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==" + }, "node_modules/uglify-js": { "version": "3.17.4", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.17.4.tgz", @@ -37180,6 +37720,11 @@ "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", "integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==" }, + "node_modules/vscode-languageserver-types": { + "version": "3.17.3", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.3.tgz", + "integrity": "sha512-SYU4z1dL0PyIMd4Vj8YOqFvHu7Hz/enbWtpfnVbJHU4Nd1YNYx8u0ennumc6h48GQNeOLxmwySmnADouT/AuZA==" + }, "node_modules/vscode-oniguruma": { "version": "1.6.2", "resolved": "https://registry.npmjs.org/vscode-oniguruma/-/vscode-oniguruma-1.6.2.tgz", @@ -37200,6 +37745,12 @@ "browser-process-hrtime": "^1.0.0" } }, + "node_modules/w3c-keyname": { + "version": "2.2.6", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.6.tgz", + "integrity": "sha512-f+fciywl1SJEniZHD6H+kUO8gOnwIr7f4ijKA6+ZvJFjeGi1r4PDLl53Ayud9O/rk64RqgoQine0feoeOU0kXg==", + "peer": true + }, "node_modules/w3c-xmlserializer": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz", @@ -38875,6 +39426,8 @@ "studio": { "version": "0.0.9", "dependencies": { + "@graphiql/react": "^0.15.0", + "@graphiql/toolkit": "^0.8.0", "@hcaptcha/react-hcaptcha": "^1.4.4", "@headlessui/react": "^1.4.1", "@monaco-editor/react": "^4.3.1", @@ -38897,12 +39450,16 @@ "awesome-debounce-promise": "^2.1.0", "blueimp-md5": "^2.19.0", "clipboard": "^2.0.8", + "clsx": "^1.2.1", "common": "*", "config": "*", "configcat-js": "^7.0.0", "dayjs": "^1.11.0", "file-saver": "^2.0.5", "generate-password": "^1.7.0", + "graphiql": "^2.2.0", + "graphql": "^16.6.0", + "graphql-ws": "^5.11.3", "html-to-image": "^1.10.8", "immutability-helper": "^3.1.1", "ip-address": "^8.1.0", @@ -39164,6 +39721,14 @@ "postcss": "^8.1.0" } }, + "studio/node_modules/clsx": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz", + "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==", + "engines": { + "node": ">=6" + } + }, "studio/node_modules/configcat-common": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/configcat-common/-/configcat-common-7.0.1.tgz", @@ -41002,6 +41567,37 @@ "unist-util-visit-parents": "^3.0.0" } }, + "@codemirror/language": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.0.0.tgz", + "integrity": "sha512-rtjk5ifyMzOna1c7PBu7J1VCt0PvA5wy3o8eMVnxMKb7z8KA7JFecvD04dSn14vj/bBaAbqRsGed5OjtofEnLA==", + "peer": true, + "requires": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/common": "^1.0.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0", + "style-mod": "^4.0.0" + } + }, + "@codemirror/state": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.2.0.tgz", + "integrity": "sha512-69QXtcrsc3RYtOtd+GsvczJ319udtBf1PTrr2KbLWM/e2CXUPnh0Nz9AUo8WfhSQ7GeL8dPVNUmhQVgpmuaNGA==", + "peer": true + }, + "@codemirror/view": { + "version": "6.9.0", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.9.0.tgz", + "integrity": "sha512-uFaqE6fBOp0Dj/tmWoe/TFlSSIPdpAzhvATgbq1eAKRkgq3hY79FioZ7nfdiT+24kz68AIWuSZ9hi3psKe36WQ==", + "peer": true, + "requires": { + "@codemirror/state": "^6.1.4", + "style-mod": "^4.0.0", + "w3c-keyname": "^2.2.4" + } + }, "@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -41268,6 +41864,46 @@ "integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==", "dev": true }, + "@graphiql/react": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@graphiql/react/-/react-0.15.0.tgz", + "integrity": "sha512-kJqkdf6d4Cck05Wt5yCDZXWfs7HZgcpuoWq/v8nOa698qVaNMM3qdG4CpRsZEexku0DSSJzWWuanxd5x+sRcFg==", + "requires": { + "@graphiql/toolkit": "^0.8.0", + "@reach/combobox": "^0.17.0", + "@reach/dialog": "^0.17.0", + "@reach/listbox": "^0.17.0", + "@reach/menu-button": "^0.17.0", + "@reach/tooltip": "^0.17.0", + "@reach/visually-hidden": "^0.17.0", + "codemirror": "^5.65.3", + "codemirror-graphql": "^2.0.2", + "copy-to-clipboard": "^3.2.0", + "graphql-language-service": "^5.1.0", + "markdown-it": "^12.2.0", + "set-value": "^4.1.0" + }, + "dependencies": { + "set-value": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-4.1.0.tgz", + "integrity": "sha512-zTEg4HL0RwVrqcWs3ztF+x1vkxfm0lP+MQQFPiMJTKVceBwEV0A569Ou8l9IYQG8jOZdMVI1hGsc0tmeD2o/Lw==", + "requires": { + "is-plain-object": "^2.0.4", + "is-primitive": "^3.0.1" + } + } + } + }, + "@graphiql/toolkit": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@graphiql/toolkit/-/toolkit-0.8.0.tgz", + "integrity": "sha512-DbMFhEKejpPzB6k8W3Mj+Rl8geXiw49USDF9Wdi06EEk1XLVh1iebDqveYY+4lViITsV4+BeGikxlqi8umfP4g==", + "requires": { + "@n1ru4l/push-pull-async-iterable-iterator": "^3.1.0", + "meros": "^1.1.4" + } + }, "@hcaptcha/react-hcaptcha": { "version": "1.4.4", "resolved": "https://registry.npmjs.org/@hcaptcha/react-hcaptcha/-/react-hcaptcha-1.4.4.tgz", @@ -42089,6 +42725,30 @@ "@jridgewell/sourcemap-codec": "1.4.14" } }, + "@lezer/common": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.0.2.tgz", + "integrity": "sha512-SVgiGtMnMnW3ActR8SXgsDhw7a0w0ChHSYAyAUxxrOiJ1OqYWEKk/xJd84tTSPo1mo6DXLObAJALNnd0Hrv7Ng==", + "peer": true + }, + "@lezer/highlight": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.1.3.tgz", + "integrity": "sha512-3vLKLPThO4td43lYRBygmMY18JN3CPh9w+XS2j8WC30vR4yZeFG4z1iFe4jXE43NtGqe//zHW5q8ENLlHvz9gw==", + "peer": true, + "requires": { + "@lezer/common": "^1.0.0" + } + }, + "@lezer/lr": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.3.3.tgz", + "integrity": "sha512-JPQe3mwJlzEVqy67iQiiGozhcngbO8QBgpqZM6oL1Wj/dXckrEexpBLeFkq0edtW5IqnPRFxA24BHJni8Js69w==", + "peer": true, + "requires": { + "@lezer/common": "^1.0.0" + } + }, "@mapbox/node-pre-gyp": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.10.tgz", @@ -42423,6 +43083,11 @@ } } }, + "@n1ru4l/push-pull-async-iterable-iterator": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@n1ru4l/push-pull-async-iterable-iterator/-/push-pull-async-iterable-iterator-3.2.0.tgz", + "integrity": "sha512-3fkKj25kEjsfObL6IlKPAlHYPq/oYwUkkQ03zsTTiDjD7vg/RxjdiLeCydqtxHZP0JgsXL3D/X5oAkMGzuUp/Q==" + }, "@next/bundle-analyzer": { "version": "13.0.5", "resolved": "https://registry.npmjs.org/@next/bundle-analyzer/-/bundle-analyzer-13.0.5.tgz", @@ -44135,6 +44800,172 @@ "@babel/runtime": "^7.13.10" } }, + "@reach/auto-id": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/auto-id/-/auto-id-0.17.0.tgz", + "integrity": "sha512-ud8iPwF52RVzEmkHq1twuqGuPA+moreumUHdtgvU3sr3/15BNhwp3KyDLrKKSz0LP1r3V4pSdyF9MbYM8BoSjA==", + "requires": { + "@reach/utils": "0.17.0", + "tslib": "^2.3.0" + } + }, + "@reach/combobox": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/combobox/-/combobox-0.17.0.tgz", + "integrity": "sha512-2mYvU5agOBCQBMdlM4cri+P1BbNwp05P1OuDyc33xJSNiBG7BMy4+ZSHJ0X4fyle6rHwSgCAOCLOeWV1XUYjoQ==", + "requires": { + "@reach/auto-id": "0.17.0", + "@reach/descendants": "0.17.0", + "@reach/popover": "0.17.0", + "@reach/portal": "0.17.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + } + }, + "@reach/descendants": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/descendants/-/descendants-0.17.0.tgz", + "integrity": "sha512-c7lUaBfjgcmKFZiAWqhG+VnXDMEhPkI4kAav/82XKZD6NVvFjsQOTH+v3tUkskrAPV44Yuch0mFW/u5Ntifr7Q==", + "requires": { + "@reach/utils": "0.17.0", + "tslib": "^2.3.0" + } + }, + "@reach/dialog": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/dialog/-/dialog-0.17.0.tgz", + "integrity": "sha512-AnfKXugqDTGbeG3c8xDcrQDE4h9b/vnc27Sa118oQSquz52fneUeX9MeFb5ZEiBJK8T5NJpv7QUTBIKnFCAH5A==", + "requires": { + "@reach/portal": "0.17.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2", + "react-focus-lock": "^2.5.2", + "react-remove-scroll": "^2.4.3", + "tslib": "^2.3.0" + } + }, + "@reach/dropdown": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/dropdown/-/dropdown-0.17.0.tgz", + "integrity": "sha512-qBTIGInhxtPHtdj4Pl2XZgZMz3e37liydh0xR3qc48syu7g71sL4nqyKjOzThykyfhA3Pb3/wFgsFJKGTSdaig==", + "requires": { + "@reach/auto-id": "0.17.0", + "@reach/descendants": "0.17.0", + "@reach/popover": "0.17.0", + "@reach/utils": "0.17.0", + "tslib": "^2.3.0" + } + }, + "@reach/listbox": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/listbox/-/listbox-0.17.0.tgz", + "integrity": "sha512-AMnH1P6/3VKy2V/nPb4Es441arYR+t4YRdh9jdcFVrCOD6y7CQrlmxsYjeg9Ocdz08XpdoEBHM3PKLJqNAUr7A==", + "requires": { + "@reach/auto-id": "0.17.0", + "@reach/descendants": "0.17.0", + "@reach/machine": "0.17.0", + "@reach/popover": "0.17.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2" + } + }, + "@reach/machine": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/machine/-/machine-0.17.0.tgz", + "integrity": "sha512-9EHnuPgXzkbRENvRUzJvVvYt+C2jp7PGN0xon7ffmKoK8rTO6eA/bb7P0xgloyDDQtu88TBUXKzW0uASqhTXGA==", + "requires": { + "@reach/utils": "0.17.0", + "@xstate/fsm": "1.4.0", + "tslib": "^2.3.0" + } + }, + "@reach/menu-button": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/menu-button/-/menu-button-0.17.0.tgz", + "integrity": "sha512-YyuYVyMZKamPtivoEI6D0UEILYH3qZtg4kJzEAuzPmoR/aHN66NZO75Fx0gtjG1S6fZfbiARaCOZJC0VEiDOtQ==", + "requires": { + "@reach/dropdown": "0.17.0", + "@reach/popover": "0.17.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + } + }, + "@reach/observe-rect": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@reach/observe-rect/-/observe-rect-1.2.0.tgz", + "integrity": "sha512-Ba7HmkFgfQxZqqaeIWWkNK0rEhpxVQHIoVyW1YDSkGsGIXzcaW4deC8B0pZrNSSyLTdIk7y+5olKt5+g0GmFIQ==" + }, + "@reach/popover": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/popover/-/popover-0.17.0.tgz", + "integrity": "sha512-yYbBF4fMz4Ml4LB3agobZjcZ/oPtPsNv70ZAd7lEC2h7cvhF453pA+zOBGYTPGupKaeBvgAnrMjj7RnxDU5hoQ==", + "requires": { + "@reach/portal": "0.17.0", + "@reach/rect": "0.17.0", + "@reach/utils": "0.17.0", + "tabbable": "^4.0.0", + "tslib": "^2.3.0" + } + }, + "@reach/portal": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/portal/-/portal-0.17.0.tgz", + "integrity": "sha512-+IxsgVycOj+WOeNPL2NdgooUdHPSY285wCtj/iWID6akyr4FgGUK7sMhRM9aGFyrGpx2vzr+eggbUmAVZwOz+A==", + "requires": { + "@reach/utils": "0.17.0", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + } + }, + "@reach/rect": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/rect/-/rect-0.17.0.tgz", + "integrity": "sha512-3YB7KA5cLjbLc20bmPkJ06DIfXSK06Cb5BbD2dHgKXjUkT9WjZaLYIbYCO8dVjwcyO3GCNfOmPxy62VsPmZwYA==", + "requires": { + "@reach/observe-rect": "1.2.0", + "@reach/utils": "0.17.0", + "prop-types": "^15.7.2", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + } + }, + "@reach/tooltip": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/tooltip/-/tooltip-0.17.0.tgz", + "integrity": "sha512-HP8Blordzqb/Cxg+jnhGmWQfKgypamcYLBPlcx6jconyV5iLJ5m93qipr1giK7MqKT2wlsKWy44ZcOrJ+Wrf8w==", + "requires": { + "@reach/auto-id": "0.17.0", + "@reach/portal": "0.17.0", + "@reach/rect": "0.17.0", + "@reach/utils": "0.17.0", + "@reach/visually-hidden": "0.17.0", + "prop-types": "^15.7.2", + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + } + }, + "@reach/utils": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/utils/-/utils-0.17.0.tgz", + "integrity": "sha512-M5y8fCBbrWeIsxedgcSw6oDlAMQDkl5uv3VnMVJ7guwpf4E48Xlh1v66z/1BgN/WYe2y8mB/ilFD2nysEfdGeA==", + "requires": { + "tiny-warning": "^1.0.3", + "tslib": "^2.3.0" + } + }, + "@reach/visually-hidden": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@reach/visually-hidden/-/visually-hidden-0.17.0.tgz", + "integrity": "sha512-T6xF3Nv8vVnjVkGU6cm0+kWtvliLqPAo8PcZ+WxkKacZsaHTjaZb4v1PaCcyQHmuTNT/vtTVNOJLG0SjQOIb7g==", + "requires": { + "prop-types": "^15.7.2", + "tslib": "^2.3.0" + } + }, "@react-dnd/asap": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@react-dnd/asap/-/asap-4.0.1.tgz", @@ -46166,7 +46997,7 @@ "@sinclair/typebox": "^0.25.1", "pg": "^8.7.1", "pg-format": "^1.0.4", - "pgsql-parser": "^13.3.0", + "pgsql-parser": "13.4.0", "postgres-array": "^3.0.1", "prettier": "^2.6.0", "prettier-plugin-sql": "^0.12.1" @@ -47351,6 +48182,11 @@ "@xtuc/long": "4.2.2" } }, + "@xstate/fsm": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@xstate/fsm/-/fsm-1.4.0.tgz", + "integrity": "sha512-uTHDeu2xI5E1IFwf37JFQM31RrH7mY7877RqPBS4ZqSNUwoLDuct8AhBWaXGnVizBAYyimVwgCyGa9z/NiRhXA==" + }, "@xtuc/ieee754": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", @@ -49297,6 +50133,19 @@ "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", "integrity": "sha512-RpAVKQA5T63xEj6/giIbUEtZwJ4UFIc3ZtvEkiaUERylqe8xb5IvqcgOurZLahv93CLKfxcw5YI+DZcUBRyLXA==" }, + "codemirror": { + "version": "5.65.11", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.65.11.tgz", + "integrity": "sha512-Gp62g2eKSCHYt10axmGhKq3WoJSvVpvhXmowNq7pZdRVowwtvBR/hi2LSP5srtctKkRT33T6/n8Kv1UGp7JW4A==" + }, + "codemirror-graphql": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/codemirror-graphql/-/codemirror-graphql-2.0.3.tgz", + "integrity": "sha512-T58f+XQVKE6/6goAADJfu56wPRcdF2RUZMHITUol6h6Uo1KKUmknV4muKNFOl6GM15BjBraysF6HATp4oY6kyA==", + "requires": { + "graphql-language-service": "5.1.1" + } + }, "coffee-script": { "version": "1.12.7", "resolved": "https://registry.npmjs.org/coffee-script/-/coffee-script-1.12.7.tgz", @@ -52024,8 +52873,7 @@ "entities": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", - "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", - "dev": true + "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==" }, "env-paths": { "version": "2.2.1", @@ -54150,6 +54998,18 @@ "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", "dev": true }, + "graphiql": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/graphiql/-/graphiql-2.2.0.tgz", + "integrity": "sha512-w1ujpCKMlkwkoUjeg0HpRiBBTm1WHAjHNkFv1TbMu6trjzz63mQ48GLZlmyQY1yhwmc+diCcvmmAt+AyvKLWWA==", + "requires": { + "@graphiql/react": "^0.15.0", + "@graphiql/toolkit": "^0.8.0", + "entities": "^2.0.0", + "graphql-language-service": "^5.1.0", + "markdown-it": "^12.2.0" + } + }, "graphlib": { "version": "2.1.8", "resolved": "https://registry.npmjs.org/graphlib/-/graphlib-2.1.8.tgz", @@ -54158,6 +55018,26 @@ "lodash": "^4.17.15" } }, + "graphql": { + "version": "16.6.0", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.6.0.tgz", + "integrity": "sha512-KPIBPDlW7NxrbT/eh4qPXz5FiFdL5UbaA0XUNz2Rp3Z3hqBSkbj0GVjwFDztsWVauZUWsbKHgMg++sk8UX0bkw==" + }, + "graphql-language-service": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/graphql-language-service/-/graphql-language-service-5.1.1.tgz", + "integrity": "sha512-gpaDT9E3+3eWhoqO4C81CGhkzr7Vp2jH/eq+ykoUbgfvMEpqhGTfCeNmrf+S4K/+4WTkAAJBsYT0/ZPZkqe/Hg==", + "requires": { + "nullthrows": "^1.0.0", + "vscode-languageserver-types": "^3.17.1" + } + }, + "graphql-ws": { + "version": "5.11.3", + "resolved": "https://registry.npmjs.org/graphql-ws/-/graphql-ws-5.11.3.tgz", + "integrity": "sha512-fU8zwSgAX2noXAsuFiCZ8BtXeXZOzXyK5u1LloCdacsVth4skdBMPO74EG51lBoWSIZ8beUocdpV8+cQHBODnQ==", + "requires": {} + }, "gray-matter": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz", @@ -55373,6 +56253,11 @@ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", "dev": true }, + "is-primitive": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-3.0.1.tgz", + "integrity": "sha512-GljRxhWvlCNRfZyORiH77FwdFwGcMO620o37EOYC0ORWdq+WYNVqW0w2Juzew4M+L81l6/QS3t5gkkihyRqv9w==" + }, "is-reference": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.0.tgz", @@ -57462,6 +58347,14 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "devOptional": true }, + "linkify-it": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.3.tgz", + "integrity": "sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==", + "requires": { + "uc.micro": "^1.0.1" + } + }, "list-item": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/list-item/-/list-item-1.1.1.tgz", @@ -57785,6 +58678,25 @@ "resolved": "https://registry.npmjs.org/markdown-extensions/-/markdown-extensions-1.1.1.tgz", "integrity": "sha512-WWC0ZuMzCyDHYCasEGs4IPvLyTGftYwh6wIEOULOF0HXcqZlhwRzrK0w2VUlxWA98xnvb/jszw4ZSkJ6ADpM6Q==" }, + "markdown-it": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.3.2.tgz", + "integrity": "sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg==", + "requires": { + "argparse": "^2.0.1", + "entities": "~2.1.0", + "linkify-it": "^3.0.1", + "mdurl": "^1.0.1", + "uc.micro": "^1.0.5" + }, + "dependencies": { + "entities": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.1.0.tgz", + "integrity": "sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w==" + } + } + }, "markdown-link": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/markdown-link/-/markdown-link-0.1.1.tgz", @@ -58509,6 +59421,12 @@ } } }, + "meros": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/meros/-/meros-1.2.1.tgz", + "integrity": "sha512-R2f/jxYqCAGI19KhAvaxSOxALBMkaXWH2a7rOyqQw+ZmizX5bKkEYWLzdhC+U82ZVVPVp6MCXe3EkVligh+12g==", + "requires": {} + }, "methods": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", @@ -60087,6 +61005,11 @@ "boolbase": "^1.0.0" } }, + "nullthrows": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/nullthrows/-/nullthrows-1.1.1.tgz", + "integrity": "sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw==" + }, "num2fraction": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/num2fraction/-/num2fraction-1.2.2.tgz", @@ -62703,6 +63626,14 @@ "use-memo-one": "^1.1.1" } }, + "react-clientside-effect": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/react-clientside-effect/-/react-clientside-effect-1.2.6.tgz", + "integrity": "sha512-XGGGRQAKY+q25Lz9a/4EPqom7WRjz3z9R2k4jhVKA/puQFH/5Nt27vFZYql4m4NVNdUvX8PS3O7r/Zzm7cjUlg==", + "requires": { + "@babel/runtime": "^7.12.13" + } + }, "react-contexify": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/react-contexify/-/react-contexify-5.0.0.tgz", @@ -62878,6 +63809,29 @@ "prop-types": "^15.7.2" } }, + "react-focus-lock": { + "version": "2.9.3", + "resolved": "https://registry.npmjs.org/react-focus-lock/-/react-focus-lock-2.9.3.tgz", + "integrity": "sha512-cGNkz9p5Fpqio6hBHlkKxzRYrBYtcPosFOL6Q3N/LSbHjwP/PTBqHpvbgaOYoE7rWfzw8qXPKTB3Tk/VPgw4NQ==", + "requires": { + "@babel/runtime": "^7.0.0", + "focus-lock": "^0.11.5", + "prop-types": "^15.6.2", + "react-clientside-effect": "^1.2.6", + "use-callback-ref": "^1.3.0", + "use-sidecar": "^1.1.2" + }, + "dependencies": { + "focus-lock": { + "version": "0.11.5", + "resolved": "https://registry.npmjs.org/focus-lock/-/focus-lock-0.11.5.tgz", + "integrity": "sha512-1mTr6pl9HBpJ8CqY7hRc38MCrcuTZIeYAkBD1gBTzbx5/to+bRBaBYtJ68iDq7ryTzAAbKrG3dVKjkrWTaaEaw==", + "requires": { + "tslib": "^2.0.3" + } + } + } + }, "react-from-dom": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/react-from-dom/-/react-from-dom-0.6.2.tgz", @@ -65695,6 +66649,8 @@ "version": "file:studio", "requires": { "@babel/core": "^7.17.5", + "@graphiql/react": "^0.15.0", + "@graphiql/toolkit": "^0.8.0", "@hcaptcha/react-hcaptcha": "^1.4.4", "@headlessui/react": "^1.4.1", "@monaco-editor/react": "^4.3.1", @@ -65752,12 +66708,16 @@ "babel-loader": "^8.2.3", "blueimp-md5": "^2.19.0", "clipboard": "^2.0.8", + "clsx": "^1.2.1", "common": "*", "config": "*", "configcat-js": "^7.0.0", "dayjs": "^1.11.0", "file-saver": "^2.0.5", "generate-password": "^1.7.0", + "graphiql": "^2.2.0", + "graphql": "^16.6.0", + "graphql-ws": "^5.11.3", "html-to-image": "^1.10.8", "immutability-helper": "^3.1.1", "ip-address": "^8.1.0", @@ -65917,6 +66877,11 @@ "postcss-value-parser": "^4.2.0" } }, + "clsx": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz", + "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==" + }, "configcat-common": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/configcat-common/-/configcat-common-7.0.1.tgz", @@ -66121,6 +67086,12 @@ } } }, + "style-mod": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.0.0.tgz", + "integrity": "sha512-OPhtyEjyyN9x3nhPsu76f52yUGXiZcgvsrFVtvTkyGRQJ0XK+GPc6ov1z+lRpbeabka+MYEQxOYRnt5nF30aMw==", + "peer": true + }, "style-to-object": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-0.3.0.tgz", @@ -66318,6 +67289,11 @@ "integrity": "sha512-qImOD23aDfnIDNqlG1NOehdB9IYsn1V9oByPjKY1nakv2MQYCEMyX033/q+aEtYCpmYK1cv2+NTmlH+ra6GA5A==", "dev": true }, + "tabbable": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-4.0.0.tgz", + "integrity": "sha512-H1XoH1URcBOa/rZZWxLxHCtOdVUEev+9vo5YdYhC9tCY4wnybX+VQrCYuy9ubkg69fCBxCONJOSLGfw0DWMffQ==" + }, "table": { "version": "6.8.1", "resolved": "https://registry.npmjs.org/table/-/table-6.8.1.tgz", @@ -67081,6 +68057,11 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.3.tgz", "integrity": "sha512-CIfGzTelbKNEnLpLdGFgdyKhG23CKdKgQPOBc+OUNrkJ2vr+KSzsSV5kq5iWhEQbok+quxgGzrAtGWCyU7tHnA==" }, + "uc.micro": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", + "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==" + }, "uglify-js": { "version": "3.17.4", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.17.4.tgz", @@ -68032,6 +69013,11 @@ "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", "integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==" }, + "vscode-languageserver-types": { + "version": "3.17.3", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.3.tgz", + "integrity": "sha512-SYU4z1dL0PyIMd4Vj8YOqFvHu7Hz/enbWtpfnVbJHU4Nd1YNYx8u0ennumc6h48GQNeOLxmwySmnADouT/AuZA==" + }, "vscode-oniguruma": { "version": "1.6.2", "resolved": "https://registry.npmjs.org/vscode-oniguruma/-/vscode-oniguruma-1.6.2.tgz", @@ -68051,6 +69037,12 @@ "browser-process-hrtime": "^1.0.0" } }, + "w3c-keyname": { + "version": "2.2.6", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.6.tgz", + "integrity": "sha512-f+fciywl1SJEniZHD6H+kUO8gOnwIr7f4ijKA6+ZvJFjeGi1r4PDLl53Ayud9O/rk64RqgoQine0feoeOU0kXg==", + "peer": true + }, "w3c-xmlserializer": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz", diff --git a/packages/ui/index.tsx b/packages/ui/index.tsx index 772f434d345..3edb9ec62c3 100644 --- a/packages/ui/index.tsx +++ b/packages/ui/index.tsx @@ -305,6 +305,7 @@ export * from './src/components/Icon/icons/IconSun' export * from './src/components/Icon/icons/IconSunrise' export * from './src/components/Icon/icons/IconSunset' export * from './src/components/Icon/icons/IconTablet' +export * from './src/components/Icon/icons/IconTable' export * from './src/components/Icon/icons/IconTag' export * from './src/components/Icon/icons/IconTarget' export * from './src/components/Icon/icons/IconTerminal' diff --git a/packages/ui/internals/icons.js b/packages/ui/internals/icons.js index 07a7f0e5539..1cde50bfbd9 100644 --- a/packages/ui/internals/icons.js +++ b/packages/ui/internals/icons.js @@ -234,6 +234,7 @@ export default { IconSunrise: 'src/components/Icon/icons/IconSunrise/index.tsx', IconSunset: 'src/components/Icon/icons/IconSunset/index.tsx', IconTablet: 'src/components/Icon/icons/IconTablet/index.tsx', + IconTable: 'src/components/Icon/icons/IconTable/index.tsx', IconTag: 'src/components/Icon/icons/IconTag/index.tsx', IconTarget: 'src/components/Icon/icons/IconTarget/index.tsx', IconTerminal: 'src/components/Icon/icons/IconTerminal/index.tsx', @@ -284,5 +285,5 @@ export default { IconZapOff: 'src/components/Icon/icons/IconZapOff/index.tsx', IconZap: 'src/components/Icon/icons/IconZap/index.tsx', IconZoomIn: 'src/components/Icon/icons/IconZoomIn/index.tsx', - IconZoomOut: 'src/components/Icon/icons/IconZoomOut/index.tsx' -} \ No newline at end of file + IconZoomOut: 'src/components/Icon/icons/IconZoomOut/index.tsx', +} diff --git a/packages/ui/internals/icons.json b/packages/ui/internals/icons.json index 992be561d20..a348ede4cf5 100644 --- a/packages/ui/internals/icons.json +++ b/packages/ui/internals/icons.json @@ -939,6 +939,10 @@ "name": "Tablet", "path": "react-feather/dist/icons/tablet" }, + "Table": { + "name": "Table", + "path": "react-feather/dist/icons/table" + }, "Tag": { "name": "Tag", "path": "react-feather/dist/icons/tag" diff --git a/packages/ui/src/components/Accordion/Accordion.tsx b/packages/ui/src/components/Accordion/Accordion.tsx index 4a802c44ed6..11ca83de563 100644 --- a/packages/ui/src/components/Accordion/Accordion.tsx +++ b/packages/ui/src/components/Accordion/Accordion.tsx @@ -37,14 +37,13 @@ interface AccordionProps { defaultActiveId?: (string | number)[] icon?: React.ReactNode iconPosition?: Align - bordered: boolean onChange?: (item: string | string[]) => void openBehaviour: 'single' | 'multiple' type: Type size: Size defaultValue?: string | string[] | undefined - justified: Boolean - chevronAlign: Align + justified?: Boolean + chevronAlign?: Align } function Accordion({ @@ -58,8 +57,8 @@ function Accordion({ type = 'default', // size, // TO DO defaultValue = undefined, - justified = true, - chevronAlign, + justified = false, + chevronAlign = 'left', }: AccordionProps) { // const [currentItems, setCurrentItems] = useState(defaultValue || []) diff --git a/packages/ui/src/components/Icon/IconImportHandler.tsx b/packages/ui/src/components/Icon/IconImportHandler.tsx index 0d158b428c6..3863d419700 100644 --- a/packages/ui/src/components/Icon/IconImportHandler.tsx +++ b/packages/ui/src/components/Icon/IconImportHandler.tsx @@ -241,6 +241,7 @@ export const Sun: Icon = require(`react-feather/dist/icons/sun`) export const Sunrise: Icon = require(`react-feather/dist/icons/sunrise`) export const Sunset: Icon = require(`react-feather/dist/icons/sunset`) export const Tablet: Icon = require(`react-feather/dist/icons/tablet`) +export const Table: Icon = require(`react-feather/dist/icons/table`) export const Tag: Icon = require(`react-feather/dist/icons/tag`) export const Target: Icon = require(`react-feather/dist/icons/target`) export const Terminal: Icon = require(`react-feather/dist/icons/terminal`) diff --git a/packages/ui/src/components/Icon/icons/IconTable/IconTable.tsx b/packages/ui/src/components/Icon/icons/IconTable/IconTable.tsx new file mode 100644 index 00000000000..c0e41b29099 --- /dev/null +++ b/packages/ui/src/components/Icon/icons/IconTable/IconTable.tsx @@ -0,0 +1,13 @@ +// DO NOT EDIT + // this file is generated by /internals/populate-icons script + import * as React from 'react' + // @ts-ignore + import { Table } from 'react-feather' + import IconBase from './../../IconBase' + + function IconTable(props: any) { + return + } + + export default IconTable + \ No newline at end of file diff --git a/packages/ui/src/components/Icon/icons/IconTable/index.tsx b/packages/ui/src/components/Icon/icons/IconTable/index.tsx new file mode 100644 index 00000000000..906c04de230 --- /dev/null +++ b/packages/ui/src/components/Icon/icons/IconTable/index.tsx @@ -0,0 +1 @@ +export { default as IconTable } from './IconTable' \ No newline at end of file diff --git a/packages/ui/src/components/Icon/icons/index.tsx b/packages/ui/src/components/Icon/icons/index.tsx index 9fc2134a5a7..5975707ac72 100644 --- a/packages/ui/src/components/Icon/icons/index.tsx +++ b/packages/ui/src/components/Icon/icons/index.tsx @@ -234,6 +234,7 @@ export * as IconSun from './IconSun' export * as IconSunrise from './IconSunrise' export * as IconSunset from './IconSunset' export * as IconTablet from './IconTablet' +export * as IconTable from './IconTable' export * as IconTag from './IconTag' export * as IconTarget from './IconTarget' export * as IconTerminal from './IconTerminal' diff --git a/packages/ui/src/components/SidePanel/SidePanel.tsx b/packages/ui/src/components/SidePanel/SidePanel.tsx index d04b062b3c2..b9595e7fec3 100644 --- a/packages/ui/src/components/SidePanel/SidePanel.tsx +++ b/packages/ui/src/components/SidePanel/SidePanel.tsx @@ -22,7 +22,7 @@ interface CustomProps { children?: React.ReactNode header?: string | React.ReactNode visible: boolean - size?: 'medium' | 'large' | 'xlarge' + size?: 'medium' | 'large' | 'xlarge' | 'xxlarge' loading?: boolean align?: 'right' | 'left' hideFooter?: boolean diff --git a/packages/ui/src/lib/theme/defaultTheme.ts b/packages/ui/src/lib/theme/defaultTheme.ts index 28fe703fb73..4617d5a8e94 100644 --- a/packages/ui/src/lib/theme/defaultTheme.ts +++ b/packages/ui/src/lib/theme/defaultTheme.ts @@ -998,6 +998,7 @@ export default { medium: `w-screen max-w-md h-full`, large: `w-screen max-w-2xl h-full`, xlarge: `w-screen max-w-3xl h-full`, + xxlarge: `w-screen max-w-4xl h-full`, }, align: { left: ` diff --git a/spec/cli_v1_commands--old.yaml b/spec/cli_v1_commands--old.yaml index d7af310d127..f3671ceb1ae 100644 --- a/spec/cli_v1_commands--old.yaml +++ b/spec/cli_v1_commands--old.yaml @@ -380,12 +380,12 @@ commands: ``` - id: supabase-functions-serve title: supabase functions serve - summary: Serve a Function locally + summary: Serve Functions locally tags: [] links: [] usage: |- ```sh - supabase functions serve [flags] + supabase functions serve [flags] ``` subcommands: [] options: |- diff --git a/spec/cli_v1_commands.yaml b/spec/cli_v1_commands.yaml index c060b75634e..daf13552001 100644 --- a/spec/cli_v1_commands.yaml +++ b/spec/cli_v1_commands.yaml @@ -761,10 +761,10 @@ commands: flags: [] - id: supabase-functions-serve title: supabase functions serve - summary: Serve a Function locally + summary: Serve all functions locally tags: [] links: [] - usage: supabase functions serve [flags] + usage: supabase functions serve [flags] subcommands: [] flags: - id: env-file diff --git a/spec/common-cli-sections.json b/spec/common-cli-sections.json index 8e5dff89916..127c10a5318 100644 --- a/spec/common-cli-sections.json +++ b/spec/common-cli-sections.json @@ -239,7 +239,7 @@ }, { "id": "supabase-functions-serve", - "title": "Serve a function", + "title": "Serve functions locally", "slug": "supabase-functions-serve", "type": "cli-command" }, diff --git a/spec/supabase_js_v2.yml b/spec/supabase_js_v2.yml index 26c48fec458..e59459ce89a 100644 --- a/spec/supabase_js_v2.yml +++ b/spec/supabase_js_v2.yml @@ -2258,6 +2258,9 @@ functions: ``` hideCodeBlock: true isSpotlight: true + description: | + When using [reserved words](https://www.postgresql.org/docs/current/sql-keywords-appendix.html) for column names you need + to add double quotes e.g. `.gt('"order"', 2)` - id: gte title: gte() $ref: '@supabase/postgrest-js.PostgrestFilterBuilder.gte' diff --git a/spec/supabase_py_v2.yml b/spec/supabase_py_v2.yml index a3af18a5acd..486e429f3e1 100644 --- a/spec/supabase_py_v2.yml +++ b/spec/supabase_py_v2.yml @@ -281,18 +281,360 @@ functions: name: Getting your data code: | ``` - r = supabase - .from('countries') - .select("*").execute() + response = supabase.table('countries').select("*").execute() + ``` + data: + sql: | + ```sql + create table + countries (id int8 primary key, name text); + + insert into + countries (id, name) + values + (1, 'Afghanistan'), + (2, 'Albania'), + (3, 'Algeria'); + ``` + response: | + ``` + APIResponse(data=[{'id': 1, 'name': 'Afghanistan'}, + {'id': 2, 'name': 'Albania'}, + {'id': 3, 'name': 'Algeria'}], + count=None) ``` - id: selecting-specific-columns name: Selecting specific columns code: | ``` - r = await supabase - .from('countries') - .select('name').execute() + response = supabase.table('countries').select('name').execute() ``` + data: + sql: | + ```sql + create table + countries (id int8 primary key, name text); + + insert into + countries (id, name) + values + (1, 'Afghanistan'), + (2, 'Albania'), + (3, 'Algeria'); + ``` + response: | + ``` + APIResponse(data=[{'name': 'Afghanistan'}, + {'name': 'Albania'}, + {'name': 'Algeria'}], + count=None) + ``` + - id: query-foreign-tables + name: Query foreign tables + description: | + If your database has foreign key relationships, you can query related tables too. + code: | + ``` + response = supabase.table('countries').select('name, cities(name)').execute() + ``` + data: + sql: | + ```sql + create table + countries (id int8 primary key, name text); + create table + cities ( + id int8 primary key, + country_id int8 not null references countries, + name text + ); + + insert into + countries (id, name) + values + (1, 'Germany'), + (2, 'Indonesia'); + insert into + cities (id, country_id, name) + values + (1, 2, 'Bali'), + (2, 1, 'Munich'); + ``` + response: | + ``` + APIResponse(data=[{'name': 'Germany', 'cities': [{'name': 'Munich'}]}, + {'name': 'Indonesia', 'cities': [{'name': 'Bali'}]}], + count=None) + ``` + - id: query-foreign-tables-through-a-join-table + name: Query foreign tables through a join table + code: | + ``` + response = supabase.table('users').select('name, teams(name)').execute() + ``` + data: + sql: | + ```sql + create table + users ( + id int8 primary key, + name text + ); + create table + teams ( + id int8 primary key, + name text + ); + -- join table + create table + users_teams ( + user_id int8 not null references users, + team_id int8 not null references teams, + -- both foreign keys must be part of a composite primary key + primary key (user_id, team_id) + ); + + insert into + users (id, name) + values + (1, 'Kiran'), + (2, 'Evan'); + insert into + teams (id, name) + values + (1, 'Green'), + (2, 'Blue'); + insert into + users_teams (user_id, team_id) + values + (1, 1), + (1, 2), + (2, 2); + ``` + response: | + ``` + APIResponse(data=[ + {'name': 'Kiran', 'teams': [{'name': 'Green'}, {'name': 'Blue'}]}, + {'name': 'Evan', 'teams': [{'name': 'Blue'}]} + ], + count=None) + ``` + description: | + If you're in a situation where your tables are **NOT** directly + related, but instead are joined by a _join table_, you can still use + the `select()` method to query the related data. The join table needs + to have the foreign keys as part of its composite primary key. + hideCodeBlock: true + - id: query-the-same-foreign-table-multiple-times + name: Query the same foreign table multiple times + code: | + ``` + response = supabase.table('messages').select('content,from:sender_id(name),to:receiver_id(name)').execute() + ``` + data: + sql: | + ```sql + create table + users (id int8 primary key, name text); + + create table + messages ( + sender_id int8 not null references users, + receiver_id int8 not null references users, + content text + ); + + insert into + users (id, name) + values + (1, 'Kiran'), + (2, 'Evan'); + + insert into + messages (sender_id, receiver_id, content) + values + (1, 2, '👋'); + ``` + response: | + ``` + APIResponse(data=[{'content': '👋', + 'from': {'name': 'Kiran'}, + 'to': {'name': 'Evan'}} + ], + count=None) + ``` + description: | + If you need to query the same foreign table twice, use the name of the + joined column to identify which join to use. You can also give each + column an alias. + hideCodeBlock: true + - id: filtering-through-foreign-tables + name: Filtering through foreign tables + code: | + ``` + response = supabase.table('cities').select('name, countries(*)').eq('countries.name', 'Estonia').execute() + ``` + data: + sql: | + ```sql + create table + countries (id int8 primary key, name text); + create table + cities ( + id int8 primary key, + country_id int8 not null references countries, + name text + ); + + insert into + countries (id, name) + values + (1, 'Germany'), + (2, 'Indonesia'); + insert into + cities (id, country_id, name) + values + (1, 2, 'Bali'), + (2, 1, 'Munich'); + ``` + response: | + ``` + APIResponse(data=[{'name': 'Bali', 'countries': None}, + {'name': 'Munich', 'countries': None}], + count=None) + ``` + description: | + NOT WORKING CURRENTLY + If the filter on a foreign table's column is not satisfied, the foreign + table returns `[]` or `null` but the parent table is not filtered out. + If you want to filter out the parent table rows, use the `!inner` hint + hideCodeBlock: true + - id: querying-foreign-table-with-count + name: Querying foreign table with count + code: | + ``` + response = supabase.table('countries').select('*, cities(count)').execute() + ``` + data: + sql: | + ```sql + create table countries ( + "id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null, + "name" text + ); + + create table cities ( + "id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null, + "name" text, + "country_id" "uuid" references public.countries on delete cascade + ); + + with country as ( + insert into countries (name) + values ('united kingdom') returning id + ) + insert into cities (name, country_id) values + ('London', (select id from country)), + ('Manchester', (select id from country)), + ('Liverpool', (select id from country)), + ('Bristol', (select id from country)); + ``` + response: | + ``` + APIResponse(data=[{'id': 1, 'name': 'Germany', 'cities': [{'count': 1}]}, + {'id': 2, 'name': 'Indonesia', 'cities': [{'count': 1}]}], + count=None) + ``` + description: | + You can get the number of rows in a related table by using the + **count** property. + hideCodeBlock: true + - id: querying-with-count-option + name: Querying with count option + code: | + ``` + response = supabase.table('countries').select('*', count='exact').execute() + ``` + data: + sql: | + ```sql + create table + countries (id int8 primary key, name text); + + insert into + countries (id, name) + values + (1, 'Afghanistan'), + (2, 'Albania'), + (3, 'Algeria'); + ``` + response: | + ``` + APIResponse(data=[{'id': 1, 'name': 'Germany'}, + {'id': 2, 'name': 'Indonesia'}], + count=2) + ``` + description: | + You can get the number of rows by using the + *count* parameter in the select query. + hideCodeBlock: true + - id: querying-json-data + name: Querying JSON data + code: | + ``` + response = supabase.table('users').select('id, name, address->city').execute() + ``` + data: + sql: | + ```sql + create table + users ( + id int8 primary key, + name text, + address jsonb + ); + + insert into + users (id, name, address) + values + (1, 'Avdotya', '{"city":"Saint Petersburg"}'); + ``` + response: | + ``` + APIResponse(data=[{'id': 1, 'name': 'Avdotya', 'city': 'Saint Petersburg'}], count=None) + ``` + description: | + You can select and filter data inside of + [JSON](/docs/guides/database/json) columns. Postgres offers some + [operators](/docs/guides/database/json#query-the-jsonb-data) for + querying JSON data. + hideCodeBlock: true + + - id: insert + title: 'Create data: insert()' + $ref: '@supabase/postgrest-js.PostgrestQueryBuilder.insert' + examples: + - id: create-a-record + name: Create a record + code: | + ``` + data, count = supabase + .table('countries') + .insert({"id": 1, "name": "Denmark"}) + .execute() + ``` + data: + sql: | + ```sql + create table + countries (id int8 primary key, name text); + ``` + response: | + ``` + APIResponse(data=[{'id': 1, 'name': 'Denmark'}], count=None) + ``` + hideCodeBlock: true + isSpotlight: true - id: invoke title: 'invoke()' diff --git a/studio/components/grid/components/header/Header.tsx b/studio/components/grid/components/header/Header.tsx index d839ced0cfd..1b7c0d8fbce 100644 --- a/studio/components/grid/components/header/Header.tsx +++ b/studio/components/grid/components/header/Header.tsx @@ -1,17 +1,9 @@ -import { FC, useState, ReactNode } from 'react' -import { - Button, - IconDownload, - IconPlus, - IconX, - IconTrash, - Dropdown, - IconColumns, - IconChevronDown, -} from 'ui' import { saveAs } from 'file-saver' +import { FC, useState, ReactNode } from 'react' +import { Button, IconDownload, IconX, IconTrash, Dropdown, IconChevronDown } from 'ui' +import { PermissionAction } from '@supabase/shared-types/out/constants' -import { useStore } from 'hooks' +import { checkPermissions, useStore } from 'hooks' import FilterDropdown from './filter' import SortPopover from './sort' import RefreshButton from './RefreshButton' @@ -80,6 +72,9 @@ const DefaultHeader: FC = ({ }) => { const canAddNew = onAddRow !== undefined || onAddColumn !== undefined + // [Joshen] Using this logic to block both column and row creation/update/delete + const canCreateColumns = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'columns') + return (
@@ -91,71 +86,73 @@ const DefaultHeader: FC = ({ <>
- -
-
-
+ {canCreateColumns && ( + +
+
+
+
+ } + > +
+

Insert row

+

Insert a new row into {table.name}

- } - > -
-

Insert row

-

Insert a new row into {table.name}

-
- , - ] - : []), - ...(onAddColumn !== undefined - ? [ - -
-
-
+ , + ] + : []), + ...(onAddColumn !== undefined + ? [ + +
+
+
+
+ } + > +
+

Insert column

+

Insert a new column into {table.name}

- } - > -
-

Insert column

-

Insert a new column into {table.name}

-
- , - ] - : []), - ]} - > - - + , + ] + : []), + ]} + > + + + )}
)} diff --git a/studio/components/grid/components/menu/ColumnMenu.tsx b/studio/components/grid/components/menu/ColumnMenu.tsx index d252aa58289..27d5f59b57a 100644 --- a/studio/components/grid/components/menu/ColumnMenu.tsx +++ b/studio/components/grid/components/menu/ColumnMenu.tsx @@ -10,7 +10,6 @@ import { IconLock, IconUnlock, } from 'ui' -import * as React from 'react' import { useDispatch, useTrackedState } from '../../store' type ColumnMenuProps = { diff --git a/studio/components/grid/types/grid.ts b/studio/components/grid/types/grid.ts index a036249a97d..bae5c96556b 100644 --- a/studio/components/grid/types/grid.ts +++ b/studio/components/grid/types/grid.ts @@ -64,6 +64,15 @@ export interface SupabaseGridProps { */ onEditRow?: (row: SupaRow) => void onError?: (error: any) => void + /** + * Toggle api preview panel open + */ + apiPreviewPanelOpen?: boolean + setApiPreviewPanelOpen?: () => void + /** + * Refresh the docs after a change is made to the table + */ + refreshDocs: () => void onExpandJSONEditor: (column: string, row: SupaRow) => void } diff --git a/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx b/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx index a982880a845..85462a7e4be 100644 --- a/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx +++ b/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx @@ -8,19 +8,18 @@ import TemplateEditor from './TemplateEditor' const EmailTemplates = observer(() => { return (
-
+ = ({}) => { icon={} primaryText="Free Plan does not include project backups." projectRef={projectRef} - secondaryText="Please upgrade to the Pro plan for up to 7 days of scheduled backups." + secondaryText="Upgrade to the Pro plan for up to 7 days of scheduled backups." /> ) } diff --git a/studio/components/interfaces/Database/Backups/PITR/PITRNotice.tsx b/studio/components/interfaces/Database/Backups/PITR/PITRNotice.tsx index cd43b19d452..daab4106406 100644 --- a/studio/components/interfaces/Database/Backups/PITR/PITRNotice.tsx +++ b/studio/components/interfaces/Database/Backups/PITR/PITRNotice.tsx @@ -1,15 +1,22 @@ import Link from 'next/link' import { Button, IconCalendar } from 'ui' import { FormPanel } from 'components/ui/Forms' -import { useParams } from 'hooks' +import * as Tooltip from '@radix-ui/react-tooltip' +import { checkPermissions, useParams } from 'hooks' import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query' import { getPITRRetentionDuration } from './PITR.utils' +import { PermissionAction } from '@supabase/shared-types/out/constants' const PITRNotice = ({}) => { const { ref: projectRef } = useParams() const { data: subscription } = useProjectSubscriptionQuery({ projectRef }) const retentionPeriod = getPITRRetentionDuration(subscription?.addons ?? []) + const canUpdateSubscription = checkPermissions( + PermissionAction.BILLING_WRITE, + 'stripe.subscriptions' + ) + return ( { You can also increase your recovery retention period updating your PITR add-on - - - - - + + {!canUpdateSubscription && ( + + +
+ + You need additional permissions to amend subscriptions + +
+
+ )} +
} > diff --git a/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx b/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx index 4b47575c1d4..b634e1365c7 100644 --- a/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx +++ b/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx @@ -2,11 +2,13 @@ import dayjs from 'dayjs' import { FC } from 'react' import { observer } from 'mobx-react-lite' import { Button, IconAlertCircle } from 'ui' +import * as Tooltip from '@radix-ui/react-tooltip' -import { useStore } from 'hooks' +import { checkPermissions, useStore } from 'hooks' import { Timezone } from './PITR.types' import { FormPanel } from 'components/ui/Forms' import TimezoneSelection from './TimezoneSelection' +import { PermissionAction } from '@supabase/shared-types/out/constants' interface Props { selectedTimezone: Timezone @@ -29,6 +31,11 @@ const PITRStatus: FC = ({ selectedTimezone, onUpdateTimezone, onSetConfig .tz(selectedTimezone?.utc[0]) .format('DD MMM YYYY, HH:mm:ss') + const canTriggerPhysicalBackup = checkPermissions( + PermissionAction.INFRA_EXECUTE, + 'queue_job.walg.prepare_restore' + ) + return ( <> = ({ selectedTimezone, onUpdateTimezone, onSetConfig You'll be able to pick the right date and time when you begin
- + + + + + {!canTriggerPhysicalBackup && ( + + +
+ + You need additional permissions to trigger a PITR recovery + +
+
+ )} +
} > diff --git a/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx b/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx index 46458d9a75d..df69111db50 100644 --- a/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx +++ b/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx @@ -60,6 +60,8 @@ const FunctionsList: FC = ({ title="Functions" ctaButtonLabel="Create a new function" onClickCta={() => createFunction()} + disabled={!canCreateFunctions} + disabledMessage="You need additional permissions to create functions" >

diff --git a/studio/components/interfaces/Database/Roles/RolesList.tsx b/studio/components/interfaces/Database/Roles/RolesList.tsx index 956fb1af750..c5059c26e05 100644 --- a/studio/components/interfaces/Database/Roles/RolesList.tsx +++ b/studio/components/interfaces/Database/Roles/RolesList.tsx @@ -1,17 +1,18 @@ +import { partition } from 'lodash' import { FC, useState, useEffect } from 'react' import { observer } from 'mobx-react-lite' import * as Tooltip from '@radix-ui/react-tooltip' import { PostgresRole } from '@supabase/postgres-meta' import { Button, Input, IconPlus, IconSearch, IconX, Badge } from 'ui' +import { PermissionAction } from '@supabase/shared-types/out/constants' -import { useStore } from 'hooks' +import { checkPermissions, useStore } from 'hooks' import SparkBar from 'components/ui/SparkBar' import { FormHeader } from 'components/ui/Forms' import RoleRow from './RoleRow' -import DeleteRoleModal from './DeleteRoleModal' import { SUPABASE_ROLES } from './Roles.constants' -import { partition } from 'lodash' import CreateRolePanel from './CreateRolePanel' +import DeleteRoleModal from './DeleteRoleModal' interface Props { onSelectRole: (role: any) => void @@ -26,6 +27,8 @@ const RolesList: FC = ({}) => { const [isCreatingRole, setIsCreatingRole] = useState(false) const [selectedRoleToDelete, setSelectedRoleToDelete] = useState() + const canUpdateRoles = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'roles') + useEffect(() => { const getMaxConnectionLimit = async () => { const res = await meta.query('show max_connections') @@ -149,13 +152,31 @@ const RolesList: FC = ({}) => {

- + + + + + {!canUpdateRoles && ( + + +
+ You need additional permissions to add a new role +
+
+ )} +
@@ -184,7 +205,12 @@ const RolesList: FC = ({}) => {
)} {otherRoles.map((role: PostgresRole, i: number) => ( - + ))}
diff --git a/studio/components/interfaces/Database/Tables/ColumnList.tsx b/studio/components/interfaces/Database/Tables/ColumnList.tsx index c5b668777fc..e53ed442863 100644 --- a/studio/components/interfaces/Database/Tables/ColumnList.tsx +++ b/studio/components/interfaces/Database/Tables/ColumnList.tsx @@ -1,11 +1,13 @@ import { FC, useState } from 'react' import { observer } from 'mobx-react-lite' +import * as Tooltip from '@radix-ui/react-tooltip' import { Input, Button, IconSearch, IconPlus, IconChevronLeft, IconEdit3, IconTrash } from 'ui' +import type { PostgresTable } from '@supabase/postgres-meta' +import { PermissionAction } from '@supabase/shared-types/out/constants' -import { useStore } from 'hooks' +import { useStore, checkPermissions } from 'hooks' import Table from 'components/to-be-cleaned/Table' import NoSearchResults from 'components/to-be-cleaned/NoSearchResults' -import type { PostgresTable } from '@supabase/postgres-meta' interface Props { selectedTable: PostgresTable @@ -30,6 +32,7 @@ const ColumnList: FC = ({ : selectedTable.columns?.filter((column: any) => column.name.includes(filterString))) ?? [] const isLocked = meta.excludedSchemas.includes(selectedTable.schema ?? '') + const canUpdateColumns = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'columns') return ( <> @@ -58,9 +61,32 @@ const ColumnList: FC = ({
{!isLocked && (
- + + + + + {!canUpdateColumns && ( + + +
+ + You need additional permissions to create columns + +
+
+ )} +
)}
@@ -103,20 +129,59 @@ const ColumnList: FC = ({
-
diff --git a/studio/components/interfaces/Database/Tables/TableList.tsx b/studio/components/interfaces/Database/Tables/TableList.tsx index de856582937..b058f9ce6f4 100644 --- a/studio/components/interfaces/Database/Tables/TableList.tsx +++ b/studio/components/interfaces/Database/Tables/TableList.tsx @@ -12,10 +12,11 @@ import { IconLock, IconCheck, } from 'ui' - import { partition } from 'lodash' +import * as Tooltip from '@radix-ui/react-tooltip' +import { PermissionAction } from '@supabase/shared-types/out/constants' -import { useStore } from 'hooks' +import { useStore, checkPermissions } from 'hooks' import Table from 'components/to-be-cleaned/Table' import NoSearchResults from 'components/to-be-cleaned/NoSearchResults' import type { PostgresTable, PostgresSchema } from '@supabase/postgres-meta' @@ -38,8 +39,8 @@ const TableList: FC = ({ onOpenTable = () => {}, }) => { const { meta } = useStore() - const [filterString, setFilterString] = useState('') + const canUpdateTables = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables') const schemas: PostgresSchema[] = meta.schemas.list() const [protectedSchemas, openSchemas] = partition(schemas, (schema) => @@ -120,9 +121,32 @@ const TableList: FC = ({
{!isLocked && (
- + + + + + {!canUpdateTables && ( + + +
+ + You need additional permissions to create tables + +
+
+ )} +
)}
@@ -183,7 +207,62 @@ const TableList: FC = ({ > {x.columns.length} columns -
diff --git a/studio/components/interfaces/Database/Wrappers/CreateWrapper.tsx b/studio/components/interfaces/Database/Wrappers/CreateWrapper.tsx index dbe8fe10c83..242345a01f7 100644 --- a/studio/components/interfaces/Database/Wrappers/CreateWrapper.tsx +++ b/studio/components/interfaces/Database/Wrappers/CreateWrapper.tsx @@ -36,7 +36,7 @@ const CreateWrapper = () => { const [selectedTableToEdit, setSelectedTableToEdit] = useState() const [formErrors, setFormErrors] = useState<{ [k: string]: string }>({}) - const canCreateWrapper = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'extensions') + const canCreateWrapper = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'wrappers') const wrapperMeta = WRAPPERS.find((wrapper) => wrapper.name === type) const initialValues = @@ -164,6 +164,7 @@ const CreateWrapper = () => { isSubmitting={isSubmitting} hasChanges={hasChanges} handleReset={handleReset} + disabled={!canCreateWrapper} helper={ !canCreateWrapper ? 'You need additional permissions to create a foreign data wrapper' diff --git a/studio/components/interfaces/Database/Wrappers/EditWrapper.tsx b/studio/components/interfaces/Database/Wrappers/EditWrapper.tsx index 2286ec04c7f..fdcec1aa4b8 100644 --- a/studio/components/interfaces/Database/Wrappers/EditWrapper.tsx +++ b/studio/components/interfaces/Database/Wrappers/EditWrapper.tsx @@ -65,7 +65,7 @@ const EditWrapper = () => { const [selectedTableToEdit, setSelectedTableToEdit] = useState() const [formErrors, setFormErrors] = useState<{ [k: string]: string }>({}) - const canCreateWrapper = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'extensions') + const canUpdateWrapper = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'wrappers') const initialValues = wrapperMeta !== undefined @@ -248,7 +248,7 @@ const EditWrapper = () => { return ( { handleReset() setWrapperTables(initialTables) }} + disabled={!canUpdateWrapper} helper={ - !canCreateWrapper - ? 'You need additional permissions to create a foreign data wrapper' + !canUpdateWrapper + ? 'You need additional permissions to edit a foreign data wrapper' : undefined } /> diff --git a/studio/components/interfaces/Database/Wrappers/WrapperRow.tsx b/studio/components/interfaces/Database/Wrappers/WrapperRow.tsx index 35b7efbed34..896cd11d45e 100644 --- a/studio/components/interfaces/Database/Wrappers/WrapperRow.tsx +++ b/studio/components/interfaces/Database/Wrappers/WrapperRow.tsx @@ -1,10 +1,12 @@ import Link from 'next/link' import Image from 'next/image' import { FC } from 'react' -import { Collapsible, IconChevronUp, Button, IconExternalLink, IconTrash, IconEdit } from 'ui' import { partition } from 'lodash' +import * as Tooltip from '@radix-ui/react-tooltip' +import { PermissionAction } from '@supabase/shared-types/out/constants' +import { Collapsible, IconChevronUp, Button, IconExternalLink, IconTrash, IconEdit } from 'ui' -import { useParams, useStore } from 'hooks' +import { useParams, useStore, checkPermissions } from 'hooks' import { WrapperMeta } from './Wrappers.types' import { FDW } from 'data/fdw/fdws-query' import { useFDWDeleteMutation } from 'data/fdw/fdw-delete-mutation' @@ -24,6 +26,8 @@ const WrapperRow: FC = ({ wrappers = [], wrapperMeta, isOpen, onOpen }) = const { project } = useProjectContext() const { mutateAsync: deleteFDW } = useFDWDeleteMutation() + const canManageWrappers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'wrappers') + const onDeleteWrapper = (wrapper: any) => { confirmAlert({ title: `Confirm to disable ${wrapper.name}`, @@ -156,21 +160,69 @@ const WrapperRow: FC = ({ wrappers = [], wrapperMeta, isOpen, onOpen }) =
- - + {canManageWrappers ? ( + + +
) diff --git a/studio/components/interfaces/Database/Wrappers/Wrappers.tsx b/studio/components/interfaces/Database/Wrappers/Wrappers.tsx index 461d9776b17..529d9cd0c16 100644 --- a/studio/components/interfaces/Database/Wrappers/Wrappers.tsx +++ b/studio/components/interfaces/Database/Wrappers/Wrappers.tsx @@ -1,4 +1,5 @@ import Link from 'next/link' +import { groupBy } from 'lodash' import { useState } from 'react' import { Button, IconExternalLink } from 'ui' import { observer } from 'mobx-react-lite' @@ -11,7 +12,6 @@ import ShimmeringLoader from 'components/ui/ShimmeringLoader' import WrappersDropdown from './WrappersDropdown' import WrappersDisabledState from './WrappersDisabledState' import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext' -import { groupBy } from 'lodash' const Wrappers = () => { const { meta } = useStore() diff --git a/studio/components/interfaces/Database/Wrappers/WrappersDropdown.tsx b/studio/components/interfaces/Database/Wrappers/WrappersDropdown.tsx index b74c9a9fffb..76a5ce5b6b4 100644 --- a/studio/components/interfaces/Database/Wrappers/WrappersDropdown.tsx +++ b/studio/components/interfaces/Database/Wrappers/WrappersDropdown.tsx @@ -3,8 +3,10 @@ import Image from 'next/image' import { FC, Fragment } from 'react' import { observer } from 'mobx-react-lite' import { Button, Dropdown, IconPlus } from 'ui' +import * as Tooltip from '@radix-ui/react-tooltip' +import { PermissionAction } from '@supabase/shared-types/out/constants' -import { useParams } from 'hooks' +import { useParams, checkPermissions } from 'hooks' import { WRAPPERS } from './Wrappers.constants' interface Props { @@ -14,6 +16,32 @@ interface Props { const WrapperDropdown: FC = ({ buttonText = 'Add wrapper', align = 'end' }) => { const { ref } = useParams() + const canManageWrappers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'wrappers') + + if (!canManageWrappers) { + return ( + + + + + + +
+ + You need additional permissions to add wrappers + +
+
+
+ ) + } return ( { + setIsGeneratingTypes(true) + const res = await get(`${API_ADMIN_URL}/projects/${ref}/types/typescript`) + + if (!res.error) { + let element = document.createElement('a') + element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(res.types)) + element.setAttribute('download', 'supabase.ts') + element.style.display = 'none' + document.body.appendChild(element) + element.click() + document.body.removeChild(element) + ui.setNotification({ + category: 'success', + message: `Successfully generated types! File is being downloaded`, + }) + } else { + ui.setNotification({ + category: 'error', + message: `Failed to generate types: ${res.error.message}`, + error: res.error, + }) + } + + setIsGeneratingTypes(false) + } + return ( + <> +

+ Generating types + + + + + +

+
+
+

+ Supabase APIs are generated from your database, which means that we can use database + introspection to generate type-safe API definitions. +

+

+ You can generate types from your database either through the{' '} + + Supabase CLI + + , or by downloading the types file via the button on the right and importing it in your + application within src/index.ts. +

+
+
+
+

+ {selectedLang === 'js' && ( + + )} +

+

+ Remember to re-generate and download this file as you make changes to your tables. +

+
+ + +
+
+ + ) +} + +const localSnippets = { + cliLogin: () => ({ + title: 'Login via the CLI with your Personal Access Token', + bash: { + code: ` +npx supabase login +`, + }, + }), + generateTypes: (ref: string) => ({ + title: 'Generate types', + bash: { + code: ` +npx supabase gen types typescript --project-id "${ref}" --schema public > types/supabase.ts +`, + }, + }), +} diff --git a/studio/components/interfaces/Docs/LangSelector.tsx b/studio/components/interfaces/Docs/LangSelector.tsx new file mode 100644 index 00000000000..a0e05272874 --- /dev/null +++ b/studio/components/interfaces/Docs/LangSelector.tsx @@ -0,0 +1,110 @@ +import { FC } from 'react' +import { Button, Dropdown, IconKey } from 'ui' +import { checkPermissions } from 'hooks' +import { PermissionAction } from '@supabase/shared-types/out/constants' + +import { showApiKey } from 'components/interfaces/Docs/Docs.types' + +const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' } + +interface Props { + selectedLang: string + setSelectedLang: (selectedLang: string) => void + showApiKey: showApiKey + setShowApiKey: (showApiKey: showApiKey) => void + apiKey: string | undefined + autoApiService: any +} + +const LangSelector: FC = ({ + selectedLang, + setSelectedLang, + showApiKey, + setShowApiKey, + apiKey, + autoApiService, +}) => { + const canReadServiceKey = checkPermissions( + PermissionAction.READ, + 'service_api_keys.service_role_key' + ) + + return ( +
+
+ + + {selectedLang == 'bash' && ( +
+
+ + Project API key : +
+ + setShowApiKey(DEFAULT_KEY)}> + hide + + {apiKey && ( + + setShowApiKey({ + key: apiKey, + name: 'anon (public)', + }) + } + > + anon (public) + + )} + {canReadServiceKey && ( + + setShowApiKey({ + key: autoApiService.serviceApiKey, + name: 'service_role (secret)', + }) + } + > + service_role (secret) + + )} + + } + > + + +
+ )} +
+
+ ) +} + +export default LangSelector diff --git a/studio/components/interfaces/Docs/ResourceContent.tsx b/studio/components/interfaces/Docs/ResourceContent.tsx index a37ed884081..21e6a3dc5fb 100644 --- a/studio/components/interfaces/Docs/ResourceContent.tsx +++ b/studio/components/interfaces/Docs/ResourceContent.tsx @@ -2,6 +2,7 @@ import Snippets from 'components/to-be-cleaned/Docs/Snippets' import CodeSnippet from 'components/to-be-cleaned/Docs/CodeSnippet' import Param from 'components/to-be-cleaned/Docs/Param' import Description from 'components/to-be-cleaned/Docs/Description' +import { IconTable } from 'ui' const ResourceContent = ({ autoApiService, @@ -29,12 +30,18 @@ const ResourceContent = ({ return ( <> -

- {resourceId} +

+ + + + {resourceId}

-
+
+ {properties.map((x) => (
-
+
-
-
+
+
-
+
))} @@ -87,8 +94,8 @@ const ResourceContent = ({ To read rows in {resourceId}, use the select method.

- - Learn more. + + Learn more

@@ -120,8 +127,11 @@ const ResourceContent = ({

Filtering

Supabase provides a wide range of filters.

- - Learn more. + + Learn more

@@ -147,8 +157,8 @@ const ResourceContent = ({ insert will also return the replaced values for UPSERT.

- - Learn more. + + Learn more

@@ -183,8 +193,8 @@ const ResourceContent = ({ update will also return the replaced values for UPDATE.

- - Learn more. + + Learn more

@@ -207,8 +217,8 @@ const ResourceContent = ({ default, so remember to specify your filters!

- - Learn more. + + Learn more

@@ -230,8 +240,8 @@ const ResourceContent = ({ users depending on Row Level Security (RLS) policies.

- - Learn more. + + Learn more

@@ -264,21 +274,6 @@ const ResourceContent = ({ - <> -

Much more

-
-
-

- These docs are a work in progress! See our{' '} - - docs - {' '} - for the additional functionality Supabase has to offer. -

-
-
-
- ) } diff --git a/studio/components/interfaces/Functions/EdgeFunctionDetails.tsx b/studio/components/interfaces/Functions/EdgeFunctionDetails.tsx new file mode 100644 index 00000000000..c93c1fefb66 --- /dev/null +++ b/studio/components/interfaces/Functions/EdgeFunctionDetails.tsx @@ -0,0 +1,332 @@ +import dayjs from 'dayjs' +import { useRouter } from 'next/router' +import { FC, useState, useEffect } from 'react' +import * as Tooltip from '@radix-ui/react-tooltip' +import { PermissionAction } from '@supabase/shared-types/out/constants' +import { + Alert, + IconGlobe, + IconTerminal, + IconMinimize2, + IconMaximize2, + IconCheck, + IconClipboard, + Button, + Modal, +} from 'ui' + +import { useStore, useParams, checkPermissions } from 'hooks' +import Panel from 'components/ui/Panel' +import CommandRender from './CommandRender' +import { useProjectApiQuery } from 'data/config/project-api-query' +import { useEdgeFunctionDeleteMutation } from 'data/edge-functions/edge-functions-delete-mutation' + +interface Props {} + +// [Joshen] Next - additional configs: Verify jwt + import maps + +const EdgeFunctionDetails: FC = () => { + const router = useRouter() + const { functions, ui } = useStore() + const { ref: projectRef, id } = useParams() + const [isCopied, setIsCopied] = useState(false) + const [showDeleteModal, setShowDeleteModal] = useState(false) + const [showInstructions, setShowInstructions] = useState(false) + const [selectedFunction, setSelectedFunction] = useState(null) + + const canDeleteEdgeFunction = checkPermissions(PermissionAction.FUNCTIONS_WRITE, '*') + const { mutateAsync: deleteEdgeFunction, isLoading: isDeleting } = useEdgeFunctionDeleteMutation() + + useEffect(() => { + setSelectedFunction(functions.byId(id)) + }, [functions.isLoaded, ui.selectedProject]) + + const { data: settings } = useProjectApiQuery({ projectRef }) + + // Get the API service + const apiService = settings?.autoApiService + const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key') + ? apiService.defaultApiKey + : undefined + + const endpoint = apiService?.app_config.endpoint ?? '' + const endpointSections = endpoint.split('.') + const functionsEndpoint = [ + ...endpointSections.slice(0, 1), + 'functions', + ...endpointSections.slice(1), + ].join('.') + const functionUrl = `${apiService?.protocol}://${functionsEndpoint}/${selectedFunction?.slug}` + + const onConfirmDelete = async () => { + if (!projectRef) return console.error('Project ref is required') + if (selectedFunction === undefined) return console.error('No edge function selected') + + try { + await deleteEdgeFunction({ projectRef, slug: selectedFunction.slug }) + ui.setNotification({ + category: 'success', + message: `Successfully deleted "${selectedFunction.name}"`, + }) + router.push(`/project/${projectRef}/functions`) + } catch (error: any) { + ui.setNotification({ + category: 'error', + message: `Failed to delete function: ${error.message}`, + }) + } + } + + const managementCommands: any = [ + { + command: `supabase functions deploy ${selectedFunction?.slug}`, + description: 'This will overwrite the deployed function with your new function', + jsx: () => { + return ( + <> + supabase functions deploy{' '} + {selectedFunction?.slug} + + ) + }, + comment: 'Deploy a new version', + }, + { + command: `supabase functions delete ${selectedFunction?.slug}`, + description: 'This will remove the function and all the logs associated with it', + jsx: () => { + return ( + <> + supabase functions delete{' '} + {selectedFunction?.slug} + + ) + }, + comment: 'Delete the function', + }, + ] + + const secretCommands: any = [ + { + command: `supabase secrets list`, + description: 'This will list all the secrets for your project', + jsx: () => { + return ( + <> + supabase secrets list + + ) + }, + comment: 'View all secrets', + }, + { + command: `supabase secrets set NAME1=VALUE1 NAME2=VALUE2`, + description: 'This will set secrets for your project', + jsx: () => { + return ( + <> + supabase secrets set NAME1=VALUE1 NAME2=VALUE2 + + ) + }, + comment: 'Set secrets for your project', + }, + { + command: `supabase secrets unset NAME1 NAME2 `, + description: 'This will delete secrets for your project', + jsx: () => { + return ( + <> + supabase secrets unset NAME1 NAME2 + + ) + }, + comment: 'Unset secrets for your project', + }, + ] + + const invokeCommands: any = [ + { + command: `curl -L -X POST '${functionUrl}' -H 'Authorization: Bearer ${ + anonKey ?? '[YOUR ANON KEY]' + }' --data '{"name":"Functions"}'`, + description: 'Invokes the hello function', + jsx: () => { + return ( + <> + curl -L -X POST 'https://{functionsEndpoint}/ + {selectedFunction?.slug}' -H 'Authorization: Bearer [YOUR ANON KEY]'{' '} + {`--data '{"name":"Functions"}'`} + + ) + }, + comment: 'Invoke your function', + }, + ] + + return ( + <> +
+
+
+

Function Name

+

{selectedFunction?.name}

+
+ +
+

Endpoint URL

+

{functionUrl}

+ +
+ +
+

Created At

+

+ {selectedFunction?.created_at && + dayjs(selectedFunction.created_at).format('dddd, MMMM D, YYYY h:mm A')} +

+
+ +
+

Last Updated At

+

+ {selectedFunction?.updated_at && + dayjs(selectedFunction.updated_at).format('dddd, MMMM D, YYYY h:mm A')} +

+
+ +
+ Deployments +
{selectedFunction?.version}
+
+ +
+ Regions +
+
+ + Earth +
+ All functions are deployed globally +
+
+
+ +
+
+
+
+ +
+

Command line access

+
+
setShowInstructions(!showInstructions)}> + {showInstructions ? ( + + ) : ( + + )} +
+
+ +
Deployment management
+ +
Invoke
+ +
Secrets management
+ +
+ + Delete Edge Function

}> + + +

+ Make sure you have made a backup if you want to restore your edge function +

+ + + + + {!canDeleteEdgeFunction && ( + + +
+ + You need additional permissions to delete an edge function + +
+
+ )} +
+
+
+
+
+ + Confirm to delete {selectedFunction?.name}} + visible={showDeleteModal} + loading={isDeleting} + onCancel={() => setShowDeleteModal(false)} + onConfirm={onConfirmDelete} + > +
+ + + Ensure that you have made a backup if you want to restore your edge function + + +
+
+ + ) +} + +export default EdgeFunctionDetails diff --git a/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx b/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx new file mode 100644 index 00000000000..0d9ce1f727b --- /dev/null +++ b/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx @@ -0,0 +1,103 @@ +import dayjs from 'dayjs' +import { FC, useState } from 'react' +import { useRouter } from 'next/router' +import { observer } from 'mobx-react-lite' +import { IconCheck, IconClipboard } from 'ui' +import * as Tooltip from '@radix-ui/react-tooltip' + +import { useParams, useStore } from 'hooks' +import Table from 'components/to-be-cleaned/Table' +import { EdgeFunctionsResponse } from 'data/edge-functions/edge-functions-query' + +interface Props { + function: EdgeFunctionsResponse +} + +const EdgeFunctionsListItem: FC = ({ function: item }) => { + const router = useRouter() + const { ui } = useStore() + const { ref } = useParams() + const [isCopied, setIsCopied] = useState(false) + + // get the .co or .net TLD from the restUrl + const restUrl = ui.selectedProject?.restUrl + const restUrlTld = new URL(restUrl as string).hostname.split('.').pop() + const functionUrl = `https://${ref}.functions.supabase.${restUrlTld}/${item.slug}` + + return ( + { + router.push(`/project/${ref}/functions/${item.id}/details`) + }} + > + +
+

{item.name}

+
+
+ +
+

{functionUrl}

+ +
+
+ +

{dayjs(item.created_at).format('DD MMM, YYYY HH:mm')}

+
+ + + +
+

{dayjs(item.updated_at).fromNow()}

+
+
+ + +
+ + Last updated on {dayjs(item.updated_at).format('DD MMM, YYYY HH:mm')} + +
+
+
+
+ +

{item.version}

+
+
+ ) +} + +export default observer(EdgeFunctionsListItem) diff --git a/studio/components/interfaces/Functions/FunctionsListItem.tsx b/studio/components/interfaces/Functions/FunctionsListItem.tsx deleted file mode 100644 index f2b9045d417..00000000000 --- a/studio/components/interfaces/Functions/FunctionsListItem.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import dayjs from 'dayjs' -import { FC } from 'react' -import { useRouter } from 'next/router' -import { observer } from 'mobx-react-lite' - -import { useStore } from 'hooks' -import Table from 'components/to-be-cleaned/Table' - -interface Props { - function: any -} - -const FunctionsListItem: FC = ({ function: item }) => { - const { ui } = useStore() - const is_functionConfirmed = item.email_confirmed_at || item.phone_confirmed_at - - const router = useRouter() - const ref = ui?.selectedProject?.ref - - // get the .co or .net TLD from the restUrl - const restUrl = ui.selectedProject?.restUrl - const restUrlTld = new URL(restUrl as string).hostname.split('.').pop() - - return ( - { - router.push(`/project/${ref}/functions/${item.id}`) - }} - > - -
- {item.name} -
-
- -
- {`https://${ref}.functions.supabase.${restUrlTld}/${item.slug}`} - {`/${item.name}`} -
-
- - - {dayjs(item.created_at).format('DD MMM, YYYY HH:mm')} - - - - - {dayjs(item.updated_at).format('DD MMM, YYYY HH:mm')} - - - - v{item.version} - - - {item.status} - -
- ) -} - -export default observer(FunctionsListItem) diff --git a/studio/components/interfaces/Functions/FunctionsNav.tsx b/studio/components/interfaces/Functions/FunctionsNav.tsx index dfe6bd5ab13..af24e28d29f 100644 --- a/studio/components/interfaces/Functions/FunctionsNav.tsx +++ b/studio/components/interfaces/Functions/FunctionsNav.tsx @@ -1,8 +1,7 @@ import { Tabs } from 'ui' import { useRouter } from 'next/router' -// @ts-ignore -const FunctionsNav = ({ item }) => { +const FunctionsNav = ({ item }: any) => { const router = useRouter() const activeRoute = router.pathname.split('/')[5] const { ref } = router.query @@ -17,9 +16,8 @@ const FunctionsNav = ({ item }) => { router.push(`/project/${ref}/functions/${item.id}/${e === 'metrics' ? '' : e}`) } > - - {/* */} + diff --git a/studio/components/interfaces/Functions/TerminalInstructions.tsx b/studio/components/interfaces/Functions/TerminalInstructions.tsx index f8f30b523ab..16a2e2eea21 100644 --- a/studio/components/interfaces/Functions/TerminalInstructions.tsx +++ b/studio/components/interfaces/Functions/TerminalInstructions.tsx @@ -10,19 +10,16 @@ import { Commands } from './Functions.types' interface Props { closable?: boolean + removeBorder?: boolean } -const TerminalInstructions: FC = ({ closable = false }) => { +const TerminalInstructions: FC = ({ closable = false, removeBorder = false }) => { const router = useRouter() const { ref: projectRef } = useParams() - const [showInstructions, setShowInstructions] = useState(!closable) - const { data: tokens } = useAccessTokensQuery() + const { data: settings } = useProjectApiQuery({ projectRef }) - const { data: settings } = useProjectApiQuery({ - projectRef, - }) const apiService = settings?.autoApiService const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key') ? apiService.defaultApiKey @@ -86,7 +83,9 @@ const TerminalInstructions: FC = ({ closable = false }) => { return (
@@ -107,7 +106,7 @@ const TerminalInstructions: FC = ({ closable = false }) => {
)}
-
+
diff --git a/studio/components/interfaces/Functions/index.ts b/studio/components/interfaces/Functions/index.ts index b096ff5e604..003d5feaca6 100644 --- a/studio/components/interfaces/Functions/index.ts +++ b/studio/components/interfaces/Functions/index.ts @@ -1,5 +1,6 @@ -import FunctionsListItem from './FunctionsListItem' +import EdgeFunctionDetails from './EdgeFunctionDetails' +import EdgeFunctionsListItem from './EdgeFunctionsListItem' import FunctionsEmptyState from './FunctionsEmptyState' import TerminalInstructions from './TerminalInstructions' -export { FunctionsListItem, FunctionsEmptyState, TerminalInstructions } +export { EdgeFunctionDetails, EdgeFunctionsListItem, FunctionsEmptyState, TerminalInstructions } diff --git a/studio/components/interfaces/GraphQL/GraphiQL.tsx b/studio/components/interfaces/GraphQL/GraphiQL.tsx new file mode 100644 index 00000000000..4780cf40d25 --- /dev/null +++ b/studio/components/interfaces/GraphQL/GraphiQL.tsx @@ -0,0 +1,583 @@ +/* Based on https://github.com/graphql/graphiql/blob/main/packages/graphiql/src/components/GraphiQL.tsx */ + +import { + Button, + ChevronDownIcon, + ChevronUpIcon, + CopyIcon, + Dialog, + ExecuteButton, + GraphiQLProvider, + HeaderEditor, + KeyboardShortcutIcon, + MergeIcon, + PlusIcon, + PrettifyIcon, + QueryEditor, + ReloadIcon, + ResponseEditor, + SettingsIcon, + Spinner, + Tab, + Tabs, + ToolbarButton, + Tooltip, + UnStyledButton, + useCopyQuery, + useDragResize, + useEditorContext, + useExecutionContext, + useMergeQuery, + usePluginContext, + usePrettifyEditors, + useSchemaContext, + useStorageContext, + useTheme, + VariableEditor, +} from '@graphiql/react' +import { Fetcher } from '@graphiql/toolkit' +import clsx from 'clsx' +import 'graphiql/graphiql.css' +import { PropsWithChildren, useEffect, useState } from 'react' +import styles from './graphiql.module.css' + +export type GraphiQLProps = { + fetcher: Fetcher + theme?: 'dark' | 'light' + apiKey?: string +} + +const GraphiQL = ({ fetcher, theme = 'dark', apiKey }: GraphiQLProps) => { + // Ensure props are correct + if (typeof fetcher !== 'function') { + throw new TypeError( + 'The `GraphiQL` component requires a `fetcher` function to be passed as prop.' + ) + } + + return ( + + + + ) +} + +type GraphiQLInterfaceProps = { + theme: 'dark' | 'light' +} + +export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => { + const editorContext = useEditorContext({ nonNull: true }) + const executionContext = useExecutionContext({ nonNull: true }) + const schemaContext = useSchemaContext({ nonNull: true }) + const storageContext = useStorageContext() + const pluginContext = usePluginContext() + + const copy = useCopyQuery() + const merge = useMergeQuery() + const prettify = usePrettifyEditors() + + const { setTheme } = useTheme() + useEffect(() => { + setTheme(theme) + }, [theme]) + + const PluginContent = pluginContext?.visiblePlugin?.content + + const pluginResize = useDragResize({ + defaultSizeRelation: 1 / 3, + direction: 'horizontal', + initiallyHidden: pluginContext?.visiblePlugin ? undefined : 'second', + onHiddenElementChange: (resizableElement) => { + if (resizableElement === 'first') { + pluginContext?.setVisiblePlugin(null) + } + }, + sizeThresholdSecond: 200, + storageKey: 'docExplorerFlex', + }) + const editorResize = useDragResize({ + direction: 'horizontal', + storageKey: 'editorFlex', + }) + const editorToolsResize = useDragResize({ + defaultSizeRelation: 3, + direction: 'vertical', + initiallyHidden: (() => { + return editorContext.initialVariables || editorContext.initialHeaders ? undefined : 'second' + })(), + sizeThresholdSecond: 60, + storageKey: 'secondaryEditorFlex', + }) + + const [activeSecondaryEditor, setActiveSecondaryEditor] = useState<'variables' | 'headers'>( + () => { + return !editorContext.initialVariables && editorContext.initialHeaders + ? 'headers' + : 'variables' + } + ) + const [showDialog, setShowDialog] = useState<'settings' | 'short-keys' | null>(null) + const [clearStorageStatus, setClearStorageStatus] = useState<'success' | 'error' | null>(null) + + const logo = + + const toolbar = ( + <> + prettify()} label="Prettify query (Shift-Ctrl-P)"> + + merge()} label="Merge fragments into query (Shift-Ctrl-M)"> + + copy()} label="Copy query (Shift-Ctrl-C)"> + + + ) + + const onClickReference = () => { + if (pluginResize.hiddenElement === 'second') { + pluginResize.setHiddenElement(null) + } + } + + const modifier = + window.navigator.platform.toLowerCase().indexOf('mac') === 0 ? ( + Cmd + ) : ( + Ctrl + ) + + return ( +
+
+
+
+
+ + {editorContext.tabs.length > 1 ? ( + <> + {editorContext.tabs.map((tab, index) => ( + + { + executionContext.stop() + editorContext.changeTab(index) + }} + > + {tab.title} + + { + if (editorContext.activeTabIndex === index) { + executionContext.stop() + } + editorContext.closeTab(index) + }} + /> + + ))} +
+ + editorContext.addTab()} + aria-label="Add tab" + > + + +
+ + ) : null} +
+
+ {editorContext.tabs.length === 1 ? ( +
+ + editorContext.addTab()} + aria-label="Add tab" + > + + +
+ ) : null} + {logo} +
+
+
+
+
+
+
+
+ +
+
+ + {toolbar} +
+
+
+
+
+
+ { + if (editorToolsResize.hiddenElement === 'second') { + editorToolsResize.setHiddenElement(null) + } + setActiveSecondaryEditor('variables') + }} + > + Variables + + + { + if (editorToolsResize.hiddenElement === 'second') { + editorToolsResize.setHiddenElement(null) + } + setActiveSecondaryEditor('headers') + }} + > + Headers + +
+ + { + editorToolsResize.setHiddenElement( + editorToolsResize.hiddenElement === 'second' ? null : 'second' + ) + }} + aria-label={ + editorToolsResize.hiddenElement === 'second' + ? 'Show editor tools' + : 'Hide editor tools' + } + > + {editorToolsResize.hiddenElement === 'second' ? ( + + +
+
+
+
+ + + +
+
+
+
+
+
+
+
+
+ {executionContext.isFetching ? : null} + +
+
+
+
+
+ +
+ {pluginContext?.visiblePlugin ?
: null} +
+ +
+
{PluginContent ? : null}
+
+
+
+
+ {pluginContext?.plugins.map((plugin) => { + const isVisible = plugin === pluginContext.visiblePlugin + const label = `${isVisible ? 'Hide' : 'Show'} ${plugin.title}` + const Icon = plugin.icon + return ( + + { + if (isVisible) { + pluginContext.setVisiblePlugin(null) + pluginResize.setHiddenElement('second') + } else { + pluginContext.setVisiblePlugin(plugin) + pluginResize.setHiddenElement(null) + } + }} + aria-label={label} + > + + + ) + })} +
+
+ + schemaContext.introspect()} + aria-label="Re-fetch GraphQL schema" + > + + + + setShowDialog('short-keys')} + aria-label="Open short keys dialog" + > + + + + setShowDialog('settings')} + aria-label="Open settings dialog" + > + + +
+
+ setShowDialog(null)}> +
+
Short Keys
+ setShowDialog(null)} /> +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Short keyFunction
+ {modifier} + {' + '} + F + Search in editor
+ {modifier} + {' + '} + K + Search in documentation
+ {modifier} + {' + '} + Enter + Execute query
+ Ctrl + {' + '} + Shift + {' + '} + P + Prettify editors
+ Ctrl + {' + '} + Shift + {' + '} + M + Merge fragments definitions into operation definition
+ Ctrl + {' + '} + Shift + {' + '} + C + Copy query
+ Ctrl + {' + '} + Shift + {' + '} + R + Re-fetch schema using introspection
+

+ The editors use{' '} + + CodeMirror Key Maps + {' '} + that add more short keys. This instance of GraphiQL uses sublime + . +

+
+
+
+ { + setShowDialog(null) + setClearStorageStatus(null) + }} + > +
+
Settings
+ { + setShowDialog(null) + setClearStorageStatus(null) + }} + /> +
+ + {storageContext ? ( +
+
+
Clear storage
+
+ Remove all locally stored data and start fresh. +
+
+
+ +
+
+ ) : null} +
+
+ ) +} + +// Configure the UI by providing this Component as a child of GraphiQL. +function GraphiQLLogo(props: PropsWithChildren) { + return ( +
+ {props.children || ( + + Graph + i + QL + + )} +
+ ) +} + +GraphiQLLogo.displayName = 'GraphiQLLogo' + +export default GraphiQL diff --git a/studio/components/interfaces/GraphQL/graphiql.module.css b/studio/components/interfaces/GraphQL/graphiql.module.css new file mode 100644 index 00000000000..dc574beed61 --- /dev/null +++ b/studio/components/interfaces/GraphQL/graphiql.module.css @@ -0,0 +1,27 @@ +.graphiqlContainer .graphiqlSessions { + margin: 0; + border-radius: 0; +} + +.graphiqlContainer .graphiqlSession { + padding: 0; +} + +.graphiqlContainer .graphiqlEditors { + border-radius: 0; +} + +.graphiqlContainer .graphiqlEditors:global(.full-height) { + margin-top: calc(0px - var(--session-header-height)); +} + +/* Colors */ +:global(body.graphiql-dark) .graphiqlContainer { + --color-base: 0, 0%, 11%; + --color-primary: 153, 50%, 50%; +} + +:global(body.graphiql-light) .graphiqlContainer { + --color-base: 210, 17%, 98%; + --color-primary: 153, 50%, 50%; +} diff --git a/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts b/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts index 2483efe39da..f1b8e5c4c85 100644 --- a/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts +++ b/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts @@ -969,4 +969,106 @@ GRANT ALL ON TABLE next_auth.verification_tokens TO postgres; GRANT ALL ON TABLE next_auth.verification_tokens TO service_role; `.trim(), }, + { + id: 16, + type: 'template', + title: 'Most frequently invoked', + description: 'Most frequently called queries in your database.', + sql: `-- Most frequently called queries + +-- A limit of 100 has been added below + +select + auth.rolname, + statements.query, + statements.calls, + -- -- Postgres 13, 14, 15 + statements.total_exec_time + statements.total_plan_time as total_time, + statements.min_exec_time + statements.min_plan_time as min_time, + statements.max_exec_time + statements.max_plan_time as max_time, + statements.mean_exec_time + statements.mean_plan_time as mean_time, + -- -- Postgres <= 12 + -- total_time, + -- min_time, + -- max_time, + -- mean_time, + statements.rows / statements.calls as avg_rows + + from pg_stat_statements as statements + inner join pg_authid as auth on statements.userid = auth.oid + order by + statements.calls desc + limit + 100;`, + }, + { + id: 17, + type: 'template', + title: 'Most time consuming', + description: 'Aggregate time spent on a query type.', + sql: `-- Most time consuming queries + +-- A limit of 100 has been added below + +select + auth.rolname, + statements.query, + statements.calls, + statements.total_exec_time + statements.total_plan_time as total_time, + to_char(((statements.total_exec_time + statements.total_plan_time)/sum(statements.total_exec_time + statements.total_plan_time) over()) * 100, 'FM90D0') || '%' as prop_total_time + from pg_stat_statements as statements + inner join pg_authid as auth on statements.userid = auth.oid + order by + total_time desc + limit + 100;`, + }, + { + id: 18, + type: 'template', + title: 'Slowest execution time', + description: 'Slowest queries based on max execution time.', + sql: `-- Slowest queries by max execution time + +-- A limit of 100 has been added below + +select + auth.rolname, + statements.query, + statements.calls, + -- -- Postgres 13, 14, 15 + statements.total_exec_time + statements.total_plan_time as total_time, + statements.min_exec_time + statements.min_plan_time as min_time, + statements.max_exec_time + statements.max_plan_time as max_time, + statements.mean_exec_time + statements.mean_plan_time as mean_time, + -- -- Postgres <= 12 + -- total_time, + -- min_time, + -- max_time, + -- mean_time, + statements.rows / statements.calls as avg_rows + from pg_stat_statements as statements + inner join pg_authid as auth on statements.userid = auth.oid + order by + max_time desc + limit + 100;`, + }, + { + id: 19, + type: 'template', + title: 'Hit rate', + description: 'See your cache and index hit rate.', + sql: `-- Cache and index hit rate + +select + 'index hit rate' as name, + (sum(idx_blks_hit)) / nullif(sum(idx_blks_hit + idx_blks_read),0) as ratio + from pg_statio_user_indexes + union all + select + 'table hit rate' as name, + sum(heap_blks_hit) / nullif(sum(heap_blks_hit) + sum(heap_blks_read),0) as ratio + from pg_statio_user_tables;`, + } ] diff --git a/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx b/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx index 111a003258a..43ce15af121 100644 --- a/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx +++ b/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx @@ -1,6 +1,6 @@ import { FC, useState, useEffect, Fragment } from 'react' import { observer } from 'mobx-react-lite' -import { useStore } from 'hooks' +import { checkPermissions, useStore } from 'hooks' import { pluckObjectFields } from 'lib/helpers' import Loading from 'components/ui/Loading' import Panel from 'components/ui/Panel' @@ -12,6 +12,7 @@ import ToggleField from 'components/to-be-cleaned/forms/ToggleField' import SchemaFormPanel from 'components/to-be-cleaned/forms/SchemaFormPanel' import { Input } from 'ui' import ShimmeringLoader from 'components/ui/ShimmeringLoader' +import { PermissionAction } from '@supabase/shared-types/out/constants' interface Props {} @@ -127,6 +128,11 @@ export const PgbouncerConfig: FC = observer( ({ projectRef, bouncerInfo, connectionInfo }) => { const { ui } = useStore() + const canUpdateConnectionPoolingConfiguration = checkPermissions( + PermissionAction.UPDATE, + 'projects' + ) + const [updates, setUpdates] = useState({ pgbouncer_enabled: bouncerInfo.pgbouncer_enabled, pool_mode: bouncerInfo.pool_mode || 'transaction', @@ -198,6 +204,8 @@ export const PgbouncerConfig: FC = observer( onChangeModel={(model: any) => setUpdates(model)} onSubmit={(model: any) => updateConfig(model)} onReset={() => setUpdates(bouncerInfo)} + disabled={!canUpdateConnectionPoolingConfiguration} + disabledMessage="You need additional permissions to update connection pooling settings" >
diff --git a/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx b/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx index 7fa753067e7..b3c47c59119 100644 --- a/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx +++ b/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx @@ -1,8 +1,10 @@ import Link from 'next/link' -import { useState } from 'react' +import { FC, useState } from 'react' +import * as Tooltip from '@radix-ui/react-tooltip' import { Button, IconAlertCircle, IconExternalLink, IconGlobe, IconLock } from 'ui' +import { PermissionAction } from '@supabase/shared-types/out/constants' -import { useParams } from 'hooks' +import { checkPermissions, useParams } from 'hooks' import Panel from 'components/ui/Panel' import { FormPanel, FormHeader } from 'components/ui/Forms' import ShimmeringLoader from 'components/ui/ShimmeringLoader' @@ -12,6 +14,62 @@ import DisallowAllModal from './DisallowAllModal' import AllowAllModal from './AllowAllModal' import { useNetworkRestrictionsQuery } from 'data/network-restrictions/network-restrictions-query' +const AllowAllAccessButton: FC<{ disabled: boolean; onClick: (value: boolean) => void }> = ({ + disabled, + onClick, +}) => ( + + + + + {disabled && ( + + +
+ + You need additional permissions to update network restrictions + +
+
+ )} +
+) + +const DisallowAllAccessButton: FC<{ disabled: boolean; onClick: (value: boolean) => void }> = ({ + disabled, + onClick, +}) => ( + + + + + {disabled && ( + + +
+ + You need additional permissions to update network restrictions + +
+
+ )} +
+) + const NetworkRestrictions = ({}) => { const { ref } = useParams() @@ -21,6 +79,8 @@ const NetworkRestrictions = ({}) => { const [selectedRestrictionToRemove, setSelectedRestrictionToRemove] = useState() const { data, isLoading } = useNetworkRestrictionsQuery({ projectRef: ref }) + const canUpdateNetworkRestrictions = checkPermissions(PermissionAction.UPDATE, 'projects') + const hasAccessToRestrictions = data?.entitlement === 'allowed' const restrictedIps = data?.config.dbAllowedCidrs ?? [] const restrictionStatus = data?.status ?? '' @@ -48,7 +108,31 @@ const NetworkRestrictions = ({}) => { - + + + + + {!canUpdateNetworkRestrictions && ( + + +
+ + You need additional permissions to update network restrictions + +
+
+ )} +
{isLoading ? ( @@ -75,12 +159,14 @@ const NetworkRestrictions = ({}) => {

- - + +
@@ -101,9 +187,10 @@ const NetworkRestrictions = ({}) => {
- +
) : isDisallowedAll ? ( @@ -125,9 +212,10 @@ const NetworkRestrictions = ({}) => {
- +
) : ( @@ -146,12 +234,14 @@ const NetworkRestrictions = ({}) => {

- - + +
{restrictedIps.map((ip) => { diff --git a/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx b/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx index 192c6137897..20935a97d97 100644 --- a/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx +++ b/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx @@ -1,8 +1,10 @@ import Link from 'next/link' import { useState, useEffect } from 'react' -import { useParams, useStore, useFlag } from 'hooks' import * as Tooltip from '@radix-ui/react-tooltip' import { Button, IconDownload, Toggle, IconLoader, Alert } from 'ui' +import { PermissionAction } from '@supabase/shared-types/out/constants' + +import { checkPermissions, useParams, useStore, useFlag } from 'hooks' import { FormHeader, FormPanel, @@ -27,6 +29,8 @@ const SSLConfiguration = () => { }) const { mutateAsync: updateSSLEnforcement } = useSSLEnforcementUpdateMutation() + const canUpdateSSLEnforcement = checkPermissions(PermissionAction.UPDATE, 'projects') + const hasAccessToSSLEnforcement = !sslEnforcementConfiguration?.isNotAllowed const env = process.env.NEXT_PUBLIC_ENVIRONMENT === 'prod' ? 'prod' : 'staging' const hasSSLCertificate = diff --git a/studio/components/interfaces/Settings/Logs/LogsErrorRenderers/ResourcesExceededErrorRenderer.tsx b/studio/components/interfaces/Settings/Logs/LogsErrorRenderers/ResourcesExceededErrorRenderer.tsx index 2473f64aa19..c8b76284adc 100644 --- a/studio/components/interfaces/Settings/Logs/LogsErrorRenderers/ResourcesExceededErrorRenderer.tsx +++ b/studio/components/interfaces/Settings/Logs/LogsErrorRenderers/ResourcesExceededErrorRenderer.tsx @@ -19,7 +19,6 @@ const ResourcesExceededErrorRenderer: React.FC = ({ error, i type="default" chevronAlign="left" size="small" - bordered={false} iconPosition="left" > diff --git a/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.tsx b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.tsx index a7d3134706e..c24fbe5a685 100644 --- a/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.tsx +++ b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.tsx @@ -1,16 +1,29 @@ +import Link from 'next/link' import { FC, useEffect } from 'react' -import { Badge, Button, IconAlertCircle, IconInfo, Loading, IconExternalLink } from 'ui' +import { useRouter } from 'next/router' +import * as Tooltip from '@radix-ui/react-tooltip' +import { PermissionAction } from '@supabase/shared-types/out/constants' +import { + Badge, + Button, + IconAlertCircle, + IconInfo, + Loading, + IconExternalLink, + Alert, + IconBookOpen, +} from 'ui' -import { useStore } from 'hooks' +import { checkPermissions, useStore } from 'hooks' import { formatBytes } from 'lib/helpers' import { PRICING_TIER_PRODUCT_IDS, USAGE_APPROACHING_THRESHOLD } from 'lib/constants' import SparkBar from 'components/ui/SparkBar' import ShimmeringLoader from 'components/ui/ShimmeringLoader' import InformationBox from 'components/ui/InformationBox' import { USAGE_BASED_PRODUCTS } from 'components/interfaces/Billing/Billing.constants' +import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext' +import { useProjectReadOnlyQuery } from 'data/config/project-read-only-query' import { ProjectUsageResponseUsageKeys, useProjectUsageQuery } from 'data/usage/project-usage-query' -import { useRouter } from 'next/router' -import * as Tooltip from '@radix-ui/react-tooltip' interface Props { projectRef?: string @@ -21,8 +34,18 @@ const ProjectUsage: FC = ({ projectRef }) => { const { data: usage, error, isLoading } = useProjectUsageQuery({ projectRef }) const router = useRouter() - const subscriptionTier = ui.selectedProject?.subscription_tier + const { project } = useProjectContext() + const { data: isReadOnlyMode } = useProjectReadOnlyQuery({ + projectRef: project?.ref, + connectionString: project?.connectionString, + }) + const canUpdateSubscription = checkPermissions( + PermissionAction.BILLING_WRITE, + 'stripe.subscriptions' + ) + + const subscriptionTier = ui.selectedProject?.subscription_tier const projectHasNoLimits = subscriptionTier === PRICING_TIER_PRODUCT_IDS.PAYG || subscriptionTier === PRICING_TIER_PRODUCT_IDS.TEAM || @@ -62,13 +85,12 @@ const ProjectUsage: FC = ({ projectRef }) => { const isPaidTier = subscriptionTier !== PRICING_TIER_PRODUCT_IDS.FREE - const featureFootnotes: Record = { - db_size: ( + const featureFootnotes: Record = { + db_size: isPaidTier ? (
{usage?.disk_volume_size_gb && Disk Size: {usage.disk_volume_size_gb} GB} - - {isPaidTier && Auto-Scaling} + Auto-Scaling
- ), + ) : null, } return ( @@ -127,7 +149,6 @@ const ProjectUsage: FC = ({ projectRef }) => { - {/* Line items */} {usage === undefined ? (
@@ -148,14 +169,16 @@ const ProjectUsage: FC = ({ projectRef }) => { usageElement = (
Not included in {planName} tier - + {canUpdateSubscription && ( + + )}
) } else if (showUsageExceedMessage) { @@ -253,6 +276,121 @@ const ProjectUsage: FC = ({ projectRef }) => { )} + + {isReadOnlyMode && product.title === 'Database' && ( +
+ +

+ {isPaidTier ? ( + <> + Your disk has reached 95% capacity and has entered{' '} + + read-only mode + + . + + ) : ( + <> + You have exceeded the 500mb Database size limit and your project is now + in{' '} + + read-only mode + + . + + )} +

+ {isPaidTier ? ( + <> +

+ For Pro and Enterprise projects,{' '} + + Disk Size expands automatically + {' '} + when it reaches 90% capacity, but can only occur once every six hours. + If the disk size has already expanded and then reaches 95% capacity + within 6 hours, then{' '} + + your disk will enter read-only mode + {' '} + until it can resize again after 6 hours. +

+

+ If you require help or need your disk changed to read/write mode so you + can delete data,{' '} + + + you can contact the support team + + + . +

+ + ) : ( +

+ You can either{' '} + + reduce your disk usage below 500mb + {' '} + or{' '} + + + upgrade your project + + + . +

+ )} + + {!isPaidTier ? ( + + ) : ( + + )} +
+
+ )}
) })} diff --git a/studio/components/interfaces/Settings/Vault/Keys/EncryptionKeysManagement.tsx b/studio/components/interfaces/Settings/Vault/Keys/EncryptionKeysManagement.tsx index 876805da8a1..63cac0d9820 100644 --- a/studio/components/interfaces/Settings/Vault/Keys/EncryptionKeysManagement.tsx +++ b/studio/components/interfaces/Settings/Vault/Keys/EncryptionKeysManagement.tsx @@ -1,6 +1,7 @@ import dayjs from 'dayjs' import Link from 'next/link' import { observer } from 'mobx-react-lite' +import * as Tooltip from '@radix-ui/react-tooltip' import { FC, Fragment, useEffect, useState } from 'react' import { Alert, @@ -11,13 +12,13 @@ import { Modal, Form, IconTrash, - Badge, IconKey, IconLoader, IconX, IconExternalLink, } from 'ui' -import { useParams, useStore } from 'hooks' +import { PermissionAction } from '@supabase/shared-types/out/constants' +import { useParams, useStore, checkPermissions } from 'hooks' import Divider from 'components/ui/Divider' const DEFAULT_KEY_NAME = 'No description provided' @@ -34,6 +35,8 @@ const EncryptionKeysManagement: FC = ({}) => { const [selectedKeyToRemove, setSelectedKeyToRemove] = useState() const [isDeletingKey, setIsDeletingKey] = useState(false) + const canManageKeys = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables') + useEffect(() => { if (id !== undefined) setSearchValue(id) }, [id]) @@ -143,9 +146,32 @@ const EncryptionKeysManagement: FC = ({}) => { - + + + + + {!canManageKeys && ( + + +
+ + You need additional permissions to add keys + +
+
+ )} +
@@ -178,12 +204,32 @@ const EncryptionKeysManagement: FC = ({}) => {

Added on {dayjs(key.created).format('MMM D, YYYY')}

- - + + + + + {!canManageSecrets && ( + + +
+ + You need additional permissions to add secrets + +
+
+ )} +
diff --git a/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx index 198e9a2a964..9996fc88488 100644 --- a/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx +++ b/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx @@ -1,21 +1,78 @@ import { FC } from 'react' import Link from 'next/link' -import { Button, IconAlertCircle, IconLock } from 'ui' +import { Button, IconAlertCircle, IconCode, IconLock } from 'ui' +import * as Tooltip from '@radix-ui/react-tooltip' import type { PostgresPolicy, PostgresTable } from '@supabase/postgres-meta' -import { useStore } from 'hooks' +import { useStore, checkPermissions } from 'hooks' +import { PermissionAction } from '@supabase/shared-types/out/constants' interface Props { table: PostgresTable + apiPreviewPanelOpen: boolean + setApiPreviewPanelOpen: (apiPreviewPanelOpen: boolean) => void + refreshDocs: () => void } -const GridHeaderActions: FC = ({ table }) => { +const GridHeaderActions: FC = ({ + table, + apiPreviewPanelOpen, + setApiPreviewPanelOpen, + refreshDocs, +}) => { const { ui, meta } = useStore() const projectRef = ui.selectedProject?.ref const policies = meta.policies.list((policy: PostgresPolicy) => policy.table_id === table.id) + const isReadOnly = + !checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables') && + !checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'columns') + + function handlePreviewToggle() { + setApiPreviewPanelOpen(!apiPreviewPanelOpen) + refreshDocs() + } + + const RenderAPIPreviewToggle = () => { + return ( + + ) + } + return (
+ {isReadOnly && ( + + +
+ Viewing as read-only +
+
+ + +
+ + You need additional permissions to manage your project's data + +
+
+
+ )} +
+ +
+ + + + + +
- - {name && ( - <> - - - - - -
{name}
- - )} {item && } @@ -140,6 +161,24 @@ const FunctionsLayout: FC = ({ title, children }) => { )} + + setShowTerminalInstructions(false)} + header={

Deploying an edge function to your project

} + customFooter={ +
+ +
+ } + > +
+ +
+
) } diff --git a/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx b/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx index cf8789a80e2..90700cd6c35 100644 --- a/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx +++ b/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx @@ -11,19 +11,30 @@ import HelpPopover from './HelpPopover' import NotificationsPopover from './NotificationsPopover' import { getResourcesExceededLimits } from 'components/ui/OveragesBanner/OveragesBanner.utils' import { useProjectUsageQuery } from 'data/usage/project-usage-query' +import { useProjectReadOnlyQuery } from 'data/config/project-read-only-query' +import { Badge } from 'ui' +import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext' const LayoutHeader = ({ customHeaderComponents, breadcrumbs = [], headerBorder = true }: any) => { const { ui } = useStore() const { selectedOrganization, selectedProject } = ui const { ref: projectRef } = useParams() + const { project } = useProjectContext() + + const { data: isReadOnlyMode } = useProjectReadOnlyQuery({ + projectRef: project?.ref, + connectionString: project?.connectionString, + }) const { data: usage } = useProjectUsageQuery({ projectRef }) const resourcesExceededLimits = getResourcesExceededLimits(usage) + const projectHasNoLimits = ui.selectedProject?.subscription_tier === PRICING_TIER_PRODUCT_IDS.PAYG || ui.selectedProject?.subscription_tier === PRICING_TIER_PRODUCT_IDS.ENTERPRISE || ui.selectedProject?.subscription_tier === PRICING_TIER_PRODUCT_IDS.TEAM + const showOverUsageBadge = selectedProject?.subscription_tier !== undefined && !projectHasNoLimits && @@ -63,6 +74,18 @@ const LayoutHeader = ({ customHeaderComponents, breadcrumbs = [], headerBorder = {/* Project Dropdown */} + {/* [Terry] Temporary until we figure out how we want to display this permanently */} + {/* context: https://www.notion.so/supabase/DB-Disk-Size-Free-tier-Read-only-Critical-f2b8937c13a149e3ac769fe5888f6db0*/} + {isReadOnlyMode && ( + + )} + {/* [Joshen TODO] Temporarily hidden until usage endpoint is sorted out */} {/* {showOverUsageBadge && (
diff --git a/studio/components/layouts/StorageLayout/StorageLayout.tsx b/studio/components/layouts/StorageLayout/StorageLayout.tsx index 93b1d1346ea..53432b6461c 100644 --- a/studio/components/layouts/StorageLayout/StorageLayout.tsx +++ b/studio/components/layouts/StorageLayout/StorageLayout.tsx @@ -40,6 +40,7 @@ const StorageLayout: FC = ({ title, children }) => { buckets, } = storageExplorerStore || {} + // [Joshen] At the moment, without the service key, we won't be able to pull any data from storage const { data: settings, isLoading } = useProjectApiQuery({ projectRef }) const apiService = settings?.autoApiService const serviceKey = find(apiService?.service_api_keys ?? [], (key) => key.tags === 'service_role') diff --git a/studio/components/layouts/StorageLayout/StorageMenu.tsx b/studio/components/layouts/StorageLayout/StorageMenu.tsx index 441e07c40a9..ae80c18a4c9 100644 --- a/studio/components/layouts/StorageLayout/StorageMenu.tsx +++ b/studio/components/layouts/StorageLayout/StorageMenu.tsx @@ -1,12 +1,15 @@ import { FC } from 'react' import Link from 'next/link' +import { find } from 'lodash' import { useRouter } from 'next/router' import { observer } from 'mobx-react-lite' -import { useParams } from 'hooks' +import * as Tooltip from '@radix-ui/react-tooltip' import { Button, Menu, IconLoader, Alert, IconEdit } from 'ui' +import { useParams } from 'hooks' import BucketRow from './BucketRow' import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore' +import { useProjectApiQuery } from 'data/config/project-api-query' interface Props {} @@ -30,22 +33,47 @@ const StorageMenu: FC = () => { openToggleBucketPublicModal, } = storageExplorerStore || {} + const { data: settings, isLoading } = useProjectApiQuery({ projectRef: ref }) + const apiService = settings?.autoApiService + const serviceKey = find(apiService?.service_api_keys ?? [], (key) => key.tags === 'service_role') + const canAccessStorage = !isLoading && apiService && serviceKey !== undefined + return (
-
- } - style={{ justifyContent: 'start' }} - onClick={openCreateBucketModal} - > - New bucket - + + +
+ } + disabled={!canAccessStorage} + style={{ justifyContent: 'start' }} + onClick={openCreateBucketModal} + > + New bucket + + + {!canAccessStorage && ( + + +
+ + You need additional permissions to create buckets + +
+
+ )} +
diff --git a/studio/components/to-be-cleaned/Docs/CodeSnippet.js b/studio/components/to-be-cleaned/Docs/CodeSnippet.js index 02bd93d5df3..47acdeff5da 100644 --- a/studio/components/to-be-cleaned/Docs/CodeSnippet.js +++ b/studio/components/to-be-cleaned/Docs/CodeSnippet.js @@ -3,12 +3,12 @@ import SimpleCodeBlock from 'components/to-be-cleaned/SimpleCodeBlock' const CodeSnippet = ({ selectedLang, snippet }) => { if (!snippet[selectedLang]) return null return ( - <> +

{snippet.title}

{snippet[selectedLang].code} - +
) } export default CodeSnippet diff --git a/studio/components/to-be-cleaned/Docs/Pages/Introduction.js b/studio/components/to-be-cleaned/Docs/Pages/Introduction.js deleted file mode 100644 index 30e24301034..00000000000 --- a/studio/components/to-be-cleaned/Docs/Pages/Introduction.js +++ /dev/null @@ -1,59 +0,0 @@ -import Snippets from '../Snippets' -import CodeSnippet from '../CodeSnippet' - -export default function Introduction({ autoApiService, selectedLang }) { - return ( - <> -

Introduction

-
-
-

- This API provides an easy way to integrate with your Postgres database. The API - documentation below is specifically generated for your database. -

-

- This is an auto-generating API, so as you make changes to your database, this - documentation will change too. -

-

- Please note: if you make changes to a field (column) name or type, the API - interface for those fields will change correspondingly. Therefore, please make sure to - update your API implementation accordingly whenever you make changes to your Supabase - schema from the graphical interface. -

-
-
- -

API URL

-
-
-

The API URL for your project.

-
-
- -
-
- -

Client Libraries

-
-
-

Your API consists of both a RESTful interface and a Realtime interface.

-

- For interacting with the Realtime streams, we provide client libraries that handle the - websockets. -

-
-
- - -
-
- - ) -} diff --git a/studio/components/to-be-cleaned/Docs/Pages/Introduction.tsx b/studio/components/to-be-cleaned/Docs/Pages/Introduction.tsx new file mode 100644 index 00000000000..61f132b1cf1 --- /dev/null +++ b/studio/components/to-be-cleaned/Docs/Pages/Introduction.tsx @@ -0,0 +1,112 @@ +import Snippets from '../Snippets' +import CodeSnippet from '../CodeSnippet' +import Image from 'next/image' +import { useStore } from 'hooks' +import { AutoApiService } from 'data/config/project-api-query' + +const libs = [ + { + name: 'Javascript', + url: 'https://supabase.com/docs/reference/javascript/introduction', + icon: 'javascript', + }, + { name: 'Flutter', url: 'https://supabase.com/docs/reference/dart/introduction', icon: 'dart' }, + { + name: 'Python', + url: 'https://supabase.com/docs/reference/python/introduction', + icon: 'python', + }, + { name: 'C#', url: 'https://supabase.com/docs/reference/csharp/introduction', icon: 'csharp' }, +] + +interface Props { + autoApiService: AutoApiService + selectedLang: string +} + +export default function Introduction({ autoApiService, selectedLang }: Props) { + const { ui } = useStore() + const { isDarkTheme } = ui + + return ( + <> +

Introduction

+
+
+

+ This API provides an easy way to integrate with your Postgres database. The API + documentation below is specifically generated for your database. +

+

+ This is an auto-generating API, so as you make changes to your database, this + documentation will change too. +

+

+ Note: if you make changes to a field (column) name or type, the API interface for + those fields will change correspondingly. Therefore, please make sure to update your API + implementation accordingly whenever you make changes to your Supabase schema from the + graphical interface. +

+ +
+

Read the reference documentation:

+
+ {libs.map((lib) => ( + + {lib.name} + {lib.name} + + ))} +
+
+
+
+ +

API URL

+
+
+

The API URL for your project.

+
+
+ +
+
+ +

Client Libraries

+
+
+

Your API consists of both a RESTful interface and a Realtime interface.

+

+ For interacting with the Realtime streams, we provide client libraries that handle the + websockets. +

+
+
+ + +
+
+ + ) +} diff --git a/studio/components/to-be-cleaned/Docs/Pages/Tables/Introduction.tsx b/studio/components/to-be-cleaned/Docs/Pages/Tables/Introduction.tsx index 8ef26409da3..ba2441ad011 100644 --- a/studio/components/to-be-cleaned/Docs/Pages/Tables/Introduction.tsx +++ b/studio/components/to-be-cleaned/Docs/Pages/Tables/Introduction.tsx @@ -1,10 +1,8 @@ -import { FC, useState } from 'react' +import { FC } from 'react' import Link from 'next/link' -import { Button, IconDownload, IconExternalLink } from 'ui' -import { useParams, useStore } from 'hooks' -import { API_ADMIN_URL } from 'lib/constants' -import { get } from 'lib/common/fetch' +import { useParams } from 'hooks' import CodeSnippet from '../../CodeSnippet' +import GeneratingTypes from 'components/interfaces/Docs/GeneratingTypes' interface Props { selectedLang: string @@ -12,35 +10,6 @@ interface Props { const Introduction: FC = ({ selectedLang }) => { const { ref } = useParams() - const { ui } = useStore() - const [isGeneratingTypes, setIsGeneratingTypes] = useState(false) - - const generateTypes = async () => { - setIsGeneratingTypes(true) - const res = await get(`${API_ADMIN_URL}/projects/${ref}/types/typescript`) - - if (!res.error) { - let element = document.createElement('a') - element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(res.types)) - element.setAttribute('download', 'supabase.ts') - element.style.display = 'none' - document.body.appendChild(element) - element.click() - document.body.removeChild(element) - ui.setNotification({ - category: 'success', - message: `Successfully generated types! File is being downloaded`, - }) - } else { - ui.setNotification({ - category: 'error', - message: `Failed to generate types: ${res.error.message}`, - error: res.error, - }) - } - - setIsGeneratingTypes(false) - } return ( <> @@ -65,48 +34,7 @@ const Introduction: FC = ({ selectedLang }) => {
-

- Generating types - - - - - -

-
-
-

- Supabase APIs are generated from your database, which means that we can use database - introspection to generate type-safe API definitions. -

-

- You can generate types from your database either through the{' '} - Supabase CLI, - or by downloading the types file via the button on the right and importing it in your - application within src/index.ts. -

-
-
- {selectedLang === 'js' && ( - - )} - - -
-
+

GraphQL vs Supabase @@ -141,22 +69,6 @@ const Introduction: FC = ({ selectedLang }) => { } const localSnippets = { - cliLogin: () => ({ - title: 'Login via the CLI with your Personal Access Token', - bash: { - code: ` -npx supabase login -`, - }, - }), - generateTypes: (ref: string) => ({ - title: 'Generate types', - bash: { - code: ` -npx supabase gen types typescript --project-id "${ref}" --schema public > types/supabase.ts -`, - }, - }), withApollo: () => ({ title: 'With Apollo GraphQL', bash: { diff --git a/studio/components/to-be-cleaned/Docs/Param.js b/studio/components/to-be-cleaned/Docs/Param.js deleted file mode 100644 index 9abb36712f8..00000000000 --- a/studio/components/to-be-cleaned/Docs/Param.js +++ /dev/null @@ -1,35 +0,0 @@ -import { Badge } from 'ui' -import Description from './Description' - -const Param = ({ - name, - type, - format, - required, - description, - metadata = {}, - onDesciptionUpdated = () => {}, -}) => { - return ( - <> -
- {name} - {required ? 'Required' : 'Optional'} -
- {format && format != type && ( -
- - {format} - {type} -
- )} - {description !== false && ( - <> - - - - )} - - ) -} -export default Param diff --git a/studio/components/to-be-cleaned/Docs/Param.tsx b/studio/components/to-be-cleaned/Docs/Param.tsx new file mode 100644 index 00000000000..611a61e707a --- /dev/null +++ b/studio/components/to-be-cleaned/Docs/Param.tsx @@ -0,0 +1,97 @@ +import { FC } from 'react' +import { Badge, IconCode, IconDatabase } from 'ui' +import Description from './Description' + +function getColumnType(type: string, format: string) { + // json and jsonb both have type=undefined, so check format instead + if (type === undefined && (format === 'jsonb' || format === 'json')) return 'json' + + switch (type) { + case 'string': + return 'string' + case 'integer': + return 'number' + case 'json': + return 'json' + case 'number': + return 'number' + case 'boolean': + return 'boolean' + default: + return '' + } +} + +interface Props { + name: string + type: string + format: string + required: boolean + description: boolean + metadata?: any + onDesciptionUpdated?: () => void +} +const Param: FC = ({ + name, + type, + format, + required, + description, + metadata = {}, + onDesciptionUpdated = () => {}, +}) => { + return ( + <> +
+
+
+ + +
+ {name} +
+
+
+ + {required ? 'Required' : 'Optional'} +
+ {format && ( +
+
+ +
+ + + + {getColumnType(type, format)} + + +
+
+
+ +
+ + + + {format} + + +
+
+
+ )} + {description !== false && ( +
+ + +
+ )} + + ) +} +export default Param diff --git a/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx b/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx index 4e05953129a..a604849edf0 100644 --- a/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx +++ b/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx @@ -1,12 +1,14 @@ import { useState } from 'react' +import * as Tooltip from '@radix-ui/react-tooltip' import { Button, Form, IconClock, Input, Listbox } from 'ui' -import { useStore } from 'hooks' +import { checkPermissions, useStore } from 'hooks' import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query' import { useProjectStorageConfigUpdateUpdateMutation } from 'data/config/project-storage-config-update-mutation' import UpgradeToPro from 'components/ui/UpgradeToPro' import { convertFromBytes, convertToBytes } from './StorageSettings.utils' import { StorageSizeUnits, STORAGE_FILE_SIZE_LIMIT_MAX_BYTES } from './StorageSettings.constants' +import { PermissionAction } from '@supabase/shared-types/out/constants' export type StorageSettingsProps = { projectRef: string | undefined @@ -42,6 +44,8 @@ const StorageConfig = ({ config, projectRef }: any) => { const [selectedUnit, setSelectedUnit] = useState(unit) let initialValues = { fileSizeLimit: value, unformattedFileSizeLimit: fileSizeLimit } + const canUpdateStorageSettings = checkPermissions(PermissionAction.UPDATE, 'projects') + const formattedMaxSizeBytes = `${new Intl.NumberFormat('en-US').format( STORAGE_FILE_SIZE_LIMIT_MAX_BYTES )} bytes` @@ -138,7 +142,7 @@ const StorageConfig = ({ config, projectRef }: any) => { id="fileSizeLimit" name="fileSizeLimit" type="number" - disabled={isFreeTier} + disabled={isFreeTier || !canUpdateStorageSettings} step={1} onKeyPress={(event) => { if (event.charCode < 48 || event.charCode > 57) { @@ -184,13 +188,20 @@ const StorageConfig = ({ config, projectRef }: any) => { icon={} primaryText="Free Plan has a fixed upload file size limit of 50 MB." projectRef={projectRef} - secondaryText="Please upgrade to Pro plan for a configurable upload file size limit of up to 5 GB." + secondaryText="Upgrade to the Pro plan for a configurable upload file size limit of up to 5 GB." />

)}
-
+
+ {!canUpdateStorageSettings ? ( +

+ You need additional permissions to update storage settings +

+ ) : ( +
+ )}
diff --git a/studio/components/to-be-cleaned/forms/SchemaForm.js b/studio/components/to-be-cleaned/forms/SchemaForm.js index bc5e6ac20a0..fa65c7b1560 100644 --- a/studio/components/to-be-cleaned/forms/SchemaForm.js +++ b/studio/components/to-be-cleaned/forms/SchemaForm.js @@ -2,10 +2,19 @@ import { AutoForm } from 'uniforms-bootstrap4' import Ajv from 'ajv' import { JSONSchemaBridge } from 'uniforms-bridge-json-schema' -const SchemaForm = ({ schema, model, children, formRef, onSubmit, onChangeModel = () => {} }) => { +const SchemaForm = ({ + schema, + model, + disabled = false, + children, + formRef, + onSubmit, + onChangeModel = () => {}, +}) => { const validatedSchema = new JSONSchemaBridge(schema, createValidator(schema)) return (
{title || ''}
-
- - -
+ + +
+ )} {message}
{ setHasChanged(true) if (onChangeModel) onChangeModel(model) diff --git a/studio/components/ui/Flag/FlagProvider.tsx b/studio/components/ui/Flag/FlagProvider.tsx index e521fec1a65..40d1ac7dae8 100644 --- a/studio/components/ui/Flag/FlagProvider.tsx +++ b/studio/components/ui/Flag/FlagProvider.tsx @@ -16,20 +16,12 @@ const FlagProvider: FC = ({ children }) => { const { Provider } = FlagContext const [store, setStore] = useState({}) - useEffect(() => { - // [Joshen] getFlags get triggered everytime the tab refocuses but this should be okay - // as per https://configcat.com/docs/sdk-reference/js/#polling-modes: - // The polling downloads the config.json at the set interval and are stored in the internal cache - // which subsequently all getValueAsync() calls are served from there - if (IS_PLATFORM) getFlags(profile) - }, [profile]) - const getFlags = async (user?: User) => { if (!client) { client = configcat.getClient( process.env.NEXT_PUBLIC_CONFIGCAT_SDK_KEY ?? '', configcat.PollingMode.AutoPoll, - { pollIntervalSeconds: 10 } + { pollIntervalSeconds: 600 } ) } @@ -44,6 +36,14 @@ const FlagProvider: FC = ({ children }) => { setStore(flagStore) } + useEffect(() => { + // [Joshen] getFlags get triggered everytime the tab refocuses but this should be okay + // as per https://configcat.com/docs/sdk-reference/js/#polling-modes: + // The polling downloads the config.json at the set interval and are stored in the internal cache + // which subsequently all getValueAsync() calls are served from there + if (IS_PLATFORM) getFlags(profile) + }, [profile]) + return {children} } diff --git a/studio/components/ui/ProductMenu/ProductMenuItem.tsx b/studio/components/ui/ProductMenu/ProductMenuItem.tsx index ca2fdcf51a7..42fb817e326 100644 --- a/studio/components/ui/ProductMenu/ProductMenuItem.tsx +++ b/studio/components/ui/ProductMenu/ProductMenuItem.tsx @@ -34,9 +34,9 @@ const ProductMenuItem: FC = ({
- {name}{' '} + {name} {label !== undefined && ( {label} )} diff --git a/studio/components/ui/UpgradeToPro.tsx b/studio/components/ui/UpgradeToPro.tsx index ca7b1b549b6..ccee10b1295 100644 --- a/studio/components/ui/UpgradeToPro.tsx +++ b/studio/components/ui/UpgradeToPro.tsx @@ -2,8 +2,11 @@ import { Button } from 'ui' import { observer } from 'mobx-react-lite' import Link from 'next/link' import { FC, ReactNode } from 'react' -import { useStore } from 'hooks' +import * as Tooltip from '@radix-ui/react-tooltip' + +import { checkPermissions, useStore, useFlag, useParams } from 'hooks' import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants' +import { PermissionAction } from '@supabase/shared-types/out/constants' interface Props { icon?: ReactNode @@ -14,8 +17,16 @@ interface Props { const UpgradeToPro: FC = ({ icon, primaryText, projectRef, secondaryText }) => { const { ui } = useStore() + const { ref } = useParams() const tier = ui.selectedProject?.subscription_tier + const canUpdateSubscription = checkPermissions( + PermissionAction.BILLING_WRITE, + 'stripe.subscriptions' + ) + const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate') + const isEnterprise = tier === PRICING_TIER_PRODUCT_IDS.ENTERPRISE + return (
= ({ icon, primaryText, projectRef, secondaryText

{secondaryText}

- - - - - + + {!canUpdateSubscription || projectUpdateDisabled ? ( + + +
+ + {projectUpdateDisabled ? ( + <> + Subscription changes are currently disabled. +
+ Our engineers are working on a fix. + + ) : !canUpdateSubscription ? ( + 'You need additional permissions to amend subscriptions' + ) : ( + '' + )} +
+
+
+ ) : ( + <> + )} +
diff --git a/studio/data/config/project-read-only-query.ts b/studio/data/config/project-read-only-query.ts new file mode 100644 index 00000000000..23312f2f67e --- /dev/null +++ b/studio/data/config/project-read-only-query.ts @@ -0,0 +1,56 @@ +import { UseQueryOptions } from '@tanstack/react-query' +import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query' + +// TODO: temporary solution to check if project is in read only mode +// until we get an api endpoint for this + +export const getProjectReadOnlySql = () => { + const sql = /* SQL */ ` + show default_transaction_read_only; + ` + + return sql +} + +export type ProjectReadOnlyVariables = { + projectRef?: string + connectionString?: string +} + +export type ProjectReadOnlyData = boolean +export type ProjectReadOnlyError = unknown + +export const useProjectReadOnlyQuery = ( + { projectRef, connectionString }: ProjectReadOnlyVariables, + options: Omit< + UseQueryOptions, + 'select' + > = {} +) => + useExecuteSqlQuery( + { + projectRef, + connectionString, + sql: getProjectReadOnlySql(), + queryKey: ['project-read-only'], + }, + { + select(data) { + return data.result[0]?.default_transaction_read_only === 'on' + }, + enabled: typeof projectRef !== 'undefined' && typeof connectionString !== 'undefined', + ...options, + } + ) + +export const useProjectReadOnlyPrefetch = ({ + projectRef, + connectionString, +}: ProjectReadOnlyVariables) => { + return useExecuteSqlPrefetch({ + projectRef, + connectionString, + sql: getProjectReadOnlySql(), + queryKey: ['project-read-only'], + }) +} diff --git a/studio/data/edge-functions/edge-functions-delete-mutation.ts b/studio/data/edge-functions/edge-functions-delete-mutation.ts new file mode 100644 index 00000000000..d642758cd9c --- /dev/null +++ b/studio/data/edge-functions/edge-functions-delete-mutation.ts @@ -0,0 +1,46 @@ +import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query' +import { delete_ } from 'lib/common/fetch' +import { API_ADMIN_URL } from 'lib/constants' +import { edgeFunctionsKeys } from './keys' + +export type EdgeFunctionsDeleteVariables = { + projectRef: string + slug: string +} + +export async function deleteEdgeFunction({ projectRef, slug }: EdgeFunctionsDeleteVariables) { + if (!projectRef) throw new Error('projectRef is required') + + const response = await delete_(`${API_ADMIN_URL}/projects/${projectRef}/functions/${slug}`, {}) + if (response.error) { + throw response.error + } + + return response +} + +type EdgeFunctionsDeleteData = Awaited> + +export const useEdgeFunctionDeleteMutation = ({ + onSuccess, + ...options +}: Omit< + UseMutationOptions, + 'mutationFn' +> = {}) => { + const queryClient = useQueryClient() + + return useMutation( + (vars) => deleteEdgeFunction(vars), + { + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(edgeFunctionsKeys.list(projectRef), { + refetchType: 'all', + }) + await onSuccess?.(data, variables, context) + }, + ...options, + } + ) +} diff --git a/studio/data/edge-functions/edge-functions-query.ts b/studio/data/edge-functions/edge-functions-query.ts new file mode 100644 index 00000000000..28bc3f8c649 --- /dev/null +++ b/studio/data/edge-functions/edge-functions-query.ts @@ -0,0 +1,57 @@ +import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query' +import { get } from 'lib/common/fetch' +import { API_ADMIN_URL } from 'lib/constants' +import { useCallback } from 'react' +import { edgeFunctionsKeys } from './keys' + +export type EdgeFunctionsVariables = { projectRef?: string } + +export type EdgeFunctionsResponse = { + id: string + name: string + slug: string + status: string + version: number + created_at: number + updated_at: number + verify_jwt: boolean + import_map: boolean +} + +export async function getEdgeFunctions( + { projectRef }: EdgeFunctionsVariables, + signal?: AbortSignal +) { + if (!projectRef) throw new Error('projectRef is required') + + const response = await get(`${API_ADMIN_URL}/projects/${projectRef}/functions`, { + signal, + }) + if (response.error) throw response.error + return response as EdgeFunctionsResponse[] +} + +export type EdgeFunctionsData = Awaited> +export type EdgeFunctionsError = unknown + +export const useEdgeFunctionsQuery = ( + { projectRef }: EdgeFunctionsVariables, + { enabled = true, ...options }: UseQueryOptions = {} +) => + useQuery( + edgeFunctionsKeys.list(projectRef), + ({ signal }) => getEdgeFunctions({ projectRef }, signal), + { enabled: enabled && typeof projectRef !== 'undefined', ...options } + ) + +export const useEdgeFunctionsPrefetch = ({ projectRef }: EdgeFunctionsVariables) => { + const client = useQueryClient() + + return useCallback(() => { + if (projectRef) { + client.prefetchQuery(edgeFunctionsKeys.list(projectRef), ({ signal }) => + getEdgeFunctions({ projectRef }, signal) + ) + } + }, [projectRef]) +} diff --git a/studio/data/edge-functions/keys.ts b/studio/data/edge-functions/keys.ts new file mode 100644 index 00000000000..dacd8d4a8dd --- /dev/null +++ b/studio/data/edge-functions/keys.ts @@ -0,0 +1,3 @@ +export const edgeFunctionsKeys = { + list: (projectRef: string | undefined) => ['projects', projectRef, 'edge-functions'] as const, +} diff --git a/studio/hooks/misc/withAuth.tsx b/studio/hooks/misc/withAuth.tsx index b41734cb1c8..d2cdc5d94fd 100644 --- a/studio/hooks/misc/withAuth.tsx +++ b/studio/hooks/misc/withAuth.tsx @@ -50,6 +50,7 @@ export function withAuth( }) usePermissionsQuery({ + enabled: IS_PLATFORM, onSuccess(permissions) { ui.setPermissions(permissions) }, diff --git a/studio/lib/common/fetch/delete.ts b/studio/lib/common/fetch/delete.ts index ff5a2f3f4eb..4bedf25cfac 100644 --- a/studio/lib/common/fetch/delete.ts +++ b/studio/lib/common/fetch/delete.ts @@ -14,7 +14,6 @@ export async function delete_( const response = await fetch(url, { method: 'DELETE', body: JSON.stringify(data), - credentials: 'include', referrerPolicy: 'no-referrer-when-downgrade', headers, ...otherOptions, diff --git a/studio/lib/common/fetch/get.ts b/studio/lib/common/fetch/get.ts index dc4f56a0816..58b3f8946d3 100644 --- a/studio/lib/common/fetch/get.ts +++ b/studio/lib/common/fetch/get.ts @@ -12,7 +12,6 @@ export async function get( const headers = await constructHeaders(requestId, optionHeaders) const response = await fetch(url, { method: 'GET', - credentials: 'include', referrerPolicy: 'no-referrer-when-downgrade', headers, ...otherOptions, @@ -37,7 +36,6 @@ export async function getWithTimeout( const headers = await constructHeaders(requestId, optionHeaders) const response = await fetch(url, { method: 'GET', - credentials: 'include', referrerPolicy: 'no-referrer-when-downgrade', headers, ...otherOptions, diff --git a/studio/lib/common/fetch/head.ts b/studio/lib/common/fetch/head.ts index 6d7e7f42d6e..2bcba4895f3 100644 --- a/studio/lib/common/fetch/head.ts +++ b/studio/lib/common/fetch/head.ts @@ -13,7 +13,6 @@ export async function head( const headers = await constructHeaders(requestId, optionHeaders) const response = await fetch(url, { method: 'HEAD', - credentials: 'include', referrerPolicy: 'no-referrer-when-downgrade', headers, ...otherOptions, @@ -39,7 +38,6 @@ export async function headWithTimeout( const headers = await constructHeaders(requestId, optionHeaders) const response = await fetch(url, { method: 'HEAD', - credentials: 'include', referrerPolicy: 'no-referrer-when-downgrade', headers, ...otherOptions, diff --git a/studio/lib/common/fetch/patch.ts b/studio/lib/common/fetch/patch.ts index 9ca15e0c989..7fcf4aad2c9 100644 --- a/studio/lib/common/fetch/patch.ts +++ b/studio/lib/common/fetch/patch.ts @@ -14,7 +14,6 @@ export async function patch( const response = await fetch(url, { method: 'PATCH', body: JSON.stringify(data), - credentials: 'include', referrerPolicy: 'no-referrer-when-downgrade', headers, ...otherOptions, diff --git a/studio/lib/common/fetch/post.ts b/studio/lib/common/fetch/post.ts index e4757dc34a6..c71f86a14b6 100644 --- a/studio/lib/common/fetch/post.ts +++ b/studio/lib/common/fetch/post.ts @@ -14,7 +14,6 @@ export async function post( const response = await fetch(url, { method: 'POST', body: JSON.stringify(data), - credentials: 'include', referrerPolicy: 'no-referrer-when-downgrade', headers, ...otherOptions, diff --git a/studio/package.json b/studio/package.json index db300011bdd..c135a48e5ea 100644 --- a/studio/package.json +++ b/studio/package.json @@ -15,6 +15,8 @@ "prettier:write": "prettier --write ." }, "dependencies": { + "@graphiql/react": "^0.15.0", + "@graphiql/toolkit": "^0.8.0", "@hcaptcha/react-hcaptcha": "^1.4.4", "@headlessui/react": "^1.4.1", "@monaco-editor/react": "^4.3.1", @@ -37,12 +39,16 @@ "awesome-debounce-promise": "^2.1.0", "blueimp-md5": "^2.19.0", "clipboard": "^2.0.8", + "clsx": "^1.2.1", "common": "*", "config": "*", "configcat-js": "^7.0.0", "dayjs": "^1.11.0", "file-saver": "^2.0.5", "generate-password": "^1.7.0", + "graphiql": "^2.2.0", + "graphql": "^16.6.0", + "graphql-ws": "^5.11.3", "html-to-image": "^1.10.8", "immutability-helper": "^3.1.1", "ip-address": "^8.1.0", diff --git a/studio/pages/_app.tsx b/studio/pages/_app.tsx index d97675d69ef..f542d30ca75 100644 --- a/studio/pages/_app.tsx +++ b/studio/pages/_app.tsx @@ -16,6 +16,7 @@ import dayjs from 'dayjs' import customParseFormat from 'dayjs/plugin/customParseFormat' import timezone from 'dayjs/plugin/timezone' import utc from 'dayjs/plugin/utc' +import relativeTime from 'dayjs/plugin/relativeTime' // @ts-ignore import Prism from 'prism-react-renderer/prism' @@ -44,6 +45,7 @@ import useAutoAuthRedirect from 'hooks/misc/useAutoAuthRedirect' dayjs.extend(customParseFormat) dayjs.extend(utc) dayjs.extend(timezone) +dayjs.extend(relativeTime) dart(Prism) diff --git a/studio/pages/project/[ref]/api/graphiql.tsx b/studio/pages/project/[ref]/api/graphiql.tsx new file mode 100644 index 00000000000..8b449994aee --- /dev/null +++ b/studio/pages/project/[ref]/api/graphiql.tsx @@ -0,0 +1,88 @@ +import { observer } from 'mobx-react-lite' +import { createGraphiQLFetcher } from '@graphiql/toolkit' + +import ExtensionCard from 'components/interfaces/Database/Extensions/ExtensionCard' +import GraphiQL from 'components/interfaces/GraphQL/GraphiQL' +import { DocsLayout } from 'components/layouts' +import Connecting from 'components/ui/Loading/Loading' +import { useParams, useStore } from 'hooks' +import { useProjectApiQuery } from 'data/config/project-api-query' +import { useEffect, useMemo } from 'react' +import { NextPageWithLayout } from 'types' +import { IconAlertCircle } from 'ui' + +const GraphiQLPage: NextPageWithLayout = () => { + const { ref: projectRef } = useParams() + const { ui, meta } = useStore() + + const isExtensionsLoading = meta.extensions.isLoading + const pgGraphqlExtension = meta.extensions.byId('pg_graphql') + + useEffect(() => { + if (ui.selectedProject?.ref) { + // Schemas may be needed when enabling the GraphQL extension + meta.schemas.load() + meta.extensions.load() + } + }, [ui.selectedProject?.ref]) + + const { + data: settings, + isError: isProjectSettingsError, + isLoading: isProjectSettingsLoading, + } = useProjectApiQuery({ + projectRef, + }) + + const apiService = settings?.autoApiService + const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key') + ? apiService.defaultApiKey + : undefined + const endpoint = settings?.autoApiService.app_config.endpoint ?? '' + + const graphqlUrl = `https://${endpoint}/graphql/v1` + + const fetcher = useMemo(() => { + return createGraphiQLFetcher({ + url: graphqlUrl, + fetch, + }) + }, [graphqlUrl]) + + if (isProjectSettingsLoading || (isExtensionsLoading && !pgGraphqlExtension)) { + return + } + + if (isProjectSettingsError) { + return ( +
+ +

Failed to retrieve API keys

+
+ ) + } + + if (pgGraphqlExtension?.installed_version === null) { + return ( +
+
+
+

Enable the GraphQL Extension

+

+ Toggle the switch below to enable the GraphQL extension. You can then use the GraphQL + API with your Supabase Database. +

+
+ + +
+
+ ) + } + + return +} + +GraphiQLPage.getLayout = (page) => {page} + +export default observer(GraphiQLPage) diff --git a/studio/pages/project/[ref]/api/index.tsx b/studio/pages/project/[ref]/api/index.tsx index 82bed5db772..5f4e22b9031 100644 --- a/studio/pages/project/[ref]/api/index.tsx +++ b/studio/pages/project/[ref]/api/index.tsx @@ -1,5 +1,4 @@ import { useRouter } from 'next/router' -import { Button, Dropdown, IconKey } from 'ui' import { FC, createContext, useContext, useEffect, useState } from 'react' import { observer, useLocalObservable } from 'mobx-react-lite' @@ -11,6 +10,7 @@ import { DocsLayout } from 'components/layouts' import { GeneralContent, ResourceContent, RpcContent } from 'components/interfaces/Docs' import { PermissionAction } from '@supabase/shared-types/out/constants' import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query' +import LangSelector from 'components/interfaces/Docs/LangSelector' const PageContext = createContext(null) @@ -79,11 +79,6 @@ const DocView: FC = observer(({}) => { : undefined const swaggerUrl = data?.autoApiService?.restUrl - const canReadServiceKey = checkPermissions( - PermissionAction.READ, - 'service_api_keys.service_role_key' - ) - const { data: jsonSchema, error: jsonSchemaError, @@ -104,7 +99,7 @@ const DocView: FC = observer(({}) => { if (error || jsonSchemaError) return ( -
+

Error connecting to API

{`${error || jsonSchemaError}`}

@@ -113,7 +108,7 @@ const DocView: FC = observer(({}) => { ) if (!data || !jsonSchema || !PageState.jsonSchema) return ( -
+

Building docs ...

) @@ -129,81 +124,17 @@ const DocView: FC = observer(({}) => { const PAGE_KEY: any = resource || rpc || page || 'index' return ( -
+
-
-
-
- - - {selectedLang == 'bash' && ( -
-
- - Project API key : -
- - setShowApiKey(DEFAULT_KEY)}> - hide - - - setShowApiKey({ - key: anonKey, - name: 'anon (public)', - }) - } - > - anon (public) - - {canReadServiceKey && ( - - setShowApiKey({ - key: autoApiService.serviceApiKey, - name: 'service_role (secret)', - }) - } - > - service_role (secret) - - )} - - } - > - - -
- )} -
-
+
+
{resource ? ( diff --git a/studio/pages/project/[ref]/database/backups/pitr.tsx b/studio/pages/project/[ref]/database/backups/pitr.tsx index 5f3eb4aadad..694e62f97c7 100644 --- a/studio/pages/project/[ref]/database/backups/pitr.tsx +++ b/studio/pages/project/[ref]/database/backups/pitr.tsx @@ -65,7 +65,7 @@ const PITR = () => { primaryText="Point in time recovery is a Pro plan add-on." secondaryText={ tier === PRICING_TIER_PRODUCT_IDS.FREE - ? 'Please upgrade to the Pro plan with the PITR add-on selected to enable point in time recovery for your project.' + ? 'Upgrade to the Pro plan with the PITR add-on selected to enable point in time recovery for your project.' : 'Please enable the add-on to enable point in time recovery for your project.' } /> diff --git a/studio/pages/project/[ref]/database/wrappers/[id].tsx b/studio/pages/project/[ref]/database/wrappers/[id].tsx index a5abeb5df61..bf197056957 100644 --- a/studio/pages/project/[ref]/database/wrappers/[id].tsx +++ b/studio/pages/project/[ref]/database/wrappers/[id].tsx @@ -9,6 +9,7 @@ import { EditWrapper } from 'components/interfaces/Database' const DatabaseWrappersNew: NextPageWithLayout = () => { const canReadWrappers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'wrappers') + if (!canReadWrappers) { return } diff --git a/studio/pages/project/[ref]/database/wrappers/index.tsx b/studio/pages/project/[ref]/database/wrappers/index.tsx index ead5fba1e25..d8df5feae34 100644 --- a/studio/pages/project/[ref]/database/wrappers/index.tsx +++ b/studio/pages/project/[ref]/database/wrappers/index.tsx @@ -9,7 +9,7 @@ import NoPermission from 'components/ui/NoPermission' import { FormsContainer } from 'components/ui/Forms' const DatabaseWrappers: NextPageWithLayout = () => { - const canReadWrappers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'wrappers') + const canReadWrappers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'tables') if (!canReadWrappers) { return } diff --git a/studio/pages/project/[ref]/database/wrappers/new.tsx b/studio/pages/project/[ref]/database/wrappers/new.tsx index 4db0245131f..225b4051123 100644 --- a/studio/pages/project/[ref]/database/wrappers/new.tsx +++ b/studio/pages/project/[ref]/database/wrappers/new.tsx @@ -8,9 +8,9 @@ import NoPermission from 'components/ui/NoPermission' import { CreateWrapper } from 'components/interfaces/Database' const DatabaseWrappersNew: NextPageWithLayout = () => { - const canReadWrappers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'wrappers') - if (!canReadWrappers) { - return + const canCreateWrappers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables') + if (!canCreateWrappers) { + return } return diff --git a/studio/pages/project/[ref]/functions/[id]/details.tsx b/studio/pages/project/[ref]/functions/[id]/details.tsx index 613833e4f31..debcd5ebe99 100644 --- a/studio/pages/project/[ref]/functions/[id]/details.tsx +++ b/studio/pages/project/[ref]/functions/[id]/details.tsx @@ -1,244 +1,21 @@ -import dayjs from 'dayjs' -import { useEffect, useState } from 'react' import { observer } from 'mobx-react-lite' -import { IconGlobe, IconTerminal } from 'ui' import { PermissionAction } from '@supabase/shared-types/out/constants' import { NextPageWithLayout } from 'types' -import { checkPermissions, useParams, useStore } from 'hooks' -import { useProjectApiQuery } from 'data/config/project-api-query' +import { checkPermissions, useParams } from 'hooks' import FunctionsLayout from 'components/layouts/FunctionsLayout' -import CommandRender from 'components/interfaces/Functions/CommandRender' import NoPermission from 'components/ui/NoPermission' +import { EdgeFunctionDetails } from 'components/interfaces/Functions' const PageLayout: NextPageWithLayout = () => { - const { ref: projectRef, id } = useParams() - - const { functions, ui } = useStore() - - const [selectedFunction, setSelectedFunction] = useState(null) - - useEffect(() => { - setSelectedFunction(functions.byId(id)) - }, [functions.isLoaded, ui.selectedProject]) - - const { data: settings } = useProjectApiQuery({ - projectRef, - }) - - // get the .co or .net TLD from the restUrl - const restUrl = ui.selectedProject?.restUrl - const restUrlTld = new URL(restUrl as string).hostname.split('.').pop() - - const managementCommands: any = [ - { - command: `supabase functions deploy ${selectedFunction?.slug}`, - description: 'This will overwrite the deployed function with your new function', - jsx: () => { - return ( - <> - supabase functions deploy{' '} - {selectedFunction?.slug} - - ) - }, - comment: 'Deploy a new version', - }, - { - command: `supabase functions delete ${selectedFunction?.slug}`, - description: 'This will remove the function and all the logs associated with it', - jsx: () => { - return ( - <> - supabase functions delete{' '} - {selectedFunction?.slug} - - ) - }, - comment: 'Delete the function', - }, - ] - - const secretCommands: any = [ - { - command: `supabase secrets list`, - description: 'This will list all the secrets for your project', - jsx: () => { - return ( - <> - supabase secrets list - - ) - }, - comment: 'View all secrets', - }, - { - command: `supabase secrets set NAME1=VALUE1 NAME2=VALUE2`, - description: 'This will set secrets for your project', - jsx: () => { - return ( - <> - supabase secrets set NAME1=VALUE1 NAME2=VALUE2 - - ) - }, - comment: 'Set secrets for your project', - }, - { - command: `supabase secrets unset NAME1 NAME2 `, - description: 'This will delete secrets for your project', - jsx: () => { - return ( - <> - supabase secrets unset NAME1 NAME2 - - ) - }, - comment: 'Unset secrets for your project', - }, - ] - - // Get the API service - const apiService = settings?.autoApiService - const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key') - ? apiService.defaultApiKey - : undefined - - const endpoint = apiService?.app_config.endpoint ?? '' - const endpointSections = endpoint.split('.') - const functionsEndpoint = [ - ...endpointSections.slice(0, 1), - 'functions', - ...endpointSections.slice(1), - ].join('.') - - const invokeCommands: any = [ - { - command: `curl -L -X POST 'https://${projectRef}.functions.supabase.${restUrlTld}/${ - selectedFunction?.slug - }' -H 'Authorization: Bearer ${anonKey ?? '[YOUR ANON KEY]'}' --data '{"name":"Functions"}'`, - description: 'Invokes the hello function', - jsx: () => { - return ( - <> - curl -L -X POST 'https://{functionsEndpoint}/ - {selectedFunction?.slug}' -H 'Authorization: Bearer [YOUR ANON KEY]'{' '} - {`--data '{"name":"Functions"}'`} - - ) - }, - comment: 'Invoke your function', - }, - ] + const { id } = useParams() const canReadFunction = checkPermissions(PermissionAction.FUNCTIONS_READ, id as string) if (!canReadFunction) { return } - return ( -
-
-
-
-
- Function Name -
{selectedFunction?.name}
-
- -
- Status -
-
-
- {selectedFunction?.status} -
- - - - -
-
-
-
-
-
- -
- Endpoint URL -
- {`https://${projectRef}.functions.supabase.co/${selectedFunction?.slug}`} -
-
- -
- Created At -
- {selectedFunction?.created_at && - dayjs(selectedFunction.created_at).format('dddd, MMMM D, YYYY h:mm A')} -
-
- -
- Updated At -
- {selectedFunction?.updated_at && - dayjs(selectedFunction.updated_at).format('dddd, MMMM D, YYYY h:mm A')} -
-
- -
- Version -
v{selectedFunction?.version}
-
- -
- Regions -
-
- - Earth -
- All functions are deployed globally -
-
-
-
- -
-
-
-
- -
-

Command line access

-
- -
Deployment management
- -
Invoke
- -
Secrets management
- -
-
-
- ) + return } PageLayout.getLayout = (page) => {page} diff --git a/studio/pages/project/[ref]/functions/index.tsx b/studio/pages/project/[ref]/functions/index.tsx index 0532afd7a8f..e78b41e0996 100644 --- a/studio/pages/project/[ref]/functions/index.tsx +++ b/studio/pages/project/[ref]/functions/index.tsx @@ -1,59 +1,53 @@ import { observer } from 'mobx-react-lite' +import { useParams } from 'hooks' import { NextPageWithLayout } from 'types' -import { useStore } from 'hooks' -import FunctionsLayout from 'components/layouts/FunctionsLayout' - import Table from 'components/to-be-cleaned/Table' -import { Function } from 'components/interfaces/Functions/Functions.types' -import { - FunctionsListItem, - FunctionsEmptyState, - TerminalInstructions, -} from 'components/interfaces/Functions' - -const EdgeFunctionsList = ({ functions }: { functions: Function[] }) => { - return ( - <> -
-
- {`${functions.length} function${ - functions.length > 1 ? 's' : '' - } deployed`} -
-
- - Name - URL - Created - Last updated - Version - Status - - } - body={ - <> - {functions.length > 0 && - functions.map((item: any) => )} - - } - /> - - - - ) -} +import FunctionsLayout from 'components/layouts/FunctionsLayout' +import { EdgeFunctionsListItem, FunctionsEmptyState } from 'components/interfaces/Functions' +import ShimmeringLoader from 'components/ui/ShimmeringLoader' +import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query' const PageLayout: NextPageWithLayout = () => { - const { functions } = useStore() - const hasFunctions = functions.list().length > 0 + const { ref } = useParams() + const { isLoading, data: functions } = useEdgeFunctionsQuery({ projectRef: ref }) + + const hasFunctions = (functions ?? []).length > 0 + + if (isLoading || functions === undefined) { + return ( +
+ + + +
+ ) + } return hasFunctions ? ( -
- - +
+
+ {`${functions.length} function${ + functions.length > 1 ? 's' : '' + } deployed`} +
+
+ Name + URL + Created + Last updated + Deployments + + } + body={ + <> + {functions.length > 0 && + functions.map((item: any) => )} + + } + /> ) : ( diff --git a/studio/pages/project/[ref]/reports/database.tsx b/studio/pages/project/[ref]/reports/database.tsx index 20ba14361d2..51ff8dfb946 100644 --- a/studio/pages/project/[ref]/reports/database.tsx +++ b/studio/pages/project/[ref]/reports/database.tsx @@ -103,24 +103,25 @@ const DatabaseUsage: FC = () => { /> -
-
- {usage?.disk_volume_size_gb && ( - Disk Size: {usage.disk_volume_size_gb} GB - )} + {isPaidTier && ( +
+
+ {usage?.disk_volume_size_gb && ( + Disk Size: {usage.disk_volume_size_gb} GB + )} + Auto-Scaling +
- {isPaidTier && Auto-Scaling} +
- - -
+ )}
diff --git a/studio/pages/project/[ref]/settings/billing/subscription.tsx b/studio/pages/project/[ref]/settings/billing/subscription.tsx index 750af452736..a47a62ad90d 100644 --- a/studio/pages/project/[ref]/settings/billing/subscription.tsx +++ b/studio/pages/project/[ref]/settings/billing/subscription.tsx @@ -36,7 +36,6 @@ interface SettingsProps { const Settings: FC = ({ project }) => { const { ui } = useStore() - const projectTier = ui.selectedProject?.subscription_tier const { data: subscription, diff --git a/studio/pages/project/[ref]/storage/buckets/index.tsx b/studio/pages/project/[ref]/storage/buckets/index.tsx index 80ca79f9f03..396a914ba2a 100644 --- a/studio/pages/project/[ref]/storage/buckets/index.tsx +++ b/studio/pages/project/[ref]/storage/buckets/index.tsx @@ -3,21 +3,21 @@ import { useRouter } from 'next/router' import { observer } from 'mobx-react-lite' import { API_URL } from 'lib/constants' -import { useFlag, useStore } from 'hooks' +import { useFlag, useParams, useStore } from 'hooks' import { post } from 'lib/common/fetch' import { PROJECT_STATUS } from 'lib/constants' import { StorageLayout } from 'components/layouts' import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState' import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore' import { NextPageWithLayout } from 'types' +import { useProjectApiQuery } from 'data/config/project-api-query' +import { find } from 'lodash' /** * PageLayout is used to setup layout - as usual it will requires inject global store */ const PageLayout: NextPageWithLayout = ({}) => { - const router = useRouter() - const { ref } = router.query - + const { ref } = useParams() const { ui } = useStore() const project = ui.selectedProject @@ -26,6 +26,11 @@ const PageLayout: NextPageWithLayout = ({}) => { const kpsEnabled = useFlag('initWithKps') + const { data: settings, isLoading } = useProjectApiQuery({ projectRef: ref }) + const apiService = settings?.autoApiService + const serviceKey = find(apiService?.service_api_keys ?? [], (key) => key.tags === 'service_role') + const canAccessStorage = !isLoading && apiService && serviceKey !== undefined + useEffect(() => { if (project && project.status === PROJECT_STATUS.INACTIVE) { post(`${API_URL}/projects/${ref}/restore`, { kps_enabled: kpsEnabled }) @@ -42,6 +47,8 @@ const PageLayout: NextPageWithLayout = ({}) => { infoButtonLabel="About storage" infoButtonUrl="https://supabase.com/docs/guides/storage" onClickCta={openCreateBucketModal} + disabled={!canAccessStorage} + disabledMessage="You need additional permissions to create buckets" >

Create buckets to store and serve any type of digital content. diff --git a/studio/public/img/graphql.svg b/studio/public/img/graphql.svg new file mode 100644 index 00000000000..8060db470ea --- /dev/null +++ b/studio/public/img/graphql.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/studio/public/img/icons/reference-auth-light.svg b/studio/public/img/icons/reference-auth-light.svg new file mode 100644 index 00000000000..3995c790842 --- /dev/null +++ b/studio/public/img/icons/reference-auth-light.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/studio/public/img/icons/reference-csharp-light.svg b/studio/public/img/icons/reference-csharp-light.svg new file mode 100644 index 00000000000..782f87bcc40 --- /dev/null +++ b/studio/public/img/icons/reference-csharp-light.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/studio/public/img/icons/reference-csharp.svg b/studio/public/img/icons/reference-csharp.svg new file mode 100644 index 00000000000..40d0375079d --- /dev/null +++ b/studio/public/img/icons/reference-csharp.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/studio/public/img/icons/reference-dart-light.svg b/studio/public/img/icons/reference-dart-light.svg new file mode 100644 index 00000000000..178f51a5b88 --- /dev/null +++ b/studio/public/img/icons/reference-dart-light.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/studio/public/img/icons/reference-dart.svg b/studio/public/img/icons/reference-dart.svg new file mode 100644 index 00000000000..33f9ad24a27 --- /dev/null +++ b/studio/public/img/icons/reference-dart.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/studio/public/img/icons/reference-javascript-light.svg b/studio/public/img/icons/reference-javascript-light.svg new file mode 100644 index 00000000000..a11845dff91 --- /dev/null +++ b/studio/public/img/icons/reference-javascript-light.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/studio/public/img/icons/reference-javascript.svg b/studio/public/img/icons/reference-javascript.svg new file mode 100644 index 00000000000..f8ce1de0403 --- /dev/null +++ b/studio/public/img/icons/reference-javascript.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/studio/public/img/icons/reference-python-light.svg b/studio/public/img/icons/reference-python-light.svg new file mode 100644 index 00000000000..1ac57aae572 --- /dev/null +++ b/studio/public/img/icons/reference-python-light.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/studio/public/img/icons/reference-python.svg b/studio/public/img/icons/reference-python.svg new file mode 100644 index 00000000000..4ca064b0b73 --- /dev/null +++ b/studio/public/img/icons/reference-python.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/studio/sentry.client.config.js b/studio/sentry.client.config.js index 456f62c88a0..23e597a09cb 100644 --- a/studio/sentry.client.config.js +++ b/studio/sentry.client.config.js @@ -39,6 +39,9 @@ Sentry.init({ // Safe to ignore since it's not a user-facing issue + we've not received any user feedback/report about it // Ref: https://github.com/supabase/supabase/pull/9729 'The provided `href` (/org/[slug]/general) value is missing query values (slug)', + 'The provided `href` (/org/[slug]/team) value is missing query values (slug)', + 'The provided `href` (/org/[slug]/billing) value is missing query values (slug)', + 'The provided `href` (/org/[slug]/invoices) value is missing query values (slug)', ], beforeSend: (event) => filterConsoleErrors(event), }) diff --git a/studio/stores/common/PostgresMetaInterface.ts b/studio/stores/common/PostgresMetaInterface.ts index 09f605b5acc..bd51fd319d5 100644 --- a/studio/stores/common/PostgresMetaInterface.ts +++ b/studio/stores/common/PostgresMetaInterface.ts @@ -117,6 +117,7 @@ export default class PostgresMetaInterface implements IPostgresMetaInterface< } } + // [Joshen] Only used for tables and views for now async loadBySchema(schema: string) { let { LOADING, ERROR, LOADED } = this.STATES try { @@ -132,7 +133,14 @@ export default class PostgresMetaInterface implements IPostgresMetaInterface< const data = response as T[] const formattedData = keyBy(data, this.identifier) - this.data = { ...this.data, ...formattedData } + // Purge existing data that belongs to given schema, otherwise + // stale data will persist + const purgedData = Object.keys(this.data) + .map((identifier: any) => this.data[identifier]) + .filter((item: any) => item.schema !== schema) + const formattedPurgedData = keyBy(purgedData, this.identifier) + + this.data = { ...formattedPurgedData, ...formattedData } this.setState(LOADED) return data diff --git a/studio/styles/ui.scss b/studio/styles/ui.scss index e927eb48782..e60672668f8 100644 --- a/studio/styles/ui.scss +++ b/studio/styles/ui.scss @@ -224,10 +224,40 @@ @apply border-b flex border-scale-500; } + &.Docs--table-editor .doc-section--introduction { + .text { + width: 85%; + } + } + + &.Docs--table-editor .doc-section--introduction { + .text { + width: 85%; + } + } + + &.Docs--table-editor .doc-section--client-libraries { + flex-direction: column; + margin-bottom: 40px; + + .text, + .code { + width: 100%; + max-width: none; + } + .code { + margin-bottom: 20px; + } + } + .doc-section article:first-child { @apply prose prose-docs prose-sm max-w-none; } + &.Docs--table-editor .doc-section__table-name { + @apply mt-12; + } + .text { @apply p-4 px-6 w-1/2; max-width: 50%; @@ -239,7 +269,7 @@ a { @apply transition; } - + a:hover { @apply text-brand-1000; } @@ -270,6 +300,9 @@ @apply text-brand-900; } } + .codeblock-container + .codeblock-container { + @apply mt-12; + } } ::-moz-selection { @@ -339,4 +372,4 @@ label { @apply mt-1; } -} \ No newline at end of file +}