Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: remove old vercel integration (#33295)

Alaister Youngf7ab150cc388
diff --git a/apps/studio/components/interfaces/Integrations/Vercel/VercelIntegration.utils.ts b/apps/studio/components/interfaces/Integrations/Vercel/VercelIntegration.utils.ts
new file mode 100644
index 00000000000..cf4a7f0c93b
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Vercel/VercelIntegration.utils.ts
@@ -0,0 +1,8 @@
+export function isVercelUrl(url: string): boolean {
+ try {
+ return new URL(url).hostname === 'vercel.com'
+ } catch {
+ // If the URL is invalid, return false
+ return false
+ }
+}
diff --git a/apps/studio/components/layouts/VercelIntegrationLayout.tsx b/apps/studio/components/layouts/VercelIntegrationLayout.tsx
deleted file mode 100644
index cd57fb5bbb1..00000000000
--- a/apps/studio/components/layouts/VercelIntegrationLayout.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import Head from 'next/head'
-import type { PropsWithChildren } from 'react'
-
-import { BASE_PATH } from 'lib/constants'
-import { Separator } from 'ui'
-
-const VercelIntegrationLayout = ({ children }: PropsWithChildren<{}>) => {
- return (
- <>
- <Head>
- <title>Supabase + Vercel</title>
- </Head>
- <main className="flex flex-col w-full h-full">
- <div>
- <div className="mx-auto px-4 sm:px-6">
- <div className="max-w-xl flex justify-between items-center mx-auto py-4">
- <div className="flex justify-start lg:w-0 lg:flex-1">
- <div>
- <span className="sr-only">Supabase</span>
- <img
- className="h-6 w-auto sm:h-6"
- src={`${BASE_PATH}/img/supabase-logo.svg`}
- alt=""
- />
- </div>
- </div>
- </div>
- </div>
- </div>
- <Separator />
- <div className="flex-grow overflow-y-auto">
- <div className="max-w-7xl h-full mx-auto px-4 sm:px-6">
- <div className="max-w-xl h-full mx-auto py-10">{children}</div>
- </div>
- </div>
- </main>
- </>
- )
-}
-export default VercelIntegrationLayout
diff --git a/apps/studio/components/to-be-cleaned/Integration/Vercel.utils.ts b/apps/studio/components/to-be-cleaned/Integration/Vercel.utils.ts
deleted file mode 100644
index b9ae4c8c945..00000000000
--- a/apps/studio/components/to-be-cleaned/Integration/Vercel.utils.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import { post, get } from 'lib/common/fetch'
-import { INTEGRATION_ENVS_ALIAS } from 'lib/vercelConfigs'
-import { API_URL } from 'lib/constants'
-
-async function doFetchVercelProjects({
- vercelToken,
- vercelTeamId,
- id,
-}: {
- vercelToken: string
- vercelTeamId?: string
- id?: string
-}) {
- let url = `${API_URL}/vercel/projects`
- if (id) {
- url += `/${id}`
- }
- if (vercelTeamId && vercelTeamId != 'null') {
- const query = new URLSearchParams({ teamId: vercelTeamId }).toString()
- url = `${url}?${query}`
- }
- const data = await get(url, {
- headers: { vercel_authorization: `Bearer ${vercelToken}` },
- })
- if (data.error != null) {
- return { error: `Retrieve vercel project${id ? '' : 's'} failed. ${data.error.message}` }
- }
- return { data }
-}
-
-export async function fetchVercelProjects(params: { vercelToken: string; vercelTeamId?: string }) {
- return (await doFetchVercelProjects(params)) as {
- data?: Record<string, any>[]
- error?: string
- }
-}
-
-export async function fetchVercelProject(params: {
- id: string
- vercelToken: string
- vercelTeamId?: string
-}) {
- return (await doFetchVercelProjects(params)) as {
- data?: Record<string, any>
- error?: string
- }
-}
-
-export async function fetchVercelProjectEnvs({
- id,
- vercelTeamId,
- vercelToken,
-}: {
- id: string
- vercelTeamId?: string
- vercelToken: string
-}): Promise<{ data?: Record<string, any>[]; error?: string }> {
- let url = `${API_URL}/vercel/projects/envs`
- if (vercelTeamId && vercelTeamId != 'null') {
- const query = new URLSearchParams({ projectId: id, teamId: vercelTeamId }).toString()
- url = `${url}?${query}`
- } else {
- const query = new URLSearchParams({ projectId: id }).toString()
- url = `${url}?${query}`
- }
- const response = await get(url, {
- headers: { vercel_authorization: `Bearer ${vercelToken}` },
- })
- if (response.error != null) {
- return { error: `Retrieve vercel project envs failed. ${response.error?.message}` }
- }
- return { data: response }
-}
-
-export async function createVercelEnv({
- key,
- value,
- type,
- target,
- vercelProjectId,
- vercelTeamId,
- vercelToken,
-}: {
- key: string
- value: string
- type: 'encrypted' | string
- target: ('production' | 'development' | 'preview')[]
- vercelProjectId: string
- vercelTeamId?: string
- vercelToken: string
-}) {
- let url = `${API_URL}/vercel/projects/envs`
- if (vercelTeamId && vercelTeamId != 'null') {
- const query = new URLSearchParams({
- projectId: vercelProjectId,
- teamId: vercelTeamId,
- }).toString()
- url = `${url}?${query}`
- } else {
- const query = new URLSearchParams({ projectId: vercelProjectId }).toString()
- url = `${url}?${query}`
- }
- return await post(
- url,
- { key, value, type, target },
- {
- headers: { vercel_authorization: `Bearer ${vercelToken}` },
- }
- )
-}
-
-export function prepareVercelEvns(
- requiredEnvs: {
- key: string
- alias: string
- type: 'encrypted' | string
- }[],
- project: {
- db_host?: string
- db_password?: string
- endpoint: string
- anon_key: string
- service_key: string
- }
-) {
- const envs: any = []
-
- requiredEnvs.forEach((x) => {
- let env: {
- key: string
- value: string
- type: 'encrypted' | string
- target: ('production' | 'development' | 'preview')[]
- } = { key: x.key, type: x.type, target: ['production', 'development', 'preview'], value: '' }
-
- switch (x.alias) {
- case INTEGRATION_ENVS_ALIAS.ENDPOINT:
- env.value = project.endpoint
- break
- case INTEGRATION_ENVS_ALIAS.ANONKEY:
- env.value = project.anon_key
- break
- case INTEGRATION_ENVS_ALIAS.SERVICEKEY:
- env.value = project.service_key
- break
- case INTEGRATION_ENVS_ALIAS.DBHOST:
- env.value = project.db_host ?? ''
- break
- case INTEGRATION_ENVS_ALIAS.DBPASSWORD:
- env.value = project.db_password ?? ''
- break
- }
-
- envs.push(env)
- })
-
- return envs
-}
diff --git a/apps/studio/lib/vercelConfigs.ts b/apps/studio/lib/vercelConfigs.ts
deleted file mode 100644
index 1a4473da6a0..00000000000
--- a/apps/studio/lib/vercelConfigs.ts
+++ /dev/null
@@ -1,545 +0,0 @@
-import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.queries'
-
-const QuickStart = SQL_TEMPLATES.filter((template) => template.type === 'quickstart')
-
-export const INTEGRATION_ENVS_ALIAS = {
- ENDPOINT: 'SUPABASE_ENDPOINT',
- ANONKEY: 'SUPABASE_ANON_KEY',
- SERVICEKEY: 'SUPABASE_SERVICE_KEY',
- DBHOST: 'SUPABASE_DB_HOST',
- DBPASSWORD: 'SUPABASE_DB_PASSWORD',
-}
-export const VERCEL_DEFAULT_EXTERNAL_ID = 'nextjs-initial-project'
-/*
-These values have to match our integrations setup (per project)
-under https://vercel.com/dashboard/supabase/integrations/console
-
-'id' needs to be the same as deploy button External ID
-https://vercel.com/docs/more/deploy-button#external-id
-*/
-export const VERCEL_INTEGRATION_CONFIGS = [
- {
- id: 'supabase_realtime_map',
- name: 'Realtime Map Database',
- template: {
- sql: `CREATE TABLE locations (
- id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- latitude numeric NOT NULL,
- longitude numeric NOT NULL,
- ref VARCHAR(40)
- );`,
- },
- envs: [
- {
- key: 'NEXT_PUBLIC_SUPABASE_ENDPOINT',
- alias: INTEGRATION_ENVS_ALIAS.ENDPOINT,
- type: 'encrypted',
- },
- {
- key: 'NEXT_PUBLIC_SUPABASE_APIKEY',
- alias: INTEGRATION_ENVS_ALIAS.ANONKEY,
- type: 'encrypted',
- },
- ],
- },
- {
- id: 'nextjs-subscription-payments',
- name: 'Next.js Subscription Payments Starter',
- template: QuickStart.find((x) => x.title == 'Stripe Subscriptions'),
- envs: [
- {
- key: 'NEXT_PUBLIC_SUPABASE_URL',
- alias: INTEGRATION_ENVS_ALIAS.ENDPOINT,
- type: 'encrypted',
- },
- {
- key: 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
- alias: INTEGRATION_ENVS_ALIAS.ANONKEY,
- type: 'encrypted',
- },
- {
- key: 'SUPABASE_SERVICE_ROLE_KEY',
- alias: INTEGRATION_ENVS_ALIAS.SERVICEKEY,
- type: 'encrypted',
- },
- ],
- },
- {
- id: 'nextjs-open-ai-doc-search',
- name: 'Next.js OpenAI Doc Search Starter',
- template: QuickStart.find((x) => x.title == 'OpenAI Vector Search'),
- envs: [
- {
- key: 'NEXT_PUBLIC_SUPABASE_URL',
- alias: INTEGRATION_ENVS_ALIAS.ENDPOINT,
- type: 'encrypted',
- },
- {
- key: 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
- alias: INTEGRATION_ENVS_ALIAS.ANONKEY,
- type: 'encrypted',
- },
- {
- key: 'SUPABASE_SERVICE_ROLE_KEY',
- alias: INTEGRATION_ENVS_ALIAS.SERVICEKEY,
- type: 'encrypted',
- },
- ],
- },
- {
- id: 'supabase-todo-list',
- name: 'Todo List Database',
- template: QuickStart.find((x) => x.title == 'Todo List'),
- envs: [
- {
- key: 'NEXT_PUBLIC_SUPABASE_URL',
- alias: INTEGRATION_ENVS_ALIAS.ENDPOINT,
- type: 'encrypted',
- },
- {
- key: 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
- alias: INTEGRATION_ENVS_ALIAS.ANONKEY,
- type: 'encrypted',
- },
- ],
- },
- {
- id: 'nextjs-initial-project',
- name: 'New Empty Database',
- template: {
- sql: '',
- },
- envs: [
- {
- key: 'NEXT_PUBLIC_SUPABASE_URL',
- alias: INTEGRATION_ENVS_ALIAS.ENDPOINT,
- type: 'encrypted',
- },
- {
- key: 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
- alias: INTEGRATION_ENVS_ALIAS.ANONKEY,
- type: 'encrypted',
- },
- {
- key: 'SUPABASE_SERVICE_ROLE_KEY',
- alias: INTEGRATION_ENVS_ALIAS.SERVICEKEY,
- type: 'encrypted',
- },
- {
- key: 'SUPABASE_DB_HOST',
- alias: INTEGRATION_ENVS_ALIAS.DBHOST,
- type: 'encrypted',
- },
- {
- key: 'SUPABASE_DB_PASSWORD',
- alias: INTEGRATION_ENVS_ALIAS.DBPASSWORD,
- type: 'encrypted',
- },
- ],
- },
- {
- id: 'nextjs-user-management',
- name: 'User Management Starter',
- template: QuickStart.find((x) => x.title == 'User Management Starter'),
- envs: [
- {
- key: 'NEXT_PUBLIC_SUPABASE_URL',
- alias: INTEGRATION_ENVS_ALIAS.ENDPOINT,
- type: 'encrypted',
- },
- {
- key: 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
- alias: INTEGRATION_ENVS_ALIAS.ANONKEY,
- type: 'encrypted',
- },
- {
- key: 'SUPABASE_SERVICE_ROLE_KEY',
- alias: INTEGRATION_ENVS_ALIAS.SERVICEKEY,
- type: 'encrypted',
- },
- ],
- },
- {
- id: 'threaded-comments',
- name: 'Threaded Comments',
- template: {
- sql: `
--- Create a table for Public Profiles
-create table profiles (
- id uuid references auth.users not null,
- updated_at timestamp with time zone,
- username text unique,
- full_name text,
- avatar_url text,
- website text,
-
- primary key (id),
- unique (username),
- constraint username_length check (char_length(username) >= 3)
-);
-
-alter table profiles enable row level security;
-
-create policy "Public profiles are viewable by everyone."
- on profiles for select
- using ( true );
-
-create policy "Users can insert their own profile."
- on profiles for insert
- with check ( (select auth.uid()) = id );
-
-create policy "Users can update own profile."
- on profiles for update
- using ( (select auth.uid()) = id );
-
--- Create a trigger to sync profiles and auth.users
-create function public.handle_new_user()
-returns trigger
-set search_path = ''
-as $$
-begin
- insert into public.profiles (id, full_name, avatar_url)
- values (new.id, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url');
- return new;
-end;
-$$ language plpgsql security definer;
-
-create trigger on_auth_user_created
- after insert on auth.users
- for each row execute procedure public.handle_new_user();
-
-
--- Create a table for posts
-create table posts (
- id bigserial not null,
- slug text not null unique,
- "createdAt" timestamp with time zone default now() not null,
- "updatedAt" timestamp with time zone default now() null,
- title text null,
- content text null,
- "isPublished" boolean default false not null,
- "authorId" uuid not null references profiles (id),
- "parentId" bigint null references posts (id),
- live boolean default true null,
- "siteId" bigint default '1' ::bigint not null,
- "isPinned" boolean default false not null,
- "isDeleted" boolean default false not null,
- "isApproved" boolean default false not null,
-
- primary key (id),
- unique (slug)
-);
-
-alter table posts enable row level security;
-
--- Create root user and initial post. Triggers update in profiles.
-insert into auth.users (id) values ('00000000-0000-0000-0000-000000000000'::uuid);
-
-update profiles
-set
- full_name = 'Admin',
- avatar_url = 'https://assets3.thrillist.com/v1/image/1875552/414x310/crop;jpeg_quality=65.jpg'
-where
- id = '00000000-0000-0000-0000-000000000000'::uuid;
-
-insert into posts (slug, title, content, "authorId") values ('root', 'Root post', 'root post', '00000000-0000-0000-0000-000000000000'::uuid);
-insert into posts (slug, title, content, "authorId", "parentId") values ('threaded-comments-123', 'threaded-comments', 'Threaded comments, built on top of Supabase and Next.js. Visit GitHub to deploy your own: https://github.com/lawrencecchen/threaded-comments', '00000000-0000-0000-0000-000000000000'::uuid, 1);
-
-create policy "Posts are viewable by everyone."
- on posts for select
- using ( true );
-
-create policy "Users can post as themselves."
- on posts for insert
- with check ( (select auth.uid()) = "authorId" );
-
--- Create a table for sites
-create table sites (
- id bigserial not null,
- "siteDomain" text not null,
- "ownerId" uuid not null,
- "name" text not null,
-
- primary key (id)
-);
-
-alter table sites enable row level security;
-
-create policy "Sites are viewable by everyone."
- on sites for select
- using ( true );
-
-create policy "Users can create their own sites."
- on sites for insert
- with check ( (select auth.uid()) = "ownerId" );
-
--- Create a table for votes
-create table votes (
- "postId" bigint not null references posts (id),
- "userId" uuid not null references profiles (id),
- "value" int not null,
-
- primary key ("postId", "userId"),
- constraint vote_quantity check (value <= 1 and value >= -1)
-);
-
-alter table votes enable row level security;
-
-create policy "Votes are viewable by everyone"
- on votes for select
- using ( true );
-
-create policy "Users can vote as themselves"
- on votes for insert
- with check ((select auth.uid()) = "userId");
-
-create policy "Users can update their own votes"
- on votes for update
- using ( (select auth.uid()) = "userId" );
-
-
--- Set up Realtime!
-begin;
- drop publication if exists supabase_realtime;
- create publication supabase_realtime;
-commit;
-alter publication supabase_realtime add table posts, sites, votes, profiles;
-
--- Set up Storage!
-insert into storage.buckets (id, name)
-values ('avatars', 'avatars');
-
-create policy "Avatar images are publicly accessible."
- on storage.objects for select
- using ( bucket_id = 'avatars' );
-
-create policy "Anyone can upload an avatar."
- on storage.objects for insert
- with check ( bucket_id = 'avatars' );
-
-drop view if exists comments_thread_with_user_vote;
-drop view if exists comments_thread;
-drop view if exists comments_with_author_votes;
-drop view if exists comments_linear_view;
-drop view if exists comment_with_author;
-
-create view comment_with_author as
- select
- p.id,
- p.slug,
- p."createdAt",
- p."updatedAt",
- p.title,
- p.content,
- p."isPublished",
- p."authorId",
- p."parentId",
- p.live,
- p."siteId",
- p."isPinned",
- p."isDeleted",
- p."isApproved",
- to_jsonb(u) as author
- from
- posts p
- inner join profiles u on p."authorId" = u.id;
-
-create view comments_linear_view as
- select
- root_c.*,
- to_jsonb(parent_c) as parent,
- coalesce(json_agg(children_c) filter (where children_c.id is not null), '[]') as responses
- from
- comment_with_author root_c
- inner join comment_with_author parent_c on root_c."parentId" = parent_c.id
- inner join sites s1 on s1.id = root_c."siteId"
- left join comment_with_author children_c on children_c."parentId" = root_c.id
- group by
- root_c.id,
- root_c.slug,
- root_c."createdAt",
- root_c."updatedAt",
- root_c.title,
- root_c.content,
- root_c."isPublished",
- root_c."authorId",
- root_c."parentId",
- root_c.live,
- root_c."siteId",
- root_c."isPinned",
- root_c."isDeleted",
- root_c."isApproved",
- root_c.author,
- parent_c.*;
-
-create or replace view comments_with_author_votes as
- select
- p.id,
- p.slug,
- p."createdAt",
- p."updatedAt",
- p.title,
- p.content,
- p."isPublished",
- p."authorId",
- p."parentId",
- p.live,
- p."siteId",
- p."isPinned",
- p."isDeleted",
- p."isApproved",
- p."author",
- coalesce (
- sum (v.value) over w,
- 0
- ) as "votes",
- sum (case when v.value > 0 then 1 else 0 end) over w as "upvotes",
- sum (case when v.value < 0 then 1 else 0 end) over w as "downvotes"
- -- (select case when auth.uid() = v."userId" then v.value else 0 end) as "userVoteValue"
- from
- comment_with_author p
- left join votes v on p.id = v."postId"
- window w as (
- partition by v."postId"
- );
-
-create recursive view comments_thread (
- id,
- slug,
- "createdAt",
- "updatedAt",
- title,
- content,
- "isPublished",
- "authorId",
- "parentId",
- live,
- "siteId",
- "isPinned",
- "isDeleted",
- "isApproved",
- "author",
- "votes",
- "upvotes",
- "downvotes",
- "depth",
- "path",
- "pathVotesRecent",
- "pathLeastRecent",
- "pathMostRecent"
-) as
- select
- id,
- slug,
- "createdAt",
- "updatedAt",
- title,
- content,
- "isPublished",
- "authorId",
- "parentId",
- live,
- "siteId",
- "isPinned",
- "isDeleted",
- "isApproved",
- "author",
- "votes",
- "upvotes",
- "downvotes",
- 0 as depth,
- array[id] as "path",
- array[id] as "pathVotesRecent",
- array[id] as "pathLeastRecent",
- array[id] as "pathMostRecent"
- from
- comments_with_author_votes
- where
- "parentId" is null
- union all
- select
- p1.id,
- p1.slug,
- p1."createdAt",
- p1."updatedAt",
- p1.title,
- p1.content,
- p1."isPublished",
- p1."authorId",
- p1."parentId",
- p1.live,
- p1."siteId",
- p1."isPinned",
- p1."isDeleted",
- p1."isApproved",
- p1."author",
- p1."votes",
- p1."upvotes",
- p1."downvotes",
- p2.depth + 1 as depth,
- p2."path" || p1.id::bigint as "path",
- p2."pathVotesRecent" || -p1."votes"::bigint || -extract(epoch from p1."createdAt")::bigint || p1.id as "pathVotesRecent",
- p2."pathLeastRecent" || extract(epoch from p1."createdAt")::bigint || p1.id as "pathLeastRecent",
- p2."pathMostRecent" || -extract(epoch from p1."createdAt")::bigint || p1.id as "pathMostRecent"
- from
- comments_with_author_votes p1
- join comments_thread p2 on p1."parentId" = p2.id;
-
-create or replace view comments_thread_with_user_vote as
- select distinct on (id)
- id,
- slug,
- "createdAt",
- "updatedAt",
- title,
- content,
- "isPublished",
- "authorId",
- "parentId",
- live,
- "siteId",
- "isPinned",
- "isDeleted",
- "isApproved",
- "author",
- "votes",
- "upvotes",
- "downvotes",
- "depth",
- "path",
- "pathVotesRecent",
- "pathLeastRecent",
- "pathMostRecent",
- coalesce(
- (
- select
- v."value"
- from
- votes v
- where
- auth.uid() = v."userId" and v."postId" = id
- ),
- 0
- ) as "userVoteValue"
- from comments_thread;
- `,
- },
- envs: [
- {
- key: 'NEXT_PUBLIC_SUPABASE_URL',
- alias: INTEGRATION_ENVS_ALIAS.ENDPOINT,
- type: 'encrypted',
- },
- {
- key: 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
- alias: INTEGRATION_ENVS_ALIAS.ANONKEY,
- type: 'encrypted',
- },
- {
- key: 'SUPABASE_SERVICE_ROLE_KEY',
- alias: INTEGRATION_ENVS_ALIAS.SERVICEKEY,
- type: 'encrypted',
- },
- ],
- },
-]
diff --git a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
index e122648eb46..5d3d5e2a23e 100644
--- a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
+++ b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
@@ -5,6 +5,7 @@ import { ChangeEvent, useRef, useState } from 'react'
import { toast } from 'sonner'
import { Alert, Button, Checkbox, Input, Listbox } from 'ui'
+import { isVercelUrl } from 'components/interfaces/Integrations/Vercel/VercelIntegration.utils'
import { Markdown } from 'components/interfaces/Markdown'
import VercelIntegrationWindowLayout from 'components/layouts/IntegrationsLayout/VercelIntegrationWindowLayout'
import { ScaffoldColumn, ScaffoldContainer } from 'components/layouts/Scaffold'
@@ -200,7 +201,7 @@ const CreateProject = () => {
snapshot.setLoading(false)
- if (next) {
+ if (next && isVercelUrl(next)) {
window.location.href = next
}
},
diff --git a/apps/studio/pages/integrations/vercel/[slug]/marketplace/choose-project.tsx b/apps/studio/pages/integrations/vercel/[slug]/marketplace/choose-project.tsx
index 640aea4062b..5bd457b5e20 100644
--- a/apps/studio/pages/integrations/vercel/[slug]/marketplace/choose-project.tsx
+++ b/apps/studio/pages/integrations/vercel/[slug]/marketplace/choose-project.tsx
@@ -4,6 +4,7 @@ import { toast } from 'sonner'
import { useParams } from 'common'
import { ENV_VAR_RAW_KEYS } from 'components/interfaces/Integrations/Vercel/Integrations-Vercel.constants'
+import { isVercelUrl } from 'components/interfaces/Integrations/Vercel/VercelIntegration.utils'
import ProjectLinker, {
ForeignProject,
} from 'components/interfaces/Integrations/VercelGithub/ProjectLinker'
@@ -26,7 +27,7 @@ const VERCEL_ICON = (
)
const VercelIntegration: NextPageWithLayout = () => {
- const { slug, configurationId, next, organizationSlug } = useParams()
+ const { slug, configurationId, next } = useParams()
/**
* Fetch the list of organization based integration installations for Vercel.
@@ -106,7 +107,7 @@ const VercelIntegration: NextPageWithLayout = () => {
const { mutate: createConnections, isLoading: isCreatingConnection } =
useIntegrationVercelConnectionsCreateMutation({
onSuccess() {
- if (next) {
+ if (next && isVercelUrl(next)) {
snapshot.setLoading(false)
window.location.href = next
}
@@ -164,7 +165,7 @@ This Supabase integration manages your environment variables automatically to pr
getForeignProjectIcon={getForeignProjectIcon}
choosePrompt="Choose Vercel Project"
onSkip={() => {
- if (next) {
+ if (next && isVercelUrl(next)) {
window.location.href = next
}
}}
diff --git a/apps/studio/pages/vercel/complete.tsx b/apps/studio/pages/vercel/complete.tsx
deleted file mode 100644
index 2b3bb711b8c..00000000000
--- a/apps/studio/pages/vercel/complete.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import VercelIntegrationLayout from 'components/layouts/VercelIntegrationLayout'
-import { Loader } from 'lucide-react'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import { createContext, useEffect, useState } from 'react'
-import { Button } from 'ui'
-
-const PageContext = createContext(null)
-function IntegrationComplete() {
- const PageState = useLocalObservable(() => ({
- supabaseProjectRef: '',
- next: '',
- loadInitialData() {
- this.getQueryParams()
- },
- getQueryParams() {
- const params = new URLSearchParams(window.location.search)
- this.next = params.get('next') as string
- this.supabaseProjectRef = params.get('supabaseProjectRef') as string
- },
- }))
- const [loading, setLoading] = useState(false)
-
- useEffect(() => {
- PageState.loadInitialData()
- }, [])
-
- function onContinue() {
- setLoading(true)
- window.location.href = PageState.next
- }
-
- return (
- // @ts-ignore
- <PageContext.Provider value={PageState}>
- <VercelIntegrationLayout>
- <div className="mx-auto max-w-sm">
- <Loader className="animate-spin" size={30} />
- <p className="pt-4 text-lg">Your new project is spinning up</p>
- <p className="pt-2">This may take up to 2 mins, but you can continue on Vercel.</p>
- <div className="py-4">
- <a
- href={`/project/${PageState.supabaseProjectRef}`}
- target="_blank"
- rel="noreferrer"
- className="hover:text-green-1000"
- >
- Open Supabase Dashboard →
- </a>
- </div>
-
- <Button disabled={loading} loading={loading} onClick={onContinue} block>
- Finish
- </Button>
- </div>
- </VercelIntegrationLayout>
- </PageContext.Provider>
- )
-}
-export default observer(IntegrationComplete)
diff --git a/apps/studio/pages/vercel/integrate.tsx b/apps/studio/pages/vercel/integrate.tsx
deleted file mode 100644
index 2ce3198ef65..00000000000
--- a/apps/studio/pages/vercel/integrate.tsx
+++ /dev/null
@@ -1,644 +0,0 @@
-import { makeAutoObservable, runInAction } from 'mobx'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import Link from 'next/link'
-import { useRouter } from 'next/router'
-import { ChangeEvent, createContext, useContext, useEffect, useState } from 'react'
-import { toast } from 'sonner'
-
-import VercelIntegrationLayout from 'components/layouts/VercelIntegrationLayout'
-import {
- createVercelEnv,
- fetchVercelProjectEnvs,
- fetchVercelProjects,
- prepareVercelEvns,
-} from 'components/to-be-cleaned/Integration/Vercel.utils'
-import { databaseIcon, vercelIcon } from 'components/to-be-cleaned/ListIcons'
-import { Loading } from 'components/ui/Loading'
-import { useProjectsQuery } from 'data/projects/projects-query'
-import { withAuth } from 'hooks/misc/withAuth'
-import { get } from 'lib/common/fetch'
-import { get as getV2 } from 'data/fetchers'
-import { API_URL } from 'lib/constants'
-import {
- INTEGRATION_ENVS_ALIAS,
- VERCEL_DEFAULT_EXTERNAL_ID,
- VERCEL_INTEGRATION_CONFIGS,
-} from 'lib/vercelConfigs'
-import type { Dictionary } from 'types'
-import { Button, Listbox, Select, Separator } from 'ui'
-import { PlusCircle, ChevronRight, X } from 'lucide-react'
-import { getAPIKeys } from 'data/config/project-settings-v2-query'
-
-interface IVercelIntegrationStore {
- code: string
- token: string
- teamId: string
- externalId: string
- configurationId: string
- next: string
- currentProjectId?: string
- selectedVercelProjectId?: string
- vercelProjects: Dictionary<any>[]
- loading: boolean
- waitingIntegration: boolean
- projectLinks: {
- vercelProjectId?: string
- supabaseProjectRef?: string
- error?: string
- result?: { status: 'waiting' | 'success' | 'fail'; message?: string }
- }[]
-
- isDeployButtonFlow: boolean
- integrationComplete: boolean
- queryParams: Dictionary<string>
- projectLinkRemaining: number
- vercelProjectsAvailable: Dictionary<string>[]
-
- loadInitialData: () => void
-}
-
-class VercelIntegrationStore implements IVercelIntegrationStore {
- code: string = ''
- token: string = ''
- teamId: string = ''
- externalId: string = ''
- configurationId: string = ''
- next: string = ''
- currentProjectId?: string
- selectedVercelProjectId?: string
- vercelProjects: Dictionary<any>[] = []
- loading: boolean = true
- // @ts-ignore
- waitingIntegration: boolean
- projectLinks: {
- vercelProjectId?: string
- supabaseProjectRef?: string
- error?: string
- result?: { status: 'waiting' | 'success' | 'fail'; message?: string }
- }[] = [
- {
- vercelProjectId: undefined,
- supabaseProjectRef: undefined,
- },
- ]
-
- constructor() {
- makeAutoObservable(this)
- // this.globalStore = globalStore
- }
-
- get isDeployButtonFlow() {
- return !!this.currentProjectId
- }
-
- // @ts-ignore
- get queryParams() {
- return {
- token: this.token,
- teamId: this.teamId,
- 'external-id': this.externalId,
- configurationId: this.configurationId,
- vercelProjectId: this.selectedVercelProjectId,
- next: this.next,
- }
- }
-
- get projectLinkRemaining() {
- if (!this.vercelProjects) return 0
- const temp = this.vercelProjects?.length - this.projectLinks.length
- return temp >= 0 ? temp : 0
- }
-
- get vercelProjectsAvailable() {
- const existed = this.projectLinks.map((x) => x.vercelProjectId)
- const filtered = this.vercelProjects.filter((x) => existed.includes(x.id) == false)
- return filtered
- }
-
- get integrationComplete() {
- if (!this.waitingIntegration) return false
- const pendingItegrations = this.projectLinks.filter((x) => !x.result || !x.result?.message)
- return pendingItegrations.length == 0
- }
-
- loadInitialData() {
- this.getQueryParams()
- this.getVercelAuthToken()
- }
-
- getQueryParams() {
- const params = new URLSearchParams(window.location.search)
- this.code = params.get('code') as string
- this.configurationId = params.get('configurationId') as string
- this.currentProjectId = params.get('currentProjectId') as string
- this.next = params.get('next') as string
- this.externalId = params.get('external-id') || VERCEL_DEFAULT_EXTERNAL_ID
- this.teamId = params.get('teamId') as string
-
- // double check and set VERCEL_DEFAULT_EXTERNAL_ID as default externalId if config invalid
- const config = VERCEL_INTEGRATION_CONFIGS.find((x) => x.id == this.externalId)
- if (!config) this.externalId = VERCEL_DEFAULT_EXTERNAL_ID
- }
-
- async getVercelAuthToken() {
- const query = new URLSearchParams({
- code: this.code,
- }).toString()
- const response = await get(`${API_URL}/vercel/token?${query}`)
- if (!response.errror) {
- this.token = response.token
- // retrieve vercel projects after getting token
- await this.getVercelProjects()
- this.loading = false
- } else {
- toast.error(`Failed to retrieve Vercel token: ${response.error.message}`)
- this.loading = false
- }
- }
- async getVercelProjects() {
- const { data, error } = await fetchVercelProjects({
- vercelTeamId: this.teamId,
- vercelToken: this.token,
- })
- if (error) {
- toast.error(error)
- } else if (data) {
- this.vercelProjects = data
- // if currentProjectId available. Auto select it
- if (this.currentProjectId) {
- // @ts-ignore
- const found = data.find((x: { id: string }) => (x.id = this.currentProjectId))
- if (found) this.selectedVercelProjectId = found.id
- }
- }
- }
-}
-const PageContext = createContext<IVercelIntegrationStore>(undefined!)
-
-const VercelIntegration = () => {
- // @ts-ignore
- const _store: IVercelIntegrationStore = useLocalObservable(() => new VercelIntegrationStore())
- const { data: projects } = useProjectsQuery()
- const isSupabaseProjectListEmpty = !projects || projects?.length === 0
-
- useEffect(() => {
- _store.loadInitialData()
- }, [])
-
- return (
- <PageContext.Provider value={_store}>
- <VercelIntegrationLayout>
- {_store.loading ? (
- <Connecting />
- ) : _store.isDeployButtonFlow ? (
- <IntegrationProject />
- ) : isSupabaseProjectListEmpty ? (
- <ProjectLinksEmptyState />
- ) : (
- <ProjectLinks />
- )}
- </VercelIntegrationLayout>
- </PageContext.Provider>
- )
-}
-export default withAuth(observer(VercelIntegration))
-
-const Connecting = () => (
- <div className="flex h-full w-full flex-col items-center justify-center">
- <div className="flex w-32 items-center justify-center">
- <Loading />
- </div>
- <p>Connecting...</p>
- </div>
-)
-
-const ProjectLinksEmptyState = () => (
- <div className="flex flex-col space-y-4">
- <p>
- You haven't created a Supabase project yet. Get started by creating a new Supabase project,
- then close this window and retry adding integration.
- </p>
- <Link href="https://supabase.com/dashboard" className="text-brand">
- Start a new Supabase project<span aria-hidden="true"> &rarr;</span>
- </Link>
- </div>
-)
-
-const UNDEFINED_SELECT_VALUE = 'undefined'
-const IntegrationProject = observer(() => {
- const _store = useContext(PageContext)
- const router = useRouter()
- const [name, setName] = useState<string>('')
- const [loading, setLoading] = useState<boolean>(false)
- const [errorMsg, setErrorMsg] = useState<string>()
-
- useEffect(() => {
- const config = VERCEL_INTEGRATION_CONFIGS.find((x) => x.id == _store.externalId)
- if (!config && !errorMsg) setErrorMsg('This integration is not supported right now')
- else setName(config?.name || _store.externalId)
- }, [_store.externalId])
-
- function onClick() {
- if (!_store.selectedVercelProjectId) {
- setErrorMsg('Error: please select a vercel project to continue')
- return
- }
- if (!_store.token || _store.token == '') {
- setErrorMsg('Error: vercel auth token is invalid')
- return
- }
-
- setLoading(true)
- const query = new URLSearchParams(_store.queryParams).toString()
- router.push(`/vercel/setupOrg?${query}`)
- }
-
- function onVercelProjectChange(e: ChangeEvent<HTMLSelectElement>) {
- setErrorMsg(undefined)
- _store.selectedVercelProjectId =
- e.target.value != UNDEFINED_SELECT_VALUE ? e.target.value : undefined
- }
-
- return (
- <div className="flex w-full flex-col items-center">
- <div className="mb-8 w-full">
- <Select
- label="Vercel project"
- value={_store.selectedVercelProjectId}
- onChange={onVercelProjectChange}
- >
- <Select.Option value={UNDEFINED_SELECT_VALUE}>---</Select.Option>
- {_store.vercelProjects?.map((x) => {
- return (
- <Select.Option key={x.id} value={x.id}>
- {x.name}
- </Select.Option>
- )
- })}
- </Select>
- </div>
- <div
- className="w-full rounded-sm border border-strong
- bg-panel-header-light [[data-theme*=dark]_&]:bg-panel-header-dark"
- >
- <div className="flex items-center justify-between p-6">
- <h4 className="my-auto mr-8 text-lg capitalize">{name}</h4>
- <Button disabled={loading || !!errorMsg} loading={loading} onClick={onClick}>
- Deploy
- </Button>
- </div>
- </div>
- {errorMsg && <p className="py-4 text-foreground-light">{errorMsg}</p>}
- </div>
- )
-})
-
-const delayTimer = (ms: number) => new Promise((res) => setTimeout(res, ms))
-const defaultVercelEnvs = [
- {
- key: 'NEXT_PUBLIC_SUPABASE_URL',
- alias: INTEGRATION_ENVS_ALIAS.ENDPOINT,
- type: 'encrypted',
- },
- {
- key: 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
- alias: INTEGRATION_ENVS_ALIAS.ANONKEY,
- type: 'encrypted',
- },
- {
- key: 'SUPABASE_SERVICE_ROLE_KEY',
- alias: INTEGRATION_ENVS_ALIAS.SERVICEKEY,
- type: 'encrypted',
- },
-]
-const ProjectLinks = observer(() => {
- const _store = useContext(PageContext)
-
- async function onSubmit() {
- if (validateInputs()) {
- runInAction(() => {
- _store.waitingIntegration = true
- })
- for (let i = 0; i < _store.projectLinks.length; i++) {
- const item = _store.projectLinks[i]
- runInAction(() => {
- item.result = { status: 'waiting' }
- })
-
- // pull vercel project env, check if supabase env is existed or not
- const { data: existedEnvs, error: fetchEnvsError }: any = await fetchVercelProjectEnvs({
- id: item.vercelProjectId as string,
- vercelTeamId: _store.teamId,
- vercelToken: _store.token,
- })
- if (fetchEnvsError) {
- console.error('envsError: ', fetchEnvsError)
- runInAction(() => {
- item.result = {
- status: 'fail',
- message: 'Error: Failed to validate Vercel project envs',
- }
- })
- continue
- }
- const found = existedEnvs.find((x: any) => x.key.includes('SUPABASE'))
- if (!!found) {
- console.error('Existed Supabase env: ', found)
- runInAction(() => {
- item.result = {
- status: 'fail',
- message: 'Error: This Vercel project already contains Supabase envs',
- }
- })
- continue
- }
- // If not, pull project detail info
- if (item.supabaseProjectRef === undefined) {
- console.error('Project ref is missing')
- runInAction(() => {
- item.result = {
- status: 'fail',
- message: 'Error: Failed to retrieve project ref',
- }
- })
- continue
- }
- const { data: settings, error } = await getV2('/platform/projects/{ref}/settings', {
- params: { path: { ref: item.supabaseProjectRef } },
- })
-
- if (error) {
- console.error('project info error: ', error)
- runInAction(() => {
- item.result = {
- status: 'fail',
- message: 'Error: Failed to fetch Supabase project details',
- }
- })
- continue
- }
-
- // Then create env for vercel project with supabase project
- const endpoint = `https://${settings.app_config?.endpoint ?? '-'}`
- const { anonKey, serviceKey } = getAPIKeys(settings)
- const vercelEnvs = prepareVercelEvns(defaultVercelEnvs, {
- endpoint,
- anon_key: anonKey?.api_key ?? '',
- service_key: serviceKey?.api_key ?? '',
- })
-
- await Promise.allSettled(
- vercelEnvs.map(async (env: any) => {
- try {
- const data = await createVercelEnv({
- ...env,
- vercelProjectId: item.vercelProjectId,
- vercelTeamId: _store.teamId,
- vercelToken: _store.token,
- })
- return data
- } catch (err) {
- console.error(`Error: ${err}`)
- }
- })
- )
-
- runInAction(() => {
- item.result = {
- status: 'success',
- message: 'Projects linked successfully',
- }
- })
- await delayTimer(1000)
- }
- }
- }
-
- function validateInputs() {
- let isValid = true
- for (let i = 0; i < _store.projectLinks.length; i++) {
- const item = _store.projectLinks[i]
- if (!item.supabaseProjectRef || !item.vercelProjectId) {
- isValid = false
- runInAction(() => {
- _store.projectLinks[i].error =
- 'Invalid selection. Please choose a Vercel project and a Supabase project to link.'
- })
- }
- }
-
- return isValid
- }
-
- function onFinish() {
- window.location.href = _store.next
- }
-
- function displayButton() {
- if (!_store.integrationComplete) {
- return (
- <Button onClick={onSubmit} loading={_store.waitingIntegration}>
- Add Integration
- </Button>
- )
- }
-
- if (_store.projectLinks.every(({ result: { status } }: any) => status === 'success')) {
- onFinish()
- } else {
- return <Button onClick={onFinish}>Finish</Button>
- }
- }
-
- return (
- <div className="flex w-full flex-col space-y-6">
- <div>
- <h4 className="text-lg">Link Vercel to Supabase</h4>
- <p>Choose which of your Vercel projects to link to your existing Supabase projects.</p>
- </div>
- <Separator />
- <div className="space-y-2">
- <div className="flex justify-between">
- <p className="text-foreground-light">Vercel Projects</p>
- <div />
- <p className="text-foreground-light">Supabase Projects</p>
- </div>
- <ProjectLinkList />
- <Separator />
- <div className="flex justify-end py-4">{displayButton()}</div>
- </div>
- </div>
- )
-})
-
-const ProjectLinkList = observer(() => {
- const _store = useContext(PageContext)
-
- function addProjectLink() {
- runInAction(() => {
- _store.projectLinks.push({
- vercelProjectId: undefined,
- supabaseProjectRef: undefined,
- })
- })
- }
- return (
- <>
- <ul>
- {_store.projectLinks.map((x, idx) => (
- <ProjectLinkItem
- key={`project-link-${idx}`}
- idx={idx}
- vercelProjectId={x.vercelProjectId}
- supabaseProjectRef={x.supabaseProjectRef}
- error={x.error}
- result={x.result}
- />
- ))}
- </ul>
- <div className="py-2">
- {_store.projectLinkRemaining == 0 ? (
- <p className="text-sm text-foreground-light">
- All Vercel projects for selected scope have been added
- </p>
- ) : (
- <div className="flex items-center space-x-2">
- <Button
- icon={<PlusCircle />}
- type="default"
- onClick={addProjectLink}
- disabled={_store.projectLinkRemaining == 0 || _store.waitingIntegration}
- >
- {`Add another Vercel Project`}
- </Button>
- <p className="text-sm text-foreground-light">
- {_store.projectLinkRemaining} project(s) remaining
- </p>
- </div>
- )}
- </div>
- </>
- )
-})
-
-interface ProjectLinkItemProps {
- idx: number
- vercelProjectId?: string
- supabaseProjectRef?: string
- error?: string
- result?: { status: 'waiting' | 'success' | 'fail'; message?: string }
-}
-const ProjectLinkItem = observer(
- ({ idx, vercelProjectId, supabaseProjectRef, error, result }: ProjectLinkItemProps) => {
- const _store = useContext(PageContext)
- const selectedVercelProject = _store.vercelProjects.find((x) => x.id == vercelProjectId)
-
- const { data: projects } = useProjectsQuery()
-
- function onVercelProjectChange(e: string) {
- const value = e != UNDEFINED_SELECT_VALUE ? e : undefined
- runInAction(() => {
- _store.projectLinks[idx].vercelProjectId = value
- _store.projectLinks[idx].error = undefined
- })
- }
-
- function onSupabaseProjectChange(e: string) {
- const value = e != UNDEFINED_SELECT_VALUE ? e : undefined
- runInAction(() => {
- _store.projectLinks[idx].supabaseProjectRef = value
- _store.projectLinks[idx].error = undefined
- })
- }
-
- function onRemove() {
- runInAction(() => {
- const filtered = _store.projectLinks.filter((_, index) => index != idx)
- _store.projectLinks = filtered
- })
- }
-
- return (
- <li className="py-2">
- <div className="relative flex w-full space-x-2">
- <div className="w-1/2 flex-grow">
- <Listbox
- value={vercelProjectId ?? UNDEFINED_SELECT_VALUE}
- onChange={onVercelProjectChange}
- >
- <Listbox.Option value={UNDEFINED_SELECT_VALUE} label="Choose a project" disabled>
- Choose a project
- </Listbox.Option>
- {selectedVercelProject && (
- <Listbox.Option
- value={selectedVercelProject.id}
- label={selectedVercelProject.name}
- addOnBefore={() => vercelIcon}
- >
- {selectedVercelProject.name}
- </Listbox.Option>
- )}
- {_store.vercelProjectsAvailable.map((x) => (
- <Listbox.Option
- key={x.id}
- value={x.id}
- label={x.name}
- addOnBefore={() => vercelIcon}
- >
- {x.name}
- </Listbox.Option>
- ))}
- </Listbox>
- </div>
- <div className="flex flex-shrink items-center">
- <ChevronRight className="text-foreground-light" />
- </div>
- <div className="w-1/2 flex-grow">
- <Listbox
- value={supabaseProjectRef ?? UNDEFINED_SELECT_VALUE}
- onChange={onSupabaseProjectChange}
- >
- <Listbox.Option value={UNDEFINED_SELECT_VALUE} label="Choose a project" disabled>
- Choose a project
- </Listbox.Option>
- {projects?.map((x: Dictionary<any>) => (
- <Listbox.Option
- key={x.id}
- value={x.ref}
- label={x.name}
- addOnBefore={() => databaseIcon}
- >
- {x.name}
- </Listbox.Option>
- ))}
- </Listbox>
- </div>
- {idx != 0 && (
- <div className="absolute top-[3px] right-[-50px]">
- <Button
- type="text"
- icon={<X size="18" strokeWidth={2} />}
- onClick={onRemove}
- disabled={_store.waitingIntegration}
- />
- </div>
- )}
- </div>
- {error && <p className="text-sm text-foreground-light">{error}</p>}
- {_store.waitingIntegration && result && (
- <p
- className={`text-sm ${
- result.status === 'waiting'
- ? 'text-foreground-light'
- : result.status === 'fail'
- ? 'text-foreground-light'
- : 'text-foreground'
- }`}
- >
- {result?.message ?? 'Processing...'}
- </p>
- )}
- </li>
- )
- }
-)
diff --git a/apps/studio/pages/vercel/setupOrg.tsx b/apps/studio/pages/vercel/setupOrg.tsx
deleted file mode 100644
index 1926a41714f..00000000000
--- a/apps/studio/pages/vercel/setupOrg.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-import { runInAction } from 'mobx'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import { useRouter } from 'next/router'
-import { ChangeEvent, createContext, useContext, useEffect, useState } from 'react'
-import { Button, Input, Select } from 'ui'
-
-import VercelIntegrationLayout from 'components/layouts/VercelIntegrationLayout'
-import { useOrganizationCreateMutation } from 'data/organizations/organization-create-mutation'
-import { useOrganizationsQuery } from 'data/organizations/organizations-query'
-
-const PageContext = createContext(null)
-function SetupOrg() {
- const PageState = useLocalObservable(() => ({
- token: '',
- teamId: '',
- externalId: '',
- configurationId: '',
- next: '',
- selectedOrg: undefined,
- vercelProjectId: undefined,
- selectMenuOpened: false,
- shouldShowOrgCreationUI: false,
- get queryParams() {
- return {
- token: this.token,
- teamId: this.teamId,
- 'external-id': this.externalId,
- configurationId: this.configurationId,
- // @ts-ignore
- supabaseOrgId: this.selectedOrg.id,
- vercelProjectId: this.vercelProjectId,
- next: this.next,
- }
- },
- get canContinue() {
- return !!this.selectedOrg
- },
- loadInitialData() {
- this.getQueryParams()
- },
- getQueryParams() {
- const params = new URLSearchParams(window.location.search)
- this.configurationId = params.get('configurationId') as string
- this.vercelProjectId = params.get('vercelProjectId') as any
- this.next = params.get('next') as string
- this.externalId = params.get('external-id') as string
- this.token = params.get('token') as string
- this.teamId = params.get('teamId') as string
- },
- toggleSelectMenu(value: any) {
- this.selectMenuOpened = value
- },
- }))
-
- const { data: organizations } = useOrganizationsQuery()
-
- useEffect(() => {
- PageState.loadInitialData()
-
- PageState.shouldShowOrgCreationUI = organizations?.length == 0
- }, [organizations])
-
- return (
- // @ts-ignore
- <PageContext.Provider value={PageState}>
- <VercelIntegrationLayout>
- {PageState.shouldShowOrgCreationUI ? <CreateOrganization /> : <OrgSelection />}
- </VercelIntegrationLayout>
- </PageContext.Provider>
- )
-}
-export default observer(SetupOrg)
-
-const CreateOrganization = observer(({}) => {
- const router = useRouter()
- const PageState: any = useContext(PageContext)
- const { data: organizations } = useOrganizationsQuery()
-
- const [orgName, setOrgName] = useState('')
-
- const { mutate: createOrganization, isLoading: isCreating } = useOrganizationCreateMutation({
- onSuccess: (org) => {
- PageState.selectedOrg = org
- const query = new URLSearchParams(PageState.queryParams).toString()
- router.push(`/vercel/setupProject?${query}`)
- },
- })
-
- return (
- <div>
- {(organizations?.length ?? 0) > 0 ? (
- <p className="mb-2">Create a new organization</p>
- ) : (
- <>
- <p className="mb-2">You do not have any organization</p>
- <p>You will need an organization to deploy this project</p>
- </>
- )}
-
- <div className="py-4">
- <Input
- autoFocus
- label="Name"
- type="text"
- placeholder="Organization name"
- descriptionText="What's the name of your company or team?"
- value={orgName}
- onChange={(e: any) => setOrgName(e.target.value)}
- />
- </div>
- <Button
- disabled={isCreating || orgName === ''}
- loading={isCreating}
- onClick={() => createOrganization({ name: orgName, tier: 'tier_free' })}
- >
- Create organization
- </Button>
- </div>
- )
-})
-
-const OrgSelection = observer(({}) => {
- const PageState: any = useContext(PageContext)
- const router = useRouter()
- const [loading, setLoading] = useState(false)
-
- const { data: organizations } = useOrganizationsQuery()
-
- useEffect(() => {
- if (!PageState.selectedOrg) {
- PageState.selectedOrg = (organizations?.length ?? 0) > 0 ? organizations?.[0] : undefined
- }
- }, [organizations])
-
- function onContinue() {
- setLoading(true)
-
- const query = new URLSearchParams(PageState.queryParams).toString()
- router.push(`/vercel/setupProject?${query}`)
- }
-
- function onNewOrg() {
- runInAction(() => {
- PageState.shouldShowOrgCreationUI = true
- })
- }
-
- function onOrgSelect(e: ChangeEvent<HTMLSelectElement>) {
- const selectedOrg = organizations?.find((x: any) => x.slug === e.target.value)
- PageState.selectedOrg = selectedOrg
- }
-
- return (
- <div>
- <div className="relative mt-1 mb-8">
- <Select
- label="Choose an organization"
- value={PageState.selectedOrg?.slug}
- onChange={onOrgSelect}
- >
- {organizations?.map((x) => {
- return (
- <Select.Option key={x.id} value={x.slug}>
- {x.name}
- </Select.Option>
- )
- })}
- </Select>
- </div>
- <div className="flex flex-col space-y-4">
- <Button
- disabled={loading || !PageState.canContinue}
- loading={loading}
- onClick={onContinue}
- block
- >
- Continue
- </Button>
- <Button type="secondary" onClick={onNewOrg} block>
- New Organization
- </Button>
- </div>
- </div>
- )
-})
diff --git a/apps/studio/pages/vercel/setupProject.tsx b/apps/studio/pages/vercel/setupProject.tsx
deleted file mode 100644
index 34e1bab9de7..00000000000
--- a/apps/studio/pages/vercel/setupProject.tsx
+++ /dev/null
@@ -1,310 +0,0 @@
-import { debounce } from 'lodash'
-import { makeAutoObservable } from 'mobx'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import { useRouter } from 'next/router'
-import { ChangeEvent, createContext, useContext, useEffect, useRef, useState } from 'react'
-import { toast } from 'sonner'
-
-import VercelIntegrationLayout from 'components/layouts/VercelIntegrationLayout'
-import {
- createVercelEnv,
- fetchVercelProject,
- prepareVercelEvns,
-} from 'components/to-be-cleaned/Integration/Vercel.utils'
-import { Loading } from 'components/ui/Loading'
-import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'
-import { useProjectCreateMutation } from 'data/projects/project-create-mutation'
-import {
- DEFAULT_MINIMUM_PASSWORD_STRENGTH,
- PRICING_TIER_PRODUCT_IDS,
- PROVIDERS,
-} from 'lib/constants'
-import passwordStrength from 'lib/password-strength'
-import { generateStrongPassword } from 'lib/project'
-import { VERCEL_INTEGRATION_CONFIGS } from 'lib/vercelConfigs'
-import { AWS_REGIONS } from 'shared-data'
-import type { Dictionary } from 'types'
-import { Button, Input, Listbox } from 'ui'
-
-interface ISetupProjectStore {
- token: string
- teamId: string
- externalId: string
- configurationId: string
- next: string
- supabaseOrgId: string
- vercelProjectId: string
- selectedVercelProject?: Dictionary<any>
- supabaseProjectRef?: string
- loading: boolean
-
- queryParams: Dictionary<string>
- selectedVercelProjectUrl: string
-
- loadInitialData: () => void
-}
-
-class SetupProjectStore implements ISetupProjectStore {
- token: string = ''
- teamId: string = ''
- externalId: string = ''
- configurationId: string = ''
- next: string = ''
- supabaseOrgId: string = ''
- vercelProjectId: string = ''
-
- selectedVercelProject?: Dictionary<any>
- supabaseProjectRef?: string
-
- loading: boolean = true
-
- constructor() {
- makeAutoObservable(this)
- }
-
- // @ts-ignore
- get queryParams() {
- return {
- next: this.next,
- supabaseProjectRef: this.supabaseProjectRef,
- }
- }
-
- get selectedVercelProjectUrl() {
- if (
- !this.selectedVercelProject ||
- !this.selectedVercelProject?.alias ||
- this.selectedVercelProject?.alias?.length == 0
- ) {
- return ''
- } else {
- return `https://${this.selectedVercelProject?.alias[0].domain}`
- }
- }
-
- loadInitialData() {
- this.getQueryParams()
- this.getVercelProject()
- }
-
- getQueryParams() {
- const params = new URLSearchParams(window.location.search)
- this.configurationId = params.get('configurationId') as string
- this.vercelProjectId = params.get('vercelProjectId') as string
- this.next = params.get('next') as string
- this.externalId = params.get('external-id') as string
- this.token = params.get('token') as string
- this.teamId = params.get('teamId') as string
- this.supabaseOrgId = params.get('supabaseOrgId') as string
- }
-
- async getVercelProject() {
- const { data, error } = await fetchVercelProject({
- id: this.vercelProjectId,
- vercelTeamId: this.teamId,
- vercelToken: this.token,
- })
- if (error) {
- toast.error(error)
- } else {
- this.selectedVercelProject = data
- }
- this.loading = false
- }
-}
-const PageContext = createContext<ISetupProjectStore>(undefined!)
-
-const SetupProject = () => {
- // @ts-ignore
- const _store: ISetupProjectStore = useLocalObservable(() => new SetupProjectStore())
-
- useEffect(() => {
- _store.loadInitialData()
- }, [])
-
- return (
- <PageContext.Provider value={_store}>
- <VercelIntegrationLayout>
- {_store.loading && <Connecting />}
- {!_store.loading && <CreateProject />}
- </VercelIntegrationLayout>
- </PageContext.Provider>
- )
-}
-export default observer(SetupProject)
-
-const Connecting = () => (
- <div className="flex h-full w-full flex-col items-center justify-center">
- <div className="flex w-32 items-center justify-center">
- <Loading />
- </div>
- <p>Connecting...</p>
- </div>
-)
-
-const CreateProject = observer(() => {
- const router = useRouter()
- const _store = useContext(PageContext)
-
- const [projectName, setProjectName] = useState('')
- const [dbPass, setDbPass] = useState('')
- const [passwordStrengthMessage, setPasswordStrengthMessage] = useState('')
- const [passwordStrengthScore, setPasswordStrengthScore] = useState(-1)
- const [dbRegion, setDbRegion] = useState(PROVIDERS.AWS.default_region.displayName)
-
- const delayedCheckPasswordStrength = useRef(
- debounce((value: string) => checkPasswordStrength(value), 300)
- ).current
-
- const { mutate: createProject, isLoading } = useProjectCreateMutation({
- onSuccess: async (res) => {
- const project = { ...res, db_host: `db.${res.ref}.supabase.co`, db_password: dbPass }
- _store.supabaseProjectRef = project.ref
-
- const requiredEnvs =
- VERCEL_INTEGRATION_CONFIGS.find((x) => x.id == _store.externalId)?.envs || []
- const envs = prepareVercelEvns(requiredEnvs, project as any)
-
- await Promise.allSettled(
- envs.map(async (env: any) => {
- try {
- const data = await createVercelEnv({
- ...env,
- vercelProjectId: _store.selectedVercelProject?.id,
- vercelTeamId: _store.teamId,
- vercelToken: _store.token,
- })
- return data
- } catch (err) {
- console.error(`Error: ${err}`)
- }
- })
- )
-
- const query = new URLSearchParams(_store.queryParams).toString()
- router.push(`/vercel/complete?${query}`)
- },
- })
-
- const canSubmit =
- projectName != '' &&
- passwordStrengthScore >= DEFAULT_MINIMUM_PASSWORD_STRENGTH &&
- dbRegion != undefined
-
- function onProjectNameChange(e: ChangeEvent<HTMLInputElement>) {
- e.target.value = e.target.value.replace(/\./g, '')
- setProjectName(e.target.value)
- }
-
- function onDbPassChange(e: ChangeEvent<HTMLInputElement>) {
- const value = e.target.value
- setDbPass(value)
- if (value == '') {
- setPasswordStrengthScore(-1)
- setPasswordStrengthMessage('')
- } else delayedCheckPasswordStrength(value)
- }
-
- async function checkPasswordStrength(value: string) {
- const { message, strength } = await passwordStrength(value)
- setPasswordStrengthScore(strength)
- setPasswordStrengthMessage(message)
- }
-
- function generatePassword() {
- const password = generateStrongPassword()
- setDbPass(password)
- delayedCheckPasswordStrength(password)
- }
-
- async function onCreateProject() {
- try {
- const dbSql =
- VERCEL_INTEGRATION_CONFIGS.find((x) => x.id == _store.externalId)?.template?.sql || ''
-
- createProject({
- cloudProvider: PROVIDERS.AWS.id,
- organizationId: Number(_store.supabaseOrgId),
- name: projectName,
- dbPass: dbPass,
- dbRegion,
- dbSql: dbSql || '',
- dbPricingTierId: PRICING_TIER_PRODUCT_IDS.FREE,
- authSiteUrl: _store.selectedVercelProjectUrl,
- })
- } catch (error) {
- console.error('Error', error)
- }
- }
-
- return (
- <div>
- <p className="mb-2">Supabase project details</p>
- <div className="py-2">
- <Input
- autoFocus
- id="projectName"
- label="Project name"
- type="text"
- placeholder=""
- descriptionText=""
- value={projectName}
- onChange={onProjectNameChange}
- />
- </div>
- <div className="py-2">
- <Input
- id="dbPass"
- label="Database Password"
- type="password"
- placeholder="Type in a strong password"
- value={dbPass}
- copy={dbPass.length > 0}
- onChange={onDbPassChange}
- descriptionText={
- <PasswordStrengthBar
- passwordStrengthScore={passwordStrengthScore}
- password={dbPass}
- passwordStrengthMessage={passwordStrengthMessage}
- generateStrongPassword={generatePassword}
- />
- }
- />
- </div>
- <div className="py-2 pb-4">
- <div className="mt-1">
- <Listbox
- label="Region"
- type="select"
- value={dbRegion}
- onChange={(region) => setDbRegion(region)}
- descriptionText="Select a region close to your users for the best performance."
- >
- {Object.keys(AWS_REGIONS).map((option: string, i) => {
- const label = Object.values(AWS_REGIONS)[i].displayName
- return (
- <Listbox.Option
- key={option}
- label={label}
- value={label}
- addOnBefore={({ active, selected }: any) => (
- <img
- alt="region icon"
- className="w-5 rounded-sm"
- src={`${router.basePath}/img/regions/${Object.keys(AWS_REGIONS)[i]}.svg`}
- />
- )}
- >
- <span className="text-foreground">{label}</span>
- </Listbox.Option>
- )
- })}
- </Listbox>
- </div>
- </div>
- <Button disabled={isLoading || !canSubmit} loading={isLoading} onClick={onCreateProject}>
- Create project
- </Button>
- </div>
- )
-})