Files
klz-cables.com/.pnpm-store/v10/files/a4/9787d7b4db884380c11a146ba289864ef846d96f5f52134a7b61eb56e09106b36b7c08d9ab544676f36d52552f1705da680f7f6bd63bb44af7ccbf6808eab5
Marc Mintel 5397309103
Some checks failed
Build & Deploy / 🔍 Prepare (push) Successful in 20s
Build & Deploy / 🧪 QA (push) Failing after 34s
Build & Deploy / 🏗️ Build (push) Has started running
Build & Deploy / 🚀 Deploy (push) Has been cancelled
Build & Deploy / 🧪 Smoke Test (push) Has been cancelled
Build & Deploy / ⚡ Lighthouse (push) Has been cancelled
Build & Deploy / 🔔 Notify (push) Has been cancelled
fix(products): fix breadcrumbs and product filtering (backport from main)
2026-02-24 16:04:21 +01:00

1 line
13 KiB
Plaintext

{"version":3,"sources":["../../src/utilities/handleEndpoints.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\nimport { match } from 'path-to-regexp'\n\nimport type { Collection } from '../collections/config/types.js'\nimport type { Endpoint, PayloadHandler, SanitizedConfig } from '../config/types.js'\nimport type { APIError } from '../errors/APIError.js'\nimport type { GlobalConfig } from '../globals/config/types.js'\nimport type { PayloadRequest } from '../types/index.js'\n\nimport { createPayloadRequest } from './createPayloadRequest.js'\nimport { formatAdminURL } from './formatAdminURL.js'\nimport { headersWithCors } from './headersWithCors.js'\nimport { mergeHeaders } from './mergeHeaders.js'\nimport { routeError } from './routeError.js'\n\nconst notFoundResponse = (req: PayloadRequest, pathname?: string) => {\n return Response.json(\n {\n message: `Route not found \"${pathname ?? new URL(req.url!).pathname}\"`,\n },\n {\n headers: headersWithCors({\n headers: new Headers(),\n req,\n }),\n status: httpStatus.NOT_FOUND,\n },\n )\n}\n\n/**\n * Attaches the Payload REST API to any backend framework that uses Fetch Request/Response\n * like Next.js (app router), Remix, Bun, Hono.\n *\n * ### Example: Using Hono\n * ```ts\n * import { handleEndpoints } from 'payload';\n * import { serve } from '@hono/node-server';\n * import { loadEnv } from 'payload/node';\n *\n * const port = 3001;\n * loadEnv();\n *\n * const { default: config } = await import('@payload-config');\n *\n * const server = serve({\n * fetch: async (request) => {\n * const response = await handleEndpoints({\n * config,\n * request: request.clone(),\n * });\n *\n * return response;\n * },\n * port,\n * });\n *\n * server.on('listening', () => {\n * console.log(`API server is listening on http://localhost:${port}/api`);\n * });\n * ```\n */\nexport const handleEndpoints = async ({\n basePath = '',\n config: incomingConfig,\n path,\n payloadInstanceCacheKey,\n request,\n}: {\n basePath?: string\n config: Promise<SanitizedConfig> | SanitizedConfig\n /** Override path from the request */\n path?: string\n payloadInstanceCacheKey?: string\n request: Request\n}): Promise<Response> => {\n let handler!: PayloadHandler\n let req: PayloadRequest\n let collection!: Collection\n\n // This can be used against GET request search params size limit.\n // Instead you can do POST request with a text body as search params.\n // We use this internally for relationships querying on the frontend\n // packages/ui/src/fields/Relationship/index.tsx\n if (\n request.method.toLowerCase() === 'post' &&\n (request.headers.get('X-Payload-HTTP-Method-Override') === 'GET' ||\n request.headers.get('X-HTTP-Method-Override') === 'GET')\n ) {\n let url = request.url\n let data: any = undefined\n\n if (request.headers.get('Content-Type') === 'application/x-www-form-urlencoded') {\n const search = await request.text()\n url = `${request.url}?${search}`\n } else if (request.headers.get('Content-Type') === 'application/json') {\n // May not be supported by every endpoint\n data = await request.json()\n\n // locale and fallbackLocale is read by createPayloadRequest to populate req.locale and req.fallbackLocale\n // => add to searchParams\n if (data?.locale) {\n url += `?locale=${data.locale}`\n }\n if (data?.fallbackLocale) {\n url += `&fallbackLocale=${data.depth}`\n }\n }\n\n const req = new Request(url, {\n // @ts-expect-error // TODO: check if this is required\n cache: request.cache,\n credentials: request.credentials,\n headers: request.headers,\n method: 'GET',\n signal: request.signal,\n })\n\n if (data) {\n // @ts-expect-error attach data to request - less overhead than using urlencoded\n req.data = data\n }\n\n const response = await handleEndpoints({\n basePath,\n config: incomingConfig,\n path,\n payloadInstanceCacheKey,\n request: req,\n })\n\n return response\n }\n\n try {\n req = await createPayloadRequest({\n canSetHeaders: true,\n config: incomingConfig,\n payloadInstanceCacheKey,\n request,\n })\n\n const { payload } = req\n const { config } = payload\n\n const pathname = path ?? new URL(req.url!).pathname\n const baseAPIPath = formatAdminURL({\n apiRoute: config.routes.api,\n path: '',\n })\n\n if (!pathname.startsWith(baseAPIPath)) {\n return notFoundResponse(req, pathname)\n }\n\n // /api/posts/route -> /posts/route\n let adjustedPathname = pathname.replace(baseAPIPath, '')\n\n let isGlobals = false\n\n // /globals/header/route -> /header/route\n if (adjustedPathname.startsWith('/globals')) {\n isGlobals = true\n adjustedPathname = adjustedPathname.replace('/globals', '')\n }\n\n const segments = adjustedPathname.split('/')\n // remove empty string first element\n segments.shift()\n\n const firstParam = segments[0]\n\n let globalConfig!: GlobalConfig\n\n // first param can be a global slug or collection slug, find the relevant config\n if (firstParam) {\n if (isGlobals) {\n globalConfig = payload.globals.config.find((each) => each.slug === firstParam)!\n } else if (payload.collections[firstParam]) {\n collection = payload.collections[firstParam]\n }\n }\n\n let endpoints: Endpoint[] | false = config.endpoints\n\n if (collection) {\n endpoints = collection.config.endpoints\n // /posts/route -> /route\n adjustedPathname = adjustedPathname.replace(`/${collection.config.slug}`, '')\n } else if (globalConfig) {\n // /header/route -> /route\n adjustedPathname = adjustedPathname.replace(`/${globalConfig.slug}`, '')\n endpoints = globalConfig.endpoints!\n }\n\n // sanitize when endpoint.path is '/'\n if (adjustedPathname === '') {\n adjustedPathname = '/'\n }\n\n if (endpoints === false) {\n return Response.json(\n {\n message: `Cannot ${req.method?.toUpperCase()} ${req.url}`,\n },\n {\n headers: headersWithCors({\n headers: new Headers(),\n req,\n }),\n status: httpStatus.NOT_IMPLEMENTED,\n },\n )\n }\n\n // Find the relevant endpoint configuration\n const endpoint = endpoints?.find((endpoint) => {\n if (endpoint.method !== req.method?.toLowerCase()) {\n return false\n }\n\n const pathMatchFn = match(endpoint.path, { decode: decodeURIComponent })\n\n const matchResult = pathMatchFn(adjustedPathname)\n\n if (!matchResult) {\n return false\n }\n\n req.routeParams = matchResult.params as Record<string, unknown>\n\n // Inject to routeParams the slug as well so it can be used later\n if (collection) {\n req.routeParams.collection = collection.config.slug\n } else if (globalConfig) {\n req.routeParams.global = globalConfig.slug\n }\n\n return true\n })\n\n if (endpoint) {\n handler = endpoint.handler\n }\n\n if (!handler) {\n // If no custom handler found and this is an OPTIONS request,\n // return default CORS response for preflight requests\n if (req.method?.toLowerCase() === 'options') {\n return Response.json(\n {},\n {\n headers: headersWithCors({\n headers: new Headers(),\n req,\n }),\n status: 200,\n },\n )\n }\n\n return notFoundResponse(req, pathname)\n }\n\n const response = await handler(req)\n\n return new Response(response.body, {\n headers: headersWithCors({\n headers: mergeHeaders(req.responseHeaders ?? new Headers(), response.headers),\n req,\n }),\n status: response.status,\n statusText: response.statusText,\n })\n } catch (_err) {\n const err = _err as APIError\n return routeError({\n collection,\n config: incomingConfig,\n err,\n req: req!,\n })\n }\n}\n"],"names":["status","httpStatus","match","createPayloadRequest","formatAdminURL","headersWithCors","mergeHeaders","routeError","notFoundResponse","req","pathname","Response","json","message","URL","url","headers","Headers","NOT_FOUND","handleEndpoints","basePath","config","incomingConfig","path","payloadInstanceCacheKey","request","handler","collection","method","toLowerCase","get","data","undefined","search","text","locale","fallbackLocale","depth","Request","cache","credentials","signal","response","canSetHeaders","payload","baseAPIPath","apiRoute","routes","api","startsWith","adjustedPathname","replace","isGlobals","segments","split","shift","firstParam","globalConfig","globals","find","each","slug","collections","endpoints","toUpperCase","NOT_IMPLEMENTED","endpoint","pathMatchFn","decode","decodeURIComponent","matchResult","routeParams","params","global","body","responseHeaders","statusText","_err","err"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AAClD,SAASC,KAAK,QAAQ,iBAAgB;AAQtC,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,UAAU,QAAQ,kBAAiB;AAE5C,MAAMC,mBAA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