The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix: correctly set entrypoint, import map path and static patterns for new functions (#40368)
Lakshan Perera426c371d597c
diff --git a/apps/studio/components/interfaces/EdgeFunctions/EdgeFunction.types.ts b/apps/studio/components/interfaces/EdgeFunctions/EdgeFunction.types.tsnew file mode 100644index 00000000000..67207cc4cce--- /dev/null+++ b/apps/studio/components/interfaces/EdgeFunctions/EdgeFunction.types.ts@@ -0,0 +1,6 @@+export type EdgeFunctionFile = {+ id: number+ name: string+ content: string+ selected?: boolean+}diff --git a/apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts b/apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.tsnew file mode 100644index 00000000000..ef19c06ae29--- /dev/null+++ b/apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts@@ -0,0 +1,32 @@+import { EdgeFunctionFile } from './EdgeFunction.types'++export const getFallbackImportMapPath = (files: Omit<EdgeFunctionFile, 'id' | 'content'>[]) => {+ // try to find a deno.json or import_map.json file+ const regex = /^.*?(deno|import_map).json*$/i+ return files.find(({ name }) => regex.test(name))?.name+}++export const getFallbackEntrypointPath = (files: Omit<EdgeFunctionFile, 'id' | 'content'>[]) => {+ // when there's no matching entrypoint path is set,+ // we use few heuristics to find an entrypoint file+ // 1. If the function has only a single TS / JS file, if so set it as entrypoint+ const jsFiles = files.filter(({ name }) => name.endsWith('.js') || name.endsWith('.ts'))+ if (jsFiles.length === 1) {+ return jsFiles[0].name+ } else if (jsFiles.length) {+ // 2. If function has a `index` or `main` file use it as the entrypoint+ const regex = /^.*?(index|main).*$/i+ const matchingFile = jsFiles.find(({ name }) => regex.test(name))+ // 3. if no valid index / main file found, we set the entrypoint expliclty to first JS file+ return matchingFile ? matchingFile.name : jsFiles[0].name+ } else {+ // no potential entrypoint files found, this will most likely result in an error on deploy+ return 'index.ts'+ }+}++export const getStaticPatterns = (files: Omit<EdgeFunctionFile, 'id' | 'content'>[]) => {+ return files+ .filter(({ name }) => !name.match(/\.(js|ts|jsx|tsx|json|wasm)$/i))+ .map(({ name }) => name)+}diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsxindex 358c8fc2ad6..bb5f3e76fa7 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx@@ -7,7 +7,8 @@ import { useParams } from 'common/hooks'import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'import type { EdgeFunctionsResponse } from 'data/edge-functions/edge-functions-query'-import { copyToClipboard, TableCell, TableRow, Tooltip, TooltipContent, TooltipTrigger } from 'ui'+import { copyToClipboard, TableCell, TableRow } from 'ui'+import { TimestampInfo } from 'ui-patterns'interface EdgeFunctionsListItemProps {function: EdgeFunctionsResponse@@ -77,16 +78,11 @@ export const EdgeFunctionsListItem = ({ function: item }: EdgeFunctionsListItemP</p></TableCell><TableCell className="lg:table-cell">- <Tooltip>- <TooltipTrigger asChild>- <div className="flex items-center space-x-2">- <p className="text-sm text-foreground-light">{dayjs(item.updated_at).fromNow()}</p>- </div>- </TooltipTrigger>- <TooltipContent side="bottom">- Last updated on {dayjs(item.updated_at).format('DD MMM, YYYY HH:mm')}- </TooltipContent>- </Tooltip>+ <TimestampInfo+ className="text-sm text-foreground-light"+ utcTimestamp={item.updated_at}+ label={dayjs(item.updated_at).fromNow()}+ /></TableCell><TableCell className="lg:table-cell"><p className="text-foreground-light">{item.version}</p>diff --git a/apps/studio/data/edge-functions/edge-function-body-query.ts b/apps/studio/data/edge-functions/edge-function-body-query.tsindex 295366c3dad..c18cd937315 100644--- a/apps/studio/data/edge-functions/edge-function-body-query.ts+++ b/apps/studio/data/edge-functions/edge-function-body-query.ts@@ -1,44 +1,16 @@import { getMultipartBoundary, parseMultipartStream } from '@mjackson/multipart-parser'import { useQuery } from '@tanstack/react-query'+import { EdgeFunctionFile } from 'components/interfaces/EdgeFunctions/EdgeFunction.types'import { get, handleError } from 'data/fetchers'import { IS_PLATFORM } from 'lib/constants'import type { ResponseError, UseCustomQueryOptions } from 'types'import { edgeFunctionsKeys } from './keys'-export type EdgeFunctionBodyVariables = {+type EdgeFunctionBodyVariables = {projectRef?: stringslug?: string}-export type EdgeFunctionFile = {- name: string- content: string-}--export type EdgeFunctionBodyResponse = {- files: EdgeFunctionFile[]-}--async function streamToString(stream: ReadableStream<Uint8Array>) {- const reader = stream.getReader()- const decoder = new TextDecoder()- let result = ''-- try {- while (true) {- const { done, value } = await reader.read()- if (done) break- result += decoder.decode(value, { stream: true })- }- // Final decode to handle any remaining bytes- result += decoder.decode()- return result- } catch (error) {- console.error('Error reading stream:', error)- throw error- }-}-export async function getEdgeFunctionBody({ projectRef, slug }: EdgeFunctionBodyVariables,signal?: AbortSignal@@ -70,7 +42,7 @@ export async function getEdgeFunctionBody(}}- return { files: files as EdgeFunctionFile[] }+ return { files: files as Omit<EdgeFunctionFile, 'id' | 'selected'>[] }}export type EdgeFunctionBodyData = Awaited<ReturnType<typeof getEdgeFunctionBody>>diff --git a/apps/studio/data/edge-functions/edge-functions-deploy-mutation.ts b/apps/studio/data/edge-functions/edge-functions-deploy-mutation.tsindex 8dcff2fbc02..fb473dee9ca 100644--- a/apps/studio/data/edge-functions/edge-functions-deploy-mutation.ts+++ b/apps/studio/data/edge-functions/edge-functions-deploy-mutation.ts@@ -2,30 +2,43 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'import { components } from 'api-types'+import {+ getFallbackEntrypointPath,+ getFallbackImportMapPath,+ getStaticPatterns,+} from 'components/interfaces/EdgeFunctions/EdgeFunctions.utils'import { handleError, post } from 'data/fetchers'import type { ResponseError, UseCustomMutationOptions } from 'types'import { edgeFunctionsKeys } from './keys'-export type EdgeFunctionsDeployVariables = {+type EdgeFunctionsDeployBodyMetadata = components['schemas']['FunctionDeployBody']['metadata']+type EdgeFunctionsDeployVariables = {projectRef: stringslug: string- metadata: components['schemas']['FunctionDeployBody']['metadata']+ metadata: Partial<EdgeFunctionsDeployBodyMetadata>files: { name: string; content: string }[]}export async function deployEdgeFunction({projectRef,slug,- metadata,+ metadata: _metadata,files,}: EdgeFunctionsDeployVariables) {if (!projectRef) throw new Error('projectRef is required')+ // [Joshen] Consolidating this logic in the RQ since these values need to be set if they're not+ // provided from the callee, and their fallback values depends on the files provided+ const metadata = { ..._metadata }+ if (!_metadata.entrypoint_path) metadata.entrypoint_path = getFallbackEntrypointPath(files)+ if (!_metadata.import_map_path) metadata.import_map_path = getFallbackImportMapPath(files)+ if (!_metadata.static_patterns) metadata.static_patterns = getStaticPatterns(files)+const { data, error } = await post(`/v1/projects/{ref}/functions/deploy`, {params: { path: { ref: projectRef }, query: { slug: slug } },body: {file: files as any,- metadata,+ metadata: metadata as EdgeFunctionsDeployBodyMetadata,},bodySerializer(body) {const formData = new FormData()diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsxindex 910cf24f35e..9814b767b44 100644--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx@@ -6,6 +6,7 @@ import { toast } from 'sonner'import { useParams } from 'common'import { DeployEdgeFunctionWarningModal } from 'components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal'+import { EdgeFunctionFile } from 'components/interfaces/EdgeFunctions/EdgeFunction.types'import DefaultLayout from 'components/layouts/DefaultLayout'import EdgeFunctionDetailsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout'import { ButtonTooltip } from 'components/ui/ButtonTooltip'@@ -58,9 +59,7 @@ const CodePage = () => {refetchIntervalInBackground: false,})- const [files, setFiles] = useState<- { id: number; name: string; content: string; selected?: boolean }[]- >([])+ const [files, setFiles] = useState<EdgeFunctionFile[]>([])const { mutate: deployFunction, isLoading: isDeploying } = useEdgeFunctionDeployMutation({onSuccess: () => {@@ -76,46 +75,14 @@ const CodePage = () => {const newEntrypointPath = selectedFunction.entrypoint_path?.split('/').pop()const newImportMapPath = selectedFunction.import_map_path?.split('/').pop()- const fallbackEntrypointPath = () => {- // when there's no matching entrypoint path is set,- // we use few heuristics to find an entrypoint file- // 1. If the function has only a single TS / JS file, if so set it as entrypoint- const jsFiles = files.filter(({ name }) => name.endsWith('.js') || name.endsWith('.ts'))- if (jsFiles.length === 1) {- return jsFiles[0].name- } else if (jsFiles.length) {- // 2. If function has a `index` or `main` file use it as the entrypoint- const regex = /^.*?(index|main).*$/i- const matchingFile = jsFiles.find(({ name }) => regex.test(name))- // 3. if no valid index / main file found, we set the entrypoint expliclty to first JS file- return matchingFile ? matchingFile.name : jsFiles[0].name- } else {- // no potential entrypoint files found, this will most likely result in an error on deploy- return 'index.ts'- }- }-- const fallbackImportMapPath = () => {- // try to find a deno.json or import_map.json file- const regex = /^.*?(deno|import_map).json*$/i- return files.find(({ name }) => regex.test(name))?.name- }-deployFunction({projectRef: ref,slug: selectedFunction.slug,metadata: {name: selectedFunction.name,verify_jwt: selectedFunction.verify_jwt,- entrypoint_path: files.some(({ name }) => name === newEntrypointPath)- ? (newEntrypointPath as string)- : fallbackEntrypointPath(),- import_map_path: files.some(({ name }) => name === newImportMapPath)- ? newImportMapPath- : fallbackImportMapPath(),- static_patterns: files- .filter(({ name }) => !name.match(/\.(js|ts|jsx|tsx|json|wasm)$/i))- .map(({ name }) => name),+ entrypoint_path: newEntrypointPath,+ import_map_path: newImportMapPath,},files: files.map(({ name, content }) => ({ name, content })),})diff --git a/apps/studio/pages/project/[ref]/functions/new.tsx b/apps/studio/pages/project/[ref]/functions/new.tsxindex 507a532cfe0..f2a58ee4e39 100644--- a/apps/studio/pages/project/[ref]/functions/new.tsx+++ b/apps/studio/pages/project/[ref]/functions/new.tsx@@ -7,6 +7,7 @@ import { toast } from 'sonner'import * as z from 'zod'import { useParams } from 'common'+import { EdgeFunctionFile } from 'components/interfaces/EdgeFunctions/EdgeFunction.types'import { EDGE_FUNCTION_TEMPLATES } from 'components/interfaces/Functions/Functions.templates'import DefaultLayout from 'components/layouts/DefaultLayout'import EdgeFunctionsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout'@@ -108,9 +109,7 @@ const NewFunctionPage = () => {const showStripeExample = useIsFeatureEnabled('edge_functions:show_stripe_example')const { openSidebar } = useSidebarManagerSnapshot()- const [files, setFiles] = useState<- { id: number; name: string; content: string; selected?: boolean }[]- >([+ const [files, setFiles] = useState<EdgeFunctionFile[]>([{id: 1,name: 'index.ts',@@ -154,13 +153,10 @@ const NewFunctionPage = () => {deployFunction({projectRef: ref,slug: values.functionName,- metadata: {- entrypoint_path: 'index.ts',- name: values.functionName,- verify_jwt: true,- },+ metadata: { name: values.functionName, verify_jwt: true },files: files.map(({ name, content }) => ({ name, content })),})+sendEvent({action: 'edge_function_deploy_button_clicked',properties: { origin: 'functions_editor' },diff --git a/packages/ui-patterns/src/TimestampInfo/index.tsx b/packages/ui-patterns/src/TimestampInfo/index.tsxindex 7fa5d6e3b2f..22b8c591d76 100644--- a/packages/ui-patterns/src/TimestampInfo/index.tsx+++ b/packages/ui-patterns/src/TimestampInfo/index.tsx@@ -51,8 +51,8 @@ export const TimestampInfo = ({utcTimestamp,className,displayAs = 'local',- format = 'DD MMM HH:mm:ss',- labelFormat = 'DD MMM HH:mm:ss',+ format = 'DD MMM YY HH:mm:ss',+ labelFormat = 'DD MMM YY HH:mm:ss',label,}: {className?: string