The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Updates to Edge Functions dashboard code editor (#39991)
Lakshan Perera95eedb927e69
diff --git a/apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx b/apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsxindex d91ae01541e..2865b092f7b 100644--- a/apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx+++ b/apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx@@ -14,7 +14,6 @@ import { basename } from 'path'import { Card, CardContent, CardHeader, CardTitle, cn, Skeleton } from 'ui'const EMPTY_FUNCTION_BODY: EdgeFunctionBodyData = {- version: 0,files: EMPTY_ARR,}@@ -95,8 +94,12 @@ const FunctionDiff = ({const language = useMemo(() => {if (!activeFileKey) return 'plaintext'- if (activeFileKey.endsWith('.ts') || activeFileKey.endsWith('.tsx')) return 'typescript'- if (activeFileKey.endsWith('.js') || activeFileKey.endsWith('.jsx')) return 'javascript'+ if (activeFileKey.endsWith('.ts') || activeFileKey.endsWith('.tsx')) {+ return 'typescript'+ }+ if (activeFileKey.endsWith('.js') || activeFileKey.endsWith('.jsx')) {+ return 'javascript'+ }if (activeFileKey.endsWith('.json')) return 'json'if (activeFileKey.endsWith('.sql')) return 'sql'return 'plaintext'diff --git a/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal.tsx b/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal.tsxindex dd143783bab..06ef8e59412 100644--- a/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal.tsx+++ b/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal.tsx@@ -17,7 +17,7 @@ export const DeployEdgeFunctionWarningModal = ({<ConfirmationModalvisible={visible}size="medium"- title="Confirm deploying updates"+ title="Confirm to deploy updates"confirmLabel="Deploy updates"confirmLabelLoading="Deploying updates"variant="warning"diff --git a/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.utils.ts b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.utils.tsnew file mode 100644index 00000000000..5e2403521f5--- /dev/null+++ b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.utils.ts@@ -0,0 +1,49 @@+export const isBinaryFile = (fileName: string): boolean => {+ const extension = fileName.split('.').pop()?.toLowerCase()+ const binaryExtensions = [+ 'wasm',+ 'jpg',+ 'jpeg',+ 'png',+ 'gif',+ 'bmp',+ 'ico',+ 'svg',+ 'mp3',+ 'mp4',+ 'avi',+ 'mov',+ 'zip',+ 'rar',+ '7z',+ 'tar',+ 'gz',+ 'bz2',+ 'pdf',+ ]+ return binaryExtensions.includes(extension || '')+}++export const getLanguageFromFileName = (fileName: string): string => {+ const extension = fileName.split('.').pop()?.toLowerCase()+ switch (extension) {+ case 'ts':+ case 'tsx':+ return 'typescript'+ case 'js':+ case 'jsx':+ return 'javascript'+ case 'json':+ return 'json'+ case 'html':+ return 'html'+ case 'css':+ return 'css'+ case 'md':+ return 'markdown'+ case 'csv':+ return 'csv'+ default:+ return 'plaintext' // Default to plaintext+ }+}diff --git a/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.tsx b/apps/studio/components/ui/FileExplorerAndEditor/index.tsxsimilarity index 58%rename from apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.tsxrename to apps/studio/components/ui/FileExplorerAndEditor/index.tsxindex f425a22b38e..f1988cff2aa 100644--- a/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.tsx+++ b/apps/studio/components/ui/FileExplorerAndEditor/index.tsx@@ -1,3 +1,4 @@+import { AnimatePresence, motion } from 'framer-motion'import { Edit, File, Plus, Trash } from 'lucide-react'import { useEffect, useState } from 'react'@@ -13,6 +14,7 @@ import {TreeView,TreeViewItem,} from 'ui'+import { getLanguageFromFileName, isBinaryFile } from './FileExplorerAndEditor.utils'interface FileData {id: number@@ -32,35 +34,16 @@ interface FileExplorerAndEditorProps {}}-const getLanguageFromFileName = (fileName: string): string => {- const extension = fileName.split('.').pop()?.toLowerCase()- switch (extension) {- case 'ts':- case 'tsx':- return 'typescript'- case 'js':- case 'jsx':- return 'javascript'- case 'json':- return 'json'- case 'html':- return 'html'- case 'css':- return 'css'- case 'md':- return 'markdown'- default:- return 'typescript' // Default to typescript- }-}+const denoJsonDefaultContent = JSON.stringify({ imports: {} }, null, '\t')-const FileExplorerAndEditor = ({+export const FileExplorerAndEditor = ({files,onFilesChange,aiEndpoint,aiMetadata,}: FileExplorerAndEditorProps) => {const selectedFile = files.find((f) => f.selected) ?? files[0]+ const [isDragOver, setIsDragOver] = useState(false)const [treeData, setTreeData] = useState({name: '',@@ -95,9 +78,55 @@ const FileExplorerAndEditor = ({])}+ const addDroppedFiles = async (droppedFiles: FileList) => {+ const newFiles: FileData[] = []+ const updatedFiles = files.map((f) => ({ ...f, selected: false }))++ for (let i = 0; i < droppedFiles.length; i++) {+ const file = droppedFiles[i]+ const newId = Math.max(0, ...files.map((f) => f.id), ...newFiles.map((f) => f.id)) + 1++ try {+ let content: string+ if (isBinaryFile(file.name)) {+ // For binary files, read as ArrayBuffer and convert to base64 or keep as binary data+ const arrayBuffer = await file.arrayBuffer()+ const bytes = new Uint8Array(arrayBuffer)+ content = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('')+ } else {+ content = await file.text()+ }++ newFiles.push({+ id: newId,+ name: file.name,+ content,+ selected: i === droppedFiles.length - 1, // Select the last dropped file+ })+ } catch (error) {+ console.error(`Failed to read file ${file.name}:`, error)+ }+ }++ if (newFiles.length > 0) {+ onFilesChange([...updatedFiles, ...newFiles])+ }+ }+const handleFileNameChange = (id: number, newName: string) => {if (!newName.trim()) return // Don't allow empty names- const updatedFiles = files.map((file) => (file.id === id ? { ...file, name: newName } : file))+ const updatedFiles = files.map((file) =>+ file.id === id+ ? {+ ...file,+ name: newName,+ content:+ newName === 'deno.json' && file.content === ''+ ? denoJsonDefaultContent+ : file.content,+ }+ : file+ )onFilesChange(updatedFiles)}@@ -145,6 +174,26 @@ const FileExplorerAndEditor = ({setTreeData(updatedTreeData)}+ const handleDragOver = (e: React.DragEvent) => {+ e.preventDefault()+ setIsDragOver(true)+ }++ const handleDragLeave = (e: React.DragEvent) => {+ e.preventDefault()+ setIsDragOver(false)+ }++ const handleDrop = async (e: React.DragEvent) => {+ e.preventDefault()+ setIsDragOver(false)++ const droppedFiles = e.dataTransfer.files+ if (droppedFiles.length > 0) {+ await addDroppedFiles(droppedFiles)+ }+ }+// Update treeData when files changeuseEffect(() => {setTreeData({@@ -161,7 +210,27 @@ const FileExplorerAndEditor = ({}, [files])return (- <div className="flex-1 overflow-hidden flex h-full">+ <div+ className={`flex-1 overflow-hidden flex h-full relative ${isDragOver ? 'bg-blue-50' : ''}`}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ >+ <AnimatePresence>+ {isDragOver && (+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: 0.1 }}+ className="absolute inset-0 bg bg-opacity-30 z-10 flex items-center justify-center"+ >+ <div className="w-96 py-20 bg bg-opacity-60 border-2 border-dashed border-muted flex items-center justify-center">+ <div className="text-base">Drop files here to add them</div>+ </div>+ </motion.div>+ )}+ </AnimatePresence><div className="w-64 border-r bg-surface-200 flex flex-col"><div className="py-4 px-6 border-b flex items-center justify-between"><h3 className="text-sm font-normal font-mono uppercase text-lighter tracking-wide">@@ -197,13 +266,17 @@ const FileExplorerAndEditor = ({icon={<File size={14} className="text-foreground-light shrink-0" />}isEditing={Boolean(element.metadata?.isEditing)}onEditSubmit={(value) => {- if (originalId !== null) handleFileNameChange(originalId, value)+ if (originalId !== null) {+ handleFileNameChange(originalId, value)+ }}}onClick={() => {if (originalId !== null) handleFileSelect(originalId)}}onDoubleClick={() => {- if (originalId !== null) handleStartRename(originalId)+ if (originalId !== null) {+ handleStartRename(originalId)+ }}}/></div>@@ -226,7 +299,9 @@ const FileExplorerAndEditor = ({<ContextMenuItem_Shadcn_className="gap-x-2"onSelect={() => {- if (originalId !== null) handleFileDelete(originalId)+ if (originalId !== null) {+ handleFileDelete(originalId)+ }}}onFocusCapture={(e) => e.stopPropagation()}>@@ -243,26 +318,36 @@ const FileExplorerAndEditor = ({</div></div><div className="flex-1 min-h-0 relative px-3 bg-surface-200">- <AIEditor- language={getLanguageFromFileName(selectedFile?.name || 'index.ts')}- value={selectedFile?.content}- onChange={handleChange}- aiEndpoint={aiEndpoint}- aiMetadata={aiMetadata}- options={{- tabSize: 2,- fontSize: 13,- minimap: { enabled: false },- wordWrap: 'on',- lineNumbers: 'on',- folding: false,- padding: { top: 20, bottom: 20 },- lineNumbersMinChars: 3,- }}- />+ {selectedFile && isBinaryFile(selectedFile.name) ? (+ <div className="flex items-center justify-center h-full">+ <div className="text-center">+ <div className="text-foreground-light text-lg mb-2">Cannot Edit Selected File</div>+ <div className="text-foreground-lighter text-sm">+ Binary files like .{selectedFile.name.split('.').pop()} cannot be edited in the text+ editor+ </div>+ </div>+ </div>+ ) : (+ <AIEditor+ language={getLanguageFromFileName(selectedFile?.name || 'index.ts')}+ value={selectedFile?.content}+ onChange={handleChange}+ aiEndpoint={aiEndpoint}+ aiMetadata={aiMetadata}+ options={{+ tabSize: 2,+ fontSize: 13,+ minimap: { enabled: false },+ wordWrap: 'on',+ lineNumbers: 'on',+ folding: false,+ padding: { top: 20, bottom: 20 },+ lineNumbersMinChars: 3,+ }}+ />+ )}</div></div>)}--export default FileExplorerAndEditordiff --git a/apps/studio/data/edge-functions/edge-function-body-query.ts b/apps/studio/data/edge-functions/edge-function-body-query.tsindex 2f9b921ad2e..7fe5947f633 100644--- a/apps/studio/data/edge-functions/edge-function-body-query.ts+++ b/apps/studio/data/edge-functions/edge-function-body-query.ts@@ -1,6 +1,7 @@+import { getMultipartBoundary, parseMultipartStream } from '@mjackson/multipart-parser'import { useQuery, UseQueryOptions } from '@tanstack/react-query'-import { constructHeaders, fetchHandler, handleError } from 'data/fetchers'-import { BASE_PATH, IS_PLATFORM } from 'lib/constants'+import { get, handleError } from 'data/fetchers'+import { IS_PLATFORM } from 'lib/constants'import { ResponseError } from 'types'import { edgeFunctionsKeys } from './keys'@@ -15,10 +16,29 @@ export type EdgeFunctionFile = {}export type EdgeFunctionBodyResponse = {- version: numberfiles: 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@@ -26,41 +46,31 @@ export async function getEdgeFunctionBody(if (!projectRef) throw new Error('projectRef is required')if (!slug) throw new Error('slug is required')- try {- // Get authorization headers- const headers = await constructHeaders({- 'Content-Type': 'application/json',- })+ const { data, response, error } = await get('/v1/projects/{ref}/functions/{function_slug}/body', {+ params: { path: { ref: projectRef, function_slug: slug } },+ headers: { Accept: 'multipart/form-data' },+ parseAs: 'stream',+ signal,+ })- // Send to our API for processing (the API will handle the fetch from v1 endpoint)- const parseResponse = await fetchHandler(`${BASE_PATH}/api/edge-functions/body`, {- method: 'POST',- body: JSON.stringify({ projectRef, slug }),- headers,- credentials: 'include',- signal,- })+ if (error) handleError(error)- if (!parseResponse.ok) {- const { error } = await parseResponse.json()- handleError(- typeof error === 'object'- ? error- : typeof error === 'string'- ? { message: error }- : { message: 'Unknown error' }- )- }+ const contentTypeHeader = response.headers.get('content-type') ?? ''+ const boundary = getMultipartBoundary(contentTypeHeader)+ const files = []- const response = (await parseResponse.json()) as EdgeFunctionBodyResponse- return response- } catch (error) {- handleError(error)- return {- version: 0,- files: [],- } as EdgeFunctionBodyResponse+ if (!data || !boundary) return { files: [] }++ for await (let part of parseMultipartStream(data, { boundary })) {+ if (part.isFile) {+ files.push({+ name: part.filename,+ content: part.text,+ })+ }}++ return { files: files as EdgeFunctionFile[] }}export type EdgeFunctionBodyData = Awaited<ReturnType<typeof getEdgeFunctionBody>>diff --git a/apps/studio/data/fetchers.ts b/apps/studio/data/fetchers.tsindex 6b2969b8217..aa8d66e428c 100644--- a/apps/studio/data/fetchers.ts+++ b/apps/studio/data/fetchers.ts@@ -24,7 +24,7 @@ export const fetchHandler: typeof fetch = async (input, init) => {}}-const client = createClient<paths>({+export const client = createClient<paths>({fetch: fetchHandler,// [Joshen] Just FYI, the replace is temporary until we update env vars API_URL to remove /platform or /v1 - should just be the base URLbaseUrl: API_URL?.replace('/platform', ''),diff --git a/apps/studio/lib/eszip-parser.test.ts b/apps/studio/lib/eszip-parser.test.tsdeleted file mode 100644index ec38531a19d..00000000000--- a/apps/studio/lib/eszip-parser.test.ts+++ /dev/null@@ -1,122 +0,0 @@-import { Parser } from '@deno/eszip'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { parseEszip } from './eszip-parser'--vi.mock('@deno/eszip', () => ({- Parser: {- createInstance: vi.fn(),- },-}))--vi.stubGlobal(- 'File',- class MockFile {- name: string- content: string-- constructor(content: string[], name: string) {- this.name = name- this.content = content[0]- }-- async text() {- return this.content- }- }-)--vi.stubGlobal(- 'URL',- class MockURL {- pathname: string-- constructor(url: string) {- this.pathname = url- }- }-)--describe('eszip-parser', () => {- const mockParser = {- parseBytes: vi.fn(),- load: vi.fn(),- getModuleSource: vi.fn(),- }-- beforeEach(() => {- vi.clearAllMocks()- ;(Parser.createInstance as any).mockResolvedValue(mockParser)- })-- afterEach(() => {- vi.resetAllMocks()- })-- describe('parseEszip', () => {- it('should successfully parse and extract files from eszip', async () => {- const mockBytes = new Uint8Array([1, 2, 3])- const mockSpecifiers = ['file1.ts', 'file2.ts']- const mockModuleSource1 = 'export const hello = "world"'- const mockModuleSource2 = 'export const foo = "bar"'-- mockParser.parseBytes.mockResolvedValue(mockSpecifiers)- mockParser.load.mockResolvedValue(undefined)- mockParser.getModuleSource- .mockResolvedValueOnce(null)- .mockResolvedValueOnce(mockModuleSource1)- .mockResolvedValueOnce(mockModuleSource2)-- const result = await parseEszip(mockBytes)-- expect(Parser.createInstance).toHaveBeenCalledTimes(1)- expect(mockParser.parseBytes).toHaveBeenCalledWith(mockBytes)- expect(mockParser.load).toHaveBeenCalled()- expect(result.version).toEqual(0)- expect(result.files).toHaveLength(2)- expect(result.files[0]).toEqual({- name: 'file1.ts',- content: mockModuleSource1,- })- expect(result.files[1]).toEqual({- name: 'file2.ts',- content: mockModuleSource2,- })- })-- it('should handle parseBytes failure', async () => {- mockParser.parseBytes.mockRejectedValue(new Error('Parse error'))- await expect(parseEszip(new Uint8Array())).rejects.toThrow('Parse error')- })-- it('should handle load failure', async () => {- mockParser.parseBytes.mockResolvedValue(['file1.ts'])- mockParser.load.mockRejectedValue(new Error('Load error'))-- await expect(parseEszip(new Uint8Array())).rejects.toThrow('Load error')- })-- it('should filter out unwanted specifiers', async () => {- const mockBytes = new Uint8Array([1, 2, 3])- const mockSpecifiers = [- 'file1.ts',- 'npm:package',- 'https://example.com/file.ts',- 'file2.ts',- '---internal',- 'jsr:package',- ]- const mockModuleSource = 'export const test = "test"'-- mockParser.parseBytes.mockResolvedValue(mockSpecifiers)- mockParser.load.mockResolvedValue(undefined)- mockParser.getModuleSource.mockResolvedValue(mockModuleSource)-- const result = await parseEszip(mockBytes)- // Only file1.ts and file2.ts should be included- expect(result.version).toEqual(0)- expect(result.files).toHaveLength(2)- expect(result.files[0].name).toBe('file1.ts')- expect(result.files[1].name).toBe('file2.ts')- })- })-})diff --git a/apps/studio/lib/eszip-parser.ts b/apps/studio/lib/eszip-parser.tsdeleted file mode 100644index 7aa5428e747..00000000000--- a/apps/studio/lib/eszip-parser.ts+++ /dev/null@@ -1,144 +0,0 @@-import { Parser } from '@deno/eszip'-import path from 'path'--function url2path(url: string) {- try {- // Parse the URL- return new URL(url).pathname- } catch (error) {- // If URL parsing fails, fallback to extracting just the filename- console.warn('Failed to parse URL:', url)- try {- // Try to extract just the filename part- const parts = url.split('/').filter(Boolean)- if (parts.length > 0) {- return parts[parts.length - 1] // Return just the filename- }- } catch (e) {- // Last resort: use the original path joining- console.error('Failed to extract filename:', e)- }- return path.join(...new URL(url).pathname.split('/').filter(Boolean))- }-}--// Initialize parser outside of request handler-let parserPromise: Promise<any> | null = null--async function getParser() {- if (!parserPromise) {- parserPromise = Parser.createInstance().catch((err) => {- console.error('Failed to create parser instance:', err)- parserPromise = null- throw err- })- }- return parserPromise-}--export async function parseEszip(bytes: Uint8Array) {- try {- const parser = await getParser()- if (!parser) {- throw new Error('Failed to initialize parser')- }-- // Parse bytes in a try-catch block- let specifiers: string[] = []- try {- specifiers = await parser.parseBytes(bytes)- } catch (parseError) {- console.error('Error parsing bytes:', parseError)- // Reset parser on parse error- parserPromise = null- throw parseError- }-- // Load in a separate try-catch- try {- await parser.load()- } catch (loadError) {- console.error('Error loading parser:', loadError)- parserPromise = null- throw loadError- }-- // Extract version- let version = parseInt(await parser.getModuleSource('---SUPABASE-ESZIP-VERSION-ESZIP---'))- if (isNaN(version)) {- version = 0- }-- // Extract files from the eszip- const files = await extractEszip(parser, specifiers, version >= 2)-- // Convert files to the expected format- const responseFiles = await Promise.all(- files.map(async (file) => {- const content = await file.text()- return {- name: file.name,- content: content,- }- })- )-- return {- version,- files: responseFiles,- }- } catch (error) {- console.error('Error in parseEszip:', error)- throw error- }-}--async function extractEszip(parser: any, specifiers: string[], isDeno2: boolean) {- const files = []-- // First, filter out the specifiers we want to keep- const filteredSpecifiers = specifiers.filter((specifier) => {- const shouldSkip =- specifier.startsWith('---') ||- specifier.startsWith('npm:') ||- specifier.startsWith('static:') ||- specifier.startsWith('vfs:') ||- specifier.startsWith('https:') ||- specifier.startsWith('jsr:')-- if (shouldSkip) {- console.log('Skipping specifier:', specifier)- } else {- console.log('Keeping specifier:', specifier)- }-- return !shouldSkip- })-- console.log('Filtered specifiers count:', filteredSpecifiers.length)- console.log('Filtered specifiers:', JSON.stringify(filteredSpecifiers))-- // Then process each one- for (const specifier of filteredSpecifiers) {- try {- // Try to get the module source- const moduleSource = await parser.getModuleSource(specifier)- let qualifiedSpecifier = specifier-- // Get the file path- if (isDeno2 && !specifier.startsWith('file://')) {- qualifiedSpecifier = `file://${specifier}`- }- const filePath = url2path(qualifiedSpecifier)-- // Create a file object- const file = new File([moduleSource], filePath)-- files.push(file)- } catch (error) {- console.error('Error processing specifier:', specifier, error)- }- }-- return files-}diff --git a/apps/studio/package.json b/apps/studio/package.jsonindex 2518fbf3c5f..35535056282 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -32,7 +32,6 @@"@ai-sdk/react": "2.0.45","@aws-sdk/credential-providers": "^3.804.0","@dagrejs/dagre": "^1.0.4",- "@deno/eszip": "0.83.0","@dnd-kit/core": "^6.1.0","@dnd-kit/modifiers": "^9.0.0","@dnd-kit/sortable": "^8.0.0",@@ -45,6 +44,7 @@"@headlessui/react": "^1.7.17","@heroicons/react": "^2.1.3","@hookform/resolvers": "^3.1.1",+ "@mjackson/multipart-parser": "^0.10.1","@modelcontextprotocol/sdk": "^1.18.0","@monaco-editor/react": "^4.6.0","@next/bundle-analyzer": "15.3.1",diff --git a/apps/studio/pages/api/edge-functions/body.ts b/apps/studio/pages/api/edge-functions/body.tsdeleted file mode 100644index ed220a07144..00000000000--- a/apps/studio/pages/api/edge-functions/body.ts+++ /dev/null@@ -1,91 +0,0 @@-import { API_URL } from 'lib/constants'-import { parseEszip } from 'lib/eszip-parser'-import { NextApiRequest, NextApiResponse } from 'next'--export default async function handler(req: NextApiRequest, res: NextApiResponse) {- const { method } = req-- switch (method) {- case 'POST':- return handlePost(req, res)- default:- return new Response(- JSON.stringify({ data: null, error: { message: `Method ${method} Not Allowed` } }),- {- status: 405,- headers: { 'Content-Type': 'application/json', Allow: 'POST' },- }- )- }-}--async function handlePost(req: NextApiRequest, res: NextApiResponse) {- try {- const { projectRef, slug } = req.body || {}-- if (!projectRef) {- return res.status(400).json({ error: 'projectRef is required' })- }- if (!slug) {- return res.status(400).json({ error: 'slug is required' })- }-- // Get authorization token from the request- const authToken = req.headers.authorization-- if (!authToken) {- return res.status(401).json({ error: 'No authorization token was found' })- }-- // Fetch the eszip data- const headers = new Headers()- headers.set('Accept', 'application/octet-stream')- headers.set('Authorization', typeof authToken === 'string' ? authToken : authToken[0])-- // Forward other important headers- if (req.headers.cookie) {- headers.set('Cookie', req.headers.cookie)- }-- const baseUrl = API_URL?.replace('/platform', '')- const url = `${baseUrl}/v1/projects/${projectRef}/functions/${slug}/body`-- const response = await fetch(url, {- method: 'GET',- headers,- credentials: 'include',- referrerPolicy: 'no-referrer-when-downgrade',- })-- if (!response.ok) {- const error = await response.json()- return res.status(response.status).json(error)- }-- // Verify content type is binary/eszip- const contentType = response.headers.get('content-type')- if (!contentType || !contentType.includes('application/octet-stream')) {- return res.status(400).json({- error:- 'Invalid response: Expected eszip file but received ' + (contentType || 'unknown format'),- })- }-- // Get the eszip data as ArrayBuffer- const arrayBuffer = await response.arrayBuffer()-- if (arrayBuffer.byteLength === 0) {- return res.status(400).json({ error: 'Invalid eszip: File is empty' })- }-- const uint8Array = new Uint8Array(arrayBuffer)-- // Parse the eszip file using our utility- const parsed = await parseEszip(uint8Array)-- return res.status(200).json(parsed)- } catch (error) {- console.error('Error processing edge function body:', error)- return res.status(500).json({ error: 'Internal server error' })- }-}diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsxindex 2de8d353006..910cf24f35e 100644--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx@@ -9,7 +9,7 @@ import { DeployEdgeFunctionWarningModal } from 'components/interfaces/EdgeFunctiimport DefaultLayout from 'components/layouts/DefaultLayout'import EdgeFunctionDetailsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout'import { ButtonTooltip } from 'components/ui/ButtonTooltip'-import FileExplorerAndEditor from 'components/ui/FileExplorerAndEditor/FileExplorerAndEditor'+import { FileExplorerAndEditor } from 'components/ui/FileExplorerAndEditor'import { useEdgeFunctionBodyQuery } from 'data/edge-functions/edge-function-body-query'import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'import { useEdgeFunctionDeployMutation } from 'data/edge-functions/edge-functions-deploy-mutation'@@ -30,7 +30,10 @@ const CodePage = () => {const { can: canDeployFunction } = useAsyncCheckPermissions(PermissionAction.FUNCTIONS_WRITE, '*')- const { data: selectedFunction } = useEdgeFunctionQuery({ projectRef: ref, slug: functionSlug })+ const { data: selectedFunction } = useEdgeFunctionQuery({+ projectRef: ref,+ slug: functionSlug,+ })const {data: functionBody,isLoading: isLoadingFiles,@@ -110,6 +113,9 @@ const CodePage = () => {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),},files: files.map(({ name, content }) => ({ name, content })),})@@ -120,31 +126,23 @@ const CodePage = () => {}}- function getBasePath(- entrypoint: string | undefined,- fileNames: string[],- version: number- ): string {+ function getBasePath(entrypoint: string | undefined, fileNames: string[]): string {if (!entrypoint) {return '/'}- let qualifiedEntrypoint = entrypoint+ let candidate = fileNames.find((name) => entrypoint.endsWith(name))- if (version >= 2) {- const candidate = fileNames.find((name) => entrypoint.endsWith(name))- if (candidate) {- qualifiedEntrypoint = `file://${candidate}`- } else {- qualifiedEntrypoint = entrypoint+ if (candidate) {+ return dirname(candidate)+ } else {+ try {+ return dirname(new URL(entrypoint).pathname)+ } catch (e) {+ console.error('Failed to parse entrypoint', entrypoint)+ return '/'}}- try {- return dirname(new URL(qualifiedEntrypoint).pathname)- } catch (e) {- console.error('Failed to parse entrypoint', qualifiedEntrypoint)- return '/'- }}const handleDeployClick = () => {@@ -152,14 +150,20 @@ const CodePage = () => {setShowDeployWarning(true)sendEvent({action: 'edge_function_deploy_updates_button_clicked',- groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },+ groups: {+ project: ref ?? 'Unknown',+ organization: org?.slug ?? 'Unknown',+ },})}const handleDeployConfirm = () => {sendEvent({action: 'edge_function_deploy_updates_confirm_clicked',- groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },+ groups: {+ project: ref ?? 'Unknown',+ organization: org?.slug ?? 'Unknown',+ },})onUpdate()}@@ -169,12 +173,9 @@ const CodePage = () => {if (selectedFunction?.entrypoint_path && functionBody) {const base_path = getBasePath(selectedFunction?.entrypoint_path,- functionBody.files.map((file) => file.name),- functionBody.version+ functionBody.files.map((file) => file.name))const filesWithRelPath = functionBody.files- // ignore empty files- .filter((file: { name: string; content: string }) => !!file.content.length)// set file paths relative to entrypoint.map((file: { name: string; content: string }) => {try {@@ -185,7 +186,8 @@ const CodePage = () => {return file}- file.name = relative(base_path, file.name)+ // prepend "/" to turn relative paths to absolute+ file.name = relative('/' + base_path, '/' + file.name)return file} catch (e) {console.error(e)diff --git a/apps/studio/pages/project/[ref]/functions/new.tsx b/apps/studio/pages/project/[ref]/functions/new.tsxindex b813c3babb6..507a532cfe0 100644--- a/apps/studio/pages/project/[ref]/functions/new.tsx+++ b/apps/studio/pages/project/[ref]/functions/new.tsx@@ -11,7 +11,8 @@ import { EDGE_FUNCTION_TEMPLATES } from 'components/interfaces/Functions/Functioimport DefaultLayout from 'components/layouts/DefaultLayout'import EdgeFunctionsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout'import { PageLayout } from 'components/layouts/PageLayout/PageLayout'-import FileExplorerAndEditor from 'components/ui/FileExplorerAndEditor/FileExplorerAndEditor'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { FileExplorerAndEditor } from 'components/ui/FileExplorerAndEditor'import { useEdgeFunctionDeployMutation } from 'data/edge-functions/edge-functions-deploy-mutation'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'@@ -19,6 +20,7 @@ import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganizationimport { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { BASE_PATH } from 'lib/constants'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import {AiIconAnimation,Button,@@ -42,8 +44,6 @@ import {TooltipContent,TooltipTrigger,} from 'ui'-import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'-import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'// Array of adjectives and nouns for random function name generationconst ADJECTIVES = [diff --git a/packages/api-types/types/platform.d.ts b/packages/api-types/types/platform.d.tsindex 3d3762b5246..802ab87b7d3 100644--- a/packages/api-types/types/platform.d.ts+++ b/packages/api-types/types/platform.d.ts@@ -3764,7 +3764,11 @@ export interface paths {}get?: neverput?: never- post?: never+ /**+ * Update publication for source+ * @description Update a publication for a source. Requires bearer auth and an active, healthy project.+ */+ post: operations['ReplicationSourcesController_updatePublication']/*** Delete publication for source* @description Delete a publication for a source. Requires bearer auth and an active, healthy project.@@ -10062,6 +10066,21 @@ export interface components {*/version_id: number}+ UpdateReplicationPublicationBody: {+ /** @description Publication tables */+ tables: {+ /**+ * @description Table name+ * @example orders+ */+ name: string+ /**+ * @description Table schema+ * @example public+ */+ schema: string+ }[]+ }UpdateSecretsConfigBody: {change_tracking_id: stringjwt_secret: string@@ -23587,6 +23606,63 @@ export interface operations {}}}+ ReplicationSourcesController_updatePublication: {+ parameters: {+ query?: never+ header?: never+ path: {+ /** @description Publication name */+ publication_name: string+ /** @description Project ref */+ ref: string+ /** @description Source id */+ source_id: number+ }+ cookie?: never+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['UpdateReplicationPublicationBody']+ }+ }+ responses: {+ /** @description Publication updated. */+ 200: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Unauthorized */+ 401: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Forbidden action */+ 403: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Rate limit exceeded */+ 429: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Unexpected error while updating publication. */+ 500: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ }+ }ReplicationSourcesController_deletePublication: {parameters: {query?: neverdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e90cc80e0b2..49e35824adb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -397,7 +397,7 @@ importers:version: 1.0.3(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])'@sentry/nextjs':specifier: ^10.3.0- version: 10.3.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])+ version: 10.3.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])'@supabase/supabase-js':specifier: 'catalog:'version: 2.75.1@@ -750,9 +750,6 @@ importers:'@dagrejs/dagre':specifier: ^1.0.4version: 1.0.4- '@deno/eszip':- specifier: 0.83.0- version: 0.83.0'@dnd-kit/core':specifier: ^6.1.0@@ -789,6 +786,9 @@ importers:'@hookform/resolvers':specifier: ^3.1.1version: 3.3.1([email protected]([email protected]))+ '@mjackson/multipart-parser':+ specifier: ^0.10.1+ version: 0.10.1'@modelcontextprotocol/sdk':specifier: ^1.18.0version: 1.18.0([email protected])@@ -812,7 +812,7 @@ importers:version: 1.1.3(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])'@sentry/nextjs':specifier: ^10.3.0- version: 10.3.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])+ version: 10.3.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])'@std/path':specifier: npm:@jsr/std__path@^1.0.8version: '@jsr/[email protected]'@@ -1227,7 +1227,7 @@ importers:version: 2.11.3(@types/[email protected])([email protected])next-router-mock:specifier: ^0.9.13- version: 0.9.13([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])+ version: 0.9.13([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])node-mocks-http:specifier: ^1.17.2version: 1.17.2(@types/[email protected])@@ -1591,7 +1591,7 @@ importers:version: 1.0.5(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])'@sentry/nextjs':specifier: ^10- version: 10.3.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])+ version: 10.3.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])'@supabase/supabase-js':specifier: 'catalog:'version: 2.75.1@@ -2576,7 +2576,7 @@ importers:version: link:../api-typesnext-router-mock:specifier: ^0.9.13- version: 0.9.13([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])+ version: 0.9.13([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])tsx:specifier: 'catalog:'version: 4.20.3@@ -3429,15 +3429,9 @@ packages:'@date-fns/[email protected]':resolution: {integrity: sha512-LBrd7MiJZ9McsOgxqWX7AaxrDjcFVjWH/tIKJd7pnR7McaslGYOP1QmmiBXdJH/H/yLCT+rcQ7FaPBUxRGUtrg==}- '@deno/[email protected]':- resolution: {integrity: sha512-gTKYMQ+uv20IUJuEBYkjovMPflFjX7caJ8cwA/sZVqic0L/PFP2gZMFt/GiCHc8eVejhlJLGxg0J4qehDq/f2A==}-'@deno/[email protected]':resolution: {integrity: sha512-4nMhecpGlPi0cSzT67L+Tm+GOJqvuk8gqHBziqcUQOarnuIax1z96/gJHCSIz2Z0zhxE6Rzwb3IZXPtFh51j+w==}- '@deno/[email protected]':- resolution: {integrity: sha512-oQ0CVmOio63wlhwQF75zA4ioolPvOwAoK0yuzcS5bDC1JUvH3y1GS8xPh8EOpcoDQRU4FTG8OQfxhpR+c6DrzA==}-'@deno/[email protected]':resolution: {integrity: sha512-q3VTHl44ad8T2Tw2SpeAvghdGOjlnLPDNO2cpOxwMrBE/PVas6geWpbpIgrM+czOCH0yejp0yi8OaTuB+NU40Q==}@@ -21852,18 +21846,8 @@ snapshots:'@date-fns/[email protected]': {}- '@deno/[email protected]':- dependencies:- '@deno/shim-deno': 0.18.2- undici: 6.21.2-'@deno/[email protected]': {}- '@deno/[email protected]':- dependencies:- '@deno/shim-deno-test': 0.5.0- which: 4.0.0-'@deno/[email protected]':dependencies:'@deno/shim-deno-test': 0.5.0@@ -27630,7 +27614,7 @@ snapshots:'@sentry/[email protected]': {}- '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])':+ '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])':dependencies:'@opentelemetry/api': 1.9.0'@opentelemetry/semantic-conventions': 1.36.0@@ -36735,7 +36719,7 @@ snapshots:dependencies:js-yaml-loader: 1.2.2- [email protected]([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]):+ [email protected]([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]):dependencies:next: 15.5.2(@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])react: 18.3.1