···110110- We care about good types – never cast things to `any` 💪
111111- Validate rather than just assert
112112113113+### Server API patterns
114114+115115+#### Input validation with Valibot
116116+117117+Use Valibot schemas from `#shared/schemas/` to validate API inputs. This ensures type safety and provides consistent error messages:
118118+119119+```typescript
120120+import * as v from 'valibot'
121121+import { PackageRouteParamsSchema } from '#shared/schemas/package'
122122+123123+// In your handler:
124124+const { packageName, version } = v.parse(PackageRouteParamsSchema, {
125125+ packageName: rawPackageName,
126126+ version: rawVersion,
127127+})
128128+```
129129+130130+#### Error handling with `handleApiError`
131131+132132+Use the `handleApiError` utility for consistent error handling in API routes. It re-throws H3 errors (like 404s) and wraps other errors with a fallback message:
133133+134134+```typescript
135135+import { ERROR_NPM_FETCH_FAILED } from '#shared/utils/constants'
136136+137137+try {
138138+ // API logic...
139139+} catch (error: unknown) {
140140+ handleApiError(error, {
141141+ statusCode: 502,
142142+ message: ERROR_NPM_FETCH_FAILED,
143143+ })
144144+}
145145+```
146146+147147+#### URL parameter parsing with `parsePackageParams`
148148+149149+Use `parsePackageParams` to extract package name and version from URL segments:
150150+151151+```typescript
152152+const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? []
153153+const { rawPackageName, rawVersion } = parsePackageParams(pkgParamSegments)
154154+```
155155+156156+This handles patterns like `/pkg`, `/pkg/v/1.0.0`, `/@scope/pkg`, and `/@scope/pkg/v/1.0.0`.
157157+158158+#### Constants
159159+160160+Define error messages and other string constants in `#shared/utils/constants.ts` to ensure consistency across the codebase:
161161+162162+```typescript
163163+export const ERROR_NPM_FETCH_FAILED = 'Failed to fetch package from npm registry.'
164164+```
165165+113166### Import order
1141671151681. Type imports first (`import type { ... }`)