{"version":3,"file":"express.mjs","names":[],"sources":["../src/adapters/express.ts"],"sourcesContent":["import type { NextFunction, Request, Response } from \"express\";\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 forwarded to Express's error pipeline (`next(err)`) on validation failure.\n * Inspect `err.reason` and `err.status` in error-handling middleware.\n */\nexport class IdParamError extends Error {\n  readonly status: number;\n  readonly reason: \"brand_mismatch\" | \"malformed\";\n\n  constructor(reason: \"brand_mismatch\" | \"malformed\", status: number) {\n    super(`ID validation failed: ${reason}`);\n    this.name = \"IdParamError\";\n    this.reason = reason;\n    this.status = status;\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. `res.headersSent`\n   * is `true` after the hook returns), the adapter takes no further action. If the hook\n   * returns without sending a response — including if it calls `next()` instead of\n   * `next(err)` — the adapter falls back to its default error behavior and calls\n   * `next(new IdParamError(...))`, ensuring the route handler never runs with an\n   * invalid or missing ID.\n   */\n  onError?: (failure: IdParamFailure, req: Request, res: Response, next: NextFunction) => 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\nfunction storeLocal(res: Response, key: string, id: unknown): void {\n  // Deliberate: Object.defineProperty over plain assignment — proto-safety; always writes an own property regardless of res.locals prototype. See CONTEXT.md postures.\n  Object.defineProperty(res.locals, key, {\n    enumerable: true,\n    writable: true,\n    configurable: true,\n    value: id,\n  });\n}\n\nfunction emitFailure(\n  failure: IdParamFailure,\n  options: IdParamOptions | undefined,\n  req: Request,\n  res: Response,\n  next: NextFunction,\n): void {\n  if (options?.onError) {\n    let nextCalledWithError = false;\n    const hookNext: NextFunction = (err?: unknown): void => {\n      if (err !== undefined) {\n        nextCalledWithError = true;\n        next(err);\n      }\n    };\n    options.onError(failure, req, res, hookNext);\n    if (!nextCalledWithError && !res.headersSent) {\n      next(new IdParamError(failure.reason, failure.status));\n    }\n    return;\n  }\n  next(new IdParamError(failure.reason, failure.status));\n}\n\n/**\n * Express middleware that validates a named route param against a codec via `safeParse`.\n *\n * **Default (no options):** calls `next(err)` with an `IdParamError` carrying `status` and `reason`,\n * so the app's existing error-handling middleware controls rendering. The adapter does not write\n * a response body itself.\n *\n * **`options.onError`:** when provided, the adapter calls the hook on validation failure. If\n * the hook sends a response (`res.headersSent` is `true` after it returns), the adapter takes\n * no further action. Otherwise — including if the hook calls `next()` instead of `next(err)` —\n * the adapter falls back to `next(new IdParamError(...))`, so the route handler never runs with\n * 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 `res.locals[paramName]` and calls `next()`.\n * This contrasts with the Fastify adapter, which mutates `request.params[paramName]` in place.\n * Express writes to `res.locals` because it has no mutable `request.params` contract that is safe\n * to write to — `req.params` is populated by Express's router and is not intended as a side-channel\n * for middleware output, while `res.locals` is the idiomatic per-request storage object.\n *\n * @example\n * ```ts\n * import { idParam, IdParamError } from \"@smonn/ids/express\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n *\n * // Default: forwards error to app error-handling middleware\n * app.get(\"/users/:id\", idParam(\"id\", usr), (req, res) => {\n *   const id = res.locals.id; // Id<\"usr\">, canonical\n * });\n *\n * // Error-handling middleware receives the typed error\n * app.use((err, req, res, next) => {\n *   if (err instanceof IdParamError) {\n *     res.status(err.status).json({ error: err.reason });\n *     return;\n *   }\n *   next(err);\n * });\n *\n * // Override: consumer fully owns the response\n * app.get(\"/orgs/:id\", idParam(\"id\", org, {\n *   onError: (failure, req, res) => res.status(failure.status).json({ error: failure.reason }),\n * }), handler);\n *\n * // Or a lightweight status remap without a full handler\n * app.get(\"/things/:id\", idParam(\"id\", thing, { status: { brand_mismatch: 400 } }), handler);\n * ```\n */\nexport function idParam<ParamKey extends string, Brand extends string>(\n  paramName: ParamKey,\n  codec: IdVerifiableCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): (req: Request, res: Response<unknown, Record<ParamKey, Id<Brand>>>, next: NextFunction) => void;\nexport function idParam<ParamKey extends string, Brand extends string>(\n  paramName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamOptions,\n): (req: Request, res: Response<unknown, Record<ParamKey, Id<Brand>>>, next: NextFunction) => void;\nexport function idParam<ParamKey extends string, Brand extends string>(\n  paramName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): (req: Request, res: Response<unknown, Record<ParamKey, Id<Brand>>>, next: NextFunction) => void {\n  return (req, res, next): void => {\n    const raw = req.params[paramName];\n    const result = codec.safeParse(raw);\n    if (!result.ok) {\n      emitFailure(resolveIdParamFailure(result.error, options), options, req, res, next);\n      return;\n    }\n    if (options?.verify) {\n      (codec as IdVerifiableCodec<Brand>)\n        .safeVerify(raw)\n        .then((verifyResult) => {\n          if (!verifyResult.ok) {\n            emitFailure(resolveVerifyFailure(options), options, req, res, next);\n            return;\n          }\n          storeLocal(res, paramName, result.id);\n          next();\n        })\n        .catch((err: unknown) => next(err));\n      return;\n    }\n    storeLocal(res, paramName, result.id);\n    next();\n  };\n}\n\n/**\n * Express middleware that validates a named query-string param against a codec via `safeParse`.\n *\n * Same failure contract as `idParam` — same `IdParamOptions` / `IdParamFailure` shape, same\n * `IdParamError` forwarded to `next(err)` — but reads `req.query[queryName]` instead of\n * `req.params[queryName]`.\n *\n * **Default (no options):** calls `next(err)` with an `IdParamError` carrying `status` and\n * `reason`, so the app's existing error-handling middleware controls rendering. The adapter\n * does not write a response body itself.\n *\n * **`options.onError`:** when provided, the adapter calls the hook on validation failure. If\n * the hook sends a response (`res.headersSent` is `true` after it returns), the adapter takes\n * no further action. Otherwise — including if the hook calls `next()` instead of `next(err)` —\n * the adapter falls back to `next(new IdParamError(...))`, so the route handler never runs with\n * 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 `res.locals[queryName]` and calls `next()`.\n * This contrasts with the Fastify adapter, which mutates `request.query[queryName]` in place. See\n * the `idParam` JSDoc for the rationale on the `res.locals` choice.\n *\n * @example\n * ```ts\n * import { idQuery, IdParamError } from \"@smonn/ids/express\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n *\n * // Default: forwards error to app error-handling middleware\n * // GET /users?userId=usr_...\n * app.get(\"/users\", idQuery(\"userId\", usr), (req, res) => {\n *   const userId = res.locals.userId; // Id<\"usr\">, canonical\n * });\n *\n * // Override: consumer fully owns the response\n * app.get(\"/search\", idQuery(\"cursor\", usr, {\n *   onError: (failure, req, res) => res.status(failure.status).json({ error: failure.reason }),\n * }), handler);\n * ```\n */\nexport function idQuery<ParamKey extends string, Brand extends string>(\n  queryName: ParamKey,\n  codec: IdVerifiableCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): (req: Request, res: Response<unknown, Record<ParamKey, Id<Brand>>>, next: NextFunction) => void;\nexport function idQuery<ParamKey extends string, Brand extends string>(\n  queryName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamOptions,\n): (req: Request, res: Response<unknown, Record<ParamKey, Id<Brand>>>, next: NextFunction) => void;\nexport function idQuery<ParamKey extends string, Brand extends string>(\n  queryName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): (req: Request, res: Response<unknown, Record<ParamKey, Id<Brand>>>, next: NextFunction) => void {\n  return (req, res, next): void => {\n    const raw: unknown = req.query[queryName];\n    const result = codec.safeParse(raw);\n    if (!result.ok) {\n      emitFailure(resolveIdParamFailure(result.error, options), options, req, res, next);\n      return;\n    }\n    if (options?.verify) {\n      (codec as IdVerifiableCodec<Brand>)\n        .safeVerify(raw)\n        .then((verifyResult) => {\n          if (!verifyResult.ok) {\n            emitFailure(resolveVerifyFailure(options), options, req, res, next);\n            return;\n          }\n          storeLocal(res, queryName, result.id);\n          next();\n        })\n        .catch((err: unknown) => next(err));\n      return;\n    }\n    storeLocal(res, queryName, result.id);\n    next();\n  };\n}\n"],"mappings":";;;;;;AAgBA,IAAa,eAAb,cAAkC,MAAM;CACtC;CACA;CAEA,YAAY,QAAwC,QAAgB;EAClE,MAAM,yBAAyB,QAAQ;EACvC,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;AACF;AAqCA,SAAS,WAAW,KAAe,KAAa,IAAmB;CAEjE,OAAO,eAAe,IAAI,QAAQ,KAAK;EACrC,YAAY;EACZ,UAAU;EACV,cAAc;EACd,OAAO;CACT,CAA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