From 1784fba03c5b2352f72b223fe18cf22e5af2844b Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 30 Nov 2026 15:02:09 +0000 Subject: [PATCH 1/3] perf: serve compact file tree slices from /api/registry/files --- nuxt.config.ts | 5 +- server/api/registry/files/[...pkg].get.ts | 99 +++-- server/utils/file-tree.ts | 359 +++++++++++++++++- shared/schemas/package.ts | 33 +- shared/types/npm-registry.ts | 29 +- test/e2e/cache-control.spec.ts | 35 ++ test/unit/config/route-rules.spec.ts | 4 + test/unit/nuxt-config.spec.ts | 3 +- .../server/api/registry/files/pkg.get.spec.ts | 223 +++++++++++ test/unit/server/utils/file-tree.spec.ts | 336 +++++++++++++++- 10 files changed, 1037 insertions(+), 89 deletions(-) create mode 100644 test/unit/server/api/registry/files/pkg.get.spec.ts diff --git a/nuxt.config.ts b/nuxt.config.ts index 91ff8abc15..cbb088d2fb 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -151,10 +151,7 @@ export default defineNuxtConfig({ isr: { expiration: false, allowQuery: [] }, cache: { maxAge: 365 * 24 * 60 * 60 }, }, - '/api/registry/files/**': { - isr: { expiration: false, allowQuery: [] }, - cache: { maxAge: 365 * 24 * 60 * 60 }, - }, + '/api/registry/files/**': { isr: false }, '/api/registry/package-meta/**': { isr: { expiration: 300, allowQuery: [] } }, '/api/registry/install-size/**': { isr: { diff --git a/server/api/registry/files/[...pkg].get.ts b/server/api/registry/files/[...pkg].get.ts index 6bde6a8566..fec04c820b 100644 --- a/server/api/registry/files/[...pkg].get.ts +++ b/server/api/registry/files/[...pkg].get.ts @@ -1,50 +1,65 @@ import * as v from 'valibot' -import { PackageVersionQuerySchema } from '#shared/schemas/package' +import { PackageFileTreeQuerySchema } from '#shared/schemas/package' +import { isExactVersion } from '#shared/utils/npm' + +const CACHE_CONTROL_IMMUTABLE = + 'public, max-age=0, s-maxage=31536000, stale-while-revalidate=31536000' +const CACHE_CONTROL_MUTABLE_VERSION = 'public, max-age=0, s-maxage=300' + +function normalizeDirParam(value: unknown): unknown { + if (typeof value !== 'string') return value + const trimmed = value.replace(/\/+$/, '') + return trimmed === '' ? undefined : trimmed +} /** - * Returns the file tree for a package version. + * Returns a compact file tree slice for a package version. * * URL patterns: - * - /api/registry/files/packageName/v/1.2.3 - required version + * - /api/registry/files/packageName/v/1.2.3 - root directory (or full tree for small packages) * - /api/registry/files/@scope/packageName/v/1.2.3 - scoped package + * + * Query parameters: + * - dir: return immediate children of a specific directory + * - expand: return the root tree with ancestor directories expanded down to this directory */ -export default defineCachedEventHandler( - async event => { - // Parse package name and version from URL segments - // Patterns: [pkg, 'v', version] or [@scope, pkg, 'v', version] - const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? [] - - const { rawPackageName, rawVersion } = parsePackageParams(pkgParamSegments) - - try { - const { packageName, version } = v.parse(PackageVersionQuerySchema, { - packageName: rawPackageName, - version: rawVersion, - }) - - const jsDelivrData = await fetchFileTree(packageName, version) - const tree = withoutFileHashes(convertToFileTree(jsDelivrData.files)) - - return { - package: packageName, - version, - default: jsDelivrData.default ?? undefined, - tree, - } satisfies PackageFileTreeResponse - } catch (error: unknown) { - handleApiError(error, { - statusCode: 502, - message: ERROR_FILE_LIST_FETCH_FAILED, - }) +export default defineEventHandler(async event => { + const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? [] + const { rawPackageName, rawVersion } = parsePackageParams(pkgParamSegments) + const query = getQuery(event) + + try { + const { packageName, version, dir, expand } = v.parse(PackageFileTreeQuerySchema, { + packageName: rawPackageName, + version: rawVersion, + dir: normalizeDirParam(query.dir), + expand: normalizeDirParam(query.expand), + }) + + const jsDelivrData = await fetchFileTree(packageName, version) + const tree = buildFileTreeSlice(jsDelivrData.files, { dir, expand }) + + if (!tree) { + throw createError({ statusCode: 404, message: 'Directory not found' }) } - }, - { - // Files for a specific version never change - cache permanently - maxAge: CACHE_MAX_AGE_ONE_YEAR, // 1 year - swr: true, - getKey: event => { - const pkg = getRouterParam(event, 'pkg') ?? '' - return `files:v3:${pkg.replace(/\/+$/, '').trim()}` - }, - }, -) + + setHeader( + event, + 'Cache-Control', + isExactVersion(version) ? CACHE_CONTROL_IMMUTABLE : CACHE_CONTROL_MUTABLE_VERSION, + ) + + return { + package: packageName, + version, + default: jsDelivrData.default ?? undefined, + tree, + } satisfies PackageFileTreeWireResponse + } catch (error: unknown) { + setHeader(event, 'Cache-Control', 'no-cache') + handleApiError(error, { + statusCode: 502, + message: ERROR_FILE_LIST_FETCH_FAILED, + }) + } +}) diff --git a/server/utils/file-tree.ts b/server/utils/file-tree.ts index 06e6d5594a..82c35f725d 100644 --- a/server/utils/file-tree.ts +++ b/server/utils/file-tree.ts @@ -1,18 +1,121 @@ +import type { ExtendedPackageJson, TypesPackageInfo } from '#shared/utils/package-analysis' +import { Buffer } from 'node:buffer' import { getLatestVersion } from 'fast-npm-meta' import { flattenFileTree } from '#server/utils/import-resolver' -import type { ExtendedPackageJson, TypesPackageInfo } from '#shared/utils/package-analysis' -/** - * Fetch the file tree from jsDelivr API. - * Returns a nested tree structure of all files in the package. - */ -export async function fetchFileTree( +export const FILE_TREE_CACHE_MAX_BYTES = 8 * 1024 * 1024 +export const FILE_TREE_CACHE_MAX_ENTRIES = 32 +export const FILE_TREE_CACHE_TTL_MS = 5 * 60 * 1000 +const FILE_TREE_FETCH_TIMEOUT_MS = 15_000 + +interface CachedFileTreeEntry { + data: JsDelivrPackageResponse + bytes: number + expiresAt: number +} + +const fileTreeCache = new Map() +const inFlightFileTreeFetches = new Map>() +let fileTreeCacheBytes = 0 + +function pruneExpiredCacheEntries(now: number): void { + for (const [key, entry] of fileTreeCache) { + if (entry.expiresAt <= now) { + fileTreeCache.delete(key) + fileTreeCacheBytes -= entry.bytes + } + } +} + +function getCachedFileTree(key: string): JsDelivrPackageResponse | undefined { + const entry = fileTreeCache.get(key) + if (!entry) return undefined + + if (entry.expiresAt <= Date.now()) { + fileTreeCache.delete(key) + fileTreeCacheBytes -= entry.bytes + return undefined + } + + fileTreeCache.delete(key) + fileTreeCache.set(key, entry) + return entry.data +} + +function setCachedFileTree(key: string, data: JsDelivrPackageResponse, bytes: number): void { + if (bytes > FILE_TREE_CACHE_MAX_BYTES) return + + const now = Date.now() + pruneExpiredCacheEntries(now) + + const existing = fileTreeCache.get(key) + if (existing) { + fileTreeCache.delete(key) + fileTreeCacheBytes -= existing.bytes + } + + while ( + (fileTreeCacheBytes + bytes > FILE_TREE_CACHE_MAX_BYTES || + fileTreeCache.size >= FILE_TREE_CACHE_MAX_ENTRIES) && + fileTreeCache.size > 0 + ) { + const oldestKey = fileTreeCache.keys().next().value + if (oldestKey === undefined) break + const oldest = fileTreeCache.get(oldestKey) + fileTreeCache.delete(oldestKey) + if (oldest) { + fileTreeCacheBytes -= oldest.bytes + } + } + + fileTreeCache.set(key, { + data, + bytes, + expiresAt: now + FILE_TREE_CACHE_TTL_MS, + }) + fileTreeCacheBytes += bytes +} + +export function clearFileTreeCache(): void { + fileTreeCache.clear() + inFlightFileTreeFetches.clear() + fileTreeCacheBytes = 0 +} + +function createAbortError(): Error { + const error = new Error('The operation was aborted') + error.name = 'AbortError' + return error +} + +function raceWithSignal(promise: Promise, signal?: AbortSignal): Promise { + if (!signal) return promise + if (signal.aborted) { + return Promise.reject(createAbortError()) + } + + return new Promise((resolve, reject) => { + const onAbort = () => reject(createAbortError()) + signal.addEventListener('abort', onAbort, { once: true }) + promise.then( + value => { + signal.removeEventListener('abort', onAbort) + resolve(value) + }, + error => { + signal.removeEventListener('abort', onAbort) + reject(error) + }, + ) + }) +} + +async function fetchFileTreeUncached( packageName: string, version: string, - signal?: AbortSignal, -): Promise { +): Promise<{ data: JsDelivrPackageResponse; bytes: number }> { const url = `https://data.jsdelivr.com/v1/packages/npm/${packageName}@${version}` - const response = await fetch(url, { signal }) + const response = await fetch(url, { signal: AbortSignal.timeout(FILE_TREE_FETCH_TIMEOUT_MS) }) if (!response.ok) { if (response.status === 404) { @@ -21,7 +124,54 @@ export async function fetchFileTree( throw createError({ statusCode: 502, message: 'Failed to fetch file list from jsDelivr' }) } - return response.json() + if (typeof response.text === 'function') { + const text = await response.text() + return { + data: JSON.parse(text) as JsDelivrPackageResponse, + bytes: Buffer.byteLength(text, 'utf8'), + } + } + + const data = (await response.json()) as JsDelivrPackageResponse + return { + data, + bytes: Buffer.byteLength(JSON.stringify(data), 'utf8'), + } +} + +/** + * Fetch the file tree from jsDelivr API, sharing a byte- and TTL-bounded in-memory LRU cache + * across slices and callers while preserving per-call `AbortSignal` cancellation. + */ +export function fetchFileTree( + packageName: string, + version: string, + signal?: AbortSignal, +): Promise { + if (signal?.aborted) { + return Promise.reject(createAbortError()) + } + + const key = `${packageName}@${version}` + const cached = getCachedFileTree(key) + if (cached) { + return Promise.resolve(cached) + } + + let pending = inFlightFileTreeFetches.get(key) + if (!pending) { + pending = fetchFileTreeUncached(packageName, version) + .then(({ data, bytes }) => { + setCachedFileTree(key, data, bytes) + return data + }) + .finally(() => { + inFlightFileTreeFetches.delete(key) + }) + inFlightFileTreeFetches.set(key, pending) + } + + return raceWithSignal(pending, signal) } /** @@ -69,13 +219,190 @@ export function convertToFileTree( } /** - * Remove file hashes from a tree. The code browser does not use them and they do not compress. + * Maximum total nodes in a tree or subtree to inline completely in a single `/api/registry/files` response. */ -export function withoutFileHashes(tree: PackageFileTree[]): PackageFileTree[] { - return tree.map(node => { - const { hash: _, children, ...rest } = node - return children ? { ...rest, children: withoutFileHashes(children) } : rest - }) +const INLINE_TREE_NODE_LIMIT = 100 + +function compareTreeNodes( + a: { type: 'file' | 'directory'; name: string }, + b: { type: 'file' | 'directory'; name: string }, +): number { + if (a.type !== b.type) { + return a.type === 'directory' ? -1 : 1 + } + return a.name.localeCompare(b.name) +} + +function computeSubtreeSize(nodes: JsDelivrFileNode[]): number { + let total = 0 + for (const node of nodes) { + if (node.type === 'directory') { + if (node.files) { + total += computeSubtreeSize(node.files) + } + } else { + total += node.size ?? 0 + } + } + return total +} + +function countNodesUpTo(nodes: JsDelivrFileNode[], limit: number, current: number = 0): number { + let count = current + for (const node of nodes) { + count++ + if (count > limit) { + return count + } + if (node.type === 'directory' && node.files) { + count = countNodesUpTo(node.files, limit, count) + if (count > limit) { + return count + } + } + } + return count +} + +function findJsDelivrDirectory( + nodes: JsDelivrFileNode[], + dirPath: string, +): JsDelivrFileNode | null { + let current: JsDelivrFileNode[] | undefined = nodes + let found: JsDelivrFileNode | undefined + + for (const part of dirPath.split('/')) { + found = current?.find(node => node.name === part && node.type === 'directory') + if (!found) { + return null + } + current = found.files + } + + return found ?? null +} + +function serializeWireNodes( + nodes: JsDelivrFileNode[], + recursive: boolean, +): PackageFileTreeWireNode[] { + const result: PackageFileTreeWireNode[] = [] + + for (const node of nodes) { + if (node.type === 'directory') { + const childNodes = node.files ?? [] + if (recursive || childNodes.length === 0) { + const children = serializeWireNodes(childNodes, recursive) + result.push({ + name: node.name, + type: 'directory', + size: children.reduce((total, child) => total + (child.size ?? 0), 0), + children, + }) + } else { + result.push({ + name: node.name, + type: 'directory', + size: computeSubtreeSize(childNodes), + }) + } + } else { + result.push({ + name: node.name, + type: 'file', + size: node.size, + }) + } + } + + result.sort(compareTreeNodes) + return result +} + +function serializeExpandedChain( + nodes: JsDelivrFileNode[], + chainParts: string[], + depth: number, + inlineLimit: number, +): PackageFileTreeWireNode[] { + const result: PackageFileTreeWireNode[] = [] + + for (const node of nodes) { + if (node.type === 'directory') { + const childNodes = node.files ?? [] + if (depth < chainParts.length && node.name === chainParts[depth]) { + const children = + depth === chainParts.length - 1 + ? serializeWireNodes(childNodes, countNodesUpTo(childNodes, inlineLimit) <= inlineLimit) + : serializeExpandedChain(childNodes, chainParts, depth + 1, inlineLimit) + result.push({ + name: node.name, + type: 'directory', + size: children.reduce((total, child) => total + (child.size ?? 0), 0), + children, + }) + } else if (childNodes.length === 0) { + result.push({ + name: node.name, + type: 'directory', + size: 0, + children: [], + }) + } else { + result.push({ + name: node.name, + type: 'directory', + size: computeSubtreeSize(childNodes), + }) + } + } else { + result.push({ + name: node.name, + type: 'file', + size: node.size, + }) + } + } + + result.sort(compareTreeNodes) + return result +} + +/** + * Build a compact wire slice of a jsDelivr file tree, omitting `hash` and `path`. + * Returns `null` when the requested `dir` or `expand` directory does not exist. + */ +export function buildFileTreeSlice( + nodes: JsDelivrFileNode[], + options: { + dir?: string + expand?: string + inlineLimit?: number + } = {}, +): PackageFileTreeWireNode[] | null { + const inlineLimit = options.inlineLimit ?? INLINE_TREE_NODE_LIMIT + + if (options.dir) { + const target = findJsDelivrDirectory(nodes, options.dir) + if (!target) { + return null + } + const childNodes = target.files ?? [] + return serializeWireNodes(childNodes, countNodesUpTo(childNodes, inlineLimit) <= inlineLimit) + } + + if (options.expand) { + const target = findJsDelivrDirectory(nodes, options.expand) + if (!target) { + return null + } + if (countNodesUpTo(nodes, inlineLimit) <= inlineLimit) { + return serializeWireNodes(nodes, true) + } + return serializeExpandedChain(nodes, options.expand.split('/'), 0, inlineLimit) + } + + return serializeWireNodes(nodes, countNodesUpTo(nodes, inlineLimit) <= inlineLimit) } /** diff --git a/shared/schemas/package.ts b/shared/schemas/package.ts index c562dd2670..49ff2abc7e 100644 --- a/shared/schemas/package.ts +++ b/shared/schemas/package.ts @@ -53,13 +53,36 @@ export const PackageRouteParamsSchema = v.object({ version: v.optional(VersionSchema), }) +export const MAX_DIRECTORY_PATH_LENGTH = 512 +export const MAX_DIRECTORY_PATH_SEGMENTS = 32 + +const DirectoryPathSchema = v.pipe( + FilePathSchema, + v.maxLength(MAX_DIRECTORY_PATH_LENGTH, 'Directory path is too long'), + v.check(input => { + const segments = input.split('/') + return ( + segments.length <= MAX_DIRECTORY_PATH_SEGMENTS && + segments.every(segment => segment.length > 0 && segment !== '.') + ) + }, 'Invalid directory path'), +) + /** - * Schema for package fetching where packageName and version are required + * Schema for file tree slice query parameters (`dir` and `expand` are mutually exclusive) */ -export const PackageVersionQuerySchema = v.object({ - packageName: PackageNameSchema, - version: VersionSchema, -}) +export const PackageFileTreeQuerySchema = v.pipe( + v.object({ + packageName: PackageNameSchema, + version: VersionSchema, + dir: v.optional(DirectoryPathSchema), + expand: v.optional(DirectoryPathSchema), + }), + v.check( + input => !(input.dir && input.expand), + 'Query parameters "dir" and "expand" cannot be used together', + ), +) /** * Schema for file fetching where version and filePath are required diff --git a/shared/types/npm-registry.ts b/shared/types/npm-registry.ts index 5b61654918..dc25ea88d5 100644 --- a/shared/types/npm-registry.ts +++ b/shared/types/npm-registry.ts @@ -377,10 +377,27 @@ export interface PackageFileTree { hash?: string /** Node size in bytes (file size or recursive directory total) */ size?: number - /** Child nodes (only for directories) */ + /** Child nodes (only for directories; undefined when not yet loaded) */ children?: PackageFileTree[] } +/** + * Compact tree node returned by `/api/registry/files/**`. + * `path` is omitted on the wire and reconstructed from tree position on the client. + */ +export interface PackageFileTreeWireNode { + /** File or directory name */ + name: string + /** Optional full path; omitted on the wire by `/api/registry/files/**` */ + path?: string + /** Node type */ + type: 'file' | 'directory' + /** Node size in bytes (file size or recursive directory total) */ + size?: number + /** Child nodes (only for directories; omitted when not yet loaded) */ + children?: PackageFileTreeWireNode[] +} + /** * Response from file tree API */ @@ -391,6 +408,16 @@ export interface PackageFileTreeResponse { tree: PackageFileTree[] } +/** + * Wire response from `/api/registry/files/**` + */ +export interface PackageFileTreeWireResponse { + package: string + version: string + default?: string + tree: PackageFileTreeWireNode[] +} + /** * Response from file content API */ diff --git a/test/e2e/cache-control.spec.ts b/test/e2e/cache-control.spec.ts index 152b9fb114..be75c0d19e 100644 --- a/test/e2e/cache-control.spec.ts +++ b/test/e2e/cache-control.spec.ts @@ -91,4 +91,39 @@ test.describe('cache control', () => { expect(response.headers()['cache-control']).not.toMatch(/\bs-maxage=/) }) } + + const files = '/api/registry/files/empathic/v/2.0.0' + + test(`caches ${files} at the CDN for a year`, async ({ page }) => { + const response = await page.request.get(files) + + expect(response.status()).toBe(200) + expect(response.headers()['cache-control']).toBe( + 'public, max-age=0, s-maxage=31536000, stale-while-revalidate=31536000', + ) + expect(response.headers()['set-cookie']).toBeUndefined() + expect(response.headers()['vary']).toBeUndefined() + }) + + for (const version of ['latest', '2', '2.0']) { + test(`gives file tree ${version} the short TTL instead of the immutable one`, async ({ + page, + }) => { + const response = await page.request.get(`/api/registry/files/empathic/v/${version}`) + + expect(response.status()).toBe(200) + expect(response.headers()['cache-control']).toBe('public, max-age=0, s-maxage=300') + }) + } + + for (const version of ['2.0.0', 'latest']) { + test(`does not cache a missing directory in ${version} at the CDN`, async ({ page }) => { + const response = await page.request.get( + `/api/registry/files/empathic/v/${version}?dir=does/not/exist`, + ) + + expect(response.status()).toBe(404) + expect(response.headers()['cache-control']).not.toMatch(/\bs-maxage=/) + }) + } }) diff --git a/test/unit/config/route-rules.spec.ts b/test/unit/config/route-rules.spec.ts index 338d73c49a..0f5d273685 100644 --- a/test/unit/config/route-rules.spec.ts +++ b/test/unit/config/route-rules.spec.ts @@ -71,6 +71,10 @@ const QUERY_HANDLERS: Record = { rule: '/api/registry/downloads/**', query: ['mode', 'filterOldVersions', 'filterThreshold', 'packages'], }, + 'server/api/registry/files/[...pkg].get.ts': { + rule: '/api/registry/files/**', + query: ['dir', 'expand'], + }, 'server/api/registry/image-proxy/index.get.ts': { rule: '/api/registry/image-proxy', query: ['url', 'sig'], diff --git a/test/unit/nuxt-config.spec.ts b/test/unit/nuxt-config.spec.ts index 6bcbda7458..9f9efefa18 100644 --- a/test/unit/nuxt-config.spec.ts +++ b/test/unit/nuxt-config.spec.ts @@ -7,7 +7,8 @@ const { routeRules } = (await import('../../nuxt.config')).default as unknown as } describe('route rules', () => { - it('takes the package file route off ISR without a cache-control header route', () => { + it('takes the package file routes off ISR without a cache-control header route', () => { expect(routeRules['/api/registry/file/**']).toEqual({ isr: false }) + expect(routeRules['/api/registry/files/**']).toEqual({ isr: false }) }) }) diff --git a/test/unit/server/api/registry/files/pkg.get.spec.ts b/test/unit/server/api/registry/files/pkg.get.spec.ts new file mode 100644 index 0000000000..1346a8ebcd --- /dev/null +++ b/test/unit/server/api/registry/files/pkg.get.spec.ts @@ -0,0 +1,223 @@ +import { afterAll, beforeEach, describe, expect, it, vi } from 'vite-plus/test' +import { createError, type H3Event } from 'h3' +import { handleApiError } from '#server/utils/error-handler' +import { buildFileTreeSlice, clearFileTreeCache, fetchFileTree } from '#server/utils/file-tree' +import { parsePackageParams } from '#server/utils/parse-package-params' +import { MAX_DIRECTORY_PATH_LENGTH, MAX_DIRECTORY_PATH_SEGMENTS } from '#shared/schemas/package' +import type { JsDelivrFileNode, JsDelivrPackageResponse } from '#shared/types' + +const upstreamFetchMock = vi.fn() +const setHeaderMock = vi.fn() + +vi.stubGlobal('fetch', upstreamFetchMock) +vi.stubGlobal('fetchFileTree', fetchFileTree) +vi.stubGlobal('buildFileTreeSlice', buildFileTreeSlice) +vi.stubGlobal('parsePackageParams', parsePackageParams) +vi.stubGlobal('handleApiError', handleApiError) +vi.stubGlobal('createError', createError) +vi.stubGlobal('setHeader', setHeaderMock) +vi.stubGlobal('ERROR_FILE_LIST_FETCH_FAILED', 'Failed to fetch file list') +vi.stubGlobal('defineEventHandler', (fn: Function) => fn) + +let routerParam: string | undefined +let queryParams: Record = {} + +vi.stubGlobal('getRouterParam', () => routerParam) +vi.stubGlobal('getQuery', () => queryParams) + +const handler = (await import('#server/api/registry/files/[...pkg].get')).default +const fakeEvent = {} as H3Event + +function makeLargeJsDelivrResponse(): JsDelivrPackageResponse { + const manyFiles: JsDelivrFileNode[] = Array.from({ length: 120 }, (_, i) => ({ + type: 'file', + name: `file-${i}.js`, + hash: `hash-${i}`, + size: 10, + })) + + return { + type: 'npm', + name: 'big-pkg', + version: '1.0.0', + default: '/index.js', + files: [ + { type: 'file', name: 'index.js', hash: 'root-hash', size: 100 }, + { + type: 'directory', + name: 'lib', + files: [ + { type: 'directory', name: 'aws', files: manyFiles }, + { + type: 'directory', + name: 'other', + files: [{ type: 'file', name: 'a.js', hash: 'a-hash', size: 5 }], + }, + ], + }, + ], + } +} + +afterAll(() => { + vi.unstubAllGlobals() +}) + +describe('files API', () => { + beforeEach(() => { + vi.clearAllMocks() + clearFileTreeCache() + routerParam = 'big-pkg/v/1.0.0' + queryParams = {} + upstreamFetchMock.mockResolvedValue({ + ok: true, + json: async () => makeLargeJsDelivrResponse(), + }) + }) + + it('returns only the root level without hash or path and sets CDN-cached revalidating Cache-Control', async () => { + const result = await handler(fakeEvent) + + expect(result).toEqual({ + package: 'big-pkg', + version: '1.0.0', + default: '/index.js', + tree: [ + { name: 'lib', type: 'directory', size: 1205 }, + { name: 'index.js', type: 'file', size: 100 }, + ], + }) + expect(setHeaderMock).toHaveBeenCalledWith( + fakeEvent, + 'Cache-Control', + 'public, max-age=0, s-maxage=31536000, stale-while-revalidate=31536000', + ) + }) + + it.each(['latest', '2', '2.0'])( + 'uses the short CDN TTL for non-exact version %s', + async version => { + routerParam = `big-pkg/v/${version}` + + await handler(fakeEvent) + + expect(setHeaderMock).toHaveBeenCalledWith( + fakeEvent, + 'Cache-Control', + 'public, max-age=0, s-maxage=300', + ) + }, + ) + + it('returns only immediate children for a dir query, stripping trailing slashes', async () => { + queryParams = { dir: 'lib/' } + + const result = await handler(fakeEvent) + + expect(result).toEqual({ + package: 'big-pkg', + version: '1.0.0', + default: '/index.js', + tree: [ + { name: 'aws', type: 'directory', size: 1200 }, + { name: 'other', type: 'directory', size: 5 }, + ], + }) + }) + + it.each(['/', '///'])('treats dir %s as the root listing', async dir => { + queryParams = { dir } + + expect(await handler(fakeEvent)).toEqual({ + package: 'big-pkg', + version: '1.0.0', + default: '/index.js', + tree: [ + { name: 'lib', type: 'directory', size: 1205 }, + { name: 'index.js', type: 'file', size: 100 }, + ], + }) + }) + + it('returns an ancestor-expanded tree for an expand query', async () => { + queryParams = { expand: 'lib/other' } + + const result = await handler(fakeEvent) + + expect(result).toEqual({ + package: 'big-pkg', + version: '1.0.0', + default: '/index.js', + tree: [ + { + name: 'lib', + type: 'directory', + size: 1205, + children: [ + { name: 'aws', type: 'directory', size: 1200 }, + { + name: 'other', + type: 'directory', + size: 5, + children: [{ name: 'a.js', type: 'file', size: 5 }], + }, + ], + }, + { name: 'index.js', type: 'file', size: 100 }, + ], + }) + }) + + it('reuses a single upstream jsDelivr fetch across multiple directory slices', async () => { + queryParams = {} + await handler(fakeEvent) + + queryParams = { dir: 'lib' } + await handler(fakeEvent) + + queryParams = { dir: 'lib/aws' } + await handler(fakeEvent) + + queryParams = { expand: 'lib/other' } + await handler(fakeEvent) + + expect(upstreamFetchMock).toHaveBeenCalledTimes(1) + }) + + it('throws 404 with Cache-Control: no-cache when the directory does not exist or is a file', async () => { + queryParams = { dir: 'nonexistent' } + await expect(handler(fakeEvent)).rejects.toMatchObject({ statusCode: 404 }) + expect(setHeaderMock).toHaveBeenLastCalledWith(fakeEvent, 'Cache-Control', 'no-cache') + + queryParams = { expand: 'index.js' } + await expect(handler(fakeEvent)).rejects.toMatchObject({ statusCode: 404 }) + expect(setHeaderMock).toHaveBeenLastCalledWith(fakeEvent, 'Cache-Control', 'no-cache') + }) + + it('sets Cache-Control: no-cache on upstream 502 errors', async () => { + upstreamFetchMock.mockResolvedValue({ ok: false, status: 500 }) + + await expect(handler(fakeEvent)).rejects.toMatchObject({ statusCode: 502 }) + expect(setHeaderMock).toHaveBeenLastCalledWith(fakeEvent, 'Cache-Control', 'no-cache') + }) + + it('rejects invalid, oversized, and over-deep paths before fetching upstream', async () => { + const tooLong = 'a'.repeat(MAX_DIRECTORY_PATH_LENGTH + 1) + const tooDeep = Array.from({ length: MAX_DIRECTORY_PATH_SEGMENTS + 1 }, () => 'a').join('/') + + queryParams = { dir: 'lib', expand: 'lib' } + await expect(handler(fakeEvent)).rejects.toMatchObject({ statusCode: 404 }) + + for (const badPath of ['../lib', '/lib', 'lib//aws', 'lib/./aws', tooLong, tooDeep]) { + queryParams = { dir: badPath } + await expect(handler(fakeEvent)).rejects.toMatchObject({ statusCode: 404 }) + expect(setHeaderMock).toHaveBeenLastCalledWith(fakeEvent, 'Cache-Control', 'no-cache') + + queryParams = { expand: badPath } + await expect(handler(fakeEvent)).rejects.toMatchObject({ statusCode: 404 }) + expect(setHeaderMock).toHaveBeenLastCalledWith(fakeEvent, 'Cache-Control', 'no-cache') + } + + expect(upstreamFetchMock).not.toHaveBeenCalled() + }) +}) diff --git a/test/unit/server/utils/file-tree.spec.ts b/test/unit/server/utils/file-tree.spec.ts index 9290a2a303..c19a38f9b5 100644 --- a/test/unit/server/utils/file-tree.spec.ts +++ b/test/unit/server/utils/file-tree.spec.ts @@ -1,10 +1,14 @@ -import { describe, expect, it, vi } from 'vite-plus/test' +import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' import type { JsDelivrFileNode, PackageFileTree } from '#shared/types' import { + buildFileTreeSlice, + clearFileTreeCache, convertToFileTree, fetchFileTree, + FILE_TREE_CACHE_MAX_BYTES, + FILE_TREE_CACHE_MAX_ENTRIES, + FILE_TREE_CACHE_TTL_MS, getPackageFileTree, - withoutFileHashes, } from '#server/utils/file-tree' const getChildren = (node?: PackageFileTree): PackageFileTree[] => node?.children ?? [] @@ -120,32 +124,173 @@ describe('convertToFileTree', () => { }) }) -describe('withoutFileHashes', () => { - it('removes hashes at every depth and keeps everything else', () => { - const tree = convertToFileTree([ - { type: 'file', name: 'index.js', hash: 'a', size: 1 }, +describe('buildFileTreeSlice', () => { + const sampleNodes: JsDelivrFileNode[] = [ + { type: 'file', name: 'index.js', hash: 'h1', size: 10 }, + { + type: 'directory', + name: 'lib', + files: [ + { + type: 'directory', + name: 'aws', + files: [ + { type: 'file', name: 's3.d.ts', hash: 'h2', size: 30 }, + { type: 'file', name: 'ec2.d.ts', hash: 'h3', size: 20 }, + ], + }, + { + type: 'directory', + name: 'stripe', + files: [{ type: 'file', name: 'client.d.ts', hash: 'h4', size: 40 }], + }, + { type: 'file', name: 'index.d.ts', hash: 'h5', size: 5 }, + ], + }, + { type: 'directory', name: 'empty', files: [] }, + ] + + it('inlines the full compact tree without hash or path when total nodes fit within inlineLimit', () => { + const slice = buildFileTreeSlice(sampleNodes, { inlineLimit: 20 }) + + expect(slice).toEqual([ + { name: 'empty', type: 'directory', size: 0, children: [] }, { + name: 'lib', type: 'directory', - name: 'dist', - files: [{ type: 'file', name: 'index.mjs', hash: 'b', size: 2 }], + size: 95, + children: [ + { + name: 'aws', + type: 'directory', + size: 50, + children: [ + { name: 'ec2.d.ts', type: 'file', size: 20 }, + { name: 's3.d.ts', type: 'file', size: 30 }, + ], + }, + { + name: 'stripe', + type: 'directory', + size: 40, + children: [{ name: 'client.d.ts', type: 'file', size: 40 }], + }, + { name: 'index.d.ts', type: 'file', size: 5 }, + ], }, + { name: 'index.js', type: 'file', size: 10 }, + ]) + }) + + it('returns only root entries when the tree exceeds inlineLimit while preserving recursive sizes', () => { + const slice = buildFileTreeSlice(sampleNodes, { inlineLimit: 2 }) + + expect(slice).toEqual([ + { name: 'empty', type: 'directory', size: 0, children: [] }, + { name: 'lib', type: 'directory', size: 95 }, + { name: 'index.js', type: 'file', size: 10 }, + ]) + }) + + it('returns only immediate children for a requested dir when its subtree exceeds inlineLimit', () => { + const slice = buildFileTreeSlice(sampleNodes, { dir: 'lib', inlineLimit: 2 }) + + expect(slice).toEqual([ + { name: 'aws', type: 'directory', size: 50 }, + { name: 'stripe', type: 'directory', size: 40 }, + { name: 'index.d.ts', type: 'file', size: 5 }, ]) + }) + + it('inlines a requested dir subtree when it fits within inlineLimit', () => { + const slice = buildFileTreeSlice(sampleNodes, { dir: 'lib', inlineLimit: 20 }) + + expect(slice).toEqual([ + { + name: 'aws', + type: 'directory', + size: 50, + children: [ + { name: 'ec2.d.ts', type: 'file', size: 20 }, + { name: 's3.d.ts', type: 'file', size: 30 }, + ], + }, + { + name: 'stripe', + type: 'directory', + size: 40, + children: [{ name: 'client.d.ts', type: 'file', size: 40 }], + }, + { name: 'index.d.ts', type: 'file', size: 5 }, + ]) + }) + + it('expands only the ancestor chain for expand and keeps sibling directories shallow', () => { + const slice = buildFileTreeSlice(sampleNodes, { expand: 'lib/aws', inlineLimit: 2 }) + + expect(slice).toEqual([ + { name: 'empty', type: 'directory', size: 0, children: [] }, + { + name: 'lib', + type: 'directory', + size: 95, + children: [ + { + name: 'aws', + type: 'directory', + size: 50, + children: [ + { name: 'ec2.d.ts', type: 'file', size: 20 }, + { name: 's3.d.ts', type: 'file', size: 30 }, + ], + }, + { name: 'stripe', type: 'directory', size: 40 }, + { name: 'index.d.ts', type: 'file', size: 5 }, + ], + }, + { name: 'index.js', type: 'file', size: 10 }, + ]) + }) + + it('omits the expanded target children when the target subtree exceeds inlineLimit', () => { + const slice = buildFileTreeSlice(sampleNodes, { expand: 'lib', inlineLimit: 2 }) - expect(withoutFileHashes(tree)).toEqual([ + expect(slice).toEqual([ + { name: 'empty', type: 'directory', size: 0, children: [] }, { - name: 'dist', - path: 'dist', + name: 'lib', type: 'directory', - size: 2, - children: [{ name: 'index.mjs', path: 'dist/index.mjs', type: 'file', size: 2 }], + size: 95, + children: [ + { name: 'aws', type: 'directory', size: 50 }, + { name: 'stripe', type: 'directory', size: 40 }, + { name: 'index.d.ts', type: 'file', size: 5 }, + ], }, - { name: 'index.js', path: 'index.js', type: 'file', size: 1 }, + { name: 'index.js', type: 'file', size: 10 }, ]) }) + + it('inlines the whole tree for expand when it fits within inlineLimit', () => { + expect(buildFileTreeSlice(sampleNodes, { expand: 'lib/aws', inlineLimit: 20 })).toEqual( + buildFileTreeSlice(sampleNodes, { inlineLimit: 20 }), + ) + }) + + it('returns null when dir or expand targets a missing path or a file', () => { + expect(buildFileTreeSlice(sampleNodes, { dir: 'missing' })).toBeNull() + expect(buildFileTreeSlice(sampleNodes, { dir: 'index.js' })).toBeNull() + expect(buildFileTreeSlice(sampleNodes, { expand: 'lib/index.d.ts' })).toBeNull() + expect(buildFileTreeSlice(sampleNodes, { expand: 'lib/missing' })).toBeNull() + }) }) describe('fetchFileTree', () => { - it('returns parsed json when response is ok', async () => { + beforeEach(() => { + clearFileTreeCache() + }) + + it('returns parsed json when response is ok and reuses cached result across calls', async () => { const body = { type: 'npm', name: 'pkg', @@ -154,22 +299,170 @@ describe('fetchFileTree', () => { files: [], } - mockFetchOk(body) + const fetchMock = mockFetchOk(body) try { - const result = await fetchFileTree('pkg', '1.0.0') - expect(result).toEqual(body) + const [first, second] = await Promise.all([ + fetchFileTree('pkg', '1.0.0'), + fetchFileTree('pkg', '1.0.0'), + ]) + const third = await fetchFileTree('pkg', '1.0.0') + expect(first).toEqual(body) + expect(second).toEqual(body) + expect(third).toEqual(body) + expect(fetchMock).toHaveBeenCalledTimes(1) } finally { vi.unstubAllGlobals() } }) - it('throws a 404 error when package is not found', async () => { - mockFetchError(404) + it('evicts least-recently-used entries when exceeding the byte or entry cap', async () => { + const halfCapText = JSON.stringify({ + type: 'npm', + name: 'large', + version: '1.0.0', + files: [{ type: 'file', name: 'x'.repeat(Math.floor(FILE_TREE_CACHE_MAX_BYTES * 0.6)) }], + }) + const fetchMock = vi.fn().mockImplementation(async () => ({ + ok: true, + text: async () => halfCapText, + })) + vi.stubGlobal('fetch', fetchMock) + + try { + await fetchFileTree('large-a', '1.0.0') + await fetchFileTree('large-b', '1.0.0') + await fetchFileTree('large-b', '1.0.0') + expect(fetchMock).toHaveBeenCalledTimes(2) + + await fetchFileTree('large-a', '1.0.0') + expect(fetchMock).toHaveBeenCalledTimes(3) + + clearFileTreeCache() + fetchMock.mockClear() + fetchMock.mockImplementation(async () => ({ + ok: true, + text: async () => '{"type":"npm","name":"small","version":"1.0.0","files":[]}', + })) + + for (let i = 0; i < FILE_TREE_CACHE_MAX_ENTRIES; i++) { + await fetchFileTree(`pkg-${i}`, '1.0.0') + } + await fetchFileTree('pkg-0', '1.0.0') + expect(fetchMock).toHaveBeenCalledTimes(FILE_TREE_CACHE_MAX_ENTRIES) + + await fetchFileTree('overflow', '1.0.0') + expect(fetchMock).toHaveBeenCalledTimes(FILE_TREE_CACHE_MAX_ENTRIES + 1) + + await fetchFileTree('pkg-0', '1.0.0') + expect(fetchMock).toHaveBeenCalledTimes(FILE_TREE_CACHE_MAX_ENTRIES + 1) + + await fetchFileTree('pkg-1', '1.0.0') + expect(fetchMock).toHaveBeenCalledTimes(FILE_TREE_CACHE_MAX_ENTRIES + 2) + } finally { + vi.unstubAllGlobals() + } + }) + + it('returns oversized trees without retaining them or evicting cached entries', async () => { + const smallText = JSON.stringify({ + type: 'npm', + name: 'small', + version: '1.0.0', + files: [], + }) + const oversizedText = JSON.stringify({ + type: 'npm', + name: 'huge', + version: '1.0.0', + files: [{ type: 'file', name: 'x'.repeat(FILE_TREE_CACHE_MAX_BYTES + 1) }], + }) + const fetchMock = vi.fn().mockImplementation(async (url: string) => ({ + ok: true, + text: async () => (url.includes('/small@') ? smallText : oversizedText), + })) + vi.stubGlobal('fetch', fetchMock) + + try { + expect(await fetchFileTree('small', '1.0.0')).toEqual(JSON.parse(smallText)) + expect(await fetchFileTree('huge', '1.0.0')).toEqual(JSON.parse(oversizedText)) + expect(await fetchFileTree('huge', '1.0.0')).toEqual(JSON.parse(oversizedText)) + expect(await fetchFileTree('small', '1.0.0')).toEqual(JSON.parse(smallText)) + expect(fetchMock).toHaveBeenCalledTimes(3) + } finally { + vi.unstubAllGlobals() + } + }) + + it('expires cached entries after the TTL window', async () => { + vi.useFakeTimers() + const fetchMock = mockFetchOk({ + type: 'npm', + name: 'pkg', + version: '1.0.0', + files: [], + }) + + try { + await fetchFileTree('pkg', '1.0.0') + vi.advanceTimersByTime(FILE_TREE_CACHE_TTL_MS - 1000) + await fetchFileTree('pkg', '1.0.0') + expect(fetchMock).toHaveBeenCalledTimes(1) + + vi.advanceTimersByTime(2000) + await fetchFileTree('pkg', '1.0.0') + expect(fetchMock).toHaveBeenCalledTimes(2) + } finally { + vi.useRealTimers() + vi.unstubAllGlobals() + } + }) + + it('shares the cache with AbortSignal callers while still honouring cancellation', async () => { + let resolveFetch!: (value: { ok: boolean; json: () => Promise }) => void + const fetchMock = vi.fn( + () => + new Promise<{ ok: boolean; json: () => Promise }>(resolve => { + resolveFetch = resolve + }), + ) + vi.stubGlobal('fetch', fetchMock) + + try { + const controller = new AbortController() + const sharedCall = fetchFileTree('pkg', '1.0.0') + const abortedCall = fetchFileTree('pkg', '1.0.0', controller.signal) + expect(fetchMock).toHaveBeenCalledTimes(1) + + controller.abort() + await expect(abortedCall).rejects.toMatchObject({ name: 'AbortError' }) + + const body = { type: 'npm', name: 'pkg', version: '1.0.0', files: [] } + resolveFetch({ ok: true, json: async () => body }) + expect(await sharedCall).toEqual(body) + + const cachedSignalCall = await fetchFileTree('pkg', '1.0.0', new AbortController().signal) + expect(cachedSignalCall).toEqual(body) + expect(fetchMock).toHaveBeenCalledTimes(1) + + const preAborted = new AbortController() + preAborted.abort() + await expect(fetchFileTree('pkg', '1.0.0', preAborted.signal)).rejects.toMatchObject({ + name: 'AbortError', + }) + } finally { + vi.unstubAllGlobals() + } + }) + + it('throws a 404 error without caching when package is not found', async () => { + const fetchMock = mockFetchError(404) mockCreateError() try { await expect(fetchFileTree('pkg', '1.0.0')).rejects.toMatchObject({ statusCode: 404 }) + await expect(fetchFileTree('pkg', '1.0.0')).rejects.toMatchObject({ statusCode: 404 }) + expect(fetchMock).toHaveBeenCalledTimes(2) } finally { vi.unstubAllGlobals() } @@ -188,6 +481,9 @@ describe('fetchFileTree', () => { }) describe('getPackageFileTree', () => { + beforeEach(() => { + clearFileTreeCache() + }) it('returns metadata and a converted tree', async () => { const body = { type: 'npm', From b08f95662326fbc599ea9dd49818d3ef73c66a1f Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 30 Nov 2026 15:02:12 +0000 Subject: [PATCH 2/3] feat: lazy-load file tree directories in the code explorer --- app/components/Code/FileTree.vue | 75 +++- app/components/Code/MobileTreeDrawer.vue | 7 + app/composables/useFileTreeState.ts | 5 + .../v/[version]/[...filePath].vue | 239 +++++++++-- app/utils/file-tree.ts | 185 +++++++++ test/e2e/package-code.spec.ts | 109 +++++ test/nuxt/components/CodeFileTree.spec.ts | 231 +++++++++++ test/nuxt/pages/PackageCodePage.spec.ts | 383 +++++++++++++++++- test/unit/app/utils/file-tree.spec.ts | 213 ++++++++++ 9 files changed, 1405 insertions(+), 42 deletions(-) create mode 100644 app/utils/file-tree.ts create mode 100644 test/unit/app/utils/file-tree.spec.ts diff --git a/app/components/Code/FileTree.vue b/app/components/Code/FileTree.vue index b2bcbf20e6..e02eb725fa 100644 --- a/app/components/Code/FileTree.vue +++ b/app/components/Code/FileTree.vue @@ -10,6 +10,11 @@ const props = defineProps<{ baseUrl: string baseRoute: Pick depth?: number + loadingDirs?: ReadonlySet +}>() + +const emit = defineEmits<{ + expandDir: [path: string] }>() const depth = computed(() => props.depth ?? 0) @@ -37,18 +42,59 @@ function getFileRoute(nodePath: string): RouteLocationRaw { const { toggleDir, isExpanded, autoExpandAncestors } = useFileTreeState(props.baseUrl) -const scrollIntoView = () => { +function expandLoadedAncestors(path: string) { + let prefix = '' + + for (const segment of path.split('/').filter(Boolean)) { + prefix = prefix ? `${prefix}/${segment}` : segment + const node = findTreeNode(props.tree, prefix) + if (!node) return + if (node.type === 'directory') { + if (node.children === undefined) return + autoExpandAncestors(prefix) + } + } +} + +function handleToggleDir(node: PackageFileTree) { + const willExpand = !isExpanded(node.path) + toggleDir(node.path) + if (willExpand && node.children === undefined) { + emit('expandDir', node.path) + } +} + +let lastScrolledPath = '' + +const scrollIntoView = (path: string) => { const el = treeRoot.value?.querySelector('[aria-current="true"]') - el?.scrollIntoView({ block: 'center', behavior: 'smooth' }) + if (el) { + lastScrolledPath = path + el.scrollIntoView({ block: 'center', behavior: 'smooth' }) + } } -// Auto-expand directories in the current path watch( - () => props.currentPath, - path => { - if (depth.value === 0 && path) { - autoExpandAncestors(path) - nextTick(scrollIntoView) + () => [props.currentPath, props.tree] as const, + ([path, nodes], previous) => { + if (depth.value === 0 && path && previous?.[0] !== path) { + expandLoadedAncestors(path) + } + + for (const node of nodes) { + if ( + node.type === 'directory' && + node.children === undefined && + isExpanded(node.path) && + !isNodeActive(node) && + !props.loadingDirs?.has(node.path) + ) { + emit('expandDir', node.path) + } + } + + if (depth.value === 0 && path && lastScrolledPath !== path) { + nextTick(() => scrollIntoView(path)) } }, { immediate: true }, @@ -64,14 +110,21 @@ watch( class="w-full justify-start! rounded-none! border-none! transition-[color,background-color]! duration-100!" block :aria-pressed="isNodeActive(node)" + :aria-busy="loadingDirs?.has(node.path) || undefined" :aria-label=" isPossiblyUnnecessaryContent(node.name, 'directory') ? `${node.name} - ${$t('code.possibly_unnecessary')}` : undefined " :style="{ paddingLeft: `${depth * 12 + 12}px` }" - @click="toggleDir(node.path)" - :classicon="isExpanded(node.path) ? 'i-lucide:chevron-down' : 'i-lucide:chevron-right'" + @click="handleToggleDir(node)" + :classicon=" + loadingDirs?.has(node.path) + ? 'i-svg-spinners:ring-resize' + : isExpanded(node.path) + ? 'i-lucide:chevron-down' + : 'i-lucide:chevron-right' + " > diff --git a/app/components/Code/MobileTreeDrawer.vue b/app/components/Code/MobileTreeDrawer.vue index dd524bf635..07cb9c96d7 100644 --- a/app/components/Code/MobileTreeDrawer.vue +++ b/app/components/Code/MobileTreeDrawer.vue @@ -6,6 +6,11 @@ defineProps<{ currentPath: string baseUrl: string baseRoute: Pick + loadingDirs?: ReadonlySet +}>() + +const emit = defineEmits<{ + expandDir: [path: string] }>() const isOpen = shallowRef(false) @@ -74,6 +79,8 @@ defineExpose({ :current-path="currentPath" :base-url="baseUrl" :base-route="baseRoute" + :loading-dirs="loadingDirs" + @expand-dir="emit('expandDir', $event)" /> diff --git a/app/composables/useFileTreeState.ts b/app/composables/useFileTreeState.ts index 7c49eac5ca..4144432e4e 100644 --- a/app/composables/useFileTreeState.ts +++ b/app/composables/useFileTreeState.ts @@ -9,6 +9,10 @@ export function useFileTreeState(baseUrl: string) { } } + function collapseDir(path: string) { + expanded.value.delete(path) + } + function isExpanded(path: string) { return expanded.value.has(path) } @@ -25,6 +29,7 @@ export function useFileTreeState(baseUrl: string) { return { toggleDir, + collapseDir, isExpanded, autoExpandAncestors, } diff --git a/app/pages/package-code/[[org]]/[packageName]/v/[version]/[...filePath].vue b/app/pages/package-code/[[org]]/[packageName]/v/[version]/[...filePath].vue index 80d9916427..1d218d7694 100644 --- a/app/pages/package-code/[[org]]/[packageName]/v/[version]/[...filePath].vue +++ b/app/pages/package-code/[[org]]/[packageName]/v/[version]/[...filePath].vue @@ -110,8 +110,50 @@ function codeVersionRoute(nextVersion: string): RouteLocationRaw { useCommandPaletteVersionCommands(commandPalettePackageContext, codeVersionRoute) // Fetch file tree -const treeRequest = useFetch( - () => `/api/registry/files/${packageName.value}/v/${version.value}`, +const filesBaseUrl = computed(() => `/api/registry/files/${packageName.value}/v/${version.value}`) +const initialExpandDir = getInitialExpandDir(filePathOrig.value) + +const loadingDirs = shallowRef(new Set()) +const inFlightDirRequests = new Map>() +const failedPathLoads = new Map() +const isLoadingPath = shallowRef(false) +const pathLoadError = shallowRef(false) + +function getErrorStatus(error: unknown): number | undefined { + if (typeof error !== 'object' || error === null) return undefined + return ( + (error as { statusCode?: number; status?: number }).statusCode ?? + (error as { status?: number }).status + ) +} + +async function fetchInitialFileTree(): Promise { + let response: PackageFileTreeWireResponse + + try { + response = await $fetch( + filesBaseUrl.value, + initialExpandDir ? { query: { expand: initialExpandDir } } : {}, + ) + } catch (error: unknown) { + if (!initialExpandDir || getErrorStatus(error) !== 404) { + throw error + } + failedPathLoads.set(`expand:${initialExpandDir}`, 'not-found') + response = await $fetch(filesBaseUrl.value) + } + + return { + package: response.package, + version: response.version, + default: response.default, + tree: hydrateFileTree(response.tree), + } +} + +const treeRequest = useAsyncData( + `file-tree:${packageName.value}@${version.value}:${initialExpandDir ?? ''}`, + fetchInitialFileTree, { immediate: !!version.value, server: false, @@ -124,33 +166,165 @@ if (useNuxtApp().isHydrating) { await Promise.all([packageRequest, treeRequest]) } -// Determine what to show based on the current path -// Note: This needs fileTree to be loaded first -const currentNode = computed(() => { - if (!fileTree.value?.tree || !filePathOrig.value) return null +function setDirLoading(dirPath: string, loading: boolean) { + const next = new Set(loadingDirs.value) + if (loading) { + next.add(dirPath) + } else { + next.delete(dirPath) + } + loadingDirs.value = next +} + +async function loadDirectory(dirPath: string): Promise { + if (!fileTree.value) return + const key = `dir:${dirPath}` + const existing = inFlightDirRequests.get(key) + if (existing) return existing + + setDirLoading(dirPath, true) + const request = $fetch(filesBaseUrl.value, { + query: { dir: dirPath }, + }) + .then(res => { + if (!fileTree.value) return + const children = hydrateFileTree(res.tree, dirPath) + fileTree.value = { + ...fileTree.value, + tree: attachDirectoryChildren(fileTree.value.tree, dirPath, children), + } + }) + .finally(() => { + inFlightDirRequests.delete(key) + setDirLoading(dirPath, false) + }) + + inFlightDirRequests.set(key, request) + return request +} + +async function expandDirectory(dirPath: string): Promise { + if (!fileTree.value) return + const key = `expand:${dirPath}` + const existing = inFlightDirRequests.get(key) + if (existing) return existing + + const request = $fetch(filesBaseUrl.value, { + query: { expand: dirPath }, + }) + .then(res => { + if (!fileTree.value) return + const incoming = hydrateFileTree(res.tree) + fileTree.value = { + ...fileTree.value, + tree: mergeFileTrees(fileTree.value.tree, incoming), + } + }) + .finally(() => { + inFlightDirRequests.delete(key) + }) + + inFlightDirRequests.set(key, request) + return request +} + +function handleExpandDir(dirPath: string) { + failedPathLoads.delete(`dir:${dirPath}`) + void loadDirectory(dirPath).catch(() => { + useFileTreeState(getCurrentCodeUrlWithPath()).collapseDir(dirPath) + }) +} + +function sliceKey(missing: MissingDirectoryFetch): string { + return `${missing.mode}:${missing.dirPath}` +} + +function nextMissingSlice(pathOrig: string): MissingDirectoryFetch | null { + const tree = fileTree.value?.tree + if (!tree) return null + const missing = resolveMissingDirectoryFetch(tree, pathOrig) + return missing && !failedPathLoads.has(sliceKey(missing)) ? missing : null +} + +async function loadMissingPath(pathOrig: string): Promise { + isLoadingPath.value = true + pathLoadError.value = false + const attempted = new Set() + let attemptKey: string | null = null + + try { + let missing = nextMissingSlice(pathOrig) + while (missing && !attempted.has(sliceKey(missing))) { + attemptKey = sliceKey(missing) + attempted.add(attemptKey) + await (missing.mode === 'dir' + ? loadDirectory(missing.dirPath) + : expandDirectory(missing.dirPath)) + missing = nextMissingSlice(pathOrig) + } - // We use original file path to correctly handle trailing slashes for file tree navigation - // - /src/index.ts - correct file path - // - /src/index.ts/ - incorrect file path (but formally can exist as a directory) - // - /src/index and /src/index/ - correct directory paths - const parts = filePathOrig.value.split('/') - let current: PackageFileTree[] | undefined = fileTree.value.tree - let lastFound: PackageFileTree | null = null - const partsLength = parts.length - - for (let i = 0; i < partsLength; i++) { - const part = parts[i] - const isLast = i === partsLength - 1 - // If the previous part is a directory and the last one is empty (like /lib/) then return the previous directory - if (!part && isLast && lastFound?.type === 'directory') return lastFound - const found: PackageFileTree | undefined = current?.find(n => n.name === part) - if (!found) return null - lastFound = found - if (found.type === 'file' && isLast) return found - current = found.children + if (attempted.size > 0 && filePathOrig.value === pathOrig) { + useFileTreeState(getCurrentCodeUrlWithPath()).autoExpandAncestors(pathOrig) + } + } catch (error: unknown) { + const kind = getErrorStatus(error) === 404 ? 'not-found' : 'error' + if (attemptKey) failedPathLoads.set(attemptKey, kind) + if (filePathOrig.value === pathOrig) pathLoadError.value = kind === 'error' + } finally { + if (filePathOrig.value === pathOrig) isLoadingPath.value = false } +} + +function retryPathLoad() { + const pathOrig = filePathOrig.value + const tree = fileTree.value?.tree + if (!pathOrig || !tree) return - return lastFound + const missing = resolveMissingDirectoryFetch(tree, pathOrig) + if (!missing) { + pathLoadError.value = false + return + } + failedPathLoads.delete(sliceKey(missing)) + void loadMissingPath(pathOrig) +} + +watch( + () => [filePathOrig.value, fileTree.value?.tree] as const, + ([pathOrig, tree], previous) => { + if (!pathOrig || !tree) { + isLoadingPath.value = false + pathLoadError.value = false + return + } + + const missing = resolveMissingDirectoryFetch(tree, pathOrig) + if (!missing) { + isLoadingPath.value = false + pathLoadError.value = false + return + } + + const attemptKey = sliceKey(missing) + if (previous?.[0] !== pathOrig && failedPathLoads.get(attemptKey) === 'error') { + failedPathLoads.delete(attemptKey) + } + + const priorFailure = failedPathLoads.get(attemptKey) + if (priorFailure) { + isLoadingPath.value = false + pathLoadError.value = priorFailure === 'error' + return + } + + void loadMissingPath(pathOrig) + }, + { immediate: true }, +) + +const currentNode = computed(() => { + if (!fileTree.value?.tree || !filePathOrig.value) return null + return findTreeNode(fileTree.value.tree, filePathOrig.value) }) const isViewingFile = computed(() => currentNode.value?.type === 'file') @@ -193,7 +367,7 @@ const { // Loading skeleton state const isLoading = computed(() => { if (!isViewingFile.value) { - return treeStatus.value !== 'success' && treeStatus.value !== 'error' + return isLoadingPath.value || (treeStatus.value !== 'success' && treeStatus.value !== 'error') } if (isFileTooLarge.value) return false @@ -488,6 +662,8 @@ useCommandPaletteContextCommands( :current-path="filePath ?? ''" :base-url="getCurrentCodeUrlWithPath()" :base-route="route" + :loading-dirs="loadingDirs" + @expand-dir="handleExpandDir" /> @@ -590,6 +766,13 @@ useCommandPaletteContextCommands( + +