From acb5affb1bd129eb313865a2346cab480f75e809 Mon Sep 17 00:00:00 2001 From: Okiki Ojo Date: Mon, 9 Feb 2026 02:58:48 -0500 Subject: [PATCH] feat(endpoints)!: add new endpoints for bundle raw, warnings, cache management, health, and static assets Introduce several new endpoints to enhance the API functionality. The new endpoints include `/v1/bundle/raw` and `/v1/bundle/warnings` for handling raw bundle requests and warnings, respectively. Additionally, cache management endpoints such as `/v1/cache/clear` and `/v1/cache/purge` are added to facilitate cache operations. Static asset endpoints for health checks, favicons, and service workers are also included, improving the overall API usability and performance. Should verify by testing each new endpoint for expected responses and functionality. Signed-off-by: Okiki Ojo --- edge/_shared/bundle/legacy-response.ts | 227 ++++++++++++++++++ edge/_shared/bundle/parse.ts | 97 ++++++++ edge/_shared/bundle/request.ts | 123 ++++++++++ edge/_shared/bundle/schema.ts | 3 + edge/_shared/middleware/cache-control.ts | 36 +++ edge/_shared/middleware/rate-limit.ts | 10 +- edge/endpoints/badge/raster/definition.ts | 22 ++ edge/endpoints/badge/raster/handler.ts | 52 ++++ edge/endpoints/badge/svg/definition.ts | 22 ++ edge/endpoints/badge/svg/handler.ts | 110 +++------ edge/endpoints/bundle/analysis/definition.ts | 22 ++ edge/endpoints/bundle/analysis/handler.ts | 52 ++++ edge/endpoints/bundle/file/definition.ts | 22 ++ edge/endpoints/bundle/file/handler.ts | 54 +++++ edge/endpoints/bundle/metafile/definition.ts | 22 ++ edge/endpoints/bundle/metafile/handler.ts | 52 ++++ edge/endpoints/bundle/mod.ts | 49 ++++ edge/endpoints/bundle/raw/definition.ts | 22 ++ edge/endpoints/bundle/raw/handler.ts | 52 ++++ edge/endpoints/bundle/run/definition.ts | 61 ++--- edge/endpoints/bundle/run/handler.ts | 114 +++++---- edge/endpoints/bundle/warnings/definition.ts | 22 ++ edge/endpoints/bundle/warnings/handler.ts | 52 ++++ edge/endpoints/cache/clear/definition.ts | 22 ++ edge/endpoints/cache/clear/handler.ts | 55 +++++ edge/endpoints/cache/purge/definition.ts | 22 ++ edge/endpoints/cache/purge/handler.ts | 71 ++++++ edge/endpoints/health/definition.ts | 22 ++ edge/endpoints/health/handler.ts | 24 ++ edge/endpoints/legacy/routes.ts | 10 +- .../definition.ts | 22 ++ .../apple-touch-icon-precomposed/handler.ts | 23 ++ .../static/apple-touch-icon/definition.ts | 22 ++ .../static/apple-touch-icon/handler.ts | 23 ++ edge/endpoints/static/favicon/definition.ts | 22 ++ edge/endpoints/static/favicon/handler.ts | 23 ++ edge/endpoints/static/llms/definition.ts | 22 ++ edge/endpoints/static/llms/handler.ts | 23 ++ edge/endpoints/static/openapi/definition.ts | 22 ++ edge/endpoints/static/openapi/handler.ts | 32 +++ edge/endpoints/static/plugin/definition.ts | 22 ++ edge/endpoints/static/plugin/handler.ts | 32 +++ edge/endpoints/static/robots/definition.ts | 22 ++ edge/endpoints/static/robots/handler.ts | 23 ++ edge/endpoints/static/sw/definition.ts | 22 ++ edge/endpoints/static/sw/handler.ts | 23 ++ edge/index.ts | 16 +- 47 files changed, 1739 insertions(+), 179 deletions(-) create mode 100644 edge/_shared/bundle/legacy-response.ts create mode 100644 edge/_shared/bundle/request.ts create mode 100644 edge/_shared/middleware/cache-control.ts create mode 100644 edge/endpoints/badge/raster/definition.ts create mode 100644 edge/endpoints/badge/raster/handler.ts create mode 100644 edge/endpoints/badge/svg/definition.ts create mode 100644 edge/endpoints/bundle/analysis/definition.ts create mode 100644 edge/endpoints/bundle/analysis/handler.ts create mode 100644 edge/endpoints/bundle/file/definition.ts create mode 100644 edge/endpoints/bundle/file/handler.ts create mode 100644 edge/endpoints/bundle/metafile/definition.ts create mode 100644 edge/endpoints/bundle/metafile/handler.ts create mode 100644 edge/endpoints/bundle/mod.ts create mode 100644 edge/endpoints/bundle/raw/definition.ts create mode 100644 edge/endpoints/bundle/raw/handler.ts create mode 100644 edge/endpoints/bundle/warnings/definition.ts create mode 100644 edge/endpoints/bundle/warnings/handler.ts create mode 100644 edge/endpoints/cache/clear/definition.ts create mode 100644 edge/endpoints/cache/clear/handler.ts create mode 100644 edge/endpoints/cache/purge/definition.ts create mode 100644 edge/endpoints/cache/purge/handler.ts create mode 100644 edge/endpoints/health/definition.ts create mode 100644 edge/endpoints/health/handler.ts create mode 100644 edge/endpoints/static/apple-touch-icon-precomposed/definition.ts create mode 100644 edge/endpoints/static/apple-touch-icon-precomposed/handler.ts create mode 100644 edge/endpoints/static/apple-touch-icon/definition.ts create mode 100644 edge/endpoints/static/apple-touch-icon/handler.ts create mode 100644 edge/endpoints/static/favicon/definition.ts create mode 100644 edge/endpoints/static/favicon/handler.ts create mode 100644 edge/endpoints/static/llms/definition.ts create mode 100644 edge/endpoints/static/llms/handler.ts create mode 100644 edge/endpoints/static/openapi/definition.ts create mode 100644 edge/endpoints/static/openapi/handler.ts create mode 100644 edge/endpoints/static/plugin/definition.ts create mode 100644 edge/endpoints/static/plugin/handler.ts create mode 100644 edge/endpoints/static/robots/definition.ts create mode 100644 edge/endpoints/static/robots/handler.ts create mode 100644 edge/endpoints/static/sw/definition.ts create mode 100644 edge/endpoints/static/sw/handler.ts diff --git a/edge/_shared/bundle/legacy-response.ts b/edge/_shared/bundle/legacy-response.ts new file mode 100644 index 0000000..945e515 --- /dev/null +++ b/edge/_shared/bundle/legacy-response.ts @@ -0,0 +1,227 @@ +/** + * Legacy Bundle Response Builder + * + * Produces legacy response formats (HTML, JS, raw JSON, badges) from a bundle result. + * This preserves behavior for old paths like /, /file, /analysis, /warnings, /raw. + * + * Flow: + * +---------+ +-----------------+ +-------------------+ + * | Result |-->| Detect mode |-->| Format response | + * +---------+ | (badge/file/...)| | (HTML/JS/JSON) | + * +-----------------+ +-------------------+ + */ + +import type { BundleResult, BundleConfig, ModuleSpec } from './types.ts' + +import { ansi } from '@bundle/utils' +import { decodeBase64 } from '@bundle/utils/encoding' +import { getEsbuild } from '@bundle/core' + +import { generateBadge } from '../external/shields.ts' +import { getBadgeKey, generateBadgeId } from '../cache/keys.ts' +import { getCachedBadge, setCachedBadge } from '../cache/operations.ts' +import { API_DOCS } from './schema.ts' + +import styleText from '../../legacy/style.ts' + +export type LegacyResponseOptions = { + url: URL + result: BundleResult + outputText?: string + cached: boolean + durationMs: number + cacheKey: string +} + +export async function generateLegacyResponse( + options: LegacyResponseOptions +): Promise { + const { url, result, outputText, cached, durationMs, cacheKey } = options + const path = url.pathname + const noCache = ['/no-cache', '/clear-cache', '/delete-cache'].includes(path) + + const analysisQuery = + url.searchParams.has('analysis') || + url.searchParams.has('analyze') || + ['/analysis', '/analyze'].includes(path) || + path.endsWith('/analysis') || + path.endsWith('/analyze') + + const analysisResult = url.searchParams.get('analysis') || url.searchParams.get('analyze') + + const metafileQuery = url.searchParams.has('metafile') || path.endsWith('/metafile') + const fileQuery = url.searchParams.has('file') || path.endsWith('/file') + + const badgeQuery = url.searchParams.has('badge') || ['/badge', '/badge/raster', '/badge-raster'].includes(path) || path.endsWith('/badge') || path.endsWith('/badge/raster') || path.endsWith('/badge-raster') + const warningsQuery = url.searchParams.has('warnings') || url.searchParams.has('warning') || path.endsWith('/warnings') + const rawQuery = url.searchParams.has('raw') || path.endsWith('/raw') + + const badgeResult = url.searchParams.get('badge') + const badgeStyle = url.searchParams.get('badge-style') + const badgeRasterQuery = url.searchParams.has('badge-raster') || url.searchParams.has('png') || ['/badge/raster', '/badge-raster'].includes(path) || path.endsWith('/badge/raster') || path.endsWith('/badge-raster') + const query = (url.searchParams.get('q') || url.searchParams.get('query')) ?? 'spring-easing' + + if (badgeQuery) { + const keyObj = buildLegacyKeyObject(result) + const badgeKey = getBadgeKey(cacheKey) + const badgeId = generateBadgeId(keyObj, { + raster: badgeRasterQuery, + result: badgeResult, + style: badgeStyle, + }) + + const cachedBadge = await getCachedBadge(badgeKey, badgeId) + if (cachedBadge) { + return new Response(badgeRasterQuery ? decodeBase64(cachedBadge) : cachedBadge, { + status: 200, + headers: { + 'Cache-Control': 'max-age=36, public', + 'Content-Type': badgeRasterQuery ? 'image/png' : 'image/svg+xml', + }, + }) + } + + const badgeResponse = await generateBadge({ + result, + url, + detail: badgeResult, + style: badgeStyle, + raster: badgeRasterQuery, + query, + }) + + if (!badgeResponse.ok || !badgeResponse.badge) { + return new Response('Badge generation failed', { + status: badgeResponse.timeout ? 504 : 502, + headers: { + 'Content-Type': 'text/plain', + 'x-content-type-options': 'nosniff', + }, + }) + } + + if (badgeResponse.isRaster) { + const badgeBytes = badgeResponse.badge as Uint8Array + const badgeCopy = Uint8Array.from(badgeBytes) + const badgeBlob = new Blob([badgeCopy]) + + await setCachedBadge(badgeKey, badgeId, badgeResponse.base64 ?? '') + return new Response(badgeBlob, { + status: 200, + headers: { + 'Cache-Control': 'max-age=30, public', + 'Content-Type': 'image/png', + }, + }) + } + + await setCachedBadge(badgeKey, badgeId, badgeResponse.badge as string) + return new Response(badgeResponse.badge as string, { + status: 200, + headers: { + 'Cache-Control': 'max-age=30, public', + 'Content-Type': 'image/svg+xml', + }, + }) + } + + if (fileQuery) { + const fileResult = outputText ?? ' ' + return new Response(fileResult, { + status: 200, + headers: { + 'Cache-Control': `max-age=${noCache ? 30 : 720}, public`, + 'Content-Type': 'text/javascript', + }, + }) + } + + if (analysisQuery && result.metafile) { + const { analyzeMetafile } = await getEsbuild() + const verboseAnalysis = analysisResult === 'verbose' + + const analysis = await analyzeMetafile(result.metafile, { + color: true, + verbose: verboseAnalysis, + }) + + return new Response(generateHtmlMessages([ansi(analysis)]), { + status: 200, + headers: { + 'Cache-Control': `max-age=${noCache ? 30 : 180}, public`, + 'Content-Type': 'text/html', + }, + }) + } + + if (metafileQuery && result.metafile) { + return new Response(JSON.stringify(result.metafile), { + status: 200, + headers: { + 'Cache-Control': `max-age=${noCache ? 30 : 180}, public`, + 'Content-Type': 'application/json', + }, + }) + } + + if (warningsQuery) { + return new Response(generateHtmlMessages(result.warnings ?? ['No warnings for this bundle']), { + status: 200, + headers: { + 'Cache-Control': 'max-age=30, public', + 'Content-Type': 'text/html', + }, + }) + } + + if (rawQuery) { + return new Response(JSON.stringify(result), { + status: 200, + headers: { + 'Cache-Control': 'max-age=30, public', + 'Content-Type': 'application/json', + }, + }) + } + + const { metafile: _metafile, warnings: _warnings, ...usefulInfo } = result + const addDocs = url.search === '' ? API_DOCS : {} + const cachedTiming = cached ? { + time: formatDuration(durationMs), + rawTime: durationMs, + } : null + + const finalResult = Object.assign({}, usefulInfo, addDocs, cachedTiming ?? {}) + + return new Response(JSON.stringify(finalResult), { + status: 200, + headers: { + 'Cache-Control': 'max-age=720, public', + 'Content-Type': 'application/json', + }, + }) +} + +export function generateHtmlMessages(msgs: string[]): string { + return [ + ``, + `
${msgs.join('\n')}
`, + ].join('') +} + +function buildLegacyKeyObject(result: BundleResult): Record { + const config = result.config as BundleConfig + const versions = result.versions ?? (result.version ? [result.version] : []) + const modules = result.modules ?? [] as ModuleSpec[] + + return Object.assign({}, config, { + versions, + modules, + initialValue: result.input.trim(), + }) +} + +function formatDuration(ms: number): string { + const seconds = ms / 1000 + return `${seconds.toFixed(1)}s` +} diff --git a/edge/_shared/bundle/parse.ts b/edge/_shared/bundle/parse.ts index d68f101..60dc2db 100644 --- a/edge/_shared/bundle/parse.ts +++ b/edge/_shared/bundle/parse.ts @@ -49,6 +49,103 @@ export const DEFAULT_INPUT_CODE = [ 'export { default } from "spring-easing";', ].join('\n') +// ============================================================================= +// Input Normalization +// ============================================================================= + +export type BundleRequestInput = URL | Record + +/** + * Build a URL from request-like input. + * + * This allows POST bodies to be normalized into the same parsing flow + * as query parameters, preserving legacy behavior. + */ +export function buildUrlFromInput( + input: Record, + baseUrl: string = 'https://bundlejs.invalid/' +): URL { + const url = new URL(baseUrl) + + const addParam = (key: string, value: unknown) => { + if (value === undefined || value === null) return + + if (Array.isArray(value)) { + url.searchParams.set(key, value.map((v) => String(v)).join(',')) + return + } + + if (typeof value === 'boolean') { + url.searchParams.set(key, value ? '' : 'false') + return + } + + if (typeof value === 'object') { + if (key === 'config') { + url.searchParams.set(key, JSON5.stringify(value)) + return + } + url.searchParams.set(key, JSON.stringify(value)) + return + } + + url.searchParams.set(key, String(value)) + } + + const entries: Array<[string, unknown]> = [ + ['q', input.q], + ['query', input.query], + ['treeshake', input.treeshake], + ['share', input.share], + ['text', input.text], + ['config', input.config], + ['minify', input.minify], + ['pretty', input.pretty], + ['sourcemap', input.sourcemap], + ['format', input.format], + ['target', input.target], + ['tsx', input.tsx], + ['jsx', input.jsx], + ['polyfill', input.polyfill], + ['analysis', input.analysis], + ['analyze', input.analyze], + ['metafile', input.metafile], + ['badge', input.badge], + ['badge-style', input['badge-style']], + ['badge-raster', input['badge-raster']], + ['png', input.png], + ['file', input.file], + ['raw', input.raw], + ['warnings', input.warnings], + ['warning', input.warning], + ['cache', input.cache], + ] + + for (const [key, value] of entries) { + addParam(key, value) + } + + return url +} + +/** + * Parse request input into bundle configuration. + * + * Accepts either a URL (GET requests) or a plain object (POST bodies). + */ +export async function parseInputToConfig( + input: BundleRequestInput, + baseUrl?: string +): Promise { + const url = input instanceof URL + ? input + : buildUrlFromInput(input, baseUrl) + + const parsed = await parseQueryToConfig(url) + + return Object.assign({}, parsed, { url }) +} + // ============================================================================= // Public API // ============================================================================= diff --git a/edge/_shared/bundle/request.ts b/edge/_shared/bundle/request.ts new file mode 100644 index 0000000..fd87732 --- /dev/null +++ b/edge/_shared/bundle/request.ts @@ -0,0 +1,123 @@ +/** + * Bundle Request Orchestration + * + * Unifies parsing, cache lookup, and bundle execution for endpoints. + * + * Flow: + * +---------+ +---------+ +---------+ +-----------+ + * | Input |-->| Parse |-->| Cache |-->| Execute | + * +---------+ +---------+ +---------+ +-----------+ + */ + +import type { BundleRequestInput } from './parse.ts' +import type { BundleResult, BundleConfig, ModuleSpec, CacheMode } from './types.ts' + +import { parseInputToConfig } from './parse.ts' +import { executeBundle, executeBundleWithOutput } from './service.ts' +import { generateCacheKey, generateEntryPointHash } from '../cache/keys.ts' +import { getCachedResult, setCachedResult } from '../cache/operations.ts' + +export type BundleResolution = { + url: URL + cacheKey: string + cached: boolean + durationMs: number + result: BundleResult + outputText?: string + config: BundleConfig + inputCode: string + modules: ModuleSpec[] + versions: string[] +} + +export interface ResolveBundleOptions { + input: BundleRequestInput + baseUrl: string + cacheMode: CacheMode + includeOutputText?: boolean | 'auto' +} + +export async function resolveBundleRequest( + options: ResolveBundleOptions +): Promise { + const { input, baseUrl, cacheMode, includeOutputText = false } = options + const startTime = performance.now() + + const { inputCode, config, modules, versions, url } = await parseInputToConfig(input, baseUrl) + const wantsOutputText = includeOutputText === 'auto' + ? shouldIncludeOutputText(url) + : includeOutputText + + const cacheKey = await generateCacheKey(config, modules, versions, inputCode) + const entryPointHash = await generateEntryPointHash(cacheKey) + + const canReadCache = cacheMode === 'use' && !wantsOutputText + + if (canReadCache) { + const cached = await getCachedResult(cacheKey) + if (cached) { + return { + url, + cacheKey, + cached: true, + durationMs: performance.now() - startTime, + result: cached, + config, + inputCode, + modules, + versions, + } + } + } + + const query = (url.searchParams.get('q') || url.searchParams.get('query')) ?? 'spring-easing' + + let result: BundleResult + let outputText: string | undefined + + if (wantsOutputText) { + const [bundleResult, rawOutput] = await executeBundleWithOutput({ + config, + inputCode, + entryPointHash, + url, + versions, + modules, + query, + }) + + result = bundleResult + outputText = rawOutput + } else { + result = await executeBundle({ + config, + inputCode, + entryPointHash, + url, + versions, + modules, + query, + }) + } + + if (cacheMode !== 'bypass') { + await setCachedResult(cacheKey, result) + } + + return { + url, + cacheKey, + cached: false, + durationMs: performance.now() - startTime, + result, + outputText, + config, + inputCode, + modules, + versions, + } +} + +function shouldIncludeOutputText(url: URL): boolean { + return url.searchParams.has('file') || url.pathname === '/file' +} diff --git a/edge/_shared/bundle/schema.ts b/edge/_shared/bundle/schema.ts index 0853c01..4580823 100644 --- a/edge/_shared/bundle/schema.ts +++ b/edge/_shared/bundle/schema.ts @@ -103,6 +103,9 @@ export const BundleQuerySchema = z.object({ .optional() .transform((v) => v === '' || v === 'true'), + /** Cache control mode */ + cache: z.enum(['use', 'bypass', 'refresh']).optional(), + /** Warnings output */ warnings: z .union([z.literal(''), z.literal('true'), z.literal('false')]) diff --git a/edge/_shared/middleware/cache-control.ts b/edge/_shared/middleware/cache-control.ts new file mode 100644 index 0000000..417c4f0 --- /dev/null +++ b/edge/_shared/middleware/cache-control.ts @@ -0,0 +1,36 @@ +/** + * Cache Control Middleware + * + * Normalizes cache behavior for bundle endpoints. + * Supports legacy paths and the `cache` query parameter. + * + * Flow: + * +-----------+ +--------------------+ +------------------+ + * | Request | ---> | Parse cache intent | ---> | Set c.var value | + * +-----------+ +--------------------+ +------------------+ + */ + +import type { CacheMode } from '../bundle/types.ts' +import type { MiddlewareHandler } from 'hono' + +export type CacheControlVariables = { + cacheMode?: CacheMode +} + +const DEFAULT_CACHE_MODE: CacheMode = 'use' + +export const cacheControlMiddleware: MiddlewareHandler = async (c, next) => { + const url = new URL(c.req.url) + const cacheParam = url.searchParams.get('cache') + + let cacheMode: CacheMode = DEFAULT_CACHE_MODE + + if (url.pathname === '/no-cache') { + cacheMode = 'bypass' + } else if (cacheParam === 'use' || cacheParam === 'bypass' || cacheParam === 'refresh') { + cacheMode = cacheParam + } + + c.set('cacheMode', cacheMode) + return await next() +} diff --git a/edge/_shared/middleware/rate-limit.ts b/edge/_shared/middleware/rate-limit.ts index 94c1d73..a2972c0 100644 --- a/edge/_shared/middleware/rate-limit.ts +++ b/edge/_shared/middleware/rate-limit.ts @@ -8,10 +8,12 @@ * - Graceful degradation when Redis unavailable */ +import type { EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + import { createMiddleware } from 'hono/factory' import { rateLimiter } from 'hono-rate-limiter' import { RedisStore } from '@hono-rate-limiter/redis' -import { getRedisClient, isCacheHealthy } from '#shared/cache/client.ts' +import { getRedisClient } from '#shared/cache/client.ts' import { rateLimitExceeded } from '#shared/response/mod.ts' export interface RateLimitOptions { @@ -23,7 +25,9 @@ export interface RateLimitOptions { /** * Create rate limit middleware with configurable limits */ -export function rateLimitMiddleware(options: RateLimitOptions) { +export function rateLimitMiddleware( + options: RateLimitOptions +): EndpointMiddlewareHandler { const { windowMs, limit, keyGenerator } = options const redis = getRedisClient() @@ -34,7 +38,7 @@ export function rateLimitMiddleware(options: RateLimitOptions) { : undefined return createMiddleware( - rateLimiter({ + rateLimiter({ windowMs, limit, standardHeaders: 'draft-6', // RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset diff --git a/edge/endpoints/badge/raster/definition.ts b/edge/endpoints/badge/raster/definition.ts new file mode 100644 index 0000000..f0dbbe4 --- /dev/null +++ b/edge/endpoints/badge/raster/definition.ts @@ -0,0 +1,22 @@ +/** + * Badge Raster Endpoint Definition + * + * GET /v1/badge/raster + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BundleQuerySchema } from '#shared/bundle/schema.ts' + +export const QuerySchema = BundleQuerySchema + +export default { + Name: 'badge-raster', + Route: '/v1/badge/raster', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/badge/raster/handler.ts b/edge/endpoints/badge/raster/handler.ts new file mode 100644 index 0000000..6643025 --- /dev/null +++ b/edge/endpoints/badge/raster/handler.ts @@ -0,0 +1,52 @@ +/** + * Badge Raster Handler + * + * GET /v1/badge/raster + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' +import type { CacheControlVariables } from '#shared/middleware/cache-control.ts' + +import { createValidator } from '#shared/middleware/validation.ts' +import { rateLimitMiddleware } from '#shared/middleware/rate-limit.ts' +import { cacheControlMiddleware } from '#shared/middleware/cache-control.ts' + +import { badRequest } from '#shared/response/mod.ts' + +import { resolveBundleRequest } from '#shared/bundle/request.ts' +import { generateLegacyResponse } from '#shared/bundle/legacy-response.ts' + +import Definition from './definition.ts' + +type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + rateLimitMiddleware({ windowMs: 60_000, limit: 300 }), + cacheControlMiddleware, + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function (c) { + const input = c.req.valid('query') + const cacheMode = c.get('cacheMode') ?? 'use' + + const resolution = await resolveBundleRequest({ + input, + baseUrl: c.req.url, + cacheMode, + }) + + if (!resolution.inputCode && resolution.modules.length === 0) { + return c.json(...badRequest(c.req.path, 'No modules or code provided')) + } + + return await generateLegacyResponse({ + url: resolution.url, + result: resolution.result, + cached: resolution.cached, + durationMs: resolution.durationMs, + cacheKey: resolution.cacheKey, + }) +} + +export default Handler diff --git a/edge/endpoints/badge/svg/definition.ts b/edge/endpoints/badge/svg/definition.ts new file mode 100644 index 0000000..ca5a105 --- /dev/null +++ b/edge/endpoints/badge/svg/definition.ts @@ -0,0 +1,22 @@ +/** + * Badge SVG Endpoint Definition + * + * GET /v1/badge + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BundleQuerySchema } from '#shared/bundle/schema.ts' + +export const QuerySchema = BundleQuerySchema + +export default { + Name: 'badge-svg', + Route: '/v1/badge', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/badge/svg/handler.ts b/edge/endpoints/badge/svg/handler.ts index 5acda04..afb0518 100644 --- a/edge/endpoints/badge/svg/handler.ts +++ b/edge/endpoints/badge/svg/handler.ts @@ -12,29 +12,29 @@ */ import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' +import type { CacheControlVariables } from '#shared/middleware/cache-control.ts' import { createValidator } from '#shared/middleware/validation.ts' -import { rateLimitMiddleware } from '#middleware/rate-limit.ts' +import { rateLimitMiddleware } from '#shared/middleware/rate-limit.ts' +import { cacheControlMiddleware } from '#shared/middleware/cache-control.ts' -import { badRequest, badGateway, gatewayTimeout } from '#shared/response/mod.ts' -import { getLogger } from '#shared/middleware/correlation.ts' +import { badRequest } from '#shared/response/mod.ts' -import { parseQueryToConfig } from '#shared/bundle/parse.ts' -import { generateCacheKey } from '#shared/cache/keys.ts' -import { getCachedResult } from '#shared/cache/operations.ts' -import { fetchBadge, type BadgeOptions } from '#shared/external/shields.ts' +import { resolveBundleRequest } from '#shared/bundle/request.ts' +import { generateLegacyResponse } from '#shared/bundle/legacy-response.ts' import Definition from './definition.ts' -export type AppEnv = FunctionAppEnv +export type AppEnv = FunctionAppEnv // ============================================================================ // MIDDLEWARE // ============================================================================ export const Middleware: EndpointMiddlewareHandler[] = [ - rateLimitMiddleware({ windowMs: 60_000, limit: 300 }), // Higher limit for badges - createValidator('query', Definition.Schemas.Query), + rateLimitMiddleware({ windowMs: 60_000, limit: 300 }), + cacheControlMiddleware, + createValidator('query', Definition.Schemas.Query), ] // ============================================================================ @@ -42,82 +42,26 @@ export const Middleware: EndpointMiddlewareHandler[] = [ // ============================================================================ export const Handler: EndpointHandler = async function (c) { - const logger = getLogger(c) - - try { - const input = c.req.valid('query') - const { inputCode, config, modules } = await parseQueryToConfig(input) - - // We need a bundle result to generate a badge - const cacheKey = generateCacheKey(config, modules) - const cached = await getCachedResult(cacheKey) - - if (!cached) { - // No cached result - can't generate badge without bundling - // (Could optionally trigger bundle here, but that's expensive for a badge request) - return c.json(...badRequest( - c.req.path, - 'No cached bundle result. Request /v1/bundle first.' - )) - } - - // Determine badge type and value - const badgeType = input.badge ?? 'gzip' - const size = cached.compressed?.[badgeType]?.size ?? cached.outputText?.length ?? 0 - const sizeFormatted = formatBytes(size) - - // Fetch badge from shields.io with timeout - const badgeOptions: BadgeOptions = { - label: badgeType === 'minified' ? 'minified' : `${badgeType} size`, - message: sizeFormatted, - color: getSizeColor(size), - } - - const svgResult = await fetchBadge(badgeOptions) - - if (!svgResult.ok) { - logger.warn('shields.io fetch failed', { status: svgResult.status }) - - if (svgResult.timeout) { - return c.json(...gatewayTimeout(c.req.path, 'Badge service timeout')) - } - return c.json(...badGateway(c.req.path, 'Badge service unavailable')) - } - - // Return SVG with cache headers - return new Response(svgResult.svg, { - headers: { - 'Content-Type': 'image/svg+xml', - 'Cache-Control': 'public, max-age=3600', // 1 hour - 'X-Cache-Key': cacheKey.slice(0, 20), - }, - }) - - } catch (error) { - logger.error('Badge generation failed', { - error: error instanceof Error ? error.message : String(error), - }) - - return c.json(...badGateway(c.req.path, 'Badge generation failed')) - } -} + const input = c.req.valid('query') + const cacheMode = c.get('cacheMode') ?? 'use' -// ============================================================================ -// HELPERS -// ============================================================================ + const resolution = await resolveBundleRequest({ + input, + baseUrl: c.req.url, + cacheMode, + }) -function formatBytes(bytes: number): string { - if (bytes < 1024) return `${bytes} B` - if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB` - return `${(bytes / (1024 * 1024)).toFixed(1)} MB` -} + if (!resolution.inputCode && resolution.modules.length === 0) { + return c.json(...badRequest(c.req.path, 'No modules or code provided')) + } -function getSizeColor(bytes: number): string { - if (bytes < 10_000) return 'brightgreen' - if (bytes < 50_000) return 'green' - if (bytes < 100_000) return 'yellow' - if (bytes < 500_000) return 'orange' - return 'red' + return await generateLegacyResponse({ + url: resolution.url, + result: resolution.result, + cached: resolution.cached, + durationMs: resolution.durationMs, + cacheKey: resolution.cacheKey, + }) } export default Handler \ No newline at end of file diff --git a/edge/endpoints/bundle/analysis/definition.ts b/edge/endpoints/bundle/analysis/definition.ts new file mode 100644 index 0000000..1b861c8 --- /dev/null +++ b/edge/endpoints/bundle/analysis/definition.ts @@ -0,0 +1,22 @@ +/** + * Bundle Analysis Endpoint Definition + * + * GET /v1/bundle/analysis + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BundleQuerySchema } from '#shared/bundle/schema.ts' + +export const QuerySchema = BundleQuerySchema + +export default { + Name: 'bundle-analysis', + Route: '/v1/bundle/analysis', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/bundle/analysis/handler.ts b/edge/endpoints/bundle/analysis/handler.ts new file mode 100644 index 0000000..5a458c1 --- /dev/null +++ b/edge/endpoints/bundle/analysis/handler.ts @@ -0,0 +1,52 @@ +/** + * Bundle Analysis Handler + * + * GET /v1/bundle/analysis + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' +import type { CacheControlVariables } from '#shared/middleware/cache-control.ts' + +import { createValidator } from '#shared/middleware/validation.ts' +import { rateLimitMiddleware } from '#shared/middleware/rate-limit.ts' +import { cacheControlMiddleware } from '#shared/middleware/cache-control.ts' + +import { badRequest } from '#shared/response/mod.ts' + +import { resolveBundleRequest } from '#shared/bundle/request.ts' +import { generateLegacyResponse } from '#shared/bundle/legacy-response.ts' + +import Definition from './definition.ts' + +type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + rateLimitMiddleware({ windowMs: 60_000, limit: 120 }), + cacheControlMiddleware, + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function (c) { + const input = c.req.valid('query') + const cacheMode = c.get('cacheMode') ?? 'use' + + const resolution = await resolveBundleRequest({ + input, + baseUrl: c.req.url, + cacheMode, + }) + + if (!resolution.inputCode && resolution.modules.length === 0) { + return c.json(...badRequest(c.req.path, 'No modules or code provided')) + } + + return await generateLegacyResponse({ + url: resolution.url, + result: resolution.result, + cached: resolution.cached, + durationMs: resolution.durationMs, + cacheKey: resolution.cacheKey, + }) +} + +export default Handler diff --git a/edge/endpoints/bundle/file/definition.ts b/edge/endpoints/bundle/file/definition.ts new file mode 100644 index 0000000..e23bc79 --- /dev/null +++ b/edge/endpoints/bundle/file/definition.ts @@ -0,0 +1,22 @@ +/** + * Bundle File Endpoint Definition + * + * GET /v1/bundle/file + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BundleQuerySchema } from '#shared/bundle/schema.ts' + +export const QuerySchema = BundleQuerySchema + +export default { + Name: 'bundle-file', + Route: '/v1/bundle/file', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/bundle/file/handler.ts b/edge/endpoints/bundle/file/handler.ts new file mode 100644 index 0000000..dd4560c --- /dev/null +++ b/edge/endpoints/bundle/file/handler.ts @@ -0,0 +1,54 @@ +/** + * Bundle File Handler + * + * GET /v1/bundle/file + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' +import type { CacheControlVariables } from '#shared/middleware/cache-control.ts' + +import { createValidator } from '#shared/middleware/validation.ts' +import { rateLimitMiddleware } from '#shared/middleware/rate-limit.ts' +import { cacheControlMiddleware } from '#shared/middleware/cache-control.ts' + +import { badRequest } from '#shared/response/mod.ts' + +import { resolveBundleRequest } from '#shared/bundle/request.ts' +import { generateLegacyResponse } from '#shared/bundle/legacy-response.ts' + +import Definition from './definition.ts' + +type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + rateLimitMiddleware({ windowMs: 60_000, limit: 120 }), + cacheControlMiddleware, + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function (c) { + const input = c.req.valid('query') + const cacheMode = c.get('cacheMode') ?? 'use' + + const resolution = await resolveBundleRequest({ + input, + baseUrl: c.req.url, + cacheMode, + includeOutputText: true, + }) + + if (!resolution.inputCode && resolution.modules.length === 0) { + return c.json(...badRequest(c.req.path, 'No modules or code provided')) + } + + return await generateLegacyResponse({ + url: resolution.url, + result: resolution.result, + outputText: resolution.outputText, + cached: resolution.cached, + durationMs: resolution.durationMs, + cacheKey: resolution.cacheKey, + }) +} + +export default Handler diff --git a/edge/endpoints/bundle/metafile/definition.ts b/edge/endpoints/bundle/metafile/definition.ts new file mode 100644 index 0000000..20ec898 --- /dev/null +++ b/edge/endpoints/bundle/metafile/definition.ts @@ -0,0 +1,22 @@ +/** + * Bundle Metafile Endpoint Definition + * + * GET /v1/bundle/metafile + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BundleQuerySchema } from '#shared/bundle/schema.ts' + +export const QuerySchema = BundleQuerySchema + +export default { + Name: 'bundle-metafile', + Route: '/v1/bundle/metafile', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/bundle/metafile/handler.ts b/edge/endpoints/bundle/metafile/handler.ts new file mode 100644 index 0000000..d04a8f5 --- /dev/null +++ b/edge/endpoints/bundle/metafile/handler.ts @@ -0,0 +1,52 @@ +/** + * Bundle Metafile Handler + * + * GET /v1/bundle/metafile + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' +import type { CacheControlVariables } from '#shared/middleware/cache-control.ts' + +import { createValidator } from '#shared/middleware/validation.ts' +import { rateLimitMiddleware } from '#shared/middleware/rate-limit.ts' +import { cacheControlMiddleware } from '#shared/middleware/cache-control.ts' + +import { badRequest } from '#shared/response/mod.ts' + +import { resolveBundleRequest } from '#shared/bundle/request.ts' +import { generateLegacyResponse } from '#shared/bundle/legacy-response.ts' + +import Definition from './definition.ts' + +type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + rateLimitMiddleware({ windowMs: 60_000, limit: 120 }), + cacheControlMiddleware, + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function (c) { + const input = c.req.valid('query') + const cacheMode = c.get('cacheMode') ?? 'use' + + const resolution = await resolveBundleRequest({ + input, + baseUrl: c.req.url, + cacheMode, + }) + + if (!resolution.inputCode && resolution.modules.length === 0) { + return c.json(...badRequest(c.req.path, 'No modules or code provided')) + } + + return await generateLegacyResponse({ + url: resolution.url, + result: resolution.result, + cached: resolution.cached, + durationMs: resolution.durationMs, + cacheKey: resolution.cacheKey, + }) +} + +export default Handler diff --git a/edge/endpoints/bundle/mod.ts b/edge/endpoints/bundle/mod.ts new file mode 100644 index 0000000..f24fc4e --- /dev/null +++ b/edge/endpoints/bundle/mod.ts @@ -0,0 +1,49 @@ +/** + * Endpoint Definitions Registry + */ + +import BundleRun from './run/definition.ts' +import BundleFile from './file/definition.ts' +import BundleMetafile from './metafile/definition.ts' +import BundleAnalysis from './analysis/definition.ts' +import BundleWarnings from './warnings/definition.ts' +import BundleRaw from './raw/definition.ts' + +import BadgeSvg from '../badge/svg/definition.ts' +import BadgeRaster from '../badge/raster/definition.ts' + +import CachePurge from '../cache/purge/definition.ts' +import CacheClear from '../cache/clear/definition.ts' + +import OpenApi from '../static/openapi/definition.ts' +import Plugin from '../static/plugin/definition.ts' +import Robots from '../static/robots/definition.ts' +import Llm from '../static/llms/definition.ts' +import ServiceWorker from '../static/sw/definition.ts' +import Favicon from '../static/favicon/definition.ts' +import AppleTouchIcon from '../static/apple-touch-icon/definition.ts' +import AppleTouchIconPrecomposed from '../static/apple-touch-icon-precomposed/definition.ts' + +import Health from '../health/definition.ts' + +export const EndpointDefinitions = { + BundleRun, + BundleFile, + BundleMetafile, + BundleAnalysis, + BundleWarnings, + BundleRaw, + BadgeSvg, + BadgeRaster, + CachePurge, + CacheClear, + OpenApi, + Plugin, + Robots, + Llm, + ServiceWorker, + Favicon, + AppleTouchIcon, + AppleTouchIconPrecomposed, + Health, +} as const diff --git a/edge/endpoints/bundle/raw/definition.ts b/edge/endpoints/bundle/raw/definition.ts new file mode 100644 index 0000000..c6871f8 --- /dev/null +++ b/edge/endpoints/bundle/raw/definition.ts @@ -0,0 +1,22 @@ +/** + * Bundle Raw Endpoint Definition + * + * GET /v1/bundle/raw + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BundleQuerySchema } from '#shared/bundle/schema.ts' + +export const QuerySchema = BundleQuerySchema + +export default { + Name: 'bundle-raw', + Route: '/v1/bundle/raw', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/bundle/raw/handler.ts b/edge/endpoints/bundle/raw/handler.ts new file mode 100644 index 0000000..a7192ee --- /dev/null +++ b/edge/endpoints/bundle/raw/handler.ts @@ -0,0 +1,52 @@ +/** + * Bundle Raw Handler + * + * GET /v1/bundle/raw + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' +import type { CacheControlVariables } from '#shared/middleware/cache-control.ts' + +import { createValidator } from '#shared/middleware/validation.ts' +import { rateLimitMiddleware } from '#shared/middleware/rate-limit.ts' +import { cacheControlMiddleware } from '#shared/middleware/cache-control.ts' + +import { badRequest } from '#shared/response/mod.ts' + +import { resolveBundleRequest } from '#shared/bundle/request.ts' +import { generateLegacyResponse } from '#shared/bundle/legacy-response.ts' + +import Definition from './definition.ts' + +type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + rateLimitMiddleware({ windowMs: 60_000, limit: 120 }), + cacheControlMiddleware, + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function (c) { + const input = c.req.valid('query') + const cacheMode = c.get('cacheMode') ?? 'use' + + const resolution = await resolveBundleRequest({ + input, + baseUrl: c.req.url, + cacheMode, + }) + + if (!resolution.inputCode && resolution.modules.length === 0) { + return c.json(...badRequest(c.req.path, 'No modules or code provided')) + } + + return await generateLegacyResponse({ + url: resolution.url, + result: resolution.result, + cached: resolution.cached, + durationMs: resolution.durationMs, + cacheKey: resolution.cacheKey, + }) +} + +export default Handler diff --git a/edge/endpoints/bundle/run/definition.ts b/edge/endpoints/bundle/run/definition.ts index 85c2666..ceb2dd9 100644 --- a/edge/endpoints/bundle/run/definition.ts +++ b/edge/endpoints/bundle/run/definition.ts @@ -12,9 +12,10 @@ import type { EndpointDefinition } from '#shared/server/types.ts' import { z } from 'zod' -import { BaseQuerySchema, BaseJsonSchema } from '#shared/server/schemas.ts' +import { BaseJsonSchema } from '#shared/server/schemas.ts' import { makeSuccessResponseSchema } from '#shared/response/schemas.ts' import { BundleResultSchema } from '#shared/schemas/bundle-result.ts' +import { BundleQuerySchema } from '#shared/bundle/schema.ts' // ============================================================================ // INPUT SCHEMAS @@ -23,35 +24,7 @@ import { BundleResultSchema } from '#shared/schemas/bundle-result.ts' /** * Query parameters (GET requests) */ -export const QuerySchema = BaseQuerySchema.extend({ - // Module selection - q: z.string().optional(), - query: z.string().optional(), // Alias for q - - // Code input - text: z.string().optional(), // Inline code - share: z.string().optional(), // LZ-compressed code - - // Treeshaking - treeshake: z.string().optional(), // Export selections - - // Build options - config: z.string().optional(), // JSON5 config - minify: z.coerce.boolean().default(true), - tsx: z.coerce.boolean().default(false), - target: z.string().default('esnext'), - format: z.enum(['esm', 'cjs', 'iife']).default('esm'), - - // Compression - compression: z.enum(['gzip', 'brotli', 'zstd', 'lz4', 'none']).default('gzip'), - - // Cache control - cache: z.enum(['use', 'bypass', 'refresh']).default('use'), - - // Output modifiers - analysis: z.coerce.boolean().default(false), - metafile: z.coerce.boolean().default(false), -}) +export const QuerySchema = BundleQuerySchema /** * Body schema (POST requests with large payloads) @@ -59,16 +32,30 @@ export const QuerySchema = BaseQuerySchema.extend({ export const JsonSchema = BaseJsonSchema.pipe( z.object({ query: z.string().optional(), + q: z.string().optional(), text: z.string().optional(), share: z.string().optional(), treeshake: z.string().optional(), - config: z.record(z.unknown()).optional(), - minify: z.boolean().default(true), - tsx: z.boolean().default(false), - target: z.string().default('esnext'), - format: z.enum(['esm', 'cjs', 'iife']).default('esm'), - compression: z.enum(['gzip', 'brotli', 'zstd', 'lz4', 'none']).default('gzip'), - cache: z.enum(['use', 'bypass', 'refresh']).default('use'), + config: z.union([z.record(z.unknown()), z.string()]).optional(), + minify: z.boolean().optional(), + pretty: z.boolean().optional(), + sourcemap: z.union([z.boolean(), z.literal('inline'), z.literal('external'), z.literal('both')]).optional(), + tsx: z.boolean().optional(), + jsx: z.boolean().optional(), + polyfill: z.boolean().optional(), + format: z.enum(['esm', 'cjs', 'iife']).optional(), + analysis: z.union([z.boolean(), z.string()]).optional(), + analyze: z.union([z.boolean(), z.string()]).optional(), + metafile: z.boolean().optional(), + badge: z.string().optional(), + 'badge-style': z.string().optional(), + 'badge-raster': z.boolean().optional(), + png: z.boolean().optional(), + file: z.boolean().optional(), + raw: z.boolean().optional(), + warnings: z.boolean().optional(), + warning: z.boolean().optional(), + cache: z.enum(['use', 'bypass', 'refresh']).optional(), }).partial() ) diff --git a/edge/endpoints/bundle/run/handler.ts b/edge/endpoints/bundle/run/handler.ts index cbfee51..bf563b7 100644 --- a/edge/endpoints/bundle/run/handler.ts +++ b/edge/endpoints/bundle/run/handler.ts @@ -16,16 +16,14 @@ import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from import type { CorrelationVariables } from '#shared/middleware/correlation.ts' import { createValidator } from '#shared/middleware/validation.ts' -import { rateLimitMiddleware } from '#middleware/rate-limit.ts' -import { cacheControlMiddleware, type CacheControlVariables } from '#middleware/cache-control.ts' +import { rateLimitMiddleware } from '#shared/middleware/rate-limit.ts' +import { cacheControlMiddleware, type CacheControlVariables } from '#shared/middleware/cache-control.ts' -import { ok, internalServerError, badRequest } from '#shared/response/mod.ts' +import { ok, internalServerError, badRequest, validationFailed } from '#shared/response/mod.ts' import { getLogger } from '#shared/middleware/correlation.ts' -import { parseQueryToConfig } from '#shared/bundle/parse.ts' -import { executeBundle } from '#shared/bundle/service.ts' -import { generateCacheKey } from '#shared/cache/keys.ts' -import { getCachedResult, setCachedResult } from '#shared/cache/operations.ts' +import { resolveBundleRequest } from '#shared/bundle/request.ts' +import { generateLegacyResponse } from '#shared/bundle/legacy-response.ts' import Definition from './definition.ts' @@ -43,7 +41,7 @@ export type AppEnv = FunctionAppEnv export const Middleware: EndpointMiddlewareHandler[] = [ // Rate limit: 120 req/min for bundling (expensive compute) - rateLimitMiddleware({ windowMs: 60_000, limit: 120 }), + rateLimitMiddleware({ windowMs: 60_000, limit: 120 }), // Parse cache mode from query cacheControlMiddleware, @@ -59,64 +57,80 @@ export const Middleware: EndpointMiddlewareHandler[] = [ export const Handler: EndpointHandler = async function (c) { const logger = getLogger(c) const startTime = performance.now() + const method = c.req.method + const isLegacyPath = !c.req.path.includes('/v1/') try { // Get input from query or body - const method = c.req.method - const input = method === 'POST' + let input = method === 'POST' ? await c.req.json() : c.req.valid('query') - - // Parse into bundle config - const { inputCode, config, modules } = await parseQueryToConfig(input) - - if (!inputCode && modules.length === 0) { - return c.json(...badRequest(c.req.path, 'No modules or code provided')) + + if (method === 'GET') { + const requestUrl = new URL(c.req.url) + if (requestUrl.searchParams.has('docs')) { + return Response.redirect( + 'https://blog.okikio.dev/documenting-an-online-bundler-bundlejs#heading-configuration' + ) + } } - - // Generate cache key - const cacheKey = generateCacheKey(config, modules) - - // Check cache (unless bypassing) - const cacheMode = c.get('cacheMode') ?? 'use' - - if (cacheMode === 'use') { - const cached = await getCachedResult(cacheKey) - if (cached) { - logger.info('Cache HIT', { key: cacheKey.slice(0, 20) }) - c.header('X-Cache', 'HIT') - return c.json(...ok({ ...cached, cached: true })) + + if (method === 'POST' && Definition.Schemas.Json) { + const result = Definition.Schemas.Json.safeParse(input) + if (!result.success) { + const errors = result.error.issues.map((issue) => ({ + field: issue.path.length > 0 ? issue.path.join('.') : '_root', + message: issue.message, + })) + return c.json(...validationFailed(c.req.path, errors)) } + + input = result.data } - - logger.info('Cache MISS - executing bundle', { - modules: modules.length, + + const cacheMode = c.get('cacheMode') ?? 'use' + + const resolution = await resolveBundleRequest({ + input, + baseUrl: c.req.url, cacheMode, + includeOutputText: isLegacyPath ? 'auto' : false, }) - c.header('X-Cache', cacheMode === 'bypass' ? 'BYPASS' : 'MISS') - - // Execute bundle - const result = await executeBundle({ - config, - inputCode, - entryPointHash: cacheKey.slice(0, 8), - }) - - // Cache result (unless bypassing) - if (cacheMode !== 'bypass') { - await setCachedResult(cacheKey, result) + + if (!resolution.inputCode && resolution.modules.length === 0) { + return c.json(...badRequest(c.req.path, 'No modules or code provided')) } - - // Add timing header + + if (isLegacyPath) { + return await generateLegacyResponse({ + url: resolution.url, + result: resolution.result, + outputText: resolution.outputText, + cached: resolution.cached, + durationMs: resolution.durationMs, + cacheKey: resolution.cacheKey, + }) + } + const duration = performance.now() - startTime c.header('X-Bundle-Duration-ms', duration.toFixed(2)) - + c.header( + 'X-Cache', + resolution.cached + ? 'HIT' + : cacheMode === 'bypass' + ? 'BYPASS' + : cacheMode === 'refresh' + ? 'REFRESH' + : 'MISS' + ) + logger.info('Bundle complete', { duration_ms: duration.toFixed(2), - output_size: result.outputText?.length ?? 0, + cached: resolution.cached, }) - - return c.json(...ok(result)) + + return c.json(...ok(resolution.result)) } catch (error) { logger.error('Bundle failed', { diff --git a/edge/endpoints/bundle/warnings/definition.ts b/edge/endpoints/bundle/warnings/definition.ts new file mode 100644 index 0000000..1a81873 --- /dev/null +++ b/edge/endpoints/bundle/warnings/definition.ts @@ -0,0 +1,22 @@ +/** + * Bundle Warnings Endpoint Definition + * + * GET /v1/bundle/warnings + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BundleQuerySchema } from '#shared/bundle/schema.ts' + +export const QuerySchema = BundleQuerySchema + +export default { + Name: 'bundle-warnings', + Route: '/v1/bundle/warnings', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/bundle/warnings/handler.ts b/edge/endpoints/bundle/warnings/handler.ts new file mode 100644 index 0000000..3e7b6b8 --- /dev/null +++ b/edge/endpoints/bundle/warnings/handler.ts @@ -0,0 +1,52 @@ +/** + * Bundle Warnings Handler + * + * GET /v1/bundle/warnings + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' +import type { CacheControlVariables } from '#shared/middleware/cache-control.ts' + +import { createValidator } from '#shared/middleware/validation.ts' +import { rateLimitMiddleware } from '#shared/middleware/rate-limit.ts' +import { cacheControlMiddleware } from '#shared/middleware/cache-control.ts' + +import { badRequest } from '#shared/response/mod.ts' + +import { resolveBundleRequest } from '#shared/bundle/request.ts' +import { generateLegacyResponse } from '#shared/bundle/legacy-response.ts' + +import Definition from './definition.ts' + +type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + rateLimitMiddleware({ windowMs: 60_000, limit: 120 }), + cacheControlMiddleware, + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function (c) { + const input = c.req.valid('query') + const cacheMode = c.get('cacheMode') ?? 'use' + + const resolution = await resolveBundleRequest({ + input, + baseUrl: c.req.url, + cacheMode, + }) + + if (!resolution.inputCode && resolution.modules.length === 0) { + return c.json(...badRequest(c.req.path, 'No modules or code provided')) + } + + return await generateLegacyResponse({ + url: resolution.url, + result: resolution.result, + cached: resolution.cached, + durationMs: resolution.durationMs, + cacheKey: resolution.cacheKey, + }) +} + +export default Handler diff --git a/edge/endpoints/cache/clear/definition.ts b/edge/endpoints/cache/clear/definition.ts new file mode 100644 index 0000000..aa61794 --- /dev/null +++ b/edge/endpoints/cache/clear/definition.ts @@ -0,0 +1,22 @@ +/** + * Cache Clear Endpoint Definition + * + * GET /v1/cache/clear + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'cache-clear', + Route: '/v1/cache/clear', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/cache/clear/handler.ts b/edge/endpoints/cache/clear/handler.ts new file mode 100644 index 0000000..d4cf16c --- /dev/null +++ b/edge/endpoints/cache/clear/handler.ts @@ -0,0 +1,55 @@ +/** + * Cache Clear Handler + * + * GET /v1/cache/clear + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import { ok, internalServerError } from '#shared/response/mod.ts' +import { flushCacheAsync } from '#shared/cache/operations.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function (c) { + try { + await flushCacheAsync() + + if (!c.req.path.includes('/v1/')) { + return new Response('Started clearing cache!', { + status: 200, + headers: { + 'Content-Type': 'text/plain', + 'x-content-type-options': 'nosniff', + }, + }) + } + + return c.json(...ok({ cleared: true })) + } catch (error) { + if (!c.req.path.includes('/v1/')) { + return new Response('Redis is unavailable, try again at a later date!', { + status: 500, + headers: { + 'Content-Type': 'text/plain', + 'x-content-type-options': 'nosniff', + }, + }) + } + + return c.json(...internalServerError( + c.req.path, + error instanceof Error ? error.message : 'Cache clear failed' + )) + } +} + +export default Handler diff --git a/edge/endpoints/cache/purge/definition.ts b/edge/endpoints/cache/purge/definition.ts new file mode 100644 index 0000000..21f2543 --- /dev/null +++ b/edge/endpoints/cache/purge/definition.ts @@ -0,0 +1,22 @@ +/** + * Cache Purge Endpoint Definition + * + * GET/POST /v1/cache/purge + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BundleQuerySchema } from '#shared/bundle/schema.ts' + +export const QuerySchema = BundleQuerySchema + +export default { + Name: 'cache-purge', + Route: '/v1/cache/purge', + Methods: ['GET', 'POST'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/cache/purge/handler.ts b/edge/endpoints/cache/purge/handler.ts new file mode 100644 index 0000000..93cd561 --- /dev/null +++ b/edge/endpoints/cache/purge/handler.ts @@ -0,0 +1,71 @@ +/** + * Cache Purge Handler + * + * GET/POST /v1/cache/purge + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import { ok, internalServerError } from '#shared/response/mod.ts' + +import { parseInputToConfig } from '#shared/bundle/parse.ts' +import { generateCacheKey, getBadgeKey, getPackageResultKey } from '#shared/cache/keys.ts' +import { deleteCachedBadges, deleteCachedResult } from '#shared/cache/operations.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function (c) { + try { + const input = c.req.method === 'POST' ? await c.req.json() : c.req.valid('query') + const { inputCode, config, versions, modules } = await parseInputToConfig(input, c.req.url) + + const jsonKey = await generateCacheKey(config, modules, versions, inputCode) + const badgeKey = getBadgeKey(jsonKey) + const moduleName = modules[0]?.[0] + const packageKey = moduleName ? getPackageResultKey(moduleName, jsonKey) : null + + await deleteCachedResult(jsonKey) + await deleteCachedBadges(badgeKey) + + if (packageKey) { + await deleteCachedResult(packageKey) + } + + if (!c.req.path.includes('/v1/')) { + return new Response('Deleted from cache!', { + status: 200, + headers: { + 'Content-Type': 'text/plain', + 'x-content-type-options': 'nosniff', + }, + }) + } + + return c.json(...ok({ deleted: true, jsonKey, badgeKey, packageKey })) + } catch (error) { + if (!c.req.path.includes('/v1/')) { + return new Response('Error, deleting from cache', { + status: 500, + headers: { + 'Content-Type': 'text/plain', + 'x-content-type-options': 'nosniff', + }, + }) + } + + return c.json(...internalServerError( + c.req.path, + error instanceof Error ? error.message : 'Cache purge failed' + )) + } +} + +export default Handler diff --git a/edge/endpoints/health/definition.ts b/edge/endpoints/health/definition.ts new file mode 100644 index 0000000..e1aceff --- /dev/null +++ b/edge/endpoints/health/definition.ts @@ -0,0 +1,22 @@ +/** + * Health Endpoint Definition + * + * GET /health + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'health', + Route: '/health', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/health/handler.ts b/edge/endpoints/health/handler.ts new file mode 100644 index 0000000..58209ce --- /dev/null +++ b/edge/endpoints/health/handler.ts @@ -0,0 +1,24 @@ +/** + * Health Handler + * + * GET /health + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' +import { ok } from '#shared/response/mod.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function (c) { + return c.json(...ok({ status: 'ok' })) +} + +export default Handler diff --git a/edge/endpoints/legacy/routes.ts b/edge/endpoints/legacy/routes.ts index ea954fe..cbda8ca 100644 --- a/edge/endpoints/legacy/routes.ts +++ b/edge/endpoints/legacy/routes.ts @@ -6,11 +6,12 @@ * Allows gradual migration without breaking existing clients. */ -import type { Hono } from 'hono' +import type { Hono, Env } from 'hono' +import type { BlankEnv } from 'hono/types' import type { EndpointHandlerModule } from '#shared/server/types.ts' -export function registerLegacyRoutes( - app: Hono, +export function registerLegacyRoutes( + app: Hono, handlers: Record ) { // Main bundle endpoint (root) @@ -69,6 +70,9 @@ export function registerLegacyRoutes( // Cache control (legacy paths) // GET /no-cache → /v1/bundle with cache=bypass // (Handled via query param in new API, but we can support path) + if (bundleRun?.default) { + app.get('/no-cache', ...(bundleRun.Middleware ?? []), bundleRun.default) + } // GET/POST /delete-cache → /v1/cache/purge const cachePurge = handlers['cache-purge'] diff --git a/edge/endpoints/static/apple-touch-icon-precomposed/definition.ts b/edge/endpoints/static/apple-touch-icon-precomposed/definition.ts new file mode 100644 index 0000000..8b554b5 --- /dev/null +++ b/edge/endpoints/static/apple-touch-icon-precomposed/definition.ts @@ -0,0 +1,22 @@ +/** + * Apple Touch Icon Precomposed Endpoint Definition + * + * GET /apple-touch-icon-precomposed.png + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'apple-touch-icon-precomposed', + Route: '/apple-touch-icon-precomposed.png', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/static/apple-touch-icon-precomposed/handler.ts b/edge/endpoints/static/apple-touch-icon-precomposed/handler.ts new file mode 100644 index 0000000..92038b4 --- /dev/null +++ b/edge/endpoints/static/apple-touch-icon-precomposed/handler.ts @@ -0,0 +1,23 @@ +/** + * Apple Touch Icon Precomposed Handler + * + * GET /apple-touch-icon-precomposed.png + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = function () { + return Response.redirect('https://bundlejs.com/favicon/apple-touch-icon.png') +} + +export default Handler diff --git a/edge/endpoints/static/apple-touch-icon/definition.ts b/edge/endpoints/static/apple-touch-icon/definition.ts new file mode 100644 index 0000000..2294e4e --- /dev/null +++ b/edge/endpoints/static/apple-touch-icon/definition.ts @@ -0,0 +1,22 @@ +/** + * Apple Touch Icon Static Endpoint Definition + * + * GET /apple-touch-icon.png + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'apple-touch-icon', + Route: '/apple-touch-icon.png', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/static/apple-touch-icon/handler.ts b/edge/endpoints/static/apple-touch-icon/handler.ts new file mode 100644 index 0000000..ae1f398 --- /dev/null +++ b/edge/endpoints/static/apple-touch-icon/handler.ts @@ -0,0 +1,23 @@ +/** + * Apple Touch Icon Static Handler + * + * GET /apple-touch-icon.png + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = function () { + return Response.redirect('https://bundlejs.com/favicon/apple-touch-icon.png') +} + +export default Handler diff --git a/edge/endpoints/static/favicon/definition.ts b/edge/endpoints/static/favicon/definition.ts new file mode 100644 index 0000000..798ed03 --- /dev/null +++ b/edge/endpoints/static/favicon/definition.ts @@ -0,0 +1,22 @@ +/** + * Favicon Static Endpoint Definition + * + * GET /favicon.ico + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'favicon', + Route: '/favicon.ico', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/static/favicon/handler.ts b/edge/endpoints/static/favicon/handler.ts new file mode 100644 index 0000000..ef57c3f --- /dev/null +++ b/edge/endpoints/static/favicon/handler.ts @@ -0,0 +1,23 @@ +/** + * Favicon Static Handler + * + * GET /favicon.ico + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = function () { + return Response.redirect('https://bundlejs.com/favicon/favicon-api.ico') +} + +export default Handler diff --git a/edge/endpoints/static/llms/definition.ts b/edge/endpoints/static/llms/definition.ts new file mode 100644 index 0000000..abf3dbb --- /dev/null +++ b/edge/endpoints/static/llms/definition.ts @@ -0,0 +1,22 @@ +/** + * LLMS Static Endpoint Definition + * + * GET /llms.txt + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'llms', + Route: '/llms.txt', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/static/llms/handler.ts b/edge/endpoints/static/llms/handler.ts new file mode 100644 index 0000000..245c914 --- /dev/null +++ b/edge/endpoints/static/llms/handler.ts @@ -0,0 +1,23 @@ +/** + * LLMS Static Handler + * + * GET /llms.txt + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = function () { + return Response.json({ message: 'no' }) +} + +export default Handler diff --git a/edge/endpoints/static/openapi/definition.ts b/edge/endpoints/static/openapi/definition.ts new file mode 100644 index 0000000..00be4d2 --- /dev/null +++ b/edge/endpoints/static/openapi/definition.ts @@ -0,0 +1,22 @@ +/** + * OpenAPI Static Endpoint Definition + * + * GET /.well-known/openapi.yaml + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'openapi', + Route: '/.well-known/openapi.yaml', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/static/openapi/handler.ts b/edge/endpoints/static/openapi/handler.ts new file mode 100644 index 0000000..b1965a8 --- /dev/null +++ b/edge/endpoints/static/openapi/handler.ts @@ -0,0 +1,32 @@ +/** + * OpenAPI Static Handler + * + * GET /.well-known/openapi.yaml + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +const OPENAPI_PATH = new URL('../../../static/.well-known/openapi.yaml', import.meta.url) + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function () { + const contents = await Deno.readFile(OPENAPI_PATH) + return new Response(contents, { + status: 200, + headers: { + 'Content-Type': 'text/yaml', + 'Cache-Control': 'max-age=180, public', + }, + }) +} + +export default Handler diff --git a/edge/endpoints/static/plugin/definition.ts b/edge/endpoints/static/plugin/definition.ts new file mode 100644 index 0000000..a5322c8 --- /dev/null +++ b/edge/endpoints/static/plugin/definition.ts @@ -0,0 +1,22 @@ +/** + * AI Plugin Static Endpoint Definition + * + * GET /.well-known/ai-plugin.json + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'plugin', + Route: '/.well-known/ai-plugin.json', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/static/plugin/handler.ts b/edge/endpoints/static/plugin/handler.ts new file mode 100644 index 0000000..f52e4ae --- /dev/null +++ b/edge/endpoints/static/plugin/handler.ts @@ -0,0 +1,32 @@ +/** + * AI Plugin Static Handler + * + * GET /.well-known/ai-plugin.json + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +const PLUGIN_PATH = new URL('../../../static/.well-known/ai-plugin.json', import.meta.url) + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = async function () { + const contents = await Deno.readFile(PLUGIN_PATH) + return new Response(contents, { + status: 200, + headers: { + 'Content-Type': 'application/json', + 'Cache-Control': 'max-age=180, public', + }, + }) +} + +export default Handler diff --git a/edge/endpoints/static/robots/definition.ts b/edge/endpoints/static/robots/definition.ts new file mode 100644 index 0000000..a54ac4f --- /dev/null +++ b/edge/endpoints/static/robots/definition.ts @@ -0,0 +1,22 @@ +/** + * Robots Static Endpoint Definition + * + * GET /robots.txt + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'robots', + Route: '/robots.txt', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/static/robots/handler.ts b/edge/endpoints/static/robots/handler.ts new file mode 100644 index 0000000..5358700 --- /dev/null +++ b/edge/endpoints/static/robots/handler.ts @@ -0,0 +1,23 @@ +/** + * Robots Static Handler + * + * GET /robots.txt + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = function () { + return Response.json({ message: 'no' }) +} + +export default Handler diff --git a/edge/endpoints/static/sw/definition.ts b/edge/endpoints/static/sw/definition.ts new file mode 100644 index 0000000..0d6de29 --- /dev/null +++ b/edge/endpoints/static/sw/definition.ts @@ -0,0 +1,22 @@ +/** + * Service Worker Static Endpoint Definition + * + * GET /sw.js + */ + +import type { EndpointDefinition } from '#shared/server/types.ts' +import { z } from 'zod' +import { BaseQuerySchema } from '#shared/server/schemas.ts' + +export const QuerySchema = BaseQuerySchema + +export default { + Name: 'sw', + Route: '/sw.js', + Methods: ['GET'] as const, + Input: QuerySchema, + Output: z.any(), + Schemas: { + Query: QuerySchema, + }, +} as const satisfies EndpointDefinition diff --git a/edge/endpoints/static/sw/handler.ts b/edge/endpoints/static/sw/handler.ts new file mode 100644 index 0000000..633369a --- /dev/null +++ b/edge/endpoints/static/sw/handler.ts @@ -0,0 +1,23 @@ +/** + * Service Worker Static Handler + * + * GET /sw.js + */ + +import type { EndpointHandler, EndpointMiddlewareHandler, FunctionAppEnv } from '#shared/server/types.ts' + +import { createValidator } from '#shared/middleware/validation.ts' + +import Definition from './definition.ts' + +export type AppEnv = FunctionAppEnv + +export const Middleware: EndpointMiddlewareHandler[] = [ + createValidator('query', Definition.Schemas.Query), +] + +export const Handler: EndpointHandler = function () { + return Response.json({ message: 'no' }) +} + +export default Handler diff --git a/edge/index.ts b/edge/index.ts index 9f690e2..61040ad 100644 --- a/edge/index.ts +++ b/edge/index.ts @@ -30,11 +30,16 @@ import * as CacheClearHandler from './endpoints/cache/clear/handler.ts' import * as OpenApiHandler from './endpoints/static/openapi/handler.ts' import * as PluginHandler from './endpoints/static/plugin/handler.ts' import * as RobotsHandler from './endpoints/static/robots/handler.ts' +import * as LlmHandler from './endpoints/static/llms/handler.ts' +import * as ServiceWorkerHandler from './endpoints/static/sw/handler.ts' +import * as FaviconHandler from './endpoints/static/favicon/handler.ts' +import * as AppleTouchIconHandler from './endpoints/static/apple-touch-icon/handler.ts' +import * as AppleTouchIconPrecomposedHandler from './endpoints/static/apple-touch-icon-precomposed/handler.ts' import * as HealthHandler from './endpoints/health/handler.ts' import { EndpointDefinitions } from './endpoints/bundle/mod.ts' -import { registerLegacyRoutes } from './endpoints/bundle/legacy/routes.ts' +import { registerLegacyRoutes } from './endpoints/legacy/routes.ts' // ============================================================================ // Handler Registry @@ -61,6 +66,11 @@ export const EndpointHandlers = { [EndpointDefinitions.OpenApi.Name]: OpenApiHandler, [EndpointDefinitions.Plugin.Name]: PluginHandler, [EndpointDefinitions.Robots.Name]: RobotsHandler, + [EndpointDefinitions.Llm.Name]: LlmHandler, + [EndpointDefinitions.ServiceWorker.Name]: ServiceWorkerHandler, + [EndpointDefinitions.Favicon.Name]: FaviconHandler, + [EndpointDefinitions.AppleTouchIcon.Name]: AppleTouchIconHandler, + [EndpointDefinitions.AppleTouchIconPrecomposed.Name]: AppleTouchIconPrecomposedHandler, // Health [EndpointDefinitions.Health.Name]: HealthHandler, @@ -86,7 +96,7 @@ const app = createApp('bundle', { Object.values(EndpointDefinitions).forEach((endpoint) => { const route = endpoint.Route - const methods = Array.from(new Set(endpoint.Methods)) as Array + const methods = Array.from(new Set(endpoint.Methods)) as Array< 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' > @@ -99,7 +109,7 @@ Object.values(EndpointDefinitions).forEach((endpoint) => { return } - app.on(methods, route, ...middleware, handler) + app.on(methods, [route], ...middleware, handler) }) // Register legacy routes for backward compatibility -- knotmirror 0.0.1