@dodopayments/better-auth 1.3.2 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/chunk-52LQJCF4.js +199 -0
  2. package/dist/chunk-52LQJCF4.js.map +1 -0
  3. package/dist/chunk-FBAIEKOL.js +70 -0
  4. package/dist/chunk-FBAIEKOL.js.map +1 -0
  5. package/dist/chunk-PXI4EHZC.js +12 -0
  6. package/dist/chunk-PXI4EHZC.js.map +1 -0
  7. package/dist/chunk-QR7PLJJQ.js +13943 -0
  8. package/dist/chunk-QR7PLJJQ.js.map +1 -0
  9. package/dist/chunk-WIFOXVZ3.js +291 -0
  10. package/dist/chunk-WIFOXVZ3.js.map +1 -0
  11. package/dist/chunk-YK6XO66Y.js +84 -0
  12. package/dist/chunk-YK6XO66Y.js.map +1 -0
  13. package/dist/chunk-Z7VSWPPK.js +181 -0
  14. package/dist/chunk-Z7VSWPPK.js.map +1 -0
  15. package/dist/client.cjs +36 -0
  16. package/dist/client.cjs.map +1 -0
  17. package/dist/client.d.cts +7 -0
  18. package/dist/client.d.ts +7 -5
  19. package/dist/client.js +6 -5
  20. package/dist/client.js.map +1 -0
  21. package/dist/hooks/customer.cjs +14036 -0
  22. package/dist/hooks/customer.cjs.map +1 -0
  23. package/dist/hooks/customer.d.cts +11 -0
  24. package/dist/hooks/customer.d.ts +11 -4
  25. package/dist/hooks/customer.js +9 -62
  26. package/dist/hooks/customer.js.map +1 -0
  27. package/dist/index.cjs +14793 -0
  28. package/dist/index.cjs.map +1 -0
  29. package/dist/index.d.cts +797 -0
  30. package/dist/index.d.ts +205 -196
  31. package/dist/index.js +55 -34
  32. package/dist/index.js.map +1 -0
  33. package/dist/plugins/checkout.cjs +14424 -0
  34. package/dist/plugins/checkout.cjs.map +1 -0
  35. package/dist/plugins/checkout.d.cts +6 -0
  36. package/dist/plugins/checkout.d.ts +6 -548
  37. package/dist/plugins/checkout.js +8 -170
  38. package/dist/plugins/checkout.js.map +1 -0
  39. package/dist/plugins/portal.cjs +14446 -0
  40. package/dist/plugins/portal.cjs.map +1 -0
  41. package/dist/plugins/portal.d.cts +6 -0
  42. package/dist/plugins/portal.d.ts +6 -204
  43. package/dist/plugins/portal.js +8 -171
  44. package/dist/plugins/portal.js.map +1 -0
  45. package/dist/plugins/webhooks.cjs +14046 -0
  46. package/dist/plugins/webhooks.cjs.map +1 -0
  47. package/dist/plugins/webhooks.d.cts +6 -0
  48. package/dist/plugins/webhooks.d.ts +6 -41
  49. package/dist/plugins/webhooks.js +7 -61
  50. package/dist/plugins/webhooks.js.map +1 -0
  51. package/dist/types-CbotWcHh.d.cts +841 -0
  52. package/dist/types-CbotWcHh.d.ts +841 -0
  53. package/dist/types.cjs +19 -0
  54. package/dist/types.cjs.map +1 -0
  55. package/dist/types.d.cts +6 -0
  56. package/dist/types.d.ts +6 -52
  57. package/dist/types.js +1 -1
  58. package/dist/types.js.map +1 -0
  59. package/package.json +5 -10
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/plugins/portal.ts","../../../../node_modules/uncrypto/dist/crypto.node.mjs","../../../../node_modules/better-call/src/error.ts","../../../../node_modules/better-call/src/utils.ts","../../../../node_modules/better-call/src/to-response.ts","../../../../node_modules/better-call/src/validator.ts","../../../../node_modules/better-call/src/crypto.ts","../../../../node_modules/better-call/src/cookies.ts","../../../../node_modules/better-call/src/context.ts","../../../../node_modules/better-call/src/middleware.ts","../../../../node_modules/better-call/src/endpoint.ts","../../../../node_modules/better-call/src/router.ts","../../../../node_modules/better-call/node_modules/.pnpm/zod@3.24.1/node_modules/zod/lib/index.mjs","../../../../node_modules/better-call/src/openapi.ts","../../../../node_modules/better-auth/dist/shared/better-auth.D4HhkCZJ.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.CW6D9eSx.mjs","../../../../node_modules/@better-auth/utils/dist/base64.mjs","../../../../node_modules/@better-auth/utils/dist/hash.mjs","../../../../node_modules/@noble/ciphers/src/_assert.ts","../../../../node_modules/@noble/ciphers/src/utils.ts","../../../../node_modules/@noble/ciphers/src/_arx.ts","../../../../node_modules/@noble/ciphers/src/_poly1305.ts","../../../../node_modules/@noble/ciphers/src/chacha.ts","../../../../node_modules/@noble/ciphers/src/cryptoNode.ts","../../../../node_modules/@noble/ciphers/src/webcrypto.ts","../../../../node_modules/jose/dist/node/esm/runtime/base64url.js","../../../../node_modules/jose/dist/node/esm/lib/buffer_utils.js","../../../../node_modules/jose/dist/node/esm/util/errors.js","../../../../node_modules/jose/dist/node/esm/runtime/is_key_object.js","../../../../node_modules/jose/dist/node/esm/runtime/webcrypto.js","../../../../node_modules/jose/dist/node/esm/lib/crypto_key.js","../../../../node_modules/jose/dist/node/esm/lib/invalid_key_input.js","../../../../node_modules/jose/dist/node/esm/runtime/is_key_like.js","../../../../node_modules/jose/dist/node/esm/lib/is_disjoint.js","../../../../node_modules/jose/dist/node/esm/lib/is_object.js","../../../../node_modules/jose/dist/node/esm/runtime/get_named_curve.js","../../../../node_modules/jose/dist/node/esm/lib/is_jwk.js","../../../../node_modules/jose/dist/node/esm/runtime/check_key_length.js","../../../../node_modules/jose/dist/node/esm/runtime/jwk_to_key.js","../../../../node_modules/jose/dist/node/esm/key/import.js","../../../../node_modules/jose/dist/node/esm/lib/check_key_type.js","../../../../node_modules/jose/dist/node/esm/lib/validate_crit.js","../../../../node_modules/jose/dist/node/esm/lib/validate_algorithms.js","../../../../node_modules/jose/dist/node/esm/runtime/verify.js","../../../../node_modules/jose/dist/node/esm/runtime/dsa_digest.js","../../../../node_modules/jose/dist/node/esm/runtime/node_key.js","../../../../node_modules/jose/dist/node/esm/runtime/sign.js","../../../../node_modules/jose/dist/node/esm/runtime/hmac_digest.js","../../../../node_modules/jose/dist/node/esm/runtime/get_sign_verify_key.js","../../../../node_modules/jose/dist/node/esm/jws/flattened/verify.js","../../../../node_modules/jose/dist/node/esm/jws/compact/verify.js","../../../../node_modules/jose/dist/node/esm/lib/epoch.js","../../../../node_modules/jose/dist/node/esm/lib/secs.js","../../../../node_modules/jose/dist/node/esm/lib/jwt_claims_set.js","../../../../node_modules/jose/dist/node/esm/jwt/verify.js","../../../../node_modules/jose/dist/node/esm/jws/flattened/sign.js","../../../../node_modules/jose/dist/node/esm/jws/compact/sign.js","../../../../node_modules/jose/dist/node/esm/jwt/produce.js","../../../../node_modules/jose/dist/node/esm/jwt/sign.js","../../../../node_modules/jose/dist/node/esm/jwks/local.js","../../../../node_modules/jose/dist/node/esm/runtime/fetch_jwks.js","../../../../node_modules/jose/dist/node/esm/jwks/remote.js","../../../../node_modules/jose/dist/node/esm/util/base64url.js","../../../../node_modules/jose/dist/node/esm/util/decode_protected_header.js","../../../../node_modules/jose/dist/node/esm/util/decode_jwt.js","../../../../node_modules/@better-auth/utils/dist/hex.mjs","../../../../node_modules/@better-auth/utils/dist/random.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.B4Qoxdgc.mjs","../../../../node_modules/better-auth/dist/crypto/index.mjs","../../../../node_modules/@better-fetch/fetch/src/error.ts","../../../../node_modules/@better-fetch/fetch/src/plugins.ts","../../../../node_modules/@better-fetch/fetch/src/retry.ts","../../../../node_modules/@better-fetch/fetch/src/auth.ts","../../../../node_modules/@better-fetch/fetch/src/utils.ts","../../../../node_modules/@better-fetch/fetch/src/create-fetch/schema.ts","../../../../node_modules/@better-fetch/fetch/src/create-fetch/index.ts","../../../../node_modules/@better-fetch/fetch/src/url.ts","../../../../node_modules/@better-fetch/fetch/src/fetch.ts","../../../../node_modules/better-auth/dist/shared/better-auth.8zoxzg-F.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.DdzSJf-n.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.VTXNLFMT.mjs","../../../../node_modules/@better-auth/utils/dist/hmac.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.tB5eU6EY.mjs","../../../../node_modules/@better-auth/utils/dist/binary.mjs","../../../../node_modules/better-auth/dist/cookies/index.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.DBGfIDnh.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.n2KFGwjY.mjs","../../../../node_modules/defu/dist/defu.mjs","../../../../node_modules/better-auth/dist/api/index.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.C1Ly154X.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.ffWeg50w.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.DGaVMVAI.mjs","../../../../node_modules/better-auth/dist/plugins/access/index.mjs","../../../../node_modules/better-auth/dist/plugins/organization/access/index.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.DXqcUO8W.mjs","../../../../node_modules/better-auth/dist/plugins/two-factor/index.mjs","../../../../node_modules/better-auth/dist/plugins/username/index.mjs","../../../../node_modules/better-auth/dist/plugins/bearer/index.mjs","../../../../node_modules/better-auth/dist/plugins/magic-link/index.mjs","../../../../node_modules/better-auth/dist/plugins/phone-number/index.mjs","../../../../node_modules/better-auth/dist/plugins/anonymous/index.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.DygEm6OX.mjs","../../../../node_modules/better-auth/dist/plugins/admin/access/index.mjs","../../../../node_modules/better-auth/dist/plugins/generic-oauth/index.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.CGrHn1Ih.mjs","../../../../node_modules/better-auth/dist/plugins/jwt/index.mjs","../../../../node_modules/better-auth/dist/plugins/multi-session/index.mjs","../../../../node_modules/better-auth/dist/plugins/email-otp/index.mjs","../../../../node_modules/better-auth/dist/plugins/one-tap/index.mjs","../../../../node_modules/better-auth/dist/plugins/oauth-proxy/index.mjs","../../../../node_modules/better-auth/dist/plugins/custom-session/index.mjs","../../../../node_modules/better-auth/dist/plugins/open-api/index.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.CvxACSRz.mjs","../../../../node_modules/better-auth/dist/plugins/captcha/index.mjs","../../../../node_modules/better-auth/dist/shared/better-auth.Bqt8-7ls.mjs","../../../../node_modules/better-auth/dist/plugins/haveibeenpwned/index.mjs","../../../../node_modules/better-auth/dist/plugins/index.mjs"],"sourcesContent":["import type { DodoPayments } from \"dodopayments\";\nimport { APIError } from \"better-auth/api\";\nimport { sessionMiddleware } from \"better-auth/api\";\nimport { createAuthEndpoint } from \"better-auth/plugins\";\nimport { z } from \"zod/v3\";\nimport {\n CustomerPortalResponse,\n PaymentItems,\n SubscriptionItems,\n} from \"../types\";\n\nexport const portal = () => (dodopayments: DodoPayments) => {\n return {\n dodoPortal: createAuthEndpoint(\n \"/dodopayments/customer/portal\",\n {\n method: \"GET\",\n use: [sessionMiddleware],\n },\n async (ctx): Promise<CustomerPortalResponse> => {\n if (!ctx.context.session?.user.id) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"User not found\",\n });\n }\n\n if (!ctx.context.session?.user.emailVerified) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"User email not verified\",\n });\n }\n\n try {\n const customers = await dodopayments.customers.list({\n email: ctx.context.session?.user.email,\n });\n let customer = customers.items[0];\n\n if (!customer) {\n // upsert the customer, if they don't exist in DodoPayments\n customer = await createCustomer(\n dodopayments,\n ctx.context.session.user.email,\n ctx.context.session.user.name,\n );\n }\n\n const customerSession =\n await dodopayments.customers.customerPortal.create(\n customer.customer_id,\n );\n\n return ctx.json({\n url: customerSession.link,\n redirect: true,\n });\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments customer portal creation failed. Error: ${e.message}`,\n );\n }\n\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Customer portal creation failed\",\n });\n }\n },\n ),\n dodoSubscriptions: createAuthEndpoint(\n \"/dodopayments/customer/subscriptions/list\",\n {\n method: \"GET\",\n query: z\n .object({\n page: z.coerce.number().optional(),\n limit: z.coerce.number().optional(),\n status: z\n .enum([\n \"active\",\n \"cancelled\",\n \"on_hold\",\n \"pending\",\n \"failed\",\n \"expired\",\n ])\n .optional(),\n })\n .optional(),\n use: [sessionMiddleware],\n },\n async (ctx): Promise<SubscriptionItems> => {\n if (!ctx.context.session.user.id) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"User not found\",\n });\n }\n\n if (!ctx.context.session?.user.emailVerified) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"User email not verified\",\n });\n }\n\n try {\n const customers = await dodopayments.customers.list({\n email: ctx.context.session?.user.email,\n });\n let customer = customers.items[0];\n\n if (!customer) {\n // upsert the customer, if they don't exist in DodoPayments\n customer = await createCustomer(\n dodopayments,\n ctx.context.session.user.email,\n ctx.context.session.user.name,\n );\n }\n\n const subscriptions = await dodopayments.subscriptions.list({\n customer_id: customer.customer_id,\n // page number is 0-indexed\n page_number: ctx.query?.page ? ctx.query.page - 1 : undefined,\n page_size: ctx.query?.limit,\n status: ctx.query?.status,\n });\n\n return ctx.json({ items: subscriptions.items });\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments subscriptions list failed. Error: ${e.message}`,\n );\n }\n\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"DodoPayments subscriptions list failed\",\n });\n }\n },\n ),\n dodoPayments: createAuthEndpoint(\n \"/dodopayments/customer/payments/list\",\n {\n method: \"GET\",\n query: z\n .object({\n page: z.coerce.number().optional(),\n limit: z.coerce.number().optional(),\n status: z\n .enum([\n \"succeeded\",\n \"failed\",\n \"cancelled\",\n \"processing\",\n \"requires_customer_action\",\n \"requires_merchant_action\",\n \"requires_payment_method\",\n \"requires_confirmation\",\n \"requires_capture\",\n \"partially_captured\",\n \"partially_captured_and_capturable\",\n ])\n .optional(),\n })\n .optional(),\n use: [sessionMiddleware],\n },\n async (ctx): Promise<PaymentItems> => {\n if (!ctx.context.session.user.id) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"User not found\",\n });\n }\n\n if (!ctx.context.session?.user.emailVerified) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"User email not verified\",\n });\n }\n\n try {\n const customers = await dodopayments.customers.list({\n email: ctx.context.session?.user.email,\n });\n let customer = customers.items[0];\n\n if (!customer) {\n // upsert the customer, if they don't exist in DodoPayments\n customer = await createCustomer(\n dodopayments,\n ctx.context.session.user.email,\n ctx.context.session.user.name,\n );\n }\n\n const payments = await dodopayments.payments.list({\n customer_id: customer.customer_id,\n // page number is 0-indexed\n page_number: ctx.query?.page ? ctx.query.page - 1 : undefined,\n page_size: ctx.query?.limit,\n status: ctx.query?.status,\n });\n\n return ctx.json({ items: payments.items });\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments orders list failed. Error: ${e.message}`,\n );\n }\n\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Orders list failed\",\n });\n }\n },\n ),\n };\n};\n\nasync function createCustomer(\n dodopayments: DodoPayments,\n email: string,\n name: string,\n) {\n const customer = await dodopayments.customers.create({\n email,\n name,\n });\n\n return customer;\n}\n","import nodeCrypto from 'node:crypto';\n\nconst subtle = nodeCrypto.webcrypto?.subtle || {};\nconst randomUUID = () => {\n return nodeCrypto.randomUUID();\n};\nconst getRandomValues = (array) => {\n return nodeCrypto.webcrypto.getRandomValues(array);\n};\nconst _crypto = {\n randomUUID,\n getRandomValues,\n subtle\n};\n\nexport { _crypto as default, getRandomValues, randomUUID, subtle };\n","export const _statusCode = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n\nexport type Status =\n\t| 100\n\t| 101\n\t| 102\n\t| 103\n\t| 200\n\t| 201\n\t| 202\n\t| 203\n\t| 204\n\t| 205\n\t| 206\n\t| 207\n\t| 208\n\t| 226\n\t| 300\n\t| 301\n\t| 302\n\t| 303\n\t| 304\n\t| 305\n\t| 306\n\t| 307\n\t| 308\n\t| 400\n\t| 401\n\t| 402\n\t| 403\n\t| 404\n\t| 405\n\t| 406\n\t| 407\n\t| 408\n\t| 409\n\t| 410\n\t| 411\n\t| 412\n\t| 413\n\t| 414\n\t| 415\n\t| 416\n\t| 417\n\t| 418\n\t| 421\n\t| 422\n\t| 423\n\t| 424\n\t| 425\n\t| 426\n\t| 428\n\t| 429\n\t| 431\n\t| 451\n\t| 500\n\t| 501\n\t| 502\n\t| 503\n\t| 504\n\t| 505\n\t| 506\n\t| 507\n\t| 508\n\t| 510\n\t| 511;\n\nexport class APIError extends Error {\n\tconstructor(\n\t\tpublic status: keyof typeof _statusCode | Status = \"INTERNAL_SERVER_ERROR\",\n\t\tpublic body:\n\t\t\t| ({\n\t\t\t\t\tmessage?: string;\n\t\t\t\t\tcode?: string;\n\t\t\t } & Record<string, any>)\n\t\t\t| undefined = undefined,\n\t\tpublic headers: HeadersInit = {},\n\t\tpublic statusCode = typeof status === \"number\" ? status : _statusCode[status],\n\t) {\n\t\tsuper(body?.message);\n\t\tthis.name = \"APIError\";\n\t\tthis.status = status;\n\t\tthis.headers = headers;\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body\n\t\t\t? {\n\t\t\t\t\tcode: body?.message\n\t\t\t\t\t\t?.toUpperCase()\n\t\t\t\t\t\t.replace(/ /g, \"_\")\n\t\t\t\t\t\t.replace(/[^A-Z0-9_]/g, \"\"),\n\t\t\t\t\t...body,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tthis.stack = \"\";\n\t}\n}\n","import { APIError } from \"./error\";\n\nexport async function getBody(request: Request) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\n\tif (!request.body) {\n\t\treturn undefined;\n\t}\n\n\tif (contentType.includes(\"application/json\")) {\n\t\treturn await request.json();\n\t}\n\n\tif (contentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, string> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, any> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"text/plain\")) {\n\t\treturn await request.text();\n\t}\n\n\tif (contentType.includes(\"application/octet-stream\")) {\n\t\treturn await request.arrayBuffer();\n\t}\n\n\tif (\n\t\tcontentType.includes(\"application/pdf\") ||\n\t\tcontentType.includes(\"image/\") ||\n\t\tcontentType.includes(\"video/\")\n\t) {\n\t\tconst blob = await request.blob();\n\t\treturn blob;\n\t}\n\n\tif (contentType.includes(\"application/stream\") || request.body instanceof ReadableStream) {\n\t\treturn request.body;\n\t}\n\n\treturn await request.text();\n}\n\nexport function isAPIError(error: any) {\n\treturn error instanceof APIError || error?.name === \"APIError\";\n}\n\nexport function tryDecode(str: string) {\n\ttry {\n\t\treturn str.includes(\"%\") ? decodeURIComponent(str) : str;\n\t} catch {\n\t\treturn str;\n\t}\n}\n","import { APIError } from \"./error\";\nimport { isAPIError } from \"./utils\";\n\nfunction isJSONSerializable(value: any) {\n\tif (value === undefined) {\n\t\treturn false;\n\t}\n\tconst t = typeof value;\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n\t\treturn true;\n\t}\n\tif (t !== \"object\") {\n\t\treturn false;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn true;\n\t}\n\tif (value.buffer) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t(value.constructor && value.constructor.name === \"Object\") ||\n\t\ttypeof value.toJSON === \"function\"\n\t);\n}\n\nexport function toResponse(data?: any, init?: ResponseInit): Response {\n\tif (data instanceof Response) {\n\t\tif (init?.headers instanceof Headers) {\n\t\t\tinit.headers.forEach((value, key) => {\n\t\t\t\tdata.headers.set(key, value);\n\t\t\t});\n\t\t}\n\t\treturn data;\n\t}\n\tif (data?._flag === \"json\") {\n\t\tconst routerResponse = data.routerResponse;\n\t\tif (routerResponse instanceof Response) {\n\t\t\treturn routerResponse;\n\t\t}\n\t\treturn toResponse(data.body, {\n\t\t\theaders: data.headers,\n\t\t\tstatus: data.status,\n\t\t});\n\t}\n\tif (isAPIError(data)) {\n\t\treturn toResponse(data.body, {\n\t\t\tstatus: data.statusCode,\n\t\t\tstatusText: data.status.toString(),\n\t\t\theaders: init?.headers || data.headers,\n\t\t});\n\t}\n\tlet body = data;\n\tlet headers = new Headers(init?.headers);\n\tif (!data) {\n\t\tif (data === null) {\n\t\t\tbody = JSON.stringify(null);\n\t\t}\n\t\theaders.set(\"content-type\", \"application/json\");\n\t} else if (typeof data === \"string\") {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"text/plain\");\n\t} else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"application/octet-stream\");\n\t} else if (data instanceof Blob) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", data.type || \"application/octet-stream\");\n\t} else if (data instanceof FormData) {\n\t\tbody = data;\n\t} else if (data instanceof URLSearchParams) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\t} else if (data instanceof ReadableStream) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"application/octet-stream\");\n\t} else if (isJSONSerializable(data)) {\n\t\tbody = JSON.stringify(data, (key, value) => {\n\t\t\tif (typeof value === \"bigint\") {\n\t\t\t\treturn value.toString();\n\t\t\t}\n\t\t\treturn value;\n\t\t});\n\t\theaders.set(\"Content-Type\", \"application/json\");\n\t}\n\n\treturn new Response(body, {\n\t\t...init,\n\t\theaders,\n\t});\n}\n","import type { EndpointOptions } from \"./endpoint\";\nimport type { InputContext } from \"./context\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\n\ntype ValidationResponse =\n\t| {\n\t\t\tdata: {\n\t\t\t\tbody: any;\n\t\t\t\tquery: any;\n\t\t\t};\n\t\t\terror: null;\n\t }\n\t| {\n\t\t\tdata: null;\n\t\t\terror: {\n\t\t\t\tmessage: string;\n\t\t\t};\n\t };\n\n/**\n * Runs validation on body and query\n * @returns error and data object\n */\nexport async function runValidation(\n\toptions: EndpointOptions,\n\tcontext: InputContext<any, any> = {},\n): Promise<ValidationResponse> {\n\tlet request = {\n\t\tbody: context.body,\n\t\tquery: context.query,\n\t} as {\n\t\tbody: any;\n\t\tquery: any;\n\t};\n\tif (options.body) {\n\t\tconst result = await options.body[\"~standard\"].validate(context.body);\n\t\tif (result.issues) {\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: fromError(result.issues, \"body\"),\n\t\t\t};\n\t\t}\n\t\trequest.body = result.value;\n\t}\n\n\tif (options.query) {\n\t\tconst result = await options.query[\"~standard\"].validate(context.query);\n\t\tif (result.issues) {\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: fromError(result.issues, \"query\"),\n\t\t\t};\n\t\t}\n\t\trequest.query = result.value;\n\t}\n\tif (options.requireHeaders && !context.headers) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: { message: \"Headers is required\" },\n\t\t};\n\t}\n\tif (options.requireRequest && !context.request) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: { message: \"Request is required\" },\n\t\t};\n\t}\n\treturn {\n\t\tdata: request,\n\t\terror: null,\n\t};\n}\n\nexport function fromError(error: readonly StandardSchemaV1.Issue[], validating: string) {\n\tconst errorMessages: string[] = [];\n\n\tfor (const issue of error) {\n\t\tconst message = issue.message;\n\t\terrorMessages.push(message);\n\t}\n\treturn {\n\t\tmessage: `Invalid ${validating} parameters`,\n\t};\n}\n","import { subtle } from \"uncrypto\";\n\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nexport const getCryptoKey = async (secret: string | BufferSource) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await subtle.importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\n\nexport const verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise<boolean> => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await subtle.sign(algorithm.name, key, new TextEncoder().encode(value));\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nexport const signCookieValue = async (value: string, secret: string | BufferSource) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\n};\n","import { signCookieValue } from \"./crypto\";\nimport { tryDecode } from \"./utils\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n\tif (typeof str !== \"string\") {\n\t\tthrow new TypeError(\"argument str must be a string\");\n\t}\n\n\tconst cookies: Map<string, string> = new Map();\n\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\n\t\tif (eqIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet endIdx = str.indexOf(\";\", index);\n\n\t\tif (endIdx === -1) {\n\t\t\tendIdx = str.length;\n\t\t} else if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 0x22) {\n\t\t\t\tval = val.slice(1, -1);\n\t\t\t}\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\n\t\tindex = endIdx + 1;\n\t}\n\n\treturn cookies;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (key: string, value: string, opt?: CookieOptions) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n","import type { EndpointOptions } from \"./endpoint\";\nimport { _statusCode, APIError, type Status } from \"./error\";\nimport type {\n\tInferParamPath,\n\tInferParamWildCard,\n\tIsEmptyObject,\n\tPrettify,\n\tUnionToIntersection,\n} from \"./helper\";\nimport type { Middleware, MiddlewareOptions } from \"./middleware\";\nimport { runValidation } from \"./validator\";\nimport {\n\tgetCookieKey,\n\tparseCookies,\n\tserializeCookie,\n\tserializeSignedCookie,\n\ttype CookieOptions,\n\ttype CookiePrefixOptions,\n} from \"./cookies\";\nimport { getCryptoKey, verifySignature } from \"./crypto\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\n\nexport type HTTPMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\nexport type Method = HTTPMethod | \"*\";\n\nexport type InferBodyInput<\n\tOptions extends EndpointOptions | MiddlewareOptions,\n\tBody = Options[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer B;\n\t\t};\n\t}\n\t\t? B\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"body\"]>\n\t\t\t: undefined,\n> = undefined extends Body\n\t? {\n\t\t\tbody?: Body;\n\t\t}\n\t: {\n\t\t\tbody: Body;\n\t\t};\n\nexport type InferBody<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer Body;\n\t\t};\n\t}\n\t\t? Body\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"body\"]>\n\t\t\t: any;\n\nexport type InferQueryInput<\n\tOptions extends EndpointOptions | MiddlewareOptions,\n\tQuery = Options[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined,\n> = undefined extends Query\n\t? {\n\t\t\tquery?: Query;\n\t\t}\n\t: {\n\t\t\tquery: Query;\n\t\t};\n\nexport type InferQuery<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined;\n\nexport type InferMethod<Options extends EndpointOptions> = Options[\"method\"] extends Array<Method>\n\t? Options[\"method\"][number]\n\t: Options[\"method\"] extends \"*\"\n\t\t? HTTPMethod\n\t\t: Options[\"method\"];\n\nexport type InferInputMethod<\n\tOptions extends EndpointOptions,\n\tMethod = Options[\"method\"] extends Array<any>\n\t\t? Options[\"method\"][number]\n\t\t: Options[\"method\"] extends \"*\"\n\t\t\t? HTTPMethod\n\t\t\t: Options[\"method\"] | undefined,\n> = undefined extends Method\n\t? {\n\t\t\tmethod?: Method;\n\t\t}\n\t: {\n\t\t\tmethod: Method;\n\t\t};\n\nexport type InferParam<Path extends string> = IsEmptyObject<\n\tInferParamPath<Path> & InferParamWildCard<Path>\n> extends true\n\t? Record<string, any> | undefined\n\t: Prettify<InferParamPath<Path> & InferParamWildCard<Path>>;\n\nexport type InferParamInput<Path extends string> = IsEmptyObject<\n\tInferParamPath<Path> & InferParamWildCard<Path>\n> extends true\n\t? {\n\t\t\tparams?: Record<string, any>;\n\t\t}\n\t: {\n\t\t\tparams: Prettify<InferParamPath<Path> & InferParamWildCard<Path>>;\n\t\t};\n\nexport type InferRequest<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireRequest\"] extends true ? Request : Request | undefined;\n\nexport type InferRequestInput<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireRequest\"] extends true\n\t\t? {\n\t\t\t\trequest: Request;\n\t\t\t}\n\t\t: {\n\t\t\t\trequest?: Request;\n\t\t\t};\n\nexport type InferHeaders<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireHeaders\"] extends true ? Headers : Headers | undefined;\n\nexport type InferHeadersInput<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireHeaders\"] extends true\n\t\t? {\n\t\t\t\theaders: HeadersInit;\n\t\t\t}\n\t\t: {\n\t\t\t\theaders?: HeadersInit;\n\t\t\t};\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> = Opts extends Middleware[]\n\t? UnionToIntersection<Awaited<ReturnType<Opts[number]>>>\n\t: {};\n\nexport type InferMiddlewareBody<Options extends MiddlewareOptions> =\n\tOptions[\"body\"] extends StandardSchemaV1<infer T> ? T : any;\n\nexport type InferMiddlewareQuery<Options extends MiddlewareOptions> =\n\tOptions[\"query\"] extends StandardSchemaV1<infer T> ? T : Record<string, any> | undefined;\n\ntype StrictKeys<T, U extends T = T> = Exclude<keyof U, keyof T> extends never ? U : never;\nexport type InputContext<\n\tPath extends string,\n\tOptions extends EndpointOptions,\n> = InferBodyInput<Options> &\n\tInferInputMethod<Options> &\n\tInferQueryInput<Options> &\n\tInferParamInput<Path> &\n\tInferRequestInput<Options> &\n\tInferHeadersInput<Options> & {\n\t\tasResponse?: boolean;\n\t\treturnHeaders?: boolean;\n\t\tuse?: Middleware[];\n\t\tpath?: string;\n\t};\n\nexport const createInternalContext = async (\n\tcontext: InputContext<any, any>,\n\t{\n\t\toptions,\n\t\tpath,\n\t}: {\n\t\toptions: EndpointOptions;\n\t\tpath: string;\n\t},\n) => {\n\tconst headers = new Headers();\n\tconst { data, error } = await runValidation(options, context);\n\tif (error) {\n\t\tthrow new APIError(400, {\n\t\t\tmessage: error.message,\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t});\n\t}\n\tconst requestHeaders: Headers | null =\n\t\t\"headers\" in context\n\t\t\t? context.headers instanceof Headers\n\t\t\t\t? context.headers\n\t\t\t\t: new Headers(context.headers)\n\t\t\t: \"request\" in context && context.request instanceof Request\n\t\t\t\t? context.request.headers\n\t\t\t\t: null;\n\tconst requestCookies = requestHeaders?.get(\"cookie\");\n\tconst parsedCookies = requestCookies ? parseCookies(requestCookies) : undefined;\n\tconst internalContext = {\n\t\t...context,\n\t\tbody: data.body,\n\t\tquery: data.query,\n\t\tpath: context.path || path,\n\t\tcontext: \"context\" in context && context.context ? context.context : {},\n\t\treturned: undefined as any,\n\t\theaders: context?.headers,\n\t\trequest: context?.request,\n\t\tparams: \"params\" in context ? context.params : undefined,\n\t\tmethod: context.method,\n\t\tsetHeader: (key: string, value: string) => {\n\t\t\theaders.set(key, value);\n\t\t},\n\t\tgetHeader: (key: string) => {\n\t\t\tif (!requestHeaders) return null;\n\t\t\treturn requestHeaders.get(key);\n\t\t},\n\t\tgetCookie: (key: string, prefix?: CookiePrefixOptions) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn parsedCookies?.get(finalKey) || null;\n\t\t},\n\t\tgetSignedCookie: async (key: string, secret: string, prefix?: CookiePrefixOptions) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst value = parsedCookies?.get(finalKey);\n\t\t\tif (!value) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\t\tif (signatureStartPos < 1) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst secretKey = await getCryptoKey(secret);\n\t\t\tconst isVerified = await verifySignature(signature, signedValue, secretKey);\n\t\t\treturn isVerified ? signedValue : false;\n\t\t},\n\t\tsetCookie: (key: string, value: string, options?: CookieOptions) => {\n\t\t\tconst cookie = serializeCookie(key, value, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tsetSignedCookie: async (\n\t\t\tkey: string,\n\t\t\tvalue: string,\n\t\t\tsecret: string,\n\t\t\toptions?: CookieOptions,\n\t\t) => {\n\t\t\tconst cookie = await serializeSignedCookie(key, value, secret, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tredirect: (url: string) => {\n\t\t\theaders.set(\"location\", url);\n\t\t\treturn new APIError(\"FOUND\", undefined, headers);\n\t\t},\n\t\terror: (\n\t\t\tstatus: keyof typeof _statusCode | Status,\n\t\t\tbody?:\n\t\t\t\t| {\n\t\t\t\t\t\tmessage?: string;\n\t\t\t\t\t\tcode?: string;\n\t\t\t\t }\n\t\t\t\t| undefined,\n\t\t\theaders?: HeadersInit,\n\t\t) => {\n\t\t\treturn new APIError(status, body, headers);\n\t\t},\n\t\tjson: (\n\t\t\tjson: Record<string, any>,\n\t\t\trouterResponse?:\n\t\t\t\t| {\n\t\t\t\t\t\tstatus?: number;\n\t\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\t\tresponse?: Response;\n\t\t\t\t\t\tbody?: Record<string, any>;\n\t\t\t\t }\n\t\t\t\t| Response,\n\t\t) => {\n\t\t\tif (!context.asResponse) {\n\t\t\t\treturn json;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbody: routerResponse?.body || json,\n\t\t\t\trouterResponse,\n\t\t\t\t_flag: \"json\",\n\t\t\t};\n\t\t},\n\t\tresponseHeaders: headers,\n\t};\n\t//if context was shimmed through the input we want to apply it\n\tfor (const middleware of options.use || []) {\n\t\tconst response = (await middleware({\n\t\t\t...internalContext,\n\t\t\treturnHeaders: true,\n\t\t\tasResponse: false,\n\t\t})) as {\n\t\t\tresponse?: any;\n\t\t\theaders?: Headers;\n\t\t};\n\t\tif (response.response) {\n\t\t\tObject.assign(internalContext.context, response.response);\n\t\t}\n\t\t/**\n\t\t * Apply headers from the middleware to the endpoint headers\n\t\t */\n\t\tif (response.headers) {\n\t\t\tresponse.headers.forEach((value, key) => {\n\t\t\t\tinternalContext.responseHeaders.set(key, value);\n\t\t\t});\n\t\t}\n\t}\n\treturn internalContext;\n};\n","import {\n\tcreateEndpoint,\n\ttype Endpoint,\n\ttype EndpointContext,\n\ttype EndpointOptions,\n} from \"./endpoint\";\nimport {\n\tcreateInternalContext,\n\ttype InferBody,\n\ttype InferBodyInput,\n\ttype InferHeaders,\n\ttype InferHeadersInput,\n\ttype InferMiddlewareBody,\n\ttype InferMiddlewareQuery,\n\ttype InferQuery,\n\ttype InferQueryInput,\n\ttype InferRequest,\n\ttype InferRequestInput,\n\ttype InferUse,\n\ttype InputContext,\n} from \"./context\";\nimport type { Prettify } from \"./helper\";\n\nexport interface MiddlewareOptions extends Omit<EndpointOptions, \"method\"> {}\n\nexport type MiddlewareResponse = null | void | undefined | Record<string, any>;\n\nexport type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<\n\tstring,\n\tOptions & {\n\t\tmethod: \"*\";\n\t}\n> & {\n\t/**\n\t * Method\n\t *\n\t * The request method\n\t */\n\tmethod: string;\n\t/**\n\t * Path\n\t *\n\t * The path of the endpoint\n\t */\n\tpath: string;\n\t/**\n\t * Body\n\t *\n\t * The body object will be the parsed JSON from the request and validated\n\t * against the body schema if it exists\n\t */\n\tbody: InferMiddlewareBody<Options>;\n\t/**\n\t * Query\n\t *\n\t * The query object will be the parsed query string from the request\n\t * and validated against the query schema if it exists\n\t */\n\tquery: InferMiddlewareQuery<Options>;\n\t/**\n\t * Params\n\t *\n\t * If the path is `/user/:id` and the request is `/user/1` then the\n\t * params will\n\t * be `{ id: \"1\" }` and if the path includes a wildcard like `/user/*`\n\t * then the\n\t * params will be `{ _: \"1\" }` where `_` is the wildcard key. If the\n\t * wildcard\n\t * is named like `/user/**:name` then the params will be `{ name: string }`\n\t */\n\tparams: string;\n\t/**\n\t * Request object\n\t *\n\t * If `requireRequest` is set to true in the endpoint options this will be\n\t * required\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t *\n\t * If `requireHeaders` is set to true in the endpoint options this will be\n\t * required\n\t */\n\theaders: InferHeaders<Options>;\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * Get header\n\t *\n\t * If it's called outside of a request it will just return null\n\t *\n\t * @param key - The key of the header\n\t * @returns\n\t */\n\tgetHeader: (key: string) => string | null;\n\t/**\n\t * JSON\n\t *\n\t * a helper function to create a JSON response with\n\t * the correct headers\n\t * and status code. If `asResponse` is set to true in\n\t * the context then\n\t * it will return a Response object instead of the\n\t * JSON object.\n\t *\n\t * @param json - The JSON object to return\n\t * @param routerResponse - The response object to\n\t * return if `asResponse` is\n\t * true in the context this will take precedence\n\t */\n\tjson: <R extends Record<string, any> | null>(\n\t\tjson: R,\n\t\trouterResponse?:\n\t\t\t| {\n\t\t\t\t\tstatus?: number;\n\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\tresponse?: Response;\n\t\t\t }\n\t\t\t| Response,\n\t) => Promise<R>;\n\t/**\n\t * Middleware context\n\t */\n\tcontext: Prettify<Context>;\n};\n\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\toptions: Options,\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tconst internalHandler = async (inputCtx: InputContext<any, any>) => {\n\t\tconst context = inputCtx as InputContext<any, any>;\n\t\tconst _handler = typeof optionsOrHandler === \"function\" ? optionsOrHandler : handler;\n\t\tconst options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\t\tconst internalContext = await createInternalContext(context, {\n\t\t\toptions,\n\t\t\tpath: \"/\",\n\t\t});\n\n\t\tif (!_handler) {\n\t\t\tthrow new Error(\"handler must be defined\");\n\t\t}\n\t\tconst response = await _handler(internalContext as any);\n\t\tconst headers = internalContext.responseHeaders;\n\t\treturn context.returnHeaders\n\t\t\t? {\n\t\t\t\t\theaders,\n\t\t\t\t\tresponse,\n\t\t\t\t}\n\t\t\t: response;\n\t};\n\tinternalHandler.options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\treturn internalHandler;\n}\n\nexport type MiddlewareInputContext<Options extends MiddlewareOptions> = InferBodyInput<Options> &\n\tInferQueryInput<Options> &\n\tInferRequestInput<Options> &\n\tInferHeadersInput<Options> & {\n\t\tasResponse?: boolean;\n\t\treturnHeaders?: boolean;\n\t\tuse?: Middleware[];\n\t};\n\nexport type Middleware<\n\tOptions extends MiddlewareOptions = MiddlewareOptions,\n\tHandler extends (inputCtx: any) => Promise<any> = any,\n> = Handler & {\n\toptions: Options;\n};\n\ncreateMiddleware.create = <\n\tE extends {\n\t\tuse?: Middleware[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype InferredContext = InferUse<E[\"use\"]>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\toptions: Options,\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createMiddleware(\n\t\t\t\t{\n\t\t\t\t\tuse: opts?.use,\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst middleware = createMiddleware(\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t\tuse: [...(opts?.use || []), ...(optionsOrHandler.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn middleware as any;\n\t}\n\treturn fn;\n};\n","import type { HasRequiredKeys, Prettify } from \"./helper\";\nimport { toResponse } from \"./to-response\";\nimport { type Middleware } from \"./middleware\";\nimport {\n\tcreateInternalContext,\n\ttype InferBody,\n\ttype InferHeaders,\n\ttype InferMethod,\n\ttype InferParam,\n\ttype InferQuery,\n\ttype InferRequest,\n\ttype InferUse,\n\ttype InputContext,\n\ttype Method,\n} from \"./context\";\nimport type { CookieOptions, CookiePrefixOptions } from \"./cookies\";\nimport { APIError, type _statusCode, type Status } from \"./error\";\nimport type { OpenAPIParameter, OpenAPISchemaType } from \"./openapi\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\nimport { isAPIError } from \"./utils\";\n\nexport interface EndpointOptions {\n\t/**\n\t * Request Method\n\t */\n\tmethod: Method | Method[];\n\t/**\n\t * Body Schema\n\t */\n\tbody?: StandardSchemaV1;\n\t/**\n\t * Query Schema\n\t */\n\tquery?: StandardSchemaV1;\n\t/**\n\t * If true headers will be required to be passed in the context\n\t */\n\trequireHeaders?: boolean;\n\t/**\n\t * If true request object will be required\n\t */\n\trequireRequest?: boolean;\n\t/**\n\t * Clone the request object from the router\n\t */\n\tcloneRequest?: boolean;\n\t/**\n\t * If true the body will be undefined\n\t */\n\tdisableBody?: boolean;\n\t/**\n\t * Endpoint metadata\n\t */\n\tmetadata?: {\n\t\t/**\n\t\t * Open API definition\n\t\t */\n\t\topenapi?: {\n\t\t\tsummary?: string;\n\t\t\tdescription?: string;\n\t\t\ttags?: string[];\n\t\t\toperationId?: string;\n\t\t\tparameters?: OpenAPIParameter[];\n\t\t\trequestBody?: {\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tresponses?: {\n\t\t\t\t[status: string]: {\n\t\t\t\t\tdescription: string;\n\t\t\t\t\tcontent?: {\n\t\t\t\t\t\t\"application/json\"?: {\n\t\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\"text/plain\"?: {\n\t\t\t\t\t\t\tschema?: {\n\t\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\"text/html\"?: {\n\t\t\t\t\t\t\tschema?: {\n\t\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\t/**\n\t\t * Infer body and query type from ts interface\n\t\t *\n\t\t * useful for generic and dynamic types\n\t\t *\n\t\t * @example\n\t\t * ```ts\n\t\t * const endpoint = createEndpoint(\"/path\", {\n\t\t * \t\tmethod: \"POST\",\n\t\t * \t\tbody: z.record(z.string()),\n\t\t * \t\t$Infer: {\n\t\t * \t\t\tbody: {} as {\n\t\t * \t\t\t\ttype: InferTypeFromOptions<Option> // custom type inference\n\t\t * \t\t\t}\n\t\t * \t\t}\n\t\t * \t}, async(ctx)=>{\n\t\t * \t\tconst body = ctx.body\n\t\t * \t})\n\t\t * ```\n\t\t */\n\t\t$Infer?: {\n\t\t\t/**\n\t\t\t * Body\n\t\t\t */\n\t\t\tbody?: any;\n\t\t\t/**\n\t\t\t * Query\n\t\t\t */\n\t\t\tquery?: Record<string, any>;\n\t\t};\n\t\t/**\n\t\t * If enabled, endpoint won't be exposed over a router\n\t\t */\n\t\tSERVER_ONLY?: boolean;\n\t\t/**\n\t\t * Extra metadata\n\t\t */\n\t\t[key: string]: any;\n\t};\n\t/**\n\t * List of middlewares to use\n\t */\n\tuse?: Middleware[];\n\t/**\n\t * A callback to run before any API error is throw or returned\n\t *\n\t * @param e - The API error\n\t * @returns - The response to return\n\t */\n\tonAPIError?: (e: APIError) => void | Promise<void>;\n}\n\nexport type EndpointContext<Path extends string, Options extends EndpointOptions, Context = {}> = {\n\t/**\n\t * Method\n\t *\n\t * The request method\n\t */\n\tmethod: InferMethod<Options>;\n\t/**\n\t * Path\n\t *\n\t * The path of the endpoint\n\t */\n\tpath: Path;\n\t/**\n\t * Body\n\t *\n\t * The body object will be the parsed JSON from the request and validated\n\t * against the body schema if it exists.\n\t */\n\tbody: InferBody<Options>;\n\t/**\n\t * Query\n\t *\n\t * The query object will be the parsed query string from the request\n\t * and validated against the query schema if it exists\n\t */\n\tquery: InferQuery<Options>;\n\t/**\n\t * Params\n\t *\n\t * If the path is `/user/:id` and the request is `/user/1` then the params will\n\t * be `{ id: \"1\" }` and if the path includes a wildcard like `/user/*` then the\n\t * params will be `{ _: \"1\" }` where `_` is the wildcard key. If the wildcard\n\t * is named like `/user/**:name` then the params will be `{ name: string }`\n\t */\n\tparams: InferParam<Path>;\n\t/**\n\t * Request object\n\t *\n\t * If `requireRequest` is set to true in the endpoint options this will be\n\t * required\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t *\n\t * If `requireHeaders` is set to true in the endpoint options this will be\n\t * required\n\t */\n\theaders: InferHeaders<Options>;\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * Get header\n\t *\n\t * If it's called outside of a request it will just return null\n\t *\n\t * @param key - The key of the header\n\t * @returns\n\t */\n\tgetHeader: (key: string) => string | null;\n\t/**\n\t * Get a cookie value from the request\n\t *\n\t * @param key - The key of the cookie\n\t * @param prefix - The prefix of the cookie between `__Secure-` and `__Host-`\n\t * @returns - The value of the cookie\n\t */\n\tgetCookie: (key: string, prefix?: CookiePrefixOptions) => string | null;\n\t/**\n\t * Get a signed cookie value from the request\n\t *\n\t * @param key - The key of the cookie\n\t * @param secret - The secret of the signed cookie\n\t * @param prefix - The prefix of the cookie between `__Secure-` and `__Host-`\n\t * @returns\n\t */\n\tgetSignedCookie: (\n\t\tkey: string,\n\t\tsecret: string,\n\t\tprefix?: CookiePrefixOptions,\n\t) => Promise<string | null>;\n\t/**\n\t * Set a cookie value in the response\n\t *\n\t * @param key - The key of the cookie\n\t * @param value - The value to set\n\t * @param options - The options of the cookie\n\t * @returns - The cookie string\n\t */\n\tsetCookie: (key: string, value: string, options?: CookieOptions) => string;\n\t/**\n\t * Set signed cookie\n\t *\n\t * @param key - The key of the cookie\n\t * @param value - The value to set\n\t * @param secret - The secret to sign the cookie with\n\t * @param options - The options of the cookie\n\t * @returns - The cookie string\n\t */\n\tsetSignedCookie: (\n\t\tkey: string,\n\t\tvalue: string,\n\t\tsecret: string,\n\t\toptions?: CookieOptions,\n\t) => Promise<string>;\n\t/**\n\t * JSON\n\t *\n\t * a helper function to create a JSON response with\n\t * the correct headers\n\t * and status code. If `asResponse` is set to true in\n\t * the context then\n\t * it will return a Response object instead of the\n\t * JSON object.\n\t *\n\t * @param json - The JSON object to return\n\t * @param routerResponse - The response object to\n\t * return if `asResponse` is\n\t * true in the context this will take precedence\n\t */\n\tjson: <R extends Record<string, any> | null>(\n\t\tjson: R,\n\t\trouterResponse?:\n\t\t\t| {\n\t\t\t\t\tstatus?: number;\n\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\tresponse?: Response;\n\t\t\t\t\tbody?: Record<string, string>;\n\t\t\t }\n\t\t\t| Response,\n\t) => Promise<R>;\n\t/**\n\t * Middleware context\n\t */\n\tcontext: Prettify<Context & InferUse<Options[\"use\"]>>;\n\t/**\n\t * Redirect to a new URL\n\t */\n\tredirect: (url: string) => APIError;\n\t/**\n\t * Return error\n\t */\n\terror: (\n\t\tstatus: keyof typeof _statusCode | Status,\n\t\tbody?: {\n\t\t\tmessage?: string;\n\t\t\tcode?: string;\n\t\t} & Record<string, any>,\n\t\theaders?: HeadersInit,\n\t) => APIError;\n};\n\nexport const createEndpoint = <Path extends string, Options extends EndpointOptions, R>(\n\tpath: Path,\n\toptions: Options,\n\thandler: (context: EndpointContext<Path, Options>) => Promise<R>,\n) => {\n\ttype Context = InputContext<Path, Options>;\n\tconst internalHandler = async <\n\t\tAsResponse extends boolean = false,\n\t\tReturnHeaders extends boolean = false,\n\t>(\n\t\t...inputCtx: HasRequiredKeys<Context> extends true\n\t\t\t? [Context & { asResponse?: AsResponse; returnHeaders?: ReturnHeaders }]\n\t\t\t: [(Context & { asResponse?: AsResponse; returnHeaders?: ReturnHeaders })?]\n\t) => {\n\t\tconst context = (inputCtx[0] || {}) as InputContext<any, any>;\n\t\tconst internalContext = await createInternalContext(context, {\n\t\t\toptions,\n\t\t\tpath,\n\t\t});\n\t\tconst response = await handler(internalContext as any).catch(async (e) => {\n\t\t\tif (isAPIError(e)) {\n\t\t\t\tconst onAPIError = options.onAPIError;\n\t\t\t\tif (onAPIError) {\n\t\t\t\t\tawait onAPIError(e);\n\t\t\t\t}\n\t\t\t\tif (context.asResponse) {\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow e;\n\t\t});\n\t\tconst headers = internalContext.responseHeaders;\n\t\ttype ResultType = [AsResponse] extends [true]\n\t\t\t? Response\n\t\t\t: [ReturnHeaders] extends [true]\n\t\t\t\t? { headers: Headers; response: R }\n\t\t\t\t: R;\n\n\t\treturn (\n\t\t\tcontext.asResponse\n\t\t\t\t? toResponse(response, {\n\t\t\t\t\t\theaders,\n\t\t\t\t\t})\n\t\t\t\t: context.returnHeaders\n\t\t\t\t\t? {\n\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\tresponse,\n\t\t\t\t\t\t}\n\t\t\t\t\t: response\n\t\t) as ResultType;\n\t};\n\tinternalHandler.options = options;\n\tinternalHandler.path = path;\n\treturn internalHandler;\n};\n\ncreateEndpoint.create = <E extends { use?: Middleware[] }>(opts?: E) => {\n\treturn <Path extends string, Opts extends EndpointOptions, R>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: (ctx: EndpointContext<Path, Opts, InferUse<E[\"use\"]>>) => Promise<R>,\n\t) => {\n\t\treturn createEndpoint(\n\t\t\tpath,\n\t\t\t{\n\t\t\t\t...options,\n\t\t\t\tuse: [...(options?.use || []), ...(opts?.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t};\n};\n\nexport type Endpoint<\n\tPath extends string = string,\n\tOptions extends EndpointOptions = EndpointOptions,\n\tHandler extends (inputCtx: any) => Promise<any> = (inputCtx: any) => Promise<any>,\n> = Handler & {\n\toptions: Options;\n\tpath: Path;\n};\n","import { createRouter as createRou3Router, addRoute, findRoute, findAllRoutes } from \"rou3\";\nimport { createEndpoint, type Endpoint } from \"./endpoint\";\nimport { generator, getHTML } from \"./openapi\";\nimport type { Middleware } from \"./middleware\";\nimport { getBody, isAPIError } from \"./utils\";\nimport { APIError } from \"./error\";\nimport { toResponse } from \"./to-response\";\n\nexport interface RouterConfig {\n\tthrowError?: boolean;\n\tonError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;\n\tbasePath?: string;\n\trouterMiddleware?: Array<{\n\t\tpath: string;\n\t\tmiddleware: Middleware;\n\t}>;\n\t/**\n\t * additional Context that needs to passed to endpoints\n\t *\n\t * this will be available on `ctx.context` on endpoints\n\t */\n\trouterContext?: Record<string, any>;\n\t/**\n\t * A callback to run before any response\n\t */\n\tonResponse?: (res: Response) => any | Promise<any>;\n\t/**\n\t * A callback to run before any request\n\t */\n\tonRequest?: (req: Request) => any | Promise<any>;\n\t/**\n\t * Open API route configuration\n\t */\n\topenapi?: {\n\t\t/**\n\t\t * Disable openapi route\n\t\t *\n\t\t * @default false\n\t\t */\n\t\tdisabled?: boolean;\n\t\t/**\n\t\t * A path to display open api using scalar\n\t\t *\n\t\t * @default \"/api/reference\"\n\t\t */\n\t\tpath?: string;\n\t\t/**\n\t\t * Scalar Configuration\n\t\t */\n\t\tscalar?: {\n\t\t\t/**\n\t\t\t * Title\n\t\t\t * @default \"Open API Reference\"\n\t\t\t */\n\t\t\ttitle?: string;\n\t\t\t/**\n\t\t\t * Description\n\t\t\t *\n\t\t\t * @default \"Better Call Open API Reference\"\n\t\t\t */\n\t\t\tdescription?: string;\n\t\t\t/**\n\t\t\t * Logo URL\n\t\t\t */\n\t\t\tlogo?: string;\n\t\t\t/**\n\t\t\t * Scalar theme\n\t\t\t * @default \"saturn\"\n\t\t\t */\n\t\t\ttheme?: string;\n\t\t};\n\t};\n}\n\nexport const createRouter = <E extends Record<string, Endpoint>, Config extends RouterConfig>(\n\tendpoints: E,\n\tconfig?: Config,\n) => {\n\tif (!config?.openapi?.disabled) {\n\t\tconst openapi = {\n\t\t\tpath: \"/api/reference\",\n\t\t\t...config?.openapi,\n\t\t};\n\t\t//@ts-expect-error\n\t\tendpoints[\"openapi\"] = createEndpoint(\n\t\t\topenapi.path,\n\t\t\t{\n\t\t\t\tmethod: \"GET\",\n\t\t\t},\n\t\t\tasync (c) => {\n\t\t\t\tconst schema = await generator(endpoints);\n\t\t\t\treturn new Response(getHTML(schema, openapi.scalar), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t}\n\tconst router = createRou3Router();\n\tconst middlewareRouter = createRou3Router();\n\n\tfor (const endpoint of Object.values(endpoints)) {\n\t\tif (!endpoint.options) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (endpoint.options?.metadata?.SERVER_ONLY) continue;\n\n\t\tconst methods = Array.isArray(endpoint.options?.method)\n\t\t\t? endpoint.options.method\n\t\t\t: [endpoint.options?.method];\n\n\t\tfor (const method of methods) {\n\t\t\taddRoute(router, method, endpoint.path, endpoint);\n\t\t}\n\t}\n\n\tif (config?.routerMiddleware?.length) {\n\t\tfor (const { path, middleware } of config.routerMiddleware) {\n\t\t\taddRoute(middlewareRouter, \"*\", path, middleware);\n\t\t}\n\t}\n\n\tconst processRequest = async (request: Request) => {\n\t\tconst url = new URL(request.url);\n\t\tconst path = config?.basePath\n\t\t\t? url.pathname\n\t\t\t\t\t.split(config.basePath)\n\t\t\t\t\t.reduce((acc, curr, index) => {\n\t\t\t\t\t\tif (index !== 0) {\n\t\t\t\t\t\t\tif (index > 1) {\n\t\t\t\t\t\t\t\tacc.push(`${config.basePath}${curr}`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tacc.push(curr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t}, [] as string[])\n\t\t\t\t\t.join(\"\")\n\t\t\t: url.pathname;\n\n\t\tif (!path?.length) {\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\n\t\tconst route = findRoute(router, request.method, path);\n\t\tif (!route?.data) {\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\n\t\tconst query: Record<string, string | string[]> = {};\n\t\turl.searchParams.forEach((value, key) => {\n\t\t\tif (key in query) {\n\t\t\t\tif (Array.isArray(query[key])) {\n\t\t\t\t\t(query[key] as string[]).push(value);\n\t\t\t\t} else {\n\t\t\t\t\tquery[key] = [query[key] as string, value];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tquery[key] = value;\n\t\t\t}\n\t\t});\n\n\t\tconst handler = route.data as Endpoint;\n\t\tconst context = {\n\t\t\tpath,\n\t\t\tmethod: request.method as \"GET\",\n\t\t\theaders: request.headers,\n\t\t\tparams: route.params ? (JSON.parse(JSON.stringify(route.params)) as any) : {},\n\t\t\trequest: request,\n\t\t\tbody: handler.options.disableBody\n\t\t\t\t? undefined\n\t\t\t\t: await getBody(handler.options.cloneRequest ? request.clone() : request),\n\t\t\tquery,\n\t\t\t_flag: \"router\" as const,\n\t\t\tasResponse: true,\n\t\t\tcontext: config?.routerContext,\n\t\t};\n\n\t\ttry {\n\t\t\tconst middlewareRoutes = findAllRoutes(middlewareRouter, \"*\", path);\n\t\t\tif (middlewareRoutes?.length) {\n\t\t\t\tfor (const { data: middleware, params } of middlewareRoutes) {\n\t\t\t\t\tconst res = await (middleware as Endpoint)({\n\t\t\t\t\t\t...context,\n\t\t\t\t\t\tparams,\n\t\t\t\t\t\tasResponse: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (res instanceof Response) return res;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst response = (await handler(context)) as Response;\n\t\t\treturn response;\n\t\t} catch (error) {\n\t\t\tif (isAPIError(error)) {\n\t\t\t\treturn toResponse(error);\n\t\t\t}\n\t\t\tconsole.error(`# SERVER_ERROR: `, error);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 500,\n\t\t\t\tstatusText: \"Internal Server Error\",\n\t\t\t});\n\t\t}\n\t};\n\n\treturn {\n\t\thandler: async (request: Request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) {\n\t\t\t\treturn onReq;\n\t\t\t}\n\t\t\tconst req = onReq instanceof Request ? onReq : request;\n\t\t\tconst res = await processRequest(req);\n\t\t\tconst onRes = await config?.onResponse?.(res);\n\t\t\tif (onRes instanceof Response) {\n\t\t\t\treturn onRes;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType<typeof createRouter>;\n","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" &&\n (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n var _a, _b;\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nconst ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n // let regex = `\\\\d{2}:\\\\d{2}:\\\\d{2}`;\n let regex = `([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d`;\n if (args.precision) {\n regex = `${regex}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n regex = `${regex}(\\\\.\\\\d+)?`;\n }\n return regex;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (!decoded.typ || !decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a, _b;\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" ||\n (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" ||\n ch.kind === \"int\" ||\n ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch (_a) {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodEnum_cache.set(this, void 0);\n }\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\").has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\n_ZodEnum_cache = new WeakMap();\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodNativeEnum_cache.set(this, void 0);\n }\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\").has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\n_ZodNativeEnum_cache = new WeakMap();\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result)\n ? result.then((data) => freeze(data))\n : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\nfunction custom(check, params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === \"function\"\n ? params(data)\n : typeof params === \"string\"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n ctx.addIssue({ code: \"custom\", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n}\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n datetimeRegex: datetimeRegex,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n ZodReadonly: ZodReadonly,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n 'enum': enumType,\n 'function': functionType,\n 'instanceof': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n 'null': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n 'undefined': undefinedType,\n union: unionType,\n unknown: unknownType,\n 'void': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\nexport { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };\n","import { ZodObject, ZodOptional, ZodSchema } from \"zod\";\nimport type { Endpoint, EndpointOptions } from \"./endpoint\";\n\nexport type OpenAPISchemaType = \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\" | \"object\";\n\nexport interface OpenAPIParameter {\n\tin: \"query\" | \"path\" | \"header\" | \"cookie\";\n\tname?: string;\n\tdescription?: string;\n\trequired?: boolean;\n\tschema?: {\n\t\ttype: OpenAPISchemaType;\n\t\tformat?: string;\n\t\titems?: {\n\t\t\ttype: OpenAPISchemaType;\n\t\t};\n\t\tenum?: string[];\n\t\tminLength?: number;\n\t\tdescription?: string;\n\t\tdefault?: string;\n\t\texample?: string;\n\t};\n}\n\nexport interface Path {\n\tget?: {\n\t\ttags?: string[];\n\t\toperationId?: string;\n\t\tdescription?: string;\n\t\tsecurity?: [{ bearerAuth: string[] }];\n\t\tparameters?: OpenAPIParameter[];\n\t\tresponses?: {\n\t\t\t[key in string]: {\n\t\t\t\tdescription?: string;\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n\tpost?: {\n\t\ttags?: string[];\n\t\toperationId?: string;\n\t\tdescription?: string;\n\t\tsecurity?: [{ bearerAuth: string[] }];\n\t\tparameters?: OpenAPIParameter[];\n\t\trequestBody?: {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\tresponses?: {\n\t\t\t[key in string]: {\n\t\t\t\tdescription?: string;\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n}\nconst paths: Record<string, Path> = {};\n\nfunction getTypeFromZodType(zodType: ZodSchema) {\n\tswitch (zodType.constructor.name) {\n\t\tcase \"ZodString\":\n\t\t\treturn \"string\";\n\t\tcase \"ZodNumber\":\n\t\t\treturn \"number\";\n\t\tcase \"ZodBoolean\":\n\t\t\treturn \"boolean\";\n\t\tcase \"ZodObject\":\n\t\t\treturn \"object\";\n\t\tcase \"ZodArray\":\n\t\t\treturn \"array\";\n\t\tdefault:\n\t\t\treturn \"string\";\n\t}\n}\n\nfunction getParameters(options: EndpointOptions) {\n\tconst parameters: OpenAPIParameter[] = [];\n\tif (options.metadata?.openapi?.parameters) {\n\t\tparameters.push(...options.metadata.openapi.parameters);\n\t\treturn parameters;\n\t}\n\tif (options.query instanceof ZodObject) {\n\t\tObject.entries(options.query.shape).forEach(([key, value]) => {\n\t\t\tif (value instanceof ZodSchema) {\n\t\t\t\tparameters.push({\n\t\t\t\t\tname: key,\n\t\t\t\t\tin: \"query\",\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t\t\t...(\"minLength\" in value && value.minLength\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tminLength: value.minLength as number,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tdescription: value.description,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\treturn parameters;\n}\n\nfunction getRequestBody(options: EndpointOptions): any {\n\tif (options.metadata?.openapi?.requestBody) {\n\t\treturn options.metadata.openapi.requestBody;\n\t}\n\tif (!options.body) return undefined;\n\tif (options.body instanceof ZodObject || options.body instanceof ZodOptional) {\n\t\t// @ts-ignore\n\t\tconst shape = options.body.shape;\n\t\tif (!shape) return undefined;\n\t\tconst properties: Record<string, any> = {};\n\t\tconst required: string[] = [];\n\t\tObject.entries(shape).forEach(([key, value]) => {\n\t\t\tif (value instanceof ZodSchema) {\n\t\t\t\tproperties[key] = {\n\t\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t\tdescription: value.description,\n\t\t\t\t};\n\t\t\t\tif (!(value instanceof ZodOptional)) {\n\t\t\t\t\trequired.push(key);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\trequired: options.body instanceof ZodOptional ? false : options.body ? true : false,\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties,\n\t\t\t\t\t\trequired,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction getResponse(responses?: Record<string, any>) {\n\treturn {\n\t\t\"400\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"message\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Bad Request. Usually due to missing parameters, or invalid parameters.\",\n\t\t},\n\t\t\"401\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"message\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Unauthorized. Due to missing or invalid authentication.\",\n\t\t},\n\t\t\"403\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Forbidden. You do not have permission to access this resource or to perform this action.\",\n\t\t},\n\t\t\"404\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Not Found. The requested resource was not found.\",\n\t\t},\n\t\t\"429\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Too Many Requests. You have exceeded the rate limit. Try again later.\",\n\t\t},\n\t\t\"500\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Internal Server Error. This is a problem with the server that you cannot fix.\",\n\t\t},\n\t\t...responses,\n\t} as any;\n}\n\nexport async function generator(\n\tendpoints: Record<string, Endpoint>,\n\tconfig?: {\n\t\turl: string;\n\t},\n) {\n\tconst components = {\n\t\tschemas: {},\n\t};\n\n\tObject.entries(endpoints).forEach(([_, value]) => {\n\t\tconst options = value.options as EndpointOptions;\n\t\tif (options.metadata?.SERVER_ONLY) return;\n\t\tif (options.method === \"GET\") {\n\t\t\tpaths[value.path] = {\n\t\t\t\tget: {\n\t\t\t\t\ttags: [\"Default\", ...(options.metadata?.openapi?.tags || [])],\n\t\t\t\t\tdescription: options.metadata?.openapi?.description,\n\t\t\t\t\toperationId: options.metadata?.openapi?.operationId,\n\t\t\t\t\tsecurity: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbearerAuth: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tparameters: getParameters(options),\n\t\t\t\t\tresponses: getResponse(options.metadata?.openapi?.responses),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (options.method === \"POST\") {\n\t\t\tconst body = getRequestBody(options);\n\t\t\tpaths[value.path] = {\n\t\t\t\tpost: {\n\t\t\t\t\ttags: [\"Default\", ...(options.metadata?.openapi?.tags || [])],\n\t\t\t\t\tdescription: options.metadata?.openapi?.description,\n\t\t\t\t\toperationId: options.metadata?.openapi?.operationId,\n\t\t\t\t\tsecurity: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbearerAuth: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tparameters: getParameters(options),\n\t\t\t\t\t...(body\n\t\t\t\t\t\t? { requestBody: body }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\t\t\t//set body none\n\t\t\t\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\tresponses: getResponse(options.metadata?.openapi?.responses),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t});\n\n\tconst res = {\n\t\topenapi: \"3.1.1\",\n\t\tinfo: {\n\t\t\ttitle: \"Better Auth\",\n\t\t\tdescription: \"API Reference for your Better Auth Instance\",\n\t\t\tversion: \"1.1.0\",\n\t\t},\n\t\tcomponents,\n\t\tsecurity: [\n\t\t\t{\n\t\t\t\tapiKeyCookie: [],\n\t\t\t},\n\t\t],\n\t\tservers: [\n\t\t\t{\n\t\t\t\turl: config?.url,\n\t\t\t},\n\t\t],\n\t\ttags: [\n\t\t\t{\n\t\t\t\tname: \"Default\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.\",\n\t\t\t},\n\t\t],\n\t\tpaths,\n\t};\n\treturn res;\n}\n\nexport const getHTML = (\n\tapiReference: Record<string, any>,\n\tconfig?: {\n\t\tlogo?: string;\n\t\ttheme?: string;\n\t\ttitle?: string;\n\t\tdescription?: string;\n\t},\n) => `<!doctype html>\n<html>\n <head>\n <title>Scalar API Reference</title>\n <meta charset=\"utf-8\" />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1\" />\n </head>\n <body>\n <script\n id=\"api-reference\"\n type=\"application/json\">\n ${JSON.stringify(apiReference)}\n </script>\n\t <script>\n var configuration = {\n\t \tfavicon: ${config?.logo ? `data:image/svg+xml;utf8,${encodeURIComponent(config.logo)}` : undefined} ,\n\t \ttheme: ${config?.theme || \"saturn\"},\n metaData: {\n\t\t\ttitle: ${config?.title || \"Open API Reference\"},\n\t\t\tdescription: ${config?.description || \"Better Call Open API\"},\n\t\t}\n }\n document.getElementById('api-reference').dataset.configuration =\n JSON.stringify(configuration)\n </script>\n\t <script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"></script>\n </body>\n</html>`;\n","import * as z from 'zod/v4';\nimport { createMiddleware, createEndpoint, APIError } from 'better-call';\nimport { g as getDate } from './better-auth.CW6D9eSx.mjs';\nimport { createHash } from '@better-auth/utils/hash';\nimport { base64, base64Url } from '@better-auth/utils/base64';\nimport { signJWT, symmetricEncrypt, symmetricDecrypt } from '../crypto/index.mjs';\nimport { betterFetch } from '@better-fetch/fetch';\nimport { jwtVerify, decodeJwt, decodeProtectedHeader, importJWK, createRemoteJWKSet } from 'jose';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport { g as generateRandomString } from './better-auth.B4Qoxdgc.mjs';\nimport { g as getOrigin, b as getHost, c as getProtocol } from './better-auth.VTXNLFMT.mjs';\nimport { deleteSessionCookie, setSessionCookie, setCookieCache } from '../cookies/index.mjs';\nimport { s as safeJSONParse } from './better-auth.tB5eU6EY.mjs';\nimport { createHMAC } from '@better-auth/utils/hmac';\nimport { binary } from '@better-auth/utils/binary';\nimport { JWTExpired } from 'jose/errors';\nimport '@better-auth/utils/random';\nimport { a as logger, g as generateId } from './better-auth.DBGfIDnh.mjs';\nimport { f as parseUserInput } from './better-auth.n2KFGwjY.mjs';\nimport { b as isDevelopment } from './better-auth.8zoxzg-F.mjs';\nimport 'defu';\nimport { B as BetterAuthError } from './better-auth.DdzSJf-n.mjs';\n\nconst optionsMiddleware = createMiddleware(async () => {\n return {};\n});\nconst createAuthMiddleware = createMiddleware.create({\n use: [\n optionsMiddleware,\n /**\n * Only use for post hooks\n */\n createMiddleware(async () => {\n return {};\n })\n ]\n});\nconst createAuthEndpoint = createEndpoint.create({\n use: [optionsMiddleware]\n});\n\nfunction escapeRegExpChar(char) {\n if (char === \"-\" || char === \"^\" || char === \"$\" || char === \"+\" || char === \".\" || char === \"(\" || char === \")\" || char === \"|\" || char === \"[\" || char === \"]\" || char === \"{\" || char === \"}\" || char === \"*\" || char === \"?\" || char === \"\\\\\") {\n return `\\\\${char}`;\n } else {\n return char;\n }\n}\nfunction escapeRegExpString(str) {\n let result = \"\";\n for (let i = 0; i < str.length; i++) {\n result += escapeRegExpChar(str[i]);\n }\n return result;\n}\nfunction transform(pattern, separator = true) {\n if (Array.isArray(pattern)) {\n let regExpPatterns = pattern.map((p) => `^${transform(p, separator)}$`);\n return `(?:${regExpPatterns.join(\"|\")})`;\n }\n let separatorSplitter = \"\";\n let separatorMatcher = \"\";\n let wildcard = \".\";\n if (separator === true) {\n separatorSplitter = \"/\";\n separatorMatcher = \"[/\\\\\\\\]\";\n wildcard = \"[^/\\\\\\\\]\";\n } else if (separator) {\n separatorSplitter = separator;\n separatorMatcher = escapeRegExpString(separatorSplitter);\n if (separatorMatcher.length > 1) {\n separatorMatcher = `(?:${separatorMatcher})`;\n wildcard = `((?!${separatorMatcher}).)`;\n } else {\n wildcard = `[^${separatorMatcher}]`;\n }\n }\n let requiredSeparator = separator ? `${separatorMatcher}+?` : \"\";\n let optionalSeparator = separator ? `${separatorMatcher}*?` : \"\";\n let segments = separator ? pattern.split(separatorSplitter) : [pattern];\n let result = \"\";\n for (let s = 0; s < segments.length; s++) {\n let segment = segments[s];\n let nextSegment = segments[s + 1];\n let currentSeparator = \"\";\n if (!segment && s > 0) {\n continue;\n }\n if (separator) {\n if (s === segments.length - 1) {\n currentSeparator = optionalSeparator;\n } else if (nextSegment !== \"**\") {\n currentSeparator = requiredSeparator;\n } else {\n currentSeparator = \"\";\n }\n }\n if (separator && segment === \"**\") {\n if (currentSeparator) {\n result += s === 0 ? \"\" : currentSeparator;\n result += `(?:${wildcard}*?${currentSeparator})*?`;\n }\n continue;\n }\n for (let c = 0; c < segment.length; c++) {\n let char = segment[c];\n if (char === \"\\\\\") {\n if (c < segment.length - 1) {\n result += escapeRegExpChar(segment[c + 1]);\n c++;\n }\n } else if (char === \"?\") {\n result += wildcard;\n } else if (char === \"*\") {\n result += `${wildcard}*?`;\n } else {\n result += escapeRegExpChar(char);\n }\n }\n result += currentSeparator;\n }\n return result;\n}\nfunction isMatch(regexp, sample) {\n if (typeof sample !== \"string\") {\n throw new TypeError(`Sample must be a string, but ${typeof sample} given`);\n }\n return regexp.test(sample);\n}\nfunction wildcardMatch(pattern, options) {\n if (typeof pattern !== \"string\" && !Array.isArray(pattern)) {\n throw new TypeError(\n `The first argument must be a single pattern string or an array of patterns, but ${typeof pattern} given`\n );\n }\n if (typeof options === \"string\" || typeof options === \"boolean\") {\n options = { separator: options };\n }\n if (arguments.length === 2 && !(typeof options === \"undefined\" || typeof options === \"object\" && options !== null && !Array.isArray(options))) {\n throw new TypeError(\n `The second argument must be an options object or a string/boolean separator, but ${typeof options} given`\n );\n }\n options = options || {};\n if (options.separator === \"\\\\\") {\n throw new Error(\n \"\\\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead\"\n );\n }\n let regexpPattern = transform(pattern, options.separator);\n let regexp = new RegExp(`^${regexpPattern}$`, options.flags);\n let fn = isMatch.bind(null, regexp);\n fn.options = options;\n fn.pattern = pattern;\n fn.regexp = regexp;\n return fn;\n}\n\nconst originCheckMiddleware = createAuthMiddleware(async (ctx) => {\n if (ctx.request?.method !== \"POST\" || !ctx.request) {\n return;\n }\n const { body, query, context } = ctx;\n const originHeader = ctx.headers?.get(\"origin\") || ctx.headers?.get(\"referer\") || \"\";\n const callbackURL = body?.callbackURL || query?.callbackURL;\n const redirectURL = body?.redirectTo;\n const errorCallbackURL = body?.errorCallbackURL;\n const newUserCallbackURL = body?.newUserCallbackURL;\n const trustedOrigins = Array.isArray(context.options.trustedOrigins) ? context.trustedOrigins : [\n ...context.trustedOrigins,\n ...await context.options.trustedOrigins?.(ctx.request) || []\n ];\n const usesCookies = ctx.headers?.has(\"cookie\");\n const matchesPattern = (url, pattern) => {\n if (url.startsWith(\"/\")) {\n return false;\n }\n if (pattern.includes(\"*\")) {\n if (pattern.includes(\"://\")) {\n return wildcardMatch(pattern)(getOrigin(url) || url);\n }\n return wildcardMatch(pattern)(getHost(url));\n }\n const protocol = getProtocol(url);\n return protocol === \"http:\" || protocol === \"https:\" || !protocol ? pattern === getOrigin(url) : url.startsWith(pattern);\n };\n const validateURL = (url, label) => {\n if (!url) {\n return;\n }\n const isTrustedOrigin = trustedOrigins.some(\n (origin) => matchesPattern(url, origin) || url?.startsWith(\"/\") && label !== \"origin\" && /^\\/(?!\\/|\\\\|%2f|%5c)[\\w\\-.\\+/@]*(?:\\?[\\w\\-.\\+/=&%@]*)?$/.test(url)\n );\n if (!isTrustedOrigin) {\n ctx.context.logger.error(`Invalid ${label}: ${url}`);\n ctx.context.logger.info(\n `If it's a valid URL, please add ${url} to trustedOrigins in your auth config\n`,\n `Current list of trustedOrigins: ${trustedOrigins}`\n );\n throw new APIError(\"FORBIDDEN\", { message: `Invalid ${label}` });\n }\n };\n if (usesCookies && !ctx.context.options.advanced?.disableCSRFCheck) {\n validateURL(originHeader, \"origin\");\n }\n callbackURL && validateURL(callbackURL, \"callbackURL\");\n redirectURL && validateURL(redirectURL, \"redirectURL\");\n errorCallbackURL && validateURL(errorCallbackURL, \"errorCallbackURL\");\n newUserCallbackURL && validateURL(newUserCallbackURL, \"newUserCallbackURL\");\n});\nconst originCheck = (getValue) => createAuthMiddleware(async (ctx) => {\n if (!ctx.request) {\n return;\n }\n const { context } = ctx;\n const callbackURL = getValue(ctx);\n const trustedOrigins = Array.isArray(\n context.options.trustedOrigins\n ) ? context.trustedOrigins : [\n ...context.trustedOrigins,\n ...await context.options.trustedOrigins?.(ctx.request) || []\n ];\n const matchesPattern = (url, pattern) => {\n if (url.startsWith(\"/\")) {\n return false;\n }\n if (pattern.includes(\"*\")) {\n if (pattern.includes(\"://\")) {\n return wildcardMatch(pattern)(getOrigin(url) || url);\n }\n return wildcardMatch(pattern)(getHost(url));\n }\n const protocol = getProtocol(url);\n return protocol === \"http:\" || protocol === \"https:\" || !protocol ? pattern === getOrigin(url) : url.startsWith(pattern);\n };\n const validateURL = (url, label) => {\n if (!url) {\n return;\n }\n const isTrustedOrigin = trustedOrigins.some(\n (origin) => matchesPattern(url, origin) || url?.startsWith(\"/\") && label !== \"origin\" && /^\\/(?!\\/|\\\\|%2f|%5c)[\\w\\-.\\+/@]*(?:\\?[\\w\\-.\\+/=&%@]*)?$/.test(\n url\n )\n );\n if (!isTrustedOrigin) {\n ctx.context.logger.error(`Invalid ${label}: ${url}`);\n ctx.context.logger.info(\n `If it's a valid URL, please add ${url} to trustedOrigins in your auth config\n`,\n `Current list of trustedOrigins: ${trustedOrigins}`\n );\n throw new APIError(\"FORBIDDEN\", { message: `Invalid ${label}` });\n }\n };\n const callbacks = Array.isArray(callbackURL) ? callbackURL : [callbackURL];\n for (const url of callbacks) {\n validateURL(url, \"callbackURL\");\n }\n});\n\nconst BASE_ERROR_CODES = {\n USER_NOT_FOUND: \"User not found\",\n FAILED_TO_CREATE_USER: \"Failed to create user\",\n FAILED_TO_CREATE_SESSION: \"Failed to create session\",\n FAILED_TO_UPDATE_USER: \"Failed to update user\",\n FAILED_TO_GET_SESSION: \"Failed to get session\",\n INVALID_PASSWORD: \"Invalid password\",\n INVALID_EMAIL: \"Invalid email\",\n INVALID_EMAIL_OR_PASSWORD: \"Invalid email or password\",\n SOCIAL_ACCOUNT_ALREADY_LINKED: \"Social account already linked\",\n PROVIDER_NOT_FOUND: \"Provider not found\",\n INVALID_TOKEN: \"invalid token\",\n ID_TOKEN_NOT_SUPPORTED: \"id_token not supported\",\n FAILED_TO_GET_USER_INFO: \"Failed to get user info\",\n USER_EMAIL_NOT_FOUND: \"User email not found\",\n EMAIL_NOT_VERIFIED: \"Email not verified\",\n PASSWORD_TOO_SHORT: \"Password too short\",\n PASSWORD_TOO_LONG: \"Password too long\",\n USER_ALREADY_EXISTS: \"User already exists\",\n EMAIL_CAN_NOT_BE_UPDATED: \"Email can not be updated\",\n CREDENTIAL_ACCOUNT_NOT_FOUND: \"Credential account not found\",\n SESSION_EXPIRED: \"Session expired. Re-authenticate to perform this action.\",\n FAILED_TO_UNLINK_LAST_ACCOUNT: \"You can't unlink your last account\",\n ACCOUNT_NOT_FOUND: \"Account not found\",\n USER_ALREADY_HAS_PASSWORD: \"User already has a password. Provide that to delete the account.\"\n};\n\nconst getSession = () => createAuthEndpoint(\n \"/get-session\",\n {\n method: \"GET\",\n query: z.optional(\n z.object({\n /**\n * If cookie cache is enabled, it will disable the cache\n * and fetch the session from the database\n */\n disableCookieCache: z.coerce.boolean().meta({\n description: \"Disable cookie cache and fetch session from database\"\n }).optional(),\n disableRefresh: z.coerce.boolean().meta({\n description: \"Disable session refresh. Useful for checking session status, without updating the session\"\n }).optional()\n })\n ),\n requireHeaders: true,\n metadata: {\n openapi: {\n description: \"Get the current session\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n session: {\n $ref: \"#/components/schemas/Session\"\n },\n user: {\n $ref: \"#/components/schemas/User\"\n }\n },\n required: [\"session\", \"user\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n try {\n const sessionCookieToken = await ctx.getSignedCookie(\n ctx.context.authCookies.sessionToken.name,\n ctx.context.secret\n );\n if (!sessionCookieToken) {\n return null;\n }\n const sessionDataCookie = ctx.getCookie(\n ctx.context.authCookies.sessionData.name\n );\n const sessionDataPayload = sessionDataCookie ? safeJSONParse(binary.decode(base64.decode(sessionDataCookie))) : null;\n if (sessionDataPayload) {\n const isValid = await createHMAC(\"SHA-256\", \"base64urlnopad\").verify(\n ctx.context.secret,\n JSON.stringify({\n ...sessionDataPayload.session,\n expiresAt: sessionDataPayload.expiresAt\n }),\n sessionDataPayload.signature\n );\n if (!isValid) {\n const dataCookie = ctx.context.authCookies.sessionData.name;\n ctx.setCookie(dataCookie, \"\", {\n maxAge: 0\n });\n return ctx.json(null);\n }\n }\n const dontRememberMe = await ctx.getSignedCookie(\n ctx.context.authCookies.dontRememberToken.name,\n ctx.context.secret\n );\n if (sessionDataPayload?.session && ctx.context.options.session?.cookieCache?.enabled && !ctx.query?.disableCookieCache) {\n const session2 = sessionDataPayload.session;\n const hasExpired = sessionDataPayload.expiresAt < Date.now() || session2.session.expiresAt < /* @__PURE__ */ new Date();\n if (!hasExpired) {\n return ctx.json(\n session2\n );\n } else {\n const dataCookie = ctx.context.authCookies.sessionData.name;\n ctx.setCookie(dataCookie, \"\", {\n maxAge: 0\n });\n }\n }\n const session = await ctx.context.internalAdapter.findSession(sessionCookieToken);\n ctx.context.session = session;\n if (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) {\n deleteSessionCookie(ctx);\n if (session) {\n await ctx.context.internalAdapter.deleteSession(\n session.session.token\n );\n }\n return ctx.json(null);\n }\n if (dontRememberMe || ctx.query?.disableRefresh) {\n return ctx.json(\n session\n );\n }\n const expiresIn = ctx.context.sessionConfig.expiresIn;\n const updateAge = ctx.context.sessionConfig.updateAge;\n const sessionIsDueToBeUpdatedDate = session.session.expiresAt.valueOf() - expiresIn * 1e3 + updateAge * 1e3;\n const shouldBeUpdated = sessionIsDueToBeUpdatedDate <= Date.now();\n if (shouldBeUpdated && (!ctx.query?.disableRefresh || !ctx.context.options.session?.disableSessionRefresh)) {\n const updatedSession = await ctx.context.internalAdapter.updateSession(\n session.session.token,\n {\n expiresAt: getDate(ctx.context.sessionConfig.expiresIn, \"sec\"),\n updatedAt: /* @__PURE__ */ new Date()\n }\n );\n if (!updatedSession) {\n deleteSessionCookie(ctx);\n return ctx.json(null, { status: 401 });\n }\n const maxAge = (updatedSession.expiresAt.valueOf() - Date.now()) / 1e3;\n await setSessionCookie(\n ctx,\n {\n session: updatedSession,\n user: session.user\n },\n false,\n {\n maxAge\n }\n );\n return ctx.json({\n session: updatedSession,\n user: session.user\n });\n }\n await setCookieCache(ctx, session);\n return ctx.json(\n session\n );\n } catch (error) {\n ctx.context.logger.error(\"INTERNAL_SERVER_ERROR\", error);\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION\n });\n }\n }\n);\nconst getSessionFromCtx = async (ctx, config) => {\n if (ctx.context.session) {\n return ctx.context.session;\n }\n const session = await getSession()({\n ...ctx,\n asResponse: false,\n headers: ctx.headers,\n returnHeaders: false,\n query: {\n ...config,\n ...ctx.query\n }\n }).catch((e) => {\n return null;\n });\n ctx.context.session = session;\n return session;\n};\nconst sessionMiddleware = createAuthMiddleware(async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (!session?.session) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n return {\n session\n };\n});\nconst requestOnlySessionMiddleware = createAuthMiddleware(\n async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (!session?.session && (ctx.request || ctx.headers)) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n return { session };\n }\n);\nconst freshSessionMiddleware = createAuthMiddleware(async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (!session?.session) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n if (ctx.context.sessionConfig.freshAge === 0) {\n return {\n session\n };\n }\n const freshAge = ctx.context.sessionConfig.freshAge;\n const lastUpdated = session.session.updatedAt?.valueOf() || session.session.createdAt.valueOf();\n const now = Date.now();\n const isFresh = now - lastUpdated < freshAge * 1e3;\n if (!isFresh) {\n throw new APIError(\"FORBIDDEN\", {\n message: \"Session is not fresh\"\n });\n }\n return {\n session\n };\n});\nconst listSessions = () => createAuthEndpoint(\n \"/list-sessions\",\n {\n method: \"GET\",\n use: [sessionMiddleware],\n requireHeaders: true,\n metadata: {\n openapi: {\n description: \"List all active sessions for the user\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"array\",\n items: {\n $ref: \"#/components/schemas/Session\"\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n try {\n const sessions = await ctx.context.internalAdapter.listSessions(\n ctx.context.session.user.id\n );\n const activeSessions = sessions.filter((session) => {\n return session.expiresAt > /* @__PURE__ */ new Date();\n });\n return ctx.json(\n activeSessions\n );\n } catch (e) {\n ctx.context.logger.error(e);\n throw ctx.error(\"INTERNAL_SERVER_ERROR\");\n }\n }\n);\nconst revokeSession = createAuthEndpoint(\n \"/revoke-session\",\n {\n method: \"POST\",\n body: z.object({\n token: z.string().meta({\n description: \"The token to revoke\"\n })\n }),\n use: [sessionMiddleware],\n requireHeaders: true,\n metadata: {\n openapi: {\n description: \"Revoke a single session\",\n requestBody: {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n token: {\n type: \"string\",\n description: \"The token to revoke\"\n }\n },\n required: [\"token\"]\n }\n }\n }\n },\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the session was revoked successfully\"\n }\n },\n required: [\"status\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const token = ctx.body.token;\n const findSession = await ctx.context.internalAdapter.findSession(token);\n if (!findSession) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Session not found\"\n });\n }\n if (findSession.session.userId !== ctx.context.session.user.id) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n try {\n await ctx.context.internalAdapter.deleteSession(token);\n } catch (error) {\n ctx.context.logger.error(\n error && typeof error === \"object\" && \"name\" in error ? error.name : \"\",\n error\n );\n throw new APIError(\"INTERNAL_SERVER_ERROR\");\n }\n return ctx.json({\n status: true\n });\n }\n);\nconst revokeSessions = createAuthEndpoint(\n \"/revoke-sessions\",\n {\n method: \"POST\",\n use: [sessionMiddleware],\n requireHeaders: true,\n metadata: {\n openapi: {\n description: \"Revoke all sessions for the user\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if all sessions were revoked successfully\"\n }\n },\n required: [\"status\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n try {\n await ctx.context.internalAdapter.deleteSessions(\n ctx.context.session.user.id\n );\n } catch (error) {\n ctx.context.logger.error(\n error && typeof error === \"object\" && \"name\" in error ? error.name : \"\",\n error\n );\n throw new APIError(\"INTERNAL_SERVER_ERROR\");\n }\n return ctx.json({\n status: true\n });\n }\n);\nconst revokeOtherSessions = createAuthEndpoint(\n \"/revoke-other-sessions\",\n {\n method: \"POST\",\n requireHeaders: true,\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Revoke all other sessions for the user except the current one\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if all other sessions were revoked successfully\"\n }\n },\n required: [\"status\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n if (!session.user) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n const sessions = await ctx.context.internalAdapter.listSessions(\n session.user.id\n );\n const activeSessions = sessions.filter((session2) => {\n return session2.expiresAt > /* @__PURE__ */ new Date();\n });\n const otherSessions = activeSessions.filter(\n (session2) => session2.token !== ctx.context.session.session.token\n );\n await Promise.all(\n otherSessions.map(\n (session2) => ctx.context.internalAdapter.deleteSession(session2.token)\n )\n );\n return ctx.json({\n status: true\n });\n }\n);\n\nasync function createEmailVerificationToken(secret, email, updateTo, expiresIn = 3600) {\n const token = await signJWT(\n {\n email: email.toLowerCase(),\n updateTo\n },\n secret,\n expiresIn\n );\n return token;\n}\nasync function sendVerificationEmailFn(ctx, user) {\n if (!ctx.context.options.emailVerification?.sendVerificationEmail) {\n ctx.context.logger.error(\"Verification email isn't enabled.\");\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Verification email isn't enabled\"\n });\n }\n const token = await createEmailVerificationToken(\n ctx.context.secret,\n user.email,\n void 0,\n ctx.context.options.emailVerification?.expiresIn\n );\n const url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n await ctx.context.options.emailVerification.sendVerificationEmail(\n {\n user,\n url,\n token\n },\n ctx.request\n );\n}\nconst sendVerificationEmail = createAuthEndpoint(\n \"/send-verification-email\",\n {\n method: \"POST\",\n body: z.object({\n email: z.email().meta({\n description: \"The email to send the verification email to\"\n }),\n callbackURL: z.string().meta({\n description: \"The URL to use for email verification callback\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Send a verification email to the user\",\n requestBody: {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n email: {\n type: \"string\",\n description: \"The email to send the verification email to\",\n example: \"user@example.com\"\n },\n callbackURL: {\n type: \"string\",\n description: \"The URL to use for email verification callback\",\n example: \"https://example.com/callback\",\n nullable: true\n }\n },\n required: [\"email\"]\n }\n }\n }\n },\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the email was sent successfully\",\n example: true\n }\n }\n }\n }\n }\n },\n \"400\": {\n description: \"Bad Request\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\",\n description: \"Error message\",\n example: \"Verification email isn't enabled\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.context.options.emailVerification?.sendVerificationEmail) {\n ctx.context.logger.error(\"Verification email isn't enabled.\");\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Verification email isn't enabled\"\n });\n }\n const { email } = ctx.body;\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n const user = await ctx.context.internalAdapter.findUserByEmail(email);\n if (!user) {\n return ctx.json({\n status: true\n });\n }\n await sendVerificationEmailFn(ctx, user.user);\n return ctx.json({\n status: true\n });\n }\n if (session?.user.emailVerified) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"You can only send a verification email to an unverified email\"\n });\n }\n if (session?.user.email !== email) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"You can only send a verification email to your own email\"\n });\n }\n await sendVerificationEmailFn(ctx, session.user);\n return ctx.json({\n status: true\n });\n }\n);\nconst verifyEmail = createAuthEndpoint(\n \"/verify-email\",\n {\n method: \"GET\",\n query: z.object({\n token: z.string().meta({\n description: \"The token to verify the email\"\n }),\n callbackURL: z.string().meta({\n description: \"The URL to redirect to after email verification\"\n }).optional()\n }),\n use: [originCheck((ctx) => ctx.query.callbackURL)],\n metadata: {\n openapi: {\n description: \"Verify the email of the user\",\n parameters: [\n {\n name: \"token\",\n in: \"query\",\n description: \"The token to verify the email\",\n required: true,\n schema: {\n type: \"string\"\n }\n },\n {\n name: \"callbackURL\",\n in: \"query\",\n description: \"The URL to redirect to after email verification\",\n required: false,\n schema: {\n type: \"string\"\n }\n }\n ],\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"User ID\"\n },\n email: {\n type: \"string\",\n description: \"User email\"\n },\n name: {\n type: \"string\",\n description: \"User name\"\n },\n image: {\n type: \"string\",\n description: \"User image URL\"\n },\n emailVerified: {\n type: \"boolean\",\n description: \"Indicates if the user email is verified\"\n },\n createdAt: {\n type: \"string\",\n description: \"User creation date\"\n },\n updatedAt: {\n type: \"string\",\n description: \"User update date\"\n }\n },\n required: [\n \"id\",\n \"email\",\n \"name\",\n \"image\",\n \"emailVerified\",\n \"createdAt\",\n \"updatedAt\"\n ]\n },\n status: {\n type: \"boolean\",\n description: \"Indicates if the email was verified successfully\"\n }\n },\n required: [\"user\", \"status\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n function redirectOnError(error) {\n if (ctx.query.callbackURL) {\n if (ctx.query.callbackURL.includes(\"?\")) {\n throw ctx.redirect(`${ctx.query.callbackURL}&error=${error}`);\n }\n throw ctx.redirect(`${ctx.query.callbackURL}?error=${error}`);\n }\n throw new APIError(\"UNAUTHORIZED\", {\n message: error\n });\n }\n const { token } = ctx.query;\n let jwt;\n try {\n jwt = await jwtVerify(\n token,\n new TextEncoder().encode(ctx.context.secret),\n {\n algorithms: [\"HS256\"]\n }\n );\n } catch (e) {\n if (e instanceof JWTExpired) {\n return redirectOnError(\"token_expired\");\n }\n return redirectOnError(\"invalid_token\");\n }\n const schema = z.object({\n email: z.string().email(),\n updateTo: z.string().optional()\n });\n const parsed = schema.parse(jwt.payload);\n const user = await ctx.context.internalAdapter.findUserByEmail(\n parsed.email\n );\n if (!user) {\n return redirectOnError(\"user_not_found\");\n }\n if (parsed.updateTo) {\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n if (ctx.query.callbackURL) {\n throw ctx.redirect(`${ctx.query.callbackURL}?error=unauthorized`);\n }\n return redirectOnError(\"unauthorized\");\n }\n if (session.user.email !== parsed.email) {\n if (ctx.query.callbackURL) {\n throw ctx.redirect(`${ctx.query.callbackURL}?error=unauthorized`);\n }\n return redirectOnError(\"unauthorized\");\n }\n const updatedUser2 = await ctx.context.internalAdapter.updateUserByEmail(\n parsed.email,\n {\n email: parsed.updateTo,\n emailVerified: false\n },\n ctx\n );\n const newToken = await createEmailVerificationToken(\n ctx.context.secret,\n parsed.updateTo\n );\n await ctx.context.options.emailVerification?.sendVerificationEmail?.(\n {\n user: updatedUser2,\n url: `${ctx.context.baseURL}/verify-email?token=${newToken}&callbackURL=${ctx.query.callbackURL || \"/\"}`,\n token: newToken\n },\n ctx.request\n );\n await setSessionCookie(ctx, {\n session: session.session,\n user: {\n ...session.user,\n email: parsed.updateTo,\n emailVerified: false\n }\n });\n if (ctx.query.callbackURL) {\n throw ctx.redirect(ctx.query.callbackURL);\n }\n return ctx.json({\n status: true,\n user: {\n id: updatedUser2.id,\n email: updatedUser2.email,\n name: updatedUser2.name,\n image: updatedUser2.image,\n emailVerified: updatedUser2.emailVerified,\n createdAt: updatedUser2.createdAt,\n updatedAt: updatedUser2.updatedAt\n }\n });\n }\n if (ctx.context.options.emailVerification?.onEmailVerification) {\n await ctx.context.options.emailVerification.onEmailVerification(\n user.user,\n ctx.request\n );\n }\n const updatedUser = await ctx.context.internalAdapter.updateUserByEmail(\n parsed.email,\n {\n emailVerified: true\n },\n ctx\n );\n if (ctx.context.options.emailVerification?.afterEmailVerification) {\n await ctx.context.options.emailVerification.afterEmailVerification(\n updatedUser,\n ctx.request\n );\n }\n if (ctx.context.options.emailVerification?.autoSignInAfterVerification) {\n const currentSession = await getSessionFromCtx(ctx);\n if (!currentSession || currentSession.user.email !== parsed.email) {\n const session = await ctx.context.internalAdapter.createSession(\n user.user.id,\n ctx\n );\n if (!session) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Failed to create session\"\n });\n }\n await setSessionCookie(ctx, {\n session,\n user: {\n ...user.user,\n emailVerified: true\n }\n });\n } else {\n await setSessionCookie(ctx, {\n session: currentSession.session,\n user: {\n ...currentSession.user,\n emailVerified: true\n }\n });\n }\n }\n if (ctx.query.callbackURL) {\n throw ctx.redirect(ctx.query.callbackURL);\n }\n return ctx.json({\n status: true,\n user: null\n });\n }\n);\n\nconst HIDE_METADATA = {\n isAction: false\n};\n\nasync function generateState(c, link) {\n const callbackURL = c.body?.callbackURL || c.context.options.baseURL;\n if (!callbackURL) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"callbackURL is required\"\n });\n }\n const codeVerifier = generateRandomString(128);\n const state = generateRandomString(32);\n const data = JSON.stringify({\n callbackURL,\n codeVerifier,\n errorURL: c.body?.errorCallbackURL,\n newUserURL: c.body?.newUserCallbackURL,\n link,\n /**\n * This is the actual expiry time of the state\n */\n expiresAt: Date.now() + 10 * 60 * 1e3,\n requestSignUp: c.body?.requestSignUp\n });\n const expiresAt = /* @__PURE__ */ new Date();\n expiresAt.setMinutes(expiresAt.getMinutes() + 10);\n const verification = await c.context.internalAdapter.createVerificationValue(\n {\n value: data,\n identifier: state,\n expiresAt\n },\n c\n );\n if (!verification) {\n c.context.logger.error(\n \"Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database\"\n );\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Unable to create verification\"\n });\n }\n return {\n state: verification.identifier,\n codeVerifier\n };\n}\nasync function parseState(c) {\n const state = c.query.state || c.body.state;\n const data = await c.context.internalAdapter.findVerificationValue(state);\n if (!data) {\n c.context.logger.error(\"State Mismatch. Verification not found\", {\n state\n });\n const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;\n throw c.redirect(`${errorURL}?error=please_restart_the_process`);\n }\n const parsedData = z.object({\n callbackURL: z.string(),\n codeVerifier: z.string(),\n errorURL: z.string().optional(),\n newUserURL: z.string().optional(),\n expiresAt: z.number(),\n link: z.object({\n email: z.string(),\n userId: z.coerce.string()\n }).optional(),\n requestSignUp: z.boolean().optional()\n }).parse(JSON.parse(data.value));\n if (!parsedData.errorURL) {\n parsedData.errorURL = `${c.context.baseURL}/error`;\n }\n if (parsedData.expiresAt < Date.now()) {\n await c.context.internalAdapter.deleteVerificationValue(data.id);\n const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;\n throw c.redirect(`${errorURL}?error=please_restart_the_process`);\n }\n await c.context.internalAdapter.deleteVerificationValue(data.id);\n return parsedData;\n}\n\nasync function generateCodeChallenge(codeVerifier) {\n const codeChallengeBytes = await createHash(\"SHA-256\").digest(codeVerifier);\n return base64Url.encode(new Uint8Array(codeChallengeBytes), {\n padding: false\n });\n}\nfunction getOAuth2Tokens(data) {\n return {\n tokenType: data.token_type,\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n accessTokenExpiresAt: data.expires_in ? getDate(data.expires_in, \"sec\") : void 0,\n refreshTokenExpiresAt: data.refresh_token_expires_in ? getDate(data.refresh_token_expires_in, \"sec\") : void 0,\n scopes: data?.scope ? typeof data.scope === \"string\" ? data.scope.split(\" \") : data.scope : [],\n idToken: data.id_token\n };\n}\nconst encodeOAuthParameter = (value) => encodeURIComponent(value).replace(/%20/g, \"+\");\nfunction getAccessTokenUtil(token, ctx) {\n if (ctx.options.account?.encryptOAuthTokens) {\n return symmetricDecrypt({\n key: ctx.secret,\n data: token\n });\n }\n return token;\n}\nfunction setTokenUtil(token, ctx) {\n if (ctx.options.account?.encryptOAuthTokens && token) {\n return symmetricEncrypt({\n key: ctx.secret,\n data: token\n });\n }\n return token ?? null;\n}\n\nasync function handleOAuthUserInfo(c, {\n userInfo,\n account,\n callbackURL,\n disableSignUp,\n overrideUserInfo\n}) {\n const dbUser = await c.context.internalAdapter.findOAuthUser(\n userInfo.email.toLowerCase(),\n account.accountId,\n account.providerId\n ).catch((e) => {\n logger.error(\n \"Better auth was unable to query your database.\\nError: \",\n e\n );\n const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;\n throw c.redirect(`${errorURL}?error=internal_server_error`);\n });\n let user = dbUser?.user;\n let isRegister = !user;\n if (dbUser) {\n const hasBeenLinked = dbUser.accounts.find(\n (a) => a.providerId === account.providerId && a.accountId === account.accountId\n );\n if (!hasBeenLinked) {\n const trustedProviders = c.context.options.account?.accountLinking?.trustedProviders;\n const isTrustedProvider = trustedProviders?.includes(\n account.providerId\n );\n if (!isTrustedProvider && !userInfo.emailVerified || c.context.options.account?.accountLinking?.enabled === false) {\n if (isDevelopment) {\n logger.warn(\n `User already exist but account isn't linked to ${account.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`\n );\n }\n return {\n error: \"account not linked\",\n data: null\n };\n }\n try {\n await c.context.internalAdapter.linkAccount(\n {\n providerId: account.providerId,\n accountId: userInfo.id.toString(),\n userId: dbUser.user.id,\n accessToken: await setTokenUtil(account.accessToken, c.context),\n refreshToken: await setTokenUtil(account.refreshToken, c.context),\n idToken: account.idToken,\n accessTokenExpiresAt: account.accessTokenExpiresAt,\n refreshTokenExpiresAt: account.refreshTokenExpiresAt,\n scope: account.scope\n },\n c\n );\n } catch (e) {\n logger.error(\"Unable to link account\", e);\n return {\n error: \"unable to link account\",\n data: null\n };\n }\n } else {\n if (c.context.options.account?.updateAccountOnSignIn !== false) {\n const updateData = Object.fromEntries(\n Object.entries({\n idToken: account.idToken,\n accessToken: await setTokenUtil(account.accessToken, c.context),\n refreshToken: await setTokenUtil(account.refreshToken, c.context),\n accessTokenExpiresAt: account.accessTokenExpiresAt,\n refreshTokenExpiresAt: account.refreshTokenExpiresAt,\n scope: account.scope\n }).filter(([_, value]) => value !== void 0)\n );\n if (Object.keys(updateData).length > 0) {\n await c.context.internalAdapter.updateAccount(\n hasBeenLinked.id,\n updateData,\n c\n );\n }\n }\n }\n if (overrideUserInfo) {\n const { id: _, ...restUserInfo } = userInfo;\n await c.context.internalAdapter.updateUser(dbUser.user.id, {\n ...restUserInfo,\n email: userInfo.email.toLowerCase(),\n emailVerified: userInfo.email.toLowerCase() === dbUser.user.email ? dbUser.user.emailVerified || userInfo.emailVerified : userInfo.emailVerified\n });\n }\n } else {\n if (disableSignUp) {\n return {\n error: \"signup disabled\",\n data: null,\n isRegister: false\n };\n }\n try {\n const { id: _, ...restUserInfo } = userInfo;\n user = await c.context.internalAdapter.createOAuthUser(\n {\n ...restUserInfo,\n email: userInfo.email.toLowerCase()\n },\n {\n accessToken: await setTokenUtil(account.accessToken, c.context),\n refreshToken: await setTokenUtil(account.refreshToken, c.context),\n idToken: account.idToken,\n accessTokenExpiresAt: account.accessTokenExpiresAt,\n refreshTokenExpiresAt: account.refreshTokenExpiresAt,\n scope: account.scope,\n providerId: account.providerId,\n accountId: userInfo.id.toString()\n },\n c\n ).then((res) => res?.user);\n if (!userInfo.emailVerified && user && c.context.options.emailVerification?.sendOnSignUp) {\n const token = await createEmailVerificationToken(\n c.context.secret,\n user.email,\n void 0,\n c.context.options.emailVerification?.expiresIn\n );\n const url = `${c.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`;\n await c.context.options.emailVerification?.sendVerificationEmail?.(\n {\n user,\n url,\n token\n },\n c.request\n );\n }\n } catch (e) {\n logger.error(e);\n if (e instanceof APIError) {\n return {\n error: e.message,\n data: null,\n isRegister: false\n };\n }\n return {\n error: \"unable to create user\",\n data: null,\n isRegister: false\n };\n }\n }\n if (!user) {\n return {\n error: \"unable to create user\",\n data: null,\n isRegister: false\n };\n }\n const session = await c.context.internalAdapter.createSession(user.id, c);\n if (!session) {\n return {\n error: \"unable to create session\",\n data: null,\n isRegister: false\n };\n }\n return {\n data: {\n session,\n user\n },\n error: null,\n isRegister\n };\n}\n\nasync function createAuthorizationURL({\n id,\n options,\n authorizationEndpoint,\n state,\n codeVerifier,\n scopes,\n claims,\n redirectURI,\n duration,\n prompt,\n accessType,\n responseType,\n display,\n loginHint,\n hd,\n responseMode,\n additionalParams,\n scopeJoiner\n}) {\n const url = new URL(authorizationEndpoint);\n url.searchParams.set(\"response_type\", responseType || \"code\");\n url.searchParams.set(\"client_id\", options.clientId);\n url.searchParams.set(\"state\", state);\n url.searchParams.set(\"scope\", scopes.join(scopeJoiner || \" \"));\n url.searchParams.set(\"redirect_uri\", options.redirectURI || redirectURI);\n duration && url.searchParams.set(\"duration\", duration);\n display && url.searchParams.set(\"display\", display);\n loginHint && url.searchParams.set(\"login_hint\", loginHint);\n prompt && url.searchParams.set(\"prompt\", prompt);\n hd && url.searchParams.set(\"hd\", hd);\n accessType && url.searchParams.set(\"access_type\", accessType);\n responseMode && url.searchParams.set(\"response_mode\", responseMode);\n if (codeVerifier) {\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n url.searchParams.set(\"code_challenge\", codeChallenge);\n }\n if (claims) {\n const claimsObj = claims.reduce(\n (acc, claim) => {\n acc[claim] = null;\n return acc;\n },\n {}\n );\n url.searchParams.set(\n \"claims\",\n JSON.stringify({\n id_token: { email: null, email_verified: null, ...claimsObj }\n })\n );\n }\n if (additionalParams) {\n Object.entries(additionalParams).forEach(([key, value]) => {\n url.searchParams.set(key, value);\n });\n }\n return url;\n}\n\nasync function validateAuthorizationCode({\n code,\n codeVerifier,\n redirectURI,\n options,\n tokenEndpoint,\n authentication,\n deviceId,\n headers,\n additionalParams = {}\n}) {\n const body = new URLSearchParams();\n const requestHeaders = {\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\",\n \"user-agent\": \"better-auth\",\n ...headers\n };\n body.set(\"grant_type\", \"authorization_code\");\n body.set(\"code\", code);\n codeVerifier && body.set(\"code_verifier\", codeVerifier);\n options.clientKey && body.set(\"client_key\", options.clientKey);\n deviceId && body.set(\"device_id\", deviceId);\n body.set(\"redirect_uri\", options.redirectURI || redirectURI);\n body.set(\"client_id\", options.clientId);\n if (authentication === \"basic\") {\n const encodedCredentials = base64.encode(\n `${options.clientId}:${options.clientSecret}`\n );\n requestHeaders[\"authorization\"] = `Basic ${encodedCredentials}`;\n } else {\n body.set(\"client_secret\", options.clientSecret);\n }\n for (const [key, value] of Object.entries(additionalParams)) {\n if (!body.has(key)) body.append(key, value);\n }\n const { data, error } = await betterFetch(tokenEndpoint, {\n method: \"POST\",\n body,\n headers: requestHeaders\n });\n if (error) {\n throw error;\n }\n const tokens = getOAuth2Tokens(data);\n return tokens;\n}\nasync function validateToken(token, jwksEndpoint) {\n const { data, error } = await betterFetch(jwksEndpoint, {\n method: \"GET\",\n headers: {\n accept: \"application/json\",\n \"user-agent\": \"better-auth\"\n }\n });\n if (error) {\n throw error;\n }\n const keys = data[\"keys\"];\n const header = JSON.parse(atob(token.split(\".\")[0]));\n const key = keys.find((key2) => key2.kid === header.kid);\n if (!key) {\n throw new Error(\"Key not found\");\n }\n const verified = await jwtVerify(token, key);\n return verified;\n}\n\nasync function refreshAccessToken({\n refreshToken,\n options,\n tokenEndpoint,\n authentication,\n extraParams,\n grantType = \"refresh_token\"\n}) {\n const body = new URLSearchParams();\n const headers = {\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\"\n };\n body.set(\"grant_type\", grantType);\n body.set(\"refresh_token\", refreshToken);\n if (authentication === \"basic\") {\n headers[\"authorization\"] = base64.encode(\n `${options.clientId}:${options.clientSecret}`\n );\n } else {\n body.set(\"client_id\", options.clientId);\n body.set(\"client_secret\", options.clientSecret);\n }\n if (extraParams) {\n for (const [key, value] of Object.entries(extraParams)) {\n body.set(key, value);\n }\n }\n const { data, error } = await betterFetch(tokenEndpoint, {\n method: \"POST\",\n body,\n headers\n });\n if (error) {\n throw error;\n }\n const tokens = {\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n tokenType: data.token_type,\n scopes: data.scope?.split(\" \"),\n idToken: data.id_token\n };\n if (data.expires_in) {\n const now = /* @__PURE__ */ new Date();\n tokens.accessTokenExpiresAt = new Date(\n now.getTime() + data.expires_in * 1e3\n );\n }\n return tokens;\n}\n\nconst apple = (options) => {\n const tokenEndpoint = \"https://appleid.apple.com/auth/token\";\n return {\n id: \"apple\",\n name: \"Apple\",\n async createAuthorizationURL({ state, scopes, redirectURI }) {\n const _scope = options.disableDefaultScope ? [] : [\"email\", \"name\"];\n options.scope && _scope.push(...options.scope);\n scopes && _scope.push(...scopes);\n const url = await createAuthorizationURL({\n id: \"apple\",\n options,\n authorizationEndpoint: \"https://appleid.apple.com/auth/authorize\",\n scopes: _scope,\n state,\n redirectURI,\n responseMode: \"form_post\",\n responseType: \"code id_token\"\n });\n return url;\n },\n validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n codeVerifier,\n redirectURI,\n options,\n tokenEndpoint\n });\n },\n async verifyIdToken(token, nonce) {\n if (options.disableIdTokenSignIn) {\n return false;\n }\n if (options.verifyIdToken) {\n return options.verifyIdToken(token, nonce);\n }\n const decodedHeader = decodeProtectedHeader(token);\n const { kid, alg: jwtAlg } = decodedHeader;\n if (!kid || !jwtAlg) return false;\n const publicKey = await getApplePublicKey(kid);\n const { payload: jwtClaims } = await jwtVerify(token, publicKey, {\n algorithms: [jwtAlg],\n issuer: \"https://appleid.apple.com\",\n audience: options.appBundleIdentifier || options.clientId,\n maxTokenAge: \"1h\"\n });\n [\"email_verified\", \"is_private_email\"].forEach((field) => {\n if (jwtClaims[field] !== void 0) {\n jwtClaims[field] = Boolean(jwtClaims[field]);\n }\n });\n if (nonce && jwtClaims.nonce !== nonce) {\n return false;\n }\n return !!jwtClaims;\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://appleid.apple.com/auth/token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n if (!token.idToken) {\n return null;\n }\n const profile = decodeJwt(token.idToken);\n if (!profile) {\n return null;\n }\n const name = token.user ? `${token.user.name?.firstName} ${token.user.name?.lastName}` : profile.name || profile.email;\n const emailVerified = typeof profile.email_verified === \"boolean\" ? profile.email_verified : profile.email_verified === \"true\";\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.sub,\n name,\n emailVerified,\n email: profile.email,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\nconst getApplePublicKey = async (kid) => {\n const APPLE_BASE_URL = \"https://appleid.apple.com\";\n const JWKS_APPLE_URI = \"/auth/keys\";\n const { data } = await betterFetch(`${APPLE_BASE_URL}${JWKS_APPLE_URI}`);\n if (!data?.keys) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Keys not found\"\n });\n }\n const jwk = data.keys.find((key) => key.kid === kid);\n if (!jwk) {\n throw new Error(`JWK with kid ${kid} not found`);\n }\n return await importJWK(jwk, jwk.alg);\n};\n\nconst discord = (options) => {\n return {\n id: \"discord\",\n name: \"Discord\",\n createAuthorizationURL({ state, scopes, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"identify\", \"email\"];\n scopes && _scopes.push(...scopes);\n options.scope && _scopes.push(...options.scope);\n return new URL(\n `https://discord.com/api/oauth2/authorize?scope=${_scopes.join(\n \"+\"\n )}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(\n options.redirectURI || redirectURI\n )}&state=${state}&prompt=${options.prompt || \"none\"}`\n );\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n redirectURI,\n options,\n tokenEndpoint: \"https://discord.com/api/oauth2/token\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://discord.com/api/oauth2/token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://discord.com/api/users/@me\",\n {\n headers: {\n authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n if (profile.avatar === null) {\n const defaultAvatarNumber = profile.discriminator === \"0\" ? Number(BigInt(profile.id) >> BigInt(22)) % 6 : parseInt(profile.discriminator) % 5;\n profile.image_url = `https://cdn.discordapp.com/embed/avatars/${defaultAvatarNumber}.png`;\n } else {\n const format = profile.avatar.startsWith(\"a_\") ? \"gif\" : \"png\";\n profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.id,\n name: profile.global_name || profile.username || \"\",\n email: profile.email,\n emailVerified: profile.verified,\n image: profile.image_url,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst facebook = (options) => {\n return {\n id: \"facebook\",\n name: \"Facebook\",\n async createAuthorizationURL({ state, scopes, redirectURI, loginHint }) {\n const _scopes = options.disableDefaultScope ? [] : [\"email\", \"public_profile\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return await createAuthorizationURL({\n id: \"facebook\",\n options,\n authorizationEndpoint: \"https://www.facebook.com/v21.0/dialog/oauth\",\n scopes: _scopes,\n state,\n redirectURI,\n loginHint,\n additionalParams: options.configId ? {\n config_id: options.configId\n } : {}\n });\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n redirectURI,\n options,\n tokenEndpoint: \"https://graph.facebook.com/oauth/access_token\"\n });\n },\n async verifyIdToken(token, nonce) {\n if (options.disableIdTokenSignIn) {\n return false;\n }\n if (options.verifyIdToken) {\n return options.verifyIdToken(token, nonce);\n }\n if (token.split(\".\").length === 3) {\n try {\n const { payload: jwtClaims } = await jwtVerify(\n token,\n createRemoteJWKSet(\n // https://developers.facebook.com/docs/facebook-login/limited-login/token/#jwks\n new URL(\n \"https://limited.facebook.com/.well-known/oauth/openid/jwks/\"\n )\n ),\n {\n algorithms: [\"RS256\"],\n audience: options.clientId,\n issuer: \"https://www.facebook.com\"\n }\n );\n if (nonce && jwtClaims.nonce !== nonce) {\n return false;\n }\n return !!jwtClaims;\n } catch (error) {\n return false;\n }\n }\n return true;\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://graph.facebook.com/v18.0/oauth/access_token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n if (token.idToken && token.idToken.split(\".\").length === 3) {\n const profile2 = decodeJwt(token.idToken);\n const user = {\n id: profile2.sub,\n name: profile2.name,\n email: profile2.email,\n picture: {\n data: {\n url: profile2.picture,\n height: 100,\n width: 100,\n is_silhouette: false\n }\n }\n };\n const userMap2 = await options.mapProfileToUser?.({\n ...user,\n email_verified: true\n });\n return {\n user: {\n ...user,\n emailVerified: true,\n ...userMap2\n },\n data: profile2\n };\n }\n const fields = [\n \"id\",\n \"name\",\n \"email\",\n \"picture\",\n ...options?.fields || []\n ];\n const { data: profile, error } = await betterFetch(\n \"https://graph.facebook.com/me?fields=\" + fields.join(\",\"),\n {\n auth: {\n type: \"Bearer\",\n token: token.accessToken\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.id,\n name: profile.name,\n email: profile.email,\n image: profile.picture.data.url,\n emailVerified: profile.email_verified,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst github = (options) => {\n const tokenEndpoint = \"https://github.com/login/oauth/access_token\";\n return {\n id: \"github\",\n name: \"GitHub\",\n createAuthorizationURL({ state, scopes, loginHint, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"read:user\", \"user:email\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return createAuthorizationURL({\n id: \"github\",\n options,\n authorizationEndpoint: \"https://github.com/login/oauth/authorize\",\n scopes: _scopes,\n state,\n redirectURI,\n loginHint,\n prompt: options.prompt\n });\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n redirectURI,\n options,\n tokenEndpoint\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://github.com/login/oauth/access_token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://api.github.com/user\",\n {\n headers: {\n \"User-Agent\": \"better-auth\",\n authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n const { data: emails } = await betterFetch(\"https://api.github.com/user/emails\", {\n headers: {\n Authorization: `Bearer ${token.accessToken}`,\n \"User-Agent\": \"better-auth\"\n }\n });\n if (!profile.email && emails) {\n profile.email = (emails.find((e) => e.primary) ?? emails[0])?.email;\n }\n const emailVerified = emails?.find((e) => e.email === profile.email)?.verified ?? false;\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.id.toString(),\n name: profile.name || profile.login,\n email: profile.email,\n image: profile.avatar_url,\n emailVerified,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst google = (options) => {\n return {\n id: \"google\",\n name: \"Google\",\n async createAuthorizationURL({\n state,\n scopes,\n codeVerifier,\n redirectURI,\n loginHint,\n display\n }) {\n if (!options.clientId || !options.clientSecret) {\n logger.error(\n \"Client Id and Client Secret is required for Google. Make sure to provide them in the options.\"\n );\n throw new BetterAuthError(\"CLIENT_ID_AND_SECRET_REQUIRED\");\n }\n if (!codeVerifier) {\n throw new BetterAuthError(\"codeVerifier is required for Google\");\n }\n const _scopes = options.disableDefaultScope ? [] : [\"email\", \"profile\", \"openid\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n if (options.prompt === \"select_account+consent\")\n options.prompt = \"select_account consent\";\n const url = await createAuthorizationURL({\n id: \"google\",\n options,\n authorizationEndpoint: \"https://accounts.google.com/o/oauth2/auth\",\n scopes: _scopes,\n state,\n codeVerifier,\n redirectURI,\n prompt: options.prompt,\n accessType: options.accessType,\n display: display || options.display,\n loginHint,\n hd: options.hd,\n additionalParams: {\n include_granted_scopes: \"true\"\n }\n });\n return url;\n },\n validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n codeVerifier,\n redirectURI,\n options,\n tokenEndpoint: \"https://oauth2.googleapis.com/token\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://www.googleapis.com/oauth2/v4/token\"\n });\n },\n async verifyIdToken(token, nonce) {\n if (options.disableIdTokenSignIn) {\n return false;\n }\n if (options.verifyIdToken) {\n return options.verifyIdToken(token, nonce);\n }\n const googlePublicKeyUrl = `https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${token}`;\n const { data: tokenInfo } = await betterFetch(googlePublicKeyUrl);\n if (!tokenInfo) {\n return false;\n }\n const isValid = tokenInfo.aud === options.clientId && (tokenInfo.iss === \"https://accounts.google.com\" || tokenInfo.iss === \"accounts.google.com\");\n return isValid;\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n if (!token.idToken) {\n return null;\n }\n const user = decodeJwt(token.idToken);\n const userMap = await options.mapProfileToUser?.(user);\n return {\n user: {\n id: user.sub,\n name: user.name,\n email: user.email,\n image: user.picture,\n emailVerified: user.email_verified,\n ...userMap\n },\n data: user\n };\n },\n options\n };\n};\n\nconst kick = (options) => {\n return {\n id: \"kick\",\n name: \"Kick\",\n createAuthorizationURL({ state, scopes, redirectURI, codeVerifier }) {\n const _scopes = options.disableDefaultScope ? [] : [\"user:read\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return createAuthorizationURL({\n id: \"kick\",\n redirectURI,\n options,\n authorizationEndpoint: \"https://id.kick.com/oauth/authorize\",\n scopes: _scopes,\n codeVerifier,\n state\n });\n },\n async validateAuthorizationCode({ code, redirectURI, codeVerifier }) {\n return validateAuthorizationCode({\n code,\n redirectURI,\n options,\n tokenEndpoint: \"https://id.kick.com/oauth/token\",\n codeVerifier\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data, error } = await betterFetch(\"https://api.kick.com/public/v1/users\", {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${token.accessToken}`\n }\n });\n if (error) {\n return null;\n }\n const profile = data.data[0];\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.user_id,\n name: profile.name,\n email: profile.email,\n image: profile.profile_picture,\n emailVerified: true,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst huggingface = (options) => {\n return {\n id: \"huggingface\",\n name: \"Hugging Face\",\n createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"openid\", \"profile\", \"email\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return createAuthorizationURL({\n id: \"huggingface\",\n options,\n authorizationEndpoint: \"https://huggingface.co/oauth/authorize\",\n scopes: _scopes,\n state,\n codeVerifier,\n redirectURI\n });\n },\n validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n codeVerifier,\n redirectURI,\n options,\n tokenEndpoint: \"https://huggingface.co/oauth/token\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://huggingface.co/oauth/token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://huggingface.co/oauth/userinfo\",\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.sub,\n name: profile.name || profile.preferred_username,\n email: profile.email,\n image: profile.picture,\n emailVerified: profile.email_verified ?? false,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst microsoft = (options) => {\n const tenant = options.tenantId || \"common\";\n const authorizationEndpoint = `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/authorize`;\n const tokenEndpoint = `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`;\n return {\n id: \"microsoft\",\n name: \"Microsoft EntraID\",\n createAuthorizationURL(data) {\n const scopes = options.disableDefaultScope ? [] : [\"openid\", \"profile\", \"email\", \"User.Read\", \"offline_access\"];\n options.scope && scopes.push(...options.scope);\n data.scopes && scopes.push(...data.scopes);\n return createAuthorizationURL({\n id: \"microsoft\",\n options,\n authorizationEndpoint,\n state: data.state,\n codeVerifier: data.codeVerifier,\n scopes,\n redirectURI: data.redirectURI,\n prompt: options.prompt\n });\n },\n validateAuthorizationCode({ code, codeVerifier, redirectURI }) {\n return validateAuthorizationCode({\n code,\n codeVerifier,\n redirectURI,\n options,\n tokenEndpoint\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n if (!token.idToken) {\n return null;\n }\n const user = decodeJwt(token.idToken);\n const profilePhotoSize = options.profilePhotoSize || 48;\n await betterFetch(\n `https://graph.microsoft.com/v1.0/me/photos/${profilePhotoSize}x${profilePhotoSize}/$value`,\n {\n headers: {\n Authorization: `Bearer ${token.accessToken}`\n },\n async onResponse(context) {\n if (options.disableProfilePhoto || !context.response.ok) {\n return;\n }\n try {\n const response = context.response.clone();\n const pictureBuffer = await response.arrayBuffer();\n const pictureBase64 = base64.encode(pictureBuffer);\n user.picture = `data:image/jpeg;base64, ${pictureBase64}`;\n } catch (e) {\n logger.error(\n e && typeof e === \"object\" && \"name\" in e ? e.name : \"\",\n e\n );\n }\n }\n }\n );\n const userMap = await options.mapProfileToUser?.(user);\n return {\n user: {\n id: user.sub,\n name: user.name,\n email: user.email,\n image: user.picture,\n emailVerified: true,\n ...userMap\n },\n data: user\n };\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n const scopes = options.disableDefaultScope ? [] : [\"openid\", \"profile\", \"email\", \"User.Read\", \"offline_access\"];\n options.scope && scopes.push(...options.scope);\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientSecret: options.clientSecret\n },\n extraParams: {\n scope: scopes.join(\" \")\n // Include the scopes in request to microsoft\n },\n tokenEndpoint\n });\n },\n options\n };\n};\n\nconst slack = (options) => {\n return {\n id: \"slack\",\n name: \"Slack\",\n createAuthorizationURL({ state, scopes, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"openid\", \"profile\", \"email\"];\n scopes && _scopes.push(...scopes);\n options.scope && _scopes.push(...options.scope);\n const url = new URL(\"https://slack.com/openid/connect/authorize\");\n url.searchParams.set(\"scope\", _scopes.join(\" \"));\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", options.clientId);\n url.searchParams.set(\"redirect_uri\", options.redirectURI || redirectURI);\n url.searchParams.set(\"state\", state);\n return url;\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n redirectURI,\n options,\n tokenEndpoint: \"https://slack.com/api/openid.connect.token\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://slack.com/api/openid.connect.token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://slack.com/api/openid.connect.userInfo\",\n {\n headers: {\n authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile[\"https://slack.com/user_id\"],\n name: profile.name || \"\",\n email: profile.email,\n emailVerified: profile.email_verified,\n image: profile.picture || profile[\"https://slack.com/user_image_512\"],\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst notion = (options) => {\n const tokenEndpoint = \"https://api.notion.com/v1/oauth/token\";\n return {\n id: \"notion\",\n name: \"Notion\",\n createAuthorizationURL({ state, scopes, loginHint, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return createAuthorizationURL({\n id: \"notion\",\n options,\n authorizationEndpoint: \"https://api.notion.com/v1/oauth/authorize\",\n scopes: _scopes,\n state,\n redirectURI,\n loginHint,\n additionalParams: {\n owner: \"user\"\n }\n });\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n redirectURI,\n options,\n tokenEndpoint\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://api.notion.com/v1/users/me\",\n {\n headers: {\n Authorization: `Bearer ${token.accessToken}`,\n \"Notion-Version\": \"2022-06-28\"\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.id,\n name: profile.name || \"Notion User\",\n email: profile.person?.email || null,\n image: profile.avatar_url,\n emailVerified: !!profile.person?.email,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst spotify = (options) => {\n return {\n id: \"spotify\",\n name: \"Spotify\",\n createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"user-read-email\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return createAuthorizationURL({\n id: \"spotify\",\n options,\n authorizationEndpoint: \"https://accounts.spotify.com/authorize\",\n scopes: _scopes,\n state,\n codeVerifier,\n redirectURI\n });\n },\n validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n codeVerifier,\n redirectURI,\n options,\n tokenEndpoint: \"https://accounts.spotify.com/api/token\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://accounts.spotify.com/api/token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://api.spotify.com/v1/me\",\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.id,\n name: profile.display_name,\n email: profile.email,\n image: profile.images[0]?.url,\n emailVerified: false,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst twitch = (options) => {\n return {\n id: \"twitch\",\n name: \"Twitch\",\n createAuthorizationURL({ state, scopes, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"user:read:email\", \"openid\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return createAuthorizationURL({\n id: \"twitch\",\n redirectURI,\n options,\n authorizationEndpoint: \"https://id.twitch.tv/oauth2/authorize\",\n scopes: _scopes,\n state,\n claims: options.claims || [\n \"email\",\n \"email_verified\",\n \"preferred_username\",\n \"picture\"\n ]\n });\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n redirectURI,\n options,\n tokenEndpoint: \"https://id.twitch.tv/oauth2/token\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://id.twitch.tv/oauth2/token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const idToken = token.idToken;\n if (!idToken) {\n logger.error(\"No idToken found in token\");\n return null;\n }\n const profile = decodeJwt(idToken);\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.sub,\n name: profile.preferred_username,\n email: profile.email,\n image: profile.picture,\n emailVerified: profile.email_verified,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst twitter = (options) => {\n return {\n id: \"twitter\",\n name: \"Twitter\",\n createAuthorizationURL(data) {\n const _scopes = options.disableDefaultScope ? [] : [\"users.read\", \"tweet.read\", \"offline.access\", \"users.email\"];\n options.scope && _scopes.push(...options.scope);\n data.scopes && _scopes.push(...data.scopes);\n return createAuthorizationURL({\n id: \"twitter\",\n options,\n authorizationEndpoint: \"https://x.com/i/oauth2/authorize\",\n scopes: _scopes,\n state: data.state,\n codeVerifier: data.codeVerifier,\n redirectURI: data.redirectURI\n });\n },\n validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n codeVerifier,\n authentication: \"basic\",\n redirectURI,\n options,\n tokenEndpoint: \"https://api.x.com/2/oauth2/token\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://api.x.com/2/oauth2/token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error: profileError } = await betterFetch(\n \"https://api.x.com/2/users/me?user.fields=profile_image_url\",\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (profileError) {\n return null;\n }\n const { data: emailData, error: emailError } = await betterFetch(\"https://api.x.com/2/users/me?user.fields=confirmed_email\", {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${token.accessToken}`\n }\n });\n let emailVerified = false;\n if (!emailError && emailData?.data?.confirmed_email) {\n profile.data.email = emailData.data.confirmed_email;\n emailVerified = true;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.data.id,\n name: profile.data.name,\n email: profile.data.email || profile.data.username || null,\n image: profile.data.profile_image_url,\n emailVerified,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst dropbox = (options) => {\n const tokenEndpoint = \"https://api.dropboxapi.com/oauth2/token\";\n return {\n id: \"dropbox\",\n name: \"Dropbox\",\n createAuthorizationURL: async ({\n state,\n scopes,\n codeVerifier,\n redirectURI\n }) => {\n const _scopes = options.disableDefaultScope ? [] : [\"account_info.read\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n const additionalParams = {};\n if (options.accessType) {\n additionalParams.token_access_type = options.accessType;\n }\n return await createAuthorizationURL({\n id: \"dropbox\",\n options,\n authorizationEndpoint: \"https://www.dropbox.com/oauth2/authorize\",\n scopes: _scopes,\n state,\n redirectURI,\n codeVerifier,\n additionalParams\n });\n },\n validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {\n return await validateAuthorizationCode({\n code,\n codeVerifier,\n redirectURI,\n options,\n tokenEndpoint\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://api.dropbox.com/oauth2/token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://api.dropboxapi.com/2/users/get_current_account\",\n {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.account_id,\n name: profile.name?.display_name,\n email: profile.email,\n emailVerified: profile.email_verified || false,\n image: profile.profile_photo_url,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst linear = (options) => {\n const tokenEndpoint = \"https://api.linear.app/oauth/token\";\n return {\n id: \"linear\",\n name: \"Linear\",\n createAuthorizationURL({ state, scopes, loginHint, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"read\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return createAuthorizationURL({\n id: \"linear\",\n options,\n authorizationEndpoint: \"https://linear.app/oauth/authorize\",\n scopes: _scopes,\n state,\n redirectURI,\n loginHint\n });\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n redirectURI,\n options,\n tokenEndpoint\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://api.linear.app/graphql\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token.accessToken}`\n },\n body: JSON.stringify({\n query: `\n\t\t\t\t\t\t\tquery {\n\t\t\t\t\t\t\t\tviewer {\n\t\t\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\t\t\tname\n\t\t\t\t\t\t\t\t\temail\n\t\t\t\t\t\t\t\t\tavatarUrl\n\t\t\t\t\t\t\t\t\tactive\n\t\t\t\t\t\t\t\t\tcreatedAt\n\t\t\t\t\t\t\t\t\tupdatedAt\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t`\n })\n }\n );\n if (error || !profile?.data?.viewer) {\n return null;\n }\n const userData = profile.data.viewer;\n const userMap = await options.mapProfileToUser?.(userData);\n return {\n user: {\n id: profile.data.viewer.id,\n name: profile.data.viewer.name,\n email: profile.data.viewer.email,\n image: profile.data.viewer.avatarUrl,\n emailVerified: true,\n ...userMap\n },\n data: userData\n };\n },\n options\n };\n};\n\nconst linkedin = (options) => {\n const authorizationEndpoint = \"https://www.linkedin.com/oauth/v2/authorization\";\n const tokenEndpoint = \"https://www.linkedin.com/oauth/v2/accessToken\";\n return {\n id: \"linkedin\",\n name: \"Linkedin\",\n createAuthorizationURL: async ({\n state,\n scopes,\n redirectURI,\n loginHint\n }) => {\n const _scopes = options.disableDefaultScope ? [] : [\"profile\", \"email\", \"openid\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return await createAuthorizationURL({\n id: \"linkedin\",\n options,\n authorizationEndpoint,\n scopes: _scopes,\n state,\n loginHint,\n redirectURI\n });\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return await validateAuthorizationCode({\n code,\n redirectURI,\n options,\n tokenEndpoint\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://api.linkedin.com/v2/userinfo\",\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.sub,\n name: profile.name,\n email: profile.email,\n emailVerified: profile.email_verified || false,\n image: profile.picture,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst cleanDoubleSlashes = (input = \"\") => {\n return input.split(\"://\").map((str) => str.replace(/\\/{2,}/g, \"/\")).join(\"://\");\n};\nconst issuerToEndpoints = (issuer) => {\n let baseUrl = issuer || \"https://gitlab.com\";\n return {\n authorizationEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/authorize`),\n tokenEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/token`),\n userinfoEndpoint: cleanDoubleSlashes(`${baseUrl}/api/v4/user`)\n };\n};\nconst gitlab = (options) => {\n const { authorizationEndpoint, tokenEndpoint, userinfoEndpoint } = issuerToEndpoints(options.issuer);\n const issuerId = \"gitlab\";\n const issuerName = \"Gitlab\";\n return {\n id: issuerId,\n name: issuerName,\n createAuthorizationURL: async ({\n state,\n scopes,\n codeVerifier,\n loginHint,\n redirectURI\n }) => {\n const _scopes = options.disableDefaultScope ? [] : [\"read_user\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return await createAuthorizationURL({\n id: issuerId,\n options,\n authorizationEndpoint,\n scopes: _scopes,\n state,\n redirectURI,\n codeVerifier,\n loginHint\n });\n },\n validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => {\n return validateAuthorizationCode({\n code,\n redirectURI,\n options,\n codeVerifier,\n tokenEndpoint\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://gitlab.com/oauth/token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n userinfoEndpoint,\n { headers: { authorization: `Bearer ${token.accessToken}` } }\n );\n if (error || profile.state !== \"active\" || profile.locked) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.id.toString(),\n name: profile.name ?? profile.username,\n email: profile.email,\n image: profile.avatar_url,\n emailVerified: true,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst tiktok = (options) => {\n return {\n id: \"tiktok\",\n name: \"TikTok\",\n createAuthorizationURL({ state, scopes, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"user.info.profile\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return new URL(\n `https://www.tiktok.com/v2/auth/authorize?scope=${_scopes.join(\n \",\"\n )}&response_type=code&client_key=${options.clientKey}&client_secret=${options.clientSecret}&redirect_uri=${encodeURIComponent(\n options.redirectURI || redirectURI\n )}&state=${state}`\n );\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n redirectURI: options.redirectURI || redirectURI,\n options,\n tokenEndpoint: \"https://open.tiktokapis.com/v2/oauth/token/\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://open.tiktokapis.com/v2/oauth/token/\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const fields = [\n \"open_id\",\n \"avatar_large_url\",\n \"display_name\",\n \"username\"\n ];\n const { data: profile, error } = await betterFetch(\n `https://open.tiktokapis.com/v2/user/info/?fields=${fields.join(\",\")}`,\n {\n headers: {\n authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n return {\n user: {\n email: profile.data.user.email || profile.data.user.username,\n id: profile.data.user.open_id,\n name: profile.data.user.display_name || profile.data.user.username,\n image: profile.data.user.avatar_large_url,\n /** @note Tiktok does not provide emailVerified or even email*/\n emailVerified: profile.data.user.email ? true : false\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst reddit = (options) => {\n return {\n id: \"reddit\",\n name: \"Reddit\",\n createAuthorizationURL({ state, scopes, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"identity\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return createAuthorizationURL({\n id: \"reddit\",\n options,\n authorizationEndpoint: \"https://www.reddit.com/api/v1/authorize\",\n scopes: _scopes,\n state,\n redirectURI,\n duration: options.duration\n });\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code,\n redirect_uri: options.redirectURI || redirectURI\n });\n const headers = {\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"text/plain\",\n \"user-agent\": \"better-auth\",\n Authorization: `Basic ${base64.encode(\n `${options.clientId}:${options.clientSecret}`\n )}`\n };\n const { data, error } = await betterFetch(\n \"https://www.reddit.com/api/v1/access_token\",\n {\n method: \"POST\",\n headers,\n body: body.toString()\n }\n );\n if (error) {\n throw error;\n }\n return getOAuth2Tokens(data);\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://www.reddit.com/api/v1/access_token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://oauth.reddit.com/api/v1/me\",\n {\n headers: {\n Authorization: `Bearer ${token.accessToken}`,\n \"User-Agent\": \"better-auth\"\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.id,\n name: profile.name,\n email: profile.oauth_client_id,\n emailVerified: profile.has_verified_email,\n image: profile.icon_img?.split(\"?\")[0],\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst roblox = (options) => {\n return {\n id: \"roblox\",\n name: \"Roblox\",\n createAuthorizationURL({ state, scopes, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"openid\", \"profile\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n return new URL(\n `https://apis.roblox.com/oauth/v1/authorize?scope=${_scopes.join(\n \"+\"\n )}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(\n options.redirectURI || redirectURI\n )}&state=${state}&prompt=${options.prompt || \"select_account+consent\"}`\n );\n },\n validateAuthorizationCode: async ({ code, redirectURI }) => {\n return validateAuthorizationCode({\n code,\n redirectURI: options.redirectURI || redirectURI,\n options,\n tokenEndpoint: \"https://apis.roblox.com/oauth/v1/token\",\n authentication: \"post\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://apis.roblox.com/oauth/v1/token\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://apis.roblox.com/oauth/v1/userinfo\",\n {\n headers: {\n authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.sub,\n name: profile.nickname || profile.preferred_username || \"\",\n image: profile.picture,\n email: profile.preferred_username || null,\n // Roblox does not provide email\n emailVerified: true,\n ...userMap\n },\n data: {\n ...profile\n }\n };\n },\n options\n };\n};\n\nvar LANG = /* @__PURE__ */ ((LANG2) => {\n LANG2[LANG2[\"RUS\"] = 0] = \"RUS\";\n LANG2[LANG2[\"UKR\"] = 1] = \"UKR\";\n LANG2[LANG2[\"ENG\"] = 3] = \"ENG\";\n LANG2[LANG2[\"SPA\"] = 4] = \"SPA\";\n LANG2[LANG2[\"GERMAN\"] = 6] = \"GERMAN\";\n LANG2[LANG2[\"POL\"] = 15] = \"POL\";\n LANG2[LANG2[\"FRA\"] = 16] = \"FRA\";\n LANG2[LANG2[\"TURKEY\"] = 82] = \"TURKEY\";\n return LANG2;\n})(LANG || {});\nconst vk = (options) => {\n return {\n id: \"vk\",\n name: \"VK\",\n async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) {\n const _scopes = options.disableDefaultScope ? [] : [\"email\", \"phone\"];\n options.scope && _scopes.push(...options.scope);\n scopes && _scopes.push(...scopes);\n const authorizationEndpoint = \"https://id.vk.com/authorize\";\n return createAuthorizationURL({\n id: \"vk\",\n options,\n authorizationEndpoint,\n scopes: _scopes,\n state,\n redirectURI,\n codeVerifier\n });\n },\n validateAuthorizationCode: async ({\n code,\n codeVerifier,\n redirectURI,\n deviceId\n }) => {\n return validateAuthorizationCode({\n code,\n codeVerifier,\n redirectURI: options.redirectURI || redirectURI,\n options,\n deviceId,\n tokenEndpoint: \"https://id.vk.com/oauth2/auth\"\n });\n },\n refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: options.clientId,\n clientKey: options.clientKey,\n clientSecret: options.clientSecret\n },\n tokenEndpoint: \"https://id.vk.com/oauth2/auth\"\n });\n },\n async getUserInfo(data) {\n if (options.getUserInfo) {\n return options.getUserInfo(data);\n }\n if (!data.accessToken) {\n return null;\n }\n const formBody = new URLSearchParams({\n access_token: data.accessToken,\n client_id: options.clientId\n }).toString();\n const { data: profile, error } = await betterFetch(\n \"https://id.vk.com/oauth2/user_info\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n },\n body: formBody\n }\n );\n if (error) {\n return null;\n }\n if (!profile.user.email) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.user.user_id,\n first_name: profile.user.first_name,\n last_name: profile.user.last_name,\n email: profile.user.email,\n image: profile.user.avatar,\n /** @note VK does not provide emailVerified*/\n emailVerified: !!profile.user.email,\n birthday: profile.user.birthday,\n sex: profile.user.sex,\n ...userMap\n },\n data: profile\n };\n },\n options\n };\n};\n\nconst zoom = (userOptions) => {\n const options = {\n pkce: true,\n ...userOptions\n };\n return {\n id: \"zoom\",\n name: \"Zoom\",\n createAuthorizationURL: async ({ state, redirectURI, codeVerifier }) => {\n const params = new URLSearchParams({\n response_type: \"code\",\n redirect_uri: options.redirectURI ? options.redirectURI : redirectURI,\n client_id: options.clientId,\n state\n });\n if (options.pkce) {\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n params.set(\"code_challenge_method\", \"S256\");\n params.set(\"code_challenge\", codeChallenge);\n }\n const url = new URL(\"https://zoom.us/oauth/authorize\");\n url.search = params.toString();\n return url;\n },\n validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => {\n return validateAuthorizationCode({\n code,\n redirectURI: options.redirectURI || redirectURI,\n codeVerifier,\n options,\n tokenEndpoint: \"https://zoom.us/oauth/token\",\n authentication: \"post\"\n });\n },\n async getUserInfo(token) {\n if (options.getUserInfo) {\n return options.getUserInfo(token);\n }\n const { data: profile, error } = await betterFetch(\n \"https://api.zoom.us/v2/users/me\",\n {\n headers: {\n authorization: `Bearer ${token.accessToken}`\n }\n }\n );\n if (error) {\n return null;\n }\n const userMap = await options.mapProfileToUser?.(profile);\n return {\n user: {\n id: profile.id,\n name: profile.display_name,\n image: profile.pic_url,\n email: profile.email,\n emailVerified: Boolean(profile.verified),\n ...userMap\n },\n data: {\n ...profile\n }\n };\n }\n };\n};\n\nconst socialProviders = {\n apple,\n discord,\n facebook,\n github,\n microsoft,\n google,\n huggingface,\n slack,\n spotify,\n twitch,\n twitter,\n dropbox,\n kick,\n linear,\n linkedin,\n gitlab,\n tiktok,\n reddit,\n roblox,\n vk,\n zoom,\n notion\n};\nconst socialProviderList = Object.keys(socialProviders);\nconst SocialProviderListEnum = z.enum(socialProviderList).or(z.string());\n\nconst signInSocial = createAuthEndpoint(\n \"/sign-in/social\",\n {\n method: \"POST\",\n body: z.object({\n /**\n * Callback URL to redirect to after the user\n * has signed in.\n */\n callbackURL: z.string().meta({\n description: \"Callback URL to redirect to after the user has signed in\"\n }).optional(),\n /**\n * callback url to redirect if the user is newly registered.\n *\n * useful if you have different routes for existing users and new users\n */\n newUserCallbackURL: z.string().optional(),\n /**\n * Callback url to redirect to if an error happens\n *\n * If it's initiated from the client sdk this defaults to\n * the current url.\n */\n errorCallbackURL: z.string().meta({\n description: \"Callback URL to redirect to if an error happens\"\n }).optional(),\n /**\n * OAuth2 provider to use`\n */\n provider: SocialProviderListEnum,\n /**\n * Disable automatic redirection to the provider\n *\n * This is useful if you want to handle the redirection\n * yourself like in a popup or a different tab.\n */\n disableRedirect: z.boolean().meta({\n description: \"Disable automatic redirection to the provider. Useful for handling the redirection yourself\"\n }).optional(),\n /**\n * ID token from the provider\n *\n * This is used to sign in the user\n * if the user is already signed in with the\n * provider in the frontend.\n *\n * Only applicable if the provider supports\n * it. Currently only `apple` and `google` is\n * supported out of the box.\n */\n idToken: z.optional(\n z.object({\n /**\n * ID token from the provider\n */\n token: z.string().meta({\n description: \"ID token from the provider\"\n }),\n /**\n * The nonce used to generate the token\n */\n nonce: z.string().meta({\n description: \"Nonce used to generate the token\"\n }).optional(),\n /**\n * Access token from the provider\n */\n accessToken: z.string().meta({\n description: \"Access token from the provider\"\n }).optional(),\n /**\n * Refresh token from the provider\n */\n refreshToken: z.string().meta({\n description: \"Refresh token from the provider\"\n }).optional(),\n /**\n * Expiry date of the token\n */\n expiresAt: z.number().meta({\n description: \"Expiry date of the token\"\n }).optional()\n })\n ),\n scopes: z.array(z.string()).meta({\n description: \"Array of scopes to request from the provider. This will override the default scopes passed.\"\n }).optional(),\n /**\n * Explicitly request sign-up\n *\n * Should be used to allow sign up when\n * disableImplicitSignUp for this provider is\n * true\n */\n requestSignUp: z.boolean().meta({\n description: \"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider\"\n }).optional(),\n /**\n * The login hint to use for the authorization code request\n */\n loginHint: z.string().meta({\n description: \"The login hint to use for the authorization code request\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Sign in with a social provider\",\n operationId: \"socialSignIn\",\n responses: {\n \"200\": {\n description: \"Success - Returns either session details or redirect URL\",\n content: {\n \"application/json\": {\n schema: {\n // todo: we need support for multiple schema\n type: \"object\",\n description: \"Session response when idToken is provided\",\n properties: {\n redirect: {\n type: \"boolean\",\n enum: [false]\n },\n token: {\n type: \"string\",\n description: \"Session token\",\n url: {\n type: \"null\",\n nullable: true\n },\n user: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n email: { type: \"string\" },\n name: {\n type: \"string\",\n nullable: true\n },\n image: {\n type: \"string\",\n nullable: true\n },\n emailVerified: {\n type: \"boolean\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\"\n }\n },\n required: [\n \"id\",\n \"email\",\n \"emailVerified\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n }\n },\n required: [\"redirect\", \"token\", \"user\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (c) => {\n const provider = c.context.socialProviders.find(\n (p) => p.id === c.body.provider\n );\n if (!provider) {\n c.context.logger.error(\n \"Provider not found. Make sure to add the provider in your auth config\",\n {\n provider: c.body.provider\n }\n );\n throw new APIError(\"NOT_FOUND\", {\n message: BASE_ERROR_CODES.PROVIDER_NOT_FOUND\n });\n }\n if (c.body.idToken) {\n if (!provider.verifyIdToken) {\n c.context.logger.error(\n \"Provider does not support id token verification\",\n {\n provider: c.body.provider\n }\n );\n throw new APIError(\"NOT_FOUND\", {\n message: BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED\n });\n }\n const { token, nonce } = c.body.idToken;\n const valid = await provider.verifyIdToken(token, nonce);\n if (!valid) {\n c.context.logger.error(\"Invalid id token\", {\n provider: c.body.provider\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.INVALID_TOKEN\n });\n }\n const userInfo = await provider.getUserInfo({\n idToken: token,\n accessToken: c.body.idToken.accessToken,\n refreshToken: c.body.idToken.refreshToken\n });\n if (!userInfo || !userInfo?.user) {\n c.context.logger.error(\"Failed to get user info\", {\n provider: c.body.provider\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO\n });\n }\n if (!userInfo.user.email) {\n c.context.logger.error(\"User email not found\", {\n provider: c.body.provider\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND\n });\n }\n const data = await handleOAuthUserInfo(c, {\n userInfo: {\n ...userInfo.user,\n email: userInfo.user.email,\n id: userInfo.user.id,\n name: userInfo.user.name || \"\",\n image: userInfo.user.image,\n emailVerified: userInfo.user.emailVerified || false\n },\n account: {\n providerId: provider.id,\n accountId: userInfo.user.id,\n accessToken: c.body.idToken.accessToken\n },\n callbackURL: c.body.callbackURL,\n disableSignUp: provider.disableImplicitSignUp && !c.body.requestSignUp || provider.disableSignUp\n });\n if (data.error) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: data.error\n });\n }\n await setSessionCookie(c, data.data);\n return c.json({\n redirect: false,\n token: data.data.session.token,\n url: void 0,\n user: {\n id: data.data.user.id,\n email: data.data.user.email,\n name: data.data.user.name,\n image: data.data.user.image,\n emailVerified: data.data.user.emailVerified,\n createdAt: data.data.user.createdAt,\n updatedAt: data.data.user.updatedAt\n }\n });\n }\n const { codeVerifier, state } = await generateState(c);\n const url = await provider.createAuthorizationURL({\n state,\n codeVerifier,\n redirectURI: `${c.context.baseURL}/callback/${provider.id}`,\n scopes: c.body.scopes,\n loginHint: c.body.loginHint\n });\n return c.json({\n url: url.toString(),\n redirect: !c.body.disableRedirect\n });\n }\n);\nconst signInEmail = createAuthEndpoint(\n \"/sign-in/email\",\n {\n method: \"POST\",\n body: z.object({\n /**\n * Email of the user\n */\n email: z.string().meta({\n description: \"Email of the user\"\n }),\n /**\n * Password of the user\n */\n password: z.string().meta({\n description: \"Password of the user\"\n }),\n /**\n * Callback URL to use as a redirect for email\n * verification and for possible redirects\n */\n callbackURL: z.string().meta({\n description: \"Callback URL to use as a redirect for email verification\"\n }).optional(),\n /**\n * If this is false, the session will not be remembered\n * @default true\n */\n rememberMe: z.boolean().meta({\n description: \"If this is false, the session will not be remembered. Default is `true`.\"\n }).default(true).optional()\n }),\n metadata: {\n openapi: {\n description: \"Sign in with email and password\",\n responses: {\n \"200\": {\n description: \"Success - Returns either session details or redirect URL\",\n content: {\n \"application/json\": {\n schema: {\n // todo: we need support for multiple schema\n type: \"object\",\n description: \"Session response when idToken is provided\",\n properties: {\n redirect: {\n type: \"boolean\",\n enum: [false]\n },\n token: {\n type: \"string\",\n description: \"Session token\"\n },\n url: {\n type: \"null\",\n nullable: true\n },\n user: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n email: { type: \"string\" },\n name: {\n type: \"string\",\n nullable: true\n },\n image: {\n type: \"string\",\n nullable: true\n },\n emailVerified: {\n type: \"boolean\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\"\n }\n },\n required: [\n \"id\",\n \"email\",\n \"emailVerified\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n },\n required: [\"redirect\", \"token\", \"user\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.context.options?.emailAndPassword?.enabled) {\n ctx.context.logger.error(\n \"Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!\"\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Email and password is not enabled\"\n });\n }\n const { email, password } = ctx.body;\n const isValidEmail = z.string().email().safeParse(email);\n if (!isValidEmail.success) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.INVALID_EMAIL\n });\n }\n const user = await ctx.context.internalAdapter.findUserByEmail(email, {\n includeAccounts: true\n });\n if (!user) {\n await ctx.context.password.hash(password);\n ctx.context.logger.error(\"User not found\", { email });\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD\n });\n }\n const credentialAccount = user.accounts.find(\n (a) => a.providerId === \"credential\"\n );\n if (!credentialAccount) {\n ctx.context.logger.error(\"Credential account not found\", { email });\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD\n });\n }\n const currentPassword = credentialAccount?.password;\n if (!currentPassword) {\n ctx.context.logger.error(\"Password not found\", { email });\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD\n });\n }\n const validPassword = await ctx.context.password.verify({\n hash: currentPassword,\n password\n });\n if (!validPassword) {\n ctx.context.logger.error(\"Invalid password\");\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD\n });\n }\n if (ctx.context.options?.emailAndPassword?.requireEmailVerification && !user.user.emailVerified) {\n if (!ctx.context.options?.emailVerification?.sendVerificationEmail) {\n throw new APIError(\"FORBIDDEN\", {\n message: BASE_ERROR_CODES.EMAIL_NOT_VERIFIED\n });\n }\n if (ctx.context.options?.emailVerification?.sendOnSignIn) {\n const token = await createEmailVerificationToken(\n ctx.context.secret,\n user.user.email,\n void 0,\n ctx.context.options.emailVerification?.expiresIn\n );\n const url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n await ctx.context.options.emailVerification.sendVerificationEmail(\n {\n user: user.user,\n url,\n token\n },\n ctx.request\n );\n }\n throw new APIError(\"FORBIDDEN\", {\n message: BASE_ERROR_CODES.EMAIL_NOT_VERIFIED\n });\n }\n const session = await ctx.context.internalAdapter.createSession(\n user.user.id,\n ctx,\n ctx.body.rememberMe === false\n );\n if (!session) {\n ctx.context.logger.error(\"Failed to create session\");\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION\n });\n }\n await setSessionCookie(\n ctx,\n {\n session,\n user: user.user\n },\n ctx.body.rememberMe === false\n );\n return ctx.json({\n redirect: !!ctx.body.callbackURL,\n token: session.token,\n url: ctx.body.callbackURL,\n user: {\n id: user.user.id,\n email: user.user.email,\n name: user.user.name,\n image: user.user.image,\n emailVerified: user.user.emailVerified,\n createdAt: user.user.createdAt,\n updatedAt: user.user.updatedAt\n }\n });\n }\n);\n\nconst schema = z.object({\n code: z.string().optional(),\n error: z.string().optional(),\n device_id: z.string().optional(),\n error_description: z.string().optional(),\n state: z.string().optional(),\n user: z.string().optional()\n});\nconst callbackOAuth = createAuthEndpoint(\n \"/callback/:id\",\n {\n method: [\"GET\", \"POST\"],\n body: schema.optional(),\n query: schema.optional(),\n metadata: HIDE_METADATA\n },\n async (c) => {\n let queryOrBody;\n const defaultErrorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;\n try {\n if (c.method === \"GET\") {\n queryOrBody = schema.parse(c.query);\n } else if (c.method === \"POST\") {\n queryOrBody = schema.parse(c.body);\n } else {\n throw new Error(\"Unsupported method\");\n }\n } catch (e) {\n c.context.logger.error(\"INVALID_CALLBACK_REQUEST\", e);\n throw c.redirect(`${defaultErrorURL}?error=invalid_callback_request`);\n }\n const { code, error, state, error_description, device_id } = queryOrBody;\n if (error) {\n throw c.redirect(\n `${defaultErrorURL}?error=${error}&error_description=${error_description}`\n );\n }\n if (!state) {\n c.context.logger.error(\"State not found\", error);\n throw c.redirect(`${defaultErrorURL}?error=state_not_found`);\n }\n const {\n codeVerifier,\n callbackURL,\n link,\n errorURL,\n newUserURL,\n requestSignUp\n } = await parseState(c);\n function redirectOnError(error2) {\n let url = errorURL || defaultErrorURL;\n if (url.includes(\"?\")) {\n url = `${url}&error=${error2}`;\n } else {\n url = `${url}?error=${error2}`;\n }\n throw c.redirect(url);\n }\n if (!code) {\n c.context.logger.error(\"Code not found\");\n throw redirectOnError(\"no_code\");\n }\n const provider = c.context.socialProviders.find(\n (p) => p.id === c.params.id\n );\n if (!provider) {\n c.context.logger.error(\n \"Oauth provider with id\",\n c.params.id,\n \"not found\"\n );\n throw redirectOnError(\"oauth_provider_not_found\");\n }\n let tokens;\n try {\n tokens = await provider.validateAuthorizationCode({\n code,\n codeVerifier,\n deviceId: device_id,\n redirectURI: `${c.context.baseURL}/callback/${provider.id}`\n });\n } catch (e) {\n c.context.logger.error(\"\", e);\n throw redirectOnError(\"invalid_code\");\n }\n const userInfo = await provider.getUserInfo({\n ...tokens,\n user: c.body?.user ? safeJSONParse(c.body.user) : void 0\n }).then((res) => res?.user);\n if (!userInfo) {\n c.context.logger.error(\"Unable to get user info\");\n return redirectOnError(\"unable_to_get_user_info\");\n }\n if (!callbackURL) {\n c.context.logger.error(\"No callback URL found\");\n throw redirectOnError(\"no_callback_url\");\n }\n if (link) {\n const trustedProviders = c.context.options.account?.accountLinking?.trustedProviders;\n const isTrustedProvider = trustedProviders?.includes(\n provider.id\n );\n if (!isTrustedProvider && !userInfo.emailVerified || c.context.options.account?.accountLinking?.enabled === false) {\n c.context.logger.error(\"Unable to link account - untrusted provider\");\n return redirectOnError(\"unable_to_link_account\");\n }\n const existingAccount = await c.context.internalAdapter.findAccount(\n userInfo.id\n );\n if (existingAccount) {\n if (existingAccount.userId.toString() !== link.userId.toString()) {\n return redirectOnError(\"account_already_linked_to_different_user\");\n }\n const updateData = Object.fromEntries(\n Object.entries({\n accessToken: await setTokenUtil(tokens.accessToken, c.context),\n refreshToken: await setTokenUtil(tokens.refreshToken, c.context),\n idToken: tokens.idToken,\n accessTokenExpiresAt: tokens.accessTokenExpiresAt,\n refreshTokenExpiresAt: tokens.refreshTokenExpiresAt,\n scope: tokens.scopes?.join(\",\")\n }).filter(([_, value]) => value !== void 0)\n );\n await c.context.internalAdapter.updateAccount(\n existingAccount.id,\n updateData\n );\n } else {\n const newAccount = await c.context.internalAdapter.createAccount(\n {\n userId: link.userId,\n providerId: provider.id,\n accountId: userInfo.id,\n ...tokens,\n accessToken: await setTokenUtil(tokens.accessToken, c.context),\n refreshToken: await setTokenUtil(tokens.refreshToken, c.context),\n scope: tokens.scopes?.join(\",\")\n },\n c\n );\n if (!newAccount) {\n return redirectOnError(\"unable_to_link_account\");\n }\n }\n let toRedirectTo2;\n try {\n const url = callbackURL;\n toRedirectTo2 = url.toString();\n } catch {\n toRedirectTo2 = callbackURL;\n }\n throw c.redirect(toRedirectTo2);\n }\n if (!userInfo.email) {\n c.context.logger.error(\n \"Provider did not return email. This could be due to misconfiguration in the provider settings.\"\n );\n return redirectOnError(\"email_not_found\");\n }\n const result = await handleOAuthUserInfo(c, {\n userInfo: {\n ...userInfo,\n email: userInfo.email,\n name: userInfo.name || userInfo.email\n },\n account: {\n providerId: provider.id,\n accountId: userInfo.id,\n ...tokens,\n scope: tokens.scopes?.join(\",\")\n },\n callbackURL,\n disableSignUp: provider.disableImplicitSignUp && !requestSignUp || provider.options?.disableSignUp,\n overrideUserInfo: provider.options?.overrideUserInfoOnSignIn\n });\n if (result.error) {\n c.context.logger.error(result.error.split(\" \").join(\"_\"));\n return redirectOnError(result.error.split(\" \").join(\"_\"));\n }\n const { session, user } = result.data;\n await setSessionCookie(c, {\n session,\n user\n });\n let toRedirectTo;\n try {\n const url = result.isRegister ? newUserURL || callbackURL : callbackURL;\n toRedirectTo = url.toString();\n } catch {\n toRedirectTo = result.isRegister ? newUserURL || callbackURL : callbackURL;\n }\n throw c.redirect(toRedirectTo);\n }\n);\n\nconst signOut = createAuthEndpoint(\n \"/sign-out\",\n {\n method: \"POST\",\n requireHeaders: true,\n metadata: {\n openapi: {\n description: \"Sign out the current user\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const sessionCookieToken = await ctx.getSignedCookie(\n ctx.context.authCookies.sessionToken.name,\n ctx.context.secret\n );\n if (!sessionCookieToken) {\n deleteSessionCookie(ctx);\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION\n });\n }\n await ctx.context.internalAdapter.deleteSession(sessionCookieToken);\n deleteSessionCookie(ctx);\n return ctx.json({\n success: true\n });\n }\n);\n\nfunction redirectError(ctx, callbackURL, query) {\n const url = callbackURL ? new URL(callbackURL, ctx.baseURL) : new URL(`${ctx.baseURL}/error`);\n if (query)\n Object.entries(query).forEach(([k, v]) => url.searchParams.set(k, v));\n return url.href;\n}\nfunction redirectCallback(ctx, callbackURL, query) {\n const url = new URL(callbackURL, ctx.baseURL);\n if (query)\n Object.entries(query).forEach(([k, v]) => url.searchParams.set(k, v));\n return url.href;\n}\nconst requestPasswordReset = createAuthEndpoint(\n \"/request-password-reset\",\n {\n method: \"POST\",\n body: z.object({\n /**\n * The email address of the user to send a password reset email to.\n */\n email: z.email().meta({\n description: \"The email address of the user to send a password reset email to\"\n }),\n /**\n * The URL to redirect the user to reset their password.\n * If the token isn't valid or expired, it'll be redirected with a query parameter `?\n * error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?\n * token=VALID_TOKEN\n */\n redirectTo: z.string().meta({\n description: \"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Send a password reset email to the user\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n },\n message: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.context.options.emailAndPassword?.sendResetPassword) {\n ctx.context.logger.error(\n \"Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!\"\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Reset password isn't enabled\"\n });\n }\n const { email, redirectTo } = ctx.body;\n const user = await ctx.context.internalAdapter.findUserByEmail(email, {\n includeAccounts: true\n });\n if (!user) {\n ctx.context.logger.error(\"Reset Password: User not found\", { email });\n return ctx.json({\n status: true,\n message: \"If this email exists in our system, check your email for the reset link\"\n });\n }\n const defaultExpiresIn = 60 * 60 * 1;\n const expiresAt = getDate(\n ctx.context.options.emailAndPassword.resetPasswordTokenExpiresIn || defaultExpiresIn,\n \"sec\"\n );\n const verificationToken = generateId(24);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: user.user.id,\n identifier: `reset-password:${verificationToken}`,\n expiresAt\n },\n ctx\n );\n const callbackURL = redirectTo ? encodeURIComponent(redirectTo) : \"\";\n const url = `${ctx.context.baseURL}/reset-password/${verificationToken}?callbackURL=${callbackURL}`;\n await ctx.context.options.emailAndPassword.sendResetPassword(\n {\n user: user.user,\n url,\n token: verificationToken\n },\n ctx.request\n );\n return ctx.json({\n status: true\n });\n }\n);\nconst forgetPassword = createAuthEndpoint(\n \"/forget-password\",\n {\n method: \"POST\",\n body: z.object({\n /**\n * The email address of the user to send a password reset email to.\n */\n email: z.string().email().meta({\n description: \"The email address of the user to send a password reset email to\"\n }),\n /**\n * The URL to redirect the user to reset their password.\n * If the token isn't valid or expired, it'll be redirected with a query parameter `?\n * error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?\n * token=VALID_TOKEN\n */\n redirectTo: z.string().meta({\n description: \"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Send a password reset email to the user\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n },\n message: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.context.options.emailAndPassword?.sendResetPassword) {\n ctx.context.logger.error(\n \"Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!\"\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Reset password isn't enabled\"\n });\n }\n const { email, redirectTo } = ctx.body;\n const user = await ctx.context.internalAdapter.findUserByEmail(email, {\n includeAccounts: true\n });\n if (!user) {\n ctx.context.logger.error(\"Reset Password: User not found\", { email });\n return ctx.json({\n status: true,\n message: \"If this email exists in our system, check your email for the reset link\"\n });\n }\n const defaultExpiresIn = 60 * 60 * 1;\n const expiresAt = getDate(\n ctx.context.options.emailAndPassword.resetPasswordTokenExpiresIn || defaultExpiresIn,\n \"sec\"\n );\n const verificationToken = generateId(24);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: user.user.id,\n identifier: `reset-password:${verificationToken}`,\n expiresAt\n },\n ctx\n );\n const callbackURL = redirectTo ? encodeURIComponent(redirectTo) : \"\";\n const url = `${ctx.context.baseURL}/reset-password/${verificationToken}?callbackURL=${callbackURL}`;\n await ctx.context.options.emailAndPassword.sendResetPassword(\n {\n user: user.user,\n url,\n token: verificationToken\n },\n ctx.request\n );\n return ctx.json({\n status: true\n });\n }\n);\nconst requestPasswordResetCallback = createAuthEndpoint(\n \"/reset-password/:token\",\n {\n method: \"GET\",\n query: z.object({\n callbackURL: z.string().meta({\n description: \"The URL to redirect the user to reset their password\"\n })\n }),\n use: [originCheck((ctx) => ctx.query.callbackURL)],\n metadata: {\n openapi: {\n description: \"Redirects the user to the callback URL with the token\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n token: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { token } = ctx.params;\n const { callbackURL } = ctx.query;\n if (!token || !callbackURL) {\n throw ctx.redirect(\n redirectError(ctx.context, callbackURL, { error: \"INVALID_TOKEN\" })\n );\n }\n const verification = await ctx.context.internalAdapter.findVerificationValue(\n `reset-password:${token}`\n );\n if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) {\n throw ctx.redirect(\n redirectError(ctx.context, callbackURL, { error: \"INVALID_TOKEN\" })\n );\n }\n throw ctx.redirect(redirectCallback(ctx.context, callbackURL, { token }));\n }\n);\nconst forgetPasswordCallback = requestPasswordResetCallback;\nconst resetPassword = createAuthEndpoint(\n \"/reset-password\",\n {\n method: \"POST\",\n query: z.object({\n token: z.string().optional()\n }).optional(),\n body: z.object({\n newPassword: z.string().meta({\n description: \"The new password to set\"\n }),\n token: z.string().meta({\n description: \"The token to reset the password\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Reset the password for a user\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const token = ctx.body.token || ctx.query?.token;\n if (!token) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.INVALID_TOKEN\n });\n }\n const { newPassword } = ctx.body;\n const minLength = ctx.context.password?.config.minPasswordLength;\n const maxLength = ctx.context.password?.config.maxPasswordLength;\n if (newPassword.length < minLength) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT\n });\n }\n if (newPassword.length > maxLength) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.PASSWORD_TOO_LONG\n });\n }\n const id = `reset-password:${token}`;\n const verification = await ctx.context.internalAdapter.findVerificationValue(id);\n if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.INVALID_TOKEN\n });\n }\n const userId = verification.value;\n const hashedPassword = await ctx.context.password.hash(newPassword);\n const accounts = await ctx.context.internalAdapter.findAccounts(userId);\n const account = accounts.find((ac) => ac.providerId === \"credential\");\n if (!account) {\n await ctx.context.internalAdapter.createAccount(\n {\n userId,\n providerId: \"credential\",\n password: hashedPassword,\n accountId: userId\n },\n ctx\n );\n } else {\n await ctx.context.internalAdapter.updatePassword(\n userId,\n hashedPassword,\n ctx\n );\n }\n await ctx.context.internalAdapter.deleteVerificationValue(verification.id);\n if (ctx.context.options.emailAndPassword?.onPasswordReset) {\n const user = await ctx.context.internalAdapter.findUserById(userId);\n if (user) {\n await ctx.context.options.emailAndPassword.onPasswordReset(\n {\n user\n },\n ctx.request\n );\n }\n }\n if (ctx.context.options.emailAndPassword?.revokeSessionsOnPasswordReset) {\n await ctx.context.internalAdapter.deleteSessions(userId);\n }\n return ctx.json({\n status: true\n });\n }\n);\n\nconst updateUser = () => createAuthEndpoint(\n \"/update-user\",\n {\n method: \"POST\",\n body: z.record(\n z.string().meta({\n description: \"Field name must be a string\"\n }),\n z.any()\n ),\n use: [sessionMiddleware],\n metadata: {\n $Infer: {\n body: {}\n },\n openapi: {\n description: \"Update the current user\",\n requestBody: {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description: \"The name of the user\"\n },\n image: {\n type: \"string\",\n description: \"The image of the user\"\n }\n }\n }\n }\n }\n },\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the update was successful\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const body = ctx.body;\n if (body.email) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED\n });\n }\n const { name, image, ...rest } = body;\n const session = ctx.context.session;\n if (image === void 0 && name === void 0 && Object.keys(rest).length === 0) {\n return ctx.json({\n status: true\n });\n }\n const additionalFields = parseUserInput(\n ctx.context.options,\n rest,\n \"update\"\n );\n const user = await ctx.context.internalAdapter.updateUser(\n session.user.id,\n {\n name,\n image,\n ...additionalFields\n },\n ctx\n );\n await setSessionCookie(ctx, {\n session: session.session,\n user\n });\n return ctx.json({\n status: true\n });\n }\n);\nconst changePassword = createAuthEndpoint(\n \"/change-password\",\n {\n method: \"POST\",\n body: z.object({\n /**\n * The new password to set\n */\n newPassword: z.string().meta({\n description: \"The new password to set\"\n }),\n /**\n * The current password of the user\n */\n currentPassword: z.string().meta({\n description: \"The current password is required\"\n }),\n /**\n * revoke all sessions that are not the\n * current one logged in by the user\n */\n revokeOtherSessions: z.boolean().meta({\n description: \"Must be a boolean value\"\n }).optional()\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Change the password of the user\",\n responses: {\n \"200\": {\n description: \"Password successfully changed\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n token: {\n type: \"string\",\n nullable: true,\n // Only present if revokeOtherSessions is true\n description: \"New session token if other sessions were revoked\"\n },\n user: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"The unique identifier of the user\"\n },\n email: {\n type: \"string\",\n format: \"email\",\n description: \"The email address of the user\"\n },\n name: {\n type: \"string\",\n description: \"The name of the user\"\n },\n image: {\n type: \"string\",\n format: \"uri\",\n nullable: true,\n description: \"The profile image URL of the user\"\n },\n emailVerified: {\n type: \"boolean\",\n description: \"Whether the email has been verified\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"When the user was created\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"When the user was last updated\"\n }\n },\n required: [\n \"id\",\n \"email\",\n \"name\",\n \"emailVerified\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n },\n required: [\"user\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { newPassword, currentPassword, revokeOtherSessions } = ctx.body;\n const session = ctx.context.session;\n const minPasswordLength = ctx.context.password.config.minPasswordLength;\n if (newPassword.length < minPasswordLength) {\n ctx.context.logger.error(\"Password is too short\");\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT\n });\n }\n const maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n if (newPassword.length > maxPasswordLength) {\n ctx.context.logger.error(\"Password is too long\");\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.PASSWORD_TOO_LONG\n });\n }\n const accounts = await ctx.context.internalAdapter.findAccounts(\n session.user.id\n );\n const account = accounts.find(\n (account2) => account2.providerId === \"credential\" && account2.password\n );\n if (!account || !account.password) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND\n });\n }\n const passwordHash = await ctx.context.password.hash(newPassword);\n const verify = await ctx.context.password.verify({\n hash: account.password,\n password: currentPassword\n });\n if (!verify) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.INVALID_PASSWORD\n });\n }\n await ctx.context.internalAdapter.updateAccount(account.id, {\n password: passwordHash\n });\n let token = null;\n if (revokeOtherSessions) {\n await ctx.context.internalAdapter.deleteSessions(session.user.id);\n const newSession = await ctx.context.internalAdapter.createSession(\n session.user.id,\n ctx\n );\n if (!newSession) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION\n });\n }\n await setSessionCookie(ctx, {\n session: newSession,\n user: session.user\n });\n token = newSession.token;\n }\n return ctx.json({\n token,\n user: {\n id: session.user.id,\n email: session.user.email,\n name: session.user.name,\n image: session.user.image,\n emailVerified: session.user.emailVerified,\n createdAt: session.user.createdAt,\n updatedAt: session.user.updatedAt\n }\n });\n }\n);\nconst setPassword = createAuthEndpoint(\n \"/set-password\",\n {\n method: \"POST\",\n body: z.object({\n /**\n * The new password to set\n */\n newPassword: z.string().meta({\n description: \"The new password to set is required\"\n })\n }),\n metadata: {\n SERVER_ONLY: true\n },\n use: [sessionMiddleware]\n },\n async (ctx) => {\n const { newPassword } = ctx.body;\n const session = ctx.context.session;\n const minPasswordLength = ctx.context.password.config.minPasswordLength;\n if (newPassword.length < minPasswordLength) {\n ctx.context.logger.error(\"Password is too short\");\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT\n });\n }\n const maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n if (newPassword.length > maxPasswordLength) {\n ctx.context.logger.error(\"Password is too long\");\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.PASSWORD_TOO_LONG\n });\n }\n const accounts = await ctx.context.internalAdapter.findAccounts(\n session.user.id\n );\n const account = accounts.find(\n (account2) => account2.providerId === \"credential\" && account2.password\n );\n const passwordHash = await ctx.context.password.hash(newPassword);\n if (!account) {\n await ctx.context.internalAdapter.linkAccount(\n {\n userId: session.user.id,\n providerId: \"credential\",\n accountId: session.user.id,\n password: passwordHash\n },\n ctx\n );\n return ctx.json({\n status: true\n });\n }\n throw new APIError(\"BAD_REQUEST\", {\n message: \"user already has a password\"\n });\n }\n);\nconst deleteUser = createAuthEndpoint(\n \"/delete-user\",\n {\n method: \"POST\",\n use: [sessionMiddleware],\n body: z.object({\n /**\n * The callback URL to redirect to after the user is deleted\n * this is only used on delete user callback\n */\n callbackURL: z.string().meta({\n description: \"The callback URL to redirect to after the user is deleted\"\n }).optional(),\n /**\n * The password of the user. If the password isn't provided, session freshness\n * will be checked.\n */\n password: z.string().meta({\n description: \"The password of the user is required to delete the user\"\n }).optional(),\n /**\n * The token to delete the user. If the token is provided, the user will be deleted\n */\n token: z.string().meta({\n description: \"The token to delete the user is required\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Delete the user\",\n responses: {\n \"200\": {\n description: \"User deletion processed successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\",\n description: \"Indicates if the operation was successful\"\n },\n message: {\n type: \"string\",\n enum: [\"User deleted\", \"Verification email sent\"],\n description: \"Status message of the deletion process\"\n }\n },\n required: [\"success\", \"message\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.context.options.user?.deleteUser?.enabled) {\n ctx.context.logger.error(\n \"Delete user is disabled. Enable it in the options\",\n {\n session: ctx.context.session\n }\n );\n throw new APIError(\"NOT_FOUND\");\n }\n const session = ctx.context.session;\n if (ctx.body.password) {\n const accounts = await ctx.context.internalAdapter.findAccounts(\n session.user.id\n );\n const account = accounts.find(\n (account2) => account2.providerId === \"credential\" && account2.password\n );\n if (!account || !account.password) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND\n });\n }\n const verify = await ctx.context.password.verify({\n hash: account.password,\n password: ctx.body.password\n });\n if (!verify) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.INVALID_PASSWORD\n });\n }\n }\n if (ctx.body.token) {\n await deleteUserCallback({\n ...ctx,\n query: {\n token: ctx.body.token\n }\n });\n return ctx.json({\n success: true,\n message: \"User deleted\"\n });\n }\n if (ctx.context.options.user.deleteUser?.sendDeleteAccountVerification) {\n const token = generateRandomString(32, \"0-9\", \"a-z\");\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: session.user.id,\n identifier: `delete-account-${token}`,\n expiresAt: new Date(\n Date.now() + (ctx.context.options.user.deleteUser?.deleteTokenExpiresIn || 60 * 60 * 24) * 1e3\n )\n },\n ctx\n );\n const url = `${ctx.context.baseURL}/delete-user/callback?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n await ctx.context.options.user.deleteUser.sendDeleteAccountVerification(\n {\n user: session.user,\n url,\n token\n },\n ctx.request\n );\n return ctx.json({\n success: true,\n message: \"Verification email sent\"\n });\n }\n if (!ctx.body.password && ctx.context.sessionConfig.freshAge !== 0) {\n const currentAge = session.session.createdAt.getTime();\n const freshAge = ctx.context.sessionConfig.freshAge * 1e3;\n const now = Date.now();\n if (now - currentAge > freshAge * 1e3) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.SESSION_EXPIRED\n });\n }\n }\n const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete;\n if (beforeDelete) {\n await beforeDelete(session.user, ctx.request);\n }\n await ctx.context.internalAdapter.deleteUser(session.user.id);\n await ctx.context.internalAdapter.deleteSessions(session.user.id);\n await ctx.context.internalAdapter.deleteAccounts(session.user.id);\n deleteSessionCookie(ctx);\n const afterDelete = ctx.context.options.user.deleteUser?.afterDelete;\n if (afterDelete) {\n await afterDelete(session.user, ctx.request);\n }\n return ctx.json({\n success: true,\n message: \"User deleted\"\n });\n }\n);\nconst deleteUserCallback = createAuthEndpoint(\n \"/delete-user/callback\",\n {\n method: \"GET\",\n query: z.object({\n token: z.string().meta({\n description: \"The token to verify the deletion request\"\n }),\n callbackURL: z.string().meta({\n description: \"The URL to redirect to after deletion\"\n }).optional()\n }),\n use: [originCheck((ctx) => ctx.query.callbackURL)],\n metadata: {\n openapi: {\n description: \"Callback to complete user deletion with verification token\",\n responses: {\n \"200\": {\n description: \"User successfully deleted\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\",\n description: \"Indicates if the deletion was successful\"\n },\n message: {\n type: \"string\",\n enum: [\"User deleted\"],\n description: \"Confirmation message\"\n }\n },\n required: [\"success\", \"message\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.context.options.user?.deleteUser?.enabled) {\n ctx.context.logger.error(\n \"Delete user is disabled. Enable it in the options\"\n );\n throw new APIError(\"NOT_FOUND\");\n }\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n throw new APIError(\"NOT_FOUND\", {\n message: BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO\n });\n }\n const token = await ctx.context.internalAdapter.findVerificationValue(\n `delete-account-${ctx.query.token}`\n );\n if (!token || token.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"NOT_FOUND\", {\n message: BASE_ERROR_CODES.INVALID_TOKEN\n });\n }\n if (token.value !== session.user.id) {\n throw new APIError(\"NOT_FOUND\", {\n message: BASE_ERROR_CODES.INVALID_TOKEN\n });\n }\n const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete;\n if (beforeDelete) {\n await beforeDelete(session.user, ctx.request);\n }\n await ctx.context.internalAdapter.deleteUser(session.user.id);\n await ctx.context.internalAdapter.deleteSessions(session.user.id);\n await ctx.context.internalAdapter.deleteAccounts(session.user.id);\n await ctx.context.internalAdapter.deleteVerificationValue(token.id);\n deleteSessionCookie(ctx);\n const afterDelete = ctx.context.options.user.deleteUser?.afterDelete;\n if (afterDelete) {\n await afterDelete(session.user, ctx.request);\n }\n if (ctx.query.callbackURL) {\n throw ctx.redirect(ctx.query.callbackURL || \"/\");\n }\n return ctx.json({\n success: true,\n message: \"User deleted\"\n });\n }\n);\nconst changeEmail = createAuthEndpoint(\n \"/change-email\",\n {\n method: \"POST\",\n body: z.object({\n newEmail: z.email().meta({\n description: \"The new email address to set must be a valid email address\"\n }),\n callbackURL: z.string().meta({\n description: \"The URL to redirect to after email verification\"\n }).optional()\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n responses: {\n \"200\": {\n description: \"Email change request processed successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the request was successful\"\n },\n message: {\n type: \"string\",\n enum: [\"Email updated\", \"Verification email sent\"],\n description: \"Status message of the email change process\",\n nullable: true\n }\n },\n required: [\"status\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.context.options.user?.changeEmail?.enabled) {\n ctx.context.logger.error(\"Change email is disabled.\");\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Change email is disabled\"\n });\n }\n const newEmail = ctx.body.newEmail.toLowerCase();\n if (newEmail === ctx.context.session.user.email) {\n ctx.context.logger.error(\"Email is the same\");\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Email is the same\"\n });\n }\n const existingUser = await ctx.context.internalAdapter.findUserByEmail(newEmail);\n if (existingUser) {\n ctx.context.logger.error(\"Email already exists\");\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Couldn't update your email\"\n });\n }\n if (ctx.context.session.user.emailVerified !== true) {\n const existing = await ctx.context.internalAdapter.findUserByEmail(newEmail);\n if (existing) {\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: BASE_ERROR_CODES.USER_ALREADY_EXISTS\n });\n }\n await ctx.context.internalAdapter.updateUserByEmail(\n ctx.context.session.user.email,\n {\n email: newEmail\n },\n ctx\n );\n await setSessionCookie(ctx, {\n session: ctx.context.session.session,\n user: {\n ...ctx.context.session.user,\n email: newEmail\n }\n });\n if (ctx.context.options.emailVerification?.sendVerificationEmail) {\n const token2 = await createEmailVerificationToken(\n ctx.context.secret,\n newEmail,\n void 0,\n ctx.context.options.emailVerification?.expiresIn\n );\n const url2 = `${ctx.context.baseURL}/verify-email?token=${token2}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n await ctx.context.options.emailVerification.sendVerificationEmail(\n {\n user: {\n ...ctx.context.session.user,\n email: newEmail\n },\n url: url2,\n token: token2\n },\n ctx.request\n );\n }\n return ctx.json({\n status: true\n });\n }\n if (!ctx.context.options.user.changeEmail.sendChangeEmailVerification) {\n ctx.context.logger.error(\"Verification email isn't enabled.\");\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Verification email isn't enabled\"\n });\n }\n const token = await createEmailVerificationToken(\n ctx.context.secret,\n ctx.context.session.user.email,\n newEmail,\n ctx.context.options.emailVerification?.expiresIn\n );\n const url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || \"/\"}`;\n await ctx.context.options.user.changeEmail.sendChangeEmailVerification(\n {\n user: ctx.context.session.user,\n newEmail,\n url,\n token\n },\n ctx.request\n );\n return ctx.json({\n status: true\n });\n }\n);\n\nfunction sanitize(input) {\n return input.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\").replace(/'/g, \"&#39;\");\n}\nconst html = (errorCode = \"Unknown\") => `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Authentication Error</title>\n <style>\n :root {\n --bg-color: #f8f9fa;\n --text-color: #212529;\n --accent-color: #000000;\n --error-color: #dc3545;\n --border-color: #e9ecef;\n }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n background-color: var(--bg-color);\n color: var(--text-color);\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n margin: 0;\n line-height: 1.5;\n }\n .error-container {\n background-color: #ffffff;\n border-radius: 12px;\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);\n padding: 2.5rem;\n text-align: center;\n max-width: 90%;\n width: 400px;\n }\n h1 {\n color: var(--error-color);\n font-size: 1.75rem;\n margin-bottom: 1rem;\n font-weight: 600;\n }\n p {\n margin-bottom: 1.5rem;\n color: #495057;\n }\n .btn {\n background-color: var(--accent-color);\n color: #ffffff;\n text-decoration: none;\n padding: 0.75rem 1.5rem;\n border-radius: 6px;\n transition: all 0.3s ease;\n display: inline-block;\n font-weight: 500;\n border: 2px solid var(--accent-color);\n }\n .btn:hover {\n background-color: #131721;\n }\n .error-code {\n font-size: 0.875rem;\n color: #6c757d;\n margin-top: 1.5rem;\n padding-top: 1.5rem;\n border-top: 1px solid var(--border-color);\n }\n .icon {\n font-size: 3rem;\n margin-bottom: 1rem;\n }\n </style>\n</head>\n<body>\n <div class=\"error-container\">\n <div class=\"icon\">\\u26A0\\uFE0F</div>\n <h1>Better Auth Error</h1>\n <p>We encountered an issue while processing your request. Please try again or contact the application owner if the problem persists.</p>\n <a href=\"/\" id=\"returnLink\" class=\"btn\">Return to Application</a>\n <div class=\"error-code\">Error Code: <span id=\"errorCode\">${sanitize(\n errorCode\n)}</span></div>\n </div>\n</body>\n</html>`;\nconst error = createAuthEndpoint(\n \"/error\",\n {\n method: \"GET\",\n metadata: {\n ...HIDE_METADATA,\n openapi: {\n description: \"Displays an error page\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"text/html\": {\n schema: {\n type: \"string\",\n description: \"The HTML content of the error page\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (c) => {\n const query = new URL(c.request?.url || \"\").searchParams.get(\"error\") || \"Unknown\";\n return new Response(html(query), {\n headers: {\n \"Content-Type\": \"text/html\"\n }\n });\n }\n);\n\nconst ok = createAuthEndpoint(\n \"/ok\",\n {\n method: \"GET\",\n metadata: {\n ...HIDE_METADATA,\n openapi: {\n description: \"Check if the API is working\",\n responses: {\n \"200\": {\n description: \"API is working\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n ok: {\n type: \"boolean\",\n description: \"Indicates if the API is working\"\n }\n },\n required: [\"ok\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n return ctx.json({\n ok: true\n });\n }\n);\n\nconst listUserAccounts = createAuthEndpoint(\n \"/list-accounts\",\n {\n method: \"GET\",\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"List all accounts linked to the user\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n provider: {\n type: \"string\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\"\n }\n },\n accountId: {\n type: \"string\"\n },\n scopes: {\n type: \"array\",\n items: {\n type: \"string\"\n }\n }\n },\n required: [\n \"id\",\n \"provider\",\n \"createdAt\",\n \"updatedAt\",\n \"accountId\",\n \"scopes\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (c) => {\n const session = c.context.session;\n const accounts = await c.context.internalAdapter.findAccounts(\n session.user.id\n );\n return c.json(\n accounts.map((a) => ({\n id: a.id,\n provider: a.providerId,\n createdAt: a.createdAt,\n updatedAt: a.updatedAt,\n accountId: a.accountId,\n scopes: a.scope?.split(\",\") || []\n }))\n );\n }\n);\nconst linkSocialAccount = createAuthEndpoint(\n \"/link-social\",\n {\n method: \"POST\",\n requireHeaders: true,\n body: z.object({\n /**\n * Callback URL to redirect to after the user has signed in.\n */\n callbackURL: z.string().meta({\n description: \"The URL to redirect to after the user has signed in\"\n }).optional(),\n /**\n * OAuth2 provider to use\n */\n provider: SocialProviderListEnum,\n /**\n * ID Token for direct authentication without redirect\n */\n idToken: z.object({\n token: z.string(),\n nonce: z.string().optional(),\n accessToken: z.string().optional(),\n refreshToken: z.string().optional(),\n scopes: z.array(z.string()).optional()\n }).optional(),\n /**\n * Whether to allow sign up for new users\n */\n requestSignUp: z.boolean().optional(),\n /**\n * Additional scopes to request when linking the account.\n * This is useful for requesting additional permissions when\n * linking a social account compared to the initial authentication.\n */\n scopes: z.array(z.string()).meta({\n description: \"Additional scopes to request from the provider\"\n }).optional(),\n /**\n * The URL to redirect to if there is an error during the link process.\n */\n errorCallbackURL: z.string().meta({\n description: \"The URL to redirect to if there is an error during the link process\"\n }).optional()\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Link a social account to the user\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n url: {\n type: \"string\",\n description: \"The authorization URL to redirect the user to\"\n },\n redirect: {\n type: \"boolean\",\n description: \"Indicates if the user should be redirected to the authorization URL\"\n },\n status: {\n type: \"boolean\"\n }\n },\n required: [\"redirect\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (c) => {\n const session = c.context.session;\n const provider = c.context.socialProviders.find(\n (p) => p.id === c.body.provider\n );\n if (!provider) {\n c.context.logger.error(\n \"Provider not found. Make sure to add the provider in your auth config\",\n {\n provider: c.body.provider\n }\n );\n throw new APIError(\"NOT_FOUND\", {\n message: BASE_ERROR_CODES.PROVIDER_NOT_FOUND\n });\n }\n if (c.body.idToken) {\n if (!provider.verifyIdToken) {\n c.context.logger.error(\n \"Provider does not support id token verification\",\n {\n provider: c.body.provider\n }\n );\n throw new APIError(\"NOT_FOUND\", {\n message: BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED\n });\n }\n const { token, nonce } = c.body.idToken;\n const valid = await provider.verifyIdToken(token, nonce);\n if (!valid) {\n c.context.logger.error(\"Invalid id token\", {\n provider: c.body.provider\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.INVALID_TOKEN\n });\n }\n const linkingUserInfo = await provider.getUserInfo({\n idToken: token,\n accessToken: c.body.idToken.accessToken,\n refreshToken: c.body.idToken.refreshToken\n });\n if (!linkingUserInfo || !linkingUserInfo?.user) {\n c.context.logger.error(\"Failed to get user info\", {\n provider: c.body.provider\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO\n });\n }\n if (!linkingUserInfo.user.email) {\n c.context.logger.error(\"User email not found\", {\n provider: c.body.provider\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND\n });\n }\n const existingAccounts = await c.context.internalAdapter.findAccounts(\n session.user.id\n );\n const hasBeenLinked = existingAccounts.find(\n (a) => a.providerId === provider.id && a.accountId === linkingUserInfo.user.id\n );\n if (hasBeenLinked) {\n return c.json({\n redirect: false,\n url: \"\",\n // this is for type inference\n status: true\n });\n }\n const trustedProviders = c.context.options.account?.accountLinking?.trustedProviders;\n const isTrustedProvider = trustedProviders?.includes(provider.id);\n if (!isTrustedProvider && !linkingUserInfo.user.emailVerified || c.context.options.account?.accountLinking?.enabled === false) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Account not linked - linking not allowed\"\n });\n }\n if (linkingUserInfo.user.email !== session.user.email && c.context.options.account?.accountLinking?.allowDifferentEmails !== true) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Account not linked - different emails not allowed\"\n });\n }\n try {\n await c.context.internalAdapter.createAccount(\n {\n userId: session.user.id,\n providerId: provider.id,\n accountId: linkingUserInfo.user.id.toString(),\n accessToken: c.body.idToken.accessToken,\n idToken: token,\n refreshToken: c.body.idToken.refreshToken,\n scope: c.body.idToken.scopes?.join(\",\")\n },\n c\n );\n } catch (e) {\n throw new APIError(\"EXPECTATION_FAILED\", {\n message: \"Account not linked - unable to create account\"\n });\n }\n if (c.context.options.account?.accountLinking?.updateUserInfoOnLink === true) {\n try {\n await c.context.internalAdapter.updateUser(session.user.id, {\n name: linkingUserInfo.user?.name,\n image: linkingUserInfo.user?.image\n });\n } catch (e) {\n console.warn(\"Could not update user - \" + e.toString());\n }\n }\n return c.json({\n redirect: false,\n url: \"\",\n // this is for type inference\n status: true\n });\n }\n const state = await generateState(c, {\n userId: session.user.id,\n email: session.user.email\n });\n const url = await provider.createAuthorizationURL({\n state: state.state,\n codeVerifier: state.codeVerifier,\n redirectURI: `${c.context.baseURL}/callback/${provider.id}`,\n scopes: c.body.scopes\n });\n return c.json({\n url: url.toString(),\n redirect: true\n });\n }\n);\nconst unlinkAccount = createAuthEndpoint(\n \"/unlink-account\",\n {\n method: \"POST\",\n body: z.object({\n providerId: z.string(),\n accountId: z.string().optional()\n }),\n use: [freshSessionMiddleware],\n metadata: {\n openapi: {\n description: \"Unlink an account\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { providerId, accountId } = ctx.body;\n const accounts = await ctx.context.internalAdapter.findAccounts(\n ctx.context.session.user.id\n );\n if (accounts.length === 1 && !ctx.context.options.account?.accountLinking?.allowUnlinkingAll) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT\n });\n }\n const accountExist = accounts.find(\n (account) => accountId ? account.accountId === accountId && account.providerId === providerId : account.providerId === providerId\n );\n if (!accountExist) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.ACCOUNT_NOT_FOUND\n });\n }\n await ctx.context.internalAdapter.deleteAccount(accountExist.id);\n return ctx.json({\n status: true\n });\n }\n);\nconst getAccessToken = createAuthEndpoint(\n \"/get-access-token\",\n {\n method: \"POST\",\n body: z.object({\n providerId: z.string().meta({\n description: \"The provider ID for the OAuth provider\"\n }),\n accountId: z.string().meta({\n description: \"The account ID associated with the refresh token\"\n }).optional(),\n userId: z.string().meta({\n description: \"The user ID associated with the account\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Get a valid access token, doing a refresh if needed\",\n responses: {\n 200: {\n description: \"A Valid access token\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n tokenType: {\n type: \"string\"\n },\n idToken: {\n type: \"string\"\n },\n accessToken: {\n type: \"string\"\n },\n refreshToken: {\n type: \"string\"\n },\n accessTokenExpiresAt: {\n type: \"string\",\n format: \"date-time\"\n },\n refreshTokenExpiresAt: {\n type: \"string\",\n format: \"date-time\"\n }\n }\n }\n }\n }\n },\n 400: {\n description: \"Invalid refresh token or provider configuration\"\n }\n }\n }\n }\n },\n async (ctx) => {\n const { providerId, accountId, userId } = ctx.body;\n const req = ctx.request;\n const session = await getSessionFromCtx(ctx);\n if (req && !session) {\n throw ctx.error(\"UNAUTHORIZED\");\n }\n let resolvedUserId = session?.user?.id || userId;\n if (!resolvedUserId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: `Either userId or session is required`\n });\n }\n if (!ctx.context.socialProviders.find((p) => p.id === providerId)) {\n throw new APIError(\"BAD_REQUEST\", {\n message: `Provider ${providerId} is not supported.`\n });\n }\n const accounts = await ctx.context.internalAdapter.findAccounts(resolvedUserId);\n const account = accounts.find(\n (acc) => accountId ? acc.id === accountId && acc.providerId === providerId : acc.providerId === providerId\n );\n if (!account) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Account not found\"\n });\n }\n const provider = ctx.context.socialProviders.find(\n (p) => p.id === providerId\n );\n if (!provider) {\n throw new APIError(\"BAD_REQUEST\", {\n message: `Provider ${providerId} not found.`\n });\n }\n try {\n let newTokens = null;\n if (account.refreshToken && (!account.accessTokenExpiresAt || account.accessTokenExpiresAt.getTime() - Date.now() < 5e3) && provider.refreshAccessToken) {\n newTokens = await provider.refreshAccessToken(\n account.refreshToken\n );\n await ctx.context.internalAdapter.updateAccount(account.id, {\n accessToken: await setTokenUtil(newTokens.accessToken, ctx.context),\n accessTokenExpiresAt: newTokens.accessTokenExpiresAt,\n refreshToken: await setTokenUtil(newTokens.refreshToken, ctx.context),\n refreshTokenExpiresAt: newTokens.refreshTokenExpiresAt\n });\n }\n const tokens = {\n accessToken: await getAccessTokenUtil(\n newTokens?.accessToken ?? account.accessToken ?? \"\",\n ctx.context\n ),\n accessTokenExpiresAt: newTokens?.accessTokenExpiresAt ?? account.accessTokenExpiresAt ?? void 0,\n scopes: account.scope?.split(\",\") ?? [],\n idToken: newTokens?.idToken ?? account.idToken ?? void 0\n };\n return ctx.json(tokens);\n } catch (error) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Failed to get a valid access token\",\n cause: error\n });\n }\n }\n);\nconst refreshToken = createAuthEndpoint(\n \"/refresh-token\",\n {\n method: \"POST\",\n body: z.object({\n providerId: z.string().meta({\n description: \"The provider ID for the OAuth provider\"\n }),\n accountId: z.string().meta({\n description: \"The account ID associated with the refresh token\"\n }).optional(),\n userId: z.string().meta({\n description: \"The user ID associated with the account\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Refresh the access token using a refresh token\",\n responses: {\n 200: {\n description: \"Access token refreshed successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n tokenType: {\n type: \"string\"\n },\n idToken: {\n type: \"string\"\n },\n accessToken: {\n type: \"string\"\n },\n refreshToken: {\n type: \"string\"\n },\n accessTokenExpiresAt: {\n type: \"string\",\n format: \"date-time\"\n },\n refreshTokenExpiresAt: {\n type: \"string\",\n format: \"date-time\"\n }\n }\n }\n }\n }\n },\n 400: {\n description: \"Invalid refresh token or provider configuration\"\n }\n }\n }\n }\n },\n async (ctx) => {\n const { providerId, accountId, userId } = ctx.body;\n const req = ctx.request;\n const session = await getSessionFromCtx(ctx);\n if (req && !session) {\n throw ctx.error(\"UNAUTHORIZED\");\n }\n let resolvedUserId = session?.user?.id || userId;\n if (!resolvedUserId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: `Either userId or session is required`\n });\n }\n const accounts = await ctx.context.internalAdapter.findAccounts(resolvedUserId);\n const account = accounts.find(\n (acc) => accountId ? acc.id === accountId && acc.providerId === providerId : acc.providerId === providerId\n );\n if (!account) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Account not found\"\n });\n }\n const provider = ctx.context.socialProviders.find(\n (p) => p.id === providerId\n );\n if (!provider) {\n throw new APIError(\"BAD_REQUEST\", {\n message: `Provider ${providerId} not found.`\n });\n }\n if (!provider.refreshAccessToken) {\n throw new APIError(\"BAD_REQUEST\", {\n message: `Provider ${providerId} does not support token refreshing.`\n });\n }\n try {\n const tokens = await provider.refreshAccessToken(\n account.refreshToken\n );\n await ctx.context.internalAdapter.updateAccount(account.id, {\n accessToken: await setTokenUtil(tokens.accessToken, ctx.context),\n refreshToken: await setTokenUtil(tokens.refreshToken, ctx.context),\n accessTokenExpiresAt: tokens.accessTokenExpiresAt,\n refreshTokenExpiresAt: tokens.refreshTokenExpiresAt\n });\n return ctx.json(tokens);\n } catch (error) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Failed to refresh access token\",\n cause: error\n });\n }\n }\n);\nconst accountInfo = createAuthEndpoint(\n \"/account-info\",\n {\n method: \"POST\",\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Get the account info provided by the provider\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n name: {\n type: \"string\"\n },\n email: {\n type: \"string\"\n },\n image: {\n type: \"string\"\n },\n emailVerified: {\n type: \"boolean\"\n }\n },\n required: [\"id\", \"emailVerified\"]\n },\n data: {\n type: \"object\",\n properties: {},\n additionalProperties: true\n }\n },\n required: [\"user\", \"data\"],\n additionalProperties: false\n }\n }\n }\n }\n }\n }\n },\n body: z.object({\n accountId: z.string().meta({\n description: \"The provider given account id for which to get the account info\"\n })\n })\n },\n async (ctx) => {\n const account = await ctx.context.internalAdapter.findAccount(\n ctx.body.accountId\n );\n if (!account || account.userId !== ctx.context.session.user.id) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Account not found\"\n });\n }\n const provider = ctx.context.socialProviders.find(\n (p) => p.id === account.providerId\n );\n if (!provider) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: `Provider account provider is ${account.providerId} but it is not configured`\n });\n }\n const tokens = await getAccessToken({\n ...ctx,\n body: {\n accountId: account.id,\n providerId: account.providerId\n },\n returnHeaders: false\n });\n const info = await provider.getUserInfo(tokens);\n return ctx.json(info);\n }\n);\n\nexport { signOut as $, originCheckMiddleware as A, BASE_ERROR_CODES as B, error as C, ok as D, accountInfo as E, getAccessToken as F, refreshToken as G, HIDE_METADATA as H, unlinkAccount as I, deleteUserCallback as J, listUserAccounts as K, linkSocialAccount as L, revokeOtherSessions as M, revokeSessions as N, revokeSession as O, requestPasswordResetCallback as P, requestPasswordReset as Q, forgetPasswordCallback as R, deleteUser as S, setPassword as T, changePassword as U, changeEmail as V, sendVerificationEmail as W, verifyEmail as X, resetPassword as Y, forgetPassword as Z, signInEmail as _, validateToken as a, callbackOAuth as a0, signInSocial as a1, requestOnlySessionMiddleware as a2, socialProviderList as a3, SocialProviderListEnum as a4, apple as a5, getApplePublicKey as a6, discord as a7, dropbox as a8, facebook as a9, github as aa, linear as ab, linkedin as ac, gitlab as ad, google as ae, kick as af, microsoft as ag, notion as ah, reddit as ai, roblox as aj, spotify as ak, tiktok as al, twitch as am, twitter as an, LANG as ao, vk as ap, zoom as aq, huggingface as ar, slack as as, generateCodeChallenge as b, createAuthorizationURL as c, getOAuth2Tokens as d, encodeOAuthParameter as e, getAccessTokenUtil as f, generateState as g, handleOAuthUserInfo as h, createAuthMiddleware as i, createAuthEndpoint as j, getSessionFromCtx as k, sessionMiddleware as l, getSession as m, freshSessionMiddleware as n, originCheck as o, parseState as p, optionsMiddleware as q, refreshAccessToken as r, setTokenUtil as s, socialProviders as t, sendVerificationEmailFn as u, validateAuthorizationCode as v, createEmailVerificationToken as w, wildcardMatch as x, listSessions as y, updateUser as z };\n","const getDate = (span, unit = \"ms\") => {\n return new Date(Date.now() + (unit === \"sec\" ? span * 1e3 : span));\n};\n\nexport { getDate as g };\n","function getAlphabet(urlSafe) {\n return urlSafe ? \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\" : \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n}\nfunction base64Encode(data, alphabet, padding) {\n let result = \"\";\n let buffer = 0;\n let shift = 0;\n for (const byte of data) {\n buffer = buffer << 8 | byte;\n shift += 8;\n while (shift >= 6) {\n shift -= 6;\n result += alphabet[buffer >> shift & 63];\n }\n }\n if (shift > 0) {\n result += alphabet[buffer << 6 - shift & 63];\n }\n if (padding) {\n const padCount = (4 - result.length % 4) % 4;\n result += \"=\".repeat(padCount);\n }\n return result;\n}\nfunction base64Decode(data, alphabet) {\n const decodeMap = /* @__PURE__ */ new Map();\n for (let i = 0; i < alphabet.length; i++) {\n decodeMap.set(alphabet[i], i);\n }\n const result = [];\n let buffer = 0;\n let bitsCollected = 0;\n for (const char of data) {\n if (char === \"=\")\n break;\n const value = decodeMap.get(char);\n if (value === void 0) {\n throw new Error(`Invalid Base64 character: ${char}`);\n }\n buffer = buffer << 6 | value;\n bitsCollected += 6;\n if (bitsCollected >= 8) {\n bitsCollected -= 8;\n result.push(buffer >> bitsCollected & 255);\n }\n }\n return Uint8Array.from(result);\n}\nconst base64 = {\n encode(data, options = {}) {\n const alphabet = getAlphabet(false);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base64Encode(buffer, alphabet, options.padding ?? true);\n },\n decode(data) {\n if (typeof data !== \"string\") {\n data = new TextDecoder().decode(data);\n }\n const urlSafe = data.includes(\"-\") || data.includes(\"_\");\n const alphabet = getAlphabet(urlSafe);\n return base64Decode(data, alphabet);\n }\n};\nconst base64Url = {\n encode(data, options = {}) {\n const alphabet = getAlphabet(true);\n const buffer = typeof data === \"string\" ? new TextEncoder().encode(data) : new Uint8Array(data);\n return base64Encode(buffer, alphabet, options.padding ?? true);\n },\n decode(data) {\n const urlSafe = data.includes(\"-\") || data.includes(\"_\");\n const alphabet = getAlphabet(urlSafe);\n return base64Decode(data, alphabet);\n }\n};\n\nexport { base64, base64Url };\n","import { subtle } from 'uncrypto';\nimport { base64Url, base64 } from './base64.mjs';\n\nfunction createHash(algorithm, encoding) {\n return {\n digest: async (input) => {\n const encoder = new TextEncoder();\n const data = typeof input === \"string\" ? encoder.encode(input) : input;\n const hashBuffer = await subtle.digest(algorithm, data);\n if (encoding === \"hex\") {\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return hashHex;\n }\n if (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n if (encoding.includes(\"url\")) {\n return base64Url.encode(hashBuffer, {\n padding: encoding !== \"base64urlnopad\"\n });\n }\n const hashBase64 = base64.encode(hashBuffer);\n return hashBase64;\n }\n return hashBuffer;\n }\n };\n}\n\nexport { createHash };\n","function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\nexport type Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr: TypedArray) =>\n new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n else if (isBytes(data)) data = copyBytes(data);\n else throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\nexport type Cipher = {\n encrypt(plaintext: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\nexport type AsyncCipher = {\n encrypt(plaintext: Uint8Array): Promise<Uint8Array>;\n decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;\n};\n\nexport type CipherWithOutput = Cipher & {\n encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n// Params is outside return type, so it is accessible before calling constructor\n// If function support multiple nonceLength's, we return best one\nexport type CipherParams = { blockSize: number; nonceLength?: number; tagLength?: number };\nexport type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = <C extends CipherCons<any>, P extends CipherParams>(\n params: P,\n c: C\n): C & P => {\n Object.assign(c, params);\n return c as C & P;\n};\n\nexport type XorStream = (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter?: number\n) => Uint8Array;\n\n// Polyfill for Safari 14\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\nexport function u64Lengths(ciphertext: Uint8Array, AAD?: Uint8Array) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes: Uint8Array) {\n return bytes.byteOffset % 4 === 0;\n}\n\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes: Uint8Array) {\n return Uint8Array.from(bytes);\n}\n\nexport function clean(...arrays: TypedArray[]) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n","// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { bool as abool, bytes as abytes, number as anumber } from './_assert.js';\nimport { XorStream, checkOpts, clean, copyBytes, u32 } from './utils.js';\n\n/*\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n*/\n\n// We can't make top-level var depend on utils.utf8ToBytes\n// because it's not present in all envs. Creating a similar fn here\nconst _utf8ToBytes = (str: string) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes('expand 16-byte k');\nconst sigma32 = _utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\nexport const sigma = sigma32_32.slice();\n\nexport function rotl(a: number, b: number): number {\n return (a << b) | (a >>> (32 - b));\n}\n\nexport type CipherCoreFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n output: Uint32Array,\n counter: number,\n rounds?: number\n) => void;\n\nexport type ExtendNonceFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n input: Uint32Array,\n output: Uint32Array\n) => void;\n\nexport type CipherOpts = {\n allowShortKeys?: boolean; // Original salsa / chacha allow 16-byte keys\n extendNonceFn?: ExtendNonceFn;\n counterLength?: number;\n counterRight?: boolean; // right: nonce|counter; left: counter|nonce\n rounds?: number;\n};\n\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b: Uint8Array) {\n return b.byteOffset % 4 === 0;\n}\n\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\n\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(\n core: CipherCoreFn,\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n data: Uint8Array,\n output: Uint8Array,\n counter: number,\n rounds: number\n): void {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0) throw new Error('arx: invalid block position');\n for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n\nexport function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(\n { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },\n opts\n );\n if (typeof core !== 'function') throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter = 0\n ): Uint8Array => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (output === undefined) output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length,\n k: Uint8Array,\n sigma: Uint32Array;\n if (l === 32) {\n toClean.push((k = copyBytes(key)));\n sigma = sigma32_32;\n } else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n } else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce)));\n\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n clean(...toClean);\n return output;\n };\n}\n","import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\nimport { Hash, Input, clean, toBytes } from './utils.js';\n\n// Poly1305 is a fast and parallel secret-key message-authentication code.\n// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf\n// https://datatracker.ietf.org/doc/html/rfc8439\n\n// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna\nconst u8to16 = (a: Uint8Array, i: number) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\nclass Poly1305 implements Hash<Poly1305> {\n readonly blockLen = 16;\n readonly outputLen = 16;\n private buffer = new Uint8Array(16);\n private r = new Uint16Array(10);\n private h = new Uint16Array(10);\n private pad = new Uint16Array(8);\n private pos = 0;\n protected finished = false;\n\n constructor(key: Input) {\n key = toBytes(key);\n abytes(key, 32);\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n\n private process(data: Uint8Array, offset: number, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n\n let c = 0;\n\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n\n private finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data: Input): this {\n aexists(this);\n const { buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n for (; pos < 16; pos++) buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\n\nexport type CHash = ReturnType<typeof wrapConstructorWithKey>;\nexport function wrapConstructorWithKey<H extends Hash<H>>(hashCons: (key: Input) => Hash<H>) {\n const hashC = (msg: Input, key: Input): Uint8Array => hashCons(key).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(32));\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input) => hashCons(key);\n return hashC;\n}\n\nexport const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));\n","// prettier-ignore\nimport { createCipher, rotl } from './_arx.js';\nimport { bytes as abytes } from './_assert.js';\nimport { poly1305 } from './_poly1305.js';\nimport {\n CipherWithOutput,\n XorStream,\n clean,\n createView,\n equalBytes,\n setBigUint64,\n wrapCipher,\n} from './utils.js';\n\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\n\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(\n s: Uint32Array, k: Uint32Array, n: Uint32Array, out: Uint32Array, cnt: number, rounds = 20\n): void {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(\n s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array\n) {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3],\n x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3],\n x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7],\n x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00; o32[oi++] = x01;\n o32[oi++] = x02; o32[oi++] = x03;\n o32[oi++] = x12; o32[oi++] = x13;\n o32[oi++] = x14; o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h: ReturnType<typeof poly1305.create>, msg: Uint8Array) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left) h.update(ZEROS16.subarray(left));\n};\n\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(\n fn: XorStream,\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n): Uint8Array {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD) updatePadded(h, AAD);\n updatePadded(h, data);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(data.length), true);\n h.update(num);\n const res = h.digest();\n clean(authKey, num);\n return res;\n}\n\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead =\n (xorStream: XorStream) =>\n (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): CipherWithOutput => {\n const tagLength = 16;\n abytes(key, 32);\n abytes(nonce);\n return {\n encrypt(plaintext: Uint8Array, output?: Uint8Array) {\n const plength = plaintext.length;\n const clength = plength + tagLength;\n if (output) {\n abytes(output, clength);\n } else {\n output = new Uint8Array(clength);\n }\n xorStream(key, nonce, plaintext, output, 1);\n const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext: Uint8Array, output?: Uint8Array) {\n const clength = ciphertext.length;\n const plength = clength - tagLength;\n if (clength < tagLength)\n throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n if (output) {\n abytes(output, plength);\n } else {\n output = new Uint8Array(plength);\n }\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag)) throw new Error('invalid tag');\n xorStream(key, nonce, data, output, 1);\n clean(tag);\n return output;\n },\n };\n };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 12, tagLength: 16 },\n _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 24, tagLength: 16 },\n _poly1305_aead(xchacha20)\n);\n","// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\n// The file will throw on node.js 14 and earlier.\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto =\n nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined;\n","// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.js on#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\n//\n// Use full path so that Node.js can rewrite it to `cryptoNode.js`.\nimport { crypto } from '@noble/ciphers/crypto';\nimport { bytes as abytes, number } from './_assert.js';\nimport { AsyncCipher, Cipher, concatBytes } from './utils.js';\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function')\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n throw new Error('crypto.getRandomValues must be defined');\n}\n\nexport function getWebcryptoSubtle() {\n if (crypto && typeof crypto.subtle === 'object' && crypto.subtle != null) return crypto.subtle;\n throw new Error('crypto.subtle must be defined');\n}\n\ntype RemoveNonceInner<T extends any[], Ret> = ((...args: T) => Ret) extends (\n arg0: any,\n arg1: any,\n ...rest: infer R\n) => any\n ? (key: Uint8Array, ...args: R) => Ret\n : never;\n\ntype RemoveNonce<T extends (...args: any) => any> = RemoveNonceInner<Parameters<T>, ReturnType<T>>;\ntype CipherWithNonce = ((key: Uint8Array, nonce: Uint8Array, ...args: any[]) => Cipher) & {\n nonceLength: number;\n};\n\n// Uses CSPRG for nonce, nonce injected in ciphertext\nexport function managedNonce<T extends CipherWithNonce>(fn: T): RemoveNonce<T> {\n number(fn.nonceLength);\n return ((key: Uint8Array, ...args: any[]): any => ({\n encrypt(plaintext: Uint8Array, ...argsEnc: any[]) {\n const { nonceLength } = fn;\n const nonce = randomBytes(nonceLength);\n const ciphertext = (fn(key, nonce, ...args).encrypt as any)(plaintext, ...argsEnc);\n const out = concatBytes(nonce, ciphertext);\n ciphertext.fill(0);\n return out;\n },\n decrypt(ciphertext: Uint8Array, ...argsDec: any[]) {\n const { nonceLength } = fn;\n const nonce = ciphertext.subarray(0, nonceLength);\n const data = ciphertext.subarray(nonceLength);\n return (fn(key, nonce, ...args).decrypt as any)(data, ...argsDec);\n },\n })) as RemoveNonce<T>;\n}\n\n// Overridable\nexport const utils = {\n async encrypt(key: Uint8Array, keyParams: any, cryptParams: any, plaintext: Uint8Array) {\n const cr = getWebcryptoSubtle();\n const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']);\n const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext);\n return new Uint8Array(ciphertext);\n },\n async decrypt(key: Uint8Array, keyParams: any, cryptParams: any, ciphertext: Uint8Array) {\n const cr = getWebcryptoSubtle();\n const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']);\n const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext);\n return new Uint8Array(plaintext);\n },\n};\n\nconst mode = {\n CBC: 'AES-CBC',\n CTR: 'AES-CTR',\n GCM: 'AES-GCM',\n} as const;\ntype BlockMode = (typeof mode)[keyof typeof mode];\n\nfunction getCryptParams(algo: BlockMode, nonce: Uint8Array, AAD?: Uint8Array) {\n if (algo === mode.CBC) return { name: mode.CBC, iv: nonce };\n if (algo === mode.CTR) return { name: mode.CTR, counter: nonce, length: 64 };\n if (algo === mode.GCM) {\n if (AAD) return { name: mode.GCM, iv: nonce, additionalData: AAD };\n else return { name: mode.GCM, iv: nonce };\n }\n\n throw new Error('unknown aes block mode');\n}\n\nfunction generate(algo: BlockMode) {\n return (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): AsyncCipher => {\n abytes(key);\n abytes(nonce);\n const keyParams = { name: algo, length: key.length * 8 };\n const cryptParams = getCryptParams(algo, nonce, AAD);\n return {\n // keyLength,\n encrypt(plaintext: Uint8Array) {\n abytes(plaintext);\n return utils.encrypt(key, keyParams, cryptParams, plaintext);\n },\n decrypt(ciphertext: Uint8Array) {\n abytes(ciphertext);\n return utils.decrypt(key, keyParams, cryptParams, ciphertext);\n },\n };\n };\n}\n\nexport const cbc = generate(mode.CBC);\nexport const ctr = generate(mode.CTR);\nexport const gcm = generate(mode.GCM);\n\n// // Type tests\n// import { siv, gcm, ctr, ecb, cbc } from '../aes.js';\n// import { xsalsa20poly1305 } from '../salsa.js';\n// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.js';\n\n// const wsiv = managedNonce(siv);\n// const wgcm = managedNonce(gcm);\n// const wctr = managedNonce(ctr);\n// const wcbc = managedNonce(cbc);\n// const wsalsapoly = managedNonce(xsalsa20poly1305);\n// const wchacha = managedNonce(chacha20poly1305);\n// const wxchacha = managedNonce(xchacha20poly1305);\n\n// // should fail\n// const wcbc2 = managedNonce(managedNonce(cbc));\n// const wctr = managedNonce(ctr);\n","import { Buffer } from 'node:buffer';\nimport { decoder } from '../lib/buffer_utils.js';\nfunction normalize(input) {\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n return encoded;\n}\nconst encode = (input) => Buffer.from(input).toString('base64url');\nexport const decodeBase64 = (input) => new Uint8Array(Buffer.from(input, 'base64'));\nexport const encodeBase64 = (input) => Buffer.from(input).toString('base64');\nexport { encode };\nexport const decode = (input) => new Uint8Array(Buffer.from(normalize(input), 'base64url'));\n","import digest from '../runtime/digest.js';\nexport const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers) {\n buf.set(buffer, i);\n i += buffer.length;\n }\n return buf;\n}\nexport function p2s(alg, p2sInput) {\n return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function lengthAndInput(input) {\n return concat(uint32be(input.length), input);\n}\nexport async function concatKdf(secret, bits, value) {\n const iterations = Math.ceil((bits >> 3) / 32);\n const res = new Uint8Array(iterations * 32);\n for (let iter = 0; iter < iterations; iter++) {\n const buf = new Uint8Array(4 + secret.length + value.length);\n buf.set(uint32be(iter + 1));\n buf.set(secret, 4);\n buf.set(value, 4 + secret.length);\n res.set(await digest('sha256', buf), iter * 32);\n }\n return res.slice(0, bits >> 3);\n}\n","export class JOSEError extends Error {\n static code = 'ERR_JOSE_GENERIC';\n code = 'ERR_JOSE_GENERIC';\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JWTExpired extends JOSEError {\n static code = 'ERR_JWT_EXPIRED';\n code = 'ERR_JWT_EXPIRED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n static code = 'ERR_JOSE_NOT_SUPPORTED';\n code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n static code = 'ERR_JWE_DECRYPTION_FAILED';\n code = 'ERR_JWE_DECRYPTION_FAILED';\n constructor(message = 'decryption operation failed', options) {\n super(message, options);\n }\n}\nexport class JWEInvalid extends JOSEError {\n static code = 'ERR_JWE_INVALID';\n code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n static code = 'ERR_JWS_INVALID';\n code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n static code = 'ERR_JWT_INVALID';\n code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n static code = 'ERR_JWK_INVALID';\n code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n static code = 'ERR_JWKS_INVALID';\n code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n static code = 'ERR_JWKS_NO_MATCHING_KEY';\n code = 'ERR_JWKS_NO_MATCHING_KEY';\n constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator];\n static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSTimeout extends JOSEError {\n static code = 'ERR_JWKS_TIMEOUT';\n code = 'ERR_JWKS_TIMEOUT';\n constructor(message = 'request timed out', options) {\n super(message, options);\n }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n constructor(message = 'signature verification failed', options) {\n super(message, options);\n }\n}\n","import * as util from 'node:util';\nexport default (obj) => util.types.isKeyObject(obj);\n","import * as crypto from 'node:crypto';\nimport * as util from 'node:util';\nconst webcrypto = crypto.webcrypto;\nexport default webcrypto;\nexport const isCryptoKey = (key) => util.types.isCryptoKey(key);\n","function unusable(name, prop = 'algorithm.name') {\n return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\n}\nfunction isAlgorithm(algorithm, name) {\n return algorithm.name === name;\n}\nfunction getHashLength(hash) {\n return parseInt(hash.name.slice(4), 10);\n}\nfunction getNamedCurve(alg) {\n switch (alg) {\n case 'ES256':\n return 'P-256';\n case 'ES384':\n return 'P-384';\n case 'ES512':\n return 'P-521';\n default:\n throw new Error('unreachable');\n }\n}\nfunction checkUsage(key, usages) {\n if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {\n let msg = 'CryptoKey does not support this operation, its usages must include ';\n if (usages.length > 2) {\n const last = usages.pop();\n msg += `one of ${usages.join(', ')}, or ${last}.`;\n }\n else if (usages.length === 2) {\n msg += `one of ${usages[0]} or ${usages[1]}.`;\n }\n else {\n msg += `${usages[0]}.`;\n }\n throw new TypeError(msg);\n }\n}\nexport function checkSigCryptoKey(key, alg, ...usages) {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512': {\n if (!isAlgorithm(key.algorithm, 'HMAC'))\n throw unusable('HMAC');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'RS256':\n case 'RS384':\n case 'RS512': {\n if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n throw unusable('RSASSA-PKCS1-v1_5');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'PS256':\n case 'PS384':\n case 'PS512': {\n if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n throw unusable('RSA-PSS');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'EdDSA': {\n if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {\n throw unusable('Ed25519 or Ed448');\n }\n break;\n }\n case 'Ed25519': {\n if (!isAlgorithm(key.algorithm, 'Ed25519'))\n throw unusable('Ed25519');\n break;\n }\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n if (!isAlgorithm(key.algorithm, 'ECDSA'))\n throw unusable('ECDSA');\n const expected = getNamedCurve(alg);\n const actual = key.algorithm.namedCurve;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.namedCurve');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usages);\n}\nexport function checkEncCryptoKey(key, alg, ...usages) {\n switch (alg) {\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM': {\n if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n throw unusable('AES-GCM');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n if (!isAlgorithm(key.algorithm, 'AES-KW'))\n throw unusable('AES-KW');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'ECDH': {\n switch (key.algorithm.name) {\n case 'ECDH':\n case 'X25519':\n case 'X448':\n break;\n default:\n throw unusable('ECDH, X25519, or X448');\n }\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW':\n if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n throw unusable('PBKDF2');\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n throw unusable('RSA-OAEP');\n const expected = parseInt(alg.slice(9), 10) || 1;\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usages);\n}\n","function message(msg, actual, ...types) {\n types = types.filter(Boolean);\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(', ')}, or ${last}.`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}.`;\n }\n else {\n msg += `of type ${types[0]}.`;\n }\n if (actual == null) {\n msg += ` Received ${actual}`;\n }\n else if (typeof actual === 'function' && actual.name) {\n msg += ` Received function ${actual.name}`;\n }\n else if (typeof actual === 'object' && actual != null) {\n if (actual.constructor?.name) {\n msg += ` Received an instance of ${actual.constructor.name}`;\n }\n }\n return msg;\n}\nexport default (actual, ...types) => {\n return message('Key must be ', actual, ...types);\n};\nexport function withAlg(alg, actual, ...types) {\n return message(`Key for the ${alg} algorithm must be `, actual, ...types);\n}\n","import webcrypto, { isCryptoKey } from './webcrypto.js';\nimport isKeyObject from './is_key_object.js';\nexport default (key) => isKeyObject(key) || isCryptoKey(key);\nconst types = ['KeyObject'];\nif (globalThis.CryptoKey || webcrypto?.CryptoKey) {\n types.push('CryptoKey');\n}\nexport { types };\n","const isDisjoint = (...headers) => {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n};\nexport default isDisjoint;\n","function isObjectLike(value) {\n return typeof value === 'object' && value !== null;\n}\nexport default function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\n","import { KeyObject } from 'node:crypto';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isCryptoKey } from './webcrypto.js';\nimport isKeyObject from './is_key_object.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nimport { isJWK } from '../lib/is_jwk.js';\nexport const weakMap = new WeakMap();\nconst namedCurveToJOSE = (namedCurve) => {\n switch (namedCurve) {\n case 'prime256v1':\n return 'P-256';\n case 'secp384r1':\n return 'P-384';\n case 'secp521r1':\n return 'P-521';\n case 'secp256k1':\n return 'secp256k1';\n default:\n throw new JOSENotSupported('Unsupported key curve for this operation');\n }\n};\nconst getNamedCurve = (kee, raw) => {\n let key;\n if (isCryptoKey(kee)) {\n key = KeyObject.from(kee);\n }\n else if (isKeyObject(kee)) {\n key = kee;\n }\n else if (isJWK(kee)) {\n return kee.crv;\n }\n else {\n throw new TypeError(invalidKeyInput(kee, ...types));\n }\n if (key.type === 'secret') {\n throw new TypeError('only \"private\" or \"public\" type keys can be used for this operation');\n }\n switch (key.asymmetricKeyType) {\n case 'ed25519':\n case 'ed448':\n return `Ed${key.asymmetricKeyType.slice(2)}`;\n case 'x25519':\n case 'x448':\n return `X${key.asymmetricKeyType.slice(1)}`;\n case 'ec': {\n const namedCurve = key.asymmetricKeyDetails.namedCurve;\n if (raw) {\n return namedCurve;\n }\n return namedCurveToJOSE(namedCurve);\n }\n default:\n throw new TypeError('Invalid asymmetric key type for this operation');\n }\n};\nexport default getNamedCurve;\n","import isObject from './is_object.js';\nexport function isJWK(key) {\n return isObject(key) && typeof key.kty === 'string';\n}\nexport function isPrivateJWK(key) {\n return key.kty !== 'oct' && typeof key.d === 'string';\n}\nexport function isPublicJWK(key) {\n return key.kty !== 'oct' && typeof key.d === 'undefined';\n}\nexport function isSecretJWK(key) {\n return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string';\n}\n","import { KeyObject } from 'node:crypto';\nexport default (key, alg) => {\n let modulusLength;\n try {\n if (key instanceof KeyObject) {\n modulusLength = key.asymmetricKeyDetails?.modulusLength;\n }\n else {\n modulusLength = Buffer.from(key.n, 'base64url').byteLength << 3;\n }\n }\n catch { }\n if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n }\n};\n","import { createPrivateKey, createPublicKey } from 'node:crypto';\nconst parse = (key) => {\n if (key.d) {\n return createPrivateKey({ format: 'jwk', key });\n }\n return createPublicKey({ format: 'jwk', key });\n};\nexport default parse;\n","import { decode as decodeBase64URL } from '../runtime/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.js';\nimport asKeyObject from '../runtime/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport isObject from '../lib/is_object.js';\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg) {\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n alg ||= jwk.alg;\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if ('oth' in jwk && jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n case 'EC':\n case 'OKP':\n return asKeyObject({ ...jwk, alg });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n","import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport isKeyLike, { types } from '../runtime/is_key_like.js';\nimport * as jwk from './is_jwk.js';\nconst tag = (key) => key?.[Symbol.toStringTag];\nconst jwkMatchesOp = (alg, key, usage) => {\n if (key.use !== undefined && key.use !== 'sig') {\n throw new TypeError('Invalid key for this operation, when present its use must be sig');\n }\n if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) {\n throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`);\n }\n if (key.alg !== undefined && key.alg !== alg) {\n throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`);\n }\n return true;\n};\nconst symmetricTypeCheck = (alg, key, usage, allowJwk) => {\n if (key instanceof Uint8Array)\n return;\n if (allowJwk && jwk.isJWK(key)) {\n if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present`);\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null));\n }\n if (key.type !== 'secret') {\n throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type \"secret\"`);\n }\n};\nconst asymmetricTypeCheck = (alg, key, usage, allowJwk) => {\n if (allowJwk && jwk.isJWK(key)) {\n switch (usage) {\n case 'sign':\n if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation be a private JWK`);\n case 'verify':\n if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation be a public JWK`);\n }\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, ...types, allowJwk ? 'JSON Web Key' : null));\n }\n if (key.type === 'secret') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type \"secret\"`);\n }\n if (usage === 'sign' && key.type === 'public') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type \"private\"`);\n }\n if (usage === 'decrypt' && key.type === 'public') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type \"private\"`);\n }\n if (key.algorithm && usage === 'verify' && key.type === 'private') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type \"public\"`);\n }\n if (key.algorithm && usage === 'encrypt' && key.type === 'private') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type \"public\"`);\n }\n};\nfunction checkKeyType(allowJwk, alg, key, usage) {\n const symmetric = alg.startsWith('HS') ||\n alg === 'dir' ||\n alg.startsWith('PBES2') ||\n /^A\\d{3}(?:GCM)?KW$/.test(alg);\n if (symmetric) {\n symmetricTypeCheck(alg, key, usage, allowJwk);\n }\n else {\n asymmetricTypeCheck(alg, key, usage, allowJwk);\n }\n}\nexport default checkKeyType.bind(undefined, false);\nexport const checkKeyTypeWithJwk = checkKeyType.bind(undefined, true);\n","import { JOSENotSupported } from '../util/errors.js';\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n }\n if (!protectedHeader || protectedHeader.crit === undefined) {\n return new Set();\n }\n if (!Array.isArray(protectedHeader.crit) ||\n protectedHeader.crit.length === 0 ||\n protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n }\n let recognized;\n if (recognizedOption !== undefined) {\n recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n }\n else {\n recognized = recognizedDefault;\n }\n for (const parameter of protectedHeader.crit) {\n if (!recognized.has(parameter)) {\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n }\n if (joseHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n }\n if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n }\n return new Set(protectedHeader.crit);\n}\nexport default validateCrit;\n","const validateAlgorithms = (option, algorithms) => {\n if (algorithms !== undefined &&\n (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n }\n if (!algorithms) {\n return undefined;\n }\n return new Set(algorithms);\n};\nexport default validateAlgorithms;\n","import * as crypto from 'node:crypto';\nimport { promisify } from 'node:util';\nimport nodeDigest from './dsa_digest.js';\nimport nodeKey from './node_key.js';\nimport sign from './sign.js';\nimport getVerifyKey from './get_sign_verify_key.js';\nconst oneShotVerify = promisify(crypto.verify);\nconst verify = async (alg, key, signature, data) => {\n const k = getVerifyKey(alg, key, 'verify');\n if (alg.startsWith('HS')) {\n const expected = await sign(alg, k, data);\n const actual = signature;\n try {\n return crypto.timingSafeEqual(actual, expected);\n }\n catch {\n return false;\n }\n }\n const algorithm = nodeDigest(alg);\n const keyInput = nodeKey(alg, k);\n try {\n return await oneShotVerify(algorithm, data, keyInput, signature);\n }\n catch {\n return false;\n }\n};\nexport default verify;\n","import { JOSENotSupported } from '../util/errors.js';\nexport default function dsaDigest(alg) {\n switch (alg) {\n case 'PS256':\n case 'RS256':\n case 'ES256':\n case 'ES256K':\n return 'sha256';\n case 'PS384':\n case 'RS384':\n case 'ES384':\n return 'sha384';\n case 'PS512':\n case 'RS512':\n case 'ES512':\n return 'sha512';\n case 'Ed25519':\n case 'EdDSA':\n return undefined;\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\n","import { constants, KeyObject } from 'node:crypto';\nimport getNamedCurve from './get_named_curve.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport checkKeyLength from './check_key_length.js';\nconst ecCurveAlgMap = new Map([\n ['ES256', 'P-256'],\n ['ES256K', 'secp256k1'],\n ['ES384', 'P-384'],\n ['ES512', 'P-521'],\n]);\nexport default function keyForCrypto(alg, key) {\n let asymmetricKeyType;\n let asymmetricKeyDetails;\n let isJWK;\n if (key instanceof KeyObject) {\n asymmetricKeyType = key.asymmetricKeyType;\n asymmetricKeyDetails = key.asymmetricKeyDetails;\n }\n else {\n isJWK = true;\n switch (key.kty) {\n case 'RSA':\n asymmetricKeyType = 'rsa';\n break;\n case 'EC':\n asymmetricKeyType = 'ec';\n break;\n case 'OKP': {\n if (key.crv === 'Ed25519') {\n asymmetricKeyType = 'ed25519';\n break;\n }\n if (key.crv === 'Ed448') {\n asymmetricKeyType = 'ed448';\n break;\n }\n throw new TypeError('Invalid key for this operation, its crv must be Ed25519 or Ed448');\n }\n default:\n throw new TypeError('Invalid key for this operation, its kty must be RSA, OKP, or EC');\n }\n }\n let options;\n switch (alg) {\n case 'Ed25519':\n if (asymmetricKeyType !== 'ed25519') {\n throw new TypeError(`Invalid key for this operation, its asymmetricKeyType must be ed25519`);\n }\n break;\n case 'EdDSA':\n if (!['ed25519', 'ed448'].includes(asymmetricKeyType)) {\n throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448');\n }\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n if (asymmetricKeyType !== 'rsa') {\n throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');\n }\n checkKeyLength(key, alg);\n break;\n case 'PS256':\n case 'PS384':\n case 'PS512':\n if (asymmetricKeyType === 'rsa-pss') {\n const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = asymmetricKeyDetails;\n const length = parseInt(alg.slice(-3), 10);\n if (hashAlgorithm !== undefined &&\n (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) {\n throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of \"alg\" ${alg}`);\n }\n if (saltLength !== undefined && saltLength > length >> 3) {\n throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of \"alg\" ${alg}`);\n }\n }\n else if (asymmetricKeyType !== 'rsa') {\n throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss');\n }\n checkKeyLength(key, alg);\n options = {\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST,\n };\n break;\n case 'ES256':\n case 'ES256K':\n case 'ES384':\n case 'ES512': {\n if (asymmetricKeyType !== 'ec') {\n throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec');\n }\n const actual = getNamedCurve(key);\n const expected = ecCurveAlgMap.get(alg);\n if (actual !== expected) {\n throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`);\n }\n options = { dsaEncoding: 'ieee-p1363' };\n break;\n }\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n if (isJWK) {\n return { format: 'jwk', key, ...options };\n }\n return options ? { ...options, key } : key;\n}\n","import * as crypto from 'node:crypto';\nimport { promisify } from 'node:util';\nimport nodeDigest from './dsa_digest.js';\nimport hmacDigest from './hmac_digest.js';\nimport nodeKey from './node_key.js';\nimport getSignKey from './get_sign_verify_key.js';\nconst oneShotSign = promisify(crypto.sign);\nconst sign = async (alg, key, data) => {\n const k = getSignKey(alg, key, 'sign');\n if (alg.startsWith('HS')) {\n const hmac = crypto.createHmac(hmacDigest(alg), k);\n hmac.update(data);\n return hmac.digest();\n }\n return oneShotSign(nodeDigest(alg), data, nodeKey(alg, k));\n};\nexport default sign;\n","import { JOSENotSupported } from '../util/errors.js';\nexport default function hmacDigest(alg) {\n switch (alg) {\n case 'HS256':\n return 'sha256';\n case 'HS384':\n return 'sha384';\n case 'HS512':\n return 'sha512';\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\n","import { KeyObject, createSecretKey } from 'node:crypto';\nimport { isCryptoKey } from './webcrypto.js';\nimport { checkSigCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nimport * as jwk from '../lib/is_jwk.js';\nexport default function getSignVerifyKey(alg, key, usage) {\n if (key instanceof Uint8Array) {\n if (!alg.startsWith('HS')) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n return createSecretKey(key);\n }\n if (key instanceof KeyObject) {\n return key;\n }\n if (isCryptoKey(key)) {\n checkSigCryptoKey(key, alg, usage);\n return KeyObject.from(key);\n }\n if (jwk.isJWK(key)) {\n if (alg.startsWith('HS')) {\n return createSecretKey(Buffer.from(key.k, 'base64url'));\n }\n return key;\n }\n throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array', 'JSON Web Key'));\n}\n","import { decode as base64url } from '../../runtime/base64url.js';\nimport verify from '../../runtime/verify.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder } from '../../lib/buffer_utils.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport isObject from '../../lib/is_object.js';\nimport { checkKeyTypeWithJwk } from '../../lib/check_key_type.js';\nimport validateCrit from '../../lib/validate_crit.js';\nimport validateAlgorithms from '../../lib/validate_algorithms.js';\nimport { isJWK } from '../../lib/is_jwk.js';\nimport { importJWK } from '../../key/import.js';\nexport async function flattenedVerify(jws, key, options) {\n if (!isObject(jws)) {\n throw new JWSInvalid('Flattened JWS must be an object');\n }\n if (jws.protected === undefined && jws.header === undefined) {\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n }\n if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n throw new JWSInvalid('JWS Protected Header incorrect type');\n }\n if (jws.payload === undefined) {\n throw new JWSInvalid('JWS Payload missing');\n }\n if (typeof jws.signature !== 'string') {\n throw new JWSInvalid('JWS Signature missing or incorrect type');\n }\n if (jws.header !== undefined && !isObject(jws.header)) {\n throw new JWSInvalid('JWS Unprotected Header incorrect type');\n }\n let parsedProt = {};\n if (jws.protected) {\n try {\n const protectedHeader = base64url(jws.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch {\n throw new JWSInvalid('JWS Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jws.header)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jws.header,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = parsedProt.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n if (algorithms && !algorithms.has(alg)) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n }\n if (b64) {\n if (typeof jws.payload !== 'string') {\n throw new JWSInvalid('JWS Payload must be a string');\n }\n }\n else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jws);\n resolvedKey = true;\n checkKeyTypeWithJwk(alg, key, 'verify');\n if (isJWK(key)) {\n key = await importJWK(key, alg);\n }\n }\n else {\n checkKeyTypeWithJwk(alg, key, 'verify');\n }\n const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);\n let signature;\n try {\n signature = base64url(jws.signature);\n }\n catch {\n throw new JWSInvalid('Failed to base64url decode the signature');\n }\n const verified = await verify(alg, key, signature, data);\n if (!verified) {\n throw new JWSSignatureVerificationFailed();\n }\n let payload;\n if (b64) {\n try {\n payload = base64url(jws.payload);\n }\n catch {\n throw new JWSInvalid('Failed to base64url decode the payload');\n }\n }\n else if (typeof jws.payload === 'string') {\n payload = encoder.encode(jws.payload);\n }\n else {\n payload = jws.payload;\n }\n const result = { payload };\n if (jws.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jws.header !== undefined) {\n result.unprotectedHeader = jws.header;\n }\n if (resolvedKey) {\n return { ...result, key };\n }\n return result;\n}\n","import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n if (jws instanceof Uint8Array) {\n jws = decoder.decode(jws);\n }\n if (typeof jws !== 'string') {\n throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n if (length !== 3) {\n throw new JWSInvalid('Invalid Compact JWS');\n }\n const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n","export default (date) => Math.floor(date.getTime() / 1000);\n","const minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;\nexport default (str) => {\n const matched = REGEX.exec(str);\n if (!matched || (matched[4] && matched[1])) {\n throw new TypeError('Invalid time period format');\n }\n const value = parseFloat(matched[2]);\n const unit = matched[3].toLowerCase();\n let numericDate;\n switch (unit) {\n case 'sec':\n case 'secs':\n case 'second':\n case 'seconds':\n case 's':\n numericDate = Math.round(value);\n break;\n case 'minute':\n case 'minutes':\n case 'min':\n case 'mins':\n case 'm':\n numericDate = Math.round(value * minute);\n break;\n case 'hour':\n case 'hours':\n case 'hr':\n case 'hrs':\n case 'h':\n numericDate = Math.round(value * hour);\n break;\n case 'day':\n case 'days':\n case 'd':\n numericDate = Math.round(value * day);\n break;\n case 'week':\n case 'weeks':\n case 'w':\n numericDate = Math.round(value * week);\n break;\n default:\n numericDate = Math.round(value * year);\n break;\n }\n if (matched[1] === '-' || matched[4] === 'ago') {\n return -numericDate;\n }\n return numericDate;\n};\n","import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { decoder } from './buffer_utils.js';\nimport epoch from './epoch.js';\nimport secs from './secs.js';\nimport isObject from './is_object.js';\nconst normalizeTyp = (value) => value.toLowerCase().replace(/^application\\//, '');\nconst checkAudiencePresence = (audPayload, audOption) => {\n if (typeof audPayload === 'string') {\n return audOption.includes(audPayload);\n }\n if (Array.isArray(audPayload)) {\n return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n }\n return false;\n};\nexport default (protectedHeader, encodedPayload, options = {}) => {\n let payload;\n try {\n payload = JSON.parse(decoder.decode(encodedPayload));\n }\n catch {\n }\n if (!isObject(payload)) {\n throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n }\n const { typ } = options;\n if (typ &&\n (typeof protectedHeader.typ !== 'string' ||\n normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, 'typ', 'check_failed');\n }\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;\n const presenceCheck = [...requiredClaims];\n if (maxTokenAge !== undefined)\n presenceCheck.push('iat');\n if (audience !== undefined)\n presenceCheck.push('aud');\n if (subject !== undefined)\n presenceCheck.push('sub');\n if (issuer !== undefined)\n presenceCheck.push('iss');\n for (const claim of new Set(presenceCheck.reverse())) {\n if (!(claim in payload)) {\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, 'missing');\n }\n }\n if (issuer &&\n !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', payload, 'iss', 'check_failed');\n }\n if (subject && payload.sub !== subject) {\n throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', payload, 'sub', 'check_failed');\n }\n if (audience &&\n !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', payload, 'aud', 'check_failed');\n }\n let tolerance;\n switch (typeof options.clockTolerance) {\n case 'string':\n tolerance = secs(options.clockTolerance);\n break;\n case 'number':\n tolerance = options.clockTolerance;\n break;\n case 'undefined':\n tolerance = 0;\n break;\n default:\n throw new TypeError('Invalid clockTolerance option type');\n }\n const { currentDate } = options;\n const now = epoch(currentDate || new Date());\n if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {\n throw new JWTClaimValidationFailed('\"iat\" claim must be a number', payload, 'iat', 'invalid');\n }\n if (payload.nbf !== undefined) {\n if (typeof payload.nbf !== 'number') {\n throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', payload, 'nbf', 'invalid');\n }\n if (payload.nbf > now + tolerance) {\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, 'nbf', 'check_failed');\n }\n }\n if (payload.exp !== undefined) {\n if (typeof payload.exp !== 'number') {\n throw new JWTClaimValidationFailed('\"exp\" claim must be a number', payload, 'exp', 'invalid');\n }\n if (payload.exp <= now - tolerance) {\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, 'exp', 'check_failed');\n }\n }\n if (maxTokenAge) {\n const age = now - payload.iat;\n const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);\n if (age - tolerance > max) {\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');\n }\n if (age < 0 - tolerance) {\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');\n }\n }\n return payload;\n};\n","import { compactVerify } from '../jws/compact/verify.js';\nimport jwtPayload from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n const verified = await compactVerify(jwt, key, options);\n if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n const payload = jwtPayload(verified.protectedHeader, verified.payload, options);\n const result = { payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n","import { encode as base64url } from '../../runtime/base64url.js';\nimport sign from '../../runtime/sign.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { encoder, decoder, concat } from '../../lib/buffer_utils.js';\nimport { checkKeyTypeWithJwk } from '../../lib/check_key_type.js';\nimport validateCrit from '../../lib/validate_crit.js';\nexport class FlattenedSign {\n _payload;\n _protectedHeader;\n _unprotectedHeader;\n constructor(payload) {\n if (!(payload instanceof Uint8Array)) {\n throw new TypeError('payload must be an instance of Uint8Array');\n }\n this._payload = payload;\n }\n setProtectedHeader(protectedHeader) {\n if (this._protectedHeader) {\n throw new TypeError('setProtectedHeader can only be called once');\n }\n this._protectedHeader = protectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n if (this._unprotectedHeader) {\n throw new TypeError('setUnprotectedHeader can only be called once');\n }\n this._unprotectedHeader = unprotectedHeader;\n return this;\n }\n async sign(key, options) {\n if (!this._protectedHeader && !this._unprotectedHeader) {\n throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');\n }\n if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this._protectedHeader,\n ...this._unprotectedHeader,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = this._protectedHeader.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n checkKeyTypeWithJwk(alg, key, 'sign');\n let payload = this._payload;\n if (b64) {\n payload = encoder.encode(base64url(payload));\n }\n let protectedHeader;\n if (this._protectedHeader) {\n protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));\n }\n else {\n protectedHeader = encoder.encode('');\n }\n const data = concat(protectedHeader, encoder.encode('.'), payload);\n const signature = await sign(alg, key, data);\n const jws = {\n signature: base64url(signature),\n payload: '',\n };\n if (b64) {\n jws.payload = decoder.decode(payload);\n }\n if (this._unprotectedHeader) {\n jws.header = this._unprotectedHeader;\n }\n if (this._protectedHeader) {\n jws.protected = decoder.decode(protectedHeader);\n }\n return jws;\n }\n}\n","import { FlattenedSign } from '../flattened/sign.js';\nexport class CompactSign {\n _flattened;\n constructor(payload) {\n this._flattened = new FlattenedSign(payload);\n }\n setProtectedHeader(protectedHeader) {\n this._flattened.setProtectedHeader(protectedHeader);\n return this;\n }\n async sign(key, options) {\n const jws = await this._flattened.sign(key, options);\n if (jws.payload === undefined) {\n throw new TypeError('use the flattened module for creating JWS with b64: false');\n }\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n }\n}\n","import epoch from '../lib/epoch.js';\nimport isObject from '../lib/is_object.js';\nimport secs from '../lib/secs.js';\nfunction validateInput(label, input) {\n if (!Number.isFinite(input)) {\n throw new TypeError(`Invalid ${label} input`);\n }\n return input;\n}\nexport class ProduceJWT {\n _payload;\n constructor(payload = {}) {\n if (!isObject(payload)) {\n throw new TypeError('JWT Claims Set MUST be an object');\n }\n this._payload = payload;\n }\n setIssuer(issuer) {\n this._payload = { ...this._payload, iss: issuer };\n return this;\n }\n setSubject(subject) {\n this._payload = { ...this._payload, sub: subject };\n return this;\n }\n setAudience(audience) {\n this._payload = { ...this._payload, aud: audience };\n return this;\n }\n setJti(jwtId) {\n this._payload = { ...this._payload, jti: jwtId };\n return this;\n }\n setNotBefore(input) {\n if (typeof input === 'number') {\n this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };\n }\n else if (input instanceof Date) {\n this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) };\n }\n else {\n this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) };\n }\n return this;\n }\n setExpirationTime(input) {\n if (typeof input === 'number') {\n this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };\n }\n else if (input instanceof Date) {\n this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) };\n }\n else {\n this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) };\n }\n return this;\n }\n setIssuedAt(input) {\n if (typeof input === 'undefined') {\n this._payload = { ...this._payload, iat: epoch(new Date()) };\n }\n else if (input instanceof Date) {\n this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) };\n }\n else if (typeof input === 'string') {\n this._payload = {\n ...this._payload,\n iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)),\n };\n }\n else {\n this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };\n }\n return this;\n }\n}\n","import { CompactSign } from '../jws/compact/sign.js';\nimport { JWTInvalid } from '../util/errors.js';\nimport { encoder } from '../lib/buffer_utils.js';\nimport { ProduceJWT } from './produce.js';\nexport class SignJWT extends ProduceJWT {\n _protectedHeader;\n setProtectedHeader(protectedHeader) {\n this._protectedHeader = protectedHeader;\n return this;\n }\n async sign(key, options) {\n const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));\n sig.setProtectedHeader(this._protectedHeader);\n if (Array.isArray(this._protectedHeader?.crit) &&\n this._protectedHeader.crit.includes('b64') &&\n this._protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n return sig.sign(key, options);\n }\n}\n","import { importJWK } from '../key/import.js';\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';\nimport isObject from '../lib/is_object.js';\nfunction getKtyFromAlg(alg) {\n switch (typeof alg === 'string' && alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n return 'RSA';\n case 'ES':\n return 'EC';\n case 'Ed':\n return 'OKP';\n default:\n throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n }\n}\nfunction isJWKSLike(jwks) {\n return (jwks &&\n typeof jwks === 'object' &&\n Array.isArray(jwks.keys) &&\n jwks.keys.every(isJWKLike));\n}\nfunction isJWKLike(key) {\n return isObject(key);\n}\nfunction clone(obj) {\n if (typeof structuredClone === 'function') {\n return structuredClone(obj);\n }\n return JSON.parse(JSON.stringify(obj));\n}\nclass LocalJWKSet {\n _jwks;\n _cached = new WeakMap();\n constructor(jwks) {\n if (!isJWKSLike(jwks)) {\n throw new JWKSInvalid('JSON Web Key Set malformed');\n }\n this._jwks = clone(jwks);\n }\n async getKey(protectedHeader, token) {\n const { alg, kid } = { ...protectedHeader, ...token?.header };\n const kty = getKtyFromAlg(alg);\n const candidates = this._jwks.keys.filter((jwk) => {\n let candidate = kty === jwk.kty;\n if (candidate && typeof kid === 'string') {\n candidate = kid === jwk.kid;\n }\n if (candidate && typeof jwk.alg === 'string') {\n candidate = alg === jwk.alg;\n }\n if (candidate && typeof jwk.use === 'string') {\n candidate = jwk.use === 'sig';\n }\n if (candidate && Array.isArray(jwk.key_ops)) {\n candidate = jwk.key_ops.includes('verify');\n }\n if (candidate) {\n switch (alg) {\n case 'ES256':\n candidate = jwk.crv === 'P-256';\n break;\n case 'ES256K':\n candidate = jwk.crv === 'secp256k1';\n break;\n case 'ES384':\n candidate = jwk.crv === 'P-384';\n break;\n case 'ES512':\n candidate = jwk.crv === 'P-521';\n break;\n case 'Ed25519':\n candidate = jwk.crv === 'Ed25519';\n break;\n case 'EdDSA':\n candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448';\n break;\n }\n }\n return candidate;\n });\n const { 0: jwk, length } = candidates;\n if (length === 0) {\n throw new JWKSNoMatchingKey();\n }\n if (length !== 1) {\n const error = new JWKSMultipleMatchingKeys();\n const { _cached } = this;\n error[Symbol.asyncIterator] = async function* () {\n for (const jwk of candidates) {\n try {\n yield await importWithAlgCache(_cached, jwk, alg);\n }\n catch { }\n }\n };\n throw error;\n }\n return importWithAlgCache(this._cached, jwk, alg);\n }\n}\nasync function importWithAlgCache(cache, jwk, alg) {\n const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);\n if (cached[alg] === undefined) {\n const key = await importJWK({ ...jwk, ext: true }, alg);\n if (key instanceof Uint8Array || key.type !== 'public') {\n throw new JWKSInvalid('JSON Web Key Set members must be public keys');\n }\n cached[alg] = key;\n }\n return cached[alg];\n}\nexport function createLocalJWKSet(jwks) {\n const set = new LocalJWKSet(jwks);\n const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(localJWKSet, {\n jwks: {\n value: () => clone(set._jwks),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n });\n return localJWKSet;\n}\n","import * as http from 'node:http';\nimport * as https from 'node:https';\nimport { once } from 'node:events';\nimport { JOSEError, JWKSTimeout } from '../util/errors.js';\nimport { concat, decoder } from '../lib/buffer_utils.js';\nconst fetchJwks = async (url, timeout, options) => {\n let get;\n switch (url.protocol) {\n case 'https:':\n get = https.get;\n break;\n case 'http:':\n get = http.get;\n break;\n default:\n throw new TypeError('Unsupported URL protocol.');\n }\n const { agent, headers } = options;\n const req = get(url.href, {\n agent,\n timeout,\n headers,\n });\n const [response] = (await Promise.race([once(req, 'response'), once(req, 'timeout')]));\n if (!response) {\n req.destroy();\n throw new JWKSTimeout();\n }\n if (response.statusCode !== 200) {\n throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');\n }\n const parts = [];\n for await (const part of response) {\n parts.push(part);\n }\n try {\n return JSON.parse(decoder.decode(concat(...parts)));\n }\n catch {\n throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');\n }\n};\nexport default fetchJwks;\n","import fetchJwks from '../runtime/fetch_jwks.js';\nimport { JWKSNoMatchingKey } from '../util/errors.js';\nimport { createLocalJWKSet } from './local.js';\nimport isObject from '../lib/is_object.js';\nfunction isCloudflareWorkers() {\n return (typeof WebSocketPair !== 'undefined' ||\n (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||\n (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));\n}\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'jose';\n const VERSION = 'v5.10.0';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nexport const jwksCache = Symbol();\nfunction isFreshJwksCache(input, cacheMaxAge) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {\n return false;\n }\n if (!('jwks' in input) ||\n !isObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isObject)) {\n return false;\n }\n return true;\n}\nclass RemoteJWKSet {\n _url;\n _timeoutDuration;\n _cooldownDuration;\n _cacheMaxAge;\n _jwksTimestamp;\n _pendingFetch;\n _options;\n _local;\n _cache;\n constructor(url, options) {\n if (!(url instanceof URL)) {\n throw new TypeError('url must be an instance of URL');\n }\n this._url = new URL(url.href);\n this._options = { agent: options?.agent, headers: options?.headers };\n this._timeoutDuration =\n typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;\n this._cooldownDuration =\n typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;\n this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;\n if (options?.[jwksCache] !== undefined) {\n this._cache = options?.[jwksCache];\n if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) {\n this._jwksTimestamp = this._cache.uat;\n this._local = createLocalJWKSet(this._cache.jwks);\n }\n }\n }\n coolingDown() {\n return typeof this._jwksTimestamp === 'number'\n ? Date.now() < this._jwksTimestamp + this._cooldownDuration\n : false;\n }\n fresh() {\n return typeof this._jwksTimestamp === 'number'\n ? Date.now() < this._jwksTimestamp + this._cacheMaxAge\n : false;\n }\n async getKey(protectedHeader, token) {\n if (!this._local || !this.fresh()) {\n await this.reload();\n }\n try {\n return await this._local(protectedHeader, token);\n }\n catch (err) {\n if (err instanceof JWKSNoMatchingKey) {\n if (this.coolingDown() === false) {\n await this.reload();\n return this._local(protectedHeader, token);\n }\n }\n throw err;\n }\n }\n async reload() {\n if (this._pendingFetch && isCloudflareWorkers()) {\n this._pendingFetch = undefined;\n }\n const headers = new Headers(this._options.headers);\n if (USER_AGENT && !headers.has('User-Agent')) {\n headers.set('User-Agent', USER_AGENT);\n this._options.headers = Object.fromEntries(headers.entries());\n }\n this._pendingFetch ||= fetchJwks(this._url, this._timeoutDuration, this._options)\n .then((json) => {\n this._local = createLocalJWKSet(json);\n if (this._cache) {\n this._cache.uat = Date.now();\n this._cache.jwks = json;\n }\n this._jwksTimestamp = Date.now();\n this._pendingFetch = undefined;\n })\n .catch((err) => {\n this._pendingFetch = undefined;\n throw err;\n });\n await this._pendingFetch;\n }\n}\nexport function createRemoteJWKSet(url, options) {\n const set = new RemoteJWKSet(url, options);\n const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(remoteJWKSet, {\n coolingDown: {\n get: () => set.coolingDown(),\n enumerable: true,\n configurable: false,\n },\n fresh: {\n get: () => set.fresh(),\n enumerable: true,\n configurable: false,\n },\n reload: {\n value: () => set.reload(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n reloading: {\n get: () => !!set._pendingFetch,\n enumerable: true,\n configurable: false,\n },\n jwks: {\n value: () => set._local?.jwks(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n });\n return remoteJWKSet;\n}\nexport const experimental_jwksCache = jwksCache;\n","import * as base64url from '../runtime/base64url.js';\nexport const encode = base64url.encode;\nexport const decode = base64url.decode;\n","import { decode as base64url } from './base64url.js';\nimport { decoder } from '../lib/buffer_utils.js';\nimport isObject from '../lib/is_object.js';\nexport function decodeProtectedHeader(token) {\n let protectedB64u;\n if (typeof token === 'string') {\n const parts = token.split('.');\n if (parts.length === 3 || parts.length === 5) {\n ;\n [protectedB64u] = parts;\n }\n }\n else if (typeof token === 'object' && token) {\n if ('protected' in token) {\n protectedB64u = token.protected;\n }\n else {\n throw new TypeError('Token does not contain a Protected Header');\n }\n }\n try {\n if (typeof protectedB64u !== 'string' || !protectedB64u) {\n throw new Error();\n }\n const result = JSON.parse(decoder.decode(base64url(protectedB64u)));\n if (!isObject(result)) {\n throw new Error();\n }\n return result;\n }\n catch {\n throw new TypeError('Invalid Token or Protected Header formatting');\n }\n}\n","import { decode as base64url } from './base64url.js';\nimport { decoder } from '../lib/buffer_utils.js';\nimport isObject from '../lib/is_object.js';\nimport { JWTInvalid } from './errors.js';\nexport function decodeJwt(jwt) {\n if (typeof jwt !== 'string')\n throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');\n const { 1: payload, length } = jwt.split('.');\n if (length === 5)\n throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');\n if (length !== 3)\n throw new JWTInvalid('Invalid JWT');\n if (!payload)\n throw new JWTInvalid('JWTs must contain a payload');\n let decoded;\n try {\n decoded = base64url(payload);\n }\n catch {\n throw new JWTInvalid('Failed to base64url decode the payload');\n }\n let result;\n try {\n result = JSON.parse(decoder.decode(decoded));\n }\n catch {\n throw new JWTInvalid('Failed to parse the decoded payload as JSON');\n }\n if (!isObject(result))\n throw new JWTInvalid('Invalid JWT Claims Set');\n return result;\n}\n","const hexadecimal = \"0123456789abcdef\";\nconst hex = {\n encode: (data) => {\n if (typeof data === \"string\") {\n data = new TextEncoder().encode(data);\n }\n if (data.byteLength === 0) {\n return \"\";\n }\n const buffer = new Uint8Array(data);\n let result = \"\";\n for (const byte of buffer) {\n result += byte.toString(16).padStart(2, \"0\");\n }\n return result;\n },\n decode: (data) => {\n if (!data) {\n return \"\";\n }\n if (typeof data === \"string\") {\n if (data.length % 2 !== 0) {\n throw new Error(\"Invalid hexadecimal string\");\n }\n if (!new RegExp(`^[${hexadecimal}]+$`).test(data)) {\n throw new Error(\"Invalid hexadecimal string\");\n }\n const result = new Uint8Array(data.length / 2);\n for (let i = 0; i < data.length; i += 2) {\n result[i / 2] = parseInt(data.slice(i, i + 2), 16);\n }\n return new TextDecoder().decode(result);\n }\n return new TextDecoder().decode(data);\n }\n};\n\nexport { hex };\n","import { getRandomValues } from 'uncrypto';\n\nfunction expandAlphabet(alphabet) {\n switch (alphabet) {\n case \"a-z\":\n return \"abcdefghijklmnopqrstuvwxyz\";\n case \"A-Z\":\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n case \"0-9\":\n return \"0123456789\";\n case \"-_\":\n return \"-_\";\n default:\n throw new Error(`Unsupported alphabet: ${alphabet}`);\n }\n}\nfunction createRandomStringGenerator(...baseAlphabets) {\n const baseCharSet = baseAlphabets.map(expandAlphabet).join(\"\");\n if (baseCharSet.length === 0) {\n throw new Error(\n \"No valid characters provided for random string generation.\"\n );\n }\n const baseCharSetLength = baseCharSet.length;\n return (length, ...alphabets) => {\n if (length <= 0) {\n throw new Error(\"Length must be a positive integer.\");\n }\n let charSet = baseCharSet;\n let charSetLength = baseCharSetLength;\n if (alphabets.length > 0) {\n charSet = alphabets.map(expandAlphabet).join(\"\");\n charSetLength = charSet.length;\n }\n const maxValid = Math.floor(256 / charSetLength) * charSetLength;\n const buf = new Uint8Array(length * 2);\n const bufLength = buf.length;\n let result = \"\";\n let bufIndex = bufLength;\n let rand;\n while (result.length < length) {\n if (bufIndex >= bufLength) {\n getRandomValues(buf);\n bufIndex = 0;\n }\n rand = buf[bufIndex++];\n if (rand < maxValid) {\n result += charSet[rand % charSetLength];\n }\n }\n return result;\n };\n}\n\nexport { createRandomStringGenerator };\n","import { createRandomStringGenerator } from '@better-auth/utils/random';\n\nconst generateRandomString = createRandomStringGenerator(\n \"a-z\",\n \"0-9\",\n \"A-Z\",\n \"-_\"\n);\n\nexport { generateRandomString as g };\n","import { createHash } from '@better-auth/utils/hash';\nimport { xchacha20poly1305 } from '@noble/ciphers/chacha';\nimport { utf8ToBytes, bytesToHex, hexToBytes as hexToBytes$1 } from '@noble/ciphers/utils';\nimport { managedNonce } from '@noble/ciphers/webcrypto';\nimport { base64 } from '@better-auth/utils/base64';\nimport { SignJWT } from 'jose';\nimport { scryptAsync } from '@noble/hashes/scrypt';\nimport { getRandomValues } from '@better-auth/utils';\nimport { hex } from '@better-auth/utils/hex';\nimport { hexToBytes } from '@noble/hashes/utils';\nexport { g as generateRandomString } from '../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\n\nasync function signJWT(payload, secret, expiresIn = 3600) {\n const jwt = await new SignJWT(payload).setProtectedHeader({ alg: \"HS256\" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret));\n return jwt;\n}\n\nfunction constantTimeEqual(a, b) {\n const aBuffer = new Uint8Array(a);\n const bBuffer = new Uint8Array(b);\n if (aBuffer.length !== bBuffer.length) {\n return false;\n }\n let c = 0;\n for (let i = 0; i < aBuffer.length; i++) {\n c |= aBuffer[i] ^ bBuffer[i];\n }\n return c === 0;\n}\n\nasync function hashToBase64(data) {\n const buffer = await createHash(\"SHA-256\").digest(data);\n return base64.encode(buffer);\n}\nasync function compareHash(data, hash) {\n const buffer = await createHash(\"SHA-256\").digest(\n typeof data === \"string\" ? new TextEncoder().encode(data) : data\n );\n const hashBuffer = base64.decode(hash);\n return constantTimeEqual(buffer, hashBuffer);\n}\n\nconst config = {\n N: 16384,\n r: 16,\n p: 1,\n dkLen: 64\n};\nasync function generateKey(password, salt) {\n return await scryptAsync(password.normalize(\"NFKC\"), salt, {\n N: config.N,\n p: config.p,\n r: config.r,\n dkLen: config.dkLen,\n maxmem: 128 * config.N * config.r * 2\n });\n}\nconst hashPassword = async (password) => {\n const salt = hex.encode(getRandomValues(new Uint8Array(16)));\n const key = await generateKey(password, salt);\n return `${salt}:${hex.encode(key)}`;\n};\nconst verifyPassword = async ({\n hash,\n password\n}) => {\n const [salt, key] = hash.split(\":\");\n const targetKey = await generateKey(password, salt);\n return constantTimeEqual(targetKey, hexToBytes(key));\n};\n\nconst symmetricEncrypt = async ({\n key,\n data\n}) => {\n const keyAsBytes = await createHash(\"SHA-256\").digest(key);\n const dataAsBytes = utf8ToBytes(data);\n const chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes));\n return bytesToHex(chacha.encrypt(dataAsBytes));\n};\nconst symmetricDecrypt = async ({\n key,\n data\n}) => {\n const keyAsBytes = await createHash(\"SHA-256\").digest(key);\n const dataAsBytes = hexToBytes$1(data);\n const chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes));\n return new TextDecoder().decode(chacha.decrypt(dataAsBytes));\n};\n\nexport { compareHash, constantTimeEqual, hashPassword, hashToBase64, signJWT, symmetricDecrypt, symmetricEncrypt, verifyPassword };\n","export class BetterFetchError extends Error {\n\tconstructor(\n\t\tpublic status: number,\n\t\tpublic statusText: string,\n\t\tpublic error: any,\n\t) {\n\t\tsuper(statusText || status.toString(), {\n\t\t\tcause: error,\n\t\t});\n\t}\n}\n","import type { StandardSchemaV1 } from \"./standard-schema\";\nimport { Schema } from \"./create-fetch\";\nimport { BetterFetchError } from \"./error\";\nimport type { BetterFetchOption } from \"./types\";\n\nexport type RequestContext<T extends Record<string, any> = any> = {\n\turl: URL | string;\n\theaders: Headers;\n\tbody: any;\n\tmethod: string;\n\tsignal: AbortSignal;\n} & BetterFetchOption<any, any, any, T>;\nexport type ResponseContext = {\n\tresponse: Response;\n\trequest: RequestContext;\n};\nexport type SuccessContext<Res = any> = {\n\tdata: Res;\n\tresponse: Response;\n\trequest: RequestContext;\n};\nexport type ErrorContext = {\n\tresponse: Response;\n\trequest: RequestContext;\n\terror: BetterFetchError & Record<string, any>;\n};\nexport interface FetchHooks<Res = any> {\n\t/**\n\t * a callback function that will be called when a\n\t * request is made.\n\t *\n\t * The returned context object will be reassigned to\n\t * the original request context.\n\t */\n\tonRequest?: <T extends Record<string, any>>(\n\t\tcontext: RequestContext<T>,\n\t) => Promise<RequestContext | void> | RequestContext | void;\n\t/**\n\t * a callback function that will be called when\n\t * response is received. This will be called before\n\t * the response is parsed and returned.\n\t *\n\t * The returned response will be reassigned to the\n\t * original response if it's changed.\n\t */\n\tonResponse?: (\n\t\tcontext: ResponseContext,\n\t) =>\n\t\t| Promise<Response | void | ResponseContext>\n\t\t| Response\n\t\t| ResponseContext\n\t\t| void;\n\t/**\n\t * a callback function that will be called when a\n\t * response is successful.\n\t */\n\tonSuccess?: (context: SuccessContext<Res>) => Promise<void> | void;\n\t/**\n\t * a callback function that will be called when an\n\t * error occurs.\n\t */\n\tonError?: (context: ErrorContext) => Promise<void> | void;\n\t/**\n\t * a callback function that will be called when a\n\t * request is retried.\n\t */\n\tonRetry?: (response: ResponseContext) => Promise<void> | void;\n\t/**\n\t * Options for the hooks\n\t */\n\thookOptions?: {\n\t\t/**\n\t\t * Clone the response\n\t\t * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone\n\t\t */\n\t\tcloneResponse?: boolean;\n\t};\n}\n\n/**\n * A plugin that returns an id and hooks\n */\nexport type BetterFetchPlugin = {\n\t/**\n\t * A unique id for the plugin\n\t */\n\tid: string;\n\t/**\n\t * A name for the plugin\n\t */\n\tname: string;\n\t/**\n\t * A description for the plugin\n\t */\n\tdescription?: string;\n\t/**\n\t * A version for the plugin\n\t */\n\tversion?: string;\n\t/**\n\t * Hooks for the plugin\n\t */\n\thooks?: FetchHooks;\n\t/**\n\t * A function that will be called when the plugin is\n\t * initialized. This will be called before the any\n\t * of the other internal functions.\n\t *\n\t * The returned options will be merged with the\n\t * original options.\n\t */\n\tinit?: (\n\t\turl: string,\n\t\toptions?: BetterFetchOption,\n\t) =>\n\t\t| Promise<{\n\t\t\t\turl: string;\n\t\t\t\toptions?: BetterFetchOption;\n\t\t }>\n\t\t| {\n\t\t\t\turl: string;\n\t\t\t\toptions?: BetterFetchOption;\n\t\t };\n\t/**\n\t * A schema for the plugin\n\t */\n\tschema?: Schema;\n\t/**\n\t * Additional options that can be passed to the plugin\n\t */\n\tgetOptions?: () => StandardSchemaV1;\n};\n\nexport const initializePlugins = async (\n\turl: string,\n\toptions?: BetterFetchOption,\n) => {\n\tlet opts = options || {};\n\tconst hooks: {\n\t\tonRequest: Array<FetchHooks[\"onRequest\"]>;\n\t\tonResponse: Array<FetchHooks[\"onResponse\"]>;\n\t\tonSuccess: Array<FetchHooks[\"onSuccess\"]>;\n\t\tonError: Array<FetchHooks[\"onError\"]>;\n\t\tonRetry: Array<FetchHooks[\"onRetry\"]>;\n\t} = {\n\t\tonRequest: [options?.onRequest],\n\t\tonResponse: [options?.onResponse],\n\t\tonSuccess: [options?.onSuccess],\n\t\tonError: [options?.onError],\n\t\tonRetry: [options?.onRetry],\n\t};\n\tif (!options || !options?.plugins) {\n\t\treturn {\n\t\t\turl,\n\t\t\toptions: opts,\n\t\t\thooks,\n\t\t};\n\t}\n\tfor (const plugin of options?.plugins || []) {\n\t\tif (plugin.init) {\n\t\t\tconst pluginRes = await plugin.init?.(url.toString(), options);\n\t\t\topts = pluginRes.options || opts;\n\t\t\turl = pluginRes.url;\n\t\t}\n\t\thooks.onRequest.push(plugin.hooks?.onRequest);\n\t\thooks.onResponse.push(plugin.hooks?.onResponse);\n\t\thooks.onSuccess.push(plugin.hooks?.onSuccess);\n\t\thooks.onError.push(plugin.hooks?.onError);\n\t\thooks.onRetry.push(plugin.hooks?.onRetry);\n\t}\n\n\treturn {\n\t\turl,\n\t\toptions: opts,\n\t\thooks,\n\t};\n};\n","export type RetryCondition = (\n\tresponse: Response | null,\n) => boolean | Promise<boolean>;\n\nexport type LinearRetry = {\n\ttype: \"linear\";\n\tattempts: number;\n\tdelay: number;\n\tshouldRetry?: RetryCondition;\n};\n\nexport type ExponentialRetry = {\n\ttype: \"exponential\";\n\tattempts: number;\n\tbaseDelay: number;\n\tmaxDelay: number;\n\tshouldRetry?: RetryCondition;\n};\n\nexport type RetryOptions = LinearRetry | ExponentialRetry | number;\n\nexport interface RetryStrategy {\n\tshouldAttemptRetry(\n\t\tattempt: number,\n\t\tresponse: Response | null,\n\t): Promise<boolean>;\n\tgetDelay(attempt: number): number;\n}\n\nclass LinearRetryStrategy implements RetryStrategy {\n\tconstructor(private options: LinearRetry) {}\n\n\tshouldAttemptRetry(\n\t\tattempt: number,\n\t\tresponse: Response | null,\n\t): Promise<boolean> {\n\t\tif (this.options.shouldRetry) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tattempt < this.options.attempts && this.options.shouldRetry(response),\n\t\t\t);\n\t\t}\n\t\treturn Promise.resolve(attempt < this.options.attempts);\n\t}\n\n\tgetDelay(): number {\n\t\treturn this.options.delay;\n\t}\n}\n\nclass ExponentialRetryStrategy implements RetryStrategy {\n\tconstructor(private options: ExponentialRetry) {}\n\n\tshouldAttemptRetry(\n\t\tattempt: number,\n\t\tresponse: Response | null,\n\t): Promise<boolean> {\n\t\tif (this.options.shouldRetry) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tattempt < this.options.attempts && this.options.shouldRetry(response),\n\t\t\t);\n\t\t}\n\t\treturn Promise.resolve(attempt < this.options.attempts);\n\t}\n\n\tgetDelay(attempt: number): number {\n\t\tconst delay = Math.min(\n\t\t\tthis.options.maxDelay,\n\t\t\tthis.options.baseDelay * 2 ** attempt,\n\t\t);\n\t\treturn delay;\n\t}\n}\n\nexport function createRetryStrategy(options: RetryOptions): RetryStrategy {\n\tif (typeof options === \"number\") {\n\t\treturn new LinearRetryStrategy({\n\t\t\ttype: \"linear\",\n\t\t\tattempts: options,\n\t\t\tdelay: 1000,\n\t\t});\n\t}\n\n\tswitch (options.type) {\n\t\tcase \"linear\":\n\t\t\treturn new LinearRetryStrategy(options);\n\t\tcase \"exponential\":\n\t\t\treturn new ExponentialRetryStrategy(options);\n\t\tdefault:\n\t\t\tthrow new Error(\"Invalid retry strategy\");\n\t}\n}\n","import type { BetterFetchOption } from \"./types\";\n\nexport type typeOrTypeReturning<T> = T | (() => T);\n/**\n * Bearer token authentication\n *\n * the value of `token` will be added to a header as\n * `auth: Bearer token`,\n */\nexport type Bearer = {\n\ttype: \"Bearer\";\n\ttoken: typeOrTypeReturning<string | undefined | Promise<string | undefined>>;\n};\n\n/**\n * Basic auth\n */\nexport type Basic = {\n\ttype: \"Basic\";\n\tusername: typeOrTypeReturning<string | undefined>;\n\tpassword: typeOrTypeReturning<string | undefined>;\n};\n\n/**\n * Custom auth\n *\n * @param prefix - prefix of the header\n * @param value - value of the header\n *\n * @example\n * ```ts\n * {\n * type: \"Custom\",\n * prefix: \"Token\",\n * value: \"token\"\n * }\n * ```\n */\nexport type Custom = {\n\ttype: \"Custom\";\n\tprefix: typeOrTypeReturning<string | undefined>;\n\tvalue: typeOrTypeReturning<string | undefined>;\n};\n\nexport type Auth = Bearer | Basic | Custom;\n\nexport const getAuthHeader = async (options?: BetterFetchOption) => {\n\tconst headers: Record<string, string> = {};\n\tconst getValue = async (\n\t\tvalue: typeOrTypeReturning<\n\t\t\tstring | undefined | Promise<string | undefined>\n\t\t>,\n\t) => (typeof value === \"function\" ? await value() : value);\n\tif (options?.auth) {\n\t\tif (options.auth.type === \"Bearer\") {\n\t\t\tconst token = await getValue(options.auth.token);\n\t\t\tif (!token) {\n\t\t\t\treturn headers;\n\t\t\t}\n\t\t\theaders[\"authorization\"] = `Bearer ${token}`;\n\t\t} else if (options.auth.type === \"Basic\") {\n\t\t\tconst username = getValue(options.auth.username);\n\t\t\tconst password = getValue(options.auth.password);\n\t\t\tif (!username || !password) {\n\t\t\t\treturn headers;\n\t\t\t}\n\t\t\theaders[\"authorization\"] = `Basic ${btoa(`${username}:${password}`)}`;\n\t\t} else if (options.auth.type === \"Custom\") {\n\t\t\tconst value = getValue(options.auth.value);\n\t\t\tif (!value) {\n\t\t\t\treturn headers;\n\t\t\t}\n\t\t\theaders[\"authorization\"] = `${getValue(options.auth.prefix)} ${value}`;\n\t\t}\n\t}\n\treturn headers;\n};\n","import type { StandardSchemaV1 } from \"./standard-schema\";\nimport { getAuthHeader } from \"./auth\";\nimport { methods } from \"./create-fetch\";\nimport type { BetterFetchOption, FetchEsque } from \"./types\";\n\nconst JSON_RE = /^application\\/(?:[\\w!#$%&*.^`~-]*\\+)?json(;.+)?$/i;\n\nexport type ResponseType = \"json\" | \"text\" | \"blob\";\nexport function detectResponseType(request: Response): ResponseType {\n\tconst _contentType = request.headers.get(\"content-type\");\n\tconst textTypes = new Set([\n\t\t\"image/svg\",\n\t\t\"application/xml\",\n\t\t\"application/xhtml\",\n\t\t\"application/html\",\n\t]);\n\tif (!_contentType) {\n\t\treturn \"json\";\n\t}\n\tconst contentType = _contentType.split(\";\").shift() || \"\";\n\tif (JSON_RE.test(contentType)) {\n\t\treturn \"json\";\n\t}\n\tif (textTypes.has(contentType) || contentType.startsWith(\"text/\")) {\n\t\treturn \"text\";\n\t}\n\treturn \"blob\";\n}\n\nexport function isJSONParsable(value: any) {\n\ttry {\n\t\tJSON.parse(value);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn false;\n\t}\n}\n\n//https://github.com/unjs/ofetch/blob/main/src/utils.ts\nexport function isJSONSerializable(value: any) {\n\tif (value === undefined) {\n\t\treturn false;\n\t}\n\tconst t = typeof value;\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n\t\treturn true;\n\t}\n\tif (t !== \"object\") {\n\t\treturn false;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn true;\n\t}\n\tif (value.buffer) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t(value.constructor && value.constructor.name === \"Object\") ||\n\t\ttypeof value.toJSON === \"function\"\n\t);\n}\n\nexport function jsonParse(text: string) {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch (error) {\n\t\treturn text;\n\t}\n}\n\nexport function isFunction(value: any): value is () => any {\n\treturn typeof value === \"function\";\n}\n\nexport function getFetch(options?: BetterFetchOption): FetchEsque {\n\tif (options?.customFetchImpl) {\n\t\treturn options.customFetchImpl;\n\t}\n\tif (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) {\n\t\treturn globalThis.fetch;\n\t}\n\tif (typeof window !== \"undefined\" && isFunction(window.fetch)) {\n\t\treturn window.fetch;\n\t}\n\tthrow new Error(\"No fetch implementation found\");\n}\n\nexport function isPayloadMethod(method?: string) {\n\tif (!method) {\n\t\treturn false;\n\t}\n\tconst payloadMethod = [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\treturn payloadMethod.includes(method.toUpperCase());\n}\n\nexport function isRouteMethod(method?: string) {\n\tconst routeMethod = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\tif (!method) {\n\t\treturn false;\n\t}\n\treturn routeMethod.includes(method.toUpperCase());\n}\n\nexport async function getHeaders(opts?: BetterFetchOption) {\n\tconst headers = new Headers(opts?.headers);\n\tconst authHeader = await getAuthHeader(opts);\n\tfor (const [key, value] of Object.entries(authHeader || {})) {\n\t\theaders.set(key, value);\n\t}\n\tif (!headers.has(\"content-type\")) {\n\t\tconst t = detectContentType(opts?.body);\n\t\tif (t) {\n\t\t\theaders.set(\"content-type\", t);\n\t\t}\n\t}\n\n\treturn headers;\n}\n\nexport function getURL(url: string, options?: BetterFetchOption) {\n\tif (url.startsWith(\"@\")) {\n\t\tconst m = url.toString().split(\"@\")[1].split(\"/\")[0];\n\t\tif (methods.includes(m)) {\n\t\t\turl = url.replace(`@${m}/`, \"/\");\n\t\t}\n\t}\n\tlet _url: string | URL;\n\ttry {\n\t\tif (url.startsWith(\"http\")) {\n\t\t\t_url = url;\n\t\t} else {\n\t\t\tlet baseURL = options?.baseURL;\n\t\t\tif (baseURL && !baseURL?.endsWith(\"/\")) {\n\t\t\t\tbaseURL = baseURL + \"/\";\n\t\t\t}\n\t\t\tif (url.startsWith(\"/\")) {\n\t\t\t\t_url = new URL(url.substring(1), baseURL);\n\t\t\t} else {\n\t\t\t\t_url = new URL(url, options?.baseURL);\n\t\t\t}\n\t\t}\n\t} catch (e) {\n\t\tif (e instanceof TypeError) {\n\t\t\tif (!options?.baseURL) {\n\t\t\t\tthrow TypeError(\n\t\t\t\t\t`Invalid URL ${url}. Are you passing in a relative url but not setting the baseURL?`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow TypeError(\n\t\t\t\t`Invalid URL ${url}. Please validate that you are passing the correct input.`,\n\t\t\t);\n\t\t}\n\t\tthrow e;\n\t}\n\n\t/**\n\t * Dynamic Parameters.\n\t */\n\tif (options?.params) {\n\t\tif (Array.isArray(options?.params)) {\n\t\t\tconst params = options?.params\n\t\t\t\t? Array.isArray(options.params)\n\t\t\t\t\t? `/${options.params.join(\"/\")}`\n\t\t\t\t\t: `/${Object.values(options.params).join(\"/\")}`\n\t\t\t\t: \"\";\n\t\t\t_url = _url.toString().split(\"/:\")[0];\n\t\t\t_url = `${_url.toString()}${params}`;\n\t\t} else {\n\t\t\tfor (const [key, value] of Object.entries(options?.params)) {\n\t\t\t\t_url = _url.toString().replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t}\n\tconst __url = new URL(_url);\n\t/**\n\t * Query Parameters\n\t */\n\tconst queryParams = options?.query;\n\tif (queryParams) {\n\t\tfor (const [key, value] of Object.entries(queryParams)) {\n\t\t\t__url.searchParams.append(key, String(value));\n\t\t}\n\t}\n\treturn __url;\n}\n\nexport function detectContentType(body: any) {\n\tif (isJSONSerializable(body)) {\n\t\treturn \"application/json\";\n\t}\n\n\treturn null;\n}\n\nexport function getBody(options?: BetterFetchOption) {\n\tif (!options?.body) {\n\t\treturn null;\n\t}\n\tconst headers = new Headers(options?.headers);\n\tif (isJSONSerializable(options.body) && !headers.has(\"content-type\")) {\n\t\tfor (const [key, value] of Object.entries(options?.body)) {\n\t\t\tif (value instanceof Date) {\n\t\t\t\toptions.body[key] = value.toISOString();\n\t\t\t}\n\t\t}\n\t\treturn JSON.stringify(options.body);\n\t}\n\n\treturn options.body;\n}\n\nexport function getMethod(url: string, options?: BetterFetchOption) {\n\tif (options?.method) {\n\t\treturn options.method.toUpperCase();\n\t}\n\tif (url.startsWith(\"@\")) {\n\t\tconst pMethod = url.split(\"@\")[1]?.split(\"/\")[0];\n\t\tif (!methods.includes(pMethod)) {\n\t\t\treturn options?.body ? \"POST\" : \"GET\";\n\t\t}\n\t\treturn pMethod.toUpperCase();\n\t}\n\treturn options?.body ? \"POST\" : \"GET\";\n}\n\nexport function getTimeout(\n\toptions?: BetterFetchOption,\n\tcontroller?: AbortController,\n) {\n\tlet abortTimeout: ReturnType<typeof setTimeout> | undefined;\n\tif (!options?.signal && options?.timeout) {\n\t\tabortTimeout = setTimeout(() => controller?.abort(), options?.timeout);\n\t}\n\treturn {\n\t\tabortTimeout,\n\t\tclearTimeout: () => {\n\t\t\tif (abortTimeout) {\n\t\t\t\tclearTimeout(abortTimeout);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function bodyParser(data: any, responseType: ResponseType) {\n\tif (responseType === \"json\") {\n\t\treturn JSON.parse(data);\n\t}\n\treturn data;\n}\n\nexport class ValidationError extends Error {\n\tpublic readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;\n\n\tconstructor(issues: ReadonlyArray<StandardSchemaV1.Issue>, message?: string) {\n\t\t// Default message fallback in case one isn't supplied.\n\t\tsuper(message || JSON.stringify(issues, null, 2));\n\t\tthis.issues = issues;\n\n\t\t// Set the prototype explicitly to ensure that instanceof works correctly.\n\t\tObject.setPrototypeOf(this, ValidationError.prototype);\n\t}\n}\n\nexport async function parseStandardSchema<TSchema extends StandardSchemaV1>(\n\tschema: TSchema,\n\tinput: StandardSchemaV1.InferInput<TSchema>,\n): Promise<StandardSchemaV1.InferOutput<TSchema>> {\n\tlet result = await schema[\"~standard\"].validate(input);\n\n\tif (result.issues) {\n\t\tthrow new ValidationError(result.issues);\n\t}\n\treturn result.value;\n}\n","import type { StandardSchemaV1 } from \"../standard-schema\";\nimport type { StringLiteralUnion } from \"../type-utils\";\n\nexport type FetchSchema = {\n\tinput?: StandardSchemaV1;\n\toutput?: StandardSchemaV1;\n\tquery?: StandardSchemaV1;\n\tparams?: StandardSchemaV1<Record<string, unknown>> | undefined;\n\tmethod?: Methods;\n};\n\nexport type Methods = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\n\nexport const methods = [\"get\", \"post\", \"put\", \"patch\", \"delete\"];\n\ntype RouteKey = StringLiteralUnion<`@${Methods}/`>;\n\nexport type FetchSchemaRoutes = {\n\t[key in RouteKey]?: FetchSchema;\n};\n\nexport const createSchema = <\n\tF extends FetchSchemaRoutes,\n\tS extends SchemaConfig,\n>(\n\tschema: F,\n\tconfig?: S,\n) => {\n\treturn {\n\t\tschema: schema as F,\n\t\tconfig: config as S,\n\t};\n};\n\nexport type SchemaConfig = {\n\tstrict?: boolean;\n\t/**\n\t * A prefix that will be prepended when it's\n\t * calling the schema.\n\t *\n\t * NOTE: Make sure to handle converting\n\t * the prefix to the baseURL in the init\n\t * function if you you are defining for a\n\t * plugin.\n\t */\n\tprefix?: \"\" | (string & Record<never, never>);\n\t/**\n\t * The base url of the schema. By default it's the baseURL of the fetch instance.\n\t */\n\tbaseURL?: \"\" | (string & Record<never, never>);\n};\n\nexport type Schema = {\n\tschema: FetchSchemaRoutes;\n\tconfig: SchemaConfig;\n};\n","import { betterFetch } from \"../fetch\";\nimport { BetterFetchPlugin } from \"../plugins\";\nimport type { BetterFetchOption } from \"../types\";\nimport { parseStandardSchema } from \"../utils\";\nimport type { BetterFetch, CreateFetchOption } from \"./types\";\n\nexport const applySchemaPlugin = (config: CreateFetchOption) =>\n\t({\n\t\tid: \"apply-schema\",\n\t\tname: \"Apply Schema\",\n\t\tversion: \"1.0.0\",\n\t\tasync init(url, options) {\n\t\t\tconst schema =\n\t\t\t\tconfig.plugins?.find((plugin) =>\n\t\t\t\t\tplugin.schema?.config\n\t\t\t\t\t\t? url.startsWith(plugin.schema.config.baseURL || \"\") ||\n\t\t\t\t\t\t\turl.startsWith(plugin.schema.config.prefix || \"\")\n\t\t\t\t\t\t: false,\n\t\t\t\t)?.schema || config.schema;\n\t\t\tif (schema) {\n\t\t\t\tlet urlKey = url;\n\t\t\t\tif (schema.config?.prefix) {\n\t\t\t\t\tif (urlKey.startsWith(schema.config.prefix)) {\n\t\t\t\t\t\turlKey = urlKey.replace(schema.config.prefix, \"\");\n\t\t\t\t\t\tif (schema.config.baseURL) {\n\t\t\t\t\t\t\turl = url.replace(schema.config.prefix, schema.config.baseURL);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (schema.config?.baseURL) {\n\t\t\t\t\tif (urlKey.startsWith(schema.config.baseURL)) {\n\t\t\t\t\t\turlKey = urlKey.replace(schema.config.baseURL, \"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst keySchema = schema.schema[urlKey];\n\t\t\t\tif (keySchema) {\n\t\t\t\t\tlet opts = {\n\t\t\t\t\t\t...options,\n\t\t\t\t\t\tmethod: keySchema.method,\n\t\t\t\t\t\toutput: keySchema.output,\n\t\t\t\t\t};\n\t\t\t\t\tif (!options?.disableValidation) {\n\t\t\t\t\t\topts = {\n\t\t\t\t\t\t\t...opts,\n\t\t\t\t\t\t\tbody: keySchema.input\n\t\t\t\t\t\t\t\t? await parseStandardSchema(keySchema.input, options?.body)\n\t\t\t\t\t\t\t\t: options?.body,\n\t\t\t\t\t\t\tparams: keySchema.params\n\t\t\t\t\t\t\t\t? await parseStandardSchema(keySchema.params, options?.params)\n\t\t\t\t\t\t\t\t: options?.params,\n\t\t\t\t\t\t\tquery: keySchema.query\n\t\t\t\t\t\t\t\t? await parseStandardSchema(keySchema.query, options?.query)\n\t\t\t\t\t\t\t\t: options?.query,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\toptions: opts,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\turl,\n\t\t\t\toptions,\n\t\t\t};\n\t\t},\n\t}) satisfies BetterFetchPlugin;\n\nexport const createFetch = <Option extends CreateFetchOption>(\n\tconfig?: Option,\n) => {\n\tasync function $fetch(url: string, options?: BetterFetchOption) {\n\t\tconst opts = {\n\t\t\t...config,\n\t\t\t...options,\n\t\t\tplugins: [...(config?.plugins || []), applySchemaPlugin(config || {})],\n\t\t} as BetterFetchOption;\n\n\t\tif (config?.catchAllError) {\n\t\t\ttry {\n\t\t\t\treturn await betterFetch(url, opts);\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tdata: null,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tstatus: 500,\n\t\t\t\t\t\tstatusText: \"Fetch Error\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Fetch related error. Captured by catchAllError option. See error property for more details.\",\n\t\t\t\t\t\terror,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn await betterFetch(url, opts);\n\t}\n\treturn $fetch as BetterFetch<Option>;\n};\n\nexport * from \"./schema\";\nexport * from \"./types\";\n","import { methods } from \"./create-fetch\";\nimport { BetterFetchOption } from \"./types\";\n\n/**\n * Normalize URL\n */\nexport function getURL(url: string, option?: BetterFetchOption) {\n\tlet { baseURL, params, query } = option || {\n\t\tquery: {},\n\t\tparams: {},\n\t\tbaseURL: \"\",\n\t};\n\tlet basePath = url.startsWith(\"http\")\n\t\t? url.split(\"/\").slice(0, 3).join(\"/\")\n\t\t: baseURL || \"\";\n\n\t/**\n\t * Remove method modifiers\n\t */\n\tif (url.startsWith(\"@\")) {\n\t\tconst m = url.toString().split(\"@\")[1].split(\"/\")[0];\n\t\tif (methods.includes(m)) {\n\t\t\turl = url.replace(`@${m}/`, \"/\");\n\t\t}\n\t}\n\n\tif (!basePath.endsWith(\"/\")) basePath += \"/\";\n\tlet [path, urlQuery] = url.replace(basePath, \"\").split(\"?\");\n\tconst queryParams = new URLSearchParams(urlQuery);\n\tfor (const [key, value] of Object.entries(query || {})) {\n\t\tif (value == null) continue;\n\t\tqueryParams.set(key, String(value));\n\t}\n\tif (params) {\n\t\tif (Array.isArray(params)) {\n\t\t\tconst paramPaths = path.split(\"/\").filter((p) => p.startsWith(\":\"));\n\t\t\tfor (const [index, key] of paramPaths.entries()) {\n\t\t\t\tconst value = params[index];\n\t\t\t\tpath = path.replace(key, value);\n\t\t\t}\n\t\t} else {\n\t\t\tfor (const [key, value] of Object.entries(params)) {\n\t\t\t\tpath = path.replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t}\n\n\tpath = path.split(\"/\").map(encodeURIComponent).join(\"/\");\n\tif (path.startsWith(\"/\")) path = path.slice(1);\n\tlet queryParamString = queryParams.toString();\n\tqueryParamString =\n\t\tqueryParamString.length > 0 ? `?${queryParamString}`.replace(/\\+/g, \"%20\") : \"\";\n\tif (!basePath.startsWith(\"http\")) {\n\t\treturn `${basePath}${path}${queryParamString}`;\n\t}\n\tconst _url = new URL(`${path}${queryParamString}`, basePath);\n\treturn _url;\n}\n","import type { StandardSchemaV1 } from \"./standard-schema\";\nimport { BetterFetchError } from \"./error\";\nimport { initializePlugins } from \"./plugins\";\nimport { createRetryStrategy } from \"./retry\";\nimport type { BetterFetchOption, BetterFetchResponse } from \"./types\";\nimport { getURL } from \"./url\";\nimport {\n\tdetectResponseType,\n\tgetBody,\n\tgetFetch,\n\tgetHeaders,\n\tgetMethod,\n\tgetTimeout,\n\tisJSONParsable,\n\tjsonParse,\n\tparseStandardSchema,\n} from \"./utils\";\n\nexport const betterFetch = async <\n\tTRes extends Option[\"output\"] extends StandardSchemaV1\n\t\t? StandardSchemaV1.InferOutput<Option[\"output\"]>\n\t\t: unknown,\n\tTErr = unknown,\n\tOption extends BetterFetchOption = BetterFetchOption<any, any, any, TRes>,\n>(\n\turl: string,\n\toptions?: Option,\n): Promise<\n\tBetterFetchResponse<\n\t\tTRes,\n\t\tTErr,\n\t\tOption[\"throw\"] extends true ? true : TErr extends false ? true : false\n\t>\n> => {\n\tconst {\n\t\thooks,\n\t\turl: __url,\n\t\toptions: opts,\n\t} = await initializePlugins(url, options);\n\tconst fetch = getFetch(opts);\n\tconst controller = new AbortController();\n\tconst signal = opts.signal ?? controller.signal;\n\tconst _url = getURL(__url, opts);\n\tconst body = getBody(opts);\n\tconst headers = await getHeaders(opts);\n\tconst method = getMethod(__url, opts);\n\tlet context = {\n\t\t...opts,\n\t\turl: _url,\n\t\theaders,\n\t\tbody,\n\t\tmethod,\n\t\tsignal,\n\t};\n\t/**\n\t * Run all on request hooks\n\t */\n\tfor (const onRequest of hooks.onRequest) {\n\t\tif (onRequest) {\n\t\t\tconst res = await onRequest(context);\n\t\t\tif (res instanceof Object) {\n\t\t\t\tcontext = res;\n\t\t\t}\n\t\t}\n\t}\n\tif (\n\t\t(\"pipeTo\" in (context as any) &&\n\t\t\ttypeof (context as any).pipeTo === \"function\") ||\n\t\ttypeof options?.body?.pipe === \"function\"\n\t) {\n\t\tif (!(\"duplex\" in context)) {\n\t\t\tcontext.duplex = \"half\";\n\t\t}\n\t}\n\n\tconst { clearTimeout } = getTimeout(opts, controller);\n\tlet response = await fetch(context.url, context);\n\tclearTimeout();\n\n\tconst responseContext = {\n\t\tresponse,\n\t\trequest: context,\n\t};\n\n\tfor (const onResponse of hooks.onResponse) {\n\t\tif (onResponse) {\n\t\t\tconst r = await onResponse({\n\t\t\t\t...responseContext,\n\t\t\t\tresponse: options?.hookOptions?.cloneResponse\n\t\t\t\t\t? response.clone()\n\t\t\t\t\t: response,\n\t\t\t});\n\t\t\tif (r instanceof Response) {\n\t\t\t\tresponse = r;\n\t\t\t} else if (r instanceof Object) {\n\t\t\t\tresponse = r.response;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * OK Branch\n\t */\n\tif (response.ok) {\n\t\tconst hasBody = context.method !== \"HEAD\";\n\t\tif (!hasBody) {\n\t\t\treturn {\n\t\t\t\tdata: \"\" as any,\n\t\t\t\terror: null,\n\t\t\t} as any;\n\t\t}\n\t\tconst responseType = detectResponseType(response);\n\t\tconst successContext = {\n\t\t\tdata: \"\" as any,\n\t\t\tresponse,\n\t\t\trequest: context,\n\t\t};\n\t\tif (responseType === \"json\" || responseType === \"text\") {\n\t\t\tconst text = await response.text();\n\t\t\tconst parser = context.jsonParser ?? jsonParse;\n\t\t\tconst data = await parser(text);\n\t\t\tsuccessContext.data = data;\n\t\t} else {\n\t\t\tsuccessContext.data = await response[responseType]();\n\t\t}\n\n\t\t/**\n\t\t * Parse the data if the output schema is defined\n\t\t */\n\t\tif (context?.output) {\n\t\t\tif (context.output && !context.disableValidation) {\n\t\t\t\tsuccessContext.data = await parseStandardSchema(\n\t\t\t\t\tcontext.output as StandardSchemaV1,\n\t\t\t\t\tsuccessContext.data,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tfor (const onSuccess of hooks.onSuccess) {\n\t\t\tif (onSuccess) {\n\t\t\t\tawait onSuccess({\n\t\t\t\t\t...successContext,\n\t\t\t\t\tresponse: options?.hookOptions?.cloneResponse\n\t\t\t\t\t\t? response.clone()\n\t\t\t\t\t\t: response,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (options?.throw) {\n\t\t\treturn successContext.data as any;\n\t\t}\n\n\t\treturn {\n\t\t\tdata: successContext.data,\n\t\t\terror: null,\n\t\t} as any;\n\t}\n\tconst parser = options?.jsonParser ?? jsonParse;\n\tconst responseText = await response.text();\n\tconst isJSONResponse = isJSONParsable(responseText);\n\tconst errorObject = isJSONResponse ? await parser(responseText) : null;\n\t/**\n\t * Error Branch\n\t */\n\tconst errorContext = {\n\t\tresponse,\n\t\tresponseText,\n\t\trequest: context,\n\t\terror: {\n\t\t\t...errorObject,\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText,\n\t\t},\n\t};\n\tfor (const onError of hooks.onError) {\n\t\tif (onError) {\n\t\t\tawait onError({\n\t\t\t\t...errorContext,\n\t\t\t\tresponse: options?.hookOptions?.cloneResponse\n\t\t\t\t\t? response.clone()\n\t\t\t\t\t: response,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (options?.retry) {\n\t\tconst retryStrategy = createRetryStrategy(options.retry);\n\t\tconst _retryAttempt = options.retryAttempt ?? 0;\n\t\tif (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) {\n\t\t\tfor (const onRetry of hooks.onRetry) {\n\t\t\t\tif (onRetry) {\n\t\t\t\t\tawait onRetry(responseContext);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst delay = retryStrategy.getDelay(_retryAttempt);\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\t\treturn await betterFetch(url, {\n\t\t\t\t...options,\n\t\t\t\tretryAttempt: _retryAttempt + 1,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (options?.throw) {\n\t\tthrow new BetterFetchError(\n\t\t\tresponse.status,\n\t\t\tresponse.statusText,\n\t\t\tisJSONResponse ? errorObject : responseText,\n\t\t);\n\t}\n\treturn {\n\t\tdata: null,\n\t\terror: {\n\t\t\t...errorObject,\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText,\n\t\t},\n\t} as any;\n};\n","const _envShim = /* @__PURE__ */ Object.create(null);\nconst _getEnv = (useShim) => globalThis.process?.env || //@ts-expect-error\nglobalThis.Deno?.env.toObject() || //@ts-expect-error\nglobalThis.__env__ || (useShim ? _envShim : globalThis);\nconst env = new Proxy(_envShim, {\n get(_, prop) {\n const env2 = _getEnv();\n return env2[prop] ?? _envShim[prop];\n },\n has(_, prop) {\n const env2 = _getEnv();\n return prop in env2 || prop in _envShim;\n },\n set(_, prop, value) {\n const env2 = _getEnv(true);\n env2[prop] = value;\n return true;\n },\n deleteProperty(_, prop) {\n if (!prop) {\n return false;\n }\n const env2 = _getEnv(true);\n delete env2[prop];\n return true;\n },\n ownKeys() {\n const env2 = _getEnv(true);\n return Object.keys(env2);\n }\n});\nfunction toBoolean(val) {\n return val ? val !== \"false\" : false;\n}\nconst nodeENV = typeof process !== \"undefined\" && process.env && process.env.NODE_ENV || \"\";\nconst isProduction = nodeENV === \"production\";\nconst isDevelopment = nodeENV === \"dev\" || nodeENV === \"development\";\nconst isTest = nodeENV === \"test\" || toBoolean(env.TEST);\n\nexport { isProduction as a, isDevelopment as b, env as e, isTest as i };\n","class BetterAuthError extends Error {\n constructor(message, cause) {\n super(message);\n this.name = \"BetterAuthError\";\n this.message = message;\n this.cause = cause;\n this.stack = \"\";\n }\n}\nclass MissingDependencyError extends BetterAuthError {\n constructor(pkgName) {\n super(\n `The package \"${pkgName}\" is required. Make sure it is installed.`,\n pkgName\n );\n }\n}\n\nexport { BetterAuthError as B, MissingDependencyError as M };\n","import { e as env } from './better-auth.8zoxzg-F.mjs';\nimport { B as BetterAuthError } from './better-auth.DdzSJf-n.mjs';\n\nfunction checkHasPath(url) {\n try {\n const parsedUrl = new URL(url);\n return parsedUrl.pathname !== \"/\";\n } catch (error) {\n throw new BetterAuthError(\n `Invalid base URL: ${url}. Please provide a valid base URL.`\n );\n }\n}\nfunction withPath(url, path = \"/api/auth\") {\n const hasPath = checkHasPath(url);\n if (hasPath) {\n return url;\n }\n path = path.startsWith(\"/\") ? path : `/${path}`;\n return `${url.replace(/\\/+$/, \"\")}${path}`;\n}\nfunction getBaseURL(url, path, request) {\n if (url) {\n return withPath(url, path);\n }\n const fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== \"/\" ? env.BASE_URL : void 0);\n if (fromEnv) {\n return withPath(fromEnv, path);\n }\n const fromRequest = request?.headers.get(\"x-forwarded-host\");\n const fromRequestProto = request?.headers.get(\"x-forwarded-proto\");\n if (fromRequest && fromRequestProto) {\n return withPath(`${fromRequestProto}://${fromRequest}`, path);\n }\n if (request) {\n const url2 = getOrigin(request.url);\n if (!url2) {\n throw new BetterAuthError(\n \"Could not get origin from request. Please provide a valid base URL.\"\n );\n }\n return withPath(url2, path);\n }\n if (typeof window !== \"undefined\" && window.location) {\n return withPath(window.location.origin, path);\n }\n return void 0;\n}\nfunction getOrigin(url) {\n try {\n const parsedUrl = new URL(url);\n return parsedUrl.origin;\n } catch (error) {\n return null;\n }\n}\nfunction getProtocol(url) {\n try {\n const parsedUrl = new URL(url);\n return parsedUrl.protocol;\n } catch (error) {\n return null;\n }\n}\nfunction getHost(url) {\n try {\n const parsedUrl = new URL(url);\n return parsedUrl.host;\n } catch (error) {\n return url;\n }\n}\n\nexport { getBaseURL as a, getHost as b, getProtocol as c, getOrigin as g };\n","import { subtle } from 'uncrypto';\nimport { hex } from './hex.mjs';\nimport { base64Url, base64 } from './base64.mjs';\n\nconst createHMAC = (algorithm = \"SHA-256\", encoding = \"none\") => {\n const hmac = {\n importKey: async (key, keyUsage) => {\n return subtle.importKey(\n \"raw\",\n typeof key === \"string\" ? new TextEncoder().encode(key) : key,\n { name: \"HMAC\", hash: { name: algorithm } },\n false,\n [keyUsage]\n );\n },\n sign: async (hmacKey, data) => {\n if (typeof hmacKey === \"string\") {\n hmacKey = await hmac.importKey(hmacKey, \"sign\");\n }\n const signature = await subtle.sign(\n \"HMAC\",\n hmacKey,\n typeof data === \"string\" ? new TextEncoder().encode(data) : data\n );\n if (encoding === \"hex\") {\n return hex.encode(signature);\n }\n if (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n return base64Url.encode(signature, {\n padding: encoding !== \"base64urlnopad\"\n });\n }\n return signature;\n },\n verify: async (hmacKey, data, signature) => {\n if (typeof hmacKey === \"string\") {\n hmacKey = await hmac.importKey(hmacKey, \"verify\");\n }\n if (encoding === \"hex\") {\n signature = hex.decode(signature);\n }\n if (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n signature = await base64.decode(signature);\n }\n return subtle.verify(\n \"HMAC\",\n hmacKey,\n typeof signature === \"string\" ? new TextEncoder().encode(signature) : signature,\n typeof data === \"string\" ? new TextEncoder().encode(data) : data\n );\n }\n };\n return hmac;\n};\n\nexport { createHMAC };\n","function safeJSONParse(data) {\n function reviver(_, value) {\n if (typeof value === \"string\") {\n const iso8601Regex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/;\n if (iso8601Regex.test(value)) {\n const date = new Date(value);\n if (!isNaN(date.getTime())) {\n return date;\n }\n }\n }\n return value;\n }\n try {\n return JSON.parse(data, reviver);\n } catch {\n return null;\n }\n}\n\nexport { safeJSONParse as s };\n","const decoders = /* @__PURE__ */ new Map();\nconst encoder = new TextEncoder();\nconst binary = {\n decode: (data, encoding = \"utf-8\") => {\n if (!decoders.has(encoding)) {\n decoders.set(encoding, new TextDecoder(encoding));\n }\n const decoder = decoders.get(encoding);\n return decoder.decode(data);\n },\n encode: encoder.encode\n};\n\nexport { binary };\n","import { B as BetterAuthError } from '../shared/better-auth.DdzSJf-n.mjs';\nimport { g as getDate } from '../shared/better-auth.CW6D9eSx.mjs';\nimport { a as isProduction, e as env } from '../shared/better-auth.8zoxzg-F.mjs';\nimport { base64Url } from '@better-auth/utils/base64';\nimport { createHMAC } from '@better-auth/utils/hmac';\nimport { s as safeJSONParse } from '../shared/better-auth.tB5eU6EY.mjs';\nimport { a as getBaseURL } from '../shared/better-auth.VTXNLFMT.mjs';\nimport { binary } from '@better-auth/utils/binary';\n\nconst createTime = (value, format) => {\n const toMilliseconds = () => {\n switch (format) {\n case \"ms\":\n return value;\n case \"s\":\n return value * 1e3;\n case \"m\":\n return value * 1e3 * 60;\n case \"h\":\n return value * 1e3 * 60 * 60;\n case \"d\":\n return value * 1e3 * 60 * 60 * 24;\n case \"w\":\n return value * 1e3 * 60 * 60 * 24 * 7;\n case \"y\":\n return value * 1e3 * 60 * 60 * 24 * 365;\n }\n };\n const time = {\n t: `${value}${format}`,\n value,\n tFormat: format,\n toMilliseconds,\n toSeconds: () => time.toMilliseconds() / 1e3,\n toMinutes: () => time.toSeconds() / 60,\n toHours: () => time.toMinutes() / 60,\n toDays: () => time.toHours() / 24,\n toWeeks: () => time.toDays() / 7,\n toYears: () => time.toDays() / 365,\n getDate: () => new Date(Date.now() + time.toMilliseconds()),\n add: (other) => {\n const otherMs = typeof other === \"string\" ? parseTime(other).toMilliseconds() : other.toMilliseconds();\n return createTime(time.toMilliseconds() + otherMs, \"ms\");\n },\n subtract: (other) => {\n const otherMs = typeof other === \"string\" ? parseTime(other).toMilliseconds() : other.toMilliseconds();\n return createTime(time.toMilliseconds() - otherMs, \"ms\");\n },\n multiply: (factor) => createTime(time.toMilliseconds() * factor, \"ms\"),\n divide: (divisor) => createTime(time.toMilliseconds() / divisor, \"ms\"),\n equals: (other) => {\n const otherMs = typeof other === \"string\" ? parseTime(other).toMilliseconds() : other.toMilliseconds();\n return time.toMilliseconds() === otherMs;\n },\n lessThan: (other) => {\n const otherMs = typeof other === \"string\" ? parseTime(other).toMilliseconds() : other.toMilliseconds();\n return time.toMilliseconds() < otherMs;\n },\n greaterThan: (other) => {\n const otherMs = typeof other === \"string\" ? parseTime(other).toMilliseconds() : other.toMilliseconds();\n return time.toMilliseconds() > otherMs;\n },\n format: (pattern) => {\n const date = time.getDate();\n return pattern.replace(/YYYY|MM|DD|HH|mm|ss/g, (match) => {\n switch (match) {\n case \"YYYY\":\n return date.getFullYear().toString();\n case \"MM\":\n return (date.getMonth() + 1).toString().padStart(2, \"0\");\n case \"DD\":\n return date.getDate().toString().padStart(2, \"0\");\n case \"HH\":\n return date.getHours().toString().padStart(2, \"0\");\n case \"mm\":\n return date.getMinutes().toString().padStart(2, \"0\");\n case \"ss\":\n return date.getSeconds().toString().padStart(2, \"0\");\n default:\n return match;\n }\n });\n },\n fromNow: () => {\n const ms = time.toMilliseconds();\n if (ms < 0) return time.ago();\n if (ms < 1e3) return \"in a few seconds\";\n if (ms < 6e4) return `in ${Math.round(ms / 1e3)} seconds`;\n if (ms < 36e5) return `in ${Math.round(ms / 6e4)} minutes`;\n if (ms < 864e5) return `in ${Math.round(ms / 36e5)} hours`;\n if (ms < 6048e5) return `in ${Math.round(ms / 864e5)} days`;\n if (ms < 26298e5) return `in ${Math.round(ms / 6048e5)} weeks`;\n if (ms < 315576e5) return `in ${Math.round(ms / 26298e5)} months`;\n return `in ${Math.round(ms / 315576e5)} years`;\n },\n ago: () => {\n const ms = -time.toMilliseconds();\n if (ms < 0) return time.fromNow();\n if (ms < 1e3) return \"a few seconds ago\";\n if (ms < 6e4) return `${Math.round(ms / 1e3)} seconds ago`;\n if (ms < 36e5) return `${Math.round(ms / 6e4)} minutes ago`;\n if (ms < 864e5) return `${Math.round(ms / 36e5)} hours ago`;\n if (ms < 6048e5) return `${Math.round(ms / 864e5)} days ago`;\n if (ms < 26298e5) return `${Math.round(ms / 6048e5)} weeks ago`;\n if (ms < 315576e5) return `${Math.round(ms / 26298e5)} months ago`;\n return `${Math.round(ms / 315576e5)} years ago`;\n }\n };\n return time;\n};\nconst parseTime = (time) => {\n const match = time.match(/^(\\d+)(ms|s|m|h|d|w|y)$/);\n if (!match) throw new Error(\"Invalid time format\");\n return createTime(parseInt(match[1]), match[2]);\n};\n\nfunction parseSetCookieHeader(setCookie) {\n const cookies = /* @__PURE__ */ new Map();\n const cookieArray = setCookie.split(\", \");\n cookieArray.forEach((cookieString) => {\n const parts = cookieString.split(\";\").map((part) => part.trim());\n const [nameValue, ...attributes] = parts;\n const [name, ...valueParts] = nameValue.split(\"=\");\n const value = valueParts.join(\"=\");\n if (!name || value === void 0) {\n return;\n }\n const attrObj = { value };\n attributes.forEach((attribute) => {\n const [attrName, ...attrValueParts] = attribute.split(\"=\");\n const attrValue = attrValueParts.join(\"=\");\n const normalizedAttrName = attrName.trim().toLowerCase();\n switch (normalizedAttrName) {\n case \"max-age\":\n attrObj[\"max-age\"] = attrValue ? parseInt(attrValue.trim(), 10) : void 0;\n break;\n case \"expires\":\n attrObj.expires = attrValue ? new Date(attrValue.trim()) : void 0;\n break;\n case \"domain\":\n attrObj.domain = attrValue ? attrValue.trim() : void 0;\n break;\n case \"path\":\n attrObj.path = attrValue ? attrValue.trim() : void 0;\n break;\n case \"secure\":\n attrObj.secure = true;\n break;\n case \"httponly\":\n attrObj.httponly = true;\n break;\n case \"samesite\":\n attrObj.samesite = attrValue ? attrValue.trim().toLowerCase() : void 0;\n break;\n default:\n attrObj[normalizedAttrName] = attrValue ? attrValue.trim() : true;\n break;\n }\n });\n cookies.set(name, attrObj);\n });\n return cookies;\n}\nfunction setCookieToHeader(headers) {\n return (context) => {\n const setCookieHeader = context.response.headers.get(\"set-cookie\");\n if (!setCookieHeader) {\n return;\n }\n const cookieMap = /* @__PURE__ */ new Map();\n const existingCookiesHeader = headers.get(\"cookie\") || \"\";\n existingCookiesHeader.split(\";\").forEach((cookie) => {\n const [name, ...rest] = cookie.trim().split(\"=\");\n if (name && rest.length > 0) {\n cookieMap.set(name, rest.join(\"=\"));\n }\n });\n const setCookieHeaders = setCookieHeader.split(\",\");\n setCookieHeaders.forEach((header) => {\n const cookies = parseSetCookieHeader(header);\n cookies.forEach((value, name) => {\n cookieMap.set(name, value.value);\n });\n });\n const updatedCookies = Array.from(cookieMap.entries()).map(([name, value]) => `${name}=${value}`).join(\"; \");\n headers.set(\"cookie\", updatedCookies);\n };\n}\n\nfunction createCookieGetter(options) {\n const secure = options.advanced?.useSecureCookies !== void 0 ? options.advanced?.useSecureCookies : options.baseURL !== void 0 ? options.baseURL.startsWith(\"https://\") ? true : false : isProduction;\n const secureCookiePrefix = secure ? \"__Secure-\" : \"\";\n const crossSubdomainEnabled = !!options.advanced?.crossSubDomainCookies?.enabled;\n const domain = crossSubdomainEnabled ? options.advanced?.crossSubDomainCookies?.domain || (options.baseURL ? new URL(options.baseURL).hostname : void 0) : void 0;\n if (crossSubdomainEnabled && !domain) {\n throw new BetterAuthError(\n \"baseURL is required when crossSubdomainCookies are enabled\"\n );\n }\n function createCookie(cookieName, overrideAttributes = {}) {\n const prefix = options.advanced?.cookiePrefix || \"better-auth\";\n const name = options.advanced?.cookies?.[cookieName]?.name || `${prefix}.${cookieName}`;\n const attributes = options.advanced?.cookies?.[cookieName]?.attributes;\n return {\n name: `${secureCookiePrefix}${name}`,\n attributes: {\n secure: !!secureCookiePrefix,\n sameSite: \"lax\",\n path: \"/\",\n httpOnly: true,\n ...crossSubdomainEnabled ? { domain } : {},\n ...options.advanced?.defaultCookieAttributes,\n ...overrideAttributes,\n ...attributes\n }\n };\n }\n return createCookie;\n}\nfunction getCookies(options) {\n const createCookie = createCookieGetter(options);\n const sessionMaxAge = options.session?.expiresIn || createTime(7, \"d\").toSeconds();\n const sessionToken = createCookie(\"session_token\", {\n maxAge: sessionMaxAge\n });\n const sessionData = createCookie(\"session_data\", {\n maxAge: options.session?.cookieCache?.maxAge || 60 * 5\n });\n const dontRememberToken = createCookie(\"dont_remember\");\n return {\n sessionToken: {\n name: sessionToken.name,\n options: sessionToken.attributes\n },\n /**\n * This cookie is used to store the session data in the cookie\n * This is useful for when you want to cache the session in the cookie\n */\n sessionData: {\n name: sessionData.name,\n options: sessionData.attributes\n },\n dontRememberToken: {\n name: dontRememberToken.name,\n options: dontRememberToken.attributes\n }\n };\n}\nasync function setCookieCache(ctx, session) {\n const shouldStoreSessionDataInCookie = ctx.context.options.session?.cookieCache?.enabled;\n if (shouldStoreSessionDataInCookie) {\n const filteredSession = Object.entries(session.session).reduce(\n (acc, [key, value]) => {\n const fieldConfig = ctx.context.options.session?.additionalFields?.[key];\n if (!fieldConfig || fieldConfig.returned !== false) {\n acc[key] = value;\n }\n return acc;\n },\n {}\n );\n const sessionData = { session: filteredSession, user: session.user };\n const data = base64Url.encode(\n JSON.stringify({\n session: sessionData,\n expiresAt: getDate(\n ctx.context.authCookies.sessionData.options.maxAge || 60,\n \"sec\"\n ).getTime(),\n signature: await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(\n ctx.context.secret,\n JSON.stringify({\n ...sessionData,\n expiresAt: getDate(\n ctx.context.authCookies.sessionData.options.maxAge || 60,\n \"sec\"\n ).getTime()\n })\n )\n }),\n {\n padding: false\n }\n );\n if (data.length > 4093) {\n throw new BetterAuthError(\n \"Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data\"\n );\n }\n ctx.setCookie(\n ctx.context.authCookies.sessionData.name,\n data,\n ctx.context.authCookies.sessionData.options\n );\n }\n}\nasync function setSessionCookie(ctx, session, dontRememberMe, overrides) {\n const dontRememberMeCookie = await ctx.getSignedCookie(\n ctx.context.authCookies.dontRememberToken.name,\n ctx.context.secret\n );\n dontRememberMe = dontRememberMe !== void 0 ? dontRememberMe : !!dontRememberMeCookie;\n const options = ctx.context.authCookies.sessionToken.options;\n const maxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn;\n await ctx.setSignedCookie(\n ctx.context.authCookies.sessionToken.name,\n session.session.token,\n ctx.context.secret,\n {\n ...options,\n maxAge,\n ...overrides\n }\n );\n if (dontRememberMe) {\n await ctx.setSignedCookie(\n ctx.context.authCookies.dontRememberToken.name,\n \"true\",\n ctx.context.secret,\n ctx.context.authCookies.dontRememberToken.options\n );\n }\n await setCookieCache(ctx, session);\n ctx.context.setNewSession(session);\n if (ctx.context.options.secondaryStorage) {\n await ctx.context.secondaryStorage?.set(\n session.session.token,\n JSON.stringify({\n user: session.user,\n session: session.session\n }),\n Math.floor(\n (new Date(session.session.expiresAt).getTime() - Date.now()) / 1e3\n )\n );\n }\n}\nfunction deleteSessionCookie(ctx, skipDontRememberMe) {\n ctx.setCookie(ctx.context.authCookies.sessionToken.name, \"\", {\n ...ctx.context.authCookies.sessionToken.options,\n maxAge: 0\n });\n ctx.setCookie(ctx.context.authCookies.sessionData.name, \"\", {\n ...ctx.context.authCookies.sessionData.options,\n maxAge: 0\n });\n if (!skipDontRememberMe) {\n ctx.setCookie(ctx.context.authCookies.dontRememberToken.name, \"\", {\n ...ctx.context.authCookies.dontRememberToken.options,\n maxAge: 0\n });\n }\n}\nfunction parseCookies(cookieHeader) {\n const cookies = cookieHeader.split(\"; \");\n const cookieMap = /* @__PURE__ */ new Map();\n cookies.forEach((cookie) => {\n const [name, value] = cookie.split(\"=\");\n cookieMap.set(name, value);\n });\n return cookieMap;\n}\nconst getSessionCookie = (request, config) => {\n if (config?.cookiePrefix) {\n if (config.cookieName) {\n config.cookiePrefix = `${config.cookiePrefix}-`;\n } else {\n config.cookiePrefix = `${config.cookiePrefix}.`;\n }\n }\n const headers = \"headers\" in request ? request.headers : request;\n const req = request instanceof Request ? request : void 0;\n getBaseURL(req?.url, config?.path, req);\n const cookies = headers.get(\"cookie\");\n if (!cookies) {\n return null;\n }\n const { cookieName = \"session_token\", cookiePrefix = \"better-auth.\" } = config || {};\n const name = `${cookiePrefix}${cookieName}`;\n const secureCookieName = `__Secure-${name}`;\n const parsedCookie = parseCookies(cookies);\n const sessionToken = parsedCookie.get(name) || parsedCookie.get(secureCookieName);\n if (sessionToken) {\n return sessionToken;\n }\n return null;\n};\nconst getCookieCache = async (request, config) => {\n const headers = request instanceof Headers ? request : request.headers;\n const cookies = headers.get(\"cookie\");\n if (!cookies) {\n return null;\n }\n const { cookieName = \"session_data\", cookiePrefix = \"better-auth\" } = config || {};\n const name = config?.isSecure !== void 0 ? config.isSecure ? `__Secure-${cookiePrefix}.${cookieName}` : `${cookiePrefix}.${cookieName}` : isProduction ? `__Secure-${cookiePrefix}.${cookieName}` : `${cookiePrefix}.${cookieName}`;\n const parsedCookie = parseCookies(cookies);\n const sessionData = parsedCookie.get(name);\n if (sessionData) {\n const sessionDataPayload = safeJSONParse(binary.decode(base64Url.decode(sessionData)));\n if (!sessionDataPayload) {\n return null;\n }\n const secret = config?.secret || env.BETTER_AUTH_SECRET;\n if (!secret) {\n throw new BetterAuthError(\n \"getCookieCache requires a secret to be provided. Either pass it as an option or set the BETTER_AUTH_SECRET environment variable\"\n );\n }\n const isValid = await createHMAC(\"SHA-256\", \"base64urlnopad\").verify(\n secret,\n JSON.stringify({\n ...sessionDataPayload.session,\n expiresAt: sessionDataPayload.expiresAt\n }),\n sessionDataPayload.signature\n );\n if (!isValid) {\n return null;\n }\n return sessionDataPayload.session;\n }\n return null;\n};\n\nexport { createCookieGetter, deleteSessionCookie, getCookieCache, getCookies, getSessionCookie, parseCookies, parseSetCookieHeader, setCookieCache, setCookieToHeader, setSessionCookie };\n","import { createRandomStringGenerator } from '@better-auth/utils/random';\n\nconst generateId = (size) => {\n return createRandomStringGenerator(\"a-z\", \"A-Z\", \"0-9\")(size || 32);\n};\n\nconst levels = [\"info\", \"success\", \"warn\", \"error\", \"debug\"];\nfunction shouldPublishLog(currentLogLevel, logLevel) {\n return levels.indexOf(logLevel) <= levels.indexOf(currentLogLevel);\n}\nconst colors = {\n reset: \"\\x1B[0m\",\n bright: \"\\x1B[1m\",\n dim: \"\\x1B[2m\",\n fg: {\n red: \"\\x1B[31m\",\n green: \"\\x1B[32m\",\n yellow: \"\\x1B[33m\",\n blue: \"\\x1B[34m\",\n magenta: \"\\x1B[35m\"}};\nconst levelColors = {\n info: colors.fg.blue,\n success: colors.fg.green,\n warn: colors.fg.yellow,\n error: colors.fg.red,\n debug: colors.fg.magenta\n};\nconst formatMessage = (level, message) => {\n const timestamp = (/* @__PURE__ */ new Date()).toISOString();\n return `${colors.dim}${timestamp}${colors.reset} ${levelColors[level]}${level.toUpperCase()}${colors.reset} ${colors.bright}[Better Auth]:${colors.reset} ${message}`;\n};\nconst createLogger = (options) => {\n const enabled = options?.disabled !== true;\n const logLevel = options?.level ?? \"error\";\n const LogFunc = (level, message, args = []) => {\n if (!enabled || !shouldPublishLog(logLevel, level)) {\n return;\n }\n const formattedMessage = formatMessage(level, message);\n if (!options || typeof options.log !== \"function\") {\n if (level === \"error\") {\n console.error(formattedMessage, ...args);\n } else if (level === \"warn\") {\n console.warn(formattedMessage, ...args);\n } else {\n console.log(formattedMessage, ...args);\n }\n return;\n }\n options.log(level === \"success\" ? \"info\" : level, message, ...args);\n };\n return Object.fromEntries(\n levels.map((level) => [\n level,\n (...[message, ...args]) => LogFunc(level, message, args)\n ])\n );\n};\nconst logger = createLogger();\n\nexport { logger as a, createLogger as c, generateId as g, levels as l, shouldPublishLog as s };\n","import * as z from 'zod/v4';\nimport { APIError } from 'better-call';\n\nconst accountSchema = z.object({\n id: z.string(),\n providerId: z.string(),\n accountId: z.string(),\n userId: z.coerce.string(),\n accessToken: z.string().nullish(),\n refreshToken: z.string().nullish(),\n idToken: z.string().nullish(),\n /**\n * Access token expires at\n */\n accessTokenExpiresAt: z.date().nullish(),\n /**\n * Refresh token expires at\n */\n refreshTokenExpiresAt: z.date().nullish(),\n /**\n * The scopes that the user has authorized\n */\n scope: z.string().nullish(),\n /**\n * Password is only stored in the credential provider\n */\n password: z.string().nullish(),\n createdAt: z.date().default(() => /* @__PURE__ */ new Date()),\n updatedAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nconst userSchema = z.object({\n id: z.string(),\n email: z.string().transform((val) => val.toLowerCase()),\n emailVerified: z.boolean().default(false),\n name: z.string(),\n image: z.string().nullish(),\n createdAt: z.date().default(() => /* @__PURE__ */ new Date()),\n updatedAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nconst sessionSchema = z.object({\n id: z.string(),\n userId: z.coerce.string(),\n expiresAt: z.date(),\n createdAt: z.date().default(() => /* @__PURE__ */ new Date()),\n updatedAt: z.date().default(() => /* @__PURE__ */ new Date()),\n token: z.string(),\n ipAddress: z.string().nullish(),\n userAgent: z.string().nullish()\n});\nconst verificationSchema = z.object({\n id: z.string(),\n value: z.string(),\n createdAt: z.date().default(() => /* @__PURE__ */ new Date()),\n updatedAt: z.date().default(() => /* @__PURE__ */ new Date()),\n expiresAt: z.date(),\n identifier: z.string()\n});\nfunction parseOutputData(data, schema) {\n const fields = schema.fields;\n const parsedData = {};\n for (const key in data) {\n const field = fields[key];\n if (!field) {\n parsedData[key] = data[key];\n continue;\n }\n if (field.returned === false) {\n continue;\n }\n parsedData[key] = data[key];\n }\n return parsedData;\n}\nfunction getAllFields(options, table) {\n let schema = {\n ...table === \"user\" ? options.user?.additionalFields : {},\n ...table === \"session\" ? options.session?.additionalFields : {}\n };\n for (const plugin of options.plugins || []) {\n if (plugin.schema && plugin.schema[table]) {\n schema = {\n ...schema,\n ...plugin.schema[table].fields\n };\n }\n }\n return schema;\n}\nfunction parseUserOutput(options, user) {\n const schema = getAllFields(options, \"user\");\n return parseOutputData(user, { fields: schema });\n}\nfunction parseAccountOutput(options, account) {\n const schema = getAllFields(options, \"account\");\n return parseOutputData(account, { fields: schema });\n}\nfunction parseSessionOutput(options, session) {\n const schema = getAllFields(options, \"session\");\n return parseOutputData(session, { fields: schema });\n}\nfunction parseInputData(data, schema) {\n const action = schema.action || \"create\";\n const fields = schema.fields;\n const parsedData = {};\n for (const key in fields) {\n if (key in data) {\n if (fields[key].input === false) {\n if (fields[key].defaultValue) {\n parsedData[key] = fields[key].defaultValue;\n continue;\n }\n continue;\n }\n if (fields[key].validator?.input && data[key] !== void 0) {\n parsedData[key] = fields[key].validator.input.parse(data[key]);\n continue;\n }\n if (fields[key].transform?.input && data[key] !== void 0) {\n parsedData[key] = fields[key].transform?.input(data[key]);\n continue;\n }\n parsedData[key] = data[key];\n continue;\n }\n if (fields[key].defaultValue && action === \"create\") {\n parsedData[key] = fields[key].defaultValue;\n continue;\n }\n if (fields[key].required && action === \"create\") {\n throw new APIError(\"BAD_REQUEST\", {\n message: `${key} is required`\n });\n }\n }\n return parsedData;\n}\nfunction parseUserInput(options, user, action) {\n const schema = getAllFields(options, \"user\");\n return parseInputData(user || {}, { fields: schema, action });\n}\nfunction parseAdditionalUserInput(options, user) {\n const schema = getAllFields(options, \"user\");\n return parseInputData(user || {}, { fields: schema });\n}\nfunction parseAccountInput(options, account) {\n const schema = getAllFields(options, \"account\");\n return parseInputData(account, { fields: schema });\n}\nfunction parseSessionInput(options, session) {\n const schema = getAllFields(options, \"session\");\n return parseInputData(session, { fields: schema });\n}\nfunction mergeSchema(schema, newSchema) {\n if (!newSchema) {\n return schema;\n }\n for (const table in newSchema) {\n const newModelName = newSchema[table]?.modelName;\n if (newModelName) {\n schema[table].modelName = newModelName;\n }\n for (const field in schema[table].fields) {\n const newField = newSchema[table]?.fields?.[field];\n if (!newField) {\n continue;\n }\n schema[table].fields[field].fieldName = newField;\n }\n }\n return schema;\n}\n\nexport { accountSchema as a, parseUserOutput as b, parseAccountOutput as c, parseSessionOutput as d, parseInputData as e, parseUserInput as f, getAllFields as g, parseAdditionalUserInput as h, parseAccountInput as i, parseSessionInput as j, mergeSchema as m, parseOutputData as p, sessionSchema as s, userSchema as u, verificationSchema as v };\n","function isPlainObject(value) {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {\n return false;\n }\n if (Symbol.iterator in value) {\n return false;\n }\n if (Symbol.toStringTag in value) {\n return Object.prototype.toString.call(value) === \"[object Module]\";\n }\n return true;\n}\n\nfunction _defu(baseObject, defaults, namespace = \".\", merger) {\n if (!isPlainObject(defaults)) {\n return _defu(baseObject, {}, namespace, merger);\n }\n const object = Object.assign({}, defaults);\n for (const key in baseObject) {\n if (key === \"__proto__\" || key === \"constructor\") {\n continue;\n }\n const value = baseObject[key];\n if (value === null || value === void 0) {\n continue;\n }\n if (merger && merger(object, key, value, namespace)) {\n continue;\n }\n if (Array.isArray(value) && Array.isArray(object[key])) {\n object[key] = [...value, ...object[key]];\n } else if (isPlainObject(value) && isPlainObject(object[key])) {\n object[key] = _defu(\n value,\n object[key],\n (namespace ? `${namespace}.` : \"\") + key.toString(),\n merger\n );\n } else {\n object[key] = value;\n }\n }\n return object;\n}\nfunction createDefu(merger) {\n return (...arguments_) => (\n // eslint-disable-next-line unicorn/no-array-reduce\n arguments_.reduce((p, c) => _defu(p, c, \"\", merger), {})\n );\n}\nconst defu = createDefu();\nconst defuFn = createDefu((object, key, currentValue) => {\n if (object[key] !== void 0 && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\nconst defuArrayFn = createDefu((object, key, currentValue) => {\n if (Array.isArray(object[key]) && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\n\nexport { createDefu, defu as default, defu, defuArrayFn, defuFn };\n","import { APIError, toResponse, createRouter } from 'better-call';\nexport { APIError } from 'better-call';\nimport { j as createAuthEndpoint, B as BASE_ERROR_CODES, w as createEmailVerificationToken, x as wildcardMatch, y as listSessions, z as updateUser, m as getSession, A as originCheckMiddleware, C as error, D as ok, E as accountInfo, F as getAccessToken, G as refreshToken, I as unlinkAccount, J as deleteUserCallback, K as listUserAccounts, L as linkSocialAccount, M as revokeOtherSessions, N as revokeSessions, O as revokeSession, P as requestPasswordResetCallback, Q as requestPasswordReset, R as forgetPasswordCallback, S as deleteUser, T as setPassword, U as changePassword, V as changeEmail, W as sendVerificationEmail, X as verifyEmail, Y as resetPassword, Z as forgetPassword, _ as signInEmail, $ as signOut, a0 as callbackOAuth, a1 as signInSocial } from '../shared/better-auth.D4HhkCZJ.mjs';\nexport { i as createAuthMiddleware, n as freshSessionMiddleware, k as getSessionFromCtx, q as optionsMiddleware, o as originCheck, a2 as requestOnlySessionMiddleware, u as sendVerificationEmailFn, l as sessionMiddleware } from '../shared/better-auth.D4HhkCZJ.mjs';\nimport * as z from 'zod/v4';\nimport { setSessionCookie } from '../cookies/index.mjs';\nimport { f as parseUserInput } from '../shared/better-auth.n2KFGwjY.mjs';\nimport { b as isDevelopment } from '../shared/better-auth.8zoxzg-F.mjs';\nimport { a as logger } from '../shared/better-auth.DBGfIDnh.mjs';\nimport { g as getIp } from '../shared/better-auth.DcfNPS8q.mjs';\nimport defu from 'defu';\nimport '../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-auth/utils/hash';\nimport '@better-auth/utils/base64';\nimport '../crypto/index.mjs';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '@better-fetch/fetch';\nimport '../shared/better-auth.VTXNLFMT.mjs';\nimport '../shared/better-auth.DdzSJf-n.mjs';\nimport '../shared/better-auth.tB5eU6EY.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'jose/errors';\n\nconst signUpEmail = () => createAuthEndpoint(\n \"/sign-up/email\",\n {\n method: \"POST\",\n body: z.record(z.string(), z.any()),\n metadata: {\n $Infer: {\n body: {}\n },\n openapi: {\n description: \"Sign up a user using email and password\",\n requestBody: {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description: \"The name of the user\"\n },\n email: {\n type: \"string\",\n description: \"The email of the user\"\n },\n password: {\n type: \"string\",\n description: \"The password of the user\"\n },\n image: {\n type: \"string\",\n description: \"The profile image URL of the user\"\n },\n callbackURL: {\n type: \"string\",\n description: \"The URL to use for email verification callback\"\n },\n rememberMe: {\n type: \"boolean\",\n description: \"If this is false, the session will not be remembered. Default is `true`.\"\n }\n },\n required: [\"name\", \"email\", \"password\"]\n }\n }\n }\n },\n responses: {\n \"200\": {\n description: \"Successfully created user\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n token: {\n type: \"string\",\n nullable: true,\n description: \"Authentication token for the session\"\n },\n user: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"The unique identifier of the user\"\n },\n email: {\n type: \"string\",\n format: \"email\",\n description: \"The email address of the user\"\n },\n name: {\n type: \"string\",\n description: \"The name of the user\"\n },\n image: {\n type: \"string\",\n format: \"uri\",\n nullable: true,\n description: \"The profile image URL of the user\"\n },\n emailVerified: {\n type: \"boolean\",\n description: \"Whether the email has been verified\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"When the user was created\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"When the user was last updated\"\n }\n },\n required: [\n \"id\",\n \"email\",\n \"name\",\n \"emailVerified\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n },\n required: [\"user\"]\n // token is optional\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.context.options.emailAndPassword?.enabled || ctx.context.options.emailAndPassword?.disableSignUp) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Email and password sign up is not enabled\"\n });\n }\n const body = ctx.body;\n const {\n name,\n email,\n password,\n image,\n callbackURL,\n rememberMe,\n ...additionalFields\n } = body;\n const isValidEmail = z.email().safeParse(email);\n if (!isValidEmail.success) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.INVALID_EMAIL\n });\n }\n const minPasswordLength = ctx.context.password.config.minPasswordLength;\n if (password.length < minPasswordLength) {\n ctx.context.logger.error(\"Password is too short\");\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT\n });\n }\n const maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n if (password.length > maxPasswordLength) {\n ctx.context.logger.error(\"Password is too long\");\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.PASSWORD_TOO_LONG\n });\n }\n const dbUser = await ctx.context.internalAdapter.findUserByEmail(email);\n if (dbUser?.user) {\n ctx.context.logger.info(`Sign-up attempt for existing email: ${email}`);\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: BASE_ERROR_CODES.USER_ALREADY_EXISTS\n });\n }\n const additionalData = parseUserInput(\n ctx.context.options,\n additionalFields\n );\n const hash = await ctx.context.password.hash(password);\n let createdUser;\n try {\n createdUser = await ctx.context.internalAdapter.createUser(\n {\n email: email.toLowerCase(),\n name,\n image,\n ...additionalData,\n emailVerified: false\n },\n ctx\n );\n if (!createdUser) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER\n });\n }\n } catch (e) {\n if (isDevelopment) {\n ctx.context.logger.error(\"Failed to create user\", e);\n }\n if (e instanceof APIError) {\n throw e;\n }\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER,\n details: e\n });\n }\n if (!createdUser) {\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER\n });\n }\n await ctx.context.internalAdapter.linkAccount(\n {\n userId: createdUser.id,\n providerId: \"credential\",\n accountId: createdUser.id,\n password: hash\n },\n ctx\n );\n if (ctx.context.options.emailVerification?.sendOnSignUp || ctx.context.options.emailAndPassword.requireEmailVerification) {\n const token = await createEmailVerificationToken(\n ctx.context.secret,\n createdUser.email,\n void 0,\n ctx.context.options.emailVerification?.expiresIn\n );\n const url = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${body.callbackURL || \"/\"}`;\n await ctx.context.options.emailVerification?.sendVerificationEmail?.(\n {\n user: createdUser,\n url,\n token\n },\n ctx.request\n );\n }\n if (ctx.context.options.emailAndPassword.autoSignIn === false || ctx.context.options.emailAndPassword.requireEmailVerification) {\n return ctx.json({\n token: null,\n user: {\n id: createdUser.id,\n email: createdUser.email,\n name: createdUser.name,\n image: createdUser.image,\n emailVerified: createdUser.emailVerified,\n createdAt: createdUser.createdAt,\n updatedAt: createdUser.updatedAt\n }\n });\n }\n const session = await ctx.context.internalAdapter.createSession(\n createdUser.id,\n ctx,\n rememberMe === false\n );\n if (!session) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION\n });\n }\n await setSessionCookie(\n ctx,\n {\n session,\n user: createdUser\n },\n rememberMe === false\n );\n return ctx.json({\n token: session.token,\n user: {\n id: createdUser.id,\n email: createdUser.email,\n name: createdUser.name,\n image: createdUser.image,\n emailVerified: createdUser.emailVerified,\n createdAt: createdUser.createdAt,\n updatedAt: createdUser.updatedAt\n }\n });\n }\n);\n\nfunction shouldRateLimit(max, window, rateLimitData) {\n const now = Date.now();\n const windowInMs = window * 1e3;\n const timeSinceLastRequest = now - rateLimitData.lastRequest;\n return timeSinceLastRequest < windowInMs && rateLimitData.count >= max;\n}\nfunction rateLimitResponse(retryAfter) {\n return new Response(\n JSON.stringify({\n message: \"Too many requests. Please try again later.\"\n }),\n {\n status: 429,\n statusText: \"Too Many Requests\",\n headers: {\n \"X-Retry-After\": retryAfter.toString()\n }\n }\n );\n}\nfunction getRetryAfter(lastRequest, window) {\n const now = Date.now();\n const windowInMs = window * 1e3;\n return Math.ceil((lastRequest + windowInMs - now) / 1e3);\n}\nfunction createDBStorage(ctx) {\n const model = \"rateLimit\";\n const db = ctx.adapter;\n return {\n get: async (key) => {\n const res = await db.findMany({\n model,\n where: [{ field: \"key\", value: key }]\n });\n const data = res[0];\n if (typeof data?.lastRequest === \"bigint\") {\n data.lastRequest = Number(data.lastRequest);\n }\n return data;\n },\n set: async (key, value, _update) => {\n try {\n if (_update) {\n await db.updateMany({\n model,\n where: [{ field: \"key\", value: key }],\n update: {\n count: value.count,\n lastRequest: value.lastRequest\n }\n });\n } else {\n await db.create({\n model,\n data: {\n key,\n count: value.count,\n lastRequest: value.lastRequest\n }\n });\n }\n } catch (e) {\n ctx.logger.error(\"Error setting rate limit\", e);\n }\n }\n };\n}\nconst memory = /* @__PURE__ */ new Map();\nfunction getRateLimitStorage(ctx) {\n if (ctx.options.rateLimit?.customStorage) {\n return ctx.options.rateLimit.customStorage;\n }\n if (ctx.rateLimit.storage === \"secondary-storage\") {\n return {\n get: async (key) => {\n const stringified = await ctx.options.secondaryStorage?.get(key);\n return stringified ? JSON.parse(stringified) : void 0;\n },\n set: async (key, value) => {\n await ctx.options.secondaryStorage?.set?.(key, JSON.stringify(value));\n }\n };\n }\n const storage = ctx.rateLimit.storage;\n if (storage === \"memory\") {\n return {\n async get(key) {\n return memory.get(key);\n },\n async set(key, value, _update) {\n memory.set(key, value);\n }\n };\n }\n return createDBStorage(ctx);\n}\nasync function onRequestRateLimit(req, ctx) {\n if (!ctx.rateLimit.enabled) {\n return;\n }\n const path = new URL(req.url).pathname.replace(\n ctx.options.basePath || \"/api/auth\",\n \"\"\n );\n let window = ctx.rateLimit.window;\n let max = ctx.rateLimit.max;\n const ip = getIp(req, ctx.options);\n if (!ip) {\n console.warn(\"No IP address found for rate limiting\");\n return;\n }\n const key = ip + path;\n const specialRules = getDefaultSpecialRules();\n const specialRule = specialRules.find((rule) => rule.pathMatcher(path));\n if (specialRule) {\n window = specialRule.window;\n max = specialRule.max;\n }\n for (const plugin of ctx.options.plugins || []) {\n if (plugin.rateLimit) {\n const matchedRule = plugin.rateLimit.find(\n (rule) => rule.pathMatcher(path)\n );\n if (matchedRule) {\n window = matchedRule.window;\n max = matchedRule.max;\n break;\n }\n }\n }\n if (ctx.rateLimit.customRules) {\n const _path = Object.keys(ctx.rateLimit.customRules).find((p) => {\n if (p.includes(\"*\")) {\n const isMatch = wildcardMatch(p)(path);\n return isMatch;\n }\n return p === path;\n });\n if (_path) {\n const customRule = ctx.rateLimit.customRules[_path];\n const resolved = typeof customRule === \"function\" ? await customRule(req) : customRule;\n if (resolved) {\n window = resolved.window;\n max = resolved.max;\n }\n }\n }\n const storage = getRateLimitStorage(ctx);\n const data = await storage.get(key);\n const now = Date.now();\n if (!data) {\n await storage.set(key, {\n key,\n count: 1,\n lastRequest: now\n });\n } else {\n const timeSinceLastRequest = now - data.lastRequest;\n if (shouldRateLimit(max, window, data)) {\n const retryAfter = getRetryAfter(data.lastRequest, window);\n return rateLimitResponse(retryAfter);\n } else if (timeSinceLastRequest > window * 1e3) {\n await storage.set(\n key,\n {\n ...data,\n count: 1,\n lastRequest: now\n },\n true\n );\n } else {\n await storage.set(\n key,\n {\n ...data,\n count: data.count + 1,\n lastRequest: now\n },\n true\n );\n }\n }\n}\nfunction getDefaultSpecialRules() {\n const specialRules = [\n {\n pathMatcher(path) {\n return path.startsWith(\"/sign-in\") || path.startsWith(\"/sign-up\") || path.startsWith(\"/change-password\") || path.startsWith(\"/change-email\");\n },\n window: 10,\n max: 3\n }\n ];\n return specialRules;\n}\n\nfunction toAuthEndpoints(endpoints, ctx) {\n const api = {};\n for (const [key, endpoint] of Object.entries(endpoints)) {\n api[key] = async (context) => {\n const authContext = await ctx;\n let internalContext = {\n ...context,\n context: {\n ...authContext,\n returned: void 0,\n responseHeaders: void 0,\n session: null\n },\n path: endpoint.path,\n headers: context?.headers ? new Headers(context?.headers) : void 0\n };\n const { beforeHooks, afterHooks } = getHooks(authContext);\n const before = await runBeforeHooks(internalContext, beforeHooks);\n if (\"context\" in before && before.context && typeof before.context === \"object\") {\n const { headers, ...rest } = before.context;\n if (headers) {\n headers.forEach((value, key2) => {\n internalContext.headers.set(key2, value);\n });\n }\n internalContext = defu(rest, internalContext);\n } else if (before) {\n return before;\n }\n internalContext.asResponse = false;\n internalContext.returnHeaders = true;\n const result = await endpoint(internalContext).catch((e) => {\n if (e instanceof APIError) {\n return {\n response: e,\n headers: e.headers ? new Headers(e.headers) : null\n };\n }\n throw e;\n });\n internalContext.context.returned = result.response;\n internalContext.context.responseHeaders = result.headers;\n const after = await runAfterHooks(internalContext, afterHooks);\n if (after.response) {\n result.response = after.response;\n }\n if (result.response instanceof APIError && !context?.asResponse) {\n throw result.response;\n }\n const response = context?.asResponse ? toResponse(result.response, {\n headers: result.headers\n }) : context?.returnHeaders ? {\n headers: result.headers,\n response: result.response\n } : result.response;\n return response;\n };\n api[key].path = endpoint.path;\n api[key].options = endpoint.options;\n }\n return api;\n}\nasync function runBeforeHooks(context, hooks) {\n let modifiedContext = {};\n for (const hook of hooks) {\n if (hook.matcher(context)) {\n const result = await hook.handler({\n ...context,\n returnHeaders: false\n });\n if (result && typeof result === \"object\") {\n if (\"context\" in result && typeof result.context === \"object\") {\n const { headers, ...rest } = result.context;\n if (headers instanceof Headers) {\n if (modifiedContext.headers) {\n headers.forEach((value, key) => {\n modifiedContext.headers?.set(key, value);\n });\n } else {\n modifiedContext.headers = headers;\n }\n }\n modifiedContext = defu(rest, modifiedContext);\n continue;\n }\n return result;\n }\n }\n }\n return { context: modifiedContext };\n}\nasync function runAfterHooks(context, hooks) {\n for (const hook of hooks) {\n if (hook.matcher(context)) {\n const result = await hook.handler(context).catch((e) => {\n if (e instanceof APIError) {\n return {\n response: e,\n headers: e.headers ? new Headers(e.headers) : null\n };\n }\n throw e;\n });\n if (result.headers) {\n result.headers.forEach((value, key) => {\n if (!context.context.responseHeaders) {\n context.context.responseHeaders = new Headers({\n [key]: value\n });\n } else {\n if (key.toLowerCase() === \"set-cookie\") {\n context.context.responseHeaders.append(key, value);\n } else {\n context.context.responseHeaders.set(key, value);\n }\n }\n });\n }\n if (result.response) {\n context.context.returned = result.response;\n }\n }\n }\n return {\n response: context.context.returned,\n headers: context.context.responseHeaders\n };\n}\nfunction getHooks(authContext) {\n const plugins = authContext.options.plugins || [];\n const beforeHooks = [];\n const afterHooks = [];\n if (authContext.options.hooks?.before) {\n beforeHooks.push({\n matcher: () => true,\n handler: authContext.options.hooks.before\n });\n }\n if (authContext.options.hooks?.after) {\n afterHooks.push({\n matcher: () => true,\n handler: authContext.options.hooks.after\n });\n }\n const pluginBeforeHooks = plugins.map((plugin) => {\n if (plugin.hooks?.before) {\n return plugin.hooks.before;\n }\n }).filter((plugin) => plugin !== void 0).flat();\n const pluginAfterHooks = plugins.map((plugin) => {\n if (plugin.hooks?.after) {\n return plugin.hooks.after;\n }\n }).filter((plugin) => plugin !== void 0).flat();\n pluginBeforeHooks.length && beforeHooks.push(...pluginBeforeHooks);\n pluginAfterHooks.length && afterHooks.push(...pluginAfterHooks);\n return {\n beforeHooks,\n afterHooks\n };\n}\n\nfunction getEndpoints(ctx, options) {\n const pluginEndpoints = options.plugins?.reduce(\n (acc, plugin) => {\n return {\n ...acc,\n ...plugin.endpoints\n };\n },\n {}\n );\n const middlewares = options.plugins?.map(\n (plugin) => plugin.middlewares?.map((m) => {\n const middleware = async (context) => {\n return m.middleware({\n ...context,\n context: {\n ...ctx,\n ...context.context\n }\n });\n };\n middleware.options = m.middleware.options;\n return {\n path: m.path,\n middleware\n };\n })\n ).filter((plugin) => plugin !== void 0).flat() || [];\n const baseEndpoints = {\n signInSocial,\n callbackOAuth,\n getSession: getSession(),\n signOut,\n signUpEmail: signUpEmail(),\n signInEmail,\n forgetPassword,\n resetPassword,\n verifyEmail,\n sendVerificationEmail,\n changeEmail,\n changePassword,\n setPassword,\n updateUser: updateUser(),\n deleteUser,\n forgetPasswordCallback,\n requestPasswordReset,\n requestPasswordResetCallback,\n listSessions: listSessions(),\n revokeSession,\n revokeSessions,\n revokeOtherSessions,\n linkSocialAccount,\n listUserAccounts,\n deleteUserCallback,\n unlinkAccount,\n refreshToken,\n getAccessToken,\n accountInfo\n };\n const endpoints = {\n ...baseEndpoints,\n ...pluginEndpoints,\n ok,\n error\n };\n const api = toAuthEndpoints(endpoints, ctx);\n return {\n api,\n middlewares\n };\n}\nconst router = (ctx, options) => {\n const { api, middlewares } = getEndpoints(ctx, options);\n const basePath = new URL(ctx.baseURL).pathname;\n return createRouter(api, {\n routerContext: ctx,\n openapi: {\n disabled: true\n },\n basePath,\n routerMiddleware: [\n {\n path: \"/**\",\n middleware: originCheckMiddleware\n },\n ...middlewares\n ],\n async onRequest(req) {\n const disabledPaths = ctx.options.disabledPaths || [];\n const path = new URL(req.url).pathname.replace(basePath, \"\");\n if (disabledPaths.includes(path)) {\n return new Response(\"Not Found\", { status: 404 });\n }\n for (const plugin of ctx.options.plugins || []) {\n if (plugin.onRequest) {\n const response = await plugin.onRequest(req, ctx);\n if (response && \"response\" in response) {\n return response.response;\n }\n }\n }\n return onRequestRateLimit(req, ctx);\n },\n async onResponse(res) {\n for (const plugin of ctx.options.plugins || []) {\n if (plugin.onResponse) {\n const response = await plugin.onResponse(res, ctx);\n if (response) {\n return response.response;\n }\n }\n }\n return res;\n },\n onError(e) {\n if (e instanceof APIError && e.status === \"FOUND\") {\n return;\n }\n if (options.onAPIError?.throw) {\n throw e;\n }\n if (options.onAPIError?.onError) {\n options.onAPIError.onError(e, ctx);\n return;\n }\n const optLogLevel = options.logger?.level;\n const log = optLogLevel === \"error\" || optLogLevel === \"warn\" || optLogLevel === \"debug\" ? logger : void 0;\n if (options.logger?.disabled !== true) {\n if (e && typeof e === \"object\" && \"message\" in e && typeof e.message === \"string\") {\n if (e.message.includes(\"no column\") || e.message.includes(\"column\") || e.message.includes(\"relation\") || e.message.includes(\"table\") || e.message.includes(\"does not exist\")) {\n ctx.logger?.error(e.message);\n return;\n }\n }\n if (e instanceof APIError) {\n if (e.status === \"INTERNAL_SERVER_ERROR\") {\n ctx.logger.error(e.status, e);\n }\n log?.error(e.message);\n } else {\n ctx.logger?.error(\n e && typeof e === \"object\" && \"name\" in e ? e.name : \"\",\n e\n );\n }\n }\n }\n });\n};\n\nexport { accountInfo, callbackOAuth, changeEmail, changePassword, createAuthEndpoint, createEmailVerificationToken, deleteUser, deleteUserCallback, error, forgetPassword, forgetPasswordCallback, getAccessToken, getEndpoints, getSession, linkSocialAccount, listSessions, listUserAccounts, ok, originCheckMiddleware, refreshToken, requestPasswordReset, requestPasswordResetCallback, resetPassword, revokeOtherSessions, revokeSession, revokeSessions, router, sendVerificationEmail, setPassword, signInEmail, signInSocial, signOut, signUpEmail, unlinkAccount, updateUser, verifyEmail };\n","import { APIError } from 'better-call';\nimport * as z from 'zod/v4';\nimport { j as createAuthEndpoint, k as getSessionFromCtx, l as sessionMiddleware, B as BASE_ERROR_CODES, a2 as requestOnlySessionMiddleware } from './better-auth.D4HhkCZJ.mjs';\nimport './better-auth.8zoxzg-F.mjs';\nimport '@better-auth/utils/base64';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport './better-auth.n2KFGwjY.mjs';\nimport { g as getDate } from './better-auth.CW6D9eSx.mjs';\nimport { B as BetterAuthError } from './better-auth.DdzSJf-n.mjs';\nimport { p as parseJSON } from './better-auth.ffWeg50w.mjs';\nimport { o as orgMiddleware, a as orgSessionMiddleware, t as teamSchema } from './better-auth.DGaVMVAI.mjs';\nimport { setSessionCookie } from '../cookies/index.mjs';\nimport './better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { h as hasPermission } from './better-auth.Dt0CvI2z.mjs';\nimport { t as toZodSchema } from './better-auth.DXqcUO8W.mjs';\nimport '@better-auth/utils/random';\nimport '@better-auth/utils/hash';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport './better-auth.B4Qoxdgc.mjs';\nimport 'kysely';\nimport { defaultRoles } from '../plugins/organization/access/index.mjs';\n\nconst shimContext = (originalObject, newContext) => {\n const shimmedObj = {};\n for (const [key, value] of Object.entries(originalObject)) {\n shimmedObj[key] = (ctx) => {\n return value({\n ...ctx,\n context: {\n ...newContext,\n ...ctx.context\n }\n });\n };\n shimmedObj[key].path = value.path;\n shimmedObj[key].method = value.method;\n shimmedObj[key].options = value.options;\n shimmedObj[key].headers = value.headers;\n }\n return shimmedObj;\n};\n\nconst getOrgAdapter = (context, options) => {\n const adapter = context.adapter;\n return {\n findOrganizationBySlug: async (slug) => {\n const organization = await adapter.findOne({\n model: \"organization\",\n where: [\n {\n field: \"slug\",\n value: slug\n }\n ]\n });\n return organization;\n },\n createOrganization: async (data) => {\n const organization = await adapter.create({\n model: \"organization\",\n data: {\n ...data.organization,\n metadata: data.organization.metadata ? JSON.stringify(data.organization.metadata) : void 0\n }\n });\n return {\n ...organization,\n metadata: organization.metadata && typeof organization.metadata === \"string\" ? JSON.parse(organization.metadata) : void 0\n };\n },\n findMemberByEmail: async (data) => {\n const user = await adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"email\",\n value: data.email\n }\n ]\n });\n if (!user) {\n return null;\n }\n const member = await adapter.findOne({\n model: \"member\",\n where: [\n {\n field: \"organizationId\",\n value: data.organizationId\n },\n {\n field: \"userId\",\n value: user.id\n }\n ]\n });\n if (!member) {\n return null;\n }\n return {\n ...member,\n user: {\n id: user.id,\n name: user.name,\n email: user.email,\n image: user.image\n }\n };\n },\n listMembers: async (data) => {\n const members = await adapter.findMany({\n model: \"member\",\n where: [\n {\n field: \"organizationId\",\n value: data.organizationId\n }\n ],\n limit: options?.membershipLimit || 100\n });\n return members;\n },\n findMemberByOrgId: async (data) => {\n const [member, user] = await Promise.all([\n await adapter.findOne({\n model: \"member\",\n where: [\n {\n field: \"userId\",\n value: data.userId\n },\n {\n field: \"organizationId\",\n value: data.organizationId\n }\n ]\n }),\n await adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"id\",\n value: data.userId\n }\n ]\n })\n ]);\n if (!user || !member) {\n return null;\n }\n return {\n ...member,\n user: {\n id: user.id,\n name: user.name,\n email: user.email,\n image: user.image\n }\n };\n },\n findMemberById: async (memberId) => {\n const member = await adapter.findOne({\n model: \"member\",\n where: [\n {\n field: \"id\",\n value: memberId\n }\n ]\n });\n if (!member) {\n return null;\n }\n const user = await adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"id\",\n value: member.userId\n }\n ]\n });\n if (!user) {\n return null;\n }\n return {\n ...member,\n user: {\n id: user.id,\n name: user.name,\n email: user.email,\n image: user.image\n }\n };\n },\n createMember: async (data) => {\n const member = await adapter.create({\n model: \"member\",\n data: {\n ...data,\n createdAt: /* @__PURE__ */ new Date()\n }\n });\n return member;\n },\n updateMember: async (memberId, role) => {\n const member = await adapter.update({\n model: \"member\",\n where: [\n {\n field: \"id\",\n value: memberId\n }\n ],\n update: {\n role\n }\n });\n return member;\n },\n deleteMember: async (memberId) => {\n const member = await adapter.delete({\n model: \"member\",\n where: [\n {\n field: \"id\",\n value: memberId\n }\n ]\n });\n return member;\n },\n updateOrganization: async (organizationId, data) => {\n const organization = await adapter.update({\n model: \"organization\",\n where: [\n {\n field: \"id\",\n value: organizationId\n }\n ],\n update: {\n ...data,\n metadata: typeof data.metadata === \"object\" ? JSON.stringify(data.metadata) : data.metadata\n }\n });\n if (!organization) {\n return null;\n }\n return {\n ...organization,\n metadata: organization.metadata ? parseJSON(organization.metadata) : void 0\n };\n },\n deleteOrganization: async (organizationId) => {\n await adapter.delete({\n model: \"member\",\n where: [\n {\n field: \"organizationId\",\n value: organizationId\n }\n ]\n });\n await adapter.delete({\n model: \"invitation\",\n where: [\n {\n field: \"organizationId\",\n value: organizationId\n }\n ]\n });\n await adapter.delete({\n model: \"organization\",\n where: [\n {\n field: \"id\",\n value: organizationId\n }\n ]\n });\n return organizationId;\n },\n setActiveOrganization: async (sessionToken, organizationId) => {\n const session = await context.internalAdapter.updateSession(\n sessionToken,\n {\n activeOrganizationId: organizationId\n }\n );\n return session;\n },\n findOrganizationById: async (organizationId) => {\n const organization = await adapter.findOne({\n model: \"organization\",\n where: [\n {\n field: \"id\",\n value: organizationId\n }\n ]\n });\n return organization;\n },\n checkMembership: async ({\n userId,\n organizationId\n }) => {\n const member = await adapter.findOne({\n model: \"member\",\n where: [\n {\n field: \"userId\",\n value: userId\n },\n {\n field: \"organizationId\",\n value: organizationId\n }\n ]\n });\n return member;\n },\n /**\n * @requires db\n */\n findFullOrganization: async ({\n organizationId,\n isSlug,\n includeTeams\n }) => {\n const org = await adapter.findOne({\n model: \"organization\",\n where: [{ field: isSlug ? \"slug\" : \"id\", value: organizationId }]\n });\n if (!org) {\n return null;\n }\n const [invitations, members, teams] = await Promise.all([\n adapter.findMany({\n model: \"invitation\",\n where: [{ field: \"organizationId\", value: org.id }]\n }),\n adapter.findMany({\n model: \"member\",\n where: [{ field: \"organizationId\", value: org.id }],\n limit: options?.membershipLimit || 100\n }),\n includeTeams ? adapter.findMany({\n model: \"team\",\n where: [{ field: \"organizationId\", value: org.id }]\n }) : null\n ]);\n if (!org) return null;\n const userIds = members.map((member) => member.userId);\n const users = userIds.length > 0 ? await adapter.findMany({\n model: \"user\",\n where: [{ field: \"id\", value: userIds, operator: \"in\" }],\n limit: options?.membershipLimit || 100\n }) : [];\n const userMap = new Map(users.map((user) => [user.id, user]));\n const membersWithUsers = members.map((member) => {\n const user = userMap.get(member.userId);\n if (!user) {\n throw new BetterAuthError(\n \"Unexpected error: User not found for member\"\n );\n }\n return {\n ...member,\n user: {\n id: user.id,\n name: user.name,\n email: user.email,\n image: user.image\n }\n };\n });\n return {\n ...org,\n invitations,\n members: membersWithUsers,\n teams\n };\n },\n listOrganizations: async (userId) => {\n const members = await adapter.findMany({\n model: \"member\",\n where: [\n {\n field: \"userId\",\n value: userId\n }\n ]\n });\n if (!members || members.length === 0) {\n return [];\n }\n const organizationIds = members.map((member) => member.organizationId);\n const organizations = await adapter.findMany({\n model: \"organization\",\n where: [\n {\n field: \"id\",\n value: organizationIds,\n operator: \"in\"\n }\n ]\n });\n return organizations;\n },\n createTeam: async (data) => {\n const team = await adapter.create({\n model: \"team\",\n data\n });\n return team;\n },\n findTeamById: async ({\n teamId,\n organizationId,\n includeTeamMembers\n }) => {\n const team = await adapter.findOne({\n model: \"team\",\n where: [\n {\n field: \"id\",\n value: teamId\n },\n ...organizationId ? [\n {\n field: \"organizationId\",\n value: organizationId\n }\n ] : []\n ]\n });\n if (!team) {\n return null;\n }\n let members = [];\n if (includeTeamMembers) {\n members = await adapter.findMany({\n model: \"teamMember\",\n where: [\n {\n field: \"teamId\",\n value: teamId\n }\n ],\n limit: options?.membershipLimit || 100\n });\n return {\n ...team,\n members\n };\n }\n return team;\n },\n updateTeam: async (teamId, data) => {\n if (\"id\" in data) data.id = void 0;\n const team = await adapter.update({\n model: \"team\",\n where: [\n {\n field: \"id\",\n value: teamId\n }\n ],\n update: {\n ...data\n }\n });\n return team;\n },\n deleteTeam: async (teamId) => {\n const team = await adapter.delete({\n model: \"team\",\n where: [\n {\n field: \"id\",\n value: teamId\n }\n ]\n });\n return team;\n },\n listTeams: async (organizationId) => {\n const teams = await adapter.findMany({\n model: \"team\",\n where: [\n {\n field: \"organizationId\",\n value: organizationId\n }\n ]\n });\n return teams;\n },\n createTeamInvitation: async ({\n email,\n role,\n teamId,\n organizationId,\n inviterId,\n expiresIn = 1e3 * 60 * 60 * 48\n // Default expiration: 48 hours\n }) => {\n const expiresAt = getDate(expiresIn);\n const invitation = await adapter.create({\n model: \"invitation\",\n data: {\n email,\n role,\n organizationId,\n teamId,\n inviterId,\n status: \"pending\",\n expiresAt\n }\n });\n return invitation;\n },\n setActiveTeam: async (sessionToken, teamId) => {\n const session = await context.internalAdapter.updateSession(\n sessionToken,\n {\n activeTeamId: teamId\n }\n );\n return session;\n },\n listTeamMembers: async (data) => {\n const members = await adapter.findMany({\n model: \"teamMember\",\n where: [\n {\n field: \"teamId\",\n value: data.teamId\n }\n ]\n });\n return members;\n },\n countMembers: async (data) => {\n const count = await adapter.count({\n model: \"member\",\n where: [{ field: \"organizationId\", value: data.organizationId }]\n });\n return count;\n },\n listTeamsByUser: async (data) => {\n const members = await adapter.findMany({\n model: \"teamMember\",\n where: [\n {\n field: \"userId\",\n value: data.userId\n }\n ]\n });\n const teams = await adapter.findMany({\n model: \"team\",\n where: [\n {\n field: \"id\",\n operator: \"in\",\n value: members.map((m) => m.teamId)\n }\n ]\n });\n return teams;\n },\n findTeamMember: async (data) => {\n const member = await adapter.findOne({\n model: \"teamMember\",\n where: [\n {\n field: \"teamId\",\n value: data.teamId\n },\n {\n field: \"userId\",\n value: data.userId\n }\n ]\n });\n return member;\n },\n findOrCreateTeamMember: async (data) => {\n const member = await adapter.findOne({\n model: \"teamMember\",\n where: [\n {\n field: \"teamId\",\n value: data.teamId\n },\n {\n field: \"userId\",\n value: data.userId\n }\n ]\n });\n if (member) return member;\n return await adapter.create({\n model: \"teamMember\",\n data: {\n teamId: data.teamId,\n userId: data.userId,\n createdAt: /* @__PURE__ */ new Date()\n }\n });\n },\n removeTeamMember: async (data) => {\n await adapter.delete({\n model: \"teamMember\",\n where: [\n {\n field: \"teamId\",\n value: data.teamId\n },\n {\n field: \"userId\",\n value: data.userId\n }\n ]\n });\n },\n findInvitationsByTeamId: async (teamId) => {\n const invitations = await adapter.findMany({\n model: \"invitation\",\n where: [\n {\n field: \"teamId\",\n value: teamId\n }\n ]\n });\n return invitations;\n },\n listUserInvitations: async (email) => {\n const invitations = await adapter.findMany({\n model: \"invitation\",\n where: [{ field: \"email\", value: email }]\n });\n return invitations;\n },\n createInvitation: async ({\n invitation,\n user\n }) => {\n const defaultExpiration = 60 * 60 * 48;\n const expiresAt = getDate(\n options?.invitationExpiresIn || defaultExpiration,\n \"sec\"\n );\n const invite = await adapter.create({\n model: \"invitation\",\n data: {\n status: \"pending\",\n expiresAt,\n inviterId: user.id,\n ...invitation,\n teamId: invitation.teamIds.join(\",\")\n }\n });\n return invite;\n },\n findInvitationById: async (id) => {\n const invitation = await adapter.findOne({\n model: \"invitation\",\n where: [\n {\n field: \"id\",\n value: id\n }\n ]\n });\n return invitation;\n },\n findPendingInvitation: async (data) => {\n const invitation = await adapter.findMany({\n model: \"invitation\",\n where: [\n {\n field: \"email\",\n value: data.email\n },\n {\n field: \"organizationId\",\n value: data.organizationId\n },\n {\n field: \"status\",\n value: \"pending\"\n }\n ]\n });\n return invitation.filter(\n (invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date()\n );\n },\n findPendingInvitations: async (data) => {\n const invitations = await adapter.findMany({\n model: \"invitation\",\n where: [\n {\n field: \"organizationId\",\n value: data.organizationId\n },\n {\n field: \"status\",\n value: \"pending\"\n }\n ]\n });\n return invitations.filter(\n (invite) => new Date(invite.expiresAt) > /* @__PURE__ */ new Date()\n );\n },\n listInvitations: async (data) => {\n const invitations = await adapter.findMany({\n model: \"invitation\",\n where: [\n {\n field: \"organizationId\",\n value: data.organizationId\n }\n ]\n });\n return invitations;\n },\n updateInvitation: async (data) => {\n const invitation = await adapter.update({\n model: \"invitation\",\n where: [\n {\n field: \"id\",\n value: data.invitationId\n }\n ],\n update: {\n status: data.status\n }\n });\n return invitation;\n }\n };\n};\n\nconst ORGANIZATION_ERROR_CODES = {\n YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION: \"You are not allowed to create a new organization\",\n YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS: \"You have reached the maximum number of organizations\",\n ORGANIZATION_ALREADY_EXISTS: \"Organization already exists\",\n ORGANIZATION_NOT_FOUND: \"Organization not found\",\n USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION: \"User is not a member of the organization\",\n YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION: \"You are not allowed to update this organization\",\n YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION: \"You are not allowed to delete this organization\",\n NO_ACTIVE_ORGANIZATION: \"No active organization\",\n USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION: \"User is already a member of this organization\",\n MEMBER_NOT_FOUND: \"Member not found\",\n ROLE_NOT_FOUND: \"Role not found\",\n YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM: \"You are not allowed to create a new team\",\n TEAM_ALREADY_EXISTS: \"Team already exists\",\n TEAM_NOT_FOUND: \"Team not found\",\n YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER: \"You cannot leave the organization as the only owner\",\n YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER: \"You are not allowed to delete this member\",\n YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION: \"You are not allowed to invite users to this organization\",\n USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION: \"User is already invited to this organization\",\n INVITATION_NOT_FOUND: \"Invitation not found\",\n YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION: \"You are not the recipient of the invitation\",\n YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION: \"You are not allowed to cancel this invitation\",\n INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION: \"Inviter is no longer a member of the organization\",\n YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE: \"you are not allowed to invite user with this role\",\n FAILED_TO_RETRIEVE_INVITATION: \"Failed to retrieve invitation\",\n YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS: \"You have reached the maximum number of teams\",\n UNABLE_TO_REMOVE_LAST_TEAM: \"Unable to remove last team\",\n YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER: \"You are not allowed to update this member\",\n ORGANIZATION_MEMBERSHIP_LIMIT_REACHED: \"Organization membership limit reached\",\n YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION: \"You are not allowed to create teams in this organization\",\n YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION: \"You are not allowed to delete teams in this organization\",\n YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM: \"You are not allowed to update this team\",\n YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM: \"You are not allowed to delete this team\",\n INVITATION_LIMIT_REACHED: \"Invitation limit reached\",\n TEAM_MEMBER_LIMIT_REACHED: \"Team member limit reached\",\n USER_IS_NOT_A_MEMBER_OF_THE_TEAM: \"User is not a member of the team\",\n YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM: \"You are not allowed to list the members of this team\",\n YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM: \"You do not have an active team\",\n YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER: \"You are not allowed to create a new member\",\n YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER: \"You are not allowed to remove a team member\",\n YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION: \"You are not allowed to access this organization as an owner\"\n};\n\nconst createInvitation = (option) => {\n const additionalFieldsSchema = toZodSchema({\n fields: option?.schema?.invitation?.additionalFields || {},\n isClientSide: true\n });\n const baseSchema = z.object({\n email: z.string().meta({\n description: \"The email address of the user to invite\"\n }),\n role: z.union([\n z.string().meta({\n description: \"The role to assign to the user\"\n }),\n z.array(\n z.string().meta({\n description: \"The roles to assign to the user\"\n })\n )\n ]).meta({\n description: 'The role(s) to assign to the user. It can be `admin`, `member`, or `guest`. Eg: \"member\"'\n }),\n organizationId: z.string().meta({\n description: \"The organization ID to invite the user to\"\n }).optional(),\n resend: z.boolean().meta({\n description: \"Resend the invitation email, if the user is already invited. Eg: true\"\n }).optional(),\n teamId: z.union([\n z.string().meta({\n description: \"The team ID to invite the user to\"\n }).optional(),\n z.array(\n z.string().meta({\n description: \"The team ID to invite the user to\"\n })\n ).optional()\n ])\n });\n return createAuthEndpoint(\n \"/organization/invite-member\",\n {\n method: \"POST\",\n use: [orgMiddleware, orgSessionMiddleware],\n body: z.object({\n ...baseSchema.shape,\n ...additionalFieldsSchema.shape\n }),\n metadata: {\n $Infer: {\n body: {}\n },\n openapi: {\n description: \"Invite a user to an organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n email: {\n type: \"string\"\n },\n role: {\n type: \"string\"\n },\n organizationId: {\n type: \"string\"\n },\n inviterId: {\n type: \"string\"\n },\n status: {\n type: \"string\"\n },\n expiresAt: {\n type: \"string\"\n }\n },\n required: [\n \"id\",\n \"email\",\n \"role\",\n \"organizationId\",\n \"inviterId\",\n \"status\",\n \"expiresAt\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n if (!organizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND\n });\n }\n const adapter = getOrgAdapter(ctx.context, option);\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId\n });\n if (!member) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n });\n }\n const canInvite = hasPermission({\n role: member.role,\n options: ctx.context.orgOptions,\n permissions: {\n invitation: [\"create\"]\n }\n });\n if (!canInvite) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION\n });\n }\n const creatorRole = ctx.context.orgOptions.creatorRole || \"owner\";\n const roles = parseRoles(ctx.body.role);\n if (member.role !== creatorRole && roles.split(\",\").includes(creatorRole)) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE\n });\n }\n const alreadyMember = await adapter.findMemberByEmail({\n email: ctx.body.email,\n organizationId\n });\n if (alreadyMember) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION\n });\n }\n const alreadyInvited = await adapter.findPendingInvitation({\n email: ctx.body.email,\n organizationId\n });\n if (alreadyInvited.length && !ctx.body.resend) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION\n });\n }\n if (alreadyInvited.length && ctx.context.orgOptions.cancelPendingInvitationsOnReInvite) {\n await adapter.updateInvitation({\n invitationId: alreadyInvited[0].id,\n status: \"canceled\"\n });\n }\n const organization = await adapter.findOrganizationById(organizationId);\n if (!organization) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND\n });\n }\n const invitationLimit = typeof ctx.context.orgOptions.invitationLimit === \"function\" ? await ctx.context.orgOptions.invitationLimit(\n {\n user: session.user,\n organization,\n member\n },\n ctx.context\n ) : ctx.context.orgOptions.invitationLimit ?? 100;\n const pendingInvitations = await adapter.findPendingInvitations({\n organizationId\n });\n if (pendingInvitations.length >= invitationLimit) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.INVITATION_LIMIT_REACHED\n });\n }\n if (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== \"undefined\" && \"teamId\" in ctx.body && ctx.body.teamId) {\n const teamIds2 = typeof ctx.body.teamId === \"string\" ? [ctx.body.teamId] : ctx.body.teamId;\n for (const teamId of teamIds2) {\n const team = await adapter.findTeamById({\n teamId,\n organizationId,\n includeTeamMembers: true\n });\n if (!team) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND\n });\n }\n const maximumMembersPerTeam = typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === \"function\" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({\n teamId,\n session,\n organizationId\n }) : ctx.context.orgOptions.teams.maximumMembersPerTeam;\n if (team.members.length >= maximumMembersPerTeam) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED\n });\n }\n }\n }\n const teamIds = \"teamId\" in ctx.body ? typeof ctx.body.teamId === \"string\" ? [ctx.body.teamId] : ctx.body.teamId ?? [] : [];\n const {\n email: _,\n role: __,\n organizationId: ___,\n resend: ____,\n ...additionalFields\n } = ctx.body;\n const invitation = await adapter.createInvitation({\n invitation: {\n role: roles,\n email: ctx.body.email.toLowerCase(),\n organizationId,\n teamIds,\n ...additionalFields ? additionalFields : {}\n },\n user: session.user\n });\n await ctx.context.orgOptions.sendInvitationEmail?.(\n {\n id: invitation.id,\n role: invitation.role,\n email: invitation.email.toLowerCase(),\n organization,\n inviter: {\n ...member,\n user: session.user\n },\n //@ts-expect-error\n invitation\n },\n ctx.request\n );\n return ctx.json(invitation);\n }\n );\n};\nconst acceptInvitation = (options) => createAuthEndpoint(\n \"/organization/accept-invitation\",\n {\n method: \"POST\",\n body: z.object({\n invitationId: z.string().meta({\n description: \"The ID of the invitation to accept\"\n })\n }),\n use: [orgMiddleware, orgSessionMiddleware],\n metadata: {\n openapi: {\n description: \"Accept an invitation to an organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n invitation: {\n type: \"object\"\n },\n member: {\n type: \"object\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const adapter = getOrgAdapter(ctx.context, options);\n const invitation = await adapter.findInvitationById(\n ctx.body.invitationId\n );\n if (!invitation || invitation.expiresAt < /* @__PURE__ */ new Date() || invitation.status !== \"pending\") {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND\n });\n }\n if (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION\n });\n }\n const membershipLimit = ctx.context.orgOptions?.membershipLimit || 100;\n const members = await adapter.listMembers({\n organizationId: invitation.organizationId\n });\n if (members.length >= membershipLimit) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED\n });\n }\n const acceptedI = await adapter.updateInvitation({\n invitationId: ctx.body.invitationId,\n status: \"accepted\"\n });\n if (!acceptedI) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.FAILED_TO_RETRIEVE_INVITATION\n });\n }\n if (ctx.context.orgOptions.teams && ctx.context.orgOptions.teams.enabled && \"teamId\" in acceptedI && acceptedI.teamId) {\n const teamIds = acceptedI.teamId.split(\",\");\n const onlyOne = teamIds.length === 1;\n for (const teamId of teamIds) {\n await adapter.findOrCreateTeamMember({\n teamId,\n userId: session.user.id\n });\n if (typeof ctx.context.orgOptions.teams.maximumMembersPerTeam !== \"undefined\") {\n const members2 = await adapter.listTeamMembers({ teamId });\n const maximumMembersPerTeam = typeof ctx.context.orgOptions.teams.maximumMembersPerTeam === \"function\" ? await ctx.context.orgOptions.teams.maximumMembersPerTeam({\n teamId,\n session,\n organizationId: invitation.organizationId\n }) : ctx.context.orgOptions.teams.maximumMembersPerTeam;\n if (members2.length >= maximumMembersPerTeam) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.TEAM_MEMBER_LIMIT_REACHED\n });\n }\n }\n }\n if (onlyOne) {\n const teamId = teamIds[0];\n const updatedSession = await adapter.setActiveTeam(\n session.session.token,\n teamId\n );\n await setSessionCookie(ctx, {\n session: updatedSession,\n user: session.user\n });\n }\n }\n const member = await adapter.createMember({\n organizationId: invitation.organizationId,\n userId: session.user.id,\n role: invitation.role,\n createdAt: /* @__PURE__ */ new Date()\n });\n await adapter.setActiveOrganization(\n session.session.token,\n invitation.organizationId\n );\n if (!acceptedI) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND\n }\n });\n }\n return ctx.json({\n invitation: acceptedI,\n member\n });\n }\n);\nconst rejectInvitation = (options) => createAuthEndpoint(\n \"/organization/reject-invitation\",\n {\n method: \"POST\",\n body: z.object({\n invitationId: z.string().meta({\n description: \"The ID of the invitation to reject\"\n })\n }),\n use: [orgMiddleware, orgSessionMiddleware],\n metadata: {\n openapi: {\n description: \"Reject an invitation to an organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n invitation: {\n type: \"object\"\n },\n member: {\n type: \"null\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n const invitation = await adapter.findInvitationById(\n ctx.body.invitationId\n );\n if (!invitation || invitation.expiresAt < /* @__PURE__ */ new Date() || invitation.status !== \"pending\") {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invitation not found!\"\n });\n }\n if (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION\n });\n }\n const rejectedI = await adapter.updateInvitation({\n invitationId: ctx.body.invitationId,\n status: \"rejected\"\n });\n return ctx.json({\n invitation: rejectedI,\n member: null\n });\n }\n);\nconst cancelInvitation = (options) => createAuthEndpoint(\n \"/organization/cancel-invitation\",\n {\n method: \"POST\",\n body: z.object({\n invitationId: z.string().meta({\n description: \"The ID of the invitation to cancel\"\n })\n }),\n use: [orgMiddleware, orgSessionMiddleware],\n openapi: {\n description: \"Cancel an invitation to an organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n invitation: {\n type: \"object\"\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const adapter = getOrgAdapter(ctx.context, options);\n const invitation = await adapter.findInvitationById(\n ctx.body.invitationId\n );\n if (!invitation) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND\n });\n }\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId: invitation.organizationId\n });\n if (!member) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n });\n }\n const canCancel = hasPermission({\n role: member.role,\n options: ctx.context.orgOptions,\n permissions: {\n invitation: [\"cancel\"]\n }\n });\n if (!canCancel) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION\n });\n }\n const canceledI = await adapter.updateInvitation({\n invitationId: ctx.body.invitationId,\n status: \"canceled\"\n });\n return ctx.json(canceledI);\n }\n);\nconst getInvitation = (options) => createAuthEndpoint(\n \"/organization/get-invitation\",\n {\n method: \"GET\",\n use: [orgMiddleware],\n requireHeaders: true,\n query: z.object({\n id: z.string().meta({\n description: \"The ID of the invitation to get\"\n })\n }),\n metadata: {\n openapi: {\n description: \"Get an invitation by ID\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n email: {\n type: \"string\"\n },\n role: {\n type: \"string\"\n },\n organizationId: {\n type: \"string\"\n },\n inviterId: {\n type: \"string\"\n },\n status: {\n type: \"string\"\n },\n expiresAt: {\n type: \"string\"\n },\n organizationName: {\n type: \"string\"\n },\n organizationSlug: {\n type: \"string\"\n },\n inviterEmail: {\n type: \"string\"\n }\n },\n required: [\n \"id\",\n \"email\",\n \"role\",\n \"organizationId\",\n \"inviterId\",\n \"status\",\n \"expiresAt\",\n \"organizationName\",\n \"organizationSlug\",\n \"inviterEmail\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Not authenticated\"\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const invitation = await adapter.findInvitationById(ctx.query.id);\n if (!invitation || invitation.status !== \"pending\" || invitation.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invitation not found!\"\n });\n }\n if (invitation.email.toLowerCase() !== session.user.email.toLowerCase()) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION\n });\n }\n const organization = await adapter.findOrganizationById(\n invitation.organizationId\n );\n if (!organization) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND\n });\n }\n const member = await adapter.findMemberByOrgId({\n userId: invitation.inviterId,\n organizationId: invitation.organizationId\n });\n if (!member) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION\n });\n }\n return ctx.json({\n ...invitation,\n organizationName: organization.name,\n organizationSlug: organization.slug,\n inviterEmail: member.user.email\n });\n }\n);\nconst listInvitations = (options) => createAuthEndpoint(\n \"/organization/list-invitations\",\n {\n method: \"GET\",\n use: [orgMiddleware, orgSessionMiddleware],\n query: z.object({\n organizationId: z.string().meta({\n description: \"The ID of the organization to list invitations for\"\n }).optional()\n }).optional()\n },\n async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Not authenticated\"\n });\n }\n const orgId = ctx.query?.organizationId || session.session.activeOrganizationId;\n if (!orgId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Organization ID is required\"\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const isMember = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId: orgId\n });\n if (!isMember) {\n throw new APIError(\"FORBIDDEN\", {\n message: \"You are not a member of this organization\"\n });\n }\n const invitations = await adapter.listInvitations({\n organizationId: orgId\n });\n return ctx.json(invitations);\n }\n);\nconst listUserInvitations = (options) => createAuthEndpoint(\n \"/organization/list-user-invitations\",\n {\n method: \"GET\",\n use: [orgMiddleware],\n query: z.object({\n email: z.string().meta({\n description: \"The email of the user to list invitations for. This only works for server side API calls.\"\n }).optional()\n }).optional()\n },\n async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (ctx.request && ctx.query?.email) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"User email cannot be passed for client side API calls.\"\n });\n }\n const userEmail = session?.user.email || ctx.query?.email;\n if (!userEmail) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Missing session headers, or email query parameter.\"\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const invitations = await adapter.listUserInvitations(userEmail);\n return ctx.json(invitations);\n }\n);\n\nconst addMember = (option) => {\n const additionalFieldsSchema = toZodSchema({\n fields: option?.schema?.member?.additionalFields || {},\n isClientSide: true\n });\n const baseSchema = z.object({\n userId: z.coerce.string().meta({\n description: 'The user Id which represents the user to be added as a member. If `null` is provided, then it\\'s expected to provide session headers. Eg: \"user-id\"'\n }),\n role: z.union([z.string(), z.array(z.string())]).meta({\n description: 'The role(s) to assign to the new member. Eg: [\"admin\", \"sale\"]'\n }),\n organizationId: z.string().meta({\n description: `An optional organization ID to pass. If not provided, will default to the user's active organization. Eg: \"org-id\"`\n }).optional(),\n teamId: z.string().meta({\n description: 'An optional team ID to add the member to. Eg: \"team-id\"'\n }).optional()\n });\n return createAuthEndpoint(\n \"/organization/add-member\",\n {\n method: \"POST\",\n body: z.object({\n ...baseSchema.shape,\n ...additionalFieldsSchema.shape\n }),\n use: [orgMiddleware],\n metadata: {\n SERVER_ONLY: true,\n $Infer: {\n body: {}\n }\n }\n },\n async (ctx) => {\n const session = ctx.body.userId ? await getSessionFromCtx(ctx).catch((e) => null) : null;\n const orgId = ctx.body.organizationId || session?.session.activeOrganizationId;\n if (!orgId) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n }\n });\n }\n const teamId = \"teamId\" in ctx.body ? ctx.body.teamId : void 0;\n if (teamId && !ctx.context.orgOptions.teams?.enabled) {\n ctx.context.logger.error(\"Teams are not enabled\");\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Teams are not enabled\"\n });\n }\n const adapter = getOrgAdapter(ctx.context, option);\n const user = await ctx.context.internalAdapter.findUserById(\n ctx.body.userId\n );\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.USER_NOT_FOUND\n });\n }\n const alreadyMember = await adapter.findMemberByEmail({\n email: user.email,\n organizationId: orgId\n });\n if (alreadyMember) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION\n });\n }\n if (teamId) {\n const team = await adapter.findTeamById({\n teamId,\n organizationId: orgId\n });\n if (!team || team.organizationId !== orgId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND\n });\n }\n }\n const membershipLimit = ctx.context.orgOptions?.membershipLimit || 100;\n const count = await adapter.countMembers({ organizationId: orgId });\n if (count >= membershipLimit) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_MEMBERSHIP_LIMIT_REACHED\n });\n }\n const {\n role: _,\n userId: __,\n organizationId: ___,\n ...additionalFields\n } = ctx.body;\n const createdMember = await adapter.createMember({\n organizationId: orgId,\n userId: user.id,\n role: parseRoles(ctx.body.role),\n createdAt: /* @__PURE__ */ new Date(),\n ...additionalFields ? additionalFields : {}\n });\n if (teamId) {\n await adapter.findOrCreateTeamMember({\n userId: user.id,\n teamId\n });\n }\n return ctx.json(createdMember);\n }\n );\n};\nconst removeMember = (options) => createAuthEndpoint(\n \"/organization/remove-member\",\n {\n method: \"POST\",\n body: z.object({\n memberIdOrEmail: z.string().meta({\n description: \"The ID or email of the member to remove\"\n }),\n /**\n * If not provided, the active organization will be used\n */\n organizationId: z.string().meta({\n description: 'The ID of the organization to remove the member from. If not provided, the active organization will be used. Eg: \"org-id\"'\n })\n }),\n use: [orgMiddleware, orgSessionMiddleware],\n metadata: {\n openapi: {\n description: \"Remove a member from an organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n member: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n userId: {\n type: \"string\"\n },\n organizationId: {\n type: \"string\"\n },\n role: {\n type: \"string\"\n }\n },\n required: [\"id\", \"userId\", \"organizationId\", \"role\"]\n }\n },\n required: [\"member\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n if (!organizationId) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n }\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId\n });\n if (!member) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n });\n }\n let toBeRemovedMember = null;\n if (ctx.body.memberIdOrEmail.includes(\"@\")) {\n toBeRemovedMember = await adapter.findMemberByEmail({\n email: ctx.body.memberIdOrEmail,\n organizationId\n });\n } else {\n toBeRemovedMember = await adapter.findMemberById(\n ctx.body.memberIdOrEmail\n );\n }\n if (!toBeRemovedMember) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n });\n }\n const roles = toBeRemovedMember.role.split(\",\");\n const creatorRole = ctx.context.orgOptions?.creatorRole || \"owner\";\n const isOwner = roles.includes(creatorRole);\n if (isOwner) {\n if (member.role !== creatorRole) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER\n });\n }\n const members = await adapter.listMembers({\n organizationId\n });\n const owners = members.filter((member2) => {\n const roles2 = member2.role.split(\",\");\n return roles2.includes(creatorRole);\n });\n if (owners.length <= 1) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER\n });\n }\n }\n const canDeleteMember = hasPermission({\n role: member.role,\n options: ctx.context.orgOptions,\n permissions: {\n member: [\"delete\"]\n }\n });\n if (!canDeleteMember) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER\n });\n }\n if (toBeRemovedMember?.organizationId !== organizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n });\n }\n await adapter.deleteMember(toBeRemovedMember.id);\n if (session.user.id === toBeRemovedMember.userId && session.session.activeOrganizationId === toBeRemovedMember.organizationId) {\n await adapter.setActiveOrganization(session.session.token, null);\n }\n return ctx.json({\n member: toBeRemovedMember\n });\n }\n);\nconst updateMemberRole = (option) => createAuthEndpoint(\n \"/organization/update-member-role\",\n {\n method: \"POST\",\n body: z.object({\n role: z.union([z.string(), z.array(z.string())]).meta({\n description: 'The new role to be applied. This can be a string or array of strings representing the roles. Eg: [\"admin\", \"sale\"]'\n }),\n memberId: z.string().meta({\n description: 'The member id to apply the role update to. Eg: \"member-id\"'\n }),\n organizationId: z.string().meta({\n description: 'An optional organization ID which the member is a part of to apply the role update. If not provided, you must provide session headers to get the active organization. Eg: \"organization-id\"'\n }).optional()\n }),\n use: [orgMiddleware, orgSessionMiddleware],\n metadata: {\n $Infer: {\n body: {}\n },\n openapi: {\n description: \"Update the role of a member in an organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n member: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n userId: {\n type: \"string\"\n },\n organizationId: {\n type: \"string\"\n },\n role: {\n type: \"string\"\n }\n },\n required: [\"id\", \"userId\", \"organizationId\", \"role\"]\n }\n },\n required: [\"member\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n if (!ctx.body.role) {\n throw new APIError(\"BAD_REQUEST\");\n }\n const organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n if (!organizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n });\n }\n const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n const roleToSet = Array.isArray(ctx.body.role) ? ctx.body.role : ctx.body.role ? [ctx.body.role] : [];\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId\n });\n if (!member) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n });\n }\n const toBeUpdatedMember = member.id !== ctx.body.memberId ? await adapter.findMemberById(ctx.body.memberId) : member;\n if (!toBeUpdatedMember) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n });\n }\n const creatorRole = ctx.context.orgOptions?.creatorRole || \"owner\";\n const updatingMemberRoles = member.role.split(\",\");\n const toBeUpdatedMemberRoles = toBeUpdatedMember.role.split(\",\");\n const isUpdatingCreator = toBeUpdatedMemberRoles.includes(creatorRole);\n const updaterIsCreator = updatingMemberRoles.includes(creatorRole);\n const isSettingCreatorRole = roleToSet.includes(creatorRole);\n if (isUpdatingCreator && !updaterIsCreator || isSettingCreatorRole && !updaterIsCreator) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER\n });\n }\n const canUpdateMember = hasPermission({\n role: member.role,\n options: ctx.context.orgOptions,\n permissions: {\n member: [\"update\"]\n },\n allowCreatorAllPermissions: true\n });\n if (!canUpdateMember) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER\n });\n }\n const updatedMember = await adapter.updateMember(\n ctx.body.memberId,\n parseRoles(ctx.body.role)\n );\n if (!updatedMember) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n });\n }\n return ctx.json(updatedMember);\n }\n);\nconst getActiveMember = (options) => createAuthEndpoint(\n \"/organization/get-active-member\",\n {\n method: \"GET\",\n use: [orgMiddleware, orgSessionMiddleware],\n requireHeaders: true,\n metadata: {\n openapi: {\n description: \"Get the member details of the active organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n userId: {\n type: \"string\"\n },\n organizationId: {\n type: \"string\"\n },\n role: {\n type: \"string\"\n }\n },\n required: [\"id\", \"userId\", \"organizationId\", \"role\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const organizationId = session.session.activeOrganizationId;\n if (!organizationId) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n }\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId\n });\n if (!member) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n }\n });\n }\n return ctx.json(member);\n }\n);\nconst leaveOrganization = (options) => createAuthEndpoint(\n \"/organization/leave\",\n {\n method: \"POST\",\n body: z.object({\n organizationId: z.string().meta({\n description: 'The organization Id for the member to leave. Eg: \"organization-id\"'\n })\n }),\n requireHeaders: true,\n use: [sessionMiddleware, orgMiddleware]\n },\n async (ctx) => {\n const session = ctx.context.session;\n const adapter = getOrgAdapter(ctx.context, options);\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId: ctx.body.organizationId\n });\n if (!member) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.MEMBER_NOT_FOUND\n });\n }\n const isOwnerLeaving = member.role === (ctx.context.orgOptions?.creatorRole || \"owner\");\n if (isOwnerLeaving) {\n const members = await ctx.context.adapter.findMany({\n model: \"member\",\n where: [\n {\n field: \"organizationId\",\n value: ctx.body.organizationId\n }\n ]\n });\n const owners = members.filter(\n (member2) => member2.role === (ctx.context.orgOptions?.creatorRole || \"owner\")\n );\n if (owners.length <= 1) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER\n });\n }\n }\n await adapter.deleteMember(member.id);\n if (session.session.activeOrganizationId === ctx.body.organizationId) {\n await adapter.setActiveOrganization(session.session.token, null);\n }\n return ctx.json(member);\n }\n);\n\nconst createOrganization = (options) => {\n const additionalFieldsSchema = toZodSchema({\n fields: options?.schema?.organization?.additionalFields || {},\n isClientSide: true\n });\n const baseSchema = z.object({\n name: z.string().meta({\n description: \"The name of the organization\"\n }),\n slug: z.string().meta({\n description: \"The slug of the organization\"\n }),\n userId: z.coerce.string().meta({\n description: 'The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server. server-only. Eg: \"user-id\"'\n }).optional(),\n logo: z.string().meta({\n description: \"The logo of the organization\"\n }).optional(),\n metadata: z.record(z.string(), z.any()).meta({\n description: \"The metadata of the organization\"\n }).optional(),\n keepCurrentActiveOrganization: z.boolean().meta({\n description: \"Whether to keep the current active organization active after creating a new one. Eg: true\"\n }).optional()\n });\n return createAuthEndpoint(\n \"/organization/create\",\n {\n method: \"POST\",\n body: z.object({\n ...baseSchema.shape,\n ...additionalFieldsSchema.shape\n }),\n use: [orgMiddleware],\n metadata: {\n $Infer: {\n body: {}\n },\n openapi: {\n description: \"Create an organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n description: \"The organization that was created\",\n $ref: \"#/components/schemas/Organization\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (!session && (ctx.request || ctx.headers)) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n let user = session?.user || null;\n if (!user) {\n if (!ctx.body.userId) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n user = await ctx.context.internalAdapter.findUserById(ctx.body.userId);\n }\n if (!user) {\n return ctx.json(null, {\n status: 401\n });\n }\n const options2 = ctx.context.orgOptions;\n const canCreateOrg = typeof options2?.allowUserToCreateOrganization === \"function\" ? await options2.allowUserToCreateOrganization(user) : options2?.allowUserToCreateOrganization === void 0 ? true : options2.allowUserToCreateOrganization;\n if (!canCreateOrg) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION\n });\n }\n const adapter = getOrgAdapter(ctx.context, options2);\n const userOrganizations = await adapter.listOrganizations(user.id);\n const hasReachedOrgLimit = typeof options2.organizationLimit === \"number\" ? userOrganizations.length >= options2.organizationLimit : typeof options2.organizationLimit === \"function\" ? await options2.organizationLimit(user) : false;\n if (hasReachedOrgLimit) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS\n });\n }\n const existingOrganization = await adapter.findOrganizationBySlug(\n ctx.body.slug\n );\n if (existingOrganization) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_ALREADY_EXISTS\n });\n }\n const {\n keepCurrentActiveOrganization: _,\n userId: __,\n ...orgData\n } = ctx.body;\n let hookResponse = void 0;\n if (options2.organizationCreation?.beforeCreate) {\n const response = await options2.organizationCreation.beforeCreate(\n {\n organization: {\n ...orgData,\n createdAt: /* @__PURE__ */ new Date()\n },\n user\n },\n ctx.request\n );\n if (response && typeof response === \"object\" && \"data\" in response) {\n hookResponse = response;\n }\n }\n const organization = await adapter.createOrganization({\n organization: {\n ...orgData,\n createdAt: /* @__PURE__ */ new Date(),\n ...hookResponse?.data || {}\n }\n });\n let member;\n let teamMember = null;\n if (options2?.teams?.enabled && options2.teams.defaultTeam?.enabled !== false) {\n const defaultTeam = await options2.teams.defaultTeam?.customCreateDefaultTeam?.(\n organization,\n ctx.request\n ) || await adapter.createTeam({\n organizationId: organization.id,\n name: `${organization.name}`,\n createdAt: /* @__PURE__ */ new Date()\n });\n member = await adapter.createMember({\n userId: user.id,\n organizationId: organization.id,\n role: ctx.context.orgOptions.creatorRole || \"owner\"\n });\n teamMember = await adapter.findOrCreateTeamMember({\n teamId: defaultTeam.id,\n userId: user.id\n });\n } else {\n member = await adapter.createMember({\n userId: user.id,\n organizationId: organization.id,\n role: ctx.context.orgOptions.creatorRole || \"owner\"\n });\n }\n if (options2.organizationCreation?.afterCreate) {\n await options2.organizationCreation.afterCreate(\n {\n organization,\n user,\n member\n },\n ctx.request\n );\n }\n if (ctx.context.session && !ctx.body.keepCurrentActiveOrganization) {\n await adapter.setActiveOrganization(\n ctx.context.session.session.token,\n organization.id\n );\n }\n if (teamMember && ctx.context.session && !ctx.body.keepCurrentActiveOrganization) {\n await adapter.setActiveTeam(\n ctx.context.session.session.token,\n teamMember.teamId\n );\n }\n return ctx.json({\n ...organization,\n metadata: ctx.body.metadata,\n members: [member]\n });\n }\n );\n};\nconst checkOrganizationSlug = (options) => createAuthEndpoint(\n \"/organization/check-slug\",\n {\n method: \"POST\",\n body: z.object({\n slug: z.string().meta({\n description: 'The organization slug to check. Eg: \"my-org\"'\n })\n }),\n use: [requestOnlySessionMiddleware, orgMiddleware]\n },\n async (ctx) => {\n const orgAdapter = getOrgAdapter(ctx.context, options);\n const org = await orgAdapter.findOrganizationBySlug(ctx.body.slug);\n if (!org) {\n return ctx.json({\n status: true\n });\n }\n throw new APIError(\"BAD_REQUEST\", {\n message: \"slug is taken\"\n });\n }\n);\nconst updateOrganization = (options) => {\n const additionalFieldsSchema = toZodSchema({\n fields: options?.schema?.organization?.additionalFields || {},\n isClientSide: true\n });\n return createAuthEndpoint(\n \"/organization/update\",\n {\n method: \"POST\",\n body: z.object({\n data: z.object({\n ...additionalFieldsSchema.shape,\n name: z.string().meta({\n description: \"The name of the organization\"\n }).optional(),\n slug: z.string().meta({\n description: \"The slug of the organization\"\n }).optional(),\n logo: z.string().meta({\n description: \"The logo of the organization\"\n }).optional(),\n metadata: z.record(z.string(), z.any()).meta({\n description: \"The metadata of the organization\"\n }).optional()\n }).partial(),\n organizationId: z.string().meta({\n description: 'The organization ID. Eg: \"org-id\"'\n }).optional()\n }),\n requireHeaders: true,\n use: [orgMiddleware],\n metadata: {\n $Infer: {\n body: {}\n },\n openapi: {\n description: \"Update an organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n description: \"The updated organization\",\n $ref: \"#/components/schemas/Organization\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = await ctx.context.getSession(ctx);\n if (!session) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"User not found\"\n });\n }\n const organizationId = ctx.body.organizationId || session.session.activeOrganizationId;\n if (!organizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId\n });\n if (!member) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION\n });\n }\n const canUpdateOrg = hasPermission({\n permissions: {\n organization: [\"update\"]\n },\n role: member.role,\n options: ctx.context.orgOptions\n });\n if (!canUpdateOrg) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION\n });\n }\n const updatedOrg = await adapter.updateOrganization(\n organizationId,\n ctx.body.data\n );\n return ctx.json(updatedOrg);\n }\n );\n};\nconst deleteOrganization = (options) => {\n return createAuthEndpoint(\n \"/organization/delete\",\n {\n method: \"POST\",\n body: z.object({\n organizationId: z.string().meta({\n description: \"The organization id to delete\"\n })\n }),\n requireHeaders: true,\n use: [orgMiddleware],\n metadata: {\n openapi: {\n description: \"Delete an organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"string\",\n description: \"The organization id that was deleted\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = await ctx.context.getSession(ctx);\n if (!session) {\n return ctx.json(null, {\n status: 401\n });\n }\n const organizationId = ctx.body.organizationId;\n if (!organizationId) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND\n }\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId\n });\n if (!member) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION\n }\n });\n }\n const canDeleteOrg = hasPermission({\n role: member.role,\n permissions: {\n organization: [\"delete\"]\n },\n options: ctx.context.orgOptions\n });\n if (!canDeleteOrg) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION\n });\n }\n if (organizationId === session.session.activeOrganizationId) {\n await adapter.setActiveOrganization(session.session.token, null);\n }\n const option = ctx.context.orgOptions.organizationDeletion;\n if (option?.disabled) {\n throw new APIError(\"FORBIDDEN\");\n }\n const org = await adapter.findOrganizationById(organizationId);\n if (!org) {\n throw new APIError(\"BAD_REQUEST\");\n }\n if (option?.beforeDelete) {\n await option.beforeDelete({\n organization: org,\n user: session.user\n });\n }\n await adapter.deleteOrganization(organizationId);\n if (option?.afterDelete) {\n await option.afterDelete({\n organization: org,\n user: session.user\n });\n }\n return ctx.json(org);\n }\n );\n};\nconst getFullOrganization = (options) => createAuthEndpoint(\n \"/organization/get-full-organization\",\n {\n method: \"GET\",\n query: z.optional(\n z.object({\n organizationId: z.string().meta({\n description: \"The organization id to get\"\n }).optional(),\n organizationSlug: z.string().meta({\n description: \"The organization slug to get\"\n }).optional()\n })\n ),\n requireHeaders: true,\n use: [orgMiddleware, orgSessionMiddleware],\n metadata: {\n openapi: {\n description: \"Get the full organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n description: \"The organization\",\n $ref: \"#/components/schemas/Organization\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const organizationId = ctx.query?.organizationSlug || ctx.query?.organizationId || session.session.activeOrganizationId;\n if (!organizationId) {\n return ctx.json(null, {\n status: 200\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const organization = await adapter.findFullOrganization({\n organizationId,\n isSlug: !!ctx.query?.organizationSlug,\n includeTeams: ctx.context.orgOptions.teams?.enabled\n });\n const isMember = organization?.members.find(\n (member) => member.userId === session.user.id\n );\n if (!isMember) {\n await adapter.setActiveOrganization(session.session.token, null);\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION\n });\n }\n if (!organization) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND\n });\n }\n return ctx.json(organization);\n }\n);\nconst setActiveOrganization = (options) => {\n return createAuthEndpoint(\n \"/organization/set-active\",\n {\n method: \"POST\",\n body: z.object({\n organizationId: z.string().meta({\n description: 'The organization id to set as active. It can be null to unset the active organization. Eg: \"org-id\"'\n }).nullable().optional(),\n organizationSlug: z.string().meta({\n description: 'The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided. Eg: \"org-slug\"'\n }).optional()\n }),\n use: [orgSessionMiddleware, orgMiddleware],\n metadata: {\n openapi: {\n description: \"Set the active organization\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n description: \"The organization\",\n $ref: \"#/components/schemas/Organization\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const adapter = getOrgAdapter(ctx.context, options);\n const session = ctx.context.session;\n let organizationId = ctx.body.organizationSlug || ctx.body.organizationId;\n if (organizationId === null) {\n const sessionOrgId = session.session.activeOrganizationId;\n if (!sessionOrgId) {\n return ctx.json(null);\n }\n const updatedSession2 = await adapter.setActiveOrganization(\n session.session.token,\n null\n );\n await setSessionCookie(ctx, {\n session: updatedSession2,\n user: session.user\n });\n return ctx.json(null);\n }\n if (!organizationId) {\n const sessionOrgId = session.session.activeOrganizationId;\n if (!sessionOrgId) {\n return ctx.json(null);\n }\n organizationId = sessionOrgId;\n }\n const isMember = await adapter.checkMembership({\n userId: session.user.id,\n organizationId\n });\n if (!isMember) {\n await adapter.setActiveOrganization(session.session.token, null);\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION\n });\n }\n let organization = await adapter.findOrganizationById(organizationId);\n if (!organization) {\n if (ctx.body.organizationSlug) {\n organization = await adapter.findOrganizationBySlug(organizationId);\n }\n if (!organization) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.ORGANIZATION_NOT_FOUND\n });\n }\n }\n const updatedSession = await adapter.setActiveOrganization(\n session.session.token,\n organization.id\n );\n await setSessionCookie(ctx, {\n session: updatedSession,\n user: session.user\n });\n return ctx.json(organization);\n }\n );\n};\nconst listOrganizations = (options) => createAuthEndpoint(\n \"/organization/list\",\n {\n method: \"GET\",\n use: [orgMiddleware, orgSessionMiddleware],\n metadata: {\n openapi: {\n description: \"List all organizations\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"array\",\n items: {\n $ref: \"#/components/schemas/Organization\"\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const adapter = getOrgAdapter(ctx.context, options);\n const organizations = await adapter.listOrganizations(\n ctx.context.session.user.id\n );\n return ctx.json(organizations);\n }\n);\n\nconst createTeam = (options) => {\n const additionalFieldsSchema = toZodSchema({\n fields: options?.schema?.team?.additionalFields ?? {},\n isClientSide: true\n });\n const baseSchema = z.object({\n name: z.string().meta({\n description: 'The name of the team. Eg: \"my-team\"'\n }),\n organizationId: z.string().meta({\n description: 'The organization ID which the team will be created in. Defaults to the active organization. Eg: \"organization-id\"'\n }).optional()\n });\n return createAuthEndpoint(\n \"/organization/create-team\",\n {\n method: \"POST\",\n body: z.object({\n ...baseSchema.shape,\n ...additionalFieldsSchema.shape\n }),\n use: [orgMiddleware],\n metadata: {\n $Infer: {\n body: {}\n },\n openapi: {\n description: \"Create a new team within an organization\",\n responses: {\n \"200\": {\n description: \"Team created successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Unique identifier of the created team\"\n },\n name: {\n type: \"string\",\n description: \"Name of the team\"\n },\n organizationId: {\n type: \"string\",\n description: \"ID of the organization the team belongs to\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the team was created\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the team was last updated\"\n }\n },\n required: [\n \"id\",\n \"name\",\n \"organizationId\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n const organizationId = ctx.body.organizationId || session?.session.activeOrganizationId;\n if (!session && (ctx.request || ctx.headers)) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n if (!organizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n if (session) {\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId\n });\n if (!member) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION\n });\n }\n const canCreate = hasPermission({\n role: member.role,\n options: ctx.context.orgOptions,\n permissions: {\n team: [\"create\"]\n }\n });\n if (!canCreate) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION\n });\n }\n }\n const existingTeams = await adapter.listTeams(organizationId);\n const maximum = typeof ctx.context.orgOptions.teams?.maximumTeams === \"function\" ? await ctx.context.orgOptions.teams?.maximumTeams(\n {\n organizationId,\n session\n },\n ctx.request\n ) : ctx.context.orgOptions.teams?.maximumTeams;\n const maxTeamsReached = maximum ? existingTeams.length >= maximum : false;\n if (maxTeamsReached) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS\n });\n }\n const { name, organizationId: _, ...additionalFields } = ctx.body;\n const createdTeam = await adapter.createTeam({\n name,\n organizationId,\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date(),\n ...additionalFields\n });\n return ctx.json(createdTeam);\n }\n );\n};\nconst removeTeam = (options) => createAuthEndpoint(\n \"/organization/remove-team\",\n {\n method: \"POST\",\n body: z.object({\n teamId: z.string().meta({\n description: `The team ID of the team to remove. Eg: \"team-id\"`\n }),\n organizationId: z.string().meta({\n description: `The organization ID which the team falls under. If not provided, it will default to the user's active organization. Eg: \"organization-id\"`\n }).optional()\n }),\n use: [orgMiddleware],\n metadata: {\n openapi: {\n description: \"Remove a team from an organization\",\n responses: {\n \"200\": {\n description: \"Team removed successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\",\n description: \"Confirmation message indicating successful removal\",\n enum: [\"Team removed successfully.\"]\n }\n },\n required: [\"message\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n const organizationId = ctx.body.organizationId || session?.session.activeOrganizationId;\n if (!organizationId) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n }\n });\n }\n if (!session && (ctx.request || ctx.headers)) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n const adapter = getOrgAdapter(ctx.context, options);\n if (session) {\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId\n });\n if (!member || session.session?.activeTeamId === ctx.body.teamId) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM\n });\n }\n const canRemove = hasPermission({\n role: member.role,\n options: ctx.context.orgOptions,\n permissions: {\n team: [\"delete\"]\n }\n });\n if (!canRemove) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION\n });\n }\n }\n const team = await adapter.findTeamById({\n teamId: ctx.body.teamId,\n organizationId\n });\n if (!team || team.organizationId !== organizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND\n });\n }\n if (!ctx.context.orgOptions.teams?.allowRemovingAllTeams) {\n const teams = await adapter.listTeams(organizationId);\n if (teams.length <= 1) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.UNABLE_TO_REMOVE_LAST_TEAM\n });\n }\n }\n await adapter.deleteTeam(team.id);\n return ctx.json({ message: \"Team removed successfully.\" });\n }\n);\nconst updateTeam = (options) => {\n const additionalFieldsSchema = toZodSchema({\n fields: options?.schema?.team?.additionalFields ?? {},\n isClientSide: true\n });\n return createAuthEndpoint(\n \"/organization/update-team\",\n {\n method: \"POST\",\n body: z.object({\n teamId: z.string().meta({\n description: `The ID of the team to be updated. Eg: \"team-id\"`\n }),\n data: z.object({\n ...teamSchema.shape,\n ...additionalFieldsSchema.shape\n }).partial()\n }),\n requireHeaders: true,\n use: [orgMiddleware, orgSessionMiddleware],\n metadata: {\n $Infer: { body: {} },\n openapi: {\n description: \"Update an existing team in an organization\",\n responses: {\n \"200\": {\n description: \"Team updated successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Unique identifier of the updated team\"\n },\n name: {\n type: \"string\",\n description: \"Updated name of the team\"\n },\n organizationId: {\n type: \"string\",\n description: \"ID of the organization the team belongs to\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the team was created\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the team was last updated\"\n }\n },\n required: [\n \"id\",\n \"name\",\n \"organizationId\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const organizationId = ctx.body.data.organizationId || session.session.activeOrganizationId;\n if (!organizationId) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n }\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId\n });\n if (!member) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM\n });\n }\n const canUpdate = hasPermission({\n role: member.role,\n options: ctx.context.orgOptions,\n permissions: {\n team: [\"update\"]\n }\n });\n if (!canUpdate) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM\n });\n }\n const team = await adapter.findTeamById({\n teamId: ctx.body.teamId,\n organizationId\n });\n if (!team || team.organizationId !== organizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND\n });\n }\n const { name, organizationId: __, ...additionalFields } = ctx.body.data;\n const updatedTeam = await adapter.updateTeam(team.id, {\n name,\n ...additionalFields\n });\n return ctx.json(updatedTeam);\n }\n );\n};\nconst listOrganizationTeams = (options) => createAuthEndpoint(\n \"/organization/list-teams\",\n {\n method: \"GET\",\n query: z.optional(\n z.object({\n organizationId: z.string().meta({\n description: `The organization ID which the teams are under to list. Defaults to the users active organization. Eg: \"organziation-id\"`\n }).optional()\n })\n ),\n requireHeaders: true,\n metadata: {\n openapi: {\n description: \"List all teams in an organization\",\n responses: {\n \"200\": {\n description: \"Teams retrieved successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Unique identifier of the team\"\n },\n name: {\n type: \"string\",\n description: \"Name of the team\"\n },\n organizationId: {\n type: \"string\",\n description: \"ID of the organization the team belongs to\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the team was created\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the team was last updated\"\n }\n },\n required: [\n \"id\",\n \"name\",\n \"organizationId\",\n \"createdAt\",\n \"updatedAt\"\n ]\n },\n description: \"Array of team objects within the organization\"\n }\n }\n }\n }\n }\n }\n },\n use: [orgMiddleware, orgSessionMiddleware]\n },\n async (ctx) => {\n const session = ctx.context.session;\n const organizationId = ctx.query?.organizationId || session?.session.activeOrganizationId;\n if (!organizationId) {\n throw ctx.error(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const member = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId: organizationId || \"\"\n });\n if (!member) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION\n });\n }\n const teams = await adapter.listTeams(organizationId);\n return ctx.json(teams);\n }\n);\nconst setActiveTeam = (options) => createAuthEndpoint(\n \"/organization/set-active-team\",\n {\n method: \"POST\",\n body: z.object({\n teamId: z.string().meta({\n description: \"The team id to set as active. It can be null to unset the active team\"\n }).nullable().optional()\n }),\n use: [orgSessionMiddleware, orgMiddleware],\n metadata: {\n openapi: {\n description: \"Set the active team\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n description: \"The team\",\n $ref: \"#/components/schemas/Team\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n const session = ctx.context.session;\n if (ctx.body.teamId === null) {\n const sessionTeamId = session.session.activeTeamId;\n if (!sessionTeamId) {\n return ctx.json(null);\n }\n const updatedSession2 = await adapter.setActiveTeam(\n session.session.token,\n null\n );\n await setSessionCookie(ctx, {\n session: updatedSession2,\n user: session.user\n });\n return ctx.json(null);\n }\n let teamId;\n if (!ctx.body.teamId) {\n const sessionTeamId = session.session.activeTeamId;\n if (!sessionTeamId) {\n return ctx.json(null);\n } else {\n teamId = sessionTeamId;\n }\n } else {\n teamId = ctx.body.teamId;\n }\n const team = await adapter.findTeamById({ teamId });\n if (!team) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.TEAM_NOT_FOUND\n });\n }\n const member = await adapter.findTeamMember({\n teamId,\n userId: session.user.id\n });\n if (!member) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM\n });\n }\n const updatedSession = await adapter.setActiveTeam(\n session.session.token,\n team.id\n );\n await setSessionCookie(ctx, {\n session: updatedSession,\n user: session.user\n });\n return ctx.json(team);\n }\n);\nconst listUserTeams = (options) => createAuthEndpoint(\n \"/organization/list-user-teams\",\n {\n method: \"GET\",\n metadata: {\n openapi: {\n description: \"List all teams that the current user is a part of.\",\n responses: {\n \"200\": {\n description: \"Teams retrieved successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"array\",\n items: {\n type: \"object\",\n description: \"The team\",\n $ref: \"#/components/schemas/Team\"\n },\n description: \"Array of team objects within the organization\"\n }\n }\n }\n }\n }\n }\n },\n use: [orgMiddleware, orgSessionMiddleware]\n },\n async (ctx) => {\n const session = ctx.context.session;\n const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n const teams = await adapter.listTeamsByUser({\n userId: session.user.id\n });\n return ctx.json(teams);\n }\n);\nconst listTeamMembers = (options) => createAuthEndpoint(\n \"/organization/list-team-members\",\n {\n method: \"GET\",\n query: z.optional(\n z.object({\n teamId: z.string().optional().meta({\n description: \"The team whose members we should return. If this is not provided the members of the current active team get returned.\"\n })\n })\n ),\n metadata: {\n openapi: {\n description: \"List the members of the given team.\",\n responses: {\n \"200\": {\n description: \"Teams retrieved successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"array\",\n items: {\n type: \"object\",\n description: \"The team member\",\n properties: {\n id: {\n type: \"string\",\n description: \"Unique identifier of the team member\"\n },\n userId: {\n type: \"string\",\n description: \"The user ID of the team member\"\n },\n teamId: {\n type: \"string\",\n description: \"The team ID of the team the team member is in\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the team member was created\"\n }\n },\n required: [\"id\", \"userId\", \"teamId\", \"createdAt\"]\n },\n description: \"Array of team member objects within the team\"\n }\n }\n }\n }\n }\n }\n },\n use: [orgMiddleware, orgSessionMiddleware]\n },\n async (ctx) => {\n const session = ctx.context.session;\n const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n let teamId = ctx.query?.teamId || session?.session.activeTeamId;\n if (!teamId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM\n });\n }\n const member = await adapter.findTeamMember({\n userId: session.user.id,\n teamId\n });\n if (!member) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_TEAM\n });\n }\n const members = await adapter.listTeamMembers({\n teamId\n });\n return ctx.json(members);\n }\n);\nconst addTeamMember = (options) => createAuthEndpoint(\n \"/organization/add-team-member\",\n {\n method: \"POST\",\n body: z.object({\n teamId: z.string().meta({\n description: \"The team the user should be a member of.\"\n }),\n userId: z.coerce.string().meta({\n description: \"The user Id which represents the user to be added as a member.\"\n })\n }),\n metadata: {\n openapi: {\n description: \"The newly created member\",\n responses: {\n \"200\": {\n description: \"Team member created successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n description: \"The team member\",\n properties: {\n id: {\n type: \"string\",\n description: \"Unique identifier of the team member\"\n },\n userId: {\n type: \"string\",\n description: \"The user ID of the team member\"\n },\n teamId: {\n type: \"string\",\n description: \"The team ID of the team the team member is in\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the team member was created\"\n }\n },\n required: [\"id\", \"userId\", \"teamId\", \"createdAt\"]\n }\n }\n }\n }\n }\n }\n },\n use: [orgMiddleware, orgSessionMiddleware]\n },\n async (ctx) => {\n const session = ctx.context.session;\n const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n if (!session.session.activeOrganizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n });\n }\n const currentMember = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId: session.session.activeOrganizationId\n });\n if (!currentMember) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION\n });\n }\n const canUpdateMember = hasPermission({\n role: currentMember.role,\n options: ctx.context.orgOptions,\n permissions: {\n member: [\"update\"]\n }\n });\n if (!canUpdateMember) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER\n });\n }\n const toBeAddedMember = await adapter.findMemberByOrgId({\n userId: ctx.body.userId,\n organizationId: session.session.activeOrganizationId\n });\n if (!toBeAddedMember) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION\n });\n }\n const teamMember = await adapter.findOrCreateTeamMember({\n teamId: ctx.body.teamId,\n userId: ctx.body.userId\n });\n return ctx.json(teamMember);\n }\n);\nconst removeTeamMember = (options) => createAuthEndpoint(\n \"/organization/remove-team-member\",\n {\n method: \"POST\",\n body: z.object({\n teamId: z.string().meta({\n description: \"The team the user should be removed from.\"\n }),\n userId: z.coerce.string().meta({\n description: \"The user which should be removed from the team.\"\n })\n }),\n metadata: {\n openapi: {\n description: \"Remove a member from a team\",\n responses: {\n \"200\": {\n description: \"Team member removed successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\",\n description: \"Confirmation message indicating successful removal\",\n enum: [\"Team member removed successfully.\"]\n }\n },\n required: [\"message\"]\n }\n }\n }\n }\n }\n }\n },\n use: [orgMiddleware, orgSessionMiddleware]\n },\n async (ctx) => {\n const session = ctx.context.session;\n const adapter = getOrgAdapter(ctx.context, ctx.context.orgOptions);\n if (!session.session.activeOrganizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n });\n }\n const currentMember = await adapter.findMemberByOrgId({\n userId: session.user.id,\n organizationId: session.session.activeOrganizationId\n });\n if (!currentMember) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION\n });\n }\n const canDeleteMember = hasPermission({\n role: currentMember.role,\n options: ctx.context.orgOptions,\n permissions: {\n member: [\"delete\"]\n }\n });\n if (!canDeleteMember) {\n throw new APIError(\"FORBIDDEN\", {\n message: ORGANIZATION_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER\n });\n }\n const toBeAddedMember = await adapter.findMemberByOrgId({\n userId: ctx.body.userId,\n organizationId: session.session.activeOrganizationId\n });\n if (!toBeAddedMember) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION\n });\n }\n await adapter.removeTeamMember({\n teamId: ctx.body.teamId,\n userId: ctx.body.userId\n });\n return ctx.json({ message: \"Team member removed successfully.\" });\n }\n);\n\nfunction parseRoles(roles) {\n return Array.isArray(roles) ? roles.join(\",\") : roles;\n}\nconst organization = (options) => {\n let endpoints = {\n /**\n * ### Endpoint\n *\n * POST `/organization/create`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.createOrganization`\n *\n * **client:**\n * `authClient.organization.create`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-create)\n */\n createOrganization: createOrganization(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/update`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.updateOrganization`\n *\n * **client:**\n * `authClient.organization.update`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-update)\n */\n updateOrganization: updateOrganization(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/delete`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.deleteOrganization`\n *\n * **client:**\n * `authClient.organization.delete`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-delete)\n */\n deleteOrganization: deleteOrganization(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/set-active`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.setActiveOrganization`\n *\n * **client:**\n * `authClient.organization.setActive`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-set-active)\n */\n setActiveOrganization: setActiveOrganization(options),\n /**\n * ### Endpoint\n *\n * GET `/organization/get-full-organization`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.getFullOrganization`\n *\n * **client:**\n * `authClient.organization.getFullOrganization`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-get-full-organization)\n */\n getFullOrganization: getFullOrganization(options),\n /**\n * ### Endpoint\n *\n * GET `/organization/list`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.listOrganizations`\n *\n * **client:**\n * `authClient.organization.list`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-list)\n */\n listOrganizations: listOrganizations(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/invite-member`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.createInvitation`\n *\n * **client:**\n * `authClient.organization.inviteMember`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-invite-member)\n */\n createInvitation: createInvitation(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/cancel-invitation`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.cancelInvitation`\n *\n * **client:**\n * `authClient.organization.cancelInvitation`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-cancel-invitation)\n */\n cancelInvitation: cancelInvitation(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/accept-invitation`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.acceptInvitation`\n *\n * **client:**\n * `authClient.organization.acceptInvitation`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-accept-invitation)\n */\n acceptInvitation: acceptInvitation(options),\n /**\n * ### Endpoint\n *\n * GET `/organization/get-invitation`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.getInvitation`\n *\n * **client:**\n * `authClient.organization.getInvitation`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-get-invitation)\n */\n getInvitation: getInvitation(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/reject-invitation`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.rejectInvitation`\n *\n * **client:**\n * `authClient.organization.rejectInvitation`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-reject-invitation)\n */\n rejectInvitation: rejectInvitation(),\n /**\n * ### Endpoint\n *\n * GET `/organization/list-invitations`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.listInvitations`\n *\n * **client:**\n * `authClient.organization.listInvitations`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-list-invitations)\n */\n listInvitations: listInvitations(options),\n /**\n * ### Endpoint\n *\n * GET `/organization/get-active-member`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.getActiveMember`\n *\n * **client:**\n * `authClient.organization.getActiveMember`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-get-active-member)\n */\n getActiveMember: getActiveMember(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/check-slug`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.checkOrganizationSlug`\n *\n * **client:**\n * `authClient.organization.checkSlug`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-check-slug)\n */\n checkOrganizationSlug: checkOrganizationSlug(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/add-member`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.addMember`\n *\n * **client:**\n * `authClient.organization.addMember`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-add-member)\n */\n addMember: addMember(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/remove-member`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.removeMember`\n *\n * **client:**\n * `authClient.organization.removeMember`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-remove-member)\n */\n removeMember: removeMember(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/update-member-role`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.updateMemberRole`\n *\n * **client:**\n * `authClient.organization.updateMemberRole`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-update-member-role)\n */\n updateMemberRole: updateMemberRole(),\n /**\n * ### Endpoint\n *\n * POST `/organization/leave`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.leaveOrganization`\n *\n * **client:**\n * `authClient.organization.leave`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-leave)\n */\n leaveOrganization: leaveOrganization(options),\n listUserInvitations: listUserInvitations(options)\n };\n const teamSupport = options?.teams?.enabled;\n const teamEndpoints = {\n /**\n * ### Endpoint\n *\n * POST `/organization/create-team`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.createTeam`\n *\n * **client:**\n * `authClient.organization.createTeam`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-create-team)\n */\n createTeam: createTeam(options),\n /**\n * ### Endpoint\n *\n * GET `/organization/list-teams`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.listOrganizationTeams`\n *\n * **client:**\n * `authClient.organization.listTeams`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-list-teams)\n */\n listOrganizationTeams: listOrganizationTeams(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/remove-team`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.removeTeam`\n *\n * **client:**\n * `authClient.organization.removeTeam`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-remove-team)\n */\n removeTeam: removeTeam(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/update-team`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.updateTeam`\n *\n * **client:**\n * `authClient.organization.updateTeam`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-method-organization-update-team)\n */\n updateTeam: updateTeam(options),\n /**\n * ### Endpoint\n *\n * POST `/organization/set-active-team`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.setActiveTeam`\n *\n * **client:**\n * `authClient.organization.setActiveTeam`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-set-active-team)\n */\n setActiveTeam: setActiveTeam(),\n /**\n * ### Endpoint\n *\n * POST `/organization/list-user-teams`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.listUserTeams`\n *\n * **client:**\n * `authClient.organization.listUserTeams`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-set-active-team)\n */\n listUserTeams: listUserTeams(),\n /**\n * ### Endpoint\n *\n * POST `/organization/list-team-members`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.listTeamMembers`\n *\n * **client:**\n * `authClient.organization.listTeamMembers`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-set-active-team)\n */\n listTeamMembers: listTeamMembers(),\n /**\n * ### Endpoint\n *\n * POST `/organization/add-team-member`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.addTeamMember`\n *\n * **client:**\n * `authClient.organization.addTeamMember`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-add-team-member)\n */\n addTeamMember: addTeamMember(),\n /**\n * ### Endpoint\n *\n * POST `/organization/remove-team-member`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.removeTeamMember`\n *\n * **client:**\n * `authClient.organization.removeTeamMember`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/organization#api-remove-team-member)\n */\n removeTeamMember: removeTeamMember()\n };\n if (teamSupport) {\n endpoints = {\n ...endpoints,\n ...teamEndpoints\n };\n }\n const roles = {\n ...defaultRoles,\n ...options?.roles\n };\n const teamSchema = teamSupport ? {\n team: {\n modelName: options?.schema?.team?.modelName,\n fields: {\n name: {\n type: \"string\",\n required: true,\n fieldName: options?.schema?.team?.fields?.name\n },\n organizationId: {\n type: \"string\",\n required: true,\n references: {\n model: \"organization\",\n field: \"id\"\n },\n fieldName: options?.schema?.team?.fields?.organizationId\n },\n createdAt: {\n type: \"date\",\n required: true,\n fieldName: options?.schema?.team?.fields?.createdAt\n },\n updatedAt: {\n type: \"date\",\n required: false,\n fieldName: options?.schema?.team?.fields?.updatedAt\n },\n ...options?.schema?.team?.additionalFields || {}\n }\n },\n teamMember: {\n modelName: options?.schema?.teamMember?.modelName,\n fields: {\n teamId: {\n type: \"string\",\n required: true,\n fieldName: options?.schema?.teamMember?.fields?.teamId\n },\n userId: {\n type: \"string\",\n required: true,\n references: {\n model: \"user\",\n field: \"id\"\n },\n fieldName: options?.schema?.teamMember?.fields?.userId\n },\n createdAt: {\n type: \"date\",\n required: false,\n fieldName: options?.schema?.teamMember?.fields?.createdAt\n }\n }\n }\n } : void 0;\n const api = shimContext(endpoints, {\n orgOptions: options || {},\n roles,\n getSession: async (context) => {\n return await getSessionFromCtx(context);\n }\n });\n return {\n id: \"organization\",\n endpoints: {\n // ...endpoints,\n ...api,\n hasPermission: createAuthEndpoint(\n \"/organization/has-permission\",\n {\n method: \"POST\",\n requireHeaders: true,\n body: z.object({\n organizationId: z.string().optional()\n }).and(\n z.union([\n z.object({\n permission: z.record(z.string(), z.array(z.string())),\n permissions: z.undefined()\n }),\n z.object({\n permission: z.undefined(),\n permissions: z.record(z.string(), z.array(z.string()))\n })\n ])\n ),\n use: [orgSessionMiddleware],\n metadata: {\n $Infer: {\n body: {}\n },\n openapi: {\n description: \"Check if the user has permission\",\n requestBody: {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n permission: {\n type: \"object\",\n description: \"The permission to check\",\n deprecated: true\n },\n permissions: {\n type: \"object\",\n description: \"The permission to check\"\n }\n },\n required: [\"permissions\"]\n }\n }\n }\n },\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n error: {\n type: \"string\"\n },\n success: {\n type: \"boolean\"\n }\n },\n required: [\"success\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const activeOrganizationId = ctx.body.organizationId || ctx.context.session.session.activeOrganizationId;\n if (!activeOrganizationId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ORGANIZATION_ERROR_CODES.NO_ACTIVE_ORGANIZATION\n });\n }\n const adapter = getOrgAdapter(ctx.context, options);\n const member = await adapter.findMemberByOrgId({\n userId: ctx.context.session.user.id,\n organizationId: activeOrganizationId\n });\n if (!member) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ORGANIZATION_ERROR_CODES.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION\n });\n }\n const result = hasPermission({\n role: member.role,\n options: options || {},\n permissions: ctx.body.permissions ?? ctx.body.permission\n });\n return ctx.json({\n error: null,\n success: result\n });\n }\n )\n },\n schema: {\n session: {\n fields: {\n activeOrganizationId: {\n type: \"string\",\n required: false,\n fieldName: options?.schema?.session?.fields?.activeOrganizationId\n },\n ...teamSupport ? {\n activeTeamId: {\n type: \"string\",\n required: false,\n fieldName: options?.schema?.session?.fields?.activeTeamId\n }\n } : {}\n }\n },\n organization: {\n modelName: options?.schema?.organization?.modelName,\n fields: {\n name: {\n type: \"string\",\n required: true,\n sortable: true,\n fieldName: options?.schema?.organization?.fields?.name\n },\n slug: {\n type: \"string\",\n unique: true,\n sortable: true,\n fieldName: options?.schema?.organization?.fields?.slug\n },\n logo: {\n type: \"string\",\n required: false,\n fieldName: options?.schema?.organization?.fields?.logo\n },\n createdAt: {\n type: \"date\",\n required: true,\n fieldName: options?.schema?.organization?.fields?.createdAt\n },\n metadata: {\n type: \"string\",\n required: false,\n fieldName: options?.schema?.organization?.fields?.metadata\n },\n ...options?.schema?.organization?.additionalFields || {}\n }\n },\n member: {\n modelName: options?.schema?.member?.modelName,\n fields: {\n organizationId: {\n type: \"string\",\n required: true,\n references: {\n model: \"organization\",\n field: \"id\"\n },\n fieldName: options?.schema?.member?.fields?.organizationId\n },\n userId: {\n type: \"string\",\n required: true,\n fieldName: options?.schema?.member?.fields?.userId,\n references: {\n model: \"user\",\n field: \"id\"\n }\n },\n role: {\n type: \"string\",\n required: true,\n sortable: true,\n defaultValue: \"member\",\n fieldName: options?.schema?.member?.fields?.role\n },\n createdAt: {\n type: \"date\",\n required: true,\n fieldName: options?.schema?.member?.fields?.createdAt\n },\n ...options?.schema?.member?.additionalFields || {}\n }\n },\n invitation: {\n modelName: options?.schema?.invitation?.modelName,\n fields: {\n organizationId: {\n type: \"string\",\n required: true,\n references: {\n model: \"organization\",\n field: \"id\"\n },\n fieldName: options?.schema?.invitation?.fields?.organizationId\n },\n email: {\n type: \"string\",\n required: true,\n sortable: true,\n fieldName: options?.schema?.invitation?.fields?.email\n },\n role: {\n type: \"string\",\n required: false,\n sortable: true,\n fieldName: options?.schema?.invitation?.fields?.role\n },\n ...teamSupport ? {\n teamId: {\n type: \"string\",\n required: false,\n sortable: true,\n fieldName: options?.schema?.invitation?.fields?.teamId\n }\n } : {},\n status: {\n type: \"string\",\n required: true,\n sortable: true,\n defaultValue: \"pending\",\n fieldName: options?.schema?.invitation?.fields?.status\n },\n expiresAt: {\n type: \"date\",\n required: true,\n fieldName: options?.schema?.invitation?.fields?.expiresAt\n },\n inviterId: {\n type: \"string\",\n references: {\n model: \"user\",\n field: \"id\"\n },\n fieldName: options?.schema?.invitation?.fields?.inviterId,\n required: true\n },\n ...options?.schema?.invitation?.additionalFields || {}\n }\n },\n ...teamSupport ? teamSchema : {}\n },\n $Infer: {\n Organization: {},\n Invitation: {},\n Member: {},\n Team: teamSupport ? {} : {},\n TeamMember: teamSupport ? {} : {},\n ActiveOrganization: {}\n },\n $ERROR_CODES: ORGANIZATION_ERROR_CODES,\n options\n };\n};\n\nexport { organization as o, parseRoles as p };\n","const PROTO_POLLUTION_PATTERNS = {\n proto: /\"(?:_|\\\\u0{2}5[Ff]){2}(?:p|\\\\u0{2}70)(?:r|\\\\u0{2}72)(?:o|\\\\u0{2}6[Ff])(?:t|\\\\u0{2}74)(?:o|\\\\u0{2}6[Ff])(?:_|\\\\u0{2}5[Ff]){2}\"\\s*:/,\n constructor: /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/,\n protoShort: /\"__proto__\"\\s*:/,\n constructorShort: /\"constructor\"\\s*:/\n};\nconst JSON_SIGNATURE = /^\\s*[\"[{]|^\\s*-?\\d{1,16}(\\.\\d{1,17})?([Ee][+-]?\\d+)?\\s*$/;\nconst SPECIAL_VALUES = {\n true: true,\n false: false,\n null: null,\n undefined: void 0,\n nan: Number.NaN,\n infinity: Number.POSITIVE_INFINITY,\n \"-infinity\": Number.NEGATIVE_INFINITY\n};\nconst ISO_DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,7}))?(?:Z|([+-])(\\d{2}):(\\d{2}))$/;\nfunction isValidDate(date) {\n return date instanceof Date && !isNaN(date.getTime());\n}\nfunction parseISODate(value) {\n const match = ISO_DATE_REGEX.exec(value);\n if (!match) return null;\n const [\n ,\n year,\n month,\n day,\n hour,\n minute,\n second,\n ms,\n offsetSign,\n offsetHour,\n offsetMinute\n ] = match;\n let date = new Date(\n Date.UTC(\n parseInt(year, 10),\n parseInt(month, 10) - 1,\n parseInt(day, 10),\n parseInt(hour, 10),\n parseInt(minute, 10),\n parseInt(second, 10),\n ms ? parseInt(ms.padEnd(3, \"0\"), 10) : 0\n )\n );\n if (offsetSign) {\n const offset = (parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) * (offsetSign === \"+\" ? -1 : 1);\n date.setUTCMinutes(date.getUTCMinutes() + offset);\n }\n return isValidDate(date) ? date : null;\n}\nfunction betterJSONParse(value, options = {}) {\n const {\n strict = false,\n warnings = false,\n reviver,\n parseDates = true\n } = options;\n if (typeof value !== \"string\") {\n return value;\n }\n const trimmed = value.trim();\n if (trimmed[0] === '\"' && trimmed.endsWith('\"') && !trimmed.slice(1, -1).includes('\"')) {\n return trimmed.slice(1, -1);\n }\n const lowerValue = trimmed.toLowerCase();\n if (lowerValue.length <= 9 && lowerValue in SPECIAL_VALUES) {\n return SPECIAL_VALUES[lowerValue];\n }\n if (!JSON_SIGNATURE.test(trimmed)) {\n if (strict) {\n throw new SyntaxError(\"[better-json] Invalid JSON\");\n }\n return value;\n }\n const hasProtoPattern = Object.entries(PROTO_POLLUTION_PATTERNS).some(\n ([key, pattern]) => {\n const matches = pattern.test(trimmed);\n if (matches && warnings) {\n console.warn(\n `[better-json] Detected potential prototype pollution attempt using ${key} pattern`\n );\n }\n return matches;\n }\n );\n if (hasProtoPattern && strict) {\n throw new Error(\n \"[better-json] Potential prototype pollution attempt detected\"\n );\n }\n try {\n const secureReviver = (key, value2) => {\n if (key === \"__proto__\" || key === \"constructor\" && value2 && typeof value2 === \"object\" && \"prototype\" in value2) {\n if (warnings) {\n console.warn(\n `[better-json] Dropping \"${key}\" key to prevent prototype pollution`\n );\n }\n return void 0;\n }\n if (parseDates && typeof value2 === \"string\") {\n const date = parseISODate(value2);\n if (date) {\n return date;\n }\n }\n return reviver ? reviver(key, value2) : value2;\n };\n return JSON.parse(trimmed, secureReviver);\n } catch (error) {\n if (strict) {\n throw error;\n }\n return value;\n }\n}\nfunction parseJSON(value, options = { strict: true }) {\n return betterJSONParse(value, options);\n}\n\nexport { parseJSON as p };\n","import { i as createAuthMiddleware, l as sessionMiddleware } from './better-auth.D4HhkCZJ.mjs';\nimport 'better-call';\nimport * as z from 'zod/v4';\nimport './better-auth.8zoxzg-F.mjs';\nimport '@better-auth/utils/base64';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport './better-auth.n2KFGwjY.mjs';\nimport { g as generateId } from './better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport '@better-auth/utils/hash';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport './better-auth.B4Qoxdgc.mjs';\n\nconst orgMiddleware = createAuthMiddleware(async () => {\n return {};\n});\nconst orgSessionMiddleware = createAuthMiddleware(\n {\n use: [sessionMiddleware]\n },\n async (ctx) => {\n const session = ctx.context.session;\n return {\n session\n };\n }\n);\n\nconst role = z.string();\nconst invitationStatus = z.enum([\"pending\", \"accepted\", \"rejected\", \"canceled\"]).default(\"pending\");\nz.object({\n id: z.string().default(generateId),\n name: z.string(),\n slug: z.string(),\n logo: z.string().nullish().optional(),\n metadata: z.record(z.string(), z.unknown()).or(z.string().transform((v) => JSON.parse(v))).optional(),\n createdAt: z.date()\n});\nz.object({\n id: z.string().default(generateId),\n organizationId: z.string(),\n userId: z.coerce.string(),\n role,\n createdAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nz.object({\n id: z.string().default(generateId),\n organizationId: z.string(),\n email: z.string(),\n role,\n status: invitationStatus,\n teamId: z.string().optional(),\n inviterId: z.string(),\n expiresAt: z.date()\n});\nconst teamSchema = z.object({\n id: z.string().default(generateId),\n name: z.string().min(1),\n organizationId: z.string(),\n createdAt: z.date(),\n updatedAt: z.date().optional()\n});\nz.object({\n id: z.string().default(generateId),\n teamId: z.string(),\n userId: z.string(),\n createdAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\nconst defaultRoles = [\"admin\", \"member\", \"owner\"];\nz.union([\n z.enum(defaultRoles),\n z.array(z.enum(defaultRoles))\n]);\n\nexport { orgSessionMiddleware as a, orgMiddleware as o, teamSchema as t };\n","import { B as BetterAuthError } from '../../shared/better-auth.DdzSJf-n.mjs';\n\nfunction role(statements) {\n return {\n authorize(request, connector = \"AND\") {\n let success = false;\n for (const [requestedResource, requestedActions] of Object.entries(\n request\n )) {\n const allowedActions = statements[requestedResource];\n if (!allowedActions) {\n return {\n success: false,\n error: `You are not allowed to access resource: ${requestedResource}`\n };\n }\n if (Array.isArray(requestedActions)) {\n success = requestedActions.every(\n (requestedAction) => allowedActions.includes(requestedAction)\n );\n } else {\n if (typeof requestedActions === \"object\") {\n const actions = requestedActions;\n if (actions.connector === \"OR\") {\n success = actions.actions.some(\n (requestedAction) => allowedActions.includes(requestedAction)\n );\n } else {\n success = actions.actions.every(\n (requestedAction) => allowedActions.includes(requestedAction)\n );\n }\n } else {\n throw new BetterAuthError(\"Invalid access control request\");\n }\n }\n if (success && connector === \"OR\") {\n return { success };\n }\n if (!success && connector === \"AND\") {\n return {\n success: false,\n error: `unauthorized to access resource \"${requestedResource}\"`\n };\n }\n }\n if (success) {\n return {\n success\n };\n }\n return {\n success: false,\n error: \"Not authorized\"\n };\n },\n statements\n };\n}\nfunction createAccessControl(s) {\n return {\n newRole(statements) {\n return role(statements);\n },\n statements: s\n };\n}\n\nexport { createAccessControl, role };\n","import { createAccessControl } from '../../access/index.mjs';\nimport '../../../shared/better-auth.DdzSJf-n.mjs';\n\nconst defaultStatements = {\n organization: [\"update\", \"delete\"],\n member: [\"create\", \"update\", \"delete\"],\n invitation: [\"create\", \"cancel\"],\n team: [\"create\", \"update\", \"delete\"]\n};\nconst defaultAc = createAccessControl(defaultStatements);\nconst adminAc = defaultAc.newRole({\n organization: [\"update\"],\n invitation: [\"create\", \"cancel\"],\n member: [\"create\", \"update\", \"delete\"],\n team: [\"create\", \"update\", \"delete\"]\n});\nconst ownerAc = defaultAc.newRole({\n organization: [\"update\", \"delete\"],\n member: [\"create\", \"update\", \"delete\"],\n invitation: [\"create\", \"cancel\"],\n team: [\"create\", \"update\", \"delete\"]\n});\nconst memberAc = defaultAc.newRole({\n organization: [],\n member: [],\n invitation: [],\n team: []\n});\nconst defaultRoles = {\n admin: adminAc,\n owner: ownerAc,\n member: memberAc\n};\n\nexport { adminAc, defaultAc, defaultRoles, defaultStatements, memberAc, ownerAc };\n","import * as z from 'zod/v4';\n\nfunction toZodSchema({\n fields,\n isClientSide\n}) {\n const zodFields = Object.keys(fields).reduce((acc, key) => {\n const field = fields[key];\n if (!field) {\n return acc;\n }\n if (isClientSide && field.input === false) {\n return acc;\n }\n if (field.type === \"string[]\" || field.type === \"number[]\") {\n return {\n ...acc,\n [key]: z.array(field.type === \"string[]\" ? z.string() : z.number())\n };\n }\n if (Array.isArray(field.type)) {\n return {\n ...acc,\n [key]: z.any()\n };\n }\n let schema2 = z[field.type]();\n if (field?.required === false) {\n schema2 = schema2.optional();\n }\n if (field?.returned === false) {\n return acc;\n }\n return {\n ...acc,\n [key]: schema2\n };\n }, {});\n const schema = z.object(zodFields);\n return schema;\n}\n\nexport { toZodSchema as t };\n","import { g as generateRandomString } from '../../shared/better-auth.B4Qoxdgc.mjs';\nimport * as z from 'zod/v4';\nimport { k as getSessionFromCtx, j as createAuthEndpoint, l as sessionMiddleware, B as BASE_ERROR_CODES, i as createAuthMiddleware } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport { APIError } from 'better-call';\nimport { setSessionCookie, deleteSessionCookie } from '../../cookies/index.mjs';\nimport { m as mergeSchema } from '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { symmetricEncrypt, symmetricDecrypt } from '../../crypto/index.mjs';\nimport { base64Url } from '@better-auth/utils/base64';\nimport { createHMAC } from '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport { createHash } from '@better-auth/utils/hash';\nimport { createOTP } from '@better-auth/utils/otp';\nimport { v as validatePassword } from '../../shared/better-auth.YwDQhoPc.mjs';\nexport { t as twoFactorClient } from '../../shared/better-auth.Ddw8bVyV.mjs';\nimport '@better-auth/utils/random';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-fetch/fetch';\nimport 'jose';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport 'jose/errors';\n\nconst TWO_FACTOR_ERROR_CODES = {\n OTP_NOT_ENABLED: \"OTP not enabled\",\n OTP_HAS_EXPIRED: \"OTP has expired\",\n TOTP_NOT_ENABLED: \"TOTP not enabled\",\n TWO_FACTOR_NOT_ENABLED: \"Two factor isn't enabled\",\n BACKUP_CODES_NOT_ENABLED: \"Backup codes aren't enabled\",\n INVALID_BACKUP_CODE: \"Invalid backup code\",\n INVALID_CODE: \"Invalid code\",\n TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: \"Too many attempts. Please request a new code.\",\n INVALID_TWO_FACTOR_COOKIE: \"Invalid two factor cookie\"\n};\n\nconst TWO_FACTOR_COOKIE_NAME = \"two_factor\";\nconst TRUST_DEVICE_COOKIE_NAME = \"trust_device\";\n\nasync function verifyTwoFactor(ctx) {\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n const cookieName = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME);\n const twoFactorCookie = await ctx.getSignedCookie(\n cookieName.name,\n ctx.context.secret\n );\n if (!twoFactorCookie) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE\n });\n }\n const verificationToken = await ctx.context.internalAdapter.findVerificationValue(twoFactorCookie);\n if (!verificationToken) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE\n });\n }\n const user = await ctx.context.internalAdapter.findUserById(\n verificationToken.value\n );\n if (!user) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE\n });\n }\n const dontRememberMe = await ctx.getSignedCookie(\n ctx.context.authCookies.dontRememberToken.name,\n ctx.context.secret\n );\n return {\n valid: async (ctx2) => {\n const session2 = await ctx2.context.internalAdapter.createSession(\n verificationToken.value,\n ctx2,\n !!dontRememberMe\n );\n if (!session2) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"failed to create session\"\n });\n }\n await setSessionCookie(ctx2, {\n session: session2,\n user\n });\n if (ctx2.body.trustDevice) {\n const trustDeviceCookie = ctx2.context.createAuthCookie(\n TRUST_DEVICE_COOKIE_NAME,\n {\n maxAge: 30 * 24 * 60 * 60\n // 30 days, it'll be refreshed on sign in requests\n }\n );\n const token = await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(\n ctx2.context.secret,\n `${user.id}!${session2.token}`\n );\n await ctx2.setSignedCookie(\n trustDeviceCookie.name,\n `${token}!${session2.token}`,\n ctx2.context.secret,\n trustDeviceCookie.attributes\n );\n ctx2.setCookie(ctx2.context.authCookies.dontRememberToken.name, \"\", {\n maxAge: 0\n });\n ctx2.setCookie(cookieName.name, \"\", {\n maxAge: 0\n });\n }\n return ctx2.json({\n token: session2.token,\n user: {\n id: user.id,\n email: user.email,\n emailVerified: user.emailVerified,\n name: user.name,\n image: user.image,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt\n }\n });\n },\n invalid: async (errorKey) => {\n throw new APIError(\"UNAUTHORIZED\", {\n message: TWO_FACTOR_ERROR_CODES[errorKey]\n });\n },\n session: {\n session: null,\n user\n },\n key: twoFactorCookie\n };\n }\n return {\n valid: async (ctx2) => {\n return ctx2.json({\n token: session.session.token,\n user: {\n id: session.user.id,\n email: session.user.email,\n emailVerified: session.user.emailVerified,\n name: session.user.name,\n image: session.user.image,\n createdAt: session.user.createdAt,\n updatedAt: session.user.updatedAt\n }\n });\n },\n invalid: async () => {\n throw new APIError(\"UNAUTHORIZED\", {\n message: TWO_FACTOR_ERROR_CODES.INVALID_TWO_FACTOR_COOKIE\n });\n },\n session,\n key: `${session.user.id}!${session.session.id}`\n };\n}\n\nfunction generateBackupCodesFn(options) {\n return Array.from({ length: options?.amount ?? 10 }).fill(null).map(() => generateRandomString(options?.length ?? 10, \"a-z\", \"0-9\", \"A-Z\")).map((code) => `${code.slice(0, 5)}-${code.slice(5)}`);\n}\nasync function generateBackupCodes(secret, options) {\n const key = secret;\n const backupCodes = options?.customBackupCodesGenerate ? options.customBackupCodesGenerate() : generateBackupCodesFn(options);\n const encCodes = await symmetricEncrypt({\n data: JSON.stringify(backupCodes),\n key\n });\n return {\n backupCodes,\n encryptedBackupCodes: encCodes\n };\n}\nasync function verifyBackupCode(data, key) {\n const codes = await getBackupCodes(data.backupCodes, key);\n if (!codes) {\n return {\n status: false,\n updated: null\n };\n }\n return {\n status: codes.includes(data.code),\n updated: codes.filter((code) => code !== data.code)\n };\n}\nasync function getBackupCodes(backupCodes, key) {\n const secret = new TextDecoder(\"utf-8\").decode(\n new TextEncoder().encode(\n await symmetricDecrypt({ key, data: backupCodes })\n )\n );\n const data = JSON.parse(secret);\n const result = z.array(z.string()).safeParse(data);\n if (result.success) {\n return result.data;\n }\n return null;\n}\nconst backupCode2fa = (options) => {\n const twoFactorTable = \"twoFactor\";\n async function storeBackupCodes(ctx, backupCodes) {\n if (options?.storeBackupCodes === \"encrypted\") {\n return await symmetricEncrypt({\n key: ctx.context.secret,\n data: backupCodes\n });\n }\n if (typeof options?.storeBackupCodes === \"object\" && \"encrypt\" in options?.storeBackupCodes) {\n return await options?.storeBackupCodes.encrypt(backupCodes);\n }\n return backupCodes;\n }\n async function decryptBackupCodes(ctx, backupCodes) {\n if (options?.storeBackupCodes === \"encrypted\") {\n return await symmetricDecrypt({\n key: ctx.context.secret,\n data: backupCodes\n });\n }\n if (typeof options?.storeBackupCodes === \"object\" && \"decrypt\" in options?.storeBackupCodes) {\n return await options?.storeBackupCodes.decrypt(backupCodes);\n }\n return backupCodes;\n }\n return {\n id: \"backup_code\",\n endpoints: {\n /**\n * ### Endpoint\n *\n * POST `/two-factor/verify-backup-code`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.verifyBackupCode`\n *\n * **client:**\n * `authClient.twoFactor.verifyBackupCode`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/2fa#api-method-two-factor-verify-backup-code)\n */\n verifyBackupCode: createAuthEndpoint(\n \"/two-factor/verify-backup-code\",\n {\n method: \"POST\",\n body: z.object({\n code: z.string().meta({\n description: `A backup code to verify. Eg: \"123456\"`\n }),\n /**\n * Disable setting the session cookie\n */\n disableSession: z.boolean().meta({\n description: \"If true, the session cookie will not be set.\"\n }).optional(),\n /**\n * if true, the device will be trusted\n * for 30 days. It'll be refreshed on\n * every sign in request within this time.\n */\n trustDevice: z.boolean().meta({\n description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Verify a backup code for two-factor authentication\",\n responses: {\n \"200\": {\n description: \"Backup code verified successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Unique identifier of the user\"\n },\n email: {\n type: \"string\",\n format: \"email\",\n nullable: true,\n description: \"User's email address\"\n },\n emailVerified: {\n type: \"boolean\",\n nullable: true,\n description: \"Whether the email is verified\"\n },\n name: {\n type: \"string\",\n nullable: true,\n description: \"User's name\"\n },\n image: {\n type: \"string\",\n format: \"uri\",\n nullable: true,\n description: \"User's profile image URL\"\n },\n twoFactorEnabled: {\n type: \"boolean\",\n description: \"Whether two-factor authentication is enabled for the user\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the user was created\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the user was last updated\"\n }\n },\n required: [\n \"id\",\n \"twoFactorEnabled\",\n \"createdAt\",\n \"updatedAt\"\n ],\n description: \"The authenticated user object with two-factor details\"\n },\n session: {\n type: \"object\",\n properties: {\n token: {\n type: \"string\",\n description: \"Session token\"\n },\n userId: {\n type: \"string\",\n description: \"ID of the user associated with the session\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the session was created\"\n },\n expiresAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the session expires\"\n }\n },\n required: [\n \"token\",\n \"userId\",\n \"createdAt\",\n \"expiresAt\"\n ],\n description: \"The current session object, included unless disableSession is true\"\n }\n },\n required: [\"user\", \"session\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { session, valid } = await verifyTwoFactor(ctx);\n const user = session.user;\n const twoFactor = await ctx.context.adapter.findOne({\n model: twoFactorTable,\n where: [\n {\n field: \"userId\",\n value: user.id\n }\n ]\n });\n if (!twoFactor) {\n throw new APIError(\"BAD_REQUEST\", {\n message: TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED\n });\n }\n const decryptedBackupCodes = await decryptBackupCodes(\n ctx,\n twoFactor.backupCodes\n );\n const validate = await verifyBackupCode(\n {\n backupCodes: decryptedBackupCodes,\n code: ctx.body.code\n },\n ctx.context.secret\n );\n if (!validate.status) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: TWO_FACTOR_ERROR_CODES.INVALID_BACKUP_CODE\n });\n }\n const updatedBackupCodes = await symmetricEncrypt({\n key: ctx.context.secret,\n data: JSON.stringify(validate.updated)\n });\n await ctx.context.adapter.updateMany({\n model: twoFactorTable,\n update: {\n backupCodes: updatedBackupCodes\n },\n where: [\n {\n field: \"userId\",\n value: user.id\n }\n ]\n });\n if (!ctx.body.disableSession) {\n return valid(ctx);\n }\n return ctx.json({\n token: session.session?.token,\n user: {\n id: session.user?.id,\n email: session.user.email,\n emailVerified: session.user.emailVerified,\n name: session.user.name,\n image: session.user.image,\n createdAt: session.user.createdAt,\n updatedAt: session.user.updatedAt\n }\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/two-factor/generate-backup-codes`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.generateBackupCodes`\n *\n * **client:**\n * `authClient.twoFactor.generateBackupCodes`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/2fa#api-method-two-factor-generate-backup-codes)\n */\n generateBackupCodes: createAuthEndpoint(\n \"/two-factor/generate-backup-codes\",\n {\n method: \"POST\",\n body: z.object({\n password: z.string().meta({\n description: \"The users password.\"\n })\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Generate new backup codes for two-factor authentication\",\n responses: {\n \"200\": {\n description: \"Backup codes generated successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the backup codes were generated successfully\",\n enum: [true]\n },\n backupCodes: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Array of generated backup codes in plain text\"\n }\n },\n required: [\"status\", \"backupCodes\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const user = ctx.context.session.user;\n if (!user.twoFactorEnabled) {\n throw new APIError(\"BAD_REQUEST\", {\n message: TWO_FACTOR_ERROR_CODES.TWO_FACTOR_NOT_ENABLED\n });\n }\n await ctx.context.password.checkPassword(user.id, ctx);\n const backupCodes = await generateBackupCodes(\n ctx.context.secret,\n options\n );\n const storedBackupCodes = await storeBackupCodes(\n ctx,\n backupCodes.encryptedBackupCodes\n );\n await ctx.context.adapter.update({\n model: twoFactorTable,\n update: {\n backupCodes: storedBackupCodes\n },\n where: [\n {\n field: \"userId\",\n value: ctx.context.session.user.id\n }\n ]\n });\n return ctx.json({\n status: true,\n backupCodes: backupCodes.backupCodes\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * GET `/two-factor/view-backup-codes`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.viewBackupCodes`\n *\n * **client:**\n * `authClient.twoFactor.viewBackupCodes`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/2fa#api-method-two-factor-view-backup-codes)\n */\n viewBackupCodes: createAuthEndpoint(\n \"/two-factor/view-backup-codes\",\n {\n method: \"GET\",\n body: z.object({\n userId: z.coerce.string().meta({\n description: `The user ID to view all backup codes. Eg: \"user-id\"`\n })\n }),\n metadata: {\n SERVER_ONLY: true\n }\n },\n async (ctx) => {\n const twoFactor = await ctx.context.adapter.findOne({\n model: twoFactorTable,\n where: [\n {\n field: \"userId\",\n value: ctx.body.userId\n }\n ]\n });\n if (!twoFactor) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Backup codes aren't enabled\"\n });\n }\n const backupCodes = await getBackupCodes(\n twoFactor.backupCodes,\n ctx.context.secret\n );\n if (!backupCodes) {\n throw new APIError(\"BAD_REQUEST\", {\n message: TWO_FACTOR_ERROR_CODES.BACKUP_CODES_NOT_ENABLED\n });\n }\n const decryptedBackupCodes = await decryptBackupCodes(\n ctx,\n twoFactor.backupCodes\n );\n return ctx.json({\n status: true,\n backupCodes: decryptedBackupCodes\n });\n }\n )\n }\n };\n};\n\nconst defaultKeyHasher = async (token) => {\n const hash = await createHash(\"SHA-256\").digest(\n new TextEncoder().encode(token)\n );\n const hashed = base64Url.encode(new Uint8Array(hash), {\n padding: false\n });\n return hashed;\n};\n\nconst otp2fa = (options) => {\n const opts = {\n storeOTP: \"plain\",\n digits: 6,\n ...options,\n period: (options?.period || 3) * 60 * 1e3\n };\n async function storeOTP(ctx, otp) {\n if (opts.storeOTP === \"hashed\") {\n return await defaultKeyHasher(otp);\n }\n if (typeof opts.storeOTP === \"object\" && \"hash\" in opts.storeOTP) {\n return await opts.storeOTP.hash(otp);\n }\n if (typeof opts.storeOTP === \"object\" && \"encrypt\" in opts.storeOTP) {\n return await opts.storeOTP.encrypt(otp);\n }\n if (opts.storeOTP === \"encrypted\") {\n return await symmetricEncrypt({\n key: ctx.context.secret,\n data: otp\n });\n }\n return otp;\n }\n async function decryptOTP(ctx, otp) {\n if (opts.storeOTP === \"hashed\") {\n return await defaultKeyHasher(otp);\n }\n if (opts.storeOTP === \"encrypted\") {\n return await symmetricDecrypt({\n key: ctx.context.secret,\n data: otp\n });\n }\n if (typeof opts.storeOTP === \"object\" && \"encrypt\" in opts.storeOTP) {\n return await opts.storeOTP.decrypt(otp);\n }\n if (typeof opts.storeOTP === \"object\" && \"hash\" in opts.storeOTP) {\n return await opts.storeOTP.hash(otp);\n }\n return otp;\n }\n const send2FaOTP = createAuthEndpoint(\n \"/two-factor/send-otp\",\n {\n method: \"POST\",\n body: z.object({\n /**\n * if true, the device will be trusted\n * for 30 days. It'll be refreshed on\n * every sign in request within this time.\n */\n trustDevice: z.boolean().optional().meta({\n description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\"\n })\n }).optional(),\n metadata: {\n openapi: {\n summary: \"Send two factor OTP\",\n description: \"Send two factor OTP to the user\",\n responses: {\n 200: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!options || !options.sendOTP) {\n ctx.context.logger.error(\n \"send otp isn't configured. Please configure the send otp function on otp options.\"\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: \"otp isn't configured\"\n });\n }\n const { session, key } = await verifyTwoFactor(ctx);\n if (!session.user.twoFactorEnabled) {\n throw new APIError(\"BAD_REQUEST\", {\n message: TWO_FACTOR_ERROR_CODES.OTP_NOT_ENABLED\n });\n }\n const code = generateRandomString(opts.digits, \"0-9\");\n const hashedCode = await storeOTP(ctx, code);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: `${hashedCode}:0`,\n identifier: `2fa-otp-${key}`,\n expiresAt: new Date(Date.now() + opts.period)\n },\n ctx\n );\n await options.sendOTP(\n { user: session.user, otp: code },\n ctx.request\n );\n return ctx.json({ status: true });\n }\n );\n const verifyOTP = createAuthEndpoint(\n \"/two-factor/verify-otp\",\n {\n method: \"POST\",\n body: z.object({\n code: z.string().meta({\n description: 'The otp code to verify. Eg: \"012345\"'\n }),\n /**\n * if true, the device will be trusted\n * for 30 days. It'll be refreshed on\n * every sign in request within this time.\n */\n trustDevice: z.boolean().optional().meta({\n description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\"\n })\n }),\n metadata: {\n openapi: {\n summary: \"Verify two factor OTP\",\n description: \"Verify two factor OTP\",\n responses: {\n \"200\": {\n description: \"Two-factor OTP verified successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n token: {\n type: \"string\",\n description: \"Session token for the authenticated session\"\n },\n user: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Unique identifier of the user\"\n },\n email: {\n type: \"string\",\n format: \"email\",\n nullable: true,\n description: \"User's email address\"\n },\n emailVerified: {\n type: \"boolean\",\n nullable: true,\n description: \"Whether the email is verified\"\n },\n name: {\n type: \"string\",\n nullable: true,\n description: \"User's name\"\n },\n image: {\n type: \"string\",\n format: \"uri\",\n nullable: true,\n description: \"User's profile image URL\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the user was created\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the user was last updated\"\n }\n },\n required: [\"id\", \"createdAt\", \"updatedAt\"],\n description: \"The authenticated user object\"\n }\n },\n required: [\"token\", \"user\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { session, key, valid, invalid } = await verifyTwoFactor(ctx);\n const toCheckOtp = await ctx.context.internalAdapter.findVerificationValue(\n `2fa-otp-${key}`\n );\n const [otp, counter] = toCheckOtp?.value?.split(\":\") ?? [];\n const decryptedOtp = await decryptOTP(ctx, otp);\n if (!toCheckOtp || toCheckOtp.expiresAt < /* @__PURE__ */ new Date()) {\n if (toCheckOtp) {\n await ctx.context.internalAdapter.deleteVerificationValue(\n toCheckOtp.id\n );\n }\n throw new APIError(\"BAD_REQUEST\", {\n message: TWO_FACTOR_ERROR_CODES.OTP_HAS_EXPIRED\n });\n }\n const allowedAttempts = options?.allowedAttempts || 5;\n if (parseInt(counter) >= allowedAttempts) {\n await ctx.context.internalAdapter.deleteVerificationValue(\n toCheckOtp.id\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: TWO_FACTOR_ERROR_CODES.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE\n });\n }\n if (decryptedOtp === ctx.body.code) {\n if (!session.user.twoFactorEnabled) {\n if (!session.session) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION\n });\n }\n const updatedUser = await ctx.context.internalAdapter.updateUser(\n session.user.id,\n {\n twoFactorEnabled: true\n }\n );\n const newSession = await ctx.context.internalAdapter.createSession(\n session.user.id,\n ctx,\n false,\n session.session\n );\n await ctx.context.internalAdapter.deleteSession(\n session.session.token\n );\n await setSessionCookie(ctx, {\n session: newSession,\n user: updatedUser\n });\n return ctx.json({\n token: newSession.token,\n user: {\n id: updatedUser.id,\n email: updatedUser.email,\n emailVerified: updatedUser.emailVerified,\n name: updatedUser.name,\n image: updatedUser.image,\n createdAt: updatedUser.createdAt,\n updatedAt: updatedUser.updatedAt\n }\n });\n }\n return valid(ctx);\n } else {\n await ctx.context.internalAdapter.updateVerificationValue(\n toCheckOtp.id,\n {\n value: `${otp}:${(parseInt(counter, 10) || 0) + 1}`\n }\n );\n return invalid(\"INVALID_CODE\");\n }\n }\n );\n return {\n id: \"otp\",\n endpoints: {\n /**\n * ### Endpoint\n *\n * POST `/two-factor/send-otp`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.send2FaOTP`\n *\n * **client:**\n * `authClient.twoFactor.sendOtp`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/2fa#api-method-two-factor-send-otp)\n */\n sendTwoFactorOTP: send2FaOTP,\n /**\n * ### Endpoint\n *\n * POST `/two-factor/verify-otp`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.verifyOTP`\n *\n * **client:**\n * `authClient.twoFactor.verifyOtp`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/2fa#api-method-two-factor-verify-otp)\n */\n verifyTwoFactorOTP: verifyOTP\n }\n };\n};\n\nconst totp2fa = (options) => {\n const opts = {\n ...options,\n digits: options?.digits || 6,\n period: options?.period || 30\n };\n const twoFactorTable = \"twoFactor\";\n const generateTOTP = createAuthEndpoint(\n \"/totp/generate\",\n {\n method: \"POST\",\n body: z.object({\n secret: z.string().meta({\n description: \"The secret to generate the TOTP code\"\n })\n }),\n metadata: {\n openapi: {\n summary: \"Generate TOTP code\",\n description: \"Use this endpoint to generate a TOTP code\",\n responses: {\n 200: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n },\n SERVER_ONLY: true\n }\n },\n async (ctx) => {\n if (options?.disable) {\n ctx.context.logger.error(\n \"totp isn't configured. please pass totp option on two factor plugin to enable totp\"\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: \"totp isn't configured\"\n });\n }\n const code = await createOTP(ctx.body.secret, {\n period: opts.period,\n digits: opts.digits\n }).totp();\n return { code };\n }\n );\n const getTOTPURI = createAuthEndpoint(\n \"/two-factor/get-totp-uri\",\n {\n method: \"POST\",\n use: [sessionMiddleware],\n body: z.object({\n password: z.string().meta({\n description: \"User password\"\n })\n }),\n metadata: {\n openapi: {\n summary: \"Get TOTP URI\",\n description: \"Use this endpoint to get the TOTP URI\",\n responses: {\n 200: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n totpURI: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (options?.disable) {\n ctx.context.logger.error(\n \"totp isn't configured. please pass totp option on two factor plugin to enable totp\"\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: \"totp isn't configured\"\n });\n }\n const user = ctx.context.session.user;\n const twoFactor = await ctx.context.adapter.findOne({\n model: twoFactorTable,\n where: [\n {\n field: \"userId\",\n value: user.id\n }\n ]\n });\n if (!twoFactor) {\n throw new APIError(\"BAD_REQUEST\", {\n message: TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED\n });\n }\n const secret = await symmetricDecrypt({\n key: ctx.context.secret,\n data: twoFactor.secret\n });\n await ctx.context.password.checkPassword(user.id, ctx);\n const totpURI = createOTP(secret, {\n digits: opts.digits,\n period: opts.period\n }).url(options?.issuer || ctx.context.appName, user.email);\n return {\n totpURI\n };\n }\n );\n const verifyTOTP = createAuthEndpoint(\n \"/two-factor/verify-totp\",\n {\n method: \"POST\",\n body: z.object({\n code: z.string().meta({\n description: 'The otp code to verify. Eg: \"012345\"'\n }),\n /**\n * if true, the device will be trusted\n * for 30 days. It'll be refreshed on\n * every sign in request within this time.\n */\n trustDevice: z.boolean().meta({\n description: \"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\"\n }).optional()\n }),\n metadata: {\n openapi: {\n summary: \"Verify two factor TOTP\",\n description: \"Verify two factor TOTP\",\n responses: {\n 200: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (options?.disable) {\n ctx.context.logger.error(\n \"totp isn't configured. please pass totp option on two factor plugin to enable totp\"\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: \"totp isn't configured\"\n });\n }\n const { session, valid, invalid } = await verifyTwoFactor(ctx);\n const user = session.user;\n const twoFactor = await ctx.context.adapter.findOne({\n model: twoFactorTable,\n where: [\n {\n field: \"userId\",\n value: user.id\n }\n ]\n });\n if (!twoFactor) {\n throw new APIError(\"BAD_REQUEST\", {\n message: TWO_FACTOR_ERROR_CODES.TOTP_NOT_ENABLED\n });\n }\n const decrypted = await symmetricDecrypt({\n key: ctx.context.secret,\n data: twoFactor.secret\n });\n const status = await createOTP(decrypted, {\n period: opts.period,\n digits: opts.digits\n }).verify(ctx.body.code);\n if (!status) {\n return invalid(\"INVALID_CODE\");\n }\n if (!user.twoFactorEnabled) {\n if (!session.session) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION\n });\n }\n const updatedUser = await ctx.context.internalAdapter.updateUser(\n user.id,\n {\n twoFactorEnabled: true\n },\n ctx\n );\n const newSession = await ctx.context.internalAdapter.createSession(user.id, ctx, false, session.session).catch((e) => {\n throw e;\n });\n await ctx.context.internalAdapter.deleteSession(session.session.token);\n await setSessionCookie(ctx, {\n session: newSession,\n user: updatedUser\n });\n }\n return valid(ctx);\n }\n );\n return {\n id: \"totp\",\n endpoints: {\n /**\n * ### Endpoint\n *\n * POST `/totp/generate`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.generateTOTP`\n *\n * **client:**\n * `authClient.totp.generate`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/totp#api-method-totp-generate)\n */\n generateTOTP,\n /**\n * ### Endpoint\n *\n * POST `/two-factor/get-totp-uri`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.getTOTPURI`\n *\n * **client:**\n * `authClient.twoFactor.getTotpUri`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/two-factor#api-method-two-factor-get-totp-uri)\n */\n getTOTPURI,\n verifyTOTP\n }\n };\n};\n\nconst schema = {\n user: {\n fields: {\n twoFactorEnabled: {\n type: \"boolean\",\n required: false,\n defaultValue: false,\n input: false\n }\n }\n },\n twoFactor: {\n fields: {\n secret: {\n type: \"string\",\n required: true,\n returned: false\n },\n backupCodes: {\n type: \"string\",\n required: true,\n returned: false\n },\n userId: {\n type: \"string\",\n required: true,\n returned: false,\n references: {\n model: \"user\",\n field: \"id\"\n }\n }\n }\n }\n};\n\nconst twoFactor = (options) => {\n const opts = {\n twoFactorTable: \"twoFactor\"\n };\n const totp = totp2fa(options?.totpOptions);\n const backupCode = backupCode2fa(options?.backupCodeOptions);\n const otp = otp2fa(options?.otpOptions);\n return {\n id: \"two-factor\",\n endpoints: {\n ...totp.endpoints,\n ...otp.endpoints,\n ...backupCode.endpoints,\n /**\n * ### Endpoint\n *\n * POST `/two-factor/enable`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.enableTwoFactor`\n *\n * **client:**\n * `authClient.twoFactor.enable`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/2fa#api-method-two-factor-enable)\n */\n enableTwoFactor: createAuthEndpoint(\n \"/two-factor/enable\",\n {\n method: \"POST\",\n body: z.object({\n password: z.string().meta({\n description: \"User password\"\n }),\n issuer: z.string().meta({\n description: \"Custom issuer for the TOTP URI\"\n }).optional()\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n summary: \"Enable two factor authentication\",\n description: \"Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.\",\n responses: {\n 200: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n totpURI: {\n type: \"string\",\n description: \"TOTP URI\"\n },\n backupCodes: {\n type: \"array\",\n items: {\n type: \"string\"\n },\n description: \"Backup codes\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const user = ctx.context.session.user;\n const { password, issuer } = ctx.body;\n const isPasswordValid = await validatePassword(ctx, {\n password,\n userId: user.id\n });\n if (!isPasswordValid) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.INVALID_PASSWORD\n });\n }\n const secret = generateRandomString(32);\n const encryptedSecret = await symmetricEncrypt({\n key: ctx.context.secret,\n data: secret\n });\n const backupCodes = await generateBackupCodes(\n ctx.context.secret,\n options?.backupCodeOptions\n );\n if (options?.skipVerificationOnEnable) {\n const updatedUser = await ctx.context.internalAdapter.updateUser(\n user.id,\n {\n twoFactorEnabled: true\n },\n ctx\n );\n const newSession = await ctx.context.internalAdapter.createSession(\n updatedUser.id,\n ctx,\n false,\n ctx.context.session.session\n );\n await setSessionCookie(ctx, {\n session: newSession,\n user: updatedUser\n });\n await ctx.context.internalAdapter.deleteSession(\n ctx.context.session.session.token\n );\n }\n await ctx.context.adapter.deleteMany({\n model: opts.twoFactorTable,\n where: [\n {\n field: \"userId\",\n value: user.id\n }\n ]\n });\n await ctx.context.adapter.create({\n model: opts.twoFactorTable,\n data: {\n secret: encryptedSecret,\n backupCodes: backupCodes.encryptedBackupCodes,\n userId: user.id\n }\n });\n const totpURI = createOTP(secret, {\n digits: options?.totpOptions?.digits || 6,\n period: options?.totpOptions?.period\n }).url(issuer || options?.issuer || ctx.context.appName, user.email);\n return ctx.json({ totpURI, backupCodes: backupCodes.backupCodes });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/two-factor/disable`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.disableTwoFactor`\n *\n * **client:**\n * `authClient.twoFactor.disable`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/2fa#api-method-two-factor-disable)\n */\n disableTwoFactor: createAuthEndpoint(\n \"/two-factor/disable\",\n {\n method: \"POST\",\n body: z.object({\n password: z.string().meta({\n description: \"User password\"\n })\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n summary: \"Disable two factor authentication\",\n description: \"Use this endpoint to disable two factor authentication.\",\n responses: {\n 200: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const user = ctx.context.session.user;\n const { password } = ctx.body;\n const isPasswordValid = await validatePassword(ctx, {\n password,\n userId: user.id\n });\n if (!isPasswordValid) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invalid password\"\n });\n }\n const updatedUser = await ctx.context.internalAdapter.updateUser(\n user.id,\n {\n twoFactorEnabled: false\n },\n ctx\n );\n await ctx.context.adapter.delete({\n model: opts.twoFactorTable,\n where: [\n {\n field: \"userId\",\n value: updatedUser.id\n }\n ]\n });\n const newSession = await ctx.context.internalAdapter.createSession(\n updatedUser.id,\n ctx,\n false,\n ctx.context.session.session\n );\n await setSessionCookie(ctx, {\n session: newSession,\n user: updatedUser\n });\n await ctx.context.internalAdapter.deleteSession(\n ctx.context.session.session.token\n );\n return ctx.json({ status: true });\n }\n )\n },\n options,\n hooks: {\n after: [\n {\n matcher(context) {\n return context.path === \"/sign-in/email\" || context.path === \"/sign-in/username\" || context.path === \"/sign-in/phone-number\";\n },\n handler: createAuthMiddleware(async (ctx) => {\n const data = ctx.context.newSession;\n if (!data) {\n return;\n }\n if (!data?.user.twoFactorEnabled) {\n return;\n }\n const trustDeviceCookieName = ctx.context.createAuthCookie(\n TRUST_DEVICE_COOKIE_NAME\n );\n const trustDeviceCookie = await ctx.getSignedCookie(\n trustDeviceCookieName.name,\n ctx.context.secret\n );\n if (trustDeviceCookie) {\n const [token, sessionToken] = trustDeviceCookie.split(\"!\");\n const expectedToken = await createHMAC(\n \"SHA-256\",\n \"base64urlnopad\"\n ).sign(ctx.context.secret, `${data.user.id}!${sessionToken}`);\n if (token === expectedToken) {\n const newToken = await createHMAC(\n \"SHA-256\",\n \"base64urlnopad\"\n ).sign(ctx.context.secret, `${data.user.id}!${sessionToken}`);\n await ctx.setSignedCookie(\n trustDeviceCookieName.name,\n `${newToken}!${data.session.token}`,\n ctx.context.secret,\n trustDeviceCookieName.attributes\n );\n return;\n }\n }\n deleteSessionCookie(ctx, true);\n await ctx.context.internalAdapter.deleteSession(data.session.token);\n const maxAge = (options?.otpOptions?.period ?? 3) * 60;\n const twoFactorCookie = ctx.context.createAuthCookie(\n TWO_FACTOR_COOKIE_NAME,\n {\n maxAge\n }\n );\n const identifier = `2fa-${generateRandomString(20)}`;\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: data.user.id,\n identifier,\n expiresAt: new Date(Date.now() + maxAge * 1e3)\n },\n ctx\n );\n await ctx.setSignedCookie(\n twoFactorCookie.name,\n identifier,\n ctx.context.secret,\n twoFactorCookie.attributes\n );\n return ctx.json({\n twoFactorRedirect: true\n });\n })\n }\n ]\n },\n schema: mergeSchema(schema, options?.schema),\n rateLimit: [\n {\n pathMatcher(path) {\n return path.startsWith(\"/two-factor/\");\n },\n window: 10,\n max: 3\n }\n ],\n $ERROR_CODES: TWO_FACTOR_ERROR_CODES\n };\n};\n\nexport { TWO_FACTOR_ERROR_CODES, twoFactor };\n","import * as z from 'zod/v4';\nimport { i as createAuthMiddleware, j as createAuthEndpoint, u as sendVerificationEmailFn, B as BASE_ERROR_CODES } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport { APIError } from 'better-call';\nimport { setSessionCookie } from '../../cookies/index.mjs';\nimport { m as mergeSchema } from '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-auth/utils/hash';\nimport '@better-auth/utils/base64';\nimport '../../crypto/index.mjs';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '@better-fetch/fetch';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'jose/errors';\n\nconst getSchema = (normalizer) => {\n return {\n user: {\n fields: {\n username: {\n type: \"string\",\n required: false,\n sortable: true,\n unique: true,\n returned: true\n },\n displayUsername: {\n type: \"string\",\n required: false,\n transform: {\n input(value) {\n return value == null ? value : normalizer(value);\n }\n }\n }\n }\n }\n };\n};\n\nconst USERNAME_ERROR_CODES = {\n INVALID_USERNAME_OR_PASSWORD: \"invalid username or password\",\n EMAIL_NOT_VERIFIED: \"email not verified\",\n UNEXPECTED_ERROR: \"unexpected error\",\n USERNAME_IS_ALREADY_TAKEN: \"username is already taken. please try another.\",\n USERNAME_TOO_SHORT: \"username is too short\",\n USERNAME_TOO_LONG: \"username is too long\",\n INVALID_USERNAME: \"username is invalid\"\n};\n\nfunction defaultUsernameValidator(username2) {\n return /^[a-zA-Z0-9_.]+$/.test(username2);\n}\nconst username = (options) => {\n const normalizer = (username2) => {\n if (options?.usernameNormalization === false) {\n return username2;\n }\n if (options?.usernameNormalization) {\n return options.usernameNormalization(username2);\n }\n return username2.toLowerCase();\n };\n return {\n id: \"username\",\n endpoints: {\n signInUsername: createAuthEndpoint(\n \"/sign-in/username\",\n {\n method: \"POST\",\n body: z.object({\n username: z.string().meta({ description: \"The username of the user\" }),\n password: z.string().meta({ description: \"The password of the user\" }),\n rememberMe: z.boolean().meta({\n description: \"Remember the user session\"\n }).optional(),\n callbackURL: z.string().meta({\n description: \"The URL to redirect to after email verification\"\n }).optional()\n }),\n metadata: {\n openapi: {\n summary: \"Sign in with username\",\n description: \"Sign in with username\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n token: {\n type: \"string\",\n description: \"Session token for the authenticated session\"\n },\n user: {\n $ref: \"#/components/schemas/User\"\n }\n },\n required: [\"token\", \"user\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.body.username || !ctx.body.password) {\n ctx.context.logger.error(\"Username or password not found\");\n throw new APIError(\"UNAUTHORIZED\", {\n message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD\n });\n }\n const minUsernameLength = options?.minUsernameLength || 3;\n const maxUsernameLength = options?.maxUsernameLength || 30;\n if (ctx.body.username.length < minUsernameLength) {\n ctx.context.logger.error(\"Username too short\", {\n username: ctx.body.username\n });\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: USERNAME_ERROR_CODES.USERNAME_TOO_SHORT\n });\n }\n if (ctx.body.username.length > maxUsernameLength) {\n ctx.context.logger.error(\"Username too long\", {\n username: ctx.body.username\n });\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: USERNAME_ERROR_CODES.USERNAME_TOO_LONG\n });\n }\n const validator = options?.usernameValidator || defaultUsernameValidator;\n if (!validator(ctx.body.username)) {\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: USERNAME_ERROR_CODES.INVALID_USERNAME\n });\n }\n const user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"username\",\n value: normalizer(ctx.body.username)\n }\n ]\n });\n if (!user) {\n await ctx.context.password.hash(ctx.body.password);\n ctx.context.logger.error(\"User not found\", {\n username: ctx.body.username\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD\n });\n }\n if (!user.emailVerified && ctx.context.options.emailAndPassword?.requireEmailVerification) {\n await sendVerificationEmailFn(ctx, user);\n throw new APIError(\"FORBIDDEN\", {\n message: USERNAME_ERROR_CODES.EMAIL_NOT_VERIFIED\n });\n }\n const account = await ctx.context.adapter.findOne({\n model: \"account\",\n where: [\n {\n field: \"userId\",\n value: user.id\n },\n {\n field: \"providerId\",\n value: \"credential\"\n }\n ]\n });\n if (!account) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD\n });\n }\n const currentPassword = account?.password;\n if (!currentPassword) {\n ctx.context.logger.error(\"Password not found\", {\n username: ctx.body.username\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD\n });\n }\n const validPassword = await ctx.context.password.verify({\n hash: currentPassword,\n password: ctx.body.password\n });\n if (!validPassword) {\n ctx.context.logger.error(\"Invalid password\");\n throw new APIError(\"UNAUTHORIZED\", {\n message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD\n });\n }\n const session = await ctx.context.internalAdapter.createSession(\n user.id,\n ctx,\n ctx.body.rememberMe === false\n );\n if (!session) {\n return ctx.json(null, {\n status: 500,\n body: {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION\n }\n });\n }\n await setSessionCookie(\n ctx,\n { session, user },\n ctx.body.rememberMe === false\n );\n return ctx.json({\n token: session.token,\n user: {\n id: user.id,\n email: user.email,\n emailVerified: user.emailVerified,\n username: user.username,\n name: user.name,\n image: user.image,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt\n }\n });\n }\n ),\n isUsernameAvailable: createAuthEndpoint(\n \"/is-username-available\",\n {\n method: \"POST\",\n body: z.object({\n username: z.string().meta({\n description: \"The username to check\"\n })\n })\n },\n async (ctx) => {\n const username2 = ctx.body.username;\n if (!username2) {\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: USERNAME_ERROR_CODES.INVALID_USERNAME\n });\n }\n const user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"username\",\n value: username2.toLowerCase()\n }\n ]\n });\n if (user) {\n return ctx.json({\n available: false\n });\n }\n return ctx.json({\n available: true\n });\n }\n )\n },\n schema: mergeSchema(getSchema(normalizer), options?.schema),\n hooks: {\n before: [\n {\n matcher(context) {\n return context.path === \"/sign-up/email\" || context.path === \"/update-user\";\n },\n handler: createAuthMiddleware(async (ctx) => {\n const username2 = ctx.body.username;\n if (username2 !== void 0 && typeof username2 === \"string\") {\n const minUsernameLength = options?.minUsernameLength || 3;\n const maxUsernameLength = options?.maxUsernameLength || 30;\n if (username2.length < minUsernameLength) {\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: USERNAME_ERROR_CODES.USERNAME_TOO_SHORT\n });\n }\n if (username2.length > maxUsernameLength) {\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: USERNAME_ERROR_CODES.USERNAME_TOO_LONG\n });\n }\n const validator = options?.usernameValidator || defaultUsernameValidator;\n const valid = await validator(username2);\n if (!valid) {\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: USERNAME_ERROR_CODES.INVALID_USERNAME\n });\n }\n const user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"username\",\n value: normalizer(username2)\n }\n ]\n });\n const blockChangeSignUp = ctx.path === \"/sign-up/email\" && user;\n const blockChangeUpdateUser = ctx.path === \"/update-user\" && user && ctx.context.session && user.id !== ctx.context.session.session.userId;\n if (blockChangeSignUp || blockChangeUpdateUser) {\n throw new APIError(\"UNPROCESSABLE_ENTITY\", {\n message: USERNAME_ERROR_CODES.USERNAME_IS_ALREADY_TAKEN\n });\n }\n }\n })\n },\n {\n matcher(context) {\n return context.path === \"/sign-up/email\" || context.path === \"/update-user\";\n },\n handler: createAuthMiddleware(async (ctx) => {\n if (ctx.body.username) {\n ctx.body.displayUsername ||= ctx.body.username;\n ctx.body.username = normalizer(ctx.body.username);\n }\n })\n }\n ]\n },\n $ERROR_CODES: USERNAME_ERROR_CODES\n };\n};\n\nexport { USERNAME_ERROR_CODES, username };\n","import { serializeSignedCookie } from 'better-call';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '@better-auth/utils/base64';\nimport { createHMAC } from '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport { parseSetCookieHeader } from '../../cookies/index.mjs';\nimport { i as createAuthMiddleware } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport 'zod/v4';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '@better-auth/utils/hash';\nimport '../../crypto/index.mjs';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '@better-fetch/fetch';\nimport 'jose/errors';\n\nconst bearer = (options) => {\n return {\n id: \"bearer\",\n hooks: {\n before: [\n {\n matcher(context) {\n return Boolean(\n context.request?.headers.get(\"authorization\") || context.headers?.get(\"authorization\")\n );\n },\n handler: createAuthMiddleware(async (c) => {\n const token = c.request?.headers.get(\"authorization\")?.replace(\"Bearer \", \"\") || c.headers?.get(\"Authorization\")?.replace(\"Bearer \", \"\");\n if (!token) {\n return;\n }\n let signedToken = \"\";\n if (token.includes(\".\")) {\n signedToken = token.replace(\"=\", \"\");\n } else {\n if (options?.requireSignature) {\n return;\n }\n signedToken = (await serializeSignedCookie(\"\", token, c.context.secret)).replace(\"=\", \"\");\n }\n try {\n const decodedToken = decodeURIComponent(signedToken);\n const isValid = await createHMAC(\n \"SHA-256\",\n \"base64urlnopad\"\n ).verify(\n c.context.secret,\n decodedToken.split(\".\")[0],\n decodedToken.split(\".\")[1]\n );\n if (!isValid) {\n return;\n }\n } catch (e) {\n return;\n }\n const existingHeaders = c.request?.headers || c.headers;\n const headers = new Headers({\n ...Object.fromEntries(existingHeaders?.entries())\n });\n headers.append(\n \"cookie\",\n `${c.context.authCookies.sessionToken.name}=${signedToken}`\n );\n return {\n context: {\n headers\n }\n };\n })\n }\n ],\n after: [\n {\n matcher(context) {\n return true;\n },\n handler: createAuthMiddleware(async (ctx) => {\n const setCookie = ctx.context.responseHeaders?.get(\"set-cookie\");\n if (!setCookie) {\n return;\n }\n const parsedCookies = parseSetCookieHeader(setCookie);\n const cookieName = ctx.context.authCookies.sessionToken.name;\n const sessionCookie = parsedCookies.get(cookieName);\n if (!sessionCookie || !sessionCookie.value || sessionCookie[\"max-age\"] === 0) {\n return;\n }\n const token = sessionCookie.value;\n const exposedHeaders = ctx.context.responseHeaders?.get(\n \"access-control-expose-headers\"\n ) || \"\";\n const headersSet = new Set(\n exposedHeaders.split(\",\").map((header) => header.trim()).filter(Boolean)\n );\n headersSet.add(\"set-auth-token\");\n ctx.setHeader(\"set-auth-token\", token);\n ctx.setHeader(\n \"Access-Control-Expose-Headers\",\n Array.from(headersSet).join(\", \")\n );\n })\n }\n ]\n }\n };\n};\n\nexport { bearer };\n","import * as z from 'zod/v4';\nimport { j as createAuthEndpoint, o as originCheck, B as BASE_ERROR_CODES } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport { APIError } from 'better-call';\nimport { setSessionCookie } from '../../cookies/index.mjs';\nimport { createHash } from '@better-auth/utils/hash';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport { base64Url } from '@better-auth/utils/base64';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport { g as generateRandomString } from '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '../../crypto/index.mjs';\nimport '@better-fetch/fetch';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'jose/errors';\nimport '@better-auth/utils/random';\n\nconst defaultKeyHasher = async (otp) => {\n const hash = await createHash(\"SHA-256\").digest(\n new TextEncoder().encode(otp)\n );\n const hashed = base64Url.encode(new Uint8Array(hash), {\n padding: false\n });\n return hashed;\n};\n\nconst magicLink = (options) => {\n const opts = {\n storeToken: \"plain\",\n ...options\n };\n async function storeToken(ctx, token) {\n if (opts.storeToken === \"hashed\") {\n return await defaultKeyHasher(token);\n }\n if (typeof opts.storeToken === \"object\" && \"type\" in opts.storeToken && opts.storeToken.type === \"custom-hasher\") {\n return await opts.storeToken.hash(token);\n }\n return token;\n }\n return {\n id: \"magic-link\",\n endpoints: {\n /**\n * ### Endpoint\n *\n * POST `/sign-in/magic-link`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.signInMagicLink`\n *\n * **client:**\n * `authClient.signIn.magicLink`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/sign-in#api-method-sign-in-magic-link)\n */\n signInMagicLink: createAuthEndpoint(\n \"/sign-in/magic-link\",\n {\n method: \"POST\",\n requireHeaders: true,\n body: z.object({\n email: z.string().meta({\n description: \"Email address to send the magic link\"\n }).email(),\n name: z.string().meta({\n description: 'User display name. Only used if the user is registering for the first time. Eg: \"my-name\"'\n }).optional(),\n callbackURL: z.string().meta({\n description: \"URL to redirect after magic link verification\"\n }).optional(),\n newUserCallbackURL: z.string().meta({\n description: \"URL to redirect after new user signup. Only used if the user is registering for the first time.\"\n }).optional(),\n errorCallbackURL: z.string().meta({\n description: \"URL to redirect after error.\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Sign in with magic link\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { email } = ctx.body;\n if (opts.disableSignUp) {\n const user = await ctx.context.internalAdapter.findUserByEmail(email);\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: BASE_ERROR_CODES.USER_NOT_FOUND\n });\n }\n }\n const verificationToken = opts?.generateToken ? await opts.generateToken(email) : generateRandomString(32, \"a-z\", \"A-Z\");\n const storedToken = await storeToken(ctx, verificationToken);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n identifier: storedToken,\n value: JSON.stringify({ email, name: ctx.body.name }),\n expiresAt: new Date(\n Date.now() + (opts.expiresIn || 60 * 5) * 1e3\n )\n },\n ctx\n );\n const realBaseURL = new URL(ctx.context.baseURL);\n const url = new URL(\n `${realBaseURL.pathname}/magic-link/verify`,\n realBaseURL.origin\n );\n url.searchParams.set(\"token\", verificationToken);\n url.searchParams.set(\"callbackURL\", ctx.body.callbackURL || \"/\");\n if (ctx.body.newUserCallbackURL) {\n url.searchParams.set(\n \"newUserCallbackURL\",\n ctx.body.newUserCallbackURL\n );\n }\n if (ctx.body.errorCallbackURL) {\n url.searchParams.set(\"errorCallbackURL\", ctx.body.errorCallbackURL);\n }\n await options.sendMagicLink(\n {\n email,\n url: url.toString(),\n token: verificationToken\n },\n ctx.request\n );\n return ctx.json({\n status: true\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * GET `/magic-link/verify`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.magicLinkVerify`\n *\n * **client:**\n * `authClient.magicLink.verify`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/magic-link#api-method-magic-link-verify)\n */\n magicLinkVerify: createAuthEndpoint(\n \"/magic-link/verify\",\n {\n method: \"GET\",\n query: z.object({\n token: z.string().meta({\n description: \"Verification token\"\n }),\n callbackURL: z.string().meta({\n description: 'URL to redirect after magic link verification, if not provided the user will be redirected to the root URL. Eg: \"/dashboard\"'\n }).optional(),\n errorCallbackURL: z.string().meta({\n description: \"URL to redirect after error.\"\n }).optional(),\n newUserCallbackURL: z.string().meta({\n description: \"URL to redirect after new user signup. Only used if the user is registering for the first time.\"\n }).optional()\n }),\n use: [\n originCheck((ctx) => {\n return ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : \"/\";\n }),\n originCheck((ctx) => {\n return ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : \"/\";\n }),\n originCheck((ctx) => {\n return ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : \"/\";\n })\n ],\n requireHeaders: true,\n metadata: {\n openapi: {\n description: \"Verify magic link\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n session: {\n $ref: \"#/components/schemas/Session\"\n },\n user: {\n $ref: \"#/components/schemas/User\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const token = ctx.query.token;\n const callbackURL = new URL(\n ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : \"/\",\n ctx.context.baseURL\n ).toString();\n const errorCallbackURL = new URL(\n ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : callbackURL,\n ctx.context.baseURL\n ).toString();\n const newUserCallbackURL = new URL(\n ctx.query.newUserCallbackURL ? decodeURIComponent(ctx.query.newUserCallbackURL) : callbackURL,\n ctx.context.baseURL\n ).toString();\n callbackURL?.startsWith(\"http\") ? callbackURL : callbackURL ? `${ctx.context.options.baseURL}${callbackURL}` : ctx.context.options.baseURL;\n const storedToken = await storeToken(ctx, token);\n const tokenValue = await ctx.context.internalAdapter.findVerificationValue(\n storedToken\n );\n if (!tokenValue) {\n throw ctx.redirect(`${errorCallbackURL}?error=INVALID_TOKEN`);\n }\n if (tokenValue.expiresAt < /* @__PURE__ */ new Date()) {\n await ctx.context.internalAdapter.deleteVerificationValue(\n tokenValue.id\n );\n throw ctx.redirect(`${errorCallbackURL}?error=EXPIRED_TOKEN`);\n }\n await ctx.context.internalAdapter.deleteVerificationValue(\n tokenValue.id\n );\n const { email, name } = JSON.parse(tokenValue.value);\n let isNewUser = false;\n let user = await ctx.context.internalAdapter.findUserByEmail(email).then((res) => res?.user);\n if (!user) {\n if (!opts.disableSignUp) {\n const newUser = await ctx.context.internalAdapter.createUser(\n {\n email,\n emailVerified: true,\n name: name || \"\"\n },\n ctx\n );\n isNewUser = true;\n user = newUser;\n if (!user) {\n throw ctx.redirect(\n `${errorCallbackURL}?error=failed_to_create_user`\n );\n }\n } else {\n throw ctx.redirect(\n `${errorCallbackURL}?error=new_user_signup_disabled`\n );\n }\n }\n if (!user.emailVerified) {\n await ctx.context.internalAdapter.updateUser(\n user.id,\n {\n emailVerified: true\n },\n ctx\n );\n }\n const session = await ctx.context.internalAdapter.createSession(\n user.id,\n ctx\n );\n if (!session) {\n throw ctx.redirect(\n `${errorCallbackURL}?error=failed_to_create_session`\n );\n }\n await setSessionCookie(ctx, {\n session,\n user\n });\n if (!ctx.query.callbackURL) {\n return ctx.json({\n token: session.token,\n user: {\n id: user.id,\n email: user.email,\n emailVerified: user.emailVerified,\n name: user.name,\n image: user.image,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt\n }\n });\n }\n if (isNewUser) {\n throw ctx.redirect(newUserCallbackURL);\n }\n throw ctx.redirect(callbackURL);\n }\n )\n },\n rateLimit: [\n {\n pathMatcher(path) {\n return path.startsWith(\"/sign-in/magic-link\") || path.startsWith(\"/magic-link/verify\");\n },\n window: opts.rateLimit?.window || 60,\n max: opts.rateLimit?.max || 5\n }\n ]\n };\n};\n\nexport { magicLink };\n","import * as z from 'zod/v4';\nimport { j as createAuthEndpoint, k as getSessionFromCtx, B as BASE_ERROR_CODES } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport { APIError } from 'better-call';\nimport { m as mergeSchema } from '../../shared/better-auth.n2KFGwjY.mjs';\nimport { g as generateRandomString } from '../../shared/better-auth.B4Qoxdgc.mjs';\nimport { setSessionCookie } from '../../cookies/index.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { g as getDate } from '../../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-auth/utils/hash';\nimport '@better-auth/utils/base64';\nimport '../../crypto/index.mjs';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '@better-fetch/fetch';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'jose/errors';\nimport '@better-auth/utils/random';\n\nconst ERROR_CODES = {\n INVALID_PHONE_NUMBER: \"Invalid phone number\",\n PHONE_NUMBER_EXIST: \"Phone number already exists\",\n INVALID_PHONE_NUMBER_OR_PASSWORD: \"Invalid phone number or password\",\n UNEXPECTED_ERROR: \"Unexpected error\",\n OTP_NOT_FOUND: \"OTP not found\",\n OTP_EXPIRED: \"OTP expired\",\n INVALID_OTP: \"Invalid OTP\",\n PHONE_NUMBER_NOT_VERIFIED: \"Phone number not verified\"\n};\n\nfunction generateOTP(size) {\n return generateRandomString(size, \"0-9\");\n}\nconst phoneNumber = (options) => {\n const opts = {\n expiresIn: options?.expiresIn || 300,\n otpLength: options?.otpLength || 6,\n ...options,\n phoneNumber: \"phoneNumber\",\n phoneNumberVerified: \"phoneNumberVerified\",\n code: \"code\",\n createdAt: \"createdAt\"\n };\n return {\n id: \"phone-number\",\n endpoints: {\n /**\n * ### Endpoint\n *\n * POST `/sign-in/phone-number`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.signInPhoneNumber`\n *\n * **client:**\n * `authClient.signIn.phoneNumber`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/phone-number#api-method-sign-in-phone-number)\n */\n signInPhoneNumber: createAuthEndpoint(\n \"/sign-in/phone-number\",\n {\n method: \"POST\",\n body: z.object({\n phoneNumber: z.string().meta({\n description: 'Phone number to sign in. Eg: \"+1234567890\"'\n }),\n password: z.string().meta({\n description: \"Password to use for sign in.\"\n }),\n rememberMe: z.boolean().meta({\n description: \"Remember the session. Eg: true\"\n }).optional()\n }),\n metadata: {\n openapi: {\n summary: \"Sign in with phone number\",\n description: \"Use this endpoint to sign in with phone number\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n $ref: \"#/components/schemas/User\"\n },\n session: {\n $ref: \"#/components/schemas/Session\"\n }\n }\n }\n }\n }\n },\n 400: {\n description: \"Invalid phone number or password\"\n }\n }\n }\n }\n },\n async (ctx) => {\n const { password, phoneNumber: phoneNumber2 } = ctx.body;\n if (opts.phoneNumberValidator) {\n const isValidNumber = await opts.phoneNumberValidator(\n ctx.body.phoneNumber\n );\n if (!isValidNumber) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_PHONE_NUMBER\n });\n }\n }\n const user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"phoneNumber\",\n value: phoneNumber2\n }\n ]\n });\n if (!user) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.INVALID_PHONE_NUMBER_OR_PASSWORD\n });\n }\n if (opts.requireVerification) {\n if (!user.phoneNumberVerified) {\n const otp = generateOTP(opts.otpLength);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: otp,\n identifier: phoneNumber2,\n expiresAt: getDate(opts.expiresIn, \"sec\")\n },\n ctx\n );\n await opts.sendOTP?.(\n {\n phoneNumber: phoneNumber2,\n code: otp\n },\n ctx.request\n );\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.PHONE_NUMBER_NOT_VERIFIED\n });\n }\n }\n const accounts = await ctx.context.internalAdapter.findAccountByUserId(user.id);\n const credentialAccount = accounts.find(\n (a) => a.providerId === \"credential\"\n );\n if (!credentialAccount) {\n ctx.context.logger.error(\"Credential account not found\", {\n phoneNumber: phoneNumber2\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.INVALID_PHONE_NUMBER_OR_PASSWORD\n });\n }\n const currentPassword = credentialAccount?.password;\n if (!currentPassword) {\n ctx.context.logger.error(\"Password not found\", { phoneNumber: phoneNumber2 });\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.UNEXPECTED_ERROR\n });\n }\n const validPassword = await ctx.context.password.verify({\n hash: currentPassword,\n password\n });\n if (!validPassword) {\n ctx.context.logger.error(\"Invalid password\");\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.INVALID_PHONE_NUMBER_OR_PASSWORD\n });\n }\n const session = await ctx.context.internalAdapter.createSession(\n user.id,\n ctx,\n ctx.body.rememberMe === false\n );\n if (!session) {\n ctx.context.logger.error(\"Failed to create session\");\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION\n });\n }\n await setSessionCookie(\n ctx,\n {\n session,\n user\n },\n ctx.body.rememberMe === false\n );\n return ctx.json({\n token: session.token,\n user: {\n id: user.id,\n email: user.email,\n emailVerified: user.emailVerified,\n name: user.name,\n image: user.image,\n phoneNumber: user.phoneNumber,\n phoneNumberVerified: user.phoneNumberVerified,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt\n }\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/phone-number/send-otp`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.sendPhoneNumberOTP`\n *\n * **client:**\n * `authClient.phoneNumber.sendOtp`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/phone-number#api-method-phone-number-send-otp)\n */\n sendPhoneNumberOTP: createAuthEndpoint(\n \"/phone-number/send-otp\",\n {\n method: \"POST\",\n body: z.object({\n phoneNumber: z.string().meta({\n description: 'Phone number to send OTP. Eg: \"+1234567890\"'\n })\n }),\n metadata: {\n openapi: {\n summary: \"Send OTP to phone number\",\n description: \"Use this endpoint to send OTP to phone number\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!options?.sendOTP) {\n ctx.context.logger.warn(\"sendOTP not implemented\");\n throw new APIError(\"NOT_IMPLEMENTED\", {\n message: \"sendOTP not implemented\"\n });\n }\n if (opts.phoneNumberValidator) {\n const isValidNumber = await opts.phoneNumberValidator(\n ctx.body.phoneNumber\n );\n if (!isValidNumber) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_PHONE_NUMBER\n });\n }\n }\n const code = generateOTP(opts.otpLength);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: `${code}:0`,\n identifier: ctx.body.phoneNumber,\n expiresAt: getDate(opts.expiresIn, \"sec\")\n },\n ctx\n );\n await options.sendOTP(\n {\n phoneNumber: ctx.body.phoneNumber,\n code\n },\n ctx.request\n );\n return ctx.json({ message: \"code sent\" });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/phone-number/verify`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.verifyPhoneNumber`\n *\n * **client:**\n * `authClient.phoneNumber.verify`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/phone-number#api-method-phone-number-verify)\n */\n verifyPhoneNumber: createAuthEndpoint(\n \"/phone-number/verify\",\n {\n method: \"POST\",\n body: z.object({\n /**\n * Phone number\n */\n phoneNumber: z.string().meta({\n description: 'Phone number to verify. Eg: \"+1234567890\"'\n }),\n /**\n * OTP code\n */\n code: z.string().meta({\n description: 'OTP code. Eg: \"123456\"'\n }),\n /**\n * Disable session creation after verification\n * @default false\n */\n disableSession: z.boolean().meta({\n description: \"Disable session creation after verification. Eg: false\"\n }).optional(),\n /**\n * This checks if there is a session already\n * and updates the phone number with the provided\n * phone number\n */\n updatePhoneNumber: z.boolean().meta({\n description: \"Check if there is a session and update the phone number. Eg: true\"\n }).optional()\n }),\n metadata: {\n openapi: {\n summary: \"Verify phone number\",\n description: \"Use this endpoint to verify phone number\",\n responses: {\n \"200\": {\n description: \"Phone number verified successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the verification was successful\",\n enum: [true]\n },\n token: {\n type: \"string\",\n nullable: true,\n description: \"Session token if session is created, null if disableSession is true or no session is created\"\n },\n user: {\n type: \"object\",\n nullable: true,\n properties: {\n id: {\n type: \"string\",\n description: \"Unique identifier of the user\"\n },\n email: {\n type: \"string\",\n format: \"email\",\n nullable: true,\n description: \"User's email address\"\n },\n emailVerified: {\n type: \"boolean\",\n nullable: true,\n description: \"Whether the email is verified\"\n },\n name: {\n type: \"string\",\n nullable: true,\n description: \"User's name\"\n },\n image: {\n type: \"string\",\n format: \"uri\",\n nullable: true,\n description: \"User's profile image URL\"\n },\n phoneNumber: {\n type: \"string\",\n description: \"User's phone number\"\n },\n phoneNumberVerified: {\n type: \"boolean\",\n description: \"Whether the phone number is verified\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the user was created\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Timestamp when the user was last updated\"\n }\n },\n required: [\n \"id\",\n \"phoneNumber\",\n \"phoneNumberVerified\",\n \"createdAt\",\n \"updatedAt\"\n ],\n description: \"User object with phone number details, null if no user is created or found\"\n }\n },\n required: [\"status\"]\n }\n }\n }\n },\n 400: {\n description: \"Invalid OTP\"\n }\n }\n }\n }\n },\n async (ctx) => {\n const otp = await ctx.context.internalAdapter.findVerificationValue(\n ctx.body.phoneNumber\n );\n if (!otp || otp.expiresAt < /* @__PURE__ */ new Date()) {\n if (otp && otp.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"OTP expired\"\n });\n }\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.OTP_NOT_FOUND\n });\n }\n const [otpValue, attempts] = otp.value.split(\":\");\n const allowedAttempts = options?.allowedAttempts || 3;\n if (attempts && parseInt(attempts) >= allowedAttempts) {\n await ctx.context.internalAdapter.deleteVerificationValue(otp.id);\n throw new APIError(\"FORBIDDEN\", {\n message: \"Too many attempts\"\n });\n }\n if (otpValue !== ctx.body.code) {\n await ctx.context.internalAdapter.updateVerificationValue(otp.id, {\n value: `${otpValue}:${parseInt(attempts || \"0\") + 1}`\n });\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invalid OTP\"\n });\n }\n await ctx.context.internalAdapter.deleteVerificationValue(otp.id);\n if (ctx.body.updatePhoneNumber) {\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: BASE_ERROR_CODES.USER_NOT_FOUND\n });\n }\n const existingUser = await ctx.context.adapter.findMany({\n model: \"user\",\n where: [\n {\n field: \"phoneNumber\",\n value: ctx.body.phoneNumber\n }\n ]\n });\n if (existingUser.length) {\n throw ctx.error(\"BAD_REQUEST\", {\n message: ERROR_CODES.PHONE_NUMBER_EXIST\n });\n }\n let user2 = await ctx.context.internalAdapter.updateUser(\n session.user.id,\n {\n [opts.phoneNumber]: ctx.body.phoneNumber,\n [opts.phoneNumberVerified]: true\n },\n ctx\n );\n return ctx.json({\n status: true,\n token: session.session.token,\n user: {\n id: user2.id,\n email: user2.email,\n emailVerified: user2.emailVerified,\n name: user2.name,\n image: user2.image,\n phoneNumber: user2.phoneNumber,\n phoneNumberVerified: user2.phoneNumberVerified,\n createdAt: user2.createdAt,\n updatedAt: user2.updatedAt\n }\n });\n }\n let user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n value: ctx.body.phoneNumber,\n field: opts.phoneNumber\n }\n ]\n });\n if (!user) {\n if (options?.signUpOnVerification) {\n user = await ctx.context.internalAdapter.createUser(\n {\n email: options.signUpOnVerification.getTempEmail(\n ctx.body.phoneNumber\n ),\n name: options.signUpOnVerification.getTempName ? options.signUpOnVerification.getTempName(\n ctx.body.phoneNumber\n ) : ctx.body.phoneNumber,\n [opts.phoneNumber]: ctx.body.phoneNumber,\n [opts.phoneNumberVerified]: true\n },\n ctx\n );\n if (!user) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER\n });\n }\n }\n } else {\n user = await ctx.context.internalAdapter.updateUser(\n user.id,\n {\n [opts.phoneNumberVerified]: true\n },\n ctx\n );\n }\n if (!user) {\n return ctx.json(null);\n }\n await options?.callbackOnVerification?.(\n {\n phoneNumber: ctx.body.phoneNumber,\n user\n },\n ctx.request\n );\n if (!user) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: BASE_ERROR_CODES.FAILED_TO_UPDATE_USER\n });\n }\n if (!ctx.body.disableSession) {\n const session = await ctx.context.internalAdapter.createSession(\n user.id,\n ctx\n );\n if (!session) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION\n });\n }\n await setSessionCookie(ctx, {\n session,\n user\n });\n return ctx.json({\n status: true,\n token: session.token,\n user: {\n id: user.id,\n email: user.email,\n emailVerified: user.emailVerified,\n name: user.name,\n image: user.image,\n phoneNumber: user.phoneNumber,\n phoneNumberVerified: user.phoneNumberVerified,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt\n }\n });\n }\n return ctx.json({\n status: true,\n token: null,\n user: {\n id: user.id,\n email: user.email,\n emailVerified: user.emailVerified,\n name: user.name,\n image: user.image,\n phoneNumber: user.phoneNumber,\n phoneNumberVerified: user.phoneNumberVerified,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt\n }\n });\n }\n ),\n /**\n * @deprecated Use requestPasswordResetPhoneNumber instead. This endpoint will be removed in the next major version.\n */\n forgetPasswordPhoneNumber: createAuthEndpoint(\n \"/phone-number/forget-password\",\n {\n method: \"POST\",\n body: z.object({\n phoneNumber: z.string().meta({\n description: `The phone number which is associated with the user. Eg: \"+1234567890\"`\n })\n }),\n metadata: {\n openapi: {\n description: \"Request OTP for password reset via phone number\",\n responses: {\n \"200\": {\n description: \"OTP sent successfully for password reset\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the OTP was sent successfully\",\n enum: [true]\n }\n },\n required: [\"status\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n value: ctx.body.phoneNumber,\n field: opts.phoneNumber\n }\n ]\n });\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"phone number isn't registered\"\n });\n }\n const code = generateOTP(opts.otpLength);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: `${code}:0`,\n identifier: `${ctx.body.phoneNumber}-request-password-reset`,\n expiresAt: getDate(opts.expiresIn, \"sec\")\n },\n ctx\n );\n await options?.sendForgetPasswordOTP?.(\n {\n phoneNumber: ctx.body.phoneNumber,\n code\n },\n ctx.request\n );\n return ctx.json({\n status: true\n });\n }\n ),\n requestPasswordResetPhoneNumber: createAuthEndpoint(\n \"/phone-number/request-password-reset\",\n {\n method: \"POST\",\n body: z.object({\n phoneNumber: z.string()\n }),\n metadata: {\n openapi: {\n description: \"Request OTP for password reset via phone number\",\n responses: {\n \"200\": {\n description: \"OTP sent successfully for password reset\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the OTP was sent successfully\",\n enum: [true]\n }\n },\n required: [\"status\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n value: ctx.body.phoneNumber,\n field: opts.phoneNumber\n }\n ]\n });\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"phone number isn't registered\"\n });\n }\n const code = generateOTP(opts.otpLength);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: `${code}:0`,\n identifier: `${ctx.body.phoneNumber}-request-password-reset`,\n expiresAt: getDate(opts.expiresIn, \"sec\")\n },\n ctx\n );\n await options?.sendPasswordResetOTP?.(\n {\n phoneNumber: ctx.body.phoneNumber,\n code\n },\n ctx.request\n );\n return ctx.json({\n status: true\n });\n }\n ),\n resetPasswordPhoneNumber: createAuthEndpoint(\n \"/phone-number/reset-password\",\n {\n method: \"POST\",\n body: z.object({\n otp: z.string().meta({\n description: 'The one time password to reset the password. Eg: \"123456\"'\n }),\n phoneNumber: z.string().meta({\n description: 'The phone number to the account which intends to reset the password for. Eg: \"+1234567890\"'\n }),\n newPassword: z.string().meta({\n description: `The new password. Eg: \"new-and-secure-password\"`\n })\n }),\n metadata: {\n openapi: {\n description: \"Reset password using phone number OTP\",\n responses: {\n \"200\": {\n description: \"Password reset successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the password was reset successfully\",\n enum: [true]\n }\n },\n required: [\"status\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const verification = await ctx.context.internalAdapter.findVerificationValue(\n `${ctx.body.phoneNumber}-request-password-reset`\n );\n if (!verification) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.OTP_NOT_FOUND\n });\n }\n if (verification.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.OTP_EXPIRED\n });\n }\n const [otpValue, attempts] = verification.value.split(\":\");\n const allowedAttempts = options?.allowedAttempts || 3;\n if (attempts && parseInt(attempts) >= allowedAttempts) {\n await ctx.context.internalAdapter.deleteVerificationValue(\n verification.id\n );\n throw new APIError(\"FORBIDDEN\", {\n message: \"Too many attempts\"\n });\n }\n if (ctx.body.otp !== otpValue) {\n await ctx.context.internalAdapter.updateVerificationValue(\n verification.id,\n {\n value: `${otpValue}:${parseInt(attempts || \"0\") + 1}`\n }\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OTP\n });\n }\n const user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"phoneNumber\",\n value: ctx.body.phoneNumber\n }\n ]\n });\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.UNEXPECTED_ERROR\n });\n }\n const hashedPassword = await ctx.context.password.hash(\n ctx.body.newPassword\n );\n await ctx.context.internalAdapter.updatePassword(\n user.id,\n hashedPassword\n );\n await ctx.context.internalAdapter.deleteVerificationValue(\n verification.id\n );\n return ctx.json({\n status: true\n });\n }\n )\n },\n schema: mergeSchema(schema, options?.schema),\n rateLimit: [\n {\n pathMatcher(path) {\n return path.startsWith(\"/phone-number\");\n },\n window: 60 * 1e3,\n max: 10\n }\n ],\n $ERROR_CODES: ERROR_CODES\n };\n};\nconst schema = {\n user: {\n fields: {\n phoneNumber: {\n type: \"string\",\n required: false,\n unique: true,\n sortable: true,\n returned: true\n },\n phoneNumberVerified: {\n type: \"boolean\",\n required: false,\n returned: true,\n input: false\n }\n }\n }\n};\n\nexport { phoneNumber };\n","import { APIError } from 'better-call';\nimport { i as createAuthMiddleware, j as createAuthEndpoint, k as getSessionFromCtx } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport 'zod/v4';\nimport { parseSetCookieHeader, setSessionCookie } from '../../cookies/index.mjs';\nimport { m as mergeSchema } from '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { g as getOrigin } from '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-auth/utils/hash';\nimport '@better-auth/utils/base64';\nimport '../../crypto/index.mjs';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '@better-fetch/fetch';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'jose/errors';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\n\nconst schema = {\n user: {\n fields: {\n isAnonymous: {\n type: \"boolean\",\n required: false\n }\n }\n }\n};\nconst anonymous = (options) => {\n const ERROR_CODES = {\n FAILED_TO_CREATE_USER: \"Failed to create user\",\n COULD_NOT_CREATE_SESSION: \"Could not create session\",\n ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY: \"Anonymous users cannot sign in again anonymously\"\n };\n return {\n id: \"anonymous\",\n endpoints: {\n signInAnonymous: createAuthEndpoint(\n \"/sign-in/anonymous\",\n {\n method: \"POST\",\n metadata: {\n openapi: {\n description: \"Sign in anonymously\",\n responses: {\n 200: {\n description: \"Sign in anonymously\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n $ref: \"#/components/schemas/User\"\n },\n session: {\n $ref: \"#/components/schemas/Session\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { emailDomainName = getOrigin(ctx.context.baseURL) } = options || {};\n const id = ctx.context.generateId({ model: \"user\" });\n const email = `temp-${id}@${emailDomainName}`;\n const name = await options?.generateName?.(ctx) || \"Anonymous\";\n const newUser = await ctx.context.internalAdapter.createUser(\n {\n email,\n emailVerified: false,\n isAnonymous: true,\n name,\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date()\n },\n ctx\n );\n if (!newUser) {\n throw ctx.error(\"INTERNAL_SERVER_ERROR\", {\n message: ERROR_CODES.FAILED_TO_CREATE_USER\n });\n }\n const session = await ctx.context.internalAdapter.createSession(\n newUser.id,\n ctx\n );\n if (!session) {\n return ctx.json(null, {\n status: 400,\n body: {\n message: ERROR_CODES.COULD_NOT_CREATE_SESSION\n }\n });\n }\n await setSessionCookie(ctx, {\n session,\n user: newUser\n });\n return ctx.json({\n token: session.token,\n user: {\n id: newUser.id,\n email: newUser.email,\n emailVerified: newUser.emailVerified,\n name: newUser.name,\n createdAt: newUser.createdAt,\n updatedAt: newUser.updatedAt\n }\n });\n }\n )\n },\n hooks: {\n after: [\n {\n matcher(ctx) {\n return ctx.path.startsWith(\"/sign-in\") || ctx.path.startsWith(\"/sign-up\") || ctx.path.startsWith(\"/callback\") || ctx.path.startsWith(\"/oauth2/callback\") || ctx.path.startsWith(\"/magic-link/verify\") || ctx.path.startsWith(\"/email-otp/verify-email\") || ctx.path.startsWith(\"/one-tap/callback\") || ctx.path.startsWith(\"/passkey/verify-authentication\");\n },\n handler: createAuthMiddleware(async (ctx) => {\n const setCookie = ctx.context.responseHeaders?.get(\"set-cookie\");\n const sessionTokenName = ctx.context.authCookies.sessionToken.name;\n const sessionCookie = parseSetCookieHeader(setCookie || \"\").get(sessionTokenName)?.value.split(\".\")[0];\n if (!sessionCookie) {\n return;\n }\n const session = await getSessionFromCtx(\n ctx,\n {\n disableRefresh: true\n }\n );\n if (!session || !session.user.isAnonymous) {\n return;\n }\n if (ctx.path === \"/sign-in/anonymous\") {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY\n });\n }\n const newSession = ctx.context.newSession;\n if (!newSession) {\n return;\n }\n if (options?.onLinkAccount) {\n await options?.onLinkAccount?.({\n anonymousUser: session,\n newUser: newSession\n });\n }\n if (!options?.disableDeleteAnonymousUser) {\n await ctx.context.internalAdapter.deleteUser(session.user.id);\n }\n })\n }\n ]\n },\n schema: mergeSchema(schema, options?.schema),\n $ERROR_CODES: ERROR_CODES\n };\n};\n\nexport { anonymous };\n","import * as z from 'zod/v4';\nimport { APIError } from 'better-call';\nimport { i as createAuthMiddleware, k as getSessionFromCtx, j as createAuthEndpoint } from './better-auth.D4HhkCZJ.mjs';\nimport { setSessionCookie, deleteSessionCookie } from '../cookies/index.mjs';\nimport { m as mergeSchema } from './better-auth.n2KFGwjY.mjs';\nimport './better-auth.8zoxzg-F.mjs';\nimport './better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { g as getDate } from './better-auth.CW6D9eSx.mjs';\nimport { g as getEndpointResponse } from './better-auth.DQI8AD7d.mjs';\nimport { h as hasPermission } from './better-auth.bkwPl2G4.mjs';\n\nconst ADMIN_ERROR_CODES = {\n FAILED_TO_CREATE_USER: \"Failed to create user\",\n USER_ALREADY_EXISTS: \"User already exists\",\n YOU_CANNOT_BAN_YOURSELF: \"You cannot ban yourself\",\n YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE: \"You are not allowed to change users role\",\n YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS: \"You are not allowed to create users\",\n YOU_ARE_NOT_ALLOWED_TO_LIST_USERS: \"You are not allowed to list users\",\n YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS: \"You are not allowed to list users sessions\",\n YOU_ARE_NOT_ALLOWED_TO_BAN_USERS: \"You are not allowed to ban users\",\n YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS: \"You are not allowed to impersonate users\",\n YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS: \"You are not allowed to revoke users sessions\",\n YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS: \"You are not allowed to delete users\",\n YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD: \"You are not allowed to set users password\",\n BANNED_USER: \"You have been banned from this application\",\n NO_DATA_TO_UPDATE: \"No data to update\",\n YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS: \"You are not allowed to update users\"\n};\n\nconst schema = {\n user: {\n fields: {\n role: {\n type: \"string\",\n required: false,\n input: false\n },\n banned: {\n type: \"boolean\",\n defaultValue: false,\n required: false,\n input: false\n },\n banReason: {\n type: \"string\",\n required: false,\n input: false\n },\n banExpires: {\n type: \"date\",\n required: false,\n input: false\n }\n }\n },\n session: {\n fields: {\n impersonatedBy: {\n type: \"string\",\n required: false\n }\n }\n }\n};\n\nfunction parseRoles(roles) {\n return Array.isArray(roles) ? roles.join(\",\") : roles;\n}\nconst admin = (options) => {\n const opts = {\n defaultRole: options?.defaultRole ?? \"user\",\n adminRoles: options?.adminRoles ?? [\"admin\"],\n bannedUserMessage: options?.bannedUserMessage ?? \"You have been banned from this application. Please contact support if you believe this is an error.\",\n ...options\n };\n const adminMiddleware = createAuthMiddleware(async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n return {\n session\n };\n });\n return {\n id: \"admin\",\n init() {\n return {\n options: {\n databaseHooks: {\n user: {\n create: {\n async before(user) {\n return {\n data: {\n role: options?.defaultRole ?? \"user\",\n ...user\n }\n };\n }\n }\n },\n session: {\n create: {\n async before(session, ctx) {\n if (!ctx) {\n return;\n }\n const user = await ctx.context.internalAdapter.findUserById(\n session.userId\n );\n if (user.banned) {\n if (user.banExpires && user.banExpires.getTime() < Date.now()) {\n await ctx.context.internalAdapter.updateUser(\n session.userId,\n {\n banned: false,\n banReason: null,\n banExpires: null\n }\n );\n return;\n }\n if (ctx && (ctx.path.startsWith(\"/callback\") || ctx.path.startsWith(\"/oauth2/callback\"))) {\n const redirectURI = ctx.context.options.onAPIError?.errorURL || `${ctx.context.baseURL}/error`;\n throw ctx.redirect(\n `${redirectURI}?error=banned&error_description=${opts.bannedUserMessage}`\n );\n }\n throw new APIError(\"FORBIDDEN\", {\n message: opts.bannedUserMessage,\n code: \"BANNED_USER\"\n });\n }\n }\n }\n }\n }\n }\n };\n },\n hooks: {\n after: [\n {\n matcher(context) {\n return context.path === \"/list-sessions\";\n },\n handler: createAuthMiddleware(async (ctx) => {\n const response = await getEndpointResponse(ctx);\n if (!response) {\n return;\n }\n const newJson = response.filter((session) => {\n return !session.impersonatedBy;\n });\n return ctx.json(newJson);\n })\n }\n ]\n },\n endpoints: {\n /**\n * ### Endpoint\n *\n * POST `/admin/set-role`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.setRole`\n *\n * **client:**\n * `authClient.admin.setRole`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-set-role)\n */\n setRole: createAuthEndpoint(\n \"/admin/set-role\",\n {\n method: \"POST\",\n body: z.object({\n userId: z.coerce.string().meta({\n description: \"The user id\"\n }),\n role: z.union([\n z.string().meta({\n description: \"The role to set. `admin` or `user` by default\"\n }),\n z.array(\n z.string().meta({\n description: \"The roles to set. `admin` or `user` by default\"\n })\n )\n ]).meta({\n description: \"The role to set, this can be a string or an array of strings. Eg: `admin` or `[admin, user]`\"\n })\n }),\n requireHeaders: true,\n use: [adminMiddleware],\n metadata: {\n openapi: {\n operationId: \"setRole\",\n summary: \"Set the role of a user\",\n description: \"Set the role of a user\",\n responses: {\n 200: {\n description: \"User role updated\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n $ref: \"#/components/schemas/User\"\n }\n }\n }\n }\n }\n }\n }\n },\n $Infer: {\n body: {}\n }\n }\n },\n async (ctx) => {\n const canSetRole = hasPermission({\n userId: ctx.context.session.user.id,\n role: ctx.context.session.user.role,\n options: opts,\n permissions: {\n user: [\"set-role\"]\n }\n });\n if (!canSetRole) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE\n });\n }\n const updatedUser = await ctx.context.internalAdapter.updateUser(\n ctx.body.userId,\n {\n role: parseRoles(ctx.body.role)\n },\n ctx\n );\n return ctx.json({\n user: updatedUser\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/create-user`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.createUser`\n *\n * **client:**\n * `authClient.admin.createUser`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-create-user)\n */\n createUser: createAuthEndpoint(\n \"/admin/create-user\",\n {\n method: \"POST\",\n body: z.object({\n email: z.string().meta({\n description: \"The email of the user\"\n }),\n password: z.string().meta({\n description: \"The password of the user\"\n }),\n name: z.string().meta({\n description: \"The name of the user\"\n }),\n role: z.union([\n z.string().meta({\n description: \"The role of the user\"\n }),\n z.array(\n z.string().meta({\n description: \"The roles of user\"\n })\n )\n ]).optional().meta({\n description: `A string or array of strings representing the roles to apply to the new user. Eg: \"user\"`\n }),\n /**\n * extra fields for user\n */\n data: z.record(z.string(), z.any()).optional().meta({\n description: \"Extra fields for the user. Including custom additional fields.\"\n })\n }),\n metadata: {\n openapi: {\n operationId: \"createUser\",\n summary: \"Create a new user\",\n description: \"Create a new user\",\n responses: {\n 200: {\n description: \"User created\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n $ref: \"#/components/schemas/User\"\n }\n }\n }\n }\n }\n }\n }\n },\n $Infer: {\n body: {}\n }\n }\n },\n async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (!session && (ctx.request || ctx.headers)) {\n throw ctx.error(\"UNAUTHORIZED\");\n }\n if (session) {\n const canCreateUser = hasPermission({\n userId: session.user.id,\n role: session.user.role,\n options: opts,\n permissions: {\n user: [\"create\"]\n }\n });\n if (!canCreateUser) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS\n });\n }\n }\n const existUser = await ctx.context.internalAdapter.findUserByEmail(\n ctx.body.email\n );\n if (existUser) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ADMIN_ERROR_CODES.USER_ALREADY_EXISTS\n });\n }\n const user = await ctx.context.internalAdapter.createUser(\n {\n email: ctx.body.email,\n name: ctx.body.name,\n role: (ctx.body.role && parseRoles(ctx.body.role)) ?? options?.defaultRole ?? \"user\",\n ...ctx.body.data\n },\n ctx\n );\n if (!user) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: ADMIN_ERROR_CODES.FAILED_TO_CREATE_USER\n });\n }\n const hashedPassword = await ctx.context.password.hash(\n ctx.body.password\n );\n await ctx.context.internalAdapter.linkAccount(\n {\n accountId: user.id,\n providerId: \"credential\",\n password: hashedPassword,\n userId: user.id\n },\n ctx\n );\n return ctx.json({\n user\n });\n }\n ),\n adminUpdateUser: createAuthEndpoint(\n \"/admin/update-user\",\n {\n method: \"POST\",\n body: z.object({\n userId: z.coerce.string().meta({\n description: \"The user id\"\n }),\n data: z.record(z.any(), z.any()).meta({\n description: \"The user data to update\"\n })\n }),\n use: [adminMiddleware],\n metadata: {\n openapi: {\n operationId: \"updateUser\",\n summary: \"Update a user\",\n description: \"Update a user's details\",\n responses: {\n 200: {\n description: \"User updated\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n $ref: \"#/components/schemas/User\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const canUpdateUser = hasPermission({\n userId: ctx.context.session.user.id,\n role: ctx.context.session.user.role,\n options: opts,\n permissions: {\n user: [\"update\"]\n }\n });\n if (!canUpdateUser) {\n throw ctx.error(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS,\n code: \"YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS\"\n });\n }\n if (Object.keys(ctx.body.data).length === 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ADMIN_ERROR_CODES.NO_DATA_TO_UPDATE\n });\n }\n const updatedUser = await ctx.context.internalAdapter.updateUser(\n ctx.body.userId,\n ctx.body.data,\n ctx\n );\n return ctx.json(updatedUser);\n }\n ),\n listUsers: createAuthEndpoint(\n \"/admin/list-users\",\n {\n method: \"GET\",\n use: [adminMiddleware],\n query: z.object({\n searchValue: z.string().optional().meta({\n description: 'The value to search for. Eg: \"some name\"'\n }),\n searchField: z.enum([\"email\", \"name\"]).meta({\n description: 'The field to search in, defaults to email. Can be `email` or `name`. Eg: \"name\"'\n }).optional(),\n searchOperator: z.enum([\"contains\", \"starts_with\", \"ends_with\"]).meta({\n description: 'The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`. Eg: \"contains\"'\n }).optional(),\n limit: z.string().meta({\n description: \"The number of users to return\"\n }).or(z.number()).optional(),\n offset: z.string().meta({\n description: \"The offset to start from\"\n }).or(z.number()).optional(),\n sortBy: z.string().meta({\n description: \"The field to sort by\"\n }).optional(),\n sortDirection: z.enum([\"asc\", \"desc\"]).meta({\n description: \"The direction to sort by\"\n }).optional(),\n filterField: z.string().meta({\n description: \"The field to filter by\"\n }).optional(),\n filterValue: z.string().meta({\n description: \"The value to filter by\"\n }).or(z.number()).or(z.boolean()).optional(),\n filterOperator: z.enum([\"eq\", \"ne\", \"lt\", \"lte\", \"gt\", \"gte\", \"contains\"]).meta({\n description: \"The operator to use for the filter\"\n }).optional()\n }),\n metadata: {\n openapi: {\n operationId: \"listUsers\",\n summary: \"List users\",\n description: \"List users\",\n responses: {\n 200: {\n description: \"List of users\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n users: {\n type: \"array\",\n items: {\n $ref: \"#/components/schemas/User\"\n }\n },\n total: {\n type: \"number\"\n },\n limit: {\n type: \"number\"\n },\n offset: {\n type: \"number\"\n }\n },\n required: [\"users\", \"total\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const canListUsers = hasPermission({\n userId: ctx.context.session.user.id,\n role: session.user.role,\n options: opts,\n permissions: {\n user: [\"list\"]\n }\n });\n if (!canListUsers) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS\n });\n }\n const where = [];\n if (ctx.query?.searchValue) {\n where.push({\n field: ctx.query.searchField || \"email\",\n operator: ctx.query.searchOperator || \"contains\",\n value: ctx.query.searchValue\n });\n }\n if (ctx.query?.filterValue) {\n where.push({\n field: ctx.query.filterField || \"email\",\n operator: ctx.query.filterOperator || \"eq\",\n value: ctx.query.filterValue\n });\n }\n try {\n const users = await ctx.context.internalAdapter.listUsers(\n Number(ctx.query?.limit) || void 0,\n Number(ctx.query?.offset) || void 0,\n ctx.query?.sortBy ? {\n field: ctx.query.sortBy,\n direction: ctx.query.sortDirection || \"asc\"\n } : void 0,\n where.length ? where : void 0\n );\n const total = await ctx.context.internalAdapter.countTotalUsers(\n where.length ? where : void 0\n );\n return ctx.json({\n users,\n total,\n limit: Number(ctx.query?.limit) || void 0,\n offset: Number(ctx.query?.offset) || void 0\n });\n } catch (e) {\n return ctx.json({\n users: [],\n total: 0\n });\n }\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/list-user-sessions`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.listUserSessions`\n *\n * **client:**\n * `authClient.admin.listUserSessions`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-list-user-sessions)\n */\n listUserSessions: createAuthEndpoint(\n \"/admin/list-user-sessions\",\n {\n method: \"POST\",\n use: [adminMiddleware],\n body: z.object({\n userId: z.coerce.string().meta({\n description: \"The user id\"\n })\n }),\n metadata: {\n openapi: {\n operationId: \"listUserSessions\",\n summary: \"List user sessions\",\n description: \"List user sessions\",\n responses: {\n 200: {\n description: \"List of user sessions\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n sessions: {\n type: \"array\",\n items: {\n $ref: \"#/components/schemas/Session\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const canListSessions = hasPermission({\n userId: ctx.context.session.user.id,\n role: session.user.role,\n options: opts,\n permissions: {\n session: [\"list\"]\n }\n });\n if (!canListSessions) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS\n });\n }\n const sessions = await ctx.context.internalAdapter.listSessions(\n ctx.body.userId\n );\n return {\n sessions\n };\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/unban-user`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.unbanUser`\n *\n * **client:**\n * `authClient.admin.unbanUser`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-unban-user)\n */\n unbanUser: createAuthEndpoint(\n \"/admin/unban-user\",\n {\n method: \"POST\",\n body: z.object({\n userId: z.coerce.string().meta({\n description: \"The user id\"\n })\n }),\n use: [adminMiddleware],\n metadata: {\n openapi: {\n operationId: \"unbanUser\",\n summary: \"Unban a user\",\n description: \"Unban a user\",\n responses: {\n 200: {\n description: \"User unbanned\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n $ref: \"#/components/schemas/User\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const canBanUser = hasPermission({\n userId: ctx.context.session.user.id,\n role: session.user.role,\n options: opts,\n permissions: {\n user: [\"ban\"]\n }\n });\n if (!canBanUser) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS\n });\n }\n const user = await ctx.context.internalAdapter.updateUser(\n ctx.body.userId,\n {\n banned: false,\n banExpires: null,\n banReason: null,\n updatedAt: /* @__PURE__ */ new Date()\n }\n );\n return ctx.json({\n user\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/ban-user`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.banUser`\n *\n * **client:**\n * `authClient.admin.banUser`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-ban-user)\n */\n banUser: createAuthEndpoint(\n \"/admin/ban-user\",\n {\n method: \"POST\",\n body: z.object({\n userId: z.coerce.string().meta({\n description: \"The user id\"\n }),\n /**\n * Reason for the ban\n */\n banReason: z.string().meta({\n description: \"The reason for the ban\"\n }).optional(),\n /**\n * Number of seconds until the ban expires\n */\n banExpiresIn: z.number().meta({\n description: \"The number of seconds until the ban expires\"\n }).optional()\n }),\n use: [adminMiddleware],\n metadata: {\n openapi: {\n operationId: \"banUser\",\n summary: \"Ban a user\",\n description: \"Ban a user\",\n responses: {\n 200: {\n description: \"User banned\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n user: {\n $ref: \"#/components/schemas/User\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const canBanUser = hasPermission({\n userId: ctx.context.session.user.id,\n role: session.user.role,\n options: opts,\n permissions: {\n user: [\"ban\"]\n }\n });\n if (!canBanUser) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS\n });\n }\n if (ctx.body.userId === ctx.context.session.user.id) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ADMIN_ERROR_CODES.YOU_CANNOT_BAN_YOURSELF\n });\n }\n const user = await ctx.context.internalAdapter.updateUser(\n ctx.body.userId,\n {\n banned: true,\n banReason: ctx.body.banReason || options?.defaultBanReason || \"No reason\",\n banExpires: ctx.body.banExpiresIn ? getDate(ctx.body.banExpiresIn, \"sec\") : options?.defaultBanExpiresIn ? getDate(options.defaultBanExpiresIn, \"sec\") : void 0,\n updatedAt: /* @__PURE__ */ new Date()\n },\n ctx\n );\n await ctx.context.internalAdapter.deleteSessions(ctx.body.userId);\n return ctx.json({\n user\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/impersonate-user`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.impersonateUser`\n *\n * **client:**\n * `authClient.admin.impersonateUser`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-impersonate-user)\n */\n impersonateUser: createAuthEndpoint(\n \"/admin/impersonate-user\",\n {\n method: \"POST\",\n body: z.object({\n userId: z.coerce.string().meta({\n description: \"The user id\"\n })\n }),\n use: [adminMiddleware],\n metadata: {\n openapi: {\n operationId: \"impersonateUser\",\n summary: \"Impersonate a user\",\n description: \"Impersonate a user\",\n responses: {\n 200: {\n description: \"Impersonation session created\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n session: {\n $ref: \"#/components/schemas/Session\"\n },\n user: {\n $ref: \"#/components/schemas/User\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const canImpersonateUser = hasPermission({\n userId: ctx.context.session.user.id,\n role: ctx.context.session.user.role,\n options: opts,\n permissions: {\n user: [\"impersonate\"]\n }\n });\n if (!canImpersonateUser) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS\n });\n }\n const targetUser = await ctx.context.internalAdapter.findUserById(\n ctx.body.userId\n );\n if (!targetUser) {\n throw new APIError(\"NOT_FOUND\", {\n message: \"User not found\"\n });\n }\n const session = await ctx.context.internalAdapter.createSession(\n targetUser.id,\n ctx,\n true,\n {\n impersonatedBy: ctx.context.session.user.id,\n expiresAt: options?.impersonationSessionDuration ? getDate(options.impersonationSessionDuration, \"sec\") : getDate(60 * 60, \"sec\")\n // 1 hour\n },\n true\n );\n if (!session) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: ADMIN_ERROR_CODES.FAILED_TO_CREATE_USER\n });\n }\n const authCookies = ctx.context.authCookies;\n deleteSessionCookie(ctx);\n const dontRememberMeCookie = await ctx.getSignedCookie(\n ctx.context.authCookies.dontRememberToken.name,\n ctx.context.secret\n );\n const adminCookieProp = ctx.context.createAuthCookie(\"admin_session\");\n await ctx.setSignedCookie(\n adminCookieProp.name,\n `${ctx.context.session.session.token}:${dontRememberMeCookie || \"\"}`,\n ctx.context.secret,\n authCookies.sessionToken.options\n );\n await setSessionCookie(\n ctx,\n {\n session,\n user: targetUser\n },\n true\n );\n return ctx.json({\n session,\n user: targetUser\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/stop-impersonating`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.stopImpersonating`\n *\n * **client:**\n * `authClient.admin.stopImpersonating`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-stop-impersonating)\n */\n stopImpersonating: createAuthEndpoint(\n \"/admin/stop-impersonating\",\n {\n method: \"POST\",\n requireHeaders: true\n },\n async (ctx) => {\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n if (!session.session.impersonatedBy) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"You are not impersonating anyone\"\n });\n }\n const user = await ctx.context.internalAdapter.findUserById(\n session.session.impersonatedBy\n );\n if (!user) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Failed to find user\"\n });\n }\n const adminCookieName = ctx.context.createAuthCookie(\"admin_session\").name;\n const adminCookie = await ctx.getSignedCookie(\n adminCookieName,\n ctx.context.secret\n );\n if (!adminCookie) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Failed to find admin session\"\n });\n }\n const [adminSessionToken, dontRememberMeCookie] = adminCookie?.split(\":\");\n const adminSession = await ctx.context.internalAdapter.findSession(adminSessionToken);\n if (!adminSession || adminSession.session.userId !== user.id) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Failed to find admin session\"\n });\n }\n await ctx.context.internalAdapter.deleteSession(\n session.session.token\n );\n await setSessionCookie(ctx, adminSession, !!dontRememberMeCookie);\n return ctx.json(adminSession);\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/revoke-user-session`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.revokeUserSession`\n *\n * **client:**\n * `authClient.admin.revokeUserSession`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-revoke-user-session)\n */\n revokeUserSession: createAuthEndpoint(\n \"/admin/revoke-user-session\",\n {\n method: \"POST\",\n body: z.object({\n sessionToken: z.string().meta({\n description: \"The session token\"\n })\n }),\n use: [adminMiddleware],\n metadata: {\n openapi: {\n operationId: \"revokeUserSession\",\n summary: \"Revoke a user session\",\n description: \"Revoke a user session\",\n responses: {\n 200: {\n description: \"Session revoked\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const canRevokeSession = hasPermission({\n userId: ctx.context.session.user.id,\n role: session.user.role,\n options: opts,\n permissions: {\n session: [\"revoke\"]\n }\n });\n if (!canRevokeSession) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS\n });\n }\n await ctx.context.internalAdapter.deleteSession(\n ctx.body.sessionToken\n );\n return ctx.json({\n success: true\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/revoke-user-sessions`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.revokeUserSessions`\n *\n * **client:**\n * `authClient.admin.revokeUserSessions`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-revoke-user-sessions)\n */\n revokeUserSessions: createAuthEndpoint(\n \"/admin/revoke-user-sessions\",\n {\n method: \"POST\",\n body: z.object({\n userId: z.coerce.string().meta({\n description: \"The user id\"\n })\n }),\n use: [adminMiddleware],\n metadata: {\n openapi: {\n operationId: \"revokeUserSessions\",\n summary: \"Revoke all user sessions\",\n description: \"Revoke all user sessions\",\n responses: {\n 200: {\n description: \"Sessions revoked\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const canRevokeSession = hasPermission({\n userId: ctx.context.session.user.id,\n role: session.user.role,\n options: opts,\n permissions: {\n session: [\"revoke\"]\n }\n });\n if (!canRevokeSession) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS\n });\n }\n await ctx.context.internalAdapter.deleteSessions(ctx.body.userId);\n return ctx.json({\n success: true\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/remove-user`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.removeUser`\n *\n * **client:**\n * `authClient.admin.removeUser`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-remove-user)\n */\n removeUser: createAuthEndpoint(\n \"/admin/remove-user\",\n {\n method: \"POST\",\n body: z.object({\n userId: z.coerce.string().meta({\n description: \"The user id\"\n })\n }),\n use: [adminMiddleware],\n metadata: {\n openapi: {\n operationId: \"removeUser\",\n summary: \"Remove a user\",\n description: \"Delete a user and all their sessions and accounts. Cannot be undone.\",\n responses: {\n 200: {\n description: \"User removed\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n const canDeleteUser = hasPermission({\n userId: ctx.context.session.user.id,\n role: session.user.role,\n options: opts,\n permissions: {\n user: [\"delete\"]\n }\n });\n if (!canDeleteUser) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS\n });\n }\n const user = await ctx.context.internalAdapter.findUserById(\n ctx.body.userId\n );\n if (!user) {\n throw new APIError(\"NOT_FOUND\", {\n message: \"User not found\"\n });\n }\n await ctx.context.internalAdapter.deleteUser(ctx.body.userId);\n return ctx.json({\n success: true\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/set-user-password`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.setUserPassword`\n *\n * **client:**\n * `authClient.admin.setUserPassword`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-set-user-password)\n */\n setUserPassword: createAuthEndpoint(\n \"/admin/set-user-password\",\n {\n method: \"POST\",\n body: z.object({\n newPassword: z.string().meta({\n description: \"The new password\"\n }),\n userId: z.coerce.string().meta({\n description: \"The user id\"\n })\n }),\n use: [adminMiddleware],\n metadata: {\n openapi: {\n operationId: \"setUserPassword\",\n summary: \"Set a user's password\",\n description: \"Set a user's password\",\n responses: {\n 200: {\n description: \"Password set\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const canSetUserPassword = hasPermission({\n userId: ctx.context.session.user.id,\n role: ctx.context.session.user.role,\n options: opts,\n permissions: {\n user: [\"set-password\"]\n }\n });\n if (!canSetUserPassword) {\n throw new APIError(\"FORBIDDEN\", {\n message: ADMIN_ERROR_CODES.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD\n });\n }\n const hashedPassword = await ctx.context.password.hash(\n ctx.body.newPassword\n );\n await ctx.context.internalAdapter.updatePassword(\n ctx.body.userId,\n hashedPassword\n );\n return ctx.json({\n status: true\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/admin/has-permission`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.userHasPermission`\n *\n * **client:**\n * `authClient.admin.hasPermission`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/admin#api-method-admin-has-permission)\n */\n userHasPermission: createAuthEndpoint(\n \"/admin/has-permission\",\n {\n method: \"POST\",\n body: z.object({\n userId: z.coerce.string().optional().meta({\n description: `The user id. Eg: \"user-id\"`\n }),\n role: z.string().optional().meta({\n description: `The role to check permission for. Eg: \"admin\"`\n })\n }).and(\n z.union([\n z.object({\n permission: z.record(z.string(), z.array(z.string())),\n permissions: z.undefined()\n }),\n z.object({\n permission: z.undefined(),\n permissions: z.record(z.string(), z.array(z.string()))\n })\n ])\n ),\n metadata: {\n openapi: {\n description: \"Check if the user has permission\",\n requestBody: {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n permission: {\n type: \"object\",\n description: \"The permission to check\",\n deprecated: true\n },\n permissions: {\n type: \"object\",\n description: \"The permission to check\"\n }\n },\n required: [\"permissions\"]\n }\n }\n }\n },\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n error: {\n type: \"string\"\n },\n success: {\n type: \"boolean\"\n }\n },\n required: [\"success\"]\n }\n }\n }\n }\n }\n },\n $Infer: {\n body: {}\n }\n }\n },\n async (ctx) => {\n if (!ctx.body?.permission && !ctx.body?.permissions) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"invalid permission check. no permission(s) were passed.\"\n });\n }\n const session = await getSessionFromCtx(ctx);\n if (!session && (ctx.request || ctx.headers) && !ctx.body.userId && !ctx.body.role) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n const user = session?.user || await ctx.context.internalAdapter.findUserById(\n ctx.body.userId\n ) || (ctx.body.role ? { id: \"\", role: ctx.body.role } : null);\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"user not found\"\n });\n }\n const result = hasPermission({\n userId: user.id,\n role: user.role,\n options,\n permissions: ctx.body.permissions ?? ctx.body.permission\n });\n return ctx.json({\n error: null,\n success: result\n });\n }\n )\n },\n $ERROR_CODES: ADMIN_ERROR_CODES,\n schema: mergeSchema(schema, opts.schema),\n options\n };\n};\n\nexport { admin as a };\n","import { createAccessControl } from '../../access/index.mjs';\nimport '../../../shared/better-auth.DdzSJf-n.mjs';\n\nconst defaultStatements = {\n user: [\n \"create\",\n \"list\",\n \"set-role\",\n \"ban\",\n \"impersonate\",\n \"delete\",\n \"set-password\",\n \"update\"\n ],\n session: [\"list\", \"revoke\", \"delete\"]\n};\nconst defaultAc = createAccessControl(defaultStatements);\nconst adminAc = defaultAc.newRole({\n user: [\n \"create\",\n \"list\",\n \"set-role\",\n \"ban\",\n \"impersonate\",\n \"delete\",\n \"set-password\",\n \"update\"\n ],\n session: [\"list\", \"revoke\", \"delete\"]\n});\nconst userAc = defaultAc.newRole({\n user: [],\n session: []\n});\nconst defaultRoles = {\n admin: adminAc,\n user: userAc\n};\n\nexport { adminAc, defaultAc, defaultRoles, defaultStatements, userAc };\n","import { betterFetch } from '@better-fetch/fetch';\nimport { APIError } from 'better-call';\nimport { decodeJwt } from 'jose';\nimport * as z from 'zod/v4';\nimport { j as createAuthEndpoint, l as sessionMiddleware, B as BASE_ERROR_CODES, g as generateState, c as createAuthorizationURL, p as parseState, v as validateAuthorizationCode, h as handleOAuthUserInfo, r as refreshAccessToken } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport { setSessionCookie } from '../../cookies/index.mjs';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport '@better-auth/utils/hash';\nimport '@better-auth/utils/base64';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '../../crypto/index.mjs';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'jose/errors';\nimport '@better-auth/utils/random';\n\nasync function getUserInfo(tokens, finalUserInfoUrl) {\n if (tokens.idToken) {\n const decoded = decodeJwt(tokens.idToken);\n if (decoded) {\n if (decoded.sub && decoded.email) {\n return {\n id: decoded.sub,\n emailVerified: decoded.email_verified,\n image: decoded.picture,\n ...decoded\n };\n }\n }\n }\n if (!finalUserInfoUrl) {\n return null;\n }\n const userInfo = await betterFetch(finalUserInfoUrl, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${tokens.accessToken}`\n }\n });\n return {\n id: userInfo.data?.sub,\n emailVerified: userInfo.data?.email_verified,\n email: userInfo.data?.email,\n image: userInfo.data?.picture,\n name: userInfo.data?.name,\n ...userInfo.data\n };\n}\nconst genericOAuth = (options) => {\n const ERROR_CODES = {\n INVALID_OAUTH_CONFIGURATION: \"Invalid OAuth configuration\"\n };\n return {\n id: \"generic-oauth\",\n init: (ctx) => {\n const genericProviders = options.config.map((c) => {\n let finalUserInfoUrl = c.userInfoUrl;\n return {\n id: c.providerId,\n name: c.providerId,\n createAuthorizationURL(data) {\n return createAuthorizationURL({\n id: c.providerId,\n options: {\n clientId: c.clientId,\n clientSecret: c.clientSecret,\n redirectURI: c.redirectURI\n },\n authorizationEndpoint: c.authorizationUrl,\n state: data.state,\n codeVerifier: c.pkce ? data.codeVerifier : void 0,\n scopes: c.scopes || [],\n redirectURI: `${ctx.baseURL}/oauth2/callback/${c.providerId}`\n });\n },\n async validateAuthorizationCode(data) {\n let finalTokenUrl = c.tokenUrl;\n if (c.discoveryUrl) {\n const discovery = await betterFetch(c.discoveryUrl, {\n method: \"GET\",\n headers: c.discoveryHeaders\n });\n if (discovery.data) {\n finalTokenUrl = discovery.data.token_endpoint;\n finalUserInfoUrl = discovery.data.userinfo_endpoint;\n }\n }\n if (!finalTokenUrl) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invalid OAuth configuration. Token URL not found.\"\n });\n }\n return validateAuthorizationCode({\n headers: c.authorizationHeaders,\n code: data.code,\n codeVerifier: data.codeVerifier,\n redirectURI: data.redirectURI,\n options: {\n clientId: c.clientId,\n clientSecret: c.clientSecret,\n redirectURI: c.redirectURI\n },\n tokenEndpoint: finalTokenUrl,\n authentication: c.authentication\n });\n },\n async refreshAccessToken(refreshToken) {\n let finalTokenUrl = c.tokenUrl;\n if (c.discoveryUrl) {\n const discovery = await betterFetch(c.discoveryUrl, {\n method: \"GET\",\n headers: c.discoveryHeaders\n });\n if (discovery.data) {\n finalTokenUrl = discovery.data.token_endpoint;\n }\n }\n if (!finalTokenUrl) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invalid OAuth configuration. Token URL not found.\"\n });\n }\n return refreshAccessToken({\n refreshToken,\n options: {\n clientId: c.clientId,\n clientSecret: c.clientSecret\n },\n authentication: c.authentication,\n tokenEndpoint: finalTokenUrl\n });\n },\n async getUserInfo(tokens) {\n const userInfo = c.getUserInfo ? await c.getUserInfo(tokens) : await getUserInfo(tokens, finalUserInfoUrl);\n if (!userInfo) {\n return null;\n }\n return {\n user: {\n id: userInfo?.id,\n email: userInfo?.email,\n emailVerified: userInfo?.emailVerified,\n image: userInfo?.image,\n name: userInfo?.name,\n ...c.mapProfileToUser?.(userInfo)\n },\n data: userInfo\n };\n }\n };\n });\n return {\n context: {\n socialProviders: genericProviders.concat(ctx.socialProviders)\n }\n };\n },\n endpoints: {\n /**\n * ### Endpoint\n *\n * POST `/sign-in/oauth2`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.signInWithOAuth2`\n *\n * **client:**\n * `authClient.signIn.oauth2`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/sign-in#api-method-sign-in-oauth2)\n */\n signInWithOAuth2: createAuthEndpoint(\n \"/sign-in/oauth2\",\n {\n method: \"POST\",\n body: z.object({\n providerId: z.string().meta({\n description: \"The provider ID for the OAuth provider\"\n }),\n callbackURL: z.string().meta({\n description: \"The URL to redirect to after sign in\"\n }).optional(),\n errorCallbackURL: z.string().meta({\n description: \"The URL to redirect to if an error occurs\"\n }).optional(),\n newUserCallbackURL: z.string().meta({\n description: 'The URL to redirect to after login if the user is new. Eg: \"/welcome\"'\n }).optional(),\n disableRedirect: z.boolean().meta({\n description: \"Disable redirect\"\n }).optional(),\n scopes: z.array(z.string()).meta({\n description: \"Scopes to be passed to the provider authorization request.\"\n }).optional(),\n requestSignUp: z.boolean().meta({\n description: \"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider. Eg: false\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Sign in with OAuth2\",\n responses: {\n 200: {\n description: \"Sign in with OAuth2\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n url: {\n type: \"string\"\n },\n redirect: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { providerId } = ctx.body;\n const config = options.config.find(\n (c) => c.providerId === providerId\n );\n if (!config) {\n throw new APIError(\"BAD_REQUEST\", {\n message: `No config found for provider ${providerId}`\n });\n }\n const {\n discoveryUrl,\n authorizationUrl,\n tokenUrl,\n clientId,\n clientSecret,\n scopes,\n redirectURI,\n responseType,\n pkce,\n prompt,\n accessType,\n authorizationUrlParams,\n responseMode,\n authentication\n } = config;\n let finalAuthUrl = authorizationUrl;\n let finalTokenUrl = tokenUrl;\n if (discoveryUrl) {\n const discovery = await betterFetch(discoveryUrl, {\n method: \"GET\",\n headers: config.discoveryHeaders,\n onError(context) {\n ctx.context.logger.error(context.error.message, context.error, {\n discoveryUrl\n });\n }\n });\n if (discovery.data) {\n finalAuthUrl = discovery.data.authorization_endpoint;\n finalTokenUrl = discovery.data.token_endpoint;\n }\n }\n if (!finalAuthUrl || !finalTokenUrl) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OAUTH_CONFIGURATION\n });\n }\n if (authorizationUrlParams) {\n const withAdditionalParams = new URL(finalAuthUrl);\n for (const [paramName, paramValue] of Object.entries(\n authorizationUrlParams\n )) {\n withAdditionalParams.searchParams.set(paramName, paramValue);\n }\n finalAuthUrl = withAdditionalParams.toString();\n }\n const { state, codeVerifier } = await generateState(ctx);\n const authUrl = await createAuthorizationURL({\n id: providerId,\n options: {\n clientId,\n redirectURI\n },\n authorizationEndpoint: finalAuthUrl,\n state,\n codeVerifier: pkce ? codeVerifier : void 0,\n scopes: ctx.body.scopes ? [...ctx.body.scopes, ...scopes || []] : scopes || [],\n redirectURI: `${ctx.context.baseURL}/oauth2/callback/${providerId}`,\n prompt,\n accessType,\n responseType,\n responseMode,\n additionalParams: authorizationUrlParams\n });\n return ctx.json({\n url: authUrl.toString(),\n redirect: !ctx.body.disableRedirect\n });\n }\n ),\n oAuth2Callback: createAuthEndpoint(\n \"/oauth2/callback/:providerId\",\n {\n method: \"GET\",\n query: z.object({\n code: z.string().meta({\n description: \"The OAuth2 code\"\n }).optional(),\n error: z.string().meta({\n description: \"The error message, if any\"\n }).optional(),\n error_description: z.string().meta({\n description: \"The error description, if any\"\n }).optional(),\n state: z.string().meta({\n description: \"The state parameter from the OAuth2 request\"\n }).optional()\n }),\n metadata: {\n client: false,\n openapi: {\n description: \"OAuth2 callback\",\n responses: {\n 200: {\n description: \"OAuth2 callback\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n url: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const defaultErrorURL = ctx.context.options.onAPIError?.errorURL || `${ctx.context.baseURL}/error`;\n if (ctx.query.error || !ctx.query.code) {\n throw ctx.redirect(\n `${defaultErrorURL}?error=${ctx.query.error || \"oAuth_code_missing\"}&error_description=${ctx.query.error_description}`\n );\n }\n const provider = options.config.find(\n (p) => p.providerId === ctx.params.providerId\n );\n if (!provider) {\n throw new APIError(\"BAD_REQUEST\", {\n message: `No config found for provider ${ctx.params.providerId}`\n });\n }\n let tokens = void 0;\n const parsedState = await parseState(ctx);\n const {\n callbackURL,\n codeVerifier,\n errorURL,\n requestSignUp,\n newUserURL,\n link\n } = parsedState;\n const code = ctx.query.code;\n function redirectOnError(error) {\n const defaultErrorURL2 = ctx.context.options.onAPIError?.errorURL || `${ctx.context.baseURL}/error`;\n let url = errorURL || defaultErrorURL2;\n if (url.includes(\"?\")) {\n url = `${url}&error=${error}`;\n } else {\n url = `${url}?error=${error}`;\n }\n throw ctx.redirect(url);\n }\n let finalTokenUrl = provider.tokenUrl;\n let finalUserInfoUrl = provider.userInfoUrl;\n if (provider.discoveryUrl) {\n const discovery = await betterFetch(provider.discoveryUrl, {\n method: \"GET\",\n headers: provider.discoveryHeaders\n });\n if (discovery.data) {\n finalTokenUrl = discovery.data.token_endpoint;\n finalUserInfoUrl = discovery.data.userinfo_endpoint;\n }\n }\n try {\n if (!finalTokenUrl) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invalid OAuth configuration.\"\n });\n }\n tokens = await validateAuthorizationCode({\n headers: provider.authorizationHeaders,\n code,\n codeVerifier: provider.pkce ? codeVerifier : void 0,\n redirectURI: `${ctx.context.baseURL}/oauth2/callback/${provider.providerId}`,\n options: {\n clientId: provider.clientId,\n clientSecret: provider.clientSecret,\n redirectURI: provider.redirectURI\n },\n tokenEndpoint: finalTokenUrl,\n authentication: provider.authentication,\n additionalParams: provider.tokenUrlParams\n });\n } catch (e) {\n ctx.context.logger.error(\n e && typeof e === \"object\" && \"name\" in e ? e.name : \"\",\n e\n );\n throw redirectOnError(\"oauth_code_verification_failed\");\n }\n if (!tokens) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invalid OAuth configuration.\"\n });\n }\n const userInfo = provider.getUserInfo ? await provider.getUserInfo(tokens) : await getUserInfo(tokens, finalUserInfoUrl);\n if (!userInfo) {\n throw redirectOnError(\"user_info_is_missing\");\n }\n const mapUser = provider.mapProfileToUser ? await provider.mapProfileToUser(userInfo) : userInfo;\n if (!mapUser?.email) {\n ctx.context.logger.error(\"Unable to get user info\", userInfo);\n throw redirectOnError(\"email_is_missing\");\n }\n if (link) {\n if (ctx.context.options.account?.accountLinking?.allowDifferentEmails !== true && link.email !== mapUser.email.toLowerCase()) {\n return redirectOnError(\"email_doesn't_match\");\n }\n const existingAccount = await ctx.context.internalAdapter.findAccountByProviderId(\n userInfo.id,\n provider.providerId\n );\n if (existingAccount) {\n if (existingAccount.userId !== link.userId) {\n return redirectOnError(\n \"account_already_linked_to_different_user\"\n );\n }\n const updateData = Object.fromEntries(\n Object.entries({\n accessToken: tokens.accessToken,\n idToken: tokens.idToken,\n refreshToken: tokens.refreshToken,\n accessTokenExpiresAt: tokens.accessTokenExpiresAt,\n refreshTokenExpiresAt: tokens.refreshTokenExpiresAt,\n scope: tokens.scopes?.join(\",\")\n }).filter(([_, value]) => value !== void 0)\n );\n await ctx.context.internalAdapter.updateAccount(\n existingAccount.id,\n updateData\n );\n } else {\n const newAccount = await ctx.context.internalAdapter.createAccount({\n userId: link.userId,\n providerId: provider.providerId,\n accountId: userInfo.id,\n accessToken: tokens.accessToken,\n accessTokenExpiresAt: tokens.accessTokenExpiresAt,\n refreshTokenExpiresAt: tokens.refreshTokenExpiresAt,\n scope: tokens.scopes?.join(\",\"),\n refreshToken: tokens.refreshToken,\n idToken: tokens.idToken\n });\n if (!newAccount) {\n return redirectOnError(\"unable_to_link_account\");\n }\n }\n let toRedirectTo2;\n try {\n const url = callbackURL;\n toRedirectTo2 = url.toString();\n } catch {\n toRedirectTo2 = callbackURL;\n }\n throw ctx.redirect(toRedirectTo2);\n }\n const result = await handleOAuthUserInfo(ctx, {\n userInfo: {\n ...userInfo,\n ...mapUser\n },\n account: {\n providerId: provider.providerId,\n accountId: userInfo.id,\n ...tokens,\n scope: tokens.scopes?.join(\",\")\n },\n callbackURL,\n disableSignUp: provider.disableImplicitSignUp && !requestSignUp || provider.disableSignUp,\n overrideUserInfo: provider.overrideUserInfo\n });\n if (result.error) {\n return redirectOnError(result.error.split(\" \").join(\"_\"));\n }\n const { session, user } = result.data;\n await setSessionCookie(ctx, {\n session,\n user\n });\n let toRedirectTo;\n try {\n const url = result.isRegister ? newUserURL || callbackURL : callbackURL;\n toRedirectTo = url.toString();\n } catch {\n toRedirectTo = result.isRegister ? newUserURL || callbackURL : callbackURL;\n }\n throw ctx.redirect(toRedirectTo);\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/oauth2/link`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.oAuth2LinkAccount`\n *\n * **client:**\n * `authClient.oauth2.link`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/generic-oauth#api-method-oauth2-link)\n */\n oAuth2LinkAccount: createAuthEndpoint(\n \"/oauth2/link\",\n {\n method: \"POST\",\n body: z.object({\n providerId: z.string(),\n /**\n * Callback URL to redirect to after the user has signed in.\n */\n callbackURL: z.string(),\n /**\n * Additional scopes to request when linking the account.\n * This is useful for requesting additional permissions when\n * linking a social account compared to the initial authentication.\n */\n scopes: z.array(z.string()).meta({\n description: \"Additional scopes to request when linking the account\"\n }).optional(),\n /**\n * The URL to redirect to if there is an error during the link process.\n */\n errorCallbackURL: z.string().meta({\n description: \"The URL to redirect to if there is an error during the link process\"\n }).optional()\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Link an OAuth2 account to the current user session\",\n responses: {\n \"200\": {\n description: \"Authorization URL generated successfully for linking an OAuth2 account\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n url: {\n type: \"string\",\n format: \"uri\",\n description: \"The authorization URL to redirect the user to for linking the OAuth2 account\"\n },\n redirect: {\n type: \"boolean\",\n description: \"Indicates that the client should redirect to the provided URL\",\n enum: [true]\n }\n },\n required: [\"url\", \"redirect\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (c) => {\n const session = c.context.session;\n const provider = options.config.find(\n (p) => p.providerId === c.body.providerId\n );\n if (!provider) {\n throw new APIError(\"NOT_FOUND\", {\n message: BASE_ERROR_CODES.PROVIDER_NOT_FOUND\n });\n }\n const {\n providerId,\n clientId,\n clientSecret,\n redirectURI,\n authorizationUrl,\n discoveryUrl,\n pkce,\n scopes,\n prompt,\n accessType,\n authorizationUrlParams\n } = provider;\n let finalAuthUrl = authorizationUrl;\n if (!finalAuthUrl) {\n if (!discoveryUrl) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OAUTH_CONFIGURATION\n });\n }\n const discovery = await betterFetch(discoveryUrl, {\n method: \"GET\",\n headers: provider.discoveryHeaders,\n onError(context) {\n c.context.logger.error(context.error.message, context.error, {\n discoveryUrl\n });\n }\n });\n if (discovery.data) {\n finalAuthUrl = discovery.data.authorization_endpoint;\n }\n }\n if (!finalAuthUrl) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OAUTH_CONFIGURATION\n });\n }\n const state = await generateState(c, {\n userId: session.user.id,\n email: session.user.email\n });\n const url = await createAuthorizationURL({\n id: providerId,\n options: {\n clientId,\n redirectURI: redirectURI || `${c.context.baseURL}/oauth2/callback/${providerId}`\n },\n authorizationEndpoint: finalAuthUrl,\n state: state.state,\n codeVerifier: pkce ? state.codeVerifier : void 0,\n scopes: c.body.scopes || scopes || [],\n redirectURI: redirectURI || `${c.context.baseURL}/oauth2/callback/${providerId}`,\n prompt,\n accessType,\n additionalParams: authorizationUrlParams\n });\n return c.json({\n url: url.toString(),\n redirect: true\n });\n }\n )\n },\n $ERROR_CODES: ERROR_CODES\n };\n};\n\nexport { genericOAuth };\n","import * as z from 'zod/v4';\n\nconst schema = {\n jwks: {\n fields: {\n publicKey: {\n type: \"string\",\n required: true\n },\n privateKey: {\n type: \"string\",\n required: true\n },\n createdAt: {\n type: \"date\",\n required: true\n }\n }\n }\n};\nz.object({\n id: z.string(),\n publicKey: z.string(),\n privateKey: z.string(),\n createdAt: z.date()\n});\n\nexport { schema as s };\n","import { s as schema } from '../../shared/better-auth.CGrHn1Ih.mjs';\nimport { importJWK, SignJWT, generateKeyPair, exportJWK } from 'jose';\nimport { B as BetterAuthError } from '../../shared/better-auth.DdzSJf-n.mjs';\nimport { symmetricEncrypt, symmetricDecrypt } from '../../crypto/index.mjs';\nimport 'better-call';\nimport { i as createAuthMiddleware, j as createAuthEndpoint, l as sessionMiddleware } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport 'zod/v4';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '@better-auth/utils/base64';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport { m as mergeSchema } from '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport '@better-auth/utils/hash';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-fetch/fetch';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../cookies/index.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport 'jose/errors';\n\nconst getJwksAdapter = (adapter) => {\n return {\n getAllKeys: async () => {\n return await adapter.findMany({\n model: \"jwks\"\n });\n },\n getLatestKey: async () => {\n const key = await adapter.findMany({\n model: \"jwks\",\n sortBy: {\n field: \"createdAt\",\n direction: \"desc\"\n },\n limit: 1\n });\n return key[0];\n },\n createJwk: async (webKey) => {\n const jwk = await adapter.create({\n model: \"jwks\",\n data: {\n ...webKey,\n createdAt: /* @__PURE__ */ new Date()\n }\n });\n return jwk;\n }\n };\n};\n\nasync function getJwtToken(ctx, options) {\n const adapter = getJwksAdapter(ctx.context.adapter);\n let key = await adapter.getLatestKey();\n const privateKeyEncryptionEnabled = !options?.jwks?.disablePrivateKeyEncryption;\n if (key === void 0) {\n const { publicWebKey, privateWebKey: privateWebKey2 } = await generateExportedKeyPair(options);\n const stringifiedPrivateWebKey = JSON.stringify(privateWebKey2);\n let jwk = {\n publicKey: JSON.stringify(publicWebKey),\n privateKey: privateKeyEncryptionEnabled ? JSON.stringify(\n await symmetricEncrypt({\n key: ctx.context.secret,\n data: stringifiedPrivateWebKey\n })\n ) : stringifiedPrivateWebKey,\n createdAt: /* @__PURE__ */ new Date()\n };\n key = await adapter.createJwk(jwk);\n }\n let privateWebKey = privateKeyEncryptionEnabled ? await symmetricDecrypt({\n key: ctx.context.secret,\n data: JSON.parse(key.privateKey)\n }).catch(() => {\n throw new BetterAuthError(\n \"Failed to decrypt private private key. Make sure the secret currently in use is the same as the one used to encrypt the private key. If you are using a different secret, either cleanup your jwks or disable private key encryption.\"\n );\n }) : key.privateKey;\n const privateKey = await importJWK(\n JSON.parse(privateWebKey),\n options?.jwks?.keyPairConfig?.alg ?? \"EdDSA\"\n );\n const payload = !options?.jwt?.definePayload ? ctx.context.session.user : await options?.jwt.definePayload(ctx.context.session);\n const jwt = await new SignJWT(payload).setProtectedHeader({\n alg: options?.jwks?.keyPairConfig?.alg ?? \"EdDSA\",\n kid: key.id\n }).setIssuedAt().setIssuer(options?.jwt?.issuer ?? ctx.context.options.baseURL).setAudience(options?.jwt?.audience ?? ctx.context.options.baseURL).setExpirationTime(options?.jwt?.expirationTime ?? \"15m\").setSubject(\n await options?.jwt?.getSubject?.(ctx.context.session) ?? ctx.context.session.user.id\n ).sign(privateKey);\n return jwt;\n}\n\nasync function generateExportedKeyPair(options) {\n const { alg, ...cfg } = options?.jwks?.keyPairConfig ?? {\n alg: \"EdDSA\",\n crv: \"Ed25519\"\n };\n const keyPairConfig = {\n ...cfg,\n extractable: true\n };\n const { publicKey, privateKey } = await generateKeyPair(alg, keyPairConfig);\n const publicWebKey = await exportJWK(publicKey);\n const privateWebKey = await exportJWK(privateKey);\n return { publicWebKey, privateWebKey };\n}\nconst jwt = (options) => {\n return {\n id: \"jwt\",\n endpoints: {\n getJwks: createAuthEndpoint(\n \"/jwks\",\n {\n method: \"GET\",\n metadata: {\n openapi: {\n description: \"Get the JSON Web Key Set\",\n responses: {\n \"200\": {\n description: \"JSON Web Key Set retrieved successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n keys: {\n type: \"array\",\n description: \"Array of public JSON Web Keys\",\n items: {\n type: \"object\",\n properties: {\n kid: {\n type: \"string\",\n description: \"Key ID uniquely identifying the key, corresponds to the 'id' from the stored Jwk\"\n },\n kty: {\n type: \"string\",\n description: \"Key type (e.g., 'RSA', 'EC', 'OKP')\"\n },\n alg: {\n type: \"string\",\n description: \"Algorithm intended for use with the key (e.g., 'EdDSA', 'RS256')\"\n },\n use: {\n type: \"string\",\n description: \"Intended use of the public key (e.g., 'sig' for signature)\",\n enum: [\"sig\"],\n nullable: true\n },\n n: {\n type: \"string\",\n description: \"Modulus for RSA keys (base64url-encoded)\",\n nullable: true\n },\n e: {\n type: \"string\",\n description: \"Exponent for RSA keys (base64url-encoded)\",\n nullable: true\n },\n crv: {\n type: \"string\",\n description: \"Curve name for elliptic curve keys (e.g., 'Ed25519', 'P-256')\",\n nullable: true\n },\n x: {\n type: \"string\",\n description: \"X coordinate for elliptic curve keys (base64url-encoded)\",\n nullable: true\n },\n y: {\n type: \"string\",\n description: \"Y coordinate for elliptic curve keys (base64url-encoded)\",\n nullable: true\n }\n },\n required: [\"kid\", \"kty\", \"alg\"]\n }\n }\n },\n required: [\"keys\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const adapter = getJwksAdapter(ctx.context.adapter);\n const keySets = await adapter.getAllKeys();\n if (keySets.length === 0) {\n const { alg, ...cfg } = options?.jwks?.keyPairConfig ?? {\n alg: \"EdDSA\",\n crv: \"Ed25519\"\n };\n const keyPairConfig = {\n ...cfg,\n extractable: true\n };\n const { publicKey, privateKey } = await generateKeyPair(\n alg,\n keyPairConfig\n );\n const publicWebKey = await exportJWK(publicKey);\n const privateWebKey = await exportJWK(privateKey);\n const stringifiedPrivateWebKey = JSON.stringify(privateWebKey);\n const privateKeyEncryptionEnabled = !options?.jwks?.disablePrivateKeyEncryption;\n let jwk = {\n publicKey: JSON.stringify({ alg, ...publicWebKey }),\n privateKey: privateKeyEncryptionEnabled ? JSON.stringify(\n await symmetricEncrypt({\n key: ctx.context.secret,\n data: stringifiedPrivateWebKey\n })\n ) : stringifiedPrivateWebKey,\n createdAt: /* @__PURE__ */ new Date()\n };\n await adapter.createJwk(jwk);\n return ctx.json({\n keys: [\n {\n ...publicWebKey,\n alg,\n kid: jwk.id\n }\n ]\n });\n }\n return ctx.json({\n keys: keySets.map((keySet) => ({\n ...JSON.parse(keySet.publicKey),\n kid: keySet.id\n }))\n });\n }\n ),\n getToken: createAuthEndpoint(\n \"/token\",\n {\n method: \"GET\",\n requireHeaders: true,\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Get a JWT token\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n token: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const jwt2 = await getJwtToken(ctx, options);\n return ctx.json({\n token: jwt2\n });\n }\n )\n },\n hooks: {\n after: [\n {\n matcher(context) {\n return context.path === \"/get-session\";\n },\n handler: createAuthMiddleware(async (ctx) => {\n const session = ctx.context.session || ctx.context.newSession;\n if (session && session.session) {\n const jwt2 = await getJwtToken(ctx, options);\n const exposedHeaders = ctx.context.responseHeaders?.get(\n \"access-control-expose-headers\"\n ) || \"\";\n const headersSet = new Set(\n exposedHeaders.split(\",\").map((header) => header.trim()).filter(Boolean)\n );\n headersSet.add(\"set-auth-jwt\");\n ctx.setHeader(\"set-auth-jwt\", jwt2);\n ctx.setHeader(\n \"Access-Control-Expose-Headers\",\n Array.from(headersSet).join(\", \")\n );\n }\n })\n }\n ]\n },\n schema: mergeSchema(schema, options?.schema)\n };\n};\n\nexport { generateExportedKeyPair, getJwtToken, jwt };\n","import * as z from 'zod/v4';\nimport { APIError } from 'better-call';\nimport { i as createAuthMiddleware, j as createAuthEndpoint, l as sessionMiddleware } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport { parseSetCookieHeader, parseCookies, setSessionCookie, deleteSessionCookie } from '../../cookies/index.mjs';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-auth/utils/hash';\nimport '@better-auth/utils/base64';\nimport '../../crypto/index.mjs';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '@better-fetch/fetch';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'jose/errors';\n\nconst multiSession = (options) => {\n const opts = {\n maximumSessions: 5,\n ...options\n };\n const isMultiSessionCookie = (key) => key.includes(\"_multi-\");\n const ERROR_CODES = {\n INVALID_SESSION_TOKEN: \"Invalid session token\"\n };\n return {\n id: \"multi-session\",\n endpoints: {\n /**\n * ### Endpoint\n *\n * GET `/multi-session/list-device-sessions`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.listDeviceSessions`\n *\n * **client:**\n * `authClient.multiSession.listDeviceSessions`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/multi-session#api-method-multi-session-list-device-sessions)\n */\n listDeviceSessions: createAuthEndpoint(\n \"/multi-session/list-device-sessions\",\n {\n method: \"GET\",\n requireHeaders: true\n },\n async (ctx) => {\n const cookieHeader = ctx.headers?.get(\"cookie\");\n if (!cookieHeader) return ctx.json([]);\n const cookies = Object.fromEntries(parseCookies(cookieHeader));\n const sessionTokens = (await Promise.all(\n Object.entries(cookies).filter(([key]) => isMultiSessionCookie(key)).map(\n async ([key]) => await ctx.getSignedCookie(key, ctx.context.secret)\n )\n )).filter((v) => v !== null);\n if (!sessionTokens.length) return ctx.json([]);\n const sessions = await ctx.context.internalAdapter.findSessions(sessionTokens);\n const validSessions = sessions.filter(\n (session) => session && session.session.expiresAt > /* @__PURE__ */ new Date()\n );\n const uniqueUserSessions = validSessions.reduce(\n (acc, session) => {\n if (!acc.find((s) => s.user.id === session.user.id)) {\n acc.push(session);\n }\n return acc;\n },\n []\n );\n return ctx.json(uniqueUserSessions);\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/multi-session/set-active`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.setActiveSession`\n *\n * **client:**\n * `authClient.multiSession.setActive`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/multi-session#api-method-multi-session-set-active)\n */\n setActiveSession: createAuthEndpoint(\n \"/multi-session/set-active\",\n {\n method: \"POST\",\n body: z.object({\n sessionToken: z.string().meta({\n description: \"The session token to set as active\"\n })\n }),\n requireHeaders: true,\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Set the active session\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n session: {\n $ref: \"#/components/schemas/Session\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const sessionToken = ctx.body.sessionToken;\n const multiSessionCookieName = `${ctx.context.authCookies.sessionToken.name}_multi-${sessionToken.toLowerCase()}`;\n const sessionCookie = await ctx.getSignedCookie(\n multiSessionCookieName,\n ctx.context.secret\n );\n if (!sessionCookie) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.INVALID_SESSION_TOKEN\n });\n }\n const session = await ctx.context.internalAdapter.findSession(sessionToken);\n if (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) {\n ctx.setCookie(multiSessionCookieName, \"\", {\n ...ctx.context.authCookies.sessionToken.options,\n maxAge: 0\n });\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.INVALID_SESSION_TOKEN\n });\n }\n await setSessionCookie(ctx, session);\n return ctx.json(session);\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/multi-session/revoke`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.revokeDeviceSession`\n *\n * **client:**\n * `authClient.multiSession.revoke`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/multi-session#api-method-multi-session-revoke)\n */\n revokeDeviceSession: createAuthEndpoint(\n \"/multi-session/revoke\",\n {\n method: \"POST\",\n body: z.object({\n sessionToken: z.string().meta({\n description: \"The session token to revoke\"\n })\n }),\n requireHeaders: true,\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Revoke a device session\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const sessionToken = ctx.body.sessionToken;\n const multiSessionCookieName = `${ctx.context.authCookies.sessionToken.name}_multi-${sessionToken.toLowerCase()}`;\n const sessionCookie = await ctx.getSignedCookie(\n multiSessionCookieName,\n ctx.context.secret\n );\n if (!sessionCookie) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.INVALID_SESSION_TOKEN\n });\n }\n await ctx.context.internalAdapter.deleteSession(sessionToken);\n ctx.setCookie(multiSessionCookieName, \"\", {\n ...ctx.context.authCookies.sessionToken.options,\n maxAge: 0\n });\n const isActive = ctx.context.session?.session.token === sessionToken;\n if (!isActive) return ctx.json({ status: true });\n const cookieHeader = ctx.headers?.get(\"cookie\");\n if (cookieHeader) {\n const cookies = Object.fromEntries(parseCookies(cookieHeader));\n const sessionTokens = (await Promise.all(\n Object.entries(cookies).filter(([key]) => isMultiSessionCookie(key)).map(\n async ([key]) => await ctx.getSignedCookie(key, ctx.context.secret)\n )\n )).filter((v) => v !== void 0);\n const internalAdapter = ctx.context.internalAdapter;\n if (sessionTokens.length > 0) {\n const sessions = await internalAdapter.findSessions(sessionTokens);\n const validSessions = sessions.filter(\n (session) => session && session.session.expiresAt > /* @__PURE__ */ new Date()\n );\n if (validSessions.length > 0) {\n const nextSession = validSessions[0];\n await setSessionCookie(ctx, nextSession);\n } else {\n deleteSessionCookie(ctx);\n }\n } else {\n deleteSessionCookie(ctx);\n }\n } else {\n deleteSessionCookie(ctx);\n }\n return ctx.json({\n status: true\n });\n }\n )\n },\n hooks: {\n after: [\n {\n matcher: () => true,\n handler: createAuthMiddleware(async (ctx) => {\n const cookieString = ctx.context.responseHeaders?.get(\"set-cookie\");\n if (!cookieString) return;\n const setCookies = parseSetCookieHeader(cookieString);\n const sessionCookieConfig = ctx.context.authCookies.sessionToken;\n const sessionToken = ctx.context.newSession?.session.token;\n if (!sessionToken) return;\n const cookies = parseCookies(ctx.headers?.get(\"cookie\") || \"\");\n const cookieName = `${sessionCookieConfig.name}_multi-${sessionToken.toLowerCase()}`;\n if (setCookies.get(cookieName) || cookies.get(cookieName)) return;\n const currentMultiSessions = Object.keys(Object.fromEntries(cookies)).filter(\n isMultiSessionCookie\n ).length + (cookieString.includes(\"session_token\") ? 1 : 0);\n if (currentMultiSessions >= opts.maximumSessions) {\n return;\n }\n await ctx.setSignedCookie(\n cookieName,\n sessionToken,\n ctx.context.secret,\n sessionCookieConfig.options\n );\n })\n },\n {\n matcher: (context) => context.path === \"/sign-out\",\n handler: createAuthMiddleware(async (ctx) => {\n const cookieHeader = ctx.headers?.get(\"cookie\");\n if (!cookieHeader) return;\n const cookies = Object.fromEntries(parseCookies(cookieHeader));\n const ids = Object.keys(cookies).map((key) => {\n if (isMultiSessionCookie(key)) {\n ctx.setCookie(key.toLowerCase(), \"\", {\n ...ctx.context.authCookies.sessionToken.options,\n maxAge: 0\n });\n const token = cookies[key].split(\".\")[0];\n return token;\n }\n return null;\n }).filter((v) => v !== null);\n await ctx.context.internalAdapter.deleteSessions(ids);\n })\n }\n ]\n },\n $ERROR_CODES: ERROR_CODES\n };\n};\n\nexport { multiSession };\n","import * as z from 'zod/v4';\nimport { APIError } from 'better-call';\nimport { j as createAuthEndpoint, i as createAuthMiddleware } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport { setSessionCookie } from '../../cookies/index.mjs';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { symmetricDecrypt, symmetricEncrypt } from '../../crypto/index.mjs';\nimport { g as getDate } from '../../shared/better-auth.CW6D9eSx.mjs';\nimport { g as getEndpointResponse } from '../../shared/better-auth.DQI8AD7d.mjs';\nimport { createHash } from '@better-auth/utils/hash';\nimport { base64Url } from '@better-auth/utils/base64';\nimport { g as generateRandomString } from '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-fetch/fetch';\nimport 'jose';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'jose/errors';\nimport '@better-auth/utils/random';\n\nconst defaultKeyHasher = async (otp) => {\n const hash = await createHash(\"SHA-256\").digest(\n new TextEncoder().encode(otp)\n );\n const hashed = base64Url.encode(new Uint8Array(hash), {\n padding: false\n });\n return hashed;\n};\nfunction splitAtLastColon(input) {\n const idx = input.lastIndexOf(\":\");\n if (idx === -1) {\n return [input, \"\"];\n }\n return [input.slice(0, idx), input.slice(idx + 1)];\n}\n\nconst types = [\"email-verification\", \"sign-in\", \"forget-password\"];\nconst emailOTP = (options) => {\n const opts = {\n expiresIn: 5 * 60,\n generateOTP: () => generateRandomString(options.otpLength ?? 6, \"0-9\"),\n storeOTP: \"plain\",\n ...options\n };\n const ERROR_CODES = {\n OTP_EXPIRED: \"otp expired\",\n INVALID_OTP: \"Invalid OTP\",\n INVALID_EMAIL: \"Invalid email\",\n USER_NOT_FOUND: \"User not found\",\n TOO_MANY_ATTEMPTS: \"Too many attempts\"\n };\n async function storeOTP(ctx, otp) {\n if (opts.storeOTP === \"encrypted\") {\n return await symmetricEncrypt({\n key: ctx.context.secret,\n data: otp\n });\n }\n if (opts.storeOTP === \"hashed\") {\n return await defaultKeyHasher(otp);\n }\n if (typeof opts.storeOTP === \"object\" && \"hash\" in opts.storeOTP) {\n return await opts.storeOTP.hash(otp);\n }\n if (typeof opts.storeOTP === \"object\" && \"encrypt\" in opts.storeOTP) {\n return await opts.storeOTP.encrypt(otp);\n }\n return otp;\n }\n async function verifyStoredOTP(ctx, storedOtp, otp) {\n if (opts.storeOTP === \"encrypted\") {\n return await symmetricDecrypt({\n key: ctx.context.secret,\n data: storedOtp\n }) === otp;\n }\n if (opts.storeOTP === \"hashed\") {\n const hashedOtp = await defaultKeyHasher(otp);\n return hashedOtp === storedOtp;\n }\n if (typeof opts.storeOTP === \"object\" && \"hash\" in opts.storeOTP) {\n const hashedOtp = await opts.storeOTP.hash(otp);\n return hashedOtp === storedOtp;\n }\n if (typeof opts.storeOTP === \"object\" && \"decrypt\" in opts.storeOTP) {\n const decryptedOtp = await opts.storeOTP.decrypt(storedOtp);\n return decryptedOtp === otp;\n }\n return otp === storedOtp;\n }\n const endpoints = {\n /**\n * ### Endpoint\n *\n * POST `/email-otp/send-verification-otp`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.sendVerificationOTP`\n *\n * **client:**\n * `authClient.emailOtp.sendVerificationOtp`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/email-otp#api-method-email-otp-send-verification-otp)\n */\n sendVerificationOTP: createAuthEndpoint(\n \"/email-otp/send-verification-otp\",\n {\n method: \"POST\",\n body: z.object({\n email: z.string({}).meta({\n description: \"Email address to send the OTP\"\n }),\n type: z.enum(types).meta({\n description: \"Type of the OTP\"\n })\n }),\n metadata: {\n openapi: {\n description: \"Send verification OTP\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!options?.sendVerificationOTP) {\n ctx.context.logger.error(\n \"send email verification is not implemented\"\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: \"send email verification is not implemented\"\n });\n }\n const email = ctx.body.email;\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\n if (!emailRegex.test(email)) {\n throw ctx.error(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_EMAIL\n });\n }\n if (opts.disableSignUp) {\n const user = await ctx.context.internalAdapter.findUserByEmail(email);\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.USER_NOT_FOUND\n });\n }\n } else if (ctx.body.type === \"forget-password\") {\n const user = await ctx.context.internalAdapter.findUserByEmail(email);\n if (!user) {\n return ctx.json({\n success: true\n });\n }\n }\n let otp = opts.generateOTP({ email, type: ctx.body.type }, ctx.request);\n let storedOTP = await storeOTP(ctx, otp);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: `${storedOTP}:0`,\n identifier: `${ctx.body.type}-otp-${email}`,\n expiresAt: getDate(opts.expiresIn, \"sec\")\n },\n ctx\n ).catch(async (error) => {\n await ctx.context.internalAdapter.deleteVerificationByIdentifier(\n `${ctx.body.type}-otp-${email}`\n );\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: `${storedOTP}:0`,\n identifier: `${ctx.body.type}-otp-${email}`,\n expiresAt: getDate(opts.expiresIn, \"sec\")\n },\n ctx\n );\n });\n await options.sendVerificationOTP(\n {\n email,\n otp,\n type: ctx.body.type\n },\n ctx.request\n );\n return ctx.json({\n success: true\n });\n }\n )\n };\n return {\n id: \"email-otp\",\n init(ctx) {\n return {\n options: {\n emailVerification: {\n ...opts.overrideDefaultEmailVerification ? {\n async sendVerificationEmail(data, request) {\n await endpoints.sendVerificationOTP({\n //@ts-expect-error - we need to pass the context\n context: ctx,\n request,\n body: {\n email: data.user.email,\n type: \"email-verification\"\n },\n ctx\n });\n }\n } : {}\n }\n }\n };\n },\n endpoints: {\n ...endpoints,\n createVerificationOTP: createAuthEndpoint(\n \"/email-otp/create-verification-otp\",\n {\n method: \"POST\",\n body: z.object({\n email: z.string({}).meta({\n description: \"Email address to send the OTP\"\n }),\n type: z.enum(types).meta({\n required: true,\n description: \"Type of the OTP\"\n })\n }),\n metadata: {\n SERVER_ONLY: true,\n openapi: {\n description: \"Create verification OTP\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const email = ctx.body.email;\n const otp = opts.generateOTP(\n { email, type: ctx.body.type },\n ctx.request\n );\n let storedOTP = await storeOTP(ctx, otp);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: `${storedOTP}:0`,\n identifier: `${ctx.body.type}-otp-${email}`,\n expiresAt: getDate(opts.expiresIn, \"sec\")\n },\n ctx\n );\n return otp;\n }\n ),\n /**\n * ### Endpoint\n *\n * GET `/email-otp/get-verification-otp`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.getVerificationOTP`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/email-otp#api-method-email-otp-get-verification-otp)\n */\n getVerificationOTP: createAuthEndpoint(\n \"/email-otp/get-verification-otp\",\n {\n method: \"GET\",\n query: z.object({\n email: z.string({}).meta({\n description: \"Email address to get the OTP\"\n }),\n type: z.enum(types).meta({\n required: true,\n description: \"Type of the OTP\"\n })\n }),\n metadata: {\n SERVER_ONLY: true,\n openapi: {\n description: \"Get verification OTP\",\n responses: {\n \"200\": {\n description: \"OTP retrieved successfully or not found/expired\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n otp: {\n type: \"string\",\n nullable: true,\n description: \"The stored OTP, or null if not found or expired\"\n }\n },\n required: [\"otp\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const email = ctx.query.email;\n const verificationValue = await ctx.context.internalAdapter.findVerificationValue(\n `${ctx.query.type}-otp-${email}`\n );\n if (!verificationValue || verificationValue.expiresAt < /* @__PURE__ */ new Date()) {\n return ctx.json({\n otp: null\n });\n }\n if (opts.storeOTP === \"hashed\" || typeof opts.storeOTP === \"object\" && \"hash\" in opts.storeOTP) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"OTP is hashed, cannot return the plain text OTP\"\n });\n }\n let [storedOtp, _attempts] = splitAtLastColon(\n verificationValue.value\n );\n let otp = storedOtp;\n if (opts.storeOTP === \"encrypted\") {\n otp = await symmetricDecrypt({\n key: ctx.context.secret,\n data: storedOtp\n });\n }\n if (typeof opts.storeOTP === \"object\" && \"decrypt\" in opts.storeOTP) {\n otp = await opts.storeOTP.decrypt(storedOtp);\n }\n return ctx.json({\n otp\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/email-otp/verify-email`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.verifyEmailOTP`\n *\n * **client:**\n * `authClient.emailOtp.verifyEmail`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/email-otp#api-method-email-otp-verify-email)\n */\n verifyEmailOTP: createAuthEndpoint(\n \"/email-otp/verify-email\",\n {\n method: \"POST\",\n body: z.object({\n email: z.string({}).meta({\n description: \"Email address to verify\"\n }),\n otp: z.string().meta({\n required: true,\n description: \"OTP to verify\"\n })\n }),\n metadata: {\n openapi: {\n description: \"Verify email OTP\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n status: {\n type: \"boolean\",\n description: \"Indicates if the verification was successful\",\n enum: [true]\n },\n token: {\n type: \"string\",\n nullable: true,\n description: \"Session token if autoSignInAfterVerification is enabled, otherwise null\"\n },\n user: {\n $ref: \"#/components/schemas/User\"\n },\n required: [\"status\", \"token\", \"user\"]\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const email = ctx.body.email;\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\n if (!emailRegex.test(email)) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_EMAIL\n });\n }\n const verificationValue = await ctx.context.internalAdapter.findVerificationValue(\n `email-verification-otp-${email}`\n );\n if (!verificationValue) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OTP\n });\n }\n if (verificationValue.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.OTP_EXPIRED\n });\n }\n const [otpValue, attempts] = splitAtLastColon(\n verificationValue.value\n );\n const allowedAttempts = options?.allowedAttempts || 3;\n if (attempts && parseInt(attempts) >= allowedAttempts) {\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n throw new APIError(\"FORBIDDEN\", {\n message: ERROR_CODES.TOO_MANY_ATTEMPTS\n });\n }\n const verified = await verifyStoredOTP(ctx, otpValue, ctx.body.otp);\n if (!verified) {\n await ctx.context.internalAdapter.updateVerificationValue(\n verificationValue.id,\n {\n value: `${otpValue}:${parseInt(attempts || \"0\") + 1}`\n }\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OTP\n });\n }\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n const user = await ctx.context.internalAdapter.findUserByEmail(email);\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.USER_NOT_FOUND\n });\n }\n const updatedUser = await ctx.context.internalAdapter.updateUser(\n user.user.id,\n {\n email,\n emailVerified: true\n },\n ctx\n );\n await ctx.context.options.emailVerification?.onEmailVerification?.(\n updatedUser,\n ctx.request\n );\n if (ctx.context.options.emailVerification?.autoSignInAfterVerification) {\n const session = await ctx.context.internalAdapter.createSession(\n updatedUser.id,\n ctx\n );\n await setSessionCookie(ctx, {\n session,\n user: updatedUser\n });\n return ctx.json({\n status: true,\n token: session.token,\n user: {\n id: updatedUser.id,\n email: updatedUser.email,\n emailVerified: updatedUser.emailVerified,\n name: updatedUser.name,\n image: updatedUser.image,\n createdAt: updatedUser.createdAt,\n updatedAt: updatedUser.updatedAt\n }\n });\n }\n return ctx.json({\n status: true,\n token: null,\n user: {\n id: updatedUser.id,\n email: updatedUser.email,\n emailVerified: updatedUser.emailVerified,\n name: updatedUser.name,\n image: updatedUser.image,\n createdAt: updatedUser.createdAt,\n updatedAt: updatedUser.updatedAt\n }\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/sign-in/email-otp`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.signInEmailOTP`\n *\n * **client:**\n * `authClient.signIn.emailOtp`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/email-otp#api-method-sign-in-email-otp)\n */\n signInEmailOTP: createAuthEndpoint(\n \"/sign-in/email-otp\",\n {\n method: \"POST\",\n body: z.object({\n email: z.string({}).meta({\n description: \"Email address to sign in\"\n }),\n otp: z.string().meta({\n required: true,\n description: \"OTP sent to the email\"\n })\n }),\n metadata: {\n openapi: {\n description: \"Sign in with email OTP\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n token: {\n type: \"string\",\n description: \"Session token for the authenticated session\"\n },\n user: {\n $ref: \"#/components/schemas/User\"\n }\n },\n required: [\"token\", \"user\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const email = ctx.body.email;\n const verificationValue = await ctx.context.internalAdapter.findVerificationValue(\n `sign-in-otp-${email}`\n );\n if (!verificationValue) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OTP\n });\n }\n if (verificationValue.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.OTP_EXPIRED\n });\n }\n const [otpValue, attempts] = splitAtLastColon(\n verificationValue.value\n );\n const allowedAttempts = options?.allowedAttempts || 3;\n if (attempts && parseInt(attempts) >= allowedAttempts) {\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n throw new APIError(\"FORBIDDEN\", {\n message: ERROR_CODES.TOO_MANY_ATTEMPTS\n });\n }\n const verified = await verifyStoredOTP(ctx, otpValue, ctx.body.otp);\n if (!verified) {\n await ctx.context.internalAdapter.updateVerificationValue(\n verificationValue.id,\n {\n value: `${otpValue}:${parseInt(attempts || \"0\") + 1}`\n }\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OTP\n });\n }\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n const user = await ctx.context.internalAdapter.findUserByEmail(email);\n if (!user) {\n if (opts.disableSignUp) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.USER_NOT_FOUND\n });\n }\n const newUser = await ctx.context.internalAdapter.createUser(\n {\n email,\n emailVerified: true,\n name: \"\"\n },\n ctx\n );\n const session2 = await ctx.context.internalAdapter.createSession(\n newUser.id,\n ctx\n );\n await setSessionCookie(ctx, {\n session: session2,\n user: newUser\n });\n return ctx.json({\n token: session2.token,\n user: {\n id: newUser.id,\n email: newUser.email,\n emailVerified: newUser.emailVerified,\n name: newUser.name,\n image: newUser.image,\n createdAt: newUser.createdAt,\n updatedAt: newUser.updatedAt\n }\n });\n }\n if (!user.user.emailVerified) {\n await ctx.context.internalAdapter.updateUser(\n user.user.id,\n {\n emailVerified: true\n },\n ctx\n );\n }\n const session = await ctx.context.internalAdapter.createSession(\n user.user.id,\n ctx\n );\n await setSessionCookie(ctx, {\n session,\n user: user.user\n });\n return ctx.json({\n token: session.token,\n user: {\n id: user.user.id,\n email: user.user.email,\n emailVerified: user.user.emailVerified,\n name: user.user.name,\n image: user.user.image,\n createdAt: user.user.createdAt,\n updatedAt: user.user.updatedAt\n }\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/forget-password/email-otp`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.forgetPasswordEmailOTP`\n *\n * **client:**\n * `authClient.forgetPassword.emailOtp`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/email-otp#api-method-forget-password-email-otp)\n */\n forgetPasswordEmailOTP: createAuthEndpoint(\n \"/forget-password/email-otp\",\n {\n method: \"POST\",\n body: z.object({\n email: z.string().meta({\n description: \"Email address to send the OTP\"\n })\n }),\n metadata: {\n openapi: {\n description: \"Forget password with email OTP\",\n responses: {\n 200: {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\",\n description: \"Indicates if the OTP was sent successfully\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const email = ctx.body.email;\n const user = await ctx.context.internalAdapter.findUserByEmail(email);\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.USER_NOT_FOUND\n });\n }\n const otp = opts.generateOTP(\n { email, type: \"forget-password\" },\n ctx.request\n );\n let storedOTP = await storeOTP(ctx, otp);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: `${storedOTP}:0`,\n identifier: `forget-password-otp-${email}`,\n expiresAt: getDate(opts.expiresIn, \"sec\")\n },\n ctx\n );\n await options.sendVerificationOTP(\n {\n email,\n otp,\n type: \"forget-password\"\n },\n ctx.request\n );\n return ctx.json({\n success: true\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/email-otp/reset-password`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.resetPasswordEmailOTP`\n *\n * **client:**\n * `authClient.emailOtp.resetPassword`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/email-otp#api-method-email-otp-reset-password)\n */\n resetPasswordEmailOTP: createAuthEndpoint(\n \"/email-otp/reset-password\",\n {\n method: \"POST\",\n body: z.object({\n email: z.string().meta({\n description: \"Email address to reset the password\"\n }),\n otp: z.string().meta({\n description: \"OTP sent to the email\"\n }),\n password: z.string().meta({\n description: \"New password\"\n })\n }),\n metadata: {\n openapi: {\n description: \"Reset password with email OTP\",\n responses: {\n 200: {\n description: \"Success\",\n contnt: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const email = ctx.body.email;\n const user = await ctx.context.internalAdapter.findUserByEmail(\n email,\n {\n includeAccounts: true\n }\n );\n if (!user) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.USER_NOT_FOUND\n });\n }\n const verificationValue = await ctx.context.internalAdapter.findVerificationValue(\n `forget-password-otp-${email}`\n );\n if (!verificationValue) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OTP\n });\n }\n if (verificationValue.expiresAt < /* @__PURE__ */ new Date()) {\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.OTP_EXPIRED\n });\n }\n const [otpValue, attempts] = splitAtLastColon(\n verificationValue.value\n );\n const allowedAttempts = options?.allowedAttempts || 3;\n if (attempts && parseInt(attempts) >= allowedAttempts) {\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n throw new APIError(\"FORBIDDEN\", {\n message: ERROR_CODES.TOO_MANY_ATTEMPTS\n });\n }\n const verified = await verifyStoredOTP(ctx, otpValue, ctx.body.otp);\n if (!verified) {\n await ctx.context.internalAdapter.updateVerificationValue(\n verificationValue.id,\n {\n value: `${otpValue}:${parseInt(attempts || \"0\") + 1}`\n }\n );\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_OTP\n });\n }\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n const passwordHash = await ctx.context.password.hash(\n ctx.body.password\n );\n const account = user.accounts.find(\n (account2) => account2.providerId === \"credential\"\n );\n if (!account) {\n await ctx.context.internalAdapter.createAccount(\n {\n userId: user.user.id,\n providerId: \"credential\",\n accountId: user.user.id,\n password: passwordHash\n },\n ctx\n );\n } else {\n await ctx.context.internalAdapter.updatePassword(\n user.user.id,\n passwordHash,\n ctx\n );\n }\n if (!user.user.emailVerified) {\n await ctx.context.internalAdapter.updateUser(\n user.user.id,\n {\n emailVerified: true\n },\n ctx\n );\n }\n return ctx.json({\n success: true\n });\n }\n )\n },\n hooks: {\n after: [\n {\n matcher(context) {\n return !!(context.path?.startsWith(\"/sign-up\") && opts.sendVerificationOnSignUp);\n },\n handler: createAuthMiddleware(async (ctx) => {\n const response = await getEndpointResponse(ctx);\n const email = response?.user.email;\n if (email) {\n const otp = opts.generateOTP(\n { email, type: ctx.body.type },\n ctx.request\n );\n let storedOTP = await storeOTP(ctx, otp);\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: `${storedOTP}:0`,\n identifier: `email-verification-otp-${email}`,\n expiresAt: getDate(opts.expiresIn, \"sec\")\n },\n ctx\n );\n await options.sendVerificationOTP(\n {\n email,\n otp,\n type: \"email-verification\"\n },\n ctx.request\n );\n }\n })\n }\n ]\n },\n $ERROR_CODES: ERROR_CODES,\n rateLimit: [\n {\n pathMatcher(path) {\n return path === \"/email-otp/send-verification-otp\";\n },\n window: 60,\n max: 3\n },\n {\n pathMatcher(path) {\n return path === \"/email-otp/verify-email\";\n },\n window: 60,\n max: 3\n },\n {\n pathMatcher(path) {\n return path === \"/sign-in/email-otp\";\n },\n window: 60,\n max: 3\n }\n ]\n };\n};\n\nexport { emailOTP };\n","import * as z from 'zod/v4';\nimport { APIError } from 'better-call';\nimport { j as createAuthEndpoint } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport { setSessionCookie } from '../../cookies/index.mjs';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-auth/utils/hash';\nimport '@better-auth/utils/base64';\nimport '../../crypto/index.mjs';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '@better-fetch/fetch';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'jose/errors';\n\nfunction toBoolean(value) {\n return value === \"true\" || value === true;\n}\n\nconst oneTap = (options) => ({\n id: \"one-tap\",\n endpoints: {\n oneTapCallback: createAuthEndpoint(\n \"/one-tap/callback\",\n {\n method: \"POST\",\n body: z.object({\n idToken: z.string().meta({\n description: \"Google ID token, which the client obtains from the One Tap API\"\n })\n }),\n metadata: {\n openapi: {\n summary: \"One tap callback\",\n description: \"Use this endpoint to authenticate with Google One Tap\",\n responses: {\n 200: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n session: {\n $ref: \"#/components/schemas/Session\"\n },\n user: {\n $ref: \"#/components/schemas/User\"\n }\n }\n }\n }\n }\n },\n 400: {\n description: \"Invalid token\"\n }\n }\n }\n }\n },\n async (ctx) => {\n const { idToken } = ctx.body;\n let payload;\n try {\n const JWKS = createRemoteJWKSet(\n new URL(\"https://www.googleapis.com/oauth2/v3/certs\")\n );\n const { payload: verifiedPayload } = await jwtVerify(\n idToken,\n JWKS,\n {\n issuer: [\"https://accounts.google.com\", \"accounts.google.com\"],\n audience: options?.clientId || ctx.context.options.socialProviders?.google?.clientId\n }\n );\n payload = verifiedPayload;\n } catch (error) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"invalid id token\"\n });\n }\n const { email, email_verified, name, picture, sub } = payload;\n if (!email) {\n return ctx.json({ error: \"Email not available in token\" });\n }\n const user = await ctx.context.internalAdapter.findUserByEmail(email);\n if (!user) {\n if (options?.disableSignup) {\n throw new APIError(\"BAD_GATEWAY\", {\n message: \"User not found\"\n });\n }\n const newUser = await ctx.context.internalAdapter.createOAuthUser(\n {\n email,\n emailVerified: typeof email_verified === \"boolean\" ? email_verified : toBoolean(email_verified),\n name,\n image: picture\n },\n {\n providerId: \"google\",\n accountId: sub\n },\n ctx\n );\n if (!newUser) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Could not create user\"\n });\n }\n const session2 = await ctx.context.internalAdapter.createSession(\n newUser.user.id,\n ctx\n );\n await setSessionCookie(ctx, {\n user: newUser.user,\n session: session2\n });\n return ctx.json({\n token: session2.token,\n user: {\n id: newUser.user.id,\n email: newUser.user.email,\n emailVerified: newUser.user.emailVerified,\n name: newUser.user.name,\n image: newUser.user.image,\n createdAt: newUser.user.createdAt,\n updatedAt: newUser.user.updatedAt\n }\n });\n }\n const account = await ctx.context.internalAdapter.findAccount(sub);\n if (!account) {\n const accountLinking = ctx.context.options.account?.accountLinking;\n const shouldLinkAccount = accountLinking?.enabled && (accountLinking.trustedProviders?.includes(\"google\") || email_verified);\n if (shouldLinkAccount) {\n await ctx.context.internalAdapter.linkAccount({\n userId: user.user.id,\n providerId: \"google\",\n accountId: sub,\n scope: \"openid,profile,email\",\n idToken\n });\n } else {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Google sub doesn't match\"\n });\n }\n }\n const session = await ctx.context.internalAdapter.createSession(\n user.user.id,\n ctx\n );\n await setSessionCookie(ctx, {\n user: user.user,\n session\n });\n return ctx.json({\n token: session.token,\n user: {\n id: user.user.id,\n email: user.user.email,\n emailVerified: user.user.emailVerified,\n name: user.user.name,\n image: user.user.image,\n createdAt: user.user.createdAt,\n updatedAt: user.user.updatedAt\n }\n });\n }\n )\n }\n});\n\nexport { oneTap };\n","import * as z from 'zod/v4';\nimport 'better-call';\nimport { i as createAuthMiddleware, j as createAuthEndpoint, o as originCheck } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport { e as env } from '../../shared/better-auth.8zoxzg-F.mjs';\nimport '@better-auth/utils/base64';\nimport '@better-auth/utils/hmac';\nimport { g as getOrigin } from '../../shared/better-auth.VTXNLFMT.mjs';\nimport '@better-auth/utils/binary';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { symmetricEncrypt, symmetricDecrypt } from '../../crypto/index.mjs';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-auth/utils/hash';\nimport '@better-fetch/fetch';\nimport 'jose';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '../../cookies/index.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport 'jose/errors';\n\nfunction getVenderBaseURL() {\n const vercel = env.VERCEL_URL ? `https://${env.VERCEL_URL}` : void 0;\n const netlify = env.NETLIFY_URL;\n const render = env.RENDER_URL;\n const aws = env.AWS_LAMBDA_FUNCTION_NAME;\n const google = env.GOOGLE_CLOUD_FUNCTION_NAME;\n const azure = env.AZURE_FUNCTION_NAME;\n return vercel || netlify || render || aws || google || azure;\n}\nconst oAuthProxy = (opts) => {\n const resolveCurrentURL = (ctx) => {\n return new URL(\n opts?.currentURL || ctx.request?.url || getVenderBaseURL() || ctx.context.baseURL\n );\n };\n return {\n id: \"oauth-proxy\",\n endpoints: {\n oAuthProxy: createAuthEndpoint(\n \"/oauth-proxy-callback\",\n {\n method: \"GET\",\n query: z.object({\n callbackURL: z.string().meta({\n description: \"The URL to redirect to after the proxy\"\n }),\n cookies: z.string().meta({\n description: \"The cookies to set after the proxy\"\n })\n }),\n use: [originCheck((ctx) => ctx.query.callbackURL)],\n metadata: {\n openapi: {\n description: \"OAuth Proxy Callback\",\n parameters: [\n {\n in: \"query\",\n name: \"callbackURL\",\n required: true,\n description: \"The URL to redirect to after the proxy\"\n },\n {\n in: \"query\",\n name: \"cookies\",\n required: true,\n description: \"The cookies to set after the proxy\"\n }\n ],\n responses: {\n 302: {\n description: \"Redirect\",\n headers: {\n Location: {\n description: \"The URL to redirect to\",\n schema: {\n type: \"string\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const cookies = ctx.query.cookies;\n const decryptedCookies = await symmetricDecrypt({\n key: ctx.context.secret,\n data: cookies\n }).catch((e) => {\n ctx.context.logger.error(e);\n return null;\n });\n const error = ctx.context.options.onAPIError?.errorURL || `${ctx.context.options.baseURL}/api/auth/error`;\n if (!decryptedCookies) {\n throw ctx.redirect(\n `${error}?error=OAuthProxy - Invalid cookies or secret`\n );\n }\n const isSecureContext = resolveCurrentURL(ctx).protocol === \"https:\";\n const prefix = ctx.context.options.advanced?.cookiePrefix || \"better-auth\";\n const cookieToSet = isSecureContext ? decryptedCookies : decryptedCookies.replace(\"Secure;\", \"\").replace(`__Secure-${prefix}`, prefix);\n ctx.setHeader(\"set-cookie\", cookieToSet);\n throw ctx.redirect(ctx.query.callbackURL);\n }\n )\n },\n hooks: {\n after: [\n {\n matcher(context) {\n return context.path?.startsWith(\"/callback\") || context.path?.startsWith(\"/oauth2/callback\");\n },\n handler: createAuthMiddleware(async (ctx) => {\n const headers = ctx.context.responseHeaders;\n const location = headers?.get(\"location\");\n if (location?.includes(\"/oauth-proxy-callback?callbackURL\")) {\n if (!location.startsWith(\"http\")) {\n return;\n }\n const locationURL = new URL(location);\n const origin = locationURL.origin;\n if (origin === getOrigin(ctx.context.baseURL)) {\n const newLocation = locationURL.searchParams.get(\"callbackURL\");\n if (!newLocation) {\n return;\n }\n ctx.setHeader(\"location\", newLocation);\n return;\n }\n const setCookies = headers?.get(\"set-cookie\");\n if (!setCookies) {\n return;\n }\n const encryptedCookies = await symmetricEncrypt({\n key: ctx.context.secret,\n data: setCookies\n });\n const locationWithCookies = `${location}&cookies=${encodeURIComponent(\n encryptedCookies\n )}`;\n ctx.setHeader(\"location\", locationWithCookies);\n }\n })\n }\n ],\n before: [\n {\n matcher(context) {\n return context.path?.startsWith(\"/sign-in/social\") || context.path?.startsWith(\"/sign-in/oauth2\");\n },\n handler: createAuthMiddleware(async (ctx) => {\n const skipProxy = ctx.request?.headers.get(\"x-skip-oauth-proxy\");\n if (skipProxy) {\n return;\n }\n const url = resolveCurrentURL(ctx);\n const productionURL = opts?.productionURL || env.BETTER_AUTH_URL;\n if (productionURL === ctx.context.options.baseURL) {\n return;\n }\n ctx.body.callbackURL = `${url.origin}${ctx.context.options.basePath || \"/api/auth\"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(\n ctx.body.callbackURL || ctx.context.baseURL\n )}`;\n return {\n context: ctx\n };\n })\n }\n ]\n }\n };\n};\n\nexport { oAuthProxy };\n","import * as z from 'zod/v4';\nimport 'better-call';\nimport { j as createAuthEndpoint, m as getSession } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '@better-auth/utils/base64';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '@better-auth/utils/hash';\nimport '../../crypto/index.mjs';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '@better-fetch/fetch';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../cookies/index.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport 'jose/errors';\n\nconst customSession = (fn, options) => {\n return {\n id: \"custom-session\",\n endpoints: {\n getSession: createAuthEndpoint(\n \"/get-session\",\n {\n method: \"GET\",\n query: z.optional(\n z.object({\n /**\n * If cookie cache is enabled, it will disable the cache\n * and fetch the session from the database\n */\n disableCookieCache: z.boolean().meta({\n description: \"Disable cookie cache and fetch session from database\"\n }).or(z.string().transform((v) => v === \"true\")).optional(),\n disableRefresh: z.boolean().meta({\n description: \"Disable session refresh. Useful for checking session status, without updating the session\"\n }).optional()\n })\n ),\n metadata: {\n CUSTOM_SESSION: true,\n openapi: {\n description: \"Get custom session data\",\n responses: {\n \"200\": {\n description: \"Success\",\n content: {\n \"application/json\": {\n schema: {\n type: \"array\",\n nullable: true,\n items: {\n $ref: \"#/components/schemas/Session\"\n }\n }\n }\n }\n }\n }\n }\n },\n requireHeaders: true\n },\n async (ctx) => {\n const session = await getSession()({\n ...ctx,\n asResponse: false,\n headers: ctx.headers,\n returnHeaders: true\n }).catch((e) => {\n return null;\n });\n if (!session?.response) {\n return ctx.json(null);\n }\n const fnResult = await fn(session.response, ctx);\n session.headers.forEach((value, key) => {\n ctx.setHeader(key, value);\n });\n return ctx.json(fnResult);\n }\n )\n }\n };\n};\n\nexport { customSession };\n","import { ZodObject, ZodType, ZodOptional, z, ZodString, ZodNumber, ZodBoolean, ZodArray } from 'zod/v4';\nimport { getEndpoints } from '../../api/index.mjs';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '@better-auth/utils/random';\nimport { APIError } from 'better-call';\nimport '@better-auth/utils/hash';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport '@better-auth/utils/base64';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport { g as getAuthTables } from '../../shared/better-auth.DORkW_Ge.mjs';\nimport 'kysely';\nimport { j as createAuthEndpoint } from '../../shared/better-auth.D4HhkCZJ.mjs';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport 'defu';\nimport '../../cookies/index.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DcfNPS8q.mjs';\nimport '../../crypto/index.mjs';\nimport '@better-fetch/fetch';\nimport 'jose/errors';\n\nfunction getTypeFromZodType(zodType) {\n if (zodType instanceof ZodString) {\n return \"string\";\n } else if (zodType instanceof ZodNumber) {\n return \"number\";\n } else if (zodType instanceof ZodBoolean) {\n return \"boolean\";\n } else if (zodType instanceof ZodObject) {\n return \"object\";\n } else if (zodType instanceof ZodArray) {\n return \"array\";\n }\n return \"string\";\n}\nfunction getFieldSchema(field) {\n const schema = {\n type: field.type === \"date\" ? \"string\" : field.type\n };\n if (field.defaultValue !== void 0) {\n schema.default = typeof field.defaultValue === \"function\" ? \"Generated at runtime\" : field.defaultValue;\n }\n if (field.input === false) {\n schema.readOnly = true;\n }\n return schema;\n}\nfunction getParameters(options) {\n const parameters = [];\n if (options.metadata?.openapi?.parameters) {\n parameters.push(...options.metadata.openapi.parameters);\n return parameters;\n }\n if (options.query instanceof ZodObject) {\n Object.entries(options.query.shape).forEach(([key, value]) => {\n if (value instanceof ZodType) {\n parameters.push({\n name: key,\n in: \"query\",\n schema: {\n type: getTypeFromZodType(value),\n ...\"minLength\" in value && value.minLength ? {\n minLength: value.minLength\n } : {},\n description: value.description\n }\n });\n }\n });\n }\n return parameters;\n}\nfunction getRequestBody(options) {\n if (options.metadata?.openapi?.requestBody) {\n return options.metadata.openapi.requestBody;\n }\n if (!options.body) return void 0;\n if (options.body instanceof ZodObject || options.body instanceof ZodOptional) {\n const shape = options.body.shape;\n if (!shape) return void 0;\n const properties = {};\n const required = [];\n Object.entries(shape).forEach(([key, value]) => {\n if (value instanceof ZodType) {\n properties[key] = {\n type: getTypeFromZodType(value),\n description: value.description\n };\n if (!(value instanceof z.ZodOptional)) {\n required.push(key);\n }\n }\n });\n return {\n required: options.body instanceof ZodOptional ? false : options.body ? true : false,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties,\n required\n }\n }\n }\n };\n }\n return void 0;\n}\nfunction getResponse(responses) {\n return {\n \"400\": {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\"\n }\n },\n required: [\"message\"]\n }\n }\n },\n description: \"Bad Request. Usually due to missing parameters, or invalid parameters.\"\n },\n \"401\": {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\"\n }\n },\n required: [\"message\"]\n }\n }\n },\n description: \"Unauthorized. Due to missing or invalid authentication.\"\n },\n \"403\": {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\"\n }\n }\n }\n }\n },\n description: \"Forbidden. You do not have permission to access this resource or to perform this action.\"\n },\n \"404\": {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\"\n }\n }\n }\n }\n },\n description: \"Not Found. The requested resource was not found.\"\n },\n \"429\": {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\"\n }\n }\n }\n }\n },\n description: \"Too Many Requests. You have exceeded the rate limit. Try again later.\"\n },\n \"500\": {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: {\n type: \"string\"\n }\n }\n }\n }\n },\n description: \"Internal Server Error. This is a problem with the server that you cannot fix.\"\n },\n ...responses\n };\n}\nfunction toOpenApiPath(path) {\n return path.split(\"/\").map((part) => part.startsWith(\":\") ? `{${part.slice(1)}}` : part).join(\"/\");\n}\nasync function generator(ctx, options) {\n const baseEndpoints = getEndpoints(ctx, {\n ...options,\n plugins: []\n });\n const tables = getAuthTables(options);\n const models = Object.entries(tables).reduce((acc, [key, value]) => {\n const modelName = key.charAt(0).toUpperCase() + key.slice(1);\n const fields = value.fields;\n const required = [];\n const properties = {\n id: { type: \"string\" }\n };\n Object.entries(fields).forEach(([fieldKey, fieldValue]) => {\n if (!fieldValue) return;\n properties[fieldKey] = getFieldSchema(fieldValue);\n if (fieldValue.required && fieldValue.input !== false) {\n required.push(fieldKey);\n }\n });\n acc[modelName] = {\n type: \"object\",\n properties,\n ...required.length > 0 ? { required } : {}\n };\n return acc;\n }, {});\n const components = {\n schemas: {\n ...models\n }\n };\n const paths = {};\n Object.entries(baseEndpoints.api).forEach(([_, value]) => {\n if (ctx.options.disabledPaths?.includes(value.path)) return;\n const options2 = value.options;\n if (options2.metadata?.SERVER_ONLY) return;\n const path = toOpenApiPath(value.path);\n if (options2.method === \"GET\") {\n paths[path] = {\n get: {\n tags: [\"Default\", ...options2.metadata?.openapi?.tags || []],\n description: options2.metadata?.openapi?.description,\n operationId: options2.metadata?.openapi?.operationId,\n security: [\n {\n bearerAuth: []\n }\n ],\n parameters: getParameters(options2),\n responses: getResponse(options2.metadata?.openapi?.responses)\n }\n };\n }\n if (options2.method === \"POST\") {\n const body = getRequestBody(options2);\n paths[path] = {\n post: {\n tags: [\"Default\", ...options2.metadata?.openapi?.tags || []],\n description: options2.metadata?.openapi?.description,\n operationId: options2.metadata?.openapi?.operationId,\n security: [\n {\n bearerAuth: []\n }\n ],\n parameters: getParameters(options2),\n ...body ? { requestBody: body } : {\n requestBody: {\n //set body none\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {}\n }\n }\n }\n }\n },\n responses: getResponse(options2.metadata?.openapi?.responses)\n }\n };\n }\n });\n for (const plugin of options.plugins || []) {\n if (plugin.id === \"open-api\") {\n continue;\n }\n const pluginEndpoints = getEndpoints(ctx, {\n ...options,\n plugins: [plugin]\n });\n const api = Object.keys(pluginEndpoints.api).map((key) => {\n if (baseEndpoints.api[key] === void 0) {\n return pluginEndpoints.api[key];\n }\n return null;\n }).filter((x) => x !== null);\n Object.entries(api).forEach(([key, value]) => {\n if (ctx.options.disabledPaths?.includes(value.path)) return;\n const options2 = value.options;\n if (options2.metadata?.SERVER_ONLY) return;\n const path = toOpenApiPath(value.path);\n if (options2.method === \"GET\") {\n paths[path] = {\n get: {\n tags: options2.metadata?.openapi?.tags || [\n plugin.id.charAt(0).toUpperCase() + plugin.id.slice(1)\n ],\n description: options2.metadata?.openapi?.description,\n operationId: options2.metadata?.openapi?.operationId,\n security: [\n {\n bearerAuth: []\n }\n ],\n parameters: getParameters(options2),\n responses: getResponse(options2.metadata?.openapi?.responses)\n }\n };\n }\n if (options2.method === \"POST\") {\n paths[path] = {\n post: {\n tags: options2.metadata?.openapi?.tags || [\n plugin.id.charAt(0).toUpperCase() + plugin.id.slice(1)\n ],\n description: options2.metadata?.openapi?.description,\n operationId: options2.metadata?.openapi?.operationId,\n security: [\n {\n bearerAuth: []\n }\n ],\n parameters: getParameters(options2),\n requestBody: getRequestBody(options2),\n responses: getResponse(options2.metadata?.openapi?.responses)\n }\n };\n }\n });\n }\n const res = {\n openapi: \"3.1.1\",\n info: {\n title: \"Better Auth\",\n description: \"API Reference for your Better Auth Instance\",\n version: \"1.1.0\"\n },\n components: {\n ...components,\n securitySchemes: {\n apiKeyCookie: {\n type: \"apiKey\",\n in: \"cookie\",\n name: \"apiKeyCookie\",\n description: \"API Key authentication via cookie\"\n },\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n description: \"Bearer token authentication\"\n }\n }\n },\n security: [\n {\n apiKeyCookie: [],\n bearerAuth: []\n }\n ],\n servers: [\n {\n url: ctx.baseURL\n }\n ],\n tags: [\n {\n name: \"Default\",\n description: \"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.\"\n }\n ],\n paths\n };\n return res;\n}\n\nconst logo = `<svg width=\"75\" height=\"75\" viewBox=\"0 0 75 75\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n<rect width=\"75\" height=\"75\" fill=\"url(#pattern0_21_12)\"/>\n<defs>\n<pattern id=\"pattern0_21_12\" patternContentUnits=\"objectBoundingBox\" width=\"1\" height=\"1\">\n<use xlink:href=\"#image0_21_12\" transform=\"scale(0.00094697)\"/>\n</pattern>\n<image id=\"image0_21_12\" width=\"1056\" height=\"1056\" xlink:href=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAEIKADAAQAAAABAAAEIAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/+ICKElDQ19QUk9GSUxFAAEBAAACGGFwcGwEAAAAbW50clJHQiBYWVogB+Y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hJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9sAQwACAgICAgIDAgIDBAMDAwQFBAQEBAUHBQUFBQUHCAcHBwcHBwgICAgICAgICgoKCgoKCwsLCwsNDQ0NDQ0NDQ0N/9sAQwECAgIDAwMGAwMGDQkHCQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0N/90ABABC/9oADAMBAAIRAxEAPwD9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//Q/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0f38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9L9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//T/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1P38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9X9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//W/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//R/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9P9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//U/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1f38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9b9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//X/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0P38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9H9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//S/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9T9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//V/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Ln/gq38a/in8Dvgp4T8R/CfxFdeG9SvvFMdlcXFoELyW5srqQxnzEcY3op4Gciv1Gr8Z/+C2X/JvXgj/sc4v/AE33lAH4z/8ADwv9tD/oq2tf9823/wAZo/4eF/tof9FW1r/vm2/+M18Z0UAfZn/Dwv8AbQ/6KtrX/fNt/wDGaP8Ah4X+2h/0VbWv++bb/wCM18Z0UAfZn/Dwv9tD/oq2tf8AfNt/8Zo/4eF/tof9FW1r/vm2/wDjNfGdFAH2Z/w8L/bQ/wCira1/3zbf/GaP+Hhf7aH/AEVbWv8Avm2/+M18Z0UAfZn/AA8L/bQ/6KtrX/fNt/8AGaP+Hhf7aH/RVta/75tv/jNfGdFAH2Z/w8L/AG0P+ira1/3zbf8Axmj/AIeF/tof9FW1r/vm2/8AjNfGdFAH63/sVftq/tTfEb9qb4deCfG3xF1TVtD1bVGgvbKdYBHPGIJW2ttiVsblB4I6V/UbX8Z//BP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bL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooA+zP+Cen/J6Hwp/7DTf+k01f2YV/Gf8A8E9P+T0PhT/2Gm/9Jpq/swoAKKKKACiiigAooooAKKKKACiiigAooooA/gDooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD7M/4J6f8nofCn/sNN/6TTV/ZhX8Z/wDwT0/5PQ+FP/Yab/0mmr+zCgAooooAKKKKACiiigAooooAKKKKACiiigD+AOiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/0f38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+M/wDwWy/5N68Ef9jnF/6b7ygD+ZuiiigAooooAKKKKACiiigAooooAKKKKAPsz/gnp/yeh8Kf+w03/pNNX9mFfxn/APBPT/k9D4U/9hpv/Saav7MKACiiigAooooAKKKKACiiigAooooAKKKKAP4A6KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP6ZP+CJv/JvXjf/ALHOX/032dfsxX4z/wDBE3/k3rxv/wBjnL/6b7Ov2YoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/S/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooA+zP+Cen/J6Hwp/7DTf+k01f2YV/Gf8A8E9P+T0PhT/2Gm/9Jpq/swoAKKKKACiiigAooooAKKKKACiiigAooooA/gDooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD7M/4J6f8nofCn/sNN/6TTV/ZhX8Z/wDwT0/5PQ+FP/Yab/0mmr+zCgAooooAKKKKACiiigAooooAKKKKACiiigD+AOiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/1P38ooooAKKKKACii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9KG4kQxRyZkMaomcueigYoA8FooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/AOxzl/8ATfZ1+zFfjP8A8ETf+TevG/8A2Ocv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//9X9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/v8ooooAKKKKACiiigAooooAKKKKACiiigAr+M//goX/wAnofFb/sNL/wCk0Nf2YV/Gf/wUL/5PQ+K3/YaX/wBJoaAPjOiiigAooooAKKKKACiiigAooooAKKKKAP6ZP+CJv/JvXjf/ALHOX/032dfsxX4z/wDBE3/k3rxv/wBjnL/6b7Ov2YoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/W/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP7/KKKKACiiigAooooAKKKKACiiigAooooAK/jP/4KF/8AJ6HxW/7DS/8ApNDX9mFfxn/8FC/+T0Pit/2Gl/8ASaGgD4zooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/1/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+M/wDwWy/5N68Ef9jnF/6b7ygD+ZuiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+/yiiigAooooAKKKKACiiigAooooAKKKKACv4z/+Chf/ACeh8Vv+w0v/AKTQ1/ZhX8Z//BQv/k9D4rf9hpf/AEmhoA+M6KKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/v8ooooAKKKKACiiigAooooAKKKKACiiigAr+M//goX/wAnofFb/sNL/wCk0Nf2YV/Gf/wUL/5PQ+K3/YaX/wBJoaAPjOiiigAooooAKKKKACiiigAooooAKKKKAP6ZP+CJv/JvXjf/ALHOX/032dfsxX4z/wDBE3/k3rxv/wBjnL/6b7Ov2YoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/R/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP7/KKKKACiiigAooooAKKKKACiiigAooooAK/jP/4KF/8AJ6HxW/7DS/8ApNDX9mFfxn/8FC/+T0Pit/2Gl/8ASaGgD4zooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/0v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+M/wDwWy/5N68Ef9jnF/6b7ygD+ZuiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+/yiiigAooooAKKKKACiiigAooooAKKKKACv4z/+Chf/ACeh8Vv+w0v/AKTQ1/ZhX8Z//BQv/k9D4rf9hpf/AEmhoA+M6KKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD1L4KfCjW/jj8U/Dvwn8OXdrY6l4kujaW9xelxbxuI2kzIY1d8YQ9FJzX6jf8OTf2hf8Aod/Bn/f3UP8A5Cr4z/4J6f8AJ6Hwp/7DTf8ApNNX9mFAH8zf/Dk39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sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooA+zP+Cen/J6Hwp/7DTf+k01f2YV/Gf8A8E9P+T0PhT/2Gm/9Jpq/swoAKKKKACiiigAooooAKKKKACiiigAooooA/gDooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD7M/4J6f8nofCn/sNN/6TTV/ZhX8Z/wDwT0/5PQ+FP/Yab/0mmr+zCgAooooAKKKKACiiigAooooAKKKKACiiigD+AOiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/1v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+M/wDwWy/5N68Ef9jnF/6b7ygD+ZuiiigAooooAKKKKACiiigAooooAKKKKAPsz/gnp/yeh8Kf+w03/pNNX9mFfxn/APBPT/k9D4U/9hpv/Saav7MKACiiigAooooAKKKKACiiigAooooAKKKKAP4A6KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP6ZP+CJv/JvXjf/ALHOX/032dfsxX4z/wDBE3/k3rxv/wBjnL/6b7Ov2YoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/X/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooA+zP+Cen/J6Hwp/7DTf+k01f2YV/Gf8A8E9P+T0PhT/2Gm/9Jpq/swoAKKKKACiiigAooooAKKKKACiiigAooooA/gDooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD7M/4J6f8nofCn/sNN/6TTV/ZhX8Z/wDwT0/5PQ+FP/Yab/0mmr+zCgAooooAKKKKACiiigAooooAKKKKACiiigD+AOiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACi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4zor7M/4d6ftof9Ep1r/vq2/wDj1H/DvT9tD/olOtf99W3/AMeoA+M6K+zP+Hen7aH/AESnWv8Avq2/+PUf8O9P20P+iU61/wB9W3/x6gD4zor7M/4d6ftof9Ep1r/vq2/+PUf8O9P20P8AolOtf99W3/x6gD4zor7M/wCHen7aH/RKda/76tv/AI9R/wAO9P20P+iU61/31bf/AB6gD9mP+CJv/JvXjf8A7HOX/wBN9nX7MV+XP/BKT4KfFP4HfBTxZ4c+LHh268N6lfeKZL23t7soXktzZWsYkHlu4xvRhyc5FfqNQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9L9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//T/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1P38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9X9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//W/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//R/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9P9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//U/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1f38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9b9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//X/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0P38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9H9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//S/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9T9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//V/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9f9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//Q/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/2Q==\"/>\n</defs>\n</svg>\n`;\n\nconst getHTML = (apiReference) => `<!doctype html>\n<html>\n <head>\n <title>Scalar API Reference</title>\n <meta charset=\"utf-8\" />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1\" />\n </head>\n <body>\n <script\n id=\"api-reference\"\n type=\"application/json\">\n ${JSON.stringify(apiReference)}\n <\\/script>\n\t <script>\n var configuration = {\n\t \tfavicon: \"data:image/svg+xml;utf8,${encodeURIComponent(logo)}\",\n\t \ttheme: \"saturn\",\n metaData: {\n\t\t\ttitle: \"Better Auth API\",\n\t\t\tdescription: \"API Reference for your Better Auth Instance\",\n\t\t}\n }\n\n document.getElementById('api-reference').dataset.configuration =\n JSON.stringify(configuration)\n <\\/script>\n\t <script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"><\\/script>\n </body>\n</html>`;\nconst openAPI = (options) => {\n const path = options?.path ?? \"/reference\";\n return {\n id: \"open-api\",\n endpoints: {\n generateOpenAPISchema: createAuthEndpoint(\n \"/open-api/generate-schema\",\n {\n method: \"GET\"\n },\n async (ctx) => {\n const schema = await generator(ctx.context, ctx.context.options);\n return ctx.json(schema);\n }\n ),\n openAPIReference: createAuthEndpoint(\n path,\n {\n method: \"GET\",\n metadata: {\n isAction: false\n }\n },\n async (ctx) => {\n if (options?.disableDefaultReference) {\n throw new APIError(\"NOT_FOUND\");\n }\n const schema = await generator(ctx.context, ctx.context.options);\n return new Response(getHTML(schema), {\n headers: {\n \"Content-Type\": \"text/html\"\n }\n });\n }\n )\n }\n };\n};\n\nexport { openAPI };\n","import * as z from 'zod/v4';\nimport { SignJWT } from 'jose';\nimport { APIError } from 'better-call';\nimport { k as getSessionFromCtx, j as createAuthEndpoint, i as createAuthMiddleware, l as sessionMiddleware } from './better-auth.D4HhkCZJ.mjs';\nimport './better-auth.8zoxzg-F.mjs';\nimport { base64Url, base64 } from '@better-auth/utils/base64';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport { parseSetCookieHeader } from '../cookies/index.mjs';\nimport './better-auth.n2KFGwjY.mjs';\nimport './better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { symmetricEncrypt, symmetricDecrypt } from '../crypto/index.mjs';\nimport { createHash } from '@better-auth/utils/hash';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport { g as generateRandomString } from './better-auth.B4Qoxdgc.mjs';\nimport { getJwtToken } from '../plugins/jwt/index.mjs';\n\nconst schema = {\n oauthApplication: {\n modelName: \"oauthApplication\",\n fields: {\n name: {\n type: \"string\"\n },\n icon: {\n type: \"string\",\n required: false\n },\n metadata: {\n type: \"string\",\n required: false\n },\n clientId: {\n type: \"string\",\n unique: true\n },\n clientSecret: {\n type: \"string\",\n required: false\n },\n redirectURLs: {\n type: \"string\"\n },\n type: {\n type: \"string\"\n },\n disabled: {\n type: \"boolean\",\n required: false,\n defaultValue: false\n },\n userId: {\n type: \"string\",\n required: false\n },\n createdAt: {\n type: \"date\"\n },\n updatedAt: {\n type: \"date\"\n }\n }\n },\n oauthAccessToken: {\n modelName: \"oauthAccessToken\",\n fields: {\n accessToken: {\n type: \"string\",\n unique: true\n },\n refreshToken: {\n type: \"string\",\n unique: true\n },\n accessTokenExpiresAt: {\n type: \"date\"\n },\n refreshTokenExpiresAt: {\n type: \"date\"\n },\n clientId: {\n type: \"string\"\n },\n userId: {\n type: \"string\",\n required: false\n },\n scopes: {\n type: \"string\"\n },\n createdAt: {\n type: \"date\"\n },\n updatedAt: {\n type: \"date\"\n }\n }\n },\n oauthConsent: {\n modelName: \"oauthConsent\",\n fields: {\n clientId: {\n type: \"string\"\n },\n userId: {\n type: \"string\"\n },\n scopes: {\n type: \"string\"\n },\n createdAt: {\n type: \"date\"\n },\n updatedAt: {\n type: \"date\"\n },\n consentGiven: {\n type: \"boolean\"\n }\n }\n }\n};\n\nfunction formatErrorURL(url, error, description) {\n return `${url.includes(\"?\") ? \"&\" : \"?\"}error=${error}&error_description=${description}`;\n}\nfunction getErrorURL(ctx, error, description) {\n const baseURL = ctx.context.options.onAPIError?.errorURL || `${ctx.context.baseURL}/error`;\n const formattedURL = formatErrorURL(baseURL, error, description);\n return formattedURL;\n}\nasync function authorize(ctx, options) {\n const handleRedirect = (url) => {\n const fromFetch = ctx.request?.headers.get(\"sec-fetch-mode\") === \"cors\";\n if (fromFetch) {\n return ctx.json({\n redirect: true,\n url\n });\n } else {\n throw ctx.redirect(url);\n }\n };\n const opts = {\n codeExpiresIn: 600,\n defaultScope: \"openid\",\n ...options,\n scopes: [\n \"openid\",\n \"profile\",\n \"email\",\n \"offline_access\",\n ...options?.scopes || []\n ]\n };\n if (!ctx.request) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"request not found\",\n error: \"invalid_request\"\n });\n }\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n await ctx.setSignedCookie(\n \"oidc_login_prompt\",\n JSON.stringify(ctx.query),\n ctx.context.secret,\n {\n maxAge: 600,\n path: \"/\",\n sameSite: \"lax\"\n }\n );\n const queryFromURL = ctx.request.url?.split(\"?\")[1];\n return handleRedirect(`${options.loginPage}?${queryFromURL}`);\n }\n const query = ctx.query;\n if (!query.client_id) {\n const errorURL = getErrorURL(\n ctx,\n \"invalid_client\",\n \"client_id is required\"\n );\n throw ctx.redirect(errorURL);\n }\n if (!query.response_type) {\n getErrorURL(\n ctx,\n \"invalid_request\",\n \"response_type is required\"\n );\n throw ctx.redirect(\n getErrorURL(ctx, \"invalid_request\", \"response_type is required\")\n );\n }\n const client = await getClient(\n ctx.query.client_id,\n ctx.context.adapter,\n options.trustedClients || []\n );\n if (!client) {\n const errorURL = getErrorURL(\n ctx,\n \"invalid_client\",\n \"client_id is required\"\n );\n throw ctx.redirect(errorURL);\n }\n const redirectURI = client.redirectURLs.find(\n (url) => url === ctx.query.redirect_uri\n );\n if (!redirectURI || !query.redirect_uri) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invalid redirect URI\"\n });\n }\n if (client.disabled) {\n const errorURL = getErrorURL(ctx, \"client_disabled\", \"client is disabled\");\n throw ctx.redirect(errorURL);\n }\n if (query.response_type !== \"code\") {\n const errorURL = getErrorURL(\n ctx,\n \"unsupported_response_type\",\n \"unsupported response type\"\n );\n throw ctx.redirect(errorURL);\n }\n const requestScope = query.scope?.split(\" \").filter((s) => s) || opts.defaultScope.split(\" \");\n const invalidScopes = requestScope.filter((scope) => {\n return !opts.scopes.includes(scope);\n });\n if (invalidScopes.length) {\n return handleRedirect(\n formatErrorURL(\n query.redirect_uri,\n \"invalid_scope\",\n `The following scopes are invalid: ${invalidScopes.join(\", \")}`\n )\n );\n }\n if ((!query.code_challenge || !query.code_challenge_method) && options.requirePKCE) {\n return handleRedirect(\n formatErrorURL(query.redirect_uri, \"invalid_request\", \"pkce is required\")\n );\n }\n if (!query.code_challenge_method) {\n query.code_challenge_method = \"plain\";\n }\n if (![\n \"s256\",\n options.allowPlainCodeChallengeMethod ? \"plain\" : \"s256\"\n ].includes(query.code_challenge_method?.toLowerCase() || \"\")) {\n return handleRedirect(\n formatErrorURL(\n query.redirect_uri,\n \"invalid_request\",\n \"invalid code_challenge method\"\n )\n );\n }\n const code = generateRandomString(32, \"a-z\", \"A-Z\", \"0-9\");\n const codeExpiresInMs = opts.codeExpiresIn * 1e3;\n const expiresAt = new Date(Date.now() + codeExpiresInMs);\n try {\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: JSON.stringify({\n clientId: client.clientId,\n redirectURI: query.redirect_uri,\n scope: requestScope,\n userId: session.user.id,\n authTime: session.session.createdAt.getTime(),\n /**\n * If the prompt is set to `consent`, then we need\n * to require the user to consent to the scopes.\n *\n * This means the code now needs to be treated as a\n * consent request.\n *\n * once the user consents, the code will be updated\n * with the actual code. This is to prevent the\n * client from using the code before the user\n * consents.\n */\n requireConsent: query.prompt === \"consent\",\n state: query.prompt === \"consent\" ? query.state : null,\n codeChallenge: query.code_challenge,\n codeChallengeMethod: query.code_challenge_method,\n nonce: query.nonce\n }),\n identifier: code,\n expiresAt\n },\n ctx\n );\n } catch (e) {\n return handleRedirect(\n formatErrorURL(\n query.redirect_uri,\n \"server_error\",\n \"An error occurred while processing the request\"\n )\n );\n }\n const redirectURIWithCode = new URL(redirectURI);\n redirectURIWithCode.searchParams.set(\"code\", code);\n redirectURIWithCode.searchParams.set(\"state\", ctx.query.state);\n if (query.prompt !== \"consent\") {\n return handleRedirect(redirectURIWithCode.toString());\n }\n if (client.skipConsent) {\n return handleRedirect(redirectURIWithCode.toString());\n }\n const hasAlreadyConsented = await ctx.context.adapter.findOne({\n model: \"oauthConsent\",\n where: [\n {\n field: \"clientId\",\n value: client.clientId\n },\n {\n field: \"userId\",\n value: session.user.id\n }\n ]\n }).then((res) => !!res?.consentGiven);\n if (hasAlreadyConsented) {\n return handleRedirect(redirectURIWithCode.toString());\n }\n if (options?.consentPage) {\n await ctx.setSignedCookie(\"oidc_consent_prompt\", code, ctx.context.secret, {\n maxAge: 600,\n path: \"/\",\n sameSite: \"lax\"\n });\n const consentURI = `${options.consentPage}?client_id=${client.clientId}&scope=${requestScope.join(\" \")}`;\n return handleRedirect(consentURI);\n }\n const htmlFn = options?.getConsentHTML;\n if (!htmlFn) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"No consent page provided\"\n });\n }\n return new Response(\n htmlFn({\n scopes: requestScope,\n clientMetadata: client.metadata,\n clientIcon: client?.icon,\n clientId: client.clientId,\n clientName: client.name,\n code\n }),\n {\n headers: {\n \"content-type\": \"text/html\"\n }\n }\n );\n}\n\nconst defaultClientSecretHasher = async (clientSecret) => {\n const hash = await createHash(\"SHA-256\").digest(\n new TextEncoder().encode(clientSecret)\n );\n const hashed = base64Url.encode(new Uint8Array(hash), {\n padding: false\n });\n return hashed;\n};\n\nconst getJwtPlugin = (ctx) => {\n return ctx.context.options.plugins?.find(\n (plugin) => plugin.id === \"jwt\"\n );\n};\nasync function getClient(clientId, adapter, trustedClients = []) {\n const trustedClient = trustedClients.find(\n (client) => client.clientId === clientId\n );\n if (trustedClient) {\n return trustedClient;\n }\n const dbClient = await adapter.findOne({\n model: \"oauthApplication\",\n where: [{ field: \"clientId\", value: clientId }]\n }).then((res) => {\n if (!res) {\n return null;\n }\n return {\n ...res,\n redirectURLs: (res.redirectURLs ?? \"\").split(\",\"),\n metadata: res.metadata ? JSON.parse(res.metadata) : {}\n };\n });\n return dbClient;\n}\nconst getMetadata = (ctx, options) => {\n const jwtPlugin = getJwtPlugin(ctx);\n const issuer = jwtPlugin && jwtPlugin.options?.jwt && jwtPlugin.options.jwt.issuer ? jwtPlugin.options.jwt.issuer : ctx.context.options.baseURL;\n const baseURL = ctx.context.baseURL;\n const supportedAlgs = options?.useJWTPlugin ? [\"RS256\", \"EdDSA\", \"none\"] : [\"HS256\", \"none\"];\n return {\n issuer,\n authorization_endpoint: `${baseURL}/oauth2/authorize`,\n token_endpoint: `${baseURL}/oauth2/token`,\n userinfo_endpoint: `${baseURL}/oauth2/userinfo`,\n jwks_uri: `${baseURL}/jwks`,\n registration_endpoint: `${baseURL}/oauth2/register`,\n scopes_supported: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n response_types_supported: [\"code\"],\n response_modes_supported: [\"query\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\"],\n acr_values_supported: [\n \"urn:mace:incommon:iap:silver\",\n \"urn:mace:incommon:iap:bronze\"\n ],\n subject_types_supported: [\"public\"],\n id_token_signing_alg_values_supported: supportedAlgs,\n token_endpoint_auth_methods_supported: [\n \"client_secret_basic\",\n \"client_secret_post\",\n \"none\"\n ],\n code_challenge_methods_supported: [\"S256\"],\n claims_supported: [\n \"sub\",\n \"iss\",\n \"aud\",\n \"exp\",\n \"nbf\",\n \"iat\",\n \"jti\",\n \"email\",\n \"email_verified\",\n \"name\"\n ],\n ...options?.metadata\n };\n};\nconst oidcProvider = (options) => {\n const modelName = {\n oauthClient: \"oauthApplication\",\n oauthAccessToken: \"oauthAccessToken\",\n oauthConsent: \"oauthConsent\"\n };\n const opts = {\n codeExpiresIn: 600,\n defaultScope: \"openid\",\n accessTokenExpiresIn: 3600,\n refreshTokenExpiresIn: 604800,\n allowPlainCodeChallengeMethod: true,\n storeClientSecret: \"plain\",\n ...options,\n scopes: [\n \"openid\",\n \"profile\",\n \"email\",\n \"offline_access\",\n ...options?.scopes || []\n ]\n };\n const trustedClients = options.trustedClients || [];\n async function storeClientSecret(ctx, clientSecret) {\n if (opts.storeClientSecret === \"encrypted\") {\n return await symmetricEncrypt({\n key: ctx.context.secret,\n data: clientSecret\n });\n }\n if (opts.storeClientSecret === \"hashed\") {\n return await defaultClientSecretHasher(clientSecret);\n }\n if (typeof opts.storeClientSecret === \"object\" && \"hash\" in opts.storeClientSecret) {\n return await opts.storeClientSecret.hash(clientSecret);\n }\n if (typeof opts.storeClientSecret === \"object\" && \"encrypt\" in opts.storeClientSecret) {\n return await opts.storeClientSecret.encrypt(clientSecret);\n }\n return clientSecret;\n }\n async function verifyStoredClientSecret(ctx, storedClientSecret, clientSecret) {\n if (opts.storeClientSecret === \"encrypted\") {\n return await symmetricDecrypt({\n key: ctx.context.secret,\n data: storedClientSecret\n }) === clientSecret;\n }\n if (opts.storeClientSecret === \"hashed\") {\n const hashedClientSecret = await defaultClientSecretHasher(clientSecret);\n return hashedClientSecret === storedClientSecret;\n }\n if (typeof opts.storeClientSecret === \"object\" && \"hash\" in opts.storeClientSecret) {\n const hashedClientSecret = await opts.storeClientSecret.hash(clientSecret);\n return hashedClientSecret === storedClientSecret;\n }\n if (typeof opts.storeClientSecret === \"object\" && \"decrypt\" in opts.storeClientSecret) {\n const decryptedClientSecret = await opts.storeClientSecret.decrypt(storedClientSecret);\n return decryptedClientSecret === clientSecret;\n }\n return clientSecret === storedClientSecret;\n }\n return {\n id: \"oidc\",\n hooks: {\n after: [\n {\n matcher() {\n return true;\n },\n handler: createAuthMiddleware(async (ctx) => {\n const cookie = await ctx.getSignedCookie(\n \"oidc_login_prompt\",\n ctx.context.secret\n );\n const cookieName = ctx.context.authCookies.sessionToken.name;\n const parsedSetCookieHeader = parseSetCookieHeader(\n ctx.context.responseHeaders?.get(\"set-cookie\") || \"\"\n );\n const hasSessionToken = parsedSetCookieHeader.has(cookieName);\n if (!cookie || !hasSessionToken) {\n return;\n }\n ctx.setCookie(\"oidc_login_prompt\", \"\", {\n maxAge: 0\n });\n const sessionCookie = parsedSetCookieHeader.get(cookieName)?.value;\n const sessionToken = sessionCookie?.split(\".\")[0];\n if (!sessionToken) {\n return;\n }\n const session = await ctx.context.internalAdapter.findSession(sessionToken);\n if (!session) {\n return;\n }\n ctx.query = JSON.parse(cookie);\n ctx.query.prompt = \"consent\";\n ctx.context.session = session;\n const response = await authorize(ctx, opts);\n return response;\n })\n }\n ]\n },\n endpoints: {\n getOpenIdConfig: createAuthEndpoint(\n \"/.well-known/openid-configuration\",\n {\n method: \"GET\",\n metadata: {\n isAction: false\n }\n },\n async (ctx) => {\n const metadata = getMetadata(ctx, options);\n return ctx.json(metadata);\n }\n ),\n oAuth2authorize: createAuthEndpoint(\n \"/oauth2/authorize\",\n {\n method: \"GET\",\n query: z.record(z.string(), z.any()),\n metadata: {\n openapi: {\n description: \"Authorize an OAuth2 request\",\n responses: {\n \"200\": {\n description: \"Authorization response generated successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n additionalProperties: true,\n description: \"Authorization response, contents depend on the authorize function implementation\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n return authorize(ctx, opts);\n }\n ),\n oAuthConsent: createAuthEndpoint(\n \"/oauth2/consent\",\n {\n method: \"POST\",\n body: z.object({\n accept: z.boolean()\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Handle OAuth2 consent\",\n responses: {\n \"200\": {\n description: \"Consent processed successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n redirectURI: {\n type: \"string\",\n format: \"uri\",\n description: \"The URI to redirect to, either with an authorization code or an error\"\n }\n },\n required: [\"redirectURI\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const storedCode = await ctx.getSignedCookie(\n \"oidc_consent_prompt\",\n ctx.context.secret\n );\n if (!storedCode) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"No consent prompt found\",\n error: \"invalid_request\"\n });\n }\n const verification = await ctx.context.internalAdapter.findVerificationValue(storedCode);\n if (!verification) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"Invalid code\",\n error: \"invalid_request\"\n });\n }\n if (verification.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"Code expired\",\n error: \"invalid_request\"\n });\n }\n const value = JSON.parse(verification.value);\n if (!value.requireConsent) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"Consent not required\",\n error: \"invalid_request\"\n });\n }\n if (!ctx.body.accept) {\n await ctx.context.internalAdapter.deleteVerificationValue(\n verification.id\n );\n return ctx.json({\n redirectURI: `${value.redirectURI}?error=access_denied&error_description=User denied access`\n });\n }\n const code = generateRandomString(32, \"a-z\", \"A-Z\", \"0-9\");\n const codeExpiresInMs = opts.codeExpiresIn * 1e3;\n const expiresAt = new Date(Date.now() + codeExpiresInMs);\n await ctx.context.internalAdapter.updateVerificationValue(\n verification.id,\n {\n value: JSON.stringify({\n ...value,\n requireConsent: false\n }),\n identifier: code,\n expiresAt\n }\n );\n await ctx.context.adapter.create({\n model: modelName.oauthConsent,\n data: {\n clientId: value.clientId,\n userId: value.userId,\n scopes: value.scope.join(\" \"),\n consentGiven: true,\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date()\n }\n });\n const redirectURI = new URL(value.redirectURI);\n redirectURI.searchParams.set(\"code\", code);\n if (value.state) redirectURI.searchParams.set(\"state\", value.state);\n return ctx.json({\n redirectURI: redirectURI.toString()\n });\n }\n ),\n oAuth2token: createAuthEndpoint(\n \"/oauth2/token\",\n {\n method: \"POST\",\n body: z.record(z.any(), z.any()),\n metadata: {\n isAction: false\n }\n },\n async (ctx) => {\n let { body } = ctx;\n if (!body) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"request body not found\",\n error: \"invalid_request\"\n });\n }\n if (body instanceof FormData) {\n body = Object.fromEntries(body.entries());\n }\n if (!(body instanceof Object)) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"request body is not an object\",\n error: \"invalid_request\"\n });\n }\n let { client_id, client_secret } = body;\n const authorization = ctx.request?.headers.get(\"authorization\") || null;\n if (authorization && !client_id && !client_secret && authorization.startsWith(\"Basic \")) {\n try {\n const encoded = authorization.replace(\"Basic \", \"\");\n const decoded = new TextDecoder().decode(base64.decode(encoded));\n if (!decoded.includes(\":\")) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid authorization header format\",\n error: \"invalid_client\"\n });\n }\n const [id, secret] = decoded.split(\":\");\n if (!id || !secret) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid authorization header format\",\n error: \"invalid_client\"\n });\n }\n client_id = id;\n client_secret = secret;\n } catch (error) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid authorization header format\",\n error: \"invalid_client\"\n });\n }\n }\n const {\n grant_type,\n code,\n redirect_uri,\n refresh_token,\n code_verifier\n } = body;\n if (grant_type === \"refresh_token\") {\n if (!refresh_token) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"refresh_token is required\",\n error: \"invalid_request\"\n });\n }\n const token = await ctx.context.adapter.findOne({\n model: modelName.oauthAccessToken,\n where: [\n {\n field: \"refreshToken\",\n value: refresh_token.toString()\n }\n ]\n });\n if (!token) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid refresh token\",\n error: \"invalid_grant\"\n });\n }\n if (token.clientId !== client_id?.toString()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid client_id\",\n error: \"invalid_client\"\n });\n }\n if (token.refreshTokenExpiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"refresh token expired\",\n error: \"invalid_grant\"\n });\n }\n const accessToken2 = generateRandomString(32, \"a-z\", \"A-Z\");\n const newRefreshToken = generateRandomString(32, \"a-z\", \"A-Z\");\n const accessTokenExpiresAt2 = new Date(\n Date.now() + opts.accessTokenExpiresIn * 1e3\n );\n const refreshTokenExpiresAt2 = new Date(\n Date.now() + opts.refreshTokenExpiresIn * 1e3\n );\n await ctx.context.adapter.create({\n model: modelName.oauthAccessToken,\n data: {\n accessToken: accessToken2,\n refreshToken: newRefreshToken,\n accessTokenExpiresAt: accessTokenExpiresAt2,\n refreshTokenExpiresAt: refreshTokenExpiresAt2,\n clientId: client_id.toString(),\n userId: token.userId,\n scopes: token.scopes,\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date()\n }\n });\n return ctx.json({\n access_token: accessToken2,\n token_type: \"bearer\",\n expires_in: opts.accessTokenExpiresIn,\n refresh_token: newRefreshToken,\n scope: token.scopes\n });\n }\n if (!code) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"code is required\",\n error: \"invalid_request\"\n });\n }\n if (options.requirePKCE && !code_verifier) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"code verifier is missing\",\n error: \"invalid_request\"\n });\n }\n const verificationValue = await ctx.context.internalAdapter.findVerificationValue(\n code.toString()\n );\n if (!verificationValue) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid code\",\n error: \"invalid_grant\"\n });\n }\n if (verificationValue.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"code expired\",\n error: \"invalid_grant\"\n });\n }\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n if (!client_id) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"client_id is required\",\n error: \"invalid_client\"\n });\n }\n if (!grant_type) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"grant_type is required\",\n error: \"invalid_request\"\n });\n }\n if (grant_type !== \"authorization_code\") {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"grant_type must be 'authorization_code'\",\n error: \"unsupported_grant_type\"\n });\n }\n if (!redirect_uri) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"redirect_uri is required\",\n error: \"invalid_request\"\n });\n }\n const client = await getClient(\n client_id.toString(),\n ctx.context.adapter,\n trustedClients\n );\n if (!client) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid client_id\",\n error: \"invalid_client\"\n });\n }\n if (client.disabled) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"client is disabled\",\n error: \"invalid_client\"\n });\n }\n const value = JSON.parse(\n verificationValue.value\n );\n if (value.clientId !== client_id.toString()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid client_id\",\n error: \"invalid_client\"\n });\n }\n if (value.redirectURI !== redirect_uri.toString()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid redirect_uri\",\n error: \"invalid_client\"\n });\n }\n if (value.codeChallenge && !code_verifier) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"code verifier is missing\",\n error: \"invalid_request\"\n });\n }\n if (client.type === \"public\") {\n if (!code_verifier) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"code verifier is required for public clients\",\n error: \"invalid_request\"\n });\n }\n } else {\n if (!client.clientSecret || !client_secret) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"client_secret is required for confidential clients\",\n error: \"invalid_client\"\n });\n }\n const isValidSecret = await verifyStoredClientSecret(\n ctx,\n client.clientSecret,\n client_secret.toString()\n );\n if (!isValidSecret) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid client_secret\",\n error: \"invalid_client\"\n });\n }\n }\n const challenge = value.codeChallengeMethod === \"plain\" ? code_verifier : await createHash(\"SHA-256\", \"base64urlnopad\").digest(\n code_verifier\n );\n if (challenge !== value.codeChallenge) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"code verification failed\",\n error: \"invalid_request\"\n });\n }\n const requestedScopes = value.scope;\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n const accessToken = generateRandomString(32, \"a-z\", \"A-Z\");\n const refreshToken = generateRandomString(32, \"A-Z\", \"a-z\");\n const accessTokenExpiresAt = new Date(\n Date.now() + opts.accessTokenExpiresIn * 1e3\n );\n const refreshTokenExpiresAt = new Date(\n Date.now() + opts.refreshTokenExpiresIn * 1e3\n );\n await ctx.context.adapter.create({\n model: modelName.oauthAccessToken,\n data: {\n accessToken,\n refreshToken,\n accessTokenExpiresAt,\n refreshTokenExpiresAt,\n clientId: client_id.toString(),\n userId: value.userId,\n scopes: requestedScopes.join(\" \"),\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date()\n }\n });\n const user = await ctx.context.internalAdapter.findUserById(\n value.userId\n );\n if (!user) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"user not found\",\n error: \"invalid_grant\"\n });\n }\n const profile = {\n given_name: user.name.split(\" \")[0],\n family_name: user.name.split(\" \")[1],\n name: user.name,\n profile: user.image,\n updated_at: user.updatedAt.toISOString()\n };\n const email = {\n email: user.email,\n email_verified: user.emailVerified\n };\n const userClaims = {\n ...requestedScopes.includes(\"profile\") ? profile : {},\n ...requestedScopes.includes(\"email\") ? email : {}\n };\n const additionalUserClaims = options.getAdditionalUserInfoClaim ? await options.getAdditionalUserInfoClaim(user, requestedScopes) : {};\n const payload = {\n sub: user.id,\n aud: client_id.toString(),\n iat: Date.now(),\n auth_time: ctx.context.session?.session.createdAt.getTime(),\n nonce: value.nonce,\n acr: \"urn:mace:incommon:iap:silver\",\n // default to silver - ⚠︎ this should be configurable and should be validated against the client's metadata\n ...userClaims,\n ...additionalUserClaims\n };\n const expirationTime = Math.floor(Date.now() / 1e3) + opts.accessTokenExpiresIn;\n let idToken;\n if (options.useJWTPlugin) {\n const jwtPlugin = getJwtPlugin(ctx);\n if (!jwtPlugin) {\n ctx.context.logger.error(\n \"OIDC: `useJWTPlugin` is enabled but the JWT plugin is not available. Make sure you have the JWT Plugin in your plugins array or set `useJWTPlugin` to false.\"\n );\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n error_description: \"JWT plugin is not enabled\",\n error: \"internal_server_error\"\n });\n }\n idToken = await getJwtToken(\n {\n ...ctx,\n context: {\n ...ctx.context,\n session: {\n session: {\n id: generateRandomString(32, \"a-z\", \"A-Z\"),\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date(),\n userId: user.id,\n expiresAt: new Date(\n Date.now() + opts.accessTokenExpiresIn * 1e3\n ),\n token: accessToken,\n ipAddress: ctx.request?.headers.get(\"x-forwarded-for\")\n },\n user\n }\n }\n },\n {\n ...jwtPlugin.options,\n jwt: {\n ...jwtPlugin.options?.jwt,\n getSubject: () => user.id,\n audience: client_id.toString(),\n issuer: ctx.context.options.baseURL,\n expirationTime,\n definePayload: () => payload\n }\n }\n );\n } else {\n idToken = await new SignJWT(payload).setProtectedHeader({ alg: \"HS256\" }).setIssuedAt().setExpirationTime(expirationTime).sign(new TextEncoder().encode(client.clientSecret));\n }\n return ctx.json(\n {\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: opts.accessTokenExpiresIn,\n refresh_token: requestedScopes.includes(\"offline_access\") ? refreshToken : void 0,\n scope: requestedScopes.join(\" \"),\n id_token: requestedScopes.includes(\"openid\") ? idToken : void 0\n },\n {\n headers: {\n \"Cache-Control\": \"no-store\",\n Pragma: \"no-cache\"\n }\n }\n );\n }\n ),\n oAuth2userInfo: createAuthEndpoint(\n \"/oauth2/userinfo\",\n {\n method: \"GET\",\n metadata: {\n isAction: false,\n openapi: {\n description: \"Get OAuth2 user information\",\n responses: {\n \"200\": {\n description: \"User information retrieved successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n sub: {\n type: \"string\",\n description: \"Subject identifier (user ID)\"\n },\n email: {\n type: \"string\",\n format: \"email\",\n nullable: true,\n description: \"User's email address, included if 'email' scope is granted\"\n },\n name: {\n type: \"string\",\n nullable: true,\n description: \"User's full name, included if 'profile' scope is granted\"\n },\n picture: {\n type: \"string\",\n format: \"uri\",\n nullable: true,\n description: \"User's profile picture URL, included if 'profile' scope is granted\"\n },\n given_name: {\n type: \"string\",\n nullable: true,\n description: \"User's given name, included if 'profile' scope is granted\"\n },\n family_name: {\n type: \"string\",\n nullable: true,\n description: \"User's family name, included if 'profile' scope is granted\"\n },\n email_verified: {\n type: \"boolean\",\n nullable: true,\n description: \"Whether the email is verified, included if 'email' scope is granted\"\n }\n },\n required: [\"sub\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n if (!ctx.request) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"request not found\",\n error: \"invalid_request\"\n });\n }\n const authorization = ctx.request.headers.get(\"authorization\");\n if (!authorization) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"authorization header not found\",\n error: \"invalid_request\"\n });\n }\n const token = authorization.replace(\"Bearer \", \"\");\n const accessToken = await ctx.context.adapter.findOne({\n model: modelName.oauthAccessToken,\n where: [\n {\n field: \"accessToken\",\n value: token\n }\n ]\n });\n if (!accessToken) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid access token\",\n error: \"invalid_token\"\n });\n }\n if (accessToken.accessTokenExpiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"The Access Token expired\",\n error: \"invalid_token\"\n });\n }\n const user = await ctx.context.internalAdapter.findUserById(\n accessToken.userId\n );\n if (!user) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"user not found\",\n error: \"invalid_token\"\n });\n }\n const requestedScopes = accessToken.scopes.split(\" \");\n const baseUserClaims = {\n sub: user.id,\n email: requestedScopes.includes(\"email\") ? user.email : void 0,\n name: requestedScopes.includes(\"profile\") ? user.name : void 0,\n picture: requestedScopes.includes(\"profile\") ? user.image : void 0,\n given_name: requestedScopes.includes(\"profile\") ? user.name.split(\" \")[0] : void 0,\n family_name: requestedScopes.includes(\"profile\") ? user.name.split(\" \")[1] : void 0,\n email_verified: requestedScopes.includes(\"email\") ? user.emailVerified : void 0\n };\n const userClaims = options.getAdditionalUserInfoClaim ? await options.getAdditionalUserInfoClaim(user, requestedScopes) : baseUserClaims;\n return ctx.json({\n ...baseUserClaims,\n ...userClaims\n });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/oauth2/register`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.registerOAuthApplication`\n *\n * **client:**\n * `authClient.oauth2.register`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/oidc-provider#api-method-oauth2-register)\n */\n registerOAuthApplication: createAuthEndpoint(\n \"/oauth2/register\",\n {\n method: \"POST\",\n body: z.object({\n redirect_uris: z.array(z.string()).meta({\n description: 'A list of redirect URIs. Eg: [\"https://client.example.com/callback\"]'\n }),\n token_endpoint_auth_method: z.enum([\"none\", \"client_secret_basic\", \"client_secret_post\"]).meta({\n description: 'The authentication method for the token endpoint. Eg: \"client_secret_basic\"'\n }).default(\"client_secret_basic\").optional(),\n grant_types: z.array(\n z.enum([\n \"authorization_code\",\n \"implicit\",\n \"password\",\n \"client_credentials\",\n \"refresh_token\",\n \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n \"urn:ietf:params:oauth:grant-type:saml2-bearer\"\n ])\n ).meta({\n description: 'The grant types supported by the application. Eg: [\"authorization_code\"]'\n }).default([\"authorization_code\"]).optional(),\n response_types: z.array(z.enum([\"code\", \"token\"])).meta({\n description: 'The response types supported by the application. Eg: [\"code\"]'\n }).default([\"code\"]).optional(),\n client_name: z.string().meta({\n description: 'The name of the application. Eg: \"My App\"'\n }).optional(),\n client_uri: z.string().meta({\n description: 'The URI of the application. Eg: \"https://client.example.com\"'\n }).optional(),\n logo_uri: z.string().meta({\n description: 'The URI of the application logo. Eg: \"https://client.example.com/logo.png\"'\n }).optional(),\n scope: z.string().meta({\n description: 'The scopes supported by the application. Separated by spaces. Eg: \"profile email\"'\n }).optional(),\n contacts: z.array(z.string()).meta({\n description: 'The contact information for the application. Eg: [\"admin@example.com\"]'\n }).optional(),\n tos_uri: z.string().meta({\n description: 'The URI of the application terms of service. Eg: \"https://client.example.com/tos\"'\n }).optional(),\n policy_uri: z.string().meta({\n description: 'The URI of the application privacy policy. Eg: \"https://client.example.com/policy\"'\n }).optional(),\n jwks_uri: z.string().meta({\n description: 'The URI of the application JWKS. Eg: \"https://client.example.com/jwks\"'\n }).optional(),\n jwks: z.record(z.any(), z.any()).meta({\n description: 'The JWKS of the application. Eg: {\"keys\": [{\"kty\": \"RSA\", \"alg\": \"RS256\", \"use\": \"sig\", \"n\": \"...\", \"e\": \"...\"}]}'\n }).optional(),\n metadata: z.record(z.any(), z.any()).meta({\n description: 'The metadata of the application. Eg: {\"key\": \"value\"}'\n }).optional(),\n software_id: z.string().meta({\n description: 'The software ID of the application. Eg: \"my-software\"'\n }).optional(),\n software_version: z.string().meta({\n description: 'The software version of the application. Eg: \"1.0.0\"'\n }).optional(),\n software_statement: z.string().meta({\n description: \"The software statement of the application.\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Register an OAuth2 application\",\n responses: {\n \"200\": {\n description: \"OAuth2 application registered successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description: \"Name of the OAuth2 application\"\n },\n icon: {\n type: \"string\",\n nullable: true,\n description: \"Icon URL for the application\"\n },\n metadata: {\n type: \"object\",\n additionalProperties: true,\n nullable: true,\n description: \"Additional metadata for the application\"\n },\n clientId: {\n type: \"string\",\n description: \"Unique identifier for the client\"\n },\n clientSecret: {\n type: \"string\",\n description: \"Secret key for the client\"\n },\n redirectURLs: {\n type: \"array\",\n items: { type: \"string\", format: \"uri\" },\n description: \"List of allowed redirect URLs\"\n },\n type: {\n type: \"string\",\n description: \"Type of the client\",\n enum: [\"web\"]\n },\n authenticationScheme: {\n type: \"string\",\n description: \"Authentication scheme used by the client\",\n enum: [\"client_secret\"]\n },\n disabled: {\n type: \"boolean\",\n description: \"Whether the client is disabled\",\n enum: [false]\n },\n userId: {\n type: \"string\",\n nullable: true,\n description: \"ID of the user who registered the client, null if registered anonymously\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Creation timestamp\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Last update timestamp\"\n }\n },\n required: [\n \"name\",\n \"clientId\",\n \"clientSecret\",\n \"redirectURLs\",\n \"type\",\n \"authenticationScheme\",\n \"disabled\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const body = ctx.body;\n const session = await getSessionFromCtx(ctx);\n if (!session && !options.allowDynamicClientRegistration) {\n throw new APIError(\"UNAUTHORIZED\", {\n error: \"invalid_token\",\n error_description: \"Authentication required for client registration\"\n });\n }\n if ((!body.grant_types || body.grant_types.includes(\"authorization_code\") || body.grant_types.includes(\"implicit\")) && (!body.redirect_uris || body.redirect_uris.length === 0)) {\n throw new APIError(\"BAD_REQUEST\", {\n error: \"invalid_redirect_uri\",\n error_description: \"Redirect URIs are required for authorization_code and implicit grant types\"\n });\n }\n if (body.grant_types && body.response_types) {\n if (body.grant_types.includes(\"authorization_code\") && !body.response_types.includes(\"code\")) {\n throw new APIError(\"BAD_REQUEST\", {\n error: \"invalid_client_metadata\",\n error_description: \"When 'authorization_code' grant type is used, 'code' response type must be included\"\n });\n }\n if (body.grant_types.includes(\"implicit\") && !body.response_types.includes(\"token\")) {\n throw new APIError(\"BAD_REQUEST\", {\n error: \"invalid_client_metadata\",\n error_description: \"When 'implicit' grant type is used, 'token' response type must be included\"\n });\n }\n }\n const clientId = options.generateClientId?.() || generateRandomString(32, \"a-z\", \"A-Z\");\n const clientSecret = options.generateClientSecret?.() || generateRandomString(32, \"a-z\", \"A-Z\");\n const storedClientSecret = await storeClientSecret(ctx, clientSecret);\n const client = await ctx.context.adapter.create({\n model: modelName.oauthClient,\n data: {\n name: body.client_name,\n icon: body.logo_uri,\n metadata: body.metadata ? JSON.stringify(body.metadata) : null,\n clientId,\n clientSecret: storedClientSecret,\n redirectURLs: body.redirect_uris.join(\",\"),\n type: \"web\",\n authenticationScheme: body.token_endpoint_auth_method || \"client_secret_basic\",\n disabled: false,\n userId: session?.session.userId,\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date()\n }\n });\n return ctx.json(\n {\n client_id: clientId,\n ...client.type !== \"public\" ? {\n client_secret: clientSecret,\n client_secret_expires_at: 0\n // 0 means it doesn't expire\n } : {},\n client_id_issued_at: Math.floor(Date.now() / 1e3),\n client_secret_expires_at: 0,\n // 0 means it doesn't expire\n redirect_uris: body.redirect_uris,\n token_endpoint_auth_method: body.token_endpoint_auth_method || \"client_secret_basic\",\n grant_types: body.grant_types || [\"authorization_code\"],\n response_types: body.response_types || [\"code\"],\n client_name: body.client_name,\n client_uri: body.client_uri,\n logo_uri: body.logo_uri,\n scope: body.scope,\n contacts: body.contacts,\n tos_uri: body.tos_uri,\n policy_uri: body.policy_uri,\n jwks_uri: body.jwks_uri,\n jwks: body.jwks,\n software_id: body.software_id,\n software_version: body.software_version,\n software_statement: body.software_statement,\n metadata: body.metadata\n },\n {\n status: 201,\n headers: {\n \"Cache-Control\": \"no-store\",\n Pragma: \"no-cache\"\n }\n }\n );\n }\n ),\n getOAuthClient: createAuthEndpoint(\n \"/oauth2/client/:id\",\n {\n method: \"GET\",\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Get OAuth2 client details\",\n responses: {\n \"200\": {\n description: \"OAuth2 client retrieved successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n clientId: {\n type: \"string\",\n description: \"Unique identifier for the client\"\n },\n name: {\n type: \"string\",\n description: \"Name of the OAuth2 application\"\n },\n icon: {\n type: \"string\",\n nullable: true,\n description: \"Icon URL for the application\"\n }\n },\n required: [\"clientId\", \"name\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const client = await getClient(\n ctx.params.id,\n ctx.context.adapter,\n trustedClients\n );\n if (!client) {\n throw new APIError(\"NOT_FOUND\", {\n error_description: \"client not found\",\n error: \"not_found\"\n });\n }\n return ctx.json({\n clientId: client.clientId,\n name: client.name,\n icon: client.icon\n });\n }\n )\n },\n schema\n };\n};\n\nexport { getMetadata as a, getClient as g, oidcProvider as o, schema as s };\n","import { betterFetch } from '@better-fetch/fetch';\n\nconst defaultEndpoints = [\n \"/sign-up/email\",\n \"/sign-in/email\",\n \"/forget-password\"\n];\nconst Providers = {\n CLOUDFLARE_TURNSTILE: \"cloudflare-turnstile\",\n GOOGLE_RECAPTCHA: \"google-recaptcha\",\n HCAPTCHA: \"hcaptcha\"\n};\nconst siteVerifyMap = {\n [Providers.CLOUDFLARE_TURNSTILE]: \"https://challenges.cloudflare.com/turnstile/v0/siteverify\",\n [Providers.GOOGLE_RECAPTCHA]: \"https://www.google.com/recaptcha/api/siteverify\",\n [Providers.HCAPTCHA]: \"https://api.hcaptcha.com/siteverify\"\n};\n\nconst EXTERNAL_ERROR_CODES = {\n VERIFICATION_FAILED: \"Captcha verification failed\",\n MISSING_RESPONSE: \"Missing CAPTCHA response\",\n UNKNOWN_ERROR: \"Something went wrong\"\n};\nconst INTERNAL_ERROR_CODES = {\n MISSING_SECRET_KEY: \"Missing secret key\",\n SERVICE_UNAVAILABLE: \"CAPTCHA service unavailable\"\n};\n\nconst middlewareResponse = ({ message, status }) => ({\n response: new Response(\n JSON.stringify({\n message\n }),\n {\n status\n }\n )\n});\n\nconst cloudflareTurnstile = async ({\n siteVerifyURL,\n captchaResponse,\n secretKey,\n remoteIP\n}) => {\n const response = await betterFetch(siteVerifyURL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n secret: secretKey,\n response: captchaResponse,\n ...remoteIP && { remoteip: remoteIP }\n })\n });\n if (!response.data || response.error) {\n throw new Error(INTERNAL_ERROR_CODES.SERVICE_UNAVAILABLE);\n }\n if (!response.data.success) {\n return middlewareResponse({\n message: EXTERNAL_ERROR_CODES.VERIFICATION_FAILED,\n status: 403\n });\n }\n return void 0;\n};\n\nconst encodeToURLParams = (obj) => {\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) {\n throw new Error(\"Input must be a non-null object.\");\n }\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(obj)) {\n if (value !== void 0 && value !== null) {\n params.append(key, String(value));\n }\n }\n return params.toString();\n};\n\nconst isV3 = (response) => {\n return \"score\" in response && typeof response.score === \"number\";\n};\nconst googleRecaptcha = async ({\n siteVerifyURL,\n captchaResponse,\n secretKey,\n minScore = 0.5,\n remoteIP\n}) => {\n const response = await betterFetch(\n siteVerifyURL,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: encodeToURLParams({\n secret: secretKey,\n response: captchaResponse,\n ...remoteIP && { remoteip: remoteIP }\n })\n }\n );\n if (!response.data || response.error) {\n throw new Error(INTERNAL_ERROR_CODES.SERVICE_UNAVAILABLE);\n }\n if (!response.data.success || isV3(response.data) && response.data.score < minScore) {\n return middlewareResponse({\n message: EXTERNAL_ERROR_CODES.VERIFICATION_FAILED,\n status: 403\n });\n }\n return void 0;\n};\n\nconst hCaptcha = async ({\n siteVerifyURL,\n captchaResponse,\n secretKey,\n siteKey,\n remoteIP\n}) => {\n const response = await betterFetch(siteVerifyURL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: encodeToURLParams({\n secret: secretKey,\n response: captchaResponse,\n ...siteKey && { sitekey: siteKey },\n ...remoteIP && { remoteip: remoteIP }\n })\n });\n if (!response.data || response.error) {\n throw new Error(INTERNAL_ERROR_CODES.SERVICE_UNAVAILABLE);\n }\n if (!response.data.success) {\n return middlewareResponse({\n message: EXTERNAL_ERROR_CODES.VERIFICATION_FAILED,\n status: 403\n });\n }\n return void 0;\n};\n\nconst captcha = (options) => ({\n id: \"captcha\",\n onRequest: async (request, ctx) => {\n try {\n const endpoints = options.endpoints?.length ? options.endpoints : defaultEndpoints;\n if (!endpoints.some((endpoint) => request.url.includes(endpoint)))\n return void 0;\n if (!options.secretKey) {\n throw new Error(INTERNAL_ERROR_CODES.MISSING_SECRET_KEY);\n }\n const captchaResponse = request.headers.get(\"x-captcha-response\");\n const remoteUserIP = request.headers.get(\"x-captcha-user-remote-ip\") ?? void 0;\n if (!captchaResponse) {\n return middlewareResponse({\n message: EXTERNAL_ERROR_CODES.MISSING_RESPONSE,\n status: 400\n });\n }\n const siteVerifyURL = options.siteVerifyURLOverride || siteVerifyMap[options.provider];\n const handlerParams = {\n siteVerifyURL,\n captchaResponse,\n secretKey: options.secretKey,\n remoteIP: remoteUserIP\n };\n if (options.provider === Providers.CLOUDFLARE_TURNSTILE) {\n return await cloudflareTurnstile(handlerParams);\n }\n if (options.provider === Providers.GOOGLE_RECAPTCHA) {\n return await googleRecaptcha({\n ...handlerParams,\n minScore: options.minScore\n });\n }\n if (options.provider === Providers.HCAPTCHA) {\n return await hCaptcha({\n ...handlerParams,\n siteKey: options.siteKey\n });\n }\n } catch (_error) {\n const errorMessage = _error instanceof Error ? _error.message : void 0;\n ctx.logger.error(errorMessage ?? \"Unknown error\", {\n endpoint: request.url,\n message: _error\n });\n return middlewareResponse({\n message: EXTERNAL_ERROR_CODES.UNKNOWN_ERROR,\n status: 500\n });\n }\n }\n});\n\nexport { captcha };\n","import * as z from 'zod/v4';\nimport { APIError } from 'better-call';\nimport { j as createAuthEndpoint, k as getSessionFromCtx, l as sessionMiddleware, i as createAuthMiddleware } from './better-auth.D4HhkCZJ.mjs';\nimport './better-auth.8zoxzg-F.mjs';\nimport { base64Url } from '@better-auth/utils/base64';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport { m as mergeSchema } from './better-auth.n2KFGwjY.mjs';\nimport './better-auth.DGaVMVAI.mjs';\nimport '../plugins/organization/access/index.mjs';\nimport '@better-auth/utils/random';\nimport { createHash } from '@better-auth/utils/hash';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport { g as generateRandomString } from './better-auth.B4Qoxdgc.mjs';\nimport './better-auth.DBGfIDnh.mjs';\nimport 'kysely';\nimport 'defu';\nimport '@better-auth/utils/otp';\nimport '../plugins/admin/access/index.mjs';\nimport '@better-fetch/fetch';\nimport './better-auth.CGrHn1Ih.mjs';\nimport { g as getDate } from './better-auth.CW6D9eSx.mjs';\nimport { g as getIp } from './better-auth.DcfNPS8q.mjs';\nimport { p as parseJSON } from './better-auth.ffWeg50w.mjs';\nimport { s as safeJSONParse } from './better-auth.tB5eU6EY.mjs';\nimport { role } from '../plugins/access/index.mjs';\n\nconst apiKeySchema = ({\n timeWindow,\n rateLimitMax\n}) => ({\n apikey: {\n fields: {\n /**\n * The name of the key.\n */\n name: {\n type: \"string\",\n required: false,\n input: false\n },\n /**\n * Shows the first few characters of the API key\n * This allows you to show those few characters in the UI to make it easier for users to identify the API key.\n */\n start: {\n type: \"string\",\n required: false,\n input: false\n },\n /**\n * The prefix of the key.\n */\n prefix: {\n type: \"string\",\n required: false,\n input: false\n },\n /**\n * The hashed key value.\n */\n key: {\n type: \"string\",\n required: true,\n input: false\n },\n /**\n * The user id of the user who created the key.\n */\n userId: {\n type: \"string\",\n references: { model: \"user\", field: \"id\" },\n required: true,\n input: false\n },\n /**\n * The interval to refill the key in milliseconds.\n */\n refillInterval: {\n type: \"number\",\n required: false,\n input: false\n },\n /**\n * The amount to refill the remaining count of the key.\n */\n refillAmount: {\n type: \"number\",\n required: false,\n input: false\n },\n /**\n * The date and time when the key was last refilled.\n */\n lastRefillAt: {\n type: \"date\",\n required: false,\n input: false\n },\n /**\n * Whether the key is enabled.\n */\n enabled: {\n type: \"boolean\",\n required: false,\n input: false,\n defaultValue: true\n },\n /**\n * Whether the key has rate limiting enabled.\n */\n rateLimitEnabled: {\n type: \"boolean\",\n required: false,\n input: false,\n defaultValue: true\n },\n /**\n * The time window in milliseconds for the rate limit.\n */\n rateLimitTimeWindow: {\n type: \"number\",\n required: false,\n input: false,\n defaultValue: timeWindow\n },\n /**\n * The maximum number of requests allowed within the `rateLimitTimeWindow`.\n */\n rateLimitMax: {\n type: \"number\",\n required: false,\n input: false,\n defaultValue: rateLimitMax\n },\n /**\n * The number of requests made within the rate limit time window\n */\n requestCount: {\n type: \"number\",\n required: false,\n input: false,\n defaultValue: 0\n },\n /**\n * The remaining number of requests before the key is revoked.\n *\n * If this is null, then the key is not revoked.\n *\n * If `refillInterval` & `refillAmount` are provided, than this will refill accordingly.\n */\n remaining: {\n type: \"number\",\n required: false,\n input: false\n },\n /**\n * The date and time of the last request made to the key.\n */\n lastRequest: {\n type: \"date\",\n required: false,\n input: false\n },\n /**\n * The date and time when the key will expire.\n */\n expiresAt: {\n type: \"date\",\n required: false,\n input: false\n },\n /**\n * The date and time when the key was created.\n */\n createdAt: {\n type: \"date\",\n required: true,\n input: false\n },\n /**\n * The date and time when the key was last updated.\n */\n updatedAt: {\n type: \"date\",\n required: true,\n input: false\n },\n /**\n * The permissions of the key.\n */\n permissions: {\n type: \"string\",\n required: false,\n input: false\n },\n /**\n * Any additional metadata you want to store with the key.\n */\n metadata: {\n type: \"string\",\n required: false,\n input: true,\n transform: {\n input(value) {\n return JSON.stringify(value);\n },\n output(value) {\n if (!value) return null;\n return parseJSON(value);\n }\n }\n }\n }\n }\n});\n\nfunction createApiKey({\n keyGenerator,\n opts,\n schema,\n deleteAllExpiredApiKeys\n}) {\n return createAuthEndpoint(\n \"/api-key/create\",\n {\n method: \"POST\",\n body: z.object({\n name: z.string().meta({ description: \"Name of the Api Key\" }).optional(),\n expiresIn: z.number().meta({\n description: \"Expiration time of the Api Key in seconds\"\n }).min(1).optional().nullable().default(null),\n userId: z.coerce.string().meta({\n description: 'User Id of the user that the Api Key belongs to. server-only. Eg: \"user-id\"'\n }).optional(),\n prefix: z.string().meta({ description: \"Prefix of the Api Key\" }).regex(/^[a-zA-Z0-9_-]+$/, {\n message: \"Invalid prefix format, must be alphanumeric and contain only underscores and hyphens.\"\n }).optional(),\n remaining: z.number().meta({\n description: \"Remaining number of requests. Server side only\"\n }).min(0).optional().nullable().default(null),\n metadata: z.any().optional(),\n refillAmount: z.number().meta({\n description: \"Amount to refill the remaining count of the Api Key. server-only. Eg: 100\"\n }).min(1).optional(),\n refillInterval: z.number().meta({\n description: \"Interval to refill the Api Key in milliseconds. server-only. Eg: 1000\"\n }).optional(),\n rateLimitTimeWindow: z.number().meta({\n description: \"The duration in milliseconds where each request is counted. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 1000\"\n }).optional(),\n rateLimitMax: z.number().meta({\n description: \"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100\"\n }).optional(),\n rateLimitEnabled: z.boolean().meta({\n description: \"Whether the key has rate limiting enabled. server-only. Eg: true\"\n }).optional(),\n permissions: z.record(z.string(), z.array(z.string())).meta({\n description: \"Permissions of the Api Key.\"\n }).optional()\n }),\n metadata: {\n openapi: {\n description: \"Create a new API key for a user\",\n responses: {\n \"200\": {\n description: \"API key created successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Unique identifier of the API key\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Creation timestamp\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Last update timestamp\"\n },\n name: {\n type: \"string\",\n nullable: true,\n description: \"Name of the API key\"\n },\n prefix: {\n type: \"string\",\n nullable: true,\n description: \"Prefix of the API key\"\n },\n start: {\n type: \"string\",\n nullable: true,\n description: \"Starting characters of the key (if configured)\"\n },\n key: {\n type: \"string\",\n description: \"The full API key (only returned on creation)\"\n },\n enabled: {\n type: \"boolean\",\n description: \"Whether the key is enabled\"\n },\n expiresAt: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"Expiration timestamp\"\n },\n userId: {\n type: \"string\",\n description: \"ID of the user owning the key\"\n },\n lastRefillAt: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"Last refill timestamp\"\n },\n lastRequest: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"Last request timestamp\"\n },\n metadata: {\n type: \"object\",\n nullable: true,\n additionalProperties: true,\n description: \"Metadata associated with the key\"\n },\n rateLimitMax: {\n type: \"number\",\n nullable: true,\n description: \"Maximum requests in time window\"\n },\n rateLimitTimeWindow: {\n type: \"number\",\n nullable: true,\n description: \"Rate limit time window in milliseconds\"\n },\n remaining: {\n type: \"number\",\n nullable: true,\n description: \"Remaining requests\"\n },\n refillAmount: {\n type: \"number\",\n nullable: true,\n description: \"Amount to refill\"\n },\n refillInterval: {\n type: \"number\",\n nullable: true,\n description: \"Refill interval in milliseconds\"\n },\n rateLimitEnabled: {\n type: \"boolean\",\n description: \"Whether rate limiting is enabled\"\n },\n requestCount: {\n type: \"number\",\n description: \"Current request count in window\"\n },\n permissions: {\n type: \"object\",\n nullable: true,\n additionalProperties: {\n type: \"array\",\n items: { type: \"string\" }\n },\n description: \"Permissions associated with the key\"\n }\n },\n required: [\n \"id\",\n \"createdAt\",\n \"updatedAt\",\n \"key\",\n \"enabled\",\n \"userId\",\n \"rateLimitEnabled\",\n \"requestCount\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const {\n name,\n expiresIn,\n prefix,\n remaining,\n metadata,\n refillAmount,\n refillInterval,\n permissions,\n rateLimitMax,\n rateLimitTimeWindow,\n rateLimitEnabled\n } = ctx.body;\n const session = await getSessionFromCtx(ctx);\n const authRequired = (ctx.request || ctx.headers) && !ctx.body.userId;\n const user = session?.user ?? (authRequired ? null : { id: ctx.body.userId });\n if (!user?.id) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.UNAUTHORIZED_SESSION\n });\n }\n if (authRequired) {\n if (refillAmount !== void 0 || refillInterval !== void 0 || rateLimitMax !== void 0 || rateLimitTimeWindow !== void 0 || rateLimitEnabled !== void 0 || permissions !== void 0 || remaining !== null) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.SERVER_ONLY_PROPERTY\n });\n }\n }\n if (metadata) {\n if (opts.enableMetadata === false) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.METADATA_DISABLED\n });\n }\n if (typeof metadata !== \"object\") {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_METADATA_TYPE\n });\n }\n }\n if (refillAmount && !refillInterval) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.REFILL_AMOUNT_AND_INTERVAL_REQUIRED\n });\n }\n if (refillInterval && !refillAmount) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.REFILL_INTERVAL_AND_AMOUNT_REQUIRED\n });\n }\n if (expiresIn) {\n if (opts.keyExpiration.disableCustomExpiresTime === true) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.KEY_DISABLED_EXPIRATION\n });\n }\n const expiresIn_in_days = expiresIn / (60 * 60 * 24);\n if (opts.keyExpiration.minExpiresIn > expiresIn_in_days) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.EXPIRES_IN_IS_TOO_SMALL\n });\n } else if (opts.keyExpiration.maxExpiresIn < expiresIn_in_days) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.EXPIRES_IN_IS_TOO_LARGE\n });\n }\n }\n if (prefix) {\n if (prefix.length < opts.minimumPrefixLength) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_PREFIX_LENGTH\n });\n }\n if (prefix.length > opts.maximumPrefixLength) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_PREFIX_LENGTH\n });\n }\n }\n if (name) {\n if (name.length < opts.minimumNameLength) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_NAME_LENGTH\n });\n }\n if (name.length > opts.maximumNameLength) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_NAME_LENGTH\n });\n }\n } else if (opts.requireName) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.NAME_REQUIRED\n });\n }\n deleteAllExpiredApiKeys(ctx.context);\n const key = await keyGenerator({\n length: opts.defaultKeyLength,\n prefix: prefix || opts.defaultPrefix\n });\n const hashed = opts.disableKeyHashing ? key : await defaultKeyHasher(key);\n let start = null;\n if (opts.startingCharactersConfig.shouldStore) {\n start = key.substring(\n 0,\n opts.startingCharactersConfig.charactersLength\n );\n }\n const defaultPermissions = opts.permissions?.defaultPermissions ? typeof opts.permissions.defaultPermissions === \"function\" ? await opts.permissions.defaultPermissions(user.id, ctx) : opts.permissions.defaultPermissions : void 0;\n const permissionsToApply = permissions ? JSON.stringify(permissions) : defaultPermissions ? JSON.stringify(defaultPermissions) : void 0;\n let data = {\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date(),\n name: name ?? null,\n prefix: prefix ?? opts.defaultPrefix ?? null,\n start,\n key: hashed,\n enabled: true,\n expiresAt: expiresIn ? getDate(expiresIn, \"sec\") : opts.keyExpiration.defaultExpiresIn ? getDate(opts.keyExpiration.defaultExpiresIn, \"sec\") : null,\n userId: user.id,\n lastRefillAt: null,\n lastRequest: null,\n metadata: null,\n rateLimitMax: rateLimitMax ?? opts.rateLimit.maxRequests ?? null,\n rateLimitTimeWindow: rateLimitTimeWindow ?? opts.rateLimit.timeWindow ?? null,\n remaining: remaining || refillAmount || null,\n refillAmount: refillAmount ?? null,\n refillInterval: refillInterval ?? null,\n rateLimitEnabled: rateLimitEnabled === void 0 ? opts.rateLimit.enabled ?? true : rateLimitEnabled,\n requestCount: 0,\n //@ts-ignore - we intentionally save the permissions as string on DB.\n permissions: permissionsToApply\n };\n if (metadata) {\n data.metadata = schema.apikey.fields.metadata.transform.input(metadata);\n }\n const apiKey = await ctx.context.adapter.create({\n model: API_KEY_TABLE_NAME,\n data\n });\n return ctx.json({\n ...apiKey,\n key,\n metadata: metadata ?? null,\n permissions: apiKey.permissions ? safeJSONParse(\n //@ts-ignore - from DB, this value is always a string\n apiKey.permissions\n ) : null\n });\n }\n );\n}\n\nfunction deleteApiKey({\n opts,\n schema,\n deleteAllExpiredApiKeys\n}) {\n return createAuthEndpoint(\n \"/api-key/delete\",\n {\n method: \"POST\",\n body: z.object({\n keyId: z.string().meta({\n description: \"The id of the Api Key\"\n })\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Delete an existing API key\",\n requestBody: {\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n keyId: {\n type: \"string\",\n description: \"The id of the API key to delete\"\n }\n },\n required: [\"keyId\"]\n }\n }\n }\n },\n responses: {\n \"200\": {\n description: \"API key deleted successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: {\n type: \"boolean\",\n description: \"Indicates if the API key was successfully deleted\"\n }\n },\n required: [\"success\"]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { keyId } = ctx.body;\n const session = ctx.context.session;\n if (session.user.banned === true) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.USER_BANNED\n });\n }\n const apiKey = await ctx.context.adapter.findOne({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"id\",\n value: keyId\n }\n ]\n });\n if (!apiKey || apiKey.userId !== session.user.id) {\n throw new APIError(\"NOT_FOUND\", {\n message: ERROR_CODES.KEY_NOT_FOUND\n });\n }\n try {\n await ctx.context.adapter.delete({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"id\",\n value: apiKey.id\n }\n ]\n });\n } catch (error) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: error?.message\n });\n }\n deleteAllExpiredApiKeys(ctx.context);\n return ctx.json({\n success: true\n });\n }\n );\n}\n\nfunction getApiKey({\n opts,\n schema,\n deleteAllExpiredApiKeys\n}) {\n return createAuthEndpoint(\n \"/api-key/get\",\n {\n method: \"GET\",\n query: z.object({\n id: z.string().meta({\n description: \"The id of the Api Key\"\n })\n }),\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"Retrieve an existing API key by ID\",\n responses: {\n \"200\": {\n description: \"API key retrieved successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"ID\"\n },\n name: {\n type: \"string\",\n nullable: true,\n description: \"The name of the key\"\n },\n start: {\n type: \"string\",\n nullable: true,\n description: \"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.\"\n },\n prefix: {\n type: \"string\",\n nullable: true,\n description: \"The API Key prefix. Stored as plain text.\"\n },\n userId: {\n type: \"string\",\n description: \"The owner of the user id\"\n },\n refillInterval: {\n type: \"number\",\n nullable: true,\n description: \"The interval in which the `remaining` count is refilled by day. Example: 1 // every day\"\n },\n refillAmount: {\n type: \"number\",\n nullable: true,\n description: \"The amount to refill\"\n },\n lastRefillAt: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"The last refill date\"\n },\n enabled: {\n type: \"boolean\",\n description: \"Sets if key is enabled or disabled\",\n default: true\n },\n rateLimitEnabled: {\n type: \"boolean\",\n description: \"Whether the key has rate limiting enabled\"\n },\n rateLimitTimeWindow: {\n type: \"number\",\n nullable: true,\n description: \"The duration in milliseconds\"\n },\n rateLimitMax: {\n type: \"number\",\n nullable: true,\n description: \"Maximum amount of requests allowed within a window\"\n },\n requestCount: {\n type: \"number\",\n description: \"The number of requests made within the rate limit time window\"\n },\n remaining: {\n type: \"number\",\n nullable: true,\n description: \"Remaining requests (every time api key is used this should updated and should be updated on refill as well)\"\n },\n lastRequest: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"When last request occurred\"\n },\n expiresAt: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"Expiry date of a key\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"created at\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"updated at\"\n },\n metadata: {\n type: \"object\",\n nullable: true,\n additionalProperties: true,\n description: \"Extra metadata about the apiKey\"\n },\n permissions: {\n type: \"string\",\n nullable: true,\n description: \"Permissions for the api key (stored as JSON string)\"\n }\n },\n required: [\n \"id\",\n \"userId\",\n \"enabled\",\n \"rateLimitEnabled\",\n \"requestCount\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const { id } = ctx.query;\n const session = ctx.context.session;\n let apiKey = await ctx.context.adapter.findOne({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"id\",\n value: id\n },\n {\n field: \"userId\",\n value: session.user.id\n }\n ]\n });\n if (!apiKey) {\n throw new APIError(\"NOT_FOUND\", {\n message: ERROR_CODES.KEY_NOT_FOUND\n });\n }\n deleteAllExpiredApiKeys(ctx.context);\n apiKey.metadata = schema.apikey.fields.metadata.transform.output(\n apiKey.metadata\n );\n const { key, ...returningApiKey } = apiKey;\n return ctx.json({\n ...returningApiKey,\n permissions: returningApiKey.permissions ? safeJSONParse(\n //@ts-ignore - From DB this is always a string\n returningApiKey.permissions\n ) : null\n });\n }\n );\n}\n\nfunction updateApiKey({\n opts,\n schema,\n deleteAllExpiredApiKeys\n}) {\n return createAuthEndpoint(\n \"/api-key/update\",\n {\n method: \"POST\",\n body: z.object({\n keyId: z.string().meta({\n description: \"The id of the Api Key\"\n }),\n userId: z.coerce.string().meta({\n description: 'The id of the user which the api key belongs to. server-only. Eg: \"some-user-id\"'\n }).optional(),\n name: z.string().meta({\n description: \"The name of the key\"\n }).optional(),\n enabled: z.boolean().meta({\n description: \"Whether the Api Key is enabled or not\"\n }).optional(),\n remaining: z.number().meta({\n description: \"The number of remaining requests\"\n }).min(1).optional(),\n refillAmount: z.number().meta({\n description: \"The refill amount\"\n }).optional(),\n refillInterval: z.number().meta({\n description: \"The refill interval\"\n }).optional(),\n metadata: z.any().optional(),\n expiresIn: z.number().meta({\n description: \"Expiration time of the Api Key in seconds\"\n }).min(1).optional().nullable(),\n rateLimitEnabled: z.boolean().meta({\n description: \"Whether the key has rate limiting enabled.\"\n }).optional(),\n rateLimitTimeWindow: z.number().meta({\n description: \"The duration in milliseconds where each request is counted. server-only. Eg: 1000\"\n }).optional(),\n rateLimitMax: z.number().meta({\n description: \"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100\"\n }).optional(),\n permissions: z.record(z.string(), z.array(z.string())).meta({\n description: \"Update the permissions on the API Key. server-only.\"\n }).optional().nullable()\n }),\n metadata: {\n openapi: {\n description: \"Update an existing API key by ID\",\n responses: {\n \"200\": {\n description: \"API key updated successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"ID\"\n },\n name: {\n type: \"string\",\n nullable: true,\n description: \"The name of the key\"\n },\n start: {\n type: \"string\",\n nullable: true,\n description: \"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.\"\n },\n prefix: {\n type: \"string\",\n nullable: true,\n description: \"The API Key prefix. Stored as plain text.\"\n },\n userId: {\n type: \"string\",\n description: \"The owner of the user id\"\n },\n refillInterval: {\n type: \"number\",\n nullable: true,\n description: \"The interval in which the `remaining` count is refilled by day. Example: 1 // every day\"\n },\n refillAmount: {\n type: \"number\",\n nullable: true,\n description: \"The amount to refill\"\n },\n lastRefillAt: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"The last refill date\"\n },\n enabled: {\n type: \"boolean\",\n description: \"Sets if key is enabled or disabled\",\n default: true\n },\n rateLimitEnabled: {\n type: \"boolean\",\n description: \"Whether the key has rate limiting enabled\"\n },\n rateLimitTimeWindow: {\n type: \"number\",\n nullable: true,\n description: \"The duration in milliseconds\"\n },\n rateLimitMax: {\n type: \"number\",\n nullable: true,\n description: \"Maximum amount of requests allowed within a window\"\n },\n requestCount: {\n type: \"number\",\n description: \"The number of requests made within the rate limit time window\"\n },\n remaining: {\n type: \"number\",\n nullable: true,\n description: \"Remaining requests (every time api key is used this should updated and should be updated on refill as well)\"\n },\n lastRequest: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"When last request occurred\"\n },\n expiresAt: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"Expiry date of a key\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"created at\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"updated at\"\n },\n metadata: {\n type: \"object\",\n nullable: true,\n additionalProperties: true,\n description: \"Extra metadata about the apiKey\"\n },\n permissions: {\n type: \"string\",\n nullable: true,\n description: \"Permissions for the api key (stored as JSON string)\"\n }\n },\n required: [\n \"id\",\n \"userId\",\n \"enabled\",\n \"rateLimitEnabled\",\n \"requestCount\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const {\n keyId,\n expiresIn,\n enabled,\n metadata,\n refillAmount,\n refillInterval,\n remaining,\n name,\n permissions,\n rateLimitEnabled,\n rateLimitTimeWindow,\n rateLimitMax\n } = ctx.body;\n const session = await getSessionFromCtx(ctx);\n const authRequired = (ctx.request || ctx.headers) && !ctx.body.userId;\n const user = session?.user ?? (authRequired ? null : { id: ctx.body.userId });\n if (!user?.id) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.UNAUTHORIZED_SESSION\n });\n }\n if (authRequired) {\n if (refillAmount !== void 0 || refillInterval !== void 0 || rateLimitMax !== void 0 || rateLimitTimeWindow !== void 0 || rateLimitEnabled !== void 0 || remaining !== void 0 || permissions !== void 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.SERVER_ONLY_PROPERTY\n });\n }\n }\n const apiKey = await ctx.context.adapter.findOne({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"id\",\n value: keyId\n },\n {\n field: \"userId\",\n value: user.id\n }\n ]\n });\n if (!apiKey) {\n throw new APIError(\"NOT_FOUND\", {\n message: ERROR_CODES.KEY_NOT_FOUND\n });\n }\n let newValues = {};\n if (name !== void 0) {\n if (name.length < opts.minimumNameLength) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_NAME_LENGTH\n });\n } else if (name.length > opts.maximumNameLength) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_NAME_LENGTH\n });\n }\n newValues.name = name;\n }\n if (enabled !== void 0) {\n newValues.enabled = enabled;\n }\n if (expiresIn !== void 0) {\n if (opts.keyExpiration.disableCustomExpiresTime === true) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.KEY_DISABLED_EXPIRATION\n });\n }\n if (expiresIn !== null) {\n const expiresIn_in_days = expiresIn / (60 * 60 * 24);\n if (expiresIn_in_days < opts.keyExpiration.minExpiresIn) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.EXPIRES_IN_IS_TOO_SMALL\n });\n } else if (expiresIn_in_days > opts.keyExpiration.maxExpiresIn) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.EXPIRES_IN_IS_TOO_LARGE\n });\n }\n }\n newValues.expiresAt = expiresIn ? getDate(expiresIn, \"sec\") : null;\n }\n if (metadata !== void 0) {\n if (typeof metadata !== \"object\") {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_METADATA_TYPE\n });\n }\n newValues.metadata = schema.apikey.fields.metadata.transform.input(metadata);\n }\n if (remaining !== void 0) {\n newValues.remaining = remaining;\n }\n if (refillAmount !== void 0 || refillInterval !== void 0) {\n if (refillAmount !== void 0 && refillInterval === void 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.REFILL_AMOUNT_AND_INTERVAL_REQUIRED\n });\n } else if (refillInterval !== void 0 && refillAmount === void 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.REFILL_INTERVAL_AND_AMOUNT_REQUIRED\n });\n }\n newValues.refillAmount = refillAmount;\n newValues.refillInterval = refillInterval;\n }\n if (rateLimitEnabled !== void 0) {\n newValues.rateLimitEnabled = rateLimitEnabled;\n }\n if (rateLimitTimeWindow !== void 0) {\n newValues.rateLimitTimeWindow = rateLimitTimeWindow;\n }\n if (rateLimitMax !== void 0) {\n newValues.rateLimitMax = rateLimitMax;\n }\n if (permissions !== void 0) {\n newValues.permissions = JSON.stringify(permissions);\n }\n if (Object.keys(newValues).length === 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.NO_VALUES_TO_UPDATE\n });\n }\n let newApiKey = apiKey;\n try {\n let result = await ctx.context.adapter.update({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"id\",\n value: apiKey.id\n }\n ],\n update: {\n lastRequest: /* @__PURE__ */ new Date(),\n remaining: apiKey.remaining === null ? null : apiKey.remaining - 1,\n ...newValues\n }\n });\n if (result) newApiKey = result;\n } catch (error) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: error?.message\n });\n }\n deleteAllExpiredApiKeys(ctx.context);\n newApiKey.metadata = schema.apikey.fields.metadata.transform.output(\n newApiKey.metadata\n );\n const { key, ...returningApiKey } = newApiKey;\n return ctx.json({\n ...returningApiKey,\n permissions: returningApiKey.permissions ? safeJSONParse(\n //@ts-ignore - from DB, this value is always a string\n returningApiKey.permissions\n ) : null\n });\n }\n );\n}\n\nfunction isRateLimited(apiKey, opts) {\n const now = /* @__PURE__ */ new Date();\n const lastRequest = apiKey.lastRequest;\n const rateLimitTimeWindow = apiKey.rateLimitTimeWindow;\n const rateLimitMax = apiKey.rateLimitMax;\n let requestCount = apiKey.requestCount;\n if (opts.rateLimit.enabled === false)\n return {\n success: true,\n message: null,\n update: { lastRequest: now },\n tryAgainIn: null\n };\n if (apiKey.rateLimitEnabled === false)\n return {\n success: true,\n message: null,\n update: { lastRequest: now },\n tryAgainIn: null\n };\n if (rateLimitTimeWindow === null || rateLimitMax === null) {\n return {\n success: true,\n message: null,\n update: null,\n tryAgainIn: null\n };\n }\n if (lastRequest === null) {\n return {\n success: true,\n message: null,\n update: { lastRequest: now, requestCount: 1 },\n tryAgainIn: null\n };\n }\n const timeSinceLastRequest = now.getTime() - lastRequest.getTime();\n if (timeSinceLastRequest > rateLimitTimeWindow) {\n return {\n success: true,\n message: null,\n update: { lastRequest: now, requestCount: 1 },\n tryAgainIn: null\n };\n }\n if (requestCount >= rateLimitMax) {\n return {\n success: false,\n message: ERROR_CODES.RATE_LIMIT_EXCEEDED,\n update: null,\n tryAgainIn: Math.ceil(rateLimitTimeWindow - timeSinceLastRequest)\n };\n }\n requestCount++;\n return {\n success: true,\n message: null,\n tryAgainIn: null,\n update: { lastRequest: now, requestCount }\n };\n}\n\nasync function validateApiKey({\n hashedKey,\n ctx,\n opts,\n schema,\n permissions\n}) {\n const apiKey = await ctx.context.adapter.findOne({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"key\",\n value: hashedKey\n }\n ]\n });\n if (!apiKey) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.INVALID_API_KEY\n });\n }\n if (apiKey.enabled === false) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.KEY_DISABLED,\n code: \"KEY_DISABLED\"\n });\n }\n if (apiKey.expiresAt) {\n const now = (/* @__PURE__ */ new Date()).getTime();\n const expiresAt = apiKey.expiresAt.getTime();\n if (now > expiresAt) {\n try {\n ctx.context.adapter.delete({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"id\",\n value: apiKey.id\n }\n ]\n });\n } catch (error) {\n ctx.context.logger.error(`Failed to delete expired API keys:`, error);\n }\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.KEY_EXPIRED,\n code: \"KEY_EXPIRED\"\n });\n }\n }\n if (permissions) {\n const apiKeyPermissions = apiKey.permissions ? safeJSONParse(\n //@ts-ignore - from DB, this value is always a string\n apiKey.permissions\n ) : null;\n if (!apiKeyPermissions) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.KEY_NOT_FOUND,\n code: \"KEY_NOT_FOUND\"\n });\n }\n const r = role(apiKeyPermissions);\n const result = r.authorize(permissions);\n if (!result.success) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.KEY_NOT_FOUND,\n code: \"KEY_NOT_FOUND\"\n });\n }\n }\n let remaining = apiKey.remaining;\n let lastRefillAt = apiKey.lastRefillAt;\n if (apiKey.remaining === 0 && apiKey.refillAmount === null) {\n try {\n ctx.context.adapter.delete({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"id\",\n value: apiKey.id\n }\n ]\n });\n } catch (error) {\n ctx.context.logger.error(`Failed to delete expired API keys:`, error);\n }\n throw new APIError(\"TOO_MANY_REQUESTS\", {\n message: ERROR_CODES.USAGE_EXCEEDED,\n code: \"USAGE_EXCEEDED\"\n });\n } else if (remaining !== null) {\n let now = (/* @__PURE__ */ new Date()).getTime();\n const refillInterval = apiKey.refillInterval;\n const refillAmount = apiKey.refillAmount;\n let lastTime = (lastRefillAt ?? apiKey.createdAt).getTime();\n if (refillInterval && refillAmount) {\n const timeSinceLastRequest = (now - lastTime) / (1e3 * 60 * 60 * 24);\n if (timeSinceLastRequest > refillInterval) {\n remaining = refillAmount;\n lastRefillAt = /* @__PURE__ */ new Date();\n }\n }\n if (remaining === 0) {\n throw new APIError(\"TOO_MANY_REQUESTS\", {\n message: ERROR_CODES.USAGE_EXCEEDED,\n code: \"USAGE_EXCEEDED\"\n });\n } else {\n remaining--;\n }\n }\n const { message, success, update, tryAgainIn } = isRateLimited(apiKey, opts);\n const newApiKey = await ctx.context.adapter.update({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"id\",\n value: apiKey.id\n }\n ],\n update: {\n ...update,\n remaining,\n lastRefillAt\n }\n });\n if (!newApiKey) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: ERROR_CODES.FAILED_TO_UPDATE_API_KEY,\n code: \"INTERNAL_SERVER_ERROR\"\n });\n }\n if (success === false) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: message ?? void 0,\n code: \"RATE_LIMITED\",\n details: {\n tryAgainIn\n }\n });\n }\n return newApiKey;\n}\nfunction verifyApiKey({\n opts,\n schema,\n deleteAllExpiredApiKeys\n}) {\n return createAuthEndpoint(\n \"/api-key/verify\",\n {\n method: \"POST\",\n body: z.object({\n key: z.string().meta({\n description: \"The key to verify\"\n }),\n permissions: z.record(z.string(), z.array(z.string())).meta({\n description: \"The permissions to verify.\"\n }).optional()\n }),\n metadata: {\n SERVER_ONLY: true\n }\n },\n async (ctx) => {\n const { key } = ctx.body;\n if (key.length < opts.defaultKeyLength) {\n return ctx.json({\n valid: false,\n error: {\n message: ERROR_CODES.INVALID_API_KEY,\n code: \"KEY_NOT_FOUND\"\n },\n key: null\n });\n }\n if (opts.customAPIKeyValidator) {\n const isValid = await opts.customAPIKeyValidator({ ctx, key });\n if (!isValid) {\n return ctx.json({\n valid: false,\n error: {\n message: ERROR_CODES.INVALID_API_KEY,\n code: \"KEY_NOT_FOUND\"\n },\n key: null\n });\n }\n }\n const hashed = opts.disableKeyHashing ? key : await defaultKeyHasher(key);\n let apiKey = null;\n try {\n apiKey = await validateApiKey({\n hashedKey: hashed,\n permissions: ctx.body.permissions,\n ctx,\n opts,\n schema\n });\n await deleteAllExpiredApiKeys(ctx.context);\n } catch (error) {\n if (error instanceof APIError) {\n return ctx.json({\n valid: false,\n error: {\n message: error.body?.message,\n code: error.body?.code\n },\n key: null\n });\n }\n return ctx.json({\n valid: false,\n error: {\n message: ERROR_CODES.INVALID_API_KEY,\n code: \"INVALID_API_KEY\"\n },\n key: null\n });\n }\n const { key: _, ...returningApiKey } = apiKey ?? {\n key: 1,\n permissions: void 0\n };\n if (\"metadata\" in returningApiKey) {\n returningApiKey.metadata = schema.apikey.fields.metadata.transform.output(\n returningApiKey.metadata\n );\n }\n returningApiKey.permissions = returningApiKey.permissions ? safeJSONParse(\n //@ts-ignore - from DB, this value is always a string\n returningApiKey.permissions\n ) : null;\n return ctx.json({\n valid: true,\n error: null,\n key: apiKey === null ? null : returningApiKey\n });\n }\n );\n}\n\nfunction listApiKeys({\n opts,\n schema,\n deleteAllExpiredApiKeys\n}) {\n return createAuthEndpoint(\n \"/api-key/list\",\n {\n method: \"GET\",\n use: [sessionMiddleware],\n metadata: {\n openapi: {\n description: \"List all API keys for the authenticated user\",\n responses: {\n \"200\": {\n description: \"API keys retrieved successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"ID\"\n },\n name: {\n type: \"string\",\n nullable: true,\n description: \"The name of the key\"\n },\n start: {\n type: \"string\",\n nullable: true,\n description: \"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.\"\n },\n prefix: {\n type: \"string\",\n nullable: true,\n description: \"The API Key prefix. Stored as plain text.\"\n },\n userId: {\n type: \"string\",\n description: \"The owner of the user id\"\n },\n refillInterval: {\n type: \"number\",\n nullable: true,\n description: \"The interval in which the `remaining` count is refilled by day. Example: 1 // every day\"\n },\n refillAmount: {\n type: \"number\",\n nullable: true,\n description: \"The amount to refill\"\n },\n lastRefillAt: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"The last refill date\"\n },\n enabled: {\n type: \"boolean\",\n description: \"Sets if key is enabled or disabled\",\n default: true\n },\n rateLimitEnabled: {\n type: \"boolean\",\n description: \"Whether the key has rate limiting enabled\"\n },\n rateLimitTimeWindow: {\n type: \"number\",\n nullable: true,\n description: \"The duration in milliseconds\"\n },\n rateLimitMax: {\n type: \"number\",\n nullable: true,\n description: \"Maximum amount of requests allowed within a window\"\n },\n requestCount: {\n type: \"number\",\n description: \"The number of requests made within the rate limit time window\"\n },\n remaining: {\n type: \"number\",\n nullable: true,\n description: \"Remaining requests (every time api key is used this should updated and should be updated on refill as well)\"\n },\n lastRequest: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"When last request occurred\"\n },\n expiresAt: {\n type: \"string\",\n format: \"date-time\",\n nullable: true,\n description: \"Expiry date of a key\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"created at\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"updated at\"\n },\n metadata: {\n type: \"object\",\n nullable: true,\n additionalProperties: true,\n description: \"Extra metadata about the apiKey\"\n },\n permissions: {\n type: \"string\",\n nullable: true,\n description: \"Permissions for the api key (stored as JSON string)\"\n }\n },\n required: [\n \"id\",\n \"userId\",\n \"enabled\",\n \"rateLimitEnabled\",\n \"requestCount\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const session = ctx.context.session;\n let apiKeys = await ctx.context.adapter.findMany({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"userId\",\n value: session.user.id\n }\n ]\n });\n deleteAllExpiredApiKeys(ctx.context);\n apiKeys = apiKeys.map((apiKey) => {\n return {\n ...apiKey,\n metadata: schema.apikey.fields.metadata.transform.output(\n apiKey.metadata\n )\n };\n });\n let returningApiKey = apiKeys.map((x) => {\n const { key, ...returningApiKey2 } = x;\n return {\n ...returningApiKey2,\n permissions: returningApiKey2.permissions ? safeJSONParse(\n //@ts-ignore - From DB this is always a string\n returningApiKey2.permissions\n ) : null\n };\n });\n return ctx.json(returningApiKey);\n }\n );\n}\n\nfunction deleteAllExpiredApiKeysEndpoint({\n deleteAllExpiredApiKeys\n}) {\n return createAuthEndpoint(\n \"/api-key/delete-all-expired-api-keys\",\n {\n method: \"POST\",\n metadata: {\n SERVER_ONLY: true,\n client: false\n }\n },\n async (ctx) => {\n try {\n await deleteAllExpiredApiKeys(ctx.context, true);\n } catch (error) {\n ctx.context.logger.error(\n \"[API KEY PLUGIN] Failed to delete expired API keys:\",\n error\n );\n return ctx.json({\n success: false,\n error\n });\n }\n return ctx.json({ success: true, error: null });\n }\n );\n}\n\nlet lastChecked = null;\nfunction deleteAllExpiredApiKeys(ctx, byPassLastCheckTime = false) {\n if (lastChecked && !byPassLastCheckTime) {\n const now = /* @__PURE__ */ new Date();\n const diff = now.getTime() - lastChecked.getTime();\n if (diff < 1e4) {\n return;\n }\n }\n lastChecked = /* @__PURE__ */ new Date();\n try {\n return ctx.adapter.deleteMany({\n model: API_KEY_TABLE_NAME,\n where: [\n {\n field: \"expiresAt\",\n operator: \"lt\",\n value: /* @__PURE__ */ new Date()\n },\n {\n field: \"expiresAt\",\n operator: \"ne\",\n value: null\n }\n ]\n });\n } catch (error) {\n ctx.logger.error(`Failed to delete expired API keys:`, error);\n }\n}\nfunction createApiKeyRoutes({\n keyGenerator,\n opts,\n schema\n}) {\n return {\n createApiKey: createApiKey({\n keyGenerator,\n opts,\n schema,\n deleteAllExpiredApiKeys\n }),\n verifyApiKey: verifyApiKey({ opts, schema, deleteAllExpiredApiKeys }),\n getApiKey: getApiKey({ opts, schema, deleteAllExpiredApiKeys }),\n updateApiKey: updateApiKey({ opts, schema, deleteAllExpiredApiKeys }),\n deleteApiKey: deleteApiKey({ opts, schema, deleteAllExpiredApiKeys }),\n listApiKeys: listApiKeys({ opts, schema, deleteAllExpiredApiKeys }),\n deleteAllExpiredApiKeys: deleteAllExpiredApiKeysEndpoint({\n deleteAllExpiredApiKeys\n })\n };\n}\n\nconst defaultKeyHasher = async (key) => {\n const hash = await createHash(\"SHA-256\").digest(\n new TextEncoder().encode(key)\n );\n const hashed = base64Url.encode(new Uint8Array(hash), {\n padding: false\n });\n return hashed;\n};\nconst ERROR_CODES = {\n INVALID_METADATA_TYPE: \"metadata must be an object or undefined\",\n REFILL_AMOUNT_AND_INTERVAL_REQUIRED: \"refillAmount is required when refillInterval is provided\",\n REFILL_INTERVAL_AND_AMOUNT_REQUIRED: \"refillInterval is required when refillAmount is provided\",\n USER_BANNED: \"User is banned\",\n UNAUTHORIZED_SESSION: \"Unauthorized or invalid session\",\n KEY_NOT_FOUND: \"API Key not found\",\n KEY_DISABLED: \"API Key is disabled\",\n KEY_EXPIRED: \"API Key has expired\",\n USAGE_EXCEEDED: \"API Key has reached its usage limit\",\n KEY_NOT_RECOVERABLE: \"API Key is not recoverable\",\n EXPIRES_IN_IS_TOO_SMALL: \"The expiresIn is smaller than the predefined minimum value.\",\n EXPIRES_IN_IS_TOO_LARGE: \"The expiresIn is larger than the predefined maximum value.\",\n INVALID_REMAINING: \"The remaining count is either too large or too small.\",\n INVALID_PREFIX_LENGTH: \"The prefix length is either too large or too small.\",\n INVALID_NAME_LENGTH: \"The name length is either too large or too small.\",\n METADATA_DISABLED: \"Metadata is disabled.\",\n RATE_LIMIT_EXCEEDED: \"Rate limit exceeded.\",\n NO_VALUES_TO_UPDATE: \"No values to update.\",\n KEY_DISABLED_EXPIRATION: \"Custom key expiration values are disabled.\",\n INVALID_API_KEY: \"Invalid API key.\",\n INVALID_USER_ID_FROM_API_KEY: \"The user id from the API key is invalid.\",\n INVALID_API_KEY_GETTER_RETURN_TYPE: \"API Key getter returned an invalid key type. Expected string.\",\n SERVER_ONLY_PROPERTY: \"The property you're trying to set can only be set from the server auth instance only.\",\n FAILED_TO_UPDATE_API_KEY: \"Failed to update API key\",\n NAME_REQUIRED: \"API Key name is required.\"\n};\nconst API_KEY_TABLE_NAME = \"apikey\";\nconst apiKey = (options) => {\n const opts = {\n ...options,\n apiKeyHeaders: options?.apiKeyHeaders ?? \"x-api-key\",\n defaultKeyLength: options?.defaultKeyLength || 64,\n maximumPrefixLength: options?.maximumPrefixLength ?? 32,\n minimumPrefixLength: options?.minimumPrefixLength ?? 1,\n maximumNameLength: options?.maximumNameLength ?? 32,\n minimumNameLength: options?.minimumNameLength ?? 1,\n enableMetadata: options?.enableMetadata ?? false,\n disableKeyHashing: options?.disableKeyHashing ?? false,\n requireName: options?.requireName ?? false,\n rateLimit: {\n enabled: options?.rateLimit?.enabled === void 0 ? true : options?.rateLimit?.enabled,\n timeWindow: options?.rateLimit?.timeWindow ?? 1e3 * 60 * 60 * 24,\n maxRequests: options?.rateLimit?.maxRequests ?? 10\n },\n keyExpiration: {\n defaultExpiresIn: options?.keyExpiration?.defaultExpiresIn ?? null,\n disableCustomExpiresTime: options?.keyExpiration?.disableCustomExpiresTime ?? false,\n maxExpiresIn: options?.keyExpiration?.maxExpiresIn ?? 365,\n minExpiresIn: options?.keyExpiration?.minExpiresIn ?? 1\n },\n startingCharactersConfig: {\n shouldStore: options?.startingCharactersConfig?.shouldStore ?? true,\n charactersLength: options?.startingCharactersConfig?.charactersLength ?? 6\n },\n disableSessionForAPIKeys: options?.disableSessionForAPIKeys ?? false\n };\n const schema = mergeSchema(\n apiKeySchema({\n rateLimitMax: opts.rateLimit.maxRequests,\n timeWindow: opts.rateLimit.timeWindow\n }),\n opts.schema\n );\n const getter = opts.customAPIKeyGetter || ((ctx) => {\n if (Array.isArray(opts.apiKeyHeaders)) {\n for (const header of opts.apiKeyHeaders) {\n const value = ctx.headers?.get(header);\n if (value) {\n return value;\n }\n }\n } else {\n return ctx.headers?.get(opts.apiKeyHeaders);\n }\n });\n const keyGenerator = opts.customKeyGenerator || (async (options2) => {\n const characters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n let apiKey2 = `${options2.prefix || \"\"}`;\n for (let i = 0; i < options2.length; i++) {\n const randomIndex = Math.floor(Math.random() * characters.length);\n apiKey2 += characters[randomIndex];\n }\n return apiKey2;\n });\n const routes = createApiKeyRoutes({ keyGenerator, opts, schema });\n return {\n id: \"api-key\",\n $ERROR_CODES: ERROR_CODES,\n hooks: {\n before: [\n {\n matcher: (ctx) => !!getter(ctx) && opts.disableSessionForAPIKeys === false,\n handler: createAuthMiddleware(async (ctx) => {\n const key = getter(ctx);\n if (typeof key !== \"string\") {\n throw new APIError(\"BAD_REQUEST\", {\n message: ERROR_CODES.INVALID_API_KEY_GETTER_RETURN_TYPE\n });\n }\n if (key.length < opts.defaultKeyLength) {\n throw new APIError(\"FORBIDDEN\", {\n message: ERROR_CODES.INVALID_API_KEY\n });\n }\n if (opts.customAPIKeyValidator) {\n const isValid = await opts.customAPIKeyValidator({ ctx, key });\n if (!isValid) {\n throw new APIError(\"FORBIDDEN\", {\n message: ERROR_CODES.INVALID_API_KEY\n });\n }\n }\n const hashed = opts.disableKeyHashing ? key : await defaultKeyHasher(key);\n const apiKey2 = await validateApiKey({\n hashedKey: hashed,\n ctx,\n opts,\n schema\n });\n await deleteAllExpiredApiKeys(ctx.context);\n let user;\n try {\n const userResult = await ctx.context.internalAdapter.findUserById(\n apiKey2.userId\n );\n if (!userResult) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: ERROR_CODES.INVALID_USER_ID_FROM_API_KEY\n });\n }\n user = userResult;\n } catch (error) {\n throw error;\n }\n const session = {\n user,\n session: {\n id: apiKey2.id,\n token: key,\n userId: user.id,\n userAgent: ctx.request?.headers.get(\"user-agent\") ?? null,\n ipAddress: ctx.request ? getIp(ctx.request, ctx.context.options) : null,\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date(),\n expiresAt: apiKey2.expiresAt || getDate(\n ctx.context.options.session?.expiresIn || 60 * 60 * 24 * 7,\n // 7 days\n \"ms\"\n )\n }\n };\n ctx.context.session = session;\n if (ctx.path === \"/get-session\") {\n return session;\n } else {\n return {\n context: ctx\n };\n }\n })\n }\n ]\n },\n endpoints: {\n /**\n * ### Endpoint\n *\n * POST `/api-key/create`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.createApiKey`\n *\n * **client:**\n * `authClient.apiKey.create`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/api-key#api-method-api-key-create)\n */\n createApiKey: routes.createApiKey,\n /**\n * ### Endpoint\n *\n * POST `/api-key/verify`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.verifyApiKey`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/api-key#api-method-api-key-verify)\n */\n verifyApiKey: routes.verifyApiKey,\n /**\n * ### Endpoint\n *\n * GET `/api-key/get`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.getApiKey`\n *\n * **client:**\n * `authClient.apiKey.get`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/api-key#api-method-api-key-get)\n */\n getApiKey: routes.getApiKey,\n /**\n * ### Endpoint\n *\n * POST `/api-key/update`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.updateApiKey`\n *\n * **client:**\n * `authClient.apiKey.update`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/api-key#api-method-api-key-update)\n */\n updateApiKey: routes.updateApiKey,\n /**\n * ### Endpoint\n *\n * POST `/api-key/delete`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.deleteApiKey`\n *\n * **client:**\n * `authClient.apiKey.delete`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/api-key#api-method-api-key-delete)\n */\n deleteApiKey: routes.deleteApiKey,\n /**\n * ### Endpoint\n *\n * GET `/api-key/list`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.listApiKeys`\n *\n * **client:**\n * `authClient.apiKey.list`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/api-key#api-method-api-key-list)\n */\n listApiKeys: routes.listApiKeys,\n /**\n * ### Endpoint\n *\n * POST `/api-key/delete-all-expired-api-keys`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.deleteAllExpiredApiKeys`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/api-key#api-method-api-key-delete-all-expired-api-keys)\n */\n deleteAllExpiredApiKeys: routes.deleteAllExpiredApiKeys\n },\n schema\n };\n};\n\nconst oneTimeToken = (options) => {\n const opts = {\n storeToken: \"plain\",\n ...options\n };\n async function storeToken(ctx, token) {\n if (opts.storeToken === \"hashed\") {\n return await defaultKeyHasher(token);\n }\n if (typeof opts.storeToken === \"object\" && \"type\" in opts.storeToken && opts.storeToken.type === \"custom-hasher\") {\n return await opts.storeToken.hash(token);\n }\n return token;\n }\n return {\n id: \"one-time-token\",\n endpoints: {\n /**\n * ### Endpoint\n *\n * GET `/one-time-token/generate`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.generateOneTimeToken`\n *\n * **client:**\n * `authClient.oneTimeToken.generate`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/one-time-token#api-method-one-time-token-generate)\n */\n generateOneTimeToken: createAuthEndpoint(\n \"/one-time-token/generate\",\n {\n method: \"GET\",\n use: [sessionMiddleware]\n },\n async (c) => {\n if (opts?.disableClientRequest && c.request) {\n throw c.error(\"BAD_REQUEST\", {\n message: \"Client requests are disabled\"\n });\n }\n const session = c.context.session;\n const token = opts?.generateToken ? await opts.generateToken(session, c) : generateRandomString(32);\n const expiresAt = new Date(\n Date.now() + (opts?.expiresIn ?? 3) * 60 * 1e3\n );\n const storedToken = await storeToken(c, token);\n await c.context.internalAdapter.createVerificationValue({\n value: session.session.token,\n identifier: `one-time-token:${storedToken}`,\n expiresAt\n });\n return c.json({ token });\n }\n ),\n /**\n * ### Endpoint\n *\n * POST `/one-time-token/verify`\n *\n * ### API Methods\n *\n * **server:**\n * `auth.api.verifyOneTimeToken`\n *\n * **client:**\n * `authClient.oneTimeToken.verify`\n *\n * @see [Read our docs to learn more.](https://better-auth.com/docs/plugins/one-time-token#api-method-one-time-token-verify)\n */\n verifyOneTimeToken: createAuthEndpoint(\n \"/one-time-token/verify\",\n {\n method: \"POST\",\n body: z.object({\n token: z.string().meta({\n description: 'The token to verify. Eg: \"some-token\"'\n })\n })\n },\n async (c) => {\n const { token } = c.body;\n const storedToken = await storeToken(c, token);\n const verificationValue = await c.context.internalAdapter.findVerificationValue(\n `one-time-token:${storedToken}`\n );\n if (!verificationValue) {\n throw c.error(\"BAD_REQUEST\", {\n message: \"Invalid token\"\n });\n }\n if (verificationValue.expiresAt < /* @__PURE__ */ new Date()) {\n await c.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n throw c.error(\"BAD_REQUEST\", {\n message: \"Token expired\"\n });\n }\n await c.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n const session = await c.context.internalAdapter.findSession(\n verificationValue.value\n );\n if (!session) {\n throw c.error(\"BAD_REQUEST\", {\n message: \"Session not found\"\n });\n }\n return c.json(session);\n }\n )\n }\n };\n};\n\nexport { API_KEY_TABLE_NAME as A, ERROR_CODES as E, apiKey as a, defaultKeyHasher as d, oneTimeToken as o };\n","import { APIError } from 'better-call';\nimport '../../shared/better-auth.D4HhkCZJ.mjs';\nimport 'zod/v4';\nimport '../../shared/better-auth.8zoxzg-F.mjs';\nimport '@better-auth/utils/base64';\nimport '@better-auth/utils/hmac';\nimport '@better-auth/utils/binary';\nimport '../../shared/better-auth.n2KFGwjY.mjs';\nimport '../../shared/better-auth.DBGfIDnh.mjs';\nimport 'defu';\nimport { createHash } from '@better-auth/utils/hash';\nimport { betterFetch } from '@better-fetch/fetch';\nimport '../../shared/better-auth.CW6D9eSx.mjs';\nimport '../../crypto/index.mjs';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport 'jose';\nimport '@noble/hashes/scrypt';\nimport '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport '../../shared/better-auth.B4Qoxdgc.mjs';\nimport '@better-auth/utils/random';\nimport '../../shared/better-auth.VTXNLFMT.mjs';\nimport '../../shared/better-auth.DdzSJf-n.mjs';\nimport '../../cookies/index.mjs';\nimport '../../shared/better-auth.tB5eU6EY.mjs';\nimport 'jose/errors';\n\nconst ERROR_CODES = {\n PASSWORD_COMPROMISED: \"The password you entered has been compromised. Please choose a different password.\"\n};\nasync function checkPasswordCompromise(password, customMessage) {\n if (!password) return;\n const sha1Hash = (await createHash(\"SHA-1\", \"hex\").digest(password)).toUpperCase();\n const prefix = sha1Hash.substring(0, 5);\n const suffix = sha1Hash.substring(5);\n try {\n const { data, error } = await betterFetch(\n `https://api.pwnedpasswords.com/range/${prefix}`,\n {\n headers: {\n \"Add-Padding\": \"true\",\n \"User-Agent\": \"BetterAuth Password Checker\"\n }\n }\n );\n if (error) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: `Failed to check password. Status: ${error.status}`\n });\n }\n const lines = data.split(\"\\n\");\n const found = lines.some(\n (line) => line.split(\":\")[0].toUpperCase() === suffix.toUpperCase()\n );\n if (found) {\n throw new APIError(\"BAD_REQUEST\", {\n message: customMessage || ERROR_CODES.PASSWORD_COMPROMISED,\n code: \"PASSWORD_COMPROMISED\"\n });\n }\n } catch (error) {\n if (error instanceof APIError) throw error;\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Failed to check password. Please try again later.\"\n });\n }\n}\nconst haveIBeenPwned = (options) => ({\n id: \"haveIBeenPwned\",\n init(ctx) {\n return {\n context: {\n password: {\n ...ctx.password,\n async hash(password) {\n await checkPasswordCompromise(\n password,\n options?.customPasswordCompromisedMessage\n );\n return ctx.password.hash(password);\n }\n }\n }\n };\n },\n $ERROR_CODES: ERROR_CODES\n});\n\nexport { haveIBeenPwned };\n","export { o as organization, p as parseRoles } from '../shared/better-auth.C1Ly154X.mjs';\nexport { TWO_FACTOR_ERROR_CODES, twoFactor } from './two-factor/index.mjs';\nexport { USERNAME_ERROR_CODES, username } from './username/index.mjs';\nexport { bearer } from './bearer/index.mjs';\nimport { k as getSessionFromCtx, j as createAuthEndpoint, i as createAuthMiddleware } from '../shared/better-auth.D4HhkCZJ.mjs';\nexport { H as HIDE_METADATA, q as optionsMiddleware } from '../shared/better-auth.D4HhkCZJ.mjs';\nexport { magicLink } from './magic-link/index.mjs';\nexport { phoneNumber } from './phone-number/index.mjs';\nexport { anonymous } from './anonymous/index.mjs';\nexport { a as admin } from '../shared/better-auth.DygEm6OX.mjs';\nexport { genericOAuth } from './generic-oauth/index.mjs';\nexport { generateExportedKeyPair, getJwtToken, jwt } from './jwt/index.mjs';\nexport { multiSession } from './multi-session/index.mjs';\nexport { emailOTP } from './email-otp/index.mjs';\nexport { oneTap } from './one-tap/index.mjs';\nexport { oAuthProxy } from './oauth-proxy/index.mjs';\nexport { customSession } from './custom-session/index.mjs';\nexport { openAPI } from './open-api/index.mjs';\nimport { o as oidcProvider, s as schema } from '../shared/better-auth.CvxACSRz.mjs';\nexport { g as getClient, a as getMetadata } from '../shared/better-auth.CvxACSRz.mjs';\nexport { captcha } from './captcha/index.mjs';\nexport { A as API_KEY_TABLE_NAME, E as ERROR_CODES, a as apiKey, d as defaultKeyHasher, o as oneTimeToken } from '../shared/better-auth.Bqt8-7ls.mjs';\nexport { haveIBeenPwned } from './haveibeenpwned/index.mjs';\nimport * as z from 'zod/v4';\nimport { APIError } from 'better-call';\nimport { a as isProduction } from '../shared/better-auth.8zoxzg-F.mjs';\nimport { base64 } from '@better-auth/utils/base64';\nimport '@better-auth/utils/hmac';\nimport { a as getBaseURL } from '../shared/better-auth.VTXNLFMT.mjs';\nimport '@better-auth/utils/binary';\nimport { parseSetCookieHeader } from '../cookies/index.mjs';\nimport '../shared/better-auth.n2KFGwjY.mjs';\nimport '../shared/better-auth.DGaVMVAI.mjs';\nimport './organization/access/index.mjs';\nimport '@better-auth/utils/random';\nimport { createHash } from '@better-auth/utils/hash';\nimport '@noble/ciphers/chacha';\nimport '@noble/ciphers/utils';\nimport '@noble/ciphers/webcrypto';\nimport { SignJWT } from 'jose';\nimport '@noble/hashes/scrypt';\nimport { subtle } from '@better-auth/utils';\nimport '@better-auth/utils/hex';\nimport '@noble/hashes/utils';\nimport { g as generateRandomString } from '../shared/better-auth.B4Qoxdgc.mjs';\nimport { a as logger } from '../shared/better-auth.DBGfIDnh.mjs';\nimport 'kysely';\nimport 'defu';\nimport '@better-auth/utils/otp';\nimport './admin/access/index.mjs';\nimport '@better-fetch/fetch';\nimport '../shared/better-auth.CGrHn1Ih.mjs';\nexport { t as twoFactorClient } from '../shared/better-auth.Ddw8bVyV.mjs';\nimport '../shared/better-auth.CW6D9eSx.mjs';\nimport '../shared/better-auth.DdzSJf-n.mjs';\nimport '../shared/better-auth.ffWeg50w.mjs';\nimport '../shared/better-auth.Dt0CvI2z.mjs';\nimport '../shared/better-auth.DXqcUO8W.mjs';\nimport '../crypto/index.mjs';\nimport '../shared/better-auth.YwDQhoPc.mjs';\nimport '../shared/better-auth.tB5eU6EY.mjs';\nimport 'jose/errors';\nimport '../shared/better-auth.DQI8AD7d.mjs';\nimport '../shared/better-auth.bkwPl2G4.mjs';\nimport '../api/index.mjs';\nimport '../shared/better-auth.DcfNPS8q.mjs';\nimport '../shared/better-auth.DORkW_Ge.mjs';\nimport './access/index.mjs';\n\nfunction redirectErrorURL(url, error, description) {\n return `${url.includes(\"?\") ? \"&\" : \"?\"}error=${error}&error_description=${description}`;\n}\nasync function authorizeMCPOAuth(ctx, options) {\n ctx.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n ctx.setHeader(\"Access-Control-Allow-Methods\", \"POST, OPTIONS\");\n ctx.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization\");\n ctx.setHeader(\"Access-Control-Max-Age\", \"86400\");\n const opts = {\n codeExpiresIn: 600,\n defaultScope: \"openid\",\n ...options,\n scopes: [\n \"openid\",\n \"profile\",\n \"email\",\n \"offline_access\",\n ...options?.scopes || []\n ]\n };\n if (!ctx.request) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"request not found\",\n error: \"invalid_request\"\n });\n }\n const session = await getSessionFromCtx(ctx);\n if (!session) {\n await ctx.setSignedCookie(\n \"oidc_login_prompt\",\n JSON.stringify(ctx.query),\n ctx.context.secret,\n {\n maxAge: 600,\n path: \"/\",\n sameSite: \"lax\"\n }\n );\n const queryFromURL = ctx.request.url?.split(\"?\")[1];\n throw ctx.redirect(`${options.loginPage}?${queryFromURL}`);\n }\n const query = ctx.query;\n console.log(query);\n if (!query.client_id) {\n throw ctx.redirect(`${ctx.context.baseURL}/error?error=invalid_client`);\n }\n if (!query.response_type) {\n throw ctx.redirect(\n redirectErrorURL(\n `${ctx.context.baseURL}/error`,\n \"invalid_request\",\n \"response_type is required\"\n )\n );\n }\n const client = await ctx.context.adapter.findOne({\n model: \"oauthApplication\",\n where: [\n {\n field: \"clientId\",\n value: ctx.query.client_id\n }\n ]\n }).then((res) => {\n if (!res) {\n return null;\n }\n return {\n ...res,\n redirectURLs: res.redirectURLs.split(\",\"),\n metadata: res.metadata ? JSON.parse(res.metadata) : {}\n };\n });\n console.log(client);\n if (!client) {\n throw ctx.redirect(`${ctx.context.baseURL}/error?error=invalid_client`);\n }\n const redirectURI = client.redirectURLs.find(\n (url) => url === ctx.query.redirect_uri\n );\n if (!redirectURI || !query.redirect_uri) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Invalid redirect URI\"\n });\n }\n if (client.disabled) {\n throw ctx.redirect(`${ctx.context.baseURL}/error?error=client_disabled`);\n }\n if (query.response_type !== \"code\") {\n throw ctx.redirect(\n `${ctx.context.baseURL}/error?error=unsupported_response_type`\n );\n }\n const requestScope = query.scope?.split(\" \").filter((s) => s) || opts.defaultScope.split(\" \");\n const invalidScopes = requestScope.filter((scope) => {\n return !opts.scopes.includes(scope);\n });\n if (invalidScopes.length) {\n throw ctx.redirect(\n redirectErrorURL(\n query.redirect_uri,\n \"invalid_scope\",\n `The following scopes are invalid: ${invalidScopes.join(\", \")}`\n )\n );\n }\n if ((!query.code_challenge || !query.code_challenge_method) && options.requirePKCE) {\n throw ctx.redirect(\n redirectErrorURL(\n query.redirect_uri,\n \"invalid_request\",\n \"pkce is required\"\n )\n );\n }\n if (!query.code_challenge_method) {\n query.code_challenge_method = \"plain\";\n }\n if (![\n \"s256\",\n options.allowPlainCodeChallengeMethod ? \"plain\" : \"s256\"\n ].includes(query.code_challenge_method?.toLowerCase() || \"\")) {\n throw ctx.redirect(\n redirectErrorURL(\n query.redirect_uri,\n \"invalid_request\",\n \"invalid code_challenge method\"\n )\n );\n }\n const code = generateRandomString(32, \"a-z\", \"A-Z\", \"0-9\");\n const codeExpiresInMs = opts.codeExpiresIn * 1e3;\n const expiresAt = new Date(Date.now() + codeExpiresInMs);\n try {\n await ctx.context.internalAdapter.createVerificationValue(\n {\n value: JSON.stringify({\n clientId: client.clientId,\n redirectURI: query.redirect_uri,\n scope: requestScope,\n userId: session.user.id,\n authTime: session.session.createdAt.getTime(),\n /**\n * If the prompt is set to `consent`, then we need\n * to require the user to consent to the scopes.\n *\n * This means the code now needs to be treated as a\n * consent request.\n *\n * once the user consents, the code will be updated\n * with the actual code. This is to prevent the\n * client from using the code before the user\n * consents.\n */\n requireConsent: query.prompt === \"consent\",\n state: query.prompt === \"consent\" ? query.state : null,\n codeChallenge: query.code_challenge,\n codeChallengeMethod: query.code_challenge_method,\n nonce: query.nonce\n }),\n identifier: code,\n expiresAt\n },\n ctx\n );\n } catch (e) {\n throw ctx.redirect(\n redirectErrorURL(\n query.redirect_uri,\n \"server_error\",\n \"An error occurred while processing the request\"\n )\n );\n }\n const redirectURIWithCode = new URL(redirectURI);\n redirectURIWithCode.searchParams.set(\"code\", code);\n redirectURIWithCode.searchParams.set(\"state\", ctx.query.state);\n if (query.prompt !== \"consent\") {\n throw ctx.redirect(redirectURIWithCode.toString());\n }\n throw ctx.redirect(redirectURIWithCode.toString());\n}\n\nconst getMCPProviderMetadata = (ctx, options) => {\n const issuer = ctx.context.options.baseURL;\n const baseURL = ctx.context.baseURL;\n if (!issuer || !baseURL) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n error: \"invalid_issuer\",\n error_description: \"issuer or baseURL is not set. If you're the app developer, please make sure to set the `baseURL` in your auth config.\"\n });\n }\n return {\n issuer,\n authorization_endpoint: `${baseURL}/mcp/authorize`,\n token_endpoint: `${baseURL}/mcp/token`,\n userinfo_endpoint: `${baseURL}/mcp/userinfo`,\n jwks_uri: `${baseURL}/mcp/jwks`,\n registration_endpoint: `${baseURL}/mcp/register`,\n scopes_supported: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n response_types_supported: [\"code\"],\n response_modes_supported: [\"query\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\"],\n acr_values_supported: [\n \"urn:mace:incommon:iap:silver\",\n \"urn:mace:incommon:iap:bronze\"\n ],\n subject_types_supported: [\"public\"],\n id_token_signing_alg_values_supported: [\"RS256\", \"none\"],\n token_endpoint_auth_methods_supported: [\n \"client_secret_basic\",\n \"client_secret_post\",\n \"none\"\n ],\n code_challenge_methods_supported: [\"S256\"],\n claims_supported: [\n \"sub\",\n \"iss\",\n \"aud\",\n \"exp\",\n \"nbf\",\n \"iat\",\n \"jti\",\n \"email\",\n \"email_verified\",\n \"name\"\n ],\n ...options?.metadata\n };\n};\nconst mcp = (options) => {\n const opts = {\n codeExpiresIn: 600,\n defaultScope: \"openid\",\n accessTokenExpiresIn: 3600,\n refreshTokenExpiresIn: 604800,\n allowPlainCodeChallengeMethod: true,\n ...options.oidcConfig,\n loginPage: options.loginPage,\n scopes: [\n \"openid\",\n \"profile\",\n \"email\",\n \"offline_access\",\n ...options.oidcConfig?.scopes || []\n ]\n };\n const modelName = {\n oauthClient: \"oauthApplication\",\n oauthAccessToken: \"oauthAccessToken\"};\n oidcProvider(opts);\n return {\n id: \"mcp\",\n hooks: {\n after: [\n {\n matcher() {\n return true;\n },\n handler: createAuthMiddleware(async (ctx) => {\n const cookie = await ctx.getSignedCookie(\n \"oidc_login_prompt\",\n ctx.context.secret\n );\n const cookieName = ctx.context.authCookies.sessionToken.name;\n const parsedSetCookieHeader = parseSetCookieHeader(\n ctx.context.responseHeaders?.get(\"set-cookie\") || \"\"\n );\n const hasSessionToken = parsedSetCookieHeader.has(cookieName);\n if (!cookie || !hasSessionToken) {\n return;\n }\n ctx.setCookie(\"oidc_login_prompt\", \"\", {\n maxAge: 0\n });\n const sessionCookie = parsedSetCookieHeader.get(cookieName)?.value;\n const sessionToken = sessionCookie?.split(\".\")[0];\n if (!sessionToken) {\n return;\n }\n const session = await ctx.context.internalAdapter.findSession(sessionToken);\n if (!session) {\n return;\n }\n ctx.query = JSON.parse(cookie);\n ctx.query.prompt = \"consent\";\n ctx.context.session = session;\n const response = await authorizeMCPOAuth(ctx, opts).catch((e) => {\n if (e instanceof APIError) {\n if (e.statusCode === 302) {\n return ctx.json({\n redirect: true,\n //@ts-expect-error\n url: e.headers.get(\"location\")\n });\n }\n }\n throw e;\n });\n return response;\n })\n }\n ]\n },\n endpoints: {\n getMcpOAuthConfig: createAuthEndpoint(\n \"/.well-known/oauth-authorization-server\",\n {\n method: \"GET\",\n metadata: {\n client: false\n }\n },\n async (c) => {\n try {\n const metadata = getMCPProviderMetadata(c, options);\n return c.json(metadata);\n } catch (e) {\n console.log(e);\n return c.json(null);\n }\n }\n ),\n mcpOAuthAuthroize: createAuthEndpoint(\n \"/mcp/authorize\",\n {\n method: \"GET\",\n query: z.record(z.string(), z.any()),\n metadata: {\n openapi: {\n description: \"Authorize an OAuth2 request using MCP\",\n responses: {\n \"200\": {\n description: \"Authorization response generated successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n additionalProperties: true,\n description: \"Authorization response, contents depend on the authorize function implementation\"\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n return authorizeMCPOAuth(ctx, opts);\n }\n ),\n mcpOAuthToken: createAuthEndpoint(\n \"/mcp/token\",\n {\n method: \"POST\",\n body: z.record(z.any(), z.any()),\n metadata: {\n isAction: false\n }\n },\n async (ctx) => {\n ctx.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n ctx.setHeader(\"Access-Control-Allow-Methods\", \"POST, OPTIONS\");\n ctx.setHeader(\n \"Access-Control-Allow-Headers\",\n \"Content-Type, Authorization\"\n );\n ctx.setHeader(\"Access-Control-Max-Age\", \"86400\");\n let { body } = ctx;\n if (!body) {\n throw ctx.error(\"BAD_REQUEST\", {\n error_description: \"request body not found\",\n error: \"invalid_request\"\n });\n }\n if (body instanceof FormData) {\n body = Object.fromEntries(body.entries());\n }\n if (!(body instanceof Object)) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"request body is not an object\",\n error: \"invalid_request\"\n });\n }\n let { client_id, client_secret } = body;\n const authorization = ctx.request?.headers.get(\"authorization\") || null;\n if (authorization && !client_id && !client_secret && authorization.startsWith(\"Basic \")) {\n try {\n const encoded = authorization.replace(\"Basic \", \"\");\n const decoded = new TextDecoder().decode(base64.decode(encoded));\n if (!decoded.includes(\":\")) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid authorization header format\",\n error: \"invalid_client\"\n });\n }\n const [id, secret] = decoded.split(\":\");\n if (!id || !secret) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid authorization header format\",\n error: \"invalid_client\"\n });\n }\n client_id = id;\n client_secret = secret;\n } catch (error) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid authorization header format\",\n error: \"invalid_client\"\n });\n }\n }\n const {\n grant_type,\n code,\n redirect_uri,\n refresh_token,\n code_verifier\n } = body;\n if (grant_type === \"refresh_token\") {\n if (!refresh_token) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"refresh_token is required\",\n error: \"invalid_request\"\n });\n }\n const token = await ctx.context.adapter.findOne({\n model: \"oauthAccessToken\",\n where: [\n {\n field: \"refreshToken\",\n value: refresh_token.toString()\n }\n ]\n });\n if (!token) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid refresh token\",\n error: \"invalid_grant\"\n });\n }\n if (token.clientId !== client_id?.toString()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid client_id\",\n error: \"invalid_client\"\n });\n }\n if (token.refreshTokenExpiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"refresh token expired\",\n error: \"invalid_grant\"\n });\n }\n const accessToken2 = generateRandomString(32, \"a-z\", \"A-Z\");\n const newRefreshToken = generateRandomString(32, \"a-z\", \"A-Z\");\n const accessTokenExpiresAt2 = new Date(\n Date.now() + opts.accessTokenExpiresIn * 1e3\n );\n const refreshTokenExpiresAt2 = new Date(\n Date.now() + opts.refreshTokenExpiresIn * 1e3\n );\n await ctx.context.adapter.create({\n model: modelName.oauthAccessToken,\n data: {\n accessToken: accessToken2,\n refreshToken: newRefreshToken,\n accessTokenExpiresAt: accessTokenExpiresAt2,\n refreshTokenExpiresAt: refreshTokenExpiresAt2,\n clientId: client_id.toString(),\n userId: token.userId,\n scopes: token.scopes,\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date()\n }\n });\n return ctx.json({\n access_token: accessToken2,\n token_type: \"bearer\",\n expires_in: opts.accessTokenExpiresIn,\n refresh_token: newRefreshToken,\n scope: token.scopes\n });\n }\n if (!code) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"code is required\",\n error: \"invalid_request\"\n });\n }\n if (opts.requirePKCE && !code_verifier) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"code verifier is missing\",\n error: \"invalid_request\"\n });\n }\n const verificationValue = await ctx.context.internalAdapter.findVerificationValue(\n code.toString()\n );\n if (!verificationValue) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid code\",\n error: \"invalid_grant\"\n });\n }\n if (verificationValue.expiresAt < /* @__PURE__ */ new Date()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"code expired\",\n error: \"invalid_grant\"\n });\n }\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n if (!client_id) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"client_id is required\",\n error: \"invalid_client\"\n });\n }\n if (!grant_type) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"grant_type is required\",\n error: \"invalid_request\"\n });\n }\n if (grant_type !== \"authorization_code\") {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"grant_type must be 'authorization_code'\",\n error: \"unsupported_grant_type\"\n });\n }\n if (!redirect_uri) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"redirect_uri is required\",\n error: \"invalid_request\"\n });\n }\n const client = await ctx.context.adapter.findOne({\n model: modelName.oauthClient,\n where: [{ field: \"clientId\", value: client_id.toString() }]\n }).then((res) => {\n if (!res) {\n return null;\n }\n return {\n ...res,\n redirectURLs: res.redirectURLs.split(\",\"),\n metadata: res.metadata ? JSON.parse(res.metadata) : {}\n };\n });\n if (!client) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid client_id\",\n error: \"invalid_client\"\n });\n }\n if (client.disabled) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"client is disabled\",\n error: \"invalid_client\"\n });\n }\n if (client.type === \"public\") {\n if (!code_verifier) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"code verifier is required for public clients\",\n error: \"invalid_request\"\n });\n }\n } else {\n if (!client_secret) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"client_secret is required for confidential clients\",\n error: \"invalid_client\"\n });\n }\n const isValidSecret = client.clientSecret === client_secret.toString();\n if (!isValidSecret) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid client_secret\",\n error: \"invalid_client\"\n });\n }\n }\n const value = JSON.parse(\n verificationValue.value\n );\n if (value.clientId !== client_id.toString()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid client_id\",\n error: \"invalid_client\"\n });\n }\n if (value.redirectURI !== redirect_uri.toString()) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"invalid redirect_uri\",\n error: \"invalid_client\"\n });\n }\n if (value.codeChallenge && !code_verifier) {\n throw new APIError(\"BAD_REQUEST\", {\n error_description: \"code verifier is missing\",\n error: \"invalid_request\"\n });\n }\n const challenge = value.codeChallengeMethod === \"plain\" ? code_verifier : await createHash(\"SHA-256\", \"base64urlnopad\").digest(\n code_verifier\n );\n if (challenge !== value.codeChallenge) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"code verification failed\",\n error: \"invalid_request\"\n });\n }\n const requestedScopes = value.scope;\n await ctx.context.internalAdapter.deleteVerificationValue(\n verificationValue.id\n );\n const accessToken = generateRandomString(32, \"a-z\", \"A-Z\");\n const refreshToken = generateRandomString(32, \"A-Z\", \"a-z\");\n const accessTokenExpiresAt = new Date(\n Date.now() + opts.accessTokenExpiresIn * 1e3\n );\n const refreshTokenExpiresAt = new Date(\n Date.now() + opts.refreshTokenExpiresIn * 1e3\n );\n await ctx.context.adapter.create({\n model: modelName.oauthAccessToken,\n data: {\n accessToken,\n refreshToken,\n accessTokenExpiresAt,\n refreshTokenExpiresAt,\n clientId: client_id.toString(),\n userId: value.userId,\n scopes: requestedScopes.join(\" \"),\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date()\n }\n });\n const user = await ctx.context.internalAdapter.findUserById(\n value.userId\n );\n if (!user) {\n throw new APIError(\"UNAUTHORIZED\", {\n error_description: \"user not found\",\n error: \"invalid_grant\"\n });\n }\n let secretKey = {\n alg: \"HS256\",\n key: await subtle.generateKey(\n {\n name: \"HMAC\",\n hash: \"SHA-256\"\n },\n true,\n [\"sign\", \"verify\"]\n )\n };\n const profile = {\n given_name: user.name.split(\" \")[0],\n family_name: user.name.split(\" \")[1],\n name: user.name,\n profile: user.image,\n updated_at: user.updatedAt.toISOString()\n };\n const email = {\n email: user.email,\n email_verified: user.emailVerified\n };\n const userClaims = {\n ...requestedScopes.includes(\"profile\") ? profile : {},\n ...requestedScopes.includes(\"email\") ? email : {}\n };\n const additionalUserClaims = opts.getAdditionalUserInfoClaim ? opts.getAdditionalUserInfoClaim(user, requestedScopes) : {};\n const idToken = await new SignJWT({\n sub: user.id,\n aud: client_id.toString(),\n iat: Date.now(),\n auth_time: ctx.context.session?.session.createdAt.getTime(),\n nonce: value.nonce,\n acr: \"urn:mace:incommon:iap:silver\",\n // default to silver - ⚠︎ this should be configurable and should be validated against the client's metadata\n ...userClaims,\n ...additionalUserClaims\n }).setProtectedHeader({ alg: secretKey.alg }).setIssuedAt().setExpirationTime(\n Math.floor(Date.now() / 1e3) + opts.accessTokenExpiresIn\n ).sign(secretKey.key);\n return ctx.json(\n {\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: opts.accessTokenExpiresIn,\n refresh_token: requestedScopes.includes(\"offline_access\") ? refreshToken : void 0,\n scope: requestedScopes.join(\" \"),\n id_token: requestedScopes.includes(\"openid\") ? idToken : void 0\n },\n {\n headers: {\n \"Cache-Control\": \"no-store\",\n Pragma: \"no-cache\"\n }\n }\n );\n }\n ),\n registerMcpClient: createAuthEndpoint(\n \"/mcp/register\",\n {\n method: \"POST\",\n body: z.object({\n redirect_uris: z.array(z.string()),\n token_endpoint_auth_method: z.enum([\"none\", \"client_secret_basic\", \"client_secret_post\"]).default(\"client_secret_basic\").optional(),\n grant_types: z.array(\n z.enum([\n \"authorization_code\",\n \"implicit\",\n \"password\",\n \"client_credentials\",\n \"refresh_token\",\n \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n \"urn:ietf:params:oauth:grant-type:saml2-bearer\"\n ])\n ).default([\"authorization_code\"]).optional(),\n response_types: z.array(z.enum([\"code\", \"token\"])).default([\"code\"]).optional(),\n client_name: z.string().optional(),\n client_uri: z.string().optional(),\n logo_uri: z.string().optional(),\n scope: z.string().optional(),\n contacts: z.array(z.string()).optional(),\n tos_uri: z.string().optional(),\n policy_uri: z.string().optional(),\n jwks_uri: z.string().optional(),\n jwks: z.record(z.string(), z.any()).optional(),\n metadata: z.record(z.any(), z.any()).optional(),\n software_id: z.string().optional(),\n software_version: z.string().optional(),\n software_statement: z.string().optional()\n }),\n metadata: {\n openapi: {\n description: \"Register an OAuth2 application\",\n responses: {\n \"200\": {\n description: \"OAuth2 application registered successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description: \"Name of the OAuth2 application\"\n },\n icon: {\n type: \"string\",\n nullable: true,\n description: \"Icon URL for the application\"\n },\n metadata: {\n type: \"object\",\n additionalProperties: true,\n nullable: true,\n description: \"Additional metadata for the application\"\n },\n clientId: {\n type: \"string\",\n description: \"Unique identifier for the client\"\n },\n clientSecret: {\n type: \"string\",\n description: \"Secret key for the client. Not included for public clients.\"\n },\n redirectURLs: {\n type: \"array\",\n items: { type: \"string\", format: \"uri\" },\n description: \"List of allowed redirect URLs\"\n },\n type: {\n type: \"string\",\n description: \"Type of the client\",\n enum: [\"web\", \"public\"]\n },\n authenticationScheme: {\n type: \"string\",\n description: \"Authentication scheme used by the client\",\n enum: [\"client_secret\", \"none\"]\n },\n disabled: {\n type: \"boolean\",\n description: \"Whether the client is disabled\",\n enum: [false]\n },\n userId: {\n type: \"string\",\n nullable: true,\n description: \"ID of the user who registered the client, null if registered anonymously\"\n },\n createdAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Creation timestamp\"\n },\n updatedAt: {\n type: \"string\",\n format: \"date-time\",\n description: \"Last update timestamp\"\n }\n },\n required: [\n \"name\",\n \"clientId\",\n \"redirectURLs\",\n \"type\",\n \"authenticationScheme\",\n \"disabled\",\n \"createdAt\",\n \"updatedAt\"\n ]\n }\n }\n }\n }\n }\n }\n }\n },\n async (ctx) => {\n const body = ctx.body;\n const session = await getSessionFromCtx(ctx);\n ctx.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n ctx.setHeader(\"Access-Control-Allow-Methods\", \"POST, OPTIONS\");\n ctx.setHeader(\n \"Access-Control-Allow-Headers\",\n \"Content-Type, Authorization\"\n );\n ctx.setHeader(\"Access-Control-Max-Age\", \"86400\");\n ctx.headers?.set(\"Access-Control-Max-Age\", \"86400\");\n if ((!body.grant_types || body.grant_types.includes(\"authorization_code\") || body.grant_types.includes(\"implicit\")) && (!body.redirect_uris || body.redirect_uris.length === 0)) {\n throw new APIError(\"BAD_REQUEST\", {\n error: \"invalid_redirect_uri\",\n error_description: \"Redirect URIs are required for authorization_code and implicit grant types\"\n });\n }\n if (body.grant_types && body.response_types) {\n if (body.grant_types.includes(\"authorization_code\") && !body.response_types.includes(\"code\")) {\n throw new APIError(\"BAD_REQUEST\", {\n error: \"invalid_client_metadata\",\n error_description: \"When 'authorization_code' grant type is used, 'code' response type must be included\"\n });\n }\n if (body.grant_types.includes(\"implicit\") && !body.response_types.includes(\"token\")) {\n throw new APIError(\"BAD_REQUEST\", {\n error: \"invalid_client_metadata\",\n error_description: \"When 'implicit' grant type is used, 'token' response type must be included\"\n });\n }\n }\n const clientId = opts.generateClientId?.() || generateRandomString(32, \"a-z\", \"A-Z\");\n const clientSecret = opts.generateClientSecret?.() || generateRandomString(32, \"a-z\", \"A-Z\");\n const clientType = body.token_endpoint_auth_method === \"none\" ? \"public\" : \"web\";\n const finalClientSecret = clientType === \"public\" ? \"\" : clientSecret;\n await ctx.context.adapter.create({\n model: modelName.oauthClient,\n data: {\n name: body.client_name,\n icon: body.logo_uri,\n metadata: body.metadata ? JSON.stringify(body.metadata) : null,\n clientId,\n clientSecret: finalClientSecret,\n redirectURLs: body.redirect_uris.join(\",\"),\n type: clientType,\n authenticationScheme: body.token_endpoint_auth_method || \"client_secret_basic\",\n disabled: false,\n userId: session?.session.userId,\n createdAt: /* @__PURE__ */ new Date(),\n updatedAt: /* @__PURE__ */ new Date()\n }\n });\n const responseData = {\n client_id: clientId,\n client_id_issued_at: Math.floor(Date.now() / 1e3),\n redirect_uris: body.redirect_uris,\n token_endpoint_auth_method: body.token_endpoint_auth_method || \"client_secret_basic\",\n grant_types: body.grant_types || [\"authorization_code\"],\n response_types: body.response_types || [\"code\"],\n client_name: body.client_name,\n client_uri: body.client_uri,\n logo_uri: body.logo_uri,\n scope: body.scope,\n contacts: body.contacts,\n tos_uri: body.tos_uri,\n policy_uri: body.policy_uri,\n jwks_uri: body.jwks_uri,\n jwks: body.jwks,\n software_id: body.software_id,\n software_version: body.software_version,\n software_statement: body.software_statement,\n metadata: body.metadata,\n ...clientType !== \"public\" ? {\n client_secret: finalClientSecret,\n client_secret_expires_at: 0\n // 0 means it doesn't expire\n } : {}\n };\n return ctx.json(responseData, {\n status: 201,\n headers: {\n \"Cache-Control\": \"no-store\",\n Pragma: \"no-cache\"\n }\n });\n }\n ),\n getMcpSession: createAuthEndpoint(\n \"/mcp/get-session\",\n {\n method: \"GET\",\n requireHeaders: true\n },\n async (c) => {\n const accessToken = c.headers?.get(\"Authorization\")?.replace(\"Bearer \", \"\");\n if (!accessToken) {\n c.headers?.set(\"WWW-Authenticate\", \"Bearer\");\n return c.json(null);\n }\n const accessTokenData = await c.context.adapter.findOne({\n model: modelName.oauthAccessToken,\n where: [\n {\n field: \"accessToken\",\n value: accessToken\n }\n ]\n });\n if (!accessTokenData) {\n return c.json(null);\n }\n return c.json(accessTokenData);\n }\n )\n },\n schema\n };\n};\nconst withMcpAuth = (auth, handler) => {\n return async (req) => {\n const baseURL = getBaseURL(auth.options.baseURL, auth.options.basePath);\n if (!baseURL && !isProduction) {\n logger.warn(\"Unable to get the baseURL, please check your config!\");\n }\n const session = await auth.api.getMcpSession({\n headers: req.headers\n });\n const wwwAuthenticateValue = `Bearer resource_metadata=${baseURL}/api/auth/.well-known/oauth-authorization-server`;\n if (!session) {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: {\n code: -32e3,\n message: \"Unauthorized: Authentication required\",\n \"www-authenticate\": wwwAuthenticateValue\n },\n id: null\n },\n {\n status: 401,\n headers: {\n \"WWW-Authenticate\": wwwAuthenticateValue\n }\n }\n );\n }\n return handler(req, session);\n };\n};\nconst oAuthDiscoveryMetadata = (auth) => {\n return async (request) => {\n const res = await auth.api.getMcpOAuthConfig();\n return new Response(JSON.stringify(res), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n \"Access-Control-Max-Age\": \"86400\"\n }\n });\n };\n};\n\nexport { createAuthEndpoint, createAuthMiddleware, getMCPProviderMetadata, mcp, oAuthDiscoveryMetadata, oidcProvider, withMcpAuth };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAAuB;AAEvB,IAAM,SAAS,mBAAAA,QAAW,WAAW,UAAU,CAAC;AAIhD,IAAM,kBAAkB,CAACC,YAAU;AACjC,SAAO,mBAAAC,QAAW,UAAU,gBAAgBD,OAAK;AACnD;;;ACRO,IAAM,cAAc;EAC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,YACtD;AAAA,UACF;AAEA,gBAAM,IAAI,SAAS,yBAAyB;AAAA,YAC1C,SAAS;AAAA,UACX,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAe,eACb,cACAC,QACA,MACA;AACA,QAAM,WAAW,MAAM,aAAa,UAAU,OAAO;AAAA,IACnD,OAAAA;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["nodeCrypto","array","nodeCrypto","error","message","options","headers","createEndpoint","util","object","array","objectUtil","errorUtil","errorMap","transform","jwt","base64","ctx","result","schema","issues","types","elements","processed","ZodFirstPartyTypeKind","z","algorithm","encoder","bytes","hex","array","isLE","bytes","sigma","output","nc","output","tag","message","message","util","crypto","util","webcrypto","algorithm","types","types","import_node_crypto","getNamedCurve","types","import_node_crypto","import_node_crypto","types","crypto","import_node_util","import_node_crypto","isJWK","crypto","import_node_crypto","types","sign","verify","algorithm","date","jwt","jwk","error","get","decode","decode","jwt","decode","jwt","error","username","isJSONSerializable","isJSONSerializable","message","schema","getURL","clearTimeout","parser","message","error","algorithm","date","encoder","decoder","message","object","isValid","error","error","email","jwt","schema","error","refreshToken","error","isValid","refreshToken","error","email","error2","revokeOtherSessions","verify","error","z","z","z","role","z","z","z","z","z","import_v4","z","defaultStatements","defaultAc","adminAc","z","z","import_v4","z","z","z","z","z","import_v4","z","z","import_v4","z","email"]}