{"version":3,"file":"fastify.mjs","names":[],"sources":["../src/adapters/fastify.ts"],"sourcesContent":["import type { FastifyReply, FastifyRequest } from \"fastify\";\nimport {\n  type IdCodec,\n  type IdParamFailure,\n  type IdVerifiableCodec,\n  resolveIdParamFailure,\n  resolveVerifyFailure,\n} from \"./adapter-types.js\";\nimport type { Id } from \"../types.js\";\n\nexport type { IdParamFailure };\n\n/**\n * Typed error thrown into Fastify's `setErrorHandler` on validation failure.\n * Inspect `err.reason` and `err.statusCode` in your error handler.\n */\nexport class IdParamError extends Error {\n  readonly statusCode: number;\n  readonly reason: \"brand_mismatch\" | \"malformed\";\n\n  constructor(reason: \"brand_mismatch\" | \"malformed\", statusCode: number) {\n    super(`ID validation failed: ${reason}`);\n    this.name = \"IdParamError\";\n    this.reason = reason;\n    this.statusCode = statusCode;\n  }\n}\n\n/**\n * Options for `idParam` and `idQuery`. All fields are optional.\n *\n * **Default validation is structural** — `safeParse` checks prefix and base32 form but does not\n * verify any cryptographic tag. For IDs using a codec that satisfies {@link IdVerifiableCodec}\n * (the **Signed Timestamp codec** or **Wrapped key codec**), set `verify: true` to also authenticate the tag.\n */\nexport type IdParamOptions = {\n  /**\n   * Called when ID validation fails. If the hook sends a response (i.e. `reply.sent` is\n   * `true` after the hook resolves), the adapter takes no further action. If the hook\n   * returns without sending a response, the adapter falls back to its default error\n   * behavior — throwing `IdParamError` — so the route handler never runs with an\n   * invalid or missing ID.\n   */\n  onError?: (\n    failure: IdParamFailure,\n    request: FastifyRequest,\n    reply: FastifyReply,\n  ) => void | Promise<void>;\n  /**\n   * Remap the default HTTP status for a failure reason without a full handler.\n   * e.g. `{ brand_mismatch: 400 }` treats both failure kinds as 400.\n   */\n  status?: { brand_mismatch?: number; malformed?: number };\n};\n\n/**\n * Extends {@link IdParamOptions} with opt-in HMAC tag verification.\n * Only accepted when the codec satisfies {@link IdVerifiableCodec} (the **Signed Timestamp codec** or **Wrapped key codec**).\n * When `verify` is truthy, the adapter calls `codec.safeVerify(raw)` after structural parse succeeds;\n * a tag mismatch is routed through the existing `\"malformed\"` failure path.\n */\nexport type IdParamVerifyOptions = IdParamOptions & {\n  /** When truthy, calls `codec.safeVerify(raw)` after structural parse and treats a tag failure as `\"malformed\"`. Accepts any boolean so computed flags (`{ verify: cfg.verifyIds }`) compile without casting. */\n  verify?: boolean;\n};\n\nasync function emitFailure(\n  failure: IdParamFailure,\n  options: IdParamOptions | undefined,\n  request: FastifyRequest,\n  reply: FastifyReply,\n): Promise<void> {\n  if (options?.onError) {\n    await options.onError(failure, request, reply);\n    if (!reply.sent) {\n      throw new IdParamError(failure.reason, failure.status);\n    }\n    return;\n  }\n  throw new IdParamError(failure.reason, failure.status);\n}\n\n/**\n * Fastify `preHandler` hook factory that validates a named route param against a codec via `safeParse`.\n *\n * **Default (no options):** throws `IdParamError` carrying `statusCode` and `reason` so the app's\n * existing `setErrorHandler` controls rendering. The adapter does not write a response body itself.\n *\n * **`options.onError`:** when provided, the adapter awaits the hook on validation failure. If the\n * hook sends a response (`reply.sent` is `true` after it resolves), the adapter takes no further\n * action. Otherwise, the adapter falls back to throwing `IdParamError`, so the route handler\n * never runs with an invalid ID.\n *\n * **`options.status`:** remaps the default HTTP status for a reason without a full handler.\n *\n * - **Brand mismatch (`invalid_prefix`) → `reason: \"brand_mismatch\"`, default 404**\n * - **Malformed or missing ID → `reason: \"malformed\"`, default 400**\n *\n * **Storage:** on success, stores the canonical `Id<Brand>` in `request.params[paramName]` by mutating\n * the params object in place. This contrasts with the Express adapter, which writes to `res.locals[paramName]`.\n * Fastify writes to `request.params` in place because Fastify's preHandler lifecycle runs before the route\n * handler and its `request` object is the idiomatic side-channel for enriched request data; there is no\n * `reply.locals` equivalent in Fastify.\n *\n * **Return type note:** the returned hook is typed as\n * `(request: FastifyRequest<{ Params: Record<string, Id<Brand>> }>, reply: FastifyReply) => Promise<void>`.\n * Assigning it to a Fastify `preHandler` slot is backward-compatible (method-signature bivariance applies).\n * However, a locally-annotated variable typed as the bare `(request: FastifyRequest, reply: FastifyReply) => Promise<void>`\n * will produce a TypeScript error under `--strictFunctionTypes` because function parameter types are contravariant.\n * Use `preHandler` assignment or let TypeScript infer the type to avoid this.\n *\n * @example\n * ```ts\n * import { idParam, IdParamError } from \"@smonn/ids/fastify\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n *\n * // Default: throws IdParamError → setErrorHandler renders it\n * fastify.get(\"/users/:id\", { preHandler: idParam(\"id\", usr) }, (request, reply) => {\n *   const id = request.params.id; // string (compile-time); Id<\"usr\"> at runtime after preHandler\n * });\n *\n * // Error handler receives the typed error\n * fastify.setErrorHandler((err, request, reply) => {\n *   if (err instanceof IdParamError) {\n *     reply.status(err.statusCode).send({ error: err.reason });\n *     return;\n *   }\n *   reply.send(err);\n * });\n *\n * // Override: consumer fully owns the error response\n * fastify.get(\"/orgs/:id\", {\n *   preHandler: idParam(\"id\", org, {\n *     onError: (failure, request, reply) =>\n *       reply.status(failure.status).send({ error: failure.reason }),\n *   }),\n * }, handler);\n *\n * // Or a lightweight status remap without a full handler\n * fastify.get(\"/things/:id\", {\n *   preHandler: idParam(\"id\", thing, { status: { brand_mismatch: 400 } }),\n * }, handler);\n * ```\n */\nexport function idParam<ParamKey extends string, Brand extends string>(\n  paramName: ParamKey,\n  codec: IdVerifiableCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): (\n  request: FastifyRequest<{ Params: Record<string, Id<Brand>> }>,\n  reply: FastifyReply,\n) => Promise<void>;\nexport function idParam<ParamKey extends string, Brand extends string>(\n  paramName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamOptions,\n): (\n  request: FastifyRequest<{ Params: Record<string, Id<Brand>> }>,\n  reply: FastifyReply,\n) => Promise<void>;\nexport function idParam<ParamKey extends string, Brand extends string>(\n  paramName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): (\n  request: FastifyRequest<{ Params: Record<string, Id<Brand>> }>,\n  reply: FastifyReply,\n) => Promise<void> {\n  return async (request, reply): Promise<void> => {\n    const raw = request.params[paramName];\n    const result = codec.safeParse(raw);\n    if (!result.ok) {\n      await emitFailure(resolveIdParamFailure(result.error, options), options, request, reply);\n      return;\n    }\n    if (options?.verify) {\n      const verifyResult = await (codec as IdVerifiableCodec<Brand>).safeVerify(raw);\n      if (!verifyResult.ok) {\n        await emitFailure(resolveVerifyFailure(options), options, request, reply);\n        return;\n      }\n    }\n    request.params[paramName] = result.id;\n  };\n}\n\n/**\n * Fastify `preHandler` hook factory that validates a named query-string param against a codec\n * via `safeParse`.\n *\n * Same failure contract as `idParam` — same `IdParamOptions` / `IdParamFailure` shape, same\n * `IdParamError` thrown into `setErrorHandler` — but reads `request.query[queryName]` instead of\n * `request.params`.\n *\n * **Default (no options):** throws `IdParamError` carrying `statusCode` and `reason` so the\n * app's existing `setErrorHandler` controls rendering. The adapter does not write a response\n * body itself.\n *\n * **`options.onError`:** when provided, the adapter awaits the hook on validation failure. If the\n * hook sends a response (`reply.sent` is `true` after it resolves), the adapter takes no further\n * action. Otherwise, the adapter falls back to throwing `IdParamError`, so the route handler\n * never runs with an invalid ID.\n *\n * **`options.status`:** remaps the default HTTP status for a reason without a full handler.\n *\n * - **Brand mismatch (`invalid_prefix`) → `reason: \"brand_mismatch\"`, default 404**\n * - **Malformed or missing query param → `reason: \"malformed\"`, default 400**\n *\n * **Storage:** on success, stores the canonical `Id<Brand>` in `request.query[queryName]` by mutating\n * the query object in place. This contrasts with the Express adapter, which writes to `res.locals[queryName]`.\n * See the `idParam` JSDoc for the rationale on in-place mutation.\n *\n * @example\n * ```ts\n * import { idQuery, IdParamError } from \"@smonn/ids/fastify\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n *\n * // Default: throws IdParamError → setErrorHandler renders it\n * // GET /users?userId=usr_...\n * fastify.get(\"/users\", { preHandler: idQuery(\"userId\", usr) }, (request, reply) => {\n *   const userId = request.query.userId; // string (compile-time); Id<\"usr\"> at runtime\n * });\n *\n * // Override: consumer fully owns the error response\n * fastify.get(\"/search\", {\n *   preHandler: idQuery(\"cursor\", usr, {\n *     onError: (failure, request, reply) =>\n *       reply.status(failure.status).send({ error: failure.reason }),\n *   }),\n * }, handler);\n * ```\n */\nexport function idQuery<ParamKey extends string, Brand extends string>(\n  queryName: ParamKey,\n  codec: IdVerifiableCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): (\n  request: FastifyRequest<{ Querystring: Record<string, Id<Brand>> }>,\n  reply: FastifyReply,\n) => Promise<void>;\nexport function idQuery<ParamKey extends string, Brand extends string>(\n  queryName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamOptions,\n): (\n  request: FastifyRequest<{ Querystring: Record<string, Id<Brand>> }>,\n  reply: FastifyReply,\n) => Promise<void>;\nexport function idQuery<ParamKey extends string, Brand extends string>(\n  queryName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): (\n  request: FastifyRequest<{ Querystring: Record<string, Id<Brand>> }>,\n  reply: FastifyReply,\n) => Promise<void> {\n  return async (request, reply): Promise<void> => {\n    const raw = request.query[queryName];\n    const result = codec.safeParse(raw);\n    if (!result.ok) {\n      await emitFailure(resolveIdParamFailure(result.error, options), options, request, reply);\n      return;\n    }\n    if (options?.verify) {\n      const verifyResult = await (codec as IdVerifiableCodec<Brand>).safeVerify(raw);\n      if (!verifyResult.ok) {\n        await emitFailure(resolveVerifyFailure(options), options, request, reply);\n        return;\n      }\n    }\n    request.query[queryName] = result.id;\n  };\n}\n"],"mappings":";;;;;;AAgBA,IAAa,eAAb,cAAkC,MAAM;CACtC;CACA;CAEA,YAAY,QAAwC,YAAoB;EACtE,MAAM,yBAAyB,QAAQ;EACvC,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,aAAa;CACpB;AACF;AAwCA,eAAe,YACb,SACA,SACA,SACA,OACe;CACf,IAAI,SAAS,SAAS;EACpB,MAAM,QAAQ,QAAQ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