Files
supabase/apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
T
Alaister YoungandAlaister Young 0c97b9789b [FE-3107] chore(studio): remove remaining Next.js references (#54426)
Removes the remaining Next.js dependencies, compatibility shims, test
mocks, ESLint/TypeScript presets, and webpack/Next workarounds from
Studio following the TanStack Start migration.

Addresses FE-3107.

**Removed:**

- `next` and `next-router-mock` from `apps/studio/package.json` (and
updated `pnpm-lock.yaml`)
- Orphaned `apps/studio/compat/next/script.tsx` shim, `script.test.tsx`,
`compat/**` knip entry, and `nextCompat()` / `ssr.noExternal` `/^next/`
plumbing from `apps/studio/vite.config.ts`
- `apps/studio/tests/lib/route-mock.ts` and all `next-router-mock`
setup/imports across `tests/vitestSetup.ts`,
`tests/lib/custom-render.tsx`, and 12 test files
- `apps/studio/tests/pages/` directory (moved the 3 remaining tests to
`components/interfaces/Organization/Organization.utils.test.ts` and
`apps/studio/tests/routes/`)
- Unused `'use client'` directives across 23 Studio files
- Next.js/webpack workarounds: `graphiqlViteWorkers()` in
`vite.config.ts`, webpack `import.meta.glob` `try/catch` fallback in
`ConnectStepsSection.tsx`, shell `NODE_ENV=test` override in
`vite.config.ts` / root `package.json` / `studio-e2e-test.yml`, Next
`getPathMatch` and `_next` passthrough in `redirects.shared.*`,
`window.next?.router` check in `monaco-graphiql-coexistence.spec.ts`,
and unused `ANALYZE` env var in `apps/studio/turbo.jsonc`
- Next-only Sentry/chunk-load filters (`NEXT_NOT_FOUND`,
`NEXT_REDIRECT`, Next `/org/[slug]/` regex, `/app:\/\//`, dead
`includeThirdPartyErrorFilter` plumbing, webpack chunk error regex) and
stale Next/Pages Router comments, docs, and `#__next` CSS selector

**Changed:**

- `apps/studio/eslint.config.cjs`: switched from
`eslint-config-supabase/next` to the new `eslint-config-supabase/react`
preset (dropping `@next/next/no-img-element: off`, keeping `.next` /
`next-env.d.ts` ignored for local checkouts with stale pre-migration
build artifacts)
- `apps/studio/tsconfig.json`: extends `tsconfig/base.json` directly
instead of `tsconfig/nextjs.json` (identical resolved compiler options)
- `apps/studio/.github/eslint-rule-baselines.json`: pruned 33 stale
`pages/...` and `types/next.ts` entries without changing any rule
thresholds
- `apps/studio/tests/lib/custom-render.tsx`: backed
`TestFrameworkProvider` with TanStack Router instead of
`next-router-mock`
-
`apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx`:
imports `graphiql/setup-workers/vite` directly
- `apps/studio/styles/globals.css`: replaced `@source
'../pages/**/*.{js,ts,jsx,tsx}'` with `@source
'../routes/**/*.{js,ts,jsx,tsx}'`
- `apps/studio/turbo.jsonc`: declared `"NEXT_PUBLIC_*"` in
`tasks.build.env` now that Turborepo infers `nitro` instead of `nextjs`
-
`apps/studio/components/interfaces/Organization/Organization.utils.ts`:
narrowed `buildOrgUrl`'s `slug` parameter to `string[] | undefined`

**Added:**

- `packages/eslint-config-supabase/shared.js` and
`packages/eslint-config-supabase/react.js` (plus `presets.test.ts`),
decoupling non-Next React apps from `eslint-config-next` with verified
zero non-`@next/*` rule drift while keeping
`eslint-config-supabase/next` unchanged for the Next.js apps

## To test

- Run `pnpm --filter eslint-config-supabase run test` and confirm preset
parity tests pass
- Run `pnpm --filter studio run lint`, `pnpm --filter studio run
lint:ratchet`, `pnpm --filter studio run typecheck`, `pnpm knip
--workspace apps/studio`, and `pnpm --filter studio run test`
- Run `pnpm --filter studio run build` and verify the production build,
prerendered routes, chunk-cycle check, and GraphiQL web workers succeed
- Smoke-test Studio locally (`pnpm dev:studio`): verify GraphiQL loads
cleanly, ConnectSheet framework steps render, and Tailwind styles on
route pages are intact

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-02 17:01:50 +08:00

390 lines
13 KiB
TypeScript

import { FileData } from '@/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types'
import { EdgeFunctionBodyData } from '@/data/edge-functions/edge-function-body-query'
// Vite stubs Node.js builtins like `path` out for browser bundles, so `path.posix` would be
// undefined at runtime in the client even though it type-checks. These are self-contained POSIX
// path helpers (no `path` import) so behavior is identical on client and server.
// Ported from the POSIX implementations in @std/path (JSR), which this file used to depend on directly.
function isPosixSeparator(code: number | undefined): boolean {
return code === 47 /* '/' */
}
function stripTrailingSeparators(segment: string): string {
if (segment.length <= 1) return segment
let end = segment.length
for (let i = segment.length - 1; i > 0; i--) {
if (isPosixSeparator(segment.charCodeAt(i))) end = i
else break
}
return segment.slice(0, end)
}
// Resolves "." and ".." segments in a posix path.
function normalizeString(path: string, allowAboveRoot: boolean): string {
let res = ''
let lastSegmentLength = 0
let lastSlash = -1
let dots = 0
let code: number | undefined
for (let i = 0; i <= path.length; ++i) {
if (i < path.length) code = path.charCodeAt(i)
else if (isPosixSeparator(code)) break
else code = 47
if (isPosixSeparator(code)) {
if (lastSlash === i - 1 || dots === 1) {
// noop
} else if (lastSlash !== i - 1 && dots === 2) {
if (
res.length < 2 ||
lastSegmentLength !== 2 ||
res.charCodeAt(res.length - 1) !== 46 /* '.' */ ||
res.charCodeAt(res.length - 2) !== 46 /* '.' */
) {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf('/')
if (lastSlashIndex === -1) {
res = ''
lastSegmentLength = 0
} else {
res = res.slice(0, lastSlashIndex)
lastSegmentLength = res.length - 1 - res.lastIndexOf('/')
}
lastSlash = i
dots = 0
continue
} else if (res.length === 2 || res.length === 1) {
res = ''
lastSegmentLength = 0
lastSlash = i
dots = 0
continue
}
}
if (allowAboveRoot) {
res += res.length > 0 ? '/..' : '..'
lastSegmentLength = 2
}
} else {
res += res.length > 0 ? '/' + path.slice(lastSlash + 1, i) : path.slice(lastSlash + 1, i)
lastSegmentLength = i - lastSlash - 1
}
lastSlash = i
dots = 0
} else if (code === 46 /* '.' */ && dots !== -1) {
++dots
} else {
dots = -1
}
}
return res
}
// Normalizes an absolute posix path (resolves "." / ".."). Assumes `path` starts with "/".
function resolveAbsolute(path: string): string {
const normalized = normalizeString(path, false)
return normalized.length > 0 ? '/' + normalized : '/'
}
function dirname(path: string): string {
if (path.length === 0) return '.'
let end = -1
let matchedNonSeparator = false
for (let i = path.length - 1; i >= 1; --i) {
if (isPosixSeparator(path.charCodeAt(i))) {
if (matchedNonSeparator) {
end = i
break
}
} else {
matchedNonSeparator = true
}
}
if (end === -1) return isPosixSeparator(path.charCodeAt(0)) ? '/' : '.'
return stripTrailingSeparators(path.slice(0, end))
}
// `from`/`to` must be absolute (leading "/"). Returns the relative path from `from` to `to`.
function relative(from: string, to: string): string {
from = resolveAbsolute(from)
to = resolveAbsolute(to)
if (from === to) return ''
let fromStart = 1
const fromEnd = from.length
for (; fromStart < fromEnd; ++fromStart) {
if (!isPosixSeparator(from.charCodeAt(fromStart))) break
}
const fromLen = fromEnd - fromStart
let toStart = 1
const toEnd = to.length
for (; toStart < toEnd; ++toStart) {
if (!isPosixSeparator(to.charCodeAt(toStart))) break
}
const toLen = toEnd - toStart
const length = fromLen < toLen ? fromLen : toLen
let lastCommonSep = -1
let i = 0
for (; i <= length; ++i) {
if (i === length) {
if (toLen > length) {
if (isPosixSeparator(to.charCodeAt(toStart + i))) {
return to.slice(toStart + i + 1)
} else if (i === 0) {
return to.slice(toStart + i)
}
} else if (fromLen > length) {
if (isPosixSeparator(from.charCodeAt(fromStart + i))) {
lastCommonSep = i
} else if (i === 0) {
lastCommonSep = 0
}
}
break
}
const fromCode = from.charCodeAt(fromStart + i)
const toCode = to.charCodeAt(toStart + i)
if (fromCode !== toCode) break
else if (isPosixSeparator(fromCode)) lastCommonSep = i
}
let out = ''
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || isPosixSeparator(from.charCodeAt(i))) {
out += out.length === 0 ? '..' : '/..'
}
}
if (out.length > 0) return out + to.slice(toStart + lastCommonSep)
let start = toStart + lastCommonSep
if (isPosixSeparator(to.charCodeAt(start))) ++start
return to.slice(start)
}
// Longest common path prefix across `paths`, comparing "/"-separated segments.
function commonPath(paths: string[]): string {
const [first = '', ...rest] = paths
const parts = first.split('/')
let endOfPrefix = parts.length
let append = ''
for (const p of rest) {
const compare = p.split('/')
if (compare.length <= endOfPrefix) {
endOfPrefix = compare.length
append = ''
}
for (let i = 0; i < endOfPrefix; i++) {
if (compare[i] !== parts[i]) {
endOfPrefix = i
append = i === 0 ? '' : '/'
break
}
}
}
return parts.slice(0, endOfPrefix).join('/') + append
}
export const getFallbackImportMapPath = (files: Omit<FileData, 'id' | 'content' | 'state'>[]) => {
// 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<FileData, 'id' | 'content' | 'state'>[]) => {
// 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') || name.endsWith('.jsx') || name.endsWith('.tsx')
)
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<FileData, 'id' | 'content' | 'state'>[]) => {
return files
.filter(({ name }) => !name.match(/\.(js|ts|jsx|tsx|json|wasm)$/i))
.map(({ name }) => name)
}
// Finds the body file the entrypoint refers to: any file whose path is a trailing path of the
// entrypoint. When several match (e.g. `index.ts` and `functions/hello/index.ts` for an entrypoint
// ending in `functions/hello/index.ts`), the one closest to the root wins.
function findEntrypointFileName(entrypoint: string, fileNames: string[]): string | undefined {
const depth = (name: string) => name.split('/').length
return fileNames
.filter((name) => entrypoint === name || entrypoint.endsWith(`/${name}`))
.sort((a, b) => depth(a) - depth(b))[0]
}
function getBasePath(entrypoint: string | undefined, fileNames: string[]): string {
if (!entrypoint) {
return '/'
}
let candidate = findEntrypointFileName(entrypoint, fileNames)
if (candidate) {
return dirname(candidate)
} else {
try {
return dirname(new URL(entrypoint).pathname)
} catch (e) {
console.error('Failed to parse entrypoint', entrypoint)
return '/'
}
}
}
export const formatFunctionBodyToFiles = ({
functionBody,
entrypointPath,
}: {
functionBody: EdgeFunctionBodyData
entrypointPath?: string
}) => {
const entrypoint_path = functionBody.metadata?.deno2_entrypoint_path ?? entrypointPath
// Set files from API response when available
if (entrypoint_path) {
const base_path = getBasePath(
entrypoint_path,
functionBody.files.map((file) => file.name)
)
const filesWithRelPath = functionBody.files
// set file paths relative to entrypoint
.map((file: { name: string; content: string }) => {
try {
// if the current file and base path doesn't share a common path,
// return unmodified file
const common_path = commonPath([base_path, file.name])
if (common_path === '' || common_path === '/tmp/') {
return file
}
// prepend "/" to turn relative paths to absolute
file.name = relative('/' + base_path, '/' + file.name)
return file
} catch (e) {
console.error(e)
// return unmodified file
return file
}
})
// sort by displayed (relative) name before assigning ids, so ids follow list order
const sortedFiles = [...filesWithRelPath].sort((a, b) =>
a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' })
)
return sortedFiles.map((file: { name: string; content: string }, index: number) => {
return {
id: index + 1,
name: file.name,
content: file.content,
state: 'unchanged',
} as FileData
})
}
return []
}
// Picks the file to open by default: the function's entrypoint, then `index.ts`, then the first file.
export const getDefaultSelectedFileId = (
files: Pick<FileData, 'id' | 'name'>[],
entrypointPath?: string | null
): number | undefined => {
const entrypointName = entrypointPath?.split('/').pop()
const entrypointFile = entrypointName
? files.find((file) => file.name === entrypointName)
: undefined
return (entrypointFile ?? files.find((file) => file.name === 'index.ts') ?? files[0])?.id
}
type FunctionZipFile = { name: string; content: string | Uint8Array<ArrayBuffer> }
// Resolves `.`, empty (e.g. from a leading `/`) and inner `..` segments, so the only `..` left are
// leading ones that reach above the base, e.g. `a/../../b` becomes `../b`.
const normalizePathSegments = (path: string): string[] =>
path.split(/[\\/]/).reduce<string[]>((segments, segment) => {
if (segment === '' || segment === '.') return segments
if (segment === '..' && segments.length > 0 && segments[segments.length - 1] !== '..') {
return segments.slice(0, -1)
}
return [...segments, segment]
}, [])
// Decides where each function file lands inside the downloaded ZIP. Paths are normalized so no
// entry can escape the extraction folder, and files that reach above the base (`../_shared`) are
// kept in place by nesting everything else under `src/`.
// - `multipart`: names include the deploy path, so they're first made relative to the function slug.
// - `eszip`: names are already relative to the function root. Running slug-relative logic on them
// would drop folders that happen to share the slug's name.
export const getFunctionZipEntries = ({
files,
slug,
source,
}: {
files: FunctionZipFile[]
slug: string
source: 'multipart' | 'eszip'
}): { path: string; content: string | Uint8Array<ArrayBuffer> }[] => {
const relativeNames = files.map(({ name }) => {
if (source === 'eszip') return normalizePathSegments(name)
const nameSections = name.split('/')
const slugIndex = nameSections.indexOf(slug)
return normalizePathSegments(nameSections.slice(slugIndex + 1).join('/'))
})
const countParentDirs = (segments: string[]) => {
const firstRealSegment = segments.findIndex((segment) => segment !== '..')
return firstRealSegment === -1 ? segments.length : firstRealSegment
}
// The deepest `../` reach decides how many `src` levels are needed to keep files in place
const maxDepth = Math.max(0, ...relativeNames.map(countParentDirs))
// The generated `src` folders must not share a name with a real top-level folder, otherwise
// e.g. `hello/index.ts` and `hello/../src/index.ts` would both end up at `src/index.ts`
const takenNames = new Set(relativeNames.map((segments) => segments[countParentDirs(segments)]))
const baseDirNames = Array.from({ length: maxDepth }, (_, i) => {
let name = i === 0 ? 'src' : `src${i}`
while (takenNames.has(name)) name += '_'
return name
})
return files.map(({ content }, index) => {
const segments = relativeNames[index]
const parentDirCount = countParentDirs(segments)
const remainingSegments = segments.slice(parentDirCount)
const depthFromBase = maxDepth - parentDirCount
const baseDirs = baseDirNames.slice(0, Math.max(depthFromBase, 0))
return { path: [...baseDirs, ...remainingSegments].join('/'), content }
})
}