The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Bring changes from https://github.com/supabase/supabase/pull/12763
Joshen Lim77b0cff3a26f
diff --git a/packages/ui/src/components/Toggle/Toggle.tsx b/packages/ui/src/components/Toggle/Toggle.tsxindex 07f4654a7ff..41d6dd4e7e3 100644--- a/packages/ui/src/components/Toggle/Toggle.tsx+++ b/packages/ui/src/components/Toggle/Toggle.tsx@@ -1,8 +1,8 @@-import React, { useEffect, useState } from 'react'+import clsx from 'clsx'+import { useEffect, useState } from 'react'import { FormLayout } from '../../lib/Layout/FormLayout'import { useFormContext } from '../Form/FormContext'-import defaultTheme from '../../lib/theme/defaultTheme'import styleHandler from '../../lib/theme/styleHandler'interface Props extends Omit<React.HTMLAttributes<HTMLButtonElement>, 'size'> {@@ -129,7 +129,7 @@ function Toggle({type="button"id={id}name={name}- className={toggleClasses.join(' ')}+ className={clsx(toggleClasses, disabled && 'opacity-50 cursor-default')}onClick={onClick}disabled={disabled}onBlur={handleBlurEvent}diff --git a/studio/components/interfaces/Functions/EdgeFunctionDetails.tsx b/studio/components/interfaces/Functions/EdgeFunctionDetails.tsxdeleted file mode 100644index 10c2fffa641..00000000000--- a/studio/components/interfaces/Functions/EdgeFunctionDetails.tsx+++ /dev/null@@ -1,332 +0,0 @@-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<Props> = () => {- 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<any>(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- : '[YOUR ANON KEY]'-- 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 (- <>- <span className="text-brand-1100">supabase</span> 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 (- <>- <span className="text-brand-1100">supabase</span> 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 (- <>- <span className="text-brand-1100">supabase</span> secrets list- </>- )- },- comment: 'View all secrets',- },- {- command: `supabase secrets set NAME1=VALUE1 NAME2=VALUE2`,- description: 'This will set secrets for your project',- jsx: () => {- return (- <>- <span className="text-brand-1100">supabase</span> 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 (- <>- <span className="text-brand-1100">supabase</span> 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 (- <>- <span className="text-brand-1100">curl</span> -L -X POST 'https://{functionsEndpoint}/- {selectedFunction?.slug}' -H 'Authorization: Bearer [YOUR ANON KEY]'{' '}- {`--data '{"name":"Functions"}'`}- </>- )- },- comment: 'Invoke your function',- },- ]-- return (- <>- <div className="space-y-8 pb-16">- <div className="space-y-6 rounded border bg-scale-100 px-10 py-8 drop-shadow-sm dark:bg-scale-300">- <div className="flex items-center">- <p className="text-sm text-scale-1000 w-[130px]">Function Name</p>- <p className="text-sm text-scale-1200">{selectedFunction?.name}</p>- </div>-- <div className="flex items-center">- <p className="text-sm text-scale-1000 w-[130px]">Endpoint URL</p>- <p className="text-sm text-scale-1200">{functionUrl}</p>- <button- type="button"- className="text-scale-900 hover:text-scale-1200 transition ml-2"- onClick={(event: any) => {- function onCopy(value: any) {- setIsCopied(true)- navigator.clipboard.writeText(value).then()- setTimeout(function () {- setIsCopied(false)- }, 3000)- }- event.stopPropagation()- onCopy(functionUrl)- }}- >- {isCopied ? (- <div className="text-brand-900">- <IconCheck size={14} strokeWidth={3} />- </div>- ) : (- <div className="relative">- <div className="block">- <IconClipboard size={14} strokeWidth={1.5} />- </div>- </div>- )}- </button>- </div>-- <div className="flex items-center">- <p className="text-sm text-scale-1000 w-[130px]">Created At</p>- <p className="text-sm text-scale-1200">- {selectedFunction?.created_at &&- dayjs(selectedFunction.created_at).format('dddd, MMMM D, YYYY h:mm A')}- </p>- </div>-- <div className="flex items-center">- <p className="text-sm text-scale-1000 w-[130px]">Last Updated At</p>- <p className="text-sm text-scale-1200">- {selectedFunction?.updated_at &&- dayjs(selectedFunction.updated_at).format('dddd, MMMM D, YYYY h:mm A')}- </p>- </div>-- <div className="flex items-center">- <span className="text-sm text-scale-1000 w-[130px]">Deployments</span>- <div className="text-sm text-scale-1200">{selectedFunction?.version}</div>- </div>-- <div className="flex items-start">- <span className="text-sm text-scale-1000 w-[130px]">Regions</span>- <div className="col-span-2 flex flex-col gap-1">- <div className="flex items-center gap-2 text-sm text-scale-1200">- <IconGlobe size={16} strokeWidth={1.5} />- <span>Earth</span>- </div>- <span className="text-sm text-scale-1000">All functions are deployed globally</span>- </div>- </div>- </div>-- <div- className="space-y-6 rounded border bg-scale-100 px-8 py-6 drop-shadow-sm dark:bg-scale-300 transition-all overflow-hidden"- style={{ maxHeight: showInstructions ? 800 : 80 }}- >- <div className="flex items-center justify-between">- <div className="flex items-center space-x-3">- <div className="flex h-8 w-8 items-center justify-center rounded border bg-scale-1200 p-2 text-scale-100 dark:bg-scale-100 dark:text-scale-1200">- <IconTerminal strokeWidth={2} />- </div>- <h4>Command line access</h4>- </div>- <div className="cursor-pointer" onClick={() => setShowInstructions(!showInstructions)}>- {showInstructions ? (- <IconMinimize2 size={14} strokeWidth={1.5} />- ) : (- <IconMaximize2 size={14} strokeWidth={1.5} />- )}- </div>- </div>-- <h5 className="text-base">Deployment management</h5>- <CommandRender commands={managementCommands} />- <h5 className="text-base">Invoke </h5>- <CommandRender commands={invokeCommands} />- <h5 className="text-base">Secrets management</h5>- <CommandRender commands={secretCommands} />- </div>-- <Panel title={<p>Delete Edge Function</p>}>- <Panel.Content>- <Alert- withIcon- variant="danger"- title="Once your function is deleted, it can no longer be restored"- >- <p className="mb-3">- Make sure you have made a backup if you want to restore your edge function- </p>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger>- <Button- type="danger"- disabled={!canDeleteEdgeFunction}- loading={selectedFunction?.id === undefined}- onClick={() => setShowDeleteModal(true)}- >- Delete edge function- </Button>- </Tooltip.Trigger>- {!canDeleteEdgeFunction && (- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-scale-100 py-1 px-2 leading-none shadow',- 'border border-scale-200',- ].join(' ')}- >- <span className="text-xs text-scale-1200">- You need additional permissions to delete an edge function- </span>- </div>- </Tooltip.Content>- )}- </Tooltip.Root>- </Alert>- </Panel.Content>- </Panel>- </div>-- <Modal- size="small"- alignFooter="right"- header={<h3>Confirm to delete {selectedFunction?.name}</h3>}- visible={showDeleteModal}- loading={isDeleting}- onCancel={() => setShowDeleteModal(false)}- onConfirm={onConfirmDelete}- >- <div className="py-6">- <Modal.Content>- <Alert withIcon variant="warning" title="This action cannot be undone">- Ensure that you have made a backup if you want to restore your edge function- </Alert>- </Modal.Content>- </div>- </Modal>- </>- )-}--export default EdgeFunctionDetailsdiff --git a/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsxnew file mode 100644index 00000000000..66e2676672a--- /dev/null+++ b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx@@ -0,0 +1,322 @@+import dayjs from 'dayjs'+import Link from 'next/link'+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,+ IconTerminal,+ IconMinimize2,+ IconMaximize2,+ Button,+ Modal,+ Form,+ Toggle,+ IconHelpCircle,+ Input,+ IconExternalLink,+} from 'ui'++import { useStore, useParams, checkPermissions } from 'hooks'+import Panel from 'components/ui/Panel'+import CommandRender from '../CommandRender'+import { generateCLICommands } from './EdgeFunctionDetails.utils'+import { useProjectApiQuery } from 'data/config/project-api-query'+import { useEdgeFunctionUpdateMutation } from 'data/edge-functions/edge-functions-update-mutation'+import { useEdgeFunctionDeleteMutation } from 'data/edge-functions/edge-functions-delete-mutation'+import {+ FormHeader,+ FormPanel,+ FormActions,+ FormSection,+ FormSectionLabel,+ FormSectionContent,+} from 'components/ui/Forms'+import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'+import clsx from 'clsx'++interface Props {}++const EdgeFunctionDetails: FC<Props> = () => {+ const router = useRouter()+ const { ui } = useStore()+ const { ref: projectRef, functionSlug } = useParams()+ const [showDeleteModal, setShowDeleteModal] = useState(false)+ const [showInstructions, setShowInstructions] = useState(false)++ const { data: settings } = useProjectApiQuery({ projectRef })+ const { data: selectedFunction } = useEdgeFunctionQuery({ projectRef, slug: functionSlug })+ const { mutateAsync: updateEdgeFunction } = useEdgeFunctionUpdateMutation()+ const { mutateAsync: deleteEdgeFunction, isLoading: isDeleting } = useEdgeFunctionDeleteMutation()++ const formId = 'edge-function-update-form'+ const canUpdateEdgeFunction = checkPermissions(PermissionAction.FUNCTIONS_WRITE, '*')++ // Get the API service+ const apiService = settings?.autoApiService+ const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key')+ ? apiService.defaultApiKey+ : '[YOUR ANON KEY]'++ 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 { managementCommands, secretCommands, invokeCommands } = generateCLICommands(+ selectedFunction,+ functionUrl,+ anonKey+ )++ const onUpdateFunction = async (values: any, { setSubmitting, resetForm }: any) => {+ if (!projectRef) return console.error('Project ref is required')+ if (selectedFunction === undefined) return console.error('No edge function selected')+ setSubmitting(true)++ try {+ await updateEdgeFunction({+ projectRef,+ slug: selectedFunction.slug,+ payload: values,+ })+ resetForm({ values, initialValues: values })+ ui.setNotification({ category: 'success', message: `Successfully updated edge function` })+ } catch (error: any) {+ ui.setNotification({+ category: 'error',+ message: `Failed to update edge function: ${error.message}`,+ })+ } finally {+ setSubmitting(false)+ }+ }++ 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}`,+ })+ }+ }++ return (+ <>+ <div className="space-y-4 pb-16">+ <Form id={formId} initialValues={{}} onSubmit={onUpdateFunction}>+ {({ isSubmitting, handleReset, values, initialValues, resetForm }: any) => {+ const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)++ useEffect(() => {+ if (selectedFunction !== undefined) {+ const formValues = {+ name: selectedFunction?.name,+ verifyJwt: selectedFunction?.verify_jwt,+ }+ resetForm({ values: formValues, initialValues: formValues })+ }+ }, [selectedFunction])+ return (+ <>+ <FormPanel+ disabled={!canUpdateEdgeFunction}+ footer={+ <div className="flex py-4 px-8">+ <FormActions+ form={formId}+ isSubmitting={isSubmitting}+ hasChanges={hasChanges}+ handleReset={handleReset}+ helper={+ !canUpdateEdgeFunction+ ? 'You need additional permissions to update this function'+ : undefined+ }+ />+ </div>+ }+ >+ <FormSection header={<FormSectionLabel>Function Details</FormSectionLabel>}>+ <FormSectionContent loading={selectedFunction === undefined}>+ <Input id="name" name="name" label="Name" />+ <Input+ disabled+ id="slug"+ name="slug"+ label="Slug"+ value={selectedFunction?.slug}+ />+ <Input disabled copy label="Endpoint URL" value={functionUrl} />+ <Input disabled label="Region" value="All functions are deployed globally" />+ <Input+ disabled+ label="Created at"+ value={dayjs(selectedFunction?.created_at ?? 0).format(+ 'dddd, MMMM D, YYYY h:mm A'+ )}+ />+ <Input+ disabled+ label="Last updated at"+ value={dayjs(selectedFunction?.updated_at ?? 0).format(+ 'dddd, MMMM D, YYYY h:mm A'+ )}+ />+ <Input disabled label="Deployments" value={selectedFunction?.version ?? 0} />+ </FormSectionContent>+ </FormSection>+ <FormSection header={<FormSectionLabel>Function Configuration</FormSectionLabel>}>+ <FormSectionContent loading={selectedFunction === undefined}>+ <Toggle+ id="verifyJwt"+ name="verifyJwt"+ label="Enforce JWT Verification"+ descriptionText="Require a valid JWT in the authorization header when invoking the function"+ />+ <div className="space-y-1 border rounded border-scale-500 bg-scale-400 px-4 py-4">+ <div className="flex items-center space-x-2">+ <p className="text-sm">+ Import maps are{' '}+ <span+ className={clsx(+ selectedFunction?.import_map ? 'text-brand-900' : 'text-amber-900'+ )}+ >+ {selectedFunction?.import_map ? 'allowed' : 'disallowed'}+ </span>{' '}+ for this function+ </p>+ </div>+ <p className="text-sm text-scale-1000">+ Import maps allow the use of bare specifiers without having to install the+ Node.js package locally+ </p>+ <div className="!mt-4">+ <Link href="https://supabase.com/docs/guides/functions/import-maps">+ <a target="_blank">+ <Button type="default" icon={<IconExternalLink strokeWidth={1.5} />}>+ More about import maps+ </Button>+ </a>+ </Link>+ </div>+ </div>+ </FormSectionContent>+ </FormSection>+ </FormPanel>+ </>+ )+ }}+ </Form>++ <div+ className="space-y-6 rounded border bg-scale-100 px-6 py-4 drop-shadow-sm dark:bg-scale-300 transition-all overflow-hidden"+ style={{ maxHeight: showInstructions ? 800 : 66 }}+ >+ <div className="flex items-center justify-between">+ <div className="flex items-center space-x-3">+ <div className="flex h-8 w-8 items-center justify-center rounded border bg-scale-1200 p-2 text-scale-100 dark:bg-scale-100 dark:text-scale-1200">+ <IconTerminal strokeWidth={2} />+ </div>+ <h4>Command line access</h4>+ </div>+ <div className="cursor-pointer" onClick={() => setShowInstructions(!showInstructions)}>+ {showInstructions ? (+ <IconMinimize2 size={14} strokeWidth={1.5} />+ ) : (+ <IconMaximize2 size={14} strokeWidth={1.5} />+ )}+ </div>+ </div>++ <h5 className="text-base">Deployment management</h5>+ <CommandRender commands={managementCommands} />+ <h5 className="text-base">Invoke </h5>+ <CommandRender commands={invokeCommands} />+ <h5 className="text-base">Secrets management</h5>+ <CommandRender commands={secretCommands} />+ </div>++ <div className="!mt-8">+ <FormHeader title="Delete Edge Function" description="" />+ <Panel>+ <Panel.Content>+ <Alert+ withIcon+ variant="danger"+ title="Once your function is deleted, it can no longer be restored"+ >+ <p className="mb-3">+ Make sure you have made a backup if you want to restore your edge function+ </p>+ <Tooltip.Root delayDuration={0}>+ <Tooltip.Trigger>+ <Button+ type="danger"+ disabled={!canUpdateEdgeFunction}+ loading={selectedFunction?.id === undefined}+ onClick={() => setShowDeleteModal(true)}+ >+ Delete edge function+ </Button>+ </Tooltip.Trigger>+ {!canUpdateEdgeFunction && (+ <Tooltip.Content side="bottom">+ <Tooltip.Arrow className="radix-tooltip-arrow" />+ <div+ className={[+ 'rounded bg-scale-100 py-1 px-2 leading-none shadow',+ 'border border-scale-200',+ ].join(' ')}+ >+ <span className="text-xs text-scale-1200">+ You need additional permissions to delete an edge function+ </span>+ </div>+ </Tooltip.Content>+ )}+ </Tooltip.Root>+ </Alert>+ </Panel.Content>+ </Panel>+ </div>+ </div>++ <Modal+ size="small"+ alignFooter="right"+ header={<h3>Confirm to delete {selectedFunction?.name}</h3>}+ visible={showDeleteModal}+ loading={isDeleting}+ onCancel={() => setShowDeleteModal(false)}+ onConfirm={onConfirmDelete}+ >+ <div className="py-6">+ <Modal.Content>+ <Alert withIcon variant="warning" title="This action cannot be undone">+ Ensure that you have made a backup if you want to restore your edge function+ </Alert>+ </Modal.Content>+ </div>+ </Modal>+ </>+ )+}++export default EdgeFunctionDetailsdiff --git a/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.utils.tsx b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.utils.tsxnew file mode 100644index 00000000000..bc2ae902432--- /dev/null+++ b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.utils.tsx@@ -0,0 +1,93 @@+export const generateCLICommands = (+ selectedFunction: any,+ functionUrl: string,+ anonKey: string+) => {+ const managementCommands: any = [+ {+ command: `supabase functions deploy ${selectedFunction?.slug}`,+ description: 'This will overwrite the deployed function with your new function',+ jsx: () => {+ return (+ <>+ <span className="text-brand-1100">supabase</span> 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 (+ <>+ <span className="text-brand-1100">supabase</span> 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 (+ <>+ <span className="text-brand-1100">supabase</span> secrets list+ </>+ )+ },+ comment: 'View all secrets',+ },+ {+ command: `supabase secrets set NAME1=VALUE1 NAME2=VALUE2`,+ description: 'This will set secrets for your project',+ jsx: () => {+ return (+ <>+ <span className="text-brand-1100">supabase</span> 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 (+ <>+ <span className="text-brand-1100">supabase</span> 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 (+ <>+ <span className="text-brand-1100">curl</span> -L -X POST '{functionUrl}' -H+ 'Authorization: Bearer [YOUR ANON KEY]' {`--data '{"name":"Functions"}'`}+ </>+ )+ },+ comment: 'Invoke your function',+ },+ ]++ return { managementCommands, secretCommands, invokeCommands }+}diff --git a/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx b/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsxindex 0d9ce1f727b..bb1b1f86edd 100644--- a/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx+++ b/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx@@ -28,7 +28,7 @@ const EdgeFunctionsListItem: FC<Props> = ({ function: item }) => {<Table.trkey={item.id}onClick={() => {- router.push(`/project/${ref}/functions/${item.id}/details`)+ router.push(`/project/${ref}/functions/${item.slug}/details`)}}><Table.td className="">diff --git a/studio/components/interfaces/Functions/FunctionsNav.tsx b/studio/components/interfaces/Functions/FunctionsNav.tsxindex af24e28d29f..d25017cef89 100644--- a/studio/components/interfaces/Functions/FunctionsNav.tsx+++ b/studio/components/interfaces/Functions/FunctionsNav.tsx@@ -13,7 +13,7 @@ const FunctionsNav = ({ item }: any) => {size="medium"activeId={!activeRoute ? 'metrics' : activeRoute}onChange={(e: string) =>- router.push(`/project/${ref}/functions/${item.id}/${e === 'metrics' ? '' : e}`)+ router.push(`/project/${ref}/functions/${item.slug}/${e === 'metrics' ? '' : e}`)}><Tabs.Panel id="details" label="Details" />diff --git a/studio/components/interfaces/Functions/index.ts b/studio/components/interfaces/Functions/index.tsindex 003d5feaca6..992b396e1be 100644--- a/studio/components/interfaces/Functions/index.ts+++ b/studio/components/interfaces/Functions/index.ts@@ -1,4 +1,4 @@-import EdgeFunctionDetails from './EdgeFunctionDetails'+import EdgeFunctionDetails from './EdgeFunctionDetails/EdgeFunctionDetails'import EdgeFunctionsListItem from './EdgeFunctionsListItem'import FunctionsEmptyState from './FunctionsEmptyState'import TerminalInstructions from './TerminalInstructions'diff --git a/studio/components/interfaces/Settings/Logs/PreviewFilterPanel.tsx b/studio/components/interfaces/Settings/Logs/PreviewFilterPanel.tsxindex a8025d482ce..b4ab97e9727 100644--- a/studio/components/interfaces/Settings/Logs/PreviewFilterPanel.tsx+++ b/studio/components/interfaces/Settings/Logs/PreviewFilterPanel.tsx@@ -183,7 +183,7 @@ const PreviewFilterPanel: FC<Props> = ({<CSVButton data={csvData} disabled={!Boolean(csvData)} title="Download data" /></div>- <Button type="secondary" onClick={onExploreClick} iconRight={<IconExternalLink size={10} />}>+ <Button type="default" onClick={onExploreClick} iconRight={<IconExternalLink size={10} />}>Explore via query</Button></div>diff --git a/studio/components/layouts/FunctionsLayout.tsx b/studio/components/layouts/FunctionsLayout.tsxindex 0dc242cd836..d7f4cc6a7de 100644--- a/studio/components/layouts/FunctionsLayout.tsx+++ b/studio/components/layouts/FunctionsLayout.tsx@@ -1,15 +1,16 @@import Link from 'next/link'-import { useRouter } from 'next/router'-import { FC, useEffect, ReactNode, useState } from 'react'+import { FC, ReactNode, useState } from 'react'import { observer } from 'mobx-react-lite'import { Button, IconExternalLink, IconCode, Modal, IconTerminal } from 'ui'-import { checkPermissions, useParams, useStore, withAuth } from 'hooks'+import { checkPermissions, useParams, withAuth } from 'hooks'import FunctionsNav from '../interfaces/Functions/FunctionsNav'import BaseLayout from 'components/layouts'import NoPermission from 'components/ui/NoPermission'import { PermissionAction } from '@supabase/shared-types/out/constants'import { TerminalInstructions } from 'components/interfaces/Functions'+import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'+import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'interface Props {title?: string@@ -17,14 +18,10 @@ interface Props {}const FunctionsLayout: FC<Props> = ({ title, children }) => {- const router = useRouter()- const { id, ref } = useParams()- const { functions, ui } = useStore()+ const { functionSlug, ref } = useParams()const [showTerminalInstructions, setShowTerminalInstructions] = useState(false)-- useEffect(() => {- if (ui.selectedProjectRef) functions.load()- }, [ui.selectedProjectRef])+ const { data: functions, isLoading } = useEdgeFunctionsQuery({ projectRef: ref })+ const { data: selectedFunction } = useEdgeFunctionQuery({ projectRef: ref, slug: functionSlug })const canReadFunctions = checkPermissions(PermissionAction.FUNCTIONS_READ, '*')if (!canReadFunctions) {@@ -37,18 +34,12 @@ const FunctionsLayout: FC<Props> = ({ title, children }) => {)}- const item = id ? functions.byId(id) : null- const name = item?.name || ''-- const hasFunctions = functions.list().length > 0+ const name = selectedFunction?.name || ''+ const hasFunctions = (functions ?? []).length > 0const centered = !hasFunctionsreturn (- <BaseLayout- isLoading={!functions.isLoaded}- title={title || 'Edge Functions'}- product="Edge Functions"- >+ <BaseLayout isLoading={isLoading} title={title || 'Edge Functions'} product="Edge Functions">{centered ? (<><div className="mx-auto max-w-5xl py-24 px-5">@@ -149,7 +140,7 @@ const FunctionsLayout: FC<Props> = ({ title, children }) => {</div></div></div>- {item && <FunctionsNav item={item} />}+ {selectedFunction !== undefined && <FunctionsNav item={selectedFunction} />}</div><divclassName={[diff --git a/studio/data/edge-functions/edge-function-query.ts b/studio/data/edge-functions/edge-function-query.tsnew file mode 100644index 00000000000..b43321d8562--- /dev/null+++ b/studio/data/edge-functions/edge-function-query.ts@@ -0,0 +1,64 @@+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 EdgeFunctionVariables = {+ projectRef?: string+ slug?: string+}++export type EdgeFunctionResponse = {+ id: string+ slug: string+ name: string+ status: string+ created_at: number+ updated_at: number+ verify_jwt: boolean+ import_map: boolean+ version: number+}++export async function getEdgeFunction(+ { projectRef, slug }: EdgeFunctionVariables,+ signal?: AbortSignal+) {+ if (!projectRef) throw new Error('projectRef is required')+ if (!slug) throw new Error('slug is required')++ const response = await get(`${API_ADMIN_URL}/projects/${projectRef}/functions/${slug}`, {+ signal,+ })+ if (response.error) throw response.error+ return response as EdgeFunctionResponse+}++export type EdgeFunctionData = Awaited<ReturnType<typeof getEdgeFunction>>+export type EdgeFunctionError = unknown++export const useEdgeFunctionQuery = <TData = EdgeFunctionData>(+ { projectRef, slug }: EdgeFunctionVariables,+ { enabled = true, ...options }: UseQueryOptions<EdgeFunctionData, EdgeFunctionError, TData> = {}+) =>+ useQuery<EdgeFunctionData, EdgeFunctionError, TData>(+ edgeFunctionsKeys.detail(projectRef, slug),+ ({ signal }) => getEdgeFunction({ projectRef, slug }, signal),+ {+ enabled: enabled && typeof projectRef !== 'undefined' && typeof slug !== 'undefined',+ ...options,+ }+ )++export const useResourcePrefetch = ({ projectRef, slug }: EdgeFunctionVariables) => {+ const client = useQueryClient()++ return useCallback(() => {+ if (projectRef && slug) {+ client.prefetchQuery(edgeFunctionsKeys.detail(projectRef, slug), ({ signal }) =>+ getEdgeFunction({ projectRef, slug }, signal)+ )+ }+ }, [projectRef, slug])+}diff --git a/studio/data/edge-functions/edge-functions-update-mutation.ts b/studio/data/edge-functions/edge-functions-update-mutation.tsnew file mode 100644index 00000000000..c7effaebacd--- /dev/null+++ b/studio/data/edge-functions/edge-functions-update-mutation.ts@@ -0,0 +1,51 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { patch } from 'lib/common/fetch'+import { API_ADMIN_URL } from 'lib/constants'+import { edgeFunctionsKeys } from './keys'++export type EdgeFunctionsUpdateVariables = {+ projectRef: string+ slug: string+ payload: {+ name?: string+ verifyJwt?: boolean+ importMap?: boolean+ }+}++export async function updateEdgeFunction({+ projectRef,+ slug,+ payload,+}: EdgeFunctionsUpdateVariables) {+ if (!projectRef) throw new Error('projectRef is required')++ const response = await patch(`${API_ADMIN_URL}/projects/${projectRef}/functions/${slug}`, payload)+ if (response.error) throw response.error++ return response+}++type EdgeFunctionsUpdateData = Awaited<ReturnType<typeof updateEdgeFunction>>++export const useEdgeFunctionUpdateMutation = ({+ onSuccess,+ ...options+}: Omit<+ UseMutationOptions<EdgeFunctionsUpdateData, unknown, EdgeFunctionsUpdateVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<EdgeFunctionsUpdateData, unknown, EdgeFunctionsUpdateVariables>(+ (vars) => updateEdgeFunction(vars),+ {+ async onSuccess(data, variables, context) {+ const { projectRef, slug } = variables+ await queryClient.invalidateQueries(edgeFunctionsKeys.detail(projectRef, slug))+ await onSuccess?.(data, variables, context)+ },+ ...options,+ }+ )+}diff --git a/studio/data/edge-functions/keys.ts b/studio/data/edge-functions/keys.tsindex dacd8d4a8dd..524062974c2 100644--- a/studio/data/edge-functions/keys.ts+++ b/studio/data/edge-functions/keys.ts@@ -1,3 +1,5 @@export const edgeFunctionsKeys = {list: (projectRef: string | undefined) => ['projects', projectRef, 'edge-functions'] as const,+ detail: (projectRef: string | undefined, slug: string | undefined) =>+ ['projects', projectRef, 'edge-function', slug] as const,}diff --git a/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx b/studio/pages/project/[ref]/functions/[functionSlug]/details.tsxnew file mode 100644index 00000000000..5ffb3c78c33--- /dev/null+++ b/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx@@ -0,0 +1,9 @@+import { observer } from 'mobx-react-lite'+import { NextPageWithLayout } from 'types'+import FunctionsLayout from 'components/layouts/FunctionsLayout'+import { EdgeFunctionDetails } from 'components/interfaces/Functions'++const PageLayout: NextPageWithLayout = () => <EdgeFunctionDetails />+PageLayout.getLayout = (page) => <FunctionsLayout>{page}</FunctionsLayout>++export default observer(PageLayout)diff --git a/studio/pages/project/[ref]/functions/[id]/index.tsx b/studio/pages/project/[ref]/functions/[functionSlug]/index.tsxsimilarity index 96%rename from studio/pages/project/[ref]/functions/[id]/index.tsxrename to studio/pages/project/[ref]/functions/[functionSlug]/index.tsxindex ed3b891d2a2..156a1da2897 100644--- a/studio/pages/project/[ref]/functions/[id]/index.tsx+++ b/studio/pages/project/[ref]/functions/[functionSlug]/index.tsx@@ -6,13 +6,14 @@ import { observer } from 'mobx-react-lite'import { PermissionAction } from '@supabase/shared-types/out/constants'import { checkPermissions, useParams } from 'hooks'-import { useFunctionsInvStatsQuery } from 'data/analytics/functions-inv-stats-query'import { ChartIntervals, NextPageWithLayout } from 'types'import { DATE_FORMAT } from 'lib/constants'import Panel from 'components/ui/Panel'import NoPermission from 'components/ui/NoPermission'import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'import FunctionsLayout from 'components/layouts/FunctionsLayout'+import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'+import { useFunctionsInvStatsQuery } from 'data/analytics/functions-inv-stats-query'const CHART_INTERVALS: ChartIntervals[] = [{@@ -49,12 +50,14 @@ function calculateHighlightedValue(array: any, attribute: string, options?: { suconst PageLayout: NextPageWithLayout = () => {const router = useRouter()- const { ref: projectRef, id } = useParams()+ const { ref: projectRef, functionSlug } = useParams()const [interval, setInterval] = useState<string>('15min')-const selectedInterval = CHART_INTERVALS.find((i) => i.key === interval) || CHART_INTERVALS[1]+ const { data: selectedFunction } = useEdgeFunctionQuery({ projectRef, slug: functionSlug })+ const id = selectedFunction?.id+const { data, error } = useFunctionsInvStatsQuery({projectRef,functionId: id,@@ -86,7 +89,7 @@ const PageLayout: NextPageWithLayout = () => {}}- const canReadFunction = checkPermissions(PermissionAction.FUNCTIONS_READ, id as string)+ const canReadFunction = checkPermissions(PermissionAction.FUNCTIONS_READ, functionSlug as string)if (!canReadFunction) {return <NoPermission isFullPage resourceText="access this edge function" />}diff --git a/studio/pages/project/[ref]/functions/[id]/invocations.tsx b/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsxsimilarity index 51%rename from studio/pages/project/[ref]/functions/[id]/invocations.tsxrename to studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsxindex 8e45b17b1de..3fc638aa7c2 100644--- a/studio/pages/project/[ref]/functions/[id]/invocations.tsx+++ b/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsx@@ -1,31 +1,28 @@-import React from 'react'-import { useRouter } from 'next/router'import { observer } from 'mobx-react-lite'-import { PermissionAction } from '@supabase/shared-types/out/constants'import { NextPageWithLayout } from 'types'-import { checkPermissions } from 'hooks'-import NoPermission from 'components/ui/NoPermission'+import { useParams } from 'hooks'import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'import FunctionsLayout from 'components/layouts/FunctionsLayout'+import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'/*** Placeholder page for logs previewers until we figure out where to slot them*/export const LogPage: NextPageWithLayout = () => {- const router = useRouter()- const { ref, id } = router.query+ const { ref, functionSlug } = useParams()+ const { data: selectedFunction, isLoading } = useEdgeFunctionQuery({+ projectRef: ref,+ slug: functionSlug,+ })- const canReadFunction = checkPermissions(PermissionAction.FUNCTIONS_READ, id as string)- if (!canReadFunction) {- return <NoPermission isFullPage resourceText="access this edge function's invocations" />- }+ if (selectedFunction === undefined || isLoading) return nullreturn (<LogsPreviewerprojectRef={ref as string}queryType={'fn_edge'}- filterOverride={{ function_id: id }}+ filterOverride={{ function_id: selectedFunction.id }}/>)}diff --git a/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx b/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsxnew file mode 100644index 00000000000..fd9510aee15--- /dev/null+++ b/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx@@ -0,0 +1,29 @@+import { observer } from 'mobx-react-lite'+import { NextPageWithLayout } from 'types'+import { useParams } from 'hooks'+import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'+import FunctionsLayout from 'components/layouts/FunctionsLayout'+import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'++export const LogPage: NextPageWithLayout = () => {+ const { ref, functionSlug } = useParams()++ const { data: selectedFunction, isLoading } = useEdgeFunctionQuery({+ projectRef: ref,+ slug: functionSlug,+ })++ if (selectedFunction === undefined || isLoading) return null++ return (+ <LogsPreviewer+ projectRef={ref as string}+ queryType={'functions'}+ filterOverride={{ 'metadata.function_id': selectedFunction.id }}+ />+ )+}++LogPage.getLayout = (page) => <FunctionsLayout>{page}</FunctionsLayout>++export default observer(LogPage)diff --git a/studio/pages/project/[ref]/functions/[id]/details.tsx b/studio/pages/project/[ref]/functions/[id]/details.tsxdeleted file mode 100644index debcd5ebe99..00000000000--- a/studio/pages/project/[ref]/functions/[id]/details.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { observer } from 'mobx-react-lite'-import { PermissionAction } from '@supabase/shared-types/out/constants'--import { NextPageWithLayout } from 'types'-import { checkPermissions, useParams } from 'hooks'-import FunctionsLayout from 'components/layouts/FunctionsLayout'-import NoPermission from 'components/ui/NoPermission'-import { EdgeFunctionDetails } from 'components/interfaces/Functions'--const PageLayout: NextPageWithLayout = () => {- const { id } = useParams()-- const canReadFunction = checkPermissions(PermissionAction.FUNCTIONS_READ, id as string)- if (!canReadFunction) {- return <NoPermission isFullPage resourceText="access this edge function's details" />- }-- return <EdgeFunctionDetails />-}--PageLayout.getLayout = (page) => <FunctionsLayout>{page}</FunctionsLayout>--export default observer(PageLayout)diff --git a/studio/pages/project/[ref]/functions/[id]/logs.tsx b/studio/pages/project/[ref]/functions/[id]/logs.tsxdeleted file mode 100644index 2913da2c2d2..00000000000--- a/studio/pages/project/[ref]/functions/[id]/logs.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { useRouter } from 'next/router'-import { observer } from 'mobx-react-lite'-import { PermissionAction } from '@supabase/shared-types/out/constants'--import { NextPageWithLayout } from 'types'-import { checkPermissions } from 'hooks'-import NoPermission from 'components/ui/NoPermission'-import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'-import FunctionsLayout from 'components/layouts/FunctionsLayout'--export const LogPage: NextPageWithLayout = () => {- const router = useRouter()- const { ref, id } = router.query-- const canReadFunction = checkPermissions(PermissionAction.FUNCTIONS_READ, id as string)- if (!canReadFunction) {- return <NoPermission isFullPage resourceText="access this edge function's logs" />- }-- return (- <LogsPreviewer- projectRef={ref as string}- queryType={'functions'}- filterOverride={{ 'metadata.function_id': id }}- />- )-}--LogPage.getLayout = (page) => <FunctionsLayout>{page}</FunctionsLayout>--export default observer(LogPage)